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