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