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
63 # define UTMP_FILE _PATH_UTMP
65 # define UTMP_FILE "/etc/utmp"
70 static struct swit switches[] = {
72 { "addr address", 0 },
78 { "sender address", 0 },
80 { "mailbox file", 0 },
82 { "home directory", -4 },
86 { "maildelivery file", 0 },
91 #define SUPPRESSDUP 10
93 #define NSUPPRESSDUP 11
94 { "nosuppressdup", 0 },
104 static int globbed = 0; /* have we built "vars" table yet? */
105 static int parsed = 0; /* have we built header field table yet */
106 static int utmped = 0; /* have we scanned umtp(x) file yet */
107 static int suppressdup = 0; /* are we suppressing duplicate messages? */
109 static int verbose = 0;
110 static int debug = 0;
112 static char *addr = NULL;
113 static char *user = NULL;
114 static char *info = NULL;
115 static char *file = NULL;
116 static char *sender = NULL;
117 static char *envelope = NULL; /* envelope information ("From " line) */
118 static char *mbox = NULL;
119 static char *home = NULL;
121 static struct passwd *pw; /* passwd file entry */
123 static char ddate[BUFSIZ]; /* record the delivery date */
126 static jmp_buf myctx;
128 /* flags for pair->p_flags */
130 #define P_ADR 0x01 /* field is address */
131 #define P_HID 0x02 /* special (fake) field */
143 * Lookup table for matching fields and patterns
144 * in messages. The rest of the table is added
145 * when the message is parsed.
147 static struct pair hdrs[NVEC + 1] = {
148 { "source", NULL, P_HID },
149 { "addr", NULL, P_HID },
150 { "Return-Path", NULL, P_ADR },
151 { "Reply-To", NULL, P_ADR },
152 { "From", NULL, P_ADR },
153 { "Sender", NULL, P_ADR },
154 { "To", NULL, P_ADR },
155 { "cc", NULL, P_ADR },
156 { "Resent-Reply-To", NULL, P_ADR },
157 { "Resent-From", NULL, P_ADR },
158 { "Resent-Sender", NULL, P_ADR },
159 { "Resent-To", NULL, P_ADR },
160 { "Resent-cc", NULL, P_ADR },
165 * The list of builtin variables to expand in a string
166 * before it is executed by the "pipe" or "qpipe" action.
168 static struct pair vars[] = {
169 { "sender", NULL, P_NIL },
170 { "address", NULL, P_NIL },
171 { "size", NULL, P_NIL },
172 { "reply-to", NULL, P_CHK },
173 { "info", NULL, P_NIL },
177 extern char **environ;
182 static int localmail (int, char *);
183 static int usr_delivery (int, char *, int);
184 static int split (char *, char **);
185 static int parse (int);
186 static void expand (char *, char *, int);
187 static void glob (int);
188 static struct pair *lookup (struct pair *, char *);
189 static int logged_in (void);
190 static int timely (char *, char *);
191 static int usr_file (int, char *, int);
192 static int usr_pipe (int, char *, char *, char **, int);
193 static int usr_folder (int, char *);
194 static RETSIGTYPE alrmser (int);
195 static void get_sender (char *, char **);
196 static int copy_message (int, char *, int);
197 static void verbose_printf (char *fmt, ...);
198 static void adorn (char *, char *, ...);
199 static void debug_printf (char *fmt, ...);
200 static int suppress_duplicates (int, char *);
201 static char *trim (char *);
205 main (int argc, char **argv)
209 char *cp, *mdlvr = NULL, buf[BUFSIZ];
210 char mailbox[BUFSIZ], tmpfil[BUFSIZ];
211 char **argp, **arguments;
214 setlocale(LC_ALL, "");
216 invo_name = r1bindex (*argv, '/');
218 /* foil search of user profile/context */
219 if (context_foil (NULL) == -1)
222 mts_init (invo_name);
223 arguments = getarguments (invo_name, argc, argv, 0);
226 /* Parse arguments */
227 while ((cp = *argp++)) {
229 switch (smatch (++cp, switches)) {
231 ambigsw (cp, switches);
234 adios (NULL, "-%s unknown", cp);
237 snprintf (buf, sizeof(buf),
238 "%s [switches] [address info sender]", invo_name);
239 print_help (buf, switches, 0);
242 print_version(invo_name);
246 if (!(addr = *argp++))/* allow -xyz arguments */
247 adios (NULL, "missing argument to %s", argp[-2]);
250 if (!(info = *argp++))/* allow -xyz arguments */
251 adios (NULL, "missing argument to %s", argp[-2]);
254 if (!(user = *argp++))/* allow -xyz arguments */
255 adios (NULL, "missing argument to %s", argp[-2]);
258 if (!(file = *argp++) || *file == '-')
259 adios (NULL, "missing argument to %s", argp[-2]);
262 if (!(sender = *argp++))/* allow -xyz arguments */
263 adios (NULL, "missing argument to %s", argp[-2]);
266 if (!(mbox = *argp++) || *mbox == '-')
267 adios (NULL, "missing argument to %s", argp[-2]);
270 if (!(home = *argp++) || *home == '-')
271 adios (NULL, "missing argument to %s", argp[-2]);
275 if (!(cp = *argp++) || *cp == '-')
276 adios (NULL, "missing argument to %s", argp[-2]);
278 adios (NULL, "only one maildelivery file at a time!");
301 switch (argp - (argv + 1)) {
317 addr = getusername ();
319 user = (cp = strchr(addr, '.')) ? ++cp : addr;
320 if ((pw = getpwnam (user)) == NULL)
321 adios (NULL, "no such local user as %s", user);
323 if (chdir (pw->pw_dir) == -1)
327 if (geteuid() == 0) {
329 initgroups (pw->pw_name, pw->pw_gid);
336 setbuf (stdin, NULL);
338 /* Record the delivery time */
339 if ((now = dlocaltimenow ()) == NULL)
340 adios (NULL, "unable to ascertain local time");
341 snprintf (ddate, sizeof(ddate), "Delivery-Date: %s\n", dtimenow (0));
344 * Copy the message to a temporary file
349 /* getting message from file */
350 if ((tempfd = open (file, O_RDONLY)) == -1)
351 adios (file, "unable to open");
353 debug_printf ("retrieving message from file \"%s\"\n", file);
354 if ((fd = copy_message (tempfd, tmpfil, 1)) == -1)
355 adios (NULL, "unable to create temporary file");
358 /* getting message from stdin */
360 debug_printf ("retrieving message from stdin\n");
361 if ((fd = copy_message (fileno (stdin), tmpfil, 1)) == -1)
362 adios (NULL, "unable to create temporary file");
366 debug_printf ("temporary file=\"%s\"\n", tmpfil);
368 /* Delete the temp file now or a copy of every single message passed through
369 slocal will be left in the /tmp directory until deleted manually! This
370 unlink() used to be under an 'else' of the 'if (debug)' above, but since
371 some people like to always run slocal with -debug and log the results,
372 the /tmp directory would get choked over time. Of course, now that we
373 always delete the temp file, the "temporary file=" message above is
374 somewhat pointless -- someone watching debug output wouldn't have a
375 chance to 'tail -f' or 'ln' the temp file before it's unlinked. The best
376 thing would be to delay this unlink() until later if debug == 1, but I'll
377 leave that for someone who cares about the temp-file-accessing
378 functionality (they'll have to watch out for cases where we adios()). */
381 if (!(fp = fdopen (fd, "r+")))
382 adios (NULL, "unable to access temporary file");
385 * If no sender given, extract it
386 * from envelope information. */
388 get_sender (envelope, &sender);
391 snprintf (mailbox, sizeof(mailbox), "%s/%s",
392 mmdfldir[0] ? mmdfldir : pw->pw_dir,
393 mmdflfil[0] ? mmdflfil : pw->pw_name);
400 debug_printf ("addr=\"%s\"\n", trim(addr));
401 debug_printf ("user=\"%s\"\n", trim(user));
402 debug_printf ("info=\"%s\"\n", trim(info));
403 debug_printf ("sender=\"%s\"\n", trim(sender));
404 debug_printf ("envelope=\"%s\"\n", envelope ? trim(envelope) : "");
405 debug_printf ("mbox=\"%s\"\n", trim(mbox));
406 debug_printf ("home=\"%s\"\n", trim(home));
407 debug_printf ("ddate=\"%s\"\n", trim(ddate));
408 debug_printf ("now=%02d:%02d\n\n", now->tw_hour, now->tw_min);
411 /* deliver the message */
412 status = localmail (fd, mdlvr);
414 return done (status != -1 ? RCV_MOK : RCV_MBX);
419 * Main routine for delivering message.
423 localmail (int fd, char *mdlvr)
425 /* check if this message is a duplicate */
427 suppress_duplicates(fd, mdlvr ? mdlvr : ".maildelivery") == DONE)
430 /* delivery according to personal Maildelivery file */
431 if (usr_delivery (fd, mdlvr ? mdlvr : ".maildelivery", 0) != -1)
434 /* delivery according to global Maildelivery file */
435 if (usr_delivery (fd, maildelivery, 1) != -1)
439 verbose_printf ("(delivering to standard mail spool)\n");
441 /* last resort - deliver to standard mail spool */
443 return usr_file (fd, mbox, MBOX_FORMAT);
445 return usr_file (fd, mbox, MMDF_FORMAT);
450 #define matches(a,b) (stringdex (b, a) >= 0)
453 * Parse the delivery file, and process incoming message.
457 usr_delivery (int fd, char *delivery, int su)
459 int i, accept, status, won, vecp, next;
460 char *field, *pattern, *action, *result, *string;
461 char buffer[BUFSIZ], tmpbuf[BUFSIZ];
462 char *cp, *vec[NVEC];
467 /* open the delivery file */
468 if ((fp = fopen (delivery, "r")) == NULL)
471 /* check if delivery file has bad ownership or permissions */
472 if (fstat (fileno (fp), &st) == -1
473 || (st.st_uid != 0 && (su || st.st_uid != pw->pw_uid))
474 || st.st_mode & (S_IWGRP|S_IWOTH)) {
476 verbose_printf ("WARNING: %s has bad ownership/modes (su=%d,uid=%d,owner=%d,mode=0%o)\n",
477 delivery, su, (int) pw->pw_uid, (int) st.st_uid, (int) st.st_mode);
485 /* read and process delivery file */
486 while (fgets (buffer, sizeof(buffer), fp)) {
487 /* skip comments and empty lines */
488 if (*buffer == '#' || *buffer == '\n')
491 /* zap trailing newline */
492 if ((cp = strchr(buffer, '\n')))
495 /* split buffer into fields */
496 vecp = split (buffer, vec);
498 /* check for too few fields */
501 debug_printf ("WARNING: entry with only %d fields, skipping.\n", vecp);
506 for (i = 0; vec[i]; i++)
507 debug_printf ("vec[%d]: \"%s\"\n", i, trim(vec[i]));
516 /* find out how to perform the action */
521 * If previous condition failed, don't
522 * do this - else fall through
525 continue; /* else fall */
529 * If already delivered, skip this action. Else
530 * consider delivered if action is successful.
533 continue; /* else fall */
538 * Take action, and consider delivered if
539 * action is successful.
548 * Take action, but don't consider delivered, even
549 * if action is successful
556 if (!strcasecmp (vec[5], "select")) {
557 if (logged_in () != -1)
559 if (vecp > 7 && timely (vec[6], vec[7]) == -1)
564 /* check if the field matches */
572 * "default" matches only if the message hasn't
573 * been delivered yet.
575 if (!strcasecmp (field, "default")) {
582 /* parse message and build lookup table */
583 if (!parsed && parse (fd) == -1) {
588 * find header field in lookup table, and
589 * see if the pattern matches.
591 if ((p = lookup (hdrs, field)) && (p->p_value != NULL)
592 && matches (p->p_value, pattern)) {
601 /* find out the action to perform */
604 /* deliver to quoted pipe */
605 if (strcasecmp (action, "qpipe"))
606 continue; /* else fall */
608 expand (tmpbuf, string, fd);
609 if (split (tmpbuf, vec) < 1)
611 status = usr_pipe (fd, tmpbuf, vec[0], vec, 0);
615 /* deliver to pipe */
616 if (strcasecmp (action, "pipe"))
617 continue; /* else fall */
621 expand (tmpbuf, string, fd);
624 status = usr_pipe (fd, tmpbuf, "/bin/sh", vec + 2, 0);
629 if (!strcasecmp (action, "file")) {
630 status = usr_file (fd, string, MBOX_FORMAT);
633 /* deliver to nmh folder */
634 else if (strcasecmp (action, "folder"))
635 continue; /* else fall */
637 status = usr_folder (fd, string);
642 if (!strcasecmp (action, "mmdf")) {
643 status = usr_file (fd, string, MMDF_FORMAT);
647 else if (strcasecmp (action, "mbox"))
648 continue; /* else fall */
652 status = usr_file (fd, string, MBOX_FORMAT);
657 if (strcasecmp (action, "destroy"))
663 if (accept && status == 0)
668 return (won ? 0 : -1);
675 * Split buffer into fields (delimited by whitespace or
676 * comma's). Return the number of fields found.
680 split (char *cp, char **vec)
687 /* split into a maximum of NVEC fields */
688 for (i = 0; i <= NVEC;) {
691 /* zap any whitespace and comma's */
692 while (isspace (*s) || *s == ',')
695 /* end of buffer, time to leave */
699 /* get double quote text as a single field */
701 for (vec[i++] = ++s; *s && *s != '"'; s++) {
703 * Check for escaped double quote. We need
704 * to shift the string to remove slash.
712 if (*s == '"') /* zap trailing double quote */
717 if (*s == QUOTE && *++s != '"')
721 /* move forward to next field delimiter */
722 while (*s && !isspace (*s) && *s != ',')
732 * Parse the headers of a message, and build the
733 * lookup table for matching fields and patterns.
742 char name[NAMESZ], field[BUFSIZ];
749 /* get a new FILE pointer to message */
750 if ((fd1 = dup (fd)) == -1)
752 if ((in = fdopen (fd1, "r")) == NULL) {
758 /* add special entries to lookup table */
759 if ((p = lookup (hdrs, "source")))
760 p->p_value = getcpy (sender);
761 if ((p = lookup (hdrs, "addr")))
762 p->p_value = getcpy (addr);
765 * Scan the headers of the message and build
768 for (i = 0, state = FLD;;) {
769 switch (state = m_getfld (state, name, field, sizeof(field), in)) {
773 lp = add (field, NULL);
774 while (state == FLDPLUS) {
775 state = m_getfld (state, name, field, sizeof(field), in);
776 lp = add (field, lp);
778 for (p = hdrs; p->p_name; p++) {
779 if (!strcasecmp (p->p_name, name)) {
780 if (!(p->p_flags & P_HID)) {
781 if ((cp = p->p_value)) {
782 if (p->p_flags & P_ADR) {
783 dp = cp + strlen (cp) - 1;
786 cp = add (",\n\t", cp);
791 p->p_value = add (lp, cp);
797 if (p->p_name == NULL && i < NVEC) {
798 p->p_name = getcpy (name);
815 advise (NULL, "format error in message");
819 advise (NULL, "internal error in m_getfld");
827 if ((p = lookup (vars, "reply-to"))) {
828 if ((q = lookup (hdrs, "reply-to")) == NULL || q->p_value == NULL)
829 q = lookup (hdrs, "from");
830 p->p_value = getcpy (q ? q->p_value : "");
831 p->p_flags &= ~P_CHK;
833 debug_printf ("vars[%d]: name=\"%s\" value=\"%s\"\n",
834 p - vars, p->p_name, trim(p->p_value));
837 for (p = hdrs; p->p_name; p++)
838 debug_printf ("hdrs[%d]: name=\"%s\" value=\"%s\"\n",
839 p - hdrs, p->p_name, p->p_value ? trim(p->p_value) : "");
850 * Expand any builtin variables such as $(sender),
851 * $(address), etc., in a string.
855 expand (char *s1, char *s2, int fd)
863 while ((c = *s2++)) {
864 if (c != '$' || *s2 != LPAREN) {
867 for (cp = ++s2; *s2 && *s2 != RPAREN; s2++)
874 if ((p = lookup (vars, cp))) {
875 if (!parsed && (p->p_flags & P_CHK))
878 strcpy (s1, p->p_value);
888 * Fill in the information missing from the "vars"
889 * table, which is necessary to expand any builtin
890 * variables in the string for a "pipe" or "qpipe"
904 if ((p = lookup (vars, "sender")))
905 p->p_value = getcpy (sender);
906 if ((p = lookup (vars, "address")))
907 p->p_value = getcpy (addr);
908 if ((p = lookup (vars, "size"))) {
909 snprintf (buffer, sizeof(buffer), "%d",
910 fstat (fd, &st) != -1 ? (int) st.st_size : 0);
911 p->p_value = getcpy (buffer);
913 if ((p = lookup (vars, "info")))
914 p->p_value = getcpy (info);
917 for (p = vars; p->p_name; p++)
918 debug_printf ("vars[%d]: name=\"%s\" value=\"%s\"\n",
919 p - vars, p->p_name, trim(p->p_value));
925 * Find a matching name in a lookup table. If found,
926 * return the "pairs" entry, else return NULL.
930 lookup (struct pair *pairs, char *key)
932 for (; pairs->p_name; pairs++)
933 if (!strcasecmp (pairs->p_name, key))
941 * Check utmp(x) file to see if user is currently
956 while ((utp = getutent()) != NULL) {
957 if (utp->ut_type == USER_PROCESS
958 && utp->ut_user[0] != 0
959 && strncmp (user, utp->ut_user, sizeof(utp->ut_user)) == 0) {
963 return (utmped = DONE);
968 return (utmped = NOTOK);
980 if ((uf = fopen (UTMP_FILE, "r")) == NULL)
983 while (fread ((char *) &ut, sizeof(ut), 1, uf) == 1) {
984 if (ut.ut_name[0] != 0
985 && strncmp (user, ut.ut_name, sizeof(ut.ut_name)) == 0) {
989 return (utmped = DONE);
994 return (utmped = NOTOK);
998 #define check(t,a,b) if (t < a || t > b) return -1
999 #define cmpar(h1,m1,h2,m2) if (h1 < h2 || (h1 == h2 && m1 < m2)) return 0
1002 timely (char *t1, char *t2)
1004 int t1hours, t1mins, t2hours, t2mins;
1006 if (sscanf (t1, "%d:%d", &t1hours, &t1mins) != 2)
1008 check (t1hours, 0, 23);
1009 check (t1mins, 0, 59);
1011 if (sscanf (t2, "%d:%d", &t2hours, &t2mins) != 2)
1013 check (t2hours, 0, 23);
1014 check (t2mins, 0, 59);
1016 cmpar (now->tw_hour, now->tw_min, t1hours, t1mins);
1017 cmpar (t2hours, t2mins, now->tw_hour, now->tw_min);
1024 * Deliver message by appending to a file.
1028 usr_file (int fd, char *mailbox, int mbx_style)
1033 verbose_printf ("delivering to file \"%s\"", mailbox);
1035 if (mbx_style == MBOX_FORMAT) {
1037 verbose_printf (" (mbox style)");
1041 verbose_printf (" (mmdf style)");
1045 /* open and lock the file */
1046 if ((md = mbx_open (mailbox, mbx_style, pw->pw_uid, pw->pw_gid, m_gmprot())) == -1) {
1048 adorn ("", "unable to open:");
1052 lseek (fd, (off_t) 0, SEEK_SET);
1054 /* append message to file */
1055 if (mbx_copy (mailbox, mbx_style, md, fd, mapping, NULL, verbose) == -1) {
1057 adorn ("", "error writing to:");
1061 /* close and unlock file */
1062 mbx_close (mailbox, md);
1065 verbose_printf (", success.\n");
1071 * Deliver message to a nmh folder.
1075 usr_folder (int fd, char *string)
1078 char folder[BUFSIZ], *vec[3];
1080 /* get folder name ready */
1082 strncpy(folder, string, sizeof(folder));
1084 snprintf(folder, sizeof(folder), "+%s", string);
1087 verbose_printf ("delivering to folder \"%s\"", folder + 1);
1089 vec[0] = "rcvstore";
1093 /* use rcvstore to put message in folder */
1094 status = usr_pipe (fd, "rcvstore", rcvstoreproc, vec, 1);
1098 * Currently, verbose status messages are handled by usr_pipe().
1102 verbose_printf (", success.\n");
1104 verbose_printf (", failed.\n");
1112 * Deliver message to a process.
1116 usr_pipe (int fd, char *cmd, char *pgm, char **vec, int suppress)
1119 int i, bytes, seconds, status;
1122 if (verbose && !suppress)
1123 verbose_printf ("delivering to pipe \"%s\"", cmd);
1125 lseek (fd, (off_t) 0, SEEK_SET);
1127 for (i = 0; (child_id = fork()) == -1 && i < 5; i++)
1134 adorn ("fork", "unable to");
1141 freopen ("/dev/null", "w", stdout);
1142 freopen ("/dev/null", "w", stderr);
1148 if ((fd = open ("/dev/tty", O_RDWR)) != -1) {
1149 ioctl (fd, TIOCNOTTY, NULL);
1152 #endif /* TIOCNOTTY */
1154 setpgid ((pid_t) 0, getpid ()); /* put in own process group */
1157 m_putenv ("USER", pw->pw_name);
1158 m_putenv ("HOME", pw->pw_dir);
1159 m_putenv ("SHELL", pw->pw_shell);
1165 /* parent process */
1166 if (!setjmp (myctx)) {
1167 SIGNAL (SIGALRM, alrmser);
1168 bytes = fstat (fd, &st) != -1 ? (int) st.st_size : 100;
1170 /* amount of time to wait depends on message size */
1172 /* give at least 5 minutes */
1174 } else if (bytes >= 90000) {
1175 /* a half hour is long enough */
1178 seconds = (bytes / 60) + 300;
1180 alarm ((unsigned int) seconds);
1181 status = pidwait (child_id, 0);
1185 if (status == RP_MOK || status == RP_OK)
1190 verbose_printf (", success.\n");
1192 if ((status & 0xff00) == 0xff00)
1193 verbose_printf (", system error\n");
1195 pidstatus (status, stdout, ", failed");
1197 return (status == 0 ? 0 : -1);
1200 * Ruthlessly kill the child and anything
1201 * else in its process group.
1203 KILLPG(child_id, SIGKILL);
1205 verbose_printf (", timed-out; terminated\n");
1215 #ifndef RELIABLE_SIGNALS
1216 SIGNAL (SIGALRM, alrmser);
1219 longjmp (myctx, DONE);
1224 * Get the `sender' from the envelope
1225 * information ("From " line).
1229 get_sender (char *envelope, char **sender)
1233 char buffer[BUFSIZ];
1235 if (envelope == NULL) {
1236 *sender = getcpy ("");
1240 i = strlen ("From ");
1241 strncpy (buffer, envelope + i, sizeof(buffer));
1242 if ((cp = strchr(buffer, '\n'))) {
1252 for (cp = buffer + strlen (buffer) - 1; cp >= buffer; cp--)
1257 *sender = getcpy (buffer);
1262 * Copy message into a temporary file.
1263 * While copying, it will do some header processing
1264 * including the extraction of the envelope information.
1268 copy_message (int qd, char *tmpfil, int fold)
1270 int i, first = 1, fd1, fd2;
1271 char buffer[BUFSIZ];
1274 strcpy (tmpfil, m_tmpfil (invo_name));
1276 /* open temporary file to put message in */
1277 if ((fd1 = open (tmpfil, O_RDWR | O_CREAT | O_TRUNC, 0600)) == -1)
1281 while ((i = read (qd, buffer, sizeof(buffer))) > 0)
1282 if (write (fd1, buffer, i) != i) {
1290 lseek (fd1, (off_t) 0, SEEK_SET);
1294 /* dup the fd for incoming message */
1295 if ((fd2 = dup (qd)) == -1) {
1300 /* now create a FILE pointer for it */
1301 if ((qfp = fdopen (fd2, "r")) == NULL) {
1307 /* dup the fd for temporary file */
1308 if ((fd2 = dup (fd1)) == -1) {
1314 /* now create a FILE pointer for it */
1315 if ((ffp = fdopen (fd2, "r+")) == NULL) {
1323 * copy message into temporary file
1324 * and massage the headers. Save
1325 * a copy of the "From " line for later.
1327 i = strlen ("From ");
1328 while (fgets (buffer, sizeof(buffer), qfp)) {
1331 if (!strncmp (buffer, "From ", i)) {
1333 char *fp, *cp, *hp, *ep;
1335 /* get copy of envelope information ("From " line) */
1336 envelope = getcpy (buffer);
1339 /* First go ahead and put "From " line in message */
1340 fputs (buffer, ffp);
1347 * Now create a "Return-Path:" line
1348 * from the "From " line.
1350 hp = cp = strchr(fp = envelope + i, ' ');
1351 while ((hp = strchr(++hp, 'r')))
1352 if (uprf (hp, "remote from")) {
1353 hp = strrchr(hp, ' ');
1357 /* return path for UUCP style addressing */
1358 ep = strchr(++hp, '\n');
1359 snprintf (buffer, sizeof(buffer), "Return-Path: %.*s!%.*s\n",
1360 ep - hp, hp, cp - fp, fp);
1362 /* return path for standard domain addressing */
1363 snprintf (buffer, sizeof(buffer), "Return-Path: %.*s\n",
1367 /* Add Return-Path header to message */
1368 fputs (buffer, ffp);
1372 /* Put the delivery date in message */
1381 fputs (buffer, ffp);
1393 lseek (fd1, (off_t) 0, SEEK_SET);
1405 * Trim strings for pretty printing of debugging output
1411 char buffer[BUFSIZ*4];
1417 /* copy string into temp buffer */
1418 strncpy (buffer, cp, sizeof(buffer));
1421 /* skip over leading whitespace */
1422 while (isspace(*bp))
1425 /* start at the end and zap trailing whitespace */
1426 for (sp = bp + strlen(bp) - 1; sp >= bp; sp--) {
1433 /* replace remaining whitespace with spaces */
1434 for (sp = bp; *sp; sp++)
1438 /* now return a copy */
1443 * Function for printing `verbose' messages.
1447 verbose_printf (char *fmt, ...)
1452 vfprintf (stdout, fmt, ap);
1455 fflush (stdout); /* now flush output */
1460 * Function for printing `verbose' delivery
1465 adorn (char *what, char *fmt, ...)
1471 eindex = errno; /* save the errno */
1472 fprintf (stdout, ", ");
1475 vfprintf (stdout, fmt, ap);
1480 fprintf (stdout, " %s: ", what);
1481 if ((s = strerror (eindex)))
1482 fprintf (stdout, "%s", s);
1484 fprintf (stdout, "Error %d", eindex);
1487 fputc ('\n', stdout);
1493 * Function for printing `debug' messages.
1497 debug_printf (char *fmt, ...)
1502 vfprintf (stderr, fmt, ap);
1508 * Check ndbm/db file(s) to see if the Message-Id of this
1509 * message matches the Message-Id of a previous message,
1510 * so we can discard it. If it doesn't match, we add the
1511 * Message-Id of this message to the ndbm/db file.
1514 suppress_duplicates (int fd, char *file)
1516 int fd1, lockfd, state, result;
1517 char *cp, buf[BUFSIZ], name[NAMESZ];
1522 if ((fd1 = dup (fd)) == -1)
1524 if (!(in = fdopen (fd1, "r"))) {
1530 for (state = FLD;;) {
1531 state = m_getfld (state, name, buf, sizeof(buf), in);
1536 /* Search for the message ID */
1537 if (strcasecmp (name, "Message-ID")) {
1538 while (state == FLDPLUS)
1539 state = m_getfld (state, name, buf, sizeof(buf), in);
1543 cp = add (buf, NULL);
1544 while (state == FLDPLUS) {
1545 state = m_getfld (state, name, buf, sizeof(buf), in);
1548 key.dptr = trimcpy (cp);
1549 key.dsize = strlen (key.dptr) + 1;
1553 if (!(db = dbm_open (file, O_RDWR | O_CREAT, 0600))) {
1554 advise (file, "unable to perform dbm_open on");
1560 * Since it is difficult to portable lock a ndbm file,
1561 * we will open and lock the Maildelivery file instead.
1562 * This will fail if your Maildelivery file doesn't
1565 if ((lockfd = lkopen(file, O_RDWR, 0)) == -1) {
1566 advise (file, "unable to perform file locking on");
1571 value = dbm_fetch (db, key);
1574 verbose_printf ("Message-ID: %s\n already received on %s",
1578 value.dptr = ddate + sizeof("Delivery-Date:");
1579 value.dsize = strlen(value.dptr) + 1;
1580 if (dbm_store (db, key, value, DBM_INSERT))
1581 advise (file, "possibly corrupt file");
1586 lkclose(lockfd, file);