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