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