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