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