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