]> diplodocus.org Git - nmh/blob - uip/slocal.c
Replaced hard-coded value with MAX_DELIMITER_SIZE in m_getfld.c.
[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 m_getfld_state_t gstate;
720
721 if (parsed++)
722 return 0;
723
724 /* get a new FILE pointer to message */
725 if ((fd1 = dup (fd)) == -1)
726 return -1;
727 if ((in = fdopen (fd1, "r")) == NULL) {
728 close (fd1);
729 return -1;
730 }
731 rewind (in);
732
733 /* add special entries to lookup table */
734 if ((p = lookup (hdrs, "source")))
735 p->p_value = getcpy (sender);
736 if ((p = lookup (hdrs, "addr")))
737 p->p_value = getcpy (addr);
738
739 /*
740 * Scan the headers of the message and build
741 * a lookup table.
742 */
743 m_getfld_state_init (&gstate);
744 for (i = 0;;) {
745 int fieldsz = sizeof field;
746 switch (state = m_getfld (gstate, name, field, &fieldsz, in)) {
747 case FLD:
748 case FLDPLUS:
749 lp = add (field, NULL);
750 while (state == FLDPLUS) {
751 fieldsz = sizeof field;
752 state = m_getfld (gstate, name, field, &fieldsz, in);
753 lp = add (field, lp);
754 }
755 for (p = hdrs; p->p_name; p++) {
756 if (!mh_strcasecmp (p->p_name, name)) {
757 if (!(p->p_flags & P_HID)) {
758 if ((cp = p->p_value)) {
759 if (p->p_flags & P_ADR) {
760 dp = cp + strlen (cp) - 1;
761 if (*dp == '\n')
762 *dp = 0;
763 cp = add (",\n\t", cp);
764 } else {
765 cp = add ("\t", cp);
766 }
767 }
768 p->p_value = add (lp, cp);
769 }
770 free (lp);
771 break;
772 }
773 }
774 if (p->p_name == NULL && i < NVEC) {
775 p->p_name = getcpy (name);
776 p->p_value = lp;
777 p->p_flags = P_NIL;
778 p++, i++;
779 p->p_name = NULL;
780 }
781 continue;
782
783 case BODY:
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 m_getfld_state_destroy (&gstate);
800 fclose (in);
801
802 if ((p = lookup (vars, "reply-to"))) {
803 if ((q = lookup (hdrs, "reply-to")) == NULL || q->p_value == NULL)
804 q = lookup (hdrs, "from");
805 p->p_value = getcpy (q ? q->p_value : "");
806 p->p_flags &= ~P_CHK;
807 if (debug)
808 debug_printf ("vars[%d]: name=\"%s\" value=\"%s\"\n",
809 p - vars, p->p_name, trim(p->p_value));
810 }
811 if (debug) {
812 for (p = hdrs; p->p_name; p++)
813 debug_printf ("hdrs[%d]: name=\"%s\" value=\"%s\"\n",
814 p - hdrs, p->p_name, p->p_value ? trim(p->p_value) : "");
815 }
816
817 return 0;
818 }
819
820
821 #define LPAREN '('
822 #define RPAREN ')'
823
824 /*
825 * Expand any builtin variables such as $(sender),
826 * $(address), etc., in a string.
827 */
828
829 static void
830 expand (char *s1, char *s2, int fd)
831 {
832 char c, *cp;
833 struct pair *p;
834
835 if (!globbed)
836 glob (fd);
837
838 while ((c = *s2++)) {
839 if (c != '$' || *s2 != LPAREN) {
840 *s1++ = c;
841 } else {
842 for (cp = ++s2; *s2 && *s2 != RPAREN; s2++)
843 continue;
844 if (*s2 != RPAREN) {
845 s2 = --cp;
846 continue;
847 }
848 *s2++ = 0;
849 if ((p = lookup (vars, cp))) {
850 if (!parsed && (p->p_flags & P_CHK))
851 parse (fd);
852
853 strcpy (s1, p->p_value);
854 s1 += strlen (s1);
855 }
856 }
857 }
858 *s1 = 0;
859 }
860
861
862 /*
863 * Fill in the information missing from the "vars"
864 * table, which is necessary to expand any builtin
865 * variables in the string for a "pipe" or "qpipe"
866 * action.
867 */
868
869 static void
870 glob (int fd)
871 {
872 char buffer[BUFSIZ];
873 struct stat st;
874 struct pair *p;
875
876 if (globbed++)
877 return;
878
879 if ((p = lookup (vars, "sender")))
880 p->p_value = getcpy (sender);
881 if ((p = lookup (vars, "address")))
882 p->p_value = getcpy (addr);
883 if ((p = lookup (vars, "size"))) {
884 snprintf (buffer, sizeof(buffer), "%d",
885 fstat (fd, &st) != -1 ? (int) st.st_size : 0);
886 p->p_value = getcpy (buffer);
887 }
888 if ((p = lookup (vars, "info")))
889 p->p_value = getcpy (info);
890
891 if (debug) {
892 for (p = vars; p->p_name; p++)
893 debug_printf ("vars[%d]: name=\"%s\" value=\"%s\"\n",
894 p - vars, p->p_name, trim(p->p_value));
895 }
896 }
897
898
899 /*
900 * Find a matching name in a lookup table. If found,
901 * return the "pairs" entry, else return NULL.
902 */
903
904 static struct pair *
905 lookup (struct pair *pairs, char *key)
906 {
907 for (; pairs->p_name; pairs++)
908 if (!mh_strcasecmp (pairs->p_name, key))
909 return pairs;
910
911 return NULL;
912 }
913
914
915 /*
916 * Check utmp(x) file to see if user is currently
917 * logged in.
918 */
919
920 static int
921 logged_in (void)
922 {
923 #if HAVE_GETUTXENT
924 struct utmpx *utp;
925
926 if (utmped)
927 return utmped;
928
929 setutxent();
930
931 while ((utp = getutxent()) != NULL) {
932 if ( utp->ut_type == USER_PROCESS && utp->ut_user[0] != 0
933 && strncmp (user, utp->ut_user, sizeof(utp->ut_user)) == 0) {
934 if (debug)
935 continue;
936 endutxent();
937 return (utmped = DONE);
938 }
939 }
940
941 endutxent();
942 #endif /* HAVE_GETUTXENT */
943 return (utmped = NOTOK);
944 }
945
946 #define check(t,a,b) if (t < a || t > b) return -1
947 #define cmpar(h1,m1,h2,m2) if (h1 < h2 || (h1 == h2 && m1 < m2)) return 0
948
949 static int
950 timely (char *t1, char *t2)
951 {
952 int t1hours, t1mins, t2hours, t2mins;
953
954 if (sscanf (t1, "%d:%d", &t1hours, &t1mins) != 2)
955 return -1;
956 check (t1hours, 0, 23);
957 check (t1mins, 0, 59);
958
959 if (sscanf (t2, "%d:%d", &t2hours, &t2mins) != 2)
960 return -1;
961 check (t2hours, 0, 23);
962 check (t2mins, 0, 59);
963
964 cmpar (now->tw_hour, now->tw_min, t1hours, t1mins);
965 cmpar (t2hours, t2mins, now->tw_hour, now->tw_min);
966
967 return -1;
968 }
969
970
971 /*
972 * Deliver message by appending to a file.
973 */
974
975 static int
976 usr_file (int fd, char *mailbox, int mbx_style)
977 {
978 int md, mapping;
979
980 if (verbose)
981 verbose_printf ("delivering to file \"%s\"", mailbox);
982
983 if (mbx_style == MBOX_FORMAT) {
984 if (verbose)
985 verbose_printf (" (mbox style)");
986 mapping = 0;
987 } else {
988 if (verbose)
989 verbose_printf (" (mmdf style)");
990 mapping = 1;
991 }
992
993 /* open and lock the file */
994 if ((md = mbx_open (mailbox, mbx_style, pw->pw_uid, pw->pw_gid, m_gmprot())) == -1) {
995 if (verbose)
996 adorn ("", "unable to open:");
997 return -1;
998 }
999
1000 lseek (fd, (off_t) 0, SEEK_SET);
1001
1002 /* append message to file */
1003 if (mbx_copy (mailbox, mbx_style, md, fd, mapping, NULL, verbose) == -1) {
1004 if (verbose)
1005 adorn ("", "error writing to:");
1006 return -1;
1007 }
1008
1009 /* close and unlock file */
1010 if (mbx_close (mailbox, md) == NOTOK) {
1011 if (verbose)
1012 adorn ("", "error closing:");
1013 return -1;
1014 }
1015
1016 if (verbose)
1017 verbose_printf (", success.\n");
1018 return 0;
1019 }
1020
1021
1022 /*
1023 * Deliver message to a nmh folder.
1024 */
1025
1026 static int
1027 usr_folder (int fd, char *string)
1028 {
1029 int status;
1030 char folder[BUFSIZ], *vec[3];
1031
1032 /* get folder name ready */
1033 if (*string == '+')
1034 strncpy(folder, string, sizeof(folder));
1035 else
1036 snprintf(folder, sizeof(folder), "+%s", string);
1037
1038 if (verbose)
1039 verbose_printf ("delivering to folder \"%s\"", folder + 1);
1040
1041 vec[0] = "rcvstore";
1042 vec[1] = folder;
1043 vec[2] = NULL;
1044
1045 /* use rcvstore to put message in folder */
1046 status = usr_pipe (fd, "rcvstore", rcvstoreproc, vec, 1);
1047
1048 return status;
1049 }
1050
1051 /*
1052 * Deliver message to a process.
1053 */
1054
1055 static int
1056 usr_pipe (int fd, char *cmd, char *pgm, char **vec, int suppress)
1057 {
1058 pid_t child_id;
1059 int i, bytes, seconds, status;
1060 struct stat st;
1061
1062 if (verbose && !suppress)
1063 verbose_printf ("delivering to pipe \"%s\"", cmd);
1064
1065 lseek (fd, (off_t) 0, SEEK_SET);
1066
1067 for (i = 0; (child_id = fork()) == -1 && i < 5; i++)
1068 sleep (5);
1069
1070 switch (child_id) {
1071 case -1:
1072 /* fork error */
1073 if (verbose)
1074 adorn ("fork", "unable to");
1075 return -1;
1076
1077 case 0:
1078 /* child process */
1079 if (fd != 0)
1080 dup2 (fd, 0);
1081 freopen ("/dev/null", "w", stdout);
1082 freopen ("/dev/null", "w", stderr);
1083 if (fd != 3)
1084 dup2 (fd, 3);
1085 closefds (4);
1086
1087 #ifdef TIOCNOTTY
1088 if ((fd = open ("/dev/tty", O_RDWR)) != -1) {
1089 ioctl (fd, TIOCNOTTY, NULL);
1090 close (fd);
1091 }
1092 #endif /* TIOCNOTTY */
1093
1094 setpgid ((pid_t) 0, getpid ()); /* put in own process group */
1095
1096 *environ = NULL;
1097 m_putenv ("USER", pw->pw_name);
1098 m_putenv ("HOME", pw->pw_dir);
1099 m_putenv ("SHELL", pw->pw_shell);
1100
1101 execvp (pgm, vec);
1102 _exit (-1);
1103
1104 default:
1105 /* parent process */
1106 if (! setjmp (myctx)) {
1107 SIGNAL (SIGALRM, alrmser);
1108 bytes = fstat (fd, &st) != -1 ? (int) st.st_size : 100;
1109
1110 /* amount of time to wait depends on message size */
1111 if (bytes <= 100) {
1112 /* give at least 5 minutes */
1113 seconds = 300;
1114 } else if (bytes >= 90000) {
1115 /* a half hour is long enough */
1116 seconds = 1800;
1117 } else {
1118 seconds = (bytes / 60) + 300;
1119 }
1120 alarm ((unsigned int) seconds);
1121 status = pidwait (child_id, 0);
1122 alarm (0);
1123
1124 if (verbose) {
1125 if (status == 0)
1126 verbose_printf (", success.\n");
1127 else
1128 if ((status & 0xff00) == 0xff00)
1129 verbose_printf (", system error\n");
1130 else
1131 pidstatus (status, stdout, ", failed");
1132 }
1133 return (status == 0 ? 0 : -1);
1134 } else {
1135 /*
1136 * Ruthlessly kill the child and anything
1137 * else in its process group.
1138 */
1139 killpg(child_id, SIGKILL);
1140 if (verbose)
1141 verbose_printf (", timed-out; terminated\n");
1142 return -1;
1143 }
1144 }
1145 }
1146
1147
1148 static void
1149 alrmser (int i)
1150 {
1151 NMH_UNUSED (i);
1152
1153 longjmp (myctx, DONE);
1154 }
1155
1156
1157 /*
1158 * Get the `sender' from the envelope
1159 * information ("From " line).
1160 */
1161
1162 static void
1163 get_sender (char *envelope, char **sender)
1164 {
1165 int i;
1166 unsigned char *cp;
1167 unsigned char buffer[BUFSIZ];
1168
1169 if (envelope == NULL) {
1170 *sender = getcpy ("");
1171 return;
1172 }
1173
1174 i = strlen ("From ");
1175 strncpy (buffer, envelope + i, sizeof(buffer));
1176 if ((cp = strchr(buffer, '\n'))) {
1177 *cp = 0;
1178 cp -= 24;
1179 if (cp < buffer)
1180 cp = buffer;
1181 } else {
1182 cp = buffer;
1183 }
1184 *cp = 0;
1185
1186 for (cp = buffer + strlen (buffer) - 1; cp >= buffer; cp--)
1187 if (isspace (*cp))
1188 *cp = 0;
1189 else
1190 break;
1191 *sender = getcpy (buffer);
1192 }
1193
1194
1195 /*
1196 * Copy message into a temporary file.
1197 * While copying, it will do some header processing
1198 * including the extraction of the envelope information.
1199 */
1200
1201 static int
1202 copy_message (int qd, char *tmpfil, int fold)
1203 {
1204 int i, first = 1, fd1, fd2;
1205 char buffer[BUFSIZ];
1206 FILE *qfp, *ffp;
1207 char *tfile = NULL;
1208
1209 tfile = m_mktemp2(NULL, invo_name, &fd1, NULL);
1210 if (tfile == NULL) return -1;
1211 fchmod(fd1, 0600);
1212 strncpy (tmpfil, tfile, BUFSIZ);
1213
1214 if (!fold) {
1215 while ((i = read (qd, buffer, sizeof(buffer))) > 0)
1216 if (write (fd1, buffer, i) != i) {
1217 you_lose:
1218 close (fd1);
1219 unlink (tmpfil);
1220 return -1;
1221 }
1222 if (i == -1)
1223 goto you_lose;
1224 lseek (fd1, (off_t) 0, SEEK_SET);
1225 return fd1;
1226 }
1227
1228 /* dup the fd for incoming message */
1229 if ((fd2 = dup (qd)) == -1) {
1230 close (fd1);
1231 return -1;
1232 }
1233
1234 /* now create a FILE pointer for it */
1235 if ((qfp = fdopen (fd2, "r")) == NULL) {
1236 close (fd1);
1237 close (fd2);
1238 return -1;
1239 }
1240
1241 /* dup the fd for temporary file */
1242 if ((fd2 = dup (fd1)) == -1) {
1243 close (fd1);
1244 fclose (qfp);
1245 return -1;
1246 }
1247
1248 /* now create a FILE pointer for it */
1249 if ((ffp = fdopen (fd2, "r+")) == NULL) {
1250 close (fd1);
1251 close (fd2);
1252 fclose (qfp);
1253 return -1;
1254 }
1255
1256 /*
1257 * copy message into temporary file
1258 * and massage the headers. Save
1259 * a copy of the "From " line for later.
1260 */
1261 i = strlen ("From ");
1262 while (fgets (buffer, sizeof(buffer), qfp)) {
1263 if (first) {
1264 first = 0;
1265 if (!strncmp (buffer, "From ", i)) {
1266 /* get copy of envelope information ("From " line) */
1267 envelope = getcpy (buffer);
1268
1269 /* Put the delivery date in message */
1270 fputs (ddate, ffp);
1271 if (ferror (ffp))
1272 goto fputs_error;
1273
1274 continue;
1275 }
1276 }
1277
1278 fputs (buffer, ffp);
1279 if (ferror (ffp))
1280 goto fputs_error;
1281 }
1282
1283 fclose (ffp);
1284 if (ferror (qfp)) {
1285 close (fd1);
1286 fclose (qfp);
1287 return -1;
1288 }
1289 fclose (qfp);
1290 lseek (fd1, (off_t) 0, SEEK_SET);
1291 return fd1;
1292
1293
1294 fputs_error:
1295 close (fd1);
1296 fclose (ffp);
1297 fclose (qfp);
1298 return -1;
1299 }
1300
1301 /*
1302 * Trim strings for pretty printing of debugging output
1303 */
1304
1305 static char *
1306 trim (char *cp)
1307 {
1308 char buffer[BUFSIZ*4];
1309 unsigned char *bp, *sp;
1310
1311 if (cp == NULL)
1312 return NULL;
1313
1314 /* copy string into temp buffer */
1315 strncpy (buffer, cp, sizeof(buffer));
1316 bp = buffer;
1317
1318 /* skip over leading whitespace */
1319 while (isspace(*bp))
1320 bp++;
1321
1322 /* start at the end and zap trailing whitespace */
1323 for (sp = bp + strlen(bp) - 1; sp >= bp; sp--) {
1324 if (isspace(*sp))
1325 *sp = 0;
1326 else
1327 break;
1328 }
1329
1330 /* replace remaining whitespace with spaces */
1331 for (sp = bp; *sp; sp++)
1332 if (isspace(*sp))
1333 *sp = ' ';
1334
1335 /* now return a copy */
1336 return getcpy(bp);
1337 }
1338
1339 /*
1340 * Function for printing `verbose' messages.
1341 */
1342
1343 static void
1344 verbose_printf (char *fmt, ...)
1345 {
1346 va_list ap;
1347
1348 va_start(ap, fmt);
1349 vfprintf (stdout, fmt, ap);
1350 va_end(ap);
1351
1352 fflush (stdout); /* now flush output */
1353 }
1354
1355
1356 /*
1357 * Function for printing `verbose' delivery
1358 * error messages.
1359 */
1360
1361 static void
1362 adorn (char *what, char *fmt, ...)
1363 {
1364 va_list ap;
1365 int eindex;
1366 char *s;
1367
1368 eindex = errno; /* save the errno */
1369 fprintf (stdout, ", ");
1370
1371 va_start(ap, fmt);
1372 vfprintf (stdout, fmt, ap);
1373 va_end(ap);
1374
1375 if (what) {
1376 if (*what)
1377 fprintf (stdout, " %s: ", what);
1378 if ((s = strerror (eindex)))
1379 fprintf (stdout, "%s", s);
1380 else
1381 fprintf (stdout, "Error %d", eindex);
1382 }
1383
1384 fputc ('\n', stdout);
1385 fflush (stdout);
1386 }
1387
1388
1389 /*
1390 * Function for printing `debug' messages.
1391 */
1392
1393 static void
1394 debug_printf (char *fmt, ...)
1395 {
1396 va_list ap;
1397
1398 va_start(ap, fmt);
1399 vfprintf (stderr, fmt, ap);
1400 va_end(ap);
1401 }
1402
1403
1404 /*
1405 * Check ndbm/db file(s) to see if the Message-Id of this
1406 * message matches the Message-Id of a previous message,
1407 * so we can discard it. If it doesn't match, we add the
1408 * Message-Id of this message to the ndbm/db file.
1409 */
1410 static int
1411 suppress_duplicates (int fd, char *file)
1412 {
1413 int fd1, lockfd, state, result;
1414 char *cp, buf[BUFSIZ], name[NAMESZ];
1415 datum key, value;
1416 DBM *db;
1417 FILE *in;
1418 m_getfld_state_t gstate;
1419
1420 if ((fd1 = dup (fd)) == -1)
1421 return -1;
1422 if (!(in = fdopen (fd1, "r"))) {
1423 close (fd1);
1424 return -1;
1425 }
1426 rewind (in);
1427
1428 m_getfld_state_init (&gstate);
1429 for (;;) {
1430 int bufsz = sizeof buf;
1431 state = m_getfld (gstate, name, buf, &bufsz, in);
1432 switch (state) {
1433 case FLD:
1434 case FLDPLUS:
1435 /* Search for the message ID */
1436 if (mh_strcasecmp (name, "Message-ID")) {
1437 while (state == FLDPLUS) {
1438 bufsz = sizeof buf;
1439 state = m_getfld (gstate, name, buf, &bufsz, in);
1440 }
1441 continue;
1442 }
1443
1444 cp = add (buf, NULL);
1445 while (state == FLDPLUS) {
1446 bufsz = sizeof buf;
1447 state = m_getfld (gstate, name, buf, &bufsz, in);
1448 cp = add (buf, cp);
1449 }
1450 key.dptr = trimcpy (cp);
1451 key.dsize = strlen (key.dptr) + 1;
1452 free (cp);
1453 cp = key.dptr;
1454
1455 if (!(db = dbm_open (file, O_RDWR | O_CREAT, 0600))) {
1456 advise (file, "unable to perform dbm_open on");
1457 free (cp);
1458 fclose (in);
1459 return -1;
1460 }
1461 /*
1462 * Since it is difficult to portable lock a ndbm file,
1463 * we will open and lock the Maildelivery file instead.
1464 * This will fail if your Maildelivery file doesn't
1465 * exist.
1466 */
1467 if ((lockfd = lkopen(file, O_RDWR, 0)) == -1) {
1468 advise (file, "unable to perform file locking on");
1469 free (cp);
1470 fclose (in);
1471 return -1;
1472 }
1473 value = dbm_fetch (db, key);
1474 if (value.dptr) {
1475 if (verbose)
1476 verbose_printf ("Message-ID: %s\n already received on %s",
1477 cp, value.dptr);
1478 result = DONE;
1479 } else {
1480 value.dptr = ddate + sizeof("Delivery-Date:");
1481 value.dsize = strlen(value.dptr) + 1;
1482 if (dbm_store (db, key, value, DBM_INSERT))
1483 advise (file, "possibly corrupt file");
1484 result = 0;
1485 }
1486
1487 dbm_close (db);
1488 lkclose(lockfd, file);
1489 free (cp);
1490 fclose (in);
1491 return result;
1492 break;
1493
1494 case BODY:
1495 case FILEEOF:
1496 break;
1497
1498 case LENERR:
1499 case FMTERR:
1500 default:
1501 break;
1502 }
1503
1504 break;
1505 }
1506 m_getfld_state_destroy (&gstate);
1507
1508 fclose (in);
1509 return 0;
1510 }