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