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