3 * slocal.c -- asynchronously filter and deliver new mail
7 * This code is Copyright (c) 2002, by the authors of nmh. See the
8 * COPYRIGHT file in the root directory of the nmh distribution for
9 * complete copyright information.
13 * Under sendmail, users should add the line
15 * "| /usr/local/nmh/lib/slocal"
17 * to their $HOME/.forward file.
19 * Under MMDF-I, users should (symbolically) link
20 * /usr/local/nmh/lib/slocal to $HOME/bin/rcvmail.
24 /* Changed to use getutent() and friends. Assumes that when getutent() exists,
25 * a number of other things also exist. Please check.
26 * Ruud de Rooij <ruud@ruud.org> Sun, 28 May 2000 17:28:55 +0200
30 #include <h/dropsbr.h>
31 #include <h/rcvmail.h>
32 #include <h/signals.h>
38 #include <sys/ioctl.h>
41 #ifdef INITGROUPS_HEADER
42 #include INITGROUPS_HEADER
44 /* On AIX 4.1, initgroups() is defined and even documented (giving the parameter
45 types as char* and int), but doesn't have a prototype in any of the system
46 header files. AIX 4.3, SunOS 4.1.3, and ULTRIX 4.2A have the same
48 extern int initgroups(char*, int);
52 #ifdef HAVE_DB1_NDBM_H
55 #ifdef HAVE_GDBM_NDBM_H
56 #include <gdbm/ndbm.h>
67 # define UTMP_FILE _PATH_UTMP
69 # define UTMP_FILE "/etc/utmp"
74 static struct swit switches[] = {
76 { "addr address", 0 },
82 { "sender address", 0 },
84 { "mailbox file", 0 },
86 { "home directory", -4 },
90 { "maildelivery file", 0 },
95 #define SUPPRESSDUP 10
97 #define NSUPPRESSDUP 11
98 { "nosuppressdup", 0 },
108 static int globbed = 0; /* have we built "vars" table yet? */
109 static int parsed = 0; /* have we built header field table yet */
110 static int utmped = 0; /* have we scanned umtp(x) file yet */
111 static int suppressdup = 0; /* are we suppressing duplicate messages? */
113 static int verbose = 0;
114 static int debug = 0;
116 static char *addr = NULL;
117 static char *user = NULL;
118 static char *info = NULL;
119 static char *file = NULL;
120 static char *sender = NULL;
121 static char *envelope = NULL; /* envelope information ("From " line) */
122 static char *mbox = NULL;
123 static char *home = NULL;
125 static struct passwd *pw; /* passwd file entry */
127 static char ddate[BUFSIZ]; /* record the delivery date */
130 static jmp_buf myctx;
132 /* flags for pair->p_flags */
134 #define P_ADR 0x01 /* field is address */
135 #define P_HID 0x02 /* special (fake) field */
147 * Lookup table for matching fields and patterns
148 * in messages. The rest of the table is added
149 * when the message is parsed.
151 static struct pair hdrs[NVEC + 1] = {
152 { "source", NULL, P_HID },
153 { "addr", NULL, P_HID },
154 { "Return-Path", NULL, P_ADR },
155 { "Reply-To", NULL, P_ADR },
156 { "From", NULL, P_ADR },
157 { "Sender", NULL, P_ADR },
158 { "To", NULL, P_ADR },
159 { "cc", NULL, P_ADR },
160 { "Resent-Reply-To", NULL, P_ADR },
161 { "Resent-From", NULL, P_ADR },
162 { "Resent-Sender", NULL, P_ADR },
163 { "Resent-To", NULL, P_ADR },
164 { "Resent-cc", NULL, P_ADR },
169 * The list of builtin variables to expand in a string
170 * before it is executed by the "pipe" or "qpipe" action.
172 static struct pair vars[] = {
173 { "sender", NULL, P_NIL },
174 { "address", NULL, P_NIL },
175 { "size", NULL, P_NIL },
176 { "reply-to", NULL, P_CHK },
177 { "info", NULL, P_NIL },
181 extern char **environ;
186 static int localmail (int, char *);
187 static int usr_delivery (int, char *, int);
188 static int split (char *, char **);
189 static int parse (int);
190 static void expand (char *, char *, int);
191 static void glob (int);
192 static struct pair *lookup (struct pair *, char *);
193 static int logged_in (void);
194 static int timely (char *, char *);
195 static int usr_file (int, char *, int);
196 static int usr_pipe (int, char *, char *, char **, int);
197 static int usr_folder (int, char *);
198 static RETSIGTYPE alrmser (int);
199 static void get_sender (char *, char **);
200 static int copy_message (int, char *, int);
201 static void verbose_printf (char *fmt, ...);
202 static void adorn (char *, char *, ...);
203 static void debug_printf (char *fmt, ...);
204 static int suppress_duplicates (int, char *);
205 static char *trim (char *);
209 main (int argc, char **argv)
213 char *cp, *mdlvr = NULL, buf[BUFSIZ];
214 char mailbox[BUFSIZ], tmpfil[BUFSIZ];
215 char **argp, **arguments;
218 setlocale(LC_ALL, "");
220 invo_name = r1bindex (*argv, '/');
222 /* foil search of user profile/context */
223 if (context_foil (NULL) == -1)
226 mts_init (invo_name);
227 arguments = getarguments (invo_name, argc, argv, 0);
230 /* Parse arguments */
231 while ((cp = *argp++)) {
233 switch (smatch (++cp, switches)) {
235 ambigsw (cp, switches);
238 adios (NULL, "-%s unknown", cp);
241 snprintf (buf, sizeof(buf),
242 "%s [switches] [address info sender]", invo_name);
243 print_help (buf, switches, 0);
246 print_version(invo_name);
250 if (!(addr = *argp++))/* allow -xyz arguments */
251 adios (NULL, "missing argument to %s", argp[-2]);
254 if (!(info = *argp++))/* allow -xyz arguments */
255 adios (NULL, "missing argument to %s", argp[-2]);
258 if (!(user = *argp++))/* allow -xyz arguments */
259 adios (NULL, "missing argument to %s", argp[-2]);
262 if (!(file = *argp++) || *file == '-')
263 adios (NULL, "missing argument to %s", argp[-2]);
266 if (!(sender = *argp++))/* allow -xyz arguments */
267 adios (NULL, "missing argument to %s", argp[-2]);
270 if (!(mbox = *argp++) || *mbox == '-')
271 adios (NULL, "missing argument to %s", argp[-2]);
274 if (!(home = *argp++) || *home == '-')
275 adios (NULL, "missing argument to %s", argp[-2]);
279 if (!(cp = *argp++) || *cp == '-')
280 adios (NULL, "missing argument to %s", argp[-2]);
282 adios (NULL, "only one maildelivery file at a time!");
305 switch (argp - (argv + 1)) {
321 addr = getusername ();
323 user = (cp = strchr(addr, '.')) ? ++cp : addr;
324 if ((pw = getpwnam (user)) == NULL)
325 adios (NULL, "no such local user as %s", user);
327 if (chdir (pw->pw_dir) == -1)
331 if (geteuid() == 0) {
333 initgroups (pw->pw_name, pw->pw_gid);
340 setbuf (stdin, NULL);
342 /* Record the delivery time */
343 if ((now = dlocaltimenow ()) == NULL)
344 adios (NULL, "unable to ascertain local time");
345 snprintf (ddate, sizeof(ddate), "Delivery-Date: %s\n", dtimenow (0));
348 * Copy the message to a temporary file
353 /* getting message from file */
354 if ((tempfd = open (file, O_RDONLY)) == -1)
355 adios (file, "unable to open");
357 debug_printf ("retrieving message from file \"%s\"\n", file);
358 if ((fd = copy_message (tempfd, tmpfil, 1)) == -1)
359 adios (NULL, "unable to create temporary file");
362 /* getting message from stdin */
364 debug_printf ("retrieving message from stdin\n");
365 if ((fd = copy_message (fileno (stdin), tmpfil, 1)) == -1)
366 adios (NULL, "unable to create temporary file");
370 debug_printf ("temporary file=\"%s\"\n", tmpfil);
372 /* Delete the temp file now or a copy of every single message passed through
373 slocal will be left in the /tmp directory until deleted manually! This
374 unlink() used to be under an 'else' of the 'if (debug)' above, but since
375 some people like to always run slocal with -debug and log the results,
376 the /tmp directory would get choked over time. Of course, now that we
377 always delete the temp file, the "temporary file=" message above is
378 somewhat pointless -- someone watching debug output wouldn't have a
379 chance to 'tail -f' or 'ln' the temp file before it's unlinked. The best
380 thing would be to delay this unlink() until later if debug == 1, but I'll
381 leave that for someone who cares about the temp-file-accessing
382 functionality (they'll have to watch out for cases where we adios()). */
385 if (!(fp = fdopen (fd, "r+")))
386 adios (NULL, "unable to access temporary file");
389 * If no sender given, extract it
390 * from envelope information. */
392 get_sender (envelope, &sender);
395 snprintf (mailbox, sizeof(mailbox), "%s/%s",
396 mmdfldir[0] ? mmdfldir : pw->pw_dir,
397 mmdflfil[0] ? mmdflfil : pw->pw_name);
404 debug_printf ("addr=\"%s\"\n", trim(addr));
405 debug_printf ("user=\"%s\"\n", trim(user));
406 debug_printf ("info=\"%s\"\n", trim(info));
407 debug_printf ("sender=\"%s\"\n", trim(sender));
408 debug_printf ("envelope=\"%s\"\n", envelope ? trim(envelope) : "");
409 debug_printf ("mbox=\"%s\"\n", trim(mbox));
410 debug_printf ("home=\"%s\"\n", trim(home));
411 debug_printf ("ddate=\"%s\"\n", trim(ddate));
412 debug_printf ("now=%02d:%02d\n\n", now->tw_hour, now->tw_min);
415 /* deliver the message */
416 status = localmail (fd, mdlvr);
418 return done (status != -1 ? RCV_MOK : RCV_MBX);
423 * Main routine for delivering message.
427 localmail (int fd, char *mdlvr)
429 /* check if this message is a duplicate */
431 suppress_duplicates(fd, mdlvr ? mdlvr : ".maildelivery") == DONE)
434 /* delivery according to personal Maildelivery file */
435 if (usr_delivery (fd, mdlvr ? mdlvr : ".maildelivery", 0) != -1)
438 /* delivery according to global Maildelivery file */
439 if (usr_delivery (fd, maildelivery, 1) != -1)
443 verbose_printf ("(delivering to standard mail spool)\n");
445 /* last resort - deliver to standard mail spool */
447 return usr_file (fd, mbox, MBOX_FORMAT);
449 return usr_file (fd, mbox, MMDF_FORMAT);
454 #define matches(a,b) (stringdex (b, a) >= 0)
457 * Parse the delivery file, and process incoming message.
461 usr_delivery (int fd, char *delivery, int su)
463 int i, accept, status, won, vecp, next;
464 char *field, *pattern, *action, *result, *string;
465 char buffer[BUFSIZ], tmpbuf[BUFSIZ];
466 char *cp, *vec[NVEC];
471 /* open the delivery file */
472 if ((fp = fopen (delivery, "r")) == NULL)
475 /* check if delivery file has bad ownership or permissions */
476 if (fstat (fileno (fp), &st) == -1
477 || (st.st_uid != 0 && (su || st.st_uid != pw->pw_uid))
478 || st.st_mode & (S_IWGRP|S_IWOTH)) {
480 verbose_printf ("WARNING: %s has bad ownership/modes (su=%d,uid=%d,owner=%d,mode=0%o)\n",
481 delivery, su, (int) pw->pw_uid, (int) st.st_uid, (int) st.st_mode);
489 /* read and process delivery file */
490 while (fgets (buffer, sizeof(buffer), fp)) {
491 /* skip comments and empty lines */
492 if (*buffer == '#' || *buffer == '\n')
495 /* zap trailing newline */
496 if ((cp = strchr(buffer, '\n')))
499 /* split buffer into fields */
500 vecp = split (buffer, vec);
502 /* check for too few fields */
505 debug_printf ("WARNING: entry with only %d fields, skipping.\n", vecp);
510 for (i = 0; vec[i]; i++)
511 debug_printf ("vec[%d]: \"%s\"\n", i, trim(vec[i]));
520 /* find out how to perform the action */
525 * If previous condition failed, don't
526 * do this - else fall through
529 continue; /* else fall */
533 * If already delivered, skip this action. Else
534 * consider delivered if action is successful.
537 continue; /* else fall */
542 * Take action, and consider delivered if
543 * action is successful.
552 * Take action, but don't consider delivered, even
553 * if action is successful
560 if (!strcasecmp (vec[5], "select")) {
561 if (logged_in () != -1)
563 if (vecp > 7 && timely (vec[6], vec[7]) == -1)
568 /* check if the field matches */
576 * "default" matches only if the message hasn't
577 * been delivered yet.
579 if (!strcasecmp (field, "default")) {
586 /* parse message and build lookup table */
587 if (!parsed && parse (fd) == -1) {
592 * find header field in lookup table, and
593 * see if the pattern matches.
595 if ((p = lookup (hdrs, field)) && (p->p_value != NULL)
596 && matches (p->p_value, pattern)) {
605 /* find out the action to perform */
608 /* deliver to quoted pipe */
609 if (strcasecmp (action, "qpipe"))
610 continue; /* else fall */
612 expand (tmpbuf, string, fd);
613 if (split (tmpbuf, vec) < 1)
615 status = usr_pipe (fd, tmpbuf, vec[0], vec, 0);
619 /* deliver to pipe */
620 if (strcasecmp (action, "pipe"))
621 continue; /* else fall */
625 expand (tmpbuf, string, fd);
628 status = usr_pipe (fd, tmpbuf, "/bin/sh", vec + 2, 0);
633 if (!strcasecmp (action, "file")) {
634 status = usr_file (fd, string, MBOX_FORMAT);
637 /* deliver to nmh folder */
638 else if (strcasecmp (action, "folder"))
639 continue; /* else fall */
641 status = usr_folder (fd, string);
646 if (!strcasecmp (action, "mmdf")) {
647 status = usr_file (fd, string, MMDF_FORMAT);
651 else if (strcasecmp (action, "mbox"))
652 continue; /* else fall */
656 status = usr_file (fd, string, MBOX_FORMAT);
661 if (strcasecmp (action, "destroy"))
667 if (accept && status == 0)
672 return (won ? 0 : -1);
679 * Split buffer into fields (delimited by whitespace or
680 * comma's). Return the number of fields found.
684 split (char *cp, char **vec)
691 /* split into a maximum of NVEC fields */
692 for (i = 0; i <= NVEC;) {
695 /* zap any whitespace and comma's */
696 while (isspace (*s) || *s == ',')
699 /* end of buffer, time to leave */
703 /* get double quote text as a single field */
705 for (vec[i++] = ++s; *s && *s != '"'; s++) {
707 * Check for escaped double quote. We need
708 * to shift the string to remove slash.
716 if (*s == '"') /* zap trailing double quote */
721 if (*s == QUOTE && *++s != '"')
725 /* move forward to next field delimiter */
726 while (*s && !isspace (*s) && *s != ',')
736 * Parse the headers of a message, and build the
737 * lookup table for matching fields and patterns.
746 char name[NAMESZ], field[BUFSIZ];
753 /* get a new FILE pointer to message */
754 if ((fd1 = dup (fd)) == -1)
756 if ((in = fdopen (fd1, "r")) == NULL) {
762 /* add special entries to lookup table */
763 if ((p = lookup (hdrs, "source")))
764 p->p_value = getcpy (sender);
765 if ((p = lookup (hdrs, "addr")))
766 p->p_value = getcpy (addr);
769 * Scan the headers of the message and build
772 for (i = 0, state = FLD;;) {
773 switch (state = m_getfld (state, name, field, sizeof(field), in)) {
777 lp = add (field, NULL);
778 while (state == FLDPLUS) {
779 state = m_getfld (state, name, field, sizeof(field), in);
780 lp = add (field, lp);
782 for (p = hdrs; p->p_name; p++) {
783 if (!strcasecmp (p->p_name, name)) {
784 if (!(p->p_flags & P_HID)) {
785 if ((cp = p->p_value)) {
786 if (p->p_flags & P_ADR) {
787 dp = cp + strlen (cp) - 1;
790 cp = add (",\n\t", cp);
795 p->p_value = add (lp, cp);
801 if (p->p_name == NULL && i < NVEC) {
802 p->p_name = getcpy (name);
819 advise (NULL, "format error in message");
823 advise (NULL, "internal error in m_getfld");
831 if ((p = lookup (vars, "reply-to"))) {
832 if ((q = lookup (hdrs, "reply-to")) == NULL || q->p_value == NULL)
833 q = lookup (hdrs, "from");
834 p->p_value = getcpy (q ? q->p_value : "");
835 p->p_flags &= ~P_CHK;
837 debug_printf ("vars[%d]: name=\"%s\" value=\"%s\"\n",
838 p - vars, p->p_name, trim(p->p_value));
841 for (p = hdrs; p->p_name; p++)
842 debug_printf ("hdrs[%d]: name=\"%s\" value=\"%s\"\n",
843 p - hdrs, p->p_name, p->p_value ? trim(p->p_value) : "");
854 * Expand any builtin variables such as $(sender),
855 * $(address), etc., in a string.
859 expand (char *s1, char *s2, int fd)
867 while ((c = *s2++)) {
868 if (c != '$' || *s2 != LPAREN) {
871 for (cp = ++s2; *s2 && *s2 != RPAREN; s2++)
878 if ((p = lookup (vars, cp))) {
879 if (!parsed && (p->p_flags & P_CHK))
882 strcpy (s1, p->p_value);
892 * Fill in the information missing from the "vars"
893 * table, which is necessary to expand any builtin
894 * variables in the string for a "pipe" or "qpipe"
908 if ((p = lookup (vars, "sender")))
909 p->p_value = getcpy (sender);
910 if ((p = lookup (vars, "address")))
911 p->p_value = getcpy (addr);
912 if ((p = lookup (vars, "size"))) {
913 snprintf (buffer, sizeof(buffer), "%d",
914 fstat (fd, &st) != -1 ? (int) st.st_size : 0);
915 p->p_value = getcpy (buffer);
917 if ((p = lookup (vars, "info")))
918 p->p_value = getcpy (info);
921 for (p = vars; p->p_name; p++)
922 debug_printf ("vars[%d]: name=\"%s\" value=\"%s\"\n",
923 p - vars, p->p_name, trim(p->p_value));
929 * Find a matching name in a lookup table. If found,
930 * return the "pairs" entry, else return NULL.
934 lookup (struct pair *pairs, char *key)
936 for (; pairs->p_name; pairs++)
937 if (!strcasecmp (pairs->p_name, key))
945 * Check utmp(x) file to see if user is currently
960 while ((utp = getutent()) != NULL) {
961 if (utp->ut_type == USER_PROCESS
962 && utp->ut_user[0] != 0
963 && strncmp (user, utp->ut_user, sizeof(utp->ut_user)) == 0) {
967 return (utmped = DONE);
972 return (utmped = NOTOK);
984 if ((uf = fopen (UTMP_FILE, "r")) == NULL)
987 while (fread ((char *) &ut, sizeof(ut), 1, uf) == 1) {
988 if (ut.ut_name[0] != 0
989 && strncmp (user, ut.ut_name, sizeof(ut.ut_name)) == 0) {
993 return (utmped = DONE);
998 return (utmped = NOTOK);
1002 #define check(t,a,b) if (t < a || t > b) return -1
1003 #define cmpar(h1,m1,h2,m2) if (h1 < h2 || (h1 == h2 && m1 < m2)) return 0
1006 timely (char *t1, char *t2)
1008 int t1hours, t1mins, t2hours, t2mins;
1010 if (sscanf (t1, "%d:%d", &t1hours, &t1mins) != 2)
1012 check (t1hours, 0, 23);
1013 check (t1mins, 0, 59);
1015 if (sscanf (t2, "%d:%d", &t2hours, &t2mins) != 2)
1017 check (t2hours, 0, 23);
1018 check (t2mins, 0, 59);
1020 cmpar (now->tw_hour, now->tw_min, t1hours, t1mins);
1021 cmpar (t2hours, t2mins, now->tw_hour, now->tw_min);
1028 * Deliver message by appending to a file.
1032 usr_file (int fd, char *mailbox, int mbx_style)
1037 verbose_printf ("delivering to file \"%s\"", mailbox);
1039 if (mbx_style == MBOX_FORMAT) {
1041 verbose_printf (" (mbox style)");
1045 verbose_printf (" (mmdf style)");
1049 /* open and lock the file */
1050 if ((md = mbx_open (mailbox, mbx_style, pw->pw_uid, pw->pw_gid, m_gmprot())) == -1) {
1052 adorn ("", "unable to open:");
1056 lseek (fd, (off_t) 0, SEEK_SET);
1058 /* append message to file */
1059 if (mbx_copy (mailbox, mbx_style, md, fd, mapping, NULL, verbose) == -1) {
1061 adorn ("", "error writing to:");
1065 /* close and unlock file */
1066 mbx_close (mailbox, md);
1069 verbose_printf (", success.\n");
1075 * Deliver message to a nmh folder.
1079 usr_folder (int fd, char *string)
1082 char folder[BUFSIZ], *vec[3];
1084 /* get folder name ready */
1086 strncpy(folder, string, sizeof(folder));
1088 snprintf(folder, sizeof(folder), "+%s", string);
1091 verbose_printf ("delivering to folder \"%s\"", folder + 1);
1093 vec[0] = "rcvstore";
1097 /* use rcvstore to put message in folder */
1098 status = usr_pipe (fd, "rcvstore", rcvstoreproc, vec, 1);
1102 * Currently, verbose status messages are handled by usr_pipe().
1106 verbose_printf (", success.\n");
1108 verbose_printf (", failed.\n");
1116 * Deliver message to a process.
1120 usr_pipe (int fd, char *cmd, char *pgm, char **vec, int suppress)
1123 int i, bytes, seconds, status;
1126 if (verbose && !suppress)
1127 verbose_printf ("delivering to pipe \"%s\"", cmd);
1129 lseek (fd, (off_t) 0, SEEK_SET);
1131 for (i = 0; (child_id = fork()) == -1 && i < 5; i++)
1138 adorn ("fork", "unable to");
1145 freopen ("/dev/null", "w", stdout);
1146 freopen ("/dev/null", "w", stderr);
1152 if ((fd = open ("/dev/tty", O_RDWR)) != -1) {
1153 ioctl (fd, TIOCNOTTY, NULL);
1156 #endif /* TIOCNOTTY */
1158 setpgid ((pid_t) 0, getpid ()); /* put in own process group */
1161 m_putenv ("USER", pw->pw_name);
1162 m_putenv ("HOME", pw->pw_dir);
1163 m_putenv ("SHELL", pw->pw_shell);
1169 /* parent process */
1170 if (!setjmp (myctx)) {
1171 SIGNAL (SIGALRM, alrmser);
1172 bytes = fstat (fd, &st) != -1 ? (int) st.st_size : 100;
1174 /* amount of time to wait depends on message size */
1176 /* give at least 5 minutes */
1178 } else if (bytes >= 90000) {
1179 /* a half hour is long enough */
1182 seconds = (bytes / 60) + 300;
1184 alarm ((unsigned int) seconds);
1185 status = pidwait (child_id, 0);
1189 if (status == RP_MOK || status == RP_OK)
1194 verbose_printf (", success.\n");
1196 if ((status & 0xff00) == 0xff00)
1197 verbose_printf (", system error\n");
1199 pidstatus (status, stdout, ", failed");
1201 return (status == 0 ? 0 : -1);
1204 * Ruthlessly kill the child and anything
1205 * else in its process group.
1207 KILLPG(child_id, SIGKILL);
1209 verbose_printf (", timed-out; terminated\n");
1219 #ifndef RELIABLE_SIGNALS
1220 SIGNAL (SIGALRM, alrmser);
1223 longjmp (myctx, DONE);
1228 * Get the `sender' from the envelope
1229 * information ("From " line).
1233 get_sender (char *envelope, char **sender)
1237 char buffer[BUFSIZ];
1239 if (envelope == NULL) {
1240 *sender = getcpy ("");
1244 i = strlen ("From ");
1245 strncpy (buffer, envelope + i, sizeof(buffer));
1246 if ((cp = strchr(buffer, '\n'))) {
1256 for (cp = buffer + strlen (buffer) - 1; cp >= buffer; cp--)
1261 *sender = getcpy (buffer);
1266 * Copy message into a temporary file.
1267 * While copying, it will do some header processing
1268 * including the extraction of the envelope information.
1272 copy_message (int qd, char *tmpfil, int fold)
1274 int i, first = 1, fd1, fd2;
1275 char buffer[BUFSIZ];
1278 strcpy (tmpfil, m_tmpfil (invo_name));
1280 /* open temporary file to put message in */
1281 if ((fd1 = open (tmpfil, O_RDWR | O_CREAT | O_TRUNC, 0600)) == -1)
1285 while ((i = read (qd, buffer, sizeof(buffer))) > 0)
1286 if (write (fd1, buffer, i) != i) {
1294 lseek (fd1, (off_t) 0, SEEK_SET);
1298 /* dup the fd for incoming message */
1299 if ((fd2 = dup (qd)) == -1) {
1304 /* now create a FILE pointer for it */
1305 if ((qfp = fdopen (fd2, "r")) == NULL) {
1311 /* dup the fd for temporary file */
1312 if ((fd2 = dup (fd1)) == -1) {
1318 /* now create a FILE pointer for it */
1319 if ((ffp = fdopen (fd2, "r+")) == NULL) {
1327 * copy message into temporary file
1328 * and massage the headers. Save
1329 * a copy of the "From " line for later.
1331 i = strlen ("From ");
1332 while (fgets (buffer, sizeof(buffer), qfp)) {
1335 if (!strncmp (buffer, "From ", i)) {
1337 char *fp, *cp, *hp, *ep;
1339 /* get copy of envelope information ("From " line) */
1340 envelope = getcpy (buffer);
1343 /* First go ahead and put "From " line in message */
1344 fputs (buffer, ffp);
1351 * Now create a "Return-Path:" line
1352 * from the "From " line.
1354 hp = cp = strchr(fp = envelope + i, ' ');
1355 while ((hp = strchr(++hp, 'r')))
1356 if (uprf (hp, "remote from")) {
1357 hp = strrchr(hp, ' ');
1361 /* return path for UUCP style addressing */
1362 ep = strchr(++hp, '\n');
1363 snprintf (buffer, sizeof(buffer), "Return-Path: %.*s!%.*s\n",
1364 ep - hp, hp, cp - fp, fp);
1366 /* return path for standard domain addressing */
1367 snprintf (buffer, sizeof(buffer), "Return-Path: %.*s\n",
1371 /* Add Return-Path header to message */
1372 fputs (buffer, ffp);
1376 /* Put the delivery date in message */
1385 fputs (buffer, ffp);
1397 lseek (fd1, (off_t) 0, SEEK_SET);
1409 * Trim strings for pretty printing of debugging output
1415 char buffer[BUFSIZ*4];
1421 /* copy string into temp buffer */
1422 strncpy (buffer, cp, sizeof(buffer));
1425 /* skip over leading whitespace */
1426 while (isspace(*bp))
1429 /* start at the end and zap trailing whitespace */
1430 for (sp = bp + strlen(bp) - 1; sp >= bp; sp--) {
1437 /* replace remaining whitespace with spaces */
1438 for (sp = bp; *sp; sp++)
1442 /* now return a copy */
1447 * Function for printing `verbose' messages.
1451 verbose_printf (char *fmt, ...)
1456 vfprintf (stdout, fmt, ap);
1459 fflush (stdout); /* now flush output */
1464 * Function for printing `verbose' delivery
1469 adorn (char *what, char *fmt, ...)
1475 eindex = errno; /* save the errno */
1476 fprintf (stdout, ", ");
1479 vfprintf (stdout, fmt, ap);
1484 fprintf (stdout, " %s: ", what);
1485 if ((s = strerror (eindex)))
1486 fprintf (stdout, "%s", s);
1488 fprintf (stdout, "Error %d", eindex);
1491 fputc ('\n', stdout);
1497 * Function for printing `debug' messages.
1501 debug_printf (char *fmt, ...)
1506 vfprintf (stderr, fmt, ap);
1512 * Check ndbm/db file(s) to see if the Message-Id of this
1513 * message matches the Message-Id of a previous message,
1514 * so we can discard it. If it doesn't match, we add the
1515 * Message-Id of this message to the ndbm/db file.
1518 suppress_duplicates (int fd, char *file)
1520 int fd1, lockfd, state, result;
1521 char *cp, buf[BUFSIZ], name[NAMESZ];
1526 if ((fd1 = dup (fd)) == -1)
1528 if (!(in = fdopen (fd1, "r"))) {
1534 for (state = FLD;;) {
1535 state = m_getfld (state, name, buf, sizeof(buf), in);
1540 /* Search for the message ID */
1541 if (strcasecmp (name, "Message-ID")) {
1542 while (state == FLDPLUS)
1543 state = m_getfld (state, name, buf, sizeof(buf), in);
1547 cp = add (buf, NULL);
1548 while (state == FLDPLUS) {
1549 state = m_getfld (state, name, buf, sizeof(buf), in);
1552 key.dptr = trimcpy (cp);
1553 key.dsize = strlen (key.dptr) + 1;
1557 if (!(db = dbm_open (file, O_RDWR | O_CREAT, 0600))) {
1558 advise (file, "unable to perform dbm_open on");
1564 * Since it is difficult to portable lock a ndbm file,
1565 * we will open and lock the Maildelivery file instead.
1566 * This will fail if your Maildelivery file doesn't
1569 if ((lockfd = lkopen(file, O_RDWR, 0)) == -1) {
1570 advise (file, "unable to perform file locking on");
1575 value = dbm_fetch (db, key);
1578 verbose_printf ("Message-ID: %s\n already received on %s",
1582 value.dptr = ddate + sizeof("Delivery-Date:");
1583 value.dsize = strlen(value.dptr) + 1;
1584 if (dbm_store (db, key, value, DBM_INSERT))
1585 advise (file, "possibly corrupt file");
1590 lkclose(lockfd, file);