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