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