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