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