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