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