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