2 * Copyright (c) 1998-2010, 2012 Sendmail, 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.1028 2013/01/02 18:57:42 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",
1227 ** DELIVER -- Deliver a message to a list of addresses.
1229 ** This routine delivers to everyone on the same host as the
1230 ** user on the head of the list. It is clever about mailers
1231 ** that don't handle multiple users. It is NOT guaranteed
1232 ** that it will deliver to all these addresses however -- so
1233 ** deliver should be called once for each address on the
1235 ** Deliver tries to be as opportunistic as possible about piggybacking
1236 ** messages. Some definitions to make understanding easier follow below.
1237 ** Piggybacking occurs when an existing connection to a mail host can
1238 ** be used to send the same message to more than one recipient at the
1239 ** same time. So "no piggybacking" means one message for one recipient
1240 ** per connection. "Intentional piggybacking" happens when the
1241 ** recipients' host address (not the mail host address) is used to
1242 ** attempt piggybacking. Recipients with the same host address
1243 ** have the same mail host. "Coincidental piggybacking" relies on
1244 ** piggybacking based on all the mail host addresses in the MX-RR. This
1245 ** is "coincidental" in the fact it could not be predicted until the
1246 ** MX Resource Records for the hosts were obtained and examined. For
1247 ** example (preference order and equivalence is important, not values):
1248 ** domain1 IN MX 10 mxhost-A
1249 ** IN MX 20 mxhost-B
1250 ** domain2 IN MX 4 mxhost-A
1252 ** Domain1 and domain2 can piggyback the same message to mxhost-A or
1253 ** mxhost-B (if mxhost-A cannot be reached).
1254 ** "Coattail piggybacking" relaxes the strictness of "coincidental
1255 ** piggybacking" in the hope that most significant (lowest value)
1256 ** MX preference host(s) can create more piggybacking. For example
1257 ** (again, preference order and equivalence is important, not values):
1258 ** domain3 IN MX 100 mxhost-C
1259 ** IN MX 100 mxhost-D
1260 ** IN MX 200 mxhost-E
1261 ** domain4 IN MX 50 mxhost-C
1262 ** IN MX 50 mxhost-D
1263 ** IN MX 80 mxhost-F
1264 ** A message for domain3 and domain4 can piggyback to mxhost-C if mxhost-C
1265 ** is available. Same with mxhost-D because in both RR's the preference
1266 ** value is the same as mxhost-C, respectively.
1267 ** So deliver attempts coattail piggybacking when possible. If the
1268 ** first MX preference level hosts cannot be used then the piggybacking
1269 ** reverts to coincidental piggybacking. Using the above example you
1270 ** cannot deliver to mxhost-F for domain3 regardless of preference value.
1271 ** ("Coattail" from "riding on the coattails of your predecessor" meaning
1272 ** gaining benefit from a predecessor effort with no or little addition
1273 ** effort. The predecessor here being the preceding MX RR).
1276 ** e -- the envelope to deliver.
1277 ** firstto -- head of the address list to deliver to.
1280 ** zero -- successfully delivered.
1281 ** else -- some failure, see ExitStat for more info.
1284 ** The standard input is passed off to someone.
1289 register ENVELOPE *e;
1292 char *host; /* host being sent to */
1293 char *user; /* user being sent to */
1295 register char **mvp;
1297 register MAILER *m; /* mailer for this recipient */
1298 ADDRESS *volatile ctladdr;
1299 #if HASSETUSERCONTEXT
1300 ADDRESS *volatile contextaddr = NULL;
1301 #endif /* HASSETUSERCONTEXT */
1302 register MCI *volatile mci;
1303 register ADDRESS *SM_NONVOLATILE to = firstto;
1304 volatile bool clever = false; /* running user smtp to this mailer */
1305 ADDRESS *volatile tochain = NULL; /* users chain in this mailer call */
1306 int rcode; /* response code */
1307 SM_NONVOLATILE int lmtp_rcode = EX_OK;
1308 SM_NONVOLATILE int nummxhosts = 0; /* number of MX hosts available */
1309 SM_NONVOLATILE int hostnum = 0; /* current MX host index */
1310 char *firstsig; /* signature of firstto */
1311 volatile pid_t pid = -1;
1312 char *volatile curhost;
1313 SM_NONVOLATILE unsigned short port = 0;
1314 SM_NONVOLATILE time_t enough = 0;
1316 char *SM_NONVOLATILE mux_path = NULL; /* path to UNIX domain socket */
1317 #endif /* NETUNIX */
1320 bool anyok; /* at least one address was OK */
1321 SM_NONVOLATILE bool goodmxfound = false; /* at least one MX was OK */
1327 static int tobufsize = 0;
1328 static char *tobuf = NULL;
1329 char *rpath; /* translated return path */
1332 char *mxhosts[MAXMXHOSTS + 1];
1333 char *pv[MAXPV + 1];
1334 char buf[MAXNAME + 1];
1335 char cbuf[MAXPATHLEN];
1338 SM_REQUIRE(firstto != NULL); /* same as to */
1339 if (!QS_IS_OK(to->q_state))
1342 suidwarn = geteuid() == 0;
1344 SM_REQUIRE(e != NULL);
1347 CurEnv = e; /* just in case */
1348 e->e_statmsg = NULL;
1349 SmtpError[0] = '\0';
1353 sm_dprintf("\n--deliver, id=%s, mailer=%s, host=`%s', first user=`%s'\n",
1354 e->e_id, m->m_name, host, to->q_user);
1356 printopenfds(false);
1359 ** Clear {client_*} macros if this is a bounce message to
1360 ** prevent rejection by check_compat ruleset.
1363 if (bitset(EF_RESPONSE, e->e_flags))
1365 macdefine(&e->e_macro, A_PERM, macid("{client_name}"), "");
1366 macdefine(&e->e_macro, A_PERM, macid("{client_ptr}"), "");
1367 macdefine(&e->e_macro, A_PERM, macid("{client_addr}"), "");
1368 macdefine(&e->e_macro, A_PERM, macid("{client_port}"), "");
1369 macdefine(&e->e_macro, A_PERM, macid("{client_resolve}"), "");
1374 ADDRESS *skip_back = NULL;
1377 ** Do initial argv setup.
1378 ** Insert the mailer name. Notice that $x expansion is
1379 ** NOT done on the mailer name. Then, if the mailer has
1380 ** a picky -f flag, we insert it as appropriate. This
1381 ** code does not check for 'pv' overflow; this places a
1382 ** manifest lower limit of 4 for MAXPV.
1383 ** The from address rewrite is expected to make
1384 ** the address relative to the other end.
1387 /* rewrite from address, using rewriting rules */
1389 SM_ASSERT(e->e_from.q_mailer != NULL);
1390 if (bitnset(M_UDBENVELOPE, e->e_from.q_mailer->m_flags))
1393 p = e->e_from.q_paddr;
1394 rpath = remotename(p, m, RF_SENDERADDR|RF_CANONICAL, &rcode, e);
1395 if (strlen(rpath) > MAXNAME)
1397 rpath = shortenstring(rpath, MAXSHORTSTR);
1399 /* avoid bogus errno */
1401 syserr("remotename: huge return path %s", rpath);
1403 rpath = sm_rpool_strdup_x(e->e_rpool, rpath);
1404 macdefine(&e->e_macro, A_PERM, 'g', rpath);
1405 macdefine(&e->e_macro, A_PERM, 'h', host);
1408 *pvp++ = m->m_argv[0];
1410 /* ignore long term host status information if mailer flag W is set */
1411 if (bitnset(M_NOHOSTSTAT, m->m_flags))
1412 IgnoreHostStatus = true;
1414 /* insert -f or -r flag as appropriate */
1416 (bitnset(M_FOPT, m->m_flags) ||
1417 bitnset(M_ROPT, m->m_flags)))
1419 if (bitnset(M_FOPT, m->m_flags))
1427 ** Append the other fixed parts of the argv. These run
1428 ** up to the first entry containing "$u". There can only
1429 ** be one of these, and there are only a few more slots
1430 ** in the pv after it.
1433 for (mvp = m->m_argv; (p = *++mvp) != NULL; )
1435 /* can't use strchr here because of sign extension problems */
1438 if ((*p++ & 0377) == MACROEXPAND)
1448 /* this entry is safe -- go ahead and process it */
1449 expand(*mvp, buf, sizeof(buf), e);
1450 *pvp++ = sm_rpool_strdup_x(e->e_rpool, buf);
1451 if (pvp >= &pv[MAXPV - 3])
1453 syserr("554 5.3.5 Too many parameters to %s before $u",
1461 ** If we have no substitution for the user name in the argument
1462 ** list, we know that we must supply the names otherwise -- and
1463 ** SMTP is the answer!!
1468 /* running LMTP or SMTP */
1472 else if (bitnset(M_LMTP, m->m_flags))
1474 /* not running LMTP */
1475 sm_syslog(LOG_ERR, NULL,
1476 "Warning: mailer %s: LMTP flag (F=z) turned off",
1478 clrbitn(M_LMTP, m->m_flags);
1482 ** At this point *mvp points to the argument with $u. We
1483 ** run through our address list and append all the addresses
1484 ** we can. If we run out of space, do not fret! We can
1485 ** always send another copy later.
1492 if (firstto->q_signature == NULL)
1493 firstto->q_signature = hostsignature(firstto->q_mailer,
1495 firstsig = firstto->q_signature;
1497 for (; to != NULL; to = to->q_next)
1499 /* avoid sending multiple recipients to dumb mailers */
1500 if (tochain != NULL && !bitnset(M_MUSER, m->m_flags))
1503 /* if already sent or not for this host, don't send */
1504 if (!QS_IS_OK(to->q_state)) /* already sent; look at next */
1508 ** Must be same mailer to keep grouping rcpts.
1509 ** If mailers don't match: continue; sendqueue is not
1510 ** sorted by mailers, so don't break;
1513 if (to->q_mailer != firstto->q_mailer)
1516 if (to->q_signature == NULL) /* for safety */
1517 to->q_signature = hostsignature(to->q_mailer,
1521 ** This is for coincidental and tailcoat piggybacking messages
1522 ** to the same mail host. While the signatures are identical
1523 ** (that's the MX-RR's are identical) we can do coincidental
1524 ** piggybacking. We try hard for coattail piggybacking
1525 ** with the same mail host when the next recipient has the
1526 ** same host at lowest preference. It may be that this
1527 ** won't work out, so 'skip_back' is maintained if a backup
1528 ** to coincidental piggybacking or full signature must happen.
1531 ret = firstto == to ? HS_MATCH_FULL :
1532 coloncmp(to->q_signature, firstsig);
1533 if (ret == HS_MATCH_FULL)
1535 else if (ret == HS_MATCH_NO)
1540 /* avoid overflowing tobuf */
1541 strsize += strlen(to->q_paddr) + 1;
1542 if (strsize > TOBUFSIZE)
1546 if (++rcptcount > to->q_mailer->m_maxrcpt)
1551 sm_dprintf("\nsend to ");
1552 printaddr(sm_debug_file(), to, false);
1555 /* compute effective uid/gid when sending */
1556 if (bitnset(M_RUNASRCPT, to->q_mailer->m_flags))
1557 # if HASSETUSERCONTEXT
1558 contextaddr = ctladdr = getctladdr(to);
1559 # else /* HASSETUSERCONTEXT */
1560 ctladdr = getctladdr(to);
1561 # endif /* HASSETUSERCONTEXT */
1565 sm_dprintf("ctladdr=");
1566 printaddr(sm_debug_file(), ctladdr, false);
1570 e->e_to = to->q_paddr;
1573 ** Check to see that these people are allowed to
1574 ** talk to each other.
1575 ** Check also for overflow of e_msgsize.
1578 if (m->m_maxsize != 0 &&
1579 (e->e_msgsize > m->m_maxsize || e->e_msgsize < 0))
1581 e->e_flags |= EF_NO_BODY_RETN;
1582 if (bitnset(M_LOCALMAILER, to->q_mailer->m_flags))
1583 to->q_status = "5.2.3";
1585 to->q_status = "5.3.4";
1587 /* set to->q_rstatus = NULL; or to the following? */
1588 usrerrenh(to->q_status,
1589 "552 Message is too large; %ld bytes max",
1591 markfailure(e, to, NULL, EX_UNAVAILABLE, false);
1592 giveresponse(EX_UNAVAILABLE, to->q_status, m,
1593 NULL, ctladdr, xstart, e, to);
1599 /* do config file checking of compatibility */
1600 quarantine = (e->e_quarmsg != NULL);
1601 rcode = rscheck("check_compat", e->e_from.q_paddr, to->q_paddr,
1602 e, RSF_RMCOMM|RSF_COUNT, 3, NULL,
1606 /* do in-code checking if not discarding */
1607 if (!bitset(EF_DISCARD, e->e_flags))
1609 rcode = checkcompat(to, e);
1615 markfailure(e, to, NULL, rcode, ovr);
1616 giveresponse(rcode, to->q_status, m,
1617 NULL, ctladdr, xstart, e, to);
1620 if (!quarantine && e->e_quarmsg != NULL)
1623 ** check_compat or checkcompat() has tried
1624 ** to quarantine but that isn't supported.
1625 ** Revert the attempt.
1628 e->e_quarmsg = NULL;
1629 macdefine(&e->e_macro, A_PERM,
1630 macid("{quarantine}"), "");
1632 if (bitset(EF_DISCARD, e->e_flags))
1636 sm_dprintf("deliver: discarding recipient ");
1637 printaddr(sm_debug_file(), to, false);
1640 /* pretend the message was sent */
1641 /* XXX should we log something here? */
1642 to->q_state = QS_DISCARDED;
1645 ** Remove discard bit to prevent discard of
1646 ** future recipients. This is safe because the
1647 ** true "global discard" has been handled before
1651 e->e_flags &= ~EF_DISCARD;
1656 ** Strip quote bits from names if the mailer is dumb
1660 if (bitnset(M_STRIPQ, m->m_flags))
1667 ** Strip all leading backslashes if requested and the
1668 ** next character is alphanumerical (the latter can
1669 ** probably relaxed a bit, see RFC2821).
1672 if (bitnset(M_STRIPBACKSL, m->m_flags) && user[0] == '\\')
1673 stripbackslash(user);
1675 /* hack attack -- delivermail compatibility */
1676 if (m == ProgMailer && *user == '|')
1680 ** If an error message has already been given, don't
1681 ** bother to send to this address.
1683 ** >>>>>>>>>> This clause assumes that the local mailer
1684 ** >> NOTE >> cannot do any further aliasing; that
1685 ** >>>>>>>>>> function is subsumed by sendmail.
1688 if (!QS_IS_OK(to->q_state))
1692 ** See if this user name is "special".
1693 ** If the user name has a slash in it, assume that this
1694 ** is a file -- send it off without further ado. Note
1695 ** that this type of addresses is not processed along
1696 ** with the others, so we fudge on the To person.
1699 if (strcmp(m->m_mailer, "[FILE]") == 0)
1701 macdefine(&e->e_macro, A_PERM, 'u', user);
1703 if (p == NULL && ctladdr != NULL)
1704 p = ctladdr->q_home;
1705 macdefine(&e->e_macro, A_PERM, 'z', p);
1706 expand(m->m_argv[1], buf, sizeof(buf), e);
1707 if (strlen(buf) > 0)
1708 rcode = mailfile(buf, m, ctladdr, SFF_CREAT, e);
1711 syserr("empty filename specification for mailer %s",
1715 giveresponse(rcode, to->q_status, m, NULL,
1716 ctladdr, xstart, e, to);
1717 markfailure(e, to, NULL, rcode, true);
1721 to->q_state = QS_SENT;
1722 if (bitnset(M_LOCALMAILER, m->m_flags) &&
1723 bitset(QPINGONSUCCESS, to->q_flags))
1725 to->q_flags |= QDELIVERED;
1726 to->q_status = "2.1.5";
1727 (void) sm_io_fprintf(e->e_xfp,
1729 "%s... Successfully delivered\n",
1733 to->q_statdate = curtime();
1734 markstats(e, to, STATS_NORMAL);
1739 ** Address is verified -- add this user to mailer
1740 ** argv, and add it to the print list of recipients.
1743 /* link together the chain of recipients */
1744 to->q_tchain = tochain;
1746 e->e_to = "[CHAIN]";
1748 macdefine(&e->e_macro, A_PERM, 'u', user); /* to user */
1750 if (p == NULL && ctladdr != NULL)
1751 p = ctladdr->q_home;
1752 macdefine(&e->e_macro, A_PERM, 'z', p); /* user's home */
1754 /* set the ${dsn_notify} macro if applicable */
1755 if (bitset(QHASNOTIFY, to->q_flags))
1757 char notify[MAXLINE];
1760 if (bitset(QPINGONSUCCESS, to->q_flags))
1761 (void) sm_strlcat(notify, "SUCCESS,",
1763 if (bitset(QPINGONFAILURE, to->q_flags))
1764 (void) sm_strlcat(notify, "FAILURE,",
1766 if (bitset(QPINGONDELAY, to->q_flags))
1767 (void) sm_strlcat(notify, "DELAY,",
1770 /* Set to NEVER or drop trailing comma */
1771 if (notify[0] == '\0')
1772 (void) sm_strlcat(notify, "NEVER",
1775 notify[strlen(notify) - 1] = '\0';
1777 macdefine(&e->e_macro, A_TEMP,
1778 macid("{dsn_notify}"), notify);
1781 macdefine(&e->e_macro, A_PERM,
1782 macid("{dsn_notify}"), NULL);
1785 ** Expand out this user into argument list.
1790 expand(*mvp, buf, sizeof(buf), e);
1791 *pvp++ = sm_rpool_strdup_x(e->e_rpool, buf);
1792 if (pvp >= &pv[MAXPV - 2])
1794 /* allow some space for trailing parms */
1800 /* see if any addresses still exist */
1801 if (tochain == NULL)
1807 /* print out messages as full list */
1809 for (to = tochain; to != NULL; to = to->q_tchain)
1810 strsize += strlen(to->q_paddr) + 1;
1811 if (strsize < TOBUFSIZE)
1812 strsize = TOBUFSIZE;
1813 if (strsize > tobufsize)
1816 tobuf = sm_pmalloc_x(strsize);
1817 tobufsize = strsize;
1821 for (to = tochain; to != NULL; to = to->q_tchain)
1823 (void) sm_strlcpyn(p, tobufsize - (p - tobuf), 2,
1827 e->e_to = tobuf + 1;
1830 ** Fill out any parameters after the $u parameter.
1835 while (*++mvp != NULL)
1837 expand(*mvp, buf, sizeof(buf), e);
1838 *pvp++ = sm_rpool_strdup_x(e->e_rpool, buf);
1839 if (pvp >= &pv[MAXPV])
1840 syserr("554 5.3.0 deliver: pv overflow after $u for %s",
1848 ** The argument vector gets built, pipes
1849 ** are created as necessary, and we fork & exec as
1851 ** If we are running SMTP, we just need to clean up.
1854 /* XXX this seems a bit weird */
1855 if (ctladdr == NULL && m != ProgMailer && m != FileMailer &&
1856 bitset(QGOODUID, e->e_from.q_flags))
1857 ctladdr = &e->e_from;
1860 if (ConfigLevel < 2)
1861 _res.options &= ~(RES_DEFNAMES | RES_DNSRCH); /* XXX */
1862 #endif /* NAMED_BIND */
1866 sm_dprintf("openmailer:");
1867 printav(sm_debug_file(), pv);
1874 ** Deal with the special case of mail handled through an IPC
1876 ** In this case we don't actually fork. We must be
1877 ** running SMTP for this to work. We will return a
1878 ** zero pid to indicate that we are running IPC.
1879 ** We also handle a debug version that just talks to stdin/out.
1890 /* make absolutely certain 0, 1, and 2 are in use */
1891 (void) sm_snprintf(wbuf, sizeof(wbuf), "%s... openmailer(%s)",
1892 shortenstring(e->e_to, MAXSHORTSTR),
1898 /* check for 8-bit available */
1899 if (bitset(EF_HAS8BIT, e->e_flags) &&
1900 bitnset(M_7BITS, m->m_flags) &&
1901 (bitset(EF_DONT_MIME, e->e_flags) ||
1902 !(bitset(MM_MIME8BIT, MimeMode) ||
1903 (bitset(EF_IS_MIME, e->e_flags) &&
1904 bitset(MM_CVTMIME, MimeMode)))))
1906 e->e_status = "5.6.3";
1907 usrerrenh(e->e_status,
1908 "554 Cannot send 8-bit data to 7-bit destination");
1914 checkfds("before delivery");
1916 /* check for Local Person Communication -- not for mortals!!! */
1917 if (strcmp(m->m_mailer, "[LPC]") == 0)
1921 /* flush any expired connections */
1922 (void) mci_scan(NULL);
1924 /* try to get a cached connection or just a slot */
1925 mci = mci_get(m->m_name, m);
1926 if (mci->mci_host == NULL)
1927 mci->mci_host = m->m_name;
1928 CurHostName = mci->mci_host;
1929 if (mci->mci_state != MCIS_CLOSED)
1931 message("Using cached SMTP/LPC connection for %s...",
1933 mci->mci_deliveries++;
1939 mci = mci_new(e->e_rpool);
1941 mci->mci_in = smioin;
1942 mci->mci_out = smioout;
1943 mci->mci_mailer = m;
1944 mci->mci_host = m->m_name;
1947 mci->mci_state = MCIS_OPENING;
1951 mci->mci_state = MCIS_OPEN;
1953 else if (strcmp(m->m_mailer, "[IPC]") == 0)
1957 if (pv[0] == NULL || pv[1] == NULL || pv[1][0] == '\0')
1959 syserr("null destination for %s mailer", m->m_mailer);
1965 if (strcmp(pv[0], "FILE") == 0)
1967 curhost = CurHostName = "localhost";
1971 # endif /* NETUNIX */
1973 CurHostName = pv[1];
1974 curhost = hostsignature(m, pv[1]);
1977 if (curhost == NULL || curhost[0] == '\0')
1979 syserr("null host signature for %s", pv[1]);
1986 syserr("554 5.3.5 non-clever IPC");
1993 # endif /* NETUNIX */
1996 port = htons((unsigned short) atoi(pv[2]));
1999 # ifdef NO_GETSERVBYNAME
2000 syserr("Invalid port number: %s", pv[2]);
2001 # else /* NO_GETSERVBYNAME */
2002 struct servent *sp = getservbyname(pv[2], "tcp");
2005 syserr("Service %s unknown", pv[2]);
2008 # endif /* NO_GETSERVBYNAME */
2012 nummxhosts = parse_hostsignature(curhost, mxhosts, m);
2013 if (TimeOuts.to_aconnect > 0)
2014 enough = curtime() + TimeOuts.to_aconnect;
2016 while (hostnum < nummxhosts)
2020 static char hostbuf[MAXNAME + 1];
2021 bool tried_fallbacksmarthost = false;
2024 if (*mxhosts[hostnum] == '[')
2026 endp = strchr(mxhosts[hostnum] + 1, ']');
2028 endp = strpbrk(endp + 1, ":,");
2031 endp = strpbrk(mxhosts[hostnum], ":,");
2032 # else /* NETINET6 */
2033 endp = strpbrk(mxhosts[hostnum], ":,");
2034 # endif /* NETINET6 */
2041 if (hostnum == 1 && skip_back != NULL)
2044 ** Coattail piggybacking is no longer an
2045 ** option with the mail host next to be tried
2046 ** no longer the lowest MX preference
2047 ** (hostnum == 1 meaning we're on the second
2048 ** preference). We do not try to coattail
2049 ** piggyback more than the first MX preference.
2050 ** Revert 'tochain' to last location for
2051 ** coincidental piggybacking. This works this
2052 ** easily because the q_tchain kept getting
2053 ** added to the top of the linked list.
2056 tochain = skip_back;
2059 if (*mxhosts[hostnum] == '\0')
2061 syserr("deliver: null host name in signature");
2067 (void) sm_strlcpy(hostbuf, mxhosts[hostnum],
2074 /* see if we already know that this host is fried */
2075 CurHostName = hostbuf;
2076 mci = mci_get(hostbuf, m);
2077 if (mci->mci_state != MCIS_CLOSED)
2083 sm_dprintf("openmailer: ");
2084 mci_dump(sm_debug_file(), mci, false);
2086 CurHostName = mci->mci_host;
2087 if (bitnset(M_LMTP, m->m_flags))
2089 else if (bitset(MCIF_ESMTP, mci->mci_flags))
2093 message("Using cached %sMTP connection to %s via %s...",
2094 type, hostbuf, m->m_name);
2095 mci->mci_deliveries++;
2098 mci->mci_mailer = m;
2099 if (mci->mci_exitstat != EX_OK)
2101 if (mci->mci_exitstat == EX_TEMPFAIL)
2104 /* Try FallbackSmartHost? */
2105 if (should_try_fbsh(e, &tried_fallbacksmarthost,
2106 hostbuf, sizeof(hostbuf),
2113 if (mci_lock_host(mci) != EX_OK)
2115 mci_setstat(mci, EX_TEMPFAIL, "4.4.5", NULL);
2120 /* try the connection */
2121 sm_setproctitle(true, e, "%s %s: %s",
2123 hostbuf, "user open");
2125 if (mux_path != NULL)
2127 message("Connecting to %s via %s...",
2128 mux_path, m->m_name);
2129 i = makeconnection_ds((char *) mux_path, mci);
2132 # endif /* NETUNIX */
2135 message("Connecting to %s via %s...",
2136 hostbuf, m->m_name);
2138 message("Connecting to %s port %d via %s...",
2139 hostbuf, ntohs(port),
2141 i = makeconnection(hostbuf, port, mci, e,
2144 mci->mci_errno = errno;
2145 mci->mci_lastuse = curtime();
2146 mci->mci_deliveries = 0;
2147 mci->mci_exitstat = i;
2148 mci_clr_extensions(mci);
2150 mci->mci_herrno = h_errno;
2151 # endif /* NAMED_BIND */
2154 ** Have we tried long enough to get a connection?
2155 ** If yes, skip to the fallback MX hosts
2159 if (enough > 0 && mci->mci_lastuse >= enough)
2163 extern int NumFallbackMXHosts;
2164 # else /* NAMED_BIND */
2165 const int NumFallbackMXHosts = 0;
2166 # endif /* NAMED_BIND */
2168 if (hostnum < nummxhosts && LogLevel > 9)
2169 sm_syslog(LOG_INFO, e->e_id,
2170 "Timeout.to_aconnect occurred before exhausting all addresses");
2172 /* turn off timeout if fallback available */
2173 if (NumFallbackMXHosts > 0)
2176 /* skip to a fallback MX host */
2177 h = nummxhosts - NumFallbackMXHosts;
2184 markstats(e, firstto, STATS_CONNECT);
2185 mci->mci_state = MCIS_OPENING;
2187 if (TrafficLogFile != NULL)
2188 (void) sm_io_fprintf(TrafficLogFile,
2190 "%05d === CONNECT %s\n",
2197 /* Try FallbackSmartHost? */
2198 if (should_try_fbsh(e, &tried_fallbacksmarthost,
2199 hostbuf, sizeof(hostbuf), i))
2203 sm_dprintf("openmailer: makeconnection => stat=%d, errno=%d\n",
2205 if (i == EX_TEMPFAIL)
2207 mci_unlock_host(mci);
2210 /* enter status of this host */
2213 /* should print some message here for -v mode */
2217 syserr("deliver: no host name");
2218 rcode = EX_SOFTWARE;
2225 /* flush any expired connections */
2226 (void) mci_scan(NULL);
2229 if (bitnset(M_LMTP, m->m_flags))
2231 /* try to get a cached connection */
2232 mci = mci_get(m->m_name, m);
2233 if (mci->mci_host == NULL)
2234 mci->mci_host = m->m_name;
2235 CurHostName = mci->mci_host;
2236 if (mci->mci_state != MCIS_CLOSED)
2238 message("Using cached LMTP connection for %s...",
2240 mci->mci_deliveries++;
2245 /* announce the connection to verbose listeners */
2246 if (host == NULL || host[0] == '\0')
2247 message("Connecting to %s...", m->m_name);
2249 message("Connecting to %s via %s...", host, m->m_name);
2250 if (TrafficLogFile != NULL)
2254 (void) sm_io_fprintf(TrafficLogFile, SM_TIME_DEFAULT,
2255 "%05d === EXEC", (int) CurrentPid);
2256 for (av = pv; *av != NULL; av++)
2257 (void) sm_io_fprintf(TrafficLogFile,
2258 SM_TIME_DEFAULT, " %s",
2260 (void) sm_io_fprintf(TrafficLogFile, SM_TIME_DEFAULT,
2265 checkfd012("before creating mail pipe");
2268 /* create a pipe to shove the mail through */
2269 if (pipe(mpvect) < 0)
2271 syserr("%s... openmailer(%s): pipe (to mailer)",
2272 shortenstring(e->e_to, MAXSHORTSTR), m->m_name);
2274 sm_dprintf("openmailer: NULL\n");
2280 /* make sure we didn't get one of the standard I/O files */
2281 if (mpvect[0] < 3 || mpvect[1] < 3)
2283 syserr("%s... openmailer(%s): bogus mpvect %d %d",
2284 shortenstring(e->e_to, MAXSHORTSTR), m->m_name,
2285 mpvect[0], mpvect[1]);
2288 sm_dprintf("openmailer: NULL\n");
2293 /* make sure system call isn't dead meat */
2294 checkfdopen(mpvect[0], "mpvect[0]");
2295 checkfdopen(mpvect[1], "mpvect[1]");
2296 if (mpvect[0] == mpvect[1] ||
2297 (e->e_lockfp != NULL &&
2298 (mpvect[0] == sm_io_getinfo(e->e_lockfp, SM_IO_WHAT_FD,
2300 mpvect[1] == sm_io_getinfo(e->e_lockfp, SM_IO_WHAT_FD,
2303 if (e->e_lockfp == NULL)
2304 syserr("%s... openmailer(%s): overlapping mpvect %d %d",
2305 shortenstring(e->e_to, MAXSHORTSTR),
2306 m->m_name, mpvect[0], mpvect[1]);
2308 syserr("%s... openmailer(%s): overlapping mpvect %d %d, lockfp = %d",
2309 shortenstring(e->e_to, MAXSHORTSTR),
2310 m->m_name, mpvect[0], mpvect[1],
2311 sm_io_getinfo(e->e_lockfp,
2312 SM_IO_WHAT_FD, NULL));
2316 /* create a return pipe */
2317 if (pipe(rpvect) < 0)
2319 syserr("%s... openmailer(%s): pipe (from mailer)",
2320 shortenstring(e->e_to, MAXSHORTSTR),
2322 (void) close(mpvect[0]);
2323 (void) close(mpvect[1]);
2325 sm_dprintf("openmailer: NULL\n");
2330 checkfdopen(rpvect[0], "rpvect[0]");
2331 checkfdopen(rpvect[1], "rpvect[1]");
2335 ** Actually fork the mailer process.
2336 ** DOFORK is clever about retrying.
2338 ** Dispose of SIGCHLD signal catchers that may be laying
2339 ** around so that endmailer will get it.
2342 if (e->e_xfp != NULL) /* for debugging */
2343 (void) sm_io_flush(e->e_xfp, SM_TIME_DEFAULT);
2344 (void) sm_io_flush(smioout, SM_TIME_DEFAULT);
2345 (void) sm_signal(SIGCHLD, SIG_DFL);
2349 /* pid is set by DOFORK */
2354 syserr("%s... openmailer(%s): cannot fork",
2355 shortenstring(e->e_to, MAXSHORTSTR), m->m_name);
2356 (void) close(mpvect[0]);
2357 (void) close(mpvect[1]);
2358 (void) close(rpvect[0]);
2359 (void) close(rpvect[1]);
2361 sm_dprintf("openmailer: NULL\n");
2369 int new_euid = NO_UID;
2370 int new_ruid = NO_UID;
2371 int new_gid = NO_GID;
2374 extern int DtableSize;
2376 CurrentPid = getpid();
2378 /* clear the events to turn off SIGALRMs */
2381 /* Reset global flags */
2382 RestartRequest = NULL;
2383 RestartWorkGroup = false;
2384 ShutdownRequest = NULL;
2387 if (e->e_lockfp != NULL)
2388 (void) close(sm_io_getinfo(e->e_lockfp,
2392 /* child -- set up input & exec mailer */
2393 (void) sm_signal(SIGALRM, sm_signal_noop);
2394 (void) sm_signal(SIGCHLD, SIG_DFL);
2395 (void) sm_signal(SIGHUP, SIG_IGN);
2396 (void) sm_signal(SIGINT, SIG_IGN);
2397 (void) sm_signal(SIGTERM, SIG_DFL);
2399 (void) sm_signal(SIGUSR1, sm_signal_noop);
2400 # endif /* SIGUSR1 */
2402 if (m != FileMailer || stat(tochain->q_user, &stb) < 0)
2405 # if HASSETUSERCONTEXT
2407 ** Set user resources.
2410 if (contextaddr != NULL)
2415 if (contextaddr->q_ruser != NULL)
2416 pwd = sm_getpwnam(contextaddr->q_ruser);
2418 pwd = sm_getpwnam(contextaddr->q_user);
2419 sucflags = LOGIN_SETRESOURCES|LOGIN_SETPRIORITY;
2420 #ifdef LOGIN_SETCPUMASK
2421 sucflags |= LOGIN_SETCPUMASK;
2422 #endif /* LOGIN_SETCPUMASK */
2423 #ifdef LOGIN_SETLOGINCLASS
2424 sucflags |= LOGIN_SETLOGINCLASS;
2425 #endif /* LOGIN_SETLOGINCLASS */
2427 sucflags |= LOGIN_SETMAC;
2428 #endif /* LOGIN_SETMAC */
2430 setusercontext(NULL, pwd, pwd->pw_uid,
2434 syserr("openmailer: setusercontext() failed");
2438 # endif /* HASSETUSERCONTEXT */
2441 /* tweak niceness */
2443 (void) nice(m->m_nice);
2444 #endif /* HASNICE */
2446 /* reset group id */
2447 if (bitnset(M_SPECIFIC_UID, m->m_flags))
2449 if (m->m_gid == NO_GID)
2454 else if (bitset(S_ISGID, stb.st_mode))
2455 new_gid = stb.st_gid;
2456 else if (ctladdr != NULL && ctladdr->q_gid != 0)
2458 if (!DontInitGroups)
2460 user = ctladdr->q_ruser;
2462 user = ctladdr->q_user;
2464 if (initgroups(user,
2465 ctladdr->q_gid) == -1
2468 syserr("openmailer: initgroups(%s, %d) failed",
2469 user, ctladdr->q_gid);
2477 gidset[0] = ctladdr->q_gid;
2478 if (setgroups(1, gidset) == -1
2481 syserr("openmailer: setgroups() failed");
2485 new_gid = ctladdr->q_gid;
2489 if (!DontInitGroups)
2492 if (initgroups(DefUser, DefGid) == -1 &&
2495 syserr("openmailer: initgroups(%s, %d) failed",
2505 if (setgroups(1, gidset) == -1
2508 syserr("openmailer: setgroups() failed");
2512 if (m->m_gid == NO_GID)
2517 if (new_gid != NO_GID)
2519 if (RunAsUid != 0 &&
2520 bitnset(M_SPECIFIC_UID, m->m_flags) &&
2521 new_gid != getgid() &&
2522 new_gid != getegid())
2524 /* Only root can change the gid */
2525 syserr("openmailer: insufficient privileges to change gid, RunAsUid=%d, new_gid=%d, gid=%d, egid=%d",
2526 (int) RunAsUid, (int) new_gid,
2527 (int) getgid(), (int) getegid());
2531 if (setgid(new_gid) < 0 && suidwarn)
2533 syserr("openmailer: setgid(%ld) failed",
2539 /* change root to some "safe" directory */
2540 if (m->m_rootdir != NULL)
2542 expand(m->m_rootdir, cbuf, sizeof(cbuf), e);
2544 sm_dprintf("openmailer: chroot %s\n",
2546 if (chroot(cbuf) < 0)
2548 syserr("openmailer: Cannot chroot(%s)",
2554 syserr("openmailer: cannot chdir(/)");
2561 sm_mbdb_terminate();
2562 if (bitnset(M_SPECIFIC_UID, m->m_flags))
2564 if (m->m_uid == NO_UID)
2565 new_euid = RunAsUid;
2567 new_euid = m->m_uid;
2570 ** Undo the effects of the uid change in main
2571 ** for signal handling. The real uid may
2572 ** be used by mailer in adding a "From "
2576 if (RealUid != 0 && RealUid != getuid())
2578 # if MAILER_SETUID_METHOD == USE_SETEUID
2580 if (setreuid(RealUid, geteuid()) < 0)
2582 syserr("openmailer: setreuid(%d, %d) failed",
2583 (int) RealUid, (int) geteuid());
2586 # endif /* HASSETREUID */
2587 # endif /* MAILER_SETUID_METHOD == USE_SETEUID */
2588 # if MAILER_SETUID_METHOD == USE_SETREUID
2590 # endif /* MAILER_SETUID_METHOD == USE_SETREUID */
2593 else if (bitset(S_ISUID, stb.st_mode))
2594 new_ruid = stb.st_uid;
2595 else if (ctladdr != NULL && ctladdr->q_uid != 0)
2596 new_ruid = ctladdr->q_uid;
2597 else if (m->m_uid != NO_UID)
2598 new_ruid = m->m_uid;
2602 # if _FFR_USE_SETLOGIN
2603 /* run disconnected from terminal and set login name */
2604 if (setsid() >= 0 &&
2605 ctladdr != NULL && ctladdr->q_uid != 0 &&
2606 new_euid == ctladdr->q_uid)
2610 pwd = sm_getpwuid(ctladdr->q_uid);
2611 if (pwd != NULL && suidwarn)
2612 (void) setlogin(pwd->pw_name);
2615 # endif /* _FFR_USE_SETLOGIN */
2617 if (new_euid != NO_UID)
2619 if (RunAsUid != 0 && new_euid != RunAsUid)
2621 /* Only root can change the uid */
2622 syserr("openmailer: insufficient privileges to change uid, new_euid=%d, RunAsUid=%d",
2623 (int) new_euid, (int) RunAsUid);
2627 vendor_set_uid(new_euid);
2628 # if MAILER_SETUID_METHOD == USE_SETEUID
2629 if (seteuid(new_euid) < 0 && suidwarn)
2631 syserr("openmailer: seteuid(%ld) failed",
2635 # endif /* MAILER_SETUID_METHOD == USE_SETEUID */
2636 # if MAILER_SETUID_METHOD == USE_SETREUID
2637 if (setreuid(new_ruid, new_euid) < 0 && suidwarn)
2639 syserr("openmailer: setreuid(%ld, %ld) failed",
2640 (long) new_ruid, (long) new_euid);
2643 # endif /* MAILER_SETUID_METHOD == USE_SETREUID */
2644 # if MAILER_SETUID_METHOD == USE_SETUID
2645 if (new_euid != geteuid() && setuid(new_euid) < 0 && suidwarn)
2647 syserr("openmailer: setuid(%ld) failed",
2651 # endif /* MAILER_SETUID_METHOD == USE_SETUID */
2653 else if (new_ruid != NO_UID)
2655 vendor_set_uid(new_ruid);
2656 if (setuid(new_ruid) < 0 && suidwarn)
2658 syserr("openmailer: setuid(%ld) failed",
2665 sm_dprintf("openmailer: running as r/euid=%d/%d, r/egid=%d/%d\n",
2666 (int) getuid(), (int) geteuid(),
2667 (int) getgid(), (int) getegid());
2669 /* move into some "safe" directory */
2670 if (m->m_execdir != NULL)
2674 for (p = m->m_execdir; p != NULL; p = q)
2679 expand(p, cbuf, sizeof(cbuf), e);
2683 sm_dprintf("openmailer: trydir %s\n",
2685 if (cbuf[0] != '\0' &&
2691 /* Check safety of program to be run */
2692 sff = SFF_ROOTOK|SFF_EXECOK;
2693 if (!bitnset(DBS_RUNWRITABLEPROGRAM,
2695 sff |= SFF_NOGWFILES|SFF_NOWWFILES;
2696 if (bitnset(DBS_RUNPROGRAMINUNSAFEDIRPATH,
2698 sff |= SFF_NOPATHCHECK;
2700 sff |= SFF_SAFEDIRPATH;
2701 ret = safefile(m->m_mailer, getuid(), getgid(),
2702 user, sff, 0, NULL);
2704 sm_syslog(LOG_INFO, e->e_id,
2705 "Warning: program %s unsafe: %s",
2706 m->m_mailer, sm_errstring(ret));
2708 /* arrange to filter std & diag output of command */
2709 (void) close(rpvect[0]);
2710 if (dup2(rpvect[1], STDOUT_FILENO) < 0)
2712 syserr("%s... openmailer(%s): cannot dup pipe %d for stdout",
2713 shortenstring(e->e_to, MAXSHORTSTR),
2714 m->m_name, rpvect[1]);
2717 (void) close(rpvect[1]);
2719 if (dup2(STDOUT_FILENO, STDERR_FILENO) < 0)
2721 syserr("%s... openmailer(%s): cannot dup stdout for stderr",
2722 shortenstring(e->e_to, MAXSHORTSTR),
2727 /* arrange to get standard input */
2728 (void) close(mpvect[1]);
2729 if (dup2(mpvect[0], STDIN_FILENO) < 0)
2731 syserr("%s... openmailer(%s): cannot dup pipe %d for stdin",
2732 shortenstring(e->e_to, MAXSHORTSTR),
2733 m->m_name, mpvect[0]);
2736 (void) close(mpvect[0]);
2738 /* arrange for all the files to be closed */
2739 sm_close_on_exec(STDERR_FILENO + 1, DtableSize);
2741 # if !_FFR_USE_SETLOGIN
2742 /* run disconnected from terminal */
2744 # endif /* !_FFR_USE_SETLOGIN */
2746 /* try to execute the mailer */
2747 (void) execve(m->m_mailer, (ARGV_T) pv,
2748 (ARGV_T) UserEnviron);
2750 syserr("Cannot exec %s", m->m_mailer);
2751 if (bitnset(M_LOCALMAILER, m->m_flags) ||
2752 transienterror(save_errno))
2754 _exit(EX_UNAVAILABLE);
2758 ** Set up return value.
2766 ** Allocate from general heap, not
2767 ** envelope rpool, because this mci
2768 ** is going to be cached.
2771 mci = mci_new(NULL);
2776 ** Prevent a storage leak by allocating
2777 ** this from the envelope rpool.
2780 mci = mci_new(e->e_rpool);
2783 mci->mci_mailer = m;
2786 mci->mci_state = MCIS_OPENING;
2791 mci->mci_state = MCIS_OPEN;
2794 (void) close(mpvect[0]);
2795 mci->mci_out = sm_io_open(SmFtStdiofd, SM_TIME_DEFAULT,
2796 (void *) &(mpvect[1]), SM_IO_WRONLY_B,
2798 if (mci->mci_out == NULL)
2800 syserr("deliver: cannot create mailer output channel, fd=%d",
2802 (void) close(mpvect[1]);
2803 (void) close(rpvect[0]);
2804 (void) close(rpvect[1]);
2809 (void) close(rpvect[1]);
2810 mci->mci_in = sm_io_open(SmFtStdiofd, SM_TIME_DEFAULT,
2811 (void *) &(rpvect[0]), SM_IO_RDONLY_B,
2813 if (mci->mci_in == NULL)
2815 syserr("deliver: cannot create mailer input channel, fd=%d",
2817 (void) close(rpvect[0]);
2818 (void) sm_io_close(mci->mci_out, SM_TIME_DEFAULT);
2819 mci->mci_out = NULL;
2826 ** If we are in SMTP opening state, send initial protocol.
2829 if (bitnset(M_7BITS, m->m_flags) &&
2830 (!clever || mci->mci_state == MCIS_OPENING))
2831 mci->mci_flags |= MCIF_7BIT;
2832 if (clever && mci->mci_state != MCIS_CLOSED)
2834 # if STARTTLS || SASL
2837 extern SOCKADDR CurHostAddr;
2838 # endif /* STARTTLS || SASL */
2841 # define DONE_AUTH(f) bitset(MCIF_AUTHACT, f)
2844 # define DONE_STARTTLS(f) bitset(MCIF_TLSACT, f)
2845 # endif /* STARTTLS */
2846 # define ONLY_HELO(f) bitset(MCIF_ONLY_EHLO, f)
2847 # define SET_HELO(f) f |= MCIF_ONLY_EHLO
2848 # define CLR_HELO(f) f &= ~MCIF_ONLY_EHLO
2850 # if STARTTLS || SASL
2851 /* don't use CurHostName, it is changed in many places */
2852 if (mci->mci_host != NULL)
2854 srvname = mci->mci_host;
2855 dotpos = strlen(srvname) - 1;
2858 if (srvname[dotpos] == '.')
2859 srvname[dotpos] = '\0';
2864 else if (mci->mci_mailer != NULL)
2866 srvname = mci->mci_mailer->m_name;
2875 /* don't set {server_name} to NULL or "": see getauth() */
2876 macdefine(&mci->mci_macro, A_TEMP, macid("{server_name}"),
2879 /* CurHostAddr is set by makeconnection() and mci_get() */
2880 if (CurHostAddr.sa.sa_family != 0)
2882 macdefine(&mci->mci_macro, A_TEMP,
2883 macid("{server_addr}"),
2884 anynet_ntoa(&CurHostAddr));
2886 else if (mci->mci_mailer != NULL)
2888 /* mailer name is unique, use it as address */
2889 macdefine(&mci->mci_macro, A_PERM,
2890 macid("{server_addr}"),
2891 mci->mci_mailer->m_name);
2895 /* don't set it to NULL or "": see getauth() */
2896 macdefine(&mci->mci_macro, A_PERM,
2897 macid("{server_addr}"), "0");
2900 /* undo change of srvname (mci->mci_host) */
2902 srvname[dotpos] = '.';
2904 reconnect: /* after switching to an encrypted connection */
2905 # endif /* STARTTLS || SASL */
2907 /* set the current connection information */
2910 mci->mci_saslcap = NULL;
2912 smtpinit(m, mci, e, ONLY_HELO(mci->mci_flags));
2913 CLR_HELO(mci->mci_flags);
2915 if (IS_DLVR_RETURN(e))
2918 ** Check whether other side can deliver e-mail
2922 if (!bitset(MCIF_DLVR_BY, mci->mci_flags))
2924 e->e_status = "5.4.7";
2925 usrerrenh(e->e_status,
2926 "554 Server does not support Deliver By");
2927 rcode = EX_UNAVAILABLE;
2930 if (e->e_deliver_by > 0 &&
2931 e->e_deliver_by - (curtime() - e->e_ctime) <
2934 e->e_status = "5.4.7";
2935 usrerrenh(e->e_status,
2936 "554 Message can't be delivered in time; %ld < %ld",
2937 e->e_deliver_by - (curtime() - e->e_ctime),
2939 rcode = EX_UNAVAILABLE;
2945 /* first TLS then AUTH to provide a security layer */
2946 if (mci->mci_state != MCIS_CLOSED &&
2947 !DONE_STARTTLS(mci->mci_flags))
2951 bool saveQuickAbort = QuickAbort;
2952 bool saveSuprErrs = SuprErrs;
2956 usetls = bitset(MCIF_TLS, mci->mci_flags);
2958 usetls = !iscltflgset(e, D_NOTLS);
2960 host = macvalue(macid("{server_name}"), e);
2966 if (rscheck("try_tls", host, NULL, e,
2967 RSF_RMCOMM, 7, host, NOQID, NULL)
2969 || Errors > olderrors)
2973 SuprErrs = saveSuprErrs;
2974 QuickAbort = saveQuickAbort;
2979 if ((rcode = starttls(m, mci, e)) == EX_OK)
2981 /* start again without STARTTLS */
2982 mci->mci_flags |= MCIF_TLSACT;
2989 ** TLS negotiation failed, what to do?
2990 ** fall back to unencrypted connection
2991 ** or abort? How to decide?
2992 ** set a macro and call a ruleset.
2995 mci->mci_flags &= ~MCIF_TLS;
3010 case EX_UNAVAILABLE:
3014 /* everything else is a failure */
3017 rcode = EX_TEMPFAIL;
3019 macdefine(&e->e_macro, A_PERM,
3020 macid("{verify}"), s);
3024 macdefine(&e->e_macro, A_PERM,
3025 macid("{verify}"), "NONE");
3031 ** rcode == EX_SOFTWARE is special:
3032 ** the TLS negotiation failed
3033 ** we have to drop the connection no matter what
3034 ** However, we call tls_server to give it the chance
3035 ** to log the problem and return an appropriate
3039 if (rscheck("tls_server",
3040 macvalue(macid("{verify}"), e),
3041 NULL, e, RSF_RMCOMM|RSF_COUNT, 5,
3042 host, NOQID, NULL) != EX_OK ||
3043 Errors > olderrors ||
3044 rcode == EX_SOFTWARE)
3046 char enhsc[ENHSCLEN];
3047 extern char MsgBuf[];
3049 if (ISSMTPCODE(MsgBuf) &&
3050 extenhsc(MsgBuf + 4, ' ', enhsc) > 0)
3052 p = sm_rpool_strdup_x(e->e_rpool,
3057 p = "403 4.7.0 server not authenticated.";
3058 (void) sm_strlcpy(enhsc, "4.7.0",
3061 SuprErrs = saveSuprErrs;
3062 QuickAbort = saveQuickAbort;
3064 if (rcode == EX_SOFTWARE)
3066 /* drop the connection */
3067 mci->mci_state = MCIS_QUITING;
3068 if (mci->mci_in != NULL)
3070 (void) sm_io_close(mci->mci_in,
3074 mci->mci_flags &= ~MCIF_TLSACT;
3075 (void) endmailer(mci, e, pv);
3079 /* abort transfer */
3080 smtpquit(m, mci, e);
3083 /* avoid bogus error msg */
3086 /* temp or permanent failure? */
3087 rcode = (*p == '4') ? EX_TEMPFAIL
3089 mci_setstat(mci, rcode, enhsc, p);
3092 ** hack to get the error message into
3093 ** the envelope (done in giveresponse())
3096 (void) sm_strlcpy(SmtpError, p,
3099 else if (mci->mci_state == MCIS_CLOSED)
3101 /* connection close caused by 421 */
3103 rcode = EX_TEMPFAIL;
3104 mci_setstat(mci, rcode, NULL, "421");
3109 QuickAbort = saveQuickAbort;
3110 SuprErrs = saveSuprErrs;
3111 if (DONE_STARTTLS(mci->mci_flags) &&
3112 mci->mci_state != MCIS_CLOSED)
3114 SET_HELO(mci->mci_flags);
3115 mci_clr_extensions(mci);
3119 # endif /* STARTTLS */
3121 /* if other server supports authentication let's authenticate */
3122 if (mci->mci_state != MCIS_CLOSED &&
3123 mci->mci_saslcap != NULL &&
3124 !DONE_AUTH(mci->mci_flags) && !iscltflgset(e, D_NOAUTH))
3126 /* Should we require some minimum authentication? */
3127 if ((ret = smtpauth(m, mci, e)) == EX_OK)
3130 sasl_ssf_t *ssf = NULL;
3132 /* Get security strength (features) */
3133 result = sasl_getprop(mci->mci_conn, SASL_SSF,
3135 (const void **) &ssf);
3136 # else /* SASL >= 20000 */
3138 # endif /* SASL >= 20000 */
3142 sm_syslog(LOG_INFO, NOQID,
3143 "AUTH=client, relay=%.100s, mech=%.16s, bits=%d",
3145 macvalue(macid("{auth_type}"), e),
3146 result == SASL_OK ? *ssf : 0);
3149 ** Only switch to encrypted connection
3150 ** if a security layer has been negotiated
3153 if (result == SASL_OK && *ssf > 0)
3158 ** Convert I/O layer to use SASL.
3159 ** If the call fails, the connection
3163 tmo = DATA_PROGRESS_TIMEOUT * 1000;
3164 if (sfdcsasl(&mci->mci_in,
3166 mci->mci_conn, tmo) == 0)
3168 mci_clr_extensions(mci);
3169 mci->mci_flags |= MCIF_AUTHACT|
3173 syserr("AUTH TLS switch failed in client");
3176 mci->mci_flags |= MCIF_AUTHACT;
3179 else if (ret == EX_TEMPFAIL)
3182 sm_syslog(LOG_ERR, NOQID,
3183 "AUTH=client, relay=%.100s, temporary failure, connection abort",
3185 smtpquit(m, mci, e);
3187 /* avoid bogus error msg */
3189 rcode = EX_TEMPFAIL;
3190 mci_setstat(mci, rcode, "4.3.0", p);
3193 ** hack to get the error message into
3194 ** the envelope (done in giveresponse())
3197 (void) sm_strlcpy(SmtpError,
3198 "Temporary AUTH failure",
3207 /* clear out per-message flags from connection structure */
3208 mci->mci_flags &= ~(MCIF_CVT7TO8|MCIF_CVT8TO7);
3210 if (bitset(EF_HAS8BIT, e->e_flags) &&
3211 !bitset(EF_DONT_MIME, e->e_flags) &&
3212 bitnset(M_7BITS, m->m_flags))
3213 mci->mci_flags |= MCIF_CVT8TO7;
3216 if (bitnset(M_MAKE8BIT, m->m_flags) &&
3217 !bitset(MCIF_7BIT, mci->mci_flags) &&
3218 (p = hvalue("Content-Transfer-Encoding", e->e_header)) != NULL &&
3219 (sm_strcasecmp(p, "quoted-printable") == 0 ||
3220 sm_strcasecmp(p, "base64") == 0) &&
3221 (p = hvalue("Content-Type", e->e_header)) != NULL)
3223 /* may want to convert 7 -> 8 */
3224 /* XXX should really parse it here -- and use a class XXX */
3225 if (sm_strncasecmp(p, "text/plain", 10) == 0 &&
3226 (p[10] == '\0' || p[10] == ' ' || p[10] == ';'))
3227 mci->mci_flags |= MCIF_CVT7TO8;
3229 #endif /* MIME7TO8 */
3233 sm_dprintf("openmailer: ");
3234 mci_dump(sm_debug_file(), mci, false);
3237 #if _FFR_CLIENT_SIZE
3239 ** See if we know the maximum size and
3240 ** abort if the message is too big.
3242 ** NOTE: _FFR_CLIENT_SIZE is untested.
3245 if (bitset(MCIF_SIZE, mci->mci_flags) &&
3246 mci->mci_maxsize > 0 &&
3247 e->e_msgsize > mci->mci_maxsize)
3249 e->e_flags |= EF_NO_BODY_RETN;
3250 if (bitnset(M_LOCALMAILER, m->m_flags))
3251 e->e_status = "5.2.3";
3253 e->e_status = "5.3.4";
3255 usrerrenh(e->e_status,
3256 "552 Message is too large; %ld bytes max",
3260 /* Need an e_message for error */
3261 (void) sm_snprintf(SmtpError, sizeof(SmtpError),
3262 "Message is too large; %ld bytes max",
3266 #endif /* _FFR_CLIENT_SIZE */
3268 if (mci->mci_state != MCIS_OPEN)
3270 /* couldn't open the mailer */
3271 rcode = mci->mci_exitstat;
3272 errno = mci->mci_errno;
3273 SM_SET_H_ERRNO(mci->mci_herrno);
3276 /* shouldn't happen */
3277 syserr("554 5.3.5 deliver: mci=%lx rcode=%d errno=%d state=%d sig=%s",
3278 (unsigned long) mci, rcode, errno,
3279 mci->mci_state, firstsig);
3280 mci_dump_all(smioout, true);
3281 rcode = EX_SOFTWARE;
3283 else if (nummxhosts > hostnum)
3285 /* try next MX site */
3294 ** Format and send message.
3299 ok = putfromline(mci, e);
3301 ok = (*e->e_puthdr)(mci, e->e_header, e, M87F_OUTER);
3303 ok = (*e->e_putbody)(mci, e, NULL);
3304 if (ok && bitset(MCIF_INLONGLINE, mci->mci_flags))
3305 ok = putline("", mci);
3308 ** Ignore an I/O error that was caused by EPIPE.
3309 ** Some broken mailers don't read the entire body
3310 ** but just exit() thus causing an I/O error.
3313 if (!ok && (sm_io_error(mci->mci_out) && errno == EPIPE))
3316 /* (always) get the exit status */
3317 rcode = endmailer(mci, e, pv);
3319 rcode = EX_TEMPFAIL;
3320 if (rcode == EX_TEMPFAIL && SmtpError[0] == '\0')
3323 ** Need an e_message for mailq display.
3324 ** We set SmtpError as
3327 (void) sm_snprintf(SmtpError, sizeof(SmtpError),
3328 "%s mailer (%s) exited with EX_TEMPFAIL",
3329 m->m_name, m->m_mailer);
3335 ** Send the MAIL FROM: protocol
3338 /* XXX this isn't pipelined... */
3339 rcode = smtpmailfrom(m, mci, e);
3344 ADDRESS *volatile pchain;
3345 # endif /* PIPELINING */
3347 /* send the recipient list */
3349 mci->mci_retryrcpt = false;
3350 mci->mci_tolist = tobuf;
3353 mci->mci_nextaddr = NULL;
3354 # endif /* PIPELINING */
3356 for (to = tochain; to != NULL; to = to->q_tchain)
3358 if (!QS_IS_UNMARKED(to->q_state))
3361 /* mark recipient state as "ok so far" */
3362 to->q_state = QS_OK;
3363 e->e_to = to->q_paddr;
3365 i = rscheck("tls_rcpt", to->q_user, NULL, e,
3366 RSF_RMCOMM|RSF_COUNT, 3,
3367 mci->mci_host, e->e_id, NULL);
3370 markfailure(e, to, mci, i, false);
3371 giveresponse(i, to->q_status, m, mci,
3372 ctladdr, xstart, e, to);
3373 if (i == EX_TEMPFAIL)
3375 mci->mci_retryrcpt = true;
3376 to->q_state = QS_RETRY;
3380 # endif /* STARTTLS */
3382 i = smtprcpt(to, m, mci, e, ctladdr, xstart);
3385 bitset(MCIF_PIPELINED, mci->mci_flags))
3388 ** Add new element to list of
3389 ** recipients for pipelining.
3392 to->q_pchain = NULL;
3393 if (mci->mci_nextaddr == NULL)
3394 mci->mci_nextaddr = to;
3399 pchain->q_pchain = to;
3400 pchain = pchain->q_pchain;
3403 # endif /* PIPELINING */
3406 markfailure(e, to, mci, i, false);
3407 giveresponse(i, to->q_status, m, mci,
3408 ctladdr, xstart, e, to);
3409 if (i == EX_TEMPFAIL)
3410 to->q_state = QS_RETRY;
3414 /* No recipients in list and no missing responses? */
3415 if (tobuf[0] == '\0'
3417 && bitset(MCIF_PIPELINED, mci->mci_flags)
3418 && mci->mci_nextaddr == NULL
3419 # endif /* PIPELINING */
3424 if (bitset(MCIF_CACHED, mci->mci_flags))
3425 smtprset(m, mci, e);
3429 e->e_to = tobuf + 1;
3430 rcode = smtpdata(m, mci, e, ctladdr, xstart);
3433 if (rcode == EX_TEMPFAIL && nummxhosts > hostnum)
3435 /* try next MX site */
3440 if (ConfigLevel < 2)
3441 _res.options |= RES_DEFNAMES | RES_DNSRCH; /* XXX */
3442 #endif /* NAMED_BIND */
3445 checkfds("after delivery");
3448 ** Do final status disposal.
3449 ** We check for something in tobuf for the SMTP case.
3450 ** If we got a temporary failure, arrange to queue the
3455 if (bitnset(M_LMTP, m->m_flags))
3463 anyok = rcode == EX_OK;
3465 for (to = tochain; to != NULL; to = to->q_tchain)
3467 /* see if address already marked */
3468 if (!QS_IS_OK(to->q_state))
3471 /* if running LMTP, get the status for each address */
3472 if (bitnset(M_LMTP, m->m_flags))
3474 if (lmtp_rcode == EX_OK)
3475 rcode = smtpgetstat(m, mci, e);
3478 strsize += sm_strlcat2(tobuf + strsize, ",",
3480 tobufsize - strsize);
3481 SM_ASSERT(strsize < tobufsize);
3486 e->e_to = to->q_paddr;
3487 markfailure(e, to, mci, rcode, true);
3488 giveresponse(rcode, to->q_status, m, mci,
3489 ctladdr, xstart, e, to);
3490 e->e_to = tobuf + 1;
3496 /* mark bad addresses */
3499 if (goodmxfound && rcode == EX_NOHOST)
3500 rcode = EX_TEMPFAIL;
3501 markfailure(e, to, mci, rcode, true);
3506 /* successful delivery */
3507 to->q_state = QS_SENT;
3508 to->q_statdate = curtime();
3512 ** Checkpoint the send list every few addresses
3515 if (CheckpointInterval > 0 && e->e_nsent >= CheckpointInterval)
3517 queueup(e, false, false);
3521 if (bitnset(M_LOCALMAILER, m->m_flags) &&
3522 bitset(QPINGONSUCCESS, to->q_flags))
3524 to->q_flags |= QDELIVERED;
3525 to->q_status = "2.1.5";
3526 (void) sm_io_fprintf(e->e_xfp, SM_TIME_DEFAULT,
3527 "%s... Successfully delivered\n",
3530 else if (bitset(QPINGONSUCCESS, to->q_flags) &&
3531 bitset(QPRIMARY, to->q_flags) &&
3532 !bitset(MCIF_DSN, mci->mci_flags))
3534 to->q_flags |= QRELAYED;
3535 (void) sm_io_fprintf(e->e_xfp, SM_TIME_DEFAULT,
3536 "%s... relayed; expect no further notifications\n",
3539 else if (IS_DLVR_NOTIFY(e) &&
3540 !bitset(MCIF_DLVR_BY, mci->mci_flags) &&
3541 bitset(QPRIMARY, to->q_flags) &&
3542 (!bitset(QHASNOTIFY, to->q_flags) ||
3543 bitset(QPINGONSUCCESS, to->q_flags) ||
3544 bitset(QPINGONFAILURE, to->q_flags) ||
3545 bitset(QPINGONDELAY, to->q_flags)))
3547 /* RFC 2852, 4.1.4.2: no NOTIFY, or not NEVER */
3548 to->q_flags |= QBYNRELAY;
3549 (void) sm_io_fprintf(e->e_xfp, SM_TIME_DEFAULT,
3550 "%s... Deliver-by notify: relayed\n",
3553 else if (IS_DLVR_TRACE(e) &&
3554 (!bitset(QHASNOTIFY, to->q_flags) ||
3555 bitset(QPINGONSUCCESS, to->q_flags) ||
3556 bitset(QPINGONFAILURE, to->q_flags) ||
3557 bitset(QPINGONDELAY, to->q_flags)) &&
3558 bitset(QPRIMARY, to->q_flags))
3560 /* RFC 2852, 4.1.4: no NOTIFY, or not NEVER */
3561 to->q_flags |= QBYTRACE;
3562 (void) sm_io_fprintf(e->e_xfp, SM_TIME_DEFAULT,
3563 "%s... Deliver-By trace: relayed\n",
3568 if (bitnset(M_LMTP, m->m_flags))
3571 ** Global information applies to the last recipient only;
3572 ** clear it out to avoid bogus errors.
3576 e->e_statmsg = NULL;
3578 /* reset the mci state for the next transaction */
3580 (mci->mci_state == MCIS_MAIL ||
3581 mci->mci_state == MCIS_RCPT ||
3582 mci->mci_state == MCIS_DATA))
3584 mci->mci_state = MCIS_OPEN;
3585 SmtpPhase = mci->mci_phase = "idle";
3586 sm_setproctitle(true, e, "%s: %s", CurHostName,
3591 if (tobuf[0] != '\0')
3593 giveresponse(rcode, NULL, m, mci, ctladdr, xstart, e, tochain);
3596 ** This code is disabled for now because I am not
3597 ** sure that copying status from the first recipient
3598 ** to all non-status'ed recipients is a good idea.
3601 if (tochain->q_message != NULL &&
3602 !bitnset(M_LMTP, m->m_flags) && rcode != EX_OK)
3604 for (to = tochain->q_tchain; to != NULL;
3607 /* see if address already marked */
3608 if (QS_IS_QUEUEUP(to->q_state) &&
3609 to->q_message == NULL)
3610 to->q_message = sm_rpool_strdup_x(e->e_rpool,
3611 tochain->q_message);
3617 markstats(e, tochain, STATS_NORMAL);
3618 mci_store_persistent(mci);
3620 /* Some recipients were tempfailed, try them on the next host */
3621 if (mci != NULL && mci->mci_retryrcpt && nummxhosts > hostnum)
3623 /* try next MX site */
3627 /* now close the connection */
3628 if (clever && mci != NULL && mci->mci_state != MCIS_CLOSED &&
3629 !bitset(MCIF_CACHED, mci->mci_flags))
3630 smtpquit(m, mci, e);
3637 ** Restore state and return.
3642 /* make absolutely certain 0, 1, and 2 are in use */
3643 (void) sm_snprintf(wbuf, sizeof(wbuf),
3644 "%s... end of deliver(%s)",
3645 e->e_to == NULL ? "NO-TO-LIST"
3646 : shortenstring(e->e_to,
3655 ** It was originally necessary to set macro 'g' to NULL
3656 ** because it previously pointed to an auto buffer.
3657 ** We don't do this any more, so this may be unnecessary.
3660 macdefine(&e->e_macro, A_PERM, 'g', (char *) NULL);
3668 ** MARKFAILURE -- mark a failure on a specific address.
3671 ** e -- the envelope we are sending.
3672 ** q -- the address to mark.
3673 ** mci -- mailer connection information.
3674 ** rcode -- the code signifying the particular failure.
3675 ** ovr -- override an existing code?
3681 ** marks the address (and possibly the envelope) with the
3682 ** failure so that an error will be returned or
3683 ** the message will be queued, as appropriate.
3687 markfailure(e, q, mci, rcode, ovr)
3688 register ENVELOPE *e;
3689 register ADDRESS *q;
3694 int save_errno = errno;
3695 char *status = NULL;
3696 char *rstatus = NULL;
3706 q->q_state = QS_QUEUEUP;
3710 q->q_state = QS_BADADDR;
3714 /* find most specific error code possible */
3715 if (mci != NULL && mci->mci_status != NULL)
3717 status = sm_rpool_strdup_x(e->e_rpool, mci->mci_status);
3718 if (mci->mci_rstatus != NULL)
3719 rstatus = sm_rpool_strdup_x(e->e_rpool,
3724 else if (e->e_status != NULL)
3726 status = e->e_status;
3755 case EX_UNAVAILABLE:
3775 if (status != NULL && *status != '\0' && (ovr || q->q_status == NULL ||
3776 *q->q_status == '\0' || *q->q_status < *status))
3778 q->q_status = status;
3779 q->q_rstatus = rstatus;
3781 if (rcode != EX_OK && q->q_rstatus == NULL &&
3782 q->q_mailer != NULL && q->q_mailer->m_diagtype != NULL &&
3783 sm_strcasecmp(q->q_mailer->m_diagtype, "X-UNIX") == 0)
3787 (void) sm_snprintf(buf, sizeof(buf), "%d", rcode);
3788 q->q_rstatus = sm_rpool_strdup_x(e->e_rpool, buf);
3791 q->q_statdate = curtime();
3792 if (CurHostName != NULL && CurHostName[0] != '\0' &&
3793 mci != NULL && !bitset(M_LOCALMAILER, mci->mci_flags))
3794 q->q_statmta = sm_rpool_strdup_x(e->e_rpool, CurHostName);
3800 ** ENDMAILER -- Wait for mailer to terminate.
3802 ** We should never get fatal errors (e.g., segmentation
3803 ** violation), so we report those specially. For other
3804 ** errors, we choose a status message (into statmsg),
3805 ** and if it represents an error, we print it.
3808 ** mci -- the mailer connection info.
3809 ** e -- the current envelope.
3810 ** pv -- the parameter vector that invoked the mailer
3811 ** (for error messages).
3814 ** exit code of mailer.
3820 static jmp_buf EndWaitTimeout;
3823 endwaittimeout(ignore)
3827 ** NOTE: THIS CAN BE CALLED FROM A SIGNAL HANDLER. DO NOT ADD
3828 ** ANYTHING TO THIS ROUTINE UNLESS YOU KNOW WHAT YOU ARE
3833 longjmp(EndWaitTimeout, 1);
3837 endmailer(mci, e, pv)
3839 register ENVELOPE *e;
3843 int save_errno = errno;
3845 SM_EVENT *ev = NULL;
3848 mci_unlock_host(mci);
3850 /* close output to mailer */
3851 if (mci->mci_out != NULL)
3853 (void) sm_io_close(mci->mci_out, SM_TIME_DEFAULT);
3854 mci->mci_out = NULL;
3857 /* copy any remaining input to transcript */
3858 if (mci->mci_in != NULL && mci->mci_state != MCIS_ERROR &&
3861 while (sfgets(buf, sizeof(buf), mci->mci_in,
3862 TimeOuts.to_quit, "Draining Input") != NULL)
3863 (void) sm_io_fputs(e->e_xfp, SM_TIME_DEFAULT, buf);
3867 /* close SASL connection */
3868 if (bitset(MCIF_AUTHACT, mci->mci_flags))
3870 sasl_dispose(&mci->mci_conn);
3871 mci->mci_flags &= ~MCIF_AUTHACT;
3877 (void) endtlsclt(mci);
3878 #endif /* STARTTLS */
3880 /* now close the input */
3881 if (mci->mci_in != NULL)
3883 (void) sm_io_close(mci->mci_in, SM_TIME_DEFAULT);
3886 mci->mci_state = MCIS_CLOSED;
3890 /* in the IPC case there is nothing to wait for */
3891 if (mci->mci_pid == 0)
3894 /* put a timeout around the wait */
3895 if (mci->mci_mailer->m_wait > 0)
3897 if (setjmp(EndWaitTimeout) == 0)
3898 ev = sm_setevent(mci->mci_mailer->m_wait,
3902 syserr("endmailer %s: wait timeout (%ld)",
3903 mci->mci_mailer->m_name,
3904 (long) mci->mci_mailer->m_wait);
3909 /* wait for the mailer process, collect status */
3910 st = waitfor(mci->mci_pid);
3918 syserr("endmailer %s: wait", mci->mci_mailer->m_name);
3924 /* normal death -- return status */
3925 return (WEXITSTATUS(st));
3928 /* it died a horrid death */
3929 syserr("451 4.3.0 mailer %s died with signal %d%s",
3930 mci->mci_mailer->m_name, WTERMSIG(st),
3931 WCOREDUMP(st) ? " (core dumped)" :
3932 (WIFSTOPPED(st) ? " (stopped)" : ""));
3934 /* log the arguments */
3935 if (pv != NULL && e->e_xfp != NULL)
3939 (void) sm_io_fprintf(e->e_xfp, SM_TIME_DEFAULT, "Arguments:");
3940 for (av = pv; *av != NULL; av++)
3941 (void) sm_io_fprintf(e->e_xfp, SM_TIME_DEFAULT, " %s",
3943 (void) sm_io_fprintf(e->e_xfp, SM_TIME_DEFAULT, "\n");
3946 ExitStat = EX_TEMPFAIL;
3950 ** GIVERESPONSE -- Interpret an error response from a mailer
3953 ** status -- the status code from the mailer (high byte
3954 ** only; core dumps must have been taken care of
3956 ** dsn -- the DSN associated with the address, if any.
3957 ** m -- the mailer info for this mailer.
3958 ** mci -- the mailer connection info -- can be NULL if the
3959 ** response is given before the connection is made.
3960 ** ctladdr -- the controlling address for the recipient
3962 ** xstart -- the transaction start time, for computing
3963 ** transaction delays.
3964 ** e -- the current envelope.
3965 ** to -- the current recipient (NULL if none).
3971 ** Errors may be incremented.
3972 ** ExitStat may be set.
3976 giveresponse(status, dsn, m, mci, ctladdr, xstart, e, to)
3986 register const char *statmsg;
3989 bool usestat = false;
3990 char dsnbuf[ENHSCLEN];
3996 syserr("giveresponse: null envelope");
4002 ** Compute status message from code.
4005 exmsg = sm_sysexmsg(status);
4008 statmsg = "250 2.0.0 Sent";
4009 if (e->e_statmsg != NULL)
4011 (void) sm_snprintf(buf, sizeof(buf), "%s (%s)",
4013 shortenstring(e->e_statmsg, 403));
4017 else if (exmsg == NULL)
4019 (void) sm_snprintf(buf, sizeof(buf),
4020 "554 5.3.0 unknown mailer error %d",
4022 status = EX_UNAVAILABLE;
4026 else if (status == EX_TEMPFAIL)
4030 (void) sm_strlcpy(bp, exmsg + 1, SPACELEFT(buf, bp));
4033 if (h_errno == TRY_AGAIN)
4034 statmsg = sm_errstring(h_errno + E_DNSBASE);
4036 #endif /* NAMED_BIND */
4039 statmsg = sm_errstring(errnum);
4041 statmsg = SmtpError;
4043 if (statmsg != NULL && statmsg[0] != '\0')
4048 case ENETDOWN: /* Network is down */
4049 #endif /* ENETDOWN */
4051 case ENETUNREACH: /* Network is unreachable */
4052 #endif /* ENETUNREACH */
4054 case ENETRESET: /* Network dropped connection on reset */
4055 #endif /* ENETRESET */
4057 case ECONNABORTED: /* Software caused connection abort */
4058 #endif /* ECONNABORTED */
4060 case EHOSTDOWN: /* Host is down */
4061 #endif /* EHOSTDOWN */
4063 case EHOSTUNREACH: /* No route to host */
4064 #endif /* EHOSTUNREACH */
4065 if (mci != NULL && mci->mci_host != NULL)
4067 (void) sm_strlcpyn(bp,
4075 (void) sm_strlcpyn(bp, SPACELEFT(buf, bp), 2, ": ",
4082 else if (status == EX_NOHOST && h_errno != 0)
4084 statmsg = sm_errstring(h_errno + E_DNSBASE);
4085 (void) sm_snprintf(buf, sizeof(buf), "%s (%s)", exmsg + 1,
4090 #endif /* NAMED_BIND */
4094 if (*statmsg++ == ':' && errnum != 0)
4096 (void) sm_snprintf(buf, sizeof(buf), "%s: %s", statmsg,
4097 sm_errstring(errnum));
4101 else if (bitnset(M_LMTP, m->m_flags) && e->e_statmsg != NULL)
4103 (void) sm_snprintf(buf, sizeof(buf), "%s (%s)", statmsg,
4104 shortenstring(e->e_statmsg, 403));
4111 ** Print the message as appropriate
4114 if (status == EX_OK || status == EX_TEMPFAIL)
4116 extern char MsgBuf[];
4118 if ((off = isenhsc(statmsg + 4, ' ')) > 0)
4122 (void) sm_snprintf(dsnbuf, sizeof(dsnbuf),
4123 "%.*s", off, statmsg + 4);
4132 message("%s", statmsg + off);
4133 if (status == EX_TEMPFAIL && e->e_xfp != NULL)
4134 (void) sm_io_fprintf(e->e_xfp, SM_TIME_DEFAULT, "%s\n",
4139 char mbuf[ENHSCLEN + 4];
4142 if ((off = isenhsc(statmsg + 4, ' ')) > 0 &&
4143 off < sizeof(mbuf) - 4)
4147 (void) sm_snprintf(dsnbuf, sizeof(dsnbuf),
4148 "%.*s", off, statmsg + 4);
4153 /* copy only part of statmsg to mbuf */
4154 (void) sm_strlcpy(mbuf, statmsg, off);
4155 (void) sm_strlcat(mbuf, " %s", sizeof(mbuf));
4160 (void) sm_snprintf(mbuf, sizeof(mbuf), "%.3s %%s",
4164 usrerr(mbuf, &statmsg[off]);
4169 ** Log a record of the transaction. Compute the new
4170 ** ExitStat -- if we already had an error, stick with
4174 if (OpMode != MD_VERIFY && !bitset(EF_VRFYONLY, e->e_flags) &&
4175 LogLevel > ((status == EX_TEMPFAIL) ? 8 : (status == EX_OK) ? 7 : 6))
4176 logdelivery(m, mci, dsn, statmsg + off, ctladdr, xstart, e);
4179 sm_dprintf("giveresponse: status=%d, dsn=%s, e->e_message=%s, errnum=%d\n",
4181 dsn == NULL ? "<NULL>" : dsn,
4182 e->e_message == NULL ? "<NULL>" : e->e_message,
4185 if (status != EX_TEMPFAIL)
4187 if (status != EX_OK && (status != EX_TEMPFAIL || e->e_message == NULL))
4188 e->e_message = sm_rpool_strdup_x(e->e_rpool, statmsg + off);
4189 if (status != EX_OK && to != NULL && to->q_message == NULL)
4191 if (!usestat && e->e_message != NULL)
4192 to->q_message = sm_rpool_strdup_x(e->e_rpool,
4195 to->q_message = sm_rpool_strdup_x(e->e_rpool,
4202 ** LOGDELIVERY -- log the delivery in the system log
4204 ** Care is taken to avoid logging lines that are too long, because
4205 ** some versions of syslog have an unfortunate proclivity for core
4206 ** dumping. This is a hack, to be sure, that is at best empirical.
4209 ** m -- the mailer info. Can be NULL for initial queue.
4210 ** mci -- the mailer connection info -- can be NULL if the
4211 ** log is occurring when no connection is active.
4212 ** dsn -- the DSN attached to the status.
4213 ** status -- the message to print for the status.
4214 ** ctladdr -- the controlling address for the to list.
4215 ** xstart -- the transaction start time, used for
4216 ** computing transaction delay.
4217 ** e -- the current envelope.
4227 logdelivery(m, mci, dsn, status, ctladdr, xstart, e)
4234 register ENVELOPE *e;
4239 time_t now = curtime();
4242 #if (SYSLOG_BUFSIZE) >= 256
4243 /* ctladdr: max 106 bytes */
4245 if (ctladdr != NULL)
4247 (void) sm_strlcpyn(bp, SPACELEFT(buf, bp), 2, ", ctladdr=",
4248 shortenstring(ctladdr->q_paddr, 83));
4250 if (bitset(QGOODUID, ctladdr->q_flags))
4252 (void) sm_snprintf(bp, SPACELEFT(buf, bp), " (%d/%d)",
4253 (int) ctladdr->q_uid,
4254 (int) ctladdr->q_gid);
4259 /* delay & xdelay: max 41 bytes */
4260 (void) sm_strlcpyn(bp, SPACELEFT(buf, bp), 2, ", delay=",
4261 pintvl(now - e->e_ctime, true));
4264 if (xstart != (time_t) 0)
4266 (void) sm_strlcpyn(bp, SPACELEFT(buf, bp), 2, ", xdelay=",
4267 pintvl(now - xstart, true));
4271 /* mailer: assume about 19 bytes (max 10 byte mailer name) */
4274 (void) sm_strlcpyn(bp, SPACELEFT(buf, bp), 2, ", mailer=",
4279 /* pri: changes with each delivery attempt */
4280 (void) sm_snprintf(bp, SPACELEFT(buf, bp), ", pri=%ld",
4281 PRT_NONNEGL(e->e_msgpriority));
4284 /* relay: max 66 bytes for IPv4 addresses */
4285 if (mci != NULL && mci->mci_host != NULL)
4287 extern SOCKADDR CurHostAddr;
4289 (void) sm_strlcpyn(bp, SPACELEFT(buf, bp), 2, ", relay=",
4290 shortenstring(mci->mci_host, 40));
4293 if (CurHostAddr.sa.sa_family != 0)
4295 (void) sm_snprintf(bp, SPACELEFT(buf, bp), " [%s]",
4296 anynet_ntoa(&CurHostAddr));
4299 else if (strcmp(status, "quarantined") == 0)
4301 if (e->e_quarmsg != NULL)
4302 (void) sm_snprintf(bp, SPACELEFT(buf, bp),
4304 shortenstring(e->e_quarmsg, 40));
4306 else if (strcmp(status, "queued") != 0)
4308 p = macvalue('h', e);
4309 if (p != NULL && p[0] != '\0')
4311 (void) sm_snprintf(bp, SPACELEFT(buf, bp),
4312 ", relay=%s", shortenstring(p, 40));
4318 if (dsn != NULL && *dsn != '\0')
4320 (void) sm_strlcpyn(bp, SPACELEFT(buf, bp), 2, ", dsn=",
4321 shortenstring(dsn, ENHSCLEN));
4327 if (e->e_ntries >= 0)
4329 (void) sm_snprintf(bp, SPACELEFT(buf, bp),
4330 ", ntries=%d", e->e_ntries + 1);
4333 #endif /* _FFR_LOG_NTRIES */
4335 # define STATLEN (((SYSLOG_BUFSIZE) - 100) / 4)
4339 # endif /* (STATLEN) < 63 */
4340 # if (STATLEN) > 203
4342 # define STATLEN 203
4343 # endif /* (STATLEN) > 203 */
4345 /* stat: max 210 bytes */
4346 if ((bp - buf) > (sizeof(buf) - ((STATLEN) + 20)))
4348 /* desperation move -- truncate data */
4349 bp = buf + sizeof(buf) - ((STATLEN) + 17);
4350 (void) sm_strlcpy(bp, "...", SPACELEFT(buf, bp));
4354 (void) sm_strlcpy(bp, ", stat=", SPACELEFT(buf, bp));
4357 (void) sm_strlcpy(bp, shortenstring(status, STATLEN),
4358 SPACELEFT(buf, bp));
4360 /* id, to: max 13 + TOBUFSIZE bytes */
4361 l = SYSLOG_BUFSIZE - 100 - strlen(buf);
4364 p = e->e_to == NULL ? "NO-TO-LIST" : e->e_to;
4365 while (strlen(p) >= l)
4369 for (q = p + l; q > p; q--)
4376 sm_syslog(LOG_INFO, e->e_id, "to=%.*s [more]%s",
4377 (int) (++q - p), p, buf);
4380 sm_syslog(LOG_INFO, e->e_id, "to=%.*s%s", l, p, buf);
4382 #else /* (SYSLOG_BUFSIZE) >= 256 */
4384 l = SYSLOG_BUFSIZE - 85;
4387 p = e->e_to == NULL ? "NO-TO-LIST" : e->e_to;
4388 while (strlen(p) >= l)
4392 for (q = p + l; q > p; q--)
4400 sm_syslog(LOG_INFO, e->e_id, "to=%.*s [more]",
4401 (int) (++q - p), p);
4404 sm_syslog(LOG_INFO, e->e_id, "to=%.*s", l, p);
4406 if (ctladdr != NULL)
4409 (void) sm_strlcpyn(bp, SPACELEFT(buf, bp), 2, "ctladdr=",
4410 shortenstring(ctladdr->q_paddr, 83));
4412 if (bitset(QGOODUID, ctladdr->q_flags))
4414 (void) sm_snprintf(bp, SPACELEFT(buf, bp), " (%d/%d)",
4415 ctladdr->q_uid, ctladdr->q_gid);
4418 sm_syslog(LOG_INFO, e->e_id, "%s", buf);
4421 (void) sm_strlcpyn(bp, SPACELEFT(buf, bp), 2, "delay=",
4422 pintvl(now - e->e_ctime, true));
4424 if (xstart != (time_t) 0)
4426 (void) sm_strlcpyn(bp, SPACELEFT(buf, bp), 2, ", xdelay=",
4427 pintvl(now - xstart, true));
4433 (void) sm_strlcpyn(bp, SPACELEFT(buf, bp), 2, ", mailer=",
4437 sm_syslog(LOG_INFO, e->e_id, "%.1000s", buf);
4441 if (mci != NULL && mci->mci_host != NULL)
4443 extern SOCKADDR CurHostAddr;
4445 (void) sm_snprintf(bp, SPACELEFT(buf, bp), "relay=%.100s",
4449 if (CurHostAddr.sa.sa_family != 0)
4450 (void) sm_snprintf(bp, SPACELEFT(buf, bp),
4452 anynet_ntoa(&CurHostAddr));
4454 else if (strcmp(status, "quarantined") == 0)
4456 if (e->e_quarmsg != NULL)
4457 (void) sm_snprintf(bp, SPACELEFT(buf, bp),
4458 ", quarantine=%.100s",
4461 else if (strcmp(status, "queued") != 0)
4463 p = macvalue('h', e);
4464 if (p != NULL && p[0] != '\0')
4465 (void) sm_snprintf(buf, sizeof(buf), "relay=%.100s", p);
4468 sm_syslog(LOG_INFO, e->e_id, "%.1000s", buf);
4470 sm_syslog(LOG_INFO, e->e_id, "stat=%s", shortenstring(status, 63));
4471 #endif /* (SYSLOG_BUFSIZE) >= 256 */
4474 ** PUTFROMLINE -- output a UNIX-style from line (or whatever)
4476 ** This can be made an arbitrary message separator by changing $l
4478 ** One of the ugliest hacks seen by human eyes is contained herein:
4479 ** UUCP wants those stupid "remote from <host>" lines. Why oh why
4480 ** does a well-meaning programmer such as myself have to deal with
4481 ** this kind of antique garbage????
4484 ** mci -- the connection information.
4485 ** e -- the envelope.
4488 ** true iff line was written successfully
4491 ** outputs some text to fp.
4499 char *template = UnixFromLine;
4503 if (bitnset(M_NHDR, mci->mci_mailer->m_flags))
4506 mci->mci_flags |= MCIF_INHEADER;
4508 if (bitnset(M_UGLYUUCP, mci->mci_mailer->m_flags))
4512 expand("\201g", buf, sizeof(buf), e);
4513 bang = strchr(buf, '!');
4517 char hname[MAXNAME];
4520 ** If we can construct a UUCP path, do so
4523 at = strrchr(buf, '@');
4526 expand("\201k", hname, sizeof(hname), e);
4531 (void) sm_snprintf(xbuf, sizeof(xbuf),
4532 "From %.800s \201d remote from %.100s\n",
4538 (void) sm_snprintf(xbuf, sizeof(xbuf),
4539 "From %.800s \201d remote from %.100s\n",
4544 expand(template, buf, sizeof(buf), e);
4545 return putxline(buf, strlen(buf), mci, PXLF_HEADER);
4549 ** PUTBODY -- put the body of a message.
4552 ** mci -- the connection information.
4553 ** e -- the envelope to put out.
4554 ** separator -- if non-NULL, a message separator that must
4555 ** not be permitted in the resulting message.
4558 ** true iff message was written successfully
4561 ** The message is written onto fp.
4564 /* values for output state variable */
4565 #define OSTATE_HEAD 0 /* at beginning of line */
4566 #define OSTATE_CR 1 /* read a carriage return */
4567 #define OSTATE_INLINE 2 /* putting rest of line */
4570 putbody(mci, e, separator)
4572 register ENVELOPE *e;
4580 char *boundaries[MAXMIMENESTING + 1];
4581 #endif /* MIME8TO7 */
4584 ** Output the body of the message
4587 if (e->e_dfp == NULL && bitset(EF_HAS_DF, e->e_flags))
4589 char *df = queuename(e, DATAFL_LETTER);
4591 e->e_dfp = sm_io_open(SmFtStdio, SM_TIME_DEFAULT, df,
4592 SM_IO_RDONLY_B, NULL);
4593 if (e->e_dfp == NULL)
4595 char *msg = "!putbody: Cannot open %s for %s from %s";
4597 if (errno == ENOENT)
4599 syserr(msg, df, e->e_to, e->e_from.q_paddr);
4603 if (e->e_dfp == NULL)
4605 if (bitset(MCIF_INHEADER, mci->mci_flags))
4607 if (!putline("", mci))
4609 mci->mci_flags &= ~MCIF_INHEADER;
4611 if (!putline("<<< No Message Collected >>>", mci))
4616 if (e->e_dfino == (ino_t) 0)
4620 if (fstat(sm_io_getinfo(e->e_dfp, SM_IO_WHAT_FD, NULL), &stbuf)
4625 e->e_dfdev = stbuf.st_dev;
4626 e->e_dfino = stbuf.st_ino;
4630 /* paranoia: the data file should always be in a rewound state */
4631 (void) bfrewind(e->e_dfp);
4633 /* simulate an I/O timeout when used as source */
4638 if (bitset(MCIF_CVT8TO7, mci->mci_flags))
4641 ** Do 8 to 7 bit MIME conversion.
4644 /* make sure it looks like a MIME message */
4645 if (hvalue("MIME-Version", e->e_header) == NULL &&
4646 !putline("MIME-Version: 1.0", mci))
4649 if (hvalue("Content-Type", e->e_header) == NULL)
4651 (void) sm_snprintf(buf, sizeof(buf),
4652 "Content-Type: text/plain; charset=%s",
4654 if (!putline(buf, mci))
4658 /* now do the hard work */
4659 boundaries[0] = NULL;
4660 mci->mci_flags |= MCIF_INHEADER;
4661 if (mime8to7(mci, e->e_header, e, boundaries, M87F_OUTER, 0) ==
4666 else if (bitset(MCIF_CVT7TO8, mci->mci_flags))
4668 if (!mime7to8(mci, e->e_header, e))
4671 # endif /* MIME7TO8 */
4672 else if (MaxMimeHeaderLength > 0 || MaxMimeFieldLength > 0)
4674 bool oldsuprerrs = SuprErrs;
4676 /* Use mime8to7 to check multipart for MIME header overflows */
4677 boundaries[0] = NULL;
4678 mci->mci_flags |= MCIF_INHEADER;
4681 ** If EF_DONT_MIME is set, we have a broken MIME message
4682 ** and don't want to generate a new bounce message whose
4683 ** body propagates the broken MIME. We can't just not call
4684 ** mime8to7() as is done above since we need the security
4685 ** checks. The best we can do is suppress the errors.
4688 if (bitset(EF_DONT_MIME, e->e_flags))
4691 if (mime8to7(mci, e->e_header, e, boundaries,
4692 M87F_OUTER|M87F_NO8TO7, 0) == SM_IO_EOF)
4695 /* restore SuprErrs */
4696 SuprErrs = oldsuprerrs;
4699 #endif /* MIME8TO7 */
4711 if (bitset(MCIF_INHEADER, mci->mci_flags))
4713 if (!putline("", mci))
4715 mci->mci_flags &= ~MCIF_INHEADER;
4718 /* determine end of buffer; allow for short mailer lines */
4719 buflim = &buf[sizeof(buf) - 1];
4720 if (mci->mci_mailer->m_linelimit > 0 &&
4721 mci->mci_mailer->m_linelimit < sizeof(buf) - 1)
4722 buflim = &buf[mci->mci_mailer->m_linelimit - 1];
4724 /* copy temp file to output with mapping */
4725 ostate = OSTATE_HEAD;
4728 while (!sm_io_error(mci->mci_out) && !dead)
4732 else if ((c = sm_io_getc(e->e_dfp, SM_TIME_DEFAULT))
4735 if (bitset(MCIF_7BIT, mci->mci_flags))
4742 mci->mci_mailer->m_flags))
4744 if (c != '\r' && c != '\n' && bp < buflim)
4750 /* check beginning of line for special cases */
4754 if (buf[0] == 'F' &&
4755 bitnset(M_ESCFROM, mci->mci_mailer->m_flags)
4756 && strncmp(buf, "From ", 5) == 0)
4760 if (buf[0] == '-' && buf[1] == '-' &&
4763 /* possible separator */
4764 int sl = strlen(separator);
4766 if (strncmp(&buf[2], separator, sl)
4770 if (buf[0] == '.' &&
4771 bitnset(M_XDOT, mci->mci_mailer->m_flags))
4776 /* now copy out saved line */
4777 if (TrafficLogFile != NULL)
4779 (void) sm_io_fprintf(TrafficLogFile,
4783 if (padc != SM_IO_EOF)
4784 (void) sm_io_putc(TrafficLogFile,
4787 for (xp = buf; xp < bp; xp++)
4788 (void) sm_io_putc(TrafficLogFile,
4790 (unsigned char) *xp);
4792 (void) sm_io_fputs(TrafficLogFile,
4794 mci->mci_mailer->m_eol);
4796 if (padc != SM_IO_EOF)
4798 if (sm_io_putc(mci->mci_out,
4799 SM_TIME_DEFAULT, padc)
4807 for (xp = buf; xp < bp; xp++)
4809 if (sm_io_putc(mci->mci_out,
4811 (unsigned char) *xp)
4822 if (sm_io_fputs(mci->mci_out,
4824 mci->mci_mailer->m_eol)
4834 SM_ASSERT(pbp < peekbuf +
4842 /* determine next state */
4844 ostate = OSTATE_HEAD;
4848 ostate = OSTATE_INLINE;
4855 if (sm_io_fputs(mci->mci_out,
4857 mci->mci_mailer->m_eol)
4861 if (TrafficLogFile != NULL)
4863 (void) sm_io_fputs(TrafficLogFile,
4865 mci->mci_mailer->m_eol);
4868 ostate = OSTATE_HEAD;
4872 /* had a naked carriage return */
4873 SM_ASSERT(pbp < peekbuf + sizeof(peekbuf));
4876 ostate = OSTATE_INLINE;
4887 mci->mci_mailer->m_flags))
4890 if (mci->mci_mailer->m_linelimit > 0 &&
4891 pos >= mci->mci_mailer->m_linelimit - 1 &&
4896 /* check next character for EOL */
4899 else if ((d = sm_io_getc(e->e_dfp,
4903 SM_ASSERT(pbp < peekbuf +
4908 if (d == '\n' || d == SM_IO_EOF)
4910 if (TrafficLogFile != NULL)
4911 (void) sm_io_putc(TrafficLogFile,
4914 if (sm_io_putc(mci->mci_out,
4926 if (sm_io_putc(mci->mci_out,
4927 SM_TIME_DEFAULT, '!')
4929 sm_io_fputs(mci->mci_out,
4931 mci->mci_mailer->m_eol)
4938 if (TrafficLogFile != NULL)
4940 (void) sm_io_fprintf(TrafficLogFile,
4943 mci->mci_mailer->m_eol);
4945 ostate = OSTATE_HEAD;
4946 SM_ASSERT(pbp < peekbuf +
4953 if (TrafficLogFile != NULL)
4954 (void) sm_io_fputs(TrafficLogFile,
4956 mci->mci_mailer->m_eol);
4957 if (sm_io_fputs(mci->mci_out,
4959 mci->mci_mailer->m_eol)
4963 ostate = OSTATE_HEAD;
4967 if (TrafficLogFile != NULL)
4968 (void) sm_io_putc(TrafficLogFile,
4971 if (sm_io_putc(mci->mci_out,
4980 ostate = OSTATE_INLINE;
4986 /* make sure we are at the beginning of a line */
4989 if (TrafficLogFile != NULL)
4991 for (xp = buf; xp < bp; xp++)
4992 (void) sm_io_putc(TrafficLogFile,
4994 (unsigned char) *xp);
4996 for (xp = buf; xp < bp; xp++)
4998 if (sm_io_putc(mci->mci_out, SM_TIME_DEFAULT,
4999 (unsigned char) *xp)
5008 if (!dead && pos > 0)
5010 if (TrafficLogFile != NULL)
5011 (void) sm_io_fputs(TrafficLogFile,
5013 mci->mci_mailer->m_eol);
5014 if (sm_io_fputs(mci->mci_out, SM_TIME_DEFAULT,
5015 mci->mci_mailer->m_eol) == SM_IO_EOF)
5020 if (sm_io_error(e->e_dfp))
5022 syserr("putbody: %s/%cf%s: read error",
5023 qid_printqueue(e->e_dfqgrp, e->e_dfqdir),
5024 DATAFL_LETTER, e->e_id);
5025 ExitStat = EX_IOERR;
5031 ** Since mailfile() uses e_dfp in a child process,
5032 ** the file offset in the stdio library for the
5033 ** parent process will not agree with the in-kernel
5034 ** file offset since the file descriptor is shared
5035 ** between the processes. Therefore, it is vital
5036 ** that the file always be rewound. This forces the
5037 ** kernel offset (lseek) and stdio library (ftell)
5042 if (e->e_dfp != NULL)
5043 (void) bfrewind(e->e_dfp);
5045 /* some mailers want extra blank line at end of message */
5046 if (!dead && bitnset(M_BLANKEND, mci->mci_mailer->m_flags) &&
5047 buf[0] != '\0' && buf[0] != '\n')
5049 if (!putline("", mci))
5054 (sm_io_flush(mci->mci_out, SM_TIME_DEFAULT) == SM_IO_EOF ||
5055 (sm_io_error(mci->mci_out) && errno != EPIPE)))
5058 syserr("putbody: write error");
5059 ExitStat = EX_IOERR;
5064 return !dead && !ioerr;
5071 ** MAILFILE -- Send a message to a file.
5073 ** If the file has the set-user-ID/set-group-ID bits set, but NO
5074 ** execute bits, sendmail will try to become the owner of that file
5075 ** rather than the real user. Obviously, this only works if
5076 ** sendmail runs as root.
5078 ** This could be done as a subordinate mailer, except that it
5079 ** is used implicitly to save messages in ~/dead.letter. We
5080 ** view this as being sufficiently important as to include it
5081 ** here. For example, if the system is dying, we shouldn't have
5082 ** to create another process plus some pipes to save the message.
5085 ** filename -- the name of the file to send to.
5086 ** mailer -- mailer definition for recipient -- if NULL,
5088 ** ctladdr -- the controlling address header -- includes
5089 ** the userid/groupid to be when sending.
5090 ** sfflags -- flags for opening.
5091 ** e -- the current envelope.
5094 ** The exit code associated with the operation.
5100 # define RETURN(st) exit(st);
5102 static jmp_buf CtxMailfileTimeout;
5105 mailfile(filename, mailer, ctladdr, sfflags, e)
5106 char *volatile filename;
5107 MAILER *volatile mailer;
5109 volatile long sfflags;
5110 register ENVELOPE *e;
5112 register SM_FILE_T *f;
5113 register pid_t pid = -1;
5117 bool suidwarn = geteuid() == 0;
5119 char *volatile realfile;
5121 char buf[MAXPATHLEN];
5122 char targetfile[MAXPATHLEN];
5126 sm_dprintf("mailfile %s\n ctladdr=", filename);
5127 printaddr(sm_debug_file(), ctladdr, false);
5131 mailer = FileMailer;
5133 if (e->e_xfp != NULL)
5134 (void) sm_io_flush(e->e_xfp, SM_TIME_DEFAULT);
5137 ** Special case /dev/null. This allows us to restrict file
5138 ** delivery to regular files only.
5141 if (sm_path_isdevnull(filename))
5144 /* check for 8-bit available */
5145 if (bitset(EF_HAS8BIT, e->e_flags) &&
5146 bitnset(M_7BITS, mailer->m_flags) &&
5147 (bitset(EF_DONT_MIME, e->e_flags) ||
5148 !(bitset(MM_MIME8BIT, MimeMode) ||
5149 (bitset(EF_IS_MIME, e->e_flags) &&
5150 bitset(MM_CVTMIME, MimeMode)))))
5152 e->e_status = "5.6.3";
5153 usrerrenh(e->e_status,
5154 "554 Cannot send 8-bit data to 7-bit destination");
5159 /* Find the actual file */
5160 if (SafeFileEnv != NULL && SafeFileEnv[0] != '\0')
5162 len = strlen(SafeFileEnv);
5164 if (strncmp(SafeFileEnv, filename, len) == 0)
5167 if (len + strlen(filename) + 1 >= sizeof(targetfile))
5169 syserr("mailfile: filename too long (%s/%s)",
5170 SafeFileEnv, filename);
5171 return EX_CANTCREAT;
5173 (void) sm_strlcpy(targetfile, SafeFileEnv, sizeof(targetfile));
5174 realfile = targetfile + len;
5175 if (*filename == '/')
5177 if (*filename != '\0')
5179 /* paranoia: trailing / should be removed in readcf */
5180 if (targetfile[len - 1] != '/')
5181 (void) sm_strlcat(targetfile,
5182 "/", sizeof(targetfile));
5183 (void) sm_strlcat(targetfile, filename,
5184 sizeof(targetfile));
5187 else if (mailer->m_rootdir != NULL)
5189 expand(mailer->m_rootdir, targetfile, sizeof(targetfile), e);
5190 len = strlen(targetfile);
5192 if (strncmp(targetfile, filename, len) == 0)
5195 if (len + strlen(filename) + 1 >= sizeof(targetfile))
5197 syserr("mailfile: filename too long (%s/%s)",
5198 targetfile, filename);
5199 return EX_CANTCREAT;
5201 realfile = targetfile + len;
5202 if (targetfile[len - 1] != '/')
5203 (void) sm_strlcat(targetfile, "/", sizeof(targetfile));
5204 if (*filename == '/')
5205 (void) sm_strlcat(targetfile, filename + 1,
5206 sizeof(targetfile));
5208 (void) sm_strlcat(targetfile, filename,
5209 sizeof(targetfile));
5213 if (sm_strlcpy(targetfile, filename, sizeof(targetfile)) >=
5216 syserr("mailfile: filename too long (%s)", filename);
5217 return EX_CANTCREAT;
5219 realfile = targetfile;
5223 ** Fork so we can change permissions here.
5224 ** Note that we MUST use fork, not vfork, because of
5225 ** the complications of calling subroutines, etc.
5230 ** Dispose of SIGCHLD signal catchers that may be laying
5231 ** around so that the waitfor() below will get it.
5234 (void) sm_signal(SIGCHLD, SIG_DFL);
5242 /* child -- actually write to file */
5246 volatile int oflags = O_WRONLY|O_APPEND;
5248 /* Reset global flags */
5249 RestartRequest = NULL;
5250 RestartWorkGroup = false;
5251 ShutdownRequest = NULL;
5253 CurrentPid = getpid();
5255 if (e->e_lockfp != NULL)
5259 fd = sm_io_getinfo(e->e_lockfp, SM_IO_WHAT_FD, NULL);
5260 /* SM_ASSERT(fd >= 0); */
5265 (void) sm_signal(SIGINT, SIG_DFL);
5266 (void) sm_signal(SIGHUP, SIG_DFL);
5267 (void) sm_signal(SIGTERM, SIG_DFL);
5268 (void) umask(OldUmask);
5272 if (setjmp(CtxMailfileTimeout) != 0)
5274 RETURN(EX_TEMPFAIL);
5277 if (TimeOuts.to_fileopen > 0)
5278 ev = sm_setevent(TimeOuts.to_fileopen, mailfiletimeout,
5283 /* check file mode to see if set-user-ID */
5284 if (stat(targetfile, &stb) < 0)
5289 /* limit the errors to those actually caused in the child */
5293 /* Allow alias expansions to use the S_IS{U,G}ID bits */
5294 if ((ctladdr != NULL && !bitset(QALIAS, ctladdr->q_flags)) ||
5295 bitset(SFF_RUNASREALUID, sfflags))
5297 /* ignore set-user-ID and set-group-ID bits */
5298 mode &= ~(S_ISGID|S_ISUID);
5300 sm_dprintf("mailfile: ignoring set-user-ID/set-group-ID bits\n");
5303 /* we have to open the data file BEFORE setuid() */
5304 if (e->e_dfp == NULL && bitset(EF_HAS_DF, e->e_flags))
5306 char *df = queuename(e, DATAFL_LETTER);
5308 e->e_dfp = sm_io_open(SmFtStdio, SM_TIME_DEFAULT, df,
5309 SM_IO_RDONLY_B, NULL);
5310 if (e->e_dfp == NULL)
5312 syserr("mailfile: Cannot open %s for %s from %s",
5313 df, e->e_to, e->e_from.q_paddr);
5317 /* select a new user to run as */
5318 if (!bitset(SFF_RUNASREALUID, sfflags))
5320 if (bitnset(M_SPECIFIC_UID, mailer->m_flags))
5322 RealUserName = NULL;
5323 if (mailer->m_uid == NO_UID)
5326 RealUid = mailer->m_uid;
5327 if (RunAsUid != 0 && RealUid != RunAsUid)
5329 /* Only root can change the uid */
5330 syserr("mailfile: insufficient privileges to change uid, RunAsUid=%d, RealUid=%d",
5331 (int) RunAsUid, (int) RealUid);
5332 RETURN(EX_TEMPFAIL);
5335 else if (bitset(S_ISUID, mode))
5337 RealUserName = NULL;
5338 RealUid = stb.st_uid;
5340 else if (ctladdr != NULL && ctladdr->q_uid != 0)
5342 if (ctladdr->q_ruser != NULL)
5343 RealUserName = ctladdr->q_ruser;
5345 RealUserName = ctladdr->q_user;
5346 RealUid = ctladdr->q_uid;
5348 else if (mailer != NULL && mailer->m_uid != NO_UID)
5350 RealUserName = DefUser;
5351 RealUid = mailer->m_uid;
5355 RealUserName = DefUser;
5359 /* select a new group to run as */
5360 if (bitnset(M_SPECIFIC_UID, mailer->m_flags))
5362 if (mailer->m_gid == NO_GID)
5365 RealGid = mailer->m_gid;
5366 if (RunAsUid != 0 &&
5367 (RealGid != getgid() ||
5368 RealGid != getegid()))
5370 /* Only root can change the gid */
5371 syserr("mailfile: insufficient privileges to change gid, RealGid=%d, RunAsUid=%d, gid=%d, egid=%d",
5372 (int) RealGid, (int) RunAsUid,
5373 (int) getgid(), (int) getegid());
5374 RETURN(EX_TEMPFAIL);
5377 else if (bitset(S_ISGID, mode))
5378 RealGid = stb.st_gid;
5379 else if (ctladdr != NULL &&
5380 ctladdr->q_uid == DefUid &&
5381 ctladdr->q_gid == 0)
5384 ** Special case: This means it is an
5385 ** alias and we should act as DefaultUser.
5386 ** See alias()'s comments.
5390 RealUserName = DefUser;
5392 else if (ctladdr != NULL && ctladdr->q_uid != 0)
5393 RealGid = ctladdr->q_gid;
5394 else if (mailer != NULL && mailer->m_gid != NO_GID)
5395 RealGid = mailer->m_gid;
5401 if (!bitset(SFF_ROOTOK, sfflags))
5409 /* set group id list (needs /etc/group access) */
5410 if (RealUserName != NULL && !DontInitGroups)
5412 if (initgroups(RealUserName, RealGid) == -1 && suidwarn)
5414 syserr("mailfile: initgroups(%s, %d) failed",
5415 RealUserName, RealGid);
5416 RETURN(EX_TEMPFAIL);
5423 gidset[0] = RealGid;
5424 if (setgroups(1, gidset) == -1 && suidwarn)
5426 syserr("mailfile: setgroups() failed");
5427 RETURN(EX_TEMPFAIL);
5432 ** If you have a safe environment, go into it.
5435 if (realfile != targetfile)
5442 sm_dprintf("mailfile: chroot %s\n", targetfile);
5443 if (chroot(targetfile) < 0)
5445 syserr("mailfile: Cannot chroot(%s)",
5447 RETURN(EX_CANTCREAT);
5453 sm_dprintf("mailfile: deliver to %s\n", realfile);
5457 syserr("mailfile: cannot chdir(/)");
5458 RETURN(EX_CANTCREAT);
5461 /* now reset the group and user ids */
5463 sm_mbdb_terminate();
5464 if (setgid(RealGid) < 0 && suidwarn)
5466 syserr("mailfile: setgid(%ld) failed", (long) RealGid);
5467 RETURN(EX_TEMPFAIL);
5469 vendor_set_uid(RealUid);
5470 if (setuid(RealUid) < 0 && suidwarn)
5472 syserr("mailfile: setuid(%ld) failed", (long) RealUid);
5473 RETURN(EX_TEMPFAIL);
5477 sm_dprintf("mailfile: running as r/euid=%d/%d, r/egid=%d/%d\n",
5478 (int) getuid(), (int) geteuid(),
5479 (int) getgid(), (int) getegid());
5482 /* move into some "safe" directory */
5483 if (mailer->m_execdir != NULL)
5487 for (p = mailer->m_execdir; p != NULL; p = q)
5492 expand(p, buf, sizeof(buf), e);
5496 sm_dprintf("mailfile: trydir %s\n",
5498 if (buf[0] != '\0' && chdir(buf) >= 0)
5504 ** Recheck the file after we have assumed the ID of the
5505 ** delivery user to make sure we can deliver to it as
5506 ** that user. This is necessary if sendmail is running
5507 ** as root and the file is on an NFS mount which treats
5512 if (bitnset(DBS_FILEDELIVERYTOSYMLINK, DontBlameSendmail))
5513 err = stat(realfile, &stb);
5515 err = lstat(realfile, &stb);
5516 #else /* HASLSTAT */
5517 err = stat(realfile, &stb);
5518 #endif /* HASLSTAT */
5522 stb.st_mode = ST_MODE_NOFILE;
5524 oflags |= O_CREAT|O_EXCL;
5526 else if (bitset(S_IXUSR|S_IXGRP|S_IXOTH, mode) ||
5527 (!bitnset(DBS_FILEDELIVERYTOHARDLINK,
5528 DontBlameSendmail) &&
5529 stb.st_nlink != 1) ||
5530 (realfile != targetfile && !S_ISREG(mode)))
5535 if (!bitnset(DBS_FILEDELIVERYTOSYMLINK, DontBlameSendmail))
5536 sfflags |= SFF_NOSLINK;
5537 if (!bitnset(DBS_FILEDELIVERYTOHARDLINK, DontBlameSendmail))
5538 sfflags |= SFF_NOHLINK;
5539 sfflags &= ~SFF_OPENASROOT;
5540 f = safefopen(realfile, oflags, mode, sfflags);
5543 if (transienterror(errno))
5545 usrerr("454 4.3.0 cannot open %s: %s",
5546 shortenstring(realfile, MAXSHORTSTR),
5547 sm_errstring(errno));
5548 RETURN(EX_TEMPFAIL);
5552 usrerr("554 5.3.0 cannot open %s: %s",
5553 shortenstring(realfile, MAXSHORTSTR),
5554 sm_errstring(errno));
5555 RETURN(EX_CANTCREAT);
5558 if (filechanged(realfile, sm_io_getinfo(f, SM_IO_WHAT_FD, NULL),
5561 syserr("554 5.3.0 file changed after open");
5562 RETURN(EX_CANTCREAT);
5564 if (fstat(sm_io_getinfo(f, SM_IO_WHAT_FD, NULL), &stb) < 0)
5566 syserr("554 5.3.0 cannot fstat %s",
5567 sm_errstring(errno));
5568 RETURN(EX_CANTCREAT);
5571 curoff = stb.st_size;
5576 memset(&mcibuf, '\0', sizeof(mcibuf));
5577 mcibuf.mci_mailer = mailer;
5579 if (bitnset(M_7BITS, mailer->m_flags))
5580 mcibuf.mci_flags |= MCIF_7BIT;
5582 /* clear out per-message flags from connection structure */
5583 mcibuf.mci_flags &= ~(MCIF_CVT7TO8|MCIF_CVT8TO7);
5585 if (bitset(EF_HAS8BIT, e->e_flags) &&
5586 !bitset(EF_DONT_MIME, e->e_flags) &&
5587 bitnset(M_7BITS, mailer->m_flags))
5588 mcibuf.mci_flags |= MCIF_CVT8TO7;
5591 if (bitnset(M_MAKE8BIT, mailer->m_flags) &&
5592 !bitset(MCIF_7BIT, mcibuf.mci_flags) &&
5593 (p = hvalue("Content-Transfer-Encoding", e->e_header)) != NULL &&
5594 (sm_strcasecmp(p, "quoted-printable") == 0 ||
5595 sm_strcasecmp(p, "base64") == 0) &&
5596 (p = hvalue("Content-Type", e->e_header)) != NULL)
5598 /* may want to convert 7 -> 8 */
5599 /* XXX should really parse it here -- and use a class XXX */
5600 if (sm_strncasecmp(p, "text/plain", 10) == 0 &&
5601 (p[10] == '\0' || p[10] == ' ' || p[10] == ';'))
5602 mcibuf.mci_flags |= MCIF_CVT7TO8;
5604 #endif /* MIME7TO8 */
5606 if (!putfromline(&mcibuf, e) ||
5607 !(*e->e_puthdr)(&mcibuf, e->e_header, e, M87F_OUTER) ||
5608 !(*e->e_putbody)(&mcibuf, e, NULL) ||
5609 !putline("\n", &mcibuf) ||
5610 (sm_io_flush(f, SM_TIME_DEFAULT) != 0 ||
5611 (SuperSafe != SAFE_NO &&
5612 fsync(sm_io_getinfo(f, SM_IO_WHAT_FD, NULL)) < 0) ||
5617 (void) ftruncate(sm_io_getinfo(f, SM_IO_WHAT_FD, NULL),
5619 #endif /* !NOFTRUNCATE */
5622 /* reset ISUID & ISGID bits for paranoid systems */
5624 (void) fchmod(sm_io_getinfo(f, SM_IO_WHAT_FD, NULL),
5626 #else /* HASFCHMOD */
5627 (void) chmod(filename, (MODE_T) mode);
5628 #endif /* HASFCHMOD */
5629 if (sm_io_close(f, SM_TIME_DEFAULT) < 0)
5631 (void) sm_io_flush(smioout, SM_TIME_DEFAULT);
5632 (void) setuid(RealUid);
5638 /* parent -- wait for exit status */
5644 syserr("mailfile: %s: wait", mailer->m_name);
5650 return (WEXITSTATUS(st));
5654 syserr("mailfile: %s: child died on signal %d",
5655 mailer->m_name, st);
5656 return EX_UNAVAILABLE;
5660 return EX_UNAVAILABLE; /* avoid compiler warning on IRIX */
5664 mailfiletimeout(ignore)
5668 ** NOTE: THIS CAN BE CALLED FROM A SIGNAL HANDLER. DO NOT ADD
5669 ** ANYTHING TO THIS ROUTINE UNLESS YOU KNOW WHAT YOU ARE
5674 longjmp(CtxMailfileTimeout, 1);
5677 ** HOSTSIGNATURE -- return the "signature" for a host.
5679 ** The signature describes how we are going to send this -- it
5680 ** can be just the hostname (for non-Internet hosts) or can be
5681 ** an ordered list of MX hosts.
5684 ** m -- the mailer describing this host.
5685 ** host -- the host name.
5688 ** The signature for this host.
5691 ** Can tweak the symbol table.
5694 #define MAXHOSTSIGNATURE 8192 /* max len of hostsignature */
5697 hostsignature(m, host)
5713 int oldoptions = _res.options;
5714 char *mxhosts[MAXMXHOSTS + 1];
5715 unsigned short mxprefs[MAXMXHOSTS + 1];
5716 #endif /* NAMED_BIND */
5719 sm_dprintf("hostsignature(%s)\n", host);
5722 ** If local delivery (and not remote), just return a constant.
5725 if (bitnset(M_LOCALMAILER, m->m_flags) &&
5726 strcmp(m->m_mailer, "[IPC]") != 0 &&
5727 !(m->m_argv[0] != NULL && strcmp(m->m_argv[0], "TCP") == 0))
5730 /* an empty host does not have MX records */
5735 ** Check to see if this uses IPC -- if not, it can't have MX records.
5738 if (strcmp(m->m_mailer, "[IPC]") != 0 ||
5739 CurEnv->e_sendmode == SM_DEFER)
5741 /* just an ordinary mailer or deferred mode */
5745 else if (m->m_argv[0] != NULL &&
5746 strcmp(m->m_argv[0], "FILE") == 0)
5748 /* rendezvous in the file system, no MX records */
5751 #endif /* NETUNIX */
5754 ** Look it up in the symbol table.
5758 s = stab(host, ST_HOSTSIG, ST_ENTER);
5759 if (s->s_hostsig.hs_sig != NULL)
5761 if (s->s_hostsig.hs_exp >= now)
5764 sm_dprintf("hostsignature(): stab(%s) found %s\n", host,
5765 s->s_hostsig.hs_sig);
5766 return s->s_hostsig.hs_sig;
5769 /* signature is expired: clear it */
5770 sm_free(s->s_hostsig.hs_sig);
5771 s->s_hostsig.hs_sig = NULL;
5774 /* set default TTL */
5775 s->s_hostsig.hs_exp = now + SM_DEFAULT_TTL;
5778 ** Not already there or expired -- create a signature.
5782 if (ConfigLevel < 2)
5783 _res.options &= ~(RES_DEFNAMES | RES_DNSRCH); /* XXX */
5785 for (hp = host; hp != NULL; hp = endp)
5790 endp = strchr(hp + 1, ']');
5792 endp = strpbrk(endp + 1, ":,");
5795 endp = strpbrk(hp, ":,");
5796 #else /* NETINET6 */
5797 endp = strpbrk(hp, ":,");
5798 #endif /* NETINET6 */
5805 if (bitnset(M_NOMX, m->m_flags))
5807 /* skip MX lookups */
5816 nmx = getmxrr(hp, mxhosts, mxprefs, true, &rcode, true,
5823 /* update the connection info for this host */
5825 mci = mci_get(hp, m);
5826 mci->mci_errno = save_errno;
5827 mci->mci_herrno = h_errno;
5828 mci->mci_lastuse = now;
5829 if (rcode == EX_NOHOST)
5830 mci_setstat(mci, rcode, "5.1.2",
5831 "550 Host unknown");
5833 mci_setstat(mci, rcode, NULL, NULL);
5835 /* use the original host name as signature */
5840 sm_dprintf("hostsignature(): getmxrr() returned %d, mxhosts[0]=%s\n",
5844 ** Set new TTL: we use only one!
5845 ** We could try to use the minimum instead.
5848 s->s_hostsig.hs_exp = now + SM_MIN(ttl, SM_DEFAULT_TTL);
5852 for (i = 0; i < nmx; i++)
5853 len += strlen(mxhosts[i]) + 1;
5854 if (s->s_hostsig.hs_sig != NULL)
5855 len += strlen(s->s_hostsig.hs_sig) + 1;
5856 if (len < 0 || len >= MAXHOSTSIGNATURE)
5858 sm_syslog(LOG_WARNING, NOQID, "hostsignature for host '%s' exceeds maxlen (%d): %d",
5859 host, MAXHOSTSIGNATURE, len);
5860 len = MAXHOSTSIGNATURE;
5862 p = sm_pmalloc_x(len);
5863 if (s->s_hostsig.hs_sig != NULL)
5865 (void) sm_strlcpy(p, s->s_hostsig.hs_sig, len);
5866 sm_free(s->s_hostsig.hs_sig); /* XXX */
5867 s->s_hostsig.hs_sig = p;
5874 s->s_hostsig.hs_sig = p;
5875 for (i = 0; i < nmx; i++)
5877 hl = strlen(mxhosts[i]);
5878 if (len - 1 < hl || len <= 1)
5880 /* force to drop out of outer loop */
5886 if (mxprefs[i] == mxprefs[i - 1])
5892 (void) sm_strlcpy(p, mxhosts[i], len);
5898 ** break out of loop if len exceeded MAXHOSTSIGNATURE
5899 ** because we won't have more space for further hosts
5900 ** anyway (separated by : in the .cf file).
5909 makelower(s->s_hostsig.hs_sig);
5910 if (ConfigLevel < 2)
5911 _res.options = oldoptions;
5912 #else /* NAMED_BIND */
5913 /* not using BIND -- the signature is just the host name */
5915 ** 'host' points to storage that will be freed after we are
5916 ** done processing the current envelope, so we copy it.
5918 s->s_hostsig.hs_sig = sm_pstrdup_x(host);
5919 #endif /* NAMED_BIND */
5921 sm_dprintf("hostsignature(%s) = %s\n", host, s->s_hostsig.hs_sig);
5922 return s->s_hostsig.hs_sig;
5925 ** PARSE_HOSTSIGNATURE -- parse the "signature" and return MX host array.
5927 ** The signature describes how we are going to send this -- it
5928 ** can be just the hostname (for non-Internet hosts) or can be
5929 ** an ordered list of MX hosts which must be randomized for equal
5930 ** MX preference values.
5933 ** sig -- the host signature.
5934 ** mxhosts -- array to populate.
5935 ** mailer -- mailer.
5938 ** The number of hosts inserted into mxhosts array.
5941 ** Randomizes equal MX preference hosts in mxhosts.
5945 parse_hostsignature(sig, mxhosts, mailer)
5950 unsigned short curpref = 0;
5951 int nmx = 0, i, j; /* NOTE: i, j, and nmx must have same type */
5953 unsigned short prefer[MAXMXHOSTS];
5954 long rndm[MAXMXHOSTS];
5956 for (hp = sig; hp != NULL; hp = endp)
5963 endp = strchr(hp + 1, ']');
5965 endp = strpbrk(endp + 1, ":,");
5968 endp = strpbrk(hp, ":,");
5969 #else /* NETINET6 */
5970 endp = strpbrk(hp, ":,");
5971 #endif /* NETINET6 */
5979 prefer[nmx] = curpref;
5980 if (mci_match(hp, mailer))
5983 rndm[nmx] = get_random();
5988 ** Since we don't have the original MX prefs,
5989 ** make our own. If the separator is a ':', that
5990 ** means the preference for the next host will be
5991 ** higher than this one, so simply increment curpref.
5999 if (++nmx >= MAXMXHOSTS)
6003 /* sort the records using the random factor for equal preferences */
6004 for (i = 0; i < nmx; i++)
6006 for (j = i + 1; j < nmx; j++)
6009 ** List is already sorted by MX preference, only
6010 ** need to look for equal preference MX records
6013 if (prefer[i] < prefer[j])
6016 if (prefer[i] > prefer[j] ||
6017 (prefer[i] == prefer[j] && rndm[i] > rndm[j]))
6019 register unsigned short tempp;
6020 register long tempr;
6021 register char *temp1;
6024 prefer[i] = prefer[j];
6027 mxhosts[i] = mxhosts[j];
6039 static SSL_CTX *clt_ctx = NULL;
6040 static bool tls_ok_clt = true;
6043 ** SETCLTTLS -- client side TLS: allow/disallow.
6046 ** tls_ok -- should tls be done?
6052 ** sets tls_ok_clt (static variable in this module)
6059 tls_ok_clt = tls_ok;
6063 ** INITCLTTLS -- initialize client side TLS
6066 ** tls_ok -- should tls initialization be done?
6072 ** sets tls_ok_clt (static variable in this module)
6081 tls_ok_clt = tls_ok;
6084 if (clt_ctx != NULL)
6085 return true; /* already done */
6086 tls_ok_clt = inittls(&clt_ctx, TLS_I_CLT, Clt_SSL_Options, false,
6087 CltCertFile, CltKeyFile,
6088 CACertPath, CACertFile, DHParams);
6093 ** STARTTLS -- try to start secure connection (client side)
6097 ** mci -- the mailer connection info.
6098 ** e -- the envelope.
6102 ** (maybe this should be some other code than EX_
6103 ** that denotes which stage failed.)
6115 SSL *clt_ssl = NULL;
6118 if (clt_ctx == NULL && !initclttls(true))
6121 # if USE_OPENSSL_ENGINE
6122 if (!SSLEngineInitialized && !SSL_set_engine(NULL))
6124 sm_syslog(LOG_ERR, NOQID,
6125 "STARTTLS=client, SSL_set_engine=failed");
6128 SSLEngineInitialized = true;
6129 # endif /* USE_OPENSSL_ENGINE */
6131 smtpmessage("STARTTLS", m, mci);
6134 smtpresult = reply(m, mci, e, TimeOuts.to_starttls, NULL, NULL,
6137 /* check return code from server */
6138 if (REPLYTYPE(smtpresult) == 4)
6140 if (smtpresult == 501)
6142 if (smtpresult == -1)
6145 /* not an expected reply but we have to deal with it */
6146 if (REPLYTYPE(smtpresult) == 5)
6147 return EX_UNAVAILABLE;
6148 if (smtpresult != 220)
6152 sm_syslog(LOG_INFO, NOQID, "STARTTLS=client, start=ok");
6154 /* start connection */
6155 if ((clt_ssl = SSL_new(clt_ctx)) == NULL)
6159 sm_syslog(LOG_ERR, NOQID,
6160 "STARTTLS=client, error: SSL_new failed");
6162 tlslogerr(LOG_WARNING, "client");
6167 rfd = sm_io_getinfo(mci->mci_in, SM_IO_WHAT_FD, NULL);
6168 wfd = sm_io_getinfo(mci->mci_out, SM_IO_WHAT_FD, NULL);
6170 /* SSL_clear(clt_ssl); ? */
6171 if (rfd < 0 || wfd < 0 ||
6172 (result = SSL_set_rfd(clt_ssl, rfd)) != 1 ||
6173 (result = SSL_set_wfd(clt_ssl, wfd)) != 1)
6177 sm_syslog(LOG_ERR, NOQID,
6178 "STARTTLS=client, error: SSL_set_xfd failed=%d",
6181 tlslogerr(LOG_WARNING, "client");
6185 SSL_set_connect_state(clt_ssl);
6186 tlsstart = curtime();
6189 if ((result = SSL_connect(clt_ssl)) <= 0)
6193 ssl_err = SSL_get_error(clt_ssl, result);
6194 i = tls_retry(clt_ssl, rfd, wfd, tlsstart,
6195 TimeOuts.to_starttls, ssl_err, "client");
6204 l = ERR_peek_error();
6205 sr = ERR_reason_error_string(l);
6206 sm_syslog(LOG_WARNING, NOQID,
6207 "STARTTLS=client, error: connect failed=%d, reason=%s, SSL_error=%d, errno=%d, retry=%d",
6208 result, sr == NULL ? "unknown" : sr, ssl_err,
6211 tlslogerr(LOG_WARNING, "client");
6218 mci->mci_ssl = clt_ssl;
6219 result = tls_get_info(mci->mci_ssl, false, mci->mci_host,
6220 &mci->mci_macro, true);
6222 /* switch to use TLS... */
6223 if (sfdctls(&mci->mci_in, &mci->mci_out, mci->mci_ssl) == 0)
6232 ** ENDTLSCLT -- shutdown secure connection (client side)
6235 ** mci -- the mailer connection info.
6247 if (!bitset(MCIF_TLSACT, mci->mci_flags))
6249 r = endtls(mci->mci_ssl, "client");
6250 mci->mci_flags &= ~MCIF_TLSACT;
6253 # endif /* STARTTLS */
6254 # if STARTTLS || SASL
6256 ** ISCLTFLGSET -- check whether client flag is set.
6260 ** flag -- flag to check in {client_flags}
6263 ** true iff flag is set.
6267 iscltflgset(e, flag)
6273 p = macvalue(macid("{client_flags}"), e);
6276 for (; *p != '\0'; p++)
6278 /* look for just this one flag */
6279 if (*p == (char) flag)
6284 # endif /* STARTTLS || SASL */