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