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