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