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