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 */
93 volatile sig_atomic_t eflag = 0; /* flag to indecate interrupt */
94 static volatile pid_t child_id;
96 /* flags for pair->p_flags */
98 #define P_ADR 0x01 /* field is address */
99 #define P_HID 0x02 /* special (fake) field */
111 ** Lookup table for matching fields and patterns
112 ** in messages. The rest of the table is added
113 ** when the message is parsed.
115 static struct pair hdrs[NVEC + 1] = {
116 { "source", NULL, P_HID },
117 { "addr", NULL, P_HID },
118 { "Return-Path", NULL, P_ADR },
119 { "Reply-To", NULL, P_ADR },
120 { "From", NULL, P_ADR },
121 { "Sender", NULL, P_ADR },
122 { "To", NULL, P_ADR },
123 { "cc", NULL, P_ADR },
124 { "Resent-Reply-To", NULL, P_ADR },
125 { "Resent-From", NULL, P_ADR },
126 { "Resent-Sender", NULL, P_ADR },
127 { "Resent-To", NULL, P_ADR },
128 { "Resent-Cc", NULL, P_ADR },
133 ** The list of builtin variables to expand in a string
134 ** before it is executed by the "pipe" or "qpipe" action.
136 static struct pair vars[] = {
137 { "sender", NULL, P_NIL },
138 { "address", NULL, P_NIL },
139 { "size", NULL, P_NIL },
140 { "reply-to", NULL, P_CHK },
141 { "info", NULL, P_NIL },
145 extern char **environ;
150 static int localmail(int, char *);
151 static int usr_delivery(int, char *, int);
152 static int split(char *, char **);
153 static int parse(int);
154 static void expand(char *, char *, int);
155 static void glob(int);
156 static struct pair *lookup(struct pair *, char *);
157 static int usr_file(int, char *);
158 static int usr_pipe(int, char *, char *, char **, int);
159 static int usr_folder(int, char *);
160 static void alrmser(int);
161 static void get_sender(char *, char **);
162 static int copy_message(int, char *, int);
163 static void verbose_printf(char *fmt, ...);
164 static void adorn(char *, char *, ...);
165 static void debug_printf(char *fmt, ...);
166 static char *trimstr(char *);
170 main(int argc, char **argv)
174 char *cp, *mdlvr = NULL, buf[BUFSIZ];
175 char mailbox[BUFSIZ], tmpfil[BUFSIZ];
176 char **argp, **arguments;
178 setlocale(LC_ALL, "");
179 invo_name = mhbasename(*argv);
181 arguments = getarguments(invo_name, argc, argv, 0);
184 /* Parse arguments */
185 while ((cp = *argp++)) {
187 switch (smatch(++cp, switches)) {
189 ambigsw(cp, switches);
192 adios(NULL, "-%s unknown", cp);
195 snprintf(buf, sizeof(buf), "%s [switches] [address info sender]", invo_name);
196 print_help(buf, switches, 0);
199 print_version(invo_name);
203 if (!(addr = *argp++)) {
204 /* allow -xyz arguments */
205 adios(NULL, "missing argument to %s",
210 if (!(info = *argp++)) {
211 /* allow -xyz arguments */
212 adios(NULL, "missing argument to %s",
217 if (!(user = *argp++)) {
218 /* allow -xyz arguments */
219 adios(NULL, "missing argument to %s",
224 if (!(file = *argp++) || *file == '-') {
225 adios(NULL, "missing argument to %s",
230 if (!(sender = *argp++)) {
231 /* allow -xyz arguments */
232 adios(NULL, "missing argument to %s",
237 if (!(mbox = *argp++) || *mbox == '-') {
238 adios(NULL, "missing argument to %s",
243 if (!(home = *argp++) || *home == '-') {
244 adios(NULL, "missing argument to %s",
250 if (!(cp = *argp++) || *cp == '-') {
251 adios(NULL, "missing argument to %s",
255 adios(NULL, "only one maildelivery file at a time!");
273 switch (argp - (argv + 1)) {
287 addr = getusername();
290 user = (cp = strchr(addr, '.')) ? ++cp : addr;
292 if (!(pw = getpwnam(user))) {
293 adios(NULL, "no such local user as %s", user);
296 if (chdir(pw->pw_dir) == -1) {
301 if (geteuid() == 0) {
303 initgroups(pw->pw_name, pw->pw_gid);
313 /* Record the delivery time */
314 if (!(now = dlocaltimenow())) {
315 adios(NULL, "unable to ascertain local time");
317 snprintf(ddate, sizeof(ddate), "Delivery-Date: %s\n", dtimenow());
320 ** Copy the message to a temporary file
325 /* getting message from file */
326 if ((tempfd = open(file, O_RDONLY)) == -1) {
327 adios(file, "unable to open");
330 debug_printf("retrieving message from file \"%s\"\n",
333 if ((fd = copy_message(tempfd, tmpfil, 1)) == -1) {
334 adios(NULL, "unable to create temporary file");
338 /* getting message from stdin */
340 debug_printf("retrieving message from stdin\n");
342 if ((fd = copy_message(fileno(stdin), tmpfil, 1)) == -1) {
343 adios(NULL, "unable to create temporary file");
348 debug_printf("temporary file=\"%s\"\n", tmpfil);
352 ** Delete the temp file now or a copy of every single message
353 ** passed through slocal will be left in the /tmp directory until
354 ** deleted manually! This unlink() used to be under an 'else'
355 ** of the 'if (debug)' above, but since some people like to
356 ** always run slocal with -debug and log the results, the /tmp
357 ** directory would get choked over time. Of course, now that
358 ** we always delete the temp file, the "temporary file=" message
359 ** above is somewhat pointless -- someone watching debug output
360 ** wouldn't have a chance to 'tail -f' or 'ln' the temp file
361 ** before it's unlinked. The best thing would be to delay this
362 ** unlink() until later if debug == 1, but I'll leave that for
363 ** someone who cares about the temp-file-accessing functionality
364 ** (they'll have to watch out for cases where we adios()).
368 if (!(fp = fdopen(fd, "r+"))) {
369 adios(NULL, "unable to access temporary file");
372 /* If no sender given, extract it from envelope information. */
374 get_sender(envelope, &sender);
377 snprintf(mailbox, sizeof(mailbox), "%s/%s",
378 mailspool, pw->pw_name);
386 debug_printf("addr=\"%s\"\n", trimstr(addr));
387 debug_printf("user=\"%s\"\n", trimstr(user));
388 debug_printf("info=\"%s\"\n", trimstr(info));
389 debug_printf("sender=\"%s\"\n", trimstr(sender));
390 debug_printf("envelope=\"%s\"\n",
391 envelope ? trimstr(envelope) : "");
392 debug_printf("mbox=\"%s\"\n", trimstr(mbox));
393 debug_printf("home=\"%s\"\n", trimstr(home));
394 debug_printf("ddate=\"%s\"\n", trimstr(ddate));
395 debug_printf("now=%02d:%02d\n\n", now->tw_hour, now->tw_min);
398 /* deliver the message */
399 status = localmail(fd, mdlvr);
401 return (status != -1 ? RCV_MOK : RCV_MBX);
406 ** Main routine for delivering message.
409 localmail(int fd, char *mdlvr)
413 /* delivery according to personal Maildelivery file */
414 if (usr_delivery(fd, mdlvr ? mdlvr : ".maildelivery", 0) != -1) {
417 /* delivery according to global Maildelivery file */
418 snprintf(buf, sizeof buf, "%s/%s", mhetcdir, "maildelivery");
419 if (usr_delivery(fd, buf, 1) != -1) {
423 verbose_printf("(delivering to standard mail spool)\n");
425 /* last resort - deliver to standard mail spool */
426 return usr_file(fd, mbox);
430 #define matches(a,b) (stringdex(b, a) >= 0)
433 ** Parse the delivery file, and process incoming message.
436 usr_delivery(int fd, char *delivery, int su)
438 int i, accept, status=1, won, vecp, next;
439 char *field, *pattern, *action, *result, *string;
440 char buffer[BUFSIZ], tmpbuf[BUFSIZ];
441 char *cp, *vec[NVEC];
446 /* open the delivery file */
447 if (!(fp = fopen(delivery, "r"))) {
450 /* check if delivery file has bad ownership or permissions */
451 if (fstat(fileno(fp), &st) == -1 ||
452 (st.st_uid != 0 && (su || st.st_uid != pw->pw_uid)) ||
453 st.st_mode & (S_IWGRP|S_IWOTH)) {
455 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);
463 /* read and process delivery file */
464 while (fgets(buffer, sizeof(buffer), fp)) {
465 /* skip comments and empty lines */
466 if (*buffer == '#' || *buffer == '\n') {
469 /* zap trailing newline */
470 if ((cp = strchr(buffer, '\n'))) {
473 /* split buffer into fields */
474 vecp = split(buffer, vec);
476 /* check for too few fields */
479 debug_printf("WARNING: entry with only %d fields, skipping.\n", vecp);
484 for (i = 0; vec[i]; i++) {
485 debug_printf("vec[%d]: \"%s\"\n",
496 /* find out how to perform the action */
501 ** If previous condition failed, don't
502 ** do this - else fall through
511 ** If already delivered, skip this action.
512 ** Else consider delivered if action is
523 ** Take action, and consider delivered if
524 ** action is successful.
533 ** Take action, but don't consider delivered,
534 ** even if action is successful
540 /* check if the field matches */
548 ** "default" matches only if the message hasn't
549 ** been delivered yet.
551 if (mh_strcasecmp(field, "default")==0) {
559 /* parse message and build lookup table */
560 if (!parsed && parse(fd) == -1) {
565 ** find header field in lookup table, and
566 ** see if the pattern matches.
568 if ((p = lookup(hdrs, field)) && p->p_value &&
569 matches(p->p_value, pattern)) {
578 /* find out the action to perform */
581 /* deliver to quoted pipe */
582 if (mh_strcasecmp(action, "qpipe")) {
587 expand(tmpbuf, string, fd);
588 if (split(tmpbuf, vec) < 1) {
591 status = usr_pipe(fd, tmpbuf, vec[0], vec, 0);
595 /* deliver to pipe */
596 if (mh_strcasecmp(action, "pipe")) {
603 expand(tmpbuf, string, fd);
606 status = usr_pipe(fd, tmpbuf, "/bin/sh", vec+2, 0);
610 if (mh_strcasecmp(action, "file")==0) {
612 status = usr_file(fd, string);
615 if (mh_strcasecmp(action, "folder")!=0) {
620 /* deliver to nmh folder */
621 status = usr_folder(fd, string);
626 if (mh_strcasecmp(action, "mbox")!=0) {
632 status = usr_file(fd, string);
637 if (mh_strcasecmp(action, "destroy")!=0) {
645 next = 0; /* action failed, mark for 'N' result */
652 return (won ? 0 : -1);
657 ** Split buffer into fields (delimited by whitespace or
658 ** comma's). Return the number of fields found.
661 split(char *cp, char **vec)
668 /* split into a maximum of NVEC fields */
669 for (i = 0; i <= NVEC;) {
672 /* zap any whitespace and comma's */
673 while (isspace(*s) || *s == ',') {
676 /* end of buffer, time to leave */
680 /* get double quote text as a single field */
682 for (vec[i++] = ++s; *s && *s != '"'; s++) {
684 ** Check for escaped double quote. We need
685 ** to shift the string to remove slash.
695 /* zap trailing double quote */
701 if (*s == '\\' && *++s != '"') {
706 /* move forward to next field delimiter */
707 while (*s && !isspace(*s) && *s != ',') {
718 ** Parse the headers of a message, and build the
719 ** lookup table for matching fields and patterns.
727 char name[NAMESZ], field[BUFSIZ];
735 /* get a new FILE pointer to message */
736 if ((fd1 = dup(fd)) == -1) {
739 if (!(in = fdopen(fd1, "r"))) {
745 /* add special entries to lookup table */
746 if ((p = lookup(hdrs, "source"))) {
747 p->p_value = getcpy(sender);
749 if ((p = lookup(hdrs, "addr"))) {
750 p->p_value = getcpy(addr);
754 ** Scan the headers of the message and build a lookup table.
756 for (i = 0, state = FLD;;) {
757 switch (state = m_getfld(state, name, field, sizeof(field),
763 while (state == FLDPLUS) {
764 state = m_getfld(state, name, field,
768 for (p = hdrs; p->p_name; p++) {
769 if (mh_strcasecmp(p->p_name, name)!=0) {
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;
777 cp = add(",\n\t", cp);
782 p->p_value = add(lp, cp);
788 if (!p->p_name && i < NVEC) {
789 p->p_name = getcpy(name);
795 if (state != FLDEOF) {
807 advise(NULL, "format error in message");
811 advise(NULL, "internal error in m_getfld");
819 if ((p = lookup(vars, "reply-to"))) {
820 if (!(q = lookup(hdrs, "reply-to")) || !q->p_value) {
821 q = lookup(hdrs, "from");
823 p->p_value = getcpy(q ? q->p_value : "");
824 p->p_flags &= ~P_CHK;
826 debug_printf("vars[%d]: name=\"%s\" value=\"%s\"\n",
827 p - vars, p->p_name, trimstr(p->p_value));
831 for (p = hdrs; p->p_name; p++) {
832 debug_printf("hdrs[%d]: name=\"%s\" value=\"%s\"\n",
834 p->p_value ? trimstr(p->p_value) : "");
842 ** Expand any builtin variables such as $(sender),
843 ** $(address), etc., in a string.
846 expand(char *s1, char *s2, int fd)
854 while ((c = *s2++)) {
855 if (c != '$' || *s2 != '(') {
858 for (cp = ++s2; *s2 && *s2 != ')'; s2++) {
866 if ((p = lookup(vars, cp))) {
867 if (!parsed && (p->p_flags & P_CHK)) {
870 strcpy(s1, p->p_value);
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"
895 if ((p = lookup(vars, "sender"))) {
896 p->p_value = getcpy(sender);
898 if ((p = lookup(vars, "address"))) {
899 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);
906 if ((p = lookup(vars, "info"))) {
907 p->p_value = getcpy(info);
910 for (p = vars; p->p_name; p++) {
911 debug_printf("vars[%d]: name=\"%s\" value=\"%s\"\n",
912 p - vars, p->p_name, trimstr(p->p_value));
919 ** Find a matching name in a lookup table. If found,
920 ** return the "pairs" entry, else return NULL.
923 lookup(struct pair *pairs, char *key)
925 for (; pairs->p_name; pairs++) {
926 if (!mh_strcasecmp(pairs->p_name, key)) {
935 ** Deliver message by appending to a file, using rcvpack(1).
938 usr_file(int fd, char *mailbox)
943 verbose_printf("delivering to file \"%s\" (mbox style)",
950 return usr_pipe(fd, "rcvpack", "rcvpack", vec, 1);
955 ** Deliver message to a nmh folder, using rcvstore(1).
958 usr_folder(int fd, char *string)
960 char folder[BUFSIZ], *vec[3];
962 /* get folder name ready */
963 if (*string == '+') {
964 strncpy(folder, string, sizeof(folder));
966 snprintf(folder, sizeof(folder), "+%s", string);
969 verbose_printf("delivering to folder \"%s\"", folder + 1);
975 return usr_pipe(fd, "rcvstore", "rcvstore", vec, 1);
979 ** Deliver message to a process.
982 usr_pipe(int fd, char *cmd, char *pgm, char **vec, int suppress)
984 int bytes, seconds, status, n;
988 if (verbose && !suppress) {
989 verbose_printf("delivering to pipe \"%s\"", cmd);
991 lseek(fd, (off_t) 0, SEEK_SET);
993 switch ((child_id = fork())) {
997 adorn("fork", "unable to");
1006 freopen("/dev/null", "w", stdout);
1007 freopen("/dev/null", "w", stderr);
1011 for (n=4; n<OPEN_MAX; n++) {
1016 if ((fd = open("/dev/tty", O_RDWR)) != -1) {
1017 ioctl(fd, TIOCNOTTY, NULL);
1020 #endif /* TIOCNOTTY */
1022 /* put in own process group */
1023 setpgid((pid_t) 0, getpid());
1025 path = getenv("PATH");
1027 m_putenv("USER", pw->pw_name);
1028 m_putenv("HOME", pw->pw_dir);
1029 m_putenv("SHELL", pw->pw_shell);
1030 m_putenv("PATH", path);
1036 /* parent process */
1037 SIGNAL(SIGALRM, alrmser);
1038 bytes = fstat(fd, &st) != -1 ? (int) st.st_size : 100;
1040 /* amount of time to wait depends on message size */
1042 /* give at least 5 minutes */
1044 } else if (bytes >= 90000) {
1045 /* a half hour is long enough */
1048 seconds = (bytes / 60) + 300;
1050 alarm((unsigned int) seconds);
1051 status = pidwait(child_id, 0);
1056 verbose_printf(", timed-out; terminated\n");
1063 verbose_printf(", success.\n");
1064 } else if ((status & 0xff00) == 0xff00) {
1065 verbose_printf(", system error\n");
1067 pidstatus(status, stdout, ", failed");
1070 return (status == 0 ? 0 : -1);
1079 kill(-child_id, SIGKILL);
1084 ** Get the `sender' from the envelope
1085 ** information ("From " line).
1088 get_sender(char *envelope, char **sender)
1092 unsigned char buffer[BUFSIZ];
1095 *sender = getcpy("");
1099 i = strlen("From ");
1100 strncpy(buffer, envelope + i, sizeof(buffer));
1101 buffer[sizeof buffer -1] = '\0'; /* ensure termination */
1102 if ((cp = strchr(buffer, '\n'))) {
1113 for (cp = buffer + strlen(buffer) - 1; cp >= buffer; cp--)
1119 *sender = getcpy(buffer);
1124 ** Copy message into a temporary file.
1125 ** While copying, it will do some header processing
1126 ** including the extraction of the envelope information.
1129 copy_message(int qd, char *tmpfil, int fold)
1131 int i, first = 1, fd1, fd2;
1132 char buffer[BUFSIZ];
1136 tfile = m_mktemp2("/tmp/", invo_name, &fd1, NULL);
1137 if (tfile == NULL) return -1;
1139 strncpy(tmpfil, tfile, BUFSIZ);
1142 while ((i = read(qd, buffer, sizeof(buffer))) > 0) {
1143 if (write(fd1, buffer, i) != i) {
1153 lseek(fd1, (off_t) 0, SEEK_SET);
1157 /* dup the fd for incoming message */
1158 if ((fd2 = dup(qd)) == -1) {
1163 /* now create a FILE pointer for it */
1164 if (!(qfp = fdopen(fd2, "r"))) {
1170 /* dup the fd for temporary file */
1171 if ((fd2 = dup(fd1)) == -1) {
1177 /* now create a FILE pointer for it */
1178 if (!(ffp = fdopen(fd2, "r+"))) {
1186 ** copy message into temporary file
1187 ** and massage the headers. Save
1188 ** a copy of the "From " line for later.
1190 i = strlen("From ");
1191 while (fgets(buffer, sizeof(buffer), qfp)) {
1194 if (strncmp(buffer, "From ", i)==0) {
1196 ** get copy of envelope information
1199 envelope = getcpy(buffer);
1201 /* Put the delivery date in message */
1223 lseek(fd1, (off_t) 0, SEEK_SET);
1234 ** Trim strings for pretty printing of debugging output
1239 char buffer[BUFSIZ*4];
1240 unsigned char *bp, *sp;
1246 /* copy string into temp buffer */
1247 strncpy(buffer, cp, sizeof(buffer));
1250 /* skip over leading whitespace */
1251 while (isspace(*bp)) {
1254 /* start at the end and zap trailing whitespace */
1255 for (sp = bp + strlen(bp) - 1; sp >= bp; sp--) {
1263 /* replace remaining whitespace with spaces */
1264 for (sp = bp; *sp; sp++) {
1273 ** Function for printing `verbose' messages.
1276 verbose_printf(char *fmt, ...)
1281 vfprintf(stdout, fmt, ap);
1288 ** Function for printing `verbose' delivery
1292 adorn(char *what, char *fmt, ...)
1298 eindex = errno; /* save the errno */
1299 fprintf(stdout, ", ");
1302 vfprintf(stdout, fmt, ap);
1307 fprintf(stdout, " %s: ", what);
1309 if ((s = strerror(eindex))) {
1310 fprintf(stdout, "%s", s);
1312 fprintf(stdout, "Error %d", eindex);
1316 fputc('\n', stdout);
1322 ** Function for printing `debug' messages.
1325 debug_printf(char *fmt, ...)
1330 vfprintf(stderr, fmt, ap);