1 /*************************************************
2 * Exim - an Internet mail transport agent *
3 *************************************************/
5 /* Copyright (c) The Exim Maintainers 2020 - 2024 */
6 /* Copyright (c) University of Cambridge 1995 - 2018 */
7 /* See the file NOTICE for conditions of use and distribution. */
8 /* SPDX-License-Identifier: GPL-2.0-or-later */
13 #if defined(SUPPORT_DANE) && defined(DISABLE_TLS)
14 # error TLS is required for DANE
18 /* Options specific to the smtp transport. This transport also supports LMTP
19 over TCP/IP. The options must be in alphabetic order (note that "_" comes
20 before the lower case letters). Some live in the transport_instance block so as
21 to be publicly visible; these are flagged with opt_public. */
23 #define LOFF(field) OPT_OFF(smtp_transport_options_block, field)
25 optionlist smtp_transport_options[] = {
26 { "*expand_multi_domain", opt_stringptr | opt_hidden | opt_public,
27 OPT_OFF(transport_instance, expand_multi_domain) },
28 { "*expand_retry_include_ip_address", opt_stringptr | opt_hidden,
29 LOFF(expand_retry_include_ip_address) },
31 { "address_retry_include_sender", opt_bool,
32 LOFF(address_retry_include_sender) },
33 { "allow_localhost", opt_bool, LOFF(allow_localhost) },
34 #ifdef EXPERIMENTAL_ARC
35 { "arc_sign", opt_stringptr, LOFF(arc_sign) },
37 { "authenticated_sender", opt_stringptr, LOFF(authenticated_sender) },
38 { "authenticated_sender_force", opt_bool, LOFF(authenticated_sender_force) },
39 { "command_timeout", opt_time, LOFF(command_timeout) },
40 { "connect_timeout", opt_time, LOFF(connect_timeout) },
41 { "connection_max_messages", opt_int | opt_public,
42 OPT_OFF(transport_instance, connection_max_messages) },
44 { "dane_require_tls_ciphers", opt_stringptr, LOFF(dane_require_tls_ciphers) },
46 { "data_timeout", opt_time, LOFF(data_timeout) },
47 { "delay_after_cutoff", opt_bool, LOFF(delay_after_cutoff) },
49 { "dkim_canon", opt_stringptr, LOFF(dkim.dkim_canon) },
50 { "dkim_domain", opt_stringptr, LOFF(dkim.dkim_domain) },
51 { "dkim_hash", opt_stringptr, LOFF(dkim.dkim_hash) },
52 { "dkim_identity", opt_stringptr, LOFF(dkim.dkim_identity) },
53 { "dkim_private_key", opt_stringptr, LOFF(dkim.dkim_private_key) },
54 { "dkim_selector", opt_stringptr, LOFF(dkim.dkim_selector) },
55 { "dkim_sign_headers", opt_stringptr, LOFF(dkim.dkim_sign_headers) },
56 { "dkim_strict", opt_stringptr, LOFF(dkim.dkim_strict) },
57 { "dkim_timestamps", opt_stringptr, LOFF(dkim.dkim_timestamps) },
59 { "dns_qualify_single", opt_bool, LOFF(dns_qualify_single) },
60 { "dns_search_parents", opt_bool, LOFF(dns_search_parents) },
61 { "dnssec_request_domains", opt_stringptr, LOFF(dnssec.request) },
62 { "dnssec_require_domains", opt_stringptr, LOFF(dnssec.require) },
63 { "dscp", opt_stringptr, LOFF(dscp) },
64 { "fallback_hosts", opt_stringptr, LOFF(fallback_hosts) },
65 { "final_timeout", opt_time, LOFF(final_timeout) },
66 { "gethostbyname", opt_bool, LOFF(gethostbyname) },
67 { "helo_data", opt_stringptr, LOFF(helo_data) },
68 #if !defined(DISABLE_TLS) && !defined(DISABLE_TLS_RESUME)
69 { "host_name_extract", opt_stringptr, LOFF(host_name_extract) },
71 { "hosts", opt_stringptr, LOFF(hosts) },
72 { "hosts_avoid_esmtp", opt_stringptr, LOFF(hosts_avoid_esmtp) },
73 { "hosts_avoid_pipelining", opt_stringptr, LOFF(hosts_avoid_pipelining) },
75 { "hosts_avoid_tls", opt_stringptr, LOFF(hosts_avoid_tls) },
77 { "hosts_max_try", opt_int, LOFF(hosts_max_try) },
78 { "hosts_max_try_hardlimit", opt_int, LOFF(hosts_max_try_hardlimit) },
80 { "hosts_nopass_tls", opt_stringptr, LOFF(hosts_nopass_tls) },
81 { "hosts_noproxy_tls", opt_stringptr, LOFF(hosts_noproxy_tls) },
83 { "hosts_override", opt_bool, LOFF(hosts_override) },
84 #ifndef DISABLE_PIPE_CONNECT
85 { "hosts_pipe_connect", opt_stringptr, LOFF(hosts_pipe_connect) },
87 { "hosts_randomize", opt_bool, LOFF(hosts_randomize) },
88 #if !defined(DISABLE_TLS) && !defined(DISABLE_OCSP)
89 { "hosts_request_ocsp", opt_stringptr, LOFF(hosts_request_ocsp) },
91 { "hosts_require_alpn", opt_stringptr, LOFF(hosts_require_alpn) },
92 { "hosts_require_auth", opt_stringptr, LOFF(hosts_require_auth) },
95 { "hosts_require_dane", opt_stringptr, LOFF(hosts_require_dane) },
98 { "hosts_require_ocsp", opt_stringptr, LOFF(hosts_require_ocsp) },
100 { "hosts_require_tls", opt_stringptr, LOFF(hosts_require_tls) },
102 { "hosts_try_auth", opt_stringptr, LOFF(hosts_try_auth) },
103 { "hosts_try_chunking", opt_stringptr, LOFF(hosts_try_chunking) },
105 { "hosts_try_dane", opt_stringptr, LOFF(hosts_try_dane) },
107 { "hosts_try_fastopen", opt_stringptr, LOFF(hosts_try_fastopen) },
109 { "hosts_try_prdr", opt_stringptr, LOFF(hosts_try_prdr) },
112 { "hosts_verify_avoid_tls", opt_stringptr, LOFF(hosts_verify_avoid_tls) },
114 { "interface", opt_stringptr, LOFF(interface) },
115 { "keepalive", opt_bool, LOFF(keepalive) },
116 { "lmtp_ignore_quota", opt_bool, LOFF(lmtp_ignore_quota) },
117 { "max_rcpt", opt_stringptr | opt_public,
118 OPT_OFF(transport_instance, max_addresses) },
119 { "message_linelength_limit", opt_int, LOFF(message_linelength_limit) },
120 { "multi_domain", opt_expand_bool | opt_public,
121 OPT_OFF(transport_instance, multi_domain) },
122 { "port", opt_stringptr, LOFF(port) },
123 { "protocol", opt_stringptr, LOFF(protocol) },
124 { "retry_include_ip_address", opt_expand_bool, LOFF(retry_include_ip_address) },
125 { "serialize_hosts", opt_stringptr, LOFF(serialize_hosts) },
126 { "size_addition", opt_int, LOFF(size_addition) },
128 { "socks_proxy", opt_stringptr, LOFF(socks_proxy) },
131 { "tls_alpn", opt_stringptr, LOFF(tls_alpn) },
132 { "tls_certificate", opt_stringptr, LOFF(tls_certificate) },
133 { "tls_crl", opt_stringptr, LOFF(tls_crl) },
134 { "tls_dh_min_bits", opt_int, LOFF(tls_dh_min_bits) },
135 { "tls_privatekey", opt_stringptr, LOFF(tls_privatekey) },
136 { "tls_require_ciphers", opt_stringptr, LOFF(tls_require_ciphers) },
137 # ifndef DISABLE_TLS_RESUME
138 { "tls_resumption_hosts", opt_stringptr, LOFF(tls_resumption_hosts) },
140 { "tls_sni", opt_stringptr, LOFF(tls_sni) },
141 { "tls_tempfail_tryclear", opt_bool, LOFF(tls_tempfail_tryclear) },
142 { "tls_try_verify_hosts", opt_stringptr, LOFF(tls_try_verify_hosts) },
143 { "tls_verify_cert_hostnames", opt_stringptr, LOFF(tls_verify_cert_hostnames)},
144 { "tls_verify_certificates", opt_stringptr, LOFF(tls_verify_certificates) },
145 { "tls_verify_hosts", opt_stringptr, LOFF(tls_verify_hosts) },
148 { "utf8_downconvert", opt_stringptr, LOFF(utf8_downconvert) },
152 /* Size of the options list. An extern variable has to be used so that its
153 address can appear in the tables drtables.c. */
155 int smtp_transport_options_count = nelem(smtp_transport_options);
161 smtp_transport_options_block smtp_transport_option_defaults = {0};
162 void smtp_transport_init(transport_instance *tblock) {}
163 BOOL smtp_transport_entry(transport_instance *tblock, address_item *addr) {return FALSE;}
164 void smtp_transport_closedown(transport_instance *tblock) {}
166 #else /*!MACRO_PREDEF*/
169 /* Default private options block for the smtp transport. */
171 smtp_transport_options_block smtp_transport_option_defaults = {
172 /* All non-mentioned elements 0/NULL/FALSE */
173 .helo_data = US"$primary_hostname",
174 .protocol = US"smtp",
175 .hosts_try_chunking = US"*",
177 .hosts_try_dane = US"*",
179 .hosts_try_fastopen = US"*",
181 .hosts_try_prdr = US"*",
184 .hosts_request_ocsp = US"*", /* hosts_request_ocsp (except under DANE; tls_client_start()) */
186 .command_timeout = 5*60,
187 .connect_timeout = 5*60,
188 .data_timeout = 5*60,
189 .final_timeout = 10*60,
190 .size_addition = 1024,
192 .hosts_max_try_hardlimit = 50,
193 .message_linelength_limit = 998,
194 .address_retry_include_sender = TRUE,
195 .dns_qualify_single = TRUE,
196 .dnssec = { .request= US"*", .require=NULL },
197 .delay_after_cutoff = TRUE,
199 .retry_include_ip_address = TRUE,
201 .tls_verify_certificates = US"system",
202 .tls_dh_min_bits = EXIM_CLIENT_DH_DEFAULT_MIN_BITS,
203 .tls_tempfail_tryclear = TRUE,
204 .tls_try_verify_hosts = US"*",
205 .tls_verify_cert_hostnames = US"*",
208 .utf8_downconvert = US"-1",
212 { .dkim_hash = US"sha256", },
216 /* some DSN flags for use later */
218 static int rf_list[] = {rf_notify_never, rf_notify_success,
219 rf_notify_failure, rf_notify_delay };
221 static uschar *rf_names[] = { US"NEVER", US"SUCCESS", US"FAILURE", US"DELAY" };
227 static uschar *smtp_command; /* Points to last cmd for error messages */
228 static uschar *mail_command; /* Points to MAIL cmd for error messages */
229 static uschar *data_command = US""; /* Points to DATA cmd for error messages */
230 static BOOL update_waiting; /* TRUE to update the "wait" database */
232 /*XXX move to smtp_context */
233 static BOOL pipelining_active; /* current transaction is in pipe mode */
236 static unsigned ehlo_response(uschar * buf, unsigned checks);
238 /* sync_responses() return codes */
240 #define RESP_BIT_HAD_5XX BIT(1)
241 #define RESP_BIT_HAD_2XX BIT(0)
242 #define RESP_HAD_2_AND_5 (RESP_BIT_HAD_2XX | RESP_BIT_HAD_5XX)
243 #define RESP_NOERROR 0
244 #define RESP_RCPT_TIMEO -1
245 #define RESP_RCPT_ERROR -2
246 #define RESP_MAIL_OR_DATA_ERROR -3
247 #define RESP_EPIPE_EHLO_ERR -4
248 #define RESP_EHLO_ERR_TLS -5
250 /******************************************************************************/
253 smtp_deliver_init(void)
257 const pcre2_code ** re;
258 const uschar * string;
261 { ®ex_AUTH, AUTHS_REGEX },
262 { ®ex_CHUNKING, US"\\n250[\\s\\-]CHUNKING(\\s|\\n|$)" },
263 { ®ex_DSN, US"\\n250[\\s\\-]DSN(\\s|\\n|$)" },
264 { ®ex_IGNOREQUOTA, US"\\n250[\\s\\-]IGNOREQUOTA(\\s|\\n|$)" },
265 { ®ex_PIPELINING, US"\\n250[\\s\\-]PIPELINING(\\s|\\n|$)" },
266 { ®ex_SIZE, US"\\n250[\\s\\-]SIZE(\\s|\\n|$)" },
269 { ®ex_STARTTLS, US"\\n250[\\s\\-]STARTTLS(\\s|\\n|$)" },
272 { ®ex_PRDR, US"\\n250[\\s\\-]PRDR(\\s|\\n|$)" },
275 { ®ex_UTF8, US"\\n250[\\s\\-]SMTPUTF8(\\s|\\n|$)" },
277 #ifndef DISABLE_PIPE_CONNECT
278 { ®ex_EARLY_PIPE, US"\\n250[\\s\\-]" EARLY_PIPE_FEATURE_NAME "(\\s|\\n|$)" },
280 #ifndef DISABLE_ESMTP_LIMITS
281 { ®ex_LIMITS, US"\\n250[\\s\\-]LIMITS\\s" },
285 for (struct list * l = list; l < list + nelem(list); l++)
287 *l->re = regex_must_compile(l->string, MCS_NOFLAGS, TRUE);
291 /*************************************************
292 * Setup entry point *
293 *************************************************/
295 /* This function is called when the transport is about to be used,
296 but before running it in a sub-process. It is used for two things:
298 (1) To set the fallback host list in addresses, when delivering.
299 (2) To pass back the interface, port, protocol, and other options, for use
300 during callout verification.
303 tblock pointer to the transport instance block
304 addrlist list of addresses about to be transported
305 tf if not NULL, pointer to block in which to return options
306 uid the uid that will be set (not used)
307 gid the gid that will be set (not used)
308 errmsg place for error message (not used)
310 Returns: OK always (FAIL, DEFER not used)
314 smtp_transport_setup(transport_instance *tblock, address_item *addrlist,
315 transport_feedback *tf, uid_t uid, gid_t gid, uschar **errmsg)
317 smtp_transport_options_block *ob = SOB tblock->options_block;
319 /* Pass back options if required. This interface is getting very messy. */
323 tf->interface = ob->interface;
325 tf->protocol = ob->protocol;
326 tf->hosts = ob->hosts;
327 tf->hosts_override = ob->hosts_override;
328 tf->hosts_randomize = ob->hosts_randomize;
329 tf->gethostbyname = ob->gethostbyname;
330 tf->qualify_single = ob->dns_qualify_single;
331 tf->search_parents = ob->dns_search_parents;
332 tf->helo_data = ob->helo_data;
335 /* Set the fallback host list for all the addresses that don't have fallback
336 host lists, provided that the local host wasn't present in the original host
339 if (!testflag(addrlist, af_local_host_removed))
340 for (; addrlist; addrlist = addrlist->next)
341 if (!addrlist->fallback_hosts) addrlist->fallback_hosts = ob->fallback_hostlist;
348 /*************************************************
349 * Initialization entry point *
350 *************************************************/
352 /* Called for each instance, after its options have been read, to
353 enable consistency checks to be done, or anything else that needs
356 Argument: pointer to the transport instance block
361 smtp_transport_init(transport_instance *tblock)
363 smtp_transport_options_block * ob = SOB tblock->options_block;
364 int old_pool = store_pool;
366 /* Retry_use_local_part defaults FALSE if unset */
368 if (tblock->retry_use_local_part == TRUE_UNSET)
369 tblock->retry_use_local_part = FALSE;
371 /* Set the default port according to the protocol */
374 ob->port = strcmpic(ob->protocol, US"lmtp") == 0
376 : strcmpic(ob->protocol, US"smtps") == 0
377 ? US"smtps" : US"smtp";
379 /* Set up the setup entry point, to be called before subprocesses for this
382 tblock->setup = smtp_transport_setup;
384 /* Complain if any of the timeouts are zero. */
386 if (ob->command_timeout <= 0 || ob->data_timeout <= 0 ||
387 ob->final_timeout <= 0)
388 log_write(0, LOG_PANIC_DIE|LOG_CONFIG,
389 "command, data, or final timeout value is zero for %s transport",
392 /* If hosts_override is set and there are local hosts, set the global
393 flag that stops verify from showing router hosts. */
395 if (ob->hosts_override && ob->hosts) tblock->overrides_hosts = TRUE;
397 /* If there are any fallback hosts listed, build a chain of host items
398 for them, but do not do any lookups at this time. */
400 store_pool = POOL_PERM;
401 host_build_hostlist(&ob->fallback_hostlist, ob->fallback_hosts, FALSE);
402 store_pool = old_pool;
409 /*************************************************
410 * Set delivery info into all active addresses *
411 *************************************************/
413 /* Only addresses whose status is >= PENDING are relevant. A lesser
414 status means that an address is not currently being processed.
417 addrlist points to a chain of addresses
418 errno_value to put in each address's errno field
419 msg to put in each address's message field
420 rc to put in each address's transport_return field
421 pass_message if TRUE, set the "pass message" flag in the address
422 host if set, mark addrs as having used this host
423 smtp_greeting from peer
424 helo_response from peer
425 start points to timestamp of delivery start
427 If errno_value has the special value ERRNO_CONNECTTIMEOUT, ETIMEDOUT is put in
428 the errno field, and RTEF_CTOUT is ORed into the more_errno field, to indicate
429 this particular type of timeout.
435 set_errno(address_item *addrlist, int errno_value, uschar *msg, int rc,
436 BOOL pass_message, host_item * host,
437 #ifdef EXPERIMENTAL_DSN_INFO
438 const uschar * smtp_greeting, const uschar * helo_response,
440 struct timeval * start
444 struct timeval deliver_time;
446 if (errno_value == ERRNO_CONNECTTIMEOUT)
448 errno_value = ETIMEDOUT;
449 orvalue = RTEF_CTOUT;
451 timesince(&deliver_time, start);
453 for (address_item * addr = addrlist; addr; addr = addr->next)
454 if (addr->transport_return >= PENDING)
456 addr->basic_errno = errno_value;
457 addr->more_errno |= orvalue;
458 addr->delivery_time = deliver_time;
462 if (pass_message) setflag(addr, af_pass_message);
464 addr->transport_return = rc;
467 addr->host_used = host;
468 if (continue_sequence > 1)
469 { clearflag(addr, af_new_conn); setflag(addr, af_cont_conn); }
471 { clearflag(addr, af_cont_conn); setflag(addr, af_new_conn); }
472 #ifdef EXPERIMENTAL_DSN_INFO
474 {uschar * s = Ustrchr(smtp_greeting, '\n'); if (s) *s = '\0';}
475 addr->smtp_greeting = smtp_greeting;
478 {uschar * s = Ustrchr(helo_response, '\n'); if (s) *s = '\0';}
479 addr->helo_response = helo_response;
486 set_errno_nohost(address_item * addrlist, int errno_value, uschar * msg, int rc,
487 BOOL pass_message, struct timeval * start)
489 set_errno(addrlist, errno_value, msg, rc, pass_message, NULL,
490 #ifdef EXPERIMENTAL_DSN_INFO
497 /*************************************************
498 * Check an SMTP response *
499 *************************************************/
501 /* This function is given an errno code and the SMTP response buffer
502 to analyse, together with the host identification for generating messages. It
503 sets an appropriate message and puts the first digit of the response code into
504 the yield variable. If no response was actually read, a suitable digit is
508 host the current host, to get its name for messages
509 errno_value pointer to the errno value
510 more_errno from the top address for use with ERRNO_FILTER_FAIL
511 buffer the SMTP response buffer
512 yield where to put a one-digit SMTP response code
513 message where to put an error message
514 pass_message set TRUE if message is an SMTP response
516 Returns: TRUE if an SMTP "QUIT" command should be sent, else FALSE
520 check_response(host_item *host, int *errno_value, int more_errno,
521 uschar *buffer, int *yield, uschar **message, BOOL *pass_message)
523 uschar * pl = pipelining_active ? US"pipelined " : US"";
526 *yield = '4'; /* Default setting is to give a temporary error */
530 case ETIMEDOUT: /* Handle response timeout */
531 *message = US string_sprintf("SMTP timeout after %s%s",
533 if (transport_count > 0)
534 *message = US string_sprintf("%s (%d bytes written)", *message,
538 case ERRNO_SMTPFORMAT: /* Handle malformed SMTP response */
539 s = string_printing(buffer);
540 Uskip_whitespace(&s);
542 ? string_sprintf("Malformed SMTP reply (an empty line) "
543 "in response to %s%s", pl, smtp_command)
544 : string_sprintf("Malformed SMTP reply in response to %s%s: %s",
545 pl, smtp_command, s);
548 case ERRNO_TLSFAILURE: /* Handle bad first read; can happen with
550 *message = US"bad first read from TLS conn";
553 case ERRNO_FILTER_FAIL: /* Handle a failed filter process error;
554 can't send QUIT as we mustn't end the DATA. */
555 *message = string_sprintf("transport filter process failed (%d)%s",
557 more_errno == EX_EXECFAILED ? ": unable to execute command" : "");
560 case ERRNO_CHHEADER_FAIL: /* Handle a failed add_headers expansion;
561 can't send QUIT as we mustn't end the DATA. */
563 string_sprintf("failed to expand headers_add or headers_remove: %s",
564 expand_string_message);
567 case ERRNO_WRITEINCOMPLETE: /* failure to write a complete data block */
568 *message = US"failed to write a data block";
572 case ERRNO_UTF8_FWD: /* no advertised SMTPUTF8, for international message */
573 *message = US"utf8 support required but not offered for forwarding";
574 DEBUG(D_deliver|D_transport) debug_printf("%s\n", *message);
579 /* Handle error responses from the remote mailer. */
583 *message = string_sprintf("SMTP error from remote mail server after %s%s: "
584 "%s", pl, smtp_command, s = string_printing(buffer));
585 *pass_message = TRUE;
590 /* No data was read. If there is no errno, this must be the EOF (i.e.
591 connection closed) case, which causes deferral. An explicit connection reset
592 error has the same effect. Otherwise, put the host's identity in the message,
593 leaving the errno value to be interpreted as well. In all cases, we have to
594 assume the connection is now dead. */
596 if (*errno_value == 0 || *errno_value == ECONNRESET)
598 *errno_value = ERRNO_SMTPCLOSED;
599 *message = US string_sprintf("Remote host closed connection "
600 "in response to %s%s", pl, smtp_command);
603 *message = US string_sprintf("%s [%s]", host->name, host->address);
610 /*************************************************
611 * Write error message to logs *
612 *************************************************/
614 /* This writes to the main log and to the message log.
617 host the current host
618 detail the current message (addr_item->message)
619 basic_errno the errno (addr_item->basic_errno)
625 write_logs(const host_item *host, const uschar *suffix, int basic_errno)
627 gstring * message = LOGGING(outgoing_port)
628 ? string_fmt_append(NULL, "H=%s [%s]:%d", host->name, host->address,
629 host->port == PORT_NONE ? 25 : host->port)
630 : string_fmt_append(NULL, "H=%s [%s]", host->name, host->address);
634 message = string_fmt_append(message, ": %s", suffix);
636 message = string_fmt_append(message, ": %s", strerror(basic_errno));
639 message = string_fmt_append(message, " %s", exim_errstr(basic_errno));
641 log_write(0, LOG_MAIN, "%Y", message);
642 deliver_msglog("%s %.*s\n", tod_stamp(tod_log), message->ptr, message->s);
646 msglog_line(host_item * host, uschar * message)
648 deliver_msglog("%s H=%s [%s] %s\n", tod_stamp(tod_log),
649 host->name, host->address, message);
654 #ifndef DISABLE_EVENT
655 /*************************************************
656 * Post-defer action *
657 *************************************************/
659 /* This expands an arbitrary per-transport string.
660 It might, for example, be used to write to the database log.
663 addr the address item containing error information
664 host the current host
671 deferred_event_raise(address_item * addr, host_item * host, uschar * evstr)
673 uschar * action = addr->transport->event_action;
674 const uschar * save_domain, * save_local;
675 uschar * save_rn, * save_tn;
680 save_domain = deliver_domain;
681 save_local = deliver_localpart;
682 save_rn = router_name;
683 save_tn = transport_name;
685 /*XXX would ip & port already be set up? */
686 deliver_host_address = string_copy(host->address);
687 deliver_host_port = host->port == PORT_NONE ? 25 : host->port;
688 event_defer_errno = addr->basic_errno;
690 router_name = addr->router->name;
691 transport_name = addr->transport->name;
692 deliver_domain = addr->domain;
693 deliver_localpart = addr->local_part;
695 (void) event_raise(action, evstr,
697 ? addr->basic_errno > 0
698 ? string_sprintf("%s: %s", addr->message, strerror(addr->basic_errno))
699 : string_copy(addr->message)
700 : addr->basic_errno > 0
701 ? string_copy(US strerror(addr->basic_errno))
705 deliver_localpart = save_local;
706 deliver_domain = save_domain;
707 router_name = save_rn;
708 router_name = save_tn;
712 /*************************************************
713 * Reap SMTP specific responses *
714 *************************************************/
716 smtp_discard_responses(smtp_context * sx, smtp_transport_options_block * ob,
719 uschar flushbuffer[4096];
723 if (!smtp_read_response(sx, flushbuffer, sizeof(flushbuffer),
724 '2', ob->command_timeout)
725 && (errno != 0 || flushbuffer[0] == 0))
732 /* Return boolean success */
735 smtp_reap_banner(smtp_context * sx)
738 #if defined(__linux__) && defined(TCP_QUICKACK)
739 { /* Hack to get QUICKACK disabled; has to be right after 3whs, and has to on->off */
740 int sock = sx->cctx.sock;
741 struct pollfd p = {.fd = sock, .events = POLLOUT};
742 if (poll(&p, 1, 1000) >= 0) /* retval test solely for compiler quitening */
744 (void) setsockopt(sock, IPPROTO_TCP, TCP_QUICKACK, US &on, sizeof(on));
745 (void) setsockopt(sock, IPPROTO_TCP, TCP_QUICKACK, US &off, sizeof(off));
749 good_response = smtp_read_response(sx, sx->buffer, sizeof(sx->buffer),
750 '2', (SOB sx->conn_args.ob)->command_timeout);
751 #ifdef EXPERIMENTAL_DSN_INFO
752 sx->smtp_greeting = string_copy(sx->buffer);
754 return good_response;
758 smtp_reap_ehlo(smtp_context * sx)
760 if (!smtp_read_response(sx, sx->buffer, sizeof(sx->buffer), '2',
761 (SOB sx->conn_args.ob)->command_timeout))
763 if (errno != 0 || sx->buffer[0] == 0 || sx->lmtp)
765 #ifdef EXPERIMENTAL_DSN_INFO
766 sx->helo_response = string_copy(sx->buffer);
772 #ifdef EXPERIMENTAL_DSN_INFO
773 sx->helo_response = string_copy(sx->buffer);
775 #ifndef DISABLE_EVENT
776 (void) event_raise(sx->conn_args.tblock->event_action,
777 US"smtp:ehlo", sx->buffer, NULL);
783 #if !defined(DISABLE_TLS) && !defined(DISABLE_TLS_RESUME)
785 /* Grab a string differentiating server behind a loadbalancer, for TLS
786 resumption when such servers do not share a session-cache */
789 ehlo_response_lbserver(smtp_context * sx, const uschar * name_extract)
792 uschar * save_item = iterate_item;
794 if (sx->conn_args.have_lbserver)
796 iterate_item = sx->buffer;
797 s = expand_cstring(name_extract);
798 iterate_item = save_item;
799 sx->conn_args.host_lbserver = s && !*s ? NULL : s;
800 sx->conn_args.have_lbserver = TRUE;
806 /******************************************************************************/
808 #ifndef DISABLE_ESMTP_LIMITS
809 /* If TLS, or TLS not offered, called with the EHLO response in the buffer.
810 Check it for a LIMITS keyword and parse values into the smtp context structure.
812 We don't bother with peers that we won't talk TLS to, even though they can,
813 just ignore their LIMITS advice (if any) and treat them as if they do not.
814 This saves us dealing with a duplicate set of values. */
817 ehlo_response_limits_read(smtp_context * sx)
821 /* matches up to just after the first space after the keyword */
823 if (regex_match(regex_LIMITS, sx->buffer, -1, &match))
824 for (const uschar * s = sx->buffer + Ustrlen(match); *s; )
826 if (Uskip_whitespace(&s) == '\n') break;
828 if (strncmpic(s, US"MAILMAX=", 8) == 0)
830 continue_limit_mail = sx->peer_limit_mail = atoi(CS (s += 8));
831 while (isdigit(*s)) s++;
833 else if (strncmpic(s, US"RCPTMAX=", 8) == 0)
835 continue_limit_rcpt = sx->peer_limit_rcpt = atoi(CS (s += 8));
836 while (isdigit(*s)) s++;
838 else if (strncmpic(s, US"RCPTDOMAINMAX=", 14) == 0)
840 continue_limit_rcptdom = sx->peer_limit_rcptdom = atoi(CS (s += 14));
841 while (isdigit(*s)) s++;
844 while (*s && !isspace(*s)) s++;
848 /* Apply given values to the current connection */
850 ehlo_limits_apply(smtp_context * sx,
851 unsigned limit_mail, unsigned limit_rcpt, unsigned limit_rcptdom)
853 if (limit_mail && limit_mail < sx->max_mail) sx->max_mail = limit_mail;
854 if (limit_rcpt && limit_rcpt < sx->max_rcpt) sx->max_rcpt = limit_rcpt;
857 DEBUG(D_transport) debug_printf("will treat as !multi_domain\n");
858 sx->single_rcpt_domain = TRUE;
862 /* Apply values from EHLO-resp to the current connection */
864 ehlo_response_limits_apply(smtp_context * sx)
866 ehlo_limits_apply(sx, sx->peer_limit_mail, sx->peer_limit_rcpt,
867 sx->peer_limit_rcptdom);
870 /* Apply values read from cache to the current connection */
872 ehlo_cache_limits_apply(smtp_context * sx)
874 # ifndef DISABLE_PIPE_CONNECT
875 ehlo_limits_apply(sx, sx->ehlo_resp.limit_mail, sx->ehlo_resp.limit_rcpt,
876 sx->ehlo_resp.limit_rcptdom);
879 #endif /*EXPERIMENTAL_ESMTP_LIMITS*/
881 /******************************************************************************/
883 #ifndef DISABLE_PIPE_CONNECT
885 ehlo_cache_key(const smtp_context * sx)
887 host_item * host = sx->conn_args.host;
888 return Ustrchr(host->address, ':')
889 ? string_sprintf("[%s]:%d.EHLO", host->address,
890 host->port == PORT_NONE ? sx->port : host->port)
891 : string_sprintf("%s:%d.EHLO", host->address,
892 host->port == PORT_NONE ? sx->port : host->port);
895 /* Cache EHLO-response info for use by early-pipe.
897 - During a normal flow on EHLO response (either cleartext or under TLS),
898 when we are willing to do PIPECONNECT and it is offered
899 - During an early-pipe flow on receiving the actual EHLO response and noting
900 disparity versus the cached info used, when PIPECONNECT is still being offered
902 We assume that suitable values have been set in the sx.ehlo_resp structure for
903 features and auths; we handle the copy of limits. */
906 write_ehlo_cache_entry(smtp_context * sx)
908 open_db dbblock, * dbm_file;
910 # ifndef DISABLE_ESMTP_LIMITS
911 sx->ehlo_resp.limit_mail = sx->peer_limit_mail;
912 sx->ehlo_resp.limit_rcpt = sx->peer_limit_rcpt;
913 sx->ehlo_resp.limit_rcptdom = sx->peer_limit_rcptdom;
916 if ((dbm_file = dbfn_open(US"misc", O_RDWR, &dbblock, TRUE, TRUE)))
918 uschar * ehlo_resp_key = ehlo_cache_key(sx);
919 dbdata_ehlo_resp er = { .data = sx->ehlo_resp };
922 # ifndef DISABLE_ESMTP_LIMITS
923 if (sx->ehlo_resp.limit_mail || sx->ehlo_resp.limit_rcpt || sx->ehlo_resp.limit_rcptdom)
924 debug_printf("writing clr %04x/%04x cry %04x/%04x lim %05d/%05d/%05d\n",
925 sx->ehlo_resp.cleartext_features, sx->ehlo_resp.cleartext_auths,
926 sx->ehlo_resp.crypted_features, sx->ehlo_resp.crypted_auths,
927 sx->ehlo_resp.limit_mail, sx->ehlo_resp.limit_rcpt,
928 sx->ehlo_resp.limit_rcptdom);
931 debug_printf("writing clr %04x/%04x cry %04x/%04x\n",
932 sx->ehlo_resp.cleartext_features, sx->ehlo_resp.cleartext_auths,
933 sx->ehlo_resp.crypted_features, sx->ehlo_resp.crypted_auths);
935 dbfn_write(dbm_file, ehlo_resp_key, &er, (int)sizeof(er));
936 dbfn_close(dbm_file);
941 invalidate_ehlo_cache_entry(smtp_context * sx)
943 open_db dbblock, * dbm_file;
945 if ( sx->early_pipe_active
946 && (dbm_file = dbfn_open(US"misc", O_RDWR, &dbblock, TRUE, TRUE)))
948 uschar * ehlo_resp_key = ehlo_cache_key(sx);
951 dbdata_ehlo_resp * er;
953 if (!(er = dbfn_read_enforce_length(dbm_file, ehlo_resp_key, sizeof(dbdata_ehlo_resp))))
954 debug_printf("no ehlo-resp record!\n");
956 debug_printf("ehlo-resp record is %.0f seconds old\n",
957 difftime(time(NULL), er->time_stamp));
960 dbfn_delete(dbm_file, ehlo_resp_key);
961 dbfn_close(dbm_file);
966 read_ehlo_cache_entry(smtp_context * sx)
971 if (!(dbm_file = dbfn_open(US"misc", O_RDONLY, &dbblock, FALSE, TRUE)))
972 { DEBUG(D_transport) debug_printf("ehlo-cache: no misc DB\n"); }
975 uschar * ehlo_resp_key = ehlo_cache_key(sx);
976 dbdata_ehlo_resp * er;
978 if (!(er = dbfn_read_enforce_length(dbm_file, ehlo_resp_key, sizeof(dbdata_ehlo_resp))))
979 { DEBUG(D_transport) debug_printf("no ehlo-resp record\n"); }
980 else if (time(NULL) - er->time_stamp > retry_data_expire)
982 DEBUG(D_transport) debug_printf("ehlo-resp record too old\n");
983 dbfn_close(dbm_file);
984 if ((dbm_file = dbfn_open(US"misc", O_RDWR, &dbblock, TRUE, TRUE)))
985 dbfn_delete(dbm_file, ehlo_resp_key);
990 # ifndef DISABLE_ESMTP_LIMITS
991 if (er->data.limit_mail || er->data.limit_rcpt || er->data.limit_rcptdom)
992 debug_printf("EHLO response bits from cache:"
993 " cleartext 0x%04x/0x%04x crypted 0x%04x/0x%04x lim %05d/%05d/%05d\n",
994 er->data.cleartext_features, er->data.cleartext_auths,
995 er->data.crypted_features, er->data.crypted_auths,
996 er->data.limit_mail, er->data.limit_rcpt, er->data.limit_rcptdom);
999 debug_printf("EHLO response bits from cache:"
1000 " cleartext 0x%04x/0x%04x crypted 0x%04x/0x%04x\n",
1001 er->data.cleartext_features, er->data.cleartext_auths,
1002 er->data.crypted_features, er->data.crypted_auths);
1004 sx->ehlo_resp = er->data;
1005 # ifndef DISABLE_ESMTP_LIMITS
1006 ehlo_cache_limits_apply(sx);
1008 dbfn_close(dbm_file);
1011 dbfn_close(dbm_file);
1018 /* Return an auths bitmap for the set of AUTH methods offered by the server
1019 which match our client-side authenticators. */
1021 static unsigned short
1022 study_ehlo_auths(smtp_context * sx)
1027 unsigned short authbits = 0;
1029 if (!sx->esmtp) return 0;
1030 if (!regex_AUTH) regex_AUTH = regex_must_compile(AUTHS_REGEX, MCS_NOFLAGS, TRUE);
1031 if (!regex_match_and_setup(regex_AUTH, sx->buffer, 0, -1)) return 0;
1032 expand_nmax = -1; /* reset */
1033 names = string_copyn(expand_nstring[1], expand_nlength[1]);
1035 for (au = auths, authnum = 0; au; au = au->next, authnum++) if (au->client)
1037 const uschar * list = names;
1039 for (int sep = ' '; s = string_nextinlist(&list, &sep, NULL, 0); )
1040 if (strcmpic(au->public_name, s) == 0)
1041 { authbits |= BIT(authnum); break; }
1045 debug_printf("server offers %s AUTH, methods '%s', usable-bitmap 0x%04x\n",
1046 tls_out.active.sock >= 0 ? "crypted" : "plaintext", names, authbits);
1048 if (tls_out.active.sock >= 0)
1049 sx->ehlo_resp.crypted_auths = authbits;
1051 sx->ehlo_resp.cleartext_auths = authbits;
1058 /* Wait for and check responses for early-pipelining.
1060 Called from the lower-level smtp_read_response() function
1061 used for general code that assume synchronisation, if context
1062 flags indicate outstanding early-pipelining commands. Also
1063 called fom sync_responses() which handles pipelined commands.
1066 sx smtp connection context
1067 countp number of outstanding responses, adjusted on return
1071 DEFER error on first read of TLS'd conn
1072 FAIL SMTP error in response
1075 smtp_reap_early_pipe(smtp_context * sx, int * countp)
1077 BOOL pending_BANNER = sx->pending_BANNER;
1078 BOOL pending_EHLO = sx->pending_EHLO;
1081 sx->pending_BANNER = FALSE; /* clear early to avoid recursion */
1082 sx->pending_EHLO = FALSE;
1088 DEBUG(D_transport) debug_printf("%s expect banner\n", __FUNCTION__);
1090 if (!smtp_reap_banner(sx))
1092 DEBUG(D_transport) debug_printf("bad banner\n");
1093 if (tls_out.active.sock >= 0) rc = DEFER;
1096 /*XXX EXPERIMENTAL_ESMTP_LIMITS ? */
1098 # if !defined(DISABLE_TLS) && !defined(DISABLE_TLS_RESUME)
1099 GET_OPTION("host_name_extract");
1100 s = ((smtp_transport_options_block *)sx->conn_args.ob)->host_name_extract;
1101 if (!s) s = HNE_DEFAULT;
1102 ehlo_response_lbserver(sx, s);
1108 unsigned peer_offered;
1109 unsigned short authbits = 0, * ap;
1111 DEBUG(D_transport) debug_printf("%s expect ehlo\n", __FUNCTION__);
1113 if (!smtp_reap_ehlo(sx))
1115 DEBUG(D_transport) debug_printf("bad response for EHLO\n");
1116 if (tls_out.active.sock >= 0) rc = DEFER;
1120 /* Compare the actual EHLO response extensions and AUTH methods to the cached
1121 value we assumed; on difference, dump or rewrite the cache and arrange for a
1124 ap = tls_out.active.sock < 0
1125 ? &sx->ehlo_resp.cleartext_auths : &sx->ehlo_resp.crypted_auths;
1127 peer_offered = ehlo_response(sx->buffer,
1128 (tls_out.active.sock < 0 ? OPTION_TLS : 0)
1129 | OPTION_CHUNKING | OPTION_PRDR | OPTION_DSN | OPTION_PIPE | OPTION_SIZE
1130 | OPTION_UTF8 | OPTION_EARLY_PIPE
1132 # ifndef DISABLE_ESMTP_LIMITS
1133 if (tls_out.active.sock >= 0 || !(peer_offered & OPTION_TLS))
1134 ehlo_response_limits_read(sx);
1136 if ( peer_offered != sx->peer_offered
1137 || (authbits = study_ehlo_auths(sx)) != *ap)
1140 debug_printf("EHLO %s extensions changed, 0x%04x/0x%04x -> 0x%04x/0x%04x\n",
1141 tls_out.active.sock < 0 ? "cleartext" : "crypted",
1142 sx->peer_offered, *ap, peer_offered, authbits);
1143 if (peer_offered & OPTION_EARLY_PIPE)
1145 *(tls_out.active.sock < 0
1146 ? &sx->ehlo_resp.cleartext_features : &sx->ehlo_resp.crypted_features) =
1149 write_ehlo_cache_entry(sx);
1153 invalidate_ehlo_cache_entry(sx);
1154 sx->early_pipe_active = FALSE; /* cancel further early-pipe on this conn */
1157 return OK; /* just carry on */
1159 # ifndef DISABLE_ESMTP_LIMITS
1160 /* If we are handling LIMITS, compare the actual EHLO LIMITS values with the
1161 cached values and invalidate cache if different. OK to carry on with
1162 connect since values are advisory. */
1164 if ( (tls_out.active.sock >= 0 || !(peer_offered & OPTION_TLS))
1165 && ( sx->peer_limit_mail != sx->ehlo_resp.limit_mail
1166 || sx->peer_limit_rcpt != sx->ehlo_resp.limit_rcpt
1167 || sx->peer_limit_rcptdom != sx->ehlo_resp.limit_rcptdom
1172 debug_printf("EHLO LIMITS changed:");
1173 if (sx->peer_limit_mail != sx->ehlo_resp.limit_mail)
1174 debug_printf(" MAILMAX %u -> %u\n", sx->ehlo_resp.limit_mail, sx->peer_limit_mail);
1175 else if (sx->peer_limit_rcpt != sx->ehlo_resp.limit_rcpt)
1176 debug_printf(" RCPTMAX %u -> %u\n", sx->ehlo_resp.limit_rcpt, sx->peer_limit_rcpt);
1178 debug_printf(" RCPTDOMAINMAX %u -> %u\n", sx->ehlo_resp.limit_rcptdom, sx->peer_limit_rcptdom);
1180 invalidate_ehlo_cache_entry(sx);
1188 invalidate_ehlo_cache_entry(sx);
1189 (void) smtp_discard_responses(sx, sx->conn_args.ob, *countp);
1192 #endif /*!DISABLE_PIPE_CONNECT*/
1195 /*************************************************
1196 * Synchronize SMTP responses *
1197 *************************************************/
1199 /* This function is called from smtp_deliver() to receive SMTP responses from
1200 the server, and match them up with the commands to which they relate. When
1201 PIPELINING is not in use, this function is called after every command, and is
1202 therefore somewhat over-engineered, but it is simpler to use a single scheme
1203 that works both with and without PIPELINING instead of having two separate sets
1206 The set of commands that are buffered up with pipelining may start with MAIL
1207 and may end with DATA; in between are RCPT commands that correspond to the
1208 addresses whose status is PENDING_DEFER. All other commands (STARTTLS, AUTH,
1209 etc.) are never buffered.
1211 Errors after MAIL or DATA abort the whole process leaving the response in the
1212 buffer. After MAIL, pending responses are flushed, and the original command is
1213 re-instated in big_buffer for error messages. For RCPT commands, the remote is
1214 permitted to reject some recipient addresses while accepting others. However
1215 certain errors clearly abort the whole process. Set the value in
1216 transport_return to PENDING_OK if the address is accepted. If there is a
1217 subsequent general error, it will get reset accordingly. If not, it will get
1218 converted to OK at the end.
1221 sx smtp connection context
1222 count the number of responses to read
1223 pending_DATA 0 if last command sent was not DATA
1224 +1 if previously had a good recipient
1225 -1 if not previously had a good recipient
1227 Returns: 3 if at least one address had 2xx and one had 5xx
1228 2 if at least one address had 5xx but none had 2xx
1229 1 if at least one host had a 2xx response, but none had 5xx
1230 0 no address had 2xx or 5xx but no errors (all 4xx, or just DATA)
1231 -1 timeout while reading RCPT response
1232 -2 I/O or other non-response error for RCPT
1233 -3 DATA or MAIL failed - errno and buffer set
1234 -4 banner or EHLO failed (early-pipelining)
1235 -5 banner or EHLO failed (early-pipelining, TLS)
1239 sync_responses(smtp_context * sx, int count, int pending_DATA)
1241 address_item * addr = sx->sync_addr;
1242 smtp_transport_options_block * ob = sx->conn_args.ob;
1245 #ifndef DISABLE_PIPE_CONNECT
1247 if ((rc = smtp_reap_early_pipe(sx, &count)) != OK)
1248 return rc == FAIL ? RESP_EPIPE_EHLO_ERR : RESP_EHLO_ERR_TLS;
1251 /* Handle the response for a MAIL command. On error, reinstate the original
1252 command in big_buffer for error message use, and flush any further pending
1253 responses before returning, except after I/O errors and timeouts. */
1255 if (sx->pending_MAIL)
1257 DEBUG(D_transport) debug_printf("%s expect mail\n", __FUNCTION__);
1259 sx->pending_MAIL = sx->RCPT_452 = FALSE;
1260 if (!smtp_read_response(sx, sx->buffer, sizeof(sx->buffer),
1261 '2', ob->command_timeout))
1263 DEBUG(D_transport) debug_printf("bad response for MAIL\n");
1264 Ustrcpy(big_buffer, mail_command); /* Fits, because it came from there! */
1265 if (errno == ERRNO_TLSFAILURE)
1266 return RESP_EHLO_ERR_TLS;
1267 if (errno == 0 && sx->buffer[0] != 0)
1270 if (sx->buffer[0] == '4')
1272 save_errno = ERRNO_MAIL4XX;
1273 addr->more_errno |= ((sx->buffer[1] - '0')*10 + sx->buffer[2] - '0') << 8;
1275 count = smtp_discard_responses(sx, ob, count);
1279 if (pending_DATA) count--; /* Number of RCPT responses to come */
1280 while (count-- > 0) /* Mark any pending addrs with the host used */
1282 while (addr->transport_return != PENDING_DEFER) addr = addr->next;
1283 addr->host_used = sx->conn_args.host;
1284 if (continue_sequence > 1)
1285 { clearflag(addr, af_new_conn); setflag(addr, af_cont_conn); }
1287 { clearflag(addr, af_cont_conn); setflag(addr, af_new_conn); }
1290 return RESP_MAIL_OR_DATA_ERROR;
1294 if (pending_DATA) count--; /* Number of RCPT responses to come */
1296 /* Read and handle the required number of RCPT responses, matching each one up
1297 with an address by scanning for the next address whose status is PENDING_DEFER.
1302 while (addr->transport_return != PENDING_DEFER)
1303 if (!(addr = addr->next))
1304 return RESP_RCPT_ERROR;
1306 /* The address was accepted */
1307 addr->host_used = sx->conn_args.host;
1308 if (continue_sequence > 1)
1309 { clearflag(addr, af_new_conn); setflag(addr, af_cont_conn); }
1311 { clearflag(addr, af_cont_conn); setflag(addr, af_new_conn); }
1313 DEBUG(D_transport) debug_printf("%s expect rcpt for %s\n", __FUNCTION__, addr->address);
1314 if (smtp_read_response(sx, sx->buffer, sizeof(sx->buffer),
1315 '2', ob->command_timeout))
1317 yield |= RESP_BIT_HAD_2XX;
1318 addr->transport_return = PENDING_OK;
1320 /* If af_dr_retry_exists is set, there was a routing delay on this address;
1321 ensure that any address-specific retry record is expunged. We do this both
1322 for the basic key and for the version that also includes the sender. */
1324 if (testflag(addr, af_dr_retry_exists))
1326 uschar * altkey = string_sprintf("%s:<%s>", addr->address_retry_key,
1328 retry_add_item(addr, altkey, rf_delete);
1329 retry_add_item(addr, addr->address_retry_key, rf_delete);
1333 /* Error on first TLS read */
1335 else if (errno == ERRNO_TLSFAILURE)
1336 return RESP_EHLO_ERR_TLS;
1338 /* Timeout while reading the response */
1340 else if (errno == ETIMEDOUT)
1342 uschar * message = string_sprintf("SMTP timeout after RCPT TO:<%s>",
1343 transport_rcpt_address(addr, sx->conn_args.tblock->rcpt_include_affixes));
1344 set_errno_nohost(sx->first_addr, ETIMEDOUT, message, DEFER, FALSE, &sx->delivery_start);
1345 retry_add_item(addr, addr->address_retry_key, 0);
1346 update_waiting = FALSE;
1347 return RESP_RCPT_TIMEO;
1350 /* Handle other errors in obtaining an SMTP response by returning -1. This
1351 will cause all the addresses to be deferred. Restore the SMTP command in
1352 big_buffer for which we are checking the response, so the error message
1355 else if (errno != 0 || sx->buffer[0] == 0)
1357 gstring gs = { .size = big_buffer_size, .ptr = 0, .s = big_buffer }, * g = &gs;
1359 /* Use taint-unchecked routines for writing into big_buffer, trusting
1360 that we'll never expand it. */
1362 g = string_fmt_append_f(g, SVFMT_TAINT_NOCHK, "RCPT TO:<%s>",
1363 transport_rcpt_address(addr, sx->conn_args.tblock->rcpt_include_affixes));
1364 string_from_gstring(g);
1365 return RESP_RCPT_ERROR;
1368 /* Handle SMTP permanent and temporary response codes. */
1373 string_sprintf("SMTP error from remote mail server after RCPT TO:<%s>: "
1374 "%s", transport_rcpt_address(addr, sx->conn_args.tblock->rcpt_include_affixes),
1375 string_printing(sx->buffer));
1376 setflag(addr, af_pass_message);
1378 msglog_line(sx->conn_args.host, addr->message);
1380 /* The response was 5xx */
1382 if (sx->buffer[0] == '5')
1384 addr->transport_return = FAIL;
1385 yield |= RESP_BIT_HAD_5XX;
1388 /* The response was 4xx */
1392 addr->transport_return = DEFER;
1393 addr->basic_errno = ERRNO_RCPT4XX;
1394 addr->more_errno |= ((sx->buffer[1] - '0')*10 + sx->buffer[2] - '0') << 8;
1398 #ifndef DISABLE_EVENT
1399 event_defer_errno = addr->more_errno;
1400 msg_event_raise(US"msg:rcpt:host:defer", addr);
1402 /* If a 452 and we've had at least one 2xx or 5xx, set next_addr to the
1403 start point for another MAIL command. */
1405 if (addr->more_errno >> 8 == 52 && yield > 0)
1407 if (!sx->RCPT_452) /* initialised at MAIL-ack above */
1410 debug_printf("%s: seen first 452 too-many-rcpts\n", __FUNCTION__);
1411 sx->RCPT_452 = TRUE;
1412 sx->next_addr = addr;
1414 addr->transport_return = PENDING_DEFER;
1415 addr->basic_errno = 0;
1419 /* Log temporary errors if there are more hosts to be tried.
1420 If not, log this last one in the == line. */
1422 if (sx->conn_args.host->next)
1423 if (LOGGING(outgoing_port))
1424 log_write(0, LOG_MAIN, "H=%s [%s]:%d %s", sx->conn_args.host->name,
1425 sx->conn_args.host->address,
1426 sx->port == PORT_NONE ? 25 : sx->port, addr->message);
1428 log_write(0, LOG_MAIN, "H=%s [%s]: %s", sx->conn_args.host->name,
1429 sx->conn_args.host->address, addr->message);
1431 #ifndef DISABLE_EVENT
1433 msg_event_raise(US"msg:rcpt:defer", addr);
1436 /* Do not put this message on the list of those waiting for specific
1437 hosts, as otherwise it is likely to be tried too often. */
1439 update_waiting = FALSE;
1441 /* Add a retry item for the address so that it doesn't get tried again
1442 too soon. If address_retry_include_sender is true, add the sender address
1443 to the retry key. */
1445 retry_add_item(addr,
1446 ob->address_retry_include_sender
1447 ? string_sprintf("%s:<%s>", addr->address_retry_key, sender_address)
1448 : addr->address_retry_key,
1454 if (count && !(addr = addr->next))
1455 return RESP_RCPT_ERROR;
1456 } /* Loop for next RCPT response */
1458 /* Update where to start at for the next block of responses, unless we
1459 have already handled all the addresses. */
1461 if (addr) sx->sync_addr = addr->next;
1463 /* Handle a response to DATA. If we have not had any good recipients, either
1464 previously or in this block, the response is ignored. */
1466 if (pending_DATA != 0)
1468 DEBUG(D_transport) debug_printf("%s expect data\n", __FUNCTION__);
1469 if (!smtp_read_response(sx, sx->buffer, sizeof(sx->buffer),
1470 '3', ob->command_timeout))
1476 if (errno == ERRNO_TLSFAILURE) /* Error on first TLS read */
1477 return RESP_EHLO_ERR_TLS;
1479 if (pending_DATA > 0 || yield & RESP_BIT_HAD_2XX)
1481 if (errno == 0 && sx->buffer[0] == '4')
1483 errno = ERRNO_DATA4XX;
1484 sx->first_addr->more_errno |= ((sx->buffer[1] - '0')*10 + sx->buffer[2] - '0') << 8;
1486 return RESP_MAIL_OR_DATA_ERROR;
1488 (void)check_response(sx->conn_args.host, &errno, 0, sx->buffer, &code, &msg, &pass_message);
1489 DEBUG(D_transport) debug_printf("%s\nerror for DATA ignored: pipelining "
1490 "is in use and there were no good recipients\n", msg);
1494 /* All responses read and handled; MAIL (if present) received 2xx and DATA (if
1495 present) received 3xx. If any RCPTs were handled and yielded anything other
1496 than 4xx, yield will be set non-zero. */
1505 /* Try an authenticator's client entry */
1508 try_authenticator(smtp_context * sx, auth_instance * au)
1510 smtp_transport_options_block * ob = sx->conn_args.ob; /* transport options */
1511 host_item * host = sx->conn_args.host; /* host to deliver to */
1514 /* Set up globals for error messages */
1516 authenticator_name = au->name;
1517 driver_srcfile = au->srcfile;
1518 driver_srcline = au->srcline;
1520 sx->outblock.authenticating = TRUE;
1521 rc = (au->info->clientcode)(au, sx, ob->command_timeout,
1522 sx->buffer, sizeof(sx->buffer));
1523 sx->outblock.authenticating = FALSE;
1524 driver_srcfile = authenticator_name = NULL; driver_srcline = 0;
1525 DEBUG(D_transport) debug_printf("%s authenticator yielded %s\n", au->name, rc_names[rc]);
1527 /* A temporary authentication failure must hold up delivery to
1528 this host. After a permanent authentication failure, we carry on
1529 to try other authentication methods. If all fail hard, try to
1530 deliver the message unauthenticated unless require_auth was set. */
1535 f.smtp_authenticated = TRUE; /* stops the outer loop */
1536 client_authenticator = au->name;
1537 if (au->set_client_id)
1538 client_authenticated_id = expand_string(au->set_client_id);
1541 /* Failure after writing a command */
1546 /* Failure after reading a response */
1550 uschar * logmsg = NULL;
1552 if (errno != 0 || sx->buffer[0] != '5') return FAIL;
1553 #ifndef DISABLE_EVENT
1555 uschar * save_name = sender_host_authenticated;
1556 sender_host_authenticated = au->name;
1557 if ((logmsg = event_raise(sx->conn_args.tblock->event_action, US"auth:fail",
1559 log_write(0, LOG_MAIN, "%s", logmsg);
1560 sender_host_authenticated = save_name;
1564 log_write(0, LOG_MAIN, "%s authenticator failed H=%s [%s] %s",
1565 au->name, host->name, host->address, sx->buffer);
1569 /* Failure by some other means. In effect, the authenticator
1570 decided it wasn't prepared to handle this case. Typically this
1571 is the result of "fail" in an expansion string. Do we need to
1572 log anything here? Feb 2006: a message is now put in the buffer
1573 if logging is required. */
1576 if (*sx->buffer != 0)
1577 log_write(0, LOG_MAIN, "%s authenticator cancelled "
1578 "authentication H=%s [%s] %s", au->name, host->name,
1579 host->address, sx->buffer);
1582 /* Internal problem, message in buffer. */
1585 set_errno_nohost(sx->addrlist, ERRNO_AUTHPROB, string_copy(sx->buffer),
1586 DEFER, FALSE, &sx->delivery_start);
1595 /* Do the client side of smtp-level authentication.
1598 sx smtp connection context
1600 sx->buffer should have the EHLO response from server (gets overwritten)
1603 OK Success, or failed (but not required): global "smtp_authenticated" set
1604 DEFER Failed authentication (and was required)
1605 ERROR Internal problem
1607 FAIL_SEND Failed communications - transmit
1612 smtp_auth(smtp_context * sx)
1614 host_item * host = sx->conn_args.host; /* host to deliver to */
1615 smtp_transport_options_block * ob = sx->conn_args.ob; /* transport options */
1616 int require_auth = verify_check_given_host(CUSS &ob->hosts_require_auth, host);
1617 #ifndef DISABLE_PIPE_CONNECT
1618 unsigned short authbits = tls_out.active.sock >= 0
1619 ? sx->ehlo_resp.crypted_auths : sx->ehlo_resp.cleartext_auths;
1621 uschar * fail_reason = US"server did not advertise AUTH support";
1623 f.smtp_authenticated = FALSE;
1624 client_authenticator = client_authenticated_id = client_authenticated_sender = NULL;
1627 regex_AUTH = regex_must_compile(AUTHS_REGEX, MCS_NOFLAGS, TRUE);
1629 /* Is the server offering AUTH? */
1633 #ifndef DISABLE_PIPE_CONNECT
1634 sx->early_pipe_active ? authbits
1637 regex_match_and_setup(regex_AUTH, sx->buffer, 0, -1)
1640 uschar * names = NULL;
1641 expand_nmax = -1; /* reset */
1643 #ifndef DISABLE_PIPE_CONNECT
1644 if (!sx->early_pipe_active)
1646 names = string_copyn(expand_nstring[1], expand_nlength[1]);
1648 /* Must not do this check until after we have saved the result of the
1649 regex match above as the check could be another RE. */
1651 if ( require_auth == OK
1652 || verify_check_given_host(CUSS &ob->hosts_try_auth, host) == OK)
1654 DEBUG(D_transport) debug_printf("scanning authentication mechanisms\n");
1655 fail_reason = US"no common mechanisms were found";
1657 #ifndef DISABLE_PIPE_CONNECT
1658 if (sx->early_pipe_active)
1660 /* Scan our authenticators (which support use by a client and were offered
1661 by the server (checked at cache-write time)), not suppressed by
1662 client_condition. If one is found, attempt to authenticate by calling its
1663 client function. We are limited to supporting up to 16 authenticator
1664 public-names by the number of bits in a short. */
1670 for (bitnum = 0, au = auths;
1671 !f.smtp_authenticated && au && bitnum < 16;
1672 bitnum++, au = au->next) if (authbits & BIT(bitnum))
1674 if ( au->client_condition
1675 && !expand_check_condition(au->client_condition, au->name,
1676 US"client authenticator"))
1678 DEBUG(D_transport) debug_printf("skipping %s authenticator: %s\n",
1679 au->name, "client_condition is false");
1683 /* Found data for a listed mechanism. Call its client entry. Set
1684 a flag in the outblock so that data is overwritten after sending so
1685 that reflections don't show it. */
1687 fail_reason = US"authentication attempt(s) failed";
1689 if ((rc = try_authenticator(sx, au)) != OK)
1696 /* Scan the configured authenticators looking for one which is configured
1697 for use as a client, which is not suppressed by client_condition, and
1698 whose name matches an authentication mechanism supported by the server.
1699 If one is found, attempt to authenticate by calling its client function.
1702 for (auth_instance * au = auths; !f.smtp_authenticated && au; au = au->next)
1707 || ( au->client_condition
1708 && !expand_check_condition(au->client_condition, au->name,
1709 US"client authenticator")))
1711 DEBUG(D_transport) debug_printf("skipping %s authenticator: %s\n",
1713 au->client ? "client_condition is false"
1714 : "not configured as a client");
1718 /* Loop to scan supported server mechanisms */
1722 int len = Ustrlen(au->public_name), rc;
1724 Uskip_whitespace(&p);
1726 if (strncmpic(au->public_name, p, len) != 0 ||
1727 (p[len] && !isspace(p[len])))
1729 while (*p && !isspace(*p)) p++;
1733 /* Found data for a listed mechanism. Call its client entry. Set
1734 a flag in the outblock so that data is overwritten after sending so
1735 that reflections don't show it. */
1737 fail_reason = US"authentication attempt(s) failed";
1739 if ((rc = try_authenticator(sx, au)) != OK)
1742 break; /* If not authenticated, try next authenticator */
1743 } /* Loop for scanning supported server mechanisms */
1744 } /* Loop for further authenticators */
1748 /* If we haven't authenticated, but are required to, give up. */
1750 if (require_auth == OK && !f.smtp_authenticated)
1752 #ifndef DISABLE_PIPE_CONNECT
1753 invalidate_ehlo_cache_entry(sx);
1755 set_errno_nohost(sx->addrlist, ERRNO_AUTHFAIL,
1756 string_sprintf("authentication required but %s", fail_reason), DEFER,
1757 FALSE, &sx->delivery_start);
1765 /* Construct AUTH appendix string for MAIL TO */
1768 sx context for smtp connection
1769 p point in sx->buffer to build string
1770 addrlist chain of potential addresses to deliver
1772 Globals f.smtp_authenticated
1773 client_authenticated_sender
1774 Return True on error, otherwise buffer has (possibly empty) terminated string
1778 smtp_mail_auth_str(smtp_context * sx, uschar * p, address_item * addrlist)
1780 smtp_transport_options_block * ob = sx->conn_args.ob;
1781 uschar * local_authenticated_sender = authenticated_sender;
1784 debug_printf("smtp_mail_auth_str: as<%s> os<%s> SA<%s>\n",
1785 authenticated_sender, ob->authenticated_sender, f.smtp_authenticated?"Y":"N");
1788 GET_OPTION("authenticated_sender");
1789 if (ob->authenticated_sender)
1791 uschar * new = expand_string(ob->authenticated_sender);
1794 if (!f.expand_string_forcedfail)
1796 uschar *message = string_sprintf("failed to expand "
1797 "authenticated_sender: %s", expand_string_message);
1798 set_errno_nohost(addrlist, ERRNO_EXPANDFAIL, message, DEFER, FALSE, &sx->delivery_start);
1803 local_authenticated_sender = new;
1806 /* Add the authenticated sender address if present */
1808 if ( (f.smtp_authenticated || ob->authenticated_sender_force)
1809 && local_authenticated_sender)
1811 string_format_nt(p, sizeof(sx->buffer) - (p-sx->buffer), " AUTH=%s",
1812 auth_xtextencode(local_authenticated_sender,
1813 Ustrlen(local_authenticated_sender)));
1814 client_authenticated_sender = string_copy(local_authenticated_sender);
1824 typedef struct smtp_compare_s
1826 const uschar * current_sender_address;
1827 struct transport_instance * tblock;
1831 /* Create a unique string that identifies this message, it is based on
1832 sender_address, helo_data and tls_certificate if enabled.
1836 smtp_local_identity(const uschar * sender, struct transport_instance * tblock)
1838 address_item * addr1;
1839 uschar * if1 = US"";
1840 uschar * helo1 = US"";
1842 uschar * tlsc1 = US"";
1844 const uschar * save_sender_address = sender_address;
1845 uschar * local_identity = NULL;
1846 smtp_transport_options_block * ob = SOB tblock->options_block;
1848 sender_address = sender;
1850 addr1 = deliver_make_addr (sender, TRUE);
1851 deliver_set_expansions(addr1);
1854 if1 = expand_string(ob->interface);
1857 helo1 = expand_string(ob->helo_data);
1860 if (ob->tls_certificate)
1861 tlsc1 = expand_string(ob->tls_certificate);
1862 local_identity = string_sprintf ("%s^%s^%s", if1, helo1, tlsc1);
1864 local_identity = string_sprintf ("%s^%s", if1, helo1);
1867 deliver_set_expansions(NULL);
1868 sender_address = save_sender_address;
1870 return local_identity;
1875 /* This routine is a callback that is called from transport_check_waiting.
1876 This function will evaluate the incoming message versus the previous
1877 message. If the incoming message is using a different local identity then
1878 we will veto this new message. */
1881 smtp_are_same_identities(uschar * message_id, smtp_compare_t * s_compare)
1883 uschar * message_local_identity,
1884 * current_local_identity,
1885 * new_sender_address;
1887 current_local_identity =
1888 smtp_local_identity(s_compare->current_sender_address, s_compare->tblock);
1890 if (!(new_sender_address = spool_sender_from_msgid(message_id)))
1894 message_local_identity =
1895 smtp_local_identity(new_sender_address, s_compare->tblock);
1897 return Ustrcmp(current_local_identity, message_local_identity) == 0;
1903 ehlo_response(uschar * buf, unsigned checks)
1905 PCRE2_SIZE bsize = Ustrlen(buf);
1906 pcre2_match_data * md = pcre2_match_data_create(1, pcre_gen_ctx);
1908 /* debug_printf("%s: check for 0x%04x\n", __FUNCTION__, checks); */
1911 if ( checks & OPTION_TLS
1912 && pcre2_match(regex_STARTTLS,
1913 (PCRE2_SPTR)buf, bsize, 0, PCRE_EOPT, md, pcre_gen_mtc_ctx) < 0)
1915 checks &= ~OPTION_TLS;
1917 if ( checks & OPTION_IGNQ
1918 && pcre2_match(regex_IGNOREQUOTA,
1919 (PCRE2_SPTR)buf, bsize, 0, PCRE_EOPT, md, pcre_gen_mtc_ctx) < 0)
1920 checks &= ~OPTION_IGNQ;
1922 if ( checks & OPTION_CHUNKING
1923 && pcre2_match(regex_CHUNKING,
1924 (PCRE2_SPTR)buf, bsize, 0, PCRE_EOPT, md, pcre_gen_mtc_ctx) < 0)
1925 checks &= ~OPTION_CHUNKING;
1927 #ifndef DISABLE_PRDR
1928 if ( checks & OPTION_PRDR
1929 && pcre2_match(regex_PRDR,
1930 (PCRE2_SPTR)buf, bsize, 0, PCRE_EOPT, md, pcre_gen_mtc_ctx) < 0)
1932 checks &= ~OPTION_PRDR;
1935 if ( checks & OPTION_UTF8
1936 && pcre2_match(regex_UTF8,
1937 (PCRE2_SPTR)buf, bsize, 0, PCRE_EOPT, md, pcre_gen_mtc_ctx) < 0)
1939 checks &= ~OPTION_UTF8;
1941 if ( checks & OPTION_DSN
1942 && pcre2_match(regex_DSN,
1943 (PCRE2_SPTR)buf, bsize, 0, PCRE_EOPT, md, pcre_gen_mtc_ctx) < 0)
1944 checks &= ~OPTION_DSN;
1946 if ( checks & OPTION_PIPE
1947 && pcre2_match(regex_PIPELINING,
1948 (PCRE2_SPTR)buf, bsize, 0, PCRE_EOPT, md, pcre_gen_mtc_ctx) < 0)
1949 checks &= ~OPTION_PIPE;
1951 if ( checks & OPTION_SIZE
1952 && pcre2_match(regex_SIZE,
1953 (PCRE2_SPTR)buf, bsize, 0, PCRE_EOPT, md, pcre_gen_mtc_ctx) < 0)
1954 checks &= ~OPTION_SIZE;
1956 #ifndef DISABLE_PIPE_CONNECT
1957 if ( checks & OPTION_EARLY_PIPE
1958 && pcre2_match(regex_EARLY_PIPE,
1959 (PCRE2_SPTR)buf, bsize, 0, PCRE_EOPT, md, pcre_gen_mtc_ctx) < 0)
1961 checks &= ~OPTION_EARLY_PIPE;
1963 /* pcre2_match_data_free(md); gen ctx needs no free */
1964 /* debug_printf("%s: found 0x%04x\n", __FUNCTION__, checks); */
1970 /* Callback for emitting a BDAT data chunk header.
1972 If given a nonzero size, first flush any buffered SMTP commands
1973 then emit the command.
1975 Reap previous SMTP command responses if requested, and always reap
1976 the response from a previous BDAT command.
1979 tctx transport context
1980 chunk_size value for SMTP BDAT command
1982 tc_chunk_last add LAST option to SMTP BDAT command
1983 tc_reap_prev reap response to previous SMTP commands
1987 DEFER TLS error on first read (EHLO-resp); errno set
1991 smtp_chunk_cmd_callback(transport_ctx * tctx, unsigned chunk_size,
1994 smtp_transport_options_block * ob = SOB tctx->tblock->options_block;
1995 smtp_context * sx = tctx->smtp_context;
1999 /* Write SMTP chunk header command. If not reaping responses, note that
2000 there may be more writes (like, the chunk data) done soon. */
2004 #ifndef DISABLE_PIPE_CONNECT
2005 BOOL new_conn = !!(sx->outblock.conn_args);
2007 if((cmd_count = smtp_write_command(sx,
2008 flags & tc_reap_prev ? SCMD_FLUSH : SCMD_MORE,
2009 "BDAT %u%s\r\n", chunk_size, flags & tc_chunk_last ? " LAST" : "")
2010 ) < 0) return ERROR;
2011 if (flags & tc_chunk_last)
2012 data_command = string_copy(big_buffer); /* Save for later error message */
2013 #ifndef DISABLE_PIPE_CONNECT
2014 /* That command write could have been the one that made the connection.
2015 Copy the fd from the client conn ctx (smtp transport specific) to the
2016 generic transport ctx. */
2019 tctx->u.fd = sx->outblock.cctx->sock;
2023 prev_cmd_count = cmd_count += sx->cmd_count;
2025 /* Reap responses for any previous, but not one we just emitted */
2029 if (sx->pending_BDAT)
2032 if (flags & tc_reap_prev && prev_cmd_count > 0)
2034 DEBUG(D_transport) debug_printf("look for %d responses"
2035 " for previous pipelined cmds\n", prev_cmd_count);
2037 switch(sync_responses(sx, prev_cmd_count, 0))
2039 case RESP_BIT_HAD_2XX: /* OK */
2040 case RESP_HAD_2_AND_5: sx->good_RCPT = TRUE; /* OK & progress made */
2041 case RESP_BIT_HAD_5XX: sx->completed_addr = TRUE; /* progress made */
2042 case RESP_NOERROR: break; /* No 2xx or 5xx, but no probs */
2044 case RESP_EHLO_ERR_TLS:errno = ERRNO_TLSFAILURE;
2046 #ifndef DISABLE_PIPE_CONNECT
2047 case RESP_EPIPE_EHLO_ERR: /* non-2xx for pipelined banner or EHLO */
2049 case RESP_RCPT_TIMEO: /* Timeout on RCPT */
2050 default: return ERROR;/* I/O error, or any MAIL/DATA error */
2053 if (!sx->pending_BDAT)
2054 pipelining_active = FALSE;
2057 /* Reap response for an outstanding BDAT */
2059 if (sx->pending_BDAT)
2061 DEBUG(D_transport) debug_printf("look for one response for BDAT\n");
2063 if (!smtp_read_response(sx, sx->buffer, sizeof(sx->buffer), '2',
2064 ob->command_timeout))
2066 if (errno == 0 && sx->buffer[0] == '4')
2068 errno = ERRNO_DATA4XX; /*XXX does this actually get used? */
2069 sx->addrlist->more_errno |=
2070 ((sx->buffer[1] - '0')*10 + sx->buffer[2] - '0') << 8;
2075 sx->pending_BDAT = FALSE;
2076 pipelining_active = FALSE;
2078 else if (chunk_size > 0)
2079 sx->pending_BDAT = TRUE;
2082 sx->cmd_count = cmd_count;
2090 check_force_dane_conn(smtp_context * sx, smtp_transport_options_block * ob)
2093 if( sx->dane_required
2094 || verify_check_given_host(CUSS &ob->hosts_try_dane, sx->conn_args.host) == OK
2096 switch (rc = tlsa_lookup(sx->conn_args.host, &sx->conn_args.tlsa_dnsa, sx->dane_required))
2098 case OK: sx->conn_args.dane = TRUE;
2099 ob->tls_tempfail_tryclear = FALSE; /* force TLS */
2100 ob->tls_sni = sx->conn_args.host->name; /* force SNI */
2102 case FAIL_FORCED: break;
2103 default: set_errno_nohost(sx->addrlist, ERRNO_DNSDEFER,
2104 string_sprintf("DANE error: tlsa lookup %s",
2106 rc, FALSE, &sx->delivery_start);
2107 # ifndef DISABLE_EVENT
2108 (void) event_raise(sx->conn_args.tblock->event_action,
2109 US"dane:fail", sx->dane_required
2110 ? US"dane-required" : US"dnssec-invalid",
2120 /*************************************************
2121 * Make connection for given message *
2122 *************************************************/
2126 sx connection context
2127 suppress_tls if TRUE, don't attempt a TLS connection - this is set for
2128 a second attempt after TLS initialization fails
2130 Returns: OK - the connection was made and the delivery attempted;
2131 fd is set in the conn context, tls_out set up.
2132 DEFER - the connection could not be made, or something failed
2133 while setting up the SMTP session, or there was a
2134 non-message-specific error, such as a timeout.
2135 ERROR - helo_data or add_headers or authenticated_sender is
2136 specified for this transport, and the string failed
2140 smtp_setup_conn(smtp_context * sx, BOOL suppress_tls)
2142 smtp_transport_options_block * ob = sx->conn_args.tblock->options_block;
2143 BOOL pass_message = FALSE;
2144 uschar * message = NULL;
2147 uschar * tls_errstr;
2150 /* Many lines of clearing individual elements of *sx that used to
2151 be here have been replaced by a full memset to zero (de41aff051).
2152 There are two callers, this file and verify.c . Now we only set
2153 up nonzero elements. */
2155 sx->conn_args.ob = ob;
2157 sx->lmtp = strcmpic(ob->protocol, US"lmtp") == 0;
2158 sx->smtps = strcmpic(ob->protocol, US"smtps") == 0;
2159 sx->send_rset = TRUE;
2160 sx->send_quit = TRUE;
2161 sx->setting_up = TRUE;
2163 sx->dsn_all_lasthop = TRUE;
2166 verify_check_given_host(CUSS &ob->hosts_require_dane, sx->conn_args.host) == OK;
2169 if ((sx->max_mail = sx->conn_args.tblock->connection_max_messages) == 0)
2170 sx->max_mail = UNLIMITED_ADDRS;
2171 sx->max_rcpt = expand_max_rcpt(sx->conn_args.tblock->max_addresses);
2172 sx->igquotstr = US"";
2173 if (!sx->helo_data) sx->helo_data = ob->helo_data;
2175 smtp_command = US"initial connection";
2177 /* Set up the buffer for reading SMTP response packets. */
2179 sx->inblock.buffer = sx->inbuffer;
2180 sx->inblock.buffersize = sizeof(sx->inbuffer);
2181 sx->inblock.ptr = sx->inbuffer;
2182 sx->inblock.ptrend = sx->inbuffer;
2184 /* Set up the buffer for holding SMTP commands while pipelining */
2186 sx->outblock.buffer = sx->outbuffer;
2187 sx->outblock.buffersize = sizeof(sx->outbuffer);
2188 sx->outblock.ptr = sx->outbuffer;
2190 /* Reset the parameters of a TLS session. */
2193 tls_out.cipher = NULL; /* the one we may use for this transport */
2194 tls_out.ourcert = NULL;
2195 tls_out.peercert = NULL;
2196 tls_out.peerdn = NULL;
2200 tls_out.ocsp = OCSP_NOT_REQ;
2201 #ifndef DISABLE_TLS_RESUME
2202 tls_out.resumption = 0;
2206 /* Flip the legacy TLS-related variables over to the outbound set in case
2207 they're used in the context of the transport. Don't bother resetting
2208 afterward (when being used by a transport) as we're in a subprocess.
2209 For verify, unflipped once the callout is dealt with */
2211 tls_modify_variables(&tls_out);
2216 set_errno_nohost(sx->addrlist, ERRNO_TLSFAILURE, US"TLS support not available",
2217 DEFER, FALSE, &sx->delivery_start);
2222 /* If we have a proxied TLS connection, check usability for this message */
2224 if (continue_hostname && continue_proxy_cipher)
2227 const uschar * sni = US"";
2229 # ifdef SUPPORT_DANE
2230 /* Check if the message will be DANE-verified; if so force TLS and its SNI */
2232 tls_out.dane_verified = FALSE;
2233 smtp_port_for_connect(sx->conn_args.host, sx->port);
2234 if ( sx->conn_args.host->dnssec == DS_YES
2235 && (rc = check_force_dane_conn(sx, ob)) != OK
2240 /* If the SNI or the DANE status required for the new message differs from the
2241 existing conn drop the connection to force a new one. */
2243 if (ob->tls_sni && !(sni = expand_cstring(ob->tls_sni)))
2244 log_write(0, LOG_MAIN|LOG_PANIC,
2245 "<%s>: failed to expand transport's tls_sni value: %s",
2246 sx->addrlist->address, expand_string_message);
2248 # ifdef SUPPORT_DANE
2249 if ( (continue_proxy_sni ? (Ustrcmp(continue_proxy_sni, sni) == 0) : !*sni)
2250 && continue_proxy_dane == sx->conn_args.dane)
2252 tls_out.sni = US sni;
2253 if ((tls_out.dane_verified = continue_proxy_dane))
2254 sx->conn_args.host->dnssec = DS_YES;
2257 if ((continue_proxy_sni ? (Ustrcmp(continue_proxy_sni, sni) == 0) : !*sni))
2258 tls_out.sni = US sni;
2263 # ifdef SUPPORT_DANE
2264 if (continue_proxy_dane != sx->conn_args.dane)
2266 "Closing proxied-TLS connection due to dane requirement mismatch\n");
2269 debug_printf("Closing proxied-TLS connection (SNI '%s') "
2270 "due to SNI mismatch (transport requirement '%s')\n",
2271 continue_proxy_sni, sni);
2273 smtp_debug_cmd(US"QUIT", 0);
2274 write(0, "QUIT\r\n", 6);
2276 continue_hostname = continue_proxy_cipher = NULL;
2277 f.continue_more = FALSE;
2278 continue_sequence = 1; /* Ensure proper logging of non-cont-conn */
2281 #endif /*!DISABLE_TLS*/
2283 /* Make a connection to the host if this isn't a continued delivery, and handle
2284 the initial interaction and HELO/EHLO/LHLO. Connect timeout errors are handled
2285 specially so they can be identified for retries. */
2287 if (!continue_hostname)
2289 if (sx->verify) HDEBUG(D_verify)
2290 debug_printf("interface=%s port=%d\n", sx->conn_args.interface, sx->port);
2292 /* Get the actual port the connection will use, into sx->conn_args.host */
2294 smtp_port_for_connect(sx->conn_args.host, sx->port);
2297 /* Do TLSA lookup for DANE */
2299 tls_out.dane_verified = FALSE;
2300 tls_out.tlsa_usage = 0;
2302 if (sx->conn_args.host->dnssec == DS_YES)
2305 if ((rc = check_force_dane_conn(sx, ob)) != OK)
2308 else if (sx->dane_required)
2310 set_errno_nohost(sx->addrlist, ERRNO_DNSDEFER,
2311 string_sprintf("DANE error: %s lookup not DNSSEC", sx->conn_args.host->name),
2312 FAIL, FALSE, &sx->delivery_start);
2313 # ifndef DISABLE_EVENT
2314 (void) event_raise(sx->conn_args.tblock->event_action,
2315 US"dane:fail", US"dane-required", NULL);
2319 else DEBUG(D_transport)
2320 debug_printf("lack of DNSSEC traceability precludes DANE\n");
2324 /* Make the TCP connection */
2326 sx->cctx.tls_ctx = NULL;
2327 sx->inblock.cctx = sx->outblock.cctx = &sx->cctx;
2328 #ifndef DISABLE_ESMTP_LIMITS
2329 sx->peer_limit_mail = sx->peer_limit_rcpt = sx->peer_limit_rcptdom =
2331 sx->avoid_option = sx->peer_offered = smtp_peer_options = 0;
2332 smtp_debug_cmd_log_init();
2334 #ifndef DISABLE_PIPE_CONNECT
2335 if ( verify_check_given_host(CUSS &ob->hosts_pipe_connect,
2336 sx->conn_args.host) == OK)
2338 /* We don't find out the local ip address until the connect, so if
2339 the helo string might use it avoid doing early-pipelining. */
2342 || sx->conn_args.interface
2343 || !Ustrstr(sx->helo_data, "$sending_ip_address")
2344 || Ustrstr(sx->helo_data, "def:sending_ip_address")
2347 sx->early_pipe_ok = TRUE;
2348 if ( read_ehlo_cache_entry(sx)
2349 && sx->ehlo_resp.cleartext_features & OPTION_EARLY_PIPE)
2352 debug_printf("Using cached cleartext PIPECONNECT\n");
2353 sx->early_pipe_active = TRUE;
2354 sx->peer_offered = sx->ehlo_resp.cleartext_features;
2357 else DEBUG(D_transport)
2358 debug_printf("helo needs $sending_ip_address; avoid early-pipelining\n");
2361 if (sx->early_pipe_active)
2363 sx->outblock.conn_args = &sx->conn_args;
2364 (void) smtp_boundsock(&sx->conn_args);
2369 blob lazy_conn = {.data = NULL};
2370 /* For TLS-connect, a TFO lazy-connect is useful since the Client Hello
2371 can go on the TCP SYN. */
2373 if ((sx->cctx.sock = smtp_connect(&sx->conn_args,
2374 sx->smtps ? &lazy_conn : NULL)) < 0)
2376 set_errno_nohost(sx->addrlist,
2377 errno == ETIMEDOUT ? ERRNO_CONNECTTIMEOUT : errno,
2378 sx->verify ? US strerror(errno) : NULL,
2379 DEFER, FALSE, &sx->delivery_start);
2380 sx->send_quit = FALSE;
2384 (void) setsockopt(sx->cctx.sock, IPPROTO_TCP, TCP_QUICKACK, US &off,
2388 /* Expand the greeting message while waiting for the initial response. (Makes
2389 sense if helo_data contains ${lookup dnsdb ...} stuff). The expansion is
2390 delayed till here so that $sending_ip_address and $sending_port are set.
2391 Those will be known even for a TFO lazy-connect, having been set by the bind().
2392 For early-pipe, we are ok if binding to a local interface; otherwise (if
2393 $sending_ip_address is seen in helo_data) we disabled early-pipe above. */
2395 GET_OPTION("helo_data");
2397 if (!(sx->helo_data = expand_string(sx->helo_data)))
2399 log_write(0, LOG_MAIN|LOG_PANIC,
2400 "<%s>: failed to expand transport's helo_data value for callout: %s",
2401 sx->addrlist->address, expand_string_message);
2406 expand_string_message = NULL;
2407 if ((sx->helo_data = string_domain_utf8_to_alabel(sx->helo_data,
2408 &expand_string_message)),
2409 expand_string_message)
2411 log_write(0, LOG_MAIN|LOG_PANIC,
2412 "<%s>: failed to expand transport's helo_data value for callout: %s",
2413 sx->addrlist->address, expand_string_message);
2415 sx->helo_data = NULL;
2419 /* The first thing is to wait for an initial OK response. The dreaded "goto"
2420 is nevertheless a reasonably clean way of programming this kind of logic,
2421 where you want to escape on any error. */
2425 #ifndef DISABLE_PIPE_CONNECT
2426 if (sx->early_pipe_active)
2428 sx->pending_BANNER = TRUE; /* sync_responses() must eventually handle */
2429 sx->outblock.cmd_count = 1;
2434 if (!smtp_reap_banner(sx))
2435 goto RESPONSE_FAILED;
2438 #ifndef DISABLE_EVENT
2441 lookup_dnssec_authenticated = sx->conn_args.host->dnssec==DS_YES ? US"yes"
2442 : sx->conn_args.host->dnssec==DS_NO ? US"no" : NULL;
2443 s = event_raise(sx->conn_args.tblock->event_action, US"smtp:connect", sx->buffer, NULL);
2446 set_errno_nohost(sx->addrlist, ERRNO_EXPANDFAIL,
2447 string_sprintf("deferred by smtp:connect event expansion: %s", s),
2448 DEFER, FALSE, &sx->delivery_start);
2455 /* Now check if the helo_data expansion went well, and sign off cleanly if
2460 message = string_sprintf("failed to expand helo_data: %s",
2461 expand_string_message);
2462 set_errno_nohost(sx->addrlist, ERRNO_EXPANDFAIL, message, DEFER, FALSE, &sx->delivery_start);
2468 /** Debugging without sending a message
2469 sx->addrlist->transport_return = DEFER;
2473 /* Errors that occur after this point follow an SMTP command, which is
2474 left in big_buffer by smtp_write_command() for use in error messages. */
2476 smtp_command = big_buffer;
2478 /* Tell the remote who we are...
2480 February 1998: A convention has evolved that ESMTP-speaking MTAs include the
2481 string "ESMTP" in their greeting lines, so make Exim send EHLO if the
2482 greeting is of this form. The assumption was that the far end supports it
2483 properly... but experience shows that there are some that give 5xx responses,
2484 even though the banner includes "ESMTP" (there's a bloody-minded one that
2485 says "ESMTP not spoken here"). Cope with that case.
2487 September 2000: Time has passed, and it seems reasonable now to always send
2488 EHLO at the start. It is also convenient to make the change while installing
2491 July 2003: Joachim Wieland met a broken server that advertises "PIPELINING"
2492 but times out after sending MAIL FROM, RCPT TO and DATA all together. There
2493 would be no way to send out the mails, so there is now a host list
2494 "hosts_avoid_esmtp" that disables ESMTP for special hosts and solves the
2495 PIPELINING problem as well. Maybe it can also be useful to cure other
2496 problems with broken servers.
2498 Exim originally sent "Helo" at this point and ran for nearly a year that way.
2499 Then somebody tried it with a Microsoft mailer... It seems that all other
2500 mailers use upper case for some reason (the RFC is quite clear about case
2501 independence) so, for peace of mind, I gave in. */
2503 sx->esmtp = verify_check_given_host(CUSS &ob->hosts_avoid_esmtp, sx->conn_args.host) != OK;
2505 /* Alas; be careful, since this goto is not an error-out, so conceivably
2506 we might set data between here and the target which we assume to exist
2507 and be usable. I can see this coming back to bite us. */
2513 smtp_peer_options |= OPTION_TLS;
2514 suppress_tls = FALSE;
2515 ob->tls_tempfail_tryclear = FALSE;
2516 smtp_command = US"SSL-on-connect";
2518 # ifndef DISABLE_TLS_RESUME
2519 /* Having no EHLO response yet, cannot peek there for a servername to detect
2520 an LB. Call this anyway, so that a dummy host_name_extract option value can
2521 force resumption attempts. */
2523 GET_OPTION("host_name_extract");
2524 if (!(s = ob->host_name_extract)) s = US"never-LB";
2525 ehlo_response_lbserver(sx, s);
2533 if (smtp_write_command(sx,
2534 #ifndef DISABLE_PIPE_CONNECT
2535 sx->early_pipe_active ? SCMD_BUFFER :
2538 "%s %s\r\n", sx->lmtp ? "LHLO" : "EHLO", sx->helo_data) < 0)
2540 sx->esmtp_sent = TRUE;
2542 #ifndef DISABLE_PIPE_CONNECT
2543 if (sx->early_pipe_active)
2545 sx->pending_EHLO = TRUE;
2547 /* If we have too many authenticators to handle and might need to AUTH
2548 for this transport, pipeline no further as we will need the
2549 list of auth methods offered. Reap the banner and EHLO. */
2551 if ( (ob->hosts_require_auth || ob->hosts_try_auth)
2552 && f.smtp_in_early_pipe_no_auth)
2555 debug_printf("may need to auth, so pipeline no further\n");
2556 if (smtp_write_command(sx, SCMD_FLUSH, NULL) < 0)
2558 if (sync_responses(sx, 2, 0) != RESP_NOERROR)
2561 debug_printf("failed reaping pipelined cmd responses\n");
2562 goto RESPONSE_FAILED;
2564 sx->early_pipe_active = FALSE;
2569 if (!smtp_reap_ehlo(sx))
2570 goto RESPONSE_FAILED;
2574 debug_printf("not sending EHLO (host matches hosts_avoid_esmtp)\n");
2576 #ifndef DISABLE_PIPE_CONNECT
2577 if (!sx->early_pipe_active)
2582 int n = sizeof(sx->buffer);
2583 uschar * rsp = sx->buffer;
2585 if (sx->esmtp_sent && (n = Ustrlen(sx->buffer) + 1) < sizeof(sx->buffer)/2)
2586 { rsp = sx->buffer + n; n = sizeof(sx->buffer) - n; }
2588 if (smtp_write_command(sx, SCMD_FLUSH, "HELO %s\r\n", sx->helo_data) < 0)
2590 good_response = smtp_read_response(sx, rsp, n, '2', ob->command_timeout);
2591 #ifdef EXPERIMENTAL_DSN_INFO
2592 sx->helo_response = string_copy(rsp);
2596 /* Handle special logging for a closed connection after HELO
2597 when had previously sent EHLO */
2599 if (rsp != sx->buffer && rsp[0] == 0 && (errno == 0 || errno == ECONNRESET))
2601 errno = ERRNO_SMTPCLOSED;
2602 goto EHLOHELO_FAILED;
2604 memmove(sx->buffer, rsp, Ustrlen(rsp));
2605 goto RESPONSE_FAILED;
2609 if (sx->esmtp || sx->lmtp)
2611 #ifndef DISABLE_PIPE_CONNECT
2612 if (!sx->early_pipe_active)
2617 sx->peer_offered = ehlo_response(sx->buffer,
2618 OPTION_TLS /* others checked later */
2619 #ifndef DISABLE_PIPE_CONNECT
2620 | (sx->early_pipe_ok
2622 | OPTION_CHUNKING | OPTION_PRDR | OPTION_DSN | OPTION_PIPE | OPTION_SIZE
2631 #ifndef DISABLE_ESMTP_LIMITS
2632 if (tls_out.active.sock >= 0 || !(sx->peer_offered & OPTION_TLS))
2634 ehlo_response_limits_read(sx);
2635 ehlo_response_limits_apply(sx);
2638 #ifndef DISABLE_PIPE_CONNECT
2639 if (sx->early_pipe_ok)
2641 sx->ehlo_resp.cleartext_features = sx->peer_offered;
2643 if ( (sx->peer_offered & (OPTION_PIPE | OPTION_EARLY_PIPE))
2644 == (OPTION_PIPE | OPTION_EARLY_PIPE))
2647 debug_printf("PIPECONNECT usable in future for this IP\n");
2648 sx->ehlo_resp.cleartext_auths = study_ehlo_auths(sx);
2649 write_ehlo_cache_entry(sx);
2653 #if !defined(DISABLE_TLS) && !defined(DISABLE_TLS_RESUME)
2654 GET_OPTION("host_name_extract");
2655 if (!(s = ob->host_name_extract)) s = HNE_DEFAULT;
2656 ehlo_response_lbserver(sx, s);
2660 /* Set tls_offered if the response to EHLO specifies support for STARTTLS. */
2663 smtp_peer_options |= sx->peer_offered & OPTION_TLS;
2668 /* For continuing deliveries down the same channel, the socket
2669 is the standard input; for a socket held open from verify it is recorded
2670 in the cutthrough context block. Either way we don't need to redo EHLO here
2671 (but may need to do so for TLS - see below).
2672 Set up the pointer "smtp_command" to where subsequent commands will be left,
2673 for error messages. Other stuff was set up for us by the delivery process. */
2675 /*XXX continue case needs to propagate DSN_INFO, prob. in deliver.c
2676 as the continue goes via pass-fd to the delivery process.
2677 It does not wait. Unclear how we keep separate host's responses
2678 separate - we could match up by host ip+port as a bodge. */
2682 if (cutthrough.cctx.sock >= 0 && cutthrough.callout_hold_only)
2684 sx->cctx = cutthrough.cctx;
2685 sx->conn_args.host->port = sx->port = cutthrough.host.port;
2689 sx->cctx.sock = 0; /* stdin */
2690 sx->cctx.tls_ctx = NULL;
2691 smtp_port_for_connect(sx->conn_args.host, sx->port); /* Record the port that was used */
2693 smtp_command = big_buffer;
2694 sx->inblock.cctx = sx->outblock.cctx = &sx->cctx;
2695 sx->peer_offered = smtp_peer_options;
2696 #ifndef DISABLE_ESMTP_LIMITS
2697 /* Limits passed by cmdline over exec. */
2698 ehlo_limits_apply(sx,
2699 sx->peer_limit_mail = continue_limit_mail,
2700 sx->peer_limit_rcpt = continue_limit_rcpt,
2701 sx->peer_limit_rcptdom = continue_limit_rcptdom);
2703 sx->helo_data = NULL; /* ensure we re-expand ob->helo_data */
2705 /* For a continued connection with TLS being proxied for us, or a
2706 held-open verify connection with TLS, nothing more to do. */
2708 if ( continue_proxy_cipher
2709 || (cutthrough.cctx.sock >= 0 && cutthrough.callout_hold_only
2710 && cutthrough.is_tls)
2713 sx->pipelining_used = pipelining_active = !!(smtp_peer_options & OPTION_PIPE);
2714 HDEBUG(D_transport) debug_printf("continued connection, %s TLS\n",
2715 continue_proxy_cipher ? "proxied" : "verify conn with");
2717 tls_out.certificate_verified = !!(continue_flags & CTF_CV);
2719 tls_out.dane_verified = !!(continue_flags & CTF_DV);
2721 #ifndef DISABLE_TLS_RESUME
2722 if (continue_flags & CTF_TR) tls_out.resumption |= RESUME_USED;
2726 HDEBUG(D_transport) debug_printf("continued connection, no TLS\n");
2729 /* If TLS is available on this connection, whether continued or not, attempt to
2730 start up a TLS session, unless the host is in hosts_avoid_tls. If successful,
2731 send another EHLO - the server may give a different answer in secure mode. We
2732 use a separate buffer for reading the response to STARTTLS so that if it is
2733 negative, the original EHLO data is available for subsequent analysis, should
2734 the client not be required to use TLS. If the response is bad, copy the buffer
2735 for error analysis. */
2738 if ( smtp_peer_options & OPTION_TLS
2740 && verify_check_given_host(CUSS &ob->hosts_avoid_tls, sx->conn_args.host) != OK
2742 || verify_check_given_host(CUSS &ob->hosts_verify_avoid_tls, sx->conn_args.host) != OK
2745 uschar buffer2[4096];
2747 if (smtp_write_command(sx, SCMD_FLUSH, "STARTTLS\r\n") < 0)
2750 #ifndef DISABLE_PIPE_CONNECT
2751 /* If doing early-pipelining reap the banner and EHLO-response but leave
2752 the response for the STARTTLS we just sent alone. On fail, assume wrong
2753 cached capability and retry with the pipelining disabled. */
2755 if (sx->early_pipe_active)
2757 if (sync_responses(sx, 2, 0) != RESP_NOERROR)
2760 debug_printf("failed reaping pipelined cmd responses\n");
2761 close(sx->cctx.sock);
2763 sx->early_pipe_active = FALSE;
2764 goto PIPE_CONNECT_RETRY;
2769 /* If there is an I/O error, transmission of this message is deferred. If
2770 there is a temporary rejection of STARRTLS and tls_tempfail_tryclear is
2771 false, we also defer. However, if there is a temporary rejection of STARTTLS
2772 and tls_tempfail_tryclear is true, or if there is an outright rejection of
2773 STARTTLS, we carry on. This means we will try to send the message in clear,
2774 unless the host is in hosts_require_tls (tested below). */
2776 if (!smtp_read_response(sx, buffer2, sizeof(buffer2), '2', ob->command_timeout))
2780 || (buffer2[0] == '4' && !ob->tls_tempfail_tryclear)
2783 Ustrncpy(sx->buffer, buffer2, sizeof(sx->buffer));
2784 sx->buffer[sizeof(sx->buffer)-1] = '\0';
2785 goto RESPONSE_FAILED;
2789 /* STARTTLS accepted: try to negotiate a TLS session. */
2794 sx->conn_args.sending_ip_address = sending_ip_address;
2795 if (!tls_client_start(&sx->cctx, &sx->conn_args, sx->addrlist, &tls_out, &tls_errstr))
2797 /* TLS negotiation failed; give an error. From outside, this function may
2798 be called again to try in clear on a new connection, if the options permit
2799 it for this host. */
2801 DEBUG(D_tls) debug_printf("TLS session fail: %s\n", tls_errstr);
2803 # ifdef SUPPORT_DANE
2804 if (sx->conn_args.dane)
2806 log_write(0, LOG_MAIN,
2807 "DANE attempt failed; TLS connection to %s [%s]: %s",
2808 sx->conn_args.host->name, sx->conn_args.host->address, tls_errstr);
2809 # ifndef DISABLE_EVENT
2810 (void) event_raise(sx->conn_args.tblock->event_action,
2811 US"dane:fail", US"validation-failure", NULL); /* could do with better detail */
2816 errno = ERRNO_TLSFAILURE;
2817 message = string_sprintf("TLS session: %s", tls_errstr);
2818 sx->send_quit = FALSE;
2821 sx->send_tlsclose = TRUE;
2823 /* TLS session is set up. Check the inblock fill level. If there is
2824 content then as we have not yet done a tls read it must have arrived before
2825 the TLS handshake, in-clear. That violates the sync requirement of the
2826 STARTTLS RFC, so fail. */
2828 if (sx->inblock.ptr != sx->inblock.ptrend)
2832 int i = sx->inblock.ptrend - sx->inblock.ptr;
2833 debug_printf("unused data in input buffer after ack for STARTTLS:\n"
2835 i > 100 ? 100 : i, sx->inblock.ptr, i > 100 ? "..." : "");
2837 tls_errstr = US"synch error before connect";
2838 goto TLS_CONN_FAILED;
2841 smtp_peer_options_wrap = smtp_peer_options;
2842 for (address_item * addr = sx->addrlist; addr; addr = addr->next)
2843 if (addr->transport_return == PENDING_DEFER)
2845 addr->cipher = tls_out.cipher;
2846 addr->ourcert = tls_out.ourcert;
2847 addr->peercert = tls_out.peercert;
2848 addr->peerdn = tls_out.peerdn;
2849 addr->ocsp = tls_out.ocsp;
2850 addr->tlsver = tls_out.ver;
2855 /* if smtps, we'll have smtp_command set to something else; always safe to
2857 smtp_command = big_buffer;
2859 /* If we started TLS, redo the EHLO/LHLO exchange over the secure channel. If
2860 helo_data is null, we are dealing with a connection that was passed from
2861 another process, and so we won't have expanded helo_data above. We have to
2862 expand it here. $sending_ip_address and $sending_port are set up right at the
2863 start of the Exim process (in exim.c). */
2865 if (tls_out.active.sock >= 0)
2867 uschar * greeting_cmd;
2871 GET_OPTION("helo_data");
2872 if (!(sx->helo_data = expand_string(ob->helo_data)))
2874 uschar *message = string_sprintf("failed to expand helo_data: %s",
2875 expand_string_message);
2876 set_errno_nohost(sx->addrlist, ERRNO_EXPANDFAIL, message, DEFER, FALSE, &sx->delivery_start);
2882 #ifndef DISABLE_PIPE_CONNECT
2883 /* For SMTPS there is no cleartext early-pipe; use the crypted permission bit.
2884 We're unlikely to get the group sent and delivered before the server sends its
2885 banner, but it's still worth sending as a group.
2886 For STARTTLS allow for cleartext early-pipe but no crypted early-pipe, but not
2889 if (sx->smtps ? sx->early_pipe_ok : sx->early_pipe_active)
2891 sx->peer_offered = sx->ehlo_resp.crypted_features;
2892 if ((sx->early_pipe_active =
2893 !!(sx->ehlo_resp.crypted_features & OPTION_EARLY_PIPE)))
2894 DEBUG(D_transport) debug_printf("Using cached crypted PIPECONNECT\n");
2897 #ifdef EXPERIMMENTAL_ESMTP_LIMITS
2898 /* As we are about to send another EHLO, forget any LIMITS received so far. */
2899 sx->peer_limit_mail = sx->peer_limit_rcpt = sx->peer_limit_rcptdom = 0;
2900 if ((sx->max_mail = sx->conn_args.tblock->connection_max_message) == 0)
2901 sx->max_mail = UNLIMITED_ADDRS;
2902 sx->max_rcpt = expand_max_rcpt(sx->conn_args.tblock->max_addresses);
2903 sx->single_rcpt_domain = FALSE;
2906 /* For SMTPS we need to wait for the initial OK response. */
2908 #ifndef DISABLE_PIPE_CONNECT
2909 if (sx->early_pipe_active)
2911 sx->pending_BANNER = TRUE;
2912 sx->outblock.cmd_count = 1;
2916 if (!smtp_reap_banner(sx))
2917 goto RESPONSE_FAILED;
2920 greeting_cmd = US"LHLO";
2922 greeting_cmd = US"EHLO";
2925 greeting_cmd = US"HELO";
2927 debug_printf("not sending EHLO (host matches hosts_avoid_esmtp)\n");
2930 if (smtp_write_command(sx,
2931 #ifndef DISABLE_PIPE_CONNECT
2932 sx->early_pipe_active ? SCMD_BUFFER :
2935 "%s %s\r\n", greeting_cmd, sx->helo_data) < 0)
2938 #ifndef DISABLE_PIPE_CONNECT
2939 if (sx->early_pipe_active)
2940 sx->pending_EHLO = TRUE;
2944 if (!smtp_reap_ehlo(sx))
2947 /* The GnuTLS layer in Exim only spots a server-rejection of a client
2948 cert late, under TLS1.3 - which means here; the first time we try to
2949 receive crypted data. Treat it as if it was a connect-time failure.
2950 See also the early-pipe equivalent... which will be hard; every call
2951 to sync_responses will need to check the result.
2952 It would be nicer to have GnuTLS check the cert during the handshake.
2953 Can it do that, with all the flexibility we need? */
2955 tls_errstr = US"error on first read";
2956 goto TLS_CONN_FAILED;
2959 goto RESPONSE_FAILED;
2961 smtp_peer_options = 0;
2965 /* If the host is required to use a secure channel, ensure that we
2969 # ifdef SUPPORT_DANE
2970 || sx->conn_args.dane
2972 || verify_check_given_host(CUSS &ob->hosts_require_tls, sx->conn_args.host) == OK
2975 errno = ERRNO_TLSREQUIRED;
2976 message = string_sprintf("a TLS session is required, but %s",
2977 smtp_peer_options & OPTION_TLS
2978 ? "an attempt to start TLS failed" : "the server did not offer TLS support");
2979 # if defined(SUPPORT_DANE) && !defined(DISABLE_EVENT)
2980 if (sx->conn_args.dane)
2981 (void) event_raise(sx->conn_args.tblock->event_action, US"dane:fail",
2982 smtp_peer_options & OPTION_TLS
2983 ? US"validation-failure" /* could do with better detail */
2984 : US"starttls-not-supported",
2989 #endif /*DISABLE_TLS*/
2991 /* If TLS is active, we have just started it up and re-done the EHLO command,
2992 so its response needs to be analyzed. If TLS is not active and this is a
2993 continued session down a previously-used socket, we haven't just done EHLO, so
2996 if ( !continue_hostname
2998 || tls_out.active.sock >= 0
3002 if (sx->esmtp || sx->lmtp)
3004 #ifndef DISABLE_PIPE_CONNECT
3005 if (!sx->early_pipe_active)
3008 sx->peer_offered = ehlo_response(sx->buffer,
3010 #ifndef DISABLE_PIPE_CONNECT
3011 | (sx->lmtp && ob->lmtp_ignore_quota ? OPTION_IGNQ : 0)
3012 | OPTION_DSN | OPTION_PIPE | OPTION_SIZE
3013 | OPTION_CHUNKING | OPTION_PRDR | OPTION_UTF8
3014 | (tls_out.active.sock >= 0 ? OPTION_EARLY_PIPE : 0) /* not for lmtp */
3018 | (sx->lmtp && ob->lmtp_ignore_quota ? OPTION_IGNQ : 0)
3021 # ifdef SUPPORT_I18N
3022 | (sx->addrlist->prop.utf8_msg ? OPTION_UTF8 : 0)
3023 /*XXX if we hand peercaps on to continued-conn processes,
3024 must not depend on this addr */
3028 | (ob->size_addition >= 0 ? OPTION_SIZE : 0)
3031 #ifndef DISABLE_PIPE_CONNECT
3032 if (tls_out.active.sock >= 0)
3033 sx->ehlo_resp.crypted_features = sx->peer_offered;
3036 #ifndef DISABLE_ESMTP_LIMITS
3037 if (tls_out.active.sock >= 0 || !(sx->peer_offered & OPTION_TLS))
3039 ehlo_response_limits_read(sx);
3040 ehlo_response_limits_apply(sx);
3045 /* Set for IGNOREQUOTA if the response to LHLO specifies support and the
3046 lmtp_ignore_quota option was set. */
3048 sx->igquotstr = sx->peer_offered & OPTION_IGNQ ? US" IGNOREQUOTA" : US"";
3050 /* If the response to EHLO specified support for the SIZE parameter, note
3051 this, provided size_addition is non-negative. */
3053 smtp_peer_options |= sx->peer_offered & OPTION_SIZE;
3055 /* Note whether the server supports PIPELINING. If hosts_avoid_esmtp matched
3056 the current host, esmtp will be false, so PIPELINING can never be used. If
3057 the current host matches hosts_avoid_pipelining, don't do it. */
3059 if ( sx->peer_offered & OPTION_PIPE
3060 && verify_check_given_host(CUSS &ob->hosts_avoid_pipelining, sx->conn_args.host) != OK)
3061 smtp_peer_options |= OPTION_PIPE;
3063 DEBUG(D_transport) debug_printf("%susing PIPELINING\n",
3064 smtp_peer_options & OPTION_PIPE ? "" : "not ");
3066 if ( sx->peer_offered & OPTION_CHUNKING
3067 && verify_check_given_host(CUSS &ob->hosts_try_chunking, sx->conn_args.host) == OK)
3068 smtp_peer_options |= OPTION_CHUNKING;
3070 if (smtp_peer_options & OPTION_CHUNKING)
3071 DEBUG(D_transport) debug_printf("CHUNKING usable\n");
3073 #ifndef DISABLE_PRDR
3074 if ( sx->peer_offered & OPTION_PRDR
3075 && verify_check_given_host(CUSS &ob->hosts_try_prdr, sx->conn_args.host) == OK)
3076 smtp_peer_options |= OPTION_PRDR;
3078 if (smtp_peer_options & OPTION_PRDR)
3079 DEBUG(D_transport) debug_printf("PRDR usable\n");
3082 /* Note if the server supports DSN */
3083 smtp_peer_options |= sx->peer_offered & OPTION_DSN;
3084 DEBUG(D_transport) debug_printf("%susing DSN\n",
3085 sx->peer_offered & OPTION_DSN ? "" : "not ");
3087 #ifndef DISABLE_PIPE_CONNECT
3088 if ( sx->early_pipe_ok
3089 && !sx->early_pipe_active
3090 && tls_out.active.sock >= 0
3091 && smtp_peer_options & OPTION_PIPE
3092 && ( sx->ehlo_resp.cleartext_features | sx->ehlo_resp.crypted_features)
3093 & OPTION_EARLY_PIPE)
3095 DEBUG(D_transport) debug_printf("PIPECONNECT usable in future for this IP\n");
3096 sx->ehlo_resp.crypted_auths = study_ehlo_auths(sx);
3097 write_ehlo_cache_entry(sx);
3101 /* Note if the response to EHLO specifies support for the AUTH extension.
3102 If it has, check that this host is one we want to authenticate to, and do
3103 the business. The host name and address must be available when the
3104 authenticator's client driver is running. */
3106 switch (yield = smtp_auth(sx))
3108 default: goto SEND_QUIT;
3110 case FAIL_SEND: goto SEND_FAILED;
3111 case FAIL: goto RESPONSE_FAILED;
3115 sx->pipelining_used = pipelining_active = !!(smtp_peer_options & OPTION_PIPE);
3117 /* The setting up of the SMTP call is now complete. Any subsequent errors are
3118 message-specific. */
3120 sx->setting_up = FALSE;
3123 if (sx->addrlist->prop.utf8_msg)
3127 /* If the transport sets a downconversion mode it overrides any set by ACL
3130 GET_OPTION("utf8_downconvert");
3131 if ((s = ob->utf8_downconvert))
3133 if (!(s = expand_string(s)))
3135 message = string_sprintf("failed to expand utf8_downconvert: %s",
3136 expand_string_message);
3137 set_errno_nohost(sx->addrlist, ERRNO_EXPANDFAIL, message, DEFER, FALSE, &sx->delivery_start);
3143 case '1': sx->addrlist->prop.utf8_downcvt = TRUE;
3144 sx->addrlist->prop.utf8_downcvt_maybe = FALSE;
3146 case '0': sx->addrlist->prop.utf8_downcvt = FALSE;
3147 sx->addrlist->prop.utf8_downcvt_maybe = FALSE;
3149 case '-': if (s[1] == '1')
3151 sx->addrlist->prop.utf8_downcvt = FALSE;
3152 sx->addrlist->prop.utf8_downcvt_maybe = TRUE;
3158 sx->utf8_needed = !sx->addrlist->prop.utf8_downcvt
3159 && !sx->addrlist->prop.utf8_downcvt_maybe;
3160 DEBUG(D_transport) if (!sx->utf8_needed)
3161 debug_printf("utf8: %s downconvert\n",
3162 sx->addrlist->prop.utf8_downcvt ? "mandatory" : "optional");
3165 /* If this is an international message we need the host to speak SMTPUTF8 */
3166 if (sx->utf8_needed && !(sx->peer_offered & OPTION_UTF8))
3168 errno = ERRNO_UTF8_FWD;
3169 goto RESPONSE_FAILED;
3171 #endif /*SUPPORT_I18N*/
3180 if (errno == ECONNREFUSED) /* first-read error on a TFO conn */
3182 /* There is a testing facility for simulating a connection timeout, as I
3183 can't think of any other way of doing this. It converts a connection
3184 refused into a timeout if the timeout is set to 999999. This is done for
3185 a 3whs connection in ip_connect(), but a TFO connection does not error
3186 there - instead it gets ECONNREFUSED on the first data read. Tracking
3187 that a TFO really was done is too hard, or we would set a
3188 sx->pending_conn_done bit and test that in smtp_reap_banner() and
3189 smtp_reap_ehlo(). That would let us also add the conn-timeout to the
3192 if (f.running_in_test_harness && ob->connect_timeout == 999999)
3194 set_errno_nohost(sx->addrlist,
3195 errno == ETIMEDOUT ? ERRNO_CONNECTTIMEOUT : errno,
3196 sx->verify ? US strerror(errno) : NULL,
3197 DEFER, FALSE, &sx->delivery_start);
3198 sx->send_quit = FALSE;
3202 /* really an error on an SMTP read */
3204 sx->send_quit = check_response(sx->conn_args.host, &errno, sx->addrlist->more_errno,
3205 sx->buffer, &code, &message, &pass_message);
3211 message = US string_sprintf("smtp send to %s [%s] failed: %s",
3212 sx->conn_args.host->name, sx->conn_args.host->address, strerror(errno));
3213 sx->send_quit = FALSE;
3219 message = string_sprintf("Remote host closed connection in response to %s"
3220 " (EHLO response was: %s)", smtp_command, sx->buffer);
3221 sx->send_quit = FALSE;
3225 /* This label is jumped to directly when a TLS negotiation has failed,
3226 or was not done for a host for which it is required. Values will be set
3227 in message and errno, and setting_up will always be true. Treat as
3228 a temporary error. */
3232 code = '4', yield = DEFER;
3236 /* The failure happened while setting up the call; see if the failure was
3237 a 5xx response (this will either be on connection, or following HELO - a 5xx
3238 after EHLO causes it to try HELO). If so, and there are no more hosts to try,
3239 fail all addresses, as this host is never going to accept them. For other
3240 errors during setting up (timeouts or whatever), defer all addresses, and
3241 yield DEFER, so that the host is not tried again for a while.
3243 XXX This peeking for another host feels like a layering violation. We want
3244 to note the host as unusable, but down here we shouldn't know if this was
3245 the last host to try for the addr(list). Perhaps the upper layer should be
3246 the one to do set_errno() ? The problem is that currently the addr is where
3247 errno etc. are stashed, but until we run out of hosts to try the errors are
3248 host-specific. Maybe we should enhance the host_item definition? */
3251 sx->ok = FALSE; /* For when reached by GOTO */
3252 set_errno(sx->addrlist, errno, message,
3253 sx->conn_args.host->next
3257 || errno == ERRNO_UTF8_FWD
3261 errno == ECONNREFUSED ? NULL : sx->conn_args.host,
3262 #ifdef EXPERIMENTAL_DSN_INFO
3263 sx->smtp_greeting, sx->helo_response,
3265 &sx->delivery_start);
3272 (void)smtp_write_command(sx, SCMD_FLUSH, "QUIT\r\n");
3275 if (sx->cctx.tls_ctx)
3277 if (sx->send_tlsclose)
3279 tls_close(sx->cctx.tls_ctx, TLS_SHUTDOWN_NOWAIT);
3280 sx->send_tlsclose = FALSE;
3282 sx->cctx.tls_ctx = NULL;
3286 /* Close the socket, and return the appropriate value, first setting
3287 works because the NULL setting is passed back to the calling process, and
3288 remote_max_parallel is forced to 1 when delivering over an existing connection,
3291 HDEBUG(D_transport|D_acl|D_v) debug_printf_indent(" SMTP(close)>>\n");
3294 shutdown(sx->cctx.sock, SHUT_WR);
3295 if (fcntl(sx->cctx.sock, F_SETFL, O_NONBLOCK) == 0)
3296 for (int i = 16; read(sx->cctx.sock, sx->inbuffer, sizeof(sx->inbuffer)) > 0 && i > 0;)
3297 i--; /* drain socket */
3298 sx->send_quit = FALSE;
3300 (void)close(sx->cctx.sock);
3303 #ifndef DISABLE_EVENT
3304 (void) event_raise(sx->conn_args.tblock->event_action, US"tcp:close", NULL, NULL);
3307 continue_transport = NULL;
3308 continue_hostname = NULL;
3315 /* Create the string of options that will be appended to the MAIL FROM:
3316 in the connection context buffer */
3319 build_mailcmd_options(smtp_context * sx, address_item * addrlist)
3321 uschar * p = sx->buffer;
3322 address_item * addr;
3327 /* If we know the receiving MTA supports the SIZE qualification, and we know it,
3328 send it, adding something to the message size to allow for imprecision
3329 and things that get added en route. Exim keeps the number of lines
3330 in a message, so we can give an accurate value for the original message, but we
3331 need some additional to handle added headers. (Double "." characters don't get
3332 included in the count.) */
3334 if ( message_size > 0
3335 && sx->peer_offered & OPTION_SIZE && !(sx->avoid_option & OPTION_SIZE))
3337 /*XXX problem here under spool_files_wireformat?
3338 Or just forget about lines? Or inflate by a fixed proportion? */
3340 sprintf(CS p, " SIZE=%d", message_size+message_linecount+(SOB sx->conn_args.ob)->size_addition);
3344 #ifndef DISABLE_PRDR
3345 /* If it supports Per-Recipient Data Responses, and we have more than one recipient,
3348 sx->prdr_active = FALSE;
3349 if (smtp_peer_options & OPTION_PRDR)
3350 for (address_item * addr = addrlist; addr; addr = addr->next)
3351 if (addr->transport_return == PENDING_DEFER)
3353 for (addr = addr->next; addr; addr = addr->next)
3354 if (addr->transport_return == PENDING_DEFER)
3355 { /* at least two recipients to send */
3356 sx->prdr_active = TRUE;
3357 sprintf(CS p, " PRDR"); p += 5;
3365 /* If it supports internationalised messages, and this meesage need that,
3368 if ( sx->peer_offered & OPTION_UTF8
3369 && addrlist->prop.utf8_msg
3370 && !addrlist->prop.utf8_downcvt
3372 Ustrcpy(p, US" SMTPUTF8"), p += 9;
3375 /* check if all addresses have DSN-lasthop flag; do not send RET and ENVID if so */
3376 for (sx->dsn_all_lasthop = TRUE, addr = addrlist, address_count = 0;
3377 addr && address_count < sx->max_rcpt; /*XXX maybe also || sx->single_rcpt_domain ? */
3378 addr = addr->next) if (addr->transport_return == PENDING_DEFER)
3381 if (!(addr->dsn_flags & rf_dsnlasthop))
3383 sx->dsn_all_lasthop = FALSE;
3388 /* Add any DSN flags to the mail command */
3390 if (sx->peer_offered & OPTION_DSN && !sx->dsn_all_lasthop)
3392 if (dsn_ret == dsn_ret_hdrs)
3393 { Ustrcpy(p, US" RET=HDRS"); p += 9; }
3394 else if (dsn_ret == dsn_ret_full)
3395 { Ustrcpy(p, US" RET=FULL"); p += 9; }
3399 string_format(p, sizeof(sx->buffer) - (p-sx->buffer), " ENVID=%s", dsn_envid);
3404 /* If an authenticated_sender override has been specified for this transport
3405 instance, expand it. If the expansion is forced to fail, and there was already
3406 an authenticated_sender for this message, the original value will be used.
3407 Other expansion failures are serious. An empty result is ignored, but there is
3408 otherwise no check - this feature is expected to be used with LMTP and other
3409 cases where non-standard addresses (e.g. without domains) might be required. */
3411 return smtp_mail_auth_str(sx, p, addrlist) ? ERROR : OK;
3416 build_rcptcmd_options(smtp_context * sx, const address_item * addr)
3418 uschar * p = sx->buffer;
3421 /* Add any DSN flags to the rcpt command */
3423 if (sx->peer_offered & OPTION_DSN && !(addr->dsn_flags & rf_dsnlasthop))
3425 if (addr->dsn_flags & rf_dsnflags)
3429 Ustrcpy(p, US" NOTIFY=");
3431 for (int i = 0; i < nelem(rf_list); i++) if (addr->dsn_flags & rf_list[i])
3433 if (!first) *p++ = ',';
3435 Ustrcpy(p, rf_names[i]);
3440 if (addr->dsn_orcpt)
3442 string_format(p, sizeof(sx->buffer) - (p-sx->buffer), " ORCPT=%s",
3451 /* Send MAIL FROM and RCPT TO commands.
3452 See sw_mrc_t definition for return codes.
3456 smtp_write_mail_and_rcpt_cmds(smtp_context * sx, int * yield)
3458 address_item * addr;
3459 #ifndef DISABLE_ESMTP_LIMITS
3460 address_item * restart_addr = NULL;
3462 int address_count, pipe_limit;
3465 if (build_mailcmd_options(sx, sx->first_addr) != OK)
3468 return sw_mrc_bad_internal;
3471 /* From here until we send the DATA command, we can make use of PIPELINING
3472 if the server host supports it. The code has to be able to check the responses
3473 at any point, for when the buffer fills up, so we write it totally generally.
3474 When PIPELINING is off, each command written reports that it has flushed the
3477 sx->pending_MAIL = TRUE; /* The block starts with MAIL */
3480 const uschar * s = sx->from_addr;
3482 uschar * errstr = NULL;
3484 /* If we must downconvert, do the from-address here. Remember we had to
3485 for the to-addresses (done below), and also (ugly) for re-doing when building
3486 the delivery log line. */
3488 if ( sx->addrlist->prop.utf8_msg
3489 && (sx->addrlist->prop.utf8_downcvt || !(sx->peer_offered & OPTION_UTF8))
3492 if (s = string_address_utf8_to_alabel(s, &errstr), errstr)
3494 set_errno_nohost(sx->addrlist, ERRNO_EXPANDFAIL, errstr, DEFER, FALSE, &sx->delivery_start);
3496 return sw_mrc_bad_internal;
3498 setflag(sx->addrlist, af_utf8_downcvt);
3502 rc = smtp_write_command(sx, pipelining_active ? SCMD_BUFFER : SCMD_FLUSH,
3503 "MAIL FROM:<%s>%s\r\n", s, sx->buffer);
3506 mail_command = string_copy(big_buffer); /* Save for later error message */
3510 case -1: /* Transmission error */
3511 return sw_mrc_bad_mail;
3513 case +1: /* Cmd was sent */
3514 if (!smtp_read_response(sx, sx->buffer, sizeof(sx->buffer), '2',
3515 (SOB sx->conn_args.ob)->command_timeout))
3517 if (errno == 0 && sx->buffer[0] == '4')
3519 errno = ERRNO_MAIL4XX;
3520 sx->addrlist->more_errno |= ((sx->buffer[1] - '0')*10 + sx->buffer[2] - '0') << 8;
3522 return sw_mrc_bad_mail;
3524 sx->pending_MAIL = FALSE;
3527 /* otherwise zero: command queued for pipeline */
3530 /* Pass over all the relevant recipient addresses for this host, which are the
3531 ones that have status PENDING_DEFER. If we are using PIPELINING, we can send
3532 several before we have to read the responses for those seen so far. This
3533 checking is done by a subroutine because it also needs to be done at the end.
3534 Send only up to max_rcpt addresses at a time, leaving next_addr pointing to
3535 the next one if not all are sent.
3537 In the MUA wrapper situation, we want to flush the PIPELINING buffer for the
3538 last address because we want to abort if any recipients have any kind of
3539 problem, temporary or permanent. We know that all recipient addresses will have
3540 the PENDING_DEFER status, because only one attempt is ever made, and we know
3541 that max_rcpt will be large, so all addresses will be done at once.
3543 For verify we flush the pipeline after any (the only) rcpt address. */
3545 for (addr = sx->first_addr, address_count = 0, pipe_limit = 100;
3546 addr && address_count < sx->max_rcpt;
3547 addr = addr->next) if (addr->transport_return == PENDING_DEFER)
3551 const uschar * rcpt_addr;
3553 #ifndef DISABLE_ESMTP_LIMITS
3554 if ( sx->single_rcpt_domain /* restriction on domains */
3555 && address_count > 0 /* not first being sent */
3556 && Ustrcmp(addr->domain, sx->first_addr->domain) != 0 /* dom diff from first */
3559 DEBUG(D_transport) debug_printf("skipping different domain %s\n", addr->domain);
3561 /* Ensure the smtp-response reaper does not think the address had a RCPT
3562 command sent for it. Reset to PENDING_DEFER in smtp_deliver(), where we
3563 goto SEND_MESSAGE. */
3565 addr->transport_return = SKIP;
3566 if (!restart_addr) restart_addr = addr; /* note restart point */
3567 continue; /* skip this one */
3571 addr->dsn_aware = sx->peer_offered & OPTION_DSN
3572 ? dsn_support_yes : dsn_support_no;
3575 if (pipe_limit-- <= 0)
3576 { no_flush = FALSE; pipe_limit = 100; }
3578 no_flush = pipelining_active && !sx->verify
3579 && (!mua_wrapper || addr->next && address_count < sx->max_rcpt);
3581 build_rcptcmd_options(sx, addr);
3583 /* Now send the RCPT command, and process outstanding responses when
3584 necessary. After a timeout on RCPT, we just end the function, leaving the
3585 yield as OK, because this error can often mean that there is a problem with
3586 just one address, so we don't want to delay the host. */
3588 rcpt_addr = transport_rcpt_address(addr, sx->conn_args.tblock->rcpt_include_affixes);
3591 if ( testflag(sx->addrlist, af_utf8_downcvt)
3592 && !(rcpt_addr = string_address_utf8_to_alabel(rcpt_addr, NULL))
3595 /*XXX could we use a per-address errstr here? Not fail the whole send? */
3596 errno = ERRNO_EXPANDFAIL;
3597 return sw_mrc_tx_fail; /*XXX too harsh? */
3601 cmds_sent = smtp_write_command(sx, no_flush ? SCMD_BUFFER : SCMD_FLUSH,
3602 "RCPT TO:<%s>%s%s\r\n", rcpt_addr, sx->igquotstr, sx->buffer);
3604 if (cmds_sent < 0) return sw_mrc_tx_fail;
3607 switch(sync_responses(sx, cmds_sent, 0))
3609 case RESP_HAD_2_AND_5: sx->ok = TRUE; /* OK & progress made */
3610 case RESP_BIT_HAD_5XX: sx->completed_addr = TRUE; /* progress made */
3613 case RESP_BIT_HAD_2XX: sx->ok = TRUE; /* OK, but if LMTP, */
3614 if (!sx->lmtp) /* can't tell about progress yet */
3615 sx->completed_addr = TRUE;
3616 case RESP_NOERROR: /* No 2xx or 5xx, but no probs */
3617 /* If any RCPT got a 452 response then next_addr has been updated
3618 for restarting with a new MAIL on the same connection. Send no more
3619 RCPTs for this MAIL. */
3623 DEBUG(D_transport) debug_printf("seen 452 too-many-rcpts\n");
3624 sx->RCPT_452 = FALSE;
3625 /* sx->next_addr has been reset for fast_retry */
3630 case RESP_RCPT_TIMEO: return sw_mrc_nonmail_read_timeo;
3631 case RESP_RCPT_ERROR: return sw_mrc_bad_read;
3632 default: return sw_mrc_bad_mail; /* any MAIL error */
3634 #ifndef DISABLE_PIPE_CONNECT
3635 case RESP_EPIPE_EHLO_ERR: return sw_mrc_bad_mail; /* non-2xx for pipelined banner or EHLO */
3636 case RESP_EHLO_ERR_TLS: return sw_mrc_bad_mail; /* TLS first-read error */
3640 } /* Loop for next address */
3642 #ifndef DISABLE_ESMTP_LIMITS
3643 sx->next_addr = restart_addr ? restart_addr : addr;
3645 sx->next_addr = addr;
3652 /*****************************************************
3653 * Proxy TLS connection for another transport process *
3654 ******************************************************/
3656 Close the unused end of the pipe, fork once more, then use the given buffer
3657 as a staging area, and select on both the given fd and the TLS'd client-fd for
3658 data to read (per the coding in ip_recv() and fd_ready() this is legitimate).
3659 Do blocking full-size writes, and reads under a timeout. Once both input
3660 channels are closed, exit the process.
3664 buf space to use for buffering
3665 bufsiz size of buffer
3666 pfd pipe filedescriptor array; [0] is comms to proxied process
3667 timeout per-read timeout, seconds
3668 host hostname of remote
3674 smtp_proxy_tls(void * ct_ctx, uschar * buf, size_t bsize, int * pfd,
3675 int timeout, const uschar * host)
3677 struct pollfd p[2] = {{.fd = tls_out.active.sock, .events = POLLIN},
3678 {.fd = pfd[0], .events = POLLIN}};
3680 BOOL send_tls_shutdown = TRUE;
3684 if ((rc = exim_fork(US"tls-proxy")))
3685 _exit(rc < 0 ? EXIT_FAILURE : EXIT_SUCCESS);
3687 set_process_info("proxying TLS connection for continued transport to %s\n", host);
3691 time_t time_left = timeout;
3692 time_t time_start = time(NULL);
3697 rc = poll(p, 2, time_left * 1000);
3699 if (rc < 0 && errno == EINTR)
3700 if ((time_left -= time(NULL) - time_start) > 0) continue;
3704 DEBUG(D_transport) if (rc == 0) debug_printf("%s: timed out\n", __FUNCTION__);
3708 /* For errors where not readable, bomb out */
3710 if (p[0].revents & POLLERR || p[1].revents & POLLERR)
3712 DEBUG(D_transport) debug_printf("select: exceptional cond on %s fd\n",
3713 p[0].revents & POLLERR ? "tls" : "proxy");
3714 if (!(p[0].revents & POLLIN || p[1].events & POLLIN))
3716 DEBUG(D_transport) debug_printf("- but also readable; no exit yet\n");
3719 while (rc < 0 || !(p[0].revents & POLLIN || p[1].revents & POLLIN));
3721 /* handle inbound data */
3722 if (p[0].revents & POLLIN)
3723 if ((rc = tls_read(ct_ctx, buf, bsize)) <= 0) /* Expect -1 for EOF; */
3724 { /* that reaps the TLS Close Notify record */
3726 shutdown(pfd[0], SHUT_WR);
3730 for (int nbytes = 0; rc - nbytes > 0; nbytes += i)
3731 if ((i = write(pfd[0], buf + nbytes, rc - nbytes)) < 0) goto done;
3733 /* Handle outbound data. We cannot yet combine payload and the TLS-close
3734 due to the limitations of the (pipe) channel feeding us. Could we use
3735 a poll/POLLRDHUP? Would that need an extra poll call after every read
3736 (likely not worth it), or (best case) could we get POLLIN+POLLRDHUP for
3737 the final data blob? */
3739 if (p[1].revents & POLLIN)
3740 if ((rc = read(pfd[0], buf, bsize)) <= 0)
3744 # ifdef EXIM_TCP_CORK /* Use _CORK to get TLS Close Notify in FIN segment */
3745 (void) setsockopt(tls_out.active.sock, IPPROTO_TCP, EXIM_TCP_CORK, US &on, sizeof(on));
3747 tls_shutdown_wr(ct_ctx);
3748 send_tls_shutdown = FALSE;
3749 shutdown(tls_out.active.sock, SHUT_WR);
3752 for (int nbytes = 0; rc - nbytes > 0; nbytes += i)
3753 if ((i = tls_write(ct_ctx, buf + nbytes, rc - nbytes, FALSE)) < 0)
3756 while (p[0].fd >= 0 || p[1].fd >= 0);
3759 if (send_tls_shutdown) tls_close(ct_ctx, TLS_SHUTDOWN_NOWAIT);
3761 testharness_pause_ms(100); /* let logging complete */
3762 exim_exit(EXIT_SUCCESS);
3767 /*************************************************
3768 * Deliver address list to given host *
3769 *************************************************/
3771 /* If continue_hostname is not null, we get here only when continuing to
3772 deliver down an existing channel. The channel was passed as the standard
3773 input. TLS is never active on a passed channel; the previous process either
3774 closes it down before passing the connection on, or inserts a TLS-proxy
3775 process and passes on a cleartext conection.
3777 Otherwise, we have to make a connection to the remote host, and do the
3778 initial protocol exchange.
3780 When running as an MUA wrapper, if the sender or any recipient is rejected,
3781 temporarily or permanently, we force failure for all recipients.
3784 addrlist chain of potential addresses to deliver; only those whose
3785 transport_return field is set to PENDING_DEFER are currently
3786 being processed; others should be skipped - they have either
3787 been delivered to an earlier host or IP address, or been
3788 failed by one of them.
3789 host host to deliver to
3790 host_af AF_INET or AF_INET6
3791 defport default TCP/IP port to use if host does not specify, in host
3793 interface interface to bind to, or NULL
3794 tblock transport instance block
3795 message_defer set TRUE if yield is OK, but all addresses were deferred
3796 because of a non-recipient, non-host failure, that is, a
3797 4xx response to MAIL FROM, DATA, or ".". This is a defer
3798 that is specific to the message.
3799 suppress_tls if TRUE, don't attempt a TLS connection - this is set for
3800 a second attempt after TLS initialization fails
3802 Returns: OK - the connection was made and the delivery attempted;
3803 the result for each address is in its data block.
3804 DEFER - the connection could not be made, or something failed
3805 while setting up the SMTP session, or there was a
3806 non-message-specific error, such as a timeout.
3807 ERROR - a filter command is specified for this transport,
3808 and there was a problem setting it up; OR helo_data
3809 or add_headers or authenticated_sender is specified
3810 for this transport, and the string failed to expand
3812 For all non-OK returns the first addr of the list carries the
3813 time taken for the attempt.
3817 smtp_deliver(address_item *addrlist, host_item *host, int host_af, int defport,
3818 uschar *interface, transport_instance *tblock,
3819 BOOL *message_defer, BOOL suppress_tls)
3821 smtp_transport_options_block * ob = SOB tblock->options_block;
3826 uschar *message = NULL;
3827 smtp_context * sx = store_get(sizeof(*sx), GET_TAINTED); /* tainted, for the data buffers */
3828 BOOL pass_message = FALSE;
3829 #ifndef DISABLE_ESMTP_LIMITS
3830 BOOL mail_limit = FALSE;
3835 BOOL tcw_done = FALSE, tcw = FALSE, passback_conn = FALSE;
3837 *message_defer = FALSE;
3838 continue_next_id[0] = '\0';
3840 memset(sx, 0, sizeof(*sx));
3841 sx->addrlist = addrlist;
3842 sx->conn_args.host = host;
3843 sx->conn_args.host_af = host_af;
3845 sx->conn_args.interface = interface;
3846 sx->helo_data = NULL;
3847 sx->conn_args.tblock = tblock;
3848 sx->conn_args.sock = -1;
3849 gettimeofday(&sx->delivery_start, NULL);
3850 sx->sync_addr = sx->first_addr = addrlist;
3857 /* Get the channel set up ready for a message, MAIL FROM being the next
3858 SMTP command to send. */
3860 if ((rc = smtp_setup_conn(sx, suppress_tls)) != OK)
3862 timesince(&addrlist->delivery_time, &sx->delivery_start);
3868 /* If the connection used DANE, ignore for now any addresses with incompatible
3869 domains. The SNI has to be the domain. Arrange a whole new TCP conn later,
3870 just in case only TLS isn't enough. */
3872 if (sx->conn_args.dane)
3874 const uschar * dane_domain = sx->first_addr->domain;
3876 for (address_item * a = sx->first_addr->next; a; a = a->next)
3877 if ( a->transport_return == PENDING_DEFER
3878 && Ustrcmp(dane_domain, a->domain) != 0)
3880 DEBUG(D_transport) debug_printf("DANE: holding %s for later\n", a->domain);
3882 a->transport_return = DANE;
3887 /* If there is a filter command specified for this transport, we can now
3888 set it up. This cannot be done until the identity of the host is known. */
3890 if (tblock->filter_command)
3892 transport_filter_timeout = tblock->filter_timeout;
3894 /* On failure, copy the error to all addresses, abandon the SMTP call, and
3897 if (!transport_set_up_command(&transport_filter_argv,
3898 tblock->filter_command, TSUC_EXPAND_ARGS, DEFER, addrlist,
3899 string_sprintf("%.50s transport filter", tblock->name), NULL))
3901 set_errno_nohost(addrlist->next, addrlist->basic_errno, addrlist->message, DEFER,
3902 FALSE, &sx->delivery_start);
3907 if ( transport_filter_argv
3908 && *transport_filter_argv
3909 && **transport_filter_argv
3910 && smtp_peer_options & OPTION_CHUNKING
3911 #ifndef DISABLE_DKIM
3912 /* When dkim signing, chunking is handled even with a transport-filter */
3913 && !(ob->dkim.dkim_private_key && ob->dkim.dkim_domain && ob->dkim.dkim_selector)
3914 && !ob->dkim.force_bodyhash
3918 smtp_peer_options &= ~OPTION_CHUNKING;
3919 DEBUG(D_transport) debug_printf("CHUNKING not usable due to transport filter\n");
3923 /* For messages that have more than the maximum number of envelope recipients,
3924 we want to send several transactions down the same SMTP connection. (See
3925 comments in deliver.c as to how this reconciles, heuristically, with
3926 remote_max_parallel.) This optimization was added to Exim after the following
3927 code was already working. The simplest way to put it in without disturbing the
3928 code was to use a goto to jump back to this point when there is another
3929 transaction to handle. */
3932 sx->from_addr = return_path;
3933 sx->sync_addr = sx->first_addr;
3935 sx->send_rset = TRUE;
3936 sx->completed_addr = FALSE;
3939 /* If we are a continued-connection-after-verify the MAIL and RCPT
3940 commands were already sent; do not re-send but do mark the addrs as
3941 having been accepted up to RCPT stage. A traditional cont-conn
3942 always has a sequence number greater than one. */
3944 if (continue_hostname && continue_sequence == 1)
3946 /* sx->pending_MAIL = FALSE; */
3948 /* sx->next_addr = NULL; */
3950 for (address_item * addr = addrlist; addr; addr = addr->next)
3951 addr->transport_return = PENDING_OK;
3955 /* Initiate a message transfer. */
3957 switch(smtp_write_mail_and_rcpt_cmds(sx, &yield))
3959 case sw_mrc_ok: break;
3960 case sw_mrc_bad_mail: goto RESPONSE_FAILED;
3961 case sw_mrc_bad_read: goto RESPONSE_FAILED;
3962 case sw_mrc_nonmail_read_timeo: goto END_OFF;
3963 case sw_mrc_bad_internal: goto SEND_QUIT;
3964 default: goto SEND_FAILED;
3967 /* If we are an MUA wrapper, abort if any RCPTs were rejected, either
3968 permanently or temporarily. We should have flushed and synced after the last
3976 for (a = sx->first_addr, cnt = 0; a && cnt < sx->max_rcpt; a = a->next, cnt++)
3977 if (a->transport_return != PENDING_OK)
3979 /*XXX could we find a better errno than 0 here? */
3980 set_errno_nohost(addrlist, 0, a->message, FAIL,
3981 testflag(a, af_pass_message), &sx->delivery_start);
3988 /* If ok is TRUE, we know we have got at least one good recipient, and must now
3989 send DATA, but if it is FALSE (in the normal, non-wrapper case), we may still
3990 have a good recipient buffered up if we are pipelining. We don't want to waste
3991 time sending DATA needlessly, so we only send it if either ok is TRUE or if we
3992 are pipelining. The responses are all handled by sync_responses().
3993 If using CHUNKING, do not send a BDAT until we know how big a chunk we want
3996 if ( !(smtp_peer_options & OPTION_CHUNKING)
3997 && (sx->ok || (pipelining_active && !mua_wrapper)))
3999 int count = smtp_write_command(sx, SCMD_FLUSH, "DATA\r\n");
4001 if (count < 0) goto SEND_FAILED;
4003 switch(sync_responses(sx, count, sx->ok ? +1 : -1))
4005 case RESP_HAD_2_AND_5: sx->ok = TRUE; /* OK & progress made */
4006 case RESP_BIT_HAD_5XX: sx->completed_addr = TRUE; /* progress made */
4009 case RESP_BIT_HAD_2XX: sx->ok = TRUE; /* OK, but if LMTP, */
4010 if (!sx->lmtp) /* can't tell about progress yet */
4011 sx->completed_addr = TRUE;
4012 case RESP_NOERROR: break; /* No 2xx or 5xx, but no probs */
4014 case RESP_RCPT_TIMEO: goto END_OFF;
4016 #ifndef DISABLE_PIPE_CONNECT
4017 case -5: /* TLS first-read error */
4018 case -4: HDEBUG(D_transport)
4019 debug_printf("failed reaping pipelined cmd responses\n");
4021 default: goto RESPONSE_FAILED; /* I/O error, or any MAIL/DATA error */
4023 pipelining_active = FALSE;
4024 data_command = string_copy(big_buffer); /* Save for later error message */
4027 /* If there were no good recipients (but otherwise there have been no
4028 problems), just set ok TRUE, since we have handled address-specific errors
4029 already. Otherwise, it's OK to send the message. Use the check/escape mechanism
4030 for handling the SMTP dot-handling protocol, flagging to apply to headers as
4031 well as body. Set the appropriate timeout value to be used for each chunk.
4032 (Haven't been able to make it work using select() for writing yet.) */
4035 && (!(smtp_peer_options & OPTION_CHUNKING) || !pipelining_active))
4037 /* Save the first address of the next batch. */
4038 sx->first_addr = sx->next_addr;
4044 transport_ctx tctx = {
4045 .u = {.fd = sx->cctx.sock}, /*XXX will this need TLS info? */
4048 .check_string = US".",
4049 .escape_string = US"..", /* Escaping strings */
4051 topt_use_crlf | topt_escape_headers
4052 | (tblock->body_only ? topt_no_headers : 0)
4053 | (tblock->headers_only ? topt_no_body : 0)
4054 | (tblock->return_path_add ? topt_add_return_path : 0)
4055 | (tblock->delivery_date_add ? topt_add_delivery_date : 0)
4056 | (tblock->envelope_to_add ? topt_add_envelope_to : 0)
4059 /* If using CHUNKING we need a callback from the generic transport
4060 support to us, for the sending of BDAT smtp commands and the reaping
4061 of responses. The callback needs a whole bunch of state so set up
4062 a transport-context structure to be passed around. */
4064 if (smtp_peer_options & OPTION_CHUNKING)
4066 tctx.check_string = tctx.escape_string = NULL;
4067 tctx.options |= topt_use_bdat;
4068 tctx.chunk_cb = smtp_chunk_cmd_callback;
4069 sx->pending_BDAT = FALSE;
4070 sx->good_RCPT = sx->ok;
4072 tctx.smtp_context = sx;
4075 tctx.options |= topt_end_dot;
4077 /* Save the first address of the next batch. */
4078 sx->first_addr = sx->next_addr;
4080 /* Responses from CHUNKING commands go in buffer. Otherwise,
4081 there has not been a response. */
4085 sigalrm_seen = FALSE;
4086 transport_write_timeout = ob->data_timeout;
4087 smtp_command = US"sending data block"; /* For error messages */
4088 DEBUG(D_transport|D_v)
4089 if (smtp_peer_options & OPTION_CHUNKING)
4090 debug_printf(" will write message using CHUNKING\n");
4092 debug_printf(" SMTP>> (writing message)\n");
4093 transport_count = 0;
4095 #ifndef DISABLE_DKIM
4097 # ifdef MEASURE_TIMING
4099 gettimeofday(&t0, NULL);
4101 dkim_exim_sign_init();
4102 # ifdef EXPERIMENTAL_ARC
4104 uschar * s = ob->arc_sign;
4107 if (!(ob->dkim.arc_signspec = s = expand_string(s)))
4109 if (!f.expand_string_forcedfail)
4111 message = US"failed to expand arc_sign";
4118 /* Ask dkim code to hash the body for ARC */
4119 (void) arc_ams_setup_sign_bodyhash();
4120 ob->dkim.force_bodyhash = TRUE;
4125 # ifdef MEASURE_TIMING
4126 report_time_since(&t0, US"dkim_exim_sign_init (delta)");
4131 /* See if we can pipeline QUIT. Reasons not to are
4132 - pipelining not active
4133 - not ok to send quit
4134 - errors in amtp transation responses
4135 - more addrs to send for this message or this host
4136 - this message was being retried
4137 - more messages for this host
4138 If we can, we want the message-write to not flush (the tail end of) its data out. */
4140 if ( sx->pipelining_used
4141 && (sx->ok && sx->completed_addr || smtp_peer_options & OPTION_CHUNKING)
4143 && !(sx->first_addr || f.continue_more)
4144 && f.deliver_firsttime
4147 smtp_compare_t t_compare =
4148 {.tblock = tblock, .current_sender_address = sender_address};
4153 ( tls_out.active.sock < 0 && !continue_proxy_cipher
4154 || verify_check_given_host(CUSS &ob->hosts_nopass_tls, host) != OK
4158 transport_check_waiting(tblock->name, host->name,
4159 tblock->connection_max_messages, continue_next_id,
4160 (oicf)smtp_are_same_identities, (void*)&t_compare);
4163 HDEBUG(D_transport) debug_printf("will pipeline QUIT\n");
4164 tctx.options |= topt_no_flush;
4168 #ifndef DISABLE_DKIM
4169 sx->ok = dkim_transport_write_message(&tctx, &ob->dkim, CUSS &message);
4171 sx->ok = transport_write_message(&tctx, 0);
4174 /* transport_write_message() uses write() because it is called from other
4175 places to write to non-sockets. This means that under some OS (e.g. Solaris)
4176 it can exit with "Broken pipe" as its error. This really means that the
4177 socket got closed at the far end. */
4179 transport_write_timeout = 0; /* for subsequent transports */
4181 /* Failure can either be some kind of I/O disaster (including timeout),
4182 or the failure of a transport filter or the expansion of added headers.
4183 Or, when CHUNKING, it can be a protocol-detected failure. */
4186 if (message) goto SEND_FAILED;
4187 else goto RESPONSE_FAILED;
4189 /* We used to send the terminating "." explicitly here, but because of
4190 buffering effects at both ends of TCP/IP connections, you don't gain
4191 anything by keeping it separate, so it might as well go in the final
4192 data buffer for efficiency. This is now done by setting the topt_end_dot
4195 smtp_command = US"end of data";
4197 /* If we can pipeline a QUIT with the data them send it now. If a new message
4198 for this host appeared in the queue while data was being sent, we will not see
4199 it and it will have to wait for a queue run. If there was one but another
4200 thread took it, we might attempt to send it - but locking of spoolfiles will
4201 detect that. Use _MORE to get QUIT in FIN segment. */
4203 if (tcw_done && !tcw)
4205 /*XXX jgh 2021/03/10 google et. al screwup. G, at least, sends TCP FIN in response to TLS
4206 close-notify. Under TLS 1.3, violating RFC.
4207 However, TLS 1.2 does not have half-close semantics. */
4209 if ( sx->cctx.tls_ctx
4210 #if 0 && !defined(DISABLE_TLS)
4211 && Ustrcmp(tls_out.ver, "TLS1.3") != 0
4213 || !f.deliver_firsttime
4215 { /* Send QUIT now and not later */
4216 (void)smtp_write_command(sx, SCMD_FLUSH, "QUIT\r\n");
4217 sx->send_quit = FALSE;
4220 { /* add QUIT to the output buffer */
4221 (void)smtp_write_command(sx, SCMD_MORE, "QUIT\r\n");
4222 sx->send_quit = FALSE; /* avoid sending it later */
4225 if (sx->cctx.tls_ctx && sx->send_tlsclose) /* need to send TLS Close Notify */
4227 # ifdef EXIM_TCP_CORK /* Use _CORK to get Close Notify in FIN segment */
4228 (void) setsockopt(sx->cctx.sock, IPPROTO_TCP, EXIM_TCP_CORK, US &on, sizeof(on));
4230 tls_shutdown_wr(sx->cctx.tls_ctx);
4231 sx->send_tlsclose = FALSE; /* avoid later repeat */
4234 HDEBUG(D_transport|D_acl|D_v) debug_printf_indent(" SMTP(shutdown)>>\n");
4235 shutdown(sx->cctx.sock, SHUT_WR); /* flush output buffer, with TCP FIN */
4239 if (smtp_peer_options & OPTION_CHUNKING && sx->cmd_count > 1)
4241 /* Reap any outstanding MAIL & RCPT commands, but not a DATA-go-ahead */
4242 switch(sync_responses(sx, sx->cmd_count-1, 0))
4244 case RESP_HAD_2_AND_5: sx->ok = TRUE; /* OK & progress made */
4245 case RESP_BIT_HAD_5XX: sx->completed_addr = TRUE; /* progress made */
4248 case RESP_BIT_HAD_2XX: sx->ok = TRUE; /* OK, but if LMTP, */
4249 if (!sx->lmtp) /* can't tell about progress yet */
4250 sx->completed_addr = TRUE;
4251 case RESP_NOERROR: break; /* No 2xx or 5xx, but no probs */
4253 case RESP_RCPT_TIMEO: goto END_OFF; /* Timeout on RCPT */
4255 #ifndef DISABLE_PIPE_CONNECT
4256 case RESP_EHLO_ERR_TLS: /* TLS first-read error */
4257 case RESP_EPIPE_EHLO_ERR: HDEBUG(D_transport)
4258 debug_printf("failed reaping pipelined cmd responses\n");
4260 default: goto RESPONSE_FAILED; /* I/O error, or any MAIL/DATA error */
4264 #ifndef DISABLE_PRDR
4265 /* For PRDR we optionally get a partial-responses warning followed by the
4266 individual responses, before going on with the overall response. If we don't
4267 get the warning then deal with per non-PRDR. */
4271 sx->ok = smtp_read_response(sx, sx->buffer, sizeof(sx->buffer), '3', ob->final_timeout);
4272 if (!sx->ok && errno == 0) switch(sx->buffer[0])
4274 case '2': sx->prdr_active = FALSE;
4277 case '4': errno = ERRNO_DATA4XX;
4278 addrlist->more_errno |=
4279 ((sx->buffer[1] - '0')*10 + sx->buffer[2] - '0') << 8;
4286 /* For non-PRDR SMTP, we now read a single response that applies to the
4287 whole message. If it is OK, then all the addresses have been delivered. */
4291 sx->ok = smtp_read_response(sx, sx->buffer, sizeof(sx->buffer), '2',
4293 if (!sx->ok && errno == 0 && sx->buffer[0] == '4')
4295 errno = ERRNO_DATA4XX;
4296 addrlist->more_errno |= ((sx->buffer[1] - '0')*10 + sx->buffer[2] - '0') << 8;
4300 /* For LMTP, we get back a response for every RCPT command that we sent;
4301 some may be accepted and some rejected. For those that get a response, their
4302 status is fixed; any that are accepted have been handed over, even if later
4303 responses crash - at least, that's how I read RFC 2033.
4305 If all went well, mark the recipient addresses as completed, record which
4306 host/IPaddress they were delivered to, and cut out RSET when sending another
4307 message down the same channel. Write the completed addresses to the journal
4308 now so that they are recorded in case there is a crash of hardware or
4309 software before the spool gets updated. Also record the final SMTP
4310 confirmation if needed (for SMTP only). */
4315 struct timeval delivery_time;
4317 uschar * conf = NULL;
4319 timesince(&delivery_time, &sx->delivery_start);
4320 sx->send_rset = FALSE;
4321 pipelining_active = FALSE;
4323 /* Set up confirmation if needed - applies only to SMTP */
4326 #ifdef DISABLE_EVENT
4327 LOGGING(smtp_confirmation) &&
4332 const uschar * s = string_printing(sx->buffer);
4333 /* deconst cast ok here as string_printing was checked to have alloc'n'copied */
4334 conf = s == sx->buffer ? US string_copy(s) : US s;
4337 /* Process all transported addresses - for LMTP or PRDR, read a status for
4338 each one. We used to drop out at first_addr, until someone returned a 452
4339 followed by a 250... and we screwed up the accepted addresses. */
4341 for (address_item * addr = addrlist; addr; addr = addr->next)
4343 if (addr->transport_return != PENDING_OK) continue;
4345 /* LMTP - if the response fails badly (e.g. timeout), use it for all the
4346 remaining addresses. Otherwise, it's a return code for just the one
4347 address. For temporary errors, add a retry item for the address so that
4348 it doesn't get tried again too soon. */
4350 #ifndef DISABLE_PRDR
4351 if (sx->lmtp || sx->prdr_active)
4356 if (!smtp_read_response(sx, sx->buffer, sizeof(sx->buffer), '2',
4359 if (errno != 0 || sx->buffer[0] == 0) goto RESPONSE_FAILED;
4360 addr->message = string_sprintf(
4361 #ifndef DISABLE_PRDR
4362 "%s error after %s: %s", sx->prdr_active ? "PRDR":"LMTP",
4364 "LMTP error after %s: %s",
4366 data_command, string_printing(sx->buffer));
4367 setflag(addr, af_pass_message); /* Allow message to go to user */
4368 if (sx->buffer[0] == '5')
4369 addr->transport_return = FAIL;
4372 errno = ERRNO_DATA4XX;
4373 addr->more_errno |= ((sx->buffer[1] - '0')*10 + sx->buffer[2] - '0') << 8;
4374 addr->transport_return = DEFER;
4375 #ifndef DISABLE_PRDR
4376 if (!sx->prdr_active)
4378 retry_add_item(addr, addr->address_retry_key, 0);
4382 sx->completed_addr = TRUE; /* NOW we can set this flag */
4383 if (LOGGING(smtp_confirmation))
4385 const uschar *s = string_printing(sx->buffer);
4386 /* deconst cast ok here as string_printing was checked to have alloc'n'copied */
4387 conf = (s == sx->buffer) ? US string_copy(s) : US s;
4391 /* SMTP, or success return from LMTP for this address. Pass back the
4392 actual host that was used. */
4394 addr->transport_return = OK;
4395 addr->host_used = host;
4396 addr->delivery_time = delivery_time;
4397 addr->special_action = flag;
4398 addr->message = conf;
4399 if (continue_sequence > 1)
4400 { clearflag(addr, af_new_conn); setflag(addr, af_cont_conn); }
4402 { clearflag(addr, af_cont_conn); setflag(addr, af_new_conn); }
4404 if (tcp_out_fastopen)
4406 setflag(addr, af_tcp_fastopen_conn);
4407 if (tcp_out_fastopen >= TFO_USED_NODATA) setflag(addr, af_tcp_fastopen);
4408 if (tcp_out_fastopen >= TFO_USED_DATA) setflag(addr, af_tcp_fastopen_data);
4410 if (sx->pipelining_used) setflag(addr, af_pipelining);
4411 #ifndef DISABLE_PIPE_CONNECT
4412 if (sx->early_pipe_active) setflag(addr, af_early_pipe);
4414 #ifndef DISABLE_PRDR
4415 if (sx->prdr_active) setflag(addr, af_prdr_used);
4417 if (smtp_peer_options & OPTION_CHUNKING) setflag(addr, af_chunking_used);
4420 #ifndef DISABLE_PRDR
4421 if (!sx->prdr_active)
4424 /* Update the journal. For homonymic addresses, use the base address plus
4425 the transport name. See lots of comments in deliver.c about the reasons
4426 for the complications when homonyms are involved. Just carry on after
4427 write error, as it may prove possible to update the spool file later. */
4429 if (testflag(addr, af_homonym))
4430 sprintf(CS sx->buffer, "%.500s/%s\n", addr->unique + 3, tblock->name);
4432 sprintf(CS sx->buffer, "%.500s\n", addr->unique);
4434 DEBUG(D_deliver) debug_printf("S:journalling %s", sx->buffer);
4435 len = Ustrlen(CS sx->buffer);
4436 if (write(journal_fd, sx->buffer, len) != len)
4437 log_write(0, LOG_MAIN|LOG_PANIC, "failed to write journal for "
4438 "%s: %s", sx->buffer, strerror(errno));
4442 #ifndef DISABLE_PRDR
4443 if (sx->prdr_active)
4445 const uschar * overall_message;
4447 /* PRDR - get the final, overall response. For any non-success
4448 upgrade all the address statuses. */
4450 sx->ok = smtp_read_response(sx, sx->buffer, sizeof(sx->buffer), '2',
4454 if(errno == 0 && sx->buffer[0] == '4')
4456 errno = ERRNO_DATA4XX;
4457 addrlist->more_errno |= ((sx->buffer[1] - '0')*10 + sx->buffer[2] - '0') << 8;
4459 for (address_item * addr = addrlist; addr != sx->first_addr; addr = addr->next)
4460 if (sx->buffer[0] == '5' || addr->transport_return == OK)
4461 addr->transport_return = PENDING_OK; /* allow set_errno action */
4462 goto RESPONSE_FAILED;
4465 /* Append the overall response to the individual PRDR response for logging
4466 and update the journal, or setup retry. */
4468 overall_message = string_printing(sx->buffer);
4469 for (address_item * addr = addrlist; addr != sx->first_addr; addr = addr->next)
4470 if (addr->transport_return == OK)
4471 addr->message = string_sprintf("%s\\n%s", addr->message, overall_message);
4473 for (address_item * addr = addrlist; addr != sx->first_addr; addr = addr->next)
4474 if (addr->transport_return == OK)
4476 if (testflag(addr, af_homonym))
4477 sprintf(CS sx->buffer, "%.500s/%s\n", addr->unique + 3, tblock->name);
4479 sprintf(CS sx->buffer, "%.500s\n", addr->unique);
4481 DEBUG(D_deliver) debug_printf("journalling(PRDR) %s\n", sx->buffer);
4482 len = Ustrlen(CS sx->buffer);
4483 if (write(journal_fd, sx->buffer, len) != len)
4484 log_write(0, LOG_MAIN|LOG_PANIC, "failed to write journal for "
4485 "%s: %s", sx->buffer, strerror(errno));
4487 else if (addr->transport_return == DEFER)
4488 /*XXX magic value -2 ? maybe host+message ? */
4489 retry_add_item(addr, addr->address_retry_key, -2);
4493 /* Ensure the journal file is pushed out to disk. */
4495 if (EXIMfsync(journal_fd) < 0)
4496 log_write(0, LOG_MAIN|LOG_PANIC, "failed to fsync journal: %s",
4502 /* Handle general (not specific to one address) failures here. The value of ok
4503 is used to skip over this code on the falling through case. A timeout causes a
4504 deferral. Other errors may defer or fail according to the response code, and
4505 may set up a special errno value, e.g. after connection chopped, which is
4506 assumed if errno == 0 and there is no text in the buffer. If control reaches
4507 here during the setting up phase (i.e. before MAIL FROM) then always defer, as
4508 the problem is not related to this specific message. */
4513 uschar * set_message;
4519 /* Clear send_quit flag if needed. Do not set. */
4520 sx->send_quit &= check_response(host, &save_errno, addrlist->more_errno,
4521 sx->buffer, &code, &message, &pass_message);
4529 message = string_sprintf("smtp send to %s [%s] failed: %s",
4530 host->name, host->address, message ? message : US strerror(save_errno));
4531 sx->send_quit = FALSE;
4539 sx->ok = FALSE; /* For when reached by GOTO */
4540 set_message = message;
4542 /* We want to handle timeouts after MAIL or "." and loss of connection after
4543 "." specially. They can indicate a problem with the sender address or with
4544 the contents of the message rather than a real error on the connection. These
4545 cases are treated in the same way as a 4xx response. This next bit of code
4546 does the classification. */
4553 message_error = TRUE;
4557 message_error = Ustrncmp(smtp_command,"MAIL",4) == 0 ||
4558 Ustrncmp(smtp_command,"end ",4) == 0;
4561 case ERRNO_SMTPCLOSED:
4562 /* If the peer closed the TCP connection after end-of-data, but before
4563 we could send QUIT, do TLS close, etc - it is a message error.
4564 If not, and all the recipients have been dealt with, call such a close
4565 no error at all; each address_item should have a suitable result already
4566 (2xx: PENDING_OK, 4xx: DEFER, 5xx: FAIL).
4567 Otherwise, it is a non-message error. */
4569 if (!(message_error = Ustrncmp(smtp_command,"end ",4) == 0))
4571 address_item * addr;
4572 for (addr = sx->addrlist; addr; addr = addr->next)
4573 if (addr->transport_return == PENDING_DEFER)
4575 if (!addr) /* all rcpts fates determined */
4577 log_write(0, LOG_MAIN, "peer close after all rcpt responses;"
4578 " converting i/o-error to no-error");
4585 #ifndef DISABLE_DKIM
4587 /* DKIM signing failure: avoid thinking we pipelined quit,
4588 just abandon the message and close the socket. */
4590 message_error = FALSE;
4591 # ifndef DISABLE_TLS
4592 if (sx->cctx.tls_ctx)
4594 tls_close(sx->cctx.tls_ctx,
4595 sx->send_tlsclose ? TLS_SHUTDOWN_WAIT : TLS_SHUTDOWN_WONLY);
4596 sx->cctx.tls_ctx = NULL;
4602 message_error = FALSE;
4606 /* Handle the cases that are treated as message errors (as opposed to
4607 host-errors). These are:
4609 (a) negative response or timeout after MAIL
4610 (b) negative response after DATA
4611 (c) negative response or timeout or dropped connection after "."
4612 (d) utf8 support required and not offered
4614 It won't be a negative response or timeout after RCPT, as that is dealt
4615 with separately above. The action in all cases is to set an appropriate
4616 error code for all the addresses, but to leave yield set to OK because the
4617 host itself has not failed. Of course, it might in practice have failed
4618 when we've had a timeout, but if so, we'll discover that at the next
4619 delivery attempt. For a temporary error, set the message_defer flag, and
4620 write to the logs for information if this is not the last host. The error
4621 for the last host will be logged as part of the address's log line. */
4625 if (mua_wrapper) code = '5'; /* Force hard failure in wrapper mode */
4627 /* If there's an errno, the message contains just the identity of
4632 else /* Anything other than 5 is treated as temporary */
4636 message = US string_sprintf("%s: %s", message, strerror(save_errno));
4638 write_logs(host, message, sx->first_addr ? sx->first_addr->basic_errno : 0);
4640 *message_defer = TRUE;
4643 DEBUG(D_transport) if (sx->cctx.sock >= 0)
4646 if (ioctl(sx->cctx.sock, TIOCOUTQ, &n) == 0)
4647 debug_printf("%d bytes remain in socket output buffer\n", n);
4651 /* Otherwise, we have an I/O error or a timeout other than after MAIL or
4652 ".", or some other transportation error. We defer all addresses and yield
4653 DEFER, except for the case of failed add_headers expansion, or a transport
4654 filter failure, when the yield should be ERROR, to stop it trying other
4659 #ifndef DISABLE_PIPE_CONNECT
4660 /* If we were early-pipelinng and the actual EHLO response did not match
4661 the cached value we assumed, we could have detected it and passed a
4662 custom errno through to here. It would be nice to RSET and retry right
4663 away, but to reliably do that we eould need an extra synch point before
4664 we committed to data and that would discard half the gained roundrips.
4665 Or we could summarily drop the TCP connection. but that is also ugly.
4666 Instead, we ignore the possibility (having freshened the cache) and rely
4667 on the server telling us with a nonmessage error if we have tried to
4668 do something it no longer supports. */
4671 yield = (save_errno == ERRNO_CHHEADER_FAIL ||
4672 save_errno == ERRNO_FILTER_FAIL) ? ERROR : DEFER;
4676 set_errno(addrlist, save_errno, set_message, set_rc, pass_message, host,
4677 #ifdef EXPERIMENTAL_DSN_INFO
4678 sx->smtp_greeting, sx->helo_response,
4680 &sx->delivery_start);
4683 /* If all has gone well, send_quit will be set TRUE, implying we can end the
4684 SMTP session tidily. However, if there were too many addresses to send in one
4685 message (indicated by first_addr being non-NULL) we want to carry on with the
4686 rest of them. Also, it is desirable to send more than one message down the SMTP
4687 connection if there are several waiting, provided we haven't already sent so
4688 many as to hit the configured limit. The function transport_check_waiting looks
4689 for a waiting message and returns its id. We pass it back to the delivery
4690 process via the reporting pipe. The variable send_rset is FALSE if a message has
4691 just been successfully transferred.
4693 If we are already sending down a continued channel, there may be further
4694 addresses not yet delivered that are aimed at the same host, but which have not
4695 been passed in this run of the transport. In this case, continue_more will be
4696 true, and all we should do is send RSET if necessary, and return, leaving the
4699 However, if no address was disposed of, i.e. all addresses got 4xx errors, we
4700 do not want to continue with other messages down the same channel, because that
4701 can lead to looping between two or more messages, all with the same,
4702 temporarily failing address(es). [The retry information isn't updated yet, so
4703 new processes keep on trying.] We probably also don't want to try more of this
4704 message's addresses either.
4706 If we have started a TLS session, we have to end it before passing the
4707 connection to a new process. However, not all servers can handle this (Exim
4708 can), so we do not pass such a connection on if the host matches
4709 hosts_nopass_tls. */
4714 debug_printf("ok=%d send_quit=%d send_rset=%d continue_more=%d "
4715 "yield=%d first_address is %sNULL\n", sx->ok, sx->send_quit,
4716 sx->send_rset, f.continue_more, yield, sx->first_addr ? "not " : "");
4718 if (sx->completed_addr && sx->ok && sx->send_quit)
4719 #ifndef DISABLE_ESMTP_LIMITS
4720 if (mail_limit = continue_sequence >= sx->max_mail)
4723 debug_printf("reached limit %u for MAILs per conn\n", sx->max_mail);
4724 /* We will close the smtp session and connection, and clear
4725 continue_hostname. Then if there are further addrs for the message we will
4726 loop to the top of this function and make a fresh connection. Any further
4727 message found in the wait-tpt hintsdb would then do a pass-fd over the
4728 transport reporting pipe to get the connection fd back to the delivery
4734 smtp_compare_t t_compare =
4735 {.tblock = tblock, .current_sender_address = sender_address};
4737 if ( sx->first_addr /* more addrs for this message */
4738 || f.continue_more /* more addrs for continued-host */
4739 || tcw_done && tcw /* more messages for host */
4742 ( tls_out.active.sock < 0 && !continue_proxy_cipher
4743 || verify_check_given_host(CUSS &ob->hosts_nopass_tls, host) != OK
4747 transport_check_waiting(tblock->name, host->name,
4748 sx->max_mail, continue_next_id,
4749 (oicf)smtp_are_same_identities, (void*)&t_compare)
4756 if (! (sx->ok = smtp_write_command(sx, SCMD_FLUSH, "RSET\r\n") >= 0))
4758 msg = US string_sprintf("smtp send to %s [%s] failed: %s", host->name,
4759 host->address, strerror(errno));
4760 sx->send_quit = FALSE;
4762 else if (! (sx->ok = smtp_read_response(sx, sx->buffer, sizeof(sx->buffer),
4763 '2', ob->command_timeout)))
4766 sx->send_quit = check_response(host, &errno, 0, sx->buffer, &code, &msg,
4770 DEBUG(D_transport) debug_printf("H=%s [%s] %s\n",
4771 host->name, host->address, msg);
4775 /* Either RSET was not needed, or it succeeded */
4782 continue_fd = sx->cctx.sock;
4783 if (sx->first_addr) /* More addresses still to be sent */
4784 { /* for this message */
4785 #ifndef DISABLE_ESMTP_LIMITS
4786 /* Any that we marked as skipped, reset to do now */
4787 for (address_item * a = sx->first_addr; a; a = a->next)
4788 if (a->transport_return == SKIP)
4789 a->transport_return = PENDING_DEFER;
4791 continue_sequence++; /* for consistency */
4792 pipelining_active = sx->pipelining_used; /* was cleared at DATA */
4796 /* If there is a next-message-id from the wait-transport hintsdb,
4797 pretend caller said it has further message for us. Note that we lose
4798 the TLS session (below), and that our caller will pass back the id to
4799 the delivery process. */
4801 if (f.continue_more)
4803 passback_conn = TRUE;
4804 continue_next_id[0] = '\0';
4806 else if (*continue_next_id)
4807 passback_conn = f.continue_more = TRUE;
4810 /* If we will be returning with the connection still open and have a TLS
4811 endpoint, shut down TLS if we must, or if this is a first-time passback
4812 fork a proxy process with the TLS state. */
4814 if (tls_out.active.sock >= 0)
4816 if ( (continue_hostname || passback_conn)
4817 && verify_check_given_host(CUSS &ob->hosts_noproxy_tls, host) == OK
4820 /* Not all MTAs allow for the continuation of the SMTP session when
4821 TLS is shut down. We test for this by sending a new EHLO. If we
4822 don't get a good response, we don't attempt to pass the socket on.
4823 NB: TLS close is *required* per RFC 9266 when tls-exporter info has
4824 been used, which we do under TLSv1.3 for the gsasl SCRAM*PLUS methods.
4827 tls_close(sx->cctx.tls_ctx,
4828 sx->send_tlsclose ? TLS_SHUTDOWN_WAIT : TLS_SHUTDOWN_WONLY);
4829 sx->send_tlsclose = FALSE;
4830 sx->cctx.tls_ctx = NULL;
4831 tls_out.active.sock = -1;
4832 smtp_peer_options = smtp_peer_options_wrap;
4834 && smtp_write_command(sx, SCMD_FLUSH, "EHLO %s\r\n",sx->helo_data)
4836 && smtp_read_response(sx, sx->buffer, sizeof(sx->buffer),
4837 '2', ob->command_timeout);
4839 else if (passback_conn)
4841 /* Set up a pipe for proxying TLS for the new transport process */
4843 smtp_peer_options |= OPTION_TLS;
4844 if ((sx->ok = socketpair(AF_UNIX, SOCK_STREAM, 0, pfd) == 0))
4846 int pid = exim_fork(US"tls-proxy-interproc");
4847 if (pid == 0) /* child; fork again to disconnect totally */
4849 /* does not return */
4850 smtp_proxy_tls(sx->cctx.tls_ctx, sx->buffer, sizeof(sx->buffer),
4851 pfd, ob->command_timeout, host->name);
4855 log_write(0, LOG_PANIC_DIE, "fork failed");
4858 continue_fd = pfd[1];
4859 /* tidy the inter-proc to disconn the proxy proc */
4860 waitpid(pid, NULL, 0);
4861 tls_close(sx->cctx.tls_ctx, TLS_NO_SHUTDOWN);
4862 sx->cctx.tls_ctx = NULL;
4863 (void)close(sx->cctx.sock);
4866 continue_proxy_cipher = tls_out.cipher;
4867 continue_proxy_sni = tls_out.sni;
4868 # ifdef SUPPORT_DANE
4869 continue_proxy_dane = tls_out.sni && tls_out.dane_verified;
4873 set_errno(sx->first_addr, errno, US"internal allocation problem",
4875 # ifdef EXPERIMENTAL_DSN_INFO
4876 sx->smtp_greeting, sx->helo_response,
4878 &sx->delivery_start);
4881 #endif /*DISABLE_TLS*/
4883 /* If a connection re-use is possible, arrange to pass back all the info
4884 about it so that further forks of the delivery process see it. */
4888 continue_transport = transport_name;
4889 continue_hostname = host->name;
4890 continue_host_address = host->address;
4893 continue_hostname = NULL;
4895 if (sx->ok && f.continue_more) /* More addresses for another run; */
4896 goto TIDYUP; /* skip the channel closedown */
4899 /* If RSET failed and there are addresses left, they get deferred.
4900 Do not pass back a next-id or conn info. */
4903 set_errno(sx->first_addr, errno, msg, DEFER, FALSE, host,
4904 #ifdef EXPERIMENTAL_DSN_INFO
4905 sx->smtp_greeting, sx->helo_response,
4907 &sx->delivery_start);
4911 /* End off tidily with QUIT unless the connection has died or the socket has
4912 been passed to another process. */
4916 { /* Use _MORE to get QUIT in FIN segment */
4917 (void)smtp_write_command(sx, SCMD_MORE, "QUIT\r\n");
4919 if (sx->cctx.tls_ctx && sx->send_tlsclose)
4921 # ifdef EXIM_TCP_CORK /* Use _CORK to get TLS Close Notify in FIN segment */
4922 (void) setsockopt(sx->cctx.sock, IPPROTO_TCP, EXIM_TCP_CORK, US &on, sizeof(on));
4924 tls_shutdown_wr(sx->cctx.tls_ctx);
4925 sx->send_tlsclose = FALSE;
4932 /* Close the socket, and return the appropriate value, first setting
4933 works because the NULL setting is passed back to the calling process, and
4934 remote_max_parallel is forced to 1 when delivering over an existing connection,
4936 If all went well and continue_more is set, we shouldn't actually get here if
4937 there are further addresses, as the return above will be taken. However,
4938 writing RSET might have failed, or there may be other addresses whose hosts are
4939 specified in the transports, and therefore not visible at top level, in which
4940 case continue_more won't get set. */
4944 /* This flushes data queued in the socket, being the QUIT and any TLS Close,
4945 sending them along with the client FIN flag. Us (we hope) sending FIN first
4946 means we (client) take the TIME_WAIT state, so the server (which likely has a
4947 higher connection rate) does not have to. */
4949 HDEBUG(D_transport|D_acl|D_v) debug_printf_indent(" SMTP(shutdown)>>\n");
4950 shutdown(sx->cctx.sock, SHUT_WR);
4953 if (sx->send_quit || tcw_done && !tcw)
4955 /* Wait for (we hope) ack of our QUIT, and a server FIN. Discard any data
4956 received, then discard the socket. Any packet received after then, or receive
4957 data still in the socket, will get a RST - hence the pause/drain. */
4959 /* Reap the response to QUIT, timing out after one second */
4960 (void) smtp_read_response(sx, sx->buffer, sizeof(sx->buffer), '2', 1);
4962 if (sx->cctx.tls_ctx)
4966 /* Reap the TLS Close Notify from the server, timing out after one second */
4967 sigalrm_seen = FALSE;
4970 n = tls_read(sx->cctx.tls_ctx, sx->inbuffer, sizeof(sx->inbuffer));
4971 while (!sigalrm_seen && n > 0);
4974 if (sx->send_tlsclose)
4976 # ifdef EXIM_TCP_CORK
4977 (void) setsockopt(sx->cctx.sock, IPPROTO_TCP, EXIM_TCP_CORK, US &on, sizeof(on));
4979 tls_close(sx->cctx.tls_ctx, TLS_SHUTDOWN_WAIT);
4982 tls_close(sx->cctx.tls_ctx, TLS_SHUTDOWN_WONLY);
4983 sx->cctx.tls_ctx = NULL;
4987 /* Drain any trailing data from the socket before close, to avoid sending a RST */
4989 if ( poll_one_fd(sx->cctx.sock, POLLIN, 20) != 0 /* 20ms */
4990 && fcntl(sx->cctx.sock, F_SETFL, O_NONBLOCK) == 0)
4991 for (int i = 16, n; /* drain socket */
4992 (n = read(sx->cctx.sock, sx->inbuffer, sizeof(sx->inbuffer))) > 0 && i > 0;
4993 i--) HDEBUG(D_transport|D_acl|D_v)
4996 debug_printf_indent(" SMTP(drain %d bytes)<< %.*s\n", n, m, sx->inbuffer);
4997 for (m = 0; m < n; m++)
4998 debug_printf("0x%02x\n", sx->inbuffer[m]);
5001 HDEBUG(D_transport|D_acl|D_v) debug_printf_indent(" SMTP(close)>>\n");
5002 (void)close(sx->cctx.sock);
5004 continue_hostname = NULL;
5005 continue_next_id[0] = '\0';
5007 #ifndef DISABLE_EVENT
5008 (void) event_raise(tblock->event_action, US"tcp:close", NULL, NULL);
5014 sx->first_addr = NULL;
5015 for (address_item * a = sx->addrlist->next; a; a = a->next)
5016 if (a->transport_return == DANE)
5018 a->transport_return = PENDING_DEFER;
5019 if (!sx->first_addr)
5021 /* Remember the new start-point in the addrlist, for smtp_setup_conn()
5022 to get the domain string for SNI */
5025 DEBUG(D_transport) debug_printf("DANE: go-around for %s\n", a->domain);
5028 continue_sequence = 1; /* for consistency */
5033 #ifndef DISABLE_ESMTP_LIMITS
5034 if (mail_limit && sx->first_addr)
5036 /* Reset the sequence count since we closed the connection. This is flagged
5037 on the pipe back to the delivery process so that it can reset it's count.
5038 Also set flags on the addr so that a non-continued-conn delivery is logged. */
5040 continue_sequence = 1; /* for consistency */
5041 goto REPEAT_CONN; /* open a fresh connection */
5046 smtp_debug_cmd_report();
5051 if (dane_held) for (address_item * a = sx->addrlist->next; a; a = a->next)
5052 if (a->transport_return == DANE)
5053 a->transport_return = PENDING_DEFER;
5061 /*************************************************
5062 * Closedown entry point *
5063 *************************************************/
5065 /* This function is called when exim is passed an open smtp channel
5066 from another incarnation, but the message which it has been asked
5067 to deliver no longer exists. The channel is on stdin.
5069 We might do fancy things like looking for another message to send down
5070 the channel, but if the one we sought has gone, it has probably been
5071 delivered by some other process that itself will seek further messages,
5072 so just close down our connection.
5074 Argument: pointer to the transport instance block
5079 smtp_transport_closedown(transport_instance *tblock)
5081 smtp_transport_options_block * ob = SOB tblock->options_block;
5082 client_conn_ctx cctx;
5083 smtp_context sx = {0};
5085 uschar inbuffer[4096];
5086 uschar outbuffer[16];
5088 /*XXX really we need an active-smtp-client ctx, rather than assuming stdout */
5089 cctx.sock = fileno(stdin);
5090 cctx.tls_ctx = cctx.sock == tls_out.active.sock ? tls_out.active.tls_ctx : NULL;
5092 sx.inblock.cctx = &cctx;
5093 sx.inblock.buffer = inbuffer;
5094 sx.inblock.buffersize = sizeof(inbuffer);
5095 sx.inblock.ptr = inbuffer;
5096 sx.inblock.ptrend = inbuffer;
5098 sx.outblock.cctx = &cctx;
5099 sx.outblock.buffersize = sizeof(outbuffer);
5100 sx.outblock.buffer = outbuffer;
5101 sx.outblock.ptr = outbuffer;
5102 sx.outblock.cmd_count = 0;
5103 sx.outblock.authenticating = FALSE;
5105 (void)smtp_write_command(&sx, SCMD_FLUSH, "QUIT\r\n");
5106 (void)smtp_read_response(&sx, buffer, sizeof(buffer), '2', ob->command_timeout);
5107 (void)close(cctx.sock);
5112 /*************************************************
5113 * Prepare addresses for delivery *
5114 *************************************************/
5116 /* This function is called to flush out error settings from previous delivery
5117 attempts to other hosts. It also records whether we got here via an MX record
5118 or not in the more_errno field of the address. We are interested only in
5119 addresses that are still marked DEFER - others may have got delivered to a
5120 previously considered IP address. Set their status to PENDING_DEFER to indicate
5121 which ones are relevant this time.
5124 addrlist the list of addresses
5125 host the host we are delivering to
5127 Returns: the first address for this delivery
5130 static address_item *
5131 prepare_addresses(address_item * addrlist, host_item * host)
5133 address_item * first_addr = NULL;
5134 for (address_item * addr = addrlist; addr; addr = addr->next)
5135 if (addr->transport_return == DEFER)
5137 if (!first_addr) first_addr = addr;
5138 addr->transport_return = PENDING_DEFER;
5139 addr->basic_errno = 0;
5140 addr->more_errno = host->mx >= 0 ? 'M' : 'A';
5141 addr->message = NULL;
5143 addr->cipher = NULL;
5144 addr->ourcert = NULL;
5145 addr->peercert = NULL;
5146 addr->peerdn = NULL;
5147 addr->ocsp = OCSP_NOT_REQ;
5148 addr->tlsver = NULL;
5150 #ifdef EXPERIMENTAL_DSN_INFO
5151 addr->smtp_greeting = NULL;
5152 addr->helo_response = NULL;
5160 /*************************************************
5161 * Main entry point *
5162 *************************************************/
5164 /* See local README for interface details. As this is a remote transport, it is
5165 given a chain of addresses to be delivered in one connection, if possible. It
5166 always returns TRUE, indicating that each address has its own independent
5167 status set, except if there is a setting up problem, in which case it returns
5171 smtp_transport_entry(
5172 transport_instance * tblock, /* data for this instantiation */
5173 address_item * addrlist) /* addresses we are working on */
5176 int hosts_defer = 0, hosts_fail = 0, hosts_looked_up = 0;
5177 int hosts_retry = 0, hosts_serial = 0, hosts_total = 0, total_hosts_tried = 0;
5178 BOOL expired = TRUE;
5179 uschar * expanded_hosts = NULL, * pistring;
5180 uschar * tid = string_sprintf("%s transport", tblock->name);
5181 smtp_transport_options_block * ob = SOB tblock->options_block;
5182 host_item * hostlist = addrlist->host_list, * host = NULL;
5186 debug_printf("%s transport entered\n", tblock->name);
5187 for (address_item * addr = addrlist; addr; addr = addr->next)
5188 debug_printf(" %s\n", addr->address);
5191 debug_printf("hostlist:\n");
5192 for (host_item * host = hostlist; host; host = host->next)
5193 debug_printf(" '%s' IP %s port %d\n", host->name, host->address, host->port);
5195 if (continue_hostname)
5196 debug_printf("already connected to %s [%s] (on fd %d)\n",
5197 continue_hostname, continue_host_address,
5198 cutthrough.cctx.sock >= 0 ? cutthrough.cctx.sock : 0);
5201 /* Check the restrictions on line length */
5203 if (max_received_linelength > ob->message_linelength_limit)
5206 gettimeofday(&now, NULL);
5208 for (address_item * addr = addrlist; addr; addr = addr->next)
5209 if (addr->transport_return == DEFER)
5210 addr->transport_return = PENDING_DEFER;
5212 set_errno_nohost(addrlist, ERRNO_SMTPFORMAT,
5213 US"message has lines too long for transport", FAIL, TRUE, &now);
5217 /* Set the flag requesting that these hosts be added to the waiting
5218 database if the delivery fails temporarily or if we are running with
5219 queue_smtp or a 2-stage queue run. This gets unset for certain
5220 kinds of error, typically those that are specific to the message. */
5222 update_waiting = TRUE;
5224 /* If a host list is not defined for the addresses - they must all have the
5225 same one in order to be passed to a single transport - or if the transport has
5226 a host list with hosts_override set, use the host list supplied with the
5227 transport. It is an error for this not to exist. */
5229 if (!hostlist || (ob->hosts_override && ob->hosts))
5233 addrlist->message = string_sprintf("%s transport called with no hosts set",
5235 addrlist->transport_return = PANIC;
5236 return FALSE; /* Only top address has status */
5239 DEBUG(D_transport) debug_printf("using the transport's hosts: %s\n",
5242 /* If the transport's host list contains no '$' characters, and we are not
5243 randomizing, it is fixed and therefore a chain of hosts can be built once
5244 and for all, and remembered for subsequent use by other calls to this
5245 transport. If, on the other hand, the host list does contain '$', or we are
5246 randomizing its order, we have to rebuild it each time. In the fixed case,
5247 as the hosts string will never be used again, it doesn't matter that we
5248 replace all the : characters with zeros. */
5252 uschar *s = ob->hosts;
5254 if (Ustrchr(s, '$'))
5256 if (!(expanded_hosts = expand_string(s)))
5258 addrlist->message = string_sprintf("failed to expand list of hosts "
5259 "\"%s\" in %s transport: %s", s, tblock->name, expand_string_message);
5260 addrlist->transport_return = f.search_find_defer ? DEFER : PANIC;
5261 return FALSE; /* Only top address has status */
5263 DEBUG(D_transport) debug_printf("expanded list of hosts \"%s\" to "
5264 "\"%s\"\n", s, expanded_hosts);
5268 if (ob->hosts_randomize) s = expanded_hosts = string_copy(s);
5272 log_write(0, LOG_MAIN|LOG_PANIC,
5273 "attempt to use tainted host list '%s' from '%s' in transport %s",
5274 s, ob->hosts, tblock->name);
5275 /* Avoid leaking info to an attacker */
5276 addrlist->message = US"internal configuration error";
5277 addrlist->transport_return = PANIC;
5281 host_build_hostlist(&hostlist, s, ob->hosts_randomize);
5283 /* Check that the expansion yielded something useful. */
5287 string_sprintf("%s transport has empty hosts setting", tblock->name);
5288 addrlist->transport_return = PANIC;
5289 return FALSE; /* Only top address has status */
5292 /* If there was no expansion of hosts, save the host list for
5295 if (!expanded_hosts) ob->hostlist = hostlist;
5298 /* This is not the first time this transport has been run in this delivery;
5299 the host list was built previously. */
5302 hostlist = ob->hostlist;
5305 /* The host list was supplied with the address. If hosts_randomize is set, we
5306 must sort it into a random order if it did not come from MX records and has not
5307 already been randomized (but don't bother if continuing down an existing
5310 else if (ob->hosts_randomize && hostlist->mx == MX_NONE && !continue_hostname)
5312 host_item *newlist = NULL;
5315 host_item *h = hostlist;
5316 hostlist = hostlist->next;
5318 h->sort_key = random_number(100);
5325 else if (h->sort_key < newlist->sort_key)
5332 host_item *hh = newlist;
5335 if (h->sort_key < hh->next->sort_key) break;
5343 hostlist = addrlist->host_list = newlist;
5346 /* Sort out the default port. */
5348 if (!smtp_get_port(ob->port, addrlist, &defport, tid)) return FALSE;
5350 /* For each host-plus-IP-address on the list:
5352 . If this is a continued delivery and the host isn't the one with the
5353 current connection, skip.
5355 . If the status is unusable (i.e. previously failed or retry checked), skip.
5357 . If no IP address set, get the address, either by turning the name into
5358 an address, calling gethostbyname if gethostbyname is on, or by calling
5359 the DNS. The DNS may yield multiple addresses, in which case insert the
5360 extra ones into the list.
5362 . Get the retry data if not previously obtained for this address and set the
5363 field which remembers the state of this address. Skip if the retry time is
5364 not reached. If not, remember whether retry data was found. The retry string
5365 contains both the name and the IP address.
5367 . Scan the list of addresses and mark those whose status is DEFER as
5368 PENDING_DEFER. These are the only ones that will be processed in this cycle
5371 . Make a delivery attempt - addresses marked PENDING_DEFER will be tried.
5372 Some addresses may be successfully delivered, others may fail, and yet
5373 others may get temporary errors and so get marked DEFER.
5375 . The return from the delivery attempt is OK if a connection was made and a
5376 valid SMTP dialogue was completed. Otherwise it is DEFER.
5378 . If OK, add a "remove" retry item for this host/IPaddress, if any.
5380 . If fail to connect, or other defer state, add a retry item.
5382 . If there are any addresses whose status is still DEFER, carry on to the
5383 next host/IPaddress, unless we have tried the number of hosts given
5384 by hosts_max_try or hosts_max_try_hardlimit; otherwise return. Note that
5385 there is some fancy logic for hosts_max_try that means its limit can be
5386 overstepped in some circumstances.
5388 If we get to the end of the list, all hosts have deferred at least one address,
5389 or not reached their retry times. If delay_after_cutoff is unset, it requests a
5390 delivery attempt to those hosts whose last try was before the arrival time of
5391 the current message. To cope with this, we have to go round the loop a second
5392 time. After that, set the status and error data for any addresses that haven't
5393 had it set already. */
5395 for (int cutoff_retry = 0;
5396 expired && cutoff_retry < (ob->delay_after_cutoff ? 1 : 2);
5399 host_item *nexthost = NULL;
5400 int unexpired_hosts_tried = 0;
5401 BOOL continue_host_tried = FALSE;
5403 retry_non_continued:
5404 for (host = hostlist;
5406 && unexpired_hosts_tried < ob->hosts_max_try
5407 && total_hosts_tried < ob->hosts_max_try_hardlimit;
5411 BOOL host_is_expired = FALSE, message_defer = FALSE, some_deferred = FALSE;
5412 address_item * first_addr = NULL;
5413 uschar * interface = NULL;
5414 const uschar * retry_host_key = NULL, * retry_message_key = NULL;
5415 uschar * serialize_key = NULL;
5417 /* Deal slightly better with a possible Linux kernel bug that results
5418 in intermittent TFO-conn fails deep into the TCP flow. Bug 2907 tracks.
5419 Hack: Clear TFO option for any further hosts on this tpt run. */
5421 if (total_hosts_tried > 0)
5423 DEBUG(D_transport|D_acl|D_v)
5424 debug_printf("Clearing TFO as not first host for message\n");
5425 ob->hosts_try_fastopen = US"";
5428 /* Default next host is next host. :-) But this can vary if the
5429 hosts_max_try limit is hit (see below). It may also be reset if a host
5430 address is looked up here (in case the host was multihomed). */
5432 nexthost = host->next;
5434 /* If the address hasn't yet been obtained from the host name, look it up
5435 now, unless the host is already marked as unusable. If it is marked as
5436 unusable, it means that the router was unable to find its IP address (in
5437 the DNS or wherever) OR we are in the 2nd time round the cutoff loop, and
5438 the lookup failed last time. We don't get this far if *all* MX records
5439 point to non-existent hosts; that is treated as a hard error.
5441 We can just skip this host entirely. When the hosts came from the router,
5442 the address will timeout based on the other host(s); when the address is
5443 looked up below, there is an explicit retry record added.
5445 Note that we mustn't skip unusable hosts if the address is not unset; they
5446 may be needed as expired hosts on the 2nd time round the cutoff loop. */
5450 int new_port, flags;
5452 if (host->status >= hstatus_unusable)
5454 DEBUG(D_transport) debug_printf("%s has no address and is unusable - skipping\n",
5459 DEBUG(D_transport) debug_printf("getting address for %s\n", host->name);
5461 /* The host name is permitted to have an attached port. Find it, and
5462 strip it from the name. Just remember it for now. */
5464 new_port = host_item_get_port(host);
5466 /* Count hosts looked up */
5470 /* Find by name if so configured, or if it's an IP address. We don't
5471 just copy the IP address, because we need the test-for-local to happen. */
5473 flags = HOST_FIND_BY_A | HOST_FIND_BY_AAAA;
5474 if (ob->dns_qualify_single) flags |= HOST_FIND_QUALIFY_SINGLE;
5475 if (ob->dns_search_parents) flags |= HOST_FIND_SEARCH_PARENTS;
5477 if (ob->gethostbyname || string_is_ip_address(host->name, NULL) != 0)
5478 rc = host_find_byname(host, NULL, flags, NULL, TRUE);
5480 rc = host_find_bydns(host, NULL, flags, NULL, NULL, NULL,
5481 &ob->dnssec, /* domains for request/require */
5484 /* Update the host (and any additional blocks, resulting from
5485 multihoming) with a host-specific port, if any. */
5487 for (host_item * hh = host; hh != nexthost; hh = hh->next) hh->port = new_port;
5489 /* Failure to find the host at this time (usually DNS temporary failure)
5490 is really a kind of routing failure rather than a transport failure.
5491 Therefore we add a retry item of the routing kind, not to stop us trying
5492 to look this name up here again, but to ensure the address gets timed
5493 out if the failures go on long enough. A complete failure at this point
5494 commonly points to a configuration error, but the best action is still
5495 to carry on for the next host. */
5497 if (rc == HOST_FIND_AGAIN || rc == HOST_FIND_SECURITY || rc == HOST_FIND_FAILED)
5499 retry_add_item(addrlist, string_sprintf("R:%s", host->name), 0);
5501 if (rc == HOST_FIND_AGAIN) hosts_defer++; else hosts_fail++;
5502 DEBUG(D_transport) debug_printf("rc = %s for %s\n", (rc == HOST_FIND_AGAIN)?
5503 "HOST_FIND_AGAIN" : "HOST_FIND_FAILED", host->name);
5504 host->status = hstatus_unusable;
5506 for (address_item * addr = addrlist; addr; addr = addr->next)
5508 if (addr->transport_return != DEFER) continue;
5509 addr->basic_errno = ERRNO_UNKNOWNHOST;
5510 addr->message = string_sprintf(
5511 rc == HOST_FIND_SECURITY
5512 ? "lookup of IP address for %s was insecure"
5513 : "failed to lookup IP address for %s",
5519 /* If the host is actually the local host, we may have a problem, or
5520 there may be some cunning configuration going on. In the problem case,
5521 log things and give up. The default transport status is already DEFER. */
5523 if (rc == HOST_FOUND_LOCAL && !ob->allow_localhost)
5525 for (address_item * addr = addrlist; addr; addr = addr->next)
5527 addr->basic_errno = ERRNO_HOST_IS_LOCAL;
5528 addr->message = string_sprintf("%s transport found host %s to be "
5529 "local", tblock->name, host->name);
5533 } /* End of block for IP address lookup */
5535 /* If this is a continued delivery, we are interested only in the host
5536 which matches the name of the existing open channel. The check is put
5537 here after the local host lookup, in case the name gets expanded as a
5538 result of the lookup. Set expired FALSE, to save the outer loop executing
5541 if (continue_sequence > 1)
5542 if ( Ustrcmp(continue_hostname, host->name) != 0
5543 || Ustrcmp(continue_host_address, host->address) != 0
5547 continue; /* With next host */
5550 continue_host_tried = TRUE;
5552 /* Reset the default next host in case a multihomed host whose addresses
5553 are not looked up till just above added to the host list. */
5555 nexthost = host->next;
5557 /* If queue_smtp is set (-odqs or the first part of a 2-stage run), or the
5558 domain is in queue_smtp_domains, we don't actually want to attempt any
5559 deliveries. When doing a queue run, queue_smtp_domains is always unset. If
5560 there is a lookup defer in queue_smtp_domains, proceed as if the domain
5561 were not in it. We don't want to hold up all SMTP deliveries! Except when
5562 doing a two-stage queue run, don't do this if forcing. */
5564 if ( (!f.deliver_force || f.queue_2stage)
5566 || match_isinlist(addrlist->domain,
5567 CUSS &queue_smtp_domains, 0,
5568 &domainlist_anchor, NULL, MCL_DOMAIN, TRUE, NULL) == OK)
5571 DEBUG(D_transport) debug_printf("first-pass routing only\n");
5573 for (address_item * addr = addrlist; addr; addr = addr->next)
5574 if (addr->transport_return == DEFER)
5575 addr->message = US"first-pass only routing due to -odqs, "
5576 "queue_smtp_domains or control=queue";
5577 continue; /* With next host */
5580 /* Count hosts being considered - purely for an intelligent comment
5581 if none are usable. */
5585 /* Set $host and $host address now in case they are needed for the
5586 interface expansion or the serialize_hosts check; they remain set if an
5587 actual delivery happens. */
5589 deliver_host = host->name;
5590 deliver_host_address = host->address;
5591 lookup_dnssec_authenticated = host->dnssec == DS_YES ? US"yes"
5592 : host->dnssec == DS_NO ? US"no"
5595 /* Set up a string for adding to the retry key if the port number is not
5596 the standard SMTP port. A host may have its own port setting that overrides
5599 pistring = string_sprintf(":%d", host->port == PORT_NONE
5600 ? defport : host->port);
5601 if (Ustrcmp(pistring, ":25") == 0) pistring = US"";
5603 /* Select IPv4 or IPv6, and choose an outgoing interface. If the interface
5604 string is set, even if constant (as different transports can have different
5605 constant settings), we must add it to the key that is used for retries,
5606 because connections to the same host from a different interface should be
5607 treated separately. */
5609 host_af = Ustrchr(host->address, ':') ? AF_INET6 : AF_INET;
5612 GET_OPTION("interface");
5613 if ((s = ob->interface) && *s)
5615 if (!smtp_get_interface(s, host_af, addrlist, &interface, tid))
5617 pistring = string_sprintf("%s/%s", pistring, interface);
5621 /* The first time round the outer loop, check the status of the host by
5622 inspecting the retry data. The second time round, we are interested only
5623 in expired hosts that haven't been tried since this message arrived. */
5625 if (cutoff_retry == 0)
5628 /* Ensure the status of the address is set by checking retry data if
5629 necessary. There may be host-specific retry data (applicable to all
5630 messages) and also data for retries of a specific message at this host.
5631 If either of these retry records are actually read, the keys used are
5632 returned to save recomputing them later. */
5634 if (exp_bool(addrlist, US"transport", tblock->name, D_transport,
5635 US"retry_include_ip_address", ob->retry_include_ip_address,
5636 ob->expand_retry_include_ip_address, &incl_ip) != OK)
5637 continue; /* with next host */
5639 host_is_expired = retry_check_address(addrlist->domain, host, pistring,
5640 incl_ip, &retry_host_key, &retry_message_key);
5642 DEBUG(D_transport) debug_printf("%s [%s]%s retry-status = %s\n", host->name,
5643 host->address ? host->address : US"", pistring,
5644 host->status == hstatus_usable ? "usable"
5645 : host->status == hstatus_unusable ? "unusable"
5646 : host->status == hstatus_unusable_expired ? "unusable (expired)" : "?");
5648 /* Skip this address if not usable at this time, noting if it wasn't
5649 actually expired, both locally and in the address. */
5651 switch (host->status)
5653 case hstatus_unusable:
5655 setflag(addrlist, af_retry_skipped);
5658 case hstatus_unusable_expired:
5661 case hwhy_retry: hosts_retry++; break;
5662 case hwhy_failed: hosts_fail++; break;
5664 case hwhy_deferred: hosts_defer++; break;
5667 /* If there was a retry message key, implying that previously there
5668 was a message-specific defer, we don't want to update the list of
5669 messages waiting for these hosts. */
5671 if (retry_message_key) update_waiting = FALSE;
5672 continue; /* With the next host or IP address */
5676 /* Second time round the loop: if the address is set but expired, and
5677 the message is newer than the last try, let it through. */
5682 || host->status != hstatus_unusable_expired
5683 || host->last_try > received_time.tv_sec)
5685 DEBUG(D_transport) debug_printf("trying expired host %s [%s]%s\n",
5686 host->name, host->address, pistring);
5687 host_is_expired = TRUE;
5690 /* Setting "expired=FALSE" doesn't actually mean not all hosts are expired;
5691 it remains TRUE only if all hosts are expired and none are actually tried.
5696 /* If this host is listed as one to which access must be serialized,
5697 see if another Exim process has a connection to it, and if so, skip
5698 this host. If not, update the database to record our connection to it
5699 and remember this for later deletion. Do not do any of this if we are
5700 sending the message down a pre-existing connection. */
5702 if ( !continue_hostname
5703 && verify_check_given_host(CUSS &ob->serialize_hosts, host) == OK)
5705 serialize_key = string_sprintf("host-serialize-%s", host->name);
5706 if (!enq_start(serialize_key, 1))
5709 debug_printf("skipping host %s because another Exim process "
5710 "is connected to it\n", host->name);
5716 /* OK, we have an IP address that is not waiting for its retry time to
5717 arrive (it might be expired) OR (second time round the loop) we have an
5718 expired host that hasn't been tried since the message arrived. Have a go
5719 at delivering the message to it. First prepare the addresses by flushing
5720 out the result of previous attempts, and finding the first address that
5721 is still to be delivered. */
5723 if (!(first_addr = prepare_addresses(addrlist, host)))
5725 /* Obscure situation; at least one case (bug 3059, fixed) where
5726 a previous host try returned DEFER, but having moved all
5727 recipients away from DEFER (the waiting-to-be-done state). */
5728 DEBUG(D_transport) debug_printf("no pending recipients\n");
5732 DEBUG(D_transport) debug_printf("delivering %s to %s [%s] (%s%s)\n",
5733 message_id, host->name, host->address, addrlist->address,
5734 addrlist->next ? ", ..." : "");
5736 set_process_info("delivering %s to %s [%s]%s (%s%s)",
5737 message_id, host->name, host->address, pistring, addrlist->address,
5738 addrlist->next ? ", ..." : "");
5740 /* This is not for real; don't do the delivery. If there are
5741 any remaining hosts, list them. */
5746 gettimeofday(&now, NULL);
5747 set_errno_nohost(addrlist, 0, NULL, OK, FALSE, &now);
5748 for (address_item * addr = addrlist; addr; addr = addr->next)
5750 addr->host_used = host;
5751 addr->special_action = '*';
5752 addr->message = US"delivery bypassed by -N option";
5756 debug_printf("*** delivery by %s transport bypassed by -N option\n"
5757 "*** host and remaining hosts:\n", tblock->name);
5758 for (host_item * host2 = host; host2; host2 = host2->next)
5759 debug_printf(" %s [%s]\n", host2->name,
5760 host2->address ? host2->address : US"unset");
5765 /* This is for real. If the host is expired, we don't count it for
5766 hosts_max_retry. This ensures that all hosts must expire before an address
5767 is timed out, unless hosts_max_try_hardlimit (which protects against
5768 lunatic DNS configurations) is reached.
5770 If the host is not expired and we are about to hit the hosts_max_retry
5771 limit, check to see if there is a subsequent hosts with a different MX
5772 value. If so, make that the next host, and don't count this one. This is a
5773 heuristic to make sure that different MXs do get tried. With a normal kind
5774 of retry rule, they would get tried anyway when the earlier hosts were
5775 delayed, but if the domain has a "retry every time" type of rule - as is
5776 often used for the the very large ISPs, that won't happen. */
5781 /* Make a copy of the host if it is local to this invocation
5782 of the transport. */
5786 thost = store_get(sizeof(host_item), GET_UNTAINTED);
5788 thost->name = string_copy(host->name);
5789 thost->address = string_copy(host->address);
5794 if (!host_is_expired && ++unexpired_hosts_tried >= ob->hosts_max_try)
5797 debug_printf("hosts_max_try limit reached with this host\n");
5798 for (host_item * h = host; h; h = h->next) if (h->mx != host->mx)
5801 unexpired_hosts_tried--;
5802 DEBUG(D_transport) debug_printf("however, a higher MX host exists "
5803 "and will be tried\n");
5808 /* Attempt the delivery. */
5810 total_hosts_tried++;
5811 rc = smtp_deliver(addrlist, thost, host_af, defport, interface, tblock,
5812 &message_defer, FALSE);
5815 OK => connection made, each address contains its result;
5816 message_defer is set for message-specific defers (when all
5817 recipients are marked defer)
5818 DEFER => there was a non-message-specific delivery problem;
5819 ERROR => there was a problem setting up the arguments for a filter,
5820 or there was a problem with expanding added headers
5823 /* If the result is not OK, there was a non-message-specific problem.
5824 If the result is DEFER, we need to write to the logs saying what happened
5825 for this particular host, except in the case of authentication and TLS
5826 failures, where the log has already been written. If all hosts defer a
5827 general message is written at the end. */
5829 if (rc == DEFER && first_addr->basic_errno != ERRNO_AUTHFAIL
5830 && first_addr->basic_errno != ERRNO_TLSFAILURE)
5831 write_logs(host, first_addr->message, first_addr->basic_errno);
5833 #ifndef DISABLE_EVENT
5835 deferred_event_raise(first_addr, host, US"msg:host:defer");
5838 /* If STARTTLS was accepted, but there was a failure in setting up the
5839 TLS session (usually a certificate screwup), and the host is not in
5840 hosts_require_tls, and tls_tempfail_tryclear is true, try again, with
5841 TLS forcibly turned off. We have to start from scratch with a new SMTP
5842 connection. That's why the retry is done from here, not from within
5843 smtp_deliver(). [Rejections of STARTTLS itself don't screw up the
5844 session, so the in-clear transmission after those errors, if permitted,
5845 happens inside smtp_deliver().] */
5849 && first_addr->basic_errno == ERRNO_TLSFAILURE
5850 && ob->tls_tempfail_tryclear
5851 && verify_check_given_host(CUSS &ob->hosts_require_tls, host) != OK
5854 log_write(0, LOG_MAIN,
5855 "%s: delivering unencrypted to H=%s [%s] (not in hosts_require_tls)",
5856 first_addr->message, host->name, host->address);
5857 first_addr = prepare_addresses(addrlist, host);
5858 rc = smtp_deliver(addrlist, thost, host_af, defport, interface, tblock,
5859 &message_defer, TRUE);
5860 if (rc == DEFER && first_addr->basic_errno != ERRNO_AUTHFAIL)
5861 write_logs(host, first_addr->message, first_addr->basic_errno);
5862 # ifndef DISABLE_EVENT
5864 deferred_event_raise(first_addr, host, US"msg:host:defer");
5867 #endif /*DISABLE_TLS*/
5869 #ifndef DISABLE_EVENT
5870 /* If the last host gave a defer raise a per-message event */
5873 && unexpired_hosts_tried < ob->hosts_max_try
5874 && total_hosts_tried < ob->hosts_max_try_hardlimit
5876 && (message_defer || rc == DEFER)
5878 deferred_event_raise(first_addr, host, US"msg:defer");
5882 /* Delivery attempt finished */
5884 set_process_info("delivering %s: just tried %s [%s]%s for %s%s: result %s",
5885 message_id, host->name, host->address, pistring, addrlist->address,
5886 addrlist->next ? " (& others)" : "", rc_to_string(rc));
5888 /* Release serialization if set up */
5890 if (serialize_key) enq_end(serialize_key);
5892 /* If the result is DEFER, or if a host retry record is known to exist, we
5893 need to add an item to the retry chain for updating the retry database
5894 at the end of delivery. We only need to add the item to the top address,
5895 of course. Also, if DEFER, we mark the IP address unusable so as to skip it
5896 for any other delivery attempts using the same address. (It is copied into
5897 the unusable tree at the outer level, so even if different address blocks
5898 contain the same address, it still won't get tried again.) */
5900 if (rc == DEFER || retry_host_key)
5902 int delete_flag = rc != DEFER ? rf_delete : 0;
5903 if (!retry_host_key)
5906 if (exp_bool(addrlist, US"transport", tblock->name, D_transport,
5907 US"retry_include_ip_address", ob->retry_include_ip_address,
5908 ob->expand_retry_include_ip_address, &incl_ip) != OK)
5909 incl_ip = TRUE; /* error; use most-specific retry record */
5911 retry_host_key = retry_host_key_build(host, incl_ip, pistring);
5914 /* If a delivery of another message over an existing SMTP connection
5915 yields DEFER, we do NOT set up retry data for the host. This covers the
5916 case when there are delays in routing the addresses in the second message
5917 that are so long that the server times out. This is alleviated by not
5918 routing addresses that previously had routing defers when handling an
5919 existing connection, but even so, this case may occur (e.g. if a
5920 previously happily routed address starts giving routing defers). If the
5921 host is genuinely down, another non-continued message delivery will
5922 notice it soon enough. */
5924 if (delete_flag != 0 || !continue_hostname)
5925 retry_add_item(first_addr, retry_host_key, rf_host | delete_flag);
5927 /* We may have tried an expired host, if its retry time has come; ensure
5928 the status reflects the expiry for the benefit of any other addresses. */
5932 host->status = host_is_expired
5933 ? hstatus_unusable_expired : hstatus_unusable;
5934 host->why = hwhy_deferred;
5938 /* If message_defer is set (host was OK, but every recipient got deferred
5939 because of some message-specific problem), or if that had happened
5940 previously so that a message retry key exists, add an appropriate item
5941 to the retry chain. Note that if there was a message defer but now there is
5942 a host defer, the message defer record gets deleted. That seems perfectly
5943 reasonable. Also, stop the message from being remembered as waiting
5944 for specific hosts. */
5946 if (message_defer || retry_message_key)
5948 int delete_flag = message_defer ? 0 : rf_delete;
5949 if (!retry_message_key)
5952 if (exp_bool(addrlist, US"transport", tblock->name, D_transport,
5953 US"retry_include_ip_address", ob->retry_include_ip_address,
5954 ob->expand_retry_include_ip_address, &incl_ip) != OK)
5955 incl_ip = TRUE; /* error; use most-specific retry record */
5957 retry_message_key = string_sprintf("%s:%s",
5958 retry_host_key_build(host, incl_ip, pistring), message_id);
5960 retry_add_item(addrlist, retry_message_key,
5961 rf_message | rf_host | delete_flag);
5962 update_waiting = FALSE;
5965 /* Any return other than DEFER (that is, OK or ERROR) means that the
5966 addresses have got their final statuses filled in for this host. In the OK
5967 case, see if any of them are deferred. */
5970 for (address_item * addr = addrlist; addr; addr = addr->next)
5971 if (addr->transport_return == DEFER)
5972 { some_deferred = TRUE; break; }
5974 /* If no addresses deferred or the result was ERROR, return. We do this for
5975 ERROR because a failing filter set-up or add_headers expansion is likely to
5976 fail for any host we try. */
5978 if (rc == ERROR || (rc == OK && !some_deferred))
5981 /* If the result was DEFER or some individual addresses deferred, let
5982 the loop run to try other hosts with the deferred addresses, except for the
5983 case when we were trying to deliver down an existing channel and failed.
5984 Don't try any other hosts in this case. */
5986 if (continue_sequence > 1) break;
5988 /* If the whole delivery, or some individual addresses, were deferred and
5989 there are more hosts that could be tried, do not count this host towards
5990 the hosts_max_try limit if the age of the message is greater than the
5991 maximum retry time for this host. This means we may try try all hosts,
5992 ignoring the limit, when messages have been around for some time. This is
5993 important because if we don't try all hosts, the address will never time
5994 out. NOTE: this does not apply to hosts_max_try_hardlimit. */
5996 if ((rc == DEFER || some_deferred) && nexthost)
5999 retry_config * retry = retry_find_config(host->name, NULL, 0, 0);
6001 if (retry && retry->rules)
6003 retry_rule *last_rule;
6004 for (last_rule = retry->rules;
6006 last_rule = last_rule->next);
6007 timedout = time(NULL) - received_time.tv_sec > last_rule->timeout;
6009 else timedout = TRUE; /* No rule => timed out */
6013 unexpired_hosts_tried--;
6014 DEBUG(D_transport) debug_printf("temporary delivery error(s) override "
6015 "hosts_max_try (message older than host's retry time)\n");
6021 if (unexpired_hosts_tried >= ob->hosts_max_try)
6022 debug_printf("reached transport hosts_max_try limit %d\n",
6024 if (total_hosts_tried >= ob->hosts_max_try_hardlimit)
6025 debug_printf("reached transport hosts_max_try_hardlimit limit %d\n",
6026 ob->hosts_max_try_hardlimit);
6029 testharness_pause_ms(500); /* let server debug out */
6030 } /* End of loop for trying multiple hosts. */
6032 /* If we failed to find a matching host in the list, for an already-open
6033 connection, just close it and start over with the list. This can happen
6034 for routing that changes from run to run, or big multi-IP sites with
6037 if (continue_sequence > 1 && !continue_host_tried)
6039 int fd = cutthrough.cctx.sock >= 0 ? cutthrough.cctx.sock : 0;
6041 DEBUG(D_transport) debug_printf("no hosts match already-open connection\n");
6043 /* A TLS conn could be open for a cutthrough, but not for a plain continued-
6045 /*XXX doublecheck that! */
6047 if (cutthrough.cctx.sock >= 0 && cutthrough.is_tls)
6049 (void) tls_write(cutthrough.cctx.tls_ctx, US"QUIT\r\n", 6, FALSE);
6050 tls_close(cutthrough.cctx.tls_ctx, TLS_SHUTDOWN_NOWAIT);
6051 cutthrough.cctx.tls_ctx = NULL;
6052 cutthrough.is_tls = FALSE;
6056 (void) write(fd, US"QUIT\r\n", 6);
6059 cutthrough.cctx.sock = -1;
6060 continue_hostname = NULL;
6061 continue_sequence = 1;
6062 goto retry_non_continued;
6065 /* This is the end of the loop that repeats iff expired is TRUE and
6066 ob->delay_after_cutoff is FALSE. The second time round we will
6067 try those hosts that haven't been tried since the message arrived. */
6071 debug_printf("all IP addresses skipped or deferred at least one address\n");
6072 if (expired && !ob->delay_after_cutoff && cutoff_retry == 0)
6073 debug_printf("retrying IP addresses not tried since message arrived\n");
6078 /* Get here if all IP addresses are skipped or defer at least one address. In
6079 MUA wrapper mode, this will happen only for connection or other non-message-
6080 specific failures. Force the delivery status for all addresses to FAIL. */
6084 for (address_item * addr = addrlist; addr; addr = addr->next)
6085 addr->transport_return = FAIL;
6089 /* In the normal, non-wrapper case, add a standard message to each deferred
6090 address if there hasn't been an error, that is, if it hasn't actually been
6091 tried this time. The variable "expired" will be FALSE if any deliveries were
6092 actually tried, or if there was at least one host that was not expired. That
6093 is, it is TRUE only if no deliveries were tried and all hosts were expired. If
6094 a delivery has been tried, an error code will be set, and the failing of the
6095 message is handled by the retry code later.
6097 If queue_smtp is set, or this transport was called to send a subsequent message
6098 down an existing TCP/IP connection, and something caused the host not to be
6099 found, we end up here, but can detect these cases and handle them specially. */
6101 for (address_item * addr = addrlist; addr; addr = addr->next)
6103 /* If host is not NULL, it means that we stopped processing the host list
6104 because of hosts_max_try or hosts_max_try_hardlimit. In the former case, this
6105 means we need to behave as if some hosts were skipped because their retry
6106 time had not come. Specifically, this prevents the address from timing out.
6107 However, if we have hit hosts_max_try_hardlimit, we want to behave as if all
6108 hosts were tried. */
6111 if (total_hosts_tried >= ob->hosts_max_try_hardlimit)
6114 debug_printf("hosts_max_try_hardlimit reached: behave as if all "
6115 "hosts were tried\n");
6120 debug_printf("hosts_max_try limit caused some hosts to be skipped\n");
6121 setflag(addr, af_retry_skipped);
6124 if (f.queue_smtp) /* no deliveries attempted */
6126 addr->transport_return = DEFER;
6127 addr->basic_errno = 0;
6128 addr->message = US"SMTP delivery explicitly queued";
6131 else if ( addr->transport_return == DEFER
6132 && (addr->basic_errno == ERRNO_UNKNOWNERROR || addr->basic_errno == 0)
6136 addr->basic_errno = ERRNO_HRETRY;
6137 if (continue_hostname)
6138 addr->message = US"no host found for existing SMTP connection";
6141 setflag(addr, af_pass_message); /* This is not a security risk */
6142 addr->message = string_sprintf(
6143 "all hosts%s have been failing for a long time %s",
6144 addr->domain ? string_sprintf(" for '%s'", addr->domain) : US"",
6145 ob->delay_after_cutoff
6146 ? US"(and retry time not reached)"
6147 : US"and were last tried after this message arrived");
6149 /* If we are already using fallback hosts, or there are no fallback hosts
6150 defined, convert the result to FAIL to cause a bounce. */
6152 if (addr->host_list == addr->fallback_hosts || !addr->fallback_hosts)
6153 addr->transport_return = FAIL;
6158 if (hosts_retry == hosts_total)
6159 s = "retry time not reached for any host%s";
6160 else if (hosts_fail == hosts_total)
6161 s = "all host address lookups%s failed permanently";
6162 else if (hosts_defer == hosts_total)
6163 s = "all host address lookups%s failed temporarily";
6164 else if (hosts_serial == hosts_total)
6165 s = "connection limit reached for all hosts%s";
6166 else if (hosts_fail+hosts_defer == hosts_total)
6167 s = "all host address lookups%s failed";
6169 s = "some host address lookups failed and retry time "
6170 "not reached for other hosts or connection limit reached%s";
6172 addr->message = string_sprintf(s,
6173 addr->domain ? string_sprintf(" for '%s'", addr->domain) : US"");
6178 /* Update the database which keeps information about which messages are waiting
6179 for which hosts to become available. For some message-specific errors, the
6180 update_waiting flag is turned off because we don't want follow-on deliveries in
6181 those cases. If this transport instance is explicitly limited to one message
6182 per connection then follow-on deliveries are not possible and there's no need
6183 to create/update the per-transport wait-<transport_name> database. */
6185 if (update_waiting && tblock->connection_max_messages != 1)
6186 transport_update_waiting(hostlist, tblock->name);
6190 DEBUG(D_transport) debug_printf("Leaving %s transport\n", tblock->name);
6192 return TRUE; /* Each address has its status */
6195 #endif /*!MACRO_PREDEF*/
6198 /* End of transport/smtp.c */