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