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