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