]> diplodocus.org Git - nmh/blob - uip/slocal.c
add rmf(1) and folder(1) to one another's SEE ALSO sections
[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 chdir ("/");
283 umask (0077);
284
285 if (geteuid() == 0) {
286 if (setgid (pw->pw_gid) != 0) {
287 adios ("setgid", "unable to set group to %ld", (long) pw->pw_gid);
288 }
289 initgroups (pw->pw_name, pw->pw_gid);
290 if (setuid (pw->pw_uid) != 0) {
291 adios ("setuid", "unable to set user to %ld", (long) pw->pw_uid);
292 }
293 }
294
295 if (info == NULL)
296 info = "";
297
298 setbuf (stdin, NULL);
299
300 /* Record the delivery time */
301 if ((now = dlocaltimenow ()) == NULL)
302 adios (NULL, "unable to ascertain local time");
303 snprintf (ddate, sizeof(ddate), "Delivery-Date: %s\n", dtimenow (0));
304
305 /*
306 * Copy the message to a temporary file
307 */
308 if (file) {
309 int tempfd;
310
311 /* getting message from file */
312 if ((tempfd = open (file, O_RDONLY)) == -1)
313 adios (file, "unable to open");
314 if (debug)
315 debug_printf ("retrieving message from file \"%s\"\n", file);
316 if ((fd = copy_message (tempfd, tmpfil, 1)) == -1)
317 adios(NULL, "unable to create temporary file in %s",
318 get_temp_dir());
319 close (tempfd);
320 } else {
321 /* getting message from stdin */
322 if (debug)
323 debug_printf ("retrieving message from stdin\n");
324 if ((fd = copy_message (fileno (stdin), tmpfil, 1)) == -1)
325 adios(NULL, "unable to create temporary file in %s",
326 get_temp_dir());
327 }
328
329 if (debug)
330 debug_printf ("temporary file=\"%s\"\n", tmpfil);
331
332 /* Delete the temp file now or a copy of every single message passed through
333 slocal will be left in the /tmp directory until deleted manually! This
334 unlink() used to be under an 'else' of the 'if (debug)' above, but since
335 some people like to always run slocal with -debug and log the results,
336 the /tmp directory would get choked over time. Of course, now that we
337 always delete the temp file, the "temporary file=" message above is
338 somewhat pointless -- someone watching debug output wouldn't have a
339 chance to 'tail -f' or 'ln' the temp file before it's unlinked. The best
340 thing would be to delay this unlink() until later if debug == 1, but I'll
341 leave that for someone who cares about the temp-file-accessing
342 functionality (they'll have to watch out for cases where we adios()). */
343 (void) m_unlink (tmpfil);
344
345 if (!(fp = fdopen (fd, "r+")))
346 adios (NULL, "unable to access temporary file");
347
348 /*
349 * If no sender given, extract it
350 * from envelope information. */
351 if (sender == NULL)
352 get_sender (envelope, &sender);
353
354 if (mbox == NULL) {
355 snprintf (mailbox, sizeof(mailbox), "%s/%s",
356 mmdfldir[0] ? mmdfldir : pw->pw_dir,
357 mmdflfil[0] ? mmdflfil : pw->pw_name);
358 mbox = mailbox;
359 }
360 if (home == NULL)
361 home = pw->pw_dir;
362
363 if (debug) {
364 debug_printf ("addr=\"%s\"\n", trim(addr));
365 debug_printf ("user=\"%s\"\n", trim(user));
366 debug_printf ("info=\"%s\"\n", trim(info));
367 debug_printf ("sender=\"%s\"\n", trim(sender));
368 debug_printf ("envelope=\"%s\"\n", envelope ? trim(envelope) : "");
369 debug_printf ("mbox=\"%s\"\n", trim(mbox));
370 debug_printf ("home=\"%s\"\n", trim(home));
371 debug_printf ("ddate=\"%s\"\n", trim(ddate));
372 debug_printf ("now=%02d:%02d\n\n", now->tw_hour, now->tw_min);
373 }
374
375 /* deliver the message */
376 status = localmail (fd, mdlvr);
377
378 done (status != -1 ? RCV_MOK : RCV_MBX);
379 return 1;
380 }
381
382
383 /*
384 * Main routine for delivering message.
385 */
386
387 static int
388 localmail (int fd, char *mdlvr)
389 {
390 /* check if this message is a duplicate */
391 if (suppressdup &&
392 suppress_duplicates(fd, mdlvr ? mdlvr : ".maildelivery") == DONE)
393 return 0;
394
395 /* delivery according to personal Maildelivery file */
396 if (usr_delivery (fd, mdlvr ? mdlvr : ".maildelivery", 0) != -1)
397 return 0;
398
399 /* delivery according to global Maildelivery file */
400 if (usr_delivery (fd, maildelivery, 1) != -1)
401 return 0;
402
403 if (verbose)
404 verbose_printf ("(delivering to standard mail spool)\n");
405
406 /* last resort - deliver to standard mail spool */
407 return usr_file (fd, mbox, MBOX_FORMAT);
408 }
409
410
411 #define matches(a,b) (stringdex (b, a) >= 0)
412
413 /*
414 * Parse the delivery file, and process incoming message.
415 */
416
417 static int
418 usr_delivery (int fd, char *delivery, int su)
419 {
420 int i, accept, status=1, won, vecp, next;
421 char *field, *pattern, *action, *result, *string;
422 char buffer[BUFSIZ], tmpbuf[BUFSIZ];
423 char *cp, *vec[NVEC];
424 struct stat st;
425 struct pair *p;
426 FILE *fp;
427
428 /* open the delivery file */
429 if ((fp = fopen (delivery, "r")) == NULL)
430 return -1;
431
432 /* check if delivery file has bad ownership or permissions */
433 if (fstat (fileno (fp), &st) == -1
434 || (st.st_uid != 0 && (su || st.st_uid != pw->pw_uid))
435 || st.st_mode & (S_IWGRP|S_IWOTH)) {
436 if (verbose) {
437 verbose_printf ("WARNING: %s has bad ownership/modes (su=%d,uid=%d,owner=%d,mode=0%o)\n",
438 delivery, su, (int) pw->pw_uid, (int) st.st_uid, (int) st.st_mode);
439 }
440 return -1;
441 }
442
443 won = 0;
444 next = 1;
445
446 /* read and process delivery file */
447 while (fgets (buffer, sizeof(buffer), fp)) {
448 /* skip comments and empty lines */
449 if (*buffer == '#' || *buffer == '\n')
450 continue;
451
452 /* zap trailing newline */
453 if ((cp = strchr(buffer, '\n')))
454 *cp = 0;
455
456 /* split buffer into fields */
457 vecp = split (buffer, vec);
458
459 /* check for too few fields */
460 if (vecp < 5) {
461 if (debug)
462 debug_printf ("WARNING: entry with only %d fields, skipping.\n", vecp);
463 continue;
464 }
465
466 if (debug) {
467 for (i = 0; vec[i]; i++)
468 debug_printf ("vec[%d]: \"%s\"\n", i, trim(vec[i]));
469 }
470
471 field = vec[0];
472 pattern = vec[1];
473 action = vec[2];
474 result = vec[3];
475 string = vec[4];
476
477 /* find out how to perform the action */
478 switch (result[0]) {
479 case 'N':
480 case 'n':
481 /*
482 * If previous condition failed, don't
483 * do this - else fall through
484 */
485 if (!next)
486 continue; /* else fall */
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; /* else fall */
495
496 case 'A':
497 case 'a':
498 /*
499 * Take action, and consider delivered if
500 * action is successful.
501 */
502 accept = 1;
503 break;
504
505 case 'R':
506 case 'r':
507 default:
508 /*
509 * Take action, but don't consider delivered, even
510 * if action is successful
511 */
512 accept = 0;
513 break;
514 }
515
516 if (vecp > 5) {
517 if (!strcasecmp (vec[5], "select")) {
518 if (logged_in () != -1)
519 continue;
520 if (vecp > 7 && timely (vec[6], vec[7]) == -1)
521 continue;
522 }
523 }
524
525 /* check if the field matches */
526 switch (*field) {
527 case '*':
528 /* always matches */
529 break;
530
531 case 'd':
532 /*
533 * "default" matches only if the message hasn't
534 * been delivered yet.
535 */
536 if (!strcasecmp (field, "default")) {
537 if (won)
538 continue;
539 break;
540 } /* else fall */
541
542 default:
543 /* parse message and build lookup table */
544 if (!parsed && parse (fd) == -1) {
545 fclose (fp);
546 return -1;
547 }
548 /*
549 * find header field in lookup table, and
550 * see if the pattern matches.
551 */
552 if ((p = lookup (hdrs, field)) && (p->p_value != NULL)
553 && matches (p->p_value, pattern)) {
554 next = 1;
555 } else {
556 next = 0;
557 continue;
558 }
559 break;
560 }
561
562 /* find out the action to perform */
563 switch (*action) {
564 case 'q':
565 /* deliver to quoted pipe */
566 if (strcasecmp (action, "qpipe"))
567 continue; /* else fall */
568 case '^':
569 expand (tmpbuf, string, fd);
570 if (split (tmpbuf, vec) < 1)
571 continue;
572 status = usr_pipe (fd, tmpbuf, vec[0], vec, 0);
573 break;
574
575 case 'p':
576 /* deliver to pipe */
577 if (strcasecmp (action, "pipe"))
578 continue; /* else fall */
579 case '|':
580 vec[2] = "sh";
581 vec[3] = "-c";
582 expand (tmpbuf, string, fd);
583 vec[4] = tmpbuf;
584 vec[5] = NULL;
585 status = usr_pipe (fd, tmpbuf, "/bin/sh", vec + 2, 0);
586 break;
587
588 case 'f':
589 /* mbox format */
590 if (!strcasecmp (action, "file")) {
591 status = usr_file (fd, string, MBOX_FORMAT);
592 break;
593 }
594 /* deliver to nmh folder */
595 else if (strcasecmp (action, "folder"))
596 continue; /* else fall */
597 case '+':
598 status = usr_folder (fd, string);
599 break;
600
601 case 'm':
602 /* mmdf format */
603 if (!strcasecmp (action, "mmdf")) {
604 status = usr_file (fd, string, MMDF_FORMAT);
605 break;
606 }
607 /* mbox format */
608 else if (strcasecmp (action, "mbox"))
609 continue; /* else fall */
610
611 case '>':
612 /* mbox format */
613 status = usr_file (fd, string, MBOX_FORMAT);
614 break;
615
616 case 'd':
617 /* ignore message */
618 if (strcasecmp (action, "destroy"))
619 continue;
620 status = 0;
621 break;
622 }
623
624 if (status) next = 0; /* action failed, mark for 'N' result */
625
626 if (accept && status == 0)
627 won++;
628 }
629
630 fclose (fp);
631 return (won ? 0 : -1);
632 }
633
634
635 #define QUOTE '\\'
636
637 /*
638 * Split buffer into fields (delimited by whitespace or
639 * comma's). Return the number of fields found.
640 */
641
642 static int
643 split (char *cp, char **vec)
644 {
645 int i;
646 char *s;
647
648 s = cp;
649
650 /* split into a maximum of NVEC fields */
651 for (i = 0; i <= NVEC;) {
652 vec[i] = NULL;
653
654 /* zap any whitespace and comma's */
655 while (isspace ((unsigned char) *s) || *s == ',')
656 *s++ = 0;
657
658 /* end of buffer, time to leave */
659 if (*s == 0)
660 break;
661
662 /* get double quote text as a single field */
663 if (*s == '"') {
664 for (vec[i++] = ++s; *s && *s != '"'; s++) {
665 /*
666 * Check for escaped double quote. We need
667 * to shift the string to remove slash.
668 */
669 if (*s == QUOTE) {
670 if (*++s == '"')
671 strcpy (s - 1, s);
672 s--;
673 }
674 }
675 if (*s == '"') /* zap trailing double quote */
676 *s++ = 0;
677 continue;
678 }
679
680 if (*s == QUOTE && *++s != '"')
681 s--;
682 vec[i++] = s++;
683
684 /* move forward to next field delimiter */
685 while (*s && !isspace ((unsigned char) *s) && *s != ',')
686 s++;
687 }
688 vec[i] = NULL;
689
690 return i;
691 }
692
693
694 /*
695 * Parse the headers of a message, and build the
696 * lookup table for matching fields and patterns.
697 */
698
699 static int
700 parse (int fd)
701 {
702 int i, state;
703 int fd1;
704 char *cp, *dp, *lp;
705 char name[NAMESZ], field[BUFSIZ];
706 struct pair *p, *q;
707 FILE *in;
708 m_getfld_state_t gstate = 0;
709
710 if (parsed++)
711 return 0;
712
713 /* get a new FILE pointer to message */
714 if ((fd1 = dup (fd)) == -1)
715 return -1;
716 if ((in = fdopen (fd1, "r")) == NULL) {
717 close (fd1);
718 return -1;
719 }
720 rewind (in);
721
722 /* add special entries to lookup table */
723 if ((p = lookup (hdrs, "source")))
724 p->p_value = getcpy (sender);
725 if ((p = lookup (hdrs, "addr")))
726 p->p_value = getcpy (addr);
727
728 /*
729 * Scan the headers of the message and build
730 * a lookup table.
731 */
732 for (i = 0;;) {
733 int fieldsz = sizeof field;
734 switch (state = m_getfld (&gstate, name, field, &fieldsz, in)) {
735 case FLD:
736 case FLDPLUS:
737 lp = add (field, NULL);
738 while (state == FLDPLUS) {
739 fieldsz = sizeof field;
740 state = m_getfld (&gstate, name, field, &fieldsz, in);
741 lp = add (field, lp);
742 }
743 for (p = hdrs; p->p_name; p++) {
744 if (!strcasecmp (p->p_name, name)) {
745 if (!(p->p_flags & P_HID)) {
746 if ((cp = p->p_value)) {
747 if (p->p_flags & P_ADR) {
748 dp = cp + strlen (cp) - 1;
749 if (*dp == '\n')
750 *dp = 0;
751 cp = add (",\n\t", cp);
752 } else {
753 cp = add ("\t", cp);
754 }
755 }
756 p->p_value = add (lp, cp);
757 }
758 free (lp);
759 break;
760 }
761 }
762 if (p->p_name == NULL && i < NVEC) {
763 p->p_name = getcpy (name);
764 p->p_value = lp;
765 p->p_flags = P_NIL;
766 p++, i++;
767 p->p_name = NULL;
768 }
769 continue;
770
771 case BODY:
772 case FILEEOF:
773 break;
774
775 case LENERR:
776 case FMTERR:
777 advise (NULL, "format error in message");
778 break;
779
780 default:
781 advise (NULL, "internal error in m_getfld");
782 fclose (in);
783 return -1;
784 }
785 break;
786 }
787 m_getfld_state_destroy (&gstate);
788 fclose (in);
789
790 if ((p = lookup (vars, "reply-to"))) {
791 if ((q = lookup (hdrs, "reply-to")) == NULL || q->p_value == NULL)
792 q = lookup (hdrs, "from");
793 p->p_value = getcpy (q ? q->p_value : "");
794 p->p_flags &= ~P_CHK;
795 if (debug)
796 debug_printf ("vars[%d]: name=\"%s\" value=\"%s\"\n",
797 p - vars, p->p_name, trim(p->p_value));
798 }
799 if (debug) {
800 for (p = hdrs; p->p_name; p++)
801 debug_printf ("hdrs[%d]: name=\"%s\" value=\"%s\"\n",
802 p - hdrs, p->p_name, p->p_value ? trim(p->p_value) : "");
803 }
804
805 return 0;
806 }
807
808
809 #define LPAREN '('
810 #define RPAREN ')'
811
812 /*
813 * Expand any builtin variables such as $(sender),
814 * $(address), etc., in a string.
815 */
816
817 static void
818 expand (char *s1, char *s2, int fd)
819 {
820 char c, *cp;
821 struct pair *p;
822
823 if (!globbed)
824 glob (fd);
825
826 while ((c = *s2++)) {
827 if (c != '$' || *s2 != LPAREN) {
828 *s1++ = c;
829 } else {
830 for (cp = ++s2; *s2 && *s2 != RPAREN; s2++)
831 continue;
832 if (*s2 != RPAREN) {
833 s2 = --cp;
834 continue;
835 }
836 *s2++ = 0;
837 if ((p = lookup (vars, cp))) {
838 if (!parsed && (p->p_flags & P_CHK))
839 parse (fd);
840
841 strcpy (s1, p->p_value);
842 s1 += strlen (s1);
843 }
844 }
845 }
846 *s1 = 0;
847 }
848
849
850 /*
851 * Fill in the information missing from the "vars"
852 * table, which is necessary to expand any builtin
853 * variables in the string for a "pipe" or "qpipe"
854 * action.
855 */
856
857 static void
858 glob (int fd)
859 {
860 char buffer[BUFSIZ];
861 struct stat st;
862 struct pair *p;
863
864 if (globbed++)
865 return;
866
867 if ((p = lookup (vars, "sender")))
868 p->p_value = getcpy (sender);
869 if ((p = lookup (vars, "address")))
870 p->p_value = getcpy (addr);
871 if ((p = lookup (vars, "size"))) {
872 snprintf (buffer, sizeof(buffer), "%d",
873 fstat (fd, &st) != -1 ? (int) st.st_size : 0);
874 p->p_value = getcpy (buffer);
875 }
876 if ((p = lookup (vars, "info")))
877 p->p_value = getcpy (info);
878
879 if (debug) {
880 for (p = vars; p->p_name; p++)
881 debug_printf ("vars[%d]: name=\"%s\" value=\"%s\"\n",
882 p - vars, p->p_name, trim(p->p_value));
883 }
884 }
885
886
887 /*
888 * Find a matching name in a lookup table. If found,
889 * return the "pairs" entry, else return NULL.
890 */
891
892 static struct pair *
893 lookup (struct pair *pairs, char *key)
894 {
895 for (; pairs->p_name; pairs++)
896 if (!strcasecmp (pairs->p_name, key))
897 return pairs;
898
899 return NULL;
900 }
901
902
903 /*
904 * Check utmp(x) file to see if user is currently
905 * logged in.
906 */
907
908 static int
909 logged_in (void)
910 {
911 #if HAVE_GETUTXENT
912 struct utmpx *utp;
913
914 if (utmped)
915 return utmped;
916
917 setutxent();
918
919 while ((utp = getutxent()) != NULL) {
920 if ( utp->ut_type == USER_PROCESS && utp->ut_user[0] != 0
921 && strncmp (user, utp->ut_user, sizeof(utp->ut_user)) == 0) {
922 if (debug)
923 continue;
924 endutxent();
925 return (utmped = DONE);
926 }
927 }
928
929 endutxent();
930 #endif /* HAVE_GETUTXENT */
931 return (utmped = NOTOK);
932 }
933
934 #define check(t,a,b) if (t < a || t > b) return -1
935 #define cmpar(h1,m1,h2,m2) if (h1 < h2 || (h1 == h2 && m1 < m2)) return 0
936
937 static int
938 timely (char *t1, char *t2)
939 {
940 int t1hours, t1mins, t2hours, t2mins;
941
942 if (sscanf (t1, "%d:%d", &t1hours, &t1mins) != 2)
943 return -1;
944 check (t1hours, 0, 23);
945 check (t1mins, 0, 59);
946
947 if (sscanf (t2, "%d:%d", &t2hours, &t2mins) != 2)
948 return -1;
949 check (t2hours, 0, 23);
950 check (t2mins, 0, 59);
951
952 cmpar (now->tw_hour, now->tw_min, t1hours, t1mins);
953 cmpar (t2hours, t2mins, now->tw_hour, now->tw_min);
954
955 return -1;
956 }
957
958
959 /*
960 * Deliver message by appending to a file.
961 */
962
963 static int
964 usr_file (int fd, char *mailbox, int mbx_style)
965 {
966 int md, mapping;
967
968 if (verbose)
969 verbose_printf ("delivering to file \"%s\"", mailbox);
970
971 if (mbx_style == MBOX_FORMAT) {
972 if (verbose)
973 verbose_printf (" (mbox style)");
974 mapping = 0;
975 } else {
976 if (verbose)
977 verbose_printf (" (mmdf style)");
978 mapping = 1;
979 }
980
981 /* open and lock the file */
982 if ((md = mbx_open (mailbox, mbx_style, pw->pw_uid, pw->pw_gid, m_gmprot())) == -1) {
983 if (verbose)
984 adorn ("", "unable to open:");
985 return -1;
986 }
987
988 lseek (fd, (off_t) 0, SEEK_SET);
989
990 /* append message to file */
991 if (mbx_copy (mailbox, mbx_style, md, fd, mapping, NULL, verbose) == -1) {
992 if (verbose)
993 adorn ("", "error writing to:");
994 return -1;
995 }
996
997 /* close and unlock file */
998 if (mbx_close (mailbox, md) == NOTOK) {
999 if (verbose)
1000 adorn ("", "error closing:");
1001 return -1;
1002 }
1003
1004 if (verbose)
1005 verbose_printf (", success.\n");
1006 return 0;
1007 }
1008
1009
1010 /*
1011 * Deliver message to a nmh folder.
1012 */
1013
1014 static int
1015 usr_folder (int fd, char *string)
1016 {
1017 int status;
1018 char folder[BUFSIZ], *vec[3];
1019
1020 /* get folder name ready */
1021 if (*string == '+')
1022 strncpy(folder, string, sizeof(folder));
1023 else
1024 snprintf(folder, sizeof(folder), "+%s", string);
1025
1026 if (verbose)
1027 verbose_printf ("delivering to folder \"%s\"", folder + 1);
1028
1029 vec[0] = "rcvstore";
1030 vec[1] = folder;
1031 vec[2] = NULL;
1032
1033 /* use rcvstore to put message in folder */
1034 status = usr_pipe (fd, "rcvstore", rcvstoreproc, vec, 1);
1035
1036 return status;
1037 }
1038
1039 /*
1040 * Deliver message to a process.
1041 */
1042
1043 static int
1044 usr_pipe (int fd_arg, char *cmd, char *pgm, char **vec, int suppress)
1045 {
1046 volatile int fd = fd_arg;
1047 pid_t child_id;
1048 int i, bytes, seconds, status;
1049 struct stat st;
1050
1051 if (verbose && !suppress)
1052 verbose_printf ("delivering to pipe \"%s\"", cmd);
1053
1054 lseek (fd, (off_t) 0, SEEK_SET);
1055
1056 for (i = 0; (child_id = fork()) == -1 && i < 5; i++)
1057 sleep (5);
1058
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 freopen ("/dev/null", "w", stdout);
1071 freopen ("/dev/null", "w", stderr);
1072 if (fd != 3)
1073 dup2 (fd, 3);
1074 closefds (4);
1075
1076 #ifdef TIOCNOTTY
1077 if ((fd = open ("/dev/tty", O_RDWR)) != -1) {
1078 ioctl (fd, TIOCNOTTY, NULL);
1079 close (fd);
1080 }
1081 #endif /* TIOCNOTTY */
1082
1083 setpgid ((pid_t) 0, getpid ()); /* put in own process group */
1084
1085 *environ = NULL;
1086 m_putenv ("USER", pw->pw_name);
1087 m_putenv ("HOME", pw->pw_dir);
1088 m_putenv ("SHELL", pw->pw_shell);
1089
1090 execvp (pgm, vec);
1091 _exit (-1);
1092
1093 default:
1094 /* parent process */
1095 if (! setjmp (myctx)) {
1096 SIGNAL (SIGALRM, alrmser);
1097 bytes = fstat (fd, &st) != -1 ? (int) st.st_size : 100;
1098
1099 /* amount of time to wait depends on message size */
1100 if (bytes <= 100) {
1101 /* give at least 5 minutes */
1102 seconds = 300;
1103 } else if (bytes >= 90000) {
1104 /* a half hour is long enough */
1105 seconds = 1800;
1106 } else {
1107 seconds = (bytes / 60) + 300;
1108 }
1109 alarm ((unsigned int) seconds);
1110 status = pidwait (child_id, 0);
1111 alarm (0);
1112
1113 if (verbose) {
1114 if (status == 0)
1115 verbose_printf (", success.\n");
1116 else
1117 if ((status & 0xff00) == 0xff00)
1118 verbose_printf (", system error\n");
1119 else
1120 pidstatus (status, stdout, ", failed");
1121 }
1122 return (status == 0 ? 0 : -1);
1123 } else {
1124 /*
1125 * Ruthlessly kill the child and anything
1126 * else in its process group.
1127 */
1128 killpg(child_id, SIGKILL);
1129 if (verbose)
1130 verbose_printf (", timed-out; terminated\n");
1131 return -1;
1132 }
1133 }
1134 }
1135
1136
1137 static void
1138 alrmser (int i)
1139 {
1140 NMH_UNUSED (i);
1141
1142 longjmp (myctx, DONE);
1143 }
1144
1145
1146 /*
1147 * Get the `sender' from the envelope
1148 * information ("From " line).
1149 */
1150
1151 static void
1152 get_sender (char *envelope, char **sender)
1153 {
1154 int i;
1155 char *cp;
1156 char buffer[BUFSIZ];
1157
1158 if (envelope == NULL) {
1159 *sender = getcpy ("");
1160 return;
1161 }
1162
1163 i = strlen ("From ");
1164 strncpy (buffer, envelope + i, sizeof(buffer));
1165 if ((cp = strchr(buffer, '\n'))) {
1166 *cp = 0;
1167 cp -= 24;
1168 if (cp < buffer)
1169 cp = buffer;
1170 } else {
1171 cp = buffer;
1172 }
1173 *cp = 0;
1174
1175 for (cp = buffer + strlen (buffer) - 1; cp >= buffer; cp--)
1176 if (isspace ((unsigned char) *cp))
1177 *cp = 0;
1178 else
1179 break;
1180 *sender = getcpy (buffer);
1181 }
1182
1183
1184 /*
1185 * Copy message into a temporary file.
1186 * While copying, it will do some header processing
1187 * including the extraction of the envelope information.
1188 */
1189
1190 static int
1191 copy_message (int qd, char *tmpfil, int fold)
1192 {
1193 int i, first = 1, fd1, fd2;
1194 char buffer[BUFSIZ];
1195 FILE *qfp, *ffp;
1196 char *tfile = NULL;
1197
1198 tfile = m_mktemp2(NULL, invo_name, &fd1, NULL);
1199 if (tfile == NULL) return -1;
1200 strncpy (tmpfil, tfile, BUFSIZ);
1201
1202 if (!fold) {
1203 while ((i = read (qd, buffer, sizeof(buffer))) > 0)
1204 if (write (fd1, buffer, i) != i) {
1205 you_lose:
1206 close (fd1);
1207 (void) m_unlink (tmpfil);
1208 return -1;
1209 }
1210 if (i == -1)
1211 goto you_lose;
1212 lseek (fd1, (off_t) 0, SEEK_SET);
1213 return fd1;
1214 }
1215
1216 /* dup the fd for incoming message */
1217 if ((fd2 = dup (qd)) == -1) {
1218 close (fd1);
1219 return -1;
1220 }
1221
1222 /* now create a FILE pointer for it */
1223 if ((qfp = fdopen (fd2, "r")) == NULL) {
1224 close (fd1);
1225 close (fd2);
1226 return -1;
1227 }
1228
1229 /* dup the fd for temporary file */
1230 if ((fd2 = dup (fd1)) == -1) {
1231 close (fd1);
1232 fclose (qfp);
1233 return -1;
1234 }
1235
1236 /* now create a FILE pointer for it */
1237 if ((ffp = fdopen (fd2, "r+")) == NULL) {
1238 close (fd1);
1239 close (fd2);
1240 fclose (qfp);
1241 return -1;
1242 }
1243
1244 /*
1245 * copy message into temporary file
1246 * and massage the headers. Save
1247 * a copy of the "From " line for later.
1248 */
1249 i = strlen ("From ");
1250 while (fgets (buffer, sizeof(buffer), qfp)) {
1251 if (first) {
1252 first = 0;
1253 if (!strncmp (buffer, "From ", i)) {
1254 /* get copy of envelope information ("From " line) */
1255 envelope = getcpy (buffer);
1256
1257 /* Put the delivery date in message */
1258 fputs (ddate, ffp);
1259 if (ferror (ffp))
1260 goto fputs_error;
1261
1262 continue;
1263 }
1264 }
1265
1266 fputs (buffer, ffp);
1267 if (ferror (ffp))
1268 goto fputs_error;
1269 }
1270
1271 fclose (ffp);
1272 if (ferror (qfp)) {
1273 close (fd1);
1274 fclose (qfp);
1275 return -1;
1276 }
1277 fclose (qfp);
1278 lseek (fd1, (off_t) 0, SEEK_SET);
1279 return fd1;
1280
1281
1282 fputs_error:
1283 close (fd1);
1284 fclose (ffp);
1285 fclose (qfp);
1286 return -1;
1287 }
1288
1289 /*
1290 * Trim strings for pretty printing of debugging output
1291 */
1292
1293 static char *
1294 trim (char *cp)
1295 {
1296 char buffer[BUFSIZ*4];
1297 char *bp, *sp;
1298
1299 if (cp == NULL)
1300 return NULL;
1301
1302 /* copy string into temp buffer */
1303 strncpy (buffer, cp, sizeof(buffer));
1304 bp = buffer;
1305
1306 /* skip over leading whitespace */
1307 while (isspace((unsigned char) *bp))
1308 bp++;
1309
1310 /* start at the end and zap trailing whitespace */
1311 for (sp = bp + strlen(bp) - 1; sp >= bp; sp--) {
1312 if (isspace((unsigned char) *sp))
1313 *sp = 0;
1314 else
1315 break;
1316 }
1317
1318 /* replace remaining whitespace with spaces */
1319 for (sp = bp; *sp; sp++)
1320 if (isspace((unsigned char) *sp))
1321 *sp = ' ';
1322
1323 /* now return a copy */
1324 return getcpy(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 vfprintf (stdout, 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 fprintf (stdout, ", ");
1358
1359 va_start(ap, fmt);
1360 vfprintf (stdout, fmt, ap);
1361 va_end(ap);
1362
1363 if (what) {
1364 if (*what)
1365 fprintf (stdout, " %s: ", what);
1366 if ((s = strerror (eindex)))
1367 fprintf (stdout, "%s", s);
1368 else
1369 fprintf (stdout, "Error %d", eindex);
1370 }
1371
1372 fputc ('\n', stdout);
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[BUFSIZ], name[NAMESZ];
1403 datum key, value;
1404 DBM *db;
1405 FILE *in;
1406 m_getfld_state_t gstate = 0;
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 for (;;) {
1417 int failed_to_lock = 0;
1418 int bufsz = sizeof buf;
1419 state = m_getfld (&gstate, name, buf, &bufsz, in);
1420 switch (state) {
1421 case FLD:
1422 case FLDPLUS:
1423 /* Search for the message ID */
1424 if (strcasecmp (name, "Message-ID")) {
1425 while (state == FLDPLUS) {
1426 bufsz = sizeof buf;
1427 state = m_getfld (&gstate, name, buf, &bufsz, in);
1428 }
1429 continue;
1430 }
1431
1432 cp = add (buf, NULL);
1433 while (state == FLDPLUS) {
1434 bufsz = sizeof buf;
1435 state = m_getfld (&gstate, name, buf, &bufsz, in);
1436 cp = add (buf, cp);
1437 }
1438 key.dptr = trimcpy (cp);
1439 key.dsize = strlen (key.dptr) + 1;
1440 free (cp);
1441 cp = key.dptr;
1442
1443 if (!(db = dbm_open (file, O_RDWR | O_CREAT, 0600))) {
1444 advise (file, "unable to perform dbm_open on");
1445 free (cp);
1446 fclose (in);
1447 return -1;
1448 }
1449 /*
1450 * Since it is difficult to portable lock a ndbm file,
1451 * we will open and lock the Maildelivery file instead.
1452 * This will fail if your Maildelivery file doesn't
1453 * exist.
1454 */
1455 if ((lockfd = lkopendata(file, O_RDWR, 0, &failed_to_lock))
1456 == -1) {
1457 advise (file, "unable to perform file locking on");
1458 free (cp);
1459 fclose (in);
1460 return -1;
1461 }
1462 value = dbm_fetch (db, key);
1463 if (value.dptr) {
1464 if (verbose)
1465 verbose_printf ("Message-ID: %s\n already received on %s",
1466 cp, value.dptr);
1467 result = DONE;
1468 } else {
1469 value.dptr = ddate + sizeof("Delivery-Date:");
1470 value.dsize = strlen(value.dptr) + 1;
1471 if (dbm_store (db, key, value, DBM_INSERT))
1472 advise (file, "possibly corrupt file");
1473 result = 0;
1474 }
1475
1476 dbm_close (db);
1477 lkclosedata(lockfd, file);
1478 free (cp);
1479 fclose (in);
1480 return result;
1481
1482 case BODY:
1483 case FILEEOF:
1484 break;
1485
1486 case LENERR:
1487 case FMTERR:
1488 default:
1489 break;
1490 }
1491
1492 break;
1493 }
1494 m_getfld_state_destroy (&gstate);
1495
1496 fclose (in);
1497 return 0;
1498 }