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