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