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