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