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