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