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