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