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