1 /*************************************************
2 * Exim - an Internet mail transport agent *
3 *************************************************/
5 /* Copyright (c) University of Cambridge 1995 - 2017 */
6 /* See the file NOTICE for conditions of use and distribution. */
12 /* Options specific to the smtp transport. This transport also supports LMTP
13 over TCP/IP. The options must be in alphabetic order (note that "_" comes
14 before the lower case letters). Some live in the transport_instance block so as
15 to be publicly visible; these are flagged with opt_public. */
17 optionlist smtp_transport_options[] = {
18 { "*expand_multi_domain", opt_stringptr | opt_hidden | opt_public,
19 (void *)offsetof(transport_instance, expand_multi_domain) },
20 { "*expand_retry_include_ip_address", opt_stringptr | opt_hidden,
21 (void *)(offsetof(smtp_transport_options_block, expand_retry_include_ip_address)) },
23 { "address_retry_include_sender", opt_bool,
24 (void *)offsetof(smtp_transport_options_block, address_retry_include_sender) },
25 { "allow_localhost", opt_bool,
26 (void *)offsetof(smtp_transport_options_block, allow_localhost) },
27 { "authenticated_sender", opt_stringptr,
28 (void *)offsetof(smtp_transport_options_block, authenticated_sender) },
29 { "authenticated_sender_force", opt_bool,
30 (void *)offsetof(smtp_transport_options_block, authenticated_sender_force) },
31 { "command_timeout", opt_time,
32 (void *)offsetof(smtp_transport_options_block, command_timeout) },
33 { "connect_timeout", opt_time,
34 (void *)offsetof(smtp_transport_options_block, connect_timeout) },
35 { "connection_max_messages", opt_int | opt_public,
36 (void *)offsetof(transport_instance, connection_max_messages) },
37 { "data_timeout", opt_time,
38 (void *)offsetof(smtp_transport_options_block, data_timeout) },
39 { "delay_after_cutoff", opt_bool,
40 (void *)offsetof(smtp_transport_options_block, delay_after_cutoff) },
42 { "dkim_canon", opt_stringptr,
43 (void *)offsetof(smtp_transport_options_block, dkim.dkim_canon) },
44 { "dkim_domain", opt_stringptr,
45 (void *)offsetof(smtp_transport_options_block, dkim.dkim_domain) },
46 { "dkim_hash", opt_stringptr,
47 (void *)offsetof(smtp_transport_options_block, dkim.dkim_hash) },
48 { "dkim_private_key", opt_stringptr,
49 (void *)offsetof(smtp_transport_options_block, dkim.dkim_private_key) },
50 { "dkim_selector", opt_stringptr,
51 (void *)offsetof(smtp_transport_options_block, dkim.dkim_selector) },
52 { "dkim_sign_headers", opt_stringptr,
53 (void *)offsetof(smtp_transport_options_block, dkim.dkim_sign_headers) },
54 { "dkim_strict", opt_stringptr,
55 (void *)offsetof(smtp_transport_options_block, dkim.dkim_strict) },
57 { "dns_qualify_single", opt_bool,
58 (void *)offsetof(smtp_transport_options_block, dns_qualify_single) },
59 { "dns_search_parents", opt_bool,
60 (void *)offsetof(smtp_transport_options_block, dns_search_parents) },
61 { "dnssec_request_domains", opt_stringptr,
62 (void *)offsetof(smtp_transport_options_block, dnssec.request) },
63 { "dnssec_require_domains", opt_stringptr,
64 (void *)offsetof(smtp_transport_options_block, dnssec.require) },
65 { "dscp", opt_stringptr,
66 (void *)offsetof(smtp_transport_options_block, dscp) },
67 { "fallback_hosts", opt_stringptr,
68 (void *)offsetof(smtp_transport_options_block, fallback_hosts) },
69 { "final_timeout", opt_time,
70 (void *)offsetof(smtp_transport_options_block, final_timeout) },
71 { "gethostbyname", opt_bool,
72 (void *)offsetof(smtp_transport_options_block, gethostbyname) },
73 { "helo_data", opt_stringptr,
74 (void *)offsetof(smtp_transport_options_block, helo_data) },
75 { "hosts", opt_stringptr,
76 (void *)offsetof(smtp_transport_options_block, hosts) },
77 { "hosts_avoid_esmtp", opt_stringptr,
78 (void *)offsetof(smtp_transport_options_block, hosts_avoid_esmtp) },
79 { "hosts_avoid_pipelining", opt_stringptr,
80 (void *)offsetof(smtp_transport_options_block, hosts_avoid_pipelining) },
82 { "hosts_avoid_tls", opt_stringptr,
83 (void *)offsetof(smtp_transport_options_block, hosts_avoid_tls) },
85 { "hosts_max_try", opt_int,
86 (void *)offsetof(smtp_transport_options_block, hosts_max_try) },
87 { "hosts_max_try_hardlimit", opt_int,
88 (void *)offsetof(smtp_transport_options_block, hosts_max_try_hardlimit) },
90 { "hosts_nopass_tls", opt_stringptr,
91 (void *)offsetof(smtp_transport_options_block, hosts_nopass_tls) },
92 { "hosts_noproxy_tls", opt_stringptr,
93 (void *)offsetof(smtp_transport_options_block, hosts_noproxy_tls) },
95 { "hosts_override", opt_bool,
96 (void *)offsetof(smtp_transport_options_block, hosts_override) },
97 { "hosts_randomize", opt_bool,
98 (void *)offsetof(smtp_transport_options_block, hosts_randomize) },
99 #if defined(SUPPORT_TLS) && !defined(DISABLE_OCSP)
100 { "hosts_request_ocsp", opt_stringptr,
101 (void *)offsetof(smtp_transport_options_block, hosts_request_ocsp) },
103 { "hosts_require_auth", opt_stringptr,
104 (void *)offsetof(smtp_transport_options_block, hosts_require_auth) },
106 # ifdef EXPERIMENTAL_DANE
107 { "hosts_require_dane", opt_stringptr,
108 (void *)offsetof(smtp_transport_options_block, hosts_require_dane) },
110 # ifndef DISABLE_OCSP
111 { "hosts_require_ocsp", opt_stringptr,
112 (void *)offsetof(smtp_transport_options_block, hosts_require_ocsp) },
114 { "hosts_require_tls", opt_stringptr,
115 (void *)offsetof(smtp_transport_options_block, hosts_require_tls) },
117 { "hosts_try_auth", opt_stringptr,
118 (void *)offsetof(smtp_transport_options_block, hosts_try_auth) },
119 { "hosts_try_chunking", opt_stringptr,
120 (void *)offsetof(smtp_transport_options_block, hosts_try_chunking) },
121 #if defined(SUPPORT_TLS) && defined(EXPERIMENTAL_DANE)
122 { "hosts_try_dane", opt_stringptr,
123 (void *)offsetof(smtp_transport_options_block, hosts_try_dane) },
125 { "hosts_try_fastopen", opt_stringptr,
126 (void *)offsetof(smtp_transport_options_block, hosts_try_fastopen) },
128 { "hosts_try_prdr", opt_stringptr,
129 (void *)offsetof(smtp_transport_options_block, hosts_try_prdr) },
132 { "hosts_verify_avoid_tls", opt_stringptr,
133 (void *)offsetof(smtp_transport_options_block, hosts_verify_avoid_tls) },
135 { "interface", opt_stringptr,
136 (void *)offsetof(smtp_transport_options_block, interface) },
137 { "keepalive", opt_bool,
138 (void *)offsetof(smtp_transport_options_block, keepalive) },
139 { "lmtp_ignore_quota", opt_bool,
140 (void *)offsetof(smtp_transport_options_block, lmtp_ignore_quota) },
141 { "max_rcpt", opt_int | opt_public,
142 (void *)offsetof(transport_instance, max_addresses) },
143 { "multi_domain", opt_expand_bool | opt_public,
144 (void *)offsetof(transport_instance, multi_domain) },
145 { "port", opt_stringptr,
146 (void *)offsetof(smtp_transport_options_block, port) },
147 { "protocol", opt_stringptr,
148 (void *)offsetof(smtp_transport_options_block, protocol) },
149 { "retry_include_ip_address", opt_expand_bool,
150 (void *)offsetof(smtp_transport_options_block, retry_include_ip_address) },
151 { "serialize_hosts", opt_stringptr,
152 (void *)offsetof(smtp_transport_options_block, serialize_hosts) },
153 { "size_addition", opt_int,
154 (void *)offsetof(smtp_transport_options_block, size_addition) }
156 ,{ "socks_proxy", opt_stringptr,
157 (void *)offsetof(smtp_transport_options_block, socks_proxy) }
160 ,{ "tls_certificate", opt_stringptr,
161 (void *)offsetof(smtp_transport_options_block, tls_certificate) },
162 { "tls_crl", opt_stringptr,
163 (void *)offsetof(smtp_transport_options_block, tls_crl) },
164 { "tls_dh_min_bits", opt_int,
165 (void *)offsetof(smtp_transport_options_block, tls_dh_min_bits) },
166 { "tls_privatekey", opt_stringptr,
167 (void *)offsetof(smtp_transport_options_block, tls_privatekey) },
168 { "tls_require_ciphers", opt_stringptr,
169 (void *)offsetof(smtp_transport_options_block, tls_require_ciphers) },
170 { "tls_sni", opt_stringptr,
171 (void *)offsetof(smtp_transport_options_block, tls_sni) },
172 { "tls_tempfail_tryclear", opt_bool,
173 (void *)offsetof(smtp_transport_options_block, tls_tempfail_tryclear) },
174 { "tls_try_verify_hosts", opt_stringptr,
175 (void *)offsetof(smtp_transport_options_block, tls_try_verify_hosts) },
176 { "tls_verify_cert_hostnames", opt_stringptr,
177 (void *)offsetof(smtp_transport_options_block,tls_verify_cert_hostnames)},
178 { "tls_verify_certificates", opt_stringptr,
179 (void *)offsetof(smtp_transport_options_block, tls_verify_certificates) },
180 { "tls_verify_hosts", opt_stringptr,
181 (void *)offsetof(smtp_transport_options_block, tls_verify_hosts) }
185 /* Size of the options list. An extern variable has to be used so that its
186 address can appear in the tables drtables.c. */
188 int smtp_transport_options_count =
189 sizeof(smtp_transport_options)/sizeof(optionlist);
195 smtp_transport_options_block smtp_transport_option_defaults = {0};
196 void smtp_transport_init(transport_instance *tblock) {}
197 BOOL smtp_transport_entry(transport_instance *tblock, address_item *addr) {return FALSE;}
198 void smtp_transport_closedown(transport_instance *tblock) {}
200 #else /*!MACRO_PREDEF*/
203 /* Default private options block for the smtp transport. */
205 smtp_transport_options_block smtp_transport_option_defaults = {
209 .fallback_hostlist = NULL,
210 .authenticated_sender = NULL,
211 .helo_data = US"$primary_hostname",
214 .protocol = US"smtp",
216 .serialize_hosts = NULL,
217 .hosts_try_auth = NULL,
218 .hosts_require_auth = NULL,
219 .hosts_try_chunking = US"*",
220 #ifdef EXPERIMENTAL_DANE
221 .hosts_try_dane = NULL,
222 .hosts_require_dane = NULL,
224 .hosts_try_fastopen = NULL,
226 .hosts_try_prdr = US"*",
229 .hosts_request_ocsp = US"*", /* hosts_request_ocsp (except under DANE; tls_client_start()) */
230 .hosts_require_ocsp = NULL,
232 .hosts_require_tls = NULL,
233 .hosts_avoid_tls = NULL,
234 .hosts_verify_avoid_tls = NULL,
235 .hosts_avoid_pipelining = NULL,
236 .hosts_avoid_esmtp = NULL,
238 .hosts_nopass_tls = NULL,
239 .hosts_noproxy_tls = US"*",
241 .command_timeout = 5*60,
242 .connect_timeout = 5*60,
243 .data_timeout = 5*60,
244 .final_timeout = 10*60,
245 .size_addition = 1024,
247 .hosts_max_try_hardlimit = 50,
248 .address_retry_include_sender = TRUE,
249 .allow_localhost = FALSE,
250 .authenticated_sender_force = FALSE,
251 .gethostbyname = FALSE,
252 .dns_qualify_single = TRUE,
253 .dns_search_parents = FALSE,
254 .dnssec = { .request=NULL, .require=NULL },
255 .delay_after_cutoff = TRUE,
256 .hosts_override = FALSE,
257 .hosts_randomize = FALSE,
259 .lmtp_ignore_quota = FALSE,
260 .expand_retry_include_ip_address = NULL,
261 .retry_include_ip_address = TRUE,
266 .tls_certificate = NULL,
268 .tls_privatekey = NULL,
269 .tls_require_ciphers = NULL,
271 .tls_verify_certificates = US"system",
272 .tls_dh_min_bits = EXIM_CLIENT_DH_DEFAULT_MIN_BITS,
273 .tls_tempfail_tryclear = TRUE,
274 .tls_verify_hosts = NULL,
275 .tls_try_verify_hosts = US"*",
276 .tls_verify_cert_hostnames = US"*",
280 {.dkim_domain = NULL,
281 .dkim_private_key = NULL,
282 .dkim_selector = NULL,
284 .dkim_sign_headers = NULL,
286 .dkim_hash = US"sha256",
287 .dot_stuffed = FALSE},
291 /* some DSN flags for use later */
293 static int rf_list[] = {rf_notify_never, rf_notify_success,
294 rf_notify_failure, rf_notify_delay };
296 static uschar *rf_names[] = { US"NEVER", US"SUCCESS", US"FAILURE", US"DELAY" };
302 static uschar *smtp_command; /* Points to last cmd for error messages */
303 static uschar *mail_command; /* Points to MAIL cmd for error messages */
304 static uschar *data_command = US""; /* Points to DATA cmd for error messages */
305 static BOOL update_waiting; /* TRUE to update the "wait" database */
307 /*XXX move to smtp_context */
308 static BOOL pipelining_active; /* current transaction is in pipe mode */
311 /*************************************************
312 * Setup entry point *
313 *************************************************/
315 /* This function is called when the transport is about to be used,
316 but before running it in a sub-process. It is used for two things:
318 (1) To set the fallback host list in addresses, when delivering.
319 (2) To pass back the interface, port, protocol, and other options, for use
320 during callout verification.
323 tblock pointer to the transport instance block
324 addrlist list of addresses about to be transported
325 tf if not NULL, pointer to block in which to return options
326 uid the uid that will be set (not used)
327 gid the gid that will be set (not used)
328 errmsg place for error message (not used)
330 Returns: OK always (FAIL, DEFER not used)
334 smtp_transport_setup(transport_instance *tblock, address_item *addrlist,
335 transport_feedback *tf, uid_t uid, gid_t gid, uschar **errmsg)
337 smtp_transport_options_block *ob =
338 (smtp_transport_options_block *)(tblock->options_block);
340 errmsg = errmsg; /* Keep picky compilers happy */
344 /* Pass back options if required. This interface is getting very messy. */
348 tf->interface = ob->interface;
350 tf->protocol = ob->protocol;
351 tf->hosts = ob->hosts;
352 tf->hosts_override = ob->hosts_override;
353 tf->hosts_randomize = ob->hosts_randomize;
354 tf->gethostbyname = ob->gethostbyname;
355 tf->qualify_single = ob->dns_qualify_single;
356 tf->search_parents = ob->dns_search_parents;
357 tf->helo_data = ob->helo_data;
360 /* Set the fallback host list for all the addresses that don't have fallback
361 host lists, provided that the local host wasn't present in the original host
364 if (!testflag(addrlist, af_local_host_removed))
365 for (; addrlist; addrlist = addrlist->next)
366 if (!addrlist->fallback_hosts) addrlist->fallback_hosts = ob->fallback_hostlist;
373 /*************************************************
374 * Initialization entry point *
375 *************************************************/
377 /* Called for each instance, after its options have been read, to
378 enable consistency checks to be done, or anything else that needs
381 Argument: pointer to the transport instance block
386 smtp_transport_init(transport_instance *tblock)
388 smtp_transport_options_block *ob =
389 (smtp_transport_options_block *)(tblock->options_block);
391 /* Retry_use_local_part defaults FALSE if unset */
393 if (tblock->retry_use_local_part == TRUE_UNSET)
394 tblock->retry_use_local_part = FALSE;
396 /* Set the default port according to the protocol */
398 if (ob->port == NULL)
399 ob->port = (strcmpic(ob->protocol, US"lmtp") == 0)? US"lmtp" :
400 (strcmpic(ob->protocol, US"smtps") == 0)? US"smtps" : US"smtp";
402 /* Set up the setup entry point, to be called before subprocesses for this
405 tblock->setup = smtp_transport_setup;
407 /* Complain if any of the timeouts are zero. */
409 if (ob->command_timeout <= 0 || ob->data_timeout <= 0 ||
410 ob->final_timeout <= 0)
411 log_write(0, LOG_PANIC_DIE|LOG_CONFIG,
412 "command, data, or final timeout value is zero for %s transport",
415 /* If hosts_override is set and there are local hosts, set the global
416 flag that stops verify from showing router hosts. */
418 if (ob->hosts_override && ob->hosts != NULL) tblock->overrides_hosts = TRUE;
420 /* If there are any fallback hosts listed, build a chain of host items
421 for them, but do not do any lookups at this time. */
423 host_build_hostlist(&(ob->fallback_hostlist), ob->fallback_hosts, FALSE);
430 /*************************************************
431 * Set delivery info into all active addresses *
432 *************************************************/
434 /* Only addresses whose status is >= PENDING are relevant. A lesser
435 status means that an address is not currently being processed.
438 addrlist points to a chain of addresses
439 errno_value to put in each address's errno field
440 msg to put in each address's message field
441 rc to put in each address's transport_return field
442 pass_message if TRUE, set the "pass message" flag in the address
443 host if set, mark addrs as having used this host
444 smtp_greeting from peer
445 helo_response from peer
447 If errno_value has the special value ERRNO_CONNECTTIMEOUT, ETIMEDOUT is put in
448 the errno field, and RTEF_CTOUT is ORed into the more_errno field, to indicate
449 this particular type of timeout.
455 set_errno(address_item *addrlist, int errno_value, uschar *msg, int rc,
456 BOOL pass_message, host_item * host
457 #ifdef EXPERIMENTAL_DSN_INFO
458 , const uschar * smtp_greeting, const uschar * helo_response
464 if (errno_value == ERRNO_CONNECTTIMEOUT)
466 errno_value = ETIMEDOUT;
467 orvalue = RTEF_CTOUT;
469 for (addr = addrlist; addr; addr = addr->next)
470 if (addr->transport_return >= PENDING)
472 addr->basic_errno = errno_value;
473 addr->more_errno |= orvalue;
477 if (pass_message) setflag(addr, af_pass_message);
479 addr->transport_return = rc;
482 addr->host_used = host;
483 #ifdef EXPERIMENTAL_DSN_INFO
485 {uschar * s = Ustrchr(smtp_greeting, '\n'); if (s) *s = '\0';}
486 addr->smtp_greeting = smtp_greeting;
489 {uschar * s = Ustrchr(helo_response, '\n'); if (s) *s = '\0';}
490 addr->helo_response = helo_response;
497 set_errno_nohost(address_item *addrlist, int errno_value, uschar *msg, int rc,
500 set_errno(addrlist, errno_value, msg, rc, pass_message, NULL
501 #ifdef EXPERIMENTAL_DSN_INFO
508 /*************************************************
509 * Check an SMTP response *
510 *************************************************/
512 /* This function is given an errno code and the SMTP response buffer
513 to analyse, together with the host identification for generating messages. It
514 sets an appropriate message and puts the first digit of the response code into
515 the yield variable. If no response was actually read, a suitable digit is
519 host the current host, to get its name for messages
520 errno_value pointer to the errno value
521 more_errno from the top address for use with ERRNO_FILTER_FAIL
522 buffer the SMTP response buffer
523 yield where to put a one-digit SMTP response code
524 message where to put an error message
525 pass_message set TRUE if message is an SMTP response
527 Returns: TRUE if an SMTP "QUIT" command should be sent, else FALSE
531 check_response(host_item *host, int *errno_value, int more_errno,
532 uschar *buffer, int *yield, uschar **message, BOOL *pass_message)
534 uschar * pl = pipelining_active ? US"pipelined " : US"";
537 *yield = '4'; /* Default setting is to give a temporary error */
541 case ETIMEDOUT: /* Handle response timeout */
542 *message = US string_sprintf("SMTP timeout after %s%s",
544 if (transport_count > 0)
545 *message = US string_sprintf("%s (%d bytes written)", *message,
549 case ERRNO_SMTPFORMAT: /* Handle malformed SMTP response */
550 s = string_printing(buffer);
551 while (isspace(*s)) s++;
553 ? string_sprintf("Malformed SMTP reply (an empty line) "
554 "in response to %s%s", pl, smtp_command)
555 : string_sprintf("Malformed SMTP reply in response to %s%s: %s",
556 pl, smtp_command, s);
559 case ERRNO_FILTER_FAIL: /* Handle a failed filter process error;
560 can't send QUIT as we mustn't end the DATA. */
561 *message = string_sprintf("transport filter process failed (%d)%s",
563 more_errno == EX_EXECFAILED ? ": unable to execute command" : "");
566 case ERRNO_CHHEADER_FAIL: /* Handle a failed add_headers expansion;
567 can't send QUIT as we mustn't end the DATA. */
569 string_sprintf("failed to expand headers_add or headers_remove: %s",
570 expand_string_message);
573 case ERRNO_WRITEINCOMPLETE: /* failure to write a complete data block */
574 *message = string_sprintf("failed to write a data block");
578 case ERRNO_UTF8_FWD: /* no advertised SMTPUTF8, for international message */
579 *message = US"utf8 support required but not offered for forwarding";
580 DEBUG(D_deliver|D_transport) debug_printf("%s\n", *message);
585 /* Handle error responses from the remote mailer. */
589 *message = string_sprintf("SMTP error from remote mail server after %s%s: "
590 "%s", pl, smtp_command, s = string_printing(buffer));
591 *pass_message = TRUE;
596 /* No data was read. If there is no errno, this must be the EOF (i.e.
597 connection closed) case, which causes deferral. An explicit connection reset
598 error has the same effect. Otherwise, put the host's identity in the message,
599 leaving the errno value to be interpreted as well. In all cases, we have to
600 assume the connection is now dead. */
602 if (*errno_value == 0 || *errno_value == ECONNRESET)
604 *errno_value = ERRNO_SMTPCLOSED;
605 *message = US string_sprintf("Remote host closed connection "
606 "in response to %s%s", pl, smtp_command);
609 *message = US string_sprintf("%s [%s]", host->name, host->address);
616 /*************************************************
617 * Write error message to logs *
618 *************************************************/
620 /* This writes to the main log and to the message log.
623 addr the address item containing error information
624 host the current host
630 write_logs(address_item *addr, host_item *host)
632 uschar * message = LOGGING(outgoing_port)
633 ? string_sprintf("H=%s [%s]:%d", host->name, host->address,
634 host->port == PORT_NONE ? 25 : host->port)
635 : string_sprintf("H=%s [%s]", host->name, host->address);
639 message = string_sprintf("%s: %s", message, addr->message);
640 if (addr->basic_errno > 0)
641 message = string_sprintf("%s: %s", message, strerror(addr->basic_errno));
642 log_write(0, LOG_MAIN, "%s", message);
643 deliver_msglog("%s %s\n", tod_stamp(tod_log), message);
647 const uschar * s = exim_errstr(addr->basic_errno);
648 log_write(0, LOG_MAIN, "%s %s", message, s);
649 deliver_msglog("%s %s %s\n", tod_stamp(tod_log), message, s);
654 msglog_line(host_item * host, uschar * message)
656 deliver_msglog("%s H=%s [%s] %s\n", tod_stamp(tod_log),
657 host->name, host->address, message);
662 #ifndef DISABLE_EVENT
663 /*************************************************
664 * Post-defer action *
665 *************************************************/
667 /* This expands an arbitrary per-transport string.
668 It might, for example, be used to write to the database log.
671 addr the address item containing error information
672 host the current host
678 deferred_event_raise(address_item *addr, host_item *host)
680 uschar * action = addr->transport->event_action;
681 const uschar * save_domain;
687 save_domain = deliver_domain;
688 save_local = deliver_localpart;
690 /*XXX would ip & port already be set up? */
691 deliver_host_address = string_copy(host->address);
692 deliver_host_port = host->port == PORT_NONE ? 25 : host->port;
693 event_defer_errno = addr->basic_errno;
695 router_name = addr->router->name;
696 transport_name = addr->transport->name;
697 deliver_domain = addr->domain;
698 deliver_localpart = addr->local_part;
700 (void) event_raise(action, US"msg:host:defer",
702 ? addr->basic_errno > 0
703 ? string_sprintf("%s: %s", addr->message, strerror(addr->basic_errno))
704 : string_copy(addr->message)
705 : addr->basic_errno > 0
706 ? string_copy(US strerror(addr->basic_errno))
709 deliver_localpart = save_local;
710 deliver_domain = save_domain;
711 router_name = transport_name = NULL;
715 /*************************************************
716 * Synchronize SMTP responses *
717 *************************************************/
719 /* This function is called from smtp_deliver() to receive SMTP responses from
720 the server, and match them up with the commands to which they relate. When
721 PIPELINING is not in use, this function is called after every command, and is
722 therefore somewhat over-engineered, but it is simpler to use a single scheme
723 that works both with and without PIPELINING instead of having two separate sets
726 The set of commands that are buffered up with pipelining may start with MAIL
727 and may end with DATA; in between are RCPT commands that correspond to the
728 addresses whose status is PENDING_DEFER. All other commands (STARTTLS, AUTH,
729 etc.) are never buffered.
731 Errors after MAIL or DATA abort the whole process leaving the response in the
732 buffer. After MAIL, pending responses are flushed, and the original command is
733 re-instated in big_buffer for error messages. For RCPT commands, the remote is
734 permitted to reject some recipient addresses while accepting others. However
735 certain errors clearly abort the whole process. Set the value in
736 transport_return to PENDING_OK if the address is accepted. If there is a
737 subsequent general error, it will get reset accordingly. If not, it will get
738 converted to OK at the end.
741 sx smtp connection context
742 count the number of responses to read
743 pending_DATA 0 if last command sent was not DATA
744 +1 if previously had a good recipient
745 -1 if not previously had a good recipient
747 Returns: 3 if at least one address had 2xx and one had 5xx
748 2 if at least one address had 5xx but none had 2xx
749 1 if at least one host had a 2xx response, but none had 5xx
750 0 no address had 2xx or 5xx but no errors (all 4xx, or just DATA)
751 -1 timeout while reading RCPT response
752 -2 I/O or other non-response error for RCPT
753 -3 DATA or MAIL failed - errno and buffer set
757 sync_responses(smtp_context * sx, int count, int pending_DATA)
759 address_item *addr = sx->sync_addr;
760 smtp_transport_options_block *ob =
761 (smtp_transport_options_block *)sx->tblock->options_block;
764 /* Handle the response for a MAIL command. On error, reinstate the original
765 command in big_buffer for error message use, and flush any further pending
766 responses before returning, except after I/O errors and timeouts. */
768 if (sx->pending_MAIL)
771 if (!smtp_read_response(&sx->inblock, sx->buffer, sizeof(sx->buffer),
772 '2', ob->command_timeout))
774 DEBUG(D_transport) debug_printf("bad response for MAIL\n");
775 Ustrcpy(big_buffer, mail_command); /* Fits, because it came from there! */
776 if (errno == 0 && sx->buffer[0] != 0)
778 uschar flushbuffer[4096];
780 if (sx->buffer[0] == '4')
782 save_errno = ERRNO_MAIL4XX;
783 addr->more_errno |= ((sx->buffer[1] - '0')*10 + sx->buffer[2] - '0') << 8;
787 if (!smtp_read_response(&sx->inblock, flushbuffer, sizeof(flushbuffer),
788 '2', ob->command_timeout)
789 && (errno != 0 || flushbuffer[0] == 0))
795 if (pending_DATA) count--; /* Number of RCPT responses to come */
796 while (count-- > 0) /* Mark any pending addrs with the host used */
798 while (addr->transport_return != PENDING_DEFER) addr = addr->next;
799 addr->host_used = sx->host;
806 if (pending_DATA) count--; /* Number of RCPT responses to come */
808 /* Read and handle the required number of RCPT responses, matching each one up
809 with an address by scanning for the next address whose status is PENDING_DEFER.
814 while (addr->transport_return != PENDING_DEFER)
815 if (!(addr = addr->next))
818 /* The address was accepted */
819 addr->host_used = sx->host;
821 if (smtp_read_response(&sx->inblock, sx->buffer, sizeof(sx->buffer),
822 '2', ob->command_timeout))
825 addr->transport_return = PENDING_OK;
827 /* If af_dr_retry_exists is set, there was a routing delay on this address;
828 ensure that any address-specific retry record is expunged. We do this both
829 for the basic key and for the version that also includes the sender. */
831 if (testflag(addr, af_dr_retry_exists))
833 uschar *altkey = string_sprintf("%s:<%s>", addr->address_retry_key,
835 retry_add_item(addr, altkey, rf_delete);
836 retry_add_item(addr, addr->address_retry_key, rf_delete);
840 /* Timeout while reading the response */
842 else if (errno == ETIMEDOUT)
844 uschar *message = string_sprintf("SMTP timeout after RCPT TO:<%s>",
845 transport_rcpt_address(addr, sx->tblock->rcpt_include_affixes));
846 set_errno_nohost(sx->first_addr, ETIMEDOUT, message, DEFER, FALSE);
847 retry_add_item(addr, addr->address_retry_key, 0);
848 update_waiting = FALSE;
852 /* Handle other errors in obtaining an SMTP response by returning -1. This
853 will cause all the addresses to be deferred. Restore the SMTP command in
854 big_buffer for which we are checking the response, so the error message
857 else if (errno != 0 || sx->buffer[0] == 0)
859 string_format(big_buffer, big_buffer_size, "RCPT TO:<%s>",
860 transport_rcpt_address(addr, sx->tblock->rcpt_include_affixes));
864 /* Handle SMTP permanent and temporary response codes. */
869 string_sprintf("SMTP error from remote mail server after RCPT TO:<%s>: "
870 "%s", transport_rcpt_address(addr, sx->tblock->rcpt_include_affixes),
871 string_printing(sx->buffer));
872 setflag(addr, af_pass_message);
874 msglog_line(sx->host, addr->message);
876 /* The response was 5xx */
878 if (sx->buffer[0] == '5')
880 addr->transport_return = FAIL;
884 /* The response was 4xx */
888 addr->transport_return = DEFER;
889 addr->basic_errno = ERRNO_RCPT4XX;
890 addr->more_errno |= ((sx->buffer[1] - '0')*10 + sx->buffer[2] - '0') << 8;
894 #ifndef DISABLE_EVENT
895 event_defer_errno = addr->more_errno;
896 msg_event_raise(US"msg:rcpt:host:defer", addr);
899 /* Log temporary errors if there are more hosts to be tried.
900 If not, log this last one in the == line. */
903 log_write(0, LOG_MAIN, "H=%s [%s]: %s",
904 sx->host->name, sx->host->address, addr->message);
906 #ifndef DISABLE_EVENT
908 msg_event_raise(US"msg:rcpt:defer", addr);
911 /* Do not put this message on the list of those waiting for specific
912 hosts, as otherwise it is likely to be tried too often. */
914 update_waiting = FALSE;
916 /* Add a retry item for the address so that it doesn't get tried again
917 too soon. If address_retry_include_sender is true, add the sender address
921 ob->address_retry_include_sender
922 ? string_sprintf("%s:<%s>", addr->address_retry_key, sender_address)
923 : addr->address_retry_key,
928 } /* Loop for next RCPT response */
930 /* Update where to start at for the next block of responses, unless we
931 have already handled all the addresses. */
933 if (addr) sx->sync_addr = addr->next;
935 /* Handle a response to DATA. If we have not had any good recipients, either
936 previously or in this block, the response is ignored. */
938 if (pending_DATA != 0 &&
939 !smtp_read_response(&sx->inblock, sx->buffer, sizeof(sx->buffer),
940 '3', ob->command_timeout))
945 if (pending_DATA > 0 || (yield & 1) != 0)
947 if (errno == 0 && sx->buffer[0] == '4')
949 errno = ERRNO_DATA4XX;
950 sx->first_addr->more_errno |= ((sx->buffer[1] - '0')*10 + sx->buffer[2] - '0') << 8;
954 (void)check_response(sx->host, &errno, 0, sx->buffer, &code, &msg, &pass_message);
955 DEBUG(D_transport) debug_printf("%s\nerror for DATA ignored: pipelining "
956 "is in use and there were no good recipients\n", msg);
959 /* All responses read and handled; MAIL (if present) received 2xx and DATA (if
960 present) received 3xx. If any RCPTs were handled and yielded anything other
961 than 4xx, yield will be set non-zero. */
968 /* Do the client side of smtp-level authentication */
971 buffer EHLO response from server (gets overwritten)
972 addrlist chain of potential addresses to deliver
973 host host to deliver to
975 ibp, obp comms channel control blocks
978 OK Success, or failed (but not required): global "smtp_authenticated" set
979 DEFER Failed authentication (and was required)
980 ERROR Internal problem
982 FAIL_SEND Failed communications - transmit
987 smtp_auth(uschar *buffer, unsigned bufsize, address_item *addrlist, host_item *host,
988 smtp_transport_options_block *ob, BOOL is_esmtp,
989 smtp_inblock *ibp, smtp_outblock *obp)
992 uschar *fail_reason = US"server did not advertise AUTH support";
994 smtp_authenticated = FALSE;
995 client_authenticator = client_authenticated_id = client_authenticated_sender = NULL;
996 require_auth = verify_check_given_host(&ob->hosts_require_auth, host);
998 if (is_esmtp && !regex_AUTH) regex_AUTH =
999 regex_must_compile(US"\\n250[\\s\\-]AUTH\\s+([\\-\\w\\s]+)(?:\\n|$)",
1002 if (is_esmtp && regex_match_and_setup(regex_AUTH, buffer, 0, -1))
1004 uschar *names = string_copyn(expand_nstring[1], expand_nlength[1]);
1005 expand_nmax = -1; /* reset */
1007 /* Must not do this check until after we have saved the result of the
1008 regex match above. */
1010 if (require_auth == OK ||
1011 verify_check_given_host(&ob->hosts_try_auth, host) == OK)
1014 fail_reason = US"no common mechanisms were found";
1016 DEBUG(D_transport) debug_printf("scanning authentication mechanisms\n");
1018 /* Scan the configured authenticators looking for one which is configured
1019 for use as a client, which is not suppressed by client_condition, and
1020 whose name matches an authentication mechanism supported by the server.
1021 If one is found, attempt to authenticate by calling its client function.
1024 for (au = auths; !smtp_authenticated && au; au = au->next)
1028 (au->client_condition != NULL &&
1029 !expand_check_condition(au->client_condition, au->name,
1030 US"client authenticator")))
1032 DEBUG(D_transport) debug_printf("skipping %s authenticator: %s\n",
1034 (au->client)? "client_condition is false" :
1035 "not configured as a client");
1039 /* Loop to scan supported server mechanisms */
1044 int len = Ustrlen(au->public_name);
1045 while (isspace(*p)) p++;
1047 if (strncmpic(au->public_name, p, len) != 0 ||
1048 (p[len] != 0 && !isspace(p[len])))
1050 while (*p != 0 && !isspace(*p)) p++;
1054 /* Found data for a listed mechanism. Call its client entry. Set
1055 a flag in the outblock so that data is overwritten after sending so
1056 that reflections don't show it. */
1058 fail_reason = US"authentication attempt(s) failed";
1059 obp->authenticating = TRUE;
1060 rc = (au->info->clientcode)(au, ibp, obp,
1061 ob->command_timeout, buffer, bufsize);
1062 obp->authenticating = FALSE;
1063 DEBUG(D_transport) debug_printf("%s authenticator yielded %d\n",
1066 /* A temporary authentication failure must hold up delivery to
1067 this host. After a permanent authentication failure, we carry on
1068 to try other authentication methods. If all fail hard, try to
1069 deliver the message unauthenticated unless require_auth was set. */
1074 smtp_authenticated = TRUE; /* stops the outer loop */
1075 client_authenticator = au->name;
1076 if (au->set_client_id != NULL)
1077 client_authenticated_id = expand_string(au->set_client_id);
1080 /* Failure after writing a command */
1085 /* Failure after reading a response */
1088 if (errno != 0 || buffer[0] != '5') return FAIL;
1089 log_write(0, LOG_MAIN, "%s authenticator failed H=%s [%s] %s",
1090 au->name, host->name, host->address, buffer);
1093 /* Failure by some other means. In effect, the authenticator
1094 decided it wasn't prepared to handle this case. Typically this
1095 is the result of "fail" in an expansion string. Do we need to
1096 log anything here? Feb 2006: a message is now put in the buffer
1097 if logging is required. */
1101 log_write(0, LOG_MAIN, "%s authenticator cancelled "
1102 "authentication H=%s [%s] %s", au->name, host->name,
1103 host->address, buffer);
1106 /* Internal problem, message in buffer. */
1109 set_errno_nohost(addrlist, ERRNO_AUTHPROB, string_copy(buffer),
1114 break; /* If not authenticated, try next authenticator */
1115 } /* Loop for scanning supported server mechanisms */
1116 } /* Loop for further authenticators */
1120 /* If we haven't authenticated, but are required to, give up. */
1122 if (require_auth == OK && !smtp_authenticated)
1124 set_errno_nohost(addrlist, ERRNO_AUTHFAIL,
1125 string_sprintf("authentication required but %s", fail_reason), DEFER,
1134 /* Construct AUTH appendix string for MAIL TO */
1137 buffer to build string
1138 addrlist chain of potential addresses to deliver
1139 ob transport options
1141 Globals smtp_authenticated
1142 client_authenticated_sender
1143 Return True on error, otherwise buffer has (possibly empty) terminated string
1147 smtp_mail_auth_str(uschar *buffer, unsigned bufsize, address_item *addrlist,
1148 smtp_transport_options_block *ob)
1150 uschar *local_authenticated_sender = authenticated_sender;
1153 debug_printf("smtp_mail_auth_str: as<%s> os<%s> SA<%s>\n", authenticated_sender, ob->authenticated_sender, smtp_authenticated?"Y":"N");
1156 if (ob->authenticated_sender != NULL)
1158 uschar *new = expand_string(ob->authenticated_sender);
1161 if (!expand_string_forcedfail)
1163 uschar *message = string_sprintf("failed to expand "
1164 "authenticated_sender: %s", expand_string_message);
1165 set_errno_nohost(addrlist, ERRNO_EXPANDFAIL, message, DEFER, FALSE);
1169 else if (new[0] != 0) local_authenticated_sender = new;
1172 /* Add the authenticated sender address if present */
1174 if ((smtp_authenticated || ob->authenticated_sender_force) &&
1175 local_authenticated_sender != NULL)
1177 string_format(buffer, bufsize, " AUTH=%s",
1178 auth_xtextencode(local_authenticated_sender,
1179 Ustrlen(local_authenticated_sender)));
1180 client_authenticated_sender = string_copy(local_authenticated_sender);
1190 #ifdef EXPERIMENTAL_DANE
1191 /* Lookup TLSA record for host/port.
1192 Return: OK success with dnssec; DANE mode
1193 DEFER Do not use this host now, may retry later
1194 FAIL_FORCED No TLSA record; DANE not usable
1195 FAIL Do not use this connection
1199 tlsa_lookup(const host_item * host, dns_answer * dnsa, BOOL dane_required)
1201 /* move this out to host.c given the similarity to dns_lookup() ? */
1203 const uschar * fullname = buffer;
1207 /* TLSA lookup string */
1208 (void)sprintf(CS buffer, "_%d._tcp.%.256s", host->port, host->name);
1210 rc = dns_lookup(dnsa, buffer, T_TLSA, &fullname);
1211 sec = dns_is_secure(dnsa);
1213 debug_printf("TLSA lookup ret %d %sDNSSEC\n", rc, sec ? "" : "not ");
1220 log_write(0, LOG_MAIN, "DANE error: TLSA lookup not DNSSEC");
1223 return DEFER; /* just defer this TLS'd conn */
1225 case DNS_NODATA: /* no TLSA RR for this lookup */
1226 case DNS_NOMATCH: /* no records at all for this lookup */
1227 return dane_required ? FAIL : FAIL_FORCED;
1231 return dane_required ? FAIL : DEFER;
1238 typedef struct smtp_compare_s
1240 uschar *current_sender_address;
1241 struct transport_instance *tblock;
1245 /* Create a unique string that identifies this message, it is based on
1246 sender_address, helo_data and tls_certificate if enabled.
1250 smtp_local_identity(uschar * sender, struct transport_instance * tblock)
1252 address_item * addr1;
1253 uschar * if1 = US"";
1254 uschar * helo1 = US"";
1256 uschar * tlsc1 = US"";
1258 uschar * save_sender_address = sender_address;
1259 uschar * local_identity = NULL;
1260 smtp_transport_options_block * ob =
1261 (smtp_transport_options_block *)tblock->options_block;
1263 sender_address = sender;
1265 addr1 = deliver_make_addr (sender, TRUE);
1266 deliver_set_expansions(addr1);
1269 if1 = expand_string(ob->interface);
1272 helo1 = expand_string(ob->helo_data);
1275 if (ob->tls_certificate)
1276 tlsc1 = expand_string(ob->tls_certificate);
1277 local_identity = string_sprintf ("%s^%s^%s", if1, helo1, tlsc1);
1279 local_identity = string_sprintf ("%s^%s", if1, helo1);
1282 deliver_set_expansions(NULL);
1283 sender_address = save_sender_address;
1285 return local_identity;
1290 /* This routine is a callback that is called from transport_check_waiting.
1291 This function will evaluate the incoming message versus the previous
1292 message. If the incoming message is using a different local identity then
1293 we will veto this new message. */
1296 smtp_are_same_identities(uschar * message_id, smtp_compare_t * s_compare)
1298 uschar * message_local_identity,
1299 * current_local_identity,
1300 * new_sender_address;
1302 current_local_identity =
1303 smtp_local_identity(s_compare->current_sender_address, s_compare->tblock);
1305 if (!(new_sender_address = deliver_get_sender_address(message_id)))
1308 message_local_identity =
1309 smtp_local_identity(new_sender_address, s_compare->tblock);
1311 return Ustrcmp(current_local_identity, message_local_identity) == 0;
1317 ehlo_response(uschar * buf, uschar checks)
1319 size_t bsize = Ustrlen(buf);
1322 if ( checks & OPTION_TLS
1323 && pcre_exec(regex_STARTTLS, NULL, CS buf, bsize, 0, PCRE_EOPT, NULL, 0) < 0)
1324 checks &= ~OPTION_TLS;
1327 if ( checks & OPTION_IGNQ
1328 && pcre_exec(regex_IGNOREQUOTA, NULL, CS buf, bsize, 0,
1329 PCRE_EOPT, NULL, 0) < 0)
1330 checks &= ~OPTION_IGNQ;
1332 if ( checks & OPTION_CHUNKING
1333 && pcre_exec(regex_CHUNKING, NULL, CS buf, bsize, 0, PCRE_EOPT, NULL, 0) < 0)
1334 checks &= ~OPTION_CHUNKING;
1336 #ifndef DISABLE_PRDR
1337 if ( checks & OPTION_PRDR
1338 && pcre_exec(regex_PRDR, NULL, CS buf, bsize, 0, PCRE_EOPT, NULL, 0) < 0)
1339 checks &= ~OPTION_PRDR;
1343 if ( checks & OPTION_UTF8
1344 && pcre_exec(regex_UTF8, NULL, CS buf, bsize, 0, PCRE_EOPT, NULL, 0) < 0)
1345 checks &= ~OPTION_UTF8;
1348 if ( checks & OPTION_DSN
1349 && pcre_exec(regex_DSN, NULL, CS buf, bsize, 0, PCRE_EOPT, NULL, 0) < 0)
1350 checks &= ~OPTION_DSN;
1352 if ( checks & OPTION_PIPE
1353 && pcre_exec(regex_PIPELINING, NULL, CS buf, bsize, 0,
1354 PCRE_EOPT, NULL, 0) < 0)
1355 checks &= ~OPTION_PIPE;
1357 if ( checks & OPTION_SIZE
1358 && pcre_exec(regex_SIZE, NULL, CS buf, bsize, 0, PCRE_EOPT, NULL, 0) < 0)
1359 checks &= ~OPTION_SIZE;
1366 /* Callback for emitting a BDAT data chunk header.
1368 If given a nonzero size, first flush any buffered SMTP commands
1369 then emit the command.
1371 Reap previous SMTP command responses if requested, and always reap
1372 the response from a previous BDAT command.
1375 tctx transport context
1376 chunk_size value for SMTP BDAT command
1378 tc_chunk_last add LAST option to SMTP BDAT command
1379 tc_reap_prev reap response to previous SMTP commands
1381 Returns: OK or ERROR
1385 smtp_chunk_cmd_callback(transport_ctx * tctx, unsigned chunk_size,
1388 smtp_transport_options_block * ob =
1389 (smtp_transport_options_block *)(tctx->tblock->options_block);
1390 smtp_context * sx = tctx->smtp_context;
1394 /* Write SMTP chunk header command. If not reaping responses, note that
1395 there may be more writes (like, the chunk data) done soon. */
1399 if((cmd_count = smtp_write_command(&sx->outblock,
1400 flags & tc_reap_prev ? SCMD_FLUSH : SCMD_MORE,
1401 "BDAT %u%s\r\n", chunk_size, flags & tc_chunk_last ? " LAST" : "")
1402 ) < 0) return ERROR;
1403 if (flags & tc_chunk_last)
1404 data_command = string_copy(big_buffer); /* Save for later error message */
1407 prev_cmd_count = cmd_count += sx->cmd_count;
1409 /* Reap responses for any previous, but not one we just emitted */
1413 if (sx->pending_BDAT)
1416 if (flags & tc_reap_prev && prev_cmd_count > 0)
1418 DEBUG(D_transport) debug_printf("look for %d responses"
1419 " for previous pipelined cmds\n", prev_cmd_count);
1421 switch(sync_responses(sx, prev_cmd_count, 0))
1423 case 1: /* 2xx (only) => OK */
1424 case 3: sx->good_RCPT = TRUE; /* 2xx & 5xx => OK & progress made */
1425 case 2: sx->completed_addr = TRUE; /* 5xx (only) => progress made */
1426 case 0: break; /* No 2xx or 5xx, but no probs */
1428 case -1: /* Timeout on RCPT */
1429 default: return ERROR; /* I/O error, or any MAIL/DATA error */
1432 if (!sx->pending_BDAT)
1433 pipelining_active = FALSE;
1436 /* Reap response for an outstanding BDAT */
1438 if (sx->pending_BDAT)
1440 DEBUG(D_transport) debug_printf("look for one response for BDAT\n");
1442 if (!smtp_read_response(&sx->inblock, sx->buffer, sizeof(sx->buffer), '2',
1443 ob->command_timeout))
1445 if (errno == 0 && sx->buffer[0] == '4')
1447 errno = ERRNO_DATA4XX; /*XXX does this actually get used? */
1448 sx->addrlist->more_errno |=
1449 ((sx->buffer[1] - '0')*10 + sx->buffer[2] - '0') << 8;
1454 sx->pending_BDAT = FALSE;
1455 pipelining_active = FALSE;
1457 else if (chunk_size > 0)
1458 sx->pending_BDAT = TRUE;
1461 sx->cmd_count = cmd_count;
1467 /*************************************************
1468 * Make connection for given message *
1469 *************************************************/
1473 ctx connection context
1474 suppress_tls if TRUE, don't attempt a TLS connection - this is set for
1475 a second attempt after TLS initialization fails
1477 Returns: OK - the connection was made and the delivery attempted;
1478 fd is set in the conn context, tls_out set up.
1479 DEFER - the connection could not be made, or something failed
1480 while setting up the SMTP session, or there was a
1481 non-message-specific error, such as a timeout.
1482 ERROR - helo_data or add_headers or authenticated_sender is
1483 specified for this transport, and the string failed
1487 smtp_setup_conn(smtp_context * sx, BOOL suppress_tls)
1489 #if defined(SUPPORT_TLS) && defined(EXPERIMENTAL_DANE)
1490 dns_answer tlsa_dnsa;
1492 BOOL pass_message = FALSE;
1493 uschar * message = NULL;
1497 sx->ob = (smtp_transport_options_block *) sx->tblock->options_block;
1499 sx->lmtp = strcmpic(sx->ob->protocol, US"lmtp") == 0;
1500 sx->smtps = strcmpic(sx->ob->protocol, US"smtps") == 0;
1502 sx->send_rset = TRUE;
1503 sx->send_quit = TRUE;
1504 sx->setting_up = TRUE;
1506 sx->esmtp_sent = FALSE;
1508 sx->utf8_needed = FALSE;
1510 sx->dsn_all_lasthop = TRUE;
1511 #if defined(SUPPORT_TLS) && defined(EXPERIMENTAL_DANE)
1513 sx->dane_required = verify_check_given_host(&sx->ob->hosts_require_dane, sx->host) == OK;
1516 if ((sx->max_rcpt = sx->tblock->max_addresses) == 0) sx->max_rcpt = 999999;
1517 sx->peer_offered = 0;
1518 sx->avoid_option = 0;
1519 sx->igquotstr = US"";
1520 if (!sx->helo_data) sx->helo_data = sx->ob->helo_data;
1521 #ifdef EXPERIMENTAL_DSN_INFO
1522 sx->smtp_greeting = NULL;
1523 sx->helo_response = NULL;
1526 smtp_command = US"initial connection";
1527 sx->buffer[0] = '\0';
1529 /* Set up the buffer for reading SMTP response packets. */
1531 sx->inblock.buffer = sx->inbuffer;
1532 sx->inblock.buffersize = sizeof(sx->inbuffer);
1533 sx->inblock.ptr = sx->inbuffer;
1534 sx->inblock.ptrend = sx->inbuffer;
1536 /* Set up the buffer for holding SMTP commands while pipelining */
1538 sx->outblock.buffer = sx->outbuffer;
1539 sx->outblock.buffersize = sizeof(sx->outbuffer);
1540 sx->outblock.ptr = sx->outbuffer;
1541 sx->outblock.cmd_count = 0;
1542 sx->outblock.authenticating = FALSE;
1544 /* Reset the parameters of a TLS session. */
1547 tls_out.cipher = NULL; /* the one we may use for this transport */
1548 tls_out.ourcert = NULL;
1549 tls_out.peercert = NULL;
1550 tls_out.peerdn = NULL;
1551 #if defined(SUPPORT_TLS) && !defined(USE_GNUTLS)
1554 tls_out.ocsp = OCSP_NOT_REQ;
1556 /* Flip the legacy TLS-related variables over to the outbound set in case
1557 they're used in the context of the transport. Don't bother resetting
1558 afterward (when being used by a transport) as we're in a subprocess.
1559 For verify, unflipped once the callout is dealt with */
1561 tls_modify_variables(&tls_out);
1566 set_errno_nohost(sx->addrlist, ERRNO_TLSFAILURE, US"TLS support not available",
1572 /* Make a connection to the host if this isn't a continued delivery, and handle
1573 the initial interaction and HELO/EHLO/LHLO. Connect timeout errors are handled
1574 specially so they can be identified for retries. */
1576 if (!continue_hostname)
1579 HDEBUG(D_verify) debug_printf("interface=%s port=%d\n", sx->interface, sx->port);
1581 /* Get the actual port the connection will use, into sx->host */
1583 smtp_port_for_connect(sx->host, sx->port);
1585 #if defined(SUPPORT_TLS) && defined(EXPERIMENTAL_DANE)
1586 /* Do TLSA lookup for DANE */
1588 tls_out.dane_verified = FALSE;
1589 tls_out.tlsa_usage = 0;
1591 if (sx->host->dnssec == DS_YES)
1593 if( sx->dane_required
1594 || verify_check_given_host(&sx->ob->hosts_try_dane, sx->host) == OK
1596 switch (rc = tlsa_lookup(sx->host, &tlsa_dnsa, sx->dane_required))
1598 case OK: sx->dane = TRUE;
1599 sx->ob->tls_tempfail_tryclear = FALSE;
1601 case FAIL_FORCED: break;
1602 default: set_errno_nohost(sx->addrlist, ERRNO_DNSDEFER,
1603 string_sprintf("DANE error: tlsa lookup %s",
1604 rc == DEFER ? "DEFER" : "FAIL"),
1609 else if (sx->dane_required)
1611 set_errno_nohost(sx->addrlist, ERRNO_DNSDEFER,
1612 string_sprintf("DANE error: %s lookup not DNSSEC", sx->host->name),
1619 /* Make the TCP connection */
1621 sx->inblock.sock = sx->outblock.sock =
1622 smtp_connect(sx->host, sx->host_af, sx->interface,
1623 sx->ob->connect_timeout, sx->tblock);
1625 if (sx->inblock.sock < 0)
1627 uschar * msg = NULL;
1630 msg = US strerror(errno);
1631 HDEBUG(D_verify) debug_printf("connect: %s\n", msg);
1633 set_errno_nohost(sx->addrlist,
1634 errno == ETIMEDOUT ? ERRNO_CONNECTTIMEOUT : errno,
1635 sx->verify ? string_sprintf("could not connect: %s", msg)
1638 sx->send_quit = FALSE;
1642 /* Expand the greeting message while waiting for the initial response. (Makes
1643 sense if helo_data contains ${lookup dnsdb ...} stuff). The expansion is
1644 delayed till here so that $sending_interface and $sending_port are set. */
1647 if (!(sx->helo_data = expand_string(sx->helo_data)))
1649 log_write(0, LOG_MAIN|LOG_PANIC,
1650 "<%s>: failed to expand transport's helo_data value for callout: %s",
1651 sx->addrlist->address, expand_string_message);
1656 expand_string_message = NULL;
1657 if ((sx->helo_data = string_domain_utf8_to_alabel(sx->helo_data,
1658 &expand_string_message)),
1659 expand_string_message)
1661 log_write(0, LOG_MAIN|LOG_PANIC,
1662 "<%s>: failed to expand transport's helo_data value for callout: %s",
1663 sx->addrlist->address, expand_string_message);
1665 sx->helo_data = NULL;
1669 /* The first thing is to wait for an initial OK response. The dreaded "goto"
1670 is nevertheless a reasonably clean way of programming this kind of logic,
1671 where you want to escape on any error. */
1678 (void) setsockopt(sx->inblock.sock, IPPROTO_TCP, TCP_QUICKACK, US &off, sizeof(off));
1680 good_response = smtp_read_response(&sx->inblock, sx->buffer, sizeof(sx->buffer),
1681 '2', sx->ob->command_timeout);
1682 #ifdef EXPERIMENTAL_DSN_INFO
1683 sx->smtp_greeting = string_copy(sx->buffer);
1685 if (!good_response) goto RESPONSE_FAILED;
1687 #ifndef DISABLE_EVENT
1690 lookup_dnssec_authenticated = sx->host->dnssec==DS_YES ? US"yes"
1691 : sx->host->dnssec==DS_NO ? US"no" : NULL;
1692 s = event_raise(sx->tblock->event_action, US"smtp:connect", sx->buffer);
1695 set_errno_nohost(sx->addrlist, ERRNO_EXPANDFAIL,
1696 string_sprintf("deferred by smtp:connect event expansion: %s", s),
1704 /* Now check if the helo_data expansion went well, and sign off cleanly if
1709 message = string_sprintf("failed to expand helo_data: %s",
1710 expand_string_message);
1711 set_errno_nohost(sx->addrlist, ERRNO_EXPANDFAIL, message, DEFER, FALSE);
1717 /** Debugging without sending a message
1718 sx->addrlist->transport_return = DEFER;
1722 /* Errors that occur after this point follow an SMTP command, which is
1723 left in big_buffer by smtp_write_command() for use in error messages. */
1725 smtp_command = big_buffer;
1727 /* Tell the remote who we are...
1729 February 1998: A convention has evolved that ESMTP-speaking MTAs include the
1730 string "ESMTP" in their greeting lines, so make Exim send EHLO if the
1731 greeting is of this form. The assumption was that the far end supports it
1732 properly... but experience shows that there are some that give 5xx responses,
1733 even though the banner includes "ESMTP" (there's a bloody-minded one that
1734 says "ESMTP not spoken here"). Cope with that case.
1736 September 2000: Time has passed, and it seems reasonable now to always send
1737 EHLO at the start. It is also convenient to make the change while installing
1740 July 2003: Joachim Wieland met a broken server that advertises "PIPELINING"
1741 but times out after sending MAIL FROM, RCPT TO and DATA all together. There
1742 would be no way to send out the mails, so there is now a host list
1743 "hosts_avoid_esmtp" that disables ESMTP for special hosts and solves the
1744 PIPELINING problem as well. Maybe it can also be useful to cure other
1745 problems with broken servers.
1747 Exim originally sent "Helo" at this point and ran for nearly a year that way.
1748 Then somebody tried it with a Microsoft mailer... It seems that all other
1749 mailers use upper case for some reason (the RFC is quite clear about case
1750 independence) so, for peace of mind, I gave in. */
1752 sx->esmtp = verify_check_given_host(&sx->ob->hosts_avoid_esmtp, sx->host) != OK;
1754 /* Alas; be careful, since this goto is not an error-out, so conceivably
1755 we might set data between here and the target which we assume to exist
1756 and be usable. I can see this coming back to bite us. */
1760 smtp_peer_options |= OPTION_TLS;
1761 suppress_tls = FALSE;
1762 sx->ob->tls_tempfail_tryclear = FALSE;
1763 smtp_command = US"SSL-on-connect";
1770 if (smtp_write_command(&sx->outblock, SCMD_FLUSH, "%s %s\r\n",
1771 sx->lmtp ? "LHLO" : "EHLO", sx->helo_data) < 0)
1773 sx->esmtp_sent = TRUE;
1774 if (!smtp_read_response(&sx->inblock, sx->buffer, sizeof(sx->buffer), '2',
1775 sx->ob->command_timeout))
1777 if (errno != 0 || sx->buffer[0] == 0 || sx->lmtp)
1779 #ifdef EXPERIMENTAL_DSN_INFO
1780 sx->helo_response = string_copy(sx->buffer);
1782 goto RESPONSE_FAILED;
1786 #ifdef EXPERIMENTAL_DSN_INFO
1787 sx->helo_response = string_copy(sx->buffer);
1792 debug_printf("not sending EHLO (host matches hosts_avoid_esmtp)\n");
1797 int n = sizeof(sx->buffer);
1798 uschar * rsp = sx->buffer;
1800 if (sx->esmtp_sent && (n = Ustrlen(sx->buffer)) < sizeof(sx->buffer)/2)
1801 { rsp = sx->buffer + n + 1; n = sizeof(sx->buffer) - n; }
1803 if (smtp_write_command(&sx->outblock, SCMD_FLUSH, "HELO %s\r\n", sx->helo_data) < 0)
1805 good_response = smtp_read_response(&sx->inblock, rsp, n,
1806 '2', sx->ob->command_timeout);
1807 #ifdef EXPERIMENTAL_DSN_INFO
1808 sx->helo_response = string_copy(rsp);
1812 /* Handle special logging for a closed connection after HELO
1813 when had previously sent EHLO */
1815 if (rsp != sx->buffer && rsp[0] == 0 && (errno == 0 || errno == ECONNRESET))
1817 errno = ERRNO_SMTPCLOSED;
1818 goto EHLOHELO_FAILED;
1820 Ustrncpy(sx->buffer, rsp, sizeof(sx->buffer)/2);
1821 goto RESPONSE_FAILED;
1825 sx->avoid_option = sx->peer_offered = smtp_peer_options = 0;
1827 if (sx->esmtp || sx->lmtp)
1829 sx->peer_offered = ehlo_response(sx->buffer,
1830 OPTION_TLS /* others checked later */
1833 /* Set tls_offered if the response to EHLO specifies support for STARTTLS. */
1836 smtp_peer_options |= sx->peer_offered & OPTION_TLS;
1841 /* For continuing deliveries down the same channel, having re-exec'd the socket
1842 is the standard input; for a socket held open from verify it is recorded
1843 in the cutthrough context block. Either way we don't need to redo EHLO here
1844 (but may need to do so for TLS - see below).
1845 Set up the pointer to where subsequent commands will be left, for
1846 error messages. Note that smtp_peer_options will have been
1847 set from the command line if they were set in the process that passed the
1850 /*XXX continue case needs to propagate DSN_INFO, prob. in deliver.c
1851 as the continue goes via transport_pass_socket() and doublefork and exec.
1852 It does not wait. Unclear how we keep separate host's responses
1853 separate - we could match up by host ip+port as a bodge. */
1857 if (cutthrough.fd >= 0 && cutthrough.callout_hold_only)
1859 sx->inblock.sock = sx->outblock.sock = cutthrough.fd;
1860 sx->host->port = sx->port = cutthrough.host.port;
1864 sx->inblock.sock = sx->outblock.sock = 0; /* stdin */
1865 smtp_port_for_connect(sx->host, sx->port); /* Record the port that was used */
1867 smtp_command = big_buffer;
1868 sx->helo_data = NULL; /* ensure we re-expand ob->helo_data */
1870 /* For a continued connection with TLS being proxied for us, or a
1871 held-open verify connection with TLS, nothing more to do. */
1873 if ( continue_proxy_cipher
1874 || (cutthrough.fd >= 0 && cutthrough.callout_hold_only && cutthrough.is_tls)
1877 sx->peer_offered = smtp_peer_options;
1878 pipelining_active = !!(smtp_peer_options & OPTION_PIPE);
1879 HDEBUG(D_transport) debug_printf("continued connection, %s TLS\n",
1880 continue_proxy_cipher ? "proxied" : "verify conn with");
1883 HDEBUG(D_transport) debug_printf("continued connection, no TLS\n");
1886 /* If TLS is available on this connection, whether continued or not, attempt to
1887 start up a TLS session, unless the host is in hosts_avoid_tls. If successful,
1888 send another EHLO - the server may give a different answer in secure mode. We
1889 use a separate buffer for reading the response to STARTTLS so that if it is
1890 negative, the original EHLO data is available for subsequent analysis, should
1891 the client not be required to use TLS. If the response is bad, copy the buffer
1892 for error analysis. */
1895 if ( smtp_peer_options & OPTION_TLS
1897 && verify_check_given_host(&sx->ob->hosts_avoid_tls, sx->host) != OK
1899 || verify_check_given_host(&sx->ob->hosts_verify_avoid_tls, sx->host) != OK
1902 uschar buffer2[4096];
1903 if (smtp_write_command(&sx->outblock, SCMD_FLUSH, "STARTTLS\r\n") < 0)
1906 /* If there is an I/O error, transmission of this message is deferred. If
1907 there is a temporary rejection of STARRTLS and tls_tempfail_tryclear is
1908 false, we also defer. However, if there is a temporary rejection of STARTTLS
1909 and tls_tempfail_tryclear is true, or if there is an outright rejection of
1910 STARTTLS, we carry on. This means we will try to send the message in clear,
1911 unless the host is in hosts_require_tls (tested below). */
1913 if (!smtp_read_response(&sx->inblock, buffer2, sizeof(buffer2), '2',
1914 sx->ob->command_timeout))
1918 || (buffer2[0] == '4' && !sx->ob->tls_tempfail_tryclear)
1921 Ustrncpy(sx->buffer, buffer2, sizeof(sx->buffer));
1922 sx->buffer[sizeof(sx->buffer)-1] = '\0';
1923 goto RESPONSE_FAILED;
1927 /* STARTTLS accepted: try to negotiate a TLS session. */
1932 address_item * addr;
1934 int rc = tls_client_start(sx->inblock.sock, sx->host, sx->addrlist, sx->tblock,
1935 # ifdef EXPERIMENTAL_DANE
1936 sx->dane ? &tlsa_dnsa : NULL,
1940 /* TLS negotiation failed; give an error. From outside, this function may
1941 be called again to try in clear on a new connection, if the options permit
1942 it for this host. */
1946 # ifdef EXPERIMENTAL_DANE
1947 if (sx->dane) log_write(0, LOG_MAIN,
1948 "DANE attempt failed; TLS connection to %s [%s]: %s",
1949 sx->host->name, sx->host->address, errstr);
1952 errno = ERRNO_TLSFAILURE;
1953 message = string_sprintf("TLS session: %s", errstr);
1954 sx->send_quit = FALSE;
1958 /* TLS session is set up */
1960 smtp_peer_options_wrap = smtp_peer_options;
1961 for (addr = sx->addrlist; addr; addr = addr->next)
1962 if (addr->transport_return == PENDING_DEFER)
1964 addr->cipher = tls_out.cipher;
1965 addr->ourcert = tls_out.ourcert;
1966 addr->peercert = tls_out.peercert;
1967 addr->peerdn = tls_out.peerdn;
1968 addr->ocsp = tls_out.ocsp;
1973 /* if smtps, we'll have smtp_command set to something else; always safe to
1975 smtp_command = big_buffer;
1977 /* If we started TLS, redo the EHLO/LHLO exchange over the secure channel. If
1978 helo_data is null, we are dealing with a connection that was passed from
1979 another process, and so we won't have expanded helo_data above. We have to
1980 expand it here. $sending_ip_address and $sending_port are set up right at the
1981 start of the Exim process (in exim.c). */
1983 if (tls_out.active >= 0)
1988 if (!sx->helo_data && !(sx->helo_data = expand_string(sx->ob->helo_data)))
1990 uschar *message = string_sprintf("failed to expand helo_data: %s",
1991 expand_string_message);
1992 set_errno_nohost(sx->addrlist, ERRNO_EXPANDFAIL, message, DEFER, FALSE);
1997 /* For SMTPS we need to wait for the initial OK response. */
2000 good_response = smtp_read_response(&sx->inblock, sx->buffer, sizeof(sx->buffer),
2001 '2', sx->ob->command_timeout);
2002 #ifdef EXPERIMENTAL_DSN_INFO
2003 sx->smtp_greeting = string_copy(sx->buffer);
2005 if (!good_response) goto RESPONSE_FAILED;
2009 greeting_cmd = "EHLO";
2012 greeting_cmd = "HELO";
2014 debug_printf("not sending EHLO (host matches hosts_avoid_esmtp)\n");
2017 if (smtp_write_command(&sx->outblock, SCMD_FLUSH, "%s %s\r\n",
2018 sx->lmtp ? "LHLO" : greeting_cmd, sx->helo_data) < 0)
2020 good_response = smtp_read_response(&sx->inblock, sx->buffer, sizeof(sx->buffer),
2021 '2', sx->ob->command_timeout);
2022 #ifdef EXPERIMENTAL_DSN_INFO
2023 sx->helo_response = string_copy(sx->buffer);
2025 if (!good_response) goto RESPONSE_FAILED;
2026 smtp_peer_options = 0;
2029 /* If the host is required to use a secure channel, ensure that we
2033 # ifdef EXPERIMENTAL_DANE
2036 || verify_check_given_host(&sx->ob->hosts_require_tls, sx->host) == OK
2039 errno = ERRNO_TLSREQUIRED;
2040 message = string_sprintf("a TLS session is required, but %s",
2041 smtp_peer_options & OPTION_TLS
2042 ? "an attempt to start TLS failed" : "the server did not offer TLS support");
2045 #endif /*SUPPORT_TLS*/
2047 /* If TLS is active, we have just started it up and re-done the EHLO command,
2048 so its response needs to be analyzed. If TLS is not active and this is a
2049 continued session down a previously-used socket, we haven't just done EHLO, so
2052 if (continue_hostname == NULL
2054 || tls_out.active >= 0
2058 if (sx->esmtp || sx->lmtp)
2060 sx->peer_offered = ehlo_response(sx->buffer,
2062 | (sx->lmtp && sx->ob->lmtp_ignore_quota ? OPTION_IGNQ : 0)
2066 | (sx->addrlist->prop.utf8_msg ? OPTION_UTF8 : 0)
2067 /*XXX if we hand peercaps on to continued-conn processes,
2068 must not depend on this addr */
2072 | (sx->ob->size_addition >= 0 ? OPTION_SIZE : 0)
2075 /* Set for IGNOREQUOTA if the response to LHLO specifies support and the
2076 lmtp_ignore_quota option was set. */
2078 sx->igquotstr = sx->peer_offered & OPTION_IGNQ ? US" IGNOREQUOTA" : US"";
2080 /* If the response to EHLO specified support for the SIZE parameter, note
2081 this, provided size_addition is non-negative. */
2083 smtp_peer_options |= sx->peer_offered & OPTION_SIZE;
2085 /* Note whether the server supports PIPELINING. If hosts_avoid_esmtp matched
2086 the current host, esmtp will be false, so PIPELINING can never be used. If
2087 the current host matches hosts_avoid_pipelining, don't do it. */
2089 if ( sx->peer_offered & OPTION_PIPE
2090 && verify_check_given_host(&sx->ob->hosts_avoid_pipelining, sx->host) != OK)
2091 smtp_peer_options |= OPTION_PIPE;
2093 DEBUG(D_transport) debug_printf("%susing PIPELINING\n",
2094 smtp_peer_options & OPTION_PIPE ? "" : "not ");
2096 if ( sx->peer_offered & OPTION_CHUNKING
2097 && verify_check_given_host(&sx->ob->hosts_try_chunking, sx->host) != OK)
2098 sx->peer_offered &= ~OPTION_CHUNKING;
2100 if (sx->peer_offered & OPTION_CHUNKING)
2101 {DEBUG(D_transport) debug_printf("CHUNKING usable\n");}
2103 #ifndef DISABLE_PRDR
2104 if ( sx->peer_offered & OPTION_PRDR
2105 && verify_check_given_host(&sx->ob->hosts_try_prdr, sx->host) != OK)
2106 sx->peer_offered &= ~OPTION_PRDR;
2108 if (sx->peer_offered & OPTION_PRDR)
2109 {DEBUG(D_transport) debug_printf("PRDR usable\n");}
2112 /* Note if the server supports DSN */
2113 smtp_peer_options |= sx->peer_offered & OPTION_DSN;
2114 DEBUG(D_transport) debug_printf("%susing DSN\n",
2115 sx->peer_offered & OPTION_DSN ? "" : "not ");
2117 /* Note if the response to EHLO specifies support for the AUTH extension.
2118 If it has, check that this host is one we want to authenticate to, and do
2119 the business. The host name and address must be available when the
2120 authenticator's client driver is running. */
2122 switch (yield = smtp_auth(sx->buffer, sizeof(sx->buffer), sx->addrlist, sx->host,
2123 sx->ob, sx->esmtp, &sx->inblock, &sx->outblock))
2125 default: goto SEND_QUIT;
2127 case FAIL_SEND: goto SEND_FAILED;
2128 case FAIL: goto RESPONSE_FAILED;
2132 pipelining_active = !!(smtp_peer_options & OPTION_PIPE);
2134 /* The setting up of the SMTP call is now complete. Any subsequent errors are
2135 message-specific. */
2137 sx->setting_up = FALSE;
2140 if (sx->addrlist->prop.utf8_msg)
2142 sx->utf8_needed = !sx->addrlist->prop.utf8_downcvt
2143 && !sx->addrlist->prop.utf8_downcvt_maybe;
2144 DEBUG(D_transport) if (!sx->utf8_needed)
2145 debug_printf("utf8: %s downconvert\n",
2146 sx->addrlist->prop.utf8_downcvt ? "mandatory" : "optional");
2149 /* If this is an international message we need the host to speak SMTPUTF8 */
2150 if (sx->utf8_needed && !(sx->peer_offered & OPTION_UTF8))
2152 errno = ERRNO_UTF8_FWD;
2153 goto RESPONSE_FAILED;
2165 sx->send_quit = check_response(sx->host, &errno, sx->addrlist->more_errno,
2166 sx->buffer, &code, &message, &pass_message);
2171 message = US string_sprintf("send() to %s [%s] failed: %s",
2172 sx->host->name, sx->host->address, strerror(errno));
2173 sx->send_quit = FALSE;
2176 /* This label is jumped to directly when a TLS negotiation has failed,
2177 or was not done for a host for which it is required. Values will be set
2178 in message and errno, and setting_up will always be true. Treat as
2179 a temporary error. */
2183 message = string_sprintf("Remote host closed connection in response to %s"
2184 " (EHLO response was: %s)", smtp_command, sx->buffer);
2185 sx->send_quit = FALSE;
2194 /* The failure happened while setting up the call; see if the failure was
2195 a 5xx response (this will either be on connection, or following HELO - a 5xx
2196 after EHLO causes it to try HELO). If so, and there are no more hosts to try,
2197 fail all addresses, as this host is never going to accept them. For other
2198 errors during setting up (timeouts or whatever), defer all addresses, and
2199 yield DEFER, so that the host is not tried again for a while.
2201 XXX This peeking for another host feels like a layering violation. We want
2202 to note the host as unusable, but down here we shouldn't know if this was
2203 the last host to try for the addr(list). Perhaps the upper layer should be
2204 the one to do set_errno() ? The problem is that currently the addr is where
2205 errno etc. are stashed, but until we run out of hosts to try the errors are
2206 host-specific. Maybe we should enhance the host_item definition? */
2209 sx->ok = FALSE; /* For when reached by GOTO */
2210 set_errno(sx->addrlist, errno, message,
2215 || errno == ERRNO_UTF8_FWD
2218 pass_message, sx->host
2219 #ifdef EXPERIMENTAL_DSN_INFO
2220 , sx->smtp_greeting, sx->helo_response
2230 (void)smtp_write_command(&sx->outblock, SCMD_FLUSH, "QUIT\r\n");
2233 tls_close(FALSE, TRUE);
2236 /* Close the socket, and return the appropriate value, first setting
2237 works because the NULL setting is passed back to the calling process, and
2238 remote_max_parallel is forced to 1 when delivering over an existing connection,
2241 HDEBUG(D_transport|D_acl|D_v) debug_printf_indent(" SMTP(close)>>\n");
2244 shutdown(sx->outblock.sock, SHUT_WR);
2245 if (fcntl(sx->inblock.sock, F_SETFL, O_NONBLOCK) == 0)
2246 for (rc = 16; read(sx->inblock.sock, sx->inbuffer, sizeof(sx->inbuffer)) > 0 && rc > 0;)
2247 rc--; /* drain socket */
2248 sx->send_quit = FALSE;
2250 (void)close(sx->inblock.sock);
2251 sx->inblock.sock = sx->outblock.sock = -1;
2253 #ifndef DISABLE_EVENT
2254 (void) event_raise(sx->tblock->event_action, US"tcp:close", NULL);
2257 continue_transport = NULL;
2258 continue_hostname = NULL;
2265 /* Create the string of options that will be appended to the MAIL FROM:
2266 in the connection context buffer */
2269 build_mailcmd_options(smtp_context * sx, address_item * addrlist)
2271 uschar * p = sx->buffer;
2272 address_item * addr;
2277 /* If we know the receiving MTA supports the SIZE qualification, and we know it,
2278 send it, adding something to the message size to allow for imprecision
2279 and things that get added en route. Exim keeps the number of lines
2280 in a message, so we can give an accurate value for the original message, but we
2281 need some additional to handle added headers. (Double "." characters don't get
2282 included in the count.) */
2284 if ( message_size > 0
2285 && sx->peer_offered & OPTION_SIZE && !(sx->avoid_option & OPTION_SIZE))
2287 /*XXX problem here under spool_files_wireformat?
2288 Or just forget about lines? Or inflate by a fixed proportion? */
2290 sprintf(CS p, " SIZE=%d", message_size+message_linecount+sx->ob->size_addition);
2294 #ifndef DISABLE_PRDR
2295 /* If it supports Per-Recipient Data Reponses, and we have omre than one recipient,
2298 sx->prdr_active = FALSE;
2299 if (sx->peer_offered & OPTION_PRDR)
2300 for (addr = addrlist; addr; addr = addr->next)
2301 if (addr->transport_return == PENDING_DEFER)
2303 for (addr = addr->next; addr; addr = addr->next)
2304 if (addr->transport_return == PENDING_DEFER)
2305 { /* at least two recipients to send */
2306 sx->prdr_active = TRUE;
2307 sprintf(CS p, " PRDR"); p += 5;
2315 /* If it supports internationalised messages, and this meesage need that,
2318 if ( sx->peer_offered & OPTION_UTF8
2319 && addrlist->prop.utf8_msg
2320 && !addrlist->prop.utf8_downcvt
2322 Ustrcpy(p, " SMTPUTF8"), p += 9;
2325 /* check if all addresses have DSN-lasthop flag; do not send RET and ENVID if so */
2326 for (sx->dsn_all_lasthop = TRUE, addr = addrlist, address_count = 0;
2327 addr && address_count < sx->max_rcpt;
2328 addr = addr->next) if (addr->transport_return == PENDING_DEFER)
2331 if (!(addr->dsn_flags & rf_dsnlasthop))
2333 sx->dsn_all_lasthop = FALSE;
2338 /* Add any DSN flags to the mail command */
2340 if (sx->peer_offered & OPTION_DSN && !sx->dsn_all_lasthop)
2342 if (dsn_ret == dsn_ret_hdrs)
2343 { Ustrcpy(p, " RET=HDRS"); p += 9; }
2344 else if (dsn_ret == dsn_ret_full)
2345 { Ustrcpy(p, " RET=FULL"); p += 9; }
2349 string_format(p, sizeof(sx->buffer) - (p-sx->buffer), " ENVID=%s", dsn_envid);
2354 /* If an authenticated_sender override has been specified for this transport
2355 instance, expand it. If the expansion is forced to fail, and there was already
2356 an authenticated_sender for this message, the original value will be used.
2357 Other expansion failures are serious. An empty result is ignored, but there is
2358 otherwise no check - this feature is expected to be used with LMTP and other
2359 cases where non-standard addresses (e.g. without domains) might be required. */
2361 if (smtp_mail_auth_str(p, sizeof(sx->buffer) - (p-sx->buffer), addrlist, sx->ob))
2369 build_rcptcmd_options(smtp_context * sx, const address_item * addr)
2371 uschar * p = sx->buffer;
2374 /* Add any DSN flags to the rcpt command */
2376 if (sx->peer_offered & OPTION_DSN && !(addr->dsn_flags & rf_dsnlasthop))
2378 if (addr->dsn_flags & rf_dsnflags)
2383 Ustrcpy(p, " NOTIFY=");
2385 for (i = 0; i < nelem(rf_list); i++) if (addr->dsn_flags & rf_list[i])
2387 if (!first) *p++ = ',';
2389 Ustrcpy(p, rf_names[i]);
2394 if (addr->dsn_orcpt)
2396 string_format(p, sizeof(sx->buffer) - (p-sx->buffer), " ORCPT=%s",
2407 0 good, rcpt results in addr->transport_return (PENDING_OK, DEFER, FAIL)
2408 -1 MAIL response error
2409 -2 any non-MAIL read i/o error
2410 -3 non-MAIL response timeout
2411 -4 internal error; channel still usable
2416 smtp_write_mail_and_rcpt_cmds(smtp_context * sx, int * yield)
2418 address_item * addr;
2422 if (build_mailcmd_options(sx, sx->first_addr) != OK)
2428 /* From here until we send the DATA command, we can make use of PIPELINING
2429 if the server host supports it. The code has to be able to check the responses
2430 at any point, for when the buffer fills up, so we write it totally generally.
2431 When PIPELINING is off, each command written reports that it has flushed the
2434 sx->pending_MAIL = TRUE; /* The block starts with MAIL */
2437 uschar * s = sx->from_addr;
2439 uschar * errstr = NULL;
2441 /* If we must downconvert, do the from-address here. Remember we had to
2442 for the to-addresses (done below), and also (ugly) for re-doing when building
2443 the delivery log line. */
2445 if ( sx->addrlist->prop.utf8_msg
2446 && (sx->addrlist->prop.utf8_downcvt || !(sx->peer_offered & OPTION_UTF8))
2449 if (s = string_address_utf8_to_alabel(s, &errstr), errstr)
2451 set_errno_nohost(sx->addrlist, ERRNO_EXPANDFAIL, errstr, DEFER, FALSE);
2455 setflag(sx->addrlist, af_utf8_downcvt);
2459 rc = smtp_write_command(&sx->outblock, pipelining_active ? SCMD_BUFFER : SCMD_FLUSH,
2460 "MAIL FROM:<%s>%s\r\n", s, sx->buffer);
2463 mail_command = string_copy(big_buffer); /* Save for later error message */
2467 case -1: /* Transmission error */
2470 case +1: /* Cmd was sent */
2471 if (!smtp_read_response(&sx->inblock, sx->buffer, sizeof(sx->buffer), '2',
2472 sx->ob->command_timeout))
2474 if (errno == 0 && sx->buffer[0] == '4')
2476 errno = ERRNO_MAIL4XX;
2477 sx->addrlist->more_errno |= ((sx->buffer[1] - '0')*10 + sx->buffer[2] - '0') << 8;
2481 sx->pending_MAIL = FALSE;
2484 /* otherwise zero: command queued for pipeline */
2487 /* Pass over all the relevant recipient addresses for this host, which are the
2488 ones that have status PENDING_DEFER. If we are using PIPELINING, we can send
2489 several before we have to read the responses for those seen so far. This
2490 checking is done by a subroutine because it also needs to be done at the end.
2491 Send only up to max_rcpt addresses at a time, leaving next_addr pointing to
2492 the next one if not all are sent.
2494 In the MUA wrapper situation, we want to flush the PIPELINING buffer for the
2495 last address because we want to abort if any recipients have any kind of
2496 problem, temporary or permanent. We know that all recipient addresses will have
2497 the PENDING_DEFER status, because only one attempt is ever made, and we know
2498 that max_rcpt will be large, so all addresses will be done at once.
2500 For verify we flush the pipeline after any (the only) rcpt address. */
2502 for (addr = sx->first_addr, address_count = 0;
2503 addr && address_count < sx->max_rcpt;
2504 addr = addr->next) if (addr->transport_return == PENDING_DEFER)
2510 if (tcp_out_fastopen && !tcp_out_fastopen_logged)
2511 setflag(addr, af_tcp_fastopen);
2513 addr->dsn_aware = sx->peer_offered & OPTION_DSN
2514 ? dsn_support_yes : dsn_support_no;
2517 no_flush = pipelining_active && !sx->verify
2518 && (!mua_wrapper || addr->next && address_count < sx->max_rcpt);
2520 build_rcptcmd_options(sx, addr);
2522 /* Now send the RCPT command, and process outstanding responses when
2523 necessary. After a timeout on RCPT, we just end the function, leaving the
2524 yield as OK, because this error can often mean that there is a problem with
2525 just one address, so we don't want to delay the host. */
2527 rcpt_addr = transport_rcpt_address(addr, sx->tblock->rcpt_include_affixes);
2530 if ( testflag(sx->addrlist, af_utf8_downcvt)
2531 && !(rcpt_addr = string_address_utf8_to_alabel(rcpt_addr, NULL))
2534 /*XXX could we use a per-address errstr here? Not fail the whole send? */
2535 errno = ERRNO_EXPANDFAIL;
2536 return -5; /*XXX too harsh? */
2540 count = smtp_write_command(&sx->outblock, no_flush ? SCMD_BUFFER : SCMD_FLUSH,
2541 "RCPT TO:<%s>%s%s\r\n", rcpt_addr, sx->igquotstr, sx->buffer);
2543 if (count < 0) return -5;
2546 switch(sync_responses(sx, count, 0))
2548 case 3: sx->ok = TRUE; /* 2xx & 5xx => OK & progress made */
2549 case 2: sx->completed_addr = TRUE; /* 5xx (only) => progress made */
2552 case 1: sx->ok = TRUE; /* 2xx (only) => OK, but if LMTP, */
2553 if (!sx->lmtp) /* can't tell about progress yet */
2554 sx->completed_addr = TRUE;
2555 case 0: /* No 2xx or 5xx, but no probs */
2558 case -1: return -3; /* Timeout on RCPT */
2559 case -2: return -2; /* non-MAIL read i/o error */
2560 default: return -1; /* any MAIL error */
2562 sx->pending_MAIL = FALSE; /* Dealt with MAIL */
2564 } /* Loop for next address */
2566 tcp_out_fastopen_logged = TRUE;
2567 sx->next_addr = addr;
2573 /*****************************************************
2574 * Proxy TLS connection for another transport process *
2575 ******************************************************/
2577 Use the given buffer as a staging area, and select on both the given fd
2578 and the TLS'd client-fd for data to read (per the coding in ip_recv() and
2579 fd_ready() this is legitimate). Do blocking full-size writes, and reads
2583 buf space to use for buffering
2584 bufsiz size of buffer
2585 proxy_fd comms to proxied process
2586 timeout per-read timeout, seconds
2590 smtp_proxy_tls(uschar * buf, size_t bsize, int proxy_fd, int timeout)
2593 int max_fd = MAX(proxy_fd, tls_out.active) + 1;
2594 int rc, i, fd_bits, nbytes;
2596 set_process_info("proxying TLS connection for continued transport");
2598 FD_SET(tls_out.active, &rfds);
2599 FD_SET(proxy_fd, &rfds);
2601 for (fd_bits = 3; fd_bits; )
2603 time_t time_left = timeout;
2604 time_t time_start = time(NULL);
2610 struct timeval tv = { time_left, 0 };
2613 (SELECT_ARG2_TYPE *)&rfds, NULL, (SELECT_ARG2_TYPE *)&efds, &tv);
2615 if (rc < 0 && errno == EINTR)
2616 if ((time_left -= time(NULL) - time_start) > 0) continue;
2620 DEBUG(D_transport) if (rc == 0) debug_printf("%s: timed out\n", __FUNCTION__);
2624 if (FD_ISSET(tls_out.active, &efds) || FD_ISSET(proxy_fd, &efds))
2626 DEBUG(D_transport) debug_printf("select: exceptional cond on %s fd\n",
2627 FD_ISSET(proxy_fd, &efds) ? "proxy" : "tls");
2631 while (rc < 0 || !(FD_ISSET(tls_out.active, &rfds) || FD_ISSET(proxy_fd, &rfds)));
2633 /* handle inbound data */
2634 if (FD_ISSET(tls_out.active, &rfds))
2635 if ((rc = tls_read(FALSE, buf, bsize)) <= 0)
2638 FD_CLR(tls_out.active, &rfds);
2639 shutdown(proxy_fd, SHUT_WR);
2644 for (nbytes = 0; rc - nbytes > 0; nbytes += i)
2645 if ((i = write(proxy_fd, buf + nbytes, rc - nbytes)) < 0) return;
2647 else if (fd_bits & 1)
2648 FD_SET(tls_out.active, &rfds);
2650 /* handle outbound data */
2651 if (FD_ISSET(proxy_fd, &rfds))
2652 if ((rc = read(proxy_fd, buf, bsize)) <= 0)
2655 tls_close(FALSE, TRUE);
2659 for (nbytes = 0; rc - nbytes > 0; nbytes += i)
2660 if ((i = tls_write(FALSE, buf + nbytes, rc - nbytes, FALSE)) < 0)
2663 else if (fd_bits & 2)
2664 FD_SET(proxy_fd, &rfds);
2670 /*************************************************
2671 * Deliver address list to given host *
2672 *************************************************/
2674 /* If continue_hostname is not null, we get here only when continuing to
2675 deliver down an existing channel. The channel was passed as the standard
2676 input. TLS is never active on a passed channel; the previous process always
2677 closes it down before passing the connection on.
2679 Otherwise, we have to make a connection to the remote host, and do the
2680 initial protocol exchange.
2682 When running as an MUA wrapper, if the sender or any recipient is rejected,
2683 temporarily or permanently, we force failure for all recipients.
2686 addrlist chain of potential addresses to deliver; only those whose
2687 transport_return field is set to PENDING_DEFER are currently
2688 being processed; others should be skipped - they have either
2689 been delivered to an earlier host or IP address, or been
2690 failed by one of them.
2691 host host to deliver to
2692 host_af AF_INET or AF_INET6
2693 defport default TCP/IP port to use if host does not specify, in host
2695 interface interface to bind to, or NULL
2696 tblock transport instance block
2697 message_defer set TRUE if yield is OK, but all addresses were deferred
2698 because of a non-recipient, non-host failure, that is, a
2699 4xx response to MAIL FROM, DATA, or ".". This is a defer
2700 that is specific to the message.
2701 suppress_tls if TRUE, don't attempt a TLS connection - this is set for
2702 a second attempt after TLS initialization fails
2704 Returns: OK - the connection was made and the delivery attempted;
2705 the result for each address is in its data block.
2706 DEFER - the connection could not be made, or something failed
2707 while setting up the SMTP session, or there was a
2708 non-message-specific error, such as a timeout.
2709 ERROR - a filter command is specified for this transport,
2710 and there was a problem setting it up; OR helo_data
2711 or add_headers or authenticated_sender is specified
2712 for this transport, and the string failed to expand
2716 smtp_deliver(address_item *addrlist, host_item *host, int host_af, int defport,
2717 uschar *interface, transport_instance *tblock,
2718 BOOL *message_defer, BOOL suppress_tls)
2724 struct timeval start_delivery_time;
2726 BOOL pass_message = FALSE;
2727 uschar *message = NULL;
2728 uschar new_message_id[MESSAGE_ID_LENGTH + 1];
2732 gettimeofday(&start_delivery_time, NULL);
2733 suppress_tls = suppress_tls; /* stop compiler warning when no TLS support */
2734 *message_defer = FALSE;
2736 sx.addrlist = addrlist;
2738 sx.host_af = host_af,
2740 sx.interface = interface;
2741 sx.helo_data = NULL;
2745 /* Get the channel set up ready for a message (MAIL FROM being the next
2746 SMTP command to send */
2748 if ((rc = smtp_setup_conn(&sx, suppress_tls)) != OK)
2751 /* If there is a filter command specified for this transport, we can now
2752 set it up. This cannot be done until the identify of the host is known. */
2754 if (tblock->filter_command)
2756 transport_filter_timeout = tblock->filter_timeout;
2758 /* On failure, copy the error to all addresses, abandon the SMTP call, and
2761 if (!transport_set_up_command(&transport_filter_argv,
2762 tblock->filter_command, TRUE, DEFER, addrlist,
2763 string_sprintf("%.50s transport", tblock->name), NULL))
2765 set_errno_nohost(addrlist->next, addrlist->basic_errno, addrlist->message, DEFER,
2771 if ( transport_filter_argv
2772 && *transport_filter_argv
2773 && **transport_filter_argv
2774 && sx.peer_offered & OPTION_CHUNKING
2777 sx.peer_offered &= ~OPTION_CHUNKING;
2778 DEBUG(D_transport) debug_printf("CHUNKING not usable due to transport filter\n");
2782 sx.first_addr = addrlist;
2784 /* For messages that have more than the maximum number of envelope recipients,
2785 we want to send several transactions down the same SMTP connection. (See
2786 comments in deliver.c as to how this reconciles, heuristically, with
2787 remote_max_parallel.) This optimization was added to Exim after the following
2788 code was already working. The simplest way to put it in without disturbing the
2789 code was to use a goto to jump back to this point when there is another
2790 transaction to handle. */
2793 sx.from_addr = return_path;
2794 sx.sync_addr = sx.first_addr;
2796 sx.send_rset = TRUE;
2797 sx.completed_addr = FALSE;
2800 /* If we are a continued-connection-after-verify the MAIL and RCPT
2801 commands were already sent; do not re-send but do mark the addrs as
2802 having been accepted up to RCPT stage. A traditional cont-conn
2803 always has a sequence number greater than one. */
2805 if (continue_hostname && continue_sequence == 1)
2807 address_item * addr;
2809 sx.peer_offered = smtp_peer_options;
2810 sx.pending_MAIL = FALSE;
2812 sx.next_addr = NULL;
2814 for (addr = addrlist; addr; addr = addr->next)
2815 addr->transport_return = PENDING_OK;
2819 /* Initiate a message transfer. */
2821 switch(smtp_write_mail_and_rcpt_cmds(&sx, &yield))
2824 case -1: case -2: goto RESPONSE_FAILED;
2825 case -3: goto END_OFF;
2826 case -4: goto SEND_QUIT;
2827 default: goto SEND_FAILED;
2830 /* If we are an MUA wrapper, abort if any RCPTs were rejected, either
2831 permanently or temporarily. We should have flushed and synced after the last
2839 for (a = sx.first_addr, cnt = 0; a && cnt < sx.max_rcpt; a = a->next, cnt++)
2840 if (a->transport_return != PENDING_OK)
2842 /*XXX could we find a better errno than 0 here? */
2843 set_errno_nohost(addrlist, 0, a->message, FAIL,
2844 testflag(a, af_pass_message));
2851 /* If ok is TRUE, we know we have got at least one good recipient, and must now
2852 send DATA, but if it is FALSE (in the normal, non-wrapper case), we may still
2853 have a good recipient buffered up if we are pipelining. We don't want to waste
2854 time sending DATA needlessly, so we only send it if either ok is TRUE or if we
2855 are pipelining. The responses are all handled by sync_responses().
2856 If using CHUNKING, do not send a BDAT until we know how big a chunk we want
2859 if ( !(sx.peer_offered & OPTION_CHUNKING)
2860 && (sx.ok || (pipelining_active && !mua_wrapper)))
2862 int count = smtp_write_command(&sx.outblock, SCMD_FLUSH, "DATA\r\n");
2864 if (count < 0) goto SEND_FAILED;
2865 switch(sync_responses(&sx, count, sx.ok ? +1 : -1))
2867 case 3: sx.ok = TRUE; /* 2xx & 5xx => OK & progress made */
2868 case 2: sx.completed_addr = TRUE; /* 5xx (only) => progress made */
2871 case 1: sx.ok = TRUE; /* 2xx (only) => OK, but if LMTP, */
2872 if (!sx.lmtp) sx.completed_addr = TRUE; /* can't tell about progress yet */
2873 case 0: break; /* No 2xx or 5xx, but no probs */
2875 case -1: goto END_OFF; /* Timeout on RCPT */
2876 default: goto RESPONSE_FAILED; /* I/O error, or any MAIL/DATA error */
2878 pipelining_active = FALSE;
2879 data_command = string_copy(big_buffer); /* Save for later error message */
2882 /* If there were no good recipients (but otherwise there have been no
2883 problems), just set ok TRUE, since we have handled address-specific errors
2884 already. Otherwise, it's OK to send the message. Use the check/escape mechanism
2885 for handling the SMTP dot-handling protocol, flagging to apply to headers as
2886 well as body. Set the appropriate timeout value to be used for each chunk.
2887 (Haven't been able to make it work using select() for writing yet.) */
2889 if (!(sx.peer_offered & OPTION_CHUNKING) && !sx.ok)
2891 /* Save the first address of the next batch. */
2892 sx.first_addr = sx.next_addr;
2898 transport_ctx tctx = {
2902 US".", US"..", /* Escaping strings */
2903 topt_use_crlf | topt_escape_headers
2904 | (tblock->body_only ? topt_no_headers : 0)
2905 | (tblock->headers_only ? topt_no_body : 0)
2906 | (tblock->return_path_add ? topt_add_return_path : 0)
2907 | (tblock->delivery_date_add ? topt_add_delivery_date : 0)
2908 | (tblock->envelope_to_add ? topt_add_envelope_to : 0)
2911 /* If using CHUNKING we need a callback from the generic transport
2912 support to us, for the sending of BDAT smtp commands and the reaping
2913 of responses. The callback needs a whole bunch of state so set up
2914 a transport-context structure to be passed around. */
2916 if (sx.peer_offered & OPTION_CHUNKING)
2918 tctx.check_string = tctx.escape_string = NULL;
2919 tctx.options |= topt_use_bdat;
2920 tctx.chunk_cb = smtp_chunk_cmd_callback;
2921 sx.pending_BDAT = FALSE;
2922 sx.good_RCPT = sx.ok;
2924 tctx.smtp_context = &sx;
2927 tctx.options |= topt_end_dot;
2929 /* Save the first address of the next batch. */
2930 sx.first_addr = sx.next_addr;
2932 /* Responses from CHUNKING commands go in buffer. Otherwise,
2933 there has not been a response. */
2937 sigalrm_seen = FALSE;
2938 transport_write_timeout = sx.ob->data_timeout;
2939 smtp_command = US"sending data block"; /* For error messages */
2940 DEBUG(D_transport|D_v)
2941 if (sx.peer_offered & OPTION_CHUNKING)
2942 debug_printf(" will write message using CHUNKING\n");
2944 debug_printf(" SMTP>> writing message and terminating \".\"\n");
2945 transport_count = 0;
2947 #ifndef DISABLE_DKIM
2948 sx.ok = dkim_transport_write_message(&tctx, &sx.ob->dkim, CUSS &message);
2950 sx.ok = transport_write_message(&tctx, 0);
2953 /* transport_write_message() uses write() because it is called from other
2954 places to write to non-sockets. This means that under some OS (e.g. Solaris)
2955 it can exit with "Broken pipe" as its error. This really means that the
2956 socket got closed at the far end. */
2958 transport_write_timeout = 0; /* for subsequent transports */
2960 /* Failure can either be some kind of I/O disaster (including timeout),
2961 or the failure of a transport filter or the expansion of added headers.
2962 Or, when CHUNKING, it can be a protocol-detected failure. */
2965 if (message) goto SEND_FAILED;
2966 else goto RESPONSE_FAILED;
2968 /* We used to send the terminating "." explicitly here, but because of
2969 buffering effects at both ends of TCP/IP connections, you don't gain
2970 anything by keeping it separate, so it might as well go in the final
2971 data buffer for efficiency. This is now done by setting the topt_end_dot
2974 smtp_command = US"end of data";
2976 if (sx.peer_offered & OPTION_CHUNKING && sx.cmd_count > 1)
2978 /* Reap any outstanding MAIL & RCPT commands, but not a DATA-go-ahead */
2979 switch(sync_responses(&sx, sx.cmd_count-1, 0))
2981 case 3: sx.ok = TRUE; /* 2xx & 5xx => OK & progress made */
2982 case 2: sx.completed_addr = TRUE; /* 5xx (only) => progress made */
2985 case 1: sx.ok = TRUE; /* 2xx (only) => OK, but if LMTP, */
2986 if (!sx.lmtp) sx.completed_addr = TRUE; /* can't tell about progress yet */
2987 case 0: break; /* No 2xx or 5xx, but no probs */
2989 case -1: goto END_OFF; /* Timeout on RCPT */
2990 default: goto RESPONSE_FAILED; /* I/O error, or any MAIL/DATA error */
2994 #ifndef DISABLE_PRDR
2995 /* For PRDR we optionally get a partial-responses warning
2996 * followed by the individual responses, before going on with
2997 * the overall response. If we don't get the warning then deal
2998 * with per non-PRDR. */
3001 sx.ok = smtp_read_response(&sx.inblock, sx.buffer, sizeof(sx.buffer), '3',
3002 sx.ob->final_timeout);
3003 if (!sx.ok && errno == 0) switch(sx.buffer[0])
3005 case '2': sx.prdr_active = FALSE;
3008 case '4': errno = ERRNO_DATA4XX;
3009 addrlist->more_errno |=
3010 ((sx.buffer[1] - '0')*10 + sx.buffer[2] - '0') << 8;
3017 /* For non-PRDR SMTP, we now read a single response that applies to the
3018 whole message. If it is OK, then all the addresses have been delivered. */
3022 sx.ok = smtp_read_response(&sx.inblock, sx.buffer, sizeof(sx.buffer), '2',
3023 sx.ob->final_timeout);
3024 if (!sx.ok && errno == 0 && sx.buffer[0] == '4')
3026 errno = ERRNO_DATA4XX;
3027 addrlist->more_errno |= ((sx.buffer[1] - '0')*10 + sx.buffer[2] - '0') << 8;
3031 /* For LMTP, we get back a response for every RCPT command that we sent;
3032 some may be accepted and some rejected. For those that get a response, their
3033 status is fixed; any that are accepted have been handed over, even if later
3034 responses crash - at least, that's how I read RFC 2033.
3036 If all went well, mark the recipient addresses as completed, record which
3037 host/IPaddress they were delivered to, and cut out RSET when sending another
3038 message down the same channel. Write the completed addresses to the journal
3039 now so that they are recorded in case there is a crash of hardware or
3040 software before the spool gets updated. Also record the final SMTP
3041 confirmation if needed (for SMTP only). */
3046 struct timeval delivery_time;
3048 uschar * conf = NULL;
3050 timesince(&delivery_time, &start_delivery_time);
3051 sx.send_rset = FALSE;
3052 pipelining_active = FALSE;
3054 /* Set up confirmation if needed - applies only to SMTP */
3057 #ifdef DISABLE_EVENT
3058 LOGGING(smtp_confirmation) &&
3063 const uschar *s = string_printing(sx.buffer);
3064 /* deconst cast ok here as string_printing was checked to have alloc'n'copied */
3065 conf = (s == sx.buffer)? US string_copy(s) : US s;
3068 /* Process all transported addresses - for LMTP or PRDR, read a status for
3071 for (addr = addrlist; addr != sx.first_addr; addr = addr->next)
3073 if (addr->transport_return != PENDING_OK) continue;
3075 /* LMTP - if the response fails badly (e.g. timeout), use it for all the
3076 remaining addresses. Otherwise, it's a return code for just the one
3077 address. For temporary errors, add a retry item for the address so that
3078 it doesn't get tried again too soon. */
3080 #ifndef DISABLE_PRDR
3081 if (sx.lmtp || sx.prdr_active)
3086 if (!smtp_read_response(&sx.inblock, sx.buffer, sizeof(sx.buffer), '2',
3087 sx.ob->final_timeout))
3089 if (errno != 0 || sx.buffer[0] == 0) goto RESPONSE_FAILED;
3090 addr->message = string_sprintf(
3091 #ifndef DISABLE_PRDR
3092 "%s error after %s: %s", sx.prdr_active ? "PRDR":"LMTP",
3094 "LMTP error after %s: %s",
3096 data_command, string_printing(sx.buffer));
3097 setflag(addr, af_pass_message); /* Allow message to go to user */
3098 if (sx.buffer[0] == '5')
3099 addr->transport_return = FAIL;
3102 errno = ERRNO_DATA4XX;
3103 addr->more_errno |= ((sx.buffer[1] - '0')*10 + sx.buffer[2] - '0') << 8;
3104 addr->transport_return = DEFER;
3105 #ifndef DISABLE_PRDR
3106 if (!sx.prdr_active)
3108 retry_add_item(addr, addr->address_retry_key, 0);
3112 sx.completed_addr = TRUE; /* NOW we can set this flag */
3113 if (LOGGING(smtp_confirmation))
3115 const uschar *s = string_printing(sx.buffer);
3116 /* deconst cast ok here as string_printing was checked to have alloc'n'copied */
3117 conf = (s == sx.buffer) ? US string_copy(s) : US s;
3121 /* SMTP, or success return from LMTP for this address. Pass back the
3122 actual host that was used. */
3124 addr->transport_return = OK;
3125 addr->more_errno = delivery_time.tv_sec;
3126 addr->delivery_usec = delivery_time.tv_usec;
3127 addr->host_used = host;
3128 addr->special_action = flag;
3129 addr->message = conf;
3130 #ifndef DISABLE_PRDR
3131 if (sx.prdr_active) setflag(addr, af_prdr_used);
3133 if (sx.peer_offered & OPTION_CHUNKING) setflag(addr, af_chunking_used);
3136 #ifndef DISABLE_PRDR
3137 if (!sx.prdr_active)
3140 /* Update the journal. For homonymic addresses, use the base address plus
3141 the transport name. See lots of comments in deliver.c about the reasons
3142 for the complications when homonyms are involved. Just carry on after
3143 write error, as it may prove possible to update the spool file later. */
3145 if (testflag(addr, af_homonym))
3146 sprintf(CS sx.buffer, "%.500s/%s\n", addr->unique + 3, tblock->name);
3148 sprintf(CS sx.buffer, "%.500s\n", addr->unique);
3150 DEBUG(D_deliver) debug_printf("S:journalling %s\n", sx.buffer);
3151 len = Ustrlen(CS sx.buffer);
3152 if (write(journal_fd, sx.buffer, len) != len)
3153 log_write(0, LOG_MAIN|LOG_PANIC, "failed to write journal for "
3154 "%s: %s", sx.buffer, strerror(errno));
3158 #ifndef DISABLE_PRDR
3161 /* PRDR - get the final, overall response. For any non-success
3162 upgrade all the address statuses. */
3163 sx.ok = smtp_read_response(&sx.inblock, sx.buffer, sizeof(sx.buffer), '2',
3164 sx.ob->final_timeout);
3167 if(errno == 0 && sx.buffer[0] == '4')
3169 errno = ERRNO_DATA4XX;
3170 addrlist->more_errno |= ((sx.buffer[1] - '0')*10 + sx.buffer[2] - '0') << 8;
3172 for (addr = addrlist; addr != sx.first_addr; addr = addr->next)
3173 if (sx.buffer[0] == '5' || addr->transport_return == OK)
3174 addr->transport_return = PENDING_OK; /* allow set_errno action */
3175 goto RESPONSE_FAILED;
3178 /* Update the journal, or setup retry. */
3179 for (addr = addrlist; addr != sx.first_addr; addr = addr->next)
3180 if (addr->transport_return == OK)
3182 if (testflag(addr, af_homonym))
3183 sprintf(CS sx.buffer, "%.500s/%s\n", addr->unique + 3, tblock->name);
3185 sprintf(CS sx.buffer, "%.500s\n", addr->unique);
3187 DEBUG(D_deliver) debug_printf("journalling(PRDR) %s\n", sx.buffer);
3188 len = Ustrlen(CS sx.buffer);
3189 if (write(journal_fd, sx.buffer, len) != len)
3190 log_write(0, LOG_MAIN|LOG_PANIC, "failed to write journal for "
3191 "%s: %s", sx.buffer, strerror(errno));
3193 else if (addr->transport_return == DEFER)
3194 retry_add_item(addr, addr->address_retry_key, -2);
3198 /* Ensure the journal file is pushed out to disk. */
3200 if (EXIMfsync(journal_fd) < 0)
3201 log_write(0, LOG_MAIN|LOG_PANIC, "failed to fsync journal: %s",
3207 /* Handle general (not specific to one address) failures here. The value of ok
3208 is used to skip over this code on the falling through case. A timeout causes a
3209 deferral. Other errors may defer or fail according to the response code, and
3210 may set up a special errno value, e.g. after connection chopped, which is
3211 assumed if errno == 0 and there is no text in the buffer. If control reaches
3212 here during the setting up phase (i.e. before MAIL FROM) then always defer, as
3213 the problem is not related to this specific message. */
3218 uschar * set_message;
3224 sx.send_quit = check_response(host, &save_errno, addrlist->more_errno,
3225 sx.buffer, &code, &message, &pass_message);
3233 message = string_sprintf("send() to %s [%s] failed: %s",
3234 host->name, host->address, message ? message : US strerror(save_errno));
3235 sx.send_quit = FALSE;
3243 sx.ok = FALSE; /* For when reached by GOTO */
3244 set_message = message;
3246 /* We want to handle timeouts after MAIL or "." and loss of connection after
3247 "." specially. They can indicate a problem with the sender address or with
3248 the contents of the message rather than a real error on the connection. These
3249 cases are treated in the same way as a 4xx response. This next bit of code
3250 does the classification. */
3257 message_error = TRUE;
3261 message_error = Ustrncmp(smtp_command,"MAIL",4) == 0 ||
3262 Ustrncmp(smtp_command,"end ",4) == 0;
3265 case ERRNO_SMTPCLOSED:
3266 message_error = Ustrncmp(smtp_command,"end ",4) == 0;
3270 message_error = FALSE;
3274 /* Handle the cases that are treated as message errors. These are:
3276 (a) negative response or timeout after MAIL
3277 (b) negative response after DATA
3278 (c) negative response or timeout or dropped connection after "."
3279 (d) utf8 support required and not offered
3281 It won't be a negative response or timeout after RCPT, as that is dealt
3282 with separately above. The action in all cases is to set an appropriate
3283 error code for all the addresses, but to leave yield set to OK because the
3284 host itself has not failed. Of course, it might in practice have failed
3285 when we've had a timeout, but if so, we'll discover that at the next
3286 delivery attempt. For a temporary error, set the message_defer flag, and
3287 write to the logs for information if this is not the last host. The error
3288 for the last host will be logged as part of the address's log line. */
3292 if (mua_wrapper) code = '5'; /* Force hard failure in wrapper mode */
3294 /* If there's an errno, the message contains just the identity of
3299 else /* Anything other than 5 is treated as temporary */
3303 message = US string_sprintf("%s: %s", message, strerror(save_errno));
3304 if (host->next != NULL) log_write(0, LOG_MAIN, "%s", message);
3305 msglog_line(host, message);
3306 *message_defer = TRUE;
3310 /* Otherwise, we have an I/O error or a timeout other than after MAIL or
3311 ".", or some other transportation error. We defer all addresses and yield
3312 DEFER, except for the case of failed add_headers expansion, or a transport
3313 filter failure, when the yield should be ERROR, to stop it trying other
3319 yield = (save_errno == ERRNO_CHHEADER_FAIL ||
3320 save_errno == ERRNO_FILTER_FAIL)? ERROR : DEFER;
3324 set_errno(addrlist, save_errno, set_message, set_rc, pass_message, host
3325 #ifdef EXPERIMENTAL_DSN_INFO
3326 , sx.smtp_greeting, sx.helo_response
3332 /* If all has gone well, send_quit will be set TRUE, implying we can end the
3333 SMTP session tidily. However, if there were too many addresses to send in one
3334 message (indicated by first_addr being non-NULL) we want to carry on with the
3335 rest of them. Also, it is desirable to send more than one message down the SMTP
3336 connection if there are several waiting, provided we haven't already sent so
3337 many as to hit the configured limit. The function transport_check_waiting looks
3338 for a waiting message and returns its id. Then transport_pass_socket tries to
3339 set up a continued delivery by passing the socket on to another process. The
3340 variable send_rset is FALSE if a message has just been successfully transfered.
3342 If we are already sending down a continued channel, there may be further
3343 addresses not yet delivered that are aimed at the same host, but which have not
3344 been passed in this run of the transport. In this case, continue_more will be
3345 true, and all we should do is send RSET if necessary, and return, leaving the
3348 However, if no address was disposed of, i.e. all addresses got 4xx errors, we
3349 do not want to continue with other messages down the same channel, because that
3350 can lead to looping between two or more messages, all with the same,
3351 temporarily failing address(es). [The retry information isn't updated yet, so
3352 new processes keep on trying.] We probably also don't want to try more of this
3353 message's addresses either.
3355 If we have started a TLS session, we have to end it before passing the
3356 connection to a new process. However, not all servers can handle this (Exim
3357 can), so we do not pass such a connection on if the host matches
3358 hosts_nopass_tls. */
3361 debug_printf("ok=%d send_quit=%d send_rset=%d continue_more=%d "
3362 "yield=%d first_address is %sNULL\n", sx.ok, sx.send_quit,
3363 sx.send_rset, continue_more, yield, sx.first_addr ? "not " : "");
3365 if (sx.completed_addr && sx.ok && sx.send_quit)
3368 smtp_compare_t t_compare;
3370 t_compare.tblock = tblock;
3371 t_compare.current_sender_address = sender_address;
3373 if ( sx.first_addr != NULL
3377 ( tls_out.active < 0 && !continue_proxy_cipher
3378 || verify_check_given_host(&sx.ob->hosts_nopass_tls, host) != OK
3382 transport_check_waiting(tblock->name, host->name,
3383 tblock->connection_max_messages, new_message_id, &more,
3384 (oicf)smtp_are_same_identities, (void*)&t_compare)
3391 if (! (sx.ok = smtp_write_command(&sx.outblock, SCMD_FLUSH, "RSET\r\n") >= 0))
3393 msg = US string_sprintf("send() to %s [%s] failed: %s", host->name,
3394 host->address, strerror(errno));
3395 sx.send_quit = FALSE;
3397 else if (! (sx.ok = smtp_read_response(&sx.inblock, sx.buffer,
3398 sizeof(sx.buffer), '2', sx.ob->command_timeout)))
3401 sx.send_quit = check_response(host, &errno, 0, sx.buffer, &code, &msg,
3405 DEBUG(D_transport) debug_printf("H=%s [%s] %s\n",
3406 host->name, host->address, msg);
3410 /* Either RSET was not needed, or it succeeded */
3415 int socket_fd = sx.inblock.sock;
3418 if (sx.first_addr != NULL) /* More addresses still to be sent */
3419 { /* in this run of the transport */
3420 continue_sequence++; /* Causes * in logging */
3424 /* Unless caller said it already has more messages listed for this host,
3425 pass the connection on to a new Exim process (below, the call to
3426 transport_pass_socket). If the caller has more ready, just return with
3427 the connection still open. */
3430 if (tls_out.active >= 0)
3432 || verify_check_given_host(&sx.ob->hosts_noproxy_tls, host) == OK)
3434 /* Before passing the socket on, or returning to caller with it still
3435 open, we must shut down TLS. Not all MTAs allow for the continuation
3436 of the SMTP session when TLS is shut down. We test for this by sending
3437 a new EHLO. If we don't get a good response, we don't attempt to pass
3440 tls_close(FALSE, TRUE);
3441 smtp_peer_options = smtp_peer_options_wrap;
3443 && smtp_write_command(&sx.outblock, SCMD_FLUSH,
3444 "EHLO %s\r\n", sx.helo_data) >= 0
3445 && smtp_read_response(&sx.inblock, sx.buffer, sizeof(sx.buffer),
3446 '2', sx.ob->command_timeout);
3448 if (sx.ok && continue_more)
3449 return yield; /* More addresses for another run */
3453 /* Set up a pipe for proxying TLS for the new transport process */
3455 smtp_peer_options |= OPTION_TLS;
3456 if (sx.ok = (socketpair(AF_UNIX, SOCK_STREAM, 0, pfd) == 0))
3459 set_errno(sx.first_addr, errno, US"internal allocation problem",
3461 # ifdef EXPERIMENTAL_DSN_INFO
3462 , sx.smtp_greeting, sx.helo_response
3469 return yield; /* More addresses for another run */
3471 /* If the socket is successfully passed, we mustn't send QUIT (or
3472 indeed anything!) from here. */
3474 /*XXX DSN_INFO: assume likely to do new HELO; but for greet we'll want to
3475 propagate it from the initial
3477 if (sx.ok && transport_pass_socket(tblock->name, host->name,
3478 host->address, new_message_id, socket_fd))
3480 sx.send_quit = FALSE;
3482 /* If TLS is still active, we need to proxy it for the transport we
3483 just passed the baton to. Fork a child to to do it, and return to
3484 get logging done asap. Which way to place the work makes assumptions
3485 about post-fork prioritisation which may not hold on all platforms. */
3487 if (tls_out.active >= 0)
3490 if (pid > 0) /* parent */
3492 DEBUG(D_transport) debug_printf("proxy-proc inter-pid %d\n", pid);
3494 waitpid(pid, NULL, 0);
3495 tls_close(FALSE, FALSE);
3496 (void)close(sx.inblock.sock);
3497 continue_transport = NULL;
3498 continue_hostname = NULL;
3501 else if (pid == 0) /* child; fork again to disconnect totally */
3506 DEBUG(D_transport) debug_printf("proxy-prox final-pid %d\n", pid);
3507 _exit(pid ? EXIT_FAILURE : EXIT_SUCCESS);
3509 smtp_proxy_tls(sx.buffer, sizeof(sx.buffer), pfd[0], sx.ob->command_timeout);
3517 /* If RSET failed and there are addresses left, they get deferred. */
3519 set_errno(sx.first_addr, errno, msg, DEFER, FALSE, host
3520 #ifdef EXPERIMENTAL_DSN_INFO
3521 , sx.smtp_greeting, sx.helo_response
3527 /* End off tidily with QUIT unless the connection has died or the socket has
3528 been passed to another process. There has been discussion on the net about what
3529 to do after sending QUIT. The wording of the RFC suggests that it is necessary
3530 to wait for a response, but on the other hand, there isn't anything one can do
3531 with an error response, other than log it. Exim used to do that. However,
3532 further discussion suggested that it is positively advantageous not to wait for
3533 the response, but to close the session immediately. This is supposed to move
3534 the TCP/IP TIME_WAIT state from the server to the client, thereby removing some
3535 load from the server. (Hosts that are both servers and clients may not see much
3536 difference, of course.) Further discussion indicated that this was safe to do
3537 on Unix systems which have decent implementations of TCP/IP that leave the
3538 connection around for a while (TIME_WAIT) after the application has gone away.
3539 This enables the response sent by the server to be properly ACKed rather than
3540 timed out, as can happen on broken TCP/IP implementations on other OS.
3542 This change is being made on 31-Jul-98. After over a year of trouble-free
3543 operation, the old commented-out code was removed on 17-Sep-99. */
3546 if (sx.send_quit) (void)smtp_write_command(&sx.outblock, SCMD_FLUSH, "QUIT\r\n");
3551 tls_close(FALSE, TRUE);
3554 /* Close the socket, and return the appropriate value, first setting
3555 works because the NULL setting is passed back to the calling process, and
3556 remote_max_parallel is forced to 1 when delivering over an existing connection,
3558 If all went well and continue_more is set, we shouldn't actually get here if
3559 there are further addresses, as the return above will be taken. However,
3560 writing RSET might have failed, or there may be other addresses whose hosts are
3561 specified in the transports, and therefore not visible at top level, in which
3562 case continue_more won't get set. */
3564 HDEBUG(D_transport|D_acl|D_v) debug_printf_indent(" SMTP(close)>>\n");
3567 shutdown(sx.outblock.sock, SHUT_WR);
3568 if (fcntl(sx.inblock.sock, F_SETFL, O_NONBLOCK) == 0)
3569 for (rc = 16; read(sx.inblock.sock, sx.inbuffer, sizeof(sx.inbuffer)) > 0 && rc > 0;)
3570 rc--; /* drain socket */
3572 (void)close(sx.inblock.sock);
3574 #ifndef DISABLE_EVENT
3575 (void) event_raise(tblock->event_action, US"tcp:close", NULL);
3578 continue_transport = NULL;
3579 continue_hostname = NULL;
3586 /*************************************************
3587 * Closedown entry point *
3588 *************************************************/
3590 /* This function is called when exim is passed an open smtp channel
3591 from another incarnation, but the message which it has been asked
3592 to deliver no longer exists. The channel is on stdin.
3594 We might do fancy things like looking for another message to send down
3595 the channel, but if the one we sought has gone, it has probably been
3596 delivered by some other process that itself will seek further messages,
3597 so just close down our connection.
3599 Argument: pointer to the transport instance block
3604 smtp_transport_closedown(transport_instance *tblock)
3606 smtp_transport_options_block *ob =
3607 (smtp_transport_options_block *)tblock->options_block;
3608 smtp_inblock inblock;
3609 smtp_outblock outblock;
3611 uschar inbuffer[4096];
3612 uschar outbuffer[16];
3614 inblock.sock = fileno(stdin);
3615 inblock.buffer = inbuffer;
3616 inblock.buffersize = sizeof(inbuffer);
3617 inblock.ptr = inbuffer;
3618 inblock.ptrend = inbuffer;
3620 outblock.sock = inblock.sock;
3621 outblock.buffersize = sizeof(outbuffer);
3622 outblock.buffer = outbuffer;
3623 outblock.ptr = outbuffer;
3624 outblock.cmd_count = 0;
3625 outblock.authenticating = FALSE;
3627 (void)smtp_write_command(&outblock, SCMD_FLUSH, "QUIT\r\n");
3628 (void)smtp_read_response(&inblock, buffer, sizeof(buffer), '2',
3629 ob->command_timeout);
3630 (void)close(inblock.sock);
3635 /*************************************************
3636 * Prepare addresses for delivery *
3637 *************************************************/
3639 /* This function is called to flush out error settings from previous delivery
3640 attempts to other hosts. It also records whether we got here via an MX record
3641 or not in the more_errno field of the address. We are interested only in
3642 addresses that are still marked DEFER - others may have got delivered to a
3643 previously considered IP address. Set their status to PENDING_DEFER to indicate
3644 which ones are relevant this time.
3647 addrlist the list of addresses
3648 host the host we are delivering to
3650 Returns: the first address for this delivery
3653 static address_item *
3654 prepare_addresses(address_item *addrlist, host_item *host)
3656 address_item *first_addr = NULL;
3658 for (addr = addrlist; addr; addr = addr->next)
3659 if (addr->transport_return == DEFER)
3661 if (!first_addr) first_addr = addr;
3662 addr->transport_return = PENDING_DEFER;
3663 addr->basic_errno = 0;
3664 addr->more_errno = (host->mx >= 0)? 'M' : 'A';
3665 addr->message = NULL;
3667 addr->cipher = NULL;
3668 addr->ourcert = NULL;
3669 addr->peercert = NULL;
3670 addr->peerdn = NULL;
3671 addr->ocsp = OCSP_NOT_REQ;
3673 #ifdef EXPERIMENTAL_DSN_INFO
3674 addr->smtp_greeting = NULL;
3675 addr->helo_response = NULL;
3683 /*************************************************
3684 * Main entry point *
3685 *************************************************/
3687 /* See local README for interface details. As this is a remote transport, it is
3688 given a chain of addresses to be delivered in one connection, if possible. It
3689 always returns TRUE, indicating that each address has its own independent
3690 status set, except if there is a setting up problem, in which case it returns
3694 smtp_transport_entry(
3695 transport_instance *tblock, /* data for this instantiation */
3696 address_item *addrlist) /* addresses we are working on */
3700 int hosts_defer = 0;
3702 int hosts_looked_up = 0;
3703 int hosts_retry = 0;
3704 int hosts_serial = 0;
3705 int hosts_total = 0;
3706 int total_hosts_tried = 0;
3708 BOOL expired = TRUE;
3709 uschar *expanded_hosts = NULL;
3711 uschar *tid = string_sprintf("%s transport", tblock->name);
3712 smtp_transport_options_block *ob =
3713 (smtp_transport_options_block *)(tblock->options_block);
3714 host_item *hostlist = addrlist->host_list;
3715 host_item *host = NULL;
3719 debug_printf("%s transport entered\n", tblock->name);
3720 for (addr = addrlist; addr; addr = addr->next)
3721 debug_printf(" %s\n", addr->address);
3724 debug_printf("hostlist:\n");
3725 for (host = hostlist; host; host = host->next)
3726 debug_printf(" %s:%d\n", host->name, host->port);
3728 if (continue_hostname)
3729 debug_printf("already connected to %s [%s] (on fd %d)\n",
3730 continue_hostname, continue_host_address,
3731 cutthrough.fd >= 0 ? cutthrough.fd : 0);
3734 /* Set the flag requesting that these hosts be added to the waiting
3735 database if the delivery fails temporarily or if we are running with
3736 queue_smtp or a 2-stage queue run. This gets unset for certain
3737 kinds of error, typically those that are specific to the message. */
3739 update_waiting = TRUE;
3741 /* If a host list is not defined for the addresses - they must all have the
3742 same one in order to be passed to a single transport - or if the transport has
3743 a host list with hosts_override set, use the host list supplied with the
3744 transport. It is an error for this not to exist. */
3746 if (!hostlist || (ob->hosts_override && ob->hosts))
3750 addrlist->message = string_sprintf("%s transport called with no hosts set",
3752 addrlist->transport_return = PANIC;
3753 return FALSE; /* Only top address has status */
3756 DEBUG(D_transport) debug_printf("using the transport's hosts: %s\n",
3759 /* If the transport's host list contains no '$' characters, and we are not
3760 randomizing, it is fixed and therefore a chain of hosts can be built once
3761 and for all, and remembered for subsequent use by other calls to this
3762 transport. If, on the other hand, the host list does contain '$', or we are
3763 randomizing its order, we have to rebuild it each time. In the fixed case,
3764 as the hosts string will never be used again, it doesn't matter that we
3765 replace all the : characters with zeros. */
3769 uschar *s = ob->hosts;
3771 if (Ustrchr(s, '$') != NULL)
3773 if (!(expanded_hosts = expand_string(s)))
3775 addrlist->message = string_sprintf("failed to expand list of hosts "
3776 "\"%s\" in %s transport: %s", s, tblock->name, expand_string_message);
3777 addrlist->transport_return = search_find_defer ? DEFER : PANIC;
3778 return FALSE; /* Only top address has status */
3780 DEBUG(D_transport) debug_printf("expanded list of hosts \"%s\" to "
3781 "\"%s\"\n", s, expanded_hosts);
3785 if (ob->hosts_randomize) s = expanded_hosts = string_copy(s);
3787 host_build_hostlist(&hostlist, s, ob->hosts_randomize);
3789 /* Check that the expansion yielded something useful. */
3793 string_sprintf("%s transport has empty hosts setting", tblock->name);
3794 addrlist->transport_return = PANIC;
3795 return FALSE; /* Only top address has status */
3798 /* If there was no expansion of hosts, save the host list for
3801 if (!expanded_hosts) ob->hostlist = hostlist;
3804 /* This is not the first time this transport has been run in this delivery;
3805 the host list was built previously. */
3808 hostlist = ob->hostlist;
3811 /* The host list was supplied with the address. If hosts_randomize is set, we
3812 must sort it into a random order if it did not come from MX records and has not
3813 already been randomized (but don't bother if continuing down an existing
3816 else if (ob->hosts_randomize && hostlist->mx == MX_NONE && !continue_hostname)
3818 host_item *newlist = NULL;
3821 host_item *h = hostlist;
3822 hostlist = hostlist->next;
3824 h->sort_key = random_number(100);
3831 else if (h->sort_key < newlist->sort_key)
3838 host_item *hh = newlist;
3841 if (h->sort_key < hh->next->sort_key) break;
3849 hostlist = addrlist->host_list = newlist;
3852 /* Sort out the default port. */
3854 if (!smtp_get_port(ob->port, addrlist, &defport, tid)) return FALSE;
3856 /* For each host-plus-IP-address on the list:
3858 . If this is a continued delivery and the host isn't the one with the
3859 current connection, skip.
3861 . If the status is unusable (i.e. previously failed or retry checked), skip.
3863 . If no IP address set, get the address, either by turning the name into
3864 an address, calling gethostbyname if gethostbyname is on, or by calling
3865 the DNS. The DNS may yield multiple addresses, in which case insert the
3866 extra ones into the list.
3868 . Get the retry data if not previously obtained for this address and set the
3869 field which remembers the state of this address. Skip if the retry time is
3870 not reached. If not, remember whether retry data was found. The retry string
3871 contains both the name and the IP address.
3873 . Scan the list of addresses and mark those whose status is DEFER as
3874 PENDING_DEFER. These are the only ones that will be processed in this cycle
3877 . Make a delivery attempt - addresses marked PENDING_DEFER will be tried.
3878 Some addresses may be successfully delivered, others may fail, and yet
3879 others may get temporary errors and so get marked DEFER.
3881 . The return from the delivery attempt is OK if a connection was made and a
3882 valid SMTP dialogue was completed. Otherwise it is DEFER.
3884 . If OK, add a "remove" retry item for this host/IPaddress, if any.
3886 . If fail to connect, or other defer state, add a retry item.
3888 . If there are any addresses whose status is still DEFER, carry on to the
3889 next host/IPaddress, unless we have tried the number of hosts given
3890 by hosts_max_try or hosts_max_try_hardlimit; otherwise return. Note that
3891 there is some fancy logic for hosts_max_try that means its limit can be
3892 overstepped in some circumstances.
3894 If we get to the end of the list, all hosts have deferred at least one address,
3895 or not reached their retry times. If delay_after_cutoff is unset, it requests a
3896 delivery attempt to those hosts whose last try was before the arrival time of
3897 the current message. To cope with this, we have to go round the loop a second
3898 time. After that, set the status and error data for any addresses that haven't
3899 had it set already. */
3901 for (cutoff_retry = 0;
3902 expired && cutoff_retry < (ob->delay_after_cutoff ? 1 : 2);
3905 host_item *nexthost = NULL;
3906 int unexpired_hosts_tried = 0;
3908 for (host = hostlist;
3910 && unexpired_hosts_tried < ob->hosts_max_try
3911 && total_hosts_tried < ob->hosts_max_try_hardlimit;
3917 BOOL host_is_expired = FALSE;
3918 BOOL message_defer = FALSE;
3919 BOOL some_deferred = FALSE;
3920 address_item *first_addr = NULL;
3921 uschar *interface = NULL;
3922 uschar *retry_host_key = NULL;
3923 uschar *retry_message_key = NULL;
3924 uschar *serialize_key = NULL;
3926 /* Default next host is next host. :-) But this can vary if the
3927 hosts_max_try limit is hit (see below). It may also be reset if a host
3928 address is looked up here (in case the host was multihomed). */
3930 nexthost = host->next;
3932 /* If the address hasn't yet been obtained from the host name, look it up
3933 now, unless the host is already marked as unusable. If it is marked as
3934 unusable, it means that the router was unable to find its IP address (in
3935 the DNS or wherever) OR we are in the 2nd time round the cutoff loop, and
3936 the lookup failed last time. We don't get this far if *all* MX records
3937 point to non-existent hosts; that is treated as a hard error.
3939 We can just skip this host entirely. When the hosts came from the router,
3940 the address will timeout based on the other host(s); when the address is
3941 looked up below, there is an explicit retry record added.
3943 Note that we mustn't skip unusable hosts if the address is not unset; they
3944 may be needed as expired hosts on the 2nd time round the cutoff loop. */
3948 int new_port, flags;
3951 if (host->status >= hstatus_unusable)
3953 DEBUG(D_transport) debug_printf("%s has no address and is unusable - skipping\n",
3958 DEBUG(D_transport) debug_printf("getting address for %s\n", host->name);
3960 /* The host name is permitted to have an attached port. Find it, and
3961 strip it from the name. Just remember it for now. */
3963 new_port = host_item_get_port(host);
3965 /* Count hosts looked up */
3969 /* Find by name if so configured, or if it's an IP address. We don't
3970 just copy the IP address, because we need the test-for-local to happen. */
3972 flags = HOST_FIND_BY_A;
3973 if (ob->dns_qualify_single) flags |= HOST_FIND_QUALIFY_SINGLE;
3974 if (ob->dns_search_parents) flags |= HOST_FIND_SEARCH_PARENTS;
3976 if (ob->gethostbyname || string_is_ip_address(host->name, NULL) != 0)
3977 rc = host_find_byname(host, NULL, flags, NULL, TRUE);
3979 rc = host_find_bydns(host, NULL, flags, NULL, NULL, NULL,
3980 &ob->dnssec, /* domains for request/require */
3983 /* Update the host (and any additional blocks, resulting from
3984 multihoming) with a host-specific port, if any. */
3986 for (hh = host; hh != nexthost; hh = hh->next) hh->port = new_port;
3988 /* Failure to find the host at this time (usually DNS temporary failure)
3989 is really a kind of routing failure rather than a transport failure.
3990 Therefore we add a retry item of the routing kind, not to stop us trying
3991 to look this name up here again, but to ensure the address gets timed
3992 out if the failures go on long enough. A complete failure at this point
3993 commonly points to a configuration error, but the best action is still
3994 to carry on for the next host. */
3996 if (rc == HOST_FIND_AGAIN || rc == HOST_FIND_SECURITY || rc == HOST_FIND_FAILED)
3998 retry_add_item(addrlist, string_sprintf("R:%s", host->name), 0);
4000 if (rc == HOST_FIND_AGAIN) hosts_defer++; else hosts_fail++;
4001 DEBUG(D_transport) debug_printf("rc = %s for %s\n", (rc == HOST_FIND_AGAIN)?
4002 "HOST_FIND_AGAIN" : "HOST_FIND_FAILED", host->name);
4003 host->status = hstatus_unusable;
4005 for (addr = addrlist; addr; addr = addr->next)
4007 if (addr->transport_return != DEFER) continue;
4008 addr->basic_errno = ERRNO_UNKNOWNHOST;
4009 addr->message = string_sprintf(
4010 rc == HOST_FIND_SECURITY
4011 ? "lookup of IP address for %s was insecure"
4012 : "failed to lookup IP address for %s",
4018 /* If the host is actually the local host, we may have a problem, or
4019 there may be some cunning configuration going on. In the problem case,
4020 log things and give up. The default transport status is already DEFER. */
4022 if (rc == HOST_FOUND_LOCAL && !ob->allow_localhost)
4024 for (addr = addrlist; addr; addr = addr->next)
4026 addr->basic_errno = 0;
4027 addr->message = string_sprintf("%s transport found host %s to be "
4028 "local", tblock->name, host->name);
4032 } /* End of block for IP address lookup */
4034 /* If this is a continued delivery, we are interested only in the host
4035 which matches the name of the existing open channel. The check is put
4036 here after the local host lookup, in case the name gets expanded as a
4037 result of the lookup. Set expired FALSE, to save the outer loop executing
4040 if ( continue_hostname
4041 && ( Ustrcmp(continue_hostname, host->name) != 0
4042 || Ustrcmp(continue_host_address, host->address) != 0
4046 continue; /* With next host */
4049 /* Reset the default next host in case a multihomed host whose addresses
4050 are not looked up till just above added to the host list. */
4052 nexthost = host->next;
4054 /* If queue_smtp is set (-odqs or the first part of a 2-stage run), or the
4055 domain is in queue_smtp_domains, we don't actually want to attempt any
4056 deliveries. When doing a queue run, queue_smtp_domains is always unset. If
4057 there is a lookup defer in queue_smtp_domains, proceed as if the domain
4058 were not in it. We don't want to hold up all SMTP deliveries! Except when
4059 doing a two-stage queue run, don't do this if forcing. */
4061 if ((!deliver_force || queue_2stage) && (queue_smtp ||
4062 match_isinlist(addrlist->domain,
4063 (const uschar **)&queue_smtp_domains, 0,
4064 &domainlist_anchor, NULL, MCL_DOMAIN, TRUE, NULL) == OK))
4067 for (addr = addrlist; addr; addr = addr->next)
4068 if (addr->transport_return == DEFER)
4069 addr->message = US"domain matches queue_smtp_domains, or -odqs set";
4070 continue; /* With next host */
4073 /* Count hosts being considered - purely for an intelligent comment
4074 if none are usable. */
4078 /* Set $host and $host address now in case they are needed for the
4079 interface expansion or the serialize_hosts check; they remain set if an
4080 actual delivery happens. */
4082 deliver_host = host->name;
4083 deliver_host_address = host->address;
4084 lookup_dnssec_authenticated = host->dnssec == DS_YES ? US"yes"
4085 : host->dnssec == DS_NO ? US"no"
4088 /* Set up a string for adding to the retry key if the port number is not
4089 the standard SMTP port. A host may have its own port setting that overrides
4092 pistring = string_sprintf(":%d", host->port == PORT_NONE
4093 ? defport : host->port);
4094 if (Ustrcmp(pistring, ":25") == 0) pistring = US"";
4096 /* Select IPv4 or IPv6, and choose an outgoing interface. If the interface
4097 string is set, even if constant (as different transports can have different
4098 constant settings), we must add it to the key that is used for retries,
4099 because connections to the same host from a different interface should be
4100 treated separately. */
4102 host_af = Ustrchr(host->address, ':') == NULL ? AF_INET : AF_INET6;
4103 if ((rs = ob->interface) && *rs)
4105 if (!smtp_get_interface(rs, host_af, addrlist, &interface, tid))
4107 pistring = string_sprintf("%s/%s", pistring, interface);
4110 /* The first time round the outer loop, check the status of the host by
4111 inspecting the retry data. The second time round, we are interested only
4112 in expired hosts that haven't been tried since this message arrived. */
4114 if (cutoff_retry == 0)
4117 /* Ensure the status of the address is set by checking retry data if
4118 necessary. There may be host-specific retry data (applicable to all
4119 messages) and also data for retries of a specific message at this host.
4120 If either of these retry records are actually read, the keys used are
4121 returned to save recomputing them later. */
4123 if (exp_bool(addrlist, US"transport", tblock->name, D_transport,
4124 US"retry_include_ip_address", ob->retry_include_ip_address,
4125 ob->expand_retry_include_ip_address, &incl_ip) != OK)
4126 continue; /* with next host */
4128 host_is_expired = retry_check_address(addrlist->domain, host, pistring,
4129 incl_ip, &retry_host_key, &retry_message_key);
4131 DEBUG(D_transport) debug_printf("%s [%s]%s retry-status = %s\n", host->name,
4132 (host->address == NULL)? US"" : host->address, pistring,
4133 (host->status == hstatus_usable)? "usable" :
4134 (host->status == hstatus_unusable)? "unusable" :
4135 (host->status == hstatus_unusable_expired)? "unusable (expired)" : "?");
4137 /* Skip this address if not usable at this time, noting if it wasn't
4138 actually expired, both locally and in the address. */
4140 switch (host->status)
4142 case hstatus_unusable:
4144 setflag(addrlist, af_retry_skipped);
4147 case hstatus_unusable_expired:
4150 case hwhy_retry: hosts_retry++; break;
4151 case hwhy_failed: hosts_fail++; break;
4153 case hwhy_deferred: hosts_defer++; break;
4156 /* If there was a retry message key, implying that previously there
4157 was a message-specific defer, we don't want to update the list of
4158 messages waiting for these hosts. */
4160 if (retry_message_key) update_waiting = FALSE;
4161 continue; /* With the next host or IP address */
4165 /* Second time round the loop: if the address is set but expired, and
4166 the message is newer than the last try, let it through. */
4171 || host->status != hstatus_unusable_expired
4172 || host->last_try > received_time.tv_sec)
4174 DEBUG(D_transport) debug_printf("trying expired host %s [%s]%s\n",
4175 host->name, host->address, pistring);
4176 host_is_expired = TRUE;
4179 /* Setting "expired=FALSE" doesn't actually mean not all hosts are expired;
4180 it remains TRUE only if all hosts are expired and none are actually tried.
4185 /* If this host is listed as one to which access must be serialized,
4186 see if another Exim process has a connection to it, and if so, skip
4187 this host. If not, update the database to record our connection to it
4188 and remember this for later deletion. Do not do any of this if we are
4189 sending the message down a pre-existing connection. */
4191 if ( !continue_hostname
4192 && verify_check_given_host(&ob->serialize_hosts, host) == OK)
4194 serialize_key = string_sprintf("host-serialize-%s", host->name);
4195 if (!enq_start(serialize_key, 1))
4198 debug_printf("skipping host %s because another Exim process "
4199 "is connected to it\n", host->name);
4205 /* OK, we have an IP address that is not waiting for its retry time to
4206 arrive (it might be expired) OR (second time round the loop) we have an
4207 expired host that hasn't been tried since the message arrived. Have a go
4208 at delivering the message to it. First prepare the addresses by flushing
4209 out the result of previous attempts, and finding the first address that
4210 is still to be delivered. */
4212 first_addr = prepare_addresses(addrlist, host);
4214 DEBUG(D_transport) debug_printf("delivering %s to %s [%s] (%s%s)\n",
4215 message_id, host->name, host->address, addrlist->address,
4216 addrlist->next ? ", ..." : "");
4218 set_process_info("delivering %s to %s [%s] (%s%s)",
4219 message_id, host->name, host->address, addrlist->address,
4220 addrlist->next ? ", ..." : "");
4222 /* This is not for real; don't do the delivery. If there are
4223 any remaining hosts, list them. */
4228 set_errno_nohost(addrlist, 0, NULL, OK, FALSE);
4229 for (addr = addrlist; addr; addr = addr->next)
4231 addr->host_used = host;
4232 addr->special_action = '*';
4233 addr->message = US"delivery bypassed by -N option";
4237 debug_printf("*** delivery by %s transport bypassed by -N option\n"
4238 "*** host and remaining hosts:\n", tblock->name);
4239 for (host2 = host; host2; host2 = host2->next)
4240 debug_printf(" %s [%s]\n", host2->name,
4241 host2->address ? host2->address : US"unset");
4246 /* This is for real. If the host is expired, we don't count it for
4247 hosts_max_retry. This ensures that all hosts must expire before an address
4248 is timed out, unless hosts_max_try_hardlimit (which protects against
4249 lunatic DNS configurations) is reached.
4251 If the host is not expired and we are about to hit the hosts_max_retry
4252 limit, check to see if there is a subsequent hosts with a different MX
4253 value. If so, make that the next host, and don't count this one. This is a
4254 heuristic to make sure that different MXs do get tried. With a normal kind
4255 of retry rule, they would get tried anyway when the earlier hosts were
4256 delayed, but if the domain has a "retry every time" type of rule - as is
4257 often used for the the very large ISPs, that won't happen. */
4262 /* Make a copy of the host if it is local to this invocation
4263 of the transport. */
4267 thost = store_get(sizeof(host_item));
4269 thost->name = string_copy(host->name);
4270 thost->address = string_copy(host->address);
4275 if (!host_is_expired && ++unexpired_hosts_tried >= ob->hosts_max_try)
4279 debug_printf("hosts_max_try limit reached with this host\n");
4280 for (h = host; h; h = h->next) if (h->mx != host->mx)
4283 unexpired_hosts_tried--;
4284 DEBUG(D_transport) debug_printf("however, a higher MX host exists "
4285 "and will be tried\n");
4290 /* Attempt the delivery. */
4292 total_hosts_tried++;
4293 rc = smtp_deliver(addrlist, thost, host_af, defport, interface, tblock,
4294 &message_defer, FALSE);
4297 OK => connection made, each address contains its result;
4298 message_defer is set for message-specific defers (when all
4299 recipients are marked defer)
4300 DEFER => there was a non-message-specific delivery problem;
4301 ERROR => there was a problem setting up the arguments for a filter,
4302 or there was a problem with expanding added headers
4305 /* If the result is not OK, there was a non-message-specific problem.
4306 If the result is DEFER, we need to write to the logs saying what happened
4307 for this particular host, except in the case of authentication and TLS
4308 failures, where the log has already been written. If all hosts defer a
4309 general message is written at the end. */
4311 if (rc == DEFER && first_addr->basic_errno != ERRNO_AUTHFAIL
4312 && first_addr->basic_errno != ERRNO_TLSFAILURE)
4313 write_logs(first_addr, host);
4315 #ifndef DISABLE_EVENT
4317 deferred_event_raise(first_addr, host);
4320 /* If STARTTLS was accepted, but there was a failure in setting up the
4321 TLS session (usually a certificate screwup), and the host is not in
4322 hosts_require_tls, and tls_tempfail_tryclear is true, try again, with
4323 TLS forcibly turned off. We have to start from scratch with a new SMTP
4324 connection. That's why the retry is done from here, not from within
4325 smtp_deliver(). [Rejections of STARTTLS itself don't screw up the
4326 session, so the in-clear transmission after those errors, if permitted,
4327 happens inside smtp_deliver().] */
4331 && first_addr->basic_errno == ERRNO_TLSFAILURE
4332 && ob->tls_tempfail_tryclear
4333 && verify_check_given_host(&ob->hosts_require_tls, host) != OK
4336 log_write(0, LOG_MAIN,
4337 "%s: delivering unencrypted to H=%s [%s] (not in hosts_require_tls)",
4338 first_addr->message, host->name, host->address);
4339 first_addr = prepare_addresses(addrlist, host);
4340 rc = smtp_deliver(addrlist, thost, host_af, defport, interface, tblock,
4341 &message_defer, TRUE);
4342 if (rc == DEFER && first_addr->basic_errno != ERRNO_AUTHFAIL)
4343 write_logs(first_addr, host);
4344 # ifndef DISABLE_EVENT
4346 deferred_event_raise(first_addr, host);
4349 #endif /*SUPPORT_TLS*/
4352 /* Delivery attempt finished */
4354 rs = rc == OK ? US"OK"
4355 : rc == DEFER ? US"DEFER"
4356 : rc == ERROR ? US"ERROR"
4359 set_process_info("delivering %s: just tried %s [%s] for %s%s: result %s",
4360 message_id, host->name, host->address, addrlist->address,
4361 addrlist->next ? " (& others)" : "", rs);
4363 /* Release serialization if set up */
4365 if (serialize_key) enq_end(serialize_key);
4367 /* If the result is DEFER, or if a host retry record is known to exist, we
4368 need to add an item to the retry chain for updating the retry database
4369 at the end of delivery. We only need to add the item to the top address,
4370 of course. Also, if DEFER, we mark the IP address unusable so as to skip it
4371 for any other delivery attempts using the same address. (It is copied into
4372 the unusable tree at the outer level, so even if different address blocks
4373 contain the same address, it still won't get tried again.) */
4375 if (rc == DEFER || retry_host_key)
4377 int delete_flag = rc != DEFER ? rf_delete : 0;
4378 if (!retry_host_key)
4381 if (exp_bool(addrlist, US"transport", tblock->name, D_transport,
4382 US"retry_include_ip_address", ob->retry_include_ip_address,
4383 ob->expand_retry_include_ip_address, &incl_ip) != OK)
4384 incl_ip = TRUE; /* error; use most-specific retry record */
4386 retry_host_key = incl_ip
4387 ? string_sprintf("T:%S:%s%s", host->name, host->address, pistring)
4388 : string_sprintf("T:%S%s", host->name, pistring);
4391 /* If a delivery of another message over an existing SMTP connection
4392 yields DEFER, we do NOT set up retry data for the host. This covers the
4393 case when there are delays in routing the addresses in the second message
4394 that are so long that the server times out. This is alleviated by not
4395 routing addresses that previously had routing defers when handling an
4396 existing connection, but even so, this case may occur (e.g. if a
4397 previously happily routed address starts giving routing defers). If the
4398 host is genuinely down, another non-continued message delivery will
4399 notice it soon enough. */
4401 if (delete_flag != 0 || !continue_hostname)
4402 retry_add_item(first_addr, retry_host_key, rf_host | delete_flag);
4404 /* We may have tried an expired host, if its retry time has come; ensure
4405 the status reflects the expiry for the benefit of any other addresses. */
4409 host->status = host_is_expired
4410 ? hstatus_unusable_expired : hstatus_unusable;
4411 host->why = hwhy_deferred;
4415 /* If message_defer is set (host was OK, but every recipient got deferred
4416 because of some message-specific problem), or if that had happened
4417 previously so that a message retry key exists, add an appropriate item
4418 to the retry chain. Note that if there was a message defer but now there is
4419 a host defer, the message defer record gets deleted. That seems perfectly
4420 reasonable. Also, stop the message from being remembered as waiting
4421 for specific hosts. */
4423 if (message_defer || retry_message_key)
4425 int delete_flag = message_defer ? 0 : rf_delete;
4426 if (!retry_message_key)
4429 if (exp_bool(addrlist, US"transport", tblock->name, D_transport,
4430 US"retry_include_ip_address", ob->retry_include_ip_address,
4431 ob->expand_retry_include_ip_address, &incl_ip) != OK)
4432 incl_ip = TRUE; /* error; use most-specific retry record */
4434 retry_message_key = incl_ip
4435 ? string_sprintf("T:%S:%s%s:%s", host->name, host->address, pistring,
4437 : string_sprintf("T:%S%s:%s", host->name, pistring, message_id);
4439 retry_add_item(addrlist, retry_message_key,
4440 rf_message | rf_host | delete_flag);
4441 update_waiting = FALSE;
4444 /* Any return other than DEFER (that is, OK or ERROR) means that the
4445 addresses have got their final statuses filled in for this host. In the OK
4446 case, see if any of them are deferred. */
4449 for (addr = addrlist; addr; addr = addr->next)
4450 if (addr->transport_return == DEFER)
4452 some_deferred = TRUE;
4456 /* If no addresses deferred or the result was ERROR, return. We do this for
4457 ERROR because a failing filter set-up or add_headers expansion is likely to
4458 fail for any host we try. */
4460 if (rc == ERROR || (rc == OK && !some_deferred))
4462 DEBUG(D_transport) debug_printf("Leaving %s transport\n", tblock->name);
4463 return TRUE; /* Each address has its status */
4466 /* If the result was DEFER or some individual addresses deferred, let
4467 the loop run to try other hosts with the deferred addresses, except for the
4468 case when we were trying to deliver down an existing channel and failed.
4469 Don't try any other hosts in this case. */
4471 if (continue_hostname) break;
4473 /* If the whole delivery, or some individual addresses, were deferred and
4474 there are more hosts that could be tried, do not count this host towards
4475 the hosts_max_try limit if the age of the message is greater than the
4476 maximum retry time for this host. This means we may try try all hosts,
4477 ignoring the limit, when messages have been around for some time. This is
4478 important because if we don't try all hosts, the address will never time
4479 out. NOTE: this does not apply to hosts_max_try_hardlimit. */
4481 if ((rc == DEFER || some_deferred) && nexthost)
4484 retry_config *retry = retry_find_config(host->name, NULL, 0, 0);
4486 if (retry && retry->rules)
4488 retry_rule *last_rule;
4489 for (last_rule = retry->rules;
4491 last_rule = last_rule->next);
4492 timedout = time(NULL) - received_time.tv_sec > last_rule->timeout;
4494 else timedout = TRUE; /* No rule => timed out */
4498 unexpired_hosts_tried--;
4499 DEBUG(D_transport) debug_printf("temporary delivery error(s) override "
4500 "hosts_max_try (message older than host's retry time)\n");
4503 } /* End of loop for trying multiple hosts. */
4505 /* This is the end of the loop that repeats iff expired is TRUE and
4506 ob->delay_after_cutoff is FALSE. The second time round we will
4507 try those hosts that haven't been tried since the message arrived. */
4511 debug_printf("all IP addresses skipped or deferred at least one address\n");
4512 if (expired && !ob->delay_after_cutoff && cutoff_retry == 0)
4513 debug_printf("retrying IP addresses not tried since message arrived\n");
4518 /* Get here if all IP addresses are skipped or defer at least one address. In
4519 MUA wrapper mode, this will happen only for connection or other non-message-
4520 specific failures. Force the delivery status for all addresses to FAIL. */
4524 for (addr = addrlist; addr; addr = addr->next)
4525 addr->transport_return = FAIL;
4529 /* In the normal, non-wrapper case, add a standard message to each deferred
4530 address if there hasn't been an error, that is, if it hasn't actually been
4531 tried this time. The variable "expired" will be FALSE if any deliveries were
4532 actually tried, or if there was at least one host that was not expired. That
4533 is, it is TRUE only if no deliveries were tried and all hosts were expired. If
4534 a delivery has been tried, an error code will be set, and the failing of the
4535 message is handled by the retry code later.
4537 If queue_smtp is set, or this transport was called to send a subsequent message
4538 down an existing TCP/IP connection, and something caused the host not to be
4539 found, we end up here, but can detect these cases and handle them specially. */
4541 for (addr = addrlist; addr; addr = addr->next)
4543 /* If host is not NULL, it means that we stopped processing the host list
4544 because of hosts_max_try or hosts_max_try_hardlimit. In the former case, this
4545 means we need to behave as if some hosts were skipped because their retry
4546 time had not come. Specifically, this prevents the address from timing out.
4547 However, if we have hit hosts_max_try_hardlimit, we want to behave as if all
4548 hosts were tried. */
4551 if (total_hosts_tried >= ob->hosts_max_try_hardlimit)
4554 debug_printf("hosts_max_try_hardlimit reached: behave as if all "
4555 "hosts were tried\n");
4560 debug_printf("hosts_max_try limit caused some hosts to be skipped\n");
4561 setflag(addr, af_retry_skipped);
4564 if (queue_smtp) /* no deliveries attempted */
4566 addr->transport_return = DEFER;
4567 addr->basic_errno = 0;
4568 addr->message = US"SMTP delivery explicitly queued";
4571 else if ( addr->transport_return == DEFER
4572 && (addr->basic_errno == ERRNO_UNKNOWNERROR || addr->basic_errno == 0)
4576 addr->basic_errno = ERRNO_HRETRY;
4577 if (continue_hostname)
4578 addr->message = US"no host found for existing SMTP connection";
4581 setflag(addr, af_pass_message); /* This is not a security risk */
4582 addr->message = string_sprintf(
4583 "all hosts%s have been failing for a long time %s",
4584 addr->domain ? string_sprintf(" for '%s'", addr->domain) : US"",
4585 ob->delay_after_cutoff
4586 ? US"(and retry time not reached)"
4587 : US"and were last tried after this message arrived");
4589 /* If we are already using fallback hosts, or there are no fallback hosts
4590 defined, convert the result to FAIL to cause a bounce. */
4592 if (addr->host_list == addr->fallback_hosts || !addr->fallback_hosts)
4593 addr->transport_return = FAIL;
4598 if (hosts_retry == hosts_total)
4599 s = "retry time not reached for any host%s";
4600 else if (hosts_fail == hosts_total)
4601 s = "all host address lookups%s failed permanently";
4602 else if (hosts_defer == hosts_total)
4603 s = "all host address lookups%s failed temporarily";
4604 else if (hosts_serial == hosts_total)
4605 s = "connection limit reached for all hosts%s";
4606 else if (hosts_fail+hosts_defer == hosts_total)
4607 s = "all host address lookups%s failed";
4609 s = "some host address lookups failed and retry time "
4610 "not reached for other hosts or connection limit reached%s";
4612 addr->message = string_sprintf(s,
4613 addr->domain ? string_sprintf(" for '%s'", addr->domain) : US"");
4618 /* Update the database which keeps information about which messages are waiting
4619 for which hosts to become available. For some message-specific errors, the
4620 update_waiting flag is turned off because we don't want follow-on deliveries in
4621 those cases. If this transport instance is explicitly limited to one message
4622 per connection then follow-on deliveries are not possible and there's no need
4623 to create/update the per-transport wait-<transport_name> database. */
4625 if (update_waiting && tblock->connection_max_messages != 1)
4626 transport_update_waiting(hostlist, tblock->name);
4630 DEBUG(D_transport) debug_printf("Leaving %s transport\n", tblock->name);
4632 return TRUE; /* Each address has its status */
4635 #endif /*!MACRO_PREDEF*/
4638 /* End of transport/smtp.c */