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