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