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