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