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