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