2 ** slocal.c -- asynchronously filter and deliver new mail
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.
10 ** Under sendmail, users should add the line
12 ** "| /usr/local/mmh/bin/slocal"
14 ** to their $HOME/.forward file.
20 #include <h/rcvmail.h>
21 #include <h/signals.h>
27 #include <sys/ioctl.h>
30 #ifdef INITGROUPS_HEADER
31 #include INITGROUPS_HEADER
34 ** On AIX 4.1, initgroups() is defined and even documented (giving the
35 ** parameter types as char* and int), but doesn't have a prototype in any
36 ** of the system header files. AIX 4.3, SunOS 4.1.3, and ULTRIX 4.2A have
39 extern int initgroups(char*, int);
42 static struct swit switches[] = {
44 { "addr address", 0 },
50 { "sender address", 0 },
52 { "mailbox file", 0 },
54 { "home directory", -4 },
58 { "maildelivery file", 0 },
73 static int globbed = 0; /* have we built "vars" table yet? */
74 static int parsed = 0; /* have we built header field table yet */
76 static int verbose = 0;
79 static char *addr = NULL;
80 static char *user = NULL;
81 static char *info = NULL;
82 static char *file = NULL;
83 static char *sender = NULL;
84 static char *envelope = NULL; /* envelope information ("From " line) */
85 static char *mbox = NULL;
86 static char *home = NULL;
88 static struct passwd *pw; /* passwd file entry */
90 static char ddate[BUFSIZ]; /* record the delivery date */
95 /* flags for pair->p_flags */
97 #define P_ADR 0x01 /* field is address */
98 #define P_HID 0x02 /* special (fake) field */
110 ** Lookup table for matching fields and patterns
111 ** in messages. The rest of the table is added
112 ** when the message is parsed.
114 static struct pair hdrs[NVEC + 1] = {
115 { "source", NULL, P_HID },
116 { "addr", NULL, P_HID },
117 { "Return-Path", NULL, P_ADR },
118 { "Reply-To", NULL, P_ADR },
119 { "From", NULL, P_ADR },
120 { "Sender", NULL, P_ADR },
121 { "To", NULL, P_ADR },
122 { "cc", NULL, P_ADR },
123 { "Resent-Reply-To", NULL, P_ADR },
124 { "Resent-From", NULL, P_ADR },
125 { "Resent-Sender", NULL, P_ADR },
126 { "Resent-To", NULL, P_ADR },
127 { "Resent-Cc", NULL, P_ADR },
132 ** The list of builtin variables to expand in a string
133 ** before it is executed by the "pipe" or "qpipe" action.
135 static struct pair vars[] = {
136 { "sender", NULL, P_NIL },
137 { "address", NULL, P_NIL },
138 { "size", NULL, P_NIL },
139 { "reply-to", NULL, P_CHK },
140 { "info", NULL, P_NIL },
144 extern char **environ;
149 static int localmail(int, char *);
150 static int usr_delivery(int, char *, int);
151 static int split(char *, char **);
152 static int parse(int);
153 static void expand(char *, char *, int);
154 static void glob(int);
155 static struct pair *lookup(struct pair *, char *);
156 static int usr_file(int, char *);
157 static int usr_pipe(int, char *, char *, char **, int);
158 static int usr_folder(int, char *);
159 static void alrmser(int);
160 static void get_sender(char *, char **);
161 static int copy_message(int, char *, int);
162 static void verbose_printf(char *fmt, ...);
163 static void adorn(char *, char *, ...);
164 static void debug_printf(char *fmt, ...);
165 static char *trim(char *);
169 main(int argc, char **argv)
173 char *cp, *mdlvr = NULL, buf[BUFSIZ];
174 char mailbox[BUFSIZ], tmpfil[BUFSIZ];
175 char **argp, **arguments;
177 setlocale(LC_ALL, "");
178 invo_name = mhbasename(*argv);
180 /* foil search of user profile/context */
181 if (context_foil(NULL) == -1) {
184 arguments = getarguments(invo_name, argc, argv, 0);
187 /* Parse arguments */
188 while ((cp = *argp++)) {
190 switch (smatch(++cp, switches)) {
192 ambigsw(cp, switches);
195 adios(NULL, "-%s unknown", cp);
198 snprintf(buf, sizeof(buf), "%s [switches] [address info sender]", invo_name);
199 print_help(buf, switches, 0);
202 print_version(invo_name);
206 if (!(addr = *argp++)) {
207 /* allow -xyz arguments */
208 adios(NULL, "missing argument to %s",
213 if (!(info = *argp++)) {
214 /* allow -xyz arguments */
215 adios(NULL, "missing argument to %s",
220 if (!(user = *argp++)) {
221 /* allow -xyz arguments */
222 adios(NULL, "missing argument to %s",
227 if (!(file = *argp++) || *file == '-') {
228 adios(NULL, "missing argument to %s",
233 if (!(sender = *argp++)) {
234 /* allow -xyz arguments */
235 adios(NULL, "missing argument to %s",
240 if (!(mbox = *argp++) || *mbox == '-') {
241 adios(NULL, "missing argument to %s",
246 if (!(home = *argp++) || *home == '-') {
247 adios(NULL, "missing argument to %s",
253 if (!(cp = *argp++) || *cp == '-') {
254 adios(NULL, "missing argument to %s",
258 adios(NULL, "only one maildelivery file at a time!");
276 switch (argp - (argv + 1)) {
290 addr = getusername();
293 user = (cp = strchr(addr, '.')) ? ++cp : addr;
295 if (!(pw = getpwnam(user))) {
296 adios(NULL, "no such local user as %s", user);
299 if (chdir(pw->pw_dir) == -1) {
304 if (geteuid() == 0) {
306 initgroups(pw->pw_name, pw->pw_gid);
316 /* Record the delivery time */
317 if (!(now = dlocaltimenow())) {
318 adios(NULL, "unable to ascertain local time");
320 snprintf(ddate, sizeof(ddate), "Delivery-Date: %s\n", dtimenow());
323 ** Copy the message to a temporary file
328 /* getting message from file */
329 if ((tempfd = open(file, O_RDONLY)) == -1) {
330 adios(file, "unable to open");
333 debug_printf("retrieving message from file \"%s\"\n",
336 if ((fd = copy_message(tempfd, tmpfil, 1)) == -1) {
337 adios(NULL, "unable to create temporary file");
341 /* getting message from stdin */
343 debug_printf("retrieving message from stdin\n");
345 if ((fd = copy_message(fileno(stdin), tmpfil, 1)) == -1) {
346 adios(NULL, "unable to create temporary file");
351 debug_printf("temporary file=\"%s\"\n", tmpfil);
355 ** Delete the temp file now or a copy of every single message
356 ** passed through slocal will be left in the /tmp directory until
357 ** deleted manually! This unlink() used to be under an 'else'
358 ** of the 'if (debug)' above, but since some people like to
359 ** always run slocal with -debug and log the results, the /tmp
360 ** directory would get choked over time. Of course, now that
361 ** we always delete the temp file, the "temporary file=" message
362 ** above is somewhat pointless -- someone watching debug output
363 ** wouldn't have a chance to 'tail -f' or 'ln' the temp file
364 ** before it's unlinked. The best thing would be to delay this
365 ** unlink() until later if debug == 1, but I'll leave that for
366 ** someone who cares about the temp-file-accessing functionality
367 ** (they'll have to watch out for cases where we adios()).
371 if (!(fp = fdopen(fd, "r+"))) {
372 adios(NULL, "unable to access temporary file");
375 /* If no sender given, extract it from envelope information. */
377 get_sender(envelope, &sender);
380 snprintf(mailbox, sizeof(mailbox), "%s/%s",
381 mailspool, pw->pw_name);
389 debug_printf("addr=\"%s\"\n", trim(addr));
390 debug_printf("user=\"%s\"\n", trim(user));
391 debug_printf("info=\"%s\"\n", trim(info));
392 debug_printf("sender=\"%s\"\n", trim(sender));
393 debug_printf("envelope=\"%s\"\n",
394 envelope ? trim(envelope) : "");
395 debug_printf("mbox=\"%s\"\n", trim(mbox));
396 debug_printf("home=\"%s\"\n", trim(home));
397 debug_printf("ddate=\"%s\"\n", trim(ddate));
398 debug_printf("now=%02d:%02d\n\n", now->tw_hour, now->tw_min);
401 /* deliver the message */
402 status = localmail(fd, mdlvr);
404 done(status != -1 ? RCV_MOK : RCV_MBX);
410 ** Main routine for delivering message.
413 localmail(int fd, char *mdlvr)
417 /* delivery according to personal Maildelivery file */
418 if (usr_delivery(fd, mdlvr ? mdlvr : ".maildelivery", 0) != -1) {
421 /* delivery according to global Maildelivery file */
422 snprintf(buf, sizeof buf, "%s/%s", mhetcdir, "maildelivery");
423 if (usr_delivery(fd, buf, 1) != -1) {
427 verbose_printf("(delivering to standard mail spool)\n");
429 /* last resort - deliver to standard mail spool */
430 return usr_file(fd, mbox);
434 #define matches(a,b) (stringdex(b, a) >= 0)
437 ** Parse the delivery file, and process incoming message.
440 usr_delivery(int fd, char *delivery, int su)
442 int i, accept, status=1, won, vecp, next;
443 char *field, *pattern, *action, *result, *string;
444 char buffer[BUFSIZ], tmpbuf[BUFSIZ];
445 char *cp, *vec[NVEC];
450 /* open the delivery file */
451 if (!(fp = fopen(delivery, "r"))) {
454 /* check if delivery file has bad ownership or permissions */
455 if (fstat(fileno(fp), &st) == -1 ||
456 (st.st_uid != 0 && (su || st.st_uid != pw->pw_uid)) ||
457 st.st_mode & (S_IWGRP|S_IWOTH)) {
459 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);
467 /* read and process delivery file */
468 while (fgets(buffer, sizeof(buffer), fp)) {
469 /* skip comments and empty lines */
470 if (*buffer == '#' || *buffer == '\n') {
473 /* zap trailing newline */
474 if ((cp = strchr(buffer, '\n'))) {
477 /* split buffer into fields */
478 vecp = split(buffer, vec);
480 /* check for too few fields */
483 debug_printf("WARNING: entry with only %d fields, skipping.\n", vecp);
488 for (i = 0; vec[i]; i++) {
489 debug_printf("vec[%d]: \"%s\"\n",
500 /* find out how to perform the action */
505 ** If previous condition failed, don't
506 ** do this - else fall through
515 ** If already delivered, skip this action.
516 ** Else consider delivered if action is
527 ** Take action, and consider delivered if
528 ** action is successful.
537 ** Take action, but don't consider delivered,
538 ** even if action is successful
544 /* check if the field matches */
552 ** "default" matches only if the message hasn't
553 ** been delivered yet.
555 if (mh_strcasecmp(field, "default")==0) {
563 /* parse message and build lookup table */
564 if (!parsed && parse(fd) == -1) {
569 ** find header field in lookup table, and
570 ** see if the pattern matches.
572 if ((p = lookup(hdrs, field)) && p->p_value &&
573 matches(p->p_value, pattern)) {
582 /* find out the action to perform */
585 /* deliver to quoted pipe */
586 if (mh_strcasecmp(action, "qpipe")) {
591 expand(tmpbuf, string, fd);
592 if (split(tmpbuf, vec) < 1) {
595 status = usr_pipe(fd, tmpbuf, vec[0], vec, 0);
599 /* deliver to pipe */
600 if (mh_strcasecmp(action, "pipe")) {
607 expand(tmpbuf, string, fd);
610 status = usr_pipe(fd, tmpbuf, "/bin/sh", vec+2, 0);
614 if (mh_strcasecmp(action, "file")==0) {
616 status = usr_file(fd, string);
619 if (mh_strcasecmp(action, "folder")!=0) {
624 /* deliver to nmh folder */
625 status = usr_folder(fd, string);
630 if (mh_strcasecmp(action, "mbox")!=0) {
636 status = usr_file(fd, string);
641 if (mh_strcasecmp(action, "destroy")!=0) {
649 next = 0; /* action failed, mark for 'N' result */
656 return (won ? 0 : -1);
661 ** Split buffer into fields (delimited by whitespace or
662 ** comma's). Return the number of fields found.
665 split(char *cp, char **vec)
672 /* split into a maximum of NVEC fields */
673 for (i = 0; i <= NVEC;) {
676 /* zap any whitespace and comma's */
677 while (isspace(*s) || *s == ',') {
680 /* end of buffer, time to leave */
684 /* get double quote text as a single field */
686 for (vec[i++] = ++s; *s && *s != '"'; s++) {
688 ** Check for escaped double quote. We need
689 ** to shift the string to remove slash.
699 /* zap trailing double quote */
705 if (*s == '\\' && *++s != '"') {
710 /* move forward to next field delimiter */
711 while (*s && !isspace(*s) && *s != ',') {
722 ** Parse the headers of a message, and build the
723 ** lookup table for matching fields and patterns.
731 char name[NAMESZ], field[BUFSIZ];
739 /* get a new FILE pointer to message */
740 if ((fd1 = dup(fd)) == -1) {
743 if (!(in = fdopen(fd1, "r"))) {
749 /* add special entries to lookup table */
750 if ((p = lookup(hdrs, "source"))) {
751 p->p_value = getcpy(sender);
753 if ((p = lookup(hdrs, "addr"))) {
754 p->p_value = getcpy(addr);
758 ** Scan the headers of the message and build a lookup table.
760 for (i = 0, state = FLD;;) {
761 switch (state = m_getfld(state, name, field, sizeof(field),
767 while (state == FLDPLUS) {
768 state = m_getfld(state, name, field,
772 for (p = hdrs; p->p_name; p++) {
773 if (mh_strcasecmp(p->p_name, name)!=0) {
774 if (!(p->p_flags & P_HID)) {
775 if ((cp = p->p_value)) {
776 if (p->p_flags & P_ADR) {
777 dp = cp + strlen(cp) - 1;
781 cp = add(",\n\t", cp);
786 p->p_value = add(lp, cp);
792 if (!p->p_name && i < NVEC) {
793 p->p_name = getcpy(name);
799 if (state != FLDEOF) {
811 advise(NULL, "format error in message");
815 advise(NULL, "internal error in m_getfld");
823 if ((p = lookup(vars, "reply-to"))) {
824 if (!(q = lookup(hdrs, "reply-to")) || !q->p_value) {
825 q = lookup(hdrs, "from");
827 p->p_value = getcpy(q ? q->p_value : "");
828 p->p_flags &= ~P_CHK;
830 debug_printf("vars[%d]: name=\"%s\" value=\"%s\"\n",
831 p - vars, p->p_name, trim(p->p_value));
835 for (p = hdrs; p->p_name; p++) {
836 debug_printf("hdrs[%d]: name=\"%s\" value=\"%s\"\n",
838 p->p_value ? trim(p->p_value) : "");
846 ** Expand any builtin variables such as $(sender),
847 ** $(address), etc., in a string.
850 expand(char *s1, char *s2, int fd)
858 while ((c = *s2++)) {
859 if (c != '$' || *s2 != '(') {
862 for (cp = ++s2; *s2 && *s2 != ')'; s2++) {
870 if ((p = lookup(vars, cp))) {
871 if (!parsed && (p->p_flags & P_CHK)) {
874 strcpy(s1, p->p_value);
884 ** Fill in the information missing from the "vars"
885 ** table, which is necessary to expand any builtin
886 ** variables in the string for a "pipe" or "qpipe"
899 if ((p = lookup(vars, "sender"))) {
900 p->p_value = getcpy(sender);
902 if ((p = lookup(vars, "address"))) {
903 p->p_value = getcpy(addr);
905 if ((p = lookup(vars, "size"))) {
906 snprintf(buffer, sizeof(buffer), "%d",
907 fstat(fd, &st) != -1 ? (int) st.st_size : 0);
908 p->p_value = getcpy(buffer);
910 if ((p = lookup(vars, "info"))) {
911 p->p_value = getcpy(info);
914 for (p = vars; p->p_name; p++) {
915 debug_printf("vars[%d]: name=\"%s\" value=\"%s\"\n",
916 p - vars, p->p_name, trim(p->p_value));
923 ** Find a matching name in a lookup table. If found,
924 ** return the "pairs" entry, else return NULL.
927 lookup(struct pair *pairs, char *key)
929 for (; pairs->p_name; pairs++) {
930 if (!mh_strcasecmp(pairs->p_name, key)) {
939 ** Deliver message by appending to a file, using rcvpack(1).
942 usr_file(int fd, char *mailbox)
947 verbose_printf("delivering to file \"%s\" (mbox style)",
954 return usr_pipe(fd, "rcvpack", "rcvpack", vec, 1);
959 ** Deliver message to a nmh folder, using rcvstore(1).
962 usr_folder(int fd, char *string)
964 char folder[BUFSIZ], *vec[3];
966 /* get folder name ready */
967 if (*string == '+') {
968 strncpy(folder, string, sizeof(folder));
970 snprintf(folder, sizeof(folder), "+%s", string);
973 verbose_printf("delivering to folder \"%s\"", folder + 1);
979 return usr_pipe(fd, "rcvstore", "rcvstore", vec, 1);
983 ** Deliver message to a process.
986 usr_pipe(int fd, char *cmd, char *pgm, char **vec, int suppress)
989 int bytes, seconds, status, n;
993 if (verbose && !suppress) {
994 verbose_printf("delivering to pipe \"%s\"", cmd);
996 lseek(fd, (off_t) 0, SEEK_SET);
998 switch ((child_id = fork())) {
1002 adorn("fork", "unable to");
1011 freopen("/dev/null", "w", stdout);
1012 freopen("/dev/null", "w", stderr);
1016 for (n=4; n<OPEN_MAX; n++) {
1021 if ((fd = open("/dev/tty", O_RDWR)) != -1) {
1022 ioctl(fd, TIOCNOTTY, NULL);
1025 #endif /* TIOCNOTTY */
1027 /* put in own process group */
1028 setpgid((pid_t) 0, getpid());
1030 path = getenv("PATH");
1032 m_putenv("USER", pw->pw_name);
1033 m_putenv("HOME", pw->pw_dir);
1034 m_putenv("SHELL", pw->pw_shell);
1035 m_putenv("PATH", path);
1041 /* parent process */
1042 if (setjmp(myctx)) {
1044 ** Ruthlessly kill the child and anything
1045 ** else in its process group.
1047 kill(-child_id, SIGKILL);
1049 verbose_printf(", timed-out; terminated\n");
1052 SIGNAL(SIGALRM, alrmser);
1053 bytes = fstat(fd, &st) != -1 ? (int) st.st_size : 100;
1055 /* amount of time to wait depends on message size */
1057 /* give at least 5 minutes */
1059 } else if (bytes >= 90000) {
1060 /* a half hour is long enough */
1063 seconds = (bytes / 60) + 300;
1065 alarm((unsigned int) seconds);
1066 status = pidwait(child_id, 0);
1071 verbose_printf(", success.\n");
1072 } else if ((status & 0xff00) == 0xff00) {
1073 verbose_printf(", system error\n");
1075 pidstatus(status, stdout, ", failed");
1078 return (status == 0 ? 0 : -1);
1086 longjmp(myctx, DONE);
1091 ** Get the `sender' from the envelope
1092 ** information ("From " line).
1095 get_sender(char *envelope, char **sender)
1099 unsigned char buffer[BUFSIZ];
1102 *sender = getcpy("");
1106 i = strlen("From ");
1107 strncpy(buffer, envelope + i, sizeof(buffer));
1108 buffer[sizeof buffer -1] = '\0'; /* ensure termination */
1109 if ((cp = strchr(buffer, '\n'))) {
1120 for (cp = buffer + strlen(buffer) - 1; cp >= buffer; cp--)
1126 *sender = getcpy(buffer);
1131 ** Copy message into a temporary file.
1132 ** While copying, it will do some header processing
1133 ** including the extraction of the envelope information.
1136 copy_message(int qd, char *tmpfil, int fold)
1138 int i, first = 1, fd1, fd2;
1139 char buffer[BUFSIZ];
1143 tfile = m_mktemp2("/tmp/", invo_name, &fd1, NULL);
1144 if (tfile == NULL) return -1;
1146 strncpy(tmpfil, tfile, BUFSIZ);
1149 while ((i = read(qd, buffer, sizeof(buffer))) > 0) {
1150 if (write(fd1, buffer, i) != i) {
1160 lseek(fd1, (off_t) 0, SEEK_SET);
1164 /* dup the fd for incoming message */
1165 if ((fd2 = dup(qd)) == -1) {
1170 /* now create a FILE pointer for it */
1171 if (!(qfp = fdopen(fd2, "r"))) {
1177 /* dup the fd for temporary file */
1178 if ((fd2 = dup(fd1)) == -1) {
1184 /* now create a FILE pointer for it */
1185 if (!(ffp = fdopen(fd2, "r+"))) {
1193 ** copy message into temporary file
1194 ** and massage the headers. Save
1195 ** a copy of the "From " line for later.
1197 i = strlen("From ");
1198 while (fgets(buffer, sizeof(buffer), qfp)) {
1201 if (strncmp(buffer, "From ", i)==0) {
1203 ** get copy of envelope information
1206 envelope = getcpy(buffer);
1208 /* Put the delivery date in message */
1230 lseek(fd1, (off_t) 0, SEEK_SET);
1241 ** Trim strings for pretty printing of debugging output
1246 char buffer[BUFSIZ*4];
1247 unsigned char *bp, *sp;
1253 /* copy string into temp buffer */
1254 strncpy(buffer, cp, sizeof(buffer));
1257 /* skip over leading whitespace */
1258 while (isspace(*bp)) {
1261 /* start at the end and zap trailing whitespace */
1262 for (sp = bp + strlen(bp) - 1; sp >= bp; sp--) {
1270 /* replace remaining whitespace with spaces */
1271 for (sp = bp; *sp; sp++) {
1280 ** Function for printing `verbose' messages.
1283 verbose_printf(char *fmt, ...)
1288 vfprintf(stdout, fmt, ap);
1295 ** Function for printing `verbose' delivery
1299 adorn(char *what, char *fmt, ...)
1305 eindex = errno; /* save the errno */
1306 fprintf(stdout, ", ");
1309 vfprintf(stdout, fmt, ap);
1314 fprintf(stdout, " %s: ", what);
1316 if ((s = strerror(eindex))) {
1317 fprintf(stdout, "%s", s);
1319 fprintf(stdout, "Error %d", eindex);
1323 fputc('\n', stdout);
1329 ** Function for printing `debug' messages.
1332 debug_printf(char *fmt, ...)
1337 vfprintf(stderr, fmt, ap);