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