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