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