]> diplodocus.org Git - nmh/blob - uip/mhlsbr.c
Fixed mhshow part markers when displaying multiple messages.
[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 holder.c_text = mh_xmalloc (sizeof(buf));
1082 strncpy (holder.c_text, buf, sizeof(buf));
1083 while (state == BODY) {
1084 putcomp (c1, &holder, BODYCOMP);
1085 bufsz = sizeof buf;
1086 state = m_getfld2(&gstate, name, holder.c_text,
1087 &bufsz);
1088 }
1089 free (holder.c_text);
1090 holder.c_text = NULL;
1091 }
1092 continue;
1093 }
1094 for (c2 = msghd; c2; c2 = c2->c_next)
1095 if (!strcasecmp (FENDNULL(c2->c_name),
1096 FENDNULL(c1->c_name))) {
1097 putcomp (c1, c2, ONECOMP);
1098 if (!(c1->c_flags & SPLIT))
1099 break;
1100 }
1101 }
1102 m_getfld_state_destroy (&gstate);
1103 return;
1104
1105 case LENERR:
1106 case FMTERR:
1107 inform("format error in message %s", mname);
1108 exitstat++;
1109 m_getfld_state_destroy (&gstate);
1110 return;
1111
1112 default:
1113 mhladios (NULL, "getfld() returned %d", state);
1114 }
1115 }
1116 }
1117
1118
1119 static int
1120 mcomp_flags (char *name)
1121 {
1122 struct pair *ap;
1123
1124 for (ap = pairs; ap->p_name; ap++)
1125 if (!strcasecmp (ap->p_name, name))
1126 return ap->p_flags;
1127
1128 return 0;
1129 }
1130
1131
1132 static char *
1133 mcomp_add (unsigned long flags, char *s1, char *s2)
1134 {
1135 char *dp;
1136
1137 if (!(flags & ADDRFMT))
1138 return add (s1, s2);
1139
1140 if (s2 && *(dp = s2 + strlen (s2) - 1) == '\n')
1141 *dp = 0;
1142
1143 return add (s1, add (",\n", s2));
1144 }
1145
1146
1147 struct pqpair {
1148 char *pq_text;
1149 char *pq_error;
1150 struct pqpair *pq_next;
1151 };
1152
1153
1154 static void
1155 mcomp_format (struct mcomp *c1, struct mcomp *c2)
1156 {
1157 int dat[5];
1158 char *ap, *cp;
1159 char error[BUFSIZ];
1160 struct pqpair *p, *q;
1161 struct pqpair pq;
1162 struct mailname *mp;
1163
1164 ap = c2->c_text;
1165 c2->c_text = NULL;
1166 dat[0] = 0;
1167 dat[1] = 0;
1168 dat[2] = filesize;
1169 dat[3] = BUFSIZ - 1;
1170 dat[4] = 0;
1171
1172 if (!(c1->c_flags & ADDRFMT)) {
1173 charstring_t scanl = charstring_create (BUFSIZ);
1174
1175 if (c1->c_c_text)
1176 c1->c_c_text->c_text = ap;
1177 if ((cp = strrchr(ap, '\n'))) /* drop ending newline */
1178 if (!cp[1])
1179 *cp = 0;
1180
1181 fmt_scan (c1->c_fmt, scanl, BUFSIZ - 1, dat, NULL);
1182 /* Don't need to append a newline, dctime() already did */
1183 c2->c_text = charstring_buffer_copy (scanl);
1184 charstring_free (scanl);
1185
1186 /* ap is now owned by the component struct, so do NOT free it here */
1187 return;
1188 }
1189
1190 (q = &pq)->pq_next = NULL;
1191 while ((cp = getname (ap))) {
1192 NEW0(p);
1193 if ((mp = getm (cp, NULL, 0, error, sizeof(error))) == NULL) {
1194 p->pq_text = mh_xstrdup(cp);
1195 p->pq_error = mh_xstrdup(error);
1196 } else {
1197 p->pq_text = getcpy (mp->m_text);
1198 mnfree (mp);
1199 }
1200 q = (q->pq_next = p);
1201 }
1202
1203 for (p = pq.pq_next; p; p = q) {
1204 charstring_t scanl = charstring_create (BUFSIZ);
1205 char *buffer;
1206
1207 if (c1->c_c_text) {
1208 c1->c_c_text->c_text = p->pq_text;
1209 p->pq_text = NULL;
1210 }
1211 if (c1->c_c_error) {
1212 c1->c_c_error->c_text = p->pq_error;
1213 p->pq_error = NULL;
1214 }
1215
1216 fmt_scan (c1->c_fmt, scanl, BUFSIZ - 1, dat, NULL);
1217 buffer = charstring_buffer_copy (scanl);
1218 if (*buffer) {
1219 if (c2->c_text)
1220 c2->c_text = add (",\n", c2->c_text);
1221 if (*(cp = buffer + strlen (buffer) - 1) == '\n')
1222 *cp = 0;
1223 c2->c_text = add (buffer, c2->c_text);
1224 }
1225 charstring_free (scanl);
1226
1227 free(p->pq_text);
1228 free(p->pq_error);
1229 q = p->pq_next;
1230 free(p);
1231 }
1232
1233 c2->c_text = add ("\n", c2->c_text);
1234 free (ap);
1235 }
1236
1237
1238 static struct mcomp *
1239 add_queue (struct mcomp **head, struct mcomp **tail, char *name, char *text, int flags)
1240 {
1241 struct mcomp *c1;
1242
1243 NEW0(c1);
1244 c1->c_flags = flags & ~INIT;
1245 if ((c1->c_name = name ? mh_xstrdup(name) : NULL))
1246 c1->c_flags |= mcomp_flags (c1->c_name);
1247 c1->c_text = text ? mh_xstrdup(text) : NULL;
1248 if (flags & INIT) {
1249 if (global.c_ovtxt)
1250 c1->c_ovtxt = mh_xstrdup(global.c_ovtxt);
1251 c1->c_offset = global.c_offset;
1252 c1->c_ovoff = global. c_ovoff;
1253 c1->c_width = c1->c_length = 0;
1254 c1->c_cwidth = global.c_cwidth;
1255 c1->c_flags |= global.c_flags & GFLAGS;
1256 }
1257 if (*head == NULL)
1258 *head = c1;
1259 if (*tail != NULL)
1260 (*tail)->c_next = c1;
1261 *tail = c1;
1262
1263 return c1;
1264 }
1265
1266
1267 static void
1268 free_queue (struct mcomp **head, struct mcomp **tail)
1269 {
1270 struct mcomp *c1, *c2;
1271
1272 for (c1 = *head; c1; c1 = c2) {
1273 c2 = c1->c_next;
1274 free(c1->c_name);
1275 free(c1->c_text);
1276 free(c1->c_ovtxt);
1277 free(c1->c_nfs);
1278 if (c1->c_fmt)
1279 fmt_free (c1->c_fmt, 0);
1280 free(c1);
1281 }
1282
1283 *head = *tail = NULL;
1284 }
1285
1286
1287 static void
1288 putcomp (struct mcomp *c1, struct mcomp *c2, int flag)
1289 {
1290 char *text; /* c1's text, or the name as a fallback. */
1291 char *trimmed_prefix;
1292 int count;
1293 bool cchdr;
1294 char *cp;
1295 const int utf8 = strcasecmp(get_charset(), "UTF-8") == 0;
1296
1297 if (! utf8 && flag != BODYCOMP) {
1298 /* Don't print 8-bit bytes in header field values if not in a
1299 UTF-8 locale, as required by RFC 6532. */
1300 c1->c_flags |= FORCE7BIT;
1301 }
1302
1303 text = c1->c_text ? c1->c_text : c1->c_name;
1304 /* Create a copy with trailing whitespace trimmed, for use with
1305 * blank lines. */
1306 trimmed_prefix = rtrim(mh_xstrdup(FENDNULL(text)));
1307
1308 cchdr = false;
1309 lm = 0;
1310 llim = c1->c_length ? c1->c_length : -1;
1311 wid = c1->c_width ? c1->c_width : global.c_width;
1312 ovoff = (c1->c_ovoff >= 0 ? c1->c_ovoff : global.c_ovoff)
1313 + c1->c_offset;
1314 if ((ovtxt = c1->c_ovtxt ? c1->c_ovtxt : global.c_ovtxt) == NULL)
1315 ovtxt = "";
1316 if (wid < ovoff + strlen (ovtxt) + 5)
1317 mhladios(NULL, "component: %s width(%d) too small for overflow(%zu)",
1318 c1->c_name, wid, ovoff + strlen (ovtxt) + 5);
1319 onelp = NULL;
1320
1321 if (c1->c_flags & CLEARTEXT) {
1322 putstr (c1->c_flags & RTRIM ? rtrim (c1->c_text) : c1->c_text,
1323 c1->c_flags);
1324 putstr ("\n", c1->c_flags);
1325 return;
1326 }
1327
1328 if (c1->c_nfs && (c1->c_flags & (ADDRFMT | DATEFMT | FORMAT)))
1329 mcomp_format (c1, c2);
1330
1331 if (c1->c_flags & CENTER) {
1332 count = (c1->c_width ? c1->c_width : global.c_width)
1333 - c1->c_offset - strlen (c2->c_text);
1334 if (!(c1->c_flags & HDROUTPUT) && !(c1->c_flags & NOCOMPONENT))
1335 count -= strlen(text) + 2;
1336 lm = c1->c_offset + (count / 2);
1337 } else {
1338 if (c1->c_offset)
1339 lm = c1->c_offset;
1340 }
1341
1342 if (!(c1->c_flags & HDROUTPUT) && !(c1->c_flags & NOCOMPONENT)) {
1343 if (c1->c_flags & UPPERCASE) /* uppercase component also */
1344 to_upper(text);
1345 putstr(text, c1->c_flags);
1346 if (flag != BODYCOMP) {
1347 putstr (": ", c1->c_flags);
1348 if (!(c1->c_flags & SPLIT))
1349 c1->c_flags |= HDROUTPUT;
1350
1351 cchdr = true;
1352 if ((count = c1->c_cwidth - strlen(text) - 2) > 0)
1353 while (count--)
1354 putstr (" ", c1->c_flags);
1355 }
1356 else
1357 c1->c_flags |= HDROUTPUT; /* for BODYCOMP */
1358 }
1359
1360 if (flag == TWOCOMP
1361 && !(c2->c_flags & HDROUTPUT)
1362 && !(c2->c_flags & NOCOMPONENT)) {
1363 if (c1->c_flags & UPPERCASE)
1364 to_upper(c2->c_name);
1365 putstr (c2->c_name, c1->c_flags);
1366 putstr (": ", c1->c_flags);
1367 if (!(c1->c_flags & SPLIT))
1368 c2->c_flags |= HDROUTPUT;
1369
1370 cchdr = true;
1371 if ((count = c1->c_cwidth - strlen (c2->c_name) - 2) > 0)
1372 while (count--)
1373 putstr (" ", c1->c_flags);
1374 }
1375 if (c1->c_flags & UPPERCASE)
1376 to_upper(c2->c_text);
1377
1378 count = 0;
1379 if (cchdr) {
1380 if (flag == TWOCOMP)
1381 count = (c1->c_cwidth >= 0) ? c1->c_cwidth
1382 : (int) strlen (c2->c_name) + 2;
1383 else
1384 count = (c1->c_cwidth >= 0) ? (size_t) c1->c_cwidth
1385 : strlen(text) + 2;
1386 }
1387 count += c1->c_offset;
1388
1389 if ((cp = oneline (c2->c_text, c1->c_flags)))
1390 /* Output line, trimming trailing whitespace if requested. */
1391 putstr (c1->c_flags & RTRIM ? rtrim (cp) : cp, c1->c_flags);
1392 if (term == '\n')
1393 putstr ("\n", c1->c_flags);
1394 while ((cp = oneline (c2->c_text, c1->c_flags))) {
1395 lm = count;
1396 if (flag == BODYCOMP
1397 && !(c1->c_flags & NOCOMPONENT)) {
1398 /* Output component, trimming trailing whitespace if there
1399 is no text on the line. */
1400 if (*cp) {
1401 putstr(text, c1->c_flags);
1402 } else {
1403 putstr (trimmed_prefix, c1->c_flags);
1404 }
1405 }
1406 if (*cp) {
1407 /* Output line, trimming trailing whitespace if requested. */
1408 putstr (c1->c_flags & RTRIM ? rtrim (cp) : cp, c1->c_flags);
1409 }
1410 if (term == '\n')
1411 putstr ("\n", c1->c_flags);
1412 }
1413 if (flag == BODYCOMP && term == '\n')
1414 c1->c_flags &= ~HDROUTPUT; /* Buffer ended on a newline */
1415
1416 free (trimmed_prefix);
1417 }
1418
1419
1420 static char *
1421 oneline (char *stuff, unsigned long flags)
1422 {
1423 bool spc;
1424 char *cp, *ret;
1425
1426 if (onelp == NULL)
1427 onelp = stuff;
1428 if (*onelp == 0)
1429 return onelp = NULL;
1430
1431 ret = onelp;
1432 term = 0;
1433 if (flags & COMPRESS) {
1434 for (spc = true, cp = ret; *onelp; onelp++)
1435 if (isspace ((unsigned char) *onelp)) {
1436 if (*onelp == '\n' && (!onelp[1] || (flags & ADDRFMT))) {
1437 term = '\n';
1438 *onelp++ = 0;
1439 break;
1440 }
1441 if (!spc) {
1442 *cp++ = ' ';
1443 spc = true;
1444 }
1445 }
1446 else {
1447 *cp++ = *onelp;
1448 spc = false;
1449 }
1450
1451 *cp = 0;
1452 }
1453 else {
1454 while (*onelp && *onelp != '\n')
1455 onelp++;
1456 if (*onelp == '\n') {
1457 term = '\n';
1458 *onelp++ = 0;
1459 }
1460 if (flags & LEFTADJUST)
1461 while (*ret == ' ' || *ret == '\t')
1462 ret++;
1463 }
1464 if (*onelp == 0 && term == '\n' && (flags & NONEWLINE))
1465 term = 0;
1466
1467 return ret;
1468 }
1469
1470
1471 static void
1472 putstr (char *string, unsigned long flags)
1473 {
1474 /* To not count, for the purpose of counting columns, all of
1475 the bytes of a multibyte character. */
1476 int char_len;
1477
1478 if (!column && lm > 0) {
1479 while (lm > 0)
1480 if (lm >= 8) {
1481 putch ('\t', flags);
1482 lm -= 8;
1483 }
1484 else {
1485 putch (' ', flags);
1486 lm--;
1487 }
1488 }
1489 lm = 0;
1490
1491 #ifdef MULTIBYTE_SUPPORT
1492 if (mbtowc (NULL, NULL, 0)) {} /* reset shift state */
1493 char_len = 0;
1494 #else
1495 NMH_UNUSED (char_len);
1496 #endif
1497
1498 while (*string) {
1499 flags &= ~INVISIBLE;
1500 #ifdef MULTIBYTE_SUPPORT
1501 /* mbtowc should never return 0, because *string is non-NULL. */
1502 if (char_len <= 0) {
1503 /* Find number of bytes in next character. */
1504 if ((char_len =
1505 mbtowc (NULL, string, (size_t) MB_CUR_MAX)) == -1) {
1506 char_len = 1;
1507 }
1508 } else {
1509 /* Multibyte character, after the first byte. */
1510 flags |= INVISIBLE;
1511 }
1512
1513 --char_len;
1514 #endif
1515 putch (*string++, flags);
1516 }
1517 }
1518
1519
1520 static void
1521 putch (char ch, unsigned long flags)
1522 {
1523 if (llim == 0)
1524 return;
1525
1526 switch (ch) {
1527 case '\n':
1528 if (llim > 0)
1529 llim--;
1530 column = 0;
1531 row++;
1532 if (ontty != ISTTY || row != global.c_length)
1533 break;
1534 if (global.c_flags & BELL)
1535 putchar ('\007');
1536 fflush (stdout);
1537 if (linefeed_typed()) {
1538 if (global.c_flags & CLEARSCR)
1539 nmh_clear_screen ();
1540 row = 0;
1541 } else {
1542 putchar ('\n');
1543 row = global.c_length / 3;
1544 }
1545 return;
1546
1547 case '\t':
1548 column |= 07;
1549 column++;
1550 break;
1551
1552 case '\b':
1553 column--;
1554 break;
1555
1556 case '\r':
1557 column = 0;
1558 break;
1559
1560 default:
1561 /*
1562 * If we are forwarding this message, and the first
1563 * column contains a dash, then add a dash and a space.
1564 */
1565 if (column == 0 && forwflg && (dashstuff >= 0) && ch == '-') {
1566 putchar ('-');
1567 putchar (' ');
1568 }
1569 /*
1570 * Increment the character count, unless
1571 * 1) In UTF-8 locale, this is other than the last byte of
1572 a multibyte character, or
1573 * 2) In C locale, will print a non-printable character.
1574 */
1575 if ((flags & FORCE7BIT) == 0) {
1576 /* UTF-8 locale */
1577 if ((flags & INVISIBLE) == 0) {
1578 /* If multibyte character, its first byte only. */
1579 ++column;
1580 }
1581 } else {
1582 /* If not an ASCII character, the replace character will be
1583 displayed. Count it. */
1584 if (! isascii((unsigned char) ch) || isprint((unsigned char) ch)) {
1585 ++column;
1586 }
1587 }
1588 break;
1589 }
1590
1591 if (column >= wid && (flags & NOWRAP) == 0) {
1592 putch ('\n', flags);
1593 if (ovoff > 0)
1594 lm = ovoff;
1595 putstr (FENDNULL(ovtxt), flags);
1596 putch (ch, flags);
1597 return;
1598 }
1599
1600 if (flags & FORCE7BIT && ! isascii((unsigned char) ch)) {
1601 putchar ('?');
1602 } else {
1603 putchar (ch);
1604 }
1605 }
1606
1607 /* linefeed_typed() makes a single read(2) from stdin and returns true
1608 * if a linefeed character is amongst the characters read.
1609 * A read error is treated as if linefeed wasn't typed.
1610 *
1611 * Typing on a TTY can cause read() to return data without typing Enter
1612 * by using the TTY's EOF character instead, normally ASCII EOT, Ctrl-D.
1613 * The linefeed can also be escaped with the TTY's LNEXT character,
1614 * normally ASCII SYN, Ctrl-V, by typing Ctrl-V Ctrl-J.
1615 * It's not possible to distinguish between the user typing a buffer's
1616 * worth of characters and then EOT, or more than the buffer can hold.
1617 * Either way, the result depends on ASCII LF, either from typing Enter
1618 * or an escaped Ctrl-J, being amongst the read characters.
1619 */
1620 static bool
1621 linefeed_typed(void)
1622 {
1623 char buf[128];
1624 ssize_t n;
1625
1626 n = read(0, buf, sizeof buf);
1627 if (n == -1) {
1628 advise("stdin", "read");
1629 return false; /* Treat as EOF. */
1630 }
1631
1632 return memchr(buf, '\n', n);
1633 }
1634
1635
1636 static void
1637 intrser (int i)
1638 {
1639 NMH_UNUSED (i);
1640
1641 discard (stdout);
1642 putchar ('\n');
1643 longjmp (env, DONE);
1644 }
1645
1646
1647 static void
1648 pipeser (int i)
1649 {
1650 NMH_UNUSED (i);
1651
1652 mhldone (NOTOK);
1653 }
1654
1655
1656 static void
1657 quitser (int i)
1658 {
1659 NMH_UNUSED (i);
1660
1661 putchar ('\n');
1662 fflush (stdout);
1663 mhldone (NOTOK);
1664 }
1665
1666
1667 static void
1668 mhladios (char *what, char *fmt, ...)
1669 {
1670 va_list ap;
1671
1672 va_start(ap, fmt);
1673 advertise (what, NULL, fmt, ap);
1674 va_end(ap);
1675 mhldone (1);
1676 }
1677
1678
1679 static void
1680 mhldone (int status)
1681 {
1682 exitstat = status;
1683 done (exitstat);
1684 }
1685
1686
1687 /*
1688 * Compile a format string used by the formatfield option and save it
1689 * for later.
1690 *
1691 * We will want the {text} (and possibly {error}) components for later,
1692 * so look for them and save them if we find them.
1693 */
1694
1695 static void
1696 compile_formatfield(struct mcomp *c1)
1697 {
1698 fmt_compile(c1->c_nfs, &c1->c_fmt, 1);
1699
1700 /*
1701 * As a note to myself and any other poor bastard who is looking through
1702 * this code in the future ....
1703 *
1704 * When the format hash table is reset later on (as it almost certainly
1705 * will be), there will still be references to these components in the
1706 * compiled format instructions. Thus these component references will
1707 * be free'd when the format instructions are free'd (by fmt_free()).
1708 *
1709 * So, in other words ... don't go free'ing them yourself!
1710 */
1711
1712 c1->c_c_text = fmt_findcomp("text");
1713 c1->c_c_error = fmt_findcomp("error");
1714 }
1715
1716 /*
1717 * Compile all of the arguments for our format list.
1718 *
1719 * Iterate through the linked list of format strings and compile them.
1720 * Note that we reset the format hash table before we start, but we do NOT
1721 * reset it between calls to fmt_compile().
1722 *
1723 */
1724
1725 static void
1726 compile_filterargs (void)
1727 {
1728 struct arglist *arg = arglist_head;
1729 struct comp *cptr;
1730 char **ap;
1731
1732 fmt_free(NULL, 1);
1733
1734 while (arg) {
1735 fmt_compile(arg->a_nfs, &arg->a_fmt, 0);
1736 arg = arg->a_next;
1737 }
1738
1739 /*
1740 * Search through and mark any components that are address components
1741 */
1742
1743 for (ap = addrcomps; *ap; ap++) {
1744 cptr = fmt_findcomp (*ap);
1745 if (cptr)
1746 cptr->c_type |= CT_ADDR;
1747 }
1748 }
1749
1750 /*
1751 * Filter the body of a message through a specified format program
1752 */
1753
1754 static void
1755 filterbody (struct mcomp *c1, char *buf, int bufsz, int state,
1756 m_getfld_state_t gstate)
1757 {
1758 struct mcomp holder;
1759 char name[NAMESZ];
1760 int fdinput[2], fdoutput[2], waitstat;
1761 ssize_t cc;
1762 pid_t writerpid, filterpid;
1763
1764 /*
1765 * Create pipes so we can communicate with our filter process.
1766 */
1767
1768 if (pipe(fdinput) < 0) {
1769 die("Unable to create input pipe");
1770 }
1771
1772 if (pipe(fdoutput) < 0) {
1773 die("Unable to create output pipe");
1774 }
1775
1776 /*
1777 * Here's what we're doing to do.
1778 *
1779 * - Fork ourselves and start writing data to the write side of the
1780 * input pipe (fdinput[1]).
1781 *
1782 * - Fork and exec our filter program. We set the standard input of
1783 * our filter program to be the read side of our input pipe (fdinput[0]).
1784 * Standard output is set to the write side of our output pipe
1785 * (fdoutput[1]).
1786 *
1787 * - We read from the read side of the output pipe (fdoutput[0]).
1788 *
1789 * We're forking because that's the simplest way to prevent any deadlocks.
1790 * (without doing something like switching to non-blocking I/O and using
1791 * select or poll, and I'm not interested in doing that).
1792 */
1793
1794 switch (writerpid = fork()) {
1795 case 0:
1796 /*
1797 * Our child process - just write to the filter input (fdinput[1]).
1798 * Close all other descriptors that we don't need.
1799 */
1800
1801 close(fdinput[0]);
1802 close(fdoutput[0]);
1803 close(fdoutput[1]);
1804
1805 /*
1806 * Call m_getfld2() until we're no longer in the BODY state
1807 */
1808
1809 while (state == BODY) {
1810 int bufsz2 = bufsz;
1811 if (write(fdinput[1], buf, strlen(buf)) < 0) {
1812 advise ("pipe output", "write");
1813 }
1814 state = m_getfld2(&gstate, name, buf, &bufsz2);
1815 }
1816
1817 /*
1818 * We should be done; time to exit.
1819 */
1820
1821 close(fdinput[1]);
1822 /*
1823 * Make sure we call _exit(), otherwise we may flush out the stdio
1824 * buffers that we have duplicated from the parent.
1825 */
1826 _exit(0);
1827 case -1:
1828 die("Unable to fork for filter writer process");
1829 break;
1830 }
1831
1832 /*
1833 * Fork and exec() our filter program, after redirecting standard in
1834 * and standard out appropriately.
1835 */
1836
1837 switch (filterpid = fork()) {
1838 char **args, *program;
1839 struct arglist *a;
1840 int i, dat[5], argp;
1841
1842 case 0:
1843 /*
1844 * Configure an argument array for us
1845 */
1846
1847 args = argsplit(formatproc, &program, &argp);
1848 args[argp + filter_nargs] = NULL;
1849 dat[0] = 0;
1850 dat[1] = 0;
1851 dat[2] = 0;
1852 dat[3] = BUFSIZ;
1853 dat[4] = 0;
1854
1855 /*
1856 * Pull out each argument and scan them.
1857 */
1858
1859 for (a = arglist_head, i = argp; a != NULL; a = a->a_next, i++) {
1860 charstring_t scanl = charstring_create (BUFSIZ);
1861
1862 fmt_scan(a->a_fmt, scanl, BUFSIZ, dat, NULL);
1863 args[i] = charstring_buffer_copy (scanl);
1864 charstring_free (scanl);
1865 /* Trim a trailing linefeed that fmt_scan() likes to put at
1866 * the end of the format string. */
1867 trim_suffix_c(args[i], '\n');
1868 if (mhldebug)
1869 fprintf(stderr, "filterarg: fmt=\"%s\", output=\"%s\"\n",
1870 a->a_nfs, args[i]);
1871 }
1872
1873 if (dup2(fdinput[0], STDIN_FILENO) < 0) {
1874 adios("formatproc", "Unable to dup2() standard input");
1875 }
1876 if (dup2(fdoutput[1], STDOUT_FILENO) < 0) {
1877 adios("formatproc", "Unable to dup2() standard output");
1878 }
1879
1880 /*
1881 * Close everything (especially the old input and output
1882 * descriptors, since they've been dup'd to stdin and stdout),
1883 * and exec the formatproc.
1884 */
1885
1886 close(fdinput[0]);
1887 close(fdinput[1]);
1888 close(fdoutput[0]);
1889 close(fdoutput[1]);
1890
1891 execvp(formatproc, args);
1892
1893 adios(formatproc, "Unable to execute filter");
1894
1895 break;
1896
1897 case -1:
1898 die("Unable to fork format program");
1899 }
1900
1901 /*
1902 * Close everything except our reader (fdoutput[0]);
1903 */
1904
1905 close(fdinput[0]);
1906 close(fdinput[1]);
1907 close(fdoutput[1]);
1908
1909 /*
1910 * As we read in this data, send it to putcomp
1911 */
1912
1913 holder.c_text = buf;
1914
1915 while ((cc = read(fdoutput[0], buf, bufsz - 1)) > 0) {
1916 buf[cc] = '\0';
1917 putcomp(c1, &holder, BODYCOMP);
1918 }
1919
1920 if (cc < 0) {
1921 die("reading from formatproc");
1922 }
1923
1924 /*
1925 * See if we got any errors along the way. I'm a little leery of calling
1926 * waitpid() without WNOHANG, but it seems to be the most correct solution.
1927 */
1928
1929 if (waitpid(filterpid, &waitstat, 0) < 0) {
1930 if (errno != ECHILD) {
1931 adios("filterproc", "Unable to determine status");
1932 }
1933 } else {
1934 if (! (WIFEXITED(waitstat) && WEXITSTATUS(waitstat) == 0)) {
1935 pidstatus(waitstat, stderr, "filterproc");
1936 }
1937 }
1938
1939 if (waitpid(writerpid, &waitstat, 0) < 0) {
1940 if (errno != ECHILD) {
1941 adios("writer process", "Unable to determine status");
1942 done(1);
1943 }
1944 } else {
1945 if (! (WIFEXITED(waitstat) && WEXITSTATUS(waitstat) == 0)) {
1946 pidstatus(waitstat, stderr, "writer process");
1947 done(1);
1948 }
1949 }
1950
1951 close(fdoutput[0]);
1952 }