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