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