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