3 * slocal.c -- asynchronously filter and deliver new mail
9 * Under sendmail, users should add the line
11 * "| /usr/local/nmh/lib/slocal"
13 * to their $HOME/.forward file.
15 * Under MMDF-I, users should (symbolically) link
16 * /usr/local/nmh/lib/slocal to $HOME/bin/rcvmail.
20 /* Changed to use getutent() and friends. Assumes that when getutent() exists,
21 * a number of other things also exist. Please check.
22 * Ruud de Rooij <ruud@ruud.org> Sun, 28 May 2000 17:28:55 +0200
26 #include <h/dropsbr.h>
27 #include <h/rcvmail.h>
28 #include <h/signals.h>
34 #include <sys/ioctl.h>
37 #ifdef INITGROUPS_HEADER
38 #include INITGROUPS_HEADER
40 /* On AIX 4.1, initgroups() is defined and even documented (giving the parameter
41 types as char* and int), but doesn't have a prototype in any of the system
42 header files. AIX 4.3, SunOS 4.1.3, and ULTRIX 4.2A have the same
44 extern int initgroups(char*, int);
48 #ifdef HAVE_DB1_NDBM_H
59 # define UTMP_FILE _PATH_UTMP
61 # define UTMP_FILE "/etc/utmp"
66 static struct swit switches[] = {
68 { "addr address", 0 },
74 { "sender address", 0 },
76 { "mailbox file", 0 },
78 { "home directory", -4 },
82 { "maildelivery file", 0 },
87 #define SUPPRESSDUP 10
89 #define NSUPPRESSDUP 11
90 { "nosuppressdup", 0 },
100 static int globbed = 0; /* have we built "vars" table yet? */
101 static int parsed = 0; /* have we built header field table yet */
102 static int utmped = 0; /* have we scanned umtp(x) file yet */
103 static int suppressdup = 0; /* are we suppressing duplicate messages? */
105 static int verbose = 0;
106 static int debug = 0;
108 static char *addr = NULL;
109 static char *user = NULL;
110 static char *info = NULL;
111 static char *file = NULL;
112 static char *sender = NULL;
113 static char *envelope = NULL; /* envelope information ("From " line) */
114 static char *mbox = NULL;
115 static char *home = NULL;
117 static struct passwd *pw; /* passwd file entry */
119 static char ddate[BUFSIZ]; /* record the delivery date */
122 static jmp_buf myctx;
124 /* flags for pair->p_flags */
126 #define P_ADR 0x01 /* field is address */
127 #define P_HID 0x02 /* special (fake) field */
139 * Lookup table for matching fields and patterns
140 * in messages. The rest of the table is added
141 * when the message is parsed.
143 static struct pair hdrs[NVEC + 1] = {
144 { "source", NULL, P_HID },
145 { "addr", NULL, P_HID },
146 { "Return-Path", NULL, P_ADR },
147 { "Reply-To", NULL, P_ADR },
148 { "From", NULL, P_ADR },
149 { "Sender", NULL, P_ADR },
150 { "To", NULL, P_ADR },
151 { "cc", NULL, P_ADR },
152 { "Resent-Reply-To", NULL, P_ADR },
153 { "Resent-From", NULL, P_ADR },
154 { "Resent-Sender", NULL, P_ADR },
155 { "Resent-To", NULL, P_ADR },
156 { "Resent-cc", NULL, P_ADR },
161 * The list of builtin variables to expand in a string
162 * before it is executed by the "pipe" or "qpipe" action.
164 static struct pair vars[] = {
165 { "sender", NULL, P_NIL },
166 { "address", NULL, P_NIL },
167 { "size", NULL, P_NIL },
168 { "reply-to", NULL, P_CHK },
169 { "info", NULL, P_NIL },
173 extern char **environ;
178 static int localmail (int, char *);
179 static int usr_delivery (int, char *, int);
180 static int split (char *, char **);
181 static int parse (int);
182 static void expand (char *, char *, int);
183 static void glob (int);
184 static struct pair *lookup (struct pair *, char *);
185 static int logged_in (void);
186 static int timely (char *, char *);
187 static int usr_file (int, char *, int);
188 static int usr_pipe (int, char *, char *, char **, int);
189 static int usr_folder (int, char *);
190 static RETSIGTYPE alrmser (int);
191 static void get_sender (char *, char **);
192 static int copy_message (int, char *, int);
193 static void verbose_printf (char *fmt, ...);
194 static void adorn (char *, char *, ...);
195 static void debug_printf (char *fmt, ...);
196 static int suppress_duplicates (int, char *);
197 static char *trim (char *);
201 main (int argc, char **argv)
205 char *cp, *mdlvr = NULL, buf[BUFSIZ];
206 char mailbox[BUFSIZ], tmpfil[BUFSIZ];
207 char **argp, **arguments;
210 setlocale(LC_ALL, "");
212 invo_name = r1bindex (*argv, '/');
214 /* foil search of user profile/context */
215 if (context_foil (NULL) == -1)
218 mts_init (invo_name);
219 arguments = getarguments (invo_name, argc, argv, 0);
222 /* Parse arguments */
223 while ((cp = *argp++)) {
225 switch (smatch (++cp, switches)) {
227 ambigsw (cp, switches);
230 adios (NULL, "-%s unknown", cp);
233 snprintf (buf, sizeof(buf),
234 "%s [switches] [address info sender]", invo_name);
235 print_help (buf, switches, 0);
238 print_version(invo_name);
242 if (!(addr = *argp++))/* allow -xyz arguments */
243 adios (NULL, "missing argument to %s", argp[-2]);
246 if (!(info = *argp++))/* allow -xyz arguments */
247 adios (NULL, "missing argument to %s", argp[-2]);
250 if (!(user = *argp++))/* allow -xyz arguments */
251 adios (NULL, "missing argument to %s", argp[-2]);
254 if (!(file = *argp++) || *file == '-')
255 adios (NULL, "missing argument to %s", argp[-2]);
258 if (!(sender = *argp++))/* allow -xyz arguments */
259 adios (NULL, "missing argument to %s", argp[-2]);
262 if (!(mbox = *argp++) || *mbox == '-')
263 adios (NULL, "missing argument to %s", argp[-2]);
266 if (!(home = *argp++) || *home == '-')
267 adios (NULL, "missing argument to %s", argp[-2]);
271 if (!(cp = *argp++) || *cp == '-')
272 adios (NULL, "missing argument to %s", argp[-2]);
274 adios (NULL, "only one maildelivery file at a time!");
297 switch (argp - (argv + 1)) {
313 addr = getusername ();
315 user = (cp = strchr(addr, '.')) ? ++cp : addr;
316 if ((pw = getpwnam (user)) == NULL)
317 adios (NULL, "no such local user as %s", user);
319 if (chdir (pw->pw_dir) == -1)
323 if (geteuid() == 0) {
325 initgroups (pw->pw_name, pw->pw_gid);
332 setbuf (stdin, NULL);
334 /* Record the delivery time */
335 if ((now = dlocaltimenow ()) == NULL)
336 adios (NULL, "unable to ascertain local time");
337 snprintf (ddate, sizeof(ddate), "Delivery-Date: %s\n", dtimenow (0));
340 * Copy the message to a temporary file
345 /* getting message from file */
346 if ((tempfd = open (file, O_RDONLY)) == -1)
347 adios (file, "unable to open");
349 debug_printf ("retrieving message from file \"%s\"\n", file);
350 if ((fd = copy_message (tempfd, tmpfil, 1)) == -1)
351 adios (NULL, "unable to create temporary file");
354 /* getting message from stdin */
356 debug_printf ("retrieving message from stdin\n");
357 if ((fd = copy_message (fileno (stdin), tmpfil, 1)) == -1)
358 adios (NULL, "unable to create temporary file");
362 debug_printf ("temporary file=\"%s\"\n", tmpfil);
364 /* Delete the temp file now or a copy of every single message passed through
365 slocal will be left in the /tmp directory until deleted manually! This
366 unlink() used to be under an 'else' of the 'if (debug)' above, but since
367 some people like to always run slocal with -debug and log the results,
368 the /tmp directory would get choked over time. Of course, now that we
369 always delete the temp file, the "temporary file=" message above is
370 somewhat pointless -- someone watching debug output wouldn't have a
371 chance to 'tail -f' or 'ln' the temp file before it's unlinked. The best
372 thing would be to delay this unlink() until later if debug == 1, but I'll
373 leave that for someone who cares about the temp-file-accessing
374 functionality (they'll have to watch out for cases where we adios()). */
377 if (!(fp = fdopen (fd, "r+")))
378 adios (NULL, "unable to access temporary file");
381 * If no sender given, extract it
382 * from envelope information. */
384 get_sender (envelope, &sender);
387 snprintf (mailbox, sizeof(mailbox), "%s/%s",
388 mmdfldir[0] ? mmdfldir : pw->pw_dir,
389 mmdflfil[0] ? mmdflfil : pw->pw_name);
396 debug_printf ("addr=\"%s\"\n", trim(addr));
397 debug_printf ("user=\"%s\"\n", trim(user));
398 debug_printf ("info=\"%s\"\n", trim(info));
399 debug_printf ("sender=\"%s\"\n", trim(sender));
400 debug_printf ("envelope=\"%s\"\n", envelope ? trim(envelope) : "");
401 debug_printf ("mbox=\"%s\"\n", trim(mbox));
402 debug_printf ("home=\"%s\"\n", trim(home));
403 debug_printf ("ddate=\"%s\"\n", trim(ddate));
404 debug_printf ("now=%02d:%02d\n\n", now->tw_hour, now->tw_min);
407 /* deliver the message */
408 status = localmail (fd, mdlvr);
410 return done (status != -1 ? RCV_MOK : RCV_MBX);
415 * Main routine for delivering message.
419 localmail (int fd, char *mdlvr)
421 /* check if this message is a duplicate */
423 suppress_duplicates(fd, mdlvr ? mdlvr : ".maildelivery") == DONE)
426 /* delivery according to personal Maildelivery file */
427 if (usr_delivery (fd, mdlvr ? mdlvr : ".maildelivery", 0) != -1)
430 /* delivery according to global Maildelivery file */
431 if (usr_delivery (fd, maildelivery, 1) != -1)
435 verbose_printf ("(delivering to standard mail spool)\n");
437 /* last resort - deliver to standard mail spool */
439 return usr_file (fd, mbox, MBOX_FORMAT);
441 return usr_file (fd, mbox, MMDF_FORMAT);
446 #define matches(a,b) (stringdex (b, a) >= 0)
449 * Parse the delivery file, and process incoming message.
453 usr_delivery (int fd, char *delivery, int su)
455 int i, accept, status, won, vecp, next;
456 char *field, *pattern, *action, *result, *string;
457 char buffer[BUFSIZ], tmpbuf[BUFSIZ];
458 char *cp, *vec[NVEC];
463 /* open the delivery file */
464 if ((fp = fopen (delivery, "r")) == NULL)
467 /* check if delivery file has bad ownership or permissions */
468 if (fstat (fileno (fp), &st) == -1
469 || (st.st_uid != 0 && (su || st.st_uid != pw->pw_uid))
470 || st.st_mode & (S_IWGRP|S_IWOTH)) {
472 verbose_printf ("WARNING: %s has bad ownership/modes (su=%d,uid=%d,owner=%d,mode=0%o)\n",
473 delivery, su, (int) pw->pw_uid, (int) st.st_uid, (int) st.st_mode);
481 /* read and process delivery file */
482 while (fgets (buffer, sizeof(buffer), fp)) {
483 /* skip comments and empty lines */
484 if (*buffer == '#' || *buffer == '\n')
487 /* zap trailing newline */
488 if ((cp = strchr(buffer, '\n')))
491 /* split buffer into fields */
492 vecp = split (buffer, vec);
494 /* check for too few fields */
497 debug_printf ("WARNING: entry with only %d fields, skipping.\n", vecp);
502 for (i = 0; vec[i]; i++)
503 debug_printf ("vec[%d]: \"%s\"\n", i, trim(vec[i]));
512 /* find out how to perform the action */
517 * If previous condition failed, don't
518 * do this - else fall through
521 continue; /* else fall */
525 * If already delivered, skip this action. Else
526 * consider delivered if action is successful.
529 continue; /* else fall */
534 * Take action, and consider delivered if
535 * action is successful.
544 * Take action, but don't consider delivered, even
545 * if action is successful
552 if (!strcasecmp (vec[5], "select")) {
553 if (logged_in () != -1)
555 if (vecp > 7 && timely (vec[6], vec[7]) == -1)
560 /* check if the field matches */
568 * "default" matches only if the message hasn't
569 * been delivered yet.
571 if (!strcasecmp (field, "default")) {
578 /* parse message and build lookup table */
579 if (!parsed && parse (fd) == -1) {
584 * find header field in lookup table, and
585 * see if the pattern matches.
587 if ((p = lookup (hdrs, field)) && (p->p_value != NULL)
588 && matches (p->p_value, pattern)) {
597 /* find out the action to perform */
600 /* deliver to quoted pipe */
601 if (strcasecmp (action, "qpipe"))
602 continue; /* else fall */
604 expand (tmpbuf, string, fd);
605 if (split (tmpbuf, vec) < 1)
607 status = usr_pipe (fd, tmpbuf, vec[0], vec, 0);
611 /* deliver to pipe */
612 if (strcasecmp (action, "pipe"))
613 continue; /* else fall */
617 expand (tmpbuf, string, fd);
620 status = usr_pipe (fd, tmpbuf, "/bin/sh", vec + 2, 0);
625 if (!strcasecmp (action, "file")) {
626 status = usr_file (fd, string, MBOX_FORMAT);
629 /* deliver to nmh folder */
630 else if (strcasecmp (action, "folder"))
631 continue; /* else fall */
633 status = usr_folder (fd, string);
638 if (!strcasecmp (action, "mmdf")) {
639 status = usr_file (fd, string, MMDF_FORMAT);
643 else if (strcasecmp (action, "mbox"))
644 continue; /* else fall */
648 status = usr_file (fd, string, MBOX_FORMAT);
653 if (strcasecmp (action, "destroy"))
659 if (accept && status == 0)
664 return (won ? 0 : -1);
671 * Split buffer into fields (delimited by whitespace or
672 * comma's). Return the number of fields found.
676 split (char *cp, char **vec)
683 /* split into a maximum of NVEC fields */
684 for (i = 0; i <= NVEC;) {
687 /* zap any whitespace and comma's */
688 while (isspace (*s) || *s == ',')
691 /* end of buffer, time to leave */
695 /* get double quote text as a single field */
697 for (vec[i++] = ++s; *s && *s != '"'; s++) {
699 * Check for escaped double quote. We need
700 * to shift the string to remove slash.
708 if (*s == '"') /* zap trailing double quote */
713 if (*s == QUOTE && *++s != '"')
717 /* move forward to next field delimiter */
718 while (*s && !isspace (*s) && *s != ',')
728 * Parse the headers of a message, and build the
729 * lookup table for matching fields and patterns.
738 char name[NAMESZ], field[BUFSIZ];
745 /* get a new FILE pointer to message */
746 if ((fd1 = dup (fd)) == -1)
748 if ((in = fdopen (fd1, "r")) == NULL) {
754 /* add special entries to lookup table */
755 if ((p = lookup (hdrs, "source")))
756 p->p_value = getcpy (sender);
757 if ((p = lookup (hdrs, "addr")))
758 p->p_value = getcpy (addr);
761 * Scan the headers of the message and build
764 for (i = 0, state = FLD;;) {
765 switch (state = m_getfld (state, name, field, sizeof(field), in)) {
769 lp = add (field, NULL);
770 while (state == FLDPLUS) {
771 state = m_getfld (state, name, field, sizeof(field), in);
772 lp = add (field, lp);
774 for (p = hdrs; p->p_name; p++) {
775 if (!strcasecmp (p->p_name, name)) {
776 if (!(p->p_flags & P_HID)) {
777 if ((cp = p->p_value)) {
778 if (p->p_flags & P_ADR) {
779 dp = cp + strlen (cp) - 1;
782 cp = add (",\n\t", cp);
787 p->p_value = add (lp, cp);
793 if (p->p_name == NULL && i < NVEC) {
794 p->p_name = getcpy (name);
811 advise (NULL, "format error in message");
815 advise (NULL, "internal error in m_getfld");
823 if ((p = lookup (vars, "reply-to"))) {
824 if ((q = lookup (hdrs, "reply-to")) == NULL || q->p_value == NULL)
825 q = lookup (hdrs, "from");
826 p->p_value = getcpy (q ? q->p_value : "");
827 p->p_flags &= ~P_CHK;
829 debug_printf ("vars[%d]: name=\"%s\" value=\"%s\"\n",
830 p - vars, p->p_name, trim(p->p_value));
833 for (p = hdrs; p->p_name; p++)
834 debug_printf ("hdrs[%d]: name=\"%s\" value=\"%s\"\n",
835 p - hdrs, p->p_name, p->p_value ? trim(p->p_value) : "");
846 * Expand any builtin variables such as $(sender),
847 * $(address), etc., in a string.
851 expand (char *s1, char *s2, int fd)
859 while ((c = *s2++)) {
860 if (c != '$' || *s2 != LPAREN) {
863 for (cp = ++s2; *s2 && *s2 != RPAREN; s2++)
870 if ((p = lookup (vars, cp))) {
871 if (!parsed && (p->p_flags & P_CHK))
874 strcpy (s1, p->p_value);
884 * Fill in the information missing from the "vars"
885 * table, which is necessary to expand any builtin
886 * variables in the string for a "pipe" or "qpipe"
900 if ((p = lookup (vars, "sender")))
901 p->p_value = getcpy (sender);
902 if ((p = lookup (vars, "address")))
903 p->p_value = getcpy (addr);
904 if ((p = lookup (vars, "size"))) {
905 snprintf (buffer, sizeof(buffer), "%d",
906 fstat (fd, &st) != -1 ? (int) st.st_size : 0);
907 p->p_value = getcpy (buffer);
909 if ((p = lookup (vars, "info")))
910 p->p_value = getcpy (info);
913 for (p = vars; p->p_name; p++)
914 debug_printf ("vars[%d]: name=\"%s\" value=\"%s\"\n",
915 p - vars, p->p_name, trim(p->p_value));
921 * Find a matching name in a lookup table. If found,
922 * return the "pairs" entry, else return NULL.
926 lookup (struct pair *pairs, char *key)
928 for (; pairs->p_name; pairs++)
929 if (!strcasecmp (pairs->p_name, key))
937 * Check utmp(x) file to see if user is currently
952 while ((utp = getutent()) != NULL) {
953 if (utp->ut_type == USER_PROCESS
954 && utp->ut_user[0] != 0
955 && strncmp (user, utp->ut_user, sizeof(utp->ut_user)) == 0) {
959 return (utmped = DONE);
964 return (utmped = NOTOK);
976 if ((uf = fopen (UTMP_FILE, "r")) == NULL)
979 while (fread ((char *) &ut, sizeof(ut), 1, uf) == 1) {
980 if (ut.ut_name[0] != 0
981 && strncmp (user, ut.ut_name, sizeof(ut.ut_name)) == 0) {
985 return (utmped = DONE);
990 return (utmped = NOTOK);
994 #define check(t,a,b) if (t < a || t > b) return -1
995 #define cmpar(h1,m1,h2,m2) if (h1 < h2 || (h1 == h2 && m1 < m2)) return 0
998 timely (char *t1, char *t2)
1000 int t1hours, t1mins, t2hours, t2mins;
1002 if (sscanf (t1, "%d:%d", &t1hours, &t1mins) != 2)
1004 check (t1hours, 0, 23);
1005 check (t1mins, 0, 59);
1007 if (sscanf (t2, "%d:%d", &t2hours, &t2mins) != 2)
1009 check (t2hours, 0, 23);
1010 check (t2mins, 0, 59);
1012 cmpar (now->tw_hour, now->tw_min, t1hours, t1mins);
1013 cmpar (t2hours, t2mins, now->tw_hour, now->tw_min);
1020 * Deliver message by appending to a file.
1024 usr_file (int fd, char *mailbox, int mbx_style)
1029 verbose_printf ("delivering to file \"%s\"", mailbox);
1031 if (mbx_style == MBOX_FORMAT) {
1033 verbose_printf (" (mbox style)");
1037 verbose_printf (" (mmdf style)");
1041 /* open and lock the file */
1042 if ((md = mbx_open (mailbox, mbx_style, pw->pw_uid, pw->pw_gid, m_gmprot())) == -1) {
1044 adorn ("", "unable to open:");
1048 lseek (fd, (off_t) 0, SEEK_SET);
1050 /* append message to file */
1051 if (mbx_copy (mailbox, mbx_style, md, fd, mapping, NULL, verbose) == -1) {
1053 adorn ("", "error writing to:");
1057 /* close and unlock file */
1058 mbx_close (mailbox, md);
1061 verbose_printf (", success.\n");
1067 * Deliver message to a nmh folder.
1071 usr_folder (int fd, char *string)
1074 char folder[BUFSIZ], *vec[3];
1076 /* get folder name ready */
1078 strncpy(folder, string, sizeof(folder));
1080 snprintf(folder, sizeof(folder), "+%s", string);
1083 verbose_printf ("delivering to folder \"%s\"", folder + 1);
1085 vec[0] = "rcvstore";
1089 /* use rcvstore to put message in folder */
1090 status = usr_pipe (fd, "rcvstore", rcvstoreproc, vec, 1);
1094 * Currently, verbose status messages are handled by usr_pipe().
1098 verbose_printf (", success.\n");
1100 verbose_printf (", failed.\n");
1108 * Deliver message to a process.
1112 usr_pipe (int fd, char *cmd, char *pgm, char **vec, int suppress)
1115 int i, bytes, seconds, status;
1118 if (verbose && !suppress)
1119 verbose_printf ("delivering to pipe \"%s\"", cmd);
1121 lseek (fd, (off_t) 0, SEEK_SET);
1123 for (i = 0; (child_id = fork()) == -1 && i < 5; i++)
1130 adorn ("fork", "unable to");
1137 freopen ("/dev/null", "w", stdout);
1138 freopen ("/dev/null", "w", stderr);
1144 if ((fd = open ("/dev/tty", O_RDWR)) != -1) {
1145 ioctl (fd, TIOCNOTTY, NULL);
1148 #endif /* TIOCNOTTY */
1150 setpgid ((pid_t) 0, getpid ()); /* put in own process group */
1153 m_putenv ("USER", pw->pw_name);
1154 m_putenv ("HOME", pw->pw_dir);
1155 m_putenv ("SHELL", pw->pw_shell);
1161 /* parent process */
1162 if (!setjmp (myctx)) {
1163 SIGNAL (SIGALRM, alrmser);
1164 bytes = fstat (fd, &st) != -1 ? (int) st.st_size : 100;
1166 /* amount of time to wait depends on message size */
1168 /* give at least 5 minutes */
1170 } else if (bytes >= 90000) {
1171 /* a half hour is long enough */
1174 seconds = (bytes / 60) + 300;
1176 alarm ((unsigned int) seconds);
1177 status = pidwait (child_id, 0);
1181 if (status == RP_MOK || status == RP_OK)
1186 verbose_printf (", success.\n");
1188 if ((status & 0xff00) == 0xff00)
1189 verbose_printf (", system error\n");
1191 pidstatus (status, stdout, ", failed");
1193 return (status == 0 ? 0 : -1);
1196 * Ruthlessly kill the child and anything
1197 * else in its process group.
1199 KILLPG(child_id, SIGKILL);
1201 verbose_printf (", timed-out; terminated\n");
1211 #ifndef RELIABLE_SIGNALS
1212 SIGNAL (SIGALRM, alrmser);
1215 longjmp (myctx, DONE);
1220 * Get the `sender' from the envelope
1221 * information ("From " line).
1225 get_sender (char *envelope, char **sender)
1229 char buffer[BUFSIZ];
1231 if (envelope == NULL) {
1232 *sender = getcpy ("");
1236 i = strlen ("From ");
1237 strncpy (buffer, envelope + i, sizeof(buffer));
1238 if ((cp = strchr(buffer, '\n'))) {
1248 for (cp = buffer + strlen (buffer) - 1; cp >= buffer; cp--)
1253 *sender = getcpy (buffer);
1258 * Copy message into a temporary file.
1259 * While copying, it will do some header processing
1260 * including the extraction of the envelope information.
1264 copy_message (int qd, char *tmpfil, int fold)
1266 int i, first = 1, fd1, fd2;
1267 char buffer[BUFSIZ];
1270 strcpy (tmpfil, m_tmpfil (invo_name));
1272 /* open temporary file to put message in */
1273 if ((fd1 = open (tmpfil, O_RDWR | O_CREAT | O_TRUNC, 0600)) == -1)
1277 while ((i = read (qd, buffer, sizeof(buffer))) > 0)
1278 if (write (fd1, buffer, i) != i) {
1286 lseek (fd1, (off_t) 0, SEEK_SET);
1290 /* dup the fd for incoming message */
1291 if ((fd2 = dup (qd)) == -1) {
1296 /* now create a FILE pointer for it */
1297 if ((qfp = fdopen (fd2, "r")) == NULL) {
1303 /* dup the fd for temporary file */
1304 if ((fd2 = dup (fd1)) == -1) {
1310 /* now create a FILE pointer for it */
1311 if ((ffp = fdopen (fd2, "r+")) == NULL) {
1319 * copy message into temporary file
1320 * and massage the headers. Save
1321 * a copy of the "From " line for later.
1323 i = strlen ("From ");
1324 while (fgets (buffer, sizeof(buffer), qfp)) {
1327 if (!strncmp (buffer, "From ", i)) {
1329 char *fp, *cp, *hp, *ep;
1331 /* get copy of envelope information ("From " line) */
1332 envelope = getcpy (buffer);
1335 /* First go ahead and put "From " line in message */
1336 fputs (buffer, ffp);
1343 * Now create a "Return-Path:" line
1344 * from the "From " line.
1346 hp = cp = strchr(fp = envelope + i, ' ');
1347 while ((hp = strchr(++hp, 'r')))
1348 if (uprf (hp, "remote from")) {
1349 hp = strrchr(hp, ' ');
1353 /* return path for UUCP style addressing */
1354 ep = strchr(++hp, '\n');
1355 snprintf (buffer, sizeof(buffer), "Return-Path: %.*s!%.*s\n",
1356 ep - hp, hp, cp - fp, fp);
1358 /* return path for standard domain addressing */
1359 snprintf (buffer, sizeof(buffer), "Return-Path: %.*s\n",
1363 /* Add Return-Path header to message */
1364 fputs (buffer, ffp);
1368 /* Put the delivery date in message */
1377 fputs (buffer, ffp);
1389 lseek (fd1, (off_t) 0, SEEK_SET);
1401 * Trim strings for pretty printing of debugging output
1407 char buffer[BUFSIZ*4];
1413 /* copy string into temp buffer */
1414 strncpy (buffer, cp, sizeof(buffer));
1417 /* skip over leading whitespace */
1418 while (isspace(*bp))
1421 /* start at the end and zap trailing whitespace */
1422 for (sp = bp + strlen(bp) - 1; sp >= bp; sp--) {
1429 /* replace remaining whitespace with spaces */
1430 for (sp = bp; *sp; sp++)
1434 /* now return a copy */
1439 * Function for printing `verbose' messages.
1443 verbose_printf (char *fmt, ...)
1448 vfprintf (stdout, fmt, ap);
1451 fflush (stdout); /* now flush output */
1456 * Function for printing `verbose' delivery
1461 adorn (char *what, char *fmt, ...)
1467 eindex = errno; /* save the errno */
1468 fprintf (stdout, ", ");
1471 vfprintf (stdout, fmt, ap);
1476 fprintf (stdout, " %s: ", what);
1477 if ((s = strerror (eindex)))
1478 fprintf (stdout, "%s", s);
1480 fprintf (stdout, "Error %d", eindex);
1483 fputc ('\n', stdout);
1489 * Function for printing `debug' messages.
1493 debug_printf (char *fmt, ...)
1498 vfprintf (stderr, fmt, ap);
1504 * Check ndbm/db file(s) to see if the Message-Id of this
1505 * message matches the Message-Id of a previous message,
1506 * so we can discard it. If it doesn't match, we add the
1507 * Message-Id of this message to the ndbm/db file.
1510 suppress_duplicates (int fd, char *file)
1512 int fd1, lockfd, state, result;
1513 char *cp, buf[BUFSIZ], name[NAMESZ];
1518 if ((fd1 = dup (fd)) == -1)
1520 if (!(in = fdopen (fd1, "r"))) {
1526 for (state = FLD;;) {
1527 state = m_getfld (state, name, buf, sizeof(buf), in);
1532 /* Search for the message ID */
1533 if (strcasecmp (name, "Message-ID")) {
1534 while (state == FLDPLUS)
1535 state = m_getfld (state, name, buf, sizeof(buf), in);
1539 cp = add (buf, NULL);
1540 while (state == FLDPLUS) {
1541 state = m_getfld (state, name, buf, sizeof(buf), in);
1544 key.dptr = trimcpy (cp);
1545 key.dsize = strlen (key.dptr) + 1;
1549 if (!(db = dbm_open (file, O_RDWR | O_CREAT, 0600))) {
1550 advise (file, "unable to perform dbm_open on");
1556 * Since it is difficult to portable lock a ndbm file,
1557 * we will open and lock the Maildelivery file instead.
1558 * This will fail if your Maildelivery file doesn't
1561 if ((lockfd = lkopen(file, O_RDWR, 0)) == -1) {
1562 advise (file, "unable to perform file locking on");
1567 value = dbm_fetch (db, key);
1570 verbose_printf ("Message-ID: %s\n already received on %s",
1574 value.dptr = ddate + sizeof("Delivery-Date:");
1575 value.dsize = strlen(value.dptr) + 1;
1576 if (dbm_store (db, key, value, DBM_INSERT))
1577 advise (file, "possibly corrupt file");
1582 lkclose(lockfd, file);