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