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/nmh/lib/slocal"
14 * to their $HOME/.forward file.
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
24 #include <h/dropsbr.h>
25 #include <h/rcvmail.h>
26 #include <h/signals.h>
33 #include <sys/ioctl.h>
36 #ifdef INITGROUPS_HEADER
37 #include INITGROUPS_HEADER
39 /* On AIX 4.1, initgroups() is defined and even documented (giving the parameter
40 types as char* and int), but doesn't have a prototype in any of the system
41 header files. AIX 4.3, SunOS 4.1.3, and ULTRIX 4.2A have the same
43 extern int initgroups(char*, int);
46 /* This define is needed for Berkeley db v2 and above to
47 * make the header file expose the 'historical' ndbm APIs.
48 * We define it unconditionally because this is simple and
51 #define DB_DBM_HSEARCH 1
61 # define UTMP_FILE _PATH_UTMP
63 # define UTMP_FILE "/etc/utmp"
68 static struct swit switches[] = {
70 { "addr address", 0 },
76 { "sender address", 0 },
78 { "mailbox file", 0 },
80 { "home directory", -4 },
84 { "maildelivery file", 0 },
89 #define SUPPRESSDUP 10
91 #define NSUPPRESSDUP 11
92 { "nosuppressdup", 0 },
102 static int globbed = 0; /* have we built "vars" table yet? */
103 static int parsed = 0; /* have we built header field table yet */
104 static int utmped = 0; /* have we scanned umtp(x) file yet */
105 static int suppressdup = 0; /* are we suppressing duplicate messages? */
107 static int verbose = 0;
108 static int debug = 0;
110 static char *addr = NULL;
111 static char *user = NULL;
112 static char *info = NULL;
113 static char *file = NULL;
114 static char *sender = NULL;
115 static char *envelope = NULL; /* envelope information ("From " line) */
116 static char *mbox = NULL;
117 static char *home = NULL;
119 static struct passwd *pw; /* passwd file entry */
121 static char ddate[BUFSIZ]; /* record the delivery date */
124 static jmp_buf myctx;
126 /* flags for pair->p_flags */
128 #define P_ADR 0x01 /* field is address */
129 #define P_HID 0x02 /* special (fake) field */
141 * Lookup table for matching fields and patterns
142 * in messages. The rest of the table is added
143 * when the message is parsed.
145 static struct pair hdrs[NVEC + 1] = {
146 { "source", NULL, P_HID },
147 { "addr", NULL, P_HID },
148 { "Return-Path", NULL, P_ADR },
149 { "Reply-To", NULL, P_ADR },
150 { "From", NULL, P_ADR },
151 { "Sender", NULL, P_ADR },
152 { "To", NULL, P_ADR },
153 { "cc", NULL, P_ADR },
154 { "Resent-Reply-To", NULL, P_ADR },
155 { "Resent-From", NULL, P_ADR },
156 { "Resent-Sender", NULL, P_ADR },
157 { "Resent-To", NULL, P_ADR },
158 { "Resent-cc", NULL, P_ADR },
163 * The list of builtin variables to expand in a string
164 * before it is executed by the "pipe" or "qpipe" action.
166 static struct pair vars[] = {
167 { "sender", NULL, P_NIL },
168 { "address", NULL, P_NIL },
169 { "size", NULL, P_NIL },
170 { "reply-to", NULL, P_CHK },
171 { "info", NULL, P_NIL },
175 extern char **environ;
180 static int localmail (int, char *);
181 static int usr_delivery (int, char *, int);
182 static int split (char *, char **);
183 static int parse (int);
184 static void expand (char *, char *, int);
185 static void glob (int);
186 static struct pair *lookup (struct pair *, char *);
187 static int logged_in (void);
188 static int timely (char *, char *);
189 static int usr_file (int, char *, int);
190 static int usr_pipe (int, char *, char *, char **, int);
191 static int usr_folder (int, char *);
192 static RETSIGTYPE alrmser (int);
193 static void get_sender (char *, char **);
194 static int copy_message (int, char *, int);
195 static void verbose_printf (char *fmt, ...);
196 static void adorn (char *, char *, ...);
197 static void debug_printf (char *fmt, ...);
198 static int suppress_duplicates (int, char *);
199 static char *trim (char *);
203 main (int argc, char **argv)
207 char *cp, *mdlvr = NULL, buf[BUFSIZ];
208 char mailbox[BUFSIZ], tmpfil[BUFSIZ];
209 char **argp, **arguments;
212 setlocale(LC_ALL, "");
214 invo_name = r1bindex (*argv, '/');
216 /* foil search of user profile/context */
217 if (context_foil (NULL) == -1)
220 mts_init (invo_name);
221 arguments = getarguments (invo_name, argc, argv, 0);
224 /* Parse arguments */
225 while ((cp = *argp++)) {
227 switch (smatch (++cp, switches)) {
229 ambigsw (cp, switches);
232 adios (NULL, "-%s unknown", cp);
235 snprintf (buf, sizeof(buf),
236 "%s [switches] [address info sender]", invo_name);
237 print_help (buf, switches, 0);
240 print_version(invo_name);
244 if (!(addr = *argp++))/* allow -xyz arguments */
245 adios (NULL, "missing argument to %s", argp[-2]);
248 if (!(info = *argp++))/* allow -xyz arguments */
249 adios (NULL, "missing argument to %s", argp[-2]);
252 if (!(user = *argp++))/* allow -xyz arguments */
253 adios (NULL, "missing argument to %s", argp[-2]);
256 if (!(file = *argp++) || *file == '-')
257 adios (NULL, "missing argument to %s", argp[-2]);
260 if (!(sender = *argp++))/* allow -xyz arguments */
261 adios (NULL, "missing argument to %s", argp[-2]);
264 if (!(mbox = *argp++) || *mbox == '-')
265 adios (NULL, "missing argument to %s", argp[-2]);
268 if (!(home = *argp++) || *home == '-')
269 adios (NULL, "missing argument to %s", argp[-2]);
273 if (!(cp = *argp++) || *cp == '-')
274 adios (NULL, "missing argument to %s", argp[-2]);
276 adios (NULL, "only one maildelivery file at a time!");
299 switch (argp - (argv + 1)) {
315 addr = getusername ();
317 user = (cp = strchr(addr, '.')) ? ++cp : addr;
318 if ((pw = getpwnam (user)) == NULL)
319 adios (NULL, "no such local user as %s", user);
321 if (chdir (pw->pw_dir) == -1)
325 if (geteuid() == 0) {
327 initgroups (pw->pw_name, pw->pw_gid);
334 setbuf (stdin, NULL);
336 /* Record the delivery time */
337 if ((now = dlocaltimenow ()) == NULL)
338 adios (NULL, "unable to ascertain local time");
339 snprintf (ddate, sizeof(ddate), "Delivery-Date: %s\n", dtimenow (0));
342 * Copy the message to a temporary file
347 /* getting message from file */
348 if ((tempfd = open (file, O_RDONLY)) == -1)
349 adios (file, "unable to open");
351 debug_printf ("retrieving message from file \"%s\"\n", file);
352 if ((fd = copy_message (tempfd, tmpfil, 1)) == -1)
353 adios (NULL, "unable to create temporary file");
356 /* getting message from stdin */
358 debug_printf ("retrieving message from stdin\n");
359 if ((fd = copy_message (fileno (stdin), tmpfil, 1)) == -1)
360 adios (NULL, "unable to create temporary file");
364 debug_printf ("temporary file=\"%s\"\n", tmpfil);
367 * Delete the temp file now or a copy of every single message
368 * passed through slocal will be left in the /tmp directory until
369 * deleted manually! This unlink() used to be under an 'else'
370 * of the 'if (debug)' above, but since some people like to
371 * always run slocal with -debug and log the results, the /tmp
372 * directory would get choked over time. Of course, now that
373 * we always delete the temp file, the "temporary file=" message
374 * above is somewhat pointless -- someone watching debug output
375 * wouldn't have a chance to 'tail -f' or 'ln' the temp file
376 * before it's unlinked. The best thing would be to delay this
377 * unlink() until later if debug == 1, but I'll leave that for
378 * someone who cares about the temp-file-accessing functionality
379 * (they'll have to watch out for cases where we adios()).
383 if (!(fp = fdopen (fd, "r+")))
384 adios (NULL, "unable to access temporary file");
387 * If no sender given, extract it
388 * from envelope information. */
390 get_sender (envelope, &sender);
393 snprintf (mailbox, sizeof(mailbox), "%s/%s",
394 mmdfldir[0] ? mmdfldir : pw->pw_dir,
395 mmdflfil[0] ? mmdflfil : pw->pw_name);
402 debug_printf ("addr=\"%s\"\n", trim(addr));
403 debug_printf ("user=\"%s\"\n", trim(user));
404 debug_printf ("info=\"%s\"\n", trim(info));
405 debug_printf ("sender=\"%s\"\n", trim(sender));
406 debug_printf ("envelope=\"%s\"\n", envelope ? trim(envelope) : "");
407 debug_printf ("mbox=\"%s\"\n", trim(mbox));
408 debug_printf ("home=\"%s\"\n", trim(home));
409 debug_printf ("ddate=\"%s\"\n", trim(ddate));
410 debug_printf ("now=%02d:%02d\n\n", now->tw_hour, now->tw_min);
413 /* deliver the message */
414 status = localmail (fd, mdlvr);
416 done (status != -1 ? RCV_MOK : RCV_MBX);
422 * Main routine for delivering message.
426 localmail (int fd, char *mdlvr)
428 /* check if this message is a duplicate */
430 suppress_duplicates(fd, mdlvr ? mdlvr : ".maildelivery") == DONE)
433 /* delivery according to personal Maildelivery file */
434 if (usr_delivery (fd, mdlvr ? mdlvr : ".maildelivery", 0) != -1)
437 /* delivery according to global Maildelivery file */
438 if (usr_delivery (fd, maildelivery, 1) != -1)
442 verbose_printf ("(delivering to standard mail spool)\n");
444 /* last resort - deliver to standard mail spool */
446 return usr_file (fd, mbox, MBOX_FORMAT);
448 return usr_file (fd, mbox, MMDF_FORMAT);
453 #define matches(a,b) (stringdex (b, a) >= 0)
456 * Parse the delivery file, and process incoming message.
460 usr_delivery (int fd, char *delivery, int su)
462 int i, accept, status=1, won, vecp, next;
463 char *field, *pattern, *action, *result, *string;
464 char buffer[BUFSIZ], tmpbuf[BUFSIZ];
465 char *cp, *vec[NVEC];
470 /* open the delivery file */
471 if ((fp = fopen (delivery, "r")) == NULL)
474 /* check if delivery file has bad ownership or permissions */
475 if (fstat (fileno (fp), &st) == -1
476 || (st.st_uid != 0 && (su || st.st_uid != pw->pw_uid))
477 || st.st_mode & (S_IWGRP|S_IWOTH)) {
479 verbose_printf ("WARNING: %s has bad ownership/modes (su=%d,uid=%d,owner=%d,mode=0%o)\n",
480 delivery, su, (int) pw->pw_uid, (int) st.st_uid, (int) st.st_mode);
488 /* read and process delivery file */
489 while (fgets (buffer, sizeof(buffer), fp)) {
490 /* skip comments and empty lines */
491 if (*buffer == '#' || *buffer == '\n')
494 /* zap trailing newline */
495 if ((cp = strchr(buffer, '\n')))
498 /* split buffer into fields */
499 vecp = split (buffer, vec);
501 /* check for too few fields */
504 debug_printf ("WARNING: entry with only %d fields, skipping.\n", vecp);
509 for (i = 0; vec[i]; i++)
510 debug_printf ("vec[%d]: \"%s\"\n", i, trim(vec[i]));
519 /* find out how to perform the action */
524 * If previous condition failed, don't
525 * do this - else fall through
528 continue; /* else fall */
532 * If already delivered, skip this action. Else
533 * consider delivered if action is successful.
536 continue; /* else fall */
541 * Take action, and consider delivered if
542 * action is successful.
551 * Take action, but don't consider delivered, even
552 * if action is successful
559 if (!mh_strcasecmp (vec[5], "select")) {
560 if (logged_in () != -1)
562 if (vecp > 7 && timely (vec[6], vec[7]) == -1)
567 /* check if the field matches */
575 * "default" matches only if the message hasn't
576 * been delivered yet.
578 if (!mh_strcasecmp (field, "default")) {
585 /* parse message and build lookup table */
586 if (!parsed && parse (fd) == -1) {
591 * find header field in lookup table, and
592 * see if the pattern matches.
594 if ((p = lookup (hdrs, field)) && (p->p_value != NULL)
595 && matches (p->p_value, pattern)) {
604 /* find out the action to perform */
607 /* deliver to quoted pipe */
608 if (mh_strcasecmp (action, "qpipe"))
609 continue; /* else fall */
611 expand (tmpbuf, string, fd);
612 if (split (tmpbuf, vec) < 1)
614 status = usr_pipe (fd, tmpbuf, vec[0], vec, 0);
618 /* deliver to pipe */
619 if (mh_strcasecmp (action, "pipe"))
620 continue; /* else fall */
624 expand (tmpbuf, string, fd);
627 status = usr_pipe (fd, tmpbuf, "/bin/sh", vec + 2, 0);
632 if (!mh_strcasecmp (action, "file")) {
633 status = usr_file (fd, string, MBOX_FORMAT);
636 /* deliver to nmh folder */
637 else if (mh_strcasecmp (action, "folder"))
638 continue; /* else fall */
640 status = usr_folder (fd, string);
645 if (!mh_strcasecmp (action, "mmdf")) {
646 status = usr_file (fd, string, MMDF_FORMAT);
650 else if (mh_strcasecmp (action, "mbox"))
651 continue; /* else fall */
655 status = usr_file (fd, string, MBOX_FORMAT);
660 if (mh_strcasecmp (action, "destroy"))
666 if (status) next = 0; /* action failed, mark for 'N' result */
668 if (accept && status == 0)
673 return (won ? 0 : -1);
680 * Split buffer into fields (delimited by whitespace or
681 * comma's). Return the number of fields found.
685 split (char *cp, char **vec)
692 /* split into a maximum of NVEC fields */
693 for (i = 0; i <= NVEC;) {
696 /* zap any whitespace and comma's */
697 while (isspace (*s) || *s == ',')
700 /* end of buffer, time to leave */
704 /* get double quote text as a single field */
706 for (vec[i++] = ++s; *s && *s != '"'; s++) {
708 * Check for escaped double quote. We need
709 * to shift the string to remove slash.
717 if (*s == '"') /* zap trailing double quote */
722 if (*s == QUOTE && *++s != '"')
726 /* move forward to next field delimiter */
727 while (*s && !isspace (*s) && *s != ',')
737 * Parse the headers of a message, and build the
738 * lookup table for matching fields and patterns.
747 char name[NAMESZ], field[BUFSIZ];
754 /* get a new FILE pointer to message */
755 if ((fd1 = dup (fd)) == -1)
757 if ((in = fdopen (fd1, "r")) == NULL) {
763 /* add special entries to lookup table */
764 if ((p = lookup (hdrs, "source")))
765 p->p_value = getcpy (sender);
766 if ((p = lookup (hdrs, "addr")))
767 p->p_value = getcpy (addr);
770 * Scan the headers of the message and build
773 for (i = 0, state = FLD;;) {
774 switch (state = m_getfld (state, name, field, sizeof(field), in)) {
778 lp = add (field, NULL);
779 while (state == FLDPLUS) {
780 state = m_getfld (state, name, field, sizeof(field), in);
781 lp = add (field, lp);
783 for (p = hdrs; p->p_name; p++) {
784 if (!mh_strcasecmp (p->p_name, name)) {
785 if (!(p->p_flags & P_HID)) {
786 if ((cp = p->p_value)) {
787 if (p->p_flags & P_ADR) {
788 dp = cp + strlen (cp) - 1;
791 cp = add (",\n\t", cp);
796 p->p_value = add (lp, cp);
802 if (p->p_name == NULL && i < NVEC) {
803 p->p_name = getcpy (name);
820 advise (NULL, "format error in message");
824 advise (NULL, "internal error in m_getfld");
832 if ((p = lookup (vars, "reply-to"))) {
833 if ((q = lookup (hdrs, "reply-to")) == NULL || q->p_value == NULL)
834 q = lookup (hdrs, "from");
835 p->p_value = getcpy (q ? q->p_value : "");
836 p->p_flags &= ~P_CHK;
838 debug_printf ("vars[%d]: name=\"%s\" value=\"%s\"\n",
839 p - vars, p->p_name, trim(p->p_value));
842 for (p = hdrs; p->p_name; p++)
843 debug_printf ("hdrs[%d]: name=\"%s\" value=\"%s\"\n",
844 p - hdrs, p->p_name, p->p_value ? trim(p->p_value) : "");
855 * Expand any builtin variables such as $(sender),
856 * $(address), etc., in a string.
860 expand (char *s1, char *s2, int fd)
868 while ((c = *s2++)) {
869 if (c != '$' || *s2 != LPAREN) {
872 for (cp = ++s2; *s2 && *s2 != RPAREN; s2++)
879 if ((p = lookup (vars, cp))) {
880 if (!parsed && (p->p_flags & P_CHK))
883 strcpy (s1, p->p_value);
893 * Fill in the information missing from the "vars"
894 * table, which is necessary to expand any builtin
895 * variables in the string for a "pipe" or "qpipe"
909 if ((p = lookup (vars, "sender")))
910 p->p_value = getcpy (sender);
911 if ((p = lookup (vars, "address")))
912 p->p_value = getcpy (addr);
913 if ((p = lookup (vars, "size"))) {
914 snprintf (buffer, sizeof(buffer), "%d",
915 fstat (fd, &st) != -1 ? (int) st.st_size : 0);
916 p->p_value = getcpy (buffer);
918 if ((p = lookup (vars, "info")))
919 p->p_value = getcpy (info);
922 for (p = vars; p->p_name; p++)
923 debug_printf ("vars[%d]: name=\"%s\" value=\"%s\"\n",
924 p - vars, p->p_name, trim(p->p_value));
930 * Find a matching name in a lookup table. If found,
931 * return the "pairs" entry, else return NULL.
935 lookup (struct pair *pairs, char *key)
937 for (; pairs->p_name; pairs++)
938 if (!mh_strcasecmp (pairs->p_name, key))
946 * Check utmp(x) file to see if user is currently
961 while ((utp = getutent()) != NULL) {
963 #ifdef HAVE_STRUCT_UTMP_UT_TYPE
964 utp->ut_type == USER_PROCESS
968 && strncmp (user, utp->ut_name, sizeof(utp->ut_name)) == 0) {
972 return (utmped = DONE);
977 return (utmped = NOTOK);
989 if ((uf = fopen (UTMP_FILE, "r")) == NULL)
992 while (fread ((char *) &ut, sizeof(ut), 1, uf) == 1) {
993 if (ut.ut_name[0] != 0
994 && strncmp (user, ut.ut_name, sizeof(ut.ut_name)) == 0) {
998 return (utmped = DONE);
1003 return (utmped = NOTOK);
1007 #define check(t,a,b) if (t < a || t > b) return -1
1008 #define cmpar(h1,m1,h2,m2) if (h1 < h2 || (h1 == h2 && m1 < m2)) return 0
1011 timely (char *t1, char *t2)
1013 int t1hours, t1mins, t2hours, t2mins;
1015 if (sscanf (t1, "%d:%d", &t1hours, &t1mins) != 2)
1017 check (t1hours, 0, 23);
1018 check (t1mins, 0, 59);
1020 if (sscanf (t2, "%d:%d", &t2hours, &t2mins) != 2)
1022 check (t2hours, 0, 23);
1023 check (t2mins, 0, 59);
1025 cmpar (now->tw_hour, now->tw_min, t1hours, t1mins);
1026 cmpar (t2hours, t2mins, now->tw_hour, now->tw_min);
1033 * Deliver message by appending to a file.
1037 usr_file (int fd, char *mailbox, int mbx_style)
1042 verbose_printf ("delivering to file \"%s\"", mailbox);
1044 if (mbx_style == MBOX_FORMAT) {
1046 verbose_printf (" (mbox style)");
1050 verbose_printf (" (mmdf style)");
1054 /* open and lock the file */
1055 if ((md = mbx_open (mailbox, mbx_style, pw->pw_uid, pw->pw_gid, m_gmprot())) == -1) {
1057 adorn ("", "unable to open:");
1061 lseek (fd, (off_t) 0, SEEK_SET);
1063 /* append message to file */
1064 if (mbx_copy (mailbox, mbx_style, md, fd, mapping, NULL, verbose) == -1) {
1066 adorn ("", "error writing to:");
1070 /* close and unlock file */
1071 if (mbx_close (mailbox, md) == NOTOK) {
1073 adorn ("", "error closing:");
1078 verbose_printf (", success.\n");
1084 * Deliver message to a nmh folder.
1088 usr_folder (int fd, char *string)
1091 char folder[BUFSIZ], *vec[3];
1093 /* get folder name ready */
1095 strncpy(folder, string, sizeof(folder));
1097 snprintf(folder, sizeof(folder), "+%s", string);
1100 verbose_printf ("delivering to folder \"%s\"", folder + 1);
1102 vec[0] = "rcvstore";
1106 /* use rcvstore to put message in folder */
1107 status = usr_pipe (fd, "rcvstore", rcvstoreproc, vec, 1);
1111 * Currently, verbose status messages are handled by usr_pipe().
1115 verbose_printf (", success.\n");
1117 verbose_printf (", failed.\n");
1125 * Deliver message to a process.
1129 usr_pipe (int fd, char *cmd, char *pgm, char **vec, int suppress)
1132 int i, bytes, seconds, status;
1135 if (verbose && !suppress)
1136 verbose_printf ("delivering to pipe \"%s\"", cmd);
1138 lseek (fd, (off_t) 0, SEEK_SET);
1140 for (i = 0; (child_id = fork()) == -1 && i < 5; i++)
1147 adorn ("fork", "unable to");
1154 freopen ("/dev/null", "w", stdout);
1155 freopen ("/dev/null", "w", stderr);
1161 if ((fd = open ("/dev/tty", O_RDWR)) != -1) {
1162 ioctl (fd, TIOCNOTTY, NULL);
1165 #endif /* TIOCNOTTY */
1167 setpgid ((pid_t) 0, getpid ()); /* put in own process group */
1170 m_putenv ("USER", pw->pw_name);
1171 m_putenv ("HOME", pw->pw_dir);
1172 m_putenv ("SHELL", pw->pw_shell);
1178 /* parent process */
1179 if (!setjmp (myctx)) {
1180 SIGNAL (SIGALRM, alrmser);
1181 bytes = fstat (fd, &st) != -1 ? (int) st.st_size : 100;
1183 /* amount of time to wait depends on message size */
1185 /* give at least 5 minutes */
1187 } else if (bytes >= 90000) {
1188 /* a half hour is long enough */
1191 seconds = (bytes / 60) + 300;
1193 alarm ((unsigned int) seconds);
1194 status = pidwait (child_id, 0);
1199 verbose_printf (", success.\n");
1201 if ((status & 0xff00) == 0xff00)
1202 verbose_printf (", system error\n");
1204 pidstatus (status, stdout, ", failed");
1206 return (status == 0 ? 0 : -1);
1209 * Ruthlessly kill the child and anything
1210 * else in its process group.
1212 KILLPG(child_id, SIGKILL);
1214 verbose_printf (", timed-out; terminated\n");
1224 #ifndef RELIABLE_SIGNALS
1225 SIGNAL (SIGALRM, alrmser);
1228 longjmp (myctx, DONE);
1233 * Get the `sender' from the envelope
1234 * information ("From " line).
1238 get_sender (char *envelope, char **sender)
1242 unsigned char buffer[BUFSIZ];
1244 if (envelope == NULL) {
1245 *sender = getcpy ("");
1249 i = strlen ("From ");
1250 strncpy (buffer, envelope + i, sizeof(buffer));
1251 if ((cp = strchr(buffer, '\n'))) {
1261 for (cp = buffer + strlen (buffer) - 1; cp >= buffer; cp--)
1266 *sender = getcpy (buffer);
1271 * Copy message into a temporary file.
1272 * While copying, it will do some header processing
1273 * including the extraction of the envelope information.
1277 copy_message (int qd, char *tmpfil, int fold)
1279 int i, first = 1, fd1, fd2;
1280 char buffer[BUFSIZ];
1284 tfile = m_mktemp2(NULL, invo_name, &fd1, NULL);
1285 if (tfile == NULL) return -1;
1287 strncpy (tmpfil, tfile, BUFSIZ);
1290 while ((i = read (qd, buffer, sizeof(buffer))) > 0)
1291 if (write (fd1, buffer, i) != i) {
1299 lseek (fd1, (off_t) 0, SEEK_SET);
1303 /* dup the fd for incoming message */
1304 if ((fd2 = dup (qd)) == -1) {
1309 /* now create a FILE pointer for it */
1310 if ((qfp = fdopen (fd2, "r")) == NULL) {
1316 /* dup the fd for temporary file */
1317 if ((fd2 = dup (fd1)) == -1) {
1323 /* now create a FILE pointer for it */
1324 if ((ffp = fdopen (fd2, "r+")) == NULL) {
1332 * copy message into temporary file
1333 * and massage the headers. Save
1334 * a copy of the "From " line for later.
1336 i = strlen ("From ");
1337 while (fgets (buffer, sizeof(buffer), qfp)) {
1340 if (!strncmp (buffer, "From ", i)) {
1342 char *fp, *cp, *hp, *ep;
1344 /* get copy of envelope information ("From " line) */
1345 envelope = getcpy (buffer);
1348 /* First go ahead and put "From " line in message */
1349 fputs (buffer, ffp);
1356 * Now create a "Return-Path:" line
1357 * from the "From " line.
1359 hp = cp = strchr(fp = envelope + i, ' ');
1360 while ((hp = strchr(++hp, 'r')))
1361 if (uprf (hp, "remote from")) {
1362 hp = strrchr(hp, ' ');
1366 /* return path for UUCP style addressing */
1367 ep = strchr(++hp, '\n');
1368 snprintf (buffer, sizeof(buffer), "Return-Path: %.*s!%.*s\n",
1369 (int)(ep - hp), hp, (int)(cp - fp), fp);
1371 /* return path for standard domain addressing */
1372 snprintf (buffer, sizeof(buffer), "Return-Path: %.*s\n",
1373 (int)(cp - fp), fp);
1376 /* Add Return-Path header to message */
1377 fputs (buffer, ffp);
1381 /* Put the delivery date in message */
1390 fputs (buffer, ffp);
1402 lseek (fd1, (off_t) 0, SEEK_SET);
1414 * Trim strings for pretty printing of debugging output
1420 char buffer[BUFSIZ*4];
1421 unsigned char *bp, *sp;
1426 /* copy string into temp buffer */
1427 strncpy (buffer, cp, sizeof(buffer));
1430 /* skip over leading whitespace */
1431 while (isspace(*bp))
1434 /* start at the end and zap trailing whitespace */
1435 for (sp = bp + strlen(bp) - 1; sp >= bp; sp--) {
1442 /* replace remaining whitespace with spaces */
1443 for (sp = bp; *sp; sp++)
1447 /* now return a copy */
1452 * Function for printing `verbose' messages.
1456 verbose_printf (char *fmt, ...)
1461 vfprintf (stdout, fmt, ap);
1464 fflush (stdout); /* now flush output */
1469 * Function for printing `verbose' delivery
1474 adorn (char *what, char *fmt, ...)
1480 eindex = errno; /* save the errno */
1481 fprintf (stdout, ", ");
1484 vfprintf (stdout, fmt, ap);
1489 fprintf (stdout, " %s: ", what);
1490 if ((s = strerror (eindex)))
1491 fprintf (stdout, "%s", s);
1493 fprintf (stdout, "Error %d", eindex);
1496 fputc ('\n', stdout);
1502 * Function for printing `debug' messages.
1506 debug_printf (char *fmt, ...)
1511 vfprintf (stderr, fmt, ap);
1517 * Check ndbm/db file(s) to see if the Message-Id of this
1518 * message matches the Message-Id of a previous message,
1519 * so we can discard it. If it doesn't match, we add the
1520 * Message-Id of this message to the ndbm/db file.
1523 suppress_duplicates (int fd, char *file)
1525 int fd1, lockfd, state, result;
1526 char *cp, buf[BUFSIZ], name[NAMESZ];
1531 if ((fd1 = dup (fd)) == -1)
1533 if (!(in = fdopen (fd1, "r"))) {
1539 for (state = FLD;;) {
1540 state = m_getfld (state, name, buf, sizeof(buf), in);
1545 /* Search for the message ID */
1546 if (mh_strcasecmp (name, "Message-ID")) {
1547 while (state == FLDPLUS)
1548 state = m_getfld (state, name, buf, sizeof(buf), in);
1552 cp = add (buf, NULL);
1553 while (state == FLDPLUS) {
1554 state = m_getfld (state, name, buf, sizeof(buf), in);
1557 key.dptr = trimcpy (cp);
1558 key.dsize = strlen (key.dptr) + 1;
1562 if (!(db = dbm_open (file, O_RDWR | O_CREAT, 0600))) {
1563 advise (file, "unable to perform dbm_open on");
1569 * Since it is difficult to portable
1570 * lock a ndbm file, we will open and
1571 * lock the Maildelivery file instead.
1572 * This will fail if your Maildelivery
1573 * file doesn't exist.
1575 if ((lockfd = lkopen(file, O_RDWR, 0)) == -1) {
1576 advise (file, "unable to perform file locking on");
1581 value = dbm_fetch (db, key);
1584 verbose_printf ("Message-ID: %s\n already received on %s",
1588 value.dptr = ddate + sizeof("Delivery-Date:");
1589 value.dsize = strlen(value.dptr) + 1;
1590 if (dbm_store (db, key, value, DBM_INSERT))
1591 advise (file, "possibly corrupt file");
1596 lkclose(lockfd, file);