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