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