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