2 * Copyright (c) 1998-2010, 2012 Proofpoint, Inc. and its suppliers.
4 * Copyright (c) 1983, 1995-1997 Eric P. Allman. All rights reserved.
5 * Copyright (c) 1988, 1993
6 * The Regents of the University of California. All rights reserved.
8 * By using this file, you agree to the terms and conditions set
9 * forth in the LICENSE file which can be found at the top level of
10 * the sendmail distribution.
17 SM_RCSID("@(#)$Id: deliver.c,v 8.1030 2013-11-22 20:51:55 ca Exp $")
20 # include <login_cap.h>
21 #endif /* HASSETUSERCONTEXT */
23 #if NETINET || NETINET6
24 # include <arpa/inet.h>
25 #endif /* NETINET || NETINET6 */
29 #endif /* STARTTLS || SASL */
31 static int deliver __P((ENVELOPE *, ADDRESS *));
32 static void dup_queue_file __P((ENVELOPE *, ENVELOPE *, int));
33 static void mailfiletimeout __P((int));
34 static void endwaittimeout __P((int));
35 static int parse_hostsignature __P((char *, char **, MAILER *));
36 static void sendenvelope __P((ENVELOPE *, int));
37 static int coloncmp __P((const char *, const char *));
40 # include <openssl/err.h>
41 static int starttls __P((MAILER *, MCI *, ENVELOPE *));
42 static int endtlsclt __P((MCI *));
45 static bool iscltflgset __P((ENVELOPE *, int));
46 # endif /* STARTTLS || SASL */
49 ** SENDALL -- actually send all the messages.
52 ** e -- the envelope to send.
53 ** mode -- the delivery mode to use. If SM_DEFAULT, use
54 ** the current e->e_sendmode.
60 ** Scans the send lists and sends everything it finds.
61 ** Delivers any appropriate error messages.
62 ** If we are running in a non-interactive mode, takes the
63 ** appropriate action.
75 register ENVELOPE *ee;
76 ENVELOPE *splitenv = NULL;
77 int oldverbose = Verbose;
78 bool somedeliveries = false, expensive = false;
82 ** If this message is to be discarded, don't bother sending
83 ** the message at all.
86 if (bitset(EF_DISCARD, e->e_flags))
89 sm_dprintf("sendall: discarding id %s\n", e->e_id);
90 e->e_flags |= EF_CLRQUEUE;
92 logundelrcpts(e, "discarded", 9, true);
93 else if (LogLevel > 4)
94 sm_syslog(LOG_INFO, e->e_id, "discarded");
95 markstats(e, NULL, STATS_REJECT);
100 ** If we have had global, fatal errors, don't bother sending
101 ** the message at all if we are in SMTP mode. Local errors
102 ** (e.g., a single address failing) will still cause the other
103 ** addresses to be sent.
106 if (bitset(EF_FATALERRS, e->e_flags) &&
107 (OpMode == MD_SMTP || OpMode == MD_DAEMON))
109 e->e_flags |= EF_CLRQUEUE;
113 /* determine actual delivery mode */
114 if (mode == SM_DEFAULT)
116 mode = e->e_sendmode;
117 if (mode != SM_VERIFY && mode != SM_DEFER &&
118 shouldqueue(e->e_msgpriority, e->e_ctime))
124 sm_dprintf("\n===== SENDALL: mode %c, id %s, e_from ",
126 printaddr(sm_debug_file(), &e->e_from, false);
127 sm_dprintf("\te_flags = ");
129 sm_dprintf("sendqueue:\n");
130 printaddr(sm_debug_file(), e->e_sendqueue, true);
134 ** Do any preprocessing necessary for the mode we are running.
135 ** Check to make sure the hop count is reasonable.
136 ** Delete sends to the sender in mailing lists.
143 if (e->e_hopcount > MaxHopCount)
147 if (e->e_sendqueue != NULL &&
148 e->e_sendqueue->q_paddr != NULL)
149 recip = e->e_sendqueue->q_paddr;
154 queueup(e, WILL_BE_QUEUED(mode), false);
155 e->e_flags |= EF_FATALERRS|EF_PM_NOTIFY|EF_CLRQUEUE;
156 ExitStat = EX_UNAVAILABLE;
157 syserr("554 5.4.6 Too many hops %d (%d max): from %s via %s, to %s",
158 e->e_hopcount, MaxHopCount, e->e_from.q_paddr,
159 RealHostName == NULL ? "localhost" : RealHostName,
161 for (q = e->e_sendqueue; q != NULL; q = q->q_next)
163 if (QS_IS_DEAD(q->q_state))
165 q->q_state = QS_BADADDR;
166 q->q_status = "5.4.6";
167 q->q_rstatus = "554 5.4.6 Too many hops";
173 ** Do sender deletion.
175 ** If the sender should be queued up, skip this.
176 ** This can happen if the name server is hosed when you
177 ** are trying to send mail. The result is that the sender
178 ** is instantiated in the queue as a recipient.
181 if (!bitset(EF_METOO, e->e_flags) &&
182 !QS_IS_QUEUEUP(e->e_from.q_state))
186 sm_dprintf("sendall: QS_SENDER ");
187 printaddr(sm_debug_file(), &e->e_from, false);
189 e->e_from.q_state = QS_SENDER;
190 (void) recipient(&e->e_from, &e->e_sendqueue, 0, e);
194 ** Handle alias owners.
196 ** We scan up the q_alias chain looking for owners.
197 ** We discard owners that are the same as the return path.
200 for (q = e->e_sendqueue; q != NULL; q = q->q_next)
202 register struct address *a;
204 for (a = q; a != NULL && a->q_owner == NULL; a = a->q_alias)
207 q->q_owner = a->q_owner;
209 if (q->q_owner != NULL &&
210 !QS_IS_DEAD(q->q_state) &&
211 strcmp(q->q_owner, e->e_from.q_paddr) == 0)
217 sm_dprintf("\nAfter first owner pass, sendq =\n");
218 printaddr(sm_debug_file(), e->e_sendqueue, true);
223 while (owner != NULL && otherowners > 0)
226 sm_dprintf("owner = \"%s\", otherowners = %d\n",
229 otherowners = bitset(EF_SENDRECEIPT, e->e_flags) ? 1 : 0;
231 for (q = e->e_sendqueue; q != NULL; q = q->q_next)
235 sm_dprintf("Checking ");
236 printaddr(sm_debug_file(), q, false);
238 if (QS_IS_DEAD(q->q_state))
241 sm_dprintf(" ... QS_IS_DEAD\n");
244 if (tTd(13, 29) && !tTd(13, 30))
246 sm_dprintf("Checking ");
247 printaddr(sm_debug_file(), q, false);
250 if (q->q_owner != NULL)
255 sm_dprintf(" ... First owner = \"%s\"\n",
259 else if (owner != q->q_owner)
261 if (strcmp(owner, q->q_owner) == 0)
264 sm_dprintf(" ... Same owner = \"%s\"\n",
267 /* make future comparisons cheap */
273 sm_dprintf(" ... Another owner \"%s\"\n",
279 else if (tTd(13, 40))
280 sm_dprintf(" ... Same owner = \"%s\"\n",
286 sm_dprintf(" ... Null owner\n");
290 if (QS_IS_BADADDR(q->q_state))
293 sm_dprintf(" ... QS_IS_BADADDR\n");
297 if (QS_IS_QUEUEUP(q->q_state))
299 MAILER *m = q->q_mailer;
302 ** If we have temporary address failures
303 ** (e.g., dns failure) and a fallback MX is
304 ** set, send directly to the fallback MX host.
307 if (FallbackMX != NULL &&
308 !wordinclass(FallbackMX, 'w') &&
310 !bitnset(M_NOMX, m->m_flags) &&
311 strcmp(m->m_mailer, "[IPC]") == 0 &&
312 m->m_argv[0] != NULL &&
313 strcmp(m->m_argv[0], "TCP") == 0)
319 sm_dprintf(" ... FallbackMX\n");
321 len = strlen(FallbackMX) + 1;
322 p = sm_rpool_malloc_x(e->e_rpool, len);
323 (void) sm_strlcpy(p, FallbackMX, len);
330 sm_dprintf(" ... QS_IS_QUEUEUP\n");
336 ** If this mailer is expensive, and if we don't
337 ** want to make connections now, just mark these
338 ** addresses and return. This is useful if we
339 ** want to batch connections to reduce load. This
340 ** will cause the messages to be queued up, and a
341 ** daemon will come along to send the messages later.
344 if (NoConnect && !Verbose &&
345 bitnset(M_EXPENSIVE, q->q_mailer->m_flags))
348 sm_dprintf(" ... expensive\n");
349 q->q_state = QS_QUEUEUP;
352 else if (bitnset(M_HOLD, q->q_mailer->m_flags) &&
353 QueueLimitId == NULL &&
354 QueueLimitSender == NULL &&
355 QueueLimitRecipient == NULL)
358 sm_dprintf(" ... hold\n");
359 q->q_state = QS_QUEUEUP;
362 else if (QueueMode != QM_QUARANTINE &&
363 e->e_quarmsg != NULL)
366 sm_dprintf(" ... quarantine: %s\n",
368 q->q_state = QS_QUEUEUP;
374 sm_dprintf(" ... deliverable\n");
375 somedeliveries = true;
379 if (owner != NULL && otherowners > 0)
382 ** Split this envelope into two.
385 ee = (ENVELOPE *) sm_rpool_malloc_x(e->e_rpool,
388 ee->e_message = NULL;
393 sm_dprintf("sendall: split %s into %s, owner = \"%s\", otherowners = %d\n",
394 e->e_id, ee->e_id, owner,
397 ee->e_header = copyheader(e->e_header, ee->e_rpool);
398 ee->e_sendqueue = copyqueue(e->e_sendqueue,
400 ee->e_errorqueue = copyqueue(e->e_errorqueue,
402 ee->e_flags = e->e_flags & ~(EF_INQUEUE|EF_CLRQUEUE|EF_FATALERRS|EF_SENDRECEIPT|EF_RET_PARAM);
403 ee->e_flags |= EF_NORECEIPT;
404 setsender(owner, ee, NULL, '\0', true);
407 sm_dprintf("sendall(split): QS_SENDER ");
408 printaddr(sm_debug_file(), &ee->e_from, false);
410 ee->e_from.q_state = QS_SENDER;
414 ee->e_qgrp = e->e_qgrp;
415 ee->e_qdir = e->e_qdir;
416 ee->e_errormode = EM_MAIL;
417 ee->e_sibling = splitenv;
418 ee->e_statmsg = NULL;
419 if (e->e_quarmsg != NULL)
420 ee->e_quarmsg = sm_rpool_strdup_x(ee->e_rpool,
424 for (q = e->e_sendqueue; q != NULL; q = q->q_next)
426 if (q->q_owner == owner)
428 q->q_state = QS_CLONED;
430 sm_dprintf("\t... stripping %s from original envelope\n",
434 for (q = ee->e_sendqueue; q != NULL; q = q->q_next)
436 if (q->q_owner != owner)
438 q->q_state = QS_CLONED;
440 sm_dprintf("\t... dropping %s from cloned envelope\n",
445 /* clear DSN parameters */
446 q->q_flags &= ~(QHASNOTIFY|Q_PINGFLAGS);
447 q->q_flags |= DefaultNotify & ~QPINGONSUCCESS;
449 sm_dprintf("\t... moving %s to cloned envelope\n",
454 if (mode != SM_VERIFY && bitset(EF_HAS_DF, e->e_flags))
455 dup_queue_file(e, ee, DATAFL_LETTER);
458 ** Give the split envelope access to the parent
459 ** transcript file for errors obtained while
460 ** processing the recipients (done before the
461 ** envelope splitting).
464 if (e->e_xfp != NULL)
465 ee->e_xfp = sm_io_dup(e->e_xfp);
467 /* failed to dup e->e_xfp, start a new transcript */
468 if (ee->e_xfp == NULL)
471 if (mode != SM_VERIFY && LogLevel > 4)
472 sm_syslog(LOG_INFO, e->e_id,
473 "%s: clone: owner=%s",
480 setsender(owner, e, NULL, '\0', true);
483 sm_dprintf("sendall(owner): QS_SENDER ");
484 printaddr(sm_debug_file(), &e->e_from, false);
486 e->e_from.q_state = QS_SENDER;
487 e->e_errormode = EM_MAIL;
488 e->e_flags |= EF_NORECEIPT;
489 e->e_flags &= ~EF_FATALERRS;
492 /* if nothing to be delivered, just queue up everything */
493 if (!somedeliveries && !WILL_BE_QUEUED(mode) &&
499 sm_dprintf("No deliveries: auto-queueing\n");
503 /* treat this as a delivery in terms of counting tries */
507 for (ee = splitenv; ee != NULL; ee = ee->e_sibling)
515 if ((WILL_BE_QUEUED(mode) || mode == SM_FORK ||
516 (mode != SM_VERIFY &&
517 (SuperSafe == SAFE_REALLY ||
518 SuperSafe == SAFE_REALLY_POSTMILTER))) &&
519 (!bitset(EF_INQUEUE, e->e_flags) || splitenv != NULL))
524 ** Be sure everything is instantiated in the queue.
525 ** Split envelopes first in case the machine crashes.
526 ** If the original were done first, we may lose
532 #else /* !HASFLOCK */
533 msync = mode == SM_FORK;
534 #endif /* !HASFLOCK */
536 for (ee = splitenv; ee != NULL; ee = ee->e_sibling)
537 queueup(ee, WILL_BE_QUEUED(mode), msync);
538 queueup(e, WILL_BE_QUEUED(mode), msync);
542 checkfds("after envelope splitting");
545 ** If we belong in background, fork now.
550 sm_dprintf("sendall: final mode = %c\n", mode);
553 sm_dprintf("\n================ Final Send Queue(s) =====================\n");
554 sm_dprintf("\n *** Envelope %s, e_from=%s ***\n",
555 e->e_id, e->e_from.q_paddr);
556 printaddr(sm_debug_file(), e->e_sendqueue, true);
557 for (ee = splitenv; ee != NULL; ee = ee->e_sibling)
559 sm_dprintf("\n *** Envelope %s, e_from=%s ***\n",
560 ee->e_id, ee->e_from.q_paddr);
561 printaddr(sm_debug_file(), ee->e_sendqueue, true);
563 sm_dprintf("==========================================================\n\n");
576 #endif /* HASFLOCK */
578 e->e_flags |= EF_INQUEUE;
579 (void) dropenvelope(e, splitenv != NULL, true);
580 for (ee = splitenv; ee != NULL; ee = ee->e_sibling)
582 if (ee->e_nrcpts > 0)
583 ee->e_flags |= EF_INQUEUE;
584 (void) dropenvelope(ee, false, true);
589 if (e->e_xfp != NULL)
590 (void) sm_io_flush(e->e_xfp, SM_TIME_DEFAULT);
594 ** Since fcntl locking has the interesting semantic that
595 ** the lock is owned by a process, not by an open file
596 ** descriptor, we have to flush this to the queue, and
597 ** then restart from scratch in the child.
601 /* save id for future use */
604 /* now drop the envelope in the parent */
605 e->e_flags |= EF_INQUEUE;
606 (void) dropenvelope(e, splitenv != NULL, false);
608 /* arrange to reacquire lock after fork */
612 for (ee = splitenv; ee != NULL; ee = ee->e_sibling)
614 /* save id for future use */
615 char *qid = ee->e_id;
617 /* drop envelope in parent */
618 ee->e_flags |= EF_INQUEUE;
619 (void) dropenvelope(ee, false, false);
621 /* and save qid for reacquisition */
625 #endif /* !HASFLOCK */
628 ** Since the delivery may happen in a child and the parent
629 ** does not wait, the parent may close the maps thereby
630 ** removing any shared memory used by the map. Therefore,
631 ** close the maps now so the child will dynamically open
632 ** them if necessary.
640 syserr("deliver: fork 1");
645 for (ee = splitenv; ee != NULL; ee = ee->e_sibling)
648 #endif /* HASFLOCK */
653 /* be sure we leave the temp files to our child */
654 /* close any random open files in the envelope */
656 if (e->e_dfp != NULL)
657 (void) sm_io_close(e->e_dfp, SM_TIME_DEFAULT);
659 e->e_flags &= ~EF_HAS_DF;
661 /* can't call unlockqueue to avoid unlink of xfp */
662 if (e->e_lockfp != NULL)
663 (void) sm_io_close(e->e_lockfp, SM_TIME_DEFAULT);
665 syserr("%s: sendall: null lockfp", e->e_id);
667 #endif /* HASFLOCK */
669 /* make sure the parent doesn't own the envelope */
673 /* catch intermediate zombie */
675 #endif /* USE_DOUBLE_FORK */
679 /* Reset global flags */
680 RestartRequest = NULL;
681 RestartWorkGroup = false;
682 ShutdownRequest = NULL;
686 ** Initialize exception stack and default exception
687 ** handler for child process.
690 sm_exc_newthread(fatal_error);
693 ** Since we have accepted responsbility for the message,
694 ** change the SIGTERM handler. intsig() (the old handler)
695 ** would remove the envelope if this was a command line
696 ** message submission.
699 (void) sm_signal(SIGTERM, SIG_DFL);
702 /* double fork to avoid zombies */
707 #endif /* USE_DOUBLE_FORK */
709 CurrentPid = getpid();
711 /* be sure we are immune from the terminal */
715 /* prevent parent from waiting if there was an error */
719 syserr("deliver: fork 2");
721 e->e_flags |= EF_INQUEUE;
724 #endif /* HASFLOCK */
725 finis(true, true, ExitStat);
728 /* be sure to give error messages in child */
732 ** Close any cached connections.
734 ** We don't send the QUIT protocol because the parent
735 ** still knows about the connection.
737 ** This should only happen when delivering an error
741 mci_flush(false, NULL);
748 ** Now reacquire and run the various queue files.
751 for (ee = splitenv; ee != NULL; ee = ee->e_sibling)
753 ENVELOPE *sibling = ee->e_sibling;
755 (void) dowork(ee->e_qgrp, ee->e_qdir, ee->e_id,
757 ee->e_sibling = sibling;
759 (void) dowork(e->e_qgrp, e->e_qdir, e->e_id,
761 finis(true, true, ExitStat);
762 #endif /* HASFLOCK */
765 sendenvelope(e, mode);
766 (void) dropenvelope(e, true, true);
767 for (ee = splitenv; ee != NULL; ee = ee->e_sibling)
770 if (mode != SM_VERIFY)
772 sendenvelope(ee, mode);
773 (void) dropenvelope(ee, true, true);
777 Verbose = oldverbose;
779 finis(true, true, ExitStat);
783 sendenvelope(e, mode)
784 register ENVELOPE *e;
791 sm_dprintf("sendenvelope(%s) e_flags=0x%lx\n",
792 e->e_id == NULL ? "[NOQUEUE]" : e->e_id,
795 sm_syslog(LOG_DEBUG, e->e_id,
796 "sendenvelope, flags=0x%lx",
800 ** If we have had global, fatal errors, don't bother sending
801 ** the message at all if we are in SMTP mode. Local errors
802 ** (e.g., a single address failing) will still cause the other
803 ** addresses to be sent.
806 if (bitset(EF_FATALERRS, e->e_flags) &&
807 (OpMode == MD_SMTP || OpMode == MD_DAEMON))
809 e->e_flags |= EF_CLRQUEUE;
814 ** Don't attempt deliveries if we want to bounce now
815 ** or if deliver-by time is exceeded.
818 if (!bitset(EF_RESPONSE, e->e_flags) &&
819 (TimeOuts.to_q_return[e->e_timeoutclass] == NOW ||
820 (IS_DLVR_RETURN(e) && e->e_deliver_by > 0 &&
821 curtime() > e->e_ctime + e->e_deliver_by)))
825 ** Run through the list and send everything.
827 ** Set EF_GLOBALERRS so that error messages during delivery
828 ** result in returned mail.
832 e->e_flags |= EF_GLOBALERRS;
834 macdefine(&e->e_macro, A_PERM, macid("{envid}"), e->e_envid);
835 macdefine(&e->e_macro, A_PERM, macid("{bodytype}"), e->e_bodytype);
838 if (!bitset(EF_SPLIT, e->e_flags))
844 ** Save old sibling and set it to NULL to avoid
845 ** queueing up the same envelopes again.
846 ** This requires that envelopes in that list have
847 ** been take care of before (or at some other place).
850 oldsib = e->e_sibling;
852 if (!split_by_recipient(e) &&
853 bitset(EF_FATALERRS, e->e_flags))
855 if (OpMode == MD_SMTP || OpMode == MD_DAEMON)
856 e->e_flags |= EF_CLRQUEUE;
859 for (ee = e->e_sibling; ee != NULL; ee = ee->e_sibling)
860 queueup(ee, false, true);
863 for (ee = e->e_sibling; ee != NULL; ee = ee->e_sibling)
865 /* now unlock the job */
869 /* this envelope is marked unused */
870 if (ee->e_dfp != NULL)
872 (void) sm_io_close(ee->e_dfp, SM_TIME_DEFAULT);
876 ee->e_flags &= ~EF_HAS_DF;
878 e->e_sibling = oldsib;
881 /* now run through the queue */
882 for (q = e->e_sendqueue; q != NULL; q = q->q_next)
885 char wbuf[MAXNAME + 20];
887 (void) sm_snprintf(wbuf, sizeof(wbuf), "sendall(%.*s)",
888 MAXNAME, q->q_paddr);
891 if (mode == SM_VERIFY)
893 e->e_to = q->q_paddr;
894 if (QS_IS_SENDABLE(q->q_state))
896 if (q->q_host != NULL && q->q_host[0] != '\0')
897 message("deliverable: mailer %s, host %s, user %s",
902 message("deliverable: mailer %s, user %s",
907 else if (QS_IS_OK(q->q_state))
910 ** Checkpoint the send list every few addresses
913 if (CheckpointInterval > 0 &&
914 e->e_nsent >= CheckpointInterval)
916 queueup(e, false, false);
919 (void) deliver(e, q);
925 e->e_dtime = curtime();
930 checkfd012("end of sendenvelope");
934 #if REQUIRES_DIR_FSYNC
936 ** SYNC_DIR -- fsync a directory based on a filename
939 ** filename -- path of file
947 sync_dir(filename, panic)
953 char dir[MAXPATHLEN];
955 if (!RequiresDirfsync)
958 /* filesystems which require the directory be synced */
959 dirp = strrchr(filename, '/');
962 if (sm_strlcpy(dir, filename, sizeof(dir)) >= sizeof(dir))
964 dir[dirp - filename] = '\0';
969 dirfd = open(dirp, O_RDONLY, 0700);
971 sm_syslog(LOG_INFO, NOQID, "sync_dir: %s: fsync(%d)",
975 if (fsync(dirfd) < 0)
978 syserr("!sync_dir: cannot fsync directory %s",
980 else if (LogLevel > 1)
981 sm_syslog(LOG_ERR, NOQID,
982 "sync_dir: cannot fsync directory %s: %s",
983 dirp, sm_errstring(errno));
988 #endif /* REQUIRES_DIR_FSYNC */
990 ** DUP_QUEUE_FILE -- duplicate a queue file into a split queue
993 ** e -- the existing envelope
994 ** ee -- the new envelope
995 ** type -- the queue file type (e.g., DATAFL_LETTER)
1002 dup_queue_file(e, ee, type)
1006 char f1buf[MAXPATHLEN], f2buf[MAXPATHLEN];
1012 ** Make sure both are in the same directory.
1015 (void) sm_strlcpy(f1buf, queuename(e, type), sizeof(f1buf));
1016 (void) sm_strlcpy(f2buf, queuename(ee, type), sizeof(f2buf));
1018 /* Force the df to disk if it's not there yet */
1019 if (type == DATAFL_LETTER && e->e_dfp != NULL &&
1020 sm_io_setinfo(e->e_dfp, SM_BF_COMMIT, NULL) < 0 &&
1023 syserr("!dup_queue_file: can't commit %s", f1buf);
1027 if (link(f1buf, f2buf) < 0)
1029 int save_errno = errno;
1031 syserr("sendall: link(%s, %s)", f1buf, f2buf);
1032 if (save_errno == EEXIST)
1034 if (unlink(f2buf) < 0)
1036 syserr("!sendall: unlink(%s): permanent",
1040 if (link(f1buf, f2buf) < 0)
1042 syserr("!sendall: link(%s, %s): permanent",
1048 SYNC_DIR(f2buf, true);
1051 ** DOFORK -- do a fork, retrying a couple of times on failure.
1053 ** This MUST be a macro, since after a vfork we are running
1054 ** two processes on the same stack!!!
1060 ** From a macro??? You've got to be kidding!
1063 ** Modifies the ==> LOCAL <== variable 'pid', leaving:
1064 ** pid of child in parent, zero in child.
1065 ** -1 on unrecoverable error.
1068 ** I'm awfully sorry this looks so awful. That's
1069 ** vfork for you.....
1072 #define NFORKTRIES 5
1078 #define DOFORK(fORKfN) \
1082 for (i = NFORKTRIES; --i >= 0; )\
1088 (void) sleep((unsigned) NFORKTRIES - i);\
1092 ** DOFORK -- simple fork interface to DOFORK.
1098 ** pid of child in parent.
1103 ** returns twice, once in parent and once in child.
1109 register pid_t pid = -1;
1116 ** COLONCMP -- compare host-signatures up to first ':' or EOS
1118 ** This takes two strings which happen to be host-signatures and
1119 ** compares them. If the lowest preference portions of the MX-RR's
1120 ** match (up to ':' or EOS, whichever is first), then we have
1121 ** match. This is used for coattail-piggybacking messages during
1122 ** message delivery.
1123 ** If the signatures are the same up to the first ':' the remainder of
1124 ** the signatures are then compared with a normal strcmp(). This saves
1125 ** re-examining the first part of the signatures.
1128 ** a - first host-signature
1129 ** b - second host-signature
1132 ** HS_MATCH_NO -- no "match".
1133 ** HS_MATCH_FIRST -- "match" for the first MX preference
1134 ** (up to the first colon (':')).
1135 ** HS_MATCH_FULL -- match for the entire MX record.
1141 #define HS_MATCH_NO 0
1142 #define HS_MATCH_FIRST 1
1143 #define HS_MATCH_FULL 2
1147 register const char *a;
1148 register const char *b;
1150 int ret = HS_MATCH_NO;
1155 /* Need to account for IPv6 bracketed addresses */
1158 else if (*a == ']' && braclev > 0)
1160 else if (*a == ':' && braclev <= 0)
1162 ret = HS_MATCH_FIRST;
1166 else if (*a == '\0')
1167 return HS_MATCH_FULL; /* a full match */
1170 if (ret == HS_MATCH_NO &&
1172 ((*a == '\0' && *(b - 1) == ':') ||
1173 (*a == ':' && *(b - 1) == '\0')))
1174 return HS_MATCH_FIRST;
1175 if (ret == HS_MATCH_FIRST && strcmp(a, b) == 0)
1176 return HS_MATCH_FULL;
1182 ** SHOULD_TRY_FBSH -- Should try FallbackSmartHost?
1186 ** tried_fallbacksmarthost -- has been tried already? (in/out)
1187 ** hostbuf -- buffer for hostname (expand FallbackSmartHost) (out)
1188 ** hbsz -- size of hostbuf
1189 ** status -- current delivery status
1192 ** true iff FallbackSmartHost should be tried.
1195 static bool should_try_fbsh __P((ENVELOPE *, bool *, char *, size_t, int));
1198 should_try_fbsh(e, tried_fallbacksmarthost, hostbuf, hbsz, status)
1200 bool *tried_fallbacksmarthost;
1206 ** If the host was not found or a temporary failure occurred
1207 ** and a FallbackSmartHost is defined (and we have not yet
1208 ** tried it), then make one last try with it as the host.
1211 if ((status == EX_NOHOST || status == EX_TEMPFAIL) &&
1212 FallbackSmartHost != NULL && !*tried_fallbacksmarthost)
1214 *tried_fallbacksmarthost = true;
1215 expand(FallbackSmartHost, hostbuf, hbsz, e);
1216 if (!wordinclass(hostbuf, 'w'))
1219 sm_dprintf("one last try with FallbackSmartHost %s\n",
1228 ** DELIVER -- Deliver a message to a list of addresses.
1230 ** This routine delivers to everyone on the same host as the
1231 ** user on the head of the list. It is clever about mailers
1232 ** that don't handle multiple users. It is NOT guaranteed
1233 ** that it will deliver to all these addresses however -- so
1234 ** deliver should be called once for each address on the
1236 ** Deliver tries to be as opportunistic as possible about piggybacking
1237 ** messages. Some definitions to make understanding easier follow below.
1238 ** Piggybacking occurs when an existing connection to a mail host can
1239 ** be used to send the same message to more than one recipient at the
1240 ** same time. So "no piggybacking" means one message for one recipient
1241 ** per connection. "Intentional piggybacking" happens when the
1242 ** recipients' host address (not the mail host address) is used to
1243 ** attempt piggybacking. Recipients with the same host address
1244 ** have the same mail host. "Coincidental piggybacking" relies on
1245 ** piggybacking based on all the mail host addresses in the MX-RR. This
1246 ** is "coincidental" in the fact it could not be predicted until the
1247 ** MX Resource Records for the hosts were obtained and examined. For
1248 ** example (preference order and equivalence is important, not values):
1249 ** domain1 IN MX 10 mxhost-A
1250 ** IN MX 20 mxhost-B
1251 ** domain2 IN MX 4 mxhost-A
1253 ** Domain1 and domain2 can piggyback the same message to mxhost-A or
1254 ** mxhost-B (if mxhost-A cannot be reached).
1255 ** "Coattail piggybacking" relaxes the strictness of "coincidental
1256 ** piggybacking" in the hope that most significant (lowest value)
1257 ** MX preference host(s) can create more piggybacking. For example
1258 ** (again, preference order and equivalence is important, not values):
1259 ** domain3 IN MX 100 mxhost-C
1260 ** IN MX 100 mxhost-D
1261 ** IN MX 200 mxhost-E
1262 ** domain4 IN MX 50 mxhost-C
1263 ** IN MX 50 mxhost-D
1264 ** IN MX 80 mxhost-F
1265 ** A message for domain3 and domain4 can piggyback to mxhost-C if mxhost-C
1266 ** is available. Same with mxhost-D because in both RR's the preference
1267 ** value is the same as mxhost-C, respectively.
1268 ** So deliver attempts coattail piggybacking when possible. If the
1269 ** first MX preference level hosts cannot be used then the piggybacking
1270 ** reverts to coincidental piggybacking. Using the above example you
1271 ** cannot deliver to mxhost-F for domain3 regardless of preference value.
1272 ** ("Coattail" from "riding on the coattails of your predecessor" meaning
1273 ** gaining benefit from a predecessor effort with no or little addition
1274 ** effort. The predecessor here being the preceding MX RR).
1277 ** e -- the envelope to deliver.
1278 ** firstto -- head of the address list to deliver to.
1281 ** zero -- successfully delivered.
1282 ** else -- some failure, see ExitStat for more info.
1285 ** The standard input is passed off to someone.
1290 register ENVELOPE *e;
1293 char *host; /* host being sent to */
1294 char *user; /* user being sent to */
1296 register char **mvp;
1298 register MAILER *m; /* mailer for this recipient */
1299 ADDRESS *volatile ctladdr;
1300 #if HASSETUSERCONTEXT
1301 ADDRESS *volatile contextaddr = NULL;
1302 #endif /* HASSETUSERCONTEXT */
1303 register MCI *volatile mci;
1304 register ADDRESS *SM_NONVOLATILE to = firstto;
1305 volatile bool clever = false; /* running user smtp to this mailer */
1306 ADDRESS *volatile tochain = NULL; /* users chain in this mailer call */
1307 int rcode; /* response code */
1308 SM_NONVOLATILE int lmtp_rcode = EX_OK;
1309 SM_NONVOLATILE int nummxhosts = 0; /* number of MX hosts available */
1310 SM_NONVOLATILE int hostnum = 0; /* current MX host index */
1311 char *firstsig; /* signature of firstto */
1312 volatile pid_t pid = -1;
1313 char *volatile curhost;
1314 SM_NONVOLATILE unsigned short port = 0;
1315 SM_NONVOLATILE time_t enough = 0;
1317 char *SM_NONVOLATILE mux_path = NULL; /* path to UNIX domain socket */
1318 #endif /* NETUNIX */
1321 bool anyok; /* at least one address was OK */
1322 SM_NONVOLATILE bool goodmxfound = false; /* at least one MX was OK */
1328 static int tobufsize = 0;
1329 static char *tobuf = NULL;
1330 char *rpath; /* translated return path */
1333 char *mxhosts[MAXMXHOSTS + 1];
1334 char *pv[MAXPV + 1];
1335 char buf[MAXNAME + 1];
1336 char cbuf[MAXPATHLEN];
1339 SM_REQUIRE(firstto != NULL); /* same as to */
1340 if (!QS_IS_OK(to->q_state))
1343 suidwarn = geteuid() == 0;
1345 SM_REQUIRE(e != NULL);
1348 CurEnv = e; /* just in case */
1349 e->e_statmsg = NULL;
1350 SmtpError[0] = '\0';
1354 sm_dprintf("\n--deliver, id=%s, mailer=%s, host=`%s', first user=`%s'\n",
1355 e->e_id, m->m_name, host, to->q_user);
1357 printopenfds(false);
1360 ** Clear {client_*} macros if this is a bounce message to
1361 ** prevent rejection by check_compat ruleset.
1364 if (bitset(EF_RESPONSE, e->e_flags))
1366 macdefine(&e->e_macro, A_PERM, macid("{client_name}"), "");
1367 macdefine(&e->e_macro, A_PERM, macid("{client_ptr}"), "");
1368 macdefine(&e->e_macro, A_PERM, macid("{client_addr}"), "");
1369 macdefine(&e->e_macro, A_PERM, macid("{client_port}"), "");
1370 macdefine(&e->e_macro, A_PERM, macid("{client_resolve}"), "");
1375 ADDRESS *skip_back = NULL;
1378 ** Do initial argv setup.
1379 ** Insert the mailer name. Notice that $x expansion is
1380 ** NOT done on the mailer name. Then, if the mailer has
1381 ** a picky -f flag, we insert it as appropriate. This
1382 ** code does not check for 'pv' overflow; this places a
1383 ** manifest lower limit of 4 for MAXPV.
1384 ** The from address rewrite is expected to make
1385 ** the address relative to the other end.
1388 /* rewrite from address, using rewriting rules */
1390 SM_ASSERT(e->e_from.q_mailer != NULL);
1391 if (bitnset(M_UDBENVELOPE, e->e_from.q_mailer->m_flags))
1394 p = e->e_from.q_paddr;
1395 rpath = remotename(p, m, RF_SENDERADDR|RF_CANONICAL, &rcode, e);
1396 if (rcode != EX_OK && bitnset(M_xSMTP, m->m_flags))
1398 if (strlen(rpath) > MAXNAME)
1400 rpath = shortenstring(rpath, MAXSHORTSTR);
1402 /* avoid bogus errno */
1404 syserr("remotename: huge return path %s", rpath);
1406 rpath = sm_rpool_strdup_x(e->e_rpool, rpath);
1407 macdefine(&e->e_macro, A_PERM, 'g', rpath);
1408 macdefine(&e->e_macro, A_PERM, 'h', host);
1411 *pvp++ = m->m_argv[0];
1413 /* ignore long term host status information if mailer flag W is set */
1414 if (bitnset(M_NOHOSTSTAT, m->m_flags))
1415 IgnoreHostStatus = true;
1417 /* insert -f or -r flag as appropriate */
1419 (bitnset(M_FOPT, m->m_flags) ||
1420 bitnset(M_ROPT, m->m_flags)))
1422 if (bitnset(M_FOPT, m->m_flags))
1430 ** Append the other fixed parts of the argv. These run
1431 ** up to the first entry containing "$u". There can only
1432 ** be one of these, and there are only a few more slots
1433 ** in the pv after it.
1436 for (mvp = m->m_argv; (p = *++mvp) != NULL; )
1438 /* can't use strchr here because of sign extension problems */
1441 if ((*p++ & 0377) == MACROEXPAND)
1451 /* this entry is safe -- go ahead and process it */
1452 expand(*mvp, buf, sizeof(buf), e);
1453 *pvp++ = sm_rpool_strdup_x(e->e_rpool, buf);
1454 if (pvp >= &pv[MAXPV - 3])
1456 syserr("554 5.3.5 Too many parameters to %s before $u",
1464 ** If we have no substitution for the user name in the argument
1465 ** list, we know that we must supply the names otherwise -- and
1466 ** SMTP is the answer!!
1471 /* running LMTP or SMTP */
1474 setbitn(M_xSMTP, m->m_flags);
1476 else if (bitnset(M_LMTP, m->m_flags))
1478 /* not running LMTP */
1479 sm_syslog(LOG_ERR, NULL,
1480 "Warning: mailer %s: LMTP flag (F=z) turned off",
1482 clrbitn(M_LMTP, m->m_flags);
1486 ** At this point *mvp points to the argument with $u. We
1487 ** run through our address list and append all the addresses
1488 ** we can. If we run out of space, do not fret! We can
1489 ** always send another copy later.
1496 if (firstto->q_signature == NULL)
1497 firstto->q_signature = hostsignature(firstto->q_mailer,
1499 firstsig = firstto->q_signature;
1501 for (; to != NULL; to = to->q_next)
1503 /* avoid sending multiple recipients to dumb mailers */
1504 if (tochain != NULL && !bitnset(M_MUSER, m->m_flags))
1507 /* if already sent or not for this host, don't send */
1508 if (!QS_IS_OK(to->q_state)) /* already sent; look at next */
1512 ** Must be same mailer to keep grouping rcpts.
1513 ** If mailers don't match: continue; sendqueue is not
1514 ** sorted by mailers, so don't break;
1517 if (to->q_mailer != firstto->q_mailer)
1520 if (to->q_signature == NULL) /* for safety */
1521 to->q_signature = hostsignature(to->q_mailer,
1525 ** This is for coincidental and tailcoat piggybacking messages
1526 ** to the same mail host. While the signatures are identical
1527 ** (that's the MX-RR's are identical) we can do coincidental
1528 ** piggybacking. We try hard for coattail piggybacking
1529 ** with the same mail host when the next recipient has the
1530 ** same host at lowest preference. It may be that this
1531 ** won't work out, so 'skip_back' is maintained if a backup
1532 ** to coincidental piggybacking or full signature must happen.
1535 ret = firstto == to ? HS_MATCH_FULL :
1536 coloncmp(to->q_signature, firstsig);
1537 if (ret == HS_MATCH_FULL)
1539 else if (ret == HS_MATCH_NO)
1544 /* avoid overflowing tobuf */
1545 strsize += strlen(to->q_paddr) + 1;
1546 if (strsize > TOBUFSIZE)
1550 if (++rcptcount > to->q_mailer->m_maxrcpt)
1555 sm_dprintf("\nsend to ");
1556 printaddr(sm_debug_file(), to, false);
1559 /* compute effective uid/gid when sending */
1560 if (bitnset(M_RUNASRCPT, to->q_mailer->m_flags))
1561 # if HASSETUSERCONTEXT
1562 contextaddr = ctladdr = getctladdr(to);
1563 # else /* HASSETUSERCONTEXT */
1564 ctladdr = getctladdr(to);
1565 # endif /* HASSETUSERCONTEXT */
1569 sm_dprintf("ctladdr=");
1570 printaddr(sm_debug_file(), ctladdr, false);
1574 e->e_to = to->q_paddr;
1577 ** Check to see that these people are allowed to
1578 ** talk to each other.
1579 ** Check also for overflow of e_msgsize.
1582 if (m->m_maxsize != 0 &&
1583 (e->e_msgsize > m->m_maxsize || e->e_msgsize < 0))
1585 e->e_flags |= EF_NO_BODY_RETN;
1586 if (bitnset(M_LOCALMAILER, to->q_mailer->m_flags))
1587 to->q_status = "5.2.3";
1589 to->q_status = "5.3.4";
1591 /* set to->q_rstatus = NULL; or to the following? */
1592 usrerrenh(to->q_status,
1593 "552 Message is too large; %ld bytes max",
1595 markfailure(e, to, NULL, EX_UNAVAILABLE, false);
1596 giveresponse(EX_UNAVAILABLE, to->q_status, m,
1597 NULL, ctladdr, xstart, e, to);
1603 /* do config file checking of compatibility */
1604 quarantine = (e->e_quarmsg != NULL);
1605 rcode = rscheck("check_compat", e->e_from.q_paddr, to->q_paddr,
1606 e, RSF_RMCOMM|RSF_COUNT, 3, NULL,
1607 e->e_id, NULL, NULL);
1610 /* do in-code checking if not discarding */
1611 if (!bitset(EF_DISCARD, e->e_flags))
1613 rcode = checkcompat(to, e);
1619 markfailure(e, to, NULL, rcode, ovr);
1620 giveresponse(rcode, to->q_status, m,
1621 NULL, ctladdr, xstart, e, to);
1624 if (!quarantine && e->e_quarmsg != NULL)
1627 ** check_compat or checkcompat() has tried
1628 ** to quarantine but that isn't supported.
1629 ** Revert the attempt.
1632 e->e_quarmsg = NULL;
1633 macdefine(&e->e_macro, A_PERM,
1634 macid("{quarantine}"), "");
1636 if (bitset(EF_DISCARD, e->e_flags))
1640 sm_dprintf("deliver: discarding recipient ");
1641 printaddr(sm_debug_file(), to, false);
1644 /* pretend the message was sent */
1645 /* XXX should we log something here? */
1646 to->q_state = QS_DISCARDED;
1649 ** Remove discard bit to prevent discard of
1650 ** future recipients. This is safe because the
1651 ** true "global discard" has been handled before
1655 e->e_flags &= ~EF_DISCARD;
1660 ** Strip quote bits from names if the mailer is dumb
1664 if (bitnset(M_STRIPQ, m->m_flags))
1671 ** Strip all leading backslashes if requested and the
1672 ** next character is alphanumerical (the latter can
1673 ** probably relaxed a bit, see RFC2821).
1676 if (bitnset(M_STRIPBACKSL, m->m_flags) && user[0] == '\\')
1677 stripbackslash(user);
1679 /* hack attack -- delivermail compatibility */
1680 if (m == ProgMailer && *user == '|')
1684 ** If an error message has already been given, don't
1685 ** bother to send to this address.
1687 ** >>>>>>>>>> This clause assumes that the local mailer
1688 ** >> NOTE >> cannot do any further aliasing; that
1689 ** >>>>>>>>>> function is subsumed by sendmail.
1692 if (!QS_IS_OK(to->q_state))
1696 ** See if this user name is "special".
1697 ** If the user name has a slash in it, assume that this
1698 ** is a file -- send it off without further ado. Note
1699 ** that this type of addresses is not processed along
1700 ** with the others, so we fudge on the To person.
1703 if (strcmp(m->m_mailer, "[FILE]") == 0)
1705 macdefine(&e->e_macro, A_PERM, 'u', user);
1707 if (p == NULL && ctladdr != NULL)
1708 p = ctladdr->q_home;
1709 macdefine(&e->e_macro, A_PERM, 'z', p);
1710 expand(m->m_argv[1], buf, sizeof(buf), e);
1711 if (strlen(buf) > 0)
1712 rcode = mailfile(buf, m, ctladdr, SFF_CREAT, e);
1715 syserr("empty filename specification for mailer %s",
1719 giveresponse(rcode, to->q_status, m, NULL,
1720 ctladdr, xstart, e, to);
1721 markfailure(e, to, NULL, rcode, true);
1725 to->q_state = QS_SENT;
1726 if (bitnset(M_LOCALMAILER, m->m_flags) &&
1727 bitset(QPINGONSUCCESS, to->q_flags))
1729 to->q_flags |= QDELIVERED;
1730 to->q_status = "2.1.5";
1731 (void) sm_io_fprintf(e->e_xfp,
1733 "%s... Successfully delivered\n",
1737 to->q_statdate = curtime();
1738 markstats(e, to, STATS_NORMAL);
1743 ** Address is verified -- add this user to mailer
1744 ** argv, and add it to the print list of recipients.
1747 /* link together the chain of recipients */
1748 to->q_tchain = tochain;
1750 e->e_to = "[CHAIN]";
1752 macdefine(&e->e_macro, A_PERM, 'u', user); /* to user */
1754 if (p == NULL && ctladdr != NULL)
1755 p = ctladdr->q_home;
1756 macdefine(&e->e_macro, A_PERM, 'z', p); /* user's home */
1758 /* set the ${dsn_notify} macro if applicable */
1759 if (bitset(QHASNOTIFY, to->q_flags))
1761 char notify[MAXLINE];
1764 if (bitset(QPINGONSUCCESS, to->q_flags))
1765 (void) sm_strlcat(notify, "SUCCESS,",
1767 if (bitset(QPINGONFAILURE, to->q_flags))
1768 (void) sm_strlcat(notify, "FAILURE,",
1770 if (bitset(QPINGONDELAY, to->q_flags))
1771 (void) sm_strlcat(notify, "DELAY,",
1774 /* Set to NEVER or drop trailing comma */
1775 if (notify[0] == '\0')
1776 (void) sm_strlcat(notify, "NEVER",
1779 notify[strlen(notify) - 1] = '\0';
1781 macdefine(&e->e_macro, A_TEMP,
1782 macid("{dsn_notify}"), notify);
1785 macdefine(&e->e_macro, A_PERM,
1786 macid("{dsn_notify}"), NULL);
1789 ** Expand out this user into argument list.
1794 expand(*mvp, buf, sizeof(buf), e);
1795 *pvp++ = sm_rpool_strdup_x(e->e_rpool, buf);
1796 if (pvp >= &pv[MAXPV - 2])
1798 /* allow some space for trailing parms */
1804 /* see if any addresses still exist */
1805 if (tochain == NULL)
1811 /* print out messages as full list */
1813 for (to = tochain; to != NULL; to = to->q_tchain)
1814 strsize += strlen(to->q_paddr) + 1;
1815 if (strsize < TOBUFSIZE)
1816 strsize = TOBUFSIZE;
1817 if (strsize > tobufsize)
1820 tobuf = sm_pmalloc_x(strsize);
1821 tobufsize = strsize;
1825 for (to = tochain; to != NULL; to = to->q_tchain)
1827 (void) sm_strlcpyn(p, tobufsize - (p - tobuf), 2,
1831 e->e_to = tobuf + 1;
1834 ** Fill out any parameters after the $u parameter.
1839 while (*++mvp != NULL)
1841 expand(*mvp, buf, sizeof(buf), e);
1842 *pvp++ = sm_rpool_strdup_x(e->e_rpool, buf);
1843 if (pvp >= &pv[MAXPV])
1844 syserr("554 5.3.0 deliver: pv overflow after $u for %s",
1852 ** The argument vector gets built, pipes
1853 ** are created as necessary, and we fork & exec as
1855 ** If we are running SMTP, we just need to clean up.
1858 /* XXX this seems a bit weird */
1859 if (ctladdr == NULL && m != ProgMailer && m != FileMailer &&
1860 bitset(QGOODUID, e->e_from.q_flags))
1861 ctladdr = &e->e_from;
1864 if (ConfigLevel < 2)
1865 _res.options &= ~(RES_DEFNAMES | RES_DNSRCH); /* XXX */
1866 #endif /* NAMED_BIND */
1870 sm_dprintf("openmailer:");
1871 printav(sm_debug_file(), pv);
1878 ** Deal with the special case of mail handled through an IPC
1880 ** In this case we don't actually fork. We must be
1881 ** running SMTP for this to work. We will return a
1882 ** zero pid to indicate that we are running IPC.
1883 ** We also handle a debug version that just talks to stdin/out.
1894 /* make absolutely certain 0, 1, and 2 are in use */
1895 (void) sm_snprintf(wbuf, sizeof(wbuf), "%s... openmailer(%s)",
1896 shortenstring(e->e_to, MAXSHORTSTR),
1902 /* check for 8-bit available */
1903 if (bitset(EF_HAS8BIT, e->e_flags) &&
1904 bitnset(M_7BITS, m->m_flags) &&
1905 (bitset(EF_DONT_MIME, e->e_flags) ||
1906 !(bitset(MM_MIME8BIT, MimeMode) ||
1907 (bitset(EF_IS_MIME, e->e_flags) &&
1908 bitset(MM_CVTMIME, MimeMode)))))
1910 e->e_status = "5.6.3";
1911 usrerrenh(e->e_status,
1912 "554 Cannot send 8-bit data to 7-bit destination");
1918 checkfds("before delivery");
1920 /* check for Local Person Communication -- not for mortals!!! */
1921 if (strcmp(m->m_mailer, "[LPC]") == 0)
1925 /* flush any expired connections */
1926 (void) mci_scan(NULL);
1928 /* try to get a cached connection or just a slot */
1929 mci = mci_get(m->m_name, m);
1930 if (mci->mci_host == NULL)
1931 mci->mci_host = m->m_name;
1932 CurHostName = mci->mci_host;
1933 if (mci->mci_state != MCIS_CLOSED)
1935 message("Using cached SMTP/LPC connection for %s...",
1937 mci->mci_deliveries++;
1943 mci = mci_new(e->e_rpool);
1945 mci->mci_in = smioin;
1946 mci->mci_out = smioout;
1947 mci->mci_mailer = m;
1948 mci->mci_host = m->m_name;
1951 mci->mci_state = MCIS_OPENING;
1955 mci->mci_state = MCIS_OPEN;
1957 else if (strcmp(m->m_mailer, "[IPC]") == 0)
1961 if (pv[0] == NULL || pv[1] == NULL || pv[1][0] == '\0')
1963 syserr("null destination for %s mailer", m->m_mailer);
1969 if (strcmp(pv[0], "FILE") == 0)
1971 curhost = CurHostName = "localhost";
1975 # endif /* NETUNIX */
1977 CurHostName = pv[1];
1978 curhost = hostsignature(m, pv[1]);
1981 if (curhost == NULL || curhost[0] == '\0')
1983 syserr("null host signature for %s", pv[1]);
1990 syserr("554 5.3.5 non-clever IPC");
1997 # endif /* NETUNIX */
2000 port = htons((unsigned short) atoi(pv[2]));
2003 # ifdef NO_GETSERVBYNAME
2004 syserr("Invalid port number: %s", pv[2]);
2005 # else /* NO_GETSERVBYNAME */
2006 struct servent *sp = getservbyname(pv[2], "tcp");
2009 syserr("Service %s unknown", pv[2]);
2012 # endif /* NO_GETSERVBYNAME */
2016 nummxhosts = parse_hostsignature(curhost, mxhosts, m);
2017 if (TimeOuts.to_aconnect > 0)
2018 enough = curtime() + TimeOuts.to_aconnect;
2020 while (hostnum < nummxhosts)
2024 static char hostbuf[MAXNAME + 1];
2025 bool tried_fallbacksmarthost = false;
2028 if (*mxhosts[hostnum] == '[')
2030 endp = strchr(mxhosts[hostnum] + 1, ']');
2032 endp = strpbrk(endp + 1, ":,");
2035 endp = strpbrk(mxhosts[hostnum], ":,");
2036 # else /* NETINET6 */
2037 endp = strpbrk(mxhosts[hostnum], ":,");
2038 # endif /* NETINET6 */
2045 if (hostnum == 1 && skip_back != NULL)
2048 ** Coattail piggybacking is no longer an
2049 ** option with the mail host next to be tried
2050 ** no longer the lowest MX preference
2051 ** (hostnum == 1 meaning we're on the second
2052 ** preference). We do not try to coattail
2053 ** piggyback more than the first MX preference.
2054 ** Revert 'tochain' to last location for
2055 ** coincidental piggybacking. This works this
2056 ** easily because the q_tchain kept getting
2057 ** added to the top of the linked list.
2060 tochain = skip_back;
2063 if (*mxhosts[hostnum] == '\0')
2065 syserr("deliver: null host name in signature");
2071 (void) sm_strlcpy(hostbuf, mxhosts[hostnum],
2078 /* see if we already know that this host is fried */
2079 CurHostName = hostbuf;
2080 mci = mci_get(hostbuf, m);
2081 if (mci->mci_state != MCIS_CLOSED)
2087 sm_dprintf("openmailer: ");
2088 mci_dump(sm_debug_file(), mci, false);
2090 CurHostName = mci->mci_host;
2091 if (bitnset(M_LMTP, m->m_flags))
2093 else if (bitset(MCIF_ESMTP, mci->mci_flags))
2097 message("Using cached %sMTP connection to %s via %s...",
2098 type, hostbuf, m->m_name);
2099 mci->mci_deliveries++;
2102 mci->mci_mailer = m;
2103 if (mci->mci_exitstat != EX_OK)
2105 if (mci->mci_exitstat == EX_TEMPFAIL)
2108 /* Try FallbackSmartHost? */
2109 if (should_try_fbsh(e, &tried_fallbacksmarthost,
2110 hostbuf, sizeof(hostbuf),
2117 if (mci_lock_host(mci) != EX_OK)
2119 mci_setstat(mci, EX_TEMPFAIL, "4.4.5", NULL);
2124 /* try the connection */
2125 sm_setproctitle(true, e, "%s %s: %s",
2127 hostbuf, "user open");
2129 if (mux_path != NULL)
2131 message("Connecting to %s via %s...",
2132 mux_path, m->m_name);
2133 i = makeconnection_ds((char *) mux_path, mci);
2136 # endif /* NETUNIX */
2139 message("Connecting to %s via %s...",
2140 hostbuf, m->m_name);
2142 message("Connecting to %s port %d via %s...",
2143 hostbuf, ntohs(port),
2145 i = makeconnection(hostbuf, port, mci, e,
2148 mci->mci_errno = errno;
2149 mci->mci_lastuse = curtime();
2150 mci->mci_deliveries = 0;
2151 mci->mci_exitstat = i;
2152 mci_clr_extensions(mci);
2154 mci->mci_herrno = h_errno;
2155 # endif /* NAMED_BIND */
2158 ** Have we tried long enough to get a connection?
2159 ** If yes, skip to the fallback MX hosts
2163 if (enough > 0 && mci->mci_lastuse >= enough)
2167 extern int NumFallbackMXHosts;
2168 # else /* NAMED_BIND */
2169 const int NumFallbackMXHosts = 0;
2170 # endif /* NAMED_BIND */
2172 if (hostnum < nummxhosts && LogLevel > 9)
2173 sm_syslog(LOG_INFO, e->e_id,
2174 "Timeout.to_aconnect occurred before exhausting all addresses");
2176 /* turn off timeout if fallback available */
2177 if (NumFallbackMXHosts > 0)
2180 /* skip to a fallback MX host */
2181 h = nummxhosts - NumFallbackMXHosts;
2188 markstats(e, firstto, STATS_CONNECT);
2189 mci->mci_state = MCIS_OPENING;
2191 if (TrafficLogFile != NULL)
2192 (void) sm_io_fprintf(TrafficLogFile,
2194 "%05d === CONNECT %s\n",
2201 /* Try FallbackSmartHost? */
2202 if (should_try_fbsh(e, &tried_fallbacksmarthost,
2203 hostbuf, sizeof(hostbuf), i))
2207 sm_dprintf("openmailer: makeconnection => stat=%d, errno=%d\n",
2209 if (i == EX_TEMPFAIL)
2211 mci_unlock_host(mci);
2214 /* enter status of this host */
2217 /* should print some message here for -v mode */
2221 syserr("deliver: no host name");
2222 rcode = EX_SOFTWARE;
2229 /* flush any expired connections */
2230 (void) mci_scan(NULL);
2233 if (bitnset(M_LMTP, m->m_flags))
2235 /* try to get a cached connection */
2236 mci = mci_get(m->m_name, m);
2237 if (mci->mci_host == NULL)
2238 mci->mci_host = m->m_name;
2239 CurHostName = mci->mci_host;
2240 if (mci->mci_state != MCIS_CLOSED)
2242 message("Using cached LMTP connection for %s...",
2244 mci->mci_deliveries++;
2249 /* announce the connection to verbose listeners */
2250 if (host == NULL || host[0] == '\0')
2251 message("Connecting to %s...", m->m_name);
2253 message("Connecting to %s via %s...", host, m->m_name);
2254 if (TrafficLogFile != NULL)
2258 (void) sm_io_fprintf(TrafficLogFile, SM_TIME_DEFAULT,
2259 "%05d === EXEC", (int) CurrentPid);
2260 for (av = pv; *av != NULL; av++)
2261 (void) sm_io_fprintf(TrafficLogFile,
2262 SM_TIME_DEFAULT, " %s",
2264 (void) sm_io_fprintf(TrafficLogFile, SM_TIME_DEFAULT,
2269 checkfd012("before creating mail pipe");
2272 /* create a pipe to shove the mail through */
2273 if (pipe(mpvect) < 0)
2275 syserr("%s... openmailer(%s): pipe (to mailer)",
2276 shortenstring(e->e_to, MAXSHORTSTR), m->m_name);
2278 sm_dprintf("openmailer: NULL\n");
2284 /* make sure we didn't get one of the standard I/O files */
2285 if (mpvect[0] < 3 || mpvect[1] < 3)
2287 syserr("%s... openmailer(%s): bogus mpvect %d %d",
2288 shortenstring(e->e_to, MAXSHORTSTR), m->m_name,
2289 mpvect[0], mpvect[1]);
2292 sm_dprintf("openmailer: NULL\n");
2297 /* make sure system call isn't dead meat */
2298 checkfdopen(mpvect[0], "mpvect[0]");
2299 checkfdopen(mpvect[1], "mpvect[1]");
2300 if (mpvect[0] == mpvect[1] ||
2301 (e->e_lockfp != NULL &&
2302 (mpvect[0] == sm_io_getinfo(e->e_lockfp, SM_IO_WHAT_FD,
2304 mpvect[1] == sm_io_getinfo(e->e_lockfp, SM_IO_WHAT_FD,
2307 if (e->e_lockfp == NULL)
2308 syserr("%s... openmailer(%s): overlapping mpvect %d %d",
2309 shortenstring(e->e_to, MAXSHORTSTR),
2310 m->m_name, mpvect[0], mpvect[1]);
2312 syserr("%s... openmailer(%s): overlapping mpvect %d %d, lockfp = %d",
2313 shortenstring(e->e_to, MAXSHORTSTR),
2314 m->m_name, mpvect[0], mpvect[1],
2315 sm_io_getinfo(e->e_lockfp,
2316 SM_IO_WHAT_FD, NULL));
2320 /* create a return pipe */
2321 if (pipe(rpvect) < 0)
2323 syserr("%s... openmailer(%s): pipe (from mailer)",
2324 shortenstring(e->e_to, MAXSHORTSTR),
2326 (void) close(mpvect[0]);
2327 (void) close(mpvect[1]);
2329 sm_dprintf("openmailer: NULL\n");
2334 checkfdopen(rpvect[0], "rpvect[0]");
2335 checkfdopen(rpvect[1], "rpvect[1]");
2339 ** Actually fork the mailer process.
2340 ** DOFORK is clever about retrying.
2342 ** Dispose of SIGCHLD signal catchers that may be laying
2343 ** around so that endmailer will get it.
2346 if (e->e_xfp != NULL) /* for debugging */
2347 (void) sm_io_flush(e->e_xfp, SM_TIME_DEFAULT);
2348 (void) sm_io_flush(smioout, SM_TIME_DEFAULT);
2349 (void) sm_signal(SIGCHLD, SIG_DFL);
2353 /* pid is set by DOFORK */
2358 syserr("%s... openmailer(%s): cannot fork",
2359 shortenstring(e->e_to, MAXSHORTSTR), m->m_name);
2360 (void) close(mpvect[0]);
2361 (void) close(mpvect[1]);
2362 (void) close(rpvect[0]);
2363 (void) close(rpvect[1]);
2365 sm_dprintf("openmailer: NULL\n");
2373 int new_euid = NO_UID;
2374 int new_ruid = NO_UID;
2375 int new_gid = NO_GID;
2378 extern int DtableSize;
2380 CurrentPid = getpid();
2382 /* clear the events to turn off SIGALRMs */
2385 /* Reset global flags */
2386 RestartRequest = NULL;
2387 RestartWorkGroup = false;
2388 ShutdownRequest = NULL;
2391 if (e->e_lockfp != NULL)
2392 (void) close(sm_io_getinfo(e->e_lockfp,
2396 /* child -- set up input & exec mailer */
2397 (void) sm_signal(SIGALRM, sm_signal_noop);
2398 (void) sm_signal(SIGCHLD, SIG_DFL);
2399 (void) sm_signal(SIGHUP, SIG_IGN);
2400 (void) sm_signal(SIGINT, SIG_IGN);
2401 (void) sm_signal(SIGTERM, SIG_DFL);
2403 (void) sm_signal(SIGUSR1, sm_signal_noop);
2404 # endif /* SIGUSR1 */
2406 if (m != FileMailer || stat(tochain->q_user, &stb) < 0)
2409 # if HASSETUSERCONTEXT
2411 ** Set user resources.
2414 if (contextaddr != NULL)
2419 if (contextaddr->q_ruser != NULL)
2420 pwd = sm_getpwnam(contextaddr->q_ruser);
2422 pwd = sm_getpwnam(contextaddr->q_user);
2423 sucflags = LOGIN_SETRESOURCES|LOGIN_SETPRIORITY;
2424 #ifdef LOGIN_SETCPUMASK
2425 sucflags |= LOGIN_SETCPUMASK;
2426 #endif /* LOGIN_SETCPUMASK */
2427 #ifdef LOGIN_SETLOGINCLASS
2428 sucflags |= LOGIN_SETLOGINCLASS;
2429 #endif /* LOGIN_SETLOGINCLASS */
2431 sucflags |= LOGIN_SETMAC;
2432 #endif /* LOGIN_SETMAC */
2434 setusercontext(NULL, pwd, pwd->pw_uid,
2438 syserr("openmailer: setusercontext() failed");
2442 # endif /* HASSETUSERCONTEXT */
2445 /* tweak niceness */
2447 (void) nice(m->m_nice);
2448 #endif /* HASNICE */
2450 /* reset group id */
2451 if (bitnset(M_SPECIFIC_UID, m->m_flags))
2453 if (m->m_gid == NO_GID)
2458 else if (bitset(S_ISGID, stb.st_mode))
2459 new_gid = stb.st_gid;
2460 else if (ctladdr != NULL && ctladdr->q_gid != 0)
2462 if (!DontInitGroups)
2464 user = ctladdr->q_ruser;
2466 user = ctladdr->q_user;
2468 if (initgroups(user,
2469 ctladdr->q_gid) == -1
2472 syserr("openmailer: initgroups(%s, %ld) failed",
2473 user, (long) ctladdr->q_gid);
2481 gidset[0] = ctladdr->q_gid;
2482 if (setgroups(1, gidset) == -1
2485 syserr("openmailer: setgroups() failed");
2489 new_gid = ctladdr->q_gid;
2493 if (!DontInitGroups)
2496 if (initgroups(DefUser, DefGid) == -1 &&
2499 syserr("openmailer: initgroups(%s, %ld) failed",
2500 DefUser, (long) DefGid);
2509 if (setgroups(1, gidset) == -1
2512 syserr("openmailer: setgroups() failed");
2516 if (m->m_gid == NO_GID)
2521 if (new_gid != NO_GID)
2523 if (RunAsUid != 0 &&
2524 bitnset(M_SPECIFIC_UID, m->m_flags) &&
2525 new_gid != getgid() &&
2526 new_gid != getegid())
2528 /* Only root can change the gid */
2529 syserr("openmailer: insufficient privileges to change gid, RunAsUid=%ld, new_gid=%ld, gid=%ld, egid=%ld",
2530 (long) RunAsUid, (long) new_gid,
2531 (long) getgid(), (long) getegid());
2535 if (setgid(new_gid) < 0 && suidwarn)
2537 syserr("openmailer: setgid(%ld) failed",
2543 /* change root to some "safe" directory */
2544 if (m->m_rootdir != NULL)
2546 expand(m->m_rootdir, cbuf, sizeof(cbuf), e);
2548 sm_dprintf("openmailer: chroot %s\n",
2550 if (chroot(cbuf) < 0)
2552 syserr("openmailer: Cannot chroot(%s)",
2558 syserr("openmailer: cannot chdir(/)");
2565 sm_mbdb_terminate();
2566 if (bitnset(M_SPECIFIC_UID, m->m_flags))
2568 if (m->m_uid == NO_UID)
2569 new_euid = RunAsUid;
2571 new_euid = m->m_uid;
2574 ** Undo the effects of the uid change in main
2575 ** for signal handling. The real uid may
2576 ** be used by mailer in adding a "From "
2580 if (RealUid != 0 && RealUid != getuid())
2582 # if MAILER_SETUID_METHOD == USE_SETEUID
2584 if (setreuid(RealUid, geteuid()) < 0)
2586 syserr("openmailer: setreuid(%d, %d) failed",
2587 (int) RealUid, (int) geteuid());
2590 # endif /* HASSETREUID */
2591 # endif /* MAILER_SETUID_METHOD == USE_SETEUID */
2592 # if MAILER_SETUID_METHOD == USE_SETREUID
2594 # endif /* MAILER_SETUID_METHOD == USE_SETREUID */
2597 else if (bitset(S_ISUID, stb.st_mode))
2598 new_ruid = stb.st_uid;
2599 else if (ctladdr != NULL && ctladdr->q_uid != 0)
2600 new_ruid = ctladdr->q_uid;
2601 else if (m->m_uid != NO_UID)
2602 new_ruid = m->m_uid;
2606 # if _FFR_USE_SETLOGIN
2607 /* run disconnected from terminal and set login name */
2608 if (setsid() >= 0 &&
2609 ctladdr != NULL && ctladdr->q_uid != 0 &&
2610 new_euid == ctladdr->q_uid)
2614 pwd = sm_getpwuid(ctladdr->q_uid);
2615 if (pwd != NULL && suidwarn)
2616 (void) setlogin(pwd->pw_name);
2619 # endif /* _FFR_USE_SETLOGIN */
2621 if (new_euid != NO_UID)
2623 if (RunAsUid != 0 && new_euid != RunAsUid)
2625 /* Only root can change the uid */
2626 syserr("openmailer: insufficient privileges to change uid, new_euid=%ld, RunAsUid=%ld",
2627 (long) new_euid, (long) RunAsUid);
2631 vendor_set_uid(new_euid);
2632 # if MAILER_SETUID_METHOD == USE_SETEUID
2633 if (seteuid(new_euid) < 0 && suidwarn)
2635 syserr("openmailer: seteuid(%ld) failed",
2639 # endif /* MAILER_SETUID_METHOD == USE_SETEUID */
2640 # if MAILER_SETUID_METHOD == USE_SETREUID
2641 if (setreuid(new_ruid, new_euid) < 0 && suidwarn)
2643 syserr("openmailer: setreuid(%ld, %ld) failed",
2644 (long) new_ruid, (long) new_euid);
2647 # endif /* MAILER_SETUID_METHOD == USE_SETREUID */
2648 # if MAILER_SETUID_METHOD == USE_SETUID
2649 if (new_euid != geteuid() && setuid(new_euid) < 0 && suidwarn)
2651 syserr("openmailer: setuid(%ld) failed",
2655 # endif /* MAILER_SETUID_METHOD == USE_SETUID */
2657 else if (new_ruid != NO_UID)
2659 vendor_set_uid(new_ruid);
2660 if (setuid(new_ruid) < 0 && suidwarn)
2662 syserr("openmailer: setuid(%ld) failed",
2669 sm_dprintf("openmailer: running as r/euid=%ld/%ld, r/egid=%ld/%ld\n",
2670 (long) getuid(), (long) geteuid(),
2671 (long) getgid(), (long) getegid());
2673 /* move into some "safe" directory */
2674 if (m->m_execdir != NULL)
2678 for (p = m->m_execdir; p != NULL; p = q)
2683 expand(p, cbuf, sizeof(cbuf), e);
2687 sm_dprintf("openmailer: trydir %s\n",
2689 if (cbuf[0] != '\0' &&
2695 /* Check safety of program to be run */
2696 sff = SFF_ROOTOK|SFF_EXECOK;
2697 if (!bitnset(DBS_RUNWRITABLEPROGRAM,
2699 sff |= SFF_NOGWFILES|SFF_NOWWFILES;
2700 if (bitnset(DBS_RUNPROGRAMINUNSAFEDIRPATH,
2702 sff |= SFF_NOPATHCHECK;
2704 sff |= SFF_SAFEDIRPATH;
2705 ret = safefile(m->m_mailer, getuid(), getgid(),
2706 user, sff, 0, NULL);
2708 sm_syslog(LOG_INFO, e->e_id,
2709 "Warning: program %s unsafe: %s",
2710 m->m_mailer, sm_errstring(ret));
2712 /* arrange to filter std & diag output of command */
2713 (void) close(rpvect[0]);
2714 if (dup2(rpvect[1], STDOUT_FILENO) < 0)
2716 syserr("%s... openmailer(%s): cannot dup pipe %d for stdout",
2717 shortenstring(e->e_to, MAXSHORTSTR),
2718 m->m_name, rpvect[1]);
2721 (void) close(rpvect[1]);
2723 if (dup2(STDOUT_FILENO, STDERR_FILENO) < 0)
2725 syserr("%s... openmailer(%s): cannot dup stdout for stderr",
2726 shortenstring(e->e_to, MAXSHORTSTR),
2731 /* arrange to get standard input */
2732 (void) close(mpvect[1]);
2733 if (dup2(mpvect[0], STDIN_FILENO) < 0)
2735 syserr("%s... openmailer(%s): cannot dup pipe %d for stdin",
2736 shortenstring(e->e_to, MAXSHORTSTR),
2737 m->m_name, mpvect[0]);
2740 (void) close(mpvect[0]);
2742 /* arrange for all the files to be closed */
2743 sm_close_on_exec(STDERR_FILENO + 1, DtableSize);
2745 # if !_FFR_USE_SETLOGIN
2746 /* run disconnected from terminal */
2748 # endif /* !_FFR_USE_SETLOGIN */
2750 /* try to execute the mailer */
2751 (void) execve(m->m_mailer, (ARGV_T) pv,
2752 (ARGV_T) UserEnviron);
2754 syserr("Cannot exec %s", m->m_mailer);
2755 if (bitnset(M_LOCALMAILER, m->m_flags) ||
2756 transienterror(save_errno))
2758 _exit(EX_UNAVAILABLE);
2762 ** Set up return value.
2770 ** Allocate from general heap, not
2771 ** envelope rpool, because this mci
2772 ** is going to be cached.
2775 mci = mci_new(NULL);
2780 ** Prevent a storage leak by allocating
2781 ** this from the envelope rpool.
2784 mci = mci_new(e->e_rpool);
2787 mci->mci_mailer = m;
2790 mci->mci_state = MCIS_OPENING;
2795 mci->mci_state = MCIS_OPEN;
2798 (void) close(mpvect[0]);
2799 mci->mci_out = sm_io_open(SmFtStdiofd, SM_TIME_DEFAULT,
2800 (void *) &(mpvect[1]), SM_IO_WRONLY_B,
2802 if (mci->mci_out == NULL)
2804 syserr("deliver: cannot create mailer output channel, fd=%d",
2806 (void) close(mpvect[1]);
2807 (void) close(rpvect[0]);
2808 (void) close(rpvect[1]);
2813 (void) close(rpvect[1]);
2814 mci->mci_in = sm_io_open(SmFtStdiofd, SM_TIME_DEFAULT,
2815 (void *) &(rpvect[0]), SM_IO_RDONLY_B,
2817 if (mci->mci_in == NULL)
2819 syserr("deliver: cannot create mailer input channel, fd=%d",
2821 (void) close(rpvect[0]);
2822 (void) sm_io_close(mci->mci_out, SM_TIME_DEFAULT);
2823 mci->mci_out = NULL;
2830 ** If we are in SMTP opening state, send initial protocol.
2833 if (bitnset(M_7BITS, m->m_flags) &&
2834 (!clever || mci->mci_state == MCIS_OPENING))
2835 mci->mci_flags |= MCIF_7BIT;
2836 if (clever && mci->mci_state != MCIS_CLOSED)
2838 # if STARTTLS || SASL
2841 extern SOCKADDR CurHostAddr;
2842 # endif /* STARTTLS || SASL */
2845 # define DONE_AUTH(f) bitset(MCIF_AUTHACT, f)
2848 # define DONE_STARTTLS(f) bitset(MCIF_TLSACT, f)
2849 # endif /* STARTTLS */
2850 # define ONLY_HELO(f) bitset(MCIF_ONLY_EHLO, f)
2851 # define SET_HELO(f) f |= MCIF_ONLY_EHLO
2852 # define CLR_HELO(f) f &= ~MCIF_ONLY_EHLO
2854 # if STARTTLS || SASL
2855 /* don't use CurHostName, it is changed in many places */
2856 if (mci->mci_host != NULL)
2858 srvname = mci->mci_host;
2859 dotpos = strlen(srvname) - 1;
2862 if (srvname[dotpos] == '.')
2863 srvname[dotpos] = '\0';
2868 else if (mci->mci_mailer != NULL)
2870 srvname = mci->mci_mailer->m_name;
2879 /* don't set {server_name} to NULL or "": see getauth() */
2880 macdefine(&mci->mci_macro, A_TEMP, macid("{server_name}"),
2883 /* CurHostAddr is set by makeconnection() and mci_get() */
2884 if (CurHostAddr.sa.sa_family != 0)
2886 macdefine(&mci->mci_macro, A_TEMP,
2887 macid("{server_addr}"),
2888 anynet_ntoa(&CurHostAddr));
2890 else if (mci->mci_mailer != NULL)
2892 /* mailer name is unique, use it as address */
2893 macdefine(&mci->mci_macro, A_PERM,
2894 macid("{server_addr}"),
2895 mci->mci_mailer->m_name);
2899 /* don't set it to NULL or "": see getauth() */
2900 macdefine(&mci->mci_macro, A_PERM,
2901 macid("{server_addr}"), "0");
2904 /* undo change of srvname (mci->mci_host) */
2906 srvname[dotpos] = '.';
2908 reconnect: /* after switching to an encrypted connection */
2909 # endif /* STARTTLS || SASL */
2911 /* set the current connection information */
2914 mci->mci_saslcap = NULL;
2916 smtpinit(m, mci, e, ONLY_HELO(mci->mci_flags));
2917 CLR_HELO(mci->mci_flags);
2919 if (IS_DLVR_RETURN(e))
2922 ** Check whether other side can deliver e-mail
2926 if (!bitset(MCIF_DLVR_BY, mci->mci_flags))
2928 e->e_status = "5.4.7";
2929 usrerrenh(e->e_status,
2930 "554 Server does not support Deliver By");
2931 rcode = EX_UNAVAILABLE;
2934 if (e->e_deliver_by > 0 &&
2935 e->e_deliver_by - (curtime() - e->e_ctime) <
2938 e->e_status = "5.4.7";
2939 usrerrenh(e->e_status,
2940 "554 Message can't be delivered in time; %ld < %ld",
2941 e->e_deliver_by - (curtime() - e->e_ctime),
2943 rcode = EX_UNAVAILABLE;
2949 /* first TLS then AUTH to provide a security layer */
2950 if (mci->mci_state != MCIS_CLOSED &&
2951 !DONE_STARTTLS(mci->mci_flags))
2955 bool saveQuickAbort = QuickAbort;
2956 bool saveSuprErrs = SuprErrs;
2960 usetls = bitset(MCIF_TLS, mci->mci_flags);
2962 usetls = !iscltflgset(e, D_NOTLS);
2964 host = macvalue(macid("{server_name}"), e);
2970 if (rscheck("try_tls", host, NULL, e,
2971 RSF_RMCOMM, 7, host, NOQID, NULL,
2973 || Errors > olderrors)
2977 SuprErrs = saveSuprErrs;
2978 QuickAbort = saveQuickAbort;
2983 if ((rcode = starttls(m, mci, e)) == EX_OK)
2985 /* start again without STARTTLS */
2986 mci->mci_flags |= MCIF_TLSACT;
2993 ** TLS negotiation failed, what to do?
2994 ** fall back to unencrypted connection
2995 ** or abort? How to decide?
2996 ** set a macro and call a ruleset.
2999 mci->mci_flags &= ~MCIF_TLS;
3014 case EX_UNAVAILABLE:
3018 /* everything else is a failure */
3021 rcode = EX_TEMPFAIL;
3023 macdefine(&e->e_macro, A_PERM,
3024 macid("{verify}"), s);
3028 macdefine(&e->e_macro, A_PERM,
3029 macid("{verify}"), "NONE");
3035 ** rcode == EX_SOFTWARE is special:
3036 ** the TLS negotiation failed
3037 ** we have to drop the connection no matter what
3038 ** However, we call tls_server to give it the chance
3039 ** to log the problem and return an appropriate
3043 if (rscheck("tls_server",
3044 macvalue(macid("{verify}"), e),
3045 NULL, e, RSF_RMCOMM|RSF_COUNT, 5,
3046 host, NOQID, NULL, NULL) != EX_OK ||
3047 Errors > olderrors ||
3048 rcode == EX_SOFTWARE)
3050 char enhsc[ENHSCLEN];
3051 extern char MsgBuf[];
3053 if (ISSMTPCODE(MsgBuf) &&
3054 extenhsc(MsgBuf + 4, ' ', enhsc) > 0)
3056 p = sm_rpool_strdup_x(e->e_rpool,
3061 p = "403 4.7.0 server not authenticated.";
3062 (void) sm_strlcpy(enhsc, "4.7.0",
3065 SuprErrs = saveSuprErrs;
3066 QuickAbort = saveQuickAbort;
3068 if (rcode == EX_SOFTWARE)
3070 /* drop the connection */
3071 mci->mci_state = MCIS_QUITING;
3072 if (mci->mci_in != NULL)
3074 (void) sm_io_close(mci->mci_in,
3078 mci->mci_flags &= ~MCIF_TLSACT;
3079 (void) endmailer(mci, e, pv);
3083 /* abort transfer */
3084 smtpquit(m, mci, e);
3087 /* avoid bogus error msg */
3090 /* temp or permanent failure? */
3091 rcode = (*p == '4') ? EX_TEMPFAIL
3093 mci_setstat(mci, rcode, enhsc, p);
3096 ** hack to get the error message into
3097 ** the envelope (done in giveresponse())
3100 (void) sm_strlcpy(SmtpError, p,
3103 else if (mci->mci_state == MCIS_CLOSED)
3105 /* connection close caused by 421 */
3107 rcode = EX_TEMPFAIL;
3108 mci_setstat(mci, rcode, NULL, "421");
3113 QuickAbort = saveQuickAbort;
3114 SuprErrs = saveSuprErrs;
3115 if (DONE_STARTTLS(mci->mci_flags) &&
3116 mci->mci_state != MCIS_CLOSED)
3118 SET_HELO(mci->mci_flags);
3119 mci_clr_extensions(mci);
3123 # endif /* STARTTLS */
3125 /* if other server supports authentication let's authenticate */
3126 if (mci->mci_state != MCIS_CLOSED &&
3127 mci->mci_saslcap != NULL &&
3128 !DONE_AUTH(mci->mci_flags) && !iscltflgset(e, D_NOAUTH))
3130 /* Should we require some minimum authentication? */
3131 if ((ret = smtpauth(m, mci, e)) == EX_OK)
3134 sasl_ssf_t *ssf = NULL;
3136 /* Get security strength (features) */
3137 result = sasl_getprop(mci->mci_conn, SASL_SSF,
3139 (const void **) &ssf);
3140 # else /* SASL >= 20000 */
3142 # endif /* SASL >= 20000 */
3146 sm_syslog(LOG_INFO, NOQID,
3147 "AUTH=client, relay=%.100s, mech=%.16s, bits=%d",
3149 macvalue(macid("{auth_type}"), e),
3150 result == SASL_OK ? *ssf : 0);
3153 ** Only switch to encrypted connection
3154 ** if a security layer has been negotiated
3157 if (result == SASL_OK && *ssf > 0)
3162 ** Convert I/O layer to use SASL.
3163 ** If the call fails, the connection
3167 tmo = DATA_PROGRESS_TIMEOUT * 1000;
3168 if (sfdcsasl(&mci->mci_in,
3170 mci->mci_conn, tmo) == 0)
3172 mci_clr_extensions(mci);
3173 mci->mci_flags |= MCIF_AUTHACT|
3177 syserr("AUTH TLS switch failed in client");
3180 mci->mci_flags |= MCIF_AUTHACT;
3183 else if (ret == EX_TEMPFAIL)
3186 sm_syslog(LOG_ERR, NOQID,
3187 "AUTH=client, relay=%.100s, temporary failure, connection abort",
3189 smtpquit(m, mci, e);
3191 /* avoid bogus error msg */
3193 rcode = EX_TEMPFAIL;
3194 mci_setstat(mci, rcode, "4.3.0", p);
3197 ** hack to get the error message into
3198 ** the envelope (done in giveresponse())
3201 (void) sm_strlcpy(SmtpError,
3202 "Temporary AUTH failure",
3211 /* clear out per-message flags from connection structure */
3212 mci->mci_flags &= ~(MCIF_CVT7TO8|MCIF_CVT8TO7);
3214 if (bitset(EF_HAS8BIT, e->e_flags) &&
3215 !bitset(EF_DONT_MIME, e->e_flags) &&
3216 bitnset(M_7BITS, m->m_flags))
3217 mci->mci_flags |= MCIF_CVT8TO7;
3220 if (bitnset(M_MAKE8BIT, m->m_flags) &&
3221 !bitset(MCIF_7BIT, mci->mci_flags) &&
3222 (p = hvalue("Content-Transfer-Encoding", e->e_header)) != NULL &&
3223 (sm_strcasecmp(p, "quoted-printable") == 0 ||
3224 sm_strcasecmp(p, "base64") == 0) &&
3225 (p = hvalue("Content-Type", e->e_header)) != NULL)
3227 /* may want to convert 7 -> 8 */
3228 /* XXX should really parse it here -- and use a class XXX */
3229 if (sm_strncasecmp(p, "text/plain", 10) == 0 &&
3230 (p[10] == '\0' || p[10] == ' ' || p[10] == ';'))
3231 mci->mci_flags |= MCIF_CVT7TO8;
3233 #endif /* MIME7TO8 */
3237 sm_dprintf("openmailer: ");
3238 mci_dump(sm_debug_file(), mci, false);
3241 #if _FFR_CLIENT_SIZE
3243 ** See if we know the maximum size and
3244 ** abort if the message is too big.
3246 ** NOTE: _FFR_CLIENT_SIZE is untested.
3249 if (bitset(MCIF_SIZE, mci->mci_flags) &&
3250 mci->mci_maxsize > 0 &&
3251 e->e_msgsize > mci->mci_maxsize)
3253 e->e_flags |= EF_NO_BODY_RETN;
3254 if (bitnset(M_LOCALMAILER, m->m_flags))
3255 e->e_status = "5.2.3";
3257 e->e_status = "5.3.4";
3259 usrerrenh(e->e_status,
3260 "552 Message is too large; %ld bytes max",
3264 /* Need an e_message for error */
3265 (void) sm_snprintf(SmtpError, sizeof(SmtpError),
3266 "Message is too large; %ld bytes max",
3270 #endif /* _FFR_CLIENT_SIZE */
3272 if (mci->mci_state != MCIS_OPEN)
3274 /* couldn't open the mailer */
3275 rcode = mci->mci_exitstat;
3276 errno = mci->mci_errno;
3277 SM_SET_H_ERRNO(mci->mci_herrno);
3280 /* shouldn't happen */
3281 syserr("554 5.3.5 deliver: mci=%lx rcode=%d errno=%d state=%d sig=%s",
3282 (unsigned long) mci, rcode, errno,
3283 mci->mci_state, firstsig);
3284 mci_dump_all(smioout, true);
3285 rcode = EX_SOFTWARE;
3287 else if (nummxhosts > hostnum)
3289 /* try next MX site */
3298 ** Format and send message.
3303 ok = putfromline(mci, e);
3305 ok = (*e->e_puthdr)(mci, e->e_header, e, M87F_OUTER);
3307 ok = (*e->e_putbody)(mci, e, NULL);
3308 if (ok && bitset(MCIF_INLONGLINE, mci->mci_flags))
3309 ok = putline("", mci);
3312 ** Ignore an I/O error that was caused by EPIPE.
3313 ** Some broken mailers don't read the entire body
3314 ** but just exit() thus causing an I/O error.
3317 if (!ok && (sm_io_error(mci->mci_out) && errno == EPIPE))
3320 /* (always) get the exit status */
3321 rcode = endmailer(mci, e, pv);
3323 rcode = EX_TEMPFAIL;
3324 if (rcode == EX_TEMPFAIL && SmtpError[0] == '\0')
3327 ** Need an e_message for mailq display.
3328 ** We set SmtpError as
3331 (void) sm_snprintf(SmtpError, sizeof(SmtpError),
3332 "%s mailer (%s) exited with EX_TEMPFAIL",
3333 m->m_name, m->m_mailer);
3339 ** Send the MAIL FROM: protocol
3342 /* XXX this isn't pipelined... */
3343 rcode = smtpmailfrom(m, mci, e);
3348 ADDRESS *volatile pchain;
3349 # endif /* PIPELINING */
3351 /* send the recipient list */
3353 mci->mci_retryrcpt = false;
3354 mci->mci_tolist = tobuf;
3357 mci->mci_nextaddr = NULL;
3358 # endif /* PIPELINING */
3360 for (to = tochain; to != NULL; to = to->q_tchain)
3362 if (!QS_IS_UNMARKED(to->q_state))
3365 /* mark recipient state as "ok so far" */
3366 to->q_state = QS_OK;
3367 e->e_to = to->q_paddr;
3369 i = rscheck("tls_rcpt", to->q_user, NULL, e,
3370 RSF_RMCOMM|RSF_COUNT, 3,
3371 mci->mci_host, e->e_id, NULL, NULL);
3374 markfailure(e, to, mci, i, false);
3375 giveresponse(i, to->q_status, m, mci,
3376 ctladdr, xstart, e, to);
3377 if (i == EX_TEMPFAIL)
3379 mci->mci_retryrcpt = true;
3380 to->q_state = QS_RETRY;
3384 # endif /* STARTTLS */
3386 i = smtprcpt(to, m, mci, e, ctladdr, xstart);
3389 bitset(MCIF_PIPELINED, mci->mci_flags))
3392 ** Add new element to list of
3393 ** recipients for pipelining.
3396 to->q_pchain = NULL;
3397 if (mci->mci_nextaddr == NULL)
3398 mci->mci_nextaddr = to;
3403 pchain->q_pchain = to;
3404 pchain = pchain->q_pchain;
3407 # endif /* PIPELINING */
3410 markfailure(e, to, mci, i, false);
3411 giveresponse(i, to->q_status, m, mci,
3412 ctladdr, xstart, e, to);
3413 if (i == EX_TEMPFAIL)
3414 to->q_state = QS_RETRY;
3418 /* No recipients in list and no missing responses? */
3419 if (tobuf[0] == '\0'
3421 && bitset(MCIF_PIPELINED, mci->mci_flags)
3422 && mci->mci_nextaddr == NULL
3423 # endif /* PIPELINING */
3428 if (bitset(MCIF_CACHED, mci->mci_flags))
3429 smtprset(m, mci, e);
3433 e->e_to = tobuf + 1;
3434 rcode = smtpdata(m, mci, e, ctladdr, xstart);
3437 if (rcode == EX_TEMPFAIL && nummxhosts > hostnum)
3439 /* try next MX site */
3444 if (ConfigLevel < 2)
3445 _res.options |= RES_DEFNAMES | RES_DNSRCH; /* XXX */
3446 #endif /* NAMED_BIND */
3449 checkfds("after delivery");
3452 ** Do final status disposal.
3453 ** We check for something in tobuf for the SMTP case.
3454 ** If we got a temporary failure, arrange to queue the
3459 if (bitnset(M_LMTP, m->m_flags))
3467 anyok = rcode == EX_OK;
3469 for (to = tochain; to != NULL; to = to->q_tchain)
3471 /* see if address already marked */
3472 if (!QS_IS_OK(to->q_state))
3475 /* if running LMTP, get the status for each address */
3476 if (bitnset(M_LMTP, m->m_flags))
3478 if (lmtp_rcode == EX_OK)
3479 rcode = smtpgetstat(m, mci, e);
3482 strsize += sm_strlcat2(tobuf + strsize, ",",
3484 tobufsize - strsize);
3485 SM_ASSERT(strsize < tobufsize);
3490 e->e_to = to->q_paddr;
3491 markfailure(e, to, mci, rcode, true);
3492 giveresponse(rcode, to->q_status, m, mci,
3493 ctladdr, xstart, e, to);
3494 e->e_to = tobuf + 1;
3500 /* mark bad addresses */
3503 if (goodmxfound && rcode == EX_NOHOST)
3504 rcode = EX_TEMPFAIL;
3505 markfailure(e, to, mci, rcode, true);
3510 /* successful delivery */
3511 to->q_state = QS_SENT;
3512 to->q_statdate = curtime();
3516 ** Checkpoint the send list every few addresses
3519 if (CheckpointInterval > 0 && e->e_nsent >= CheckpointInterval)
3521 queueup(e, false, false);
3525 if (bitnset(M_LOCALMAILER, m->m_flags) &&
3526 bitset(QPINGONSUCCESS, to->q_flags))
3528 to->q_flags |= QDELIVERED;
3529 to->q_status = "2.1.5";
3530 (void) sm_io_fprintf(e->e_xfp, SM_TIME_DEFAULT,
3531 "%s... Successfully delivered\n",
3534 else if (bitset(QPINGONSUCCESS, to->q_flags) &&
3535 bitset(QPRIMARY, to->q_flags) &&
3536 !bitset(MCIF_DSN, mci->mci_flags))
3538 to->q_flags |= QRELAYED;
3539 (void) sm_io_fprintf(e->e_xfp, SM_TIME_DEFAULT,
3540 "%s... relayed; expect no further notifications\n",
3543 else if (IS_DLVR_NOTIFY(e) &&
3544 !bitset(MCIF_DLVR_BY, mci->mci_flags) &&
3545 bitset(QPRIMARY, to->q_flags) &&
3546 (!bitset(QHASNOTIFY, to->q_flags) ||
3547 bitset(QPINGONSUCCESS, to->q_flags) ||
3548 bitset(QPINGONFAILURE, to->q_flags) ||
3549 bitset(QPINGONDELAY, to->q_flags)))
3551 /* RFC 2852, 4.1.4.2: no NOTIFY, or not NEVER */
3552 to->q_flags |= QBYNRELAY;
3553 (void) sm_io_fprintf(e->e_xfp, SM_TIME_DEFAULT,
3554 "%s... Deliver-by notify: relayed\n",
3557 else if (IS_DLVR_TRACE(e) &&
3558 (!bitset(QHASNOTIFY, to->q_flags) ||
3559 bitset(QPINGONSUCCESS, to->q_flags) ||
3560 bitset(QPINGONFAILURE, to->q_flags) ||
3561 bitset(QPINGONDELAY, to->q_flags)) &&
3562 bitset(QPRIMARY, to->q_flags))
3564 /* RFC 2852, 4.1.4: no NOTIFY, or not NEVER */
3565 to->q_flags |= QBYTRACE;
3566 (void) sm_io_fprintf(e->e_xfp, SM_TIME_DEFAULT,
3567 "%s... Deliver-By trace: relayed\n",
3572 if (bitnset(M_LMTP, m->m_flags))
3575 ** Global information applies to the last recipient only;
3576 ** clear it out to avoid bogus errors.
3580 e->e_statmsg = NULL;
3582 /* reset the mci state for the next transaction */
3584 (mci->mci_state == MCIS_MAIL ||
3585 mci->mci_state == MCIS_RCPT ||
3586 mci->mci_state == MCIS_DATA))
3588 mci->mci_state = MCIS_OPEN;
3589 SmtpPhase = mci->mci_phase = "idle";
3590 sm_setproctitle(true, e, "%s: %s", CurHostName,
3595 if (tobuf[0] != '\0')
3597 giveresponse(rcode, NULL, m, mci, ctladdr, xstart, e, NULL);
3600 ** This code is disabled for now because I am not
3601 ** sure that copying status from the first recipient
3602 ** to all non-status'ed recipients is a good idea.
3605 if (tochain->q_message != NULL &&
3606 !bitnset(M_LMTP, m->m_flags) && rcode != EX_OK)
3608 for (to = tochain->q_tchain; to != NULL;
3611 /* see if address already marked */
3612 if (QS_IS_QUEUEUP(to->q_state) &&
3613 to->q_message == NULL)
3614 to->q_message = sm_rpool_strdup_x(e->e_rpool,
3615 tochain->q_message);
3621 markstats(e, tochain, STATS_NORMAL);
3622 mci_store_persistent(mci);
3624 /* Some recipients were tempfailed, try them on the next host */
3625 if (mci != NULL && mci->mci_retryrcpt && nummxhosts > hostnum)
3627 /* try next MX site */
3631 /* now close the connection */
3632 if (clever && mci != NULL && mci->mci_state != MCIS_CLOSED &&
3633 !bitset(MCIF_CACHED, mci->mci_flags))
3634 smtpquit(m, mci, e);
3641 ** Restore state and return.
3646 /* make absolutely certain 0, 1, and 2 are in use */
3647 (void) sm_snprintf(wbuf, sizeof(wbuf),
3648 "%s... end of deliver(%s)",
3649 e->e_to == NULL ? "NO-TO-LIST"
3650 : shortenstring(e->e_to,
3659 ** It was originally necessary to set macro 'g' to NULL
3660 ** because it previously pointed to an auto buffer.
3661 ** We don't do this any more, so this may be unnecessary.
3664 macdefine(&e->e_macro, A_PERM, 'g', (char *) NULL);
3672 ** MARKFAILURE -- mark a failure on a specific address.
3675 ** e -- the envelope we are sending.
3676 ** q -- the address to mark.
3677 ** mci -- mailer connection information.
3678 ** rcode -- the code signifying the particular failure.
3679 ** ovr -- override an existing code?
3685 ** marks the address (and possibly the envelope) with the
3686 ** failure so that an error will be returned or
3687 ** the message will be queued, as appropriate.
3691 markfailure(e, q, mci, rcode, ovr)
3692 register ENVELOPE *e;
3693 register ADDRESS *q;
3698 int save_errno = errno;
3699 char *status = NULL;
3700 char *rstatus = NULL;
3710 q->q_state = QS_QUEUEUP;
3714 q->q_state = QS_BADADDR;
3718 /* find most specific error code possible */
3719 if (mci != NULL && mci->mci_status != NULL)
3721 status = sm_rpool_strdup_x(e->e_rpool, mci->mci_status);
3722 if (mci->mci_rstatus != NULL)
3723 rstatus = sm_rpool_strdup_x(e->e_rpool,
3728 else if (e->e_status != NULL)
3730 status = e->e_status;
3759 case EX_UNAVAILABLE:
3779 if (status != NULL && *status != '\0' && (ovr || q->q_status == NULL ||
3780 *q->q_status == '\0' || *q->q_status < *status))
3782 q->q_status = status;
3783 q->q_rstatus = rstatus;
3785 if (rcode != EX_OK && q->q_rstatus == NULL &&
3786 q->q_mailer != NULL && q->q_mailer->m_diagtype != NULL &&
3787 sm_strcasecmp(q->q_mailer->m_diagtype, "X-UNIX") == 0)
3791 (void) sm_snprintf(buf, sizeof(buf), "%d", rcode);
3792 q->q_rstatus = sm_rpool_strdup_x(e->e_rpool, buf);
3795 q->q_statdate = curtime();
3796 if (CurHostName != NULL && CurHostName[0] != '\0' &&
3797 mci != NULL && !bitset(M_LOCALMAILER, mci->mci_flags))
3798 q->q_statmta = sm_rpool_strdup_x(e->e_rpool, CurHostName);
3804 ** ENDMAILER -- Wait for mailer to terminate.
3806 ** We should never get fatal errors (e.g., segmentation
3807 ** violation), so we report those specially. For other
3808 ** errors, we choose a status message (into statmsg),
3809 ** and if it represents an error, we print it.
3812 ** mci -- the mailer connection info.
3813 ** e -- the current envelope.
3814 ** pv -- the parameter vector that invoked the mailer
3815 ** (for error messages).
3818 ** exit code of mailer.
3824 static jmp_buf EndWaitTimeout;
3827 endwaittimeout(ignore)
3831 ** NOTE: THIS CAN BE CALLED FROM A SIGNAL HANDLER. DO NOT ADD
3832 ** ANYTHING TO THIS ROUTINE UNLESS YOU KNOW WHAT YOU ARE
3837 longjmp(EndWaitTimeout, 1);
3841 endmailer(mci, e, pv)
3843 register ENVELOPE *e;
3847 int save_errno = errno;
3849 SM_EVENT *ev = NULL;
3852 mci_unlock_host(mci);
3854 /* close output to mailer */
3855 if (mci->mci_out != NULL)
3857 (void) sm_io_close(mci->mci_out, SM_TIME_DEFAULT);
3858 mci->mci_out = NULL;
3861 /* copy any remaining input to transcript */
3862 if (mci->mci_in != NULL && mci->mci_state != MCIS_ERROR &&
3865 while (sfgets(buf, sizeof(buf), mci->mci_in,
3866 TimeOuts.to_quit, "Draining Input") != NULL)
3867 (void) sm_io_fputs(e->e_xfp, SM_TIME_DEFAULT, buf);
3871 /* close SASL connection */
3872 if (bitset(MCIF_AUTHACT, mci->mci_flags))
3874 sasl_dispose(&mci->mci_conn);
3875 mci->mci_flags &= ~MCIF_AUTHACT;
3881 (void) endtlsclt(mci);
3882 #endif /* STARTTLS */
3884 /* now close the input */
3885 if (mci->mci_in != NULL)
3887 (void) sm_io_close(mci->mci_in, SM_TIME_DEFAULT);
3890 mci->mci_state = MCIS_CLOSED;
3894 /* in the IPC case there is nothing to wait for */
3895 if (mci->mci_pid == 0)
3898 /* put a timeout around the wait */
3899 if (mci->mci_mailer->m_wait > 0)
3901 if (setjmp(EndWaitTimeout) == 0)
3902 ev = sm_setevent(mci->mci_mailer->m_wait,
3906 syserr("endmailer %s: wait timeout (%ld)",
3907 mci->mci_mailer->m_name,
3908 (long) mci->mci_mailer->m_wait);
3913 /* wait for the mailer process, collect status */
3914 st = waitfor(mci->mci_pid);
3922 syserr("endmailer %s: wait", mci->mci_mailer->m_name);
3928 /* normal death -- return status */
3929 return (WEXITSTATUS(st));
3932 /* it died a horrid death */
3933 syserr("451 4.3.0 mailer %s died with signal %d%s",
3934 mci->mci_mailer->m_name, WTERMSIG(st),
3935 WCOREDUMP(st) ? " (core dumped)" :
3936 (WIFSTOPPED(st) ? " (stopped)" : ""));
3938 /* log the arguments */
3939 if (pv != NULL && e->e_xfp != NULL)
3943 (void) sm_io_fprintf(e->e_xfp, SM_TIME_DEFAULT, "Arguments:");
3944 for (av = pv; *av != NULL; av++)
3945 (void) sm_io_fprintf(e->e_xfp, SM_TIME_DEFAULT, " %s",
3947 (void) sm_io_fprintf(e->e_xfp, SM_TIME_DEFAULT, "\n");
3950 ExitStat = EX_TEMPFAIL;
3954 ** GIVERESPONSE -- Interpret an error response from a mailer
3957 ** status -- the status code from the mailer (high byte
3958 ** only; core dumps must have been taken care of
3960 ** dsn -- the DSN associated with the address, if any.
3961 ** m -- the mailer info for this mailer.
3962 ** mci -- the mailer connection info -- can be NULL if the
3963 ** response is given before the connection is made.
3964 ** ctladdr -- the controlling address for the recipient
3966 ** xstart -- the transaction start time, for computing
3967 ** transaction delays.
3968 ** e -- the current envelope.
3969 ** to -- the current recipient (NULL if none).
3975 ** Errors may be incremented.
3976 ** ExitStat may be set.
3980 giveresponse(status, dsn, m, mci, ctladdr, xstart, e, to)
3990 register const char *statmsg;
3993 bool usestat = false;
3994 char dsnbuf[ENHSCLEN];
4000 syserr("giveresponse: null envelope");
4006 ** Compute status message from code.
4009 exmsg = sm_sysexmsg(status);
4012 statmsg = "250 2.0.0 Sent";
4013 if (e->e_statmsg != NULL)
4015 (void) sm_snprintf(buf, sizeof(buf), "%s (%s)",
4017 shortenstring(e->e_statmsg, 403));
4021 else if (exmsg == NULL)
4023 (void) sm_snprintf(buf, sizeof(buf),
4024 "554 5.3.0 unknown mailer error %d",
4026 status = EX_UNAVAILABLE;
4030 else if (status == EX_TEMPFAIL)
4034 (void) sm_strlcpy(bp, exmsg + 1, SPACELEFT(buf, bp));
4037 if (h_errno == TRY_AGAIN)
4038 statmsg = sm_errstring(h_errno + E_DNSBASE);
4040 #endif /* NAMED_BIND */
4043 statmsg = sm_errstring(errnum);
4045 statmsg = SmtpError;
4047 if (statmsg != NULL && statmsg[0] != '\0')
4052 case ENETDOWN: /* Network is down */
4053 #endif /* ENETDOWN */
4055 case ENETUNREACH: /* Network is unreachable */
4056 #endif /* ENETUNREACH */
4058 case ENETRESET: /* Network dropped connection on reset */
4059 #endif /* ENETRESET */
4061 case ECONNABORTED: /* Software caused connection abort */
4062 #endif /* ECONNABORTED */
4064 case EHOSTDOWN: /* Host is down */
4065 #endif /* EHOSTDOWN */
4067 case EHOSTUNREACH: /* No route to host */
4068 #endif /* EHOSTUNREACH */
4069 if (mci != NULL && mci->mci_host != NULL)
4071 (void) sm_strlcpyn(bp,
4079 (void) sm_strlcpyn(bp, SPACELEFT(buf, bp), 2, ": ",
4086 else if (status == EX_NOHOST && h_errno != 0)
4088 statmsg = sm_errstring(h_errno + E_DNSBASE);
4089 (void) sm_snprintf(buf, sizeof(buf), "%s (%s)", exmsg + 1,
4094 #endif /* NAMED_BIND */
4098 if (*statmsg++ == ':' && errnum != 0)
4100 (void) sm_snprintf(buf, sizeof(buf), "%s: %s", statmsg,
4101 sm_errstring(errnum));
4105 else if (bitnset(M_LMTP, m->m_flags) && e->e_statmsg != NULL)
4107 (void) sm_snprintf(buf, sizeof(buf), "%s (%s)", statmsg,
4108 shortenstring(e->e_statmsg, 403));
4115 ** Print the message as appropriate
4118 if (status == EX_OK || status == EX_TEMPFAIL)
4120 extern char MsgBuf[];
4122 if ((off = isenhsc(statmsg + 4, ' ')) > 0)
4126 (void) sm_snprintf(dsnbuf, sizeof(dsnbuf),
4127 "%.*s", off, statmsg + 4);
4136 message("%s", statmsg + off);
4137 if (status == EX_TEMPFAIL && e->e_xfp != NULL)
4138 (void) sm_io_fprintf(e->e_xfp, SM_TIME_DEFAULT, "%s\n",
4143 char mbuf[ENHSCLEN + 4];
4146 if ((off = isenhsc(statmsg + 4, ' ')) > 0 &&
4147 off < sizeof(mbuf) - 4)
4151 (void) sm_snprintf(dsnbuf, sizeof(dsnbuf),
4152 "%.*s", off, statmsg + 4);
4157 /* copy only part of statmsg to mbuf */
4158 (void) sm_strlcpy(mbuf, statmsg, off);
4159 (void) sm_strlcat(mbuf, " %s", sizeof(mbuf));
4164 (void) sm_snprintf(mbuf, sizeof(mbuf), "%.3s %%s",
4168 usrerr(mbuf, &statmsg[off]);
4173 ** Log a record of the transaction. Compute the new ExitStat
4174 ** -- if we already had an error, stick with that.
4177 if (OpMode != MD_VERIFY && !bitset(EF_VRFYONLY, e->e_flags) &&
4178 LogLevel > ((status == EX_TEMPFAIL) ? 8 : (status == EX_OK) ? 7 : 6))
4179 logdelivery(m, mci, dsn, statmsg + off, ctladdr, xstart, e, to, status);
4182 sm_dprintf("giveresponse: status=%d, dsn=%s, e->e_message=%s, errnum=%d\n",
4184 dsn == NULL ? "<NULL>" : dsn,
4185 e->e_message == NULL ? "<NULL>" : e->e_message,
4188 if (status != EX_TEMPFAIL)
4190 if (status != EX_OK && (status != EX_TEMPFAIL || e->e_message == NULL))
4191 e->e_message = sm_rpool_strdup_x(e->e_rpool, statmsg + off);
4192 if (status != EX_OK && to != NULL && to->q_message == NULL)
4194 if (!usestat && e->e_message != NULL)
4195 to->q_message = sm_rpool_strdup_x(e->e_rpool,
4198 to->q_message = sm_rpool_strdup_x(e->e_rpool,
4205 ** LOGDELIVERY -- log the delivery in the system log
4207 ** Care is taken to avoid logging lines that are too long, because
4208 ** some versions of syslog have an unfortunate proclivity for core
4209 ** dumping. This is a hack, to be sure, that is at best empirical.
4212 ** m -- the mailer info. Can be NULL for initial queue.
4213 ** mci -- the mailer connection info -- can be NULL if the
4214 ** log is occurring when no connection is active.
4215 ** dsn -- the DSN attached to the status.
4216 ** status -- the message to print for the status.
4217 ** ctladdr -- the controlling address for the to list.
4218 ** xstart -- the transaction start time, used for
4219 ** computing transaction delay.
4220 ** e -- the current envelope.
4221 ** to -- the current recipient (NULL if none).
4222 ** rcode -- status code
4232 logdelivery(m, mci, dsn, status, ctladdr, xstart, e, to, rcode)
4239 register ENVELOPE *e;
4246 time_t now = curtime();
4249 #if (SYSLOG_BUFSIZE) >= 256
4250 /* ctladdr: max 106 bytes */
4252 if (ctladdr != NULL)
4254 (void) sm_strlcpyn(bp, SPACELEFT(buf, bp), 2, ", ctladdr=",
4255 shortenstring(ctladdr->q_paddr, 83));
4257 if (bitset(QGOODUID, ctladdr->q_flags))
4259 (void) sm_snprintf(bp, SPACELEFT(buf, bp), " (%d/%d)",
4260 (int) ctladdr->q_uid,
4261 (int) ctladdr->q_gid);
4266 /* delay & xdelay: max 41 bytes */
4267 (void) sm_strlcpyn(bp, SPACELEFT(buf, bp), 2, ", delay=",
4268 pintvl(now - e->e_ctime, true));
4271 if (xstart != (time_t) 0)
4273 (void) sm_strlcpyn(bp, SPACELEFT(buf, bp), 2, ", xdelay=",
4274 pintvl(now - xstart, true));
4278 /* mailer: assume about 19 bytes (max 10 byte mailer name) */
4281 (void) sm_strlcpyn(bp, SPACELEFT(buf, bp), 2, ", mailer=",
4288 p = macvalue(macid("{verify}"), e);
4289 if (p == NULL || *p == '\0')
4291 (void) sm_snprintf(bp, SPACELEFT(buf, bp), ", tls_verify=%.20s", p);
4293 # endif /* STARTTLS */
4294 # endif /* _FFR_LOG_MORE2 */
4296 /* pri: changes with each delivery attempt */
4297 (void) sm_snprintf(bp, SPACELEFT(buf, bp), ", pri=%ld",
4298 PRT_NONNEGL(e->e_msgpriority));
4301 /* relay: max 66 bytes for IPv4 addresses */
4302 if (mci != NULL && mci->mci_host != NULL)
4304 extern SOCKADDR CurHostAddr;
4306 (void) sm_strlcpyn(bp, SPACELEFT(buf, bp), 2, ", relay=",
4307 shortenstring(mci->mci_host, 40));
4310 if (CurHostAddr.sa.sa_family != 0)
4312 (void) sm_snprintf(bp, SPACELEFT(buf, bp), " [%s]",
4313 anynet_ntoa(&CurHostAddr));
4316 else if (strcmp(status, "quarantined") == 0)
4318 if (e->e_quarmsg != NULL)
4319 (void) sm_snprintf(bp, SPACELEFT(buf, bp),
4321 shortenstring(e->e_quarmsg, 40));
4323 else if (strcmp(status, "queued") != 0)
4325 p = macvalue('h', e);
4326 if (p != NULL && p[0] != '\0')
4328 (void) sm_snprintf(bp, SPACELEFT(buf, bp),
4329 ", relay=%s", shortenstring(p, 40));
4335 if (dsn != NULL && *dsn != '\0')
4337 (void) sm_strlcpyn(bp, SPACELEFT(buf, bp), 2, ", dsn=",
4338 shortenstring(dsn, ENHSCLEN));
4344 if (e->e_ntries >= 0)
4346 (void) sm_snprintf(bp, SPACELEFT(buf, bp),
4347 ", ntries=%d", e->e_ntries + 1);
4350 #endif /* _FFR_LOG_NTRIES */
4352 # define STATLEN (((SYSLOG_BUFSIZE) - 100) / 4)
4356 # endif /* (STATLEN) < 63 */
4357 # if (STATLEN) > 203
4359 # define STATLEN 203
4360 # endif /* (STATLEN) > 203 */
4365 ** per-rcpt status: to->q_rstatus
4366 ** global status: e->e_text
4368 ** We (re)use STATLEN here, is that a good choice?
4370 ** stat=Deferred: ...
4371 ** has sometimes the same text?
4373 ** Note: this doesn't show the stage at which the error happened.
4374 ** can/should we log that?
4375 ** XS_* in reply() basically encodes the state.
4378 /* only show errors */
4379 if (rcode != EX_OK && to != NULL && to->q_rstatus != NULL &&
4380 *to->q_rstatus != '\0')
4382 (void) sm_snprintf(bp, SPACELEFT(buf, bp),
4384 shortenstring(to->q_rstatus, STATLEN));
4387 else if (rcode != EX_OK && e->e_text != NULL)
4389 (void) sm_snprintf(bp, SPACELEFT(buf, bp),
4390 ", reply=%d %s%s%s",
4393 (e->e_renhsc[0] != '\0') ? " " : "",
4394 shortenstring(e->e_text, STATLEN));
4399 /* stat: max 210 bytes */
4400 if ((bp - buf) > (sizeof(buf) - ((STATLEN) + 20)))
4402 /* desperation move -- truncate data */
4403 bp = buf + sizeof(buf) - ((STATLEN) + 17);
4404 (void) sm_strlcpy(bp, "...", SPACELEFT(buf, bp));
4408 (void) sm_strlcpy(bp, ", stat=", SPACELEFT(buf, bp));
4411 (void) sm_strlcpy(bp, shortenstring(status, STATLEN),
4412 SPACELEFT(buf, bp));
4414 /* id, to: max 13 + TOBUFSIZE bytes */
4415 l = SYSLOG_BUFSIZE - 100 - strlen(buf);
4418 p = e->e_to == NULL ? "NO-TO-LIST" : e->e_to;
4419 while (strlen(p) >= l)
4423 for (q = p + l; q > p; q--)
4425 /* XXX a comma in an address will break this! */
4431 sm_syslog(LOG_INFO, e->e_id, "to=%.*s [more]%s",
4432 (int) (++q - p), p, buf);
4435 sm_syslog(LOG_INFO, e->e_id, "to=%.*s%s", l, p, buf);
4437 #else /* (SYSLOG_BUFSIZE) >= 256 */
4439 l = SYSLOG_BUFSIZE - 85;
4442 p = e->e_to == NULL ? "NO-TO-LIST" : e->e_to;
4443 while (strlen(p) >= l)
4447 for (q = p + l; q > p; q--)
4455 sm_syslog(LOG_INFO, e->e_id, "to=%.*s [more]",
4456 (int) (++q - p), p);
4459 sm_syslog(LOG_INFO, e->e_id, "to=%.*s", l, p);
4461 if (ctladdr != NULL)
4464 (void) sm_strlcpyn(bp, SPACELEFT(buf, bp), 2, "ctladdr=",
4465 shortenstring(ctladdr->q_paddr, 83));
4467 if (bitset(QGOODUID, ctladdr->q_flags))
4469 (void) sm_snprintf(bp, SPACELEFT(buf, bp), " (%d/%d)",
4470 ctladdr->q_uid, ctladdr->q_gid);
4473 sm_syslog(LOG_INFO, e->e_id, "%s", buf);
4476 (void) sm_strlcpyn(bp, SPACELEFT(buf, bp), 2, "delay=",
4477 pintvl(now - e->e_ctime, true));
4479 if (xstart != (time_t) 0)
4481 (void) sm_strlcpyn(bp, SPACELEFT(buf, bp), 2, ", xdelay=",
4482 pintvl(now - xstart, true));
4488 (void) sm_strlcpyn(bp, SPACELEFT(buf, bp), 2, ", mailer=",
4492 sm_syslog(LOG_INFO, e->e_id, "%.1000s", buf);
4496 if (mci != NULL && mci->mci_host != NULL)
4498 extern SOCKADDR CurHostAddr;
4500 (void) sm_snprintf(bp, SPACELEFT(buf, bp), "relay=%.100s",
4504 if (CurHostAddr.sa.sa_family != 0)
4505 (void) sm_snprintf(bp, SPACELEFT(buf, bp),
4507 anynet_ntoa(&CurHostAddr));
4509 else if (strcmp(status, "quarantined") == 0)
4511 if (e->e_quarmsg != NULL)
4512 (void) sm_snprintf(bp, SPACELEFT(buf, bp),
4513 ", quarantine=%.100s",
4516 else if (strcmp(status, "queued") != 0)
4518 p = macvalue('h', e);
4519 if (p != NULL && p[0] != '\0')
4520 (void) sm_snprintf(buf, sizeof(buf), "relay=%.100s", p);
4523 sm_syslog(LOG_INFO, e->e_id, "%.1000s", buf);
4525 sm_syslog(LOG_INFO, e->e_id, "stat=%s", shortenstring(status, 63));
4526 #endif /* (SYSLOG_BUFSIZE) >= 256 */
4529 ** PUTFROMLINE -- output a UNIX-style from line (or whatever)
4531 ** This can be made an arbitrary message separator by changing $l
4533 ** One of the ugliest hacks seen by human eyes is contained herein:
4534 ** UUCP wants those stupid "remote from <host>" lines. Why oh why
4535 ** does a well-meaning programmer such as myself have to deal with
4536 ** this kind of antique garbage????
4539 ** mci -- the connection information.
4540 ** e -- the envelope.
4543 ** true iff line was written successfully
4546 ** outputs some text to fp.
4554 char *template = UnixFromLine;
4558 if (bitnset(M_NHDR, mci->mci_mailer->m_flags))
4561 mci->mci_flags |= MCIF_INHEADER;
4563 if (bitnset(M_UGLYUUCP, mci->mci_mailer->m_flags))
4567 expand("\201g", buf, sizeof(buf), e);
4568 bang = strchr(buf, '!');
4572 char hname[MAXNAME];
4575 ** If we can construct a UUCP path, do so
4578 at = strrchr(buf, '@');
4581 expand("\201k", hname, sizeof(hname), e);
4586 (void) sm_snprintf(xbuf, sizeof(xbuf),
4587 "From %.800s \201d remote from %.100s\n",
4593 (void) sm_snprintf(xbuf, sizeof(xbuf),
4594 "From %.800s \201d remote from %.100s\n",
4599 expand(template, buf, sizeof(buf), e);
4600 return putxline(buf, strlen(buf), mci, PXLF_HEADER);
4604 ** PUTBODY -- put the body of a message.
4607 ** mci -- the connection information.
4608 ** e -- the envelope to put out.
4609 ** separator -- if non-NULL, a message separator that must
4610 ** not be permitted in the resulting message.
4613 ** true iff message was written successfully
4616 ** The message is written onto fp.
4619 /* values for output state variable */
4620 #define OSTATE_HEAD 0 /* at beginning of line */
4621 #define OSTATE_CR 1 /* read a carriage return */
4622 #define OSTATE_INLINE 2 /* putting rest of line */
4625 putbody(mci, e, separator)
4627 register ENVELOPE *e;
4635 char *boundaries[MAXMIMENESTING + 1];
4636 #endif /* MIME8TO7 */
4639 ** Output the body of the message
4642 if (e->e_dfp == NULL && bitset(EF_HAS_DF, e->e_flags))
4644 char *df = queuename(e, DATAFL_LETTER);
4646 e->e_dfp = sm_io_open(SmFtStdio, SM_TIME_DEFAULT, df,
4647 SM_IO_RDONLY_B, NULL);
4648 if (e->e_dfp == NULL)
4650 char *msg = "!putbody: Cannot open %s for %s from %s";
4652 if (errno == ENOENT)
4654 syserr(msg, df, e->e_to, e->e_from.q_paddr);
4658 if (e->e_dfp == NULL)
4660 if (bitset(MCIF_INHEADER, mci->mci_flags))
4662 if (!putline("", mci))
4664 mci->mci_flags &= ~MCIF_INHEADER;
4666 if (!putline("<<< No Message Collected >>>", mci))
4671 if (e->e_dfino == (ino_t) 0)
4675 if (fstat(sm_io_getinfo(e->e_dfp, SM_IO_WHAT_FD, NULL), &stbuf)
4680 e->e_dfdev = stbuf.st_dev;
4681 e->e_dfino = stbuf.st_ino;
4685 /* paranoia: the data file should always be in a rewound state */
4686 (void) bfrewind(e->e_dfp);
4688 /* simulate an I/O timeout when used as source */
4693 if (bitset(MCIF_CVT8TO7, mci->mci_flags))
4696 ** Do 8 to 7 bit MIME conversion.
4699 /* make sure it looks like a MIME message */
4700 if (hvalue("MIME-Version", e->e_header) == NULL &&
4701 !putline("MIME-Version: 1.0", mci))
4704 if (hvalue("Content-Type", e->e_header) == NULL)
4706 (void) sm_snprintf(buf, sizeof(buf),
4707 "Content-Type: text/plain; charset=%s",
4709 if (!putline(buf, mci))
4713 /* now do the hard work */
4714 boundaries[0] = NULL;
4715 mci->mci_flags |= MCIF_INHEADER;
4716 if (mime8to7(mci, e->e_header, e, boundaries, M87F_OUTER, 0) ==
4721 else if (bitset(MCIF_CVT7TO8, mci->mci_flags))
4723 if (!mime7to8(mci, e->e_header, e))
4726 # endif /* MIME7TO8 */
4727 else if (MaxMimeHeaderLength > 0 || MaxMimeFieldLength > 0)
4729 bool oldsuprerrs = SuprErrs;
4731 /* Use mime8to7 to check multipart for MIME header overflows */
4732 boundaries[0] = NULL;
4733 mci->mci_flags |= MCIF_INHEADER;
4736 ** If EF_DONT_MIME is set, we have a broken MIME message
4737 ** and don't want to generate a new bounce message whose
4738 ** body propagates the broken MIME. We can't just not call
4739 ** mime8to7() as is done above since we need the security
4740 ** checks. The best we can do is suppress the errors.
4743 if (bitset(EF_DONT_MIME, e->e_flags))
4746 if (mime8to7(mci, e->e_header, e, boundaries,
4747 M87F_OUTER|M87F_NO8TO7, 0) == SM_IO_EOF)
4750 /* restore SuprErrs */
4751 SuprErrs = oldsuprerrs;
4754 #endif /* MIME8TO7 */
4766 if (bitset(MCIF_INHEADER, mci->mci_flags))
4768 if (!putline("", mci))
4770 mci->mci_flags &= ~MCIF_INHEADER;
4773 /* determine end of buffer; allow for short mailer lines */
4774 buflim = &buf[sizeof(buf) - 1];
4775 if (mci->mci_mailer->m_linelimit > 0 &&
4776 mci->mci_mailer->m_linelimit < sizeof(buf) - 1)
4777 buflim = &buf[mci->mci_mailer->m_linelimit - 1];
4779 /* copy temp file to output with mapping */
4780 ostate = OSTATE_HEAD;
4783 while (!sm_io_error(mci->mci_out) && !dead)
4787 else if ((c = sm_io_getc(e->e_dfp, SM_TIME_DEFAULT))
4790 if (bitset(MCIF_7BIT, mci->mci_flags))
4797 mci->mci_mailer->m_flags))
4799 if (c != '\r' && c != '\n' && bp < buflim)
4805 /* check beginning of line for special cases */
4809 if (buf[0] == 'F' &&
4810 bitnset(M_ESCFROM, mci->mci_mailer->m_flags)
4811 && strncmp(buf, "From ", 5) == 0)
4815 if (buf[0] == '-' && buf[1] == '-' &&
4818 /* possible separator */
4819 int sl = strlen(separator);
4821 if (strncmp(&buf[2], separator, sl)
4825 if (buf[0] == '.' &&
4826 bitnset(M_XDOT, mci->mci_mailer->m_flags))
4831 /* now copy out saved line */
4832 if (TrafficLogFile != NULL)
4834 (void) sm_io_fprintf(TrafficLogFile,
4838 if (padc != SM_IO_EOF)
4839 (void) sm_io_putc(TrafficLogFile,
4842 for (xp = buf; xp < bp; xp++)
4843 (void) sm_io_putc(TrafficLogFile,
4845 (unsigned char) *xp);
4847 (void) sm_io_fputs(TrafficLogFile,
4849 mci->mci_mailer->m_eol);
4851 if (padc != SM_IO_EOF)
4853 if (sm_io_putc(mci->mci_out,
4854 SM_TIME_DEFAULT, padc)
4862 for (xp = buf; xp < bp; xp++)
4864 if (sm_io_putc(mci->mci_out,
4866 (unsigned char) *xp)
4877 if (sm_io_fputs(mci->mci_out,
4879 mci->mci_mailer->m_eol)
4889 SM_ASSERT(pbp < peekbuf +
4897 /* determine next state */
4899 ostate = OSTATE_HEAD;
4903 ostate = OSTATE_INLINE;
4910 if (sm_io_fputs(mci->mci_out,
4912 mci->mci_mailer->m_eol)
4916 if (TrafficLogFile != NULL)
4918 (void) sm_io_fputs(TrafficLogFile,
4920 mci->mci_mailer->m_eol);
4923 ostate = OSTATE_HEAD;
4927 /* had a naked carriage return */
4928 SM_ASSERT(pbp < peekbuf + sizeof(peekbuf));
4931 ostate = OSTATE_INLINE;
4942 mci->mci_mailer->m_flags))
4945 if (mci->mci_mailer->m_linelimit > 0 &&
4946 pos >= mci->mci_mailer->m_linelimit - 1 &&
4951 /* check next character for EOL */
4954 else if ((d = sm_io_getc(e->e_dfp,
4958 SM_ASSERT(pbp < peekbuf +
4963 if (d == '\n' || d == SM_IO_EOF)
4965 if (TrafficLogFile != NULL)
4966 (void) sm_io_putc(TrafficLogFile,
4969 if (sm_io_putc(mci->mci_out,
4981 if (sm_io_putc(mci->mci_out,
4982 SM_TIME_DEFAULT, '!')
4984 sm_io_fputs(mci->mci_out,
4986 mci->mci_mailer->m_eol)
4993 if (TrafficLogFile != NULL)
4995 (void) sm_io_fprintf(TrafficLogFile,
4998 mci->mci_mailer->m_eol);
5000 ostate = OSTATE_HEAD;
5001 SM_ASSERT(pbp < peekbuf +
5008 if (TrafficLogFile != NULL)
5009 (void) sm_io_fputs(TrafficLogFile,
5011 mci->mci_mailer->m_eol);
5012 if (sm_io_fputs(mci->mci_out,
5014 mci->mci_mailer->m_eol)
5018 ostate = OSTATE_HEAD;
5022 if (TrafficLogFile != NULL)
5023 (void) sm_io_putc(TrafficLogFile,
5026 if (sm_io_putc(mci->mci_out,
5035 ostate = OSTATE_INLINE;
5041 /* make sure we are at the beginning of a line */
5044 if (TrafficLogFile != NULL)
5046 for (xp = buf; xp < bp; xp++)
5047 (void) sm_io_putc(TrafficLogFile,
5049 (unsigned char) *xp);
5051 for (xp = buf; xp < bp; xp++)
5053 if (sm_io_putc(mci->mci_out, SM_TIME_DEFAULT,
5054 (unsigned char) *xp)
5063 if (!dead && pos > 0)
5065 if (TrafficLogFile != NULL)
5066 (void) sm_io_fputs(TrafficLogFile,
5068 mci->mci_mailer->m_eol);
5069 if (sm_io_fputs(mci->mci_out, SM_TIME_DEFAULT,
5070 mci->mci_mailer->m_eol) == SM_IO_EOF)
5075 if (sm_io_error(e->e_dfp))
5077 syserr("putbody: %s/%cf%s: read error",
5078 qid_printqueue(e->e_dfqgrp, e->e_dfqdir),
5079 DATAFL_LETTER, e->e_id);
5080 ExitStat = EX_IOERR;
5086 ** Since mailfile() uses e_dfp in a child process,
5087 ** the file offset in the stdio library for the
5088 ** parent process will not agree with the in-kernel
5089 ** file offset since the file descriptor is shared
5090 ** between the processes. Therefore, it is vital
5091 ** that the file always be rewound. This forces the
5092 ** kernel offset (lseek) and stdio library (ftell)
5097 if (e->e_dfp != NULL)
5098 (void) bfrewind(e->e_dfp);
5100 /* some mailers want extra blank line at end of message */
5101 if (!dead && bitnset(M_BLANKEND, mci->mci_mailer->m_flags) &&
5102 buf[0] != '\0' && buf[0] != '\n')
5104 if (!putline("", mci))
5109 (sm_io_flush(mci->mci_out, SM_TIME_DEFAULT) == SM_IO_EOF ||
5110 (sm_io_error(mci->mci_out) && errno != EPIPE)))
5113 syserr("putbody: write error");
5114 ExitStat = EX_IOERR;
5119 return !dead && !ioerr;
5126 ** MAILFILE -- Send a message to a file.
5128 ** If the file has the set-user-ID/set-group-ID bits set, but NO
5129 ** execute bits, sendmail will try to become the owner of that file
5130 ** rather than the real user. Obviously, this only works if
5131 ** sendmail runs as root.
5133 ** This could be done as a subordinate mailer, except that it
5134 ** is used implicitly to save messages in ~/dead.letter. We
5135 ** view this as being sufficiently important as to include it
5136 ** here. For example, if the system is dying, we shouldn't have
5137 ** to create another process plus some pipes to save the message.
5140 ** filename -- the name of the file to send to.
5141 ** mailer -- mailer definition for recipient -- if NULL,
5143 ** ctladdr -- the controlling address header -- includes
5144 ** the userid/groupid to be when sending.
5145 ** sfflags -- flags for opening.
5146 ** e -- the current envelope.
5149 ** The exit code associated with the operation.
5155 # define RETURN(st) exit(st);
5157 static jmp_buf CtxMailfileTimeout;
5160 mailfile(filename, mailer, ctladdr, sfflags, e)
5161 char *volatile filename;
5162 MAILER *volatile mailer;
5164 volatile long sfflags;
5165 register ENVELOPE *e;
5167 register SM_FILE_T *f;
5168 register pid_t pid = -1;
5172 bool suidwarn = geteuid() == 0;
5174 char *volatile realfile;
5176 char buf[MAXPATHLEN];
5177 char targetfile[MAXPATHLEN];
5181 sm_dprintf("mailfile %s\n ctladdr=", filename);
5182 printaddr(sm_debug_file(), ctladdr, false);
5186 mailer = FileMailer;
5188 if (e->e_xfp != NULL)
5189 (void) sm_io_flush(e->e_xfp, SM_TIME_DEFAULT);
5192 ** Special case /dev/null. This allows us to restrict file
5193 ** delivery to regular files only.
5196 if (sm_path_isdevnull(filename))
5199 /* check for 8-bit available */
5200 if (bitset(EF_HAS8BIT, e->e_flags) &&
5201 bitnset(M_7BITS, mailer->m_flags) &&
5202 (bitset(EF_DONT_MIME, e->e_flags) ||
5203 !(bitset(MM_MIME8BIT, MimeMode) ||
5204 (bitset(EF_IS_MIME, e->e_flags) &&
5205 bitset(MM_CVTMIME, MimeMode)))))
5207 e->e_status = "5.6.3";
5208 usrerrenh(e->e_status,
5209 "554 Cannot send 8-bit data to 7-bit destination");
5214 /* Find the actual file */
5215 if (SafeFileEnv != NULL && SafeFileEnv[0] != '\0')
5217 len = strlen(SafeFileEnv);
5219 if (strncmp(SafeFileEnv, filename, len) == 0)
5222 if (len + strlen(filename) + 1 >= sizeof(targetfile))
5224 syserr("mailfile: filename too long (%s/%s)",
5225 SafeFileEnv, filename);
5226 return EX_CANTCREAT;
5228 (void) sm_strlcpy(targetfile, SafeFileEnv, sizeof(targetfile));
5229 realfile = targetfile + len;
5230 if (*filename == '/')
5232 if (*filename != '\0')
5234 /* paranoia: trailing / should be removed in readcf */
5235 if (targetfile[len - 1] != '/')
5236 (void) sm_strlcat(targetfile,
5237 "/", sizeof(targetfile));
5238 (void) sm_strlcat(targetfile, filename,
5239 sizeof(targetfile));
5242 else if (mailer->m_rootdir != NULL)
5244 expand(mailer->m_rootdir, targetfile, sizeof(targetfile), e);
5245 len = strlen(targetfile);
5247 if (strncmp(targetfile, filename, len) == 0)
5250 if (len + strlen(filename) + 1 >= sizeof(targetfile))
5252 syserr("mailfile: filename too long (%s/%s)",
5253 targetfile, filename);
5254 return EX_CANTCREAT;
5256 realfile = targetfile + len;
5257 if (targetfile[len - 1] != '/')
5258 (void) sm_strlcat(targetfile, "/", sizeof(targetfile));
5259 if (*filename == '/')
5260 (void) sm_strlcat(targetfile, filename + 1,
5261 sizeof(targetfile));
5263 (void) sm_strlcat(targetfile, filename,
5264 sizeof(targetfile));
5268 if (sm_strlcpy(targetfile, filename, sizeof(targetfile)) >=
5271 syserr("mailfile: filename too long (%s)", filename);
5272 return EX_CANTCREAT;
5274 realfile = targetfile;
5278 ** Fork so we can change permissions here.
5279 ** Note that we MUST use fork, not vfork, because of
5280 ** the complications of calling subroutines, etc.
5285 ** Dispose of SIGCHLD signal catchers that may be laying
5286 ** around so that the waitfor() below will get it.
5289 (void) sm_signal(SIGCHLD, SIG_DFL);
5297 /* child -- actually write to file */
5301 volatile int oflags = O_WRONLY|O_APPEND;
5303 /* Reset global flags */
5304 RestartRequest = NULL;
5305 RestartWorkGroup = false;
5306 ShutdownRequest = NULL;
5308 CurrentPid = getpid();
5310 if (e->e_lockfp != NULL)
5314 fd = sm_io_getinfo(e->e_lockfp, SM_IO_WHAT_FD, NULL);
5315 /* SM_ASSERT(fd >= 0); */
5320 (void) sm_signal(SIGINT, SIG_DFL);
5321 (void) sm_signal(SIGHUP, SIG_DFL);
5322 (void) sm_signal(SIGTERM, SIG_DFL);
5323 (void) umask(OldUmask);
5327 if (setjmp(CtxMailfileTimeout) != 0)
5329 RETURN(EX_TEMPFAIL);
5332 if (TimeOuts.to_fileopen > 0)
5333 ev = sm_setevent(TimeOuts.to_fileopen, mailfiletimeout,
5338 /* check file mode to see if set-user-ID */
5339 if (stat(targetfile, &stb) < 0)
5344 /* limit the errors to those actually caused in the child */
5348 /* Allow alias expansions to use the S_IS{U,G}ID bits */
5349 if ((ctladdr != NULL && !bitset(QALIAS, ctladdr->q_flags)) ||
5350 bitset(SFF_RUNASREALUID, sfflags))
5352 /* ignore set-user-ID and set-group-ID bits */
5353 mode &= ~(S_ISGID|S_ISUID);
5355 sm_dprintf("mailfile: ignoring set-user-ID/set-group-ID bits\n");
5358 /* we have to open the data file BEFORE setuid() */
5359 if (e->e_dfp == NULL && bitset(EF_HAS_DF, e->e_flags))
5361 char *df = queuename(e, DATAFL_LETTER);
5363 e->e_dfp = sm_io_open(SmFtStdio, SM_TIME_DEFAULT, df,
5364 SM_IO_RDONLY_B, NULL);
5365 if (e->e_dfp == NULL)
5367 syserr("mailfile: Cannot open %s for %s from %s",
5368 df, e->e_to, e->e_from.q_paddr);
5372 /* select a new user to run as */
5373 if (!bitset(SFF_RUNASREALUID, sfflags))
5375 if (bitnset(M_SPECIFIC_UID, mailer->m_flags))
5377 RealUserName = NULL;
5378 if (mailer->m_uid == NO_UID)
5381 RealUid = mailer->m_uid;
5382 if (RunAsUid != 0 && RealUid != RunAsUid)
5384 /* Only root can change the uid */
5385 syserr("mailfile: insufficient privileges to change uid, RunAsUid=%ld, RealUid=%ld",
5386 (long) RunAsUid, (long) RealUid);
5387 RETURN(EX_TEMPFAIL);
5390 else if (bitset(S_ISUID, mode))
5392 RealUserName = NULL;
5393 RealUid = stb.st_uid;
5395 else if (ctladdr != NULL && ctladdr->q_uid != 0)
5397 if (ctladdr->q_ruser != NULL)
5398 RealUserName = ctladdr->q_ruser;
5400 RealUserName = ctladdr->q_user;
5401 RealUid = ctladdr->q_uid;
5403 else if (mailer != NULL && mailer->m_uid != NO_UID)
5405 RealUserName = DefUser;
5406 RealUid = mailer->m_uid;
5410 RealUserName = DefUser;
5414 /* select a new group to run as */
5415 if (bitnset(M_SPECIFIC_UID, mailer->m_flags))
5417 if (mailer->m_gid == NO_GID)
5420 RealGid = mailer->m_gid;
5421 if (RunAsUid != 0 &&
5422 (RealGid != getgid() ||
5423 RealGid != getegid()))
5425 /* Only root can change the gid */
5426 syserr("mailfile: insufficient privileges to change gid, RealGid=%ld, RunAsUid=%ld, gid=%ld, egid=%ld",
5427 (long) RealGid, (long) RunAsUid,
5428 (long) getgid(), (long) getegid());
5429 RETURN(EX_TEMPFAIL);
5432 else if (bitset(S_ISGID, mode))
5433 RealGid = stb.st_gid;
5434 else if (ctladdr != NULL &&
5435 ctladdr->q_uid == DefUid &&
5436 ctladdr->q_gid == 0)
5439 ** Special case: This means it is an
5440 ** alias and we should act as DefaultUser.
5441 ** See alias()'s comments.
5445 RealUserName = DefUser;
5447 else if (ctladdr != NULL && ctladdr->q_uid != 0)
5448 RealGid = ctladdr->q_gid;
5449 else if (mailer != NULL && mailer->m_gid != NO_GID)
5450 RealGid = mailer->m_gid;
5456 if (!bitset(SFF_ROOTOK, sfflags))
5464 /* set group id list (needs /etc/group access) */
5465 if (RealUserName != NULL && !DontInitGroups)
5467 if (initgroups(RealUserName, RealGid) == -1 && suidwarn)
5469 syserr("mailfile: initgroups(%s, %ld) failed",
5470 RealUserName, (long) RealGid);
5471 RETURN(EX_TEMPFAIL);
5478 gidset[0] = RealGid;
5479 if (setgroups(1, gidset) == -1 && suidwarn)
5481 syserr("mailfile: setgroups() failed");
5482 RETURN(EX_TEMPFAIL);
5487 ** If you have a safe environment, go into it.
5490 if (realfile != targetfile)
5497 sm_dprintf("mailfile: chroot %s\n", targetfile);
5498 if (chroot(targetfile) < 0)
5500 syserr("mailfile: Cannot chroot(%s)",
5502 RETURN(EX_CANTCREAT);
5508 sm_dprintf("mailfile: deliver to %s\n", realfile);
5512 syserr("mailfile: cannot chdir(/)");
5513 RETURN(EX_CANTCREAT);
5516 /* now reset the group and user ids */
5518 sm_mbdb_terminate();
5519 if (setgid(RealGid) < 0 && suidwarn)
5521 syserr("mailfile: setgid(%ld) failed", (long) RealGid);
5522 RETURN(EX_TEMPFAIL);
5524 vendor_set_uid(RealUid);
5525 if (setuid(RealUid) < 0 && suidwarn)
5527 syserr("mailfile: setuid(%ld) failed", (long) RealUid);
5528 RETURN(EX_TEMPFAIL);
5532 sm_dprintf("mailfile: running as r/euid=%ld/%ld, r/egid=%ld/%ld\n",
5533 (long) getuid(), (long) geteuid(),
5534 (long) getgid(), (long) getegid());
5537 /* move into some "safe" directory */
5538 if (mailer->m_execdir != NULL)
5542 for (p = mailer->m_execdir; p != NULL; p = q)
5547 expand(p, buf, sizeof(buf), e);
5551 sm_dprintf("mailfile: trydir %s\n",
5553 if (buf[0] != '\0' && chdir(buf) >= 0)
5559 ** Recheck the file after we have assumed the ID of the
5560 ** delivery user to make sure we can deliver to it as
5561 ** that user. This is necessary if sendmail is running
5562 ** as root and the file is on an NFS mount which treats
5567 if (bitnset(DBS_FILEDELIVERYTOSYMLINK, DontBlameSendmail))
5568 err = stat(realfile, &stb);
5570 err = lstat(realfile, &stb);
5571 #else /* HASLSTAT */
5572 err = stat(realfile, &stb);
5573 #endif /* HASLSTAT */
5577 stb.st_mode = ST_MODE_NOFILE;
5579 oflags |= O_CREAT|O_EXCL;
5581 else if (bitset(S_IXUSR|S_IXGRP|S_IXOTH, mode) ||
5582 (!bitnset(DBS_FILEDELIVERYTOHARDLINK,
5583 DontBlameSendmail) &&
5584 stb.st_nlink != 1) ||
5585 (realfile != targetfile && !S_ISREG(mode)))
5590 if (!bitnset(DBS_FILEDELIVERYTOSYMLINK, DontBlameSendmail))
5591 sfflags |= SFF_NOSLINK;
5592 if (!bitnset(DBS_FILEDELIVERYTOHARDLINK, DontBlameSendmail))
5593 sfflags |= SFF_NOHLINK;
5594 sfflags &= ~SFF_OPENASROOT;
5595 f = safefopen(realfile, oflags, mode, sfflags);
5598 if (transienterror(errno))
5600 usrerr("454 4.3.0 cannot open %s: %s",
5601 shortenstring(realfile, MAXSHORTSTR),
5602 sm_errstring(errno));
5603 RETURN(EX_TEMPFAIL);
5607 usrerr("554 5.3.0 cannot open %s: %s",
5608 shortenstring(realfile, MAXSHORTSTR),
5609 sm_errstring(errno));
5610 RETURN(EX_CANTCREAT);
5613 if (filechanged(realfile, sm_io_getinfo(f, SM_IO_WHAT_FD, NULL),
5616 syserr("554 5.3.0 file changed after open");
5617 RETURN(EX_CANTCREAT);
5619 if (fstat(sm_io_getinfo(f, SM_IO_WHAT_FD, NULL), &stb) < 0)
5621 syserr("554 5.3.0 cannot fstat %s",
5622 sm_errstring(errno));
5623 RETURN(EX_CANTCREAT);
5626 curoff = stb.st_size;
5631 memset(&mcibuf, '\0', sizeof(mcibuf));
5632 mcibuf.mci_mailer = mailer;
5634 if (bitnset(M_7BITS, mailer->m_flags))
5635 mcibuf.mci_flags |= MCIF_7BIT;
5637 /* clear out per-message flags from connection structure */
5638 mcibuf.mci_flags &= ~(MCIF_CVT7TO8|MCIF_CVT8TO7);
5640 if (bitset(EF_HAS8BIT, e->e_flags) &&
5641 !bitset(EF_DONT_MIME, e->e_flags) &&
5642 bitnset(M_7BITS, mailer->m_flags))
5643 mcibuf.mci_flags |= MCIF_CVT8TO7;
5646 if (bitnset(M_MAKE8BIT, mailer->m_flags) &&
5647 !bitset(MCIF_7BIT, mcibuf.mci_flags) &&
5648 (p = hvalue("Content-Transfer-Encoding", e->e_header)) != NULL &&
5649 (sm_strcasecmp(p, "quoted-printable") == 0 ||
5650 sm_strcasecmp(p, "base64") == 0) &&
5651 (p = hvalue("Content-Type", e->e_header)) != NULL)
5653 /* may want to convert 7 -> 8 */
5654 /* XXX should really parse it here -- and use a class XXX */
5655 if (sm_strncasecmp(p, "text/plain", 10) == 0 &&
5656 (p[10] == '\0' || p[10] == ' ' || p[10] == ';'))
5657 mcibuf.mci_flags |= MCIF_CVT7TO8;
5659 #endif /* MIME7TO8 */
5661 if (!putfromline(&mcibuf, e) ||
5662 !(*e->e_puthdr)(&mcibuf, e->e_header, e, M87F_OUTER) ||
5663 !(*e->e_putbody)(&mcibuf, e, NULL) ||
5664 !putline("\n", &mcibuf) ||
5665 (sm_io_flush(f, SM_TIME_DEFAULT) != 0 ||
5666 (SuperSafe != SAFE_NO &&
5667 fsync(sm_io_getinfo(f, SM_IO_WHAT_FD, NULL)) < 0) ||
5672 (void) ftruncate(sm_io_getinfo(f, SM_IO_WHAT_FD, NULL),
5674 #endif /* !NOFTRUNCATE */
5677 /* reset ISUID & ISGID bits for paranoid systems */
5679 (void) fchmod(sm_io_getinfo(f, SM_IO_WHAT_FD, NULL),
5681 #else /* HASFCHMOD */
5682 (void) chmod(filename, (MODE_T) mode);
5683 #endif /* HASFCHMOD */
5684 if (sm_io_close(f, SM_TIME_DEFAULT) < 0)
5686 (void) sm_io_flush(smioout, SM_TIME_DEFAULT);
5687 (void) setuid(RealUid);
5693 /* parent -- wait for exit status */
5699 syserr("mailfile: %s: wait", mailer->m_name);
5705 return (WEXITSTATUS(st));
5709 syserr("mailfile: %s: child died on signal %d",
5710 mailer->m_name, st);
5711 return EX_UNAVAILABLE;
5715 return EX_UNAVAILABLE; /* avoid compiler warning on IRIX */
5719 mailfiletimeout(ignore)
5723 ** NOTE: THIS CAN BE CALLED FROM A SIGNAL HANDLER. DO NOT ADD
5724 ** ANYTHING TO THIS ROUTINE UNLESS YOU KNOW WHAT YOU ARE
5729 longjmp(CtxMailfileTimeout, 1);
5732 ** HOSTSIGNATURE -- return the "signature" for a host.
5734 ** The signature describes how we are going to send this -- it
5735 ** can be just the hostname (for non-Internet hosts) or can be
5736 ** an ordered list of MX hosts.
5739 ** m -- the mailer describing this host.
5740 ** host -- the host name.
5743 ** The signature for this host.
5746 ** Can tweak the symbol table.
5749 #define MAXHOSTSIGNATURE 8192 /* max len of hostsignature */
5752 hostsignature(m, host)
5768 int oldoptions = _res.options;
5769 char *mxhosts[MAXMXHOSTS + 1];
5770 unsigned short mxprefs[MAXMXHOSTS + 1];
5771 #endif /* NAMED_BIND */
5774 sm_dprintf("hostsignature(%s)\n", host);
5777 ** If local delivery (and not remote), just return a constant.
5780 if (bitnset(M_LOCALMAILER, m->m_flags) &&
5781 strcmp(m->m_mailer, "[IPC]") != 0 &&
5782 !(m->m_argv[0] != NULL && strcmp(m->m_argv[0], "TCP") == 0))
5785 /* an empty host does not have MX records */
5790 ** Check to see if this uses IPC -- if not, it can't have MX records.
5793 if (strcmp(m->m_mailer, "[IPC]") != 0 ||
5794 CurEnv->e_sendmode == SM_DEFER)
5796 /* just an ordinary mailer or deferred mode */
5800 else if (m->m_argv[0] != NULL &&
5801 strcmp(m->m_argv[0], "FILE") == 0)
5803 /* rendezvous in the file system, no MX records */
5806 #endif /* NETUNIX */
5809 ** Look it up in the symbol table.
5813 s = stab(host, ST_HOSTSIG, ST_ENTER);
5814 if (s->s_hostsig.hs_sig != NULL)
5816 if (s->s_hostsig.hs_exp >= now)
5819 sm_dprintf("hostsignature(): stab(%s) found %s\n", host,
5820 s->s_hostsig.hs_sig);
5821 return s->s_hostsig.hs_sig;
5824 /* signature is expired: clear it */
5825 sm_free(s->s_hostsig.hs_sig);
5826 s->s_hostsig.hs_sig = NULL;
5829 /* set default TTL */
5830 s->s_hostsig.hs_exp = now + SM_DEFAULT_TTL;
5833 ** Not already there or expired -- create a signature.
5837 if (ConfigLevel < 2)
5838 _res.options &= ~(RES_DEFNAMES | RES_DNSRCH); /* XXX */
5840 for (hp = host; hp != NULL; hp = endp)
5845 endp = strchr(hp + 1, ']');
5847 endp = strpbrk(endp + 1, ":,");
5850 endp = strpbrk(hp, ":,");
5851 #else /* NETINET6 */
5852 endp = strpbrk(hp, ":,");
5853 #endif /* NETINET6 */
5860 if (bitnset(M_NOMX, m->m_flags))
5862 /* skip MX lookups */
5871 nmx = getmxrr(hp, mxhosts, mxprefs, true, &rcode, true,
5878 /* update the connection info for this host */
5880 mci = mci_get(hp, m);
5881 mci->mci_errno = save_errno;
5882 mci->mci_herrno = h_errno;
5883 mci->mci_lastuse = now;
5884 if (rcode == EX_NOHOST)
5885 mci_setstat(mci, rcode, "5.1.2",
5886 "550 Host unknown");
5888 mci_setstat(mci, rcode, NULL, NULL);
5890 /* use the original host name as signature */
5895 sm_dprintf("hostsignature(): getmxrr() returned %d, mxhosts[0]=%s\n",
5899 ** Set new TTL: we use only one!
5900 ** We could try to use the minimum instead.
5903 s->s_hostsig.hs_exp = now + SM_MIN(ttl, SM_DEFAULT_TTL);
5907 for (i = 0; i < nmx; i++)
5908 len += strlen(mxhosts[i]) + 1;
5909 if (s->s_hostsig.hs_sig != NULL)
5910 len += strlen(s->s_hostsig.hs_sig) + 1;
5911 if (len < 0 || len >= MAXHOSTSIGNATURE)
5913 sm_syslog(LOG_WARNING, NOQID, "hostsignature for host '%s' exceeds maxlen (%d): %d",
5914 host, MAXHOSTSIGNATURE, len);
5915 len = MAXHOSTSIGNATURE;
5917 p = sm_pmalloc_x(len);
5918 if (s->s_hostsig.hs_sig != NULL)
5920 (void) sm_strlcpy(p, s->s_hostsig.hs_sig, len);
5921 sm_free(s->s_hostsig.hs_sig); /* XXX */
5922 s->s_hostsig.hs_sig = p;
5929 s->s_hostsig.hs_sig = p;
5930 for (i = 0; i < nmx; i++)
5932 hl = strlen(mxhosts[i]);
5933 if (len - 1 < hl || len <= 1)
5935 /* force to drop out of outer loop */
5941 if (mxprefs[i] == mxprefs[i - 1])
5947 (void) sm_strlcpy(p, mxhosts[i], len);
5953 ** break out of loop if len exceeded MAXHOSTSIGNATURE
5954 ** because we won't have more space for further hosts
5955 ** anyway (separated by : in the .cf file).
5964 makelower(s->s_hostsig.hs_sig);
5965 if (ConfigLevel < 2)
5966 _res.options = oldoptions;
5967 #else /* NAMED_BIND */
5968 /* not using BIND -- the signature is just the host name */
5970 ** 'host' points to storage that will be freed after we are
5971 ** done processing the current envelope, so we copy it.
5973 s->s_hostsig.hs_sig = sm_pstrdup_x(host);
5974 #endif /* NAMED_BIND */
5976 sm_dprintf("hostsignature(%s) = %s\n", host, s->s_hostsig.hs_sig);
5977 return s->s_hostsig.hs_sig;
5980 ** PARSE_HOSTSIGNATURE -- parse the "signature" and return MX host array.
5982 ** The signature describes how we are going to send this -- it
5983 ** can be just the hostname (for non-Internet hosts) or can be
5984 ** an ordered list of MX hosts which must be randomized for equal
5985 ** MX preference values.
5988 ** sig -- the host signature.
5989 ** mxhosts -- array to populate.
5990 ** mailer -- mailer.
5993 ** The number of hosts inserted into mxhosts array.
5996 ** Randomizes equal MX preference hosts in mxhosts.
6000 parse_hostsignature(sig, mxhosts, mailer)
6005 unsigned short curpref = 0;
6006 int nmx = 0, i, j; /* NOTE: i, j, and nmx must have same type */
6008 unsigned short prefer[MAXMXHOSTS];
6009 long rndm[MAXMXHOSTS];
6011 for (hp = sig; hp != NULL; hp = endp)
6018 endp = strchr(hp + 1, ']');
6020 endp = strpbrk(endp + 1, ":,");
6023 endp = strpbrk(hp, ":,");
6024 #else /* NETINET6 */
6025 endp = strpbrk(hp, ":,");
6026 #endif /* NETINET6 */
6034 prefer[nmx] = curpref;
6035 if (mci_match(hp, mailer))
6038 rndm[nmx] = get_random();
6043 ** Since we don't have the original MX prefs,
6044 ** make our own. If the separator is a ':', that
6045 ** means the preference for the next host will be
6046 ** higher than this one, so simply increment curpref.
6054 if (++nmx >= MAXMXHOSTS)
6058 /* sort the records using the random factor for equal preferences */
6059 for (i = 0; i < nmx; i++)
6061 for (j = i + 1; j < nmx; j++)
6064 ** List is already sorted by MX preference, only
6065 ** need to look for equal preference MX records
6068 if (prefer[i] < prefer[j])
6071 if (prefer[i] > prefer[j] ||
6072 (prefer[i] == prefer[j] && rndm[i] > rndm[j]))
6074 register unsigned short tempp;
6075 register long tempr;
6076 register char *temp1;
6079 prefer[i] = prefer[j];
6082 mxhosts[i] = mxhosts[j];
6094 static SSL_CTX *clt_ctx = NULL;
6095 static bool tls_ok_clt = true;
6098 ** SETCLTTLS -- client side TLS: allow/disallow.
6101 ** tls_ok -- should tls be done?
6107 ** sets tls_ok_clt (static variable in this module)
6114 tls_ok_clt = tls_ok;
6118 ** INITCLTTLS -- initialize client side TLS
6121 ** tls_ok -- should tls initialization be done?
6127 ** sets tls_ok_clt (static variable in this module)
6136 tls_ok_clt = tls_ok;
6139 if (clt_ctx != NULL)
6140 return true; /* already done */
6141 tls_ok_clt = inittls(&clt_ctx, TLS_I_CLT, Clt_SSL_Options, false,
6142 CltCertFile, CltKeyFile,
6143 CACertPath, CACertFile, DHParams);
6148 ** STARTTLS -- try to start secure connection (client side)
6152 ** mci -- the mailer connection info.
6153 ** e -- the envelope.
6157 ** (maybe this should be some other code than EX_
6158 ** that denotes which stage failed.)
6170 SSL *clt_ssl = NULL;
6173 if (clt_ctx == NULL && !initclttls(true))
6176 # if USE_OPENSSL_ENGINE
6177 if (!SSLEngineInitialized && !SSL_set_engine(NULL))
6179 sm_syslog(LOG_ERR, NOQID,
6180 "STARTTLS=client, SSL_set_engine=failed");
6183 SSLEngineInitialized = true;
6184 # endif /* USE_OPENSSL_ENGINE */
6186 smtpmessage("STARTTLS", m, mci);
6189 smtpresult = reply(m, mci, e, TimeOuts.to_starttls, NULL, NULL,
6192 /* check return code from server */
6193 if (REPLYTYPE(smtpresult) == 4)
6195 if (smtpresult == 501)
6197 if (smtpresult == -1)
6200 /* not an expected reply but we have to deal with it */
6201 if (REPLYTYPE(smtpresult) == 5)
6202 return EX_UNAVAILABLE;
6203 if (smtpresult != 220)
6207 sm_syslog(LOG_INFO, NOQID, "STARTTLS=client, start=ok");
6209 /* start connection */
6210 if ((clt_ssl = SSL_new(clt_ctx)) == NULL)
6214 sm_syslog(LOG_ERR, NOQID,
6215 "STARTTLS=client, error: SSL_new failed");
6217 tlslogerr(LOG_WARNING, "client");
6221 /* SSL_clear(clt_ssl); ? */
6223 if (get_tls_se_options(e, clt_ssl, false) != 0)
6225 sm_syslog(LOG_ERR, NOQID,
6226 "STARTTLS=client, get_tls_se_options=fail");
6230 rfd = sm_io_getinfo(mci->mci_in, SM_IO_WHAT_FD, NULL);
6231 wfd = sm_io_getinfo(mci->mci_out, SM_IO_WHAT_FD, NULL);
6233 if (rfd < 0 || wfd < 0 ||
6234 (result = SSL_set_rfd(clt_ssl, rfd)) != 1 ||
6235 (result = SSL_set_wfd(clt_ssl, wfd)) != 1)
6239 sm_syslog(LOG_ERR, NOQID,
6240 "STARTTLS=client, error: SSL_set_xfd failed=%d",
6243 tlslogerr(LOG_WARNING, "client");
6247 SSL_set_connect_state(clt_ssl);
6248 tlsstart = curtime();
6251 if ((result = SSL_connect(clt_ssl)) <= 0)
6254 int save_errno = errno;
6256 ssl_err = SSL_get_error(clt_ssl, result);
6257 i = tls_retry(clt_ssl, rfd, wfd, tlsstart,
6258 TimeOuts.to_starttls, ssl_err, "client");
6267 l = ERR_peek_error();
6268 sr = ERR_reason_error_string(l);
6269 sm_syslog(LOG_WARNING, NOQID,
6270 "STARTTLS=client, error: connect failed=%d, reason=%s, SSL_error=%d, errno=%d, retry=%d",
6271 result, sr == NULL ? "unknown" : sr, ssl_err,
6274 tlslogerr(LOG_WARNING, "client");
6281 mci->mci_ssl = clt_ssl;
6282 result = tls_get_info(mci->mci_ssl, false, mci->mci_host,
6283 &mci->mci_macro, true);
6285 /* switch to use TLS... */
6286 if (sfdctls(&mci->mci_in, &mci->mci_out, mci->mci_ssl) == 0)
6295 ** ENDTLSCLT -- shutdown secure connection (client side)
6298 ** mci -- the mailer connection info.
6310 if (!bitset(MCIF_TLSACT, mci->mci_flags))
6312 r = endtls(mci->mci_ssl, "client");
6313 mci->mci_flags &= ~MCIF_TLSACT;
6316 # endif /* STARTTLS */
6317 # if STARTTLS || SASL
6319 ** ISCLTFLGSET -- check whether client flag is set.
6323 ** flag -- flag to check in {client_flags}
6326 ** true iff flag is set.
6330 iscltflgset(e, flag)
6336 p = macvalue(macid("{client_flags}"), e);
6339 for (; *p != '\0'; p++)
6341 /* look for just this one flag */
6342 if (*p == (char) flag)
6347 # endif /* STARTTLS || SASL */