Switch from using RETSIGTYPE via autoconf to void, since POSIX says that's
[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 void 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     return usr_file (fd, mbox, MBOX_FORMAT);
443 }
444
445
446 #define matches(a,b) (stringdex (b, a) >= 0)
447
448 /*
449  * Parse the delivery file, and process incoming message.
450  */
451
452 static int
453 usr_delivery (int fd, char *delivery, int su)
454 {
455     int i, accept, status=1, won, vecp, next;
456     char *field, *pattern, *action, *result, *string;
457     char buffer[BUFSIZ], tmpbuf[BUFSIZ];
458     char *cp, *vec[NVEC];
459     struct stat st;
460     struct pair *p;
461     FILE *fp;
462
463     /* open the delivery file */
464     if ((fp = fopen (delivery, "r")) == NULL)
465         return -1;
466
467     /* check if delivery file has bad ownership or permissions */
468     if (fstat (fileno (fp), &st) == -1
469             || (st.st_uid != 0 && (su || st.st_uid != pw->pw_uid))
470             || st.st_mode & (S_IWGRP|S_IWOTH)) {
471         if (verbose) {
472             verbose_printf ("WARNING: %s has bad ownership/modes (su=%d,uid=%d,owner=%d,mode=0%o)\n",
473                     delivery, su, (int) pw->pw_uid, (int) st.st_uid, (int) st.st_mode);
474         }
475         return -1;
476     }
477
478     won = 0;
479     next = 1;
480
481     /* read and process delivery file */
482     while (fgets (buffer, sizeof(buffer), fp)) {
483         /* skip comments and empty lines */
484         if (*buffer == '#' || *buffer == '\n')
485             continue;
486
487         /* zap trailing newline */
488         if ((cp = strchr(buffer, '\n')))
489             *cp = 0;
490
491         /* split buffer into fields */
492         vecp = split (buffer, vec);
493
494         /* check for too few fields */
495         if (vecp < 5) {
496             if (debug)
497                 debug_printf ("WARNING: entry with only %d fields, skipping.\n", vecp);
498             continue;
499         }
500
501         if (debug) {
502             for (i = 0; vec[i]; i++)
503                 debug_printf ("vec[%d]: \"%s\"\n", i, trim(vec[i]));
504         }
505
506         field   = vec[0];
507         pattern = vec[1];
508         action  = vec[2];
509         result  = vec[3];
510         string  = vec[4];
511
512         /* find out how to perform the action */
513         switch (result[0]) {
514             case 'N':
515             case 'n':
516                 /*
517                  * If previous condition failed, don't
518                  * do this - else fall through
519                  */
520                 if (!next)
521                     continue;   /* else fall */
522
523             case '?': 
524                 /*
525                  * If already delivered, skip this action.  Else
526                  * consider delivered if action is successful.
527                  */
528                 if (won)
529                     continue;   /* else fall */
530
531             case 'A': 
532             case 'a': 
533                 /*
534                  * Take action, and consider delivered if
535                  * action is successful.
536                  */
537                 accept = 1;
538                 break;
539
540             case 'R': 
541             case 'r': 
542             default: 
543                 /*
544                  * Take action, but don't consider delivered, even
545                  * if action is successful
546                  */
547                 accept = 0;
548                 break;
549         }
550
551         if (vecp > 5) {
552             if (!mh_strcasecmp (vec[5], "select")) {
553                 if (logged_in () != -1)
554                     continue;
555                 if (vecp > 7 && timely (vec[6], vec[7]) == -1)
556                     continue;
557             }
558         }
559
560         /* check if the field matches */
561         switch (*field) {
562             case '*': 
563             /* always matches */
564                 break;
565
566             case 'd': 
567             /*
568              * "default" matches only if the message hasn't
569              * been delivered yet.
570              */
571                 if (!mh_strcasecmp (field, "default")) {
572                     if (won)
573                         continue;
574                     break;
575                 }               /* else fall */
576
577             default: 
578                 /* parse message and build lookup table */
579                 if (!parsed && parse (fd) == -1) {
580                     fclose (fp);
581                     return -1;
582                 }
583                 /*
584                  * find header field in lookup table, and
585                  * see if the pattern matches.
586                  */
587                 if ((p = lookup (hdrs, field)) && (p->p_value != NULL)
588                         && matches (p->p_value, pattern)) {
589                     next = 1;
590                 } else {
591                     next = 0;
592                     continue;
593                 }
594                 break;
595         }
596
597         /* find out the action to perform */
598         switch (*action) {
599             case 'q':
600                 /* deliver to quoted pipe */
601                 if (mh_strcasecmp (action, "qpipe"))
602                     continue;   /* else fall */
603             case '^':
604                 expand (tmpbuf, string, fd);
605                 if (split (tmpbuf, vec) < 1)
606                     continue;
607                 status = usr_pipe (fd, tmpbuf, vec[0], vec, 0);
608                 break;
609
610             case 'p': 
611                 /* deliver to pipe */
612                 if (mh_strcasecmp (action, "pipe"))
613                     continue;   /* else fall */
614             case '|': 
615                 vec[2] = "sh";
616                 vec[3] = "-c";
617                 expand (tmpbuf, string, fd);
618                 vec[4] = tmpbuf;
619                 vec[5] = NULL;
620                 status = usr_pipe (fd, tmpbuf, "/bin/sh", vec + 2, 0);
621                 break;
622
623             case 'f': 
624                 /* mbox format */
625                 if (!mh_strcasecmp (action, "file")) {
626                     status = usr_file (fd, string, MBOX_FORMAT);
627                     break;
628                 }
629                 /* deliver to nmh folder */
630                 else if (mh_strcasecmp (action, "folder"))
631                     continue;   /* else fall */
632             case '+':
633                 status = usr_folder (fd, string);
634                 break;
635
636             case 'm':
637                 /* mmdf format */
638                 if (!mh_strcasecmp (action, "mmdf")) {
639                     status = usr_file (fd, string, MMDF_FORMAT);
640                     break;
641                 }
642                 /* mbox format */
643                 else if (mh_strcasecmp (action, "mbox"))
644                     continue;   /* else fall */
645
646             case '>': 
647                 /* mbox format */
648                 status = usr_file (fd, string, MBOX_FORMAT);
649                 break;
650
651             case 'd': 
652                 /* ignore message */
653                 if (mh_strcasecmp (action, "destroy"))
654                     continue;
655                 status = 0;
656                 break;
657         }
658
659         if (status) next = 0;   /* action failed, mark for 'N' result */
660
661         if (accept && status == 0)
662             won++;
663     }
664
665     fclose (fp);
666     return (won ? 0 : -1);
667 }
668
669
670 #define QUOTE   '\\'
671
672 /*
673  * Split buffer into fields (delimited by whitespace or
674  * comma's).  Return the number of fields found.
675  */
676
677 static int
678 split (char *cp, char **vec)
679 {
680     int i;
681     unsigned char *s;
682
683     s = cp;
684
685     /* split into a maximum of NVEC fields */
686     for (i = 0; i <= NVEC;) {
687         vec[i] = NULL;
688
689         /* zap any whitespace and comma's */
690         while (isspace (*s) || *s == ',')
691             *s++ = 0;
692
693         /* end of buffer, time to leave */
694         if (*s == 0)
695             break;
696
697         /* get double quote text as a single field */
698         if (*s == '"') {
699             for (vec[i++] = ++s; *s && *s != '"'; s++) {
700                 /*
701                  * Check for escaped double quote.  We need
702                  * to shift the string to remove slash.
703                  */
704                 if (*s == QUOTE) {
705                     if (*++s == '"')
706                         strcpy (s - 1, s);
707                     s--;
708                 }
709             }
710             if (*s == '"')      /* zap trailing double quote */
711                 *s++ = 0;
712             continue;
713         }
714
715         if (*s == QUOTE && *++s != '"')
716             s--;
717         vec[i++] = s++;
718
719         /* move forward to next field delimiter */
720         while (*s && !isspace (*s) && *s != ',')
721             s++;
722     }
723     vec[i] = NULL;
724
725     return i;
726 }
727
728
729 /*
730  * Parse the headers of a message, and build the
731  * lookup table for matching fields and patterns.
732  */
733
734 static int
735 parse (int fd)
736 {
737     int i, state;
738     int fd1;
739     char *cp, *dp, *lp;
740     char name[NAMESZ], field[BUFSIZ];
741     struct pair *p, *q;
742     FILE  *in;
743
744     if (parsed++)
745         return 0;
746
747     /* get a new FILE pointer to message */
748     if ((fd1 = dup (fd)) == -1)
749         return -1;
750     if ((in = fdopen (fd1, "r")) == NULL) {
751         close (fd1);
752         return -1;
753     }
754     rewind (in);
755
756     /* add special entries to lookup table */
757     if ((p = lookup (hdrs, "source")))
758         p->p_value = getcpy (sender);
759     if ((p = lookup (hdrs, "addr")))
760         p->p_value = getcpy (addr);
761
762     /*
763      * Scan the headers of the message and build
764      * a lookup table.
765      */
766     for (i = 0, state = FLD;;) {
767         switch (state = m_getfld (state, name, field, sizeof(field), in)) {
768             case FLD: 
769             case FLDEOF: 
770             case FLDPLUS: 
771                 lp = add (field, NULL);
772                 while (state == FLDPLUS) {
773                     state = m_getfld (state, name, field, sizeof(field), in);
774                     lp = add (field, lp);
775                 }
776                 for (p = hdrs; p->p_name; p++) {
777                     if (!mh_strcasecmp (p->p_name, name)) {
778                         if (!(p->p_flags & P_HID)) {
779                             if ((cp = p->p_value)) {
780                                 if (p->p_flags & P_ADR) {
781                                     dp = cp + strlen (cp) - 1;
782                                     if (*dp == '\n')
783                                         *dp = 0;
784                                     cp = add (",\n\t", cp);
785                                 } else {
786                                     cp = add ("\t", cp);
787                                 }
788                             }
789                             p->p_value = add (lp, cp);
790                         }
791                         free (lp);
792                         break;
793                     }
794                 }
795                 if (p->p_name == NULL && i < NVEC) {
796                     p->p_name = getcpy (name);
797                     p->p_value = lp;
798                     p->p_flags = P_NIL;
799                     p++, i++;
800                     p->p_name = NULL;
801                 }
802                 if (state != FLDEOF)
803                     continue;
804                 break;
805
806             case BODY: 
807             case BODYEOF: 
808             case FILEEOF: 
809                 break;
810
811             case LENERR: 
812             case FMTERR: 
813                 advise (NULL, "format error in message");
814                 break;
815
816             default: 
817                 advise (NULL, "internal error in m_getfld");
818                 fclose (in);
819                 return -1;
820         }
821         break;
822     }
823     fclose (in);
824
825     if ((p = lookup (vars, "reply-to"))) {
826         if ((q = lookup (hdrs, "reply-to")) == NULL || q->p_value == NULL)
827             q = lookup (hdrs, "from");
828         p->p_value = getcpy (q ? q->p_value : "");
829         p->p_flags &= ~P_CHK;
830         if (debug)
831             debug_printf ("vars[%d]: name=\"%s\" value=\"%s\"\n",
832                     p - vars, p->p_name, trim(p->p_value));
833     }
834     if (debug) {
835         for (p = hdrs; p->p_name; p++)
836             debug_printf ("hdrs[%d]: name=\"%s\" value=\"%s\"\n",
837                 p - hdrs, p->p_name, p->p_value ? trim(p->p_value) : "");
838     }
839
840     return 0;
841 }
842
843
844 #define LPAREN  '('
845 #define RPAREN  ')'
846
847 /*
848  * Expand any builtin variables such as $(sender),
849  * $(address), etc., in a string.
850  */
851
852 static void
853 expand (char *s1, char *s2, int fd)
854 {
855     char c, *cp;
856     struct pair *p;
857
858     if (!globbed)
859         glob (fd);
860
861     while ((c = *s2++)) {
862         if (c != '$' || *s2 != LPAREN) {
863             *s1++ = c;
864         } else {
865             for (cp = ++s2; *s2 && *s2 != RPAREN; s2++)
866                 continue;
867             if (*s2 != RPAREN) {
868                 s2 = --cp;
869                 continue;
870             }
871             *s2++ = 0;
872             if ((p = lookup (vars, cp))) {
873                 if (!parsed && (p->p_flags & P_CHK))
874                     parse (fd);
875
876                 strcpy (s1, p->p_value);
877                 s1 += strlen (s1);
878             }
879         }
880     }
881     *s1 = 0;
882 }
883
884
885 /*
886  * Fill in the information missing from the "vars"
887  * table, which is necessary to expand any builtin
888  * variables in the string for a "pipe" or "qpipe"
889  * action.
890  */
891
892 static void
893 glob (int fd)
894 {
895     char buffer[BUFSIZ];
896     struct stat st;
897     struct pair *p;
898
899     if (globbed++)
900         return;
901
902     if ((p = lookup (vars, "sender")))
903         p->p_value = getcpy (sender);
904     if ((p = lookup (vars, "address")))
905         p->p_value = getcpy (addr);
906     if ((p = lookup (vars, "size"))) {
907         snprintf (buffer, sizeof(buffer), "%d",
908                 fstat (fd, &st) != -1 ? (int) st.st_size : 0);
909         p->p_value = getcpy (buffer);
910     }
911     if ((p = lookup (vars, "info")))
912         p->p_value = getcpy (info);
913
914     if (debug) {
915         for (p = vars; p->p_name; p++)
916             debug_printf ("vars[%d]: name=\"%s\" value=\"%s\"\n",
917                     p - vars, p->p_name, trim(p->p_value));
918     }
919 }
920
921
922 /*
923  * Find a matching name in a lookup table.  If found,
924  * return the "pairs" entry, else return NULL.
925  */
926
927 static struct pair *
928 lookup (struct pair *pairs, char *key)
929 {
930     for (; pairs->p_name; pairs++)
931         if (!mh_strcasecmp (pairs->p_name, key))
932             return pairs;
933
934     return NULL;
935 }
936
937
938 /*
939  * Check utmp(x) file to see if user is currently
940  * logged in.
941  */
942
943 #ifdef HAVE_GETUTENT
944 static int
945 logged_in (void)
946 {
947     struct utmp * utp;
948
949     if (utmped)
950         return utmped;
951
952     setutent();
953
954     while ((utp = getutent()) != NULL) {
955         if (
956 #ifdef HAVE_STRUCT_UTMP_UT_TYPE
957                 utp->ut_type == USER_PROCESS
958                 &&
959 #endif
960                 utp->ut_name[0] != 0
961                 && strncmp (user, utp->ut_name, sizeof(utp->ut_name)) == 0) {
962             if (debug)
963                 continue;
964             endutent();
965             return (utmped = DONE);
966         }
967     }
968
969     endutent();
970     return (utmped = NOTOK);
971 }
972 #else
973 static int
974 logged_in (void)
975 {
976     struct utmp ut;
977     FILE *uf;
978
979     if (utmped)
980         return utmped;
981
982     if ((uf = fopen (UTMP_FILE, "r")) == NULL)
983         return NOTOK;
984
985     while (fread ((char *) &ut, sizeof(ut), 1, uf) == 1) {
986         if (ut.ut_name[0] != 0
987             && strncmp (user, ut.ut_name, sizeof(ut.ut_name)) == 0) {
988             if (debug)
989                 continue;
990             fclose (uf);
991             return (utmped = DONE);
992         }
993     }
994
995     fclose (uf);
996     return (utmped = NOTOK);
997 }
998 #endif
999
1000 #define check(t,a,b)            if (t < a || t > b) return -1
1001 #define cmpar(h1,m1,h2,m2)      if (h1 < h2 || (h1 == h2 && m1 < m2)) return 0
1002
1003 static int
1004 timely (char *t1, char *t2)
1005 {
1006     int t1hours, t1mins, t2hours, t2mins;
1007
1008     if (sscanf (t1, "%d:%d", &t1hours, &t1mins) != 2)
1009         return -1;
1010     check (t1hours, 0, 23);
1011     check (t1mins, 0, 59);
1012
1013     if (sscanf (t2, "%d:%d", &t2hours, &t2mins) != 2)
1014         return -1;
1015     check (t2hours, 0, 23);
1016     check (t2mins, 0, 59);
1017
1018     cmpar (now->tw_hour, now->tw_min, t1hours, t1mins);
1019     cmpar (t2hours, t2mins, now->tw_hour, now->tw_min);
1020
1021     return -1;
1022 }
1023
1024
1025 /*
1026  * Deliver message by appending to a file.
1027  */
1028
1029 static int
1030 usr_file (int fd, char *mailbox, int mbx_style)
1031 {
1032     int md, mapping;
1033
1034     if (verbose)
1035         verbose_printf ("delivering to file \"%s\"", mailbox);
1036
1037     if (mbx_style == MBOX_FORMAT) {
1038         if (verbose)
1039             verbose_printf (" (mbox style)");
1040         mapping = 0;
1041     } else {
1042         if (verbose)
1043             verbose_printf (" (mmdf style)");
1044         mapping = 1;
1045     }
1046
1047     /* open and lock the file */
1048     if ((md = mbx_open (mailbox, mbx_style, pw->pw_uid, pw->pw_gid, m_gmprot())) == -1) {
1049         if (verbose)
1050             adorn ("", "unable to open:");
1051         return -1;
1052     }
1053
1054     lseek (fd, (off_t) 0, SEEK_SET);
1055
1056     /* append message to file */
1057     if (mbx_copy (mailbox, mbx_style, md, fd, mapping, NULL, verbose) == -1) {
1058         if (verbose)
1059             adorn ("", "error writing to:");
1060         return -1;
1061     }
1062
1063     /* close and unlock file */
1064     if (mbx_close (mailbox, md) == NOTOK) {
1065         if (verbose)
1066             adorn ("", "error closing:");
1067         return -1;
1068     }
1069
1070     if (verbose)
1071         verbose_printf (", success.\n");
1072     return 0;
1073 }
1074
1075
1076 /*
1077  * Deliver message to a nmh folder.
1078  */
1079
1080 static int
1081 usr_folder (int fd, char *string)
1082 {
1083     int status;
1084     char folder[BUFSIZ], *vec[3];
1085
1086     /* get folder name ready */
1087     if (*string == '+')
1088         strncpy(folder, string, sizeof(folder));
1089     else
1090         snprintf(folder, sizeof(folder), "+%s", string);
1091
1092     if (verbose)
1093         verbose_printf ("delivering to folder \"%s\"", folder + 1);
1094
1095     vec[0] = "rcvstore";
1096     vec[1] = folder;
1097     vec[2] = NULL;
1098
1099     /* use rcvstore to put message in folder */
1100     status = usr_pipe (fd, "rcvstore", rcvstoreproc, vec, 1);
1101
1102 #if 0
1103     /*
1104      * Currently, verbose status messages are handled by usr_pipe().
1105      */
1106     if (verbose) {
1107         if (status == 0)
1108             verbose_printf (", success.\n");
1109         else
1110             verbose_printf (", failed.\n");
1111     }
1112 #endif
1113
1114     return status;
1115 }
1116
1117 /*
1118  * Deliver message to a process.
1119  */
1120
1121 static int
1122 usr_pipe (int fd, char *cmd, char *pgm, char **vec, int suppress)
1123 {
1124     pid_t child_id;
1125     int i, bytes, seconds, status;
1126     struct stat st;
1127
1128     if (verbose && !suppress)
1129         verbose_printf ("delivering to pipe \"%s\"", cmd);
1130
1131     lseek (fd, (off_t) 0, SEEK_SET);
1132
1133     for (i = 0; (child_id = fork()) == -1 && i < 5; i++)
1134         sleep (5);
1135
1136     switch (child_id) {
1137         case -1: 
1138             /* fork error */
1139             if (verbose)
1140                 adorn ("fork", "unable to");
1141             return -1;
1142
1143         case 0: 
1144             /* child process */
1145             if (fd != 0)
1146                 dup2 (fd, 0);
1147             freopen ("/dev/null", "w", stdout);
1148             freopen ("/dev/null", "w", stderr);
1149             if (fd != 3)
1150                 dup2 (fd, 3);
1151             closefds (4);
1152
1153 #ifdef TIOCNOTTY
1154             if ((fd = open ("/dev/tty", O_RDWR)) != -1) {
1155                 ioctl (fd, TIOCNOTTY, NULL);
1156                 close (fd);
1157             }
1158 #endif /* TIOCNOTTY */
1159
1160             setpgid ((pid_t) 0, getpid ());     /* put in own process group */
1161
1162             *environ = NULL;
1163             m_putenv ("USER", pw->pw_name);
1164             m_putenv ("HOME", pw->pw_dir);
1165             m_putenv ("SHELL", pw->pw_shell);
1166
1167             execvp (pgm, vec);
1168             _exit (-1);
1169
1170         default: 
1171             /* parent process */
1172             if (!setjmp (myctx)) {
1173                 SIGNAL (SIGALRM, alrmser);
1174                 bytes = fstat (fd, &st) != -1 ? (int) st.st_size : 100;
1175
1176                 /* amount of time to wait depends on message size */
1177                 if (bytes <= 100) {
1178                     /* give at least 5 minutes */
1179                     seconds = 300;
1180                 } else if (bytes >= 90000) {
1181                     /* a half hour is long enough */
1182                     seconds = 1800;
1183                 } else {
1184                     seconds = (bytes / 60) + 300;
1185                 }
1186                 alarm ((unsigned int) seconds);
1187                 status = pidwait (child_id, 0);
1188                 alarm (0);
1189
1190                 if (verbose) {
1191                     if (status == 0)
1192                         verbose_printf (", success.\n");
1193                     else
1194                         if ((status & 0xff00) == 0xff00)
1195                             verbose_printf (", system error\n");
1196                         else
1197                             pidstatus (status, stdout, ", failed");
1198                 }
1199                 return (status == 0 ? 0 : -1);
1200             } else {
1201                 /*
1202                  * Ruthlessly kill the child and anything
1203                  * else in its process group.
1204                  */
1205                 killpg(child_id, SIGKILL);
1206                 if (verbose)
1207                     verbose_printf (", timed-out; terminated\n");
1208                 return -1;
1209             }
1210     }
1211 }
1212
1213
1214 static void
1215 alrmser (int i)
1216 {
1217 #ifndef RELIABLE_SIGNALS
1218     SIGNAL (SIGALRM, alrmser);
1219 #endif
1220
1221     longjmp (myctx, DONE);
1222 }
1223
1224
1225 /*
1226  * Get the `sender' from the envelope
1227  * information ("From " line).
1228  */
1229
1230 static void
1231 get_sender (char *envelope, char **sender)
1232 {
1233     int i;
1234     unsigned char *cp;
1235     unsigned char buffer[BUFSIZ];
1236
1237     if (envelope == NULL) {
1238         *sender = getcpy ("");
1239         return;
1240     }
1241
1242     i = strlen ("From ");
1243     strncpy (buffer, envelope + i, sizeof(buffer));
1244     if ((cp = strchr(buffer, '\n'))) {
1245         *cp = 0;
1246         cp -= 24;
1247         if (cp < buffer)
1248             cp = buffer;
1249     } else {
1250         cp = buffer;
1251     }
1252     *cp = 0;
1253
1254     for (cp = buffer + strlen (buffer) - 1; cp >= buffer; cp--)
1255         if (isspace (*cp))
1256             *cp = 0;
1257         else
1258             break;
1259     *sender = getcpy (buffer);
1260 }
1261
1262
1263 /*
1264  * Copy message into a temporary file.
1265  * While copying, it will do some header processing
1266  * including the extraction of the envelope information.
1267  */
1268
1269 static int
1270 copy_message (int qd, char *tmpfil, int fold)
1271 {
1272     int i, first = 1, fd1, fd2;
1273     char buffer[BUFSIZ];
1274     FILE *qfp, *ffp;
1275     char *tfile = NULL;
1276
1277     tfile = m_mktemp2(NULL, invo_name, &fd1, NULL);
1278     if (tfile == NULL) return -1;
1279     fchmod(fd1, 0600);
1280     strncpy (tmpfil, tfile, BUFSIZ);
1281
1282     if (!fold) {
1283         while ((i = read (qd, buffer, sizeof(buffer))) > 0)
1284             if (write (fd1, buffer, i) != i) {
1285 you_lose:
1286                 close (fd1);
1287                 unlink (tmpfil);
1288                 return -1;
1289             }
1290         if (i == -1)
1291             goto you_lose;
1292         lseek (fd1, (off_t) 0, SEEK_SET);
1293         return fd1;
1294     }
1295
1296     /* dup the fd for incoming message */
1297     if ((fd2 = dup (qd)) == -1) {
1298         close (fd1);
1299         return -1;
1300     }
1301
1302     /* now create a FILE pointer for it */
1303     if ((qfp = fdopen (fd2, "r")) == NULL) {
1304         close (fd1);
1305         close (fd2);
1306         return -1;
1307     }
1308
1309     /* dup the fd for temporary file */
1310     if ((fd2 = dup (fd1)) == -1) {
1311         close (fd1);
1312         fclose (qfp);
1313         return -1;
1314     }
1315
1316     /* now create a FILE pointer for it */
1317     if ((ffp = fdopen (fd2, "r+")) == NULL) {
1318         close (fd1);
1319         close (fd2);
1320         fclose (qfp);
1321         return -1;
1322     }
1323
1324     /*
1325      * copy message into temporary file
1326      * and massage the headers.  Save
1327      * a copy of the "From " line for later.
1328      */
1329     i = strlen ("From ");
1330     while (fgets (buffer, sizeof(buffer), qfp)) {
1331         if (first) {
1332             first = 0;
1333             if (!strncmp (buffer, "From ", i)) {
1334                 /* get copy of envelope information ("From " line) */
1335                 envelope = getcpy (buffer);
1336
1337 #if 0
1338                 /* First go ahead and put "From " line in message */
1339                 fputs (buffer, ffp);
1340                 if (ferror (ffp))
1341                     goto fputs_error;
1342 #endif
1343
1344                 /* Put the delivery date in message */
1345                 fputs (ddate, ffp);
1346                 if (ferror (ffp))
1347                     goto fputs_error;
1348
1349                 continue;
1350             }
1351         }
1352
1353         fputs (buffer, ffp);
1354         if (ferror (ffp))
1355             goto fputs_error;
1356     }
1357
1358     fclose (ffp);
1359     if (ferror (qfp)) {
1360         close (fd1);
1361         fclose (qfp);
1362         return -1;
1363     }
1364     fclose (qfp);
1365     lseek (fd1, (off_t) 0, SEEK_SET);
1366     return fd1;
1367
1368
1369 fputs_error:
1370     close (fd1);
1371     fclose (ffp);
1372     fclose (qfp);
1373     return -1;
1374 }
1375
1376 /*
1377  * Trim strings for pretty printing of debugging output
1378  */
1379
1380 static char *
1381 trim (char *cp)
1382 {
1383     char buffer[BUFSIZ*4];
1384     unsigned char *bp, *sp;
1385
1386     if (cp == NULL)
1387         return NULL;
1388
1389     /* copy string into temp buffer */
1390     strncpy (buffer, cp, sizeof(buffer));
1391     bp = buffer;
1392
1393     /* skip over leading whitespace */
1394     while (isspace(*bp))
1395         bp++;
1396
1397     /* start at the end and zap trailing whitespace */
1398     for (sp = bp + strlen(bp) - 1; sp >= bp; sp--) {
1399         if (isspace(*sp))
1400             *sp = 0;
1401         else
1402             break;
1403     }
1404
1405     /* replace remaining whitespace with spaces */
1406     for (sp = bp; *sp; sp++)
1407         if (isspace(*sp))
1408             *sp = ' ';
1409
1410     /* now return a copy */
1411     return getcpy(bp);
1412 }
1413
1414 /*
1415  * Function for printing `verbose' messages.
1416  */
1417
1418 static void
1419 verbose_printf (char *fmt, ...)
1420 {
1421     va_list ap;
1422
1423     va_start(ap, fmt);
1424     vfprintf (stdout, fmt, ap);
1425     va_end(ap);
1426
1427     fflush (stdout);    /* now flush output */
1428 }
1429
1430
1431 /*
1432  * Function for printing `verbose' delivery
1433  * error messages.
1434  */
1435
1436 static void
1437 adorn (char *what, char *fmt, ...)
1438 {
1439     va_list ap;
1440     int eindex;
1441     char *s;
1442
1443     eindex = errno;     /* save the errno */
1444     fprintf (stdout, ", ");
1445
1446     va_start(ap, fmt);
1447     vfprintf (stdout, fmt, ap);
1448     va_end(ap);
1449
1450     if (what) {
1451         if (*what)
1452             fprintf (stdout, " %s: ", what);
1453         if ((s = strerror (eindex)))
1454             fprintf (stdout, "%s", s);
1455         else
1456             fprintf (stdout, "Error %d", eindex);
1457     }
1458
1459     fputc ('\n', stdout);
1460     fflush (stdout);
1461 }
1462
1463
1464 /*
1465  * Function for printing `debug' messages.
1466  */
1467
1468 static void
1469 debug_printf (char *fmt, ...)
1470 {
1471     va_list ap;
1472
1473     va_start(ap, fmt);
1474     vfprintf (stderr, fmt, ap);
1475     va_end(ap);
1476 }
1477
1478
1479 /*
1480  * Check ndbm/db file(s) to see if the Message-Id of this
1481  * message matches the Message-Id of a previous message,
1482  * so we can discard it.  If it doesn't match, we add the
1483  * Message-Id of this message to the ndbm/db file.
1484  */
1485 static int
1486 suppress_duplicates (int fd, char *file)
1487 {
1488     int fd1, lockfd, state, result;
1489     char *cp, buf[BUFSIZ], name[NAMESZ];
1490     datum key, value;
1491     DBM *db;
1492     FILE *in;
1493
1494     if ((fd1 = dup (fd)) == -1)
1495         return -1;
1496     if (!(in = fdopen (fd1, "r"))) {
1497         close (fd1);
1498         return -1;
1499     }
1500     rewind (in);
1501
1502     for (state = FLD;;) {
1503         state = m_getfld (state, name, buf, sizeof(buf), in);
1504         switch (state) {
1505             case FLD:
1506             case FLDPLUS:
1507             case FLDEOF:
1508                 /* Search for the message ID */
1509                 if (mh_strcasecmp (name, "Message-ID")) {
1510                     while (state == FLDPLUS)
1511                         state = m_getfld (state, name, buf, sizeof(buf), in);
1512                     continue;
1513                 }
1514
1515                 cp = add (buf, NULL);
1516                 while (state == FLDPLUS) {
1517                     state = m_getfld (state, name, buf, sizeof(buf), in);
1518                     cp = add (buf, cp);
1519                 }
1520                 key.dptr = trimcpy (cp);
1521                 key.dsize = strlen (key.dptr) + 1;
1522                 free (cp);
1523                 cp = key.dptr;
1524
1525                 if (!(db = dbm_open (file, O_RDWR | O_CREAT, 0600))) {
1526                     advise (file, "unable to perform dbm_open on");
1527                     free (cp);
1528                     fclose (in);
1529                     return -1;
1530                 }
1531                 /*
1532                  * Since it is difficult to portable lock a ndbm file,
1533                  * we will open and lock the Maildelivery file instead.
1534                  * This will fail if your Maildelivery file doesn't
1535                  * exist.
1536                  */
1537                 if ((lockfd = lkopen(file, O_RDWR, 0)) == -1) {
1538                     advise (file, "unable to perform file locking on");
1539                     free (cp);
1540                     fclose (in);
1541                     return -1;
1542                 }
1543                 value = dbm_fetch (db, key);
1544                 if (value.dptr) {
1545                     if (verbose)
1546                         verbose_printf ("Message-ID: %s\n            already received on %s",
1547                                  cp, value.dptr);
1548                     result = DONE;
1549                 } else {
1550                     value.dptr  = ddate + sizeof("Delivery-Date:");
1551                     value.dsize = strlen(value.dptr) + 1;
1552                     if (dbm_store (db, key, value, DBM_INSERT))
1553                         advise (file, "possibly corrupt file");
1554                     result = 0;
1555                 }
1556
1557                 dbm_close (db);
1558                 lkclose(lockfd, file);
1559                 free (cp);
1560                 fclose (in);
1561                 return result;
1562                 break;
1563
1564            case BODY:
1565            case BODYEOF:
1566            case FILEEOF:
1567                 break;
1568
1569            case LENERR:
1570            case FMTERR:
1571            default:
1572                 break;
1573         }
1574
1575         break;
1576     }
1577
1578     fclose (in);
1579     return 0;
1580 }