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