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