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