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