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