propagate and check return status of close() in slocal
[mmh] / uip / slocal.c
1
2 /*
3  * slocal.c -- asynchronously filter and deliver new mail
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 /*
11  *  Under sendmail, users should add the line
12  *
13  *      "| /usr/local/nmh/lib/slocal"
14  *
15  *  to their $HOME/.forward file.
16  *
17  */
18
19 /* Changed to use getutent() and friends.  Assumes that when getutent() exists,
20  * a number of other things also exist.  Please check.
21  * Ruud de Rooij <ruud@ruud.org>  Sun, 28 May 2000 17:28:55 +0200
22  */
23
24 #include <h/mh.h>
25 #include <h/dropsbr.h>
26 #include <h/rcvmail.h>
27 #include <h/signals.h>
28 #include <h/tws.h>
29 #include <h/mts.h>
30 #include <h/utils.h>
31
32 #include <pwd.h>
33 #include <signal.h>
34 #include <sys/ioctl.h>
35 #include <fcntl.h>
36
37 #ifdef INITGROUPS_HEADER
38 #include INITGROUPS_HEADER
39 #else
40 /* On AIX 4.1, initgroups() is defined and even documented (giving the parameter
41    types as char* and int), but doesn't have a prototype in any of the system
42    header files.  AIX 4.3, SunOS 4.1.3, and ULTRIX 4.2A have the same
43    problem. */
44 extern int  initgroups(char*, int);
45 #endif
46
47 /* This define is needed for Berkeley db v2 and above to
48  * make the header file expose the 'historical' ndbm APIs.
49  * We define it unconditionally because this is simple and
50  * harmless.
51  */
52 #define DB_DBM_HSEARCH 1
53 #ifdef NDBM_HEADER
54 #include NDBM_HEADER
55 #endif
56
57 #include <utmp.h>
58
59 #ifndef HAVE_GETUTENT
60 # ifndef UTMP_FILE
61 #  ifdef _PATH_UTMP
62 #   define UTMP_FILE _PATH_UTMP
63 #  else
64 #   define UTMP_FILE "/etc/utmp"
65 #  endif
66 # endif
67 #endif
68
69 static struct swit switches[] = {
70 #define ADDRSW         0
71     { "addr address", 0 },
72 #define USERSW         1
73     { "user name", 0 },
74 #define FILESW         2
75     { "file file", 0 },
76 #define SENDERSW       3
77     { "sender address", 0 },
78 #define MAILBOXSW      4
79     { "mailbox file", 0 },
80 #define HOMESW         5
81     { "home directory", -4 },
82 #define INFOSW         6
83     { "info data", 0 },
84 #define MAILSW         7
85     { "maildelivery file", 0 },
86 #define VERBSW         8
87     { "verbose", 0 },
88 #define NVERBSW        9
89     { "noverbose", 0 },
90 #define SUPPRESSDUP   10
91     { "suppressdup", 0 },
92 #define NSUPPRESSDUP 11
93     { "nosuppressdup", 0 },
94 #define DEBUGSW       12
95     { "debug", 0 },
96 #define VERSIONSW     13
97     { "version", 0 },
98 #define HELPSW        14
99     { "help", 0 },
100     { NULL, 0 }
101 };
102
103 static int globbed = 0;         /* have we built "vars" table yet?        */
104 static int parsed = 0;          /* have we built header field table yet   */
105 static int utmped = 0;          /* have we scanned umtp(x) file yet       */
106 static int suppressdup = 0;     /* are we suppressing duplicate messages? */
107
108 static int verbose = 0;
109 static int debug = 0;
110
111 static char *addr = NULL;
112 static char *user = NULL;
113 static char *info = NULL;
114 static char *file = NULL;
115 static char *sender = NULL;
116 static char *envelope = NULL;   /* envelope information ("From " line)  */
117 static char *mbox = NULL;
118 static char *home = NULL;
119
120 static struct passwd *pw;       /* passwd file entry */
121
122 static char ddate[BUFSIZ];      /* record the delivery date */
123 struct tws *now;
124
125 static jmp_buf myctx;
126
127 /* flags for pair->p_flags */
128 #define P_NIL  0x00
129 #define P_ADR  0x01     /* field is address     */
130 #define P_HID  0x02     /* special (fake) field */
131 #define P_CHK  0x04
132
133 struct pair {
134     char *p_name;
135     char *p_value;
136     char  p_flags;
137 };
138
139 #define NVEC 100
140
141 /*
142  * Lookup table for matching fields and patterns
143  * in messages.  The rest of the table is added
144  * when the message is parsed.
145  */
146 static struct pair hdrs[NVEC + 1] = {
147     { "source",          NULL, P_HID },
148     { "addr",            NULL, P_HID },
149     { "Return-Path",     NULL, P_ADR },
150     { "Reply-To",        NULL, P_ADR },
151     { "From",            NULL, P_ADR },
152     { "Sender",          NULL, P_ADR },
153     { "To",              NULL, P_ADR },
154     { "cc",              NULL, P_ADR },
155     { "Resent-Reply-To", NULL, P_ADR },
156     { "Resent-From",     NULL, P_ADR },
157     { "Resent-Sender",   NULL, P_ADR },
158     { "Resent-To",       NULL, P_ADR },
159     { "Resent-cc",       NULL, P_ADR },
160     { NULL, NULL, 0 }
161 };
162
163 /*
164  * The list of builtin variables to expand in a string
165  * before it is executed by the "pipe" or "qpipe" action.
166  */
167 static struct pair vars[] = {
168     { "sender",   NULL, P_NIL },
169     { "address",  NULL, P_NIL },
170     { "size",     NULL, P_NIL },
171     { "reply-to", NULL, P_CHK },
172     { "info",     NULL, P_NIL },
173     { NULL, NULL, 0 }
174 };
175
176 extern char **environ;
177
178 /*
179  * static prototypes
180  */
181 static int localmail (int, char *);
182 static int usr_delivery (int, char *, int);
183 static int split (char *, char **);
184 static int parse (int);
185 static void expand (char *, char *, int);
186 static void glob (int);
187 static struct pair *lookup (struct pair *, char *);
188 static int logged_in (void);
189 static int timely (char *, char *);
190 static int usr_file (int, char *, int);
191 static int usr_pipe (int, char *, char *, char **, int);
192 static int usr_folder (int, char *);
193 static RETSIGTYPE alrmser (int);
194 static void get_sender (char *, char **);
195 static int copy_message (int, char *, int);
196 static void verbose_printf (char *fmt, ...);
197 static void adorn (char *, char *, ...);
198 static void debug_printf (char *fmt, ...);
199 static int suppress_duplicates (int, char *);
200 static char *trim (char *);
201
202
203 int
204 main (int argc, char **argv)
205 {
206     int fd, status;
207     FILE *fp = stdin;
208     char *cp, *mdlvr = NULL, buf[BUFSIZ];
209     char mailbox[BUFSIZ], tmpfil[BUFSIZ];
210     char **argp, **arguments;
211
212 #ifdef LOCALE
213     setlocale(LC_ALL, "");
214 #endif
215     invo_name = r1bindex (*argv, '/');
216
217     /* foil search of user profile/context */
218     if (context_foil (NULL) == -1)
219         done (1);
220
221     mts_init (invo_name);
222     arguments = getarguments (invo_name, argc, argv, 0);
223     argp = arguments;
224
225     /* Parse arguments */
226     while ((cp = *argp++)) {
227         if (*cp == '-') {
228             switch (smatch (++cp, switches)) {
229                 case AMBIGSW: 
230                     ambigsw (cp, switches);
231                     done (1);
232                 case UNKWNSW: 
233                     adios (NULL, "-%s unknown", cp);
234
235                 case HELPSW: 
236                     snprintf (buf, sizeof(buf),
237                         "%s [switches] [address info sender]", invo_name);
238                     print_help (buf, switches, 0);
239                     done (1);
240                 case VERSIONSW:
241                     print_version(invo_name);
242                     done (1);
243
244                 case ADDRSW: 
245                     if (!(addr = *argp++))/* allow -xyz arguments */
246                         adios (NULL, "missing argument to %s", argp[-2]);
247                     continue;
248                 case INFOSW: 
249                     if (!(info = *argp++))/* allow -xyz arguments */
250                         adios (NULL, "missing argument to %s", argp[-2]);
251                     continue;
252                 case USERSW: 
253                     if (!(user = *argp++))/* allow -xyz arguments */
254                         adios (NULL, "missing argument to %s", argp[-2]);
255                     continue;
256                 case FILESW: 
257                     if (!(file = *argp++) || *file == '-')
258                         adios (NULL, "missing argument to %s", argp[-2]);
259                     continue;
260                 case SENDERSW: 
261                     if (!(sender = *argp++))/* allow -xyz arguments */
262                         adios (NULL, "missing argument to %s", argp[-2]);
263                     continue;
264                 case MAILBOXSW: 
265                     if (!(mbox = *argp++) || *mbox == '-')
266                         adios (NULL, "missing argument to %s", argp[-2]);
267                     continue;
268                 case HOMESW: 
269                     if (!(home = *argp++) || *home == '-')
270                         adios (NULL, "missing argument to %s", argp[-2]);
271                     continue;
272
273                 case MAILSW: 
274                     if (!(cp = *argp++) || *cp == '-')
275                         adios (NULL, "missing argument to %s", argp[-2]);
276                     if (mdlvr)
277                         adios (NULL, "only one maildelivery file at a time!");
278                     mdlvr = cp;
279                     continue;
280
281                 case VERBSW: 
282                     verbose++;
283                     continue;
284                 case NVERBSW: 
285                     verbose = 0;
286                     continue;
287
288                 case SUPPRESSDUP:
289                     suppressdup++;
290                     continue;
291                 case NSUPPRESSDUP:
292                     suppressdup = 0;
293                     continue;
294                 case DEBUGSW: 
295                     debug++;
296                     continue;
297             }
298         }
299
300         switch (argp - (argv + 1)) {
301             case 1: 
302                 addr = cp;
303                 break;
304
305             case 2: 
306                 info = cp;
307                 break;
308
309             case 3: 
310                 sender = cp;
311                 break;
312         }
313     }
314
315     if (addr == NULL)
316         addr = getusername ();
317     if (user == NULL)
318         user = (cp = strchr(addr, '.')) ? ++cp : addr;
319     if ((pw = getpwnam (user)) == NULL)
320         adios (NULL, "no such local user as %s", user);
321
322     if (chdir (pw->pw_dir) == -1)
323         chdir ("/");
324     umask (0077);
325
326     if (geteuid() == 0) {
327         setgid (pw->pw_gid);
328         initgroups (pw->pw_name, pw->pw_gid);
329         setuid (pw->pw_uid);
330     }
331     
332     if (info == NULL)
333         info = "";
334
335     setbuf (stdin, NULL);
336
337     /* Record the delivery time */
338     if ((now = dlocaltimenow ()) == NULL)
339         adios (NULL, "unable to ascertain local time");
340     snprintf (ddate, sizeof(ddate), "Delivery-Date: %s\n", dtimenow (0));
341
342     /*
343      * Copy the message to a temporary file
344      */
345     if (file) {
346         int tempfd;
347
348         /* getting message from file */
349         if ((tempfd = open (file, O_RDONLY)) == -1)
350             adios (file, "unable to open");
351         if (debug)
352             debug_printf ("retrieving message from file \"%s\"\n", file);
353         if ((fd = copy_message (tempfd, tmpfil, 1)) == -1)
354             adios (NULL, "unable to create temporary file");
355         close (tempfd);
356     } else {
357         /* getting message from stdin */
358         if (debug)
359             debug_printf ("retrieving message from stdin\n");
360         if ((fd = copy_message (fileno (stdin), tmpfil, 1)) == -1)
361             adios (NULL, "unable to create temporary file");
362     }
363
364     if (debug)
365         debug_printf ("temporary file=\"%s\"\n", tmpfil);
366
367     /* Delete the temp file now or a copy of every single message passed through
368        slocal will be left in the /tmp directory until deleted manually!  This
369        unlink() used to be under an 'else' of the 'if (debug)' above, but since
370        some people like to always run slocal with -debug and log the results,
371        the /tmp directory would get choked over time.  Of course, now that we
372        always delete the temp file, the "temporary file=" message above is
373        somewhat pointless -- someone watching debug output wouldn't have a
374        chance to 'tail -f' or 'ln' the temp file before it's unlinked.  The best
375        thing would be to delay this unlink() until later if debug == 1, but I'll
376        leave that for someone who cares about the temp-file-accessing
377        functionality (they'll have to watch out for cases where we adios()). */
378     unlink (tmpfil);
379
380     if (!(fp = fdopen (fd, "r+")))
381         adios (NULL, "unable to access temporary file");
382
383     /*
384      * If no sender given, extract it
385      * from envelope information.  */
386     if (sender == NULL)
387         get_sender (envelope, &sender);
388
389     if (mbox == NULL) {
390         snprintf (mailbox, sizeof(mailbox), "%s/%s",
391                 mmdfldir[0] ? mmdfldir : pw->pw_dir,
392                 mmdflfil[0] ? mmdflfil : pw->pw_name);
393         mbox = mailbox;
394     }
395     if (home == NULL)
396         home = pw->pw_dir;
397
398     if (debug) {
399         debug_printf ("addr=\"%s\"\n", trim(addr));
400         debug_printf ("user=\"%s\"\n", trim(user));
401         debug_printf ("info=\"%s\"\n", trim(info));
402         debug_printf ("sender=\"%s\"\n", trim(sender));
403         debug_printf ("envelope=\"%s\"\n", envelope ? trim(envelope) : "");
404         debug_printf ("mbox=\"%s\"\n", trim(mbox));
405         debug_printf ("home=\"%s\"\n", trim(home));
406         debug_printf ("ddate=\"%s\"\n", trim(ddate));
407         debug_printf ("now=%02d:%02d\n\n", now->tw_hour, now->tw_min);
408     }
409
410     /* deliver the message */
411     status = localmail (fd, mdlvr);
412
413     done (status != -1 ? RCV_MOK : RCV_MBX);
414     return 1;
415 }
416
417
418 /*
419  * Main routine for delivering message.
420  */
421
422 static int
423 localmail (int fd, char *mdlvr)
424 {
425     /* check if this message is a duplicate */
426     if (suppressdup &&
427         suppress_duplicates(fd, mdlvr ? mdlvr : ".maildelivery") == DONE)
428         return 0;
429
430     /* delivery according to personal Maildelivery file */
431     if (usr_delivery (fd, mdlvr ? mdlvr : ".maildelivery", 0) != -1)
432         return 0;
433
434     /* delivery according to global Maildelivery file */
435     if (usr_delivery (fd, maildelivery, 1) != -1)
436         return 0;
437
438     if (verbose)
439         verbose_printf ("(delivering to standard mail spool)\n");
440
441     /* last resort - deliver to standard mail spool */
442 #ifdef SLOCAL_MBOX
443     return usr_file (fd, mbox, MBOX_FORMAT);
444 #else
445     return usr_file (fd, mbox, MMDF_FORMAT);
446 #endif
447 }
448
449
450 #define matches(a,b) (stringdex (b, a) >= 0)
451
452 /*
453  * Parse the delivery file, and process incoming message.
454  */
455
456 static int
457 usr_delivery (int fd, char *delivery, int su)
458 {
459     int i, accept, status=1, won, vecp, next;
460     char *field, *pattern, *action, *result, *string;
461     char buffer[BUFSIZ], tmpbuf[BUFSIZ];
462     char *cp, *vec[NVEC];
463     struct stat st;
464     struct pair *p;
465     FILE *fp;
466
467     /* open the delivery file */
468     if ((fp = fopen (delivery, "r")) == NULL)
469         return -1;
470
471     /* check if delivery file has bad ownership or permissions */
472     if (fstat (fileno (fp), &st) == -1
473             || (st.st_uid != 0 && (su || st.st_uid != pw->pw_uid))
474             || st.st_mode & (S_IWGRP|S_IWOTH)) {
475         if (verbose) {
476             verbose_printf ("WARNING: %s has bad ownership/modes (su=%d,uid=%d,owner=%d,mode=0%o)\n",
477                     delivery, su, (int) pw->pw_uid, (int) st.st_uid, (int) st.st_mode);
478         }
479         return -1;
480     }
481
482     won = 0;
483     next = 1;
484
485     /* read and process delivery file */
486     while (fgets (buffer, sizeof(buffer), fp)) {
487         /* skip comments and empty lines */
488         if (*buffer == '#' || *buffer == '\n')
489             continue;
490
491         /* zap trailing newline */
492         if ((cp = strchr(buffer, '\n')))
493             *cp = 0;
494
495         /* split buffer into fields */
496         vecp = split (buffer, vec);
497
498         /* check for too few fields */
499         if (vecp < 5) {
500             if (debug)
501                 debug_printf ("WARNING: entry with only %d fields, skipping.\n", vecp);
502             continue;
503         }
504
505         if (debug) {
506             for (i = 0; vec[i]; i++)
507                 debug_printf ("vec[%d]: \"%s\"\n", i, trim(vec[i]));
508         }
509
510         field   = vec[0];
511         pattern = vec[1];
512         action  = vec[2];
513         result  = vec[3];
514         string  = vec[4];
515
516         /* find out how to perform the action */
517         switch (result[0]) {
518             case 'N':
519             case 'n':
520                 /*
521                  * If previous condition failed, don't
522                  * do this - else fall through
523                  */
524                 if (!next)
525                     continue;   /* else fall */
526
527             case '?': 
528                 /*
529                  * If already delivered, skip this action.  Else
530                  * consider delivered if action is successful.
531                  */
532                 if (won)
533                     continue;   /* else fall */
534
535             case 'A': 
536             case 'a': 
537                 /*
538                  * Take action, and consider delivered if
539                  * action is successful.
540                  */
541                 accept = 1;
542                 break;
543
544             case 'R': 
545             case 'r': 
546             default: 
547                 /*
548                  * Take action, but don't consider delivered, even
549                  * if action is successful
550                  */
551                 accept = 0;
552                 break;
553         }
554
555         if (vecp > 5) {
556             if (!mh_strcasecmp (vec[5], "select")) {
557                 if (logged_in () != -1)
558                     continue;
559                 if (vecp > 7 && timely (vec[6], vec[7]) == -1)
560                     continue;
561             }
562         }
563
564         /* check if the field matches */
565         switch (*field) {
566             case '*': 
567             /* always matches */
568                 break;
569
570             case 'd': 
571             /*
572              * "default" matches only if the message hasn't
573              * been delivered yet.
574              */
575                 if (!mh_strcasecmp (field, "default")) {
576                     if (won)
577                         continue;
578                     break;
579                 }               /* else fall */
580
581             default: 
582                 /* parse message and build lookup table */
583                 if (!parsed && parse (fd) == -1) {
584                     fclose (fp);
585                     return -1;
586                 }
587                 /*
588                  * find header field in lookup table, and
589                  * see if the pattern matches.
590                  */
591                 if ((p = lookup (hdrs, field)) && (p->p_value != NULL)
592                         && matches (p->p_value, pattern)) {
593                     next = 1;
594                 } else {
595                     next = 0;
596                     continue;
597                 }
598                 break;
599         }
600
601         /* find out the action to perform */
602         switch (*action) {
603             case 'q':
604                 /* deliver to quoted pipe */
605                 if (mh_strcasecmp (action, "qpipe"))
606                     continue;   /* else fall */
607             case '^':
608                 expand (tmpbuf, string, fd);
609                 if (split (tmpbuf, vec) < 1)
610                     continue;
611                 status = usr_pipe (fd, tmpbuf, vec[0], vec, 0);
612                 break;
613
614             case 'p': 
615                 /* deliver to pipe */
616                 if (mh_strcasecmp (action, "pipe"))
617                     continue;   /* else fall */
618             case '|': 
619                 vec[2] = "sh";
620                 vec[3] = "-c";
621                 expand (tmpbuf, string, fd);
622                 vec[4] = tmpbuf;
623                 vec[5] = NULL;
624                 status = usr_pipe (fd, tmpbuf, "/bin/sh", vec + 2, 0);
625                 break;
626
627             case 'f': 
628                 /* mbox format */
629                 if (!mh_strcasecmp (action, "file")) {
630                     status = usr_file (fd, string, MBOX_FORMAT);
631                     break;
632                 }
633                 /* deliver to nmh folder */
634                 else if (mh_strcasecmp (action, "folder"))
635                     continue;   /* else fall */
636             case '+':
637                 status = usr_folder (fd, string);
638                 break;
639
640             case 'm':
641                 /* mmdf format */
642                 if (!mh_strcasecmp (action, "mmdf")) {
643                     status = usr_file (fd, string, MMDF_FORMAT);
644                     break;
645                 }
646                 /* mbox format */
647                 else if (mh_strcasecmp (action, "mbox"))
648                     continue;   /* else fall */
649
650             case '>': 
651                 /* mbox format */
652                 status = usr_file (fd, string, MBOX_FORMAT);
653                 break;
654
655             case 'd': 
656                 /* ignore message */
657                 if (mh_strcasecmp (action, "destroy"))
658                     continue;
659                 status = 0;
660                 break;
661         }
662
663         if (status) next = 0;   /* action failed, mark for 'N' result */
664
665         if (accept && status == 0)
666             won++;
667     }
668
669     fclose (fp);
670     return (won ? 0 : -1);
671 }
672
673
674 #define QUOTE   '\\'
675
676 /*
677  * Split buffer into fields (delimited by whitespace or
678  * comma's).  Return the number of fields found.
679  */
680
681 static int
682 split (char *cp, char **vec)
683 {
684     int i;
685     unsigned char *s;
686
687     s = cp;
688
689     /* split into a maximum of NVEC fields */
690     for (i = 0; i <= NVEC;) {
691         vec[i] = NULL;
692
693         /* zap any whitespace and comma's */
694         while (isspace (*s) || *s == ',')
695             *s++ = 0;
696
697         /* end of buffer, time to leave */
698         if (*s == 0)
699             break;
700
701         /* get double quote text as a single field */
702         if (*s == '"') {
703             for (vec[i++] = ++s; *s && *s != '"'; s++) {
704                 /*
705                  * Check for escaped double quote.  We need
706                  * to shift the string to remove slash.
707                  */
708                 if (*s == QUOTE) {
709                     if (*++s == '"')
710                         strcpy (s - 1, s);
711                     s--;
712                 }
713             }
714             if (*s == '"')      /* zap trailing double quote */
715                 *s++ = 0;
716             continue;
717         }
718
719         if (*s == QUOTE && *++s != '"')
720             s--;
721         vec[i++] = s++;
722
723         /* move forward to next field delimiter */
724         while (*s && !isspace (*s) && *s != ',')
725             s++;
726     }
727     vec[i] = NULL;
728
729     return i;
730 }
731
732
733 /*
734  * Parse the headers of a message, and build the
735  * lookup table for matching fields and patterns.
736  */
737
738 static int
739 parse (int fd)
740 {
741     int i, state;
742     int fd1;
743     char *cp, *dp, *lp;
744     char name[NAMESZ], field[BUFSIZ];
745     struct pair *p, *q;
746     FILE  *in;
747
748     if (parsed++)
749         return 0;
750
751     /* get a new FILE pointer to message */
752     if ((fd1 = dup (fd)) == -1)
753         return -1;
754     if ((in = fdopen (fd1, "r")) == NULL) {
755         close (fd1);
756         return -1;
757     }
758     rewind (in);
759
760     /* add special entries to lookup table */
761     if ((p = lookup (hdrs, "source")))
762         p->p_value = getcpy (sender);
763     if ((p = lookup (hdrs, "addr")))
764         p->p_value = getcpy (addr);
765
766     /*
767      * Scan the headers of the message and build
768      * a lookup table.
769      */
770     for (i = 0, state = FLD;;) {
771         switch (state = m_getfld (state, name, field, sizeof(field), in)) {
772             case FLD: 
773             case FLDEOF: 
774             case FLDPLUS: 
775                 lp = add (field, NULL);
776                 while (state == FLDPLUS) {
777                     state = m_getfld (state, name, field, sizeof(field), in);
778                     lp = add (field, lp);
779                 }
780                 for (p = hdrs; p->p_name; p++) {
781                     if (!mh_strcasecmp (p->p_name, name)) {
782                         if (!(p->p_flags & P_HID)) {
783                             if ((cp = p->p_value)) {
784                                 if (p->p_flags & P_ADR) {
785                                     dp = cp + strlen (cp) - 1;
786                                     if (*dp == '\n')
787                                         *dp = 0;
788                                     cp = add (",\n\t", cp);
789                                 } else {
790                                     cp = add ("\t", cp);
791                                 }
792                             }
793                             p->p_value = add (lp, cp);
794                         }
795                         free (lp);
796                         break;
797                     }
798                 }
799                 if (p->p_name == NULL && i < NVEC) {
800                     p->p_name = getcpy (name);
801                     p->p_value = lp;
802                     p->p_flags = P_NIL;
803                     p++, i++;
804                     p->p_name = NULL;
805                 }
806                 if (state != FLDEOF)
807                     continue;
808                 break;
809
810             case BODY: 
811             case BODYEOF: 
812             case FILEEOF: 
813                 break;
814
815             case LENERR: 
816             case FMTERR: 
817                 advise (NULL, "format error in message");
818                 break;
819
820             default: 
821                 advise (NULL, "internal error in m_getfld");
822                 fclose (in);
823                 return -1;
824         }
825         break;
826     }
827     fclose (in);
828
829     if ((p = lookup (vars, "reply-to"))) {
830         if ((q = lookup (hdrs, "reply-to")) == NULL || q->p_value == NULL)
831             q = lookup (hdrs, "from");
832         p->p_value = getcpy (q ? q->p_value : "");
833         p->p_flags &= ~P_CHK;
834         if (debug)
835             debug_printf ("vars[%d]: name=\"%s\" value=\"%s\"\n",
836                     p - vars, p->p_name, trim(p->p_value));
837     }
838     if (debug) {
839         for (p = hdrs; p->p_name; p++)
840             debug_printf ("hdrs[%d]: name=\"%s\" value=\"%s\"\n",
841                 p - hdrs, p->p_name, p->p_value ? trim(p->p_value) : "");
842     }
843
844     return 0;
845 }
846
847
848 #define LPAREN  '('
849 #define RPAREN  ')'
850
851 /*
852  * Expand any builtin variables such as $(sender),
853  * $(address), etc., in a string.
854  */
855
856 static void
857 expand (char *s1, char *s2, int fd)
858 {
859     char c, *cp;
860     struct pair *p;
861
862     if (!globbed)
863         glob (fd);
864
865     while ((c = *s2++)) {
866         if (c != '$' || *s2 != LPAREN) {
867             *s1++ = c;
868         } else {
869             for (cp = ++s2; *s2 && *s2 != RPAREN; s2++)
870                 continue;
871             if (*s2 != RPAREN) {
872                 s2 = --cp;
873                 continue;
874             }
875             *s2++ = 0;
876             if ((p = lookup (vars, cp))) {
877                 if (!parsed && (p->p_flags & P_CHK))
878                     parse (fd);
879
880                 strcpy (s1, p->p_value);
881                 s1 += strlen (s1);
882             }
883         }
884     }
885     *s1 = 0;
886 }
887
888
889 /*
890  * Fill in the information missing from the "vars"
891  * table, which is necessary to expand any builtin
892  * variables in the string for a "pipe" or "qpipe"
893  * action.
894  */
895
896 static void
897 glob (int fd)
898 {
899     char buffer[BUFSIZ];
900     struct stat st;
901     struct pair *p;
902
903     if (globbed++)
904         return;
905
906     if ((p = lookup (vars, "sender")))
907         p->p_value = getcpy (sender);
908     if ((p = lookup (vars, "address")))
909         p->p_value = getcpy (addr);
910     if ((p = lookup (vars, "size"))) {
911         snprintf (buffer, sizeof(buffer), "%d",
912                 fstat (fd, &st) != -1 ? (int) st.st_size : 0);
913         p->p_value = getcpy (buffer);
914     }
915     if ((p = lookup (vars, "info")))
916         p->p_value = getcpy (info);
917
918     if (debug) {
919         for (p = vars; p->p_name; p++)
920             debug_printf ("vars[%d]: name=\"%s\" value=\"%s\"\n",
921                     p - vars, p->p_name, trim(p->p_value));
922     }
923 }
924
925
926 /*
927  * Find a matching name in a lookup table.  If found,
928  * return the "pairs" entry, else return NULL.
929  */
930
931 static struct pair *
932 lookup (struct pair *pairs, char *key)
933 {
934     for (; pairs->p_name; pairs++)
935         if (!mh_strcasecmp (pairs->p_name, key))
936             return pairs;
937
938     return NULL;
939 }
940
941
942 /*
943  * Check utmp(x) file to see if user is currently
944  * logged in.
945  */
946
947 #ifdef HAVE_GETUTENT
948 static int
949 logged_in (void)
950 {
951     struct utmp * utp;
952
953     if (utmped)
954         return utmped;
955
956     setutent();
957
958     while ((utp = getutent()) != NULL) {
959         if (
960 #ifdef HAVE_STRUCT_UTMP_UT_TYPE
961                 utp->ut_type == USER_PROCESS
962                 &&
963 #endif
964                 utp->ut_name[0] != 0
965                 && strncmp (user, utp->ut_name, sizeof(utp->ut_name)) == 0) {
966             if (debug)
967                 continue;
968             endutent();
969             return (utmped = DONE);
970         }
971     }
972
973     endutent();
974     return (utmped = NOTOK);
975 }
976 #else
977 static int
978 logged_in (void)
979 {
980     struct utmp ut;
981     FILE *uf;
982
983     if (utmped)
984         return utmped;
985
986     if ((uf = fopen (UTMP_FILE, "r")) == NULL)
987         return NOTOK;
988
989     while (fread ((char *) &ut, sizeof(ut), 1, uf) == 1) {
990         if (ut.ut_name[0] != 0
991             && strncmp (user, ut.ut_name, sizeof(ut.ut_name)) == 0) {
992             if (debug)
993                 continue;
994             fclose (uf);
995             return (utmped = DONE);
996         }
997     }
998
999     fclose (uf);
1000     return (utmped = NOTOK);
1001 }
1002 #endif
1003
1004 #define check(t,a,b)            if (t < a || t > b) return -1
1005 #define cmpar(h1,m1,h2,m2)      if (h1 < h2 || (h1 == h2 && m1 < m2)) return 0
1006
1007 static int
1008 timely (char *t1, char *t2)
1009 {
1010     int t1hours, t1mins, t2hours, t2mins;
1011
1012     if (sscanf (t1, "%d:%d", &t1hours, &t1mins) != 2)
1013         return -1;
1014     check (t1hours, 0, 23);
1015     check (t1mins, 0, 59);
1016
1017     if (sscanf (t2, "%d:%d", &t2hours, &t2mins) != 2)
1018         return -1;
1019     check (t2hours, 0, 23);
1020     check (t2mins, 0, 59);
1021
1022     cmpar (now->tw_hour, now->tw_min, t1hours, t1mins);
1023     cmpar (t2hours, t2mins, now->tw_hour, now->tw_min);
1024
1025     return -1;
1026 }
1027
1028
1029 /*
1030  * Deliver message by appending to a file.
1031  */
1032
1033 static int
1034 usr_file (int fd, char *mailbox, int mbx_style)
1035 {
1036     int md, mapping;
1037
1038     if (verbose)
1039         verbose_printf ("delivering to file \"%s\"", mailbox);
1040
1041     if (mbx_style == MBOX_FORMAT) {
1042         if (verbose)
1043             verbose_printf (" (mbox style)");
1044         mapping = 0;
1045     } else {
1046         if (verbose)
1047             verbose_printf (" (mmdf style)");
1048         mapping = 1;
1049     }
1050
1051     /* open and lock the file */
1052     if ((md = mbx_open (mailbox, mbx_style, pw->pw_uid, pw->pw_gid, m_gmprot())) == -1) {
1053         if (verbose)
1054             adorn ("", "unable to open:");
1055         return -1;
1056     }
1057
1058     lseek (fd, (off_t) 0, SEEK_SET);
1059
1060     /* append message to file */
1061     if (mbx_copy (mailbox, mbx_style, md, fd, mapping, NULL, verbose) == -1) {
1062         if (verbose)
1063             adorn ("", "error writing to:");
1064         return -1;
1065     }
1066
1067     /* close and unlock file */
1068     if (mbx_close (mailbox, md) == NOTOK) {
1069         if (verbose)
1070             adorn ("", "error closing:");
1071         return -1;
1072     }
1073
1074     if (verbose)
1075         verbose_printf (", success.\n");
1076     return 0;
1077 }
1078
1079
1080 /*
1081  * Deliver message to a nmh folder.
1082  */
1083
1084 static int
1085 usr_folder (int fd, char *string)
1086 {
1087     int status;
1088     char folder[BUFSIZ], *vec[3];
1089
1090     /* get folder name ready */
1091     if (*string == '+')
1092         strncpy(folder, string, sizeof(folder));
1093     else
1094         snprintf(folder, sizeof(folder), "+%s", string);
1095
1096     if (verbose)
1097         verbose_printf ("delivering to folder \"%s\"", folder + 1);
1098
1099     vec[0] = "rcvstore";
1100     vec[1] = folder;
1101     vec[2] = NULL;
1102
1103     /* use rcvstore to put message in folder */
1104     status = usr_pipe (fd, "rcvstore", rcvstoreproc, vec, 1);
1105
1106 #if 0
1107     /*
1108      * Currently, verbose status messages are handled by usr_pipe().
1109      */
1110     if (verbose) {
1111         if (status == 0)
1112             verbose_printf (", success.\n");
1113         else
1114             verbose_printf (", failed.\n");
1115     }
1116 #endif
1117
1118     return status;
1119 }
1120
1121 /*
1122  * Deliver message to a process.
1123  */
1124
1125 static int
1126 usr_pipe (int fd, char *cmd, char *pgm, char **vec, int suppress)
1127 {
1128     pid_t child_id;
1129     int i, bytes, seconds, status;
1130     struct stat st;
1131
1132     if (verbose && !suppress)
1133         verbose_printf ("delivering to pipe \"%s\"", cmd);
1134
1135     lseek (fd, (off_t) 0, SEEK_SET);
1136
1137     for (i = 0; (child_id = fork()) == -1 && i < 5; i++)
1138         sleep (5);
1139
1140     switch (child_id) {
1141         case -1: 
1142             /* fork error */
1143             if (verbose)
1144                 adorn ("fork", "unable to");
1145             return -1;
1146
1147         case 0: 
1148             /* child process */
1149             if (fd != 0)
1150                 dup2 (fd, 0);
1151             freopen ("/dev/null", "w", stdout);
1152             freopen ("/dev/null", "w", stderr);
1153             if (fd != 3)
1154                 dup2 (fd, 3);
1155             closefds (4);
1156
1157 #ifdef TIOCNOTTY
1158             if ((fd = open ("/dev/tty", O_RDWR)) != -1) {
1159                 ioctl (fd, TIOCNOTTY, NULL);
1160                 close (fd);
1161             }
1162 #endif /* TIOCNOTTY */
1163
1164             setpgid ((pid_t) 0, getpid ());     /* put in own process group */
1165
1166             *environ = NULL;
1167             m_putenv ("USER", pw->pw_name);
1168             m_putenv ("HOME", pw->pw_dir);
1169             m_putenv ("SHELL", pw->pw_shell);
1170
1171             execvp (pgm, vec);
1172             _exit (-1);
1173
1174         default: 
1175             /* parent process */
1176             if (!setjmp (myctx)) {
1177                 SIGNAL (SIGALRM, alrmser);
1178                 bytes = fstat (fd, &st) != -1 ? (int) st.st_size : 100;
1179
1180                 /* amount of time to wait depends on message size */
1181                 if (bytes <= 100) {
1182                     /* give at least 5 minutes */
1183                     seconds = 300;
1184                 } else if (bytes >= 90000) {
1185                     /* a half hour is long enough */
1186                     seconds = 1800;
1187                 } else {
1188                     seconds = (bytes / 60) + 300;
1189                 }
1190                 alarm ((unsigned int) seconds);
1191                 status = pidwait (child_id, 0);
1192                 alarm (0);
1193
1194                 if (verbose) {
1195                     if (status == 0)
1196                         verbose_printf (", success.\n");
1197                     else
1198                         if ((status & 0xff00) == 0xff00)
1199                             verbose_printf (", system error\n");
1200                         else
1201                             pidstatus (status, stdout, ", failed");
1202                 }
1203                 return (status == 0 ? 0 : -1);
1204             } else {
1205                 /*
1206                  * Ruthlessly kill the child and anything
1207                  * else in its process group.
1208                  */
1209                 KILLPG(child_id, SIGKILL);
1210                 if (verbose)
1211                     verbose_printf (", timed-out; terminated\n");
1212                 return -1;
1213             }
1214     }
1215 }
1216
1217
1218 static RETSIGTYPE
1219 alrmser (int i)
1220 {
1221 #ifndef RELIABLE_SIGNALS
1222     SIGNAL (SIGALRM, alrmser);
1223 #endif
1224
1225     longjmp (myctx, DONE);
1226 }
1227
1228
1229 /*
1230  * Get the `sender' from the envelope
1231  * information ("From " line).
1232  */
1233
1234 static void
1235 get_sender (char *envelope, char **sender)
1236 {
1237     int i;
1238     unsigned char *cp;
1239     unsigned char buffer[BUFSIZ];
1240
1241     if (envelope == NULL) {
1242         *sender = getcpy ("");
1243         return;
1244     }
1245
1246     i = strlen ("From ");
1247     strncpy (buffer, envelope + i, sizeof(buffer));
1248     if ((cp = strchr(buffer, '\n'))) {
1249         *cp = 0;
1250         cp -= 24;
1251         if (cp < buffer)
1252             cp = buffer;
1253     } else {
1254         cp = buffer;
1255     }
1256     *cp = 0;
1257
1258     for (cp = buffer + strlen (buffer) - 1; cp >= buffer; cp--)
1259         if (isspace (*cp))
1260             *cp = 0;
1261         else
1262             break;
1263     *sender = getcpy (buffer);
1264 }
1265
1266
1267 /*
1268  * Copy message into a temporary file.
1269  * While copying, it will do some header processing
1270  * including the extraction of the envelope information.
1271  */
1272
1273 static int
1274 copy_message (int qd, char *tmpfil, int fold)
1275 {
1276     int i, first = 1, fd1, fd2;
1277     char buffer[BUFSIZ];
1278     FILE *qfp, *ffp;
1279     char *tfile = NULL;
1280
1281     tfile = m_mktemp2(NULL, invo_name, &fd1, NULL);
1282     if (tfile == NULL) return -1;
1283     fchmod(fd1, 0600);
1284     strncpy (tmpfil, tfile, BUFSIZ);
1285
1286     if (!fold) {
1287         while ((i = read (qd, buffer, sizeof(buffer))) > 0)
1288             if (write (fd1, buffer, i) != i) {
1289 you_lose:
1290                 close (fd1);
1291                 unlink (tmpfil);
1292                 return -1;
1293             }
1294         if (i == -1)
1295             goto you_lose;
1296         lseek (fd1, (off_t) 0, SEEK_SET);
1297         return fd1;
1298     }
1299
1300     /* dup the fd for incoming message */
1301     if ((fd2 = dup (qd)) == -1) {
1302         close (fd1);
1303         return -1;
1304     }
1305
1306     /* now create a FILE pointer for it */
1307     if ((qfp = fdopen (fd2, "r")) == NULL) {
1308         close (fd1);
1309         close (fd2);
1310         return -1;
1311     }
1312
1313     /* dup the fd for temporary file */
1314     if ((fd2 = dup (fd1)) == -1) {
1315         close (fd1);
1316         fclose (qfp);
1317         return -1;
1318     }
1319
1320     /* now create a FILE pointer for it */
1321     if ((ffp = fdopen (fd2, "r+")) == NULL) {
1322         close (fd1);
1323         close (fd2);
1324         fclose (qfp);
1325         return -1;
1326     }
1327
1328     /*
1329      * copy message into temporary file
1330      * and massage the headers.  Save
1331      * a copy of the "From " line for later.
1332      */
1333     i = strlen ("From ");
1334     while (fgets (buffer, sizeof(buffer), qfp)) {
1335         if (first) {
1336             first = 0;
1337             if (!strncmp (buffer, "From ", i)) {
1338 #ifdef RPATHS
1339                 char *fp, *cp, *hp, *ep;
1340 #endif
1341                 /* get copy of envelope information ("From " line) */
1342                 envelope = getcpy (buffer);
1343
1344 #if 0
1345                 /* First go ahead and put "From " line in message */
1346                 fputs (buffer, ffp);
1347                 if (ferror (ffp))
1348                     goto fputs_error;
1349 #endif
1350
1351 #ifdef RPATHS
1352                 /*
1353                  * Now create a "Return-Path:" line
1354                  * from the "From " line.
1355                  */
1356                 hp = cp = strchr(fp = envelope + i, ' ');
1357                 while ((hp = strchr(++hp, 'r')))
1358                     if (uprf (hp, "remote from")) {
1359                         hp = strrchr(hp, ' ');
1360                         break;
1361                     }
1362                 if (hp) {
1363                     /* return path for UUCP style addressing */
1364                     ep = strchr(++hp, '\n');
1365                     snprintf (buffer, sizeof(buffer), "Return-Path: %.*s!%.*s\n",
1366                         (int)(ep - hp), hp, (int)(cp - fp), fp);
1367                 } else {
1368                     /* return path for standard domain addressing */
1369                     snprintf (buffer, sizeof(buffer), "Return-Path: %.*s\n",
1370                         (int)(cp - fp), fp);
1371                 }
1372
1373                 /* Add Return-Path header to message */
1374                 fputs (buffer, ffp);
1375                 if (ferror (ffp))
1376                     goto fputs_error;
1377 #endif
1378                 /* Put the delivery date in message */
1379                 fputs (ddate, ffp);
1380                 if (ferror (ffp))
1381                     goto fputs_error;
1382
1383                 continue;
1384             }
1385         }
1386
1387         fputs (buffer, ffp);
1388         if (ferror (ffp))
1389             goto fputs_error;
1390     }
1391
1392     fclose (ffp);
1393     if (ferror (qfp)) {
1394         close (fd1);
1395         fclose (qfp);
1396         return -1;
1397     }
1398     fclose (qfp);
1399     lseek (fd1, (off_t) 0, SEEK_SET);
1400     return fd1;
1401
1402
1403 fputs_error:
1404     close (fd1);
1405     fclose (ffp);
1406     fclose (qfp);
1407     return -1;
1408 }
1409
1410 /*
1411  * Trim strings for pretty printing of debugging output
1412  */
1413
1414 static char *
1415 trim (char *cp)
1416 {
1417     char buffer[BUFSIZ*4];
1418     unsigned char *bp, *sp;
1419
1420     if (cp == NULL)
1421         return NULL;
1422
1423     /* copy string into temp buffer */
1424     strncpy (buffer, cp, sizeof(buffer));
1425     bp = buffer;
1426
1427     /* skip over leading whitespace */
1428     while (isspace(*bp))
1429         bp++;
1430
1431     /* start at the end and zap trailing whitespace */
1432     for (sp = bp + strlen(bp) - 1; sp >= bp; sp--) {
1433         if (isspace(*sp))
1434             *sp = 0;
1435         else
1436             break;
1437     }
1438
1439     /* replace remaining whitespace with spaces */
1440     for (sp = bp; *sp; sp++)
1441         if (isspace(*sp))
1442             *sp = ' ';
1443
1444     /* now return a copy */
1445     return getcpy(bp);
1446 }
1447
1448 /*
1449  * Function for printing `verbose' messages.
1450  */
1451
1452 static void
1453 verbose_printf (char *fmt, ...)
1454 {
1455     va_list ap;
1456
1457     va_start(ap, fmt);
1458     vfprintf (stdout, fmt, ap);
1459     va_end(ap);
1460
1461     fflush (stdout);    /* now flush output */
1462 }
1463
1464
1465 /*
1466  * Function for printing `verbose' delivery
1467  * error messages.
1468  */
1469
1470 static void
1471 adorn (char *what, char *fmt, ...)
1472 {
1473     va_list ap;
1474     int eindex;
1475     char *s;
1476
1477     eindex = errno;     /* save the errno */
1478     fprintf (stdout, ", ");
1479
1480     va_start(ap, fmt);
1481     vfprintf (stdout, fmt, ap);
1482     va_end(ap);
1483
1484     if (what) {
1485         if (*what)
1486             fprintf (stdout, " %s: ", what);
1487         if ((s = strerror (eindex)))
1488             fprintf (stdout, "%s", s);
1489         else
1490             fprintf (stdout, "Error %d", eindex);
1491     }
1492
1493     fputc ('\n', stdout);
1494     fflush (stdout);
1495 }
1496
1497
1498 /*
1499  * Function for printing `debug' messages.
1500  */
1501
1502 static void
1503 debug_printf (char *fmt, ...)
1504 {
1505     va_list ap;
1506
1507     va_start(ap, fmt);
1508     vfprintf (stderr, fmt, ap);
1509     va_end(ap);
1510 }
1511
1512
1513 /*
1514  * Check ndbm/db file(s) to see if the Message-Id of this
1515  * message matches the Message-Id of a previous message,
1516  * so we can discard it.  If it doesn't match, we add the
1517  * Message-Id of this message to the ndbm/db file.
1518  */
1519 static int
1520 suppress_duplicates (int fd, char *file)
1521 {
1522     int fd1, lockfd, state, result;
1523     char *cp, buf[BUFSIZ], name[NAMESZ];
1524     datum key, value;
1525     DBM *db;
1526     FILE *in;
1527
1528     if ((fd1 = dup (fd)) == -1)
1529         return -1;
1530     if (!(in = fdopen (fd1, "r"))) {
1531         close (fd1);
1532         return -1;
1533     }
1534     rewind (in);
1535
1536     for (state = FLD;;) {
1537         state = m_getfld (state, name, buf, sizeof(buf), in);
1538         switch (state) {
1539             case FLD:
1540             case FLDPLUS:
1541             case FLDEOF:
1542                 /* Search for the message ID */
1543                 if (mh_strcasecmp (name, "Message-ID")) {
1544                     while (state == FLDPLUS)
1545                         state = m_getfld (state, name, buf, sizeof(buf), in);
1546                     continue;
1547                 }
1548
1549                 cp = add (buf, NULL);
1550                 while (state == FLDPLUS) {
1551                     state = m_getfld (state, name, buf, sizeof(buf), in);
1552                     cp = add (buf, cp);
1553                 }
1554                 key.dptr = trimcpy (cp);
1555                 key.dsize = strlen (key.dptr) + 1;
1556                 free (cp);
1557                 cp = key.dptr;
1558
1559                 if (!(db = dbm_open (file, O_RDWR | O_CREAT, 0600))) {
1560                     advise (file, "unable to perform dbm_open on");
1561                     free (cp);
1562                     fclose (in);
1563                     return -1;
1564                 }
1565                 /*
1566                  * Since it is difficult to portable lock a ndbm file,
1567                  * we will open and lock the Maildelivery file instead.
1568                  * This will fail if your Maildelivery file doesn't
1569                  * exist.
1570                  */
1571                 if ((lockfd = lkopen(file, O_RDWR, 0)) == -1) {
1572                     advise (file, "unable to perform file locking on");
1573                     free (cp);
1574                     fclose (in);
1575                     return -1;
1576                 }
1577                 value = dbm_fetch (db, key);
1578                 if (value.dptr) {
1579                     if (verbose)
1580                         verbose_printf ("Message-ID: %s\n            already received on %s",
1581                                  cp, value.dptr);
1582                     result = DONE;
1583                 } else {
1584                     value.dptr  = ddate + sizeof("Delivery-Date:");
1585                     value.dsize = strlen(value.dptr) + 1;
1586                     if (dbm_store (db, key, value, DBM_INSERT))
1587                         advise (file, "possibly corrupt file");
1588                     result = 0;
1589                 }
1590
1591                 dbm_close (db);
1592                 lkclose(lockfd, file);
1593                 free (cp);
1594                 fclose (in);
1595                 return result;
1596                 break;
1597
1598            case BODY:
1599            case BODYEOF:
1600            case FILEEOF:
1601                 break;
1602
1603            case LENERR:
1604            case FMTERR:
1605            default:
1606                 break;
1607         }
1608
1609         break;
1610     }
1611
1612     fclose (in);
1613     return 0;
1614 }