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