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