Basic work to add arguments to formatproc calls.
[mmh] / uip / mhlsbr.c
1
2 /*
3  * mhlsbr.c -- main routines for nmh message lister
4  *
5  * This code is Copyright (c) 2002, by the authors of nmh.  See the
6  * COPYRIGHT file in the root directory of the nmh distribution for
7  * complete copyright information.
8  */
9
10 #include <h/mh.h>
11 #include <h/signals.h>
12 #include <h/addrsbr.h>
13 #include <h/fmt_scan.h>
14 #include <h/tws.h>
15 #include <h/utils.h>
16 #include <h/m_setjmp.h>
17 #include <signal.h>
18 #include <errno.h>
19 #include <sys/wait.h>
20 #include <sys/types.h>
21
22 /*
23  * MAJOR BUG:
24  * for a component containing addresses, ADDRFMT, if COMPRESS is also
25  * set, then addresses get split wrong (not at the spaces between commas).
26  * To fix this correctly, putstr() should know about "atomic" strings that
27  * must NOT be broken across lines.  That's too difficult for right now
28  * (it turns out that there are a number of degernate cases), so in
29  * oneline(), instead of
30  *
31  *       (*onelp == '\n' && !onelp[1])
32  *
33  * being a terminating condition,
34  *
35  *       (*onelp == '\n' && (!onelp[1] || (flags & ADDRFMT)))
36  *
37  * is used instead.  This cuts the line prematurely, and gives us a much
38  * better chance of getting things right.
39  */
40
41 #define ONECOMP  0
42 #define TWOCOMP  1
43 #define BODYCOMP 2
44
45 #define QUOTE   '\\'
46
47 static struct swit mhlswitches[] = {
48 #define BELLSW         0
49     { "bell", 0 },
50 #define NBELLSW        1
51     { "nobell", 0 },
52 #define CLRSW          2
53     { "clear", 0 },
54 #define NCLRSW         3
55     { "noclear", 0 },
56 #define FACESW         4
57     { "faceproc program", 0 },
58 #define NFACESW        5
59     { "nofaceproc", 0 },
60 #define FOLDSW         6
61     { "folder +folder", 0 },
62 #define FORMSW         7
63     { "form formfile", 0 },
64 #define PROGSW         8
65     { "moreproc program", 0 },
66 #define NPROGSW        9
67     { "nomoreproc", 0 },
68 #define LENSW         10
69     { "length lines", 0 },
70 #define WIDTHSW       11
71     { "width columns", 0 },
72 #define SLEEPSW       12
73     { "sleep seconds",  0 },
74 #define BITSTUFFSW    13
75     { "dashstuffing", -12 },    /* interface from forw */
76 #define NBITSTUFFSW   14
77     { "nodashstuffing", -14 },  /* interface from forw */
78 #define VERSIONSW     15
79     { "version", 0 },
80 #define HELPSW        16
81     { "help", 0 },
82 #define FORW1SW       17
83     { "forward", -7 },          /* interface from forw */
84 #define FORW2SW       18
85     { "forwall", -7 },          /* interface from forw */
86 #define DGSTSW        19
87     { "digest list", -6 },
88 #define VOLUMSW       20
89     { "volume number", -6 },
90 #define ISSUESW       21
91     { "issue number", -5 },
92 #define NBODYSW       22
93     { "nobody", -6 },
94 #define FMTPROCSW     23
95     { "fmtproc program", 0 },
96 #define NFMTPROCSW    24
97     { "nofmtproc", 0 },
98     { NULL, 0 }
99 };
100
101 #define NOCOMPONENT 0x000001    /* don't show component name         */
102 #define UPPERCASE   0x000002    /* display in all upper case         */
103 #define CENTER      0x000004    /* center line                       */
104 #define CLEARTEXT   0x000008    /* cleartext                         */
105 #define EXTRA       0x000010    /* an "extra" component              */
106 #define HDROUTPUT   0x000020    /* already output                    */
107 #define CLEARSCR    0x000040    /* clear screen                      */
108 #define LEFTADJUST  0x000080    /* left justify multiple lines       */
109 #define COMPRESS    0x000100    /* compress text                     */
110 #define ADDRFMT     0x000200    /* contains addresses                */
111 #define BELL        0x000400    /* sound bell at EOP                 */
112 #define DATEFMT     0x000800    /* contains dates                    */
113 #define FORMAT      0x001000    /* parse address/date/RFC-2047 field */
114 #define INIT        0x002000    /* initialize component              */
115 #define FACEFMT     0x004000    /* contains face                     */
116 #define FACEDFLT    0x008000    /* default for face                  */
117 #define SPLIT       0x010000    /* split headers (don't concatenate) */
118 #define NONEWLINE   0x020000    /* don't write trailing newline      */
119 #define NOWRAP      0x040000    /* Don't wrap lines ever             */
120 #define FMTFILTER   0x080000    /* Filter through format filter      */
121 #define LBITS   "\020\01NOCOMPONENT\02UPPERCASE\03CENTER\04CLEARTEXT\05EXTRA\06HDROUTPUT\07CLEARSCR\010LEFTADJUST\011COMPRESS\012ADDRFMT\013BELL\014DATEFMT\015FORMAT\016INIT\017FACEFMT\020FACEDFLT\021SPLIT\022NONEWLINE\023NOWRAP\024FMTFILTER"
122 #define GFLAGS  (NOCOMPONENT | UPPERCASE | CENTER | LEFTADJUST | COMPRESS | SPLIT | NOWRAP)
123
124 /*
125  * A list of format arguments
126  */
127
128 struct arglist {
129     struct format *a_fmt;
130     char *a_nfs;
131     struct arglist *a_next;
132 };
133
134 struct mcomp {
135     char *c_name;               /* component name          */
136     char *c_text;               /* component text          */
137     char *c_ovtxt;              /* text overflow indicator */
138     char *c_nfs;                /* iff FORMAT              */
139     struct format *c_fmt;       /*   ..                    */
140     char *c_face;               /* face designator         */
141     int c_offset;               /* left margin indentation */
142     int c_ovoff;                /* overflow indentation    */
143     int c_width;                /* width of field          */
144     int c_cwidth;               /* width of component      */
145     int c_length;               /* length in lines         */
146     long c_flags;
147     struct arglist *c_f_args;   /* Argument list for filter*/
148     struct arglist *c_f_tail;   /* Pointer to tail of list */
149     int c_nargs;                /* Number of arguments     */
150     struct mcomp *c_next;
151 };
152
153 static struct mcomp *msghd = NULL;
154 static struct mcomp *msgtl = NULL;
155 static struct mcomp *fmthd = NULL;
156 static struct mcomp *fmttl = NULL;
157
158 static struct mcomp global = {
159     NULL, NULL, NULL, NULL, NULL, NULL, 0, -1, 80, -1, 40, BELL, NULL
160 };
161
162 static struct mcomp holder = {
163     NULL, NULL, NULL, NULL, NULL, NULL, 0, 0, 0, 0, 0, NOCOMPONENT, NULL
164 };
165
166 struct pair {
167     char *p_name;
168     long p_flags;
169 };
170
171 static struct pair pairs[] = {
172     { "Date",            DATEFMT },
173     { "From",            ADDRFMT|FACEDFLT },
174     { "Sender",          ADDRFMT },
175     { "Reply-To",        ADDRFMT },
176     { "To",              ADDRFMT },
177     { "cc",              ADDRFMT },
178     { "Bcc",             ADDRFMT },
179     { "Resent-Date",     DATEFMT },
180     { "Resent-From",     ADDRFMT },
181     { "Resent-Sender",   ADDRFMT },
182     { "Resent-Reply-To", ADDRFMT },
183     { "Resent-To",       ADDRFMT },
184     { "Resent-cc",       ADDRFMT },
185     { "Resent-Bcc",      ADDRFMT },
186     { "Face",            FACEFMT },
187     { NULL,              0 }
188 };
189
190 struct triple {
191     char *t_name;
192     long t_on;
193     long t_off;
194 };
195
196 static struct triple triples[] = {
197     { "nocomponent",   NOCOMPONENT, 0 },
198     { "uppercase",     UPPERCASE,   0 },
199     { "nouppercase",   0,           UPPERCASE },
200     { "center",        CENTER,      0 },
201     { "nocenter",      0,           CENTER },
202     { "clearscreen",   CLEARSCR,    0 },
203     { "noclearscreen", 0,           CLEARSCR },
204     { "noclear",       0,           CLEARSCR },
205     { "leftadjust",    LEFTADJUST,  0 },
206     { "noleftadjust",  0,           LEFTADJUST },
207     { "compress",      COMPRESS,    0 },
208     { "nocompress",    0,           COMPRESS },
209     { "split",         SPLIT,       0 },
210     { "nosplit",       0,           SPLIT },
211     { "addrfield",     ADDRFMT,     DATEFMT },
212     { "bell",          BELL,        0 },
213     { "nobell",        0,           BELL },
214     { "datefield",     DATEFMT,     ADDRFMT },
215     { "newline",       0,           NONEWLINE },
216     { "nonewline",     NONEWLINE,   0 },
217     { "wrap",          0,           NOWRAP },
218     { "nowrap",        NOWRAP,      0 },
219     { "format",        FMTFILTER,   0 },
220     { "noformat",      0,           FMTFILTER },
221     { NULL,            0,           0 }
222 };
223
224
225 static int bellflg   = 0;
226 static int clearflg  = 0;
227 static int dashstuff = 0;
228 static int dobody    = 1;
229 static int forwflg   = 0;
230 static int forwall   = 0;
231
232 static int sleepsw = NOTOK;
233
234 static char *digest = NULL;
235 static int volume = 0;
236 static int issue = 0;
237
238 static int exitstat = 0;
239 static int mhldebug = 0;
240
241 #define PITTY   (-1)
242 #define NOTTY   0
243 #define ISTTY   1
244 static int ontty = NOTTY;
245
246 static int row;
247 static unsigned int column;
248
249 static int lm;
250 static int llim;
251 static int ovoff;
252 static int term;
253 static unsigned int wid;
254
255 static char *ovtxt;
256
257 static unsigned char *onelp;
258
259 static char *parptr;
260
261 static int num_ignores = 0;
262 static char *ignores[MAXARGS];
263
264 static  jmp_buf env;
265 static  jmp_buf mhlenv;
266
267 static char delim3[] =          /* from forw.c */
268     "\n----------------------------------------------------------------------\n\n";
269 static char delim4[] = "\n------------------------------\n\n";
270
271 static FILE *(*mhl_action) () = (FILE *(*) ()) 0;
272
273 static struct comp *mhlcomp[128];
274
275 /*
276  * Redefine a couple of functions.
277  * These are undefined later in the code.
278  */
279 #define adios mhladios
280 #define done  mhldone
281
282 /*
283  * prototypes
284  */
285 static void mhl_format (char *, int, int);
286 static int evalvar (struct mcomp *);
287 static int ptoi (char *, int *);
288 static int ptos (char *, char **);
289 static char *parse (void);
290 static void process (char *, char *, int, int);
291 static void mhlfile (FILE *, char *, int, int);
292 static int mcomp_flags (char *);
293 static char *mcomp_add (long, char *, char *);
294 static void mcomp_format (struct mcomp *, struct mcomp *);
295 static struct mcomp *add_queue (struct mcomp **, struct mcomp **, char *, char *, int);
296 static void free_queue (struct mcomp **, struct mcomp **);
297 static void putcomp (struct mcomp *, struct mcomp *, int);
298 static char *oneline (char *, long);
299 static void putstr (char *, long);
300 static void putch (char, long);
301 static void intrser (int);
302 static void pipeser (int);
303 static void quitser (int);
304 static void face_format (struct mcomp *);
305 static int doface (struct mcomp *);
306 static void mhladios (char *, char *, ...);
307 static void mhldone (int);
308 static void m_popen (char *);
309 static void filterbody (struct mcomp *, char *, int, int, FILE *);
310 static int compileargs (struct mcomp *, char *);
311 static int checkcomp (char *, char *);
312 static void addcomp (int, char *, char *);
313 static void freecomps (void);
314 static void freecomptext (void);
315
316
317 int
318 mhl (int argc, char **argv)
319 {
320     int length = 0, nomore = 0;
321     int i, width = 0, vecp = 0;
322     char *cp, *folder = NULL, *form = NULL;
323     char buf[BUFSIZ], *files[MAXARGS];
324     char **argp, **arguments;
325
326     invo_name = r1bindex (argv[0], '/');
327
328     /* read user profile/context */
329     context_read();
330
331     arguments = getarguments (invo_name, argc, argv, 1);
332     argp = arguments;
333
334     if ((cp = getenv ("MHLDEBUG")) && *cp)
335         mhldebug++;
336
337     if ((cp = getenv ("FACEPROC")))
338         faceproc = cp;
339
340     while ((cp = *argp++)) {
341         if (*cp == '-') {
342             switch (smatch (++cp, mhlswitches)) {
343                 case AMBIGSW: 
344                     ambigsw (cp, mhlswitches);
345                     done (1);
346                 case UNKWNSW: 
347                     adios (NULL, "-%s unknown\n", cp);
348
349                 case HELPSW: 
350                     snprintf (buf, sizeof(buf), "%s [switches] [files ...]", invo_name);
351                     print_help (buf, mhlswitches, 1);
352                     done (1);
353                 case VERSIONSW:
354                     print_version(invo_name);
355                     done (1);
356
357                 case BELLSW: 
358                     bellflg = 1;
359                     continue;
360                 case NBELLSW: 
361                     bellflg = -1;
362                     continue;
363
364                 case CLRSW: 
365                     clearflg = 1;
366                     continue;
367                 case NCLRSW: 
368                     clearflg = -1;
369                     continue;
370
371                 case FOLDSW: 
372                     if (!(folder = *argp++) || *folder == '-')
373                         adios (NULL, "missing argument to %s", argp[-2]);
374                     continue;
375                 case FORMSW: 
376                     if (!(form = *argp++) || *form == '-')
377                         adios (NULL, "missing argument to %s", argp[-2]);
378                     continue;
379
380                 case FACESW:
381                     if (!(faceproc = *argp++) || *faceproc == '-')
382                         adios (NULL, "missing argument to %s", argp[-2]);
383                     continue;
384                 case NFACESW:
385                     faceproc = NULL;
386                     continue;
387                 case SLEEPSW:
388                     if (!(cp = *argp++) || *cp == '-')
389                         adios (NULL, "missing argument to %s", argp[-2]);
390                     sleepsw = atoi (cp);/* ZERO ok! */
391                     continue;
392
393                 case PROGSW:
394                     if (!(moreproc = *argp++) || *moreproc == '-')
395                         adios (NULL, "missing argument to %s", argp[-2]);
396                     continue;
397                 case NPROGSW:
398                     nomore++;
399                     continue;
400
401                 case FMTPROCSW:
402                     if (!(formatproc = *argp++) || *formatproc == '-')
403                         adios (NULL, "missing argument to %s", argp[-2]);
404                     continue;
405                 case NFMTPROCSW:
406                     formatproc = NULL;
407                     continue;
408
409                 case LENSW: 
410                     if (!(cp = *argp++) || *cp == '-')
411                         adios (NULL, "missing argument to %s", argp[-2]);
412                     if ((length = atoi (cp)) < 1)
413                         adios (NULL, "bad argument %s %s", argp[-2], cp);
414                     continue;
415                 case WIDTHSW: 
416                     if (!(cp = *argp++) || *cp == '-')
417                         adios (NULL, "missing argument to %s", argp[-2]);
418                     if ((width = atoi (cp)) < 1)
419                         adios (NULL, "bad argument %s %s", argp[-2], cp);
420                     continue;
421
422                 case DGSTSW: 
423                     if (!(digest = *argp++) || *digest == '-')
424                         adios (NULL, "missing argument to %s", argp[-2]);
425                     continue;
426                 case ISSUESW:
427                     if (!(cp = *argp++) || *cp == '-')
428                         adios (NULL, "missing argument to %s", argp[-2]);
429                     if ((issue = atoi (cp)) < 1)
430                         adios (NULL, "bad argument %s %s", argp[-2], cp);
431                     continue;
432                 case VOLUMSW:
433                     if (!(cp = *argp++) || *cp == '-')
434                         adios (NULL, "missing argument to %s", argp[-2]);
435                     if ((volume = atoi (cp)) < 1)
436                         adios (NULL, "bad argument %s %s", argp[-2], cp);
437                     continue;
438
439                 case FORW2SW: 
440                     forwall++;  /* fall */
441                 case FORW1SW: 
442                     forwflg++;
443                     clearflg = -1;/* XXX */
444                     continue;
445
446                 case BITSTUFFSW: 
447                     dashstuff = 1;      /* trinary logic */
448                     continue;
449                 case NBITSTUFFSW: 
450                     dashstuff = -1;     /* trinary logic */
451                     continue;
452
453                 case NBODYSW: 
454                     dobody = 0;
455                     continue;
456             }
457         }
458         files[vecp++] = cp;
459     }
460
461     if (!folder)
462         folder = getenv ("mhfolder");
463
464     if (isatty (fileno (stdout))) {
465         if (!nomore && !sc_hardcopy() && moreproc && *moreproc != '\0') {
466             if (mhl_action) {
467                 SIGNAL (SIGINT, SIG_IGN);
468                 SIGNAL2 (SIGQUIT, quitser);
469             }
470             SIGNAL2 (SIGPIPE, pipeser);
471             m_popen (moreproc);
472             ontty = PITTY;
473         } else {
474             SIGNAL (SIGINT, SIG_IGN);
475             SIGNAL2 (SIGQUIT, quitser);
476             ontty = ISTTY;
477         }
478     } else {
479         ontty = NOTTY;
480     }
481
482     for (i = 0; i < sizeof(mhlcomp)/sizeof(mhlcomp[0]); i++)
483         mhlcomp[i] = NULL;
484
485     mhl_format (form ? form : mhlformat, length, width);
486
487     if (vecp == 0) {
488         process (folder, NULL, 1, vecp = 1);
489     } else {
490         for (i = 0; i < vecp; i++)
491             process (folder, files[i], i + 1, vecp);
492     }
493
494     freecomps();
495
496     if (forwall) {
497         if (digest) {
498             printf ("%s", delim4);
499             if (volume == 0) {
500                 snprintf (buf, sizeof(buf), "End of %s Digest\n", digest);
501             } else {
502                 snprintf (buf, sizeof(buf), "End of %s Digest [Volume %d Issue %d]\n",
503                         digest, volume, issue);
504             }
505             i = strlen (buf);
506             for (cp = buf + i; i > 1; i--)
507                 *cp++ = '*';
508             *cp++ = '\n';
509             *cp = 0;
510             printf ("%s", buf);
511         }
512         else
513             printf ("\n------- End of Forwarded Message%s\n",
514                     vecp > 1 ? "s" : "");
515     }
516
517     fflush(stdout);
518     if(ferror(stdout)){
519             adios("output", "error writing");
520     }
521     
522     if (clearflg > 0 && ontty == NOTTY)
523         clear_screen ();
524
525     if (ontty == PITTY)
526         m_pclose ();
527
528     return exitstat;
529 }
530
531
532 static void
533 mhl_format (char *file, int length, int width)
534 {
535     int i;
536     char *bp, *cp, **ip;
537     char *ap, buffer[BUFSIZ], name[NAMESZ];
538     struct mcomp *c1;
539     struct stat st;
540     FILE *fp;
541     static dev_t dev = 0;
542     static ino_t ino = 0;
543     static time_t mtime = 0;
544
545     if (fmthd != NULL) {
546         if (stat (etcpath (file), &st) != NOTOK
547                 && mtime == st.st_mtime
548                 && dev == st.st_dev
549                 && ino == st.st_ino)
550             goto out;
551         else
552             free_queue (&fmthd, &fmttl);
553     }
554
555     if ((fp = fopen (etcpath (file), "r")) == NULL)
556         adios (file, "unable to open format file");
557
558     if (fstat (fileno (fp), &st) != NOTOK) {
559         mtime = st.st_mtime;
560         dev = st.st_dev;
561         ino = st.st_ino;
562     }
563
564     global.c_ovtxt = global.c_nfs = NULL;
565     global.c_fmt = NULL;
566     global.c_offset = 0;
567     global.c_ovoff = -1;
568     if ((i = sc_width ()) > 5)
569         global.c_width = i;
570     global.c_cwidth = -1;
571     if ((i = sc_length ()) > 5)
572         global.c_length = i - 1;
573     global.c_flags = BELL;              /* BELL is default */
574     *(ip = ignores) = NULL;
575
576     while (vfgets (fp, &ap) == OK) {
577         bp = ap;
578         if (*bp == ';')
579             continue;
580
581         if ((cp = strchr(bp, '\n')))
582             *cp = 0;
583
584         if (*bp == ':') {
585             c1 = add_queue (&fmthd, &fmttl, NULL, bp + 1, CLEARTEXT);
586             continue;
587         }
588
589         parptr = bp;
590         strncpy (name, parse(), sizeof(name));
591         switch (*parptr) {
592             case '\0': 
593             case ',': 
594             case '=': 
595                 /*
596                  * Split this list of fields to ignore, and copy
597                  * it to the end of the current "ignores" list.
598                  */
599                 if (!mh_strcasecmp (name, "ignores")) {
600                     char **tmparray, **p;
601                     int n = 0;
602
603                     /* split the fields */
604                     tmparray = brkstring (getcpy (++parptr), ",", NULL);
605
606                     /* count number of fields split */
607                     p = tmparray;
608                     while (*p++)
609                         n++;
610
611                     /* copy pointers to split fields to ignores array */
612                     ip = copyip (tmparray, ip, MAXARGS - num_ignores);
613                     num_ignores += n;
614                     continue;
615                 }
616                 parptr = bp;
617                 while (*parptr) {
618                     if (evalvar (&global))
619                         adios (NULL, "format file syntax error: %s", bp);
620                     if (*parptr)
621                         parptr++;
622                 }
623                 continue;
624
625             case ':': 
626                 c1 = add_queue (&fmthd, &fmttl, name, NULL, INIT);
627                 while (*parptr == ':' || *parptr == ',') {
628                     parptr++;
629                     if (evalvar (c1))
630                         adios (NULL, "format file syntax error: %s", bp);
631                 }
632                 if (!c1->c_nfs && global.c_nfs) {
633                     if (c1->c_flags & DATEFMT) {
634                         if (global.c_flags & DATEFMT)
635                             c1->c_nfs = getcpy (global.c_nfs);
636                     }
637                     else
638                         if (c1->c_flags & ADDRFMT) {
639                             if (global.c_flags & ADDRFMT)
640                                 c1->c_nfs = getcpy (global.c_nfs);
641                         }
642                 }
643                 continue;
644
645             default: 
646                 adios (NULL, "format file syntax error: %s", bp);
647         }
648     }
649     fclose (fp);
650
651     if (mhldebug) {
652         for (c1 = fmthd; c1; c1 = c1->c_next) {
653             fprintf (stderr, "c1: name=\"%s\" text=\"%s\" ovtxt=\"%s\"\n",
654                     c1->c_name, c1->c_text, c1->c_ovtxt);
655             fprintf (stderr, "\tnfs=0x%x fmt=0x%x\n",
656                      (unsigned int)(unsigned long) c1->c_nfs,
657                      (unsigned int)(unsigned long) c1->c_fmt);
658             fprintf (stderr, "\toffset=%d ovoff=%d width=%d cwidth=%d length=%d\n",
659                     c1->c_offset, c1->c_ovoff, c1->c_width,
660                     c1->c_cwidth, c1->c_length);
661             fprintf (stderr, "\tflags=%s\n",
662                     snprintb (buffer, sizeof(buffer), (unsigned) c1->c_flags, LBITS));
663         }
664     }
665
666 out:
667     if (clearflg == 1) {
668         global.c_flags |= CLEARSCR;
669     } else {
670         if (clearflg == -1)
671             global.c_flags &= ~CLEARSCR;
672     }
673
674     switch (bellflg) {          /* command line may override format file */
675         case 1: 
676             global.c_flags |= BELL;
677             break;
678         case -1: 
679             global.c_flags &= ~BELL;
680             break;
681     }
682
683     if (length)
684         global.c_length = length;
685     if (width)
686         global.c_width = width;
687     if (global.c_length < 5)
688         global.c_length = 10000;
689     if (global.c_width < 5)
690         global.c_width = 10000;
691 }
692
693
694 static int
695 evalvar (struct mcomp *c1)
696 {
697     char *cp, name[NAMESZ];
698     struct triple *ap;
699
700     if (!*parptr)
701         return 0;
702     strncpy (name, parse(), sizeof(name));
703
704     if (!mh_strcasecmp (name, "component")) {
705         if (ptos (name, &c1->c_text))
706             return 1;
707         c1->c_flags &= ~NOCOMPONENT;
708         return 0;
709     }
710
711     if (!mh_strcasecmp (name, "overflowtext"))
712         return ptos (name, &c1->c_ovtxt);
713
714     if (!mh_strcasecmp (name, "formatfield")) {
715         char *nfs;
716
717         if (ptos (name, &cp))
718             return 1;
719         nfs = new_fs (NULL, NULL, cp);
720         c1->c_nfs = getcpy (nfs);
721         c1->c_flags |= FORMAT;
722         return 0;
723     }
724
725     if (!mh_strcasecmp (name, "decode")) {
726         char *nfs;
727
728         nfs = new_fs (NULL, NULL, "%(decode{text})");
729         c1->c_nfs = getcpy (nfs);
730         c1->c_flags |= FORMAT;
731         return 0;
732     }
733
734     if (!mh_strcasecmp (name, "offset"))
735         return ptoi (name, &c1->c_offset);
736     if (!mh_strcasecmp (name, "overflowoffset"))
737         return ptoi (name, &c1->c_ovoff);
738     if (!mh_strcasecmp (name, "width"))
739         return ptoi (name, &c1->c_width);
740     if (!mh_strcasecmp (name, "compwidth"))
741         return ptoi (name, &c1->c_cwidth);
742     if (!mh_strcasecmp (name, "length"))
743         return ptoi (name, &c1->c_length);
744     if (!mh_strcasecmp (name, "nodashstuffing"))
745         return (dashstuff = -1);
746
747     for (ap = triples; ap->t_name; ap++)
748         if (!mh_strcasecmp (ap->t_name, name)) {
749             c1->c_flags |= ap->t_on;
750             c1->c_flags &= ~ap->t_off;
751             return 0;
752         }
753
754    if (!mh_strcasecmp (name, "formatarg")) {
755         char *nfs;
756         int rc;
757
758         if (ptos (name, &cp))
759             return 1;
760         nfs = new_fs (NULL, NULL, cp);
761
762         rc = compileargs(c1, nfs);
763
764         return rc;
765     }
766
767
768     return 1;
769 }
770
771
772 static int
773 ptoi (char *name, int *i)
774 {
775     char *cp;
776
777     if (*parptr++ != '=' || !*(cp = parse ())) {
778         advise (NULL, "missing argument to variable %s", name);
779         return 1;
780     }
781
782     *i = atoi (cp);
783     return 0;
784 }
785
786
787 static int
788 ptos (char *name, char **s)
789 {
790     char c, *cp;
791
792     if (*parptr++ != '=') {
793         advise (NULL, "missing argument to variable %s", name);
794         return 1;
795     }
796
797     if (*parptr != '"') {
798         for (cp = parptr;
799                 *parptr && *parptr != ':' && *parptr != ',';
800                 parptr++)
801             continue;
802     } else {
803         for (cp = ++parptr; *parptr && *parptr != '"'; parptr++)
804             if (*parptr == QUOTE)
805                 if (!*++parptr)
806                     parptr--;
807     }
808     c = *parptr;
809     *parptr = 0;
810     *s = getcpy (cp);
811     if ((*parptr = c) == '"')
812         parptr++;
813     return 0;
814 }
815
816
817 static char *
818 parse (void)
819 {
820     int c;
821     char *cp;
822     static char result[NAMESZ];
823
824     for (cp = result; *parptr && (cp - result < NAMESZ); parptr++) {
825         c = *parptr;
826         if (isalnum (c)
827                 || c == '.'
828                 || c == '-'
829                 || c == '_'
830                 || c =='['
831                 || c == ']')
832             *cp++ = c;
833         else
834             break;
835     }
836     *cp = '\0';
837
838     return result;
839 }
840
841
842 static void
843 process (char *folder, char *fname, int ofilen, int ofilec)
844 {
845     char *cp = NULL;
846     FILE *fp = NULL;
847     struct mcomp *c1;
848
849     switch (m_setjmp (env)) {
850         case OK: 
851             if (fname) {
852                 fp = mhl_action ? (*mhl_action) (fname) : fopen (fname, "r");
853                 if (fp == NULL) {
854                     advise (fname, "unable to open");
855                     exitstat++;
856                     return;
857                 }
858             } else {
859                 fname = "(stdin)";
860                 fp = stdin;
861             }
862             cp = folder ? concat (folder, ":", fname, NULL) : getcpy (fname);
863             if (ontty != PITTY)
864                 SIGNAL (SIGINT, intrser);
865             mhlfile (fp, cp, ofilen, ofilec);  /* FALL THROUGH! */
866
867         default: 
868             if (ontty != PITTY)
869                 SIGNAL (SIGINT, SIG_IGN);
870             if (mhl_action == NULL && fp != stdin)
871                 fclose (fp);
872             free (cp);
873             if (holder.c_text) {
874                 free (holder.c_text);
875                 holder.c_text = NULL;
876             }
877             free_queue (&msghd, &msgtl);
878             for (c1 = fmthd; c1; c1 = c1->c_next)
879                 c1->c_flags &= ~HDROUTPUT;
880             break;
881     }
882
883     freecomptext();
884 }
885
886
887 static void
888 mhlfile (FILE *fp, char *mname, int ofilen, int ofilec)
889 {
890     int state, bucket;
891     struct mcomp *c1, *c2, *c3;
892     char **ip, name[NAMESZ], buf[BUFSIZ];
893
894     if (forwall) {
895         if (digest)
896             printf ("%s", ofilen == 1 ? delim3 : delim4);
897         else {
898             printf ("\n-------");
899             if (ofilen == 1)
900                 printf (" Forwarded Message%s", ofilec > 1 ? "s" : "");
901             else
902                 printf (" Message %d", ofilen);
903             printf ("\n\n");
904         }
905     } else {
906         switch (ontty) {
907             case PITTY: 
908                 if (ofilec > 1) {
909                     if (ofilen > 1) {
910                         if ((global.c_flags & CLEARSCR))
911                             clear_screen ();
912                         else
913                             printf ("\n\n\n");
914                     }
915                     printf (">>> %s\n\n", mname);
916                 }
917                 break;
918
919             case ISTTY: 
920                 strncpy (buf, "\n", sizeof(buf));
921                 if (ofilec > 1) {
922                     if (SOprintf ("Press <return> to list \"%s\"...", mname)) {
923                         if (ofilen > 1)
924                             printf ("\n\n\n");
925                         printf ("Press <return> to list \"%s\"...", mname);
926                     }
927                     fflush (stdout);
928                     buf[0] = 0;
929                     read (fileno (stdout), buf, sizeof(buf));
930                 }
931                 if (strchr(buf, '\n')) {
932                     if ((global.c_flags & CLEARSCR))
933                         clear_screen ();
934                 }
935                 else
936                     printf ("\n");
937                 break;
938
939             default: 
940                 if (ofilec > 1) {
941                     if (ofilen > 1) {
942                         printf ("\n\n\n");
943                         if (clearflg > 0)
944                             clear_screen ();
945                     }
946                     printf (">>> %s\n\n", mname);
947                 }
948                 break;
949         }
950     }
951
952     for (state = FLD;;) {
953         switch (state = m_getfld (state, name, buf, sizeof(buf), fp)) {
954             case FLD: 
955             case FLDPLUS: 
956                 bucket = checkcomp(name, buf);
957                 for (ip = ignores; *ip; ip++)
958                     if (!mh_strcasecmp (name, *ip)) {
959                         while (state == FLDPLUS) {
960                             state = m_getfld (state, name, buf, sizeof(buf), fp);
961                             addcomp(bucket, name, buf);
962                         }
963                         break;
964                     }
965                 if (*ip)
966                     continue;
967
968                 for (c2 = fmthd; c2; c2 = c2->c_next)
969                     if (!mh_strcasecmp (c2->c_name, name))
970                         break;
971                 c1 = NULL;
972                 if (!((c3 = c2 ? c2 : &global)->c_flags & SPLIT))
973                     for (c1 = msghd; c1; c1 = c1->c_next)
974                         if (!mh_strcasecmp (c1->c_name, c3->c_name)) {
975                             c1->c_text =
976                                 mcomp_add (c1->c_flags, buf, c1->c_text);
977                             break;
978                         }
979                 if (c1 == NULL)
980                     c1 = add_queue (&msghd, &msgtl, name, buf, 0);
981                 while (state == FLDPLUS) {
982                     state = m_getfld (state, name, buf, sizeof(buf), fp);
983                     c1->c_text = add (buf, c1->c_text);
984                     addcomp(bucket, name, buf);
985                 }
986                 if (c2 == NULL)
987                     c1->c_flags |= EXTRA;
988                 continue;
989
990             case BODY: 
991             case FILEEOF: 
992                 row = column = 0;
993                 for (c1 = fmthd; c1; c1 = c1->c_next) {
994                     if (c1->c_flags & CLEARTEXT) {
995                         putcomp (c1, c1, ONECOMP);
996                         continue;
997                     }
998                     if (!mh_strcasecmp (c1->c_name, "messagename")) {
999                         holder.c_text = concat ("(Message ", mname, ")\n",
1000                                             NULL);
1001                         putcomp (c1, &holder, ONECOMP);
1002                         free (holder.c_text);
1003                         holder.c_text = NULL;
1004                         continue;
1005                     }
1006                     if (!mh_strcasecmp (c1->c_name, "extras")) {
1007                         for (c2 = msghd; c2; c2 = c2->c_next)
1008                             if (c2->c_flags & EXTRA)
1009                                 putcomp (c1, c2, TWOCOMP);
1010                         continue;
1011                     }
1012                     if (dobody && !mh_strcasecmp (c1->c_name, "body")) {
1013                         if (c1->c_flags & FMTFILTER && state == BODY &&
1014                                                         formatproc != NULL) {
1015                             filterbody(c1, buf, sizeof(buf), state, fp);
1016                         } else {
1017                             holder.c_text = mh_xmalloc (sizeof(buf));
1018                             strncpy (holder.c_text, buf, sizeof(buf));
1019                             while (state == BODY) {
1020                                 putcomp (c1, &holder, BODYCOMP);
1021                                 state = m_getfld (state, name, holder.c_text,
1022                                             sizeof(buf), fp);
1023                             }
1024                             free (holder.c_text);
1025                             holder.c_text = NULL;
1026                         }
1027                         continue;
1028                     }
1029                     for (c2 = msghd; c2; c2 = c2->c_next)
1030                         if (!mh_strcasecmp (c2->c_name, c1->c_name)) {
1031                             putcomp (c1, c2, ONECOMP);
1032                             if (!(c1->c_flags & SPLIT))
1033                                 break;
1034                         }
1035                     if (faceproc && c2 == NULL && (c1->c_flags & FACEFMT))
1036                         for (c2 = msghd; c2; c2 = c2->c_next)
1037                             if (c2->c_flags & FACEDFLT) {
1038                                 if (c2->c_face == NULL)
1039                                     face_format (c2);
1040                                 if ((holder.c_text = c2->c_face)) {
1041                                     putcomp (c1, &holder, ONECOMP);
1042                                     holder.c_text = NULL;
1043                                 }
1044                                 break;
1045                             }
1046                 }
1047                 return;
1048
1049             case LENERR: 
1050             case FMTERR: 
1051                 advise (NULL, "format error in message %s", mname);
1052                 exitstat++;
1053                 return;
1054
1055             default: 
1056                 adios (NULL, "getfld() returned %d", state);
1057         }
1058     }
1059 }
1060
1061
1062 static int
1063 mcomp_flags (char *name)
1064 {
1065     struct pair *ap;
1066
1067     for (ap = pairs; ap->p_name; ap++)
1068         if (!mh_strcasecmp (ap->p_name, name))
1069             return (ap->p_flags);
1070
1071     return 0;
1072 }
1073
1074
1075 static char *
1076 mcomp_add (long flags, char *s1, char *s2)
1077 {
1078     char *dp;
1079
1080     if (!(flags & ADDRFMT))
1081         return add (s1, s2);
1082
1083     if (s2 && *(dp = s2 + strlen (s2) - 1) == '\n')
1084         *dp = 0;
1085
1086     return add (s1, add (",\n", s2));
1087 }
1088
1089
1090 struct pqpair {
1091     char *pq_text;
1092     char *pq_error;
1093     struct pqpair *pq_next;
1094 };
1095
1096
1097 static void
1098 mcomp_format (struct mcomp *c1, struct mcomp *c2)
1099 {
1100     int dat[5];
1101     char *ap, *cp;
1102     char buffer[BUFSIZ], error[BUFSIZ];
1103     struct comp *cptr;
1104     struct pqpair *p, *q;
1105     struct pqpair pq;
1106     struct mailname *mp;
1107
1108     ap = c2->c_text;
1109     c2->c_text = NULL;
1110     dat[0] = 0;
1111     dat[1] = 0;
1112     dat[2] = 0;
1113     dat[3] = sizeof(buffer) - 1;
1114     dat[4] = 0;
1115     fmt_compile (c1->c_nfs, &c1->c_fmt);
1116
1117     if (!(c1->c_flags & ADDRFMT)) {
1118         FINDCOMP (cptr, "text");
1119         if (cptr)
1120             cptr->c_text = ap;
1121         if ((cp = strrchr(ap, '\n')))   /* drop ending newline */
1122             if (!cp[1])
1123                 *cp = 0;
1124
1125         fmt_scan (c1->c_fmt, buffer, sizeof(buffer) - 1, dat);
1126         /* Don't need to append a newline, dctime() already did */
1127         c2->c_text = getcpy (buffer);
1128
1129         free (ap);
1130         return;
1131     }
1132
1133     (q = &pq)->pq_next = NULL;
1134     while ((cp = getname (ap))) {
1135         if ((p = (struct pqpair *) calloc ((size_t) 1, sizeof(*p))) == NULL)
1136             adios (NULL, "unable to allocate pqpair memory");
1137
1138         if ((mp = getm (cp, NULL, 0, AD_NAME, error)) == NULL) {
1139             p->pq_text = getcpy (cp);
1140             p->pq_error = getcpy (error);
1141         } else {
1142             if ((c1->c_flags & FACEDFLT) && c2->c_face == NULL) {
1143                 char   *h, *o;
1144                 if ((h = mp->m_host) == NULL)
1145                     h = LocalName (0);
1146                 if ((o = OfficialName (h)))
1147                     h = o;
1148                 c2->c_face = concat ("address ", h, " ", mp->m_mbox,
1149                                     NULL);
1150             }
1151             p->pq_text = getcpy (mp->m_text);
1152             mnfree (mp);
1153         }
1154         q = (q->pq_next = p);
1155     }
1156
1157     for (p = pq.pq_next; p; p = q) {
1158         FINDCOMP (cptr, "text");
1159         if (cptr)
1160             cptr->c_text = p->pq_text;
1161         FINDCOMP (cptr, "error");
1162         if (cptr)
1163             cptr->c_text = p->pq_error;
1164
1165         fmt_scan (c1->c_fmt, buffer, sizeof(buffer) - 1, dat);
1166         if (*buffer) {
1167             if (c2->c_text)
1168                 c2->c_text = add (",\n", c2->c_text);
1169             if (*(cp = buffer + strlen (buffer) - 1) == '\n')
1170                 *cp = 0;
1171             c2->c_text = add (buffer, c2->c_text);
1172         }
1173
1174         free (p->pq_text);
1175         if (p->pq_error)
1176             free (p->pq_error);
1177         q = p->pq_next;
1178         free ((char *) p);
1179     }
1180
1181     c2->c_text = add ("\n", c2->c_text);
1182     free (ap);
1183 }
1184
1185
1186 static struct mcomp *
1187 add_queue (struct mcomp **head, struct mcomp **tail, char *name, char *text, int flags)
1188 {
1189     struct mcomp *c1;
1190
1191     if ((c1 = (struct mcomp *) calloc ((size_t) 1, sizeof(*c1))) == NULL)
1192         adios (NULL, "unable to allocate comp memory");
1193
1194     c1->c_flags = flags & ~INIT;
1195     if ((c1->c_name = name ? getcpy (name) : NULL))
1196         c1->c_flags |= mcomp_flags (c1->c_name);
1197     c1->c_text = text ? getcpy (text) : NULL;
1198     if (flags & INIT) {
1199         if (global.c_ovtxt)
1200             c1->c_ovtxt = getcpy (global.c_ovtxt);
1201         c1->c_offset = global.c_offset;
1202         c1->c_ovoff = global. c_ovoff;
1203         c1->c_width = c1->c_length = 0;
1204         c1->c_cwidth = global.c_cwidth;
1205         c1->c_flags |= global.c_flags & GFLAGS;
1206     }
1207     if (*head == NULL)
1208         *head = c1;
1209     if (*tail != NULL)
1210         (*tail)->c_next = c1;
1211     *tail = c1;
1212
1213     return c1;
1214 }
1215
1216
1217 static void
1218 free_queue (struct mcomp **head, struct mcomp **tail)
1219 {
1220     struct mcomp *c1, *c2;
1221
1222     for (c1 = *head; c1; c1 = c2) {
1223         c2 = c1->c_next;
1224         if (c1->c_name)
1225             free (c1->c_name);
1226         if (c1->c_text)
1227             free (c1->c_text);
1228         if (c1->c_ovtxt)
1229             free (c1->c_ovtxt);
1230         if (c1->c_nfs)
1231             free (c1->c_nfs);
1232         if (c1->c_fmt)
1233             free ((char *) c1->c_fmt);
1234         if (c1->c_face)
1235             free (c1->c_face);
1236         if (c1->c_f_args) {
1237             struct arglist *a1, *a2;
1238             for (a1 = c1->c_f_args; a1; a1 = a2) {
1239                 a2 = a1->a_next;
1240                 if (a1->a_fmt)
1241                     free(a1->a_fmt);
1242                 if (a1->a_nfs)
1243                     free(a1->a_nfs);
1244             }
1245             free(a1);
1246         }
1247         free ((char *) c1);
1248     }
1249
1250     *head = *tail = NULL;
1251 }
1252
1253
1254 static void
1255 putcomp (struct mcomp *c1, struct mcomp *c2, int flag)
1256 {
1257     int count, cchdr;
1258     unsigned char *cp;
1259
1260     cchdr = 0;
1261     lm = 0;
1262     llim = c1->c_length ? c1->c_length : -1;
1263     wid = c1->c_width ? c1->c_width : global.c_width;
1264     ovoff = (c1->c_ovoff >= 0 ? c1->c_ovoff : global.c_ovoff)
1265         + c1->c_offset;
1266     if ((ovtxt = c1->c_ovtxt ? c1->c_ovtxt : global.c_ovtxt) == NULL)
1267         ovtxt = "";
1268     if (wid < ovoff + strlen (ovtxt) + 5)
1269         adios (NULL, "component: %s width(%d) too small for overflow(%d)",
1270                 c1->c_name, wid, ovoff + strlen (ovtxt) + 5);
1271     onelp = NULL;
1272
1273     if (c1->c_flags & CLEARTEXT) {
1274         putstr (c1->c_text, c1->c_flags);
1275         putstr ("\n", c1->c_flags);
1276         return;
1277     }
1278
1279     if (c1->c_flags & FACEFMT)
1280         switch (doface (c2)) {
1281             case NOTOK:         /* error */
1282             case OK:            /* async faceproc */
1283                 return;
1284
1285             default:            /* sync faceproc */
1286                 break;
1287         }
1288
1289     if (c1->c_nfs && (c1->c_flags & (ADDRFMT | DATEFMT | FORMAT)))
1290         mcomp_format (c1, c2);
1291
1292     if (c1->c_flags & CENTER) {
1293         count = (c1->c_width ? c1->c_width : global.c_width)
1294             - c1->c_offset - strlen (c2->c_text);
1295         if (!(c1->c_flags & HDROUTPUT) && !(c1->c_flags & NOCOMPONENT))
1296             count -= strlen (c1->c_text ? c1->c_text : c1->c_name) + 2;
1297         lm = c1->c_offset + (count / 2);
1298     } else {
1299         if (c1->c_offset)
1300             lm = c1->c_offset;
1301     }
1302
1303     if (!(c1->c_flags & HDROUTPUT) && !(c1->c_flags & NOCOMPONENT)) {
1304         if (c1->c_flags & UPPERCASE)            /* uppercase component also */
1305             for (cp = (c1->c_text ? c1->c_text : c1->c_name); *cp; cp++)
1306                 if (islower (*cp))
1307                     *cp = toupper (*cp);
1308         putstr (c1->c_text ? c1->c_text : c1->c_name, c1->c_flags);
1309         if (flag != BODYCOMP) {
1310             putstr (": ", c1->c_flags);
1311             if (!(c1->c_flags & SPLIT))
1312                 c1->c_flags |= HDROUTPUT;
1313
1314         cchdr++;
1315         if ((count = c1->c_cwidth -
1316                 strlen (c1->c_text ? c1->c_text : c1->c_name) - 2) > 0)
1317             while (count--)
1318                 putstr (" ", c1->c_flags);
1319         }
1320         else
1321             c1->c_flags |= HDROUTPUT;           /* for BODYCOMP */
1322     }
1323
1324     if (flag == TWOCOMP
1325             && !(c2->c_flags & HDROUTPUT)
1326             && !(c2->c_flags & NOCOMPONENT)) {
1327         if (c1->c_flags & UPPERCASE)
1328             for (cp = c2->c_name; *cp; cp++)
1329                 if (islower (*cp))
1330                     *cp = toupper (*cp);
1331         putstr (c2->c_name, c1->c_flags);
1332         putstr (": ", c1->c_flags);
1333         if (!(c1->c_flags & SPLIT))
1334             c2->c_flags |= HDROUTPUT;
1335
1336         cchdr++;
1337         if ((count = c1->c_cwidth - strlen (c2->c_name) - 2) > 0)
1338             while (count--)
1339                 putstr (" ", c1->c_flags);
1340     }
1341     if (c1->c_flags & UPPERCASE)
1342         for (cp = c2->c_text; *cp; cp++)
1343             if (islower (*cp))
1344                 *cp = toupper (*cp);
1345
1346     count = 0;
1347     if (cchdr) {
1348         if (flag == TWOCOMP)
1349             count = (c1->c_cwidth >= 0) ? c1->c_cwidth
1350                         : (int) strlen (c2->c_name) + 2;
1351         else
1352             count = (c1->c_cwidth >= 0) ? (size_t) c1->c_cwidth
1353                         : strlen (c1->c_text ? c1->c_text : c1->c_name) + 2;
1354     }
1355     count += c1->c_offset;
1356
1357     if ((cp = oneline (c2->c_text, c1->c_flags)))
1358        putstr(cp, c1->c_flags);
1359     if (term == '\n')
1360         putstr ("\n", c1->c_flags);
1361     while ((cp = oneline (c2->c_text, c1->c_flags))) {
1362         lm = count;
1363         if (flag == BODYCOMP
1364                 && !(c1->c_flags & NOCOMPONENT))
1365             putstr (c1->c_text ? c1->c_text : c1->c_name, c1->c_flags);
1366         if (*cp)
1367             putstr (cp, c1->c_flags);
1368         if (term == '\n')
1369             putstr ("\n", c1->c_flags);
1370     }
1371     if (flag == BODYCOMP && term == '\n')
1372         c1->c_flags &= ~HDROUTPUT;              /* Buffer ended on a newline */
1373 }
1374
1375
1376 static char *
1377 oneline (char *stuff, long flags)
1378 {
1379     int spc;
1380     char *cp, *ret;
1381
1382     if (onelp == NULL)
1383         onelp = stuff;
1384     if (*onelp == 0)
1385         return (onelp = NULL);
1386
1387     ret = onelp;
1388     term = 0;
1389     if (flags & COMPRESS) {
1390         for (spc = 1, cp = ret; *onelp; onelp++)
1391             if (isspace (*onelp)) {
1392                 if (*onelp == '\n' && (!onelp[1] || (flags & ADDRFMT))) {
1393                     term = '\n';
1394                     *onelp++ = 0;
1395                     break;
1396                 }
1397                 else
1398                     if (!spc) {
1399                         *cp++ = ' ';
1400                         spc++;
1401                     }
1402             }
1403             else {
1404                 *cp++ = *onelp;
1405                 spc = 0;
1406             }
1407
1408         *cp = 0;
1409     }
1410     else {
1411         while (*onelp && *onelp != '\n')
1412             onelp++;
1413         if (*onelp == '\n') {
1414             term = '\n';
1415             *onelp++ = 0;
1416         }
1417         if (flags & LEFTADJUST)
1418             while (*ret == ' ' || *ret == '\t')
1419                 ret++;
1420     }
1421     if (*onelp == 0 && term == '\n' && (flags & NONEWLINE))
1422         term = 0;
1423
1424     return ret;
1425 }
1426
1427
1428 static void
1429 putstr (char *string, long flags)
1430 {
1431     if (!column && lm > 0) {
1432         while (lm > 0)
1433             if (lm >= 8) {
1434                 putch ('\t', flags);
1435                 lm -= 8;
1436             }
1437             else {
1438                 putch (' ', flags);
1439                 lm--;
1440             }
1441     }
1442     lm = 0;
1443     while (*string)
1444         putch (*string++, flags);
1445 }
1446
1447
1448 static void
1449 putch (char ch, long flags)
1450 {
1451     char buf[BUFSIZ];
1452
1453     if (llim == 0)
1454         return;
1455
1456     switch (ch) {
1457         case '\n': 
1458             if (llim > 0)
1459                 llim--;
1460             column = 0;
1461             row++;
1462             if (ontty != ISTTY || row != global.c_length)
1463                 break;
1464             if (global.c_flags & BELL)
1465                 putchar ('\007');
1466             fflush (stdout);
1467             buf[0] = 0;
1468             read (fileno (stdout), buf, sizeof(buf));
1469             if (strchr(buf, '\n')) {
1470                 if (global.c_flags & CLEARSCR)
1471                     clear_screen ();
1472                 row = 0;
1473             } else {
1474                 putchar ('\n');
1475                 row = global.c_length / 3;
1476             }
1477             return;
1478
1479         case '\t': 
1480             column |= 07;
1481             column++;
1482             break;
1483
1484         case '\b': 
1485             column--;
1486             break;
1487
1488         case '\r': 
1489             column = 0;
1490             break;
1491
1492         default: 
1493             /*
1494              * If we are forwarding this message, and the first
1495              * column contains a dash, then add a dash and a space.
1496              */
1497             if (column == 0 && forwflg && (dashstuff >= 0) && ch == '-') {
1498                 putchar ('-');
1499                 putchar (' ');
1500             }
1501             if (ch >= ' ')
1502                 column++;
1503             break;
1504     }
1505
1506     if (column >= wid && (flags & NOWRAP) == 0) {
1507         putch ('\n', flags);
1508         if (ovoff > 0)
1509             lm = ovoff;
1510         putstr (ovtxt ? ovtxt : "", flags);
1511         putch (ch, flags);
1512         return;
1513     }
1514
1515     putchar (ch);
1516 }
1517
1518
1519 static void
1520 intrser (int i)
1521 {
1522     NMH_UNUSED (i);
1523
1524     discard (stdout);
1525     putchar ('\n');
1526     longjmp (env, DONE);
1527 }
1528
1529
1530 static void
1531 pipeser (int i)
1532 {
1533     NMH_UNUSED (i);
1534
1535     done (NOTOK);
1536 }
1537
1538
1539 static void
1540 quitser (int i)
1541 {
1542     NMH_UNUSED (i);
1543
1544     putchar ('\n');
1545     fflush (stdout);
1546     done (NOTOK);
1547 }
1548
1549
1550 static void
1551 face_format (struct mcomp *c1)
1552 {
1553     char *cp;
1554     struct mailname *mp;
1555
1556     if ((cp = c1->c_text) == NULL)
1557         return;
1558
1559     if ((cp = getname (cp))) {
1560         if ((mp = getm (cp, NULL, 0, AD_NAME, NULL))) {
1561             char *h, *o;
1562             if ((h = mp->m_host) == NULL)
1563                 h = LocalName (0);
1564             if ((o = OfficialName (h)))
1565                 h = o;
1566             c1->c_face = concat ("address ", h, " ", mp->m_mbox, NULL);
1567         }
1568
1569         while ((cp = getname (cp)))
1570             continue;
1571     }
1572 }
1573
1574
1575 /*
1576  * faceproc is two elements defining the image agent's location:
1577  *     Internet host
1578  *     UDP port
1579  */
1580
1581 #include <sys/socket.h>
1582 #include <netinet/in.h>
1583 #include <netdb.h>
1584 #include <arpa/inet.h>
1585
1586 static int
1587 doface (struct mcomp *c1)
1588 {
1589     int result, sd;
1590     static int inited = OK;
1591     static struct sockaddr_storage ss;
1592     static socklen_t socklen;
1593     static int socktype;
1594     static int protocol;
1595
1596     if (inited == OK) {
1597         char *cp;
1598         char **ap = brkstring (cp = getcpy (faceproc), " ", "\n");
1599         struct addrinfo hints, *res;
1600
1601         if (ap[0] == NULL || ap[1] == NULL) {
1602 bad_faceproc: ;
1603             free (cp);
1604             return (inited = NOTOK);
1605         }
1606
1607         memset(&hints, 0, sizeof(hints));
1608 #ifdef AI_ADDRCONFIG
1609         hints.ai_flags = AI_ADDRCONFIG;
1610 #endif
1611         hints.ai_family = PF_UNSPEC;
1612         hints.ai_socktype = SOCK_DGRAM;
1613
1614         if (getaddrinfo(ap[0], ap[1], &hints, &res) != 0)
1615             goto bad_faceproc;
1616
1617         memcpy(&ss, res->ai_addr, res->ai_addrlen);
1618         socklen = res->ai_addrlen;
1619         socktype = res->ai_socktype;
1620         protocol = res->ai_protocol;
1621         freeaddrinfo(res);
1622
1623         inited = DONE;
1624     }
1625     if (inited == NOTOK)
1626         return NOTOK;
1627
1628     if ((sd = socket (ss.ss_family, socktype, protocol)) == NOTOK)
1629         return NOTOK;
1630
1631     result = sendto (sd, c1->c_text, strlen (c1->c_text), 0,
1632                 (struct sockaddr *) &ss, socklen);
1633
1634     close (sd);
1635
1636     return (result != NOTOK ? OK : NOTOK);
1637 }
1638
1639 /*
1640  * COMMENTED OUT
1641  * This version doesn't use sockets
1642  */
1643 #if 0
1644
1645 static int
1646 doface (struct mcomp *c1)
1647 {
1648     int i, len, vecp;
1649     pid_t child_id;
1650     int result, pdi[2], pdo[2];
1651     char *bp, *cp;
1652     char buffer[BUFSIZ], *vec[10];
1653
1654     if (pipe (pdi) == NOTOK)
1655         return NOTOK;
1656     if (pipe (pdo) == NOTOK) {
1657         close (pdi[0]);
1658         close (pdi[1]);
1659         return NOTOK;
1660     }
1661
1662     for (i = 0; (child_id = vfork()) == NOTOK && i < 5; i++)
1663         sleep (5);
1664
1665     switch (child_id) {
1666         case NOTOK: 
1667             /* oops... fork error */
1668             return NOTOK;
1669
1670         case OK: 
1671             /* child process */
1672             SIGNAL (SIGINT, SIG_IGN);
1673             SIGNAL (SIGQUIT, SIG_IGN);
1674             if (pdi[0] != fileno (stdin)) {
1675                 dup2 (pdi[0], fileno (stdin));
1676                 close (pdi[0]);
1677             }
1678             close (pdi[1]);
1679             close (pdo[0]);
1680             if (pdo[1] != fileno (stdout)) {
1681                 dup2 (pdo[1], fileno (stdout));
1682                 close (pdo[1]);
1683             }
1684             vecp = 0;
1685             vec[vecp++] = r1bindex (faceproc, '/');
1686             vec[vecp++] = "-e";
1687             if (sleepsw != NOTOK) {
1688                 vec[vecp++] = "-s";
1689                 snprintf (buffer, sizeof(buffer), "%d", sleepsw);
1690                 vec[vecp++] = buffer;
1691             }
1692             vec[vecp] = NULL;
1693             execvp (faceproc, vec);
1694             fprintf (stderr, "unable to exec ");
1695             perror (faceproc);
1696             _exit (-1);         /* NOTREACHED */
1697
1698         default: 
1699             /* parent process */
1700             close (pdi[0]);
1701             i = strlen (c1->c_text);
1702             if (write (pdi[1], c1->c_text, i) != i)
1703                 adios ("pipe", "error writing to");
1704             free (c1->c_text), c1->c_text = NULL;
1705             close (pdi[1]);
1706
1707             close (pdo[1]);
1708             cp = NULL, len = 0;
1709             result = DONE;
1710             while ((i = read (pdo[0], buffer, strlen (buffer))) > 0) {
1711                 if (cp) {
1712                     int j;
1713                     char *dp;
1714                     dp = mh_xrealloc (cp, (unsigned) (j = len + i));
1715                     memcpy(dp + len, buffer, i);
1716                     cp = dp, len = j;
1717                 }
1718                 else {
1719                     cp = mh_xmalloc ((unsigned) i);
1720                     memcpy(cp, buffer, i);
1721                     len = i;
1722                 }
1723                 if (result == DONE)
1724                     for (bp = buffer + i - 1; bp >= buffer; bp--)
1725                         if (!isascii (*bp) || iscntrl (*bp)) {
1726                             result = OK;
1727                             break;
1728                         }
1729             }
1730             close (pdo[0]);
1731
1732 /* no waiting for child... */
1733
1734             if (result == OK) { /* binary */
1735                 if (write (1, cp, len) != len)
1736                     adios ("writing", "error");
1737                 free (cp);
1738             }
1739             else                /* empty */
1740                 if ((c1->c_text = cp) == NULL)
1741                     result = OK;
1742             break;
1743     }
1744
1745     return result;
1746 }
1747 #endif /* COMMENTED OUT */
1748
1749
1750 int
1751 mhlsbr (int argc, char **argv, FILE *(*action)())
1752 {
1753     SIGNAL_HANDLER istat = NULL, pstat = NULL, qstat = NULL;
1754     char *cp = NULL;
1755     struct mcomp *c1;
1756
1757     switch (m_setjmp (mhlenv)) {
1758         case OK: 
1759             cp = invo_name;
1760             sleepsw = 0;        /* XXX */
1761             bellflg = clearflg = forwflg = forwall = exitstat = 0;
1762             digest = NULL;
1763             ontty = NOTTY;
1764             mhl_action = action;
1765
1766             /*
1767              * If signal is at default action, then start ignoring
1768              * it, else let it set to its current action.
1769              */
1770             if ((istat = SIGNAL (SIGINT, SIG_IGN)) != SIG_DFL)
1771                 SIGNAL (SIGINT, istat);
1772             if ((qstat = SIGNAL (SIGQUIT, SIG_IGN)) != SIG_DFL)
1773                 SIGNAL (SIGQUIT, qstat);
1774             pstat = SIGNAL (SIGPIPE, pipeser);
1775             mhl (argc, argv);                  /* FALL THROUGH! */
1776
1777         default: 
1778             SIGNAL (SIGINT, istat);
1779             SIGNAL (SIGQUIT, qstat);
1780             SIGNAL (SIGPIPE, SIG_IGN);/* should probably change to block instead */
1781             if (ontty == PITTY)
1782                 m_pclose ();
1783             SIGNAL (SIGPIPE, pstat);
1784             invo_name = cp;
1785             if (holder.c_text) {
1786                 free (holder.c_text);
1787                 holder.c_text = NULL;
1788             }
1789             free_queue (&msghd, &msgtl);
1790             for (c1 = fmthd; c1; c1 = c1->c_next)
1791                 c1->c_flags &= ~HDROUTPUT;
1792             return exitstat;
1793     }
1794 }
1795
1796 #undef adios
1797 #undef done
1798
1799 static void
1800 mhladios (char *what, char *fmt, ...)
1801 {
1802     va_list ap;
1803
1804     va_start(ap, fmt);
1805     advertise (what, NULL, fmt, ap);
1806     va_end(ap);
1807     mhldone (1);
1808 }
1809
1810
1811 static void
1812 mhldone (int status)
1813 {
1814     exitstat = status;
1815     if (mhl_action)
1816         longjmp (mhlenv, DONE);
1817     else
1818         done (exitstat);
1819 }
1820
1821
1822 static  int m_pid = NOTOK;
1823 static  int sd = NOTOK;
1824
1825 static void
1826 m_popen (char *name)
1827 {
1828     int pd[2];
1829
1830     if (mhl_action && (sd = dup (fileno (stdout))) == NOTOK)
1831         adios ("standard output", "unable to dup()");
1832
1833     if (pipe (pd) == NOTOK)
1834         adios ("pipe", "unable to");
1835
1836     switch (m_pid = vfork()) {
1837         case NOTOK: 
1838             adios ("fork", "unable to");
1839
1840         case OK: 
1841             SIGNAL (SIGINT, SIG_DFL);
1842             SIGNAL (SIGQUIT, SIG_DFL);
1843
1844             close (pd[1]);
1845             if (pd[0] != fileno (stdin)) {
1846                 dup2 (pd[0], fileno (stdin));
1847                 close (pd[0]);
1848             }
1849             execlp (name, r1bindex (name, '/'), NULL);
1850             fprintf (stderr, "unable to exec ");
1851             perror (name);
1852             _exit (-1);
1853
1854         default: 
1855             close (pd[0]);
1856             if (pd[1] != fileno (stdout)) {
1857                 dup2 (pd[1], fileno (stdout));
1858                 close (pd[1]);
1859             }
1860     }
1861 }
1862
1863
1864 void
1865 m_pclose (void)
1866 {
1867     if (m_pid == NOTOK)
1868         return;
1869
1870     if (sd != NOTOK) {
1871         fflush (stdout);
1872         if (dup2 (sd, fileno (stdout)) == NOTOK)
1873             adios ("standard output", "unable to dup2()");
1874
1875         clearerr (stdout);
1876         close (sd);
1877         sd = NOTOK;
1878     }
1879     else
1880         fclose (stdout);
1881
1882     pidwait (m_pid, OK);
1883     m_pid = NOTOK;
1884 }
1885
1886
1887 /*
1888  * Compile a format string and add it to the list of arguments used by
1889  * the formatproc.
1890  *
1891  * This deserves some explanation.  Here's the deal:
1892  *
1893  * We want to keep track of components used as arguments by formatproc,
1894  * but the hash table is reset every time fmt_compile is called.  So we
1895  * iterate through the function list looking for things that use components
1896  * and save the name.  And because we might get the same components used
1897  * by different arguments we need to keep track to every reference of
1898  * every component so we can add them when the message is processed.  So
1899  * we compile the argument string now (to get the components we use) and
1900  * save them for later.
1901  */
1902
1903 static int
1904 compileargs (struct mcomp *c1, char *nfs)
1905 {
1906     struct format *fmt;
1907     struct arglist *args;
1908     int i;
1909
1910     i = fmt_compile(nfs, &fmt);
1911
1912     args = (struct arglist *) mh_xmalloc(sizeof(struct arglist));
1913
1914     if (! args)
1915         adios (NULL, "Unable to allocate formatproc args storage");
1916
1917     args->a_fmt = fmt;
1918     args->a_nfs = format_string;
1919     args->a_next = NULL;
1920     c1->c_nargs++;
1921     format_string = NULL;
1922
1923     if (c1->c_f_tail)
1924         c1->c_f_tail->a_next = args;
1925
1926     c1->c_f_tail = args;
1927
1928     if (! c1->c_f_args)
1929         c1->c_f_args = args;
1930
1931     if (i == 0)
1932         return 0;
1933
1934     /*
1935      * If wantcomp ever changes size, we need to change the size
1936      * of mhlcomp as well
1937      */
1938
1939     for (i = 0; i < sizeof(wantcomp)/sizeof(wantcomp[0]); i++) {
1940         if (wantcomp[i]) {
1941             if (mhlcomp[i]) {
1942                 struct comp *c;
1943                 for (c = mhlcomp[i]; c->c_next != NULL; c = c->c_next)
1944                     ;
1945                 c->c_next = wantcomp[i];
1946             } else
1947                 mhlcomp[i] = wantcomp[i];
1948         }
1949     }
1950
1951     return 0;
1952 }
1953
1954 /*
1955  * Check to see if we are interested in a component.  If we are, save
1956  * the text.
1957  */
1958
1959 static int
1960 checkcomp(char *name, char *buf)
1961 {
1962     int found = 0, i;
1963     struct comp *c;
1964     int bucket = CHASH(name);
1965     char *cp;
1966  
1967     if ((c = mhlcomp[bucket])) {
1968         do {
1969             if (mh_strcasecmp(name, c->c_name) == 0) {
1970                 found++;
1971                 if (! c->c_text) {
1972                     i = strlen(c->c_text = strdup(buf)) - 1;
1973                     if (c->c_text[i] == '\n')
1974                         c->c_text[i] = '\0';
1975                 } else {
1976                     i = strlen(cp = c->c_text) - 1;
1977                     if (cp[i] == '\n') {
1978                         if (c->c_type & CT_ADDR) {
1979                             cp[i] = '\0';
1980                             cp = add (",\n\t", cp);
1981                         } else {
1982                             cp = add ("\t", cp);
1983                         }
1984                     }
1985                     c->c_text = add (buf, cp);
1986                 }
1987             }
1988         } while ((c = c->c_next));
1989     }
1990
1991     return found ? bucket : -1;
1992 }
1993
1994 /*
1995  * Add text to an existing component
1996  */
1997
1998 static void
1999 addcomp(int bucket, char *name, char *buf)
2000 {
2001     struct comp *c;
2002
2003     if (bucket != -1) {
2004         c = mhlcomp[bucket];
2005         do {
2006             if (mh_strcasecmp(name, c->c_name) == 0)
2007                 c->c_text = add (buf, c->c_text);
2008         } while ((c = c->c_next));
2009     }
2010 }
2011
2012 /*
2013  * Free up saved component structures
2014  */
2015
2016 static void
2017 freecomps(void)
2018 {
2019     struct comp *c1, *c2;
2020     int i;
2021
2022     for (i = 0; i < sizeof(mhlcomp)/sizeof(mhlcomp[0]); i++) {
2023         if ((c1 = mhlcomp[i]))
2024             for (; c1; c1 = c2) {
2025                 c2 = c1->c_next;
2026                 if (c1->c_text)
2027                     free(c1->c_text);
2028                 free(c1);
2029             }
2030     }
2031 }
2032
2033 /*
2034  * Just free up the component text.
2035  */
2036
2037 static void
2038 freecomptext(void)
2039 {
2040     struct comp *c1;
2041     int i;
2042
2043     for (i = 0; i < sizeof(mhlcomp)/sizeof(mhlcomp[0]); i++) {
2044         if ((c1 = mhlcomp[i]))
2045             for (; c1; c1 = c1->c_next) {
2046                 if (c1->c_text) {
2047                     free(c1->c_text);
2048                     c1->c_text = NULL;
2049                 }
2050             }
2051     }
2052 }
2053
2054 /*
2055  * Filter the body of a message through a specified format program
2056  */
2057
2058 static void
2059 filterbody (struct mcomp *c1, char *buf, int bufsz, int state, FILE *fp)
2060 {
2061     struct mcomp holder;
2062     char name[NAMESZ];
2063     int fdinput[2], fdoutput[2], waitstat;
2064     ssize_t cc;
2065     pid_t writerpid, filterpid;
2066
2067     /*
2068      * Create pipes so we can communicate with our filter process.
2069      */
2070
2071     if (pipe(fdinput) < 0) {
2072         adios(NULL, "Unable to create input pipe");
2073     }
2074
2075     if (pipe(fdoutput) < 0) {
2076         adios(NULL, "Unable to create output pipe");
2077     }
2078
2079     /*
2080      * Here's what we're doing to do.
2081      *
2082      * - Fork ourselves and start writing data to the write side of the
2083      *   input pipe (fdinput[1]).
2084      *
2085      * - Fork and exec our filter program.  We set the standard input of
2086      *   our filter program to be the read side of our input pipe (fdinput[0]).
2087      *   Standard output is set to the write side of our output pipe
2088      *   (fdoutput[1]).
2089      *
2090      * - We read from the read side of the output pipe (fdoutput[0]).
2091      *
2092      * We're forking because that's the simplest way to prevent any deadlocks.
2093      * (without doing something like switching to non-blocking I/O and using
2094      * select or poll, and I'm not interested in doing that).
2095      */
2096
2097     switch (writerpid = fork()) {
2098     case 0:
2099         /*
2100          * Our child process - just write to the filter input (fdinput[1]).
2101          * Close all other descriptors that we don't need.
2102          */
2103
2104         close(fdinput[0]);
2105         close(fdoutput[0]);
2106         close(fdoutput[1]);
2107
2108         /*
2109          * Call m_getfld() until we're no longer in the BODY state
2110          */
2111
2112         while (state == BODY) {
2113             write(fdinput[1], buf, strlen(buf));
2114             state = m_getfld(state, name, buf, bufsz, fp);
2115         }
2116
2117         /*
2118          * We should be done; time to exit.
2119          */
2120
2121         close(fdinput[1]);
2122         exit(0);
2123         break;
2124     case -1:
2125         adios(NULL, "Unable to fork for filter writer process");
2126         break;
2127     }
2128
2129     /*
2130      * Fork and exec() our filter program, after redirecting standard in
2131      * and standard out appropriately.
2132      */
2133
2134     switch (filterpid = fork()) {
2135         char **args;
2136         struct arglist *a;
2137         int i, dat[5], s;
2138
2139     case 0:
2140         /*
2141          * Allocate an argument array for us
2142          */
2143
2144         args = (char **) mh_xmalloc((c1->c_nargs + 2) * sizeof(char *));
2145         args[0] = formatproc;
2146         args[c1->c_nargs + 1] = NULL;
2147         dat[0] = 0;
2148         dat[1] = 0;
2149         dat[2] = 0;
2150         dat[3] = BUFSIZ;
2151         dat[4] = 0;
2152
2153         /*
2154          * Pull out each argument and scan them.
2155          */
2156
2157         for (a = c1->c_f_args, i = 1; a != NULL; a = a->a_next, i++) {
2158             args[i] = mh_xmalloc(BUFSIZ);
2159             fmt_scan(a->a_fmt, args[i], BUFSIZ, dat);
2160             /*
2161              * fmt_scan likes to put a trailing newline at the end of the
2162              * format string.  If we have one, get rid of it.
2163              */
2164             s = strlen(args[i]);
2165             if (args[i][s - 1] == '\n')
2166                 args[i][s - 1] = '\0';
2167         }
2168
2169         if (dup2(fdinput[0], STDIN_FILENO) < 0) {
2170             adios("formatproc", "Unable to dup2() standard input");
2171         }
2172         if (dup2(fdoutput[1], STDOUT_FILENO) < 0) {
2173             adios("formatproc", "Unable to dup2() standard output");
2174         }
2175
2176         /*
2177          * Close everything (especially the old input and output
2178          * descriptors, since they've been dup'd to stdin and stdout),
2179          * and exec the formatproc.
2180          */
2181
2182         close(fdinput[0]);
2183         close(fdinput[1]);
2184         close(fdoutput[0]);
2185         close(fdoutput[1]);
2186
2187         execvp(formatproc, args);
2188
2189         adios(formatproc, "Unable to execute filter");
2190
2191         break;
2192
2193     case -1:
2194         adios(NULL, "Unable to fork format program");
2195     }
2196
2197     /*
2198      * Close everything except our reader (fdoutput[0]);
2199      */
2200
2201     close(fdinput[0]);
2202     close(fdinput[1]);
2203     close(fdoutput[1]);
2204
2205     /*
2206      * As we read in this data, send it to putcomp
2207      */
2208
2209     holder.c_text = buf;
2210
2211     while ((cc = read(fdoutput[0], buf, bufsz - 1)) > 0) {
2212         buf[cc] = '\0';
2213         putcomp(c1, &holder, BODYCOMP);
2214     }
2215
2216     if (cc < 0) {
2217         adios(NULL, "reading from formatproc");
2218     }
2219
2220     /*
2221      * See if we got any errors along the way.  I'm a little leery of calling
2222      * waitpid() without WNOHANG, but it seems to be the most correct solution.
2223      */
2224
2225     if (waitpid(filterpid, &waitstat, 0) < 0) {
2226         if (errno != ECHILD) {
2227             adios("filterproc", "Unable to determine status");
2228         }
2229     } else {
2230         if (! (WIFEXITED(waitstat) && WEXITSTATUS(waitstat) == 0)) {
2231             pidstatus(waitstat, stderr, "filterproc");
2232         }
2233     }
2234
2235     if (waitpid(writerpid, &waitstat, 0) < 0) {
2236         if (errno != ECHILD) {
2237             adios("writer process", "Unable to determine status");
2238             done(1);
2239         }
2240     } else {
2241         if (! (WIFEXITED(waitstat) && WEXITSTATUS(waitstat) == 0)) {
2242             pidstatus(waitstat, stderr, "writer process");
2243             done(1);
2244         }
2245     }
2246
2247     close(fdoutput[0]);
2248 }