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