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