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