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