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.
19 #include <h/rcvmail.h>
20 #include <h/signals.h>
25 #include <sys/ioctl.h>
33 #ifdef INITGROUPS_HEADER
34 #include INITGROUPS_HEADER
37 ** On AIX 4.1, initgroups() is defined and even documented (giving the
38 ** parameter types as char* and int), but doesn't have a prototype in any
39 ** of the system header files. AIX 4.3, SunOS 4.1.3, and ULTRIX 4.2A have
42 extern int initgroups(char*, int);
45 static struct swit switches[] = {
47 { "addr address", 0 },
53 { "sender address", 0 },
55 { "mailbox file", 0 },
57 { "home directory", -4 },
61 { "maildelivery file", 0 },
76 static int globbed = 0; /* have we built "vars" table yet? */
77 static int parsed = 0; /* have we built header field table yet */
79 static int verbose = 0;
82 static char *addr = NULL;
83 static char *user = NULL;
84 static char *info = NULL;
85 static char *file = NULL;
86 static char *sender = NULL;
87 static char *envelope = NULL; /* envelope information ("From " line) */
88 static char *mbox = NULL;
89 static char *home = NULL;
91 static struct passwd *pw; /* passwd file entry */
93 static char ddate[BUFSIZ]; /* record the delivery date */
96 volatile sig_atomic_t eflag = 0; /* flag to indecate interrupt */
97 static volatile pid_t child_id;
99 /* flags for pair->p_flags */
101 #define P_ADR 0x01 /* field is address */
102 #define P_HID 0x02 /* special (fake) field */
114 ** Lookup table for matching fields and patterns
115 ** in messages. The rest of the table is added
116 ** when the message is parsed.
118 static struct pair hdrs[NVEC + 1] = {
119 { "source", NULL, P_HID },
120 { "addr", NULL, P_HID },
121 { "Return-Path", NULL, P_ADR },
122 { "Reply-To", NULL, P_ADR },
123 { "From", NULL, P_ADR },
124 { "Sender", NULL, P_ADR },
125 { "To", NULL, P_ADR },
126 { "cc", NULL, P_ADR },
127 { "Resent-Reply-To", NULL, P_ADR },
128 { "Resent-From", NULL, P_ADR },
129 { "Resent-Sender", NULL, P_ADR },
130 { "Resent-To", NULL, P_ADR },
131 { "Resent-Cc", NULL, P_ADR },
136 ** The list of builtin variables to expand in a string
137 ** before it is executed by the "pipe" or "qpipe" action.
139 static struct pair vars[] = {
140 { "sender", NULL, P_NIL },
141 { "address", NULL, P_NIL },
142 { "size", NULL, P_NIL },
143 { "reply-to", NULL, P_CHK },
144 { "info", NULL, P_NIL },
148 extern char **environ;
153 static int localmail(int, char *);
154 static int usr_delivery(int, char *, int);
155 static int split(char *, char **);
156 static int parse(int);
157 static void expand(char *, char *, int);
158 static void glob(int);
159 static struct pair *lookup(struct pair *, char *);
160 static int usr_file(int, char *);
161 static int usr_pipe(int, char *, char *, char **, int);
162 static int usr_folder(int, char *);
163 static void alrmser(int);
164 static void get_sender(char *, char **);
165 static int copy_message(int, char *, int);
166 static void verbose_printf(char *fmt, ...);
167 static void adorn(char *, char *, ...);
168 static void debug_printf(char *fmt, ...);
169 static char *trimstr(char *);
173 main(int argc, char **argv)
177 char *cp, *mdlvr = NULL, buf[BUFSIZ];
178 char mailbox[BUFSIZ], tmpfil[BUFSIZ];
179 char **argp, **arguments;
181 setlocale(LC_ALL, "");
182 invo_name = mhbasename(*argv);
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(EX_USAGE, NULL, "-%s unknown", cp);
198 snprintf(buf, sizeof(buf), "%s [switches] [address info sender]", invo_name);
199 print_help(buf, switches, 0);
200 exit(argc == 2 ? EX_OK : EX_USAGE);
202 print_version(invo_name);
203 exit(argc == 2 ? EX_OK : EX_USAGE);
206 if (!(addr = *argp++)) {
207 /* allow -xyz arguments */
208 adios(EX_USAGE, NULL, "missing argument to %s",
213 if (!(info = *argp++)) {
214 /* allow -xyz arguments */
215 adios(EX_USAGE, NULL, "missing argument to %s",
220 if (!(user = *argp++)) {
221 /* allow -xyz arguments */
222 adios(EX_USAGE, NULL, "missing argument to %s",
227 if (!(file = *argp++) || *file == '-') {
228 adios(EX_USAGE, NULL, "missing argument to %s",
233 if (!(sender = *argp++)) {
234 /* allow -xyz arguments */
235 adios(EX_USAGE, NULL, "missing argument to %s",
240 if (!(mbox = *argp++) || *mbox == '-') {
241 adios(EX_USAGE, NULL, "missing argument to %s",
246 if (!(home = *argp++) || *home == '-') {
247 adios(EX_USAGE, NULL, "missing argument to %s",
253 if (!(cp = *argp++) || *cp == '-') {
254 adios(EX_USAGE, NULL, "missing argument to %s",
258 adios(EX_USAGE, 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(EX_NOUSER, 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(EX_OSERR, 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(EX_IOERR, file, "unable to open");
333 debug_printf("retrieving message from file \"%s\"\n",
336 if ((fd = copy_message(tempfd, tmpfil, 1)) == -1) {
337 adios(EX_CANTCREAT, 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(EX_CANTCREAT, 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(EX_IOERR, 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", trimstr(addr));
390 debug_printf("user=\"%s\"\n", trimstr(user));
391 debug_printf("info=\"%s\"\n", trimstr(info));
392 debug_printf("sender=\"%s\"\n", trimstr(sender));
393 debug_printf("envelope=\"%s\"\n",
394 envelope ? trimstr(envelope) : "");
395 debug_printf("mbox=\"%s\"\n", trimstr(mbox));
396 debug_printf("home=\"%s\"\n", trimstr(home));
397 debug_printf("ddate=\"%s\"\n", trimstr(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 return (status != -1 ? RCV_MOK : RCV_MBX);
409 ** Main routine for delivering message.
412 localmail(int fd, char *mdlvr)
416 /* delivery according to personal Maildelivery file */
417 if (usr_delivery(fd, mdlvr ? mdlvr : ".maildelivery", 0) != -1) {
420 /* delivery according to global Maildelivery file */
421 snprintf(buf, sizeof buf, "%s/%s", mhetcdir, "maildelivery");
422 if (usr_delivery(fd, buf, 1) != -1) {
426 verbose_printf("(delivering to standard mail spool)\n");
428 /* last resort - deliver to standard mail spool */
429 return usr_file(fd, mbox);
433 #define matches(a,b) (stringdex(b, a) >= 0)
436 ** Parse the delivery file, and process incoming message.
439 usr_delivery(int fd, char *delivery, int su)
441 int i, accept, status=1, won, vecp, next;
442 char *field, *pattern, *action, *result, *string;
443 char buffer[BUFSIZ], tmpbuf[BUFSIZ];
444 char *cp, *vec[NVEC];
449 /* open the delivery file */
450 if (!(fp = fopen(delivery, "r"))) {
453 /* check if delivery file has bad ownership or permissions */
454 if (fstat(fileno(fp), &st) == -1 ||
455 (st.st_uid != 0 && (su || st.st_uid != pw->pw_uid)) ||
456 st.st_mode & (S_IWGRP|S_IWOTH)) {
458 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 /* read and process delivery file */
467 while (fgets(buffer, sizeof(buffer), fp)) {
468 /* skip comments and empty lines */
469 if (*buffer == '#' || *buffer == '\n') {
472 /* zap trailing newline */
473 if ((cp = strchr(buffer, '\n'))) {
476 /* split buffer into fields */
477 vecp = split(buffer, vec);
479 /* check for too few fields */
482 debug_printf("WARNING: entry with only %d fields, skipping.\n", vecp);
487 for (i = 0; vec[i]; i++) {
488 debug_printf("vec[%d]: \"%s\"\n",
499 /* find out how to perform the action */
504 ** If previous condition failed, don't
505 ** do this - else fall through
514 ** If already delivered, skip this action.
515 ** Else consider delivered if action is
526 ** Take action, and consider delivered if
527 ** action is successful.
536 ** Take action, but don't consider delivered,
537 ** even if action is successful
543 /* check if the field matches */
551 ** "default" matches only if the message hasn't
552 ** been delivered yet.
554 if (mh_strcasecmp(field, "default")==0) {
562 /* parse message and build lookup table */
563 if (!parsed && parse(fd) == -1) {
568 ** find header field in lookup table, and
569 ** see if the pattern matches.
571 if ((p = lookup(hdrs, field)) && p->p_value &&
572 matches(p->p_value, pattern)) {
581 /* find out the action to perform */
584 /* deliver to quoted pipe */
585 if (mh_strcasecmp(action, "qpipe")) {
590 expand(tmpbuf, string, fd);
591 if (split(tmpbuf, vec) < 1) {
594 status = usr_pipe(fd, tmpbuf, vec[0], vec, 0);
598 /* deliver to pipe */
599 if (mh_strcasecmp(action, "pipe")) {
606 expand(tmpbuf, string, fd);
609 status = usr_pipe(fd, tmpbuf, "/bin/sh", vec+2, 0);
613 if (mh_strcasecmp(action, "file")==0) {
615 status = usr_file(fd, string);
618 if (mh_strcasecmp(action, "folder")!=0) {
623 /* deliver to nmh folder */
624 status = usr_folder(fd, string);
629 if (mh_strcasecmp(action, "mbox")!=0) {
635 status = usr_file(fd, string);
640 if (mh_strcasecmp(action, "destroy")!=0) {
648 next = 0; /* action failed, mark for 'N' result */
655 return (won ? 0 : -1);
660 ** Split buffer into fields (delimited by whitespace or
661 ** comma's). Return the number of fields found.
664 split(char *cp, char **vec)
671 /* split into a maximum of NVEC fields */
672 for (i = 0; i <= NVEC;) {
675 /* zap any whitespace and comma's */
676 while (isspace(*s) || *s == ',') {
679 /* end of buffer, time to leave */
683 /* get double quote text as a single field */
685 for (vec[i++] = ++s; *s && *s != '"'; s++) {
687 ** Check for escaped double quote. We need
688 ** to shift the string to remove slash.
698 /* zap trailing double quote */
704 if (*s == '\\' && *++s != '"') {
709 /* move forward to next field delimiter */
710 while (*s && !isspace(*s) && *s != ',') {
721 ** Parse the headers of a message, and build the
722 ** lookup table for matching fields and patterns.
730 char name[NAMESZ], field[BUFSIZ];
738 /* get a new FILE pointer to message */
739 if ((fd1 = dup(fd)) == -1) {
742 if (!(in = fdopen(fd1, "r"))) {
748 /* add special entries to lookup table */
749 if ((p = lookup(hdrs, "source"))) {
750 p->p_value = getcpy(sender);
752 if ((p = lookup(hdrs, "addr"))) {
753 p->p_value = getcpy(addr);
757 ** Scan the headers of the message and build a lookup table.
759 for (i = 0, state = FLD;;) {
760 switch (state = m_getfld(state, name, field, sizeof(field),
766 while (state == FLDPLUS) {
767 state = m_getfld(state, name, field,
771 for (p = hdrs; p->p_name; p++) {
772 if (mh_strcasecmp(p->p_name, name)!=0) {
773 if (!(p->p_flags & P_HID)) {
774 if ((cp = p->p_value)) {
775 if (p->p_flags & P_ADR) {
776 dp = cp + strlen(cp) - 1;
780 cp = add(",\n\t", cp);
785 p->p_value = add(lp, cp);
791 if (!p->p_name && i < NVEC) {
792 p->p_name = getcpy(name);
798 if (state != FLDEOF) {
810 advise(NULL, "format error in message");
814 advise(NULL, "internal error in m_getfld");
822 if ((p = lookup(vars, "reply-to"))) {
823 if (!(q = lookup(hdrs, "reply-to")) || !q->p_value) {
824 q = lookup(hdrs, "from");
826 p->p_value = getcpy(q ? q->p_value : "");
827 p->p_flags &= ~P_CHK;
829 debug_printf("vars[%d]: name=\"%s\" value=\"%s\"\n",
830 p - vars, p->p_name, trimstr(p->p_value));
834 for (p = hdrs; p->p_name; p++) {
835 debug_printf("hdrs[%d]: name=\"%s\" value=\"%s\"\n",
837 p->p_value ? trimstr(p->p_value) : "");
845 ** Expand any builtin variables such as $(sender),
846 ** $(address), etc., in a string.
849 expand(char *s1, char *s2, int fd)
857 while ((c = *s2++)) {
858 if (c != '$' || *s2 != '(') {
861 for (cp = ++s2; *s2 && *s2 != ')'; s2++) {
869 if ((p = lookup(vars, cp))) {
870 if (!parsed && (p->p_flags & P_CHK)) {
873 strcpy(s1, p->p_value);
883 ** Fill in the information missing from the "vars"
884 ** table, which is necessary to expand any builtin
885 ** variables in the string for a "pipe" or "qpipe"
898 if ((p = lookup(vars, "sender"))) {
899 p->p_value = getcpy(sender);
901 if ((p = lookup(vars, "address"))) {
902 p->p_value = getcpy(addr);
904 if ((p = lookup(vars, "size"))) {
905 snprintf(buffer, sizeof(buffer), "%d",
906 fstat(fd, &st) != -1 ? (int) st.st_size : 0);
907 p->p_value = getcpy(buffer);
909 if ((p = lookup(vars, "info"))) {
910 p->p_value = getcpy(info);
913 for (p = vars; p->p_name; p++) {
914 debug_printf("vars[%d]: name=\"%s\" value=\"%s\"\n",
915 p - vars, p->p_name, trimstr(p->p_value));
922 ** Find a matching name in a lookup table. If found,
923 ** return the "pairs" entry, else return NULL.
926 lookup(struct pair *pairs, char *key)
928 for (; pairs->p_name; pairs++) {
929 if (!mh_strcasecmp(pairs->p_name, key)) {
938 ** Deliver message by appending to a file, using rcvpack(1).
941 usr_file(int fd, char *mailbox)
946 verbose_printf("delivering to file \"%s\" (mbox style)",
953 return usr_pipe(fd, "rcvpack", "rcvpack", vec, 1);
958 ** Deliver message to a nmh folder, using rcvstore(1).
961 usr_folder(int fd, char *string)
963 char folder[BUFSIZ], *vec[3];
965 /* get folder name ready */
966 if (*string == '+') {
967 strncpy(folder, string, sizeof(folder));
969 snprintf(folder, sizeof(folder), "+%s", string);
972 verbose_printf("delivering to folder \"%s\"", folder + 1);
978 return usr_pipe(fd, "rcvstore", "rcvstore", vec, 1);
982 ** Deliver message to a process.
985 usr_pipe(int fd, char *cmd, char *pgm, char **vec, int suppress)
987 int bytes, seconds, status, n;
991 if (verbose && !suppress) {
992 verbose_printf("delivering to pipe \"%s\"", cmd);
994 lseek(fd, (off_t) 0, SEEK_SET);
996 switch ((child_id = fork())) {
1000 adorn("fork", "unable to");
1009 freopen("/dev/null", "w", stdout);
1010 freopen("/dev/null", "w", stderr);
1014 for (n=4; n<OPEN_MAX; n++) {
1019 if ((fd = open("/dev/tty", O_RDWR)) != -1) {
1020 ioctl(fd, TIOCNOTTY, NULL);
1023 #endif /* TIOCNOTTY */
1025 /* put in own process group */
1026 setpgid((pid_t) 0, getpid());
1028 path = getenv("PATH");
1030 m_putenv("USER", pw->pw_name);
1031 m_putenv("HOME", pw->pw_dir);
1032 m_putenv("SHELL", pw->pw_shell);
1033 m_putenv("PATH", path);
1039 /* parent process */
1040 SIGNAL(SIGALRM, alrmser);
1041 bytes = fstat(fd, &st) != -1 ? (int) st.st_size : 100;
1043 /* amount of time to wait depends on message size */
1045 /* give at least 5 minutes */
1047 } else if (bytes >= 90000) {
1048 /* a half hour is long enough */
1051 seconds = (bytes / 60) + 300;
1053 alarm((unsigned int) seconds);
1054 status = pidwait(child_id, 0);
1059 verbose_printf(", timed-out; terminated\n");
1066 verbose_printf(", success.\n");
1067 } else if ((status & 0xff00) == 0xff00) {
1068 verbose_printf(", system error\n");
1070 pidstatus(status, stdout, ", failed");
1073 return (status == 0 ? 0 : -1);
1082 kill(-child_id, SIGKILL);
1087 ** Get the `sender' from the envelope
1088 ** information ("From " line).
1091 get_sender(char *envelope, char **sender)
1095 unsigned char buffer[BUFSIZ];
1098 *sender = getcpy("");
1102 i = strlen("From ");
1103 strncpy(buffer, envelope + i, sizeof(buffer));
1104 buffer[sizeof buffer -1] = '\0'; /* ensure termination */
1105 if ((cp = strchr(buffer, '\n'))) {
1116 for (cp = buffer + strlen(buffer) - 1; cp >= buffer; cp--)
1122 *sender = getcpy(buffer);
1127 ** Copy message into a temporary file.
1128 ** While copying, it will do some header processing
1129 ** including the extraction of the envelope information.
1132 copy_message(int qd, char *tmpfil, int fold)
1134 int i, first = 1, fd1, fd2;
1135 char buffer[BUFSIZ];
1139 tfile = m_mktemp2("/tmp/", invo_name, &fd1, NULL);
1140 if (tfile == NULL) return -1;
1142 strncpy(tmpfil, tfile, BUFSIZ);
1145 while ((i = read(qd, buffer, sizeof(buffer))) > 0) {
1146 if (write(fd1, buffer, i) != i) {
1156 lseek(fd1, (off_t) 0, SEEK_SET);
1160 /* dup the fd for incoming message */
1161 if ((fd2 = dup(qd)) == -1) {
1166 /* now create a FILE pointer for it */
1167 if (!(qfp = fdopen(fd2, "r"))) {
1173 /* dup the fd for temporary file */
1174 if ((fd2 = dup(fd1)) == -1) {
1180 /* now create a FILE pointer for it */
1181 if (!(ffp = fdopen(fd2, "r+"))) {
1189 ** copy message into temporary file
1190 ** and massage the headers. Save
1191 ** a copy of the "From " line for later.
1193 i = strlen("From ");
1194 while (fgets(buffer, sizeof(buffer), qfp)) {
1197 if (strncmp(buffer, "From ", i)==0) {
1199 ** get copy of envelope information
1202 envelope = getcpy(buffer);
1204 /* Put the delivery date in message */
1226 lseek(fd1, (off_t) 0, SEEK_SET);
1237 ** Trim strings for pretty printing of debugging output
1242 char buffer[BUFSIZ*4];
1243 unsigned char *bp, *sp;
1249 /* copy string into temp buffer */
1250 strncpy(buffer, cp, sizeof(buffer));
1253 /* skip over leading whitespace */
1254 while (isspace(*bp)) {
1257 /* start at the end and zap trailing whitespace */
1258 for (sp = bp + strlen(bp) - 1; sp >= bp; sp--) {
1266 /* replace remaining whitespace with spaces */
1267 for (sp = bp; *sp; sp++) {
1276 ** Function for printing `verbose' messages.
1279 verbose_printf(char *fmt, ...)
1284 vfprintf(stdout, fmt, ap);
1291 ** Function for printing `verbose' delivery
1295 adorn(char *what, char *fmt, ...)
1301 eindex = errno; /* save the errno */
1302 fprintf(stdout, ", ");
1305 vfprintf(stdout, fmt, ap);
1310 fprintf(stdout, " %s: ", what);
1312 if ((s = strerror(eindex))) {
1313 fprintf(stdout, "%s", s);
1315 fprintf(stdout, "Error %d", eindex);
1319 fputc('\n', stdout);
1325 ** Function for printing `debug' messages.
1328 debug_printf(char *fmt, ...)
1333 vfprintf(stderr, fmt, ap);