2 * Copyright (c) 1998 Sendmail, Inc. All rights reserved.
3 * Copyright (c) 1983, 1995-1997 Eric P. Allman. All rights reserved.
4 * Copyright (c) 1988, 1993
5 * The Regents of the University of California. All rights reserved.
7 * By using this file, you agree to the terms and conditions set
8 * forth in the LICENSE file which can be found at the top level of
9 * the sendmail distribution.
14 static char sccsid[] = "@(#)deliver.c 8.367 (Berkeley) 1/18/1999";
25 # include <login_cap.h>
29 extern char SmtpError[];
33 ** SENDALL -- actually send all the messages.
36 ** e -- the envelope to send.
37 ** mode -- the delivery mode to use. If SM_DEFAULT, use
38 ** the current e->e_sendmode.
44 ** Scans the send lists and sends everything it finds.
45 ** Delivers any appropriate error messages.
46 ** If we are running in a non-interactive mode, takes the
47 ** appropriate action.
58 register ENVELOPE *ee;
59 ENVELOPE *splitenv = NULL;
60 int oldverbose = Verbose;
61 bool somedeliveries = FALSE, expensive = FALSE;
63 void sendenvelope __P((ENVELOPE *, int));
66 ** If this message is to be discarded, don't bother sending
67 ** the message at all.
70 if (bitset(EF_DISCARD, e->e_flags))
73 printf("sendall: discarding id %s\n", e->e_id);
74 e->e_flags |= EF_CLRQUEUE;
76 sm_syslog(LOG_INFO, e->e_id, "discarded");
77 markstats(e, NULL, TRUE);
82 ** If we have had global, fatal errors, don't bother sending
83 ** the message at all if we are in SMTP mode. Local errors
84 ** (e.g., a single address failing) will still cause the other
85 ** addresses to be sent.
88 if (bitset(EF_FATALERRS, e->e_flags) &&
89 (OpMode == MD_SMTP || OpMode == MD_DAEMON))
91 e->e_flags |= EF_CLRQUEUE;
95 /* determine actual delivery mode */
96 if (mode == SM_DEFAULT)
99 if (mode != SM_VERIFY && mode != SM_DEFER &&
100 shouldqueue(e->e_msgpriority, e->e_ctime))
106 extern void printenvflags __P((ENVELOPE *));
108 printf("\n===== SENDALL: mode %c, id %s, e_from ",
110 printaddr(&e->e_from, FALSE);
111 printf("\te_flags = ");
113 printf("sendqueue:\n");
114 printaddr(e->e_sendqueue, TRUE);
118 ** Do any preprocessing necessary for the mode we are running.
119 ** Check to make sure the hop count is reasonable.
120 ** Delete sends to the sender in mailing lists.
127 if (e->e_hopcount > MaxHopCount)
131 queueup(e, mode == SM_QUEUE || mode == SM_DEFER);
133 e->e_flags |= EF_FATALERRS|EF_PM_NOTIFY|EF_CLRQUEUE;
134 syserr("554 Too many hops %d (%d max): from %s via %s, to %s",
135 e->e_hopcount, MaxHopCount, e->e_from.q_paddr,
136 RealHostName == NULL ? "localhost" : RealHostName,
137 e->e_sendqueue->q_paddr);
138 e->e_sendqueue->q_status = "5.4.6";
143 ** Do sender deletion.
145 ** If the sender has the QQUEUEUP flag set, skip this.
146 ** This can happen if the name server is hosed when you
147 ** are trying to send mail. The result is that the sender
148 ** is instantiated in the queue as a recipient.
151 if (!bitset(EF_METOO, e->e_flags) &&
152 !bitset(QQUEUEUP, e->e_from.q_flags))
156 printf("sendall: QDONTSEND ");
157 printaddr(&e->e_from, FALSE);
159 e->e_from.q_flags |= QDONTSEND;
160 (void) recipient(&e->e_from, &e->e_sendqueue, 0, e);
164 ** Handle alias owners.
166 ** We scan up the q_alias chain looking for owners.
167 ** We discard owners that are the same as the return path.
170 for (q = e->e_sendqueue; q != NULL; q = q->q_next)
172 register struct address *a;
174 for (a = q; a != NULL && a->q_owner == NULL; a = a->q_alias)
177 q->q_owner = a->q_owner;
179 if (q->q_owner != NULL &&
180 !bitset(QDONTSEND, q->q_flags) &&
181 strcmp(q->q_owner, e->e_from.q_paddr) == 0)
187 printf("\nAfter first owner pass, sendq =\n");
188 printaddr(e->e_sendqueue, TRUE);
193 while (owner != NULL && otherowners > 0)
196 printf("owner = \"%s\", otherowners = %d\n",
199 otherowners = bitset(EF_SENDRECEIPT, e->e_flags) ? 1 : 0;
201 for (q = e->e_sendqueue; q != NULL; q = q->q_next)
208 if (bitset(QDONTSEND, q->q_flags))
211 printf(" ... QDONTSEND\n");
214 if (tTd(13, 29) && !tTd(13, 30))
220 if (q->q_owner != NULL)
225 printf(" ... First owner = \"%s\"\n",
229 else if (owner != q->q_owner)
231 if (strcmp(owner, q->q_owner) == 0)
234 printf(" ... Same owner = \"%s\"\n",
237 /* make future comparisons cheap */
243 printf(" ... Another owner \"%s\"\n",
249 else if (tTd(13, 40))
250 printf(" ... Same owner = \"%s\"\n",
256 printf(" ... Null owner\n");
261 ** If this mailer is expensive, and if we don't
262 ** want to make connections now, just mark these
263 ** addresses and return. This is useful if we
264 ** want to batch connections to reduce load. This
265 ** will cause the messages to be queued up, and a
266 ** daemon will come along to send the messages later.
269 if (bitset(QBADADDR|QQUEUEUP, q->q_flags))
272 printf(" ... QBADADDR|QQUEUEUP\n");
275 if (NoConnect && !Verbose &&
276 bitnset(M_EXPENSIVE, q->q_mailer->m_flags))
279 printf(" ... expensive\n");
280 q->q_flags |= QQUEUEUP;
286 printf(" ... deliverable\n");
287 somedeliveries = TRUE;
291 if (owner != NULL && otherowners > 0)
293 extern HDR *copyheader __P((HDR *));
294 extern ADDRESS *copyqueue __P((ADDRESS *));
295 extern void dup_queue_file __P((ENVELOPE *, ENVELOPE *, int));
298 ** Split this envelope into two.
301 ee = (ENVELOPE *) xalloc(sizeof(ENVELOPE));
304 (void) queuename(ee, '\0');
307 printf("sendall: split %s into %s, owner = \"%s\", otherowners = %d\n",
308 e->e_id, ee->e_id, owner, otherowners);
310 ee->e_header = copyheader(e->e_header);
311 ee->e_sendqueue = copyqueue(e->e_sendqueue);
312 ee->e_errorqueue = copyqueue(e->e_errorqueue);
313 ee->e_flags = e->e_flags & ~(EF_INQUEUE|EF_CLRQUEUE|EF_FATALERRS|EF_SENDRECEIPT|EF_RET_PARAM);
314 ee->e_flags |= EF_NORECEIPT;
315 setsender(owner, ee, NULL, '\0', TRUE);
318 printf("sendall(split): QDONTSEND ");
319 printaddr(&ee->e_from, FALSE);
321 ee->e_from.q_flags |= QDONTSEND;
324 ee->e_errormode = EM_MAIL;
325 ee->e_sibling = splitenv;
328 for (q = e->e_sendqueue; q != NULL; q = q->q_next)
330 if (q->q_owner == owner)
332 q->q_flags |= QDONTSEND;
333 q->q_flags &= ~(QQUEUEUP|QBADADDR);
335 printf("\t... stripping %s from original envelope\n",
339 for (q = ee->e_sendqueue; q != NULL; q = q->q_next)
341 if (q->q_owner != owner)
343 q->q_flags |= QDONTSEND;
344 q->q_flags &= ~(QQUEUEUP|QBADADDR);
346 printf("\t... dropping %s from cloned envelope\n",
351 /* clear DSN parameters */
352 q->q_flags &= ~(QHASNOTIFY|Q_PINGFLAGS);
353 q->q_flags |= DefaultNotify & ~QPINGONSUCCESS;
355 printf("\t... moving %s to cloned envelope\n",
360 if (mode != SM_VERIFY && bitset(EF_HAS_DF, e->e_flags))
361 dup_queue_file(e, ee, 'd');
363 if (mode != SM_VERIFY && LogLevel > 4)
364 sm_syslog(LOG_INFO, ee->e_id,
365 "clone %s, owner=%s",
372 setsender(owner, e, NULL, '\0', TRUE);
375 printf("sendall(owner): QDONTSEND ");
376 printaddr(&e->e_from, FALSE);
378 e->e_from.q_flags |= QDONTSEND;
379 e->e_errormode = EM_MAIL;
380 e->e_flags |= EF_NORECEIPT;
381 e->e_flags &= ~EF_FATALERRS;
384 /* if nothing to be delivered, just queue up everything */
385 if (!somedeliveries && mode != SM_QUEUE && mode != SM_DEFER &&
389 printf("No deliveries: auto-queuing\n");
392 /* treat this as a delivery in terms of counting tries */
393 e->e_dtime = curtime();
396 for (ee = splitenv; ee != NULL; ee = ee->e_sibling)
398 ee->e_dtime = curtime();
405 if ((mode == SM_QUEUE || mode == SM_DEFER || mode == SM_FORK ||
406 (mode != SM_VERIFY && SuperSafe)) &&
407 (!bitset(EF_INQUEUE, e->e_flags) || splitenv != NULL))
409 /* be sure everything is instantiated in the queue */
410 queueup(e, mode == SM_QUEUE || mode == SM_DEFER);
411 for (ee = splitenv; ee != NULL; ee = ee->e_sibling)
412 queueup(ee, mode == SM_QUEUE || mode == SM_DEFER);
417 checkfds("after envelope splitting");
420 ** If we belong in background, fork now.
425 printf("sendall: final mode = %c\n", mode);
428 printf("\n================ Final Send Queue(s) =====================\n");
429 printf("\n *** Envelope %s, e_from=%s ***\n",
430 e->e_id, e->e_from.q_paddr);
431 printaddr(e->e_sendqueue, TRUE);
432 for (ee = splitenv; ee != NULL; ee = ee->e_sibling)
434 printf("\n *** Envelope %s, e_from=%s ***\n",
435 ee->e_id, ee->e_from.q_paddr);
436 printaddr(ee->e_sendqueue, TRUE);
438 printf("==========================================================\n\n");
453 e->e_flags |= EF_INQUEUE;
454 dropenvelope(e, splitenv != NULL);
455 for (ee = splitenv; ee != NULL; ee = ee->e_sibling)
457 if (ee->e_nrcpts > 0)
458 ee->e_flags |= EF_INQUEUE;
459 dropenvelope(ee, FALSE);
464 if (e->e_xfp != NULL)
465 (void) fflush(e->e_xfp);
469 ** Since fcntl locking has the interesting semantic that
470 ** the lock is owned by a process, not by an open file
471 ** descriptor, we have to flush this to the queue, and
472 ** then restart from scratch in the child.
476 /* save id for future use */
479 /* now drop the envelope in the parent */
480 e->e_flags |= EF_INQUEUE;
481 dropenvelope(e, splitenv != NULL);
483 /* arrange to reacquire lock after fork */
487 for (ee = splitenv; ee != NULL; ee = ee->e_sibling)
489 /* save id for future use */
490 char *qid = ee->e_id;
492 /* drop envelope in parent */
493 ee->e_flags |= EF_INQUEUE;
494 dropenvelope(ee, FALSE);
496 /* and save qid for reacquisition */
500 # endif /* !HASFLOCK */
509 for (ee = splitenv; ee != NULL; ee = ee->e_sibling)
512 # endif /* HASFLOCK */
517 /* be sure we leave the temp files to our child */
518 /* close any random open files in the envelope */
520 if (e->e_dfp != NULL)
521 (void) xfclose(e->e_dfp, "sendenvelope dfp", e->e_id);
523 e->e_flags &= ~EF_HAS_DF;
525 /* can't call unlockqueue to avoid unlink of xfp */
526 if (e->e_lockfp != NULL)
527 (void) xfclose(e->e_lockfp, "sendenvelope lockfp", e->e_id);
531 /* make sure the parent doesn't own the envelope */
534 /* catch intermediate zombie */
539 /* double fork to avoid zombies */
544 /* be sure we are immune from the terminal */
547 /* prevent parent from waiting if there was an error */
551 e->e_flags |= EF_INQUEUE;
554 # endif /* HASFLOCK */
555 finis(TRUE, ExitStat);
558 /* be sure to give error messages in child */
562 ** Close any cached connections.
564 ** We don't send the QUIT protocol because the parent
565 ** still knows about the connection.
567 ** This should only happen when delivering an error
571 mci_flush(FALSE, NULL);
574 ** Since the delivery may happen in a child and the parent
575 ** does not wait, the parent may close the maps thereby
576 ** removing any shared memory used by the map. Therefore,
577 ** open a copy of the maps for the delivery process.
587 ** Now reacquire and run the various queue files.
590 for (ee = splitenv; ee != NULL; ee = ee->e_sibling)
592 ENVELOPE *sibling = ee->e_sibling;
594 (void) dowork(ee->e_id, FALSE, FALSE, ee);
595 ee->e_sibling = sibling;
597 (void) dowork(e->e_id, FALSE, FALSE, e);
598 finis(TRUE, ExitStat);
599 # endif /* !HASFLOCK */
602 sendenvelope(e, mode);
603 dropenvelope(e, TRUE);
604 for (ee = splitenv; ee != NULL; ee = ee->e_sibling)
607 if (mode != SM_VERIFY)
609 sendenvelope(ee, mode);
610 dropenvelope(ee, TRUE);
614 Verbose = oldverbose;
616 finis(TRUE, ExitStat);
620 sendenvelope(e, mode)
621 register ENVELOPE *e;
628 printf("sendenvelope(%s) e_flags=0x%lx\n",
629 e->e_id == NULL ? "[NOQUEUE]" : e->e_id,
632 sm_syslog(LOG_DEBUG, e->e_id,
633 "sendenvelope, flags=0x%x",
637 ** If we have had global, fatal errors, don't bother sending
638 ** the message at all if we are in SMTP mode. Local errors
639 ** (e.g., a single address failing) will still cause the other
640 ** addresses to be sent.
643 if (bitset(EF_FATALERRS, e->e_flags) &&
644 (OpMode == MD_SMTP || OpMode == MD_DAEMON))
646 e->e_flags |= EF_CLRQUEUE;
651 ** Run through the list and send everything.
653 ** Set EF_GLOBALERRS so that error messages during delivery
654 ** result in returned mail.
658 e->e_flags |= EF_GLOBALERRS;
659 define(macid("{envid}", NULL), e->e_envid, e);
660 define(macid("{bodytype}", NULL), e->e_bodytype, e);
663 /* now run through the queue */
664 for (q = e->e_sendqueue; q != NULL; q = q->q_next)
667 char wbuf[MAXNAME + 20];
669 (void) snprintf(wbuf, sizeof wbuf, "sendall(%.*s)",
670 MAXNAME, q->q_paddr);
673 if (mode == SM_VERIFY)
675 e->e_to = q->q_paddr;
676 if (!bitset(QDONTSEND|QBADADDR, q->q_flags))
678 if (q->q_host != NULL && q->q_host[0] != '\0')
679 message("deliverable: mailer %s, host %s, user %s",
684 message("deliverable: mailer %s, user %s",
689 else if (!bitset(QDONTSEND|QBADADDR, q->q_flags))
691 extern int deliver __P((ENVELOPE *, ADDRESS *));
695 ** Checkpoint the send list every few addresses
698 if (e->e_nsent >= CheckpointInterval)
704 (void) deliver(e, q);
710 e->e_dtime = curtime();
715 checkfd012("end of sendenvelope");
719 ** DUP_QUEUE_FILE -- duplicate a queue file into a split queue
722 ** e -- the existing envelope
723 ** ee -- the new envelope
724 ** type -- the queue file type (e.g., 'd')
731 dup_queue_file(e, ee, type)
732 struct envelope *e, *ee;
735 char f1buf[MAXQFNAME], f2buf[MAXQFNAME];
739 snprintf(f1buf, sizeof f1buf, "%s", queuename(e, type));
740 snprintf(f2buf, sizeof f2buf, "%s", queuename(ee, type));
741 if (link(f1buf, f2buf) < 0)
743 int saverrno = errno;
745 syserr("sendall: link(%s, %s)", f1buf, f2buf);
746 if (saverrno == EEXIST)
748 if (unlink(f2buf) < 0)
750 syserr("!sendall: unlink(%s): permanent",
754 if (link(f1buf, f2buf) < 0)
756 syserr("!sendall: link(%s, %s): permanent",
764 ** DOFORK -- do a fork, retrying a couple of times on failure.
766 ** This MUST be a macro, since after a vfork we are running
767 ** two processes on the same stack!!!
773 ** From a macro??? You've got to be kidding!
776 ** Modifies the ==> LOCAL <== variable 'pid', leaving:
777 ** pid of child in parent, zero in child.
778 ** -1 on unrecoverable error.
781 ** I'm awfully sorry this looks so awful. That's
782 ** vfork for you.....
785 # define NFORKTRIES 5
791 # define DOFORK(fORKfN) \
795 for (i = NFORKTRIES; --i >= 0; )\
801 sleep((unsigned) NFORKTRIES - i);\
805 ** DOFORK -- simple fork interface to DOFORK.
811 ** pid of child in parent.
816 ** returns twice, once in parent and once in child.
822 register pid_t pid = -1;
828 ** DELIVER -- Deliver a message to a list of addresses.
830 ** This routine delivers to everyone on the same host as the
831 ** user on the head of the list. It is clever about mailers
832 ** that don't handle multiple users. It is NOT guaranteed
833 ** that it will deliver to all these addresses however -- so
834 ** deliver should be called once for each address on the
838 ** e -- the envelope to deliver.
839 ** firstto -- head of the address list to deliver to.
842 ** zero -- successfully delivered.
843 ** else -- some failure, see ExitStat for more info.
846 ** The standard input is passed off to someone.
858 register ENVELOPE *e;
861 char *host; /* host being sent to */
862 char *user; /* user being sent to */
866 register MAILER *m; /* mailer for this recipient */
867 ADDRESS *volatile ctladdr;
868 ADDRESS *volatile contextaddr = NULL;
869 register MCI *volatile mci;
870 register ADDRESS *to = firstto;
871 volatile bool clever = FALSE; /* running user smtp to this mailer */
872 ADDRESS *volatile tochain = NULL; /* users chain in this mailer call */
873 int rcode; /* response code */
874 int lmtp_rcode = EX_OK;
875 char *firstsig; /* signature of firstto */
877 char *volatile curhost;
878 register u_short port = 0;
881 bool anyok; /* at least one address was OK */
882 bool goodmxfound = FALSE; /* at least one MX was OK */
886 char tobuf[TOBUFSIZE]; /* text line of to people */
887 char buf[MAXNAME + 1];
888 char rpathbuf[MAXNAME + 1]; /* translated return path */
889 extern int checkcompat __P((ADDRESS *, ENVELOPE *));
890 extern void markfailure __P((ENVELOPE *, ADDRESS *, MCI *, int));
893 if (bitset(QDONTSEND|QBADADDR|QQUEUEUP, to->q_flags))
896 suidwarn = geteuid() == 0;
899 /* unless interactive, try twice, over a minute */
900 if (OpMode == MD_DAEMON || OpMode == MD_SMTP)
909 CurEnv = e; /* just in case */
917 printf("\n--deliver, id=%s, mailer=%s, host=`%s', first user=`%s'\n",
918 e->e_id, m->m_name, host, to->q_user);
923 ** Clear $&{client_*} macros if this is a bounce message to
924 ** prevent rejection by check_compat ruleset.
927 if (bitset(EF_RESPONSE, e->e_flags))
929 define(macid("{client_name}", NULL), "", e);
930 define(macid("{client_addr}", NULL), "", e);
931 define(macid("{client_port}", NULL), "", e);
935 ** Do initial argv setup.
936 ** Insert the mailer name. Notice that $x expansion is
937 ** NOT done on the mailer name. Then, if the mailer has
938 ** a picky -f flag, we insert it as appropriate. This
939 ** code does not check for 'pv' overflow; this places a
940 ** manifest lower limit of 4 for MAXPV.
941 ** The from address rewrite is expected to make
942 ** the address relative to the other end.
945 /* rewrite from address, using rewriting rules */
947 if (bitnset(M_UDBENVELOPE, e->e_from.q_mailer->m_flags))
950 p = e->e_from.q_paddr;
951 p = remotename(p, m, RF_SENDERADDR|RF_CANONICAL, &rcode, e);
952 if (strlen(p) >= (SIZE_T) sizeof rpathbuf)
954 p = shortenstring(p, MAXSHORTSTR);
955 syserr("remotename: huge return %s", p);
957 snprintf(rpathbuf, sizeof rpathbuf, "%s", p);
958 define('g', rpathbuf, e); /* translated return path */
959 define('h', host, e); /* to host */
962 *pvp++ = m->m_argv[0];
964 /* insert -f or -r flag as appropriate */
965 if (FromFlag && (bitnset(M_FOPT, m->m_flags) || bitnset(M_ROPT, m->m_flags)))
967 if (bitnset(M_FOPT, m->m_flags))
971 *pvp++ = newstr(rpathbuf);
975 ** Append the other fixed parts of the argv. These run
976 ** up to the first entry containing "$u". There can only
977 ** be one of these, and there are only a few more slots
978 ** in the pv after it.
981 for (mvp = m->m_argv; (p = *++mvp) != NULL; )
983 /* can't use strchr here because of sign extension problems */
986 if ((*p++ & 0377) == MACROEXPAND)
996 /* this entry is safe -- go ahead and process it */
997 expand(*mvp, buf, sizeof buf, e);
998 *pvp++ = newstr(buf);
999 if (pvp >= &pv[MAXPV - 3])
1001 syserr("554 Too many parameters to %s before $u", pv[0]);
1007 ** If we have no substitution for the user name in the argument
1008 ** list, we know that we must supply the names otherwise -- and
1009 ** SMTP is the answer!!
1019 /* oops! we don't implement SMTP */
1020 syserr("554 SMTP style mailer not implemented");
1021 return (EX_SOFTWARE);
1026 ** At this point *mvp points to the argument with $u. We
1027 ** run through our address list and append all the addresses
1028 ** we can. If we run out of space, do not fret! We can
1029 ** always send another copy later.
1035 firstsig = hostsignature(firstto->q_mailer, firstto->q_host, e);
1036 for (; to != NULL; to = to->q_next)
1038 /* avoid sending multiple recipients to dumb mailers */
1039 if (tobuf[0] != '\0' && !bitnset(M_MUSER, m->m_flags))
1042 /* if already sent or not for this host, don't send */
1043 if (bitset(QDONTSEND|QBADADDR|QQUEUEUP, to->q_flags) ||
1044 to->q_mailer != firstto->q_mailer ||
1045 strcmp(hostsignature(to->q_mailer, to->q_host, e), firstsig) != 0)
1048 /* avoid overflowing tobuf */
1049 if (sizeof tobuf < (strlen(to->q_paddr) + strlen(tobuf) + 2))
1054 printf("\nsend to ");
1055 printaddr(to, FALSE);
1058 /* compute effective uid/gid when sending */
1059 if (bitnset(M_RUNASRCPT, to->q_mailer->m_flags))
1060 contextaddr = ctladdr = getctladdr(to);
1065 printaddr(ctladdr, FALSE);
1069 e->e_to = to->q_paddr;
1072 printf("deliver: QDONTSEND ");
1073 printaddr(to, FALSE);
1075 to->q_flags |= QDONTSEND;
1078 ** Check to see that these people are allowed to
1079 ** talk to each other.
1082 if (m->m_maxsize != 0 && e->e_msgsize > m->m_maxsize)
1084 e->e_flags |= EF_NO_BODY_RETN;
1085 if (bitnset(M_LOCALMAILER, to->q_mailer->m_flags))
1086 to->q_status = "5.2.3";
1088 to->q_status = "5.3.4";
1089 usrerr("552 Message is too large; %ld bytes max", m->m_maxsize);
1090 markfailure(e, to, NULL, EX_UNAVAILABLE);
1091 giveresponse(EX_UNAVAILABLE, m, NULL, ctladdr, xstart, e);
1098 /* do config file checking of compatibility */
1099 rcode = rscheck("check_compat",
1100 e->e_from.q_paddr, to->q_paddr, e);
1103 /* do in-code checking if not discarding */
1104 if (!bitset(EF_DISCARD, e->e_flags))
1105 rcode = checkcompat(to, e);
1109 markfailure(e, to, NULL, rcode);
1110 giveresponse(rcode, m, NULL, ctladdr, xstart, e);
1113 if (bitset(EF_DISCARD, e->e_flags))
1117 printf("deliver: discarding recipient ");
1118 printaddr(to, FALSE);
1122 ** Remove discard bit to prevent discard of
1123 ** future recipients
1125 e->e_flags &= ~EF_DISCARD;
1131 ** Strip quote bits from names if the mailer is dumb
1135 if (bitnset(M_STRIPQ, m->m_flags))
1141 /* hack attack -- delivermail compatibility */
1142 if (m == ProgMailer && *user == '|')
1146 ** If an error message has already been given, don't
1147 ** bother to send to this address.
1149 ** >>>>>>>>>> This clause assumes that the local mailer
1150 ** >> NOTE >> cannot do any further aliasing; that
1151 ** >>>>>>>>>> function is subsumed by sendmail.
1154 if (bitset(QBADADDR|QQUEUEUP, to->q_flags))
1158 ** See if this user name is "special".
1159 ** If the user name has a slash in it, assume that this
1160 ** is a file -- send it off without further ado. Note
1161 ** that this type of addresses is not processed along
1162 ** with the others, so we fudge on the To person.
1165 if (strcmp(m->m_mailer, "[FILE]") == 0)
1167 define('u', user, e); /* to user */
1169 if (p == NULL && ctladdr != NULL)
1170 p = ctladdr->q_home;
1171 define('z', p, e); /* user's home */
1172 expand(m->m_argv[1], buf, sizeof buf, e);
1173 if (strlen(buf) > 0)
1174 rcode = mailfile(buf, m, ctladdr, SFF_CREAT, e);
1177 syserr("empty filename specification for mailer %s",
1181 giveresponse(rcode, m, NULL, ctladdr, xstart, e);
1182 markfailure(e, to, NULL, rcode);
1186 to->q_flags |= QSENT;
1187 if (bitnset(M_LOCALMAILER, m->m_flags) &&
1188 bitset(QPINGONSUCCESS, to->q_flags))
1190 to->q_flags |= QDELIVERED;
1191 to->q_status = "2.1.5";
1192 fprintf(e->e_xfp, "%s... Successfully delivered\n",
1196 to->q_statdate = curtime();
1197 markstats(e, to, FALSE);
1202 ** Address is verified -- add this user to mailer
1203 ** argv, and add it to the print list of recipients.
1206 /* link together the chain of recipients */
1207 to->q_tchain = tochain;
1210 /* create list of users for error messages */
1211 (void) strcat(tobuf, ",");
1212 (void) strcat(tobuf, to->q_paddr);
1213 define('u', user, e); /* to user */
1215 if (p == NULL && ctladdr != NULL)
1216 p = ctladdr->q_home;
1217 define('z', p, e); /* user's home */
1220 ** Expand out this user into argument list.
1225 expand(*mvp, buf, sizeof buf, e);
1226 *pvp++ = newstr(buf);
1227 if (pvp >= &pv[MAXPV - 2])
1229 /* allow some space for trailing parms */
1235 /* see if any addresses still exist */
1236 if (tobuf[0] == '\0')
1238 define('g', (char *) NULL, e);
1242 /* print out messages as full list */
1243 e->e_to = tobuf + 1;
1246 ** Fill out any parameters after the $u parameter.
1249 while (!clever && *++mvp != NULL)
1251 expand(*mvp, buf, sizeof buf, e);
1252 *pvp++ = newstr(buf);
1253 if (pvp >= &pv[MAXPV])
1254 syserr("554 deliver: pv overflow after $u for %s", pv[0]);
1260 ** The argument vector gets built, pipes
1261 ** are created as necessary, and we fork & exec as
1263 ** If we are running SMTP, we just need to clean up.
1266 /*XXX this seems a bit wierd */
1267 if (ctladdr == NULL && m != ProgMailer && m != FileMailer &&
1268 bitset(QGOODUID, e->e_from.q_flags))
1269 ctladdr = &e->e_from;
1272 if (ConfigLevel < 2)
1273 _res.options &= ~(RES_DEFNAMES | RES_DNSRCH); /* XXX */
1278 printf("openmailer:");
1289 ** Deal with the special case of mail handled through an IPC
1291 ** In this case we don't actually fork. We must be
1292 ** running SMTP for this to work. We will return a
1293 ** zero pid to indicate that we are running IPC.
1294 ** We also handle a debug version that just talks to stdin/out.
1305 /* make absolutely certain 0, 1, and 2 are in use */
1306 snprintf(wbuf, sizeof wbuf, "%s... openmailer(%s)",
1307 shortenstring(e->e_to, MAXSHORTSTR), m->m_name);
1312 /* check for 8-bit available */
1313 if (bitset(EF_HAS8BIT, e->e_flags) &&
1314 bitnset(M_7BITS, m->m_flags) &&
1315 (bitset(EF_DONT_MIME, e->e_flags) ||
1316 !(bitset(MM_MIME8BIT, MimeMode) ||
1317 (bitset(EF_IS_MIME, e->e_flags) &&
1318 bitset(MM_CVTMIME, MimeMode)))))
1320 usrerr("554 Cannot send 8-bit data to 7-bit destination");
1322 e->e_status = "5.6.3";
1327 checkfds("before delivery");
1329 /* check for Local Person Communication -- not for mortals!!! */
1330 if (strcmp(m->m_mailer, "[LPC]") == 0)
1332 mci = (MCI *) xalloc(sizeof *mci);
1333 bzero((char *) mci, sizeof *mci);
1334 mci->mci_in = stdin;
1335 mci->mci_out = stdout;
1336 mci->mci_state = clever ? MCIS_OPENING : MCIS_OPEN;
1337 mci->mci_mailer = m;
1339 else if (strcmp(m->m_mailer, "[IPC]") == 0 ||
1340 strcmp(m->m_mailer, "[TCP]") == 0)
1345 if (pv[0] == NULL || pv[1] == NULL || pv[1][0] == '\0')
1347 syserr("null host name for %s mailer", m->m_mailer);
1352 CurHostName = pv[1];
1353 curhost = hostsignature(m, pv[1], e);
1355 if (curhost == NULL || curhost[0] == '\0')
1357 syserr("null host signature for %s", pv[1]);
1364 syserr("554 non-clever IPC");
1370 port = htons(atoi(pv[2]));
1373 struct servent *sp = getservbyname(pv[2], "tcp");
1376 syserr("Service %s unknown", pv[2]);
1382 while (*curhost != '\0')
1384 static char hostbuf[MAXNAME + 1];
1385 extern int makeconnection __P((char *, u_short, MCI *, ENVELOPE *));
1387 /* pull the next host from the signature */
1388 p = strchr(curhost, ':');
1390 p = (char *) &curhost[strlen(curhost)];
1393 syserr("deliver: null host name in signature");
1398 if (i >= sizeof hostbuf)
1399 i = sizeof hostbuf - 1;
1400 strncpy(hostbuf, curhost, i);
1406 /* see if we already know that this host is fried */
1407 CurHostName = hostbuf;
1408 mci = mci_get(hostbuf, m);
1409 if (mci->mci_state != MCIS_CLOSED)
1413 printf("openmailer: ");
1414 mci_dump(mci, FALSE);
1416 CurHostName = mci->mci_host;
1417 message("Using cached %sSMTP connection to %s via %s...",
1418 bitset(MCIF_ESMTP, mci->mci_flags) ? "E" : "",
1419 hostbuf, m->m_name);
1422 mci->mci_mailer = m;
1423 if (mci->mci_exitstat != EX_OK)
1425 if (mci->mci_exitstat == EX_TEMPFAIL)
1430 if (mci_lock_host(mci) != EX_OK)
1432 mci_setstat(mci, EX_TEMPFAIL, "4.4.5", NULL);
1437 /* try the connection */
1438 sm_setproctitle(TRUE, "%s %s: %s", e->e_id, hostbuf, "user open");
1440 message("Connecting to %s via %s...",
1441 hostbuf, m->m_name);
1443 message("Connecting to %s port %d via %s...",
1444 hostbuf, ntohs(port), m->m_name);
1445 i = makeconnection(hostbuf, port, mci, e);
1446 mci->mci_lastuse = curtime();
1447 mci->mci_exitstat = i;
1448 mci->mci_errno = errno;
1450 mci->mci_herrno = h_errno;
1455 mci->mci_state = MCIS_OPENING;
1457 if (TrafficLogFile != NULL)
1458 fprintf(TrafficLogFile, "%05d === CONNECT %s\n",
1459 (int) getpid(), hostbuf);
1465 printf("openmailer: makeconnection => stat=%d, errno=%d\n",
1467 if (i == EX_TEMPFAIL)
1469 mci_unlock_host(mci);
1472 /* enter status of this host */
1475 /* should print some message here for -v mode */
1479 syserr("deliver: no host name");
1480 rcode = EX_SOFTWARE;
1484 #else /* no DAEMON */
1485 syserr("554 openmailer: no IPC");
1487 printf("openmailer: NULL\n");
1488 rcode = EX_UNAVAILABLE;
1494 /* flush any expired connections */
1495 (void) mci_scan(NULL);
1499 if (bitnset(M_LMTP, m->m_flags))
1501 /* try to get a cached connection */
1502 mci = mci_get(m->m_name, m);
1503 if (mci->mci_host == NULL)
1504 mci->mci_host = m->m_name;
1505 CurHostName = mci->mci_host;
1506 if (mci->mci_state != MCIS_CLOSED)
1508 message("Using cached LMTP connection for %s...",
1515 /* announce the connection to verbose listeners */
1516 if (host == NULL || host[0] == '\0')
1517 message("Connecting to %s...", m->m_name);
1519 message("Connecting to %s via %s...", host, m->m_name);
1520 if (TrafficLogFile != NULL)
1524 fprintf(TrafficLogFile, "%05d === EXEC", (int) getpid());
1525 for (av = pv; *av != NULL; av++)
1526 fprintf(TrafficLogFile, " %s", *av);
1527 fprintf(TrafficLogFile, "\n");
1531 checkfd012("before creating mail pipe");
1534 /* create a pipe to shove the mail through */
1535 if (pipe(mpvect) < 0)
1537 syserr("%s... openmailer(%s): pipe (to mailer)",
1538 shortenstring(e->e_to, MAXSHORTSTR), m->m_name);
1540 printf("openmailer: NULL\n");
1546 /* make sure we didn't get one of the standard I/O files */
1547 if (mpvect[0] < 3 || mpvect[1] < 3)
1549 syserr("%s... openmailer(%s): bogus mpvect %d %d",
1550 shortenstring(e->e_to, MAXSHORTSTR), m->m_name,
1551 mpvect[0], mpvect[1]);
1554 printf("openmailer: NULL\n");
1559 /* make sure system call isn't dead meat */
1560 checkfdopen(mpvect[0], "mpvect[0]");
1561 checkfdopen(mpvect[1], "mpvect[1]");
1562 if (mpvect[0] == mpvect[1] ||
1563 (e->e_lockfp != NULL &&
1564 (mpvect[0] == fileno(e->e_lockfp) ||
1565 mpvect[1] == fileno(e->e_lockfp))))
1567 if (e->e_lockfp == NULL)
1568 syserr("%s... openmailer(%s): overlapping mpvect %d %d",
1569 shortenstring(e->e_to, MAXSHORTSTR),
1570 m->m_name, mpvect[0], mpvect[1]);
1572 syserr("%s... openmailer(%s): overlapping mpvect %d %d, lockfp = %d",
1573 shortenstring(e->e_to, MAXSHORTSTR),
1574 m->m_name, mpvect[0], mpvect[1],
1575 fileno(e->e_lockfp));
1579 /* if this mailer speaks smtp, create a return pipe */
1583 if (pipe(rpvect) < 0)
1585 syserr("%s... openmailer(%s): pipe (from mailer)",
1586 shortenstring(e->e_to, MAXSHORTSTR),
1588 (void) close(mpvect[0]);
1589 (void) close(mpvect[1]);
1591 printf("openmailer: NULL\n");
1596 checkfdopen(rpvect[0], "rpvect[0]");
1597 checkfdopen(rpvect[1], "rpvect[1]");
1603 ** Actually fork the mailer process.
1604 ** DOFORK is clever about retrying.
1606 ** Dispose of SIGCHLD signal catchers that may be laying
1607 ** around so that endmail will get it.
1610 if (e->e_xfp != NULL)
1611 (void) fflush(e->e_xfp); /* for debugging */
1612 (void) fflush(stdout);
1613 (void) setsignal(SIGCHLD, SIG_DFL);
1615 /* pid is set by DOFORK */
1619 syserr("%s... openmailer(%s): cannot fork",
1620 shortenstring(e->e_to, MAXSHORTSTR), m->m_name);
1621 (void) close(mpvect[0]);
1622 (void) close(mpvect[1]);
1626 (void) close(rpvect[0]);
1627 (void) close(rpvect[1]);
1631 printf("openmailer: NULL\n");
1639 int new_euid = NO_UID;
1640 int new_ruid = NO_UID;
1641 int new_gid = NO_GID;
1643 extern int DtableSize;
1645 if (e->e_lockfp != NULL)
1646 (void) close(fileno(e->e_lockfp));
1648 /* child -- set up input & exec mailer */
1649 (void) setsignal(SIGINT, SIG_IGN);
1650 (void) setsignal(SIGHUP, SIG_IGN);
1651 (void) setsignal(SIGTERM, SIG_DFL);
1653 if (m != FileMailer || stat(tochain->q_user, &stb) < 0)
1656 #if HASSETUSERCONTEXT
1658 ** Set user resources.
1661 if (contextaddr != NULL)
1665 if (contextaddr->q_ruser != NULL)
1666 pwd = sm_getpwnam(contextaddr->q_ruser);
1668 pwd = sm_getpwnam(contextaddr->q_user);
1670 (void) setusercontext(NULL,
1672 LOGIN_SETRESOURCES|LOGIN_SETPRIORITY);
1676 /* tweak niceness */
1680 /* reset group id */
1681 if (bitnset(M_SPECIFIC_UID, m->m_flags))
1683 else if (bitset(S_ISGID, stb.st_mode))
1684 new_gid = stb.st_gid;
1685 else if (ctladdr != NULL && ctladdr->q_gid != 0)
1687 if (!DontInitGroups)
1689 char *u = ctladdr->q_ruser;
1692 u = ctladdr->q_user;
1694 if (initgroups(u, ctladdr->q_gid) == -1 && suidwarn)
1695 syserr("openmailer: initgroups(%s, %d) failed",
1702 gidset[0] = ctladdr->q_gid;
1703 if (setgroups(1, gidset) == -1 && suidwarn)
1704 syserr("openmailer: setgroups() failed");
1706 new_gid = ctladdr->q_gid;
1710 if (!DontInitGroups)
1712 if (initgroups(DefUser, DefGid) == -1 && suidwarn)
1713 syserr("openmailer: initgroups(%s, %d) failed",
1721 if (setgroups(1, gidset) == -1 && suidwarn)
1722 syserr("openmailer: setgroups() failed");
1729 if (new_gid != NO_GID && setgid(new_gid) < 0 && suidwarn)
1730 syserr("openmailer: setgid(%ld) failed",
1735 if (bitnset(M_SPECIFIC_UID, m->m_flags))
1736 new_euid = m->m_uid;
1737 else if (bitset(S_ISUID, stb.st_mode))
1738 new_ruid = stb.st_uid;
1739 else if (ctladdr != NULL && ctladdr->q_uid != 0)
1740 new_ruid = ctladdr->q_uid;
1741 else if (m->m_uid != 0)
1742 new_ruid = m->m_uid;
1745 if (new_euid != NO_UID)
1747 vendor_set_uid(new_euid);
1749 if (seteuid(new_euid) < 0 && suidwarn)
1750 syserr("openmailer: seteuid(%ld) failed",
1754 if (setreuid(new_ruid, new_euid) < 0 && suidwarn)
1755 syserr("openmailer: setreuid(%ld, %ld) failed",
1756 (long) new_ruid, (long) new_euid);
1758 if (new_euid != geteuid() && setuid(new_euid) < 0 && suidwarn)
1759 syserr("openmailer: setuid(%ld) failed",
1764 else if (new_ruid != NO_UID)
1766 vendor_set_uid(new_ruid);
1767 if (setuid(new_ruid) < 0 && suidwarn)
1768 syserr("openmailer: setuid(%ld) failed",
1773 printf("openmailer: running as r/euid=%d/%d\n",
1774 (int) getuid(), (int) geteuid());
1776 /* move into some "safe" directory */
1777 if (m->m_execdir != NULL)
1780 char buf[MAXLINE + 1];
1782 for (p = m->m_execdir; p != NULL; p = q)
1787 expand(p, buf, sizeof buf, e);
1791 printf("openmailer: trydir %s\n",
1793 if (buf[0] != '\0' && chdir(buf) >= 0)
1798 /* arrange to filter std & diag output of command */
1802 (void) close(rpvect[0]);
1803 if (dup2(rpvect[1], STDOUT_FILENO) < 0)
1805 syserr("%s... openmailer(%s): cannot dup pipe %d for stdout",
1806 shortenstring(e->e_to, MAXSHORTSTR),
1807 m->m_name, rpvect[1]);
1810 (void) close(rpvect[1]);
1814 /* put mailer output in transcript */
1815 if (dup2(fileno(e->e_xfp), STDOUT_FILENO) < 0)
1817 syserr("%s... openmailer(%s): cannot dup xscript %d for stdout",
1818 shortenstring(e->e_to, MAXSHORTSTR),
1819 m->m_name, fileno(e->e_xfp));
1824 if (dup2(STDOUT_FILENO, STDERR_FILENO) < 0)
1826 syserr("%s... openmailer(%s): cannot dup stdout for stderr",
1827 shortenstring(e->e_to, MAXSHORTSTR),
1832 /* arrange to get standard input */
1833 (void) close(mpvect[1]);
1834 if (dup2(mpvect[0], STDIN_FILENO) < 0)
1836 syserr("%s... openmailer(%s): cannot dup pipe %d for stdin",
1837 shortenstring(e->e_to, MAXSHORTSTR),
1838 m->m_name, mpvect[0]);
1841 (void) close(mpvect[0]);
1843 /* arrange for all the files to be closed */
1844 for (i = 3; i < DtableSize; i++)
1848 if ((j = fcntl(i, F_GETFD, 0)) != -1)
1849 (void) fcntl(i, F_SETFD, j | 1);
1852 /* run disconnected from terminal */
1855 /* try to execute the mailer */
1856 execve(m->m_mailer, (ARGV_T) pv, (ARGV_T) UserEnviron);
1858 syserr("Cannot exec %s", m->m_mailer);
1859 if (bitnset(M_LOCALMAILER, m->m_flags) ||
1860 transienterror(saveerrno))
1862 _exit(EX_UNAVAILABLE);
1866 ** Set up return value.
1871 mci = (MCI *) xalloc(sizeof *mci);
1872 bzero((char *) mci, sizeof *mci);
1874 mci->mci_mailer = m;
1877 mci->mci_state = MCIS_OPENING;
1882 mci->mci_state = MCIS_OPEN;
1885 (void) close(mpvect[0]);
1886 mci->mci_out = fdopen(mpvect[1], "w");
1887 if (mci->mci_out == NULL)
1889 syserr("deliver: cannot create mailer output channel, fd=%d",
1891 (void) close(mpvect[1]);
1895 (void) close(rpvect[0]);
1896 (void) close(rpvect[1]);
1905 (void) close(rpvect[1]);
1906 mci->mci_in = fdopen(rpvect[0], "r");
1907 if (mci->mci_in == NULL)
1909 syserr("deliver: cannot create mailer input channel, fd=%d",
1911 (void) close(rpvect[0]);
1912 fclose(mci->mci_out);
1913 mci->mci_out = NULL;
1921 mci->mci_flags |= MCIF_TEMP;
1927 ** If we are in SMTP opening state, send initial protocol.
1930 if (bitnset(M_7BITS, m->m_flags) &&
1931 (!clever || mci->mci_state == MCIS_OPENING))
1932 mci->mci_flags |= MCIF_7BIT;
1934 if (clever && mci->mci_state != MCIS_CLOSED)
1936 extern void smtpinit __P((MAILER *, MCI *, ENVELOPE *));
1938 smtpinit(m, mci, e);
1943 /* clear out per-message flags from connection structure */
1944 mci->mci_flags &= ~(MCIF_CVT7TO8|MCIF_CVT8TO7);
1946 if (bitset(EF_HAS8BIT, e->e_flags) &&
1947 !bitset(EF_DONT_MIME, e->e_flags) &&
1948 bitnset(M_7BITS, m->m_flags))
1949 mci->mci_flags |= MCIF_CVT8TO7;
1952 if (bitnset(M_MAKE8BIT, m->m_flags) &&
1953 !bitset(MCIF_7BIT, mci->mci_flags) &&
1954 (p = hvalue("Content-Transfer-Encoding", e->e_header)) != NULL &&
1955 (strcasecmp(p, "quoted-printable") == 0 ||
1956 strcasecmp(p, "base64") == 0) &&
1957 (p = hvalue("Content-Type", e->e_header)) != NULL)
1959 /* may want to convert 7 -> 8 */
1960 /* XXX should really parse it here -- and use a class XXX */
1961 if (strncasecmp(p, "text/plain", 10) == 0 &&
1962 (p[10] == '\0' || p[10] == ' ' || p[10] == ';'))
1963 mci->mci_flags |= MCIF_CVT7TO8;
1969 printf("openmailer: ");
1970 mci_dump(mci, FALSE);
1973 if (mci->mci_state != MCIS_OPEN)
1975 /* couldn't open the mailer */
1976 rcode = mci->mci_exitstat;
1977 errno = mci->mci_errno;
1979 h_errno = mci->mci_herrno;
1983 /* shouldn't happen */
1984 syserr("554 deliver: mci=%lx rcode=%d errno=%d state=%d sig=%s",
1985 (long) mci, rcode, errno, mci->mci_state,
1988 rcode = EX_SOFTWARE;
1991 else if (curhost != NULL && *curhost != '\0')
1993 /* try next MX site */
2001 ** Format and send message.
2004 mci->mci_contentlen = 0;
2005 putfromline(mci, e);
2006 (*e->e_puthdr)(mci, e->e_header, e, M87F_OUTER);
2007 (*e->e_putbody)(mci, e, NULL);
2009 /* get the exit status */
2010 rcode = endmailer(mci, e, pv);
2015 extern int smtpmailfrom __P((MAILER *, MCI *, ENVELOPE *));
2016 extern int smtprcpt __P((ADDRESS *, MAILER *, MCI *, ENVELOPE *));
2017 extern int smtpdata __P((MAILER *, MCI *, ENVELOPE *));
2020 ** Send the MAIL FROM: protocol
2023 rcode = smtpmailfrom(m, mci, e);
2026 register char *t = tobuf;
2029 /* send the recipient list */
2031 for (to = tochain; to != NULL; to = to->q_tchain)
2033 e->e_to = to->q_paddr;
2034 if (strlen(to->q_paddr) + (t - tobuf) + 2 > sizeof tobuf)
2036 /* not enough room */
2039 else if ((i = smtprcpt(to, m, mci, e)) != EX_OK)
2041 markfailure(e, to, mci, i);
2042 giveresponse(i, m, mci, ctladdr, xstart, e);
2047 for (p = to->q_paddr; *p; *t++ = *p++)
2053 /* now send the data */
2054 if (tobuf[0] == '\0')
2058 if (bitset(MCIF_CACHED, mci->mci_flags))
2059 smtprset(m, mci, e);
2063 e->e_to = tobuf + 1;
2064 rcode = smtpdata(m, mci, e);
2068 if (rcode == EX_TEMPFAIL && curhost != NULL && *curhost != '\0')
2070 /* try next MX site */
2075 #else /* not SMTP */
2077 syserr("554 deliver: need SMTP compiled to use clever mailer");
2083 if (ConfigLevel < 2)
2084 _res.options |= RES_DEFNAMES | RES_DNSRCH; /* XXX */
2088 checkfds("after delivery");
2091 ** Do final status disposal.
2092 ** We check for something in tobuf for the SMTP case.
2093 ** If we got a temporary failure, arrange to queue the
2099 if (bitnset(M_LMTP, m->m_flags))
2107 anyok = rcode == EX_OK;
2109 for (to = tochain; to != NULL; to = to->q_tchain)
2111 /* see if address already marked */
2112 if (bitset(QBADADDR|QQUEUEUP, to->q_flags))
2116 /* if running LMTP, get the status for each address */
2117 if (bitnset(M_LMTP, m->m_flags))
2119 extern int smtpgetstat __P((MAILER *, MCI *, ENVELOPE *));
2121 if (lmtp_rcode == EX_OK)
2122 rcode = smtpgetstat(m, mci, e);
2125 if (strlen(to->q_paddr) + strlen(tobuf) + 2 > sizeof tobuf)
2127 syserr("LMTP tobuf overflow");
2132 strcat(tobuf, to->q_paddr);
2138 e->e_to = to->q_paddr;
2139 markfailure(e, to, mci, rcode);
2140 giveresponse(rcode, m, mci, ctladdr, xstart, e);
2141 e->e_to = tobuf + 1;
2148 /* mark bad addresses */
2151 if (goodmxfound && rcode == EX_NOHOST)
2152 rcode = EX_TEMPFAIL;
2153 markfailure(e, to, mci, rcode);
2158 /* successful delivery */
2159 to->q_flags |= QSENT;
2160 to->q_statdate = curtime();
2162 if (bitnset(M_LOCALMAILER, m->m_flags) &&
2163 bitset(QPINGONSUCCESS, to->q_flags))
2165 to->q_flags |= QDELIVERED;
2166 to->q_status = "2.1.5";
2167 fprintf(e->e_xfp, "%s... Successfully delivered\n",
2170 else if (bitset(QPINGONSUCCESS, to->q_flags) &&
2171 bitset(QPRIMARY, to->q_flags) &&
2172 !bitset(MCIF_DSN, mci->mci_flags))
2174 to->q_flags |= QRELAYED;
2175 fprintf(e->e_xfp, "%s... relayed; expect no further notifications\n",
2181 if (bitnset(M_LMTP, m->m_flags))
2184 ** Global information applies to the last recipient only;
2185 ** clear it out to avoid bogus errors.
2189 e->e_statmsg = NULL;
2191 /* reset the mci state for the next transaction */
2192 if (mci != NULL && mci->mci_state == MCIS_ACTIVE)
2193 mci->mci_state = MCIS_OPEN;
2197 if (tobuf[0] != '\0')
2198 giveresponse(rcode, m, mci, ctladdr, xstart, e);
2200 markstats(e, tochain, FALSE);
2201 mci_store_persistent(mci);
2204 /* now close the connection */
2205 if (clever && mci != NULL && mci->mci_state != MCIS_CLOSED &&
2206 !bitset(MCIF_CACHED, mci->mci_flags))
2207 smtpquit(m, mci, e);
2211 ** Restore state and return.
2218 /* make absolutely certain 0, 1, and 2 are in use */
2219 snprintf(wbuf, sizeof wbuf, "%s... end of deliver(%s)",
2220 e->e_to == NULL ? "NO-TO-LIST"
2221 : shortenstring(e->e_to, MAXSHORTSTR),
2228 define('g', (char *) NULL, e);
2232 ** MARKFAILURE -- mark a failure on a specific address.
2235 ** e -- the envelope we are sending.
2236 ** q -- the address to mark.
2237 ** mci -- mailer connection information.
2238 ** rcode -- the code signifying the particular failure.
2244 ** marks the address (and possibly the envelope) with the
2245 ** failure so that an error will be returned or
2246 ** the message will be queued, as appropriate.
2250 markfailure(e, q, mci, rcode)
2251 register ENVELOPE *e;
2252 register ADDRESS *q;
2266 q->q_flags |= QQUEUEUP;
2267 q->q_flags &= ~QDONTSEND;
2271 q->q_flags |= QBADADDR;
2275 /* find most specific error code possible */
2276 if (mci != NULL && mci->mci_status != NULL)
2278 q->q_status = mci->mci_status;
2279 if (mci->mci_rstatus != NULL)
2280 q->q_rstatus = newstr(mci->mci_rstatus);
2282 q->q_rstatus = NULL;
2284 else if (e->e_status != NULL)
2286 q->q_status = e->e_status;
2287 q->q_rstatus = NULL;
2315 case EX_UNAVAILABLE:
2336 q->q_statdate = curtime();
2337 if (CurHostName != NULL && CurHostName[0] != '\0')
2338 q->q_statmta = newstr(CurHostName);
2339 if (rcode != EX_OK && q->q_rstatus == NULL &&
2340 q->q_mailer != NULL && q->q_mailer->m_diagtype != NULL &&
2341 strcasecmp(q->q_mailer->m_diagtype, "UNIX") == 0)
2345 (void) snprintf(buf, sizeof buf, "%d", rcode);
2346 q->q_rstatus = newstr(buf);
2350 ** ENDMAILER -- Wait for mailer to terminate.
2352 ** We should never get fatal errors (e.g., segmentation
2353 ** violation), so we report those specially. For other
2354 ** errors, we choose a status message (into statmsg),
2355 ** and if it represents an error, we print it.
2358 ** pid -- pid of mailer.
2359 ** e -- the current envelope.
2360 ** pv -- the parameter vector that invoked the mailer
2361 ** (for error messages).
2364 ** exit code of mailer.
2371 endmailer(mci, e, pv)
2373 register ENVELOPE *e;
2378 mci_unlock_host(mci);
2380 /* close any connections */
2381 if (mci->mci_in != NULL)
2382 (void) xfclose(mci->mci_in, mci->mci_mailer->m_name, "mci_in");
2383 if (mci->mci_out != NULL)
2384 (void) xfclose(mci->mci_out, mci->mci_mailer->m_name, "mci_out");
2385 mci->mci_in = mci->mci_out = NULL;
2386 mci->mci_state = MCIS_CLOSED;
2388 /* in the IPC case there is nothing to wait for */
2389 if (mci->mci_pid == 0)
2392 #if _FFR_TIMEOUT_WAIT
2393 put a timeout around the wait
2396 /* wait for the mailer process to die and collect status */
2397 st = waitfor(mci->mci_pid);
2400 syserr("endmailer %s: wait", mci->mci_mailer->m_name);
2401 return (EX_SOFTWARE);
2406 /* normal death -- return status */
2407 return (WEXITSTATUS(st));
2410 /* it died a horrid death */
2411 syserr("451 mailer %s died with signal %o",
2412 mci->mci_mailer->m_name, st);
2414 /* log the arguments */
2415 if (pv != NULL && e->e_xfp != NULL)
2419 fprintf(e->e_xfp, "Arguments:");
2420 for (av = pv; *av != NULL; av++)
2421 fprintf(e->e_xfp, " %s", *av);
2422 fprintf(e->e_xfp, "\n");
2425 ExitStat = EX_TEMPFAIL;
2426 return (EX_TEMPFAIL);
2429 ** GIVERESPONSE -- Interpret an error response from a mailer
2432 ** stat -- the status code from the mailer (high byte
2433 ** only; core dumps must have been taken care of
2435 ** m -- the mailer info for this mailer.
2436 ** mci -- the mailer connection info -- can be NULL if the
2437 ** response is given before the connection is made.
2438 ** ctladdr -- the controlling address for the recipient
2440 ** xstart -- the transaction start time, for computing
2441 ** transaction delays.
2442 ** e -- the current envelope.
2448 ** Errors may be incremented.
2449 ** ExitStat may be set.
2453 giveresponse(stat, m, mci, ctladdr, xstart, e)
2461 register const char *statmsg;
2462 extern char *SysExMsg[];
2468 syserr("giveresponse: null envelope");
2471 ** Compute status message from code.
2474 i = stat - EX__BASE;
2477 statmsg = "250 Sent";
2478 if (e->e_statmsg != NULL)
2480 (void) snprintf(buf, sizeof buf, "%s (%s)",
2481 statmsg, shortenstring(e->e_statmsg, 403));
2485 else if (i < 0 || i >= N_SysEx)
2487 (void) snprintf(buf, sizeof buf, "554 unknown mailer error %d",
2489 stat = EX_UNAVAILABLE;
2492 else if (stat == EX_TEMPFAIL)
2496 snprintf(bp, SPACELEFT(buf, bp), "%s", SysExMsg[i] + 1);
2499 if (h_errno == TRY_AGAIN)
2500 statmsg = errstring(h_errno+E_DNSBASE);
2505 statmsg = errstring(errno);
2509 statmsg = SmtpError;
2515 if (statmsg != NULL && statmsg[0] != '\0')
2516 snprintf(bp, SPACELEFT(buf, bp), ": %s", statmsg);
2520 else if (stat == EX_NOHOST && h_errno != 0)
2522 statmsg = errstring(h_errno + E_DNSBASE);
2523 (void) snprintf(buf, sizeof buf, "%s (%s)",
2524 SysExMsg[i] + 1, statmsg);
2530 statmsg = SysExMsg[i];
2531 if (*statmsg++ == ':' && errno != 0)
2533 (void) snprintf(buf, sizeof buf, "%s: %s",
2534 statmsg, errstring(errno));
2540 ** Print the message as appropriate
2543 if (stat == EX_OK || stat == EX_TEMPFAIL)
2545 extern char MsgBuf[];
2547 message("%s", &statmsg[4]);
2548 if (stat == EX_TEMPFAIL && e->e_xfp != NULL)
2549 fprintf(e->e_xfp, "%s\n", &MsgBuf[4]);
2556 snprintf(mbuf, sizeof mbuf, "%.3s %%s", statmsg);
2557 usrerr(mbuf, &statmsg[4]);
2562 ** Log a record of the transaction. Compute the new
2563 ** ExitStat -- if we already had an error, stick with
2567 if (OpMode != MD_VERIFY && !bitset(EF_VRFYONLY, e->e_flags) &&
2568 LogLevel > ((stat == EX_TEMPFAIL) ? 8 : (stat == EX_OK) ? 7 : 6))
2569 logdelivery(m, mci, &statmsg[4], ctladdr, xstart, e);
2572 printf("giveresponse: stat=%d, e->e_message=%s\n",
2573 stat, e->e_message == NULL ? "<NULL>" : e->e_message);
2575 if (stat != EX_TEMPFAIL)
2577 if (stat != EX_OK && (stat != EX_TEMPFAIL || e->e_message == NULL))
2579 if (e->e_message != NULL)
2581 e->e_message = newstr(&statmsg[4]);
2589 ** LOGDELIVERY -- log the delivery in the system log
2591 ** Care is taken to avoid logging lines that are too long, because
2592 ** some versions of syslog have an unfortunate proclivity for core
2593 ** dumping. This is a hack, to be sure, that is at best empirical.
2596 ** m -- the mailer info. Can be NULL for initial queue.
2597 ** mci -- the mailer connection info -- can be NULL if the
2598 ** log is occuring when no connection is active.
2599 ** stat -- the message to print for the status.
2600 ** ctladdr -- the controlling address for the to list.
2601 ** xstart -- the transaction start time, used for
2602 ** computing transaction delay.
2603 ** e -- the current envelope.
2613 logdelivery(m, mci, stat, ctladdr, xstart, e)
2619 register ENVELOPE *e;
2626 # if (SYSLOG_BUFSIZE) >= 256
2627 /* ctladdr: max 106 bytes */
2629 if (ctladdr != NULL)
2631 snprintf(bp, SPACELEFT(buf, bp), ", ctladdr=%s",
2632 shortenstring(ctladdr->q_paddr, 83));
2634 if (bitset(QGOODUID, ctladdr->q_flags))
2636 (void) snprintf(bp, SPACELEFT(buf, bp), " (%d/%d)",
2637 ctladdr->q_uid, ctladdr->q_gid);
2642 /* delay & xdelay: max 41 bytes */
2643 snprintf(bp, SPACELEFT(buf, bp), ", delay=%s",
2644 pintvl(curtime() - e->e_ctime, TRUE));
2647 if (xstart != (time_t) 0)
2649 snprintf(bp, SPACELEFT(buf, bp), ", xdelay=%s",
2650 pintvl(curtime() - xstart, TRUE));
2654 /* mailer: assume about 19 bytes (max 10 byte mailer name) */
2657 snprintf(bp, SPACELEFT(buf, bp), ", mailer=%s", m->m_name);
2661 /* relay: max 66 bytes for IPv4 addresses */
2662 if (mci != NULL && mci->mci_host != NULL)
2665 extern SOCKADDR CurHostAddr;
2668 snprintf(bp, SPACELEFT(buf, bp), ", relay=%s",
2669 shortenstring(mci->mci_host, 40));
2673 if (CurHostAddr.sa.sa_family != 0)
2675 snprintf(bp, SPACELEFT(buf, bp), " [%s]",
2676 anynet_ntoa(&CurHostAddr));
2680 else if (strcmp(stat, "queued") != 0)
2682 p = macvalue('h', e);
2683 if (p != NULL && p[0] != '\0')
2685 snprintf(bp, SPACELEFT(buf, bp), ", relay=%s",
2686 shortenstring(p, 40));
2691 #define STATLEN (((SYSLOG_BUFSIZE) - 100) / 4)
2698 # define STATLEN 203
2701 /* stat: max 210 bytes */
2702 if ((bp - buf) > (sizeof buf - ((STATLEN) + 20)))
2704 /* desperation move -- truncate data */
2705 bp = buf + sizeof buf - ((STATLEN) + 17);
2710 (void) strcpy(bp, ", stat=");
2713 (void) strcpy(bp, shortenstring(stat, (STATLEN)));
2715 /* id, to: max 13 + TOBUFSIZE bytes */
2716 l = SYSLOG_BUFSIZE - 100 - strlen(buf);
2718 while (strlen(p) >= (SIZE_T) l)
2720 register char *q = strchr(p + l, ',');
2724 sm_syslog(LOG_INFO, e->e_id,
2729 sm_syslog(LOG_INFO, e->e_id, "to=%s%s", p, buf);
2731 # else /* we have a very short log buffer size */
2733 l = SYSLOG_BUFSIZE - 85;
2735 while (strlen(p) >= (SIZE_T) l)
2737 register char *q = strchr(p + l, ',');
2741 sm_syslog(LOG_INFO, e->e_id,
2746 sm_syslog(LOG_INFO, e->e_id, "to=%s", p);
2748 if (ctladdr != NULL)
2751 snprintf(bp, SPACELEFT(buf, bp), "ctladdr=%s",
2752 shortenstring(ctladdr->q_paddr, 83));
2754 if (bitset(QGOODUID, ctladdr->q_flags))
2756 (void) snprintf(bp, SPACELEFT(buf, bp), " (%d/%d)",
2757 ctladdr->q_uid, ctladdr->q_gid);
2760 sm_syslog(LOG_INFO, e->e_id, "%s", buf);
2763 snprintf(bp, SPACELEFT(buf, bp), "delay=%s",
2764 pintvl(curtime() - e->e_ctime, TRUE));
2766 if (xstart != (time_t) 0)
2768 snprintf(bp, SPACELEFT(buf, bp), ", xdelay=%s",
2769 pintvl(curtime() - xstart, TRUE));
2775 snprintf(bp, SPACELEFT(buf, bp), ", mailer=%s", m->m_name);
2778 sm_syslog(LOG_INFO, e->e_id, "%.1000s", buf);
2782 if (mci != NULL && mci->mci_host != NULL)
2785 extern SOCKADDR CurHostAddr;
2788 snprintf(bp, SPACELEFT(buf, bp), "relay=%.100s", mci->mci_host);
2792 if (CurHostAddr.sa.sa_family != 0)
2793 snprintf(bp, SPACELEFT(buf, bp), " [%.100s]",
2794 anynet_ntoa(&CurHostAddr));
2797 else if (strcmp(stat, "queued") != 0)
2799 p = macvalue('h', e);
2800 if (p != NULL && p[0] != '\0')
2801 snprintf(buf, sizeof buf, "relay=%.100s", p);
2804 sm_syslog(LOG_INFO, e->e_id, "%.1000s", buf);
2806 sm_syslog(LOG_INFO, e->e_id, "stat=%s", shortenstring(stat, 63));
2807 # endif /* short log buffer */
2810 ** PUTFROMLINE -- output a UNIX-style from line (or whatever)
2812 ** This can be made an arbitrary message separator by changing $l
2814 ** One of the ugliest hacks seen by human eyes is contained herein:
2815 ** UUCP wants those stupid "remote from <host>" lines. Why oh why
2816 ** does a well-meaning programmer such as myself have to deal with
2817 ** this kind of antique garbage????
2820 ** mci -- the connection information.
2821 ** e -- the envelope.
2827 ** outputs some text to fp.
2835 char *template = UnixFromLine;
2839 if (bitnset(M_NHDR, mci->mci_mailer->m_flags))
2842 mci->mci_flags |= MCIF_INHEADER;
2844 if (bitnset(M_UGLYUUCP, mci->mci_mailer->m_flags))
2848 expand("\201g", buf, sizeof buf, e);
2849 bang = strchr(buf, '!');
2853 char hname[MAXNAME];
2856 ** If we can construct a UUCP path, do so
2859 at = strrchr(buf, '@');
2862 expand( "\201k", hname, sizeof hname, e);
2867 (void) snprintf(xbuf, sizeof xbuf,
2868 "From %.800s \201d remote from %.100s\n",
2874 (void) snprintf(xbuf, sizeof xbuf,
2875 "From %.800s \201d remote from %.100s\n",
2880 expand(template, buf, sizeof buf, e);
2881 putxline(buf, strlen(buf), mci, PXLF_HEADER);
2884 ** PUTBODY -- put the body of a message.
2887 ** mci -- the connection information.
2888 ** e -- the envelope to put out.
2889 ** separator -- if non-NULL, a message separator that must
2890 ** not be permitted in the resulting message.
2896 ** The message is written onto fp.
2899 /* values for output state variable */
2900 #define OS_HEAD 0 /* at beginning of line */
2901 #define OS_CR 1 /* read a carriage return */
2902 #define OS_INLINE 2 /* putting rest of line */
2905 putbody(mci, e, separator)
2907 register ENVELOPE *e;
2911 char *boundaries[MAXMIMENESTING + 1];
2914 ** Output the body of the message
2917 if (e->e_dfp == NULL && bitset(EF_HAS_DF, e->e_flags))
2919 char *df = queuename(e, 'd');
2921 e->e_dfp = fopen(df, "r");
2922 if (e->e_dfp == NULL)
2923 syserr("putbody: Cannot open %s for %s from %s",
2924 df, e->e_to, e->e_from.q_paddr);
2926 if (e->e_dfp == NULL)
2928 if (bitset(MCIF_INHEADER, mci->mci_flags))
2931 mci->mci_flags &= ~MCIF_INHEADER;
2933 putline("<<< No Message Collected >>>", mci);
2936 if (e->e_dfino == (ino_t) 0)
2940 if (fstat(fileno(e->e_dfp), &stbuf) < 0)
2944 e->e_dfdev = stbuf.st_dev;
2945 e->e_dfino = stbuf.st_ino;
2951 if (bitset(MCIF_CVT8TO7, mci->mci_flags))
2954 ** Do 8 to 7 bit MIME conversion.
2957 /* make sure it looks like a MIME message */
2958 if (hvalue("MIME-Version", e->e_header) == NULL)
2959 putline("MIME-Version: 1.0", mci);
2961 if (hvalue("Content-Type", e->e_header) == NULL)
2963 snprintf(buf, sizeof buf,
2964 "Content-Type: text/plain; charset=%s",
2969 /* now do the hard work */
2970 boundaries[0] = NULL;
2971 mci->mci_flags |= MCIF_INHEADER;
2972 mime8to7(mci, e->e_header, e, boundaries, M87F_OUTER);
2975 else if (bitset(MCIF_CVT7TO8, mci->mci_flags))
2977 mime7to8(mci, e->e_header, e);
2980 else if (MaxMimeHeaderLength > 0 || MaxMimeFieldLength > 0)
2982 /* Use mime8to7 to check multipart for MIME header overflows */
2983 boundaries[0] = NULL;
2984 mci->mci_flags |= MCIF_INHEADER;
2985 mime8to7(mci, e->e_header, e, boundaries, M87F_OUTER|M87F_NO8TO7);
3001 if (bitset(MCIF_INHEADER, mci->mci_flags))
3004 mci->mci_flags &= ~MCIF_INHEADER;
3007 /* determine end of buffer; allow for short mailer lines */
3008 buflim = &buf[sizeof buf - 1];
3009 if (mci->mci_mailer->m_linelimit > 0 &&
3010 mci->mci_mailer->m_linelimit < sizeof buf - 1)
3011 buflim = &buf[mci->mci_mailer->m_linelimit - 1];
3012 eol_len = strlen(mci->mci_mailer->m_eol);
3014 /* copy temp file to output with mapping */
3018 while (!ferror(mci->mci_out))
3022 else if ((c = getc(e->e_dfp)) == EOF)
3024 if (bitset(MCIF_7BIT, mci->mci_flags))
3031 bitnset(M_NONULLS, mci->mci_mailer->m_flags))
3034 if (c != '\r' && c != '\n' && bp < buflim)
3040 /* check beginning of line for special cases */
3044 if (buf[0] == 'F' &&
3045 bitnset(M_ESCFROM, mci->mci_mailer->m_flags) &&
3046 strncmp(buf, "From ", 5) == 0)
3050 if (buf[0] == '-' && buf[1] == '-' &&
3053 /* possible separator */
3054 int sl = strlen(separator);
3056 if (strncmp(&buf[2], separator, sl) == 0)
3059 if (buf[0] == '.' &&
3060 bitnset(M_XDOT, mci->mci_mailer->m_flags))
3065 /* now copy out saved line */
3066 if (TrafficLogFile != NULL)
3068 fprintf(TrafficLogFile, "%05d >>> ",
3071 putc(padc, TrafficLogFile);
3072 for (xp = buf; xp < bp; xp++)
3073 putc(*xp, TrafficLogFile);
3075 fputs(mci->mci_mailer->m_eol,
3080 putc(padc, mci->mci_out);
3081 mci->mci_contentlen++;
3084 for (xp = buf; xp < bp; xp++)
3086 putc(*xp, mci->mci_out);
3087 mci->mci_contentlen++;
3091 fputs(mci->mci_mailer->m_eol,
3093 mci->mci_contentlen += eol_len;
3104 /* determine next state */
3117 fputs(mci->mci_mailer->m_eol, mci->mci_out);
3118 mci->mci_contentlen += eol_len;
3119 if (TrafficLogFile != NULL)
3121 fputs(mci->mci_mailer->m_eol,
3128 /* had a naked carriage return */
3142 bitnset(M_NONULLS, mci->mci_mailer->m_flags))
3146 if (mci->mci_mailer->m_linelimit > 0 &&
3147 pos > mci->mci_mailer->m_linelimit &&
3150 putc('!', mci->mci_out);
3151 mci->mci_contentlen++;
3152 fputs(mci->mci_mailer->m_eol, mci->mci_out);
3153 mci->mci_contentlen += eol_len;
3154 if (TrafficLogFile != NULL)
3156 fprintf(TrafficLogFile, "!%s",
3157 mci->mci_mailer->m_eol);
3165 if (TrafficLogFile != NULL)
3166 fputs(mci->mci_mailer->m_eol,
3168 fputs(mci->mci_mailer->m_eol, mci->mci_out);
3169 mci->mci_contentlen += eol_len;
3175 if (TrafficLogFile != NULL)
3176 putc(c, TrafficLogFile);
3177 putc(c, mci->mci_out);
3178 mci->mci_contentlen++;
3186 /* make sure we are at the beginning of a line */
3189 if (TrafficLogFile != NULL)
3191 for (xp = buf; xp < bp; xp++)
3192 putc(*xp, TrafficLogFile);
3194 for (xp = buf; xp < bp; xp++)
3196 putc(*xp, mci->mci_out);
3197 mci->mci_contentlen++;
3203 if (TrafficLogFile != NULL)
3204 fputs(mci->mci_mailer->m_eol, TrafficLogFile);
3205 fputs(mci->mci_mailer->m_eol, mci->mci_out);
3206 mci->mci_contentlen += eol_len;
3210 if (ferror(e->e_dfp))
3212 syserr("putbody: df%s: read error", e->e_id);
3213 ExitStat = EX_IOERR;
3217 /* some mailers want extra blank line at end of message */
3218 if (bitnset(M_BLANKEND, mci->mci_mailer->m_flags) &&
3219 buf[0] != '\0' && buf[0] != '\n')
3222 (void) fflush(mci->mci_out);
3223 if (ferror(mci->mci_out) && errno != EPIPE)
3225 syserr("putbody: write error");
3226 ExitStat = EX_IOERR;
3231 ** MAILFILE -- Send a message to a file.
3233 ** If the file has the setuid/setgid bits set, but NO execute
3234 ** bits, sendmail will try to become the owner of that file
3235 ** rather than the real user. Obviously, this only works if
3236 ** sendmail runs as root.
3238 ** This could be done as a subordinate mailer, except that it
3239 ** is used implicitly to save messages in ~/dead.letter. We
3240 ** view this as being sufficiently important as to include it
3241 ** here. For example, if the system is dying, we shouldn't have
3242 ** to create another process plus some pipes to save the message.
3245 ** filename -- the name of the file to send to.
3246 ** mailer -- mailer definition for recipient -- if NULL,
3248 ** ctladdr -- the controlling address header -- includes
3249 ** the userid/groupid to be when sending.
3250 ** sfflags -- flags for opening.
3251 ** e -- the current envelope.
3254 ** The exit code associated with the operation.
3260 static jmp_buf CtxMailfileTimeout;
3261 static void mailfiletimeout __P((void));
3264 mailfile(filename, mailer, ctladdr, sfflags, e)
3265 char *volatile filename;
3266 MAILER *volatile mailer;
3268 volatile int sfflags;
3269 register ENVELOPE *e;
3272 register pid_t pid = -1;
3273 volatile int mode = ST_MODE_NOFILE;
3274 bool suidwarn = geteuid() == 0;
3280 printf("mailfile %s\n ctladdr=", filename);
3281 printaddr(ctladdr, FALSE);
3285 mailer = FileMailer;
3287 if (e->e_xfp != NULL)
3291 ** Special case /dev/null. This allows us to restrict file
3292 ** delivery to regular files only.
3295 if (strcmp(filename, "/dev/null") == 0)
3298 /* check for 8-bit available */
3299 if (bitset(EF_HAS8BIT, e->e_flags) &&
3300 bitnset(M_7BITS, mailer->m_flags) &&
3301 (bitset(EF_DONT_MIME, e->e_flags) ||
3302 !(bitset(MM_MIME8BIT, MimeMode) ||
3303 (bitset(EF_IS_MIME, e->e_flags) &&
3304 bitset(MM_CVTMIME, MimeMode)))))
3306 usrerr("554 Cannot send 8-bit data to 7-bit destination");
3307 e->e_status = "5.6.3";
3312 ** Fork so we can change permissions here.
3313 ** Note that we MUST use fork, not vfork, because of
3314 ** the complications of calling subroutines, etc.
3323 /* child -- actually write to file */
3327 volatile int oflags = O_WRONLY|O_APPEND;
3329 if (e->e_lockfp != NULL)
3330 (void) close(fileno(e->e_lockfp));
3332 (void) setsignal(SIGINT, SIG_DFL);
3333 (void) setsignal(SIGHUP, SIG_DFL);
3334 (void) setsignal(SIGTERM, SIG_DFL);
3335 (void) umask(OldUmask);
3339 if (setjmp(CtxMailfileTimeout) != 0)
3344 if (TimeOuts.to_fileopen > 0)
3345 ev = setevent(TimeOuts.to_fileopen, mailfiletimeout, 0);
3350 if (bitset(DBS_FILEDELIVERYTOSYMLINK, DontBlameSendmail))
3351 err = stat(filename, &stb);
3353 err = lstat(filename, &stb);
3356 if (stat(filename, &stb) < 0)
3359 stb.st_mode = ST_MODE_NOFILE;
3361 oflags |= O_CREAT|O_EXCL;
3363 else if (bitset(S_IXUSR|S_IXGRP|S_IXOTH, stb.st_mode) ||
3364 (!bitset(DBS_FILEDELIVERYTOHARDLINK, DontBlameSendmail) &&
3365 stb.st_nlink != 1) ||
3366 (SafeFileEnv != NULL && !S_ISREG(stb.st_mode)))
3368 if (mode == ST_MODE_NOFILE)
3371 /* limit the errors to those actually caused in the child */
3375 if (ctladdr != NULL || bitset(SFF_RUNASREALUID, sfflags))
3377 /* ignore setuid and setgid bits */
3378 mode &= ~(S_ISGID|S_ISUID);
3381 /* we have to open the dfile BEFORE setuid */
3382 if (e->e_dfp == NULL && bitset(EF_HAS_DF, e->e_flags))
3384 char *df = queuename(e, 'd');
3386 e->e_dfp = fopen(df, "r");
3387 if (e->e_dfp == NULL)
3389 syserr("mailfile: Cannot open %s for %s from %s",
3390 df, e->e_to, e->e_from.q_paddr);
3394 /* select a new user to run as */
3395 if (!bitset(SFF_RUNASREALUID, sfflags))
3397 if (bitnset(M_SPECIFIC_UID, mailer->m_flags))
3399 RealUserName = NULL;
3400 RealUid = mailer->m_uid;
3402 else if (bitset(S_ISUID, mode))
3404 RealUserName = NULL;
3405 RealUid = stb.st_uid;
3407 else if (ctladdr != NULL && ctladdr->q_uid != 0)
3409 if (ctladdr->q_ruser != NULL)
3410 RealUserName = ctladdr->q_ruser;
3412 RealUserName = ctladdr->q_user;
3413 RealUid = ctladdr->q_uid;
3415 else if (mailer != NULL && mailer->m_uid != 0)
3417 RealUserName = DefUser;
3418 RealUid = mailer->m_uid;
3422 RealUserName = DefUser;
3426 /* select a new group to run as */
3427 if (bitnset(M_SPECIFIC_UID, mailer->m_flags))
3428 RealGid = mailer->m_gid;
3429 else if (bitset(S_ISGID, mode))
3430 RealGid = stb.st_gid;
3431 else if (ctladdr != NULL && ctladdr->q_uid != 0)
3432 RealGid = ctladdr->q_gid;
3433 else if (mailer != NULL && mailer->m_gid != 0)
3434 RealGid = mailer->m_gid;
3440 if (!bitset(SFF_ROOTOK, sfflags))
3448 /* set group id list (needs /etc/group access) */
3449 if (RealUserName != NULL && !DontInitGroups)
3451 if (initgroups(RealUserName, RealGid) == -1 && suidwarn)
3452 syserr("mailfile: initgroups(%s, %d) failed",
3453 RealUserName, RealGid);
3459 gidset[0] = RealGid;
3460 if (setgroups(1, gidset) == -1 && suidwarn)
3461 syserr("mailfile: setgroups() failed");
3464 /* if you have a safe environment, go into it */
3465 if (SafeFileEnv != NULL && SafeFileEnv[0] != '\0')
3469 if (chroot(SafeFileEnv) < 0)
3471 syserr("mailfile: Cannot chroot(%s)",
3475 i = strlen(SafeFileEnv);
3476 if (strncmp(SafeFileEnv, filename, i) == 0)
3480 syserr("mailfile: cannot chdir(/)");
3482 /* now reset the group and user ids */
3484 if (setgid(RealGid) < 0 && suidwarn)
3485 syserr("mailfile: setgid(%ld) failed", (long) RealGid);
3486 vendor_set_uid(RealUid);
3487 if (setuid(RealUid) < 0 && suidwarn)
3488 syserr("mailfile: setuid(%ld) failed", (long) RealUid);
3490 /* move into some "safe" directory */
3491 if (mailer->m_execdir != NULL)
3494 char buf[MAXLINE + 1];
3496 for (p = mailer->m_execdir; p != NULL; p = q)
3501 expand(p, buf, sizeof buf, e);
3505 printf("mailfile: trydir %s\n",
3507 if (buf[0] != '\0' && chdir(buf) >= 0)
3512 sfflags |= SFF_NOPATHCHECK;
3513 if (!bitset(DBS_FILEDELIVERYTOSYMLINK, DontBlameSendmail))
3514 sfflags |= SFF_NOSLINK;
3515 if (!bitset(DBS_FILEDELIVERYTOHARDLINK, DontBlameSendmail))
3516 sfflags |= SFF_NOHLINK;
3517 sfflags &= ~SFF_OPENASROOT;
3518 f = safefopen(filename, oflags, FileMode, sfflags);
3521 message("554 cannot open %s: %s",
3522 shortenstring(filename, MAXSHORTSTR),
3526 if (filechanged(filename, fileno(f), &stb))
3528 message("554 file changed after open");
3531 if (fstat(fileno(f), &stb) < 0)
3533 message("554 cannot fstat %s", errstring(errno));
3540 bzero(&mcibuf, sizeof mcibuf);
3541 mcibuf.mci_mailer = mailer;
3543 mcibuf.mci_contentlen = 0;
3544 if (bitnset(M_7BITS, mailer->m_flags))
3545 mcibuf.mci_flags |= MCIF_7BIT;
3547 /* clear out per-message flags from connection structure */
3548 mcibuf.mci_flags &= ~(MCIF_CVT7TO8|MCIF_CVT8TO7);
3550 if (bitset(EF_HAS8BIT, e->e_flags) &&
3551 !bitset(EF_DONT_MIME, e->e_flags) &&
3552 bitnset(M_7BITS, mailer->m_flags))
3553 mcibuf.mci_flags |= MCIF_CVT8TO7;
3556 if (bitnset(M_MAKE8BIT, mailer->m_flags) &&
3557 !bitset(MCIF_7BIT, mcibuf.mci_flags) &&
3558 (p = hvalue("Content-Transfer-Encoding", e->e_header)) != NULL &&
3559 (strcasecmp(p, "quoted-printable") == 0 ||
3560 strcasecmp(p, "base64") == 0) &&
3561 (p = hvalue("Content-Type", e->e_header)) != NULL)
3563 /* may want to convert 7 -> 8 */
3564 /* XXX should really parse it here -- and use a class XXX */
3565 if (strncasecmp(p, "text/plain", 10) == 0 &&
3566 (p[10] == '\0' || p[10] == ' ' || p[10] == ';'))
3567 mcibuf.mci_flags |= MCIF_CVT7TO8;
3571 putfromline(&mcibuf, e);
3572 (*e->e_puthdr)(&mcibuf, e->e_header, e, M87F_OUTER);
3573 (*e->e_putbody)(&mcibuf, e, NULL);
3574 putline("\n", &mcibuf);
3575 if (fflush(f) < 0 || ferror(f))
3577 message("451 I/O error: %s", errstring(errno));
3581 /* reset ISUID & ISGID bits for paranoid systems */
3583 (void) fchmod(fileno(f), (MODE_T) stb.st_mode);
3585 (void) chmod(filename, (MODE_T) stb.st_mode);
3587 (void) xfclose(f, "mailfile", filename);
3588 (void) fflush(stdout);
3595 /* parent -- wait for exit status */
3601 syserr("mailfile: %s: wait", mailer->m_name);
3602 return (EX_SOFTWARE);
3605 return (WEXITSTATUS(st));
3608 syserr("mailfile: %s: child died on signal %d",
3609 mailer->m_name, st);
3610 return (EX_UNAVAILABLE);
3614 return EX_UNAVAILABLE; /* avoid compiler warning on IRIX */
3620 longjmp(CtxMailfileTimeout, 1);
3623 ** HOSTSIGNATURE -- return the "signature" for a host.
3625 ** The signature describes how we are going to send this -- it
3626 ** can be just the hostname (for non-Internet hosts) or can be
3627 ** an ordered list of MX hosts.
3630 ** m -- the mailer describing this host.
3631 ** host -- the host name.
3632 ** e -- the current envelope.
3635 ** The signature for this host.
3638 ** Can tweak the symbol table.
3642 hostsignature(m, host, e)
3655 int oldoptions = _res.options;
3656 char *mxhosts[MAXMXHOSTS + 1];
3660 ** Check to see if this uses IPC -- if not, it can't have MX records.
3664 if (strcmp(p, "[IPC]") != 0 && strcmp(p, "[TCP]") != 0)
3666 /* just an ordinary mailer */
3671 ** Look it up in the symbol table.
3674 s = stab(host, ST_HOSTSIG, ST_ENTER);
3675 if (s->s_hostsig != NULL)
3676 return s->s_hostsig;
3679 ** Not already there -- create a signature.
3683 if (ConfigLevel < 2)
3684 _res.options &= ~(RES_DEFNAMES | RES_DNSRCH); /* XXX */
3686 for (hp = host; hp != NULL; hp = endp)
3688 endp = strchr(hp, ':');
3692 if (bitnset(M_NOMX, m->m_flags))
3694 /* skip MX lookups */
3702 nmx = getmxrr(hp, mxhosts, TRUE, &rcode);
3707 /* update the connection info for this host */
3708 mci = mci_get(hp, m);
3709 mci->mci_errno = errno;
3710 mci->mci_herrno = h_errno;
3711 mci->mci_lastuse = curtime();
3712 mci_setstat(mci, rcode, NULL, NULL);
3714 /* use the original host name as signature */
3721 for (i = 0; i < nmx; i++)
3723 len += strlen(mxhosts[i]) + 1;
3725 if (s->s_hostsig != NULL)
3726 len += strlen(s->s_hostsig) + 1;
3728 if (s->s_hostsig != NULL)
3730 (void) strcpy(p, s->s_hostsig);
3738 for (i = 0; i < nmx; i++)
3742 strcpy(p, mxhosts[i]);
3748 makelower(s->s_hostsig);
3749 if (ConfigLevel < 2)
3750 _res.options = oldoptions;
3752 /* not using BIND -- the signature is just the host name */
3753 s->s_hostsig = host;
3756 printf("hostsignature(%s) = %s\n", host, s->s_hostsig);
3757 return s->s_hostsig;