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