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