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