]> diplodocus.org Git - nmh/blob - uip/mhlsbr.c
picksbr.c: fprintf(3) function pointer using `%p' and union.
[nmh] / uip / mhlsbr.c
1 /* mhlsbr.c -- main routines for nmh message lister
2 *
3 * This code is Copyright (c) 2002, by the authors of nmh. See the
4 * COPYRIGHT file in the root directory of the nmh distribution for
5 * complete copyright information.
6 */
7
8 #include <h/mh.h>
9 #include <h/signals.h>
10 #include <h/addrsbr.h>
11 #include <h/fmt_scan.h>
12 #include <h/tws.h>
13 #include "h/done.h"
14 #include <h/utils.h>
15 #include "sbr/m_popen.h"
16 #include <setjmp.h>
17 #include <sys/types.h>
18 #include "sbr/terminal.h"
19
20 /*
21 * MAJOR BUG:
22 * for a component containing addresses, ADDRFMT, if COMPRESS is also
23 * set, then addresses get split wrong (not at the spaces between commas).
24 * To fix this correctly, putstr() should know about "atomic" strings that
25 * must NOT be broken across lines. That's too difficult for right now
26 * (it turns out that there are a number of degenerate cases), so in
27 * oneline(), instead of
28 *
29 * (*onelp == '\n' && !onelp[1])
30 *
31 * being a terminating condition,
32 *
33 * (*onelp == '\n' && (!onelp[1] || (flags & ADDRFMT)))
34 *
35 * is used instead. This cuts the line prematurely, and gives us a much
36 * better chance of getting things right.
37 */
38
39 #define ONECOMP 0
40 #define TWOCOMP 1
41 #define BODYCOMP 2
42
43 #define QUOTE '\\'
44
45 #define MHL_SWITCHES \
46 X("bell", 0, BELLSW) \
47 X("nobell", 0, NBELLSW) \
48 X("clear", 0, CLRSW) \
49 X("noclear", 0, NCLRSW) \
50 X("folder +folder", 0, FOLDSW) \
51 X("form formfile", 0, FORMSW) \
52 X("moreproc program", 0, PROGSW) \
53 X("nomoreproc", 0, NPROGSW) \
54 X("length lines", 0, LENSW) \
55 X("width columns", 0, WIDTHSW) \
56 X("sleep seconds", 0, SLEEPSW) \
57 X("dashstuffing", -12, BITSTUFFSW) /* interface from forw */ \
58 X("nodashstuffing", -14, NBITSTUFFSW) /* interface from forw */ \
59 X("version", 0, VERSIONSW) \
60 X("help", 0, HELPSW) \
61 X("forward", -7, FORW1SW) /* interface from forw */ \
62 X("forwall", -7, FORW2SW) /* interface from forw */ \
63 X("digest list", -6, DGSTSW) \
64 X("volume number", -6, VOLUMSW) \
65 X("issue number", -5, ISSUESW) \
66 X("nobody", -6, NBODYSW) \
67 X("fmtproc program", 0, FMTPROCSW) \
68 X("nofmtproc", 0, NFMTPROCSW) \
69
70 #define X(sw, minchars, id) id,
71 DEFINE_SWITCH_ENUM(MHL);
72 #undef X
73
74 #define X(sw, minchars, id) { sw, minchars, id },
75 DEFINE_SWITCH_ARRAY(MHL, mhlswitches);
76 #undef X
77
78 #define NOCOMPONENT 0x000001 /* don't show component name */
79 #define UPPERCASE 0x000002 /* display in all upper case */
80 #define CENTER 0x000004 /* center line */
81 #define CLEARTEXT 0x000008 /* cleartext */
82 #define EXTRA 0x000010 /* an "extra" component */
83 #define HDROUTPUT 0x000020 /* already output */
84 #define CLEARSCR 0x000040 /* clear screen */
85 #define LEFTADJUST 0x000080 /* left justify multiple lines */
86 #define COMPRESS 0x000100 /* compress text */
87 #define ADDRFMT 0x000200 /* contains addresses */
88 #define BELL 0x000400 /* sound bell at EOP */
89 #define DATEFMT 0x000800 /* contains dates */
90 #define FORMAT 0x001000 /* parse address/date/RFC-2047 field */
91 #define INIT 0x002000 /* initialize component */
92 #define RTRIM 0x004000 /* trim trailing whitespace */
93 #define SPLIT 0x010000 /* split headers (don't concatenate) */
94 #define NONEWLINE 0x020000 /* don't write trailing newline */
95 #define NOWRAP 0x040000 /* Don't wrap lines ever */
96 #define FMTFILTER 0x080000 /* Filter through format filter */
97 #define INVISIBLE 0x100000 /* count byte in display columns? */
98 #define FORCE7BIT 0x200000 /* don't display 8-bit bytes */
99 #define LBITS "\020\01NOCOMPONENT\02UPPERCASE\03CENTER\04CLEARTEXT\05EXTRA\06HDROUTPUT\07CLEARSCR\010LEFTADJUST\011COMPRESS\012ADDRFMT\013BELL\014DATEFMT\015FORMAT\016INIT\017RTRIM\021SPLIT\022NONEWLINE\023NOWRAP\024FMTFILTER\025INVISIBLE\026FORCE7BIT"
100 #define GFLAGS (NOCOMPONENT | UPPERCASE | CENTER | LEFTADJUST | COMPRESS | SPLIT | NOWRAP)
101
102 /*
103 * A format string to be used as a command-line argument to the body
104 * format filter.
105 */
106
107 struct arglist {
108 struct format *a_fmt;
109 char *a_nfs;
110 struct arglist *a_next;
111 };
112
113 /*
114 * Linked list of command line arguments for the body format filter. This
115 * USED to be in "struct mcomp", but the format API got cleaned up and even
116 * though it reduced the code we had to do, it make things more complicated
117 * for us. Specifically:
118 *
119 * - The interface to the hash table has been cleaned up, which means the
120 * rooting around in the hash table is no longer necessary (yay!). But
121 * this ALSO means that we have to make sure that we call our format
122 * compilation routines before we process the message, because the
123 * components need to be visible in the hash table so we can save them for
124 * later. So we moved them out of "mcomp" and now compile them right before
125 * header processing starts.
126 * - We also use format strings to handle other components in the mhl
127 * configuration (using "formatfield" and "decode"), but here life
128 * gets complicated: they aren't dealt with in the normal way. Instead
129 * of referring to a component like {from}, each component is processed
130 * using the special {text} component. But these format strings need to be
131 * compiled BEFORE we compile the format arguments; in the previous
132 * implementation they were compiled and scanned as the headers were
133 * read, and that would reset the hash table that we need to populate
134 * the components used by the body format filter. So we are compiling
135 * the formatfield component strings ahead of time and then scanning them
136 * later.
137 *
138 * Okay, fine ... this was broken before. But you know what? Fixing this
139 * the right way will make things easier down the road.
140 *
141 * One side-effect to this change: format strings are now compiled only once
142 * for components specified with "formatfield", but they are compiled for
143 * every message for format arguments.
144 */
145
146 static struct arglist *arglist_head;
147 static struct arglist *arglist_tail;
148 static int filter_nargs = 0;
149
150 /*
151 * Flags/options for each component
152 */
153
154 struct mcomp {
155 char *c_name; /* component name */
156 char *c_text; /* component text */
157 char *c_ovtxt; /* text overflow indicator */
158 char *c_nfs; /* iff FORMAT */
159 struct format *c_fmt; /* .. */
160 struct comp *c_c_text; /* Ref to {text} in FORMAT */
161 struct comp *c_c_error; /* Ref to {error} */
162 int c_offset; /* left margin indentation */
163 int c_ovoff; /* overflow indentation */
164 int c_width; /* width of field */
165 int c_cwidth; /* width of component */
166 int c_length; /* length in lines */
167 unsigned long c_flags;
168 struct mcomp *c_next;
169 };
170
171 static struct mcomp *msghd = NULL;
172 static struct mcomp *msgtl = NULL;
173 static struct mcomp *fmthd = NULL;
174 static struct mcomp *fmttl = NULL;
175
176 static struct mcomp global = {
177 NULL, NULL, NULL, NULL, NULL, NULL, NULL, 0, -1, 80, -1, 40, BELL, NULL
178 };
179
180 static struct mcomp holder = {
181 NULL, NULL, NULL, NULL, NULL, NULL, NULL, 0, 0, 0, 0, 0, NOCOMPONENT, NULL
182 };
183
184 struct pair {
185 char *p_name;
186 unsigned long p_flags;
187 };
188
189 static struct pair pairs[] = {
190 { "Date", DATEFMT },
191 { "From", ADDRFMT },
192 { "Sender", ADDRFMT },
193 { "Reply-To", ADDRFMT },
194 { "To", ADDRFMT },
195 { "cc", ADDRFMT },
196 { "Bcc", ADDRFMT },
197 { "Resent-Date", DATEFMT },
198 { "Resent-From", ADDRFMT },
199 { "Resent-Sender", ADDRFMT },
200 { "Resent-Reply-To", ADDRFMT },
201 { "Resent-To", ADDRFMT },
202 { "Resent-cc", ADDRFMT },
203 { "Resent-Bcc", ADDRFMT },
204 { NULL, 0 }
205 };
206
207 struct triple {
208 char *t_name;
209 unsigned long t_on;
210 unsigned long t_off;
211 };
212
213 static struct triple triples[] = {
214 { "nocomponent", NOCOMPONENT, 0 },
215 { "uppercase", UPPERCASE, 0 },
216 { "nouppercase", 0, UPPERCASE },
217 { "center", CENTER, 0 },
218 { "nocenter", 0, CENTER },
219 { "clearscreen", CLEARSCR, 0 },
220 { "noclearscreen", 0, CLEARSCR },
221 { "noclear", 0, CLEARSCR },
222 { "leftadjust", LEFTADJUST, 0 },
223 { "noleftadjust", 0, LEFTADJUST },
224 { "compress", COMPRESS, 0 },
225 { "nocompress", 0, COMPRESS },
226 { "split", SPLIT, 0 },
227 { "nosplit", 0, SPLIT },
228 { "rtrim", RTRIM, 0 },
229 { "nortrim", 0, RTRIM },
230 { "addrfield", ADDRFMT, DATEFMT },
231 { "bell", BELL, 0 },
232 { "nobell", 0, BELL },
233 { "datefield", DATEFMT, ADDRFMT },
234 { "newline", 0, NONEWLINE },
235 { "nonewline", NONEWLINE, 0 },
236 { "wrap", 0, NOWRAP },
237 { "nowrap", NOWRAP, 0 },
238 { "format", FMTFILTER, 0 },
239 { "noformat", 0, FMTFILTER },
240 { NULL, 0, 0 }
241 };
242
243 static char *addrcomps[] = {
244 "from",
245 "sender",
246 "reply-to",
247 "to",
248 "cc",
249 "bcc",
250 "resent-from",
251 "resent-sender",
252 "resent-reply-to",
253 "resent-to",
254 "resent-cc",
255 "resent-bcc",
256 NULL
257 };
258
259
260 static int bellflg = 0;
261 static int clearflg = 0;
262 static int dashstuff = 0;
263 static int dobody = 1;
264 static int forwflg = 0;
265 static int forwall = 0;
266
267 static int sleepsw = NOTOK;
268
269 static char *digest = NULL;
270 static int volume = 0;
271 static int issue = 0;
272
273 static int exitstat = 0;
274 static int mhldebug = 0;
275
276 static int filesize = 0;
277
278 #define PITTY (-1)
279 #define NOTTY 0
280 #define ISTTY 1
281 static int ontty = NOTTY;
282
283 static int row;
284 static unsigned int column;
285
286 static int lm;
287 static int llim;
288 static int ovoff;
289 static int term;
290 static unsigned int wid;
291
292 static char *ovtxt;
293
294 static char *onelp;
295
296 static char *parptr;
297
298 static int num_ignores = 0;
299 static char *ignores[MAXARGS];
300
301 static jmp_buf env;
302
303 static char delim3[] = /* from forw.c */
304 "\n----------------------------------------------------------------------\n\n";
305 static char delim4[] = "\n------------------------------\n\n";
306
307 /*
308 * prototypes
309 */
310 static void mhl_format (char *, int, int);
311 static int evalvar (struct mcomp *);
312 static int ptoi (char *, int *);
313 static int ptos (char *, char **);
314 static char *parse (void);
315 static void process (char *, char *, int, int);
316 static void mhlfile (FILE *, char *, int, int);
317 static int mcomp_flags (char *) PURE;
318 static char *mcomp_add (unsigned long, char *, char *);
319 static void mcomp_format (struct mcomp *, struct mcomp *);
320 static struct mcomp *add_queue (struct mcomp **, struct mcomp **, char *, char *, int);
321 static void free_queue (struct mcomp **, struct mcomp **);
322 static void putcomp (struct mcomp *, struct mcomp *, int);
323 static char *oneline (char *, unsigned long);
324 static void putstr (char *, unsigned long);
325 static void putch (char, unsigned long);
326 static bool linefeed_typed(void);
327 static void intrser (int);
328 static void pipeser (int);
329 static void quitser (int);
330 static void mhladios (char *, char *, ...) CHECK_PRINTF(2, 3) NORETURN;
331 static void mhldone (int) NORETURN;
332 static void filterbody (struct mcomp *, char *, int, int,
333 m_getfld_state_t);
334 static void compile_formatfield(struct mcomp *);
335 static void compile_filterargs (void);
336
337
338 int
339 mhl (int argc, char **argv)
340 {
341 int length = 0, nomore = 0;
342 unsigned int i, vecp = 0;
343 int width = 0;
344 char *cp, *folder = NULL, *form = NULL;
345 char buf[BUFSIZ], *files[MAXARGS];
346 char **argp, **arguments;
347
348 /* Need this if called from main() of show(1). */
349 invo_name = r1bindex (argv[0], '/');
350
351 arguments = getarguments (invo_name, argc, argv, 1);
352 argp = arguments;
353
354 if ((cp = getenv ("MHLDEBUG")) && *cp)
355 mhldebug++;
356
357 while ((cp = *argp++)) {
358 if (*cp == '-') {
359 switch (smatch (++cp, mhlswitches)) {
360 case AMBIGSW:
361 ambigsw (cp, mhlswitches);
362 mhldone (1);
363 case UNKWNSW:
364 mhladios (NULL, "-%s unknown\n", cp);
365
366 case HELPSW:
367 snprintf (buf, sizeof(buf), "%s [switches] [files ...]", invo_name);
368 print_help (buf, mhlswitches, 1);
369 mhldone (0);
370 case VERSIONSW:
371 print_version(invo_name);
372 mhldone (0);
373
374 case BELLSW:
375 bellflg = 1;
376 continue;
377 case NBELLSW:
378 bellflg = -1;
379 continue;
380
381 case CLRSW:
382 clearflg = 1;
383 continue;
384 case NCLRSW:
385 clearflg = -1;
386 continue;
387
388 case FOLDSW:
389 if (!(folder = *argp++) || *folder == '-')
390 mhladios (NULL, "missing argument to %s", argp[-2]);
391 continue;
392 case FORMSW:
393 if (!(form = *argp++) || *form == '-')
394 mhladios (NULL, "missing argument to %s", argp[-2]);
395 continue;
396
397 case SLEEPSW:
398 if (!(cp = *argp++) || *cp == '-')
399 mhladios (NULL, "missing argument to %s", argp[-2]);
400 sleepsw = atoi (cp);/* ZERO ok! */
401 continue;
402
403 case PROGSW:
404 if (!(moreproc = *argp++) || *moreproc == '-')
405 mhladios (NULL, "missing argument to %s", argp[-2]);
406 continue;
407 case NPROGSW:
408 nomore++;
409 continue;
410
411 case FMTPROCSW:
412 if (!(formatproc = *argp++) || *formatproc == '-')
413 mhladios (NULL, "missing argument to %s", argp[-2]);
414 continue;
415 case NFMTPROCSW:
416 formatproc = NULL;
417 continue;
418
419 case LENSW:
420 if (!(cp = *argp++) || *cp == '-')
421 mhladios (NULL, "missing argument to %s", argp[-2]);
422 if ((length = atoi (cp)) < 1)
423 mhladios (NULL, "bad argument %s %s", argp[-2], cp);
424 continue;
425 case WIDTHSW:
426 if (!(cp = *argp++) || *cp == '-')
427 mhladios (NULL, "missing argument to %s", argp[-2]);
428 if ((width = atoi (cp)) < 1)
429 mhladios (NULL, "bad argument %s %s", argp[-2], cp);
430 continue;
431
432 case DGSTSW:
433 if (!(digest = *argp++) || *digest == '-')
434 mhladios (NULL, "missing argument to %s", argp[-2]);
435 continue;
436 case ISSUESW:
437 if (!(cp = *argp++) || *cp == '-')
438 mhladios (NULL, "missing argument to %s", argp[-2]);
439 if ((issue = atoi (cp)) < 1)
440 mhladios (NULL, "bad argument %s %s", argp[-2], cp);
441 continue;
442 case VOLUMSW:
443 if (!(cp = *argp++) || *cp == '-')
444 mhladios (NULL, "missing argument to %s", argp[-2]);
445 if ((volume = atoi (cp)) < 1)
446 mhladios (NULL, "bad argument %s %s", argp[-2], cp);
447 continue;
448
449 case FORW2SW:
450 forwall++;
451 /* FALLTHRU */
452 case FORW1SW:
453 forwflg++;
454 clearflg = -1;/* XXX */
455 continue;
456
457 case BITSTUFFSW:
458 dashstuff = 1; /* ternary logic */
459 continue;
460 case NBITSTUFFSW:
461 dashstuff = -1; /* ternary logic */
462 continue;
463
464 case NBODYSW:
465 dobody = 0;
466 continue;
467 }
468 }
469 files[vecp++] = cp;
470 }
471
472 if (!folder)
473 folder = getenv ("mhfolder");
474
475 if (isatty (fileno (stdout))) {
476 if (!nomore && moreproc && *moreproc != '\0') {
477 SIGNAL2 (SIGPIPE, pipeser);
478 m_popen(moreproc, false);
479 ontty = PITTY;
480 } else {
481 SIGNAL (SIGINT, SIG_IGN);
482 SIGNAL2 (SIGQUIT, quitser);
483 ontty = ISTTY;
484 }
485 } else {
486 ontty = NOTTY;
487 }
488
489 mhl_format (form ? form : mhlformat, length, width);
490
491 if (vecp == 0) {
492 process (folder, NULL, 1, vecp = 1);
493 } else {
494 for (i = 0; i < vecp; i++)
495 process (folder, files[i], i + 1, vecp);
496 }
497
498 if (forwall) {
499 if (digest) {
500 fputs(delim4, stdout);
501 if (volume == 0) {
502 snprintf (buf, sizeof(buf), "End of %s Digest\n", digest);
503 } else {
504 snprintf (buf, sizeof(buf), "End of %s Digest [Volume %d Issue %d]\n",
505 digest, volume, issue);
506 }
507 i = strlen (buf);
508 for (cp = buf + i; i > 1; i--)
509 *cp++ = '*';
510 *cp++ = '\n';
511 *cp = 0;
512 fputs(buf, stdout);
513 }
514 else
515 printf ("\n------- End of Forwarded Message%s\n",
516 PLURALS(vecp));
517 }
518
519 fflush(stdout);
520 if(ferror(stdout)){
521 mhladios("output", "error writing");
522 }
523
524 if (clearflg > 0 && ontty == NOTTY)
525 nmh_clear_screen ();
526
527 if (ontty == PITTY)
528 m_pclose ();
529
530 return exitstat;
531 }
532
533
534 static void
535 mhl_format (char *file, int length, int width)
536 {
537 int i;
538 char *bp, **ip;
539 char *ap, name[NAMESZ];
540 struct mcomp *c1;
541 struct stat st;
542 FILE *fp;
543 static dev_t dev = 0;
544 static ino_t ino = 0;
545 static time_t mtime = 0;
546
547 if (fmthd != NULL) {
548 if (stat (etcpath (file), &st) != NOTOK
549 && mtime == st.st_mtime
550 && dev == st.st_dev
551 && ino == st.st_ino)
552 goto out;
553 free_queue (&fmthd, &fmttl);
554 }
555
556 if ((fp = fopen (etcpath (file), "r")) == NULL)
557 mhladios (file, "unable to open format file");
558
559 if (fstat (fileno (fp), &st) != NOTOK) {
560 mtime = st.st_mtime;
561 dev = st.st_dev;
562 ino = st.st_ino;
563 }
564
565 global.c_ovtxt = global.c_nfs = NULL;
566 global.c_fmt = NULL;
567 global.c_offset = 0;
568 global.c_ovoff = -1;
569 if ((i = sc_width ()) > 5)
570 global.c_width = i;
571 global.c_cwidth = -1;
572 if ((i = sc_length ()) > 5)
573 global.c_length = i - 1;
574 global.c_flags = BELL; /* BELL is default */
575 *(ip = ignores) = NULL;
576 filter_nargs = 0;
577
578 while (vfgets (fp, &ap) == OK) {
579 bp = ap;
580 if (*bp == ';')
581 continue;
582
583 trim_suffix_c(bp, '\n');
584
585 if (*bp == ':') {
586 (void) add_queue (&fmthd, &fmttl, NULL, bp + 1, CLEARTEXT);
587 continue;
588 }
589
590 parptr = bp;
591 strncpy (name, parse(), sizeof(name));
592 switch (*parptr) {
593 case '\0':
594 case ',':
595 case '=':
596 /*
597 * Split this list of fields to ignore, and copy
598 * it to the end of the current "ignores" list.
599 */
600 if (!strcasecmp (name, "ignores")) {
601 char **tmparray, **p;
602 int n = 0;
603
604 /* split the fields */
605 tmparray = brkstring (mh_xstrdup(++parptr), ",", NULL);
606
607 /* count number of fields split */
608 p = tmparray;
609 while (*p++)
610 n++;
611
612 /* copy pointers to split fields to ignores array */
613 ip = copyip (tmparray, ip, MAXARGS - num_ignores);
614 num_ignores += n;
615 continue;
616 }
617 parptr = bp;
618 while (*parptr) {
619 if (evalvar (&global))
620 mhladios (NULL, "format file syntax error: %s", bp);
621 if (*parptr)
622 parptr++;
623 }
624 continue;
625
626 case ':':
627 c1 = add_queue (&fmthd, &fmttl, name, NULL, INIT);
628 while (*parptr == ':' || *parptr == ',') {
629 parptr++;
630 if (evalvar (c1))
631 mhladios (NULL, "format file syntax error: %s", bp);
632 }
633 if (!c1->c_nfs && global.c_nfs) {
634 if (c1->c_flags & DATEFMT) {
635 if (global.c_flags & DATEFMT) {
636 c1->c_nfs = mh_xstrdup(global.c_nfs);
637 compile_formatfield(c1);
638 }
639 } else if (c1->c_flags & ADDRFMT) {
640 if (global.c_flags & ADDRFMT) {
641 c1->c_nfs = mh_xstrdup(global.c_nfs);
642 compile_formatfield(c1);
643 }
644 }
645 }
646 continue;
647
648 default:
649 mhladios (NULL, "format file syntax error: %s", bp);
650 }
651 }
652 fclose (fp);
653
654 if (mhldebug) {
655 for (c1 = fmthd; c1; c1 = c1->c_next) {
656 char buffer[BUFSIZ];
657
658 fprintf (stderr, "c1: name=\"%s\" text=\"%s\" ovtxt=\"%s\"\n",
659 c1->c_name, c1->c_text, c1->c_ovtxt);
660 fprintf(stderr, "\tnfs=%p fmt=%p\n",
661 (void *)c1->c_nfs, (void *)c1->c_fmt);
662 fprintf (stderr, "\toffset=%d ovoff=%d width=%d cwidth=%d length=%d\n",
663 c1->c_offset, c1->c_ovoff, c1->c_width,
664 c1->c_cwidth, c1->c_length);
665 fprintf (stderr, "\tflags=%s\n",
666 snprintb (buffer, sizeof(buffer), (unsigned) c1->c_flags, LBITS));
667 }
668 }
669
670 out:
671 if (clearflg == 1) {
672 global.c_flags |= CLEARSCR;
673 } else {
674 if (clearflg == -1)
675 global.c_flags &= ~CLEARSCR;
676 }
677
678 switch (bellflg) { /* command line may override format file */
679 case 1:
680 global.c_flags |= BELL;
681 break;
682 case -1:
683 global.c_flags &= ~BELL;
684 break;
685 }
686
687 if (length)
688 global.c_length = length;
689 if (width)
690 global.c_width = width;
691 if (global.c_length < 5)
692 global.c_length = 10000;
693 if (global.c_width < 5)
694 global.c_width = 10000;
695 }
696
697
698 static int
699 evalvar (struct mcomp *c1)
700 {
701 char *cp, name[NAMESZ];
702 struct triple *ap;
703
704 if (!*parptr)
705 return 0;
706 strncpy (name, parse(), sizeof(name));
707
708 if (!strcasecmp (name, "component")) {
709 if (ptos (name, &c1->c_text))
710 return 1;
711 c1->c_flags &= ~NOCOMPONENT;
712 return 0;
713 }
714
715 if (!strcasecmp (name, "overflowtext"))
716 return ptos (name, &c1->c_ovtxt);
717
718 if (!strcasecmp (name, "formatfield")) {
719 if (ptos (name, &cp))
720 return 1;
721 c1->c_nfs = getcpy (new_fs (NULL, NULL, cp));
722 compile_formatfield(c1);
723 c1->c_flags |= FORMAT;
724 return 0;
725 }
726
727 if (!strcasecmp (name, "decode")) {
728 c1->c_nfs = getcpy (new_fs (NULL, NULL, "%(decode{text})"));
729 compile_formatfield(c1);
730 c1->c_flags |= FORMAT;
731 return 0;
732 }
733
734 if (!strcasecmp (name, "offset"))
735 return ptoi (name, &c1->c_offset);
736 if (!strcasecmp (name, "overflowoffset"))
737 return ptoi (name, &c1->c_ovoff);
738 if (!strcasecmp (name, "width"))
739 return ptoi (name, &c1->c_width);
740 if (!strcasecmp (name, "compwidth"))
741 return ptoi (name, &c1->c_cwidth);
742 if (!strcasecmp (name, "length"))
743 return ptoi (name, &c1->c_length);
744 if (!strcasecmp (name, "nodashstuffing"))
745 return dashstuff = -1;
746
747 for (ap = triples; ap->t_name; ap++)
748 if (!strcasecmp (ap->t_name, name)) {
749 c1->c_flags |= ap->t_on;
750 c1->c_flags &= ~ap->t_off;
751 return 0;
752 }
753
754 if (!strcasecmp (name, "formatarg")) {
755 struct arglist *args;
756
757 if (ptos (name, &cp))
758 return 1;
759
760 if (! c1->c_name || strcasecmp (c1->c_name, "body")) {
761 inform("format filters are currently only supported on "
762 "the \"body\" component");
763 return 1;
764 }
765
766 NEW0(args);
767
768 if (arglist_tail)
769 arglist_tail->a_next = args;
770
771 arglist_tail = args;
772
773 if (! arglist_head)
774 arglist_head = args;
775
776 args->a_nfs = getcpy (new_fs (NULL, NULL, cp));
777 filter_nargs++;
778
779 return 0;
780 }
781
782 return 1;
783 }
784
785
786 static int
787 ptoi (char *name, int *i)
788 {
789 char *cp;
790
791 if (*parptr++ != '=' || !*(cp = parse ())) {
792 inform("missing argument to variable %s", name);
793 return 1;
794 }
795
796 *i = atoi (cp);
797 return 0;
798 }
799
800
801 static int
802 ptos (char *name, char **s)
803 {
804 char c, *cp;
805
806 if (*parptr++ != '=') {
807 inform("missing argument to variable %s", name);
808 return 1;
809 }
810
811 if (*parptr != '"') {
812 for (cp = parptr;
813 *parptr && *parptr != ':' && *parptr != ',';
814 parptr++)
815 continue;
816 } else {
817 for (cp = ++parptr; *parptr && *parptr != '"'; parptr++)
818 if (*parptr == QUOTE)
819 if (!*++parptr)
820 parptr--;
821 }
822 c = *parptr;
823 *parptr = 0;
824 *s = mh_xstrdup(cp);
825 if ((*parptr = c) == '"')
826 parptr++;
827 return 0;
828 }
829
830
831 static char *
832 parse (void)
833 {
834 int c;
835 char *cp;
836 static char result[NAMESZ];
837
838 for (cp = result; *parptr && (cp - result < NAMESZ); parptr++) {
839 c = *parptr;
840 if (!isalnum (c)
841 && c != '.'
842 && c != '-'
843 && c != '_'
844 && c !='['
845 && c != ']')
846 break;
847 *cp++ = c;
848 }
849 *cp = '\0';
850
851 return result;
852 }
853
854
855 /*
856 * Process one file/message
857 */
858
859 static void
860 process (char *folder, char *fname, int ofilen, int ofilec)
861 {
862 /* static to prevent "might be clobbered" warning from gcc 4.9.2: */
863 static char *cp;
864 static FILE *fp;
865 struct mcomp *c1;
866 struct stat st;
867 struct arglist *ap;
868 /* volatile to prevent "might be clobbered" warning from gcc: */
869 char *volatile fname2 = fname ? fname : "(stdin)";
870
871 cp = NULL;
872 fp = NULL;
873
874 switch (setjmp (env)) {
875 case OK:
876 if (fname) {
877 fp = fopen(fname, "r");
878 if (fp == NULL) {
879 advise (fname, "unable to open");
880 exitstat++;
881 return;
882 }
883 } else {
884 fp = stdin;
885 }
886 if (fstat(fileno(fp), &st) == 0) {
887 filesize = st.st_size;
888 } else {
889 filesize = 0;
890 }
891 cp = folder ? concat (folder, ":", fname2, NULL) : mh_xstrdup(fname2);
892 if (ontty != PITTY)
893 SIGNAL (SIGINT, intrser);
894 mhlfile (fp, cp, ofilen, ofilec);
895 free (cp);
896
897 for (ap = arglist_head; ap; ap = ap->a_next) {
898 fmt_free(ap->a_fmt, 0);
899 ap->a_fmt = NULL;
900 }
901
902 if (arglist_head)
903 fmt_free(NULL, 1);
904 /* FALLTHRU */
905
906 default:
907 if (ontty != PITTY)
908 SIGNAL (SIGINT, SIG_IGN);
909 if (fp != stdin && fp != NULL)
910 fclose (fp);
911 free(holder.c_text);
912 holder.c_text = NULL;
913 free_queue (&msghd, &msgtl);
914 for (c1 = fmthd; c1; c1 = c1->c_next)
915 c1->c_flags &= ~HDROUTPUT;
916 break;
917 }
918
919 }
920
921
922 static void
923 mhlfile (FILE *fp, char *mname, int ofilen, int ofilec)
924 {
925 int state, bucket;
926 struct mcomp *c1, *c2, *c3;
927 char **ip, name[NAMESZ], buf[NMH_BUFSIZ];
928 m_getfld_state_t gstate;
929
930 compile_filterargs();
931
932 if (forwall) {
933 if (digest)
934 fputs(ofilen == 1 ? delim3 : delim4, stdout);
935 else {
936 printf ("\n-------");
937 if (ofilen == 1)
938 printf (" Forwarded Message%s", PLURALS(ofilec));
939 else
940 printf (" Message %d", ofilen);
941 puts("\n");
942 }
943 } else {
944 switch (ontty) {
945 case PITTY:
946 if (ofilec > 1) {
947 if (ofilen > 1) {
948 if ((global.c_flags & CLEARSCR))
949 nmh_clear_screen ();
950 else
951 puts("\n\n");
952 }
953 printf (">>> %s\n\n", mname);
954 }
955 break;
956
957 case ISTTY:
958 if (ofilec > 1) {
959 if (SOprintf ("Press <return> to list \"%s\"...", mname)) {
960 if (ofilen > 1)
961 puts("\n\n");
962 printf ("Press <return> to list \"%s\"...", mname);
963 }
964 fflush (stdout);
965 }
966 if (ofilec == 1 || linefeed_typed()) {
967 if ((global.c_flags & CLEARSCR))
968 nmh_clear_screen ();
969 }
970 else
971 putchar('\n');
972 break;
973
974 default:
975 if (ofilec > 1) {
976 if (ofilen > 1) {
977 puts("\n\n");
978 if (clearflg > 0)
979 nmh_clear_screen ();
980 }
981 printf (">>> %s\n\n", mname);
982 }
983 break;
984 }
985 }
986
987 gstate = m_getfld_state_init(fp);
988 for (;;) {
989 int bufsz = sizeof buf;
990 switch (state = m_getfld2(&gstate, name, buf, &bufsz)) {
991 case FLD:
992 case FLDPLUS:
993 bucket = fmt_addcomptext(name, buf);
994 for (ip = ignores; *ip; ip++)
995 if (!strcasecmp (name, *ip)) {
996 while (state == FLDPLUS) {
997 bufsz = sizeof buf;
998 state = m_getfld2(&gstate, name, buf, &bufsz);
999 fmt_appendcomp(bucket, name, buf);
1000 }
1001 break;
1002 }
1003 if (*ip)
1004 continue;
1005
1006 for (c2 = fmthd; c2; c2 = c2->c_next)
1007 if (!strcasecmp (FENDNULL(c2->c_name), name))
1008 break;
1009 c1 = NULL;
1010 if (!((c3 = c2 ? c2 : &global)->c_flags & SPLIT))
1011 for (c1 = msghd; c1; c1 = c1->c_next)
1012 if (!strcasecmp (FENDNULL(c1->c_name),
1013 FENDNULL(c3->c_name))) {
1014 c1->c_text =
1015 mcomp_add (c1->c_flags, buf, c1->c_text);
1016 break;
1017 }
1018 if (c1 == NULL)
1019 c1 = add_queue (&msghd, &msgtl, name, buf, 0);
1020 while (state == FLDPLUS) {
1021 bufsz = sizeof buf;
1022 state = m_getfld2(&gstate, name, buf, &bufsz);
1023 c1->c_text = add (buf, c1->c_text);
1024 fmt_appendcomp(bucket, name, buf);
1025 }
1026 if (c2 == NULL)
1027 c1->c_flags |= EXTRA;
1028 continue;
1029
1030 case BODY:
1031 case FILEEOF:
1032 row = column = 0;
1033 for (c1 = fmthd; c1; c1 = c1->c_next) {
1034 if (c1->c_flags & CLEARTEXT) {
1035 putcomp (c1, c1, ONECOMP);
1036 continue;
1037 }
1038 if (!c1->c_name ||
1039 !strcasecmp (c1->c_name, "messagename")) {
1040 holder.c_text = concat ("(Message ", mname, ")\n",
1041 NULL);
1042 putcomp (c1, &holder, ONECOMP);
1043 free (holder.c_text);
1044 holder.c_text = NULL;
1045 continue;
1046 }
1047 if (!c1->c_name || !strcasecmp (c1->c_name, "extras")) {
1048 for (c2 = msghd; c2; c2 = c2->c_next)
1049 if (c2->c_flags & EXTRA)
1050 putcomp (c1, c2, TWOCOMP);
1051 continue;
1052 }
1053 if (dobody && (!c1->c_name ||
1054 !strcasecmp (c1->c_name, "body"))) {
1055 if (c1->c_flags & FMTFILTER && state == BODY &&
1056 formatproc != NULL) {
1057 filterbody(c1, buf, sizeof(buf), state, gstate);
1058 } else {
1059 holder.c_text = mh_xmalloc (sizeof(buf));
1060 strncpy (holder.c_text, buf, sizeof(buf));
1061 while (state == BODY) {
1062 putcomp (c1, &holder, BODYCOMP);
1063 bufsz = sizeof buf;
1064 state = m_getfld2(&gstate, name, holder.c_text,
1065 &bufsz);
1066 }
1067 free (holder.c_text);
1068 holder.c_text = NULL;
1069 }
1070 continue;
1071 }
1072 for (c2 = msghd; c2; c2 = c2->c_next)
1073 if (!strcasecmp (FENDNULL(c2->c_name),
1074 FENDNULL(c1->c_name))) {
1075 putcomp (c1, c2, ONECOMP);
1076 if (!(c1->c_flags & SPLIT))
1077 break;
1078 }
1079 }
1080 m_getfld_state_destroy (&gstate);
1081 return;
1082
1083 case LENERR:
1084 case FMTERR:
1085 inform("format error in message %s", mname);
1086 exitstat++;
1087 m_getfld_state_destroy (&gstate);
1088 return;
1089
1090 default:
1091 mhladios (NULL, "getfld() returned %d", state);
1092 }
1093 }
1094 }
1095
1096
1097 static int
1098 mcomp_flags (char *name)
1099 {
1100 struct pair *ap;
1101
1102 for (ap = pairs; ap->p_name; ap++)
1103 if (!strcasecmp (ap->p_name, name))
1104 return ap->p_flags;
1105
1106 return 0;
1107 }
1108
1109
1110 static char *
1111 mcomp_add (unsigned long flags, char *s1, char *s2)
1112 {
1113 char *dp;
1114
1115 if (!(flags & ADDRFMT))
1116 return add (s1, s2);
1117
1118 if (s2 && *(dp = s2 + strlen (s2) - 1) == '\n')
1119 *dp = 0;
1120
1121 return add (s1, add (",\n", s2));
1122 }
1123
1124
1125 struct pqpair {
1126 char *pq_text;
1127 char *pq_error;
1128 struct pqpair *pq_next;
1129 };
1130
1131
1132 static void
1133 mcomp_format (struct mcomp *c1, struct mcomp *c2)
1134 {
1135 int dat[5];
1136 char *ap, *cp;
1137 char error[BUFSIZ];
1138 struct pqpair *p, *q;
1139 struct pqpair pq;
1140 struct mailname *mp;
1141
1142 ap = c2->c_text;
1143 c2->c_text = NULL;
1144 dat[0] = 0;
1145 dat[1] = 0;
1146 dat[2] = filesize;
1147 dat[3] = BUFSIZ - 1;
1148 dat[4] = 0;
1149
1150 if (!(c1->c_flags & ADDRFMT)) {
1151 charstring_t scanl = charstring_create (BUFSIZ);
1152
1153 if (c1->c_c_text)
1154 c1->c_c_text->c_text = ap;
1155 if ((cp = strrchr(ap, '\n'))) /* drop ending newline */
1156 if (!cp[1])
1157 *cp = 0;
1158
1159 fmt_scan (c1->c_fmt, scanl, BUFSIZ - 1, dat, NULL);
1160 /* Don't need to append a newline, dctime() already did */
1161 c2->c_text = charstring_buffer_copy (scanl);
1162 charstring_free (scanl);
1163
1164 /* ap is now owned by the component struct, so do NOT free it here */
1165 return;
1166 }
1167
1168 (q = &pq)->pq_next = NULL;
1169 while ((cp = getname (ap))) {
1170 NEW0(p);
1171 if ((mp = getm (cp, NULL, 0, error, sizeof(error))) == NULL) {
1172 p->pq_text = mh_xstrdup(cp);
1173 p->pq_error = mh_xstrdup(error);
1174 } else {
1175 p->pq_text = getcpy (mp->m_text);
1176 mnfree (mp);
1177 }
1178 q = (q->pq_next = p);
1179 }
1180
1181 for (p = pq.pq_next; p; p = q) {
1182 charstring_t scanl = charstring_create (BUFSIZ);
1183 char *buffer;
1184
1185 if (c1->c_c_text) {
1186 c1->c_c_text->c_text = p->pq_text;
1187 p->pq_text = NULL;
1188 }
1189 if (c1->c_c_error) {
1190 c1->c_c_error->c_text = p->pq_error;
1191 p->pq_error = NULL;
1192 }
1193
1194 fmt_scan (c1->c_fmt, scanl, BUFSIZ - 1, dat, NULL);
1195 buffer = charstring_buffer_copy (scanl);
1196 if (*buffer) {
1197 if (c2->c_text)
1198 c2->c_text = add (",\n", c2->c_text);
1199 if (*(cp = buffer + strlen (buffer) - 1) == '\n')
1200 *cp = 0;
1201 c2->c_text = add (buffer, c2->c_text);
1202 }
1203 charstring_free (scanl);
1204
1205 free(p->pq_text);
1206 free(p->pq_error);
1207 q = p->pq_next;
1208 free(p);
1209 }
1210
1211 c2->c_text = add ("\n", c2->c_text);
1212 free (ap);
1213 }
1214
1215
1216 static struct mcomp *
1217 add_queue (struct mcomp **head, struct mcomp **tail, char *name, char *text, int flags)
1218 {
1219 struct mcomp *c1;
1220
1221 NEW0(c1);
1222 c1->c_flags = flags & ~INIT;
1223 if ((c1->c_name = name ? mh_xstrdup(name) : NULL))
1224 c1->c_flags |= mcomp_flags (c1->c_name);
1225 c1->c_text = text ? mh_xstrdup(text) : NULL;
1226 if (flags & INIT) {
1227 if (global.c_ovtxt)
1228 c1->c_ovtxt = mh_xstrdup(global.c_ovtxt);
1229 c1->c_offset = global.c_offset;
1230 c1->c_ovoff = global. c_ovoff;
1231 c1->c_width = c1->c_length = 0;
1232 c1->c_cwidth = global.c_cwidth;
1233 c1->c_flags |= global.c_flags & GFLAGS;
1234 }
1235 if (*head == NULL)
1236 *head = c1;
1237 if (*tail != NULL)
1238 (*tail)->c_next = c1;
1239 *tail = c1;
1240
1241 return c1;
1242 }
1243
1244
1245 static void
1246 free_queue (struct mcomp **head, struct mcomp **tail)
1247 {
1248 struct mcomp *c1, *c2;
1249
1250 for (c1 = *head; c1; c1 = c2) {
1251 c2 = c1->c_next;
1252 free(c1->c_name);
1253 free(c1->c_text);
1254 free(c1->c_ovtxt);
1255 free(c1->c_nfs);
1256 if (c1->c_fmt)
1257 fmt_free (c1->c_fmt, 0);
1258 free(c1);
1259 }
1260
1261 *head = *tail = NULL;
1262 }
1263
1264
1265 static void
1266 putcomp (struct mcomp *c1, struct mcomp *c2, int flag)
1267 {
1268 char *text; /* c1's text, or the name as a fallback. */
1269 char *trimmed_prefix;
1270 int count, cchdr;
1271 char *cp;
1272 const int utf8 = strcasecmp(get_charset(), "UTF-8") == 0;
1273
1274 if (! utf8 && flag != BODYCOMP) {
1275 /* Don't print 8-bit bytes in header field values if not in a
1276 UTF-8 locale, as required by RFC 6532. */
1277 c1->c_flags |= FORCE7BIT;
1278 }
1279
1280 text = c1->c_text ? c1->c_text : c1->c_name;
1281 /* Create a copy with trailing whitespace trimmed, for use with
1282 * blank lines. */
1283 trimmed_prefix = rtrim(mh_xstrdup(FENDNULL(text)));
1284
1285 cchdr = 0;
1286 lm = 0;
1287 llim = c1->c_length ? c1->c_length : -1;
1288 wid = c1->c_width ? c1->c_width : global.c_width;
1289 ovoff = (c1->c_ovoff >= 0 ? c1->c_ovoff : global.c_ovoff)
1290 + c1->c_offset;
1291 if ((ovtxt = c1->c_ovtxt ? c1->c_ovtxt : global.c_ovtxt) == NULL)
1292 ovtxt = "";
1293 if (wid < ovoff + strlen (ovtxt) + 5)
1294 mhladios(NULL, "component: %s width(%d) too small for overflow(%zu)",
1295 c1->c_name, wid, ovoff + strlen (ovtxt) + 5);
1296 onelp = NULL;
1297
1298 if (c1->c_flags & CLEARTEXT) {
1299 putstr (c1->c_flags & RTRIM ? rtrim (c1->c_text) : c1->c_text,
1300 c1->c_flags);
1301 putstr ("\n", c1->c_flags);
1302 return;
1303 }
1304
1305 if (c1->c_nfs && (c1->c_flags & (ADDRFMT | DATEFMT | FORMAT)))
1306 mcomp_format (c1, c2);
1307
1308 if (c1->c_flags & CENTER) {
1309 count = (c1->c_width ? c1->c_width : global.c_width)
1310 - c1->c_offset - strlen (c2->c_text);
1311 if (!(c1->c_flags & HDROUTPUT) && !(c1->c_flags & NOCOMPONENT))
1312 count -= strlen(text) + 2;
1313 lm = c1->c_offset + (count / 2);
1314 } else {
1315 if (c1->c_offset)
1316 lm = c1->c_offset;
1317 }
1318
1319 if (!(c1->c_flags & HDROUTPUT) && !(c1->c_flags & NOCOMPONENT)) {
1320 if (c1->c_flags & UPPERCASE) /* uppercase component also */
1321 to_upper(text);
1322 putstr(text, c1->c_flags);
1323 if (flag != BODYCOMP) {
1324 putstr (": ", c1->c_flags);
1325 if (!(c1->c_flags & SPLIT))
1326 c1->c_flags |= HDROUTPUT;
1327
1328 cchdr++;
1329 if ((count = c1->c_cwidth - strlen(text) - 2) > 0)
1330 while (count--)
1331 putstr (" ", c1->c_flags);
1332 }
1333 else
1334 c1->c_flags |= HDROUTPUT; /* for BODYCOMP */
1335 }
1336
1337 if (flag == TWOCOMP
1338 && !(c2->c_flags & HDROUTPUT)
1339 && !(c2->c_flags & NOCOMPONENT)) {
1340 if (c1->c_flags & UPPERCASE)
1341 to_upper(c2->c_name);
1342 putstr (c2->c_name, c1->c_flags);
1343 putstr (": ", c1->c_flags);
1344 if (!(c1->c_flags & SPLIT))
1345 c2->c_flags |= HDROUTPUT;
1346
1347 cchdr++;
1348 if ((count = c1->c_cwidth - strlen (c2->c_name) - 2) > 0)
1349 while (count--)
1350 putstr (" ", c1->c_flags);
1351 }
1352 if (c1->c_flags & UPPERCASE)
1353 to_upper(c2->c_text);
1354
1355 count = 0;
1356 if (cchdr) {
1357 if (flag == TWOCOMP)
1358 count = (c1->c_cwidth >= 0) ? c1->c_cwidth
1359 : (int) strlen (c2->c_name) + 2;
1360 else
1361 count = (c1->c_cwidth >= 0) ? (size_t) c1->c_cwidth
1362 : strlen(text) + 2;
1363 }
1364 count += c1->c_offset;
1365
1366 if ((cp = oneline (c2->c_text, c1->c_flags)))
1367 /* Output line, trimming trailing whitespace if requested. */
1368 putstr (c1->c_flags & RTRIM ? rtrim (cp) : cp, c1->c_flags);
1369 if (term == '\n')
1370 putstr ("\n", c1->c_flags);
1371 while ((cp = oneline (c2->c_text, c1->c_flags))) {
1372 lm = count;
1373 if (flag == BODYCOMP
1374 && !(c1->c_flags & NOCOMPONENT)) {
1375 /* Output component, trimming trailing whitespace if there
1376 is no text on the line. */
1377 if (*cp) {
1378 putstr(text, c1->c_flags);
1379 } else {
1380 putstr (trimmed_prefix, c1->c_flags);
1381 }
1382 }
1383 if (*cp) {
1384 /* Output line, trimming trailing whitespace if requested. */
1385 putstr (c1->c_flags & RTRIM ? rtrim (cp) : cp, c1->c_flags);
1386 }
1387 if (term == '\n')
1388 putstr ("\n", c1->c_flags);
1389 }
1390 if (flag == BODYCOMP && term == '\n')
1391 c1->c_flags &= ~HDROUTPUT; /* Buffer ended on a newline */
1392
1393 free (trimmed_prefix);
1394 }
1395
1396
1397 static char *
1398 oneline (char *stuff, unsigned long flags)
1399 {
1400 int spc;
1401 char *cp, *ret;
1402
1403 if (onelp == NULL)
1404 onelp = stuff;
1405 if (*onelp == 0)
1406 return onelp = NULL;
1407
1408 ret = onelp;
1409 term = 0;
1410 if (flags & COMPRESS) {
1411 for (spc = 1, cp = ret; *onelp; onelp++)
1412 if (isspace ((unsigned char) *onelp)) {
1413 if (*onelp == '\n' && (!onelp[1] || (flags & ADDRFMT))) {
1414 term = '\n';
1415 *onelp++ = 0;
1416 break;
1417 }
1418 if (!spc) {
1419 *cp++ = ' ';
1420 spc++;
1421 }
1422 }
1423 else {
1424 *cp++ = *onelp;
1425 spc = 0;
1426 }
1427
1428 *cp = 0;
1429 }
1430 else {
1431 while (*onelp && *onelp != '\n')
1432 onelp++;
1433 if (*onelp == '\n') {
1434 term = '\n';
1435 *onelp++ = 0;
1436 }
1437 if (flags & LEFTADJUST)
1438 while (*ret == ' ' || *ret == '\t')
1439 ret++;
1440 }
1441 if (*onelp == 0 && term == '\n' && (flags & NONEWLINE))
1442 term = 0;
1443
1444 return ret;
1445 }
1446
1447
1448 static void
1449 putstr (char *string, unsigned long flags)
1450 {
1451 /* To not count, for the purpose of counting columns, all of
1452 the bytes of a multibyte character. */
1453 int char_len;
1454
1455 if (!column && lm > 0) {
1456 while (lm > 0)
1457 if (lm >= 8) {
1458 putch ('\t', flags);
1459 lm -= 8;
1460 }
1461 else {
1462 putch (' ', flags);
1463 lm--;
1464 }
1465 }
1466 lm = 0;
1467
1468 #ifdef MULTIBYTE_SUPPORT
1469 if (mbtowc (NULL, NULL, 0)) {} /* reset shift state */
1470 char_len = 0;
1471 #else
1472 NMH_UNUSED (char_len);
1473 #endif
1474
1475 while (*string) {
1476 flags &= ~INVISIBLE;
1477 #ifdef MULTIBYTE_SUPPORT
1478 /* mbtowc should never return 0, because *string is non-NULL. */
1479 if (char_len <= 0) {
1480 /* Find number of bytes in next character. */
1481 if ((char_len =
1482 mbtowc (NULL, string, (size_t) MB_CUR_MAX)) == -1) {
1483 char_len = 1;
1484 }
1485 } else {
1486 /* Multibyte character, after the first byte. */
1487 flags |= INVISIBLE;
1488 }
1489
1490 --char_len;
1491 #endif
1492 putch (*string++, flags);
1493 }
1494 }
1495
1496
1497 static void
1498 putch (char ch, unsigned long flags)
1499 {
1500 if (llim == 0)
1501 return;
1502
1503 switch (ch) {
1504 case '\n':
1505 if (llim > 0)
1506 llim--;
1507 column = 0;
1508 row++;
1509 if (ontty != ISTTY || row != global.c_length)
1510 break;
1511 if (global.c_flags & BELL)
1512 putchar ('\007');
1513 fflush (stdout);
1514 if (linefeed_typed()) {
1515 if (global.c_flags & CLEARSCR)
1516 nmh_clear_screen ();
1517 row = 0;
1518 } else {
1519 putchar ('\n');
1520 row = global.c_length / 3;
1521 }
1522 return;
1523
1524 case '\t':
1525 column |= 07;
1526 column++;
1527 break;
1528
1529 case '\b':
1530 column--;
1531 break;
1532
1533 case '\r':
1534 column = 0;
1535 break;
1536
1537 default:
1538 /*
1539 * If we are forwarding this message, and the first
1540 * column contains a dash, then add a dash and a space.
1541 */
1542 if (column == 0 && forwflg && (dashstuff >= 0) && ch == '-') {
1543 putchar ('-');
1544 putchar (' ');
1545 }
1546 /*
1547 * Increment the character count, unless
1548 * 1) In UTF-8 locale, this is other than the last byte of
1549 a multibyte character, or
1550 * 2) In C locale, will print a non-printable character.
1551 */
1552 if ((flags & FORCE7BIT) == 0) {
1553 /* UTF-8 locale */
1554 if ((flags & INVISIBLE) == 0) {
1555 /* If multibyte character, its first byte only. */
1556 ++column;
1557 }
1558 } else {
1559 /* If not an ASCII character, the replace character will be
1560 displayed. Count it. */
1561 if (! isascii((unsigned char) ch) || isprint((unsigned char) ch)) {
1562 ++column;
1563 }
1564 }
1565 break;
1566 }
1567
1568 if (column >= wid && (flags & NOWRAP) == 0) {
1569 putch ('\n', flags);
1570 if (ovoff > 0)
1571 lm = ovoff;
1572 putstr (FENDNULL(ovtxt), flags);
1573 putch (ch, flags);
1574 return;
1575 }
1576
1577 if (flags & FORCE7BIT && ! isascii((unsigned char) ch)) {
1578 putchar ('?');
1579 } else {
1580 putchar (ch);
1581 }
1582 }
1583
1584 /* linefeed_typed() makes a single read(2) from stdin and returns true
1585 * if a linefeed character is amongst the characters read.
1586 * A read error is treated as if linefeed wasn't typed.
1587 *
1588 * Typing on a TTY can cause read() to return data without typing Enter
1589 * by using the TTY's EOF character instead, normally ASCII EOT, Ctrl-D.
1590 * The linefeed can also be escaped with the TTY's LNEXT character,
1591 * normally ASCII SYN, Ctrl-V, by typing Ctrl-V Ctrl-J.
1592 * It's not possible to distinguish between the user typing a buffer's
1593 * worth of characters and then EOT, or more than the buffer can hold.
1594 * Either way, the result depends on ASCII LF, either from typing Enter
1595 * or an escaped Ctrl-J, being amongst the read characters.
1596 */
1597 static bool linefeed_typed(void)
1598 {
1599 char buf[128];
1600 ssize_t n;
1601
1602 n = read(0, buf, sizeof buf);
1603 if (n == -1) {
1604 advise("stdin", "read");
1605 return false; /* Treat as EOF. */
1606 }
1607
1608 return memchr(buf, '\n', n);
1609 }
1610
1611
1612 static void
1613 intrser (int i)
1614 {
1615 NMH_UNUSED (i);
1616
1617 discard (stdout);
1618 putchar ('\n');
1619 longjmp (env, DONE);
1620 }
1621
1622
1623 static void
1624 pipeser (int i)
1625 {
1626 NMH_UNUSED (i);
1627
1628 mhldone (NOTOK);
1629 }
1630
1631
1632 static void
1633 quitser (int i)
1634 {
1635 NMH_UNUSED (i);
1636
1637 putchar ('\n');
1638 fflush (stdout);
1639 mhldone (NOTOK);
1640 }
1641
1642
1643 static void
1644 mhladios (char *what, char *fmt, ...)
1645 {
1646 va_list ap;
1647
1648 va_start(ap, fmt);
1649 advertise (what, NULL, fmt, ap);
1650 va_end(ap);
1651 mhldone (1);
1652 }
1653
1654
1655 static void
1656 mhldone (int status)
1657 {
1658 exitstat = status;
1659 done (exitstat);
1660 }
1661
1662
1663 /*
1664 * Compile a format string used by the formatfield option and save it
1665 * for later.
1666 *
1667 * We will want the {text} (and possibly {error}) components for later,
1668 * so look for them and save them if we find them.
1669 */
1670
1671 static void
1672 compile_formatfield(struct mcomp *c1)
1673 {
1674 fmt_compile(c1->c_nfs, &c1->c_fmt, 1);
1675
1676 /*
1677 * As a note to myself and any other poor bastard who is looking through
1678 * this code in the future ....
1679 *
1680 * When the format hash table is reset later on (as it almost certainly
1681 * will be), there will still be references to these components in the
1682 * compiled format instructions. Thus these component references will
1683 * be free'd when the format instructions are free'd (by fmt_free()).
1684 *
1685 * So, in other words ... don't go free'ing them yourself!
1686 */
1687
1688 c1->c_c_text = fmt_findcomp("text");
1689 c1->c_c_error = fmt_findcomp("error");
1690 }
1691
1692 /*
1693 * Compile all of the arguments for our format list.
1694 *
1695 * Iterate through the linked list of format strings and compile them.
1696 * Note that we reset the format hash table before we start, but we do NOT
1697 * reset it between calls to fmt_compile().
1698 *
1699 */
1700
1701 static void
1702 compile_filterargs (void)
1703 {
1704 struct arglist *arg = arglist_head;
1705 struct comp *cptr;
1706 char **ap;
1707
1708 fmt_free(NULL, 1);
1709
1710 while (arg) {
1711 fmt_compile(arg->a_nfs, &arg->a_fmt, 0);
1712 arg = arg->a_next;
1713 }
1714
1715 /*
1716 * Search through and mark any components that are address components
1717 */
1718
1719 for (ap = addrcomps; *ap; ap++) {
1720 cptr = fmt_findcomp (*ap);
1721 if (cptr)
1722 cptr->c_type |= CT_ADDR;
1723 }
1724 }
1725
1726 /*
1727 * Filter the body of a message through a specified format program
1728 */
1729
1730 static void
1731 filterbody (struct mcomp *c1, char *buf, int bufsz, int state,
1732 m_getfld_state_t gstate)
1733 {
1734 struct mcomp holder;
1735 char name[NAMESZ];
1736 int fdinput[2], fdoutput[2], waitstat;
1737 ssize_t cc;
1738 pid_t writerpid, filterpid;
1739
1740 /*
1741 * Create pipes so we can communicate with our filter process.
1742 */
1743
1744 if (pipe(fdinput) < 0) {
1745 adios(NULL, "Unable to create input pipe");
1746 }
1747
1748 if (pipe(fdoutput) < 0) {
1749 adios(NULL, "Unable to create output pipe");
1750 }
1751
1752 /*
1753 * Here's what we're doing to do.
1754 *
1755 * - Fork ourselves and start writing data to the write side of the
1756 * input pipe (fdinput[1]).
1757 *
1758 * - Fork and exec our filter program. We set the standard input of
1759 * our filter program to be the read side of our input pipe (fdinput[0]).
1760 * Standard output is set to the write side of our output pipe
1761 * (fdoutput[1]).
1762 *
1763 * - We read from the read side of the output pipe (fdoutput[0]).
1764 *
1765 * We're forking because that's the simplest way to prevent any deadlocks.
1766 * (without doing something like switching to non-blocking I/O and using
1767 * select or poll, and I'm not interested in doing that).
1768 */
1769
1770 switch (writerpid = fork()) {
1771 case 0:
1772 /*
1773 * Our child process - just write to the filter input (fdinput[1]).
1774 * Close all other descriptors that we don't need.
1775 */
1776
1777 close(fdinput[0]);
1778 close(fdoutput[0]);
1779 close(fdoutput[1]);
1780
1781 /*
1782 * Call m_getfld2() until we're no longer in the BODY state
1783 */
1784
1785 while (state == BODY) {
1786 int bufsz2 = bufsz;
1787 if (write(fdinput[1], buf, strlen(buf)) < 0) {
1788 advise ("pipe output", "write");
1789 }
1790 state = m_getfld2(&gstate, name, buf, &bufsz2);
1791 }
1792
1793 /*
1794 * We should be done; time to exit.
1795 */
1796
1797 close(fdinput[1]);
1798 /*
1799 * Make sure we call _exit(), otherwise we may flush out the stdio
1800 * buffers that we have duplicated from the parent.
1801 */
1802 _exit(0);
1803 case -1:
1804 adios(NULL, "Unable to fork for filter writer process");
1805 break;
1806 }
1807
1808 /*
1809 * Fork and exec() our filter program, after redirecting standard in
1810 * and standard out appropriately.
1811 */
1812
1813 switch (filterpid = fork()) {
1814 char **args, *program;
1815 struct arglist *a;
1816 int i, dat[5], s, argp;
1817
1818 case 0:
1819 /*
1820 * Configure an argument array for us
1821 */
1822
1823 args = argsplit(formatproc, &program, &argp);
1824 args[argp + filter_nargs] = NULL;
1825 dat[0] = 0;
1826 dat[1] = 0;
1827 dat[2] = 0;
1828 dat[3] = BUFSIZ;
1829 dat[4] = 0;
1830
1831 /*
1832 * Pull out each argument and scan them.
1833 */
1834
1835 for (a = arglist_head, i = argp; a != NULL; a = a->a_next, i++) {
1836 charstring_t scanl = charstring_create (BUFSIZ);
1837
1838 fmt_scan(a->a_fmt, scanl, BUFSIZ, dat, NULL);
1839 args[i] = charstring_buffer_copy (scanl);
1840 charstring_free (scanl);
1841 /*
1842 * fmt_scan likes to put a trailing newline at the end of the
1843 * format string. If we have one, get rid of it.
1844 */
1845 s = strlen(args[i]);
1846 if (args[i][s - 1] == '\n')
1847 args[i][s - 1] = '\0';
1848
1849 if (mhldebug)
1850 fprintf(stderr, "filterarg: fmt=\"%s\", output=\"%s\"\n",
1851 a->a_nfs, args[i]);
1852 }
1853
1854 if (dup2(fdinput[0], STDIN_FILENO) < 0) {
1855 adios("formatproc", "Unable to dup2() standard input");
1856 }
1857 if (dup2(fdoutput[1], STDOUT_FILENO) < 0) {
1858 adios("formatproc", "Unable to dup2() standard output");
1859 }
1860
1861 /*
1862 * Close everything (especially the old input and output
1863 * descriptors, since they've been dup'd to stdin and stdout),
1864 * and exec the formatproc.
1865 */
1866
1867 close(fdinput[0]);
1868 close(fdinput[1]);
1869 close(fdoutput[0]);
1870 close(fdoutput[1]);
1871
1872 execvp(formatproc, args);
1873
1874 adios(formatproc, "Unable to execute filter");
1875
1876 break;
1877
1878 case -1:
1879 adios(NULL, "Unable to fork format program");
1880 }
1881
1882 /*
1883 * Close everything except our reader (fdoutput[0]);
1884 */
1885
1886 close(fdinput[0]);
1887 close(fdinput[1]);
1888 close(fdoutput[1]);
1889
1890 /*
1891 * As we read in this data, send it to putcomp
1892 */
1893
1894 holder.c_text = buf;
1895
1896 while ((cc = read(fdoutput[0], buf, bufsz - 1)) > 0) {
1897 buf[cc] = '\0';
1898 putcomp(c1, &holder, BODYCOMP);
1899 }
1900
1901 if (cc < 0) {
1902 adios(NULL, "reading from formatproc");
1903 }
1904
1905 /*
1906 * See if we got any errors along the way. I'm a little leery of calling
1907 * waitpid() without WNOHANG, but it seems to be the most correct solution.
1908 */
1909
1910 if (waitpid(filterpid, &waitstat, 0) < 0) {
1911 if (errno != ECHILD) {
1912 adios("filterproc", "Unable to determine status");
1913 }
1914 } else {
1915 if (! (WIFEXITED(waitstat) && WEXITSTATUS(waitstat) == 0)) {
1916 pidstatus(waitstat, stderr, "filterproc");
1917 }
1918 }
1919
1920 if (waitpid(writerpid, &waitstat, 0) < 0) {
1921 if (errno != ECHILD) {
1922 adios("writer process", "Unable to determine status");
1923 done(1);
1924 }
1925 } else {
1926 if (! (WIFEXITED(waitstat) && WEXITSTATUS(waitstat) == 0)) {
1927 pidstatus(waitstat, stderr, "writer process");
1928 done(1);
1929 }
1930 }
1931
1932 close(fdoutput[0]);
1933 }