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