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