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