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