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