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