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>
58 #if defined(HAVE_DB_H) && defined(HAVE_LIBDB)
59 #define DB_DBM_HSEARCH 1
72 # define UTMP_FILE _PATH_UTMP
74 # define UTMP_FILE "/etc/utmp"
79 static struct swit switches[] = {
81 { "addr address", 0 },
87 { "sender address", 0 },
89 { "mailbox file", 0 },
91 { "home directory", -4 },
95 { "maildelivery file", 0 },
100 #define SUPPRESSDUP 10
101 { "suppressdup", 0 },
102 #define NSUPPRESSDUP 11
103 { "nosuppressdup", 0 },
113 static int globbed = 0; /* have we built "vars" table yet? */
114 static int parsed = 0; /* have we built header field table yet */
115 static int utmped = 0; /* have we scanned umtp(x) file yet */
116 static int suppressdup = 0; /* are we suppressing duplicate messages? */
118 static int verbose = 0;
119 static int debug = 0;
121 static char *addr = NULL;
122 static char *user = NULL;
123 static char *info = NULL;
124 static char *file = NULL;
125 static char *sender = NULL;
126 static char *envelope = NULL; /* envelope information ("From " line) */
127 static char *mbox = NULL;
128 static char *home = NULL;
130 static struct passwd *pw; /* passwd file entry */
132 static char ddate[BUFSIZ]; /* record the delivery date */
135 static jmp_buf myctx;
137 /* flags for pair->p_flags */
139 #define P_ADR 0x01 /* field is address */
140 #define P_HID 0x02 /* special (fake) field */
152 * Lookup table for matching fields and patterns
153 * in messages. The rest of the table is added
154 * when the message is parsed.
156 static struct pair hdrs[NVEC + 1] = {
157 { "source", NULL, P_HID },
158 { "addr", NULL, P_HID },
159 { "Return-Path", NULL, P_ADR },
160 { "Reply-To", NULL, P_ADR },
161 { "From", NULL, P_ADR },
162 { "Sender", NULL, P_ADR },
163 { "To", NULL, P_ADR },
164 { "cc", NULL, P_ADR },
165 { "Resent-Reply-To", NULL, P_ADR },
166 { "Resent-From", NULL, P_ADR },
167 { "Resent-Sender", NULL, P_ADR },
168 { "Resent-To", NULL, P_ADR },
169 { "Resent-cc", NULL, P_ADR },
174 * The list of builtin variables to expand in a string
175 * before it is executed by the "pipe" or "qpipe" action.
177 static struct pair vars[] = {
178 { "sender", NULL, P_NIL },
179 { "address", NULL, P_NIL },
180 { "size", NULL, P_NIL },
181 { "reply-to", NULL, P_CHK },
182 { "info", NULL, P_NIL },
186 extern char **environ;
191 static int localmail (int, char *);
192 static int usr_delivery (int, char *, int);
193 static int split (char *, char **);
194 static int parse (int);
195 static void expand (char *, char *, int);
196 static void glob (int);
197 static struct pair *lookup (struct pair *, char *);
198 static int logged_in (void);
199 static int timely (char *, char *);
200 static int usr_file (int, char *, int);
201 static int usr_pipe (int, char *, char *, char **, int);
202 static int usr_folder (int, char *);
203 static RETSIGTYPE alrmser (int);
204 static void get_sender (char *, char **);
205 static int copy_message (int, char *, int);
206 static void verbose_printf (char *fmt, ...);
207 static void adorn (char *, char *, ...);
208 static void debug_printf (char *fmt, ...);
209 static int suppress_duplicates (int, char *);
210 static char *trim (char *);
214 main (int argc, char **argv)
218 char *cp, *mdlvr = NULL, buf[BUFSIZ];
219 char mailbox[BUFSIZ], tmpfil[BUFSIZ];
220 char **argp, **arguments;
223 setlocale(LC_ALL, "");
225 invo_name = r1bindex (*argv, '/');
227 /* foil search of user profile/context */
228 if (context_foil (NULL) == -1)
231 mts_init (invo_name);
232 arguments = getarguments (invo_name, argc, argv, 0);
235 /* Parse arguments */
236 while ((cp = *argp++)) {
238 switch (smatch (++cp, switches)) {
240 ambigsw (cp, switches);
243 adios (NULL, "-%s unknown", cp);
246 snprintf (buf, sizeof(buf),
247 "%s [switches] [address info sender]", invo_name);
248 print_help (buf, switches, 0);
251 print_version(invo_name);
255 if (!(addr = *argp++))/* allow -xyz arguments */
256 adios (NULL, "missing argument to %s", argp[-2]);
259 if (!(info = *argp++))/* allow -xyz arguments */
260 adios (NULL, "missing argument to %s", argp[-2]);
263 if (!(user = *argp++))/* allow -xyz arguments */
264 adios (NULL, "missing argument to %s", argp[-2]);
267 if (!(file = *argp++) || *file == '-')
268 adios (NULL, "missing argument to %s", argp[-2]);
271 if (!(sender = *argp++))/* allow -xyz arguments */
272 adios (NULL, "missing argument to %s", argp[-2]);
275 if (!(mbox = *argp++) || *mbox == '-')
276 adios (NULL, "missing argument to %s", argp[-2]);
279 if (!(home = *argp++) || *home == '-')
280 adios (NULL, "missing argument to %s", argp[-2]);
284 if (!(cp = *argp++) || *cp == '-')
285 adios (NULL, "missing argument to %s", argp[-2]);
287 adios (NULL, "only one maildelivery file at a time!");
310 switch (argp - (argv + 1)) {
326 addr = getusername ();
328 user = (cp = strchr(addr, '.')) ? ++cp : addr;
329 if ((pw = getpwnam (user)) == NULL)
330 adios (NULL, "no such local user as %s", user);
332 if (chdir (pw->pw_dir) == -1)
336 if (geteuid() == 0) {
338 initgroups (pw->pw_name, pw->pw_gid);
345 setbuf (stdin, NULL);
347 /* Record the delivery time */
348 if ((now = dlocaltimenow ()) == NULL)
349 adios (NULL, "unable to ascertain local time");
350 snprintf (ddate, sizeof(ddate), "Delivery-Date: %s\n", dtimenow (0));
353 * Copy the message to a temporary file
358 /* getting message from file */
359 if ((tempfd = open (file, O_RDONLY)) == -1)
360 adios (file, "unable to open");
362 debug_printf ("retrieving message from file \"%s\"\n", file);
363 if ((fd = copy_message (tempfd, tmpfil, 1)) == -1)
364 adios (NULL, "unable to create temporary file");
367 /* getting message from stdin */
369 debug_printf ("retrieving message from stdin\n");
370 if ((fd = copy_message (fileno (stdin), tmpfil, 1)) == -1)
371 adios (NULL, "unable to create temporary file");
375 debug_printf ("temporary file=\"%s\"\n", tmpfil);
377 /* Delete the temp file now or a copy of every single message passed through
378 slocal will be left in the /tmp directory until deleted manually! This
379 unlink() used to be under an 'else' of the 'if (debug)' above, but since
380 some people like to always run slocal with -debug and log the results,
381 the /tmp directory would get choked over time. Of course, now that we
382 always delete the temp file, the "temporary file=" message above is
383 somewhat pointless -- someone watching debug output wouldn't have a
384 chance to 'tail -f' or 'ln' the temp file before it's unlinked. The best
385 thing would be to delay this unlink() until later if debug == 1, but I'll
386 leave that for someone who cares about the temp-file-accessing
387 functionality (they'll have to watch out for cases where we adios()). */
390 if (!(fp = fdopen (fd, "r+")))
391 adios (NULL, "unable to access temporary file");
394 * If no sender given, extract it
395 * from envelope information. */
397 get_sender (envelope, &sender);
400 snprintf (mailbox, sizeof(mailbox), "%s/%s",
401 mmdfldir[0] ? mmdfldir : pw->pw_dir,
402 mmdflfil[0] ? mmdflfil : pw->pw_name);
409 debug_printf ("addr=\"%s\"\n", trim(addr));
410 debug_printf ("user=\"%s\"\n", trim(user));
411 debug_printf ("info=\"%s\"\n", trim(info));
412 debug_printf ("sender=\"%s\"\n", trim(sender));
413 debug_printf ("envelope=\"%s\"\n", envelope ? trim(envelope) : "");
414 debug_printf ("mbox=\"%s\"\n", trim(mbox));
415 debug_printf ("home=\"%s\"\n", trim(home));
416 debug_printf ("ddate=\"%s\"\n", trim(ddate));
417 debug_printf ("now=%02d:%02d\n\n", now->tw_hour, now->tw_min);
420 /* deliver the message */
421 status = localmail (fd, mdlvr);
423 return done (status != -1 ? RCV_MOK : RCV_MBX);
428 * Main routine for delivering message.
432 localmail (int fd, char *mdlvr)
434 /* check if this message is a duplicate */
436 suppress_duplicates(fd, mdlvr ? mdlvr : ".maildelivery") == DONE)
439 /* delivery according to personal Maildelivery file */
440 if (usr_delivery (fd, mdlvr ? mdlvr : ".maildelivery", 0) != -1)
443 /* delivery according to global Maildelivery file */
444 if (usr_delivery (fd, maildelivery, 1) != -1)
448 verbose_printf ("(delivering to standard mail spool)\n");
450 /* last resort - deliver to standard mail spool */
452 return usr_file (fd, mbox, MBOX_FORMAT);
454 return usr_file (fd, mbox, MMDF_FORMAT);
459 #define matches(a,b) (stringdex (b, a) >= 0)
462 * Parse the delivery file, and process incoming message.
466 usr_delivery (int fd, char *delivery, int su)
468 int i, accept, status=1, won, vecp, next;
469 char *field, *pattern, *action, *result, *string;
470 char buffer[BUFSIZ], tmpbuf[BUFSIZ];
471 char *cp, *vec[NVEC];
476 /* open the delivery file */
477 if ((fp = fopen (delivery, "r")) == NULL)
480 /* check if delivery file has bad ownership or permissions */
481 if (fstat (fileno (fp), &st) == -1
482 || (st.st_uid != 0 && (su || st.st_uid != pw->pw_uid))
483 || st.st_mode & (S_IWGRP|S_IWOTH)) {
485 verbose_printf ("WARNING: %s has bad ownership/modes (su=%d,uid=%d,owner=%d,mode=0%o)\n",
486 delivery, su, (int) pw->pw_uid, (int) st.st_uid, (int) st.st_mode);
494 /* read and process delivery file */
495 while (fgets (buffer, sizeof(buffer), fp)) {
496 /* skip comments and empty lines */
497 if (*buffer == '#' || *buffer == '\n')
500 /* zap trailing newline */
501 if ((cp = strchr(buffer, '\n')))
504 /* split buffer into fields */
505 vecp = split (buffer, vec);
507 /* check for too few fields */
510 debug_printf ("WARNING: entry with only %d fields, skipping.\n", vecp);
515 for (i = 0; vec[i]; i++)
516 debug_printf ("vec[%d]: \"%s\"\n", i, trim(vec[i]));
525 /* find out how to perform the action */
530 * If previous condition failed, don't
531 * do this - else fall through
534 continue; /* else fall */
538 * If already delivered, skip this action. Else
539 * consider delivered if action is successful.
542 continue; /* else fall */
547 * Take action, and consider delivered if
548 * action is successful.
557 * Take action, but don't consider delivered, even
558 * if action is successful
565 if (!strcasecmp (vec[5], "select")) {
566 if (logged_in () != -1)
568 if (vecp > 7 && timely (vec[6], vec[7]) == -1)
573 /* check if the field matches */
581 * "default" matches only if the message hasn't
582 * been delivered yet.
584 if (!strcasecmp (field, "default")) {
591 /* parse message and build lookup table */
592 if (!parsed && parse (fd) == -1) {
597 * find header field in lookup table, and
598 * see if the pattern matches.
600 if ((p = lookup (hdrs, field)) && (p->p_value != NULL)
601 && matches (p->p_value, pattern)) {
610 /* find out the action to perform */
613 /* deliver to quoted pipe */
614 if (strcasecmp (action, "qpipe"))
615 continue; /* else fall */
617 expand (tmpbuf, string, fd);
618 if (split (tmpbuf, vec) < 1)
620 status = usr_pipe (fd, tmpbuf, vec[0], vec, 0);
624 /* deliver to pipe */
625 if (strcasecmp (action, "pipe"))
626 continue; /* else fall */
630 expand (tmpbuf, string, fd);
633 status = usr_pipe (fd, tmpbuf, "/bin/sh", vec + 2, 0);
638 if (!strcasecmp (action, "file")) {
639 status = usr_file (fd, string, MBOX_FORMAT);
642 /* deliver to nmh folder */
643 else if (strcasecmp (action, "folder"))
644 continue; /* else fall */
646 status = usr_folder (fd, string);
651 if (!strcasecmp (action, "mmdf")) {
652 status = usr_file (fd, string, MMDF_FORMAT);
656 else if (strcasecmp (action, "mbox"))
657 continue; /* else fall */
661 status = usr_file (fd, string, MBOX_FORMAT);
666 if (strcasecmp (action, "destroy"))
672 if (status) next = 0; /* action failed, mark for 'N' result */
674 if (accept && status == 0)
679 return (won ? 0 : -1);
686 * Split buffer into fields (delimited by whitespace or
687 * comma's). Return the number of fields found.
691 split (char *cp, char **vec)
698 /* split into a maximum of NVEC fields */
699 for (i = 0; i <= NVEC;) {
702 /* zap any whitespace and comma's */
703 while (isspace (*s) || *s == ',')
706 /* end of buffer, time to leave */
710 /* get double quote text as a single field */
712 for (vec[i++] = ++s; *s && *s != '"'; s++) {
714 * Check for escaped double quote. We need
715 * to shift the string to remove slash.
723 if (*s == '"') /* zap trailing double quote */
728 if (*s == QUOTE && *++s != '"')
732 /* move forward to next field delimiter */
733 while (*s && !isspace (*s) && *s != ',')
743 * Parse the headers of a message, and build the
744 * lookup table for matching fields and patterns.
753 char name[NAMESZ], field[BUFSIZ];
760 /* get a new FILE pointer to message */
761 if ((fd1 = dup (fd)) == -1)
763 if ((in = fdopen (fd1, "r")) == NULL) {
769 /* add special entries to lookup table */
770 if ((p = lookup (hdrs, "source")))
771 p->p_value = getcpy (sender);
772 if ((p = lookup (hdrs, "addr")))
773 p->p_value = getcpy (addr);
776 * Scan the headers of the message and build
779 for (i = 0, state = FLD;;) {
780 switch (state = m_getfld (state, name, field, sizeof(field), in)) {
784 lp = add (field, NULL);
785 while (state == FLDPLUS) {
786 state = m_getfld (state, name, field, sizeof(field), in);
787 lp = add (field, lp);
789 for (p = hdrs; p->p_name; p++) {
790 if (!strcasecmp (p->p_name, name)) {
791 if (!(p->p_flags & P_HID)) {
792 if ((cp = p->p_value)) {
793 if (p->p_flags & P_ADR) {
794 dp = cp + strlen (cp) - 1;
797 cp = add (",\n\t", cp);
802 p->p_value = add (lp, cp);
808 if (p->p_name == NULL && i < NVEC) {
809 p->p_name = getcpy (name);
826 advise (NULL, "format error in message");
830 advise (NULL, "internal error in m_getfld");
838 if ((p = lookup (vars, "reply-to"))) {
839 if ((q = lookup (hdrs, "reply-to")) == NULL || q->p_value == NULL)
840 q = lookup (hdrs, "from");
841 p->p_value = getcpy (q ? q->p_value : "");
842 p->p_flags &= ~P_CHK;
844 debug_printf ("vars[%d]: name=\"%s\" value=\"%s\"\n",
845 p - vars, p->p_name, trim(p->p_value));
848 for (p = hdrs; p->p_name; p++)
849 debug_printf ("hdrs[%d]: name=\"%s\" value=\"%s\"\n",
850 p - hdrs, p->p_name, p->p_value ? trim(p->p_value) : "");
861 * Expand any builtin variables such as $(sender),
862 * $(address), etc., in a string.
866 expand (char *s1, char *s2, int fd)
874 while ((c = *s2++)) {
875 if (c != '$' || *s2 != LPAREN) {
878 for (cp = ++s2; *s2 && *s2 != RPAREN; s2++)
885 if ((p = lookup (vars, cp))) {
886 if (!parsed && (p->p_flags & P_CHK))
889 strcpy (s1, p->p_value);
899 * Fill in the information missing from the "vars"
900 * table, which is necessary to expand any builtin
901 * variables in the string for a "pipe" or "qpipe"
915 if ((p = lookup (vars, "sender")))
916 p->p_value = getcpy (sender);
917 if ((p = lookup (vars, "address")))
918 p->p_value = getcpy (addr);
919 if ((p = lookup (vars, "size"))) {
920 snprintf (buffer, sizeof(buffer), "%d",
921 fstat (fd, &st) != -1 ? (int) st.st_size : 0);
922 p->p_value = getcpy (buffer);
924 if ((p = lookup (vars, "info")))
925 p->p_value = getcpy (info);
928 for (p = vars; p->p_name; p++)
929 debug_printf ("vars[%d]: name=\"%s\" value=\"%s\"\n",
930 p - vars, p->p_name, trim(p->p_value));
936 * Find a matching name in a lookup table. If found,
937 * return the "pairs" entry, else return NULL.
941 lookup (struct pair *pairs, char *key)
943 for (; pairs->p_name; pairs++)
944 if (!strcasecmp (pairs->p_name, key))
952 * Check utmp(x) file to see if user is currently
967 while ((utp = getutent()) != NULL) {
968 if (utp->ut_type == USER_PROCESS
969 && utp->ut_user[0] != 0
970 && strncmp (user, utp->ut_user, sizeof(utp->ut_user)) == 0) {
974 return (utmped = DONE);
979 return (utmped = NOTOK);
991 if ((uf = fopen (UTMP_FILE, "r")) == NULL)
994 while (fread ((char *) &ut, sizeof(ut), 1, uf) == 1) {
995 if (ut.ut_name[0] != 0
996 && strncmp (user, ut.ut_name, sizeof(ut.ut_name)) == 0) {
1000 return (utmped = DONE);
1005 return (utmped = NOTOK);
1009 #define check(t,a,b) if (t < a || t > b) return -1
1010 #define cmpar(h1,m1,h2,m2) if (h1 < h2 || (h1 == h2 && m1 < m2)) return 0
1013 timely (char *t1, char *t2)
1015 int t1hours, t1mins, t2hours, t2mins;
1017 if (sscanf (t1, "%d:%d", &t1hours, &t1mins) != 2)
1019 check (t1hours, 0, 23);
1020 check (t1mins, 0, 59);
1022 if (sscanf (t2, "%d:%d", &t2hours, &t2mins) != 2)
1024 check (t2hours, 0, 23);
1025 check (t2mins, 0, 59);
1027 cmpar (now->tw_hour, now->tw_min, t1hours, t1mins);
1028 cmpar (t2hours, t2mins, now->tw_hour, now->tw_min);
1035 * Deliver message by appending to a file.
1039 usr_file (int fd, char *mailbox, int mbx_style)
1044 verbose_printf ("delivering to file \"%s\"", mailbox);
1046 if (mbx_style == MBOX_FORMAT) {
1048 verbose_printf (" (mbox style)");
1052 verbose_printf (" (mmdf style)");
1056 /* open and lock the file */
1057 if ((md = mbx_open (mailbox, mbx_style, pw->pw_uid, pw->pw_gid, m_gmprot())) == -1) {
1059 adorn ("", "unable to open:");
1063 lseek (fd, (off_t) 0, SEEK_SET);
1065 /* append message to file */
1066 if (mbx_copy (mailbox, mbx_style, md, fd, mapping, NULL, verbose) == -1) {
1068 adorn ("", "error writing to:");
1072 /* close and unlock file */
1073 mbx_close (mailbox, md);
1076 verbose_printf (", success.\n");
1082 * Deliver message to a nmh folder.
1086 usr_folder (int fd, char *string)
1089 char folder[BUFSIZ], *vec[3];
1091 /* get folder name ready */
1093 strncpy(folder, string, sizeof(folder));
1095 snprintf(folder, sizeof(folder), "+%s", string);
1098 verbose_printf ("delivering to folder \"%s\"", folder + 1);
1100 vec[0] = "rcvstore";
1104 /* use rcvstore to put message in folder */
1105 status = usr_pipe (fd, "rcvstore", rcvstoreproc, vec, 1);
1109 * Currently, verbose status messages are handled by usr_pipe().
1113 verbose_printf (", success.\n");
1115 verbose_printf (", failed.\n");
1123 * Deliver message to a process.
1127 usr_pipe (int fd, char *cmd, char *pgm, char **vec, int suppress)
1130 int i, bytes, seconds, status;
1133 if (verbose && !suppress)
1134 verbose_printf ("delivering to pipe \"%s\"", cmd);
1136 lseek (fd, (off_t) 0, SEEK_SET);
1138 for (i = 0; (child_id = fork()) == -1 && i < 5; i++)
1145 adorn ("fork", "unable to");
1152 freopen ("/dev/null", "w", stdout);
1153 freopen ("/dev/null", "w", stderr);
1159 if ((fd = open ("/dev/tty", O_RDWR)) != -1) {
1160 ioctl (fd, TIOCNOTTY, NULL);
1163 #endif /* TIOCNOTTY */
1165 setpgid ((pid_t) 0, getpid ()); /* put in own process group */
1168 m_putenv ("USER", pw->pw_name);
1169 m_putenv ("HOME", pw->pw_dir);
1170 m_putenv ("SHELL", pw->pw_shell);
1176 /* parent process */
1177 if (!setjmp (myctx)) {
1178 SIGNAL (SIGALRM, alrmser);
1179 bytes = fstat (fd, &st) != -1 ? (int) st.st_size : 100;
1181 /* amount of time to wait depends on message size */
1183 /* give at least 5 minutes */
1185 } else if (bytes >= 90000) {
1186 /* a half hour is long enough */
1189 seconds = (bytes / 60) + 300;
1191 alarm ((unsigned int) seconds);
1192 status = pidwait (child_id, 0);
1196 if (status == RP_MOK || status == RP_OK)
1201 verbose_printf (", success.\n");
1203 if ((status & 0xff00) == 0xff00)
1204 verbose_printf (", system error\n");
1206 pidstatus (status, stdout, ", failed");
1208 return (status == 0 ? 0 : -1);
1211 * Ruthlessly kill the child and anything
1212 * else in its process group.
1214 KILLPG(child_id, SIGKILL);
1216 verbose_printf (", timed-out; terminated\n");
1226 #ifndef RELIABLE_SIGNALS
1227 SIGNAL (SIGALRM, alrmser);
1230 longjmp (myctx, DONE);
1235 * Get the `sender' from the envelope
1236 * information ("From " line).
1240 get_sender (char *envelope, char **sender)
1244 char buffer[BUFSIZ];
1246 if (envelope == NULL) {
1247 *sender = getcpy ("");
1251 i = strlen ("From ");
1252 strncpy (buffer, envelope + i, sizeof(buffer));
1253 if ((cp = strchr(buffer, '\n'))) {
1263 for (cp = buffer + strlen (buffer) - 1; cp >= buffer; cp--)
1268 *sender = getcpy (buffer);
1273 * Copy message into a temporary file.
1274 * While copying, it will do some header processing
1275 * including the extraction of the envelope information.
1279 copy_message (int qd, char *tmpfil, int fold)
1281 int i, first = 1, fd1, fd2;
1282 char buffer[BUFSIZ];
1285 strcpy (tmpfil, m_tmpfil (invo_name));
1287 /* open temporary file to put message in */
1288 if ((fd1 = open (tmpfil, O_RDWR | O_CREAT | O_TRUNC, 0600)) == -1)
1292 while ((i = read (qd, buffer, sizeof(buffer))) > 0)
1293 if (write (fd1, buffer, i) != i) {
1301 lseek (fd1, (off_t) 0, SEEK_SET);
1305 /* dup the fd for incoming message */
1306 if ((fd2 = dup (qd)) == -1) {
1311 /* now create a FILE pointer for it */
1312 if ((qfp = fdopen (fd2, "r")) == NULL) {
1318 /* dup the fd for temporary file */
1319 if ((fd2 = dup (fd1)) == -1) {
1325 /* now create a FILE pointer for it */
1326 if ((ffp = fdopen (fd2, "r+")) == NULL) {
1334 * copy message into temporary file
1335 * and massage the headers. Save
1336 * a copy of the "From " line for later.
1338 i = strlen ("From ");
1339 while (fgets (buffer, sizeof(buffer), qfp)) {
1342 if (!strncmp (buffer, "From ", i)) {
1344 char *fp, *cp, *hp, *ep;
1346 /* get copy of envelope information ("From " line) */
1347 envelope = getcpy (buffer);
1350 /* First go ahead and put "From " line in message */
1351 fputs (buffer, ffp);
1358 * Now create a "Return-Path:" line
1359 * from the "From " line.
1361 hp = cp = strchr(fp = envelope + i, ' ');
1362 while ((hp = strchr(++hp, 'r')))
1363 if (uprf (hp, "remote from")) {
1364 hp = strrchr(hp, ' ');
1368 /* return path for UUCP style addressing */
1369 ep = strchr(++hp, '\n');
1370 snprintf (buffer, sizeof(buffer), "Return-Path: %.*s!%.*s\n",
1371 ep - hp, hp, cp - fp, fp);
1373 /* return path for standard domain addressing */
1374 snprintf (buffer, sizeof(buffer), "Return-Path: %.*s\n",
1378 /* Add Return-Path header to message */
1379 fputs (buffer, ffp);
1383 /* Put the delivery date in message */
1392 fputs (buffer, ffp);
1404 lseek (fd1, (off_t) 0, SEEK_SET);
1416 * Trim strings for pretty printing of debugging output
1422 char buffer[BUFSIZ*4];
1428 /* copy string into temp buffer */
1429 strncpy (buffer, cp, sizeof(buffer));
1432 /* skip over leading whitespace */
1433 while (isspace(*bp))
1436 /* start at the end and zap trailing whitespace */
1437 for (sp = bp + strlen(bp) - 1; sp >= bp; sp--) {
1444 /* replace remaining whitespace with spaces */
1445 for (sp = bp; *sp; sp++)
1449 /* now return a copy */
1454 * Function for printing `verbose' messages.
1458 verbose_printf (char *fmt, ...)
1463 vfprintf (stdout, fmt, ap);
1466 fflush (stdout); /* now flush output */
1471 * Function for printing `verbose' delivery
1476 adorn (char *what, char *fmt, ...)
1482 eindex = errno; /* save the errno */
1483 fprintf (stdout, ", ");
1486 vfprintf (stdout, fmt, ap);
1491 fprintf (stdout, " %s: ", what);
1492 if ((s = strerror (eindex)))
1493 fprintf (stdout, "%s", s);
1495 fprintf (stdout, "Error %d", eindex);
1498 fputc ('\n', stdout);
1504 * Function for printing `debug' messages.
1508 debug_printf (char *fmt, ...)
1513 vfprintf (stderr, fmt, ap);
1519 * Check ndbm/db file(s) to see if the Message-Id of this
1520 * message matches the Message-Id of a previous message,
1521 * so we can discard it. If it doesn't match, we add the
1522 * Message-Id of this message to the ndbm/db file.
1525 suppress_duplicates (int fd, char *file)
1527 int fd1, lockfd, state, result;
1528 char *cp, buf[BUFSIZ], name[NAMESZ];
1533 if ((fd1 = dup (fd)) == -1)
1535 if (!(in = fdopen (fd1, "r"))) {
1541 for (state = FLD;;) {
1542 state = m_getfld (state, name, buf, sizeof(buf), in);
1547 /* Search for the message ID */
1548 if (strcasecmp (name, "Message-ID")) {
1549 while (state == FLDPLUS)
1550 state = m_getfld (state, name, buf, sizeof(buf), in);
1554 cp = add (buf, NULL);
1555 while (state == FLDPLUS) {
1556 state = m_getfld (state, name, buf, sizeof(buf), in);
1559 key.dptr = trimcpy (cp);
1560 key.dsize = strlen (key.dptr) + 1;
1564 if (!(db = dbm_open (file, O_RDWR | O_CREAT, 0600))) {
1565 advise (file, "unable to perform dbm_open on");
1571 * Since it is difficult to portable lock a ndbm file,
1572 * we will open and lock the Maildelivery file instead.
1573 * This will fail if your Maildelivery file doesn't
1576 if ((lockfd = lkopen(file, O_RDWR, 0)) == -1) {
1577 advise (file, "unable to perform file locking on");
1582 value = dbm_fetch (db, key);
1585 verbose_printf ("Message-ID: %s\n already received on %s",
1589 value.dptr = ddate + sizeof("Delivery-Date:");
1590 value.dsize = strlen(value.dptr) + 1;
1591 if (dbm_store (db, key, value, DBM_INSERT))
1592 advise (file, "possibly corrupt file");
1597 lkclose(lockfd, file);