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