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