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