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 },
75 char *version=VERSION;
77 static int globbed = 0; /* have we built "vars" table yet? */
78 static int parsed = 0; /* have we built header field table yet */
80 static int verbose = 0;
83 static char *addr = NULL;
84 static char *user = NULL;
85 static char *info = NULL;
86 static char *file = NULL;
87 static char *sender = NULL;
88 static char *envelope = NULL; /* envelope information ("From " line) */
89 static char *mbox = NULL;
90 static char *home = NULL;
92 static struct passwd *pw; /* passwd file entry */
94 static char ddate[BUFSIZ]; /* record the delivery date */
97 volatile sig_atomic_t eflag = 0; /* flag to indecate interrupt */
98 static volatile pid_t child_id;
100 /* flags for pair->p_flags */
102 #define P_ADR 0x01 /* field is address */
103 #define P_HID 0x02 /* special (fake) field */
115 ** Lookup table for matching fields and patterns
116 ** in messages. The rest of the table is added
117 ** when the message is parsed.
119 static struct pair hdrs[NVEC + 1] = {
120 { "source", NULL, P_HID },
121 { "addr", NULL, P_HID },
122 { "Return-Path", NULL, P_ADR },
123 { "Reply-To", NULL, P_ADR },
124 { "From", NULL, P_ADR },
125 { "Sender", NULL, P_ADR },
126 { "To", NULL, P_ADR },
127 { "cc", NULL, P_ADR },
128 { "Resent-Reply-To", NULL, P_ADR },
129 { "Resent-From", NULL, P_ADR },
130 { "Resent-Sender", NULL, P_ADR },
131 { "Resent-To", NULL, P_ADR },
132 { "Resent-Cc", NULL, P_ADR },
137 ** The list of builtin variables to expand in a string
138 ** before it is executed by the "pipe" or "qpipe" action.
140 static struct pair vars[] = {
141 { "sender", NULL, P_NIL },
142 { "address", NULL, P_NIL },
143 { "size", NULL, P_NIL },
144 { "reply-to", NULL, P_CHK },
145 { "info", NULL, P_NIL },
149 extern char **environ;
154 static int localmail(int, char *);
155 static int usr_delivery(int, char *, int);
156 static int split(char *, char **);
157 static int parse(int);
158 static void expand(char *, char *, int);
159 static void glob(int);
160 static struct pair *lookup(struct pair *, char *);
161 static int usr_file(int, char *);
162 static int usr_pipe(int, char *, char *, char **, int);
163 static int usr_folder(int, char *);
164 static void alrmser(int);
165 static void get_sender(char *, char **);
166 static int copy_message(int, char *, int);
167 static void verbose_printf(char *fmt, ...);
168 static void adorn(char *, char *, ...);
169 static void debug_printf(char *fmt, ...);
170 static char *trimstr(char *);
174 main(int argc, char **argv)
178 char *cp, *mdlvr = NULL, buf[BUFSIZ];
179 char mailbox[BUFSIZ], tmpfil[BUFSIZ];
180 char **argp, **arguments;
182 setlocale(LC_ALL, "");
183 invo_name = mhbasename(*argv);
185 arguments = getarguments(invo_name, argc, argv, 0);
188 /* Parse arguments */
189 while ((cp = *argp++)) {
191 switch (smatch(++cp, switches)) {
193 ambigsw(cp, switches);
196 adios(EX_USAGE, NULL, "-%s unknown", cp);
199 snprintf(buf, sizeof(buf), "%s [switches] [address info sender]", invo_name);
200 print_help(buf, switches, 0);
201 exit(argc == 2 ? EX_OK : EX_USAGE);
203 print_version(invo_name);
204 exit(argc == 2 ? EX_OK : EX_USAGE);
207 if (!(addr = *argp++)) {
208 /* allow -xyz arguments */
209 adios(EX_USAGE, NULL, "missing argument to %s",
214 if (!(info = *argp++)) {
215 /* allow -xyz arguments */
216 adios(EX_USAGE, NULL, "missing argument to %s",
221 if (!(user = *argp++)) {
222 /* allow -xyz arguments */
223 adios(EX_USAGE, NULL, "missing argument to %s",
228 if (!(file = *argp++) || *file == '-') {
229 adios(EX_USAGE, NULL, "missing argument to %s",
234 if (!(sender = *argp++)) {
235 /* allow -xyz arguments */
236 adios(EX_USAGE, NULL, "missing argument to %s",
241 if (!(mbox = *argp++) || *mbox == '-') {
242 adios(EX_USAGE, NULL, "missing argument to %s",
247 if (!(home = *argp++) || *home == '-') {
248 adios(EX_USAGE, NULL, "missing argument to %s",
254 if (!(cp = *argp++) || *cp == '-') {
255 adios(EX_USAGE, NULL, "missing argument to %s",
259 adios(EX_USAGE, NULL, "only one maildelivery file at a time!");
277 switch (argp - (argv + 1)) {
291 addr = getusername();
294 user = (cp = strchr(addr, '.')) ? ++cp : addr;
296 if (!(pw = getpwnam(user))) {
297 adios(EX_NOUSER, NULL, "no such local user as %s", user);
300 if (chdir(pw->pw_dir) == -1) {
305 if (geteuid() == 0) {
307 initgroups(pw->pw_name, pw->pw_gid);
317 /* Record the delivery time */
318 if (!(now = dlocaltimenow())) {
319 adios(EX_OSERR, NULL, "unable to ascertain local time");
321 snprintf(ddate, sizeof(ddate), "Delivery-Date: %s\n", dtimenow());
324 ** Copy the message to a temporary file
329 /* getting message from file */
330 if ((tempfd = open(file, O_RDONLY)) == -1) {
331 adios(EX_IOERR, file, "unable to open");
334 debug_printf("retrieving message from file \"%s\"\n",
337 if ((fd = copy_message(tempfd, tmpfil, 1)) == -1) {
338 adios(EX_CANTCREAT, NULL, "unable to create temporary file");
342 /* getting message from stdin */
344 debug_printf("retrieving message from stdin\n");
346 if ((fd = copy_message(fileno(stdin), tmpfil, 1)) == -1) {
347 adios(EX_CANTCREAT, NULL, "unable to create temporary file");
352 debug_printf("temporary file=\"%s\"\n", tmpfil);
356 ** Delete the temp file now or a copy of every single message
357 ** passed through slocal will be left in the /tmp directory until
358 ** deleted manually! This unlink() used to be under an 'else'
359 ** of the 'if (debug)' above, but since some people like to
360 ** always run slocal with -debug and log the results, the /tmp
361 ** directory would get choked over time. Of course, now that
362 ** we always delete the temp file, the "temporary file=" message
363 ** above is somewhat pointless -- someone watching debug output
364 ** wouldn't have a chance to 'tail -f' or 'ln' the temp file
365 ** before it's unlinked. The best thing would be to delay this
366 ** unlink() until later if debug == 1, but I'll leave that for
367 ** someone who cares about the temp-file-accessing functionality
368 ** (they'll have to watch out for cases where we adios()).
372 if (!(fp = fdopen(fd, "r+"))) {
373 adios(EX_IOERR, NULL, "unable to access temporary file");
376 /* If no sender given, extract it from envelope information. */
378 get_sender(envelope, &sender);
381 snprintf(mailbox, sizeof(mailbox), "%s/%s",
382 mailspool, pw->pw_name);
390 debug_printf("addr=\"%s\"\n", trimstr(addr));
391 debug_printf("user=\"%s\"\n", trimstr(user));
392 debug_printf("info=\"%s\"\n", trimstr(info));
393 debug_printf("sender=\"%s\"\n", trimstr(sender));
394 debug_printf("envelope=\"%s\"\n",
395 envelope ? trimstr(envelope) : "");
396 debug_printf("mbox=\"%s\"\n", trimstr(mbox));
397 debug_printf("home=\"%s\"\n", trimstr(home));
398 debug_printf("ddate=\"%s\"\n", trimstr(ddate));
399 debug_printf("now=%02d:%02d\n\n", now->tw_hour, now->tw_min);
402 /* deliver the message */
403 status = localmail(fd, mdlvr);
405 return (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.
729 struct field f = {{0}};
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 = mh_xstrdup(sender);
753 if ((p = lookup(hdrs, "addr"))) {
754 p->p_value = mh_xstrdup(addr);
758 ** Scan the headers of the message and build a lookup table.
760 for (i = 0, state = FLD2;;) {
761 switch (state = m_getfld2(state, &f, in)) {
767 lp = mh_xstrdup(f.value);
768 for (p = hdrs; p->p_name; p++) {
769 if (mh_strcasecmp(p->p_name, f.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 = mh_xstrdup(f.name);
803 advise(NULL, "format error in message");
807 advise(NULL, "internal error in m_getfld");
815 if ((p = lookup(vars, "reply-to"))) {
816 if (!(q = lookup(hdrs, "reply-to")) || !q->p_value) {
817 q = lookup(hdrs, "from");
819 p->p_value = mh_xstrdup(q ? q->p_value : "");
820 p->p_flags &= ~P_CHK;
822 debug_printf("vars[%d]: name=\"%s\" value=\"%s\"\n",
823 p - vars, p->p_name, trimstr(p->p_value));
827 for (p = hdrs; p->p_name; p++) {
828 debug_printf("hdrs[%d]: name=\"%s\" value=\"%s\"\n",
830 p->p_value ? trimstr(p->p_value) : "");
838 ** Expand any builtin variables such as $(sender),
839 ** $(address), etc., in a string.
842 expand(char *s1, char *s2, int fd)
850 while ((c = *s2++)) {
851 if (c != '$' || *s2 != '(') {
854 for (cp = ++s2; *s2 && *s2 != ')'; s2++) {
862 if ((p = lookup(vars, cp))) {
863 if (!parsed && (p->p_flags & P_CHK)) {
866 strcpy(s1, p->p_value);
876 ** Fill in the information missing from the "vars"
877 ** table, which is necessary to expand any builtin
878 ** variables in the string for a "pipe" or "qpipe"
891 if ((p = lookup(vars, "sender"))) {
892 p->p_value = mh_xstrdup(sender);
894 if ((p = lookup(vars, "address"))) {
895 p->p_value = mh_xstrdup(addr);
897 if ((p = lookup(vars, "size"))) {
898 snprintf(buffer, sizeof(buffer), "%d",
899 fstat(fd, &st) != -1 ? (int) st.st_size : 0);
900 p->p_value = mh_xstrdup(buffer);
902 if ((p = lookup(vars, "info"))) {
903 p->p_value = mh_xstrdup(info);
906 for (p = vars; p->p_name; p++) {
907 debug_printf("vars[%d]: name=\"%s\" value=\"%s\"\n",
908 p - vars, p->p_name, trimstr(p->p_value));
915 ** Find a matching name in a lookup table. If found,
916 ** return the "pairs" entry, else return NULL.
919 lookup(struct pair *pairs, char *key)
921 for (; pairs->p_name; pairs++) {
922 if (!mh_strcasecmp(pairs->p_name, key)) {
931 ** Deliver message by appending to a file, using rcvpack(1).
934 usr_file(int fd, char *mailbox)
939 verbose_printf("delivering to file \"%s\" (mbox style)",
946 return usr_pipe(fd, "rcvpack", "rcvpack", vec, 1);
951 ** Deliver message to a nmh folder, using rcvstore(1).
954 usr_folder(int fd, char *string)
956 char folder[BUFSIZ], *vec[3];
958 /* get folder name ready */
959 if (*string == '+') {
960 strncpy(folder, string, sizeof(folder));
962 snprintf(folder, sizeof(folder), "+%s", string);
965 verbose_printf("delivering to folder \"%s\"", folder + 1);
971 return usr_pipe(fd, "rcvstore", "rcvstore", vec, 1);
975 ** Deliver message to a process.
978 usr_pipe(int fd, char *cmd, char *pgm, char **vec, int suppress)
980 int bytes, seconds, status, n;
984 if (verbose && !suppress) {
985 verbose_printf("delivering to pipe \"%s\"", cmd);
987 lseek(fd, (off_t) 0, SEEK_SET);
989 switch ((child_id = fork())) {
993 adorn("fork", "unable to");
1002 freopen("/dev/null", "w", stdout);
1003 freopen("/dev/null", "w", stderr);
1007 for (n=4; n<OPEN_MAX; n++) {
1012 if ((fd = open("/dev/tty", O_RDWR)) != -1) {
1013 ioctl(fd, TIOCNOTTY, NULL);
1016 #endif /* TIOCNOTTY */
1018 /* put in own process group */
1019 setpgid((pid_t) 0, getpid());
1021 path = getenv("PATH");
1023 m_putenv("USER", pw->pw_name);
1024 m_putenv("HOME", pw->pw_dir);
1025 m_putenv("SHELL", pw->pw_shell);
1026 m_putenv("PATH", path);
1032 /* parent process */
1033 SIGNAL(SIGALRM, alrmser);
1034 bytes = fstat(fd, &st) != -1 ? (int) st.st_size : 100;
1036 /* amount of time to wait depends on message size */
1038 /* give at least 5 minutes */
1040 } else if (bytes >= 90000) {
1041 /* a half hour is long enough */
1044 seconds = (bytes / 60) + 300;
1046 alarm((unsigned int) seconds);
1047 status = pidwait(child_id, 0);
1052 verbose_printf(", timed-out; terminated\n");
1059 verbose_printf(", success.\n");
1060 } else if ((status & 0xff00) == 0xff00) {
1061 verbose_printf(", system error\n");
1063 pidstatus(status, stdout, ", failed");
1066 return (status == 0 ? 0 : -1);
1075 kill(-child_id, SIGKILL);
1080 ** Get the `sender' from the envelope
1081 ** information ("From " line).
1084 get_sender(char *envelope, char **sender)
1088 unsigned char buffer[BUFSIZ];
1091 *sender = mh_xstrdup("");
1095 i = strlen("From ");
1096 strncpy(buffer, envelope + i, sizeof(buffer));
1097 buffer[sizeof buffer -1] = '\0'; /* ensure termination */
1098 if ((cp = strchr(buffer, '\n'))) {
1109 for (cp = buffer + strlen(buffer) - 1; cp >= buffer; cp--)
1115 *sender = mh_xstrdup(buffer);
1120 ** Copy message into a temporary file.
1121 ** While copying, it will do some header processing
1122 ** including the extraction of the envelope information.
1125 copy_message(int qd, char *tmpfil, int fold)
1127 int i, first = 1, fd1, fd2;
1128 char buffer[BUFSIZ];
1132 tfile = m_mktemp2("/tmp/", invo_name, &fd1, NULL);
1133 if (tfile == NULL) return -1;
1135 strncpy(tmpfil, tfile, BUFSIZ);
1138 while ((i = read(qd, buffer, sizeof(buffer))) > 0) {
1139 if (write(fd1, buffer, i) != i) {
1149 lseek(fd1, (off_t) 0, SEEK_SET);
1153 /* dup the fd for incoming message */
1154 if ((fd2 = dup(qd)) == -1) {
1159 /* now create a FILE pointer for it */
1160 if (!(qfp = fdopen(fd2, "r"))) {
1166 /* dup the fd for temporary file */
1167 if ((fd2 = dup(fd1)) == -1) {
1173 /* now create a FILE pointer for it */
1174 if (!(ffp = fdopen(fd2, "r+"))) {
1182 ** copy message into temporary file
1183 ** and massage the headers. Save
1184 ** a copy of the "From " line for later.
1186 i = strlen("From ");
1187 while (fgets(buffer, sizeof(buffer), qfp)) {
1190 if (strncmp(buffer, "From ", i)==0) {
1192 ** get copy of envelope information
1195 envelope = mh_xstrdup(buffer);
1197 /* Put the delivery date in message */
1219 lseek(fd1, (off_t) 0, SEEK_SET);
1230 ** Trim strings for pretty printing of debugging output
1235 char buffer[BUFSIZ*4];
1236 unsigned char *bp, *sp;
1242 /* copy string into temp buffer */
1243 strncpy(buffer, cp, sizeof(buffer));
1246 /* skip over leading whitespace */
1247 while (isspace(*bp)) {
1250 /* start at the end and zap trailing whitespace */
1251 for (sp = bp + strlen(bp) - 1; sp >= bp; sp--) {
1259 /* replace remaining whitespace with spaces */
1260 for (sp = bp; *sp; sp++) {
1265 return mh_xstrdup(bp);
1269 ** Function for printing `verbose' messages.
1272 verbose_printf(char *fmt, ...)
1277 vfprintf(stdout, fmt, ap);
1284 ** Function for printing `verbose' delivery
1288 adorn(char *what, char *fmt, ...)
1294 eindex = errno; /* save the errno */
1295 fprintf(stdout, ", ");
1298 vfprintf(stdout, fmt, ap);
1303 fprintf(stdout, " %s: ", what);
1305 if ((s = strerror(eindex))) {
1306 fprintf(stdout, "%s", s);
1308 fprintf(stdout, "Error %d", eindex);
1312 fputc('\n', stdout);
1318 ** Function for printing `debug' messages.
1321 debug_printf(char *fmt, ...)
1326 vfprintf(stderr, fmt, ap);