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