Use writev(2) when sending delivery status to the parent
[exim.git] / src / src / transports / smtp.c
CommitLineData
0756eb3c
PH
1/*************************************************
2* Exim - an Internet mail transport agent *
3*************************************************/
4
d4e5e70b 5/* Copyright (c) University of Cambridge 1995 - 2017 */
0756eb3c
PH
6/* See the file NOTICE for conditions of use and distribution. */
7
8#include "../exim.h"
9#include "smtp.h"
10
0756eb3c
PH
11
12/* Options specific to the smtp transport. This transport also supports LMTP
13over TCP/IP. The options must be in alphabetic order (note that "_" comes
14before the lower case letters). Some live in the transport_instance block so as
15to be publicly visible; these are flagged with opt_public. */
16
17optionlist smtp_transport_options[] = {
506900af
JH
18 { "*expand_multi_domain", opt_stringptr | opt_hidden | opt_public,
19 (void *)offsetof(transport_instance, expand_multi_domain) },
9c695f6d
JH
20 { "*expand_retry_include_ip_address", opt_stringptr | opt_hidden,
21 (void *)(offsetof(smtp_transport_options_block, expand_retry_include_ip_address)) },
22
48c7f9e2
PH
23 { "address_retry_include_sender", opt_bool,
24 (void *)offsetof(smtp_transport_options_block, address_retry_include_sender) },
0756eb3c
PH
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) },
382afc6b
PH
29 { "authenticated_sender_force", opt_bool,
30 (void *)offsetof(smtp_transport_options_block, authenticated_sender_force) },
0756eb3c
PH
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) },
80a47a2c 41#ifndef DISABLE_DKIM
f7572e5a 42 { "dkim_canon", opt_stringptr,
ff5aac2b 43 (void *)offsetof(smtp_transport_options_block, dkim.dkim_canon) },
f7572e5a 44 { "dkim_domain", opt_stringptr,
ff5aac2b 45 (void *)offsetof(smtp_transport_options_block, dkim.dkim_domain) },
d73e45df
JH
46 { "dkim_hash", opt_stringptr,
47 (void *)offsetof(smtp_transport_options_block, dkim.dkim_hash) },
f7572e5a 48 { "dkim_private_key", opt_stringptr,
ff5aac2b 49 (void *)offsetof(smtp_transport_options_block, dkim.dkim_private_key) },
f7572e5a 50 { "dkim_selector", opt_stringptr,
ff5aac2b 51 (void *)offsetof(smtp_transport_options_block, dkim.dkim_selector) },
f7572e5a 52 { "dkim_sign_headers", opt_stringptr,
ff5aac2b 53 (void *)offsetof(smtp_transport_options_block, dkim.dkim_sign_headers) },
f7572e5a 54 { "dkim_strict", opt_stringptr,
ff5aac2b 55 (void *)offsetof(smtp_transport_options_block, dkim.dkim_strict) },
80a47a2c 56#endif
0756eb3c
PH
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) },
578897ea 61 { "dnssec_request_domains", opt_stringptr,
7cd171b7 62 (void *)offsetof(smtp_transport_options_block, dnssec.request) },
578897ea 63 { "dnssec_require_domains", opt_stringptr,
7cd171b7 64 (void *)offsetof(smtp_transport_options_block, dnssec.require) },
9e4f5962
PP
65 { "dscp", opt_stringptr,
66 (void *)offsetof(smtp_transport_options_block, dscp) },
0756eb3c
PH
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) },
c51b8e75
PH
79 { "hosts_avoid_pipelining", opt_stringptr,
80 (void *)offsetof(smtp_transport_options_block, hosts_avoid_pipelining) },
80a47a2c 81#ifdef SUPPORT_TLS
0756eb3c
PH
82 { "hosts_avoid_tls", opt_stringptr,
83 (void *)offsetof(smtp_transport_options_block, hosts_avoid_tls) },
80a47a2c 84#endif
0756eb3c
PH
85 { "hosts_max_try", opt_int,
86 (void *)offsetof(smtp_transport_options_block, hosts_max_try) },
533244af
PH
87 { "hosts_max_try_hardlimit", opt_int,
88 (void *)offsetof(smtp_transport_options_block, hosts_max_try_hardlimit) },
80a47a2c 89#ifdef SUPPORT_TLS
0756eb3c
PH
90 { "hosts_nopass_tls", opt_stringptr,
91 (void *)offsetof(smtp_transport_options_block, hosts_nopass_tls) },
875512a3
JH
92 { "hosts_noproxy_tls", opt_stringptr,
93 (void *)offsetof(smtp_transport_options_block, hosts_noproxy_tls) },
80a47a2c 94#endif
0756eb3c
PH
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) },
f2de3a33 99#if defined(SUPPORT_TLS) && !defined(DISABLE_OCSP)
44662487
JH
100 { "hosts_request_ocsp", opt_stringptr,
101 (void *)offsetof(smtp_transport_options_block, hosts_request_ocsp) },
102#endif
0756eb3c
PH
103 { "hosts_require_auth", opt_stringptr,
104 (void *)offsetof(smtp_transport_options_block, hosts_require_auth) },
80a47a2c 105#ifdef SUPPORT_TLS
7a31d643
JH
106# ifdef EXPERIMENTAL_DANE
107 { "hosts_require_dane", opt_stringptr,
108 (void *)offsetof(smtp_transport_options_block, hosts_require_dane) },
109# endif
f2de3a33 110# ifndef DISABLE_OCSP
f5d78688
JH
111 { "hosts_require_ocsp", opt_stringptr,
112 (void *)offsetof(smtp_transport_options_block, hosts_require_ocsp) },
113# endif
0756eb3c
PH
114 { "hosts_require_tls", opt_stringptr,
115 (void *)offsetof(smtp_transport_options_block, hosts_require_tls) },
80a47a2c 116#endif
0756eb3c
PH
117 { "hosts_try_auth", opt_stringptr,
118 (void *)offsetof(smtp_transport_options_block, hosts_try_auth) },
f98442df
JH
119 { "hosts_try_chunking", opt_stringptr,
120 (void *)offsetof(smtp_transport_options_block, hosts_try_chunking) },
7a31d643 121#if defined(SUPPORT_TLS) && defined(EXPERIMENTAL_DANE)
96e47838
TL
122 { "hosts_try_dane", opt_stringptr,
123 (void *)offsetof(smtp_transport_options_block, hosts_try_dane) },
124#endif
fb05276a
JH
125 { "hosts_try_fastopen", opt_stringptr,
126 (void *)offsetof(smtp_transport_options_block, hosts_try_fastopen) },
8ccd00b1 127#ifndef DISABLE_PRDR
fd98a5c6
JH
128 { "hosts_try_prdr", opt_stringptr,
129 (void *)offsetof(smtp_transport_options_block, hosts_try_prdr) },
130#endif
99400968
JH
131#ifdef SUPPORT_TLS
132 { "hosts_verify_avoid_tls", opt_stringptr,
133 (void *)offsetof(smtp_transport_options_block, hosts_verify_avoid_tls) },
134#endif
0756eb3c
PH
135 { "interface", opt_stringptr,
136 (void *)offsetof(smtp_transport_options_block, interface) },
137 { "keepalive", opt_bool,
138 (void *)offsetof(smtp_transport_options_block, keepalive) },
f1513293
PH
139 { "lmtp_ignore_quota", opt_bool,
140 (void *)offsetof(smtp_transport_options_block, lmtp_ignore_quota) },
0756eb3c
PH
141 { "max_rcpt", opt_int | opt_public,
142 (void *)offsetof(transport_instance, max_addresses) },
506900af 143 { "multi_domain", opt_expand_bool | opt_public,
0756eb3c
PH
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) },
9c695f6d 149 { "retry_include_ip_address", opt_expand_bool,
0756eb3c
PH
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) }
f0989ec0 155#ifdef SUPPORT_SOCKS
7eb6c37c
JH
156 ,{ "socks_proxy", opt_stringptr,
157 (void *)offsetof(smtp_transport_options_block, socks_proxy) }
158#endif
80a47a2c 159#ifdef SUPPORT_TLS
0756eb3c
PH
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) },
54c90be1
PP
164 { "tls_dh_min_bits", opt_int,
165 (void *)offsetof(smtp_transport_options_block, tls_dh_min_bits) },
0756eb3c
PH
166 { "tls_privatekey", opt_stringptr,
167 (void *)offsetof(smtp_transport_options_block, tls_privatekey) },
3f0945ff 168 { "tls_require_ciphers", opt_stringptr,
0756eb3c 169 (void *)offsetof(smtp_transport_options_block, tls_require_ciphers) },
3f0945ff
PP
170 { "tls_sni", opt_stringptr,
171 (void *)offsetof(smtp_transport_options_block, tls_sni) },
0756eb3c
PH
172 { "tls_tempfail_tryclear", opt_bool,
173 (void *)offsetof(smtp_transport_options_block, tls_tempfail_tryclear) },
a63be306
WB
174 { "tls_try_verify_hosts", opt_stringptr,
175 (void *)offsetof(smtp_transport_options_block, tls_try_verify_hosts) },
e51c7be2
JH
176 { "tls_verify_cert_hostnames", opt_stringptr,
177 (void *)offsetof(smtp_transport_options_block,tls_verify_cert_hostnames)},
0756eb3c 178 { "tls_verify_certificates", opt_stringptr,
a63be306
WB
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) }
80a47a2c 182#endif
0756eb3c
PH
183};
184
185/* Size of the options list. An extern variable has to be used so that its
186address can appear in the tables drtables.c. */
187
188int smtp_transport_options_count =
189 sizeof(smtp_transport_options)/sizeof(optionlist);
190
d185889f
JH
191
192#ifdef MACRO_PREDEF
193
194/* Dummy values */
195smtp_transport_options_block smtp_transport_option_defaults = {0};
196void smtp_transport_init(transport_instance *tblock) {}
197BOOL smtp_transport_entry(transport_instance *tblock, address_item *addr) {return FALSE;}
198void smtp_transport_closedown(transport_instance *tblock) {}
199
200#else /*!MACRO_PREDEF*/
201
202
0756eb3c
PH
203/* Default private options block for the smtp transport. */
204
205smtp_transport_options_block smtp_transport_option_defaults = {
838d897c
JH
206 .hosts = NULL,
207 .hosts = NULL,
208 .hostlist = NULL,
209 .fallback_hostlist = NULL,
210 .authenticated_sender = NULL,
211 .helo_data = US"$primary_hostname",
212 .interface = NULL,
213 .port = NULL,
214 .protocol = US"smtp",
215 .dscp = NULL,
216 .serialize_hosts = NULL,
217 .hosts_try_auth = NULL,
218 .hosts_require_auth = NULL,
219 .hosts_try_chunking = US"*",
96e47838 220#ifdef EXPERIMENTAL_DANE
838d897c
JH
221 .hosts_try_dane = NULL,
222 .hosts_require_dane = NULL,
96e47838 223#endif
838d897c 224 .hosts_try_fastopen = NULL,
8ccd00b1 225#ifndef DISABLE_PRDR
838d897c 226 .hosts_try_prdr = US"*",
f5d78688 227#endif
f2de3a33 228#ifndef DISABLE_OCSP
838d897c
JH
229 .hosts_request_ocsp = US"*", /* hosts_request_ocsp (except under DANE; tls_client_start()) */
230 .hosts_require_ocsp = NULL,
fd98a5c6 231#endif
838d897c
JH
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,
57cc2785 237#ifdef SUPPORT_TLS
838d897c
JH
238 .hosts_nopass_tls = NULL,
239 .hosts_noproxy_tls = US"*",
57cc2785 240#endif
838d897c
JH
241 .command_timeout = 5*60,
242 .connect_timeout = 5*60,
243 .data_timeout = 5*60,
244 .final_timeout = 10*60,
245 .size_addition = 1024,
246 .hosts_max_try = 5,
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,
258 .keepalive = TRUE,
259 .lmtp_ignore_quota = FALSE,
260 .expand_retry_include_ip_address = NULL,
261 .retry_include_ip_address = TRUE,
f0989ec0 262#ifdef SUPPORT_SOCKS
838d897c 263 .socks_proxy = NULL,
b8bf753b 264#endif
80a47a2c 265#ifdef SUPPORT_TLS
838d897c
JH
266 .tls_certificate = NULL,
267 .tls_crl = NULL,
268 .tls_privatekey = NULL,
269 .tls_require_ciphers = NULL,
270 .tls_sni = 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"*",
80a47a2c
TK
277#endif
278#ifndef DISABLE_DKIM
838d897c
JH
279 .dkim =
280 {.dkim_domain = NULL,
281 .dkim_private_key = NULL,
282 .dkim_selector = NULL,
283 .dkim_canon = NULL,
284 .dkim_sign_headers = NULL,
285 .dkim_strict = NULL,
d73e45df 286 .dkim_hash = US"sha256",
838d897c 287 .dot_stuffed = FALSE},
80a47a2c 288#endif
0756eb3c
PH
289};
290
6c1c3d1d
WB
291/* some DSN flags for use later */
292
293static int rf_list[] = {rf_notify_never, rf_notify_success,
294 rf_notify_failure, rf_notify_delay };
295
45500060 296static uschar *rf_names[] = { US"NEVER", US"SUCCESS", US"FAILURE", US"DELAY" };
6c1c3d1d
WB
297
298
0756eb3c
PH
299
300/* Local statics */
301
87cb4a16
JH
302static uschar *smtp_command; /* Points to last cmd for error messages */
303static uschar *mail_command; /* Points to MAIL cmd for error messages */
304static uschar *data_command = US""; /* Points to DATA cmd for error messages */
305static BOOL update_waiting; /* TRUE to update the "wait" database */
875512a3
JH
306
307/*XXX move to smtp_context */
87cb4a16 308static BOOL pipelining_active; /* current transaction is in pipe mode */
0756eb3c
PH
309
310
311/*************************************************
312* Setup entry point *
313*************************************************/
314
315/* This function is called when the transport is about to be used,
316but before running it in a sub-process. It is used for two things:
317
318 (1) To set the fallback host list in addresses, when delivering.
26da7e20
PH
319 (2) To pass back the interface, port, protocol, and other options, for use
320 during callout verification.
0756eb3c
PH
321
322Arguments:
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
929ba01c
PH
326 uid the uid that will be set (not used)
327 gid the gid that will be set (not used)
0756eb3c
PH
328 errmsg place for error message (not used)
329
330Returns: OK always (FAIL, DEFER not used)
331*/
332
333static int
334smtp_transport_setup(transport_instance *tblock, address_item *addrlist,
929ba01c 335 transport_feedback *tf, uid_t uid, gid_t gid, uschar **errmsg)
0756eb3c
PH
336{
337smtp_transport_options_block *ob =
338 (smtp_transport_options_block *)(tblock->options_block);
339
340errmsg = errmsg; /* Keep picky compilers happy */
929ba01c
PH
341uid = uid;
342gid = gid;
0756eb3c
PH
343
344/* Pass back options if required. This interface is getting very messy. */
345
02b41d71 346if (tf)
0756eb3c
PH
347 {
348 tf->interface = ob->interface;
349 tf->port = ob->port;
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;
26da7e20 357 tf->helo_data = ob->helo_data;
0756eb3c
PH
358 }
359
360/* Set the fallback host list for all the addresses that don't have fallback
361host lists, provided that the local host wasn't present in the original host
362list. */
363
364if (!testflag(addrlist, af_local_host_removed))
02b41d71
JH
365 for (; addrlist; addrlist = addrlist->next)
366 if (!addrlist->fallback_hosts) addrlist->fallback_hosts = ob->fallback_hostlist;
0756eb3c
PH
367
368return OK;
369}
370
371
372
373/*************************************************
374* Initialization entry point *
375*************************************************/
376
377/* Called for each instance, after its options have been read, to
378enable consistency checks to be done, or anything else that needs
379to be set up.
380
381Argument: pointer to the transport instance block
382Returns: nothing
383*/
384
385void
386smtp_transport_init(transport_instance *tblock)
387{
388smtp_transport_options_block *ob =
389 (smtp_transport_options_block *)(tblock->options_block);
390
391/* Retry_use_local_part defaults FALSE if unset */
392
393if (tblock->retry_use_local_part == TRUE_UNSET)
394 tblock->retry_use_local_part = FALSE;
395
396/* Set the default port according to the protocol */
397
398if (ob->port == NULL)
061b7ebd
PP
399 ob->port = (strcmpic(ob->protocol, US"lmtp") == 0)? US"lmtp" :
400 (strcmpic(ob->protocol, US"smtps") == 0)? US"smtps" : US"smtp";
0756eb3c
PH
401
402/* Set up the setup entry point, to be called before subprocesses for this
403transport. */
404
405tblock->setup = smtp_transport_setup;
406
407/* Complain if any of the timeouts are zero. */
408
409if (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",
413 tblock->name);
414
415/* If hosts_override is set and there are local hosts, set the global
416flag that stops verify from showing router hosts. */
417
418if (ob->hosts_override && ob->hosts != NULL) tblock->overrides_hosts = TRUE;
419
420/* If there are any fallback hosts listed, build a chain of host items
421for them, but do not do any lookups at this time. */
422
423host_build_hostlist(&(ob->fallback_hostlist), ob->fallback_hosts, FALSE);
424}
425
426
427
428
429
430/*************************************************
431* Set delivery info into all active addresses *
432*************************************************/
433
434/* Only addresses whose status is >= PENDING are relevant. A lesser
435status means that an address is not currently being processed.
436
437Arguments:
447d236c
PH
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
c562fd30 443 host if set, mark addrs as having used this host
895fbaf2
JH
444 smtp_greeting from peer
445 helo_response from peer
0756eb3c
PH
446
447If errno_value has the special value ERRNO_CONNECTTIMEOUT, ETIMEDOUT is put in
448the errno field, and RTEF_CTOUT is ORed into the more_errno field, to indicate
449this particular type of timeout.
450
451Returns: nothing
452*/
453
7cd1141b
PH
454static void
455set_errno(address_item *addrlist, int errno_value, uschar *msg, int rc,
895fbaf2
JH
456 BOOL pass_message, host_item * host
457#ifdef EXPERIMENTAL_DSN_INFO
458 , const uschar * smtp_greeting, const uschar * helo_response
459#endif
460 )
0756eb3c
PH
461{
462address_item *addr;
463int orvalue = 0;
464if (errno_value == ERRNO_CONNECTTIMEOUT)
465 {
466 errno_value = ETIMEDOUT;
467 orvalue = RTEF_CTOUT;
468 }
895fbaf2 469for (addr = addrlist; addr; addr = addr->next)
168dec3b 470 if (addr->transport_return >= PENDING)
447d236c 471 {
168dec3b
JH
472 addr->basic_errno = errno_value;
473 addr->more_errno |= orvalue;
02b41d71 474 if (msg)
168dec3b
JH
475 {
476 addr->message = msg;
477 if (pass_message) setflag(addr, af_pass_message);
478 }
479 addr->transport_return = rc;
480 if (host)
895fbaf2 481 {
168dec3b 482 addr->host_used = host;
895fbaf2
JH
483#ifdef EXPERIMENTAL_DSN_INFO
484 if (smtp_greeting)
485 {uschar * s = Ustrchr(smtp_greeting, '\n'); if (s) *s = '\0';}
486 addr->smtp_greeting = smtp_greeting;
487
488 if (helo_response)
489 {uschar * s = Ustrchr(helo_response, '\n'); if (s) *s = '\0';}
490 addr->helo_response = helo_response;
491#endif
492 }
447d236c 493 }
0756eb3c
PH
494}
495
895fbaf2
JH
496static void
497set_errno_nohost(address_item *addrlist, int errno_value, uschar *msg, int rc,
498 BOOL pass_message)
499{
500set_errno(addrlist, errno_value, msg, rc, pass_message, NULL
501#ifdef EXPERIMENTAL_DSN_INFO
502 , NULL, NULL
503#endif
504 );
505}
0756eb3c
PH
506
507
508/*************************************************
509* Check an SMTP response *
510*************************************************/
511
512/* This function is given an errno code and the SMTP response buffer
513to analyse, together with the host identification for generating messages. It
514sets an appropriate message and puts the first digit of the response code into
515the yield variable. If no response was actually read, a suitable digit is
516chosen.
517
518Arguments:
447d236c
PH
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
4c04137d 524 message where to put an error message
447d236c
PH
525 pass_message set TRUE if message is an SMTP response
526
527Returns: TRUE if an SMTP "QUIT" command should be sent, else FALSE
0756eb3c
PH
528*/
529
a7538db1
JH
530static BOOL
531check_response(host_item *host, int *errno_value, int more_errno,
447d236c 532 uschar *buffer, int *yield, uschar **message, BOOL *pass_message)
0756eb3c 533{
0d9fa8c0 534uschar * pl = pipelining_active ? US"pipelined " : US"";
e9166683 535const uschar * s;
0756eb3c
PH
536
537*yield = '4'; /* Default setting is to give a temporary error */
538
e9166683 539switch(*errno_value)
0756eb3c 540 {
e9166683
JH
541 case ETIMEDOUT: /* Handle response timeout */
542 *message = US string_sprintf("SMTP timeout after %s%s",
543 pl, smtp_command);
544 if (transport_count > 0)
545 *message = US string_sprintf("%s (%d bytes written)", *message,
546 transport_count);
547 return FALSE;
548
549 case ERRNO_SMTPFORMAT: /* Handle malformed SMTP response */
550 s = string_printing(buffer);
551 while (isspace(*s)) s++;
552 *message = *s == 0
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);
557 return FALSE;
558
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",
562 more_errno,
563 more_errno == EX_EXECFAILED ? ": unable to execute command" : "");
564 return FALSE;
565
566 case ERRNO_CHHEADER_FAIL: /* Handle a failed add_headers expansion;
567 can't send QUIT as we mustn't end the DATA. */
568 *message =
569 string_sprintf("failed to expand headers_add or headers_remove: %s",
570 expand_string_message);
571 return FALSE;
572
573 case ERRNO_WRITEINCOMPLETE: /* failure to write a complete data block */
574 *message = string_sprintf("failed to write a data block");
575 return FALSE;
0756eb3c 576
8c5d388a 577#ifdef SUPPORT_I18N
e9166683
JH
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);
581 return TRUE;
250b6871 582#endif
e9166683 583 }
250b6871 584
0756eb3c
PH
585/* Handle error responses from the remote mailer. */
586
587if (buffer[0] != 0)
588 {
e9166683
JH
589 *message = string_sprintf("SMTP error from remote mail server after %s%s: "
590 "%s", pl, smtp_command, s = string_printing(buffer));
447d236c 591 *pass_message = TRUE;
0756eb3c
PH
592 *yield = buffer[0];
593 return TRUE;
594 }
595
596/* No data was read. If there is no errno, this must be the EOF (i.e.
19b9dc85
PH
597connection closed) case, which causes deferral. An explicit connection reset
598error has the same effect. Otherwise, put the host's identity in the message,
599leaving the errno value to be interpreted as well. In all cases, we have to
600assume the connection is now dead. */
0756eb3c 601
19b9dc85 602if (*errno_value == 0 || *errno_value == ECONNRESET)
0756eb3c
PH
603 {
604 *errno_value = ERRNO_SMTPCLOSED;
c562fd30 605 *message = US string_sprintf("Remote host closed connection "
02b41d71 606 "in response to %s%s", pl, smtp_command);
0756eb3c 607 }
de6273b4
JH
608else
609 *message = US string_sprintf("%s [%s]", host->name, host->address);
0756eb3c
PH
610
611return FALSE;
612}
613
614
615
616/*************************************************
617* Write error message to logs *
618*************************************************/
619
620/* This writes to the main log and to the message log.
621
622Arguments:
623 addr the address item containing error information
624 host the current host
625
626Returns: nothing
627*/
628
629static void
630write_logs(address_item *addr, host_item *host)
631{
584ddd64
JH
632uschar * 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);
c562fd30
JH
636
637if (addr->message)
0756eb3c 638 {
c562fd30 639 message = string_sprintf("%s: %s", message, addr->message);
0756eb3c
PH
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);
644 }
645else
646 {
37f3dc43
JH
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);
0756eb3c
PH
650 }
651}
652
c562fd30
JH
653static void
654msglog_line(host_item * host, uschar * message)
655{
37f3dc43
JH
656deliver_msglog("%s H=%s [%s] %s\n", tod_stamp(tod_log),
657 host->name, host->address, message);
c562fd30
JH
658}
659
0756eb3c
PH
660
661
0cbf2b82 662#ifndef DISABLE_EVENT
d68218c7
JH
663/*************************************************
664* Post-defer action *
665*************************************************/
666
667/* This expands an arbitrary per-transport string.
668 It might, for example, be used to write to the database log.
669
670Arguments:
d68218c7
JH
671 addr the address item containing error information
672 host the current host
673
674Returns: nothing
675*/
676
677static void
774ef2d7 678deferred_event_raise(address_item *addr, host_item *host)
d68218c7 679{
774ef2d7 680uschar * action = addr->transport->event_action;
55414b25 681const uschar * save_domain;
a7538db1
JH
682uschar * save_local;
683
d68218c7 684if (!action)
a7538db1 685 return;
d68218c7 686
a7538db1
JH
687save_domain = deliver_domain;
688save_local = deliver_localpart;
689
690/*XXX would ip & port already be set up? */
691deliver_host_address = string_copy(host->address);
774ef2d7
JH
692deliver_host_port = host->port == PORT_NONE ? 25 : host->port;
693event_defer_errno = addr->basic_errno;
d68218c7
JH
694
695router_name = addr->router->name;
696transport_name = addr->transport->name;
a7538db1
JH
697deliver_domain = addr->domain;
698deliver_localpart = addr->local_part;
699
774ef2d7 700(void) event_raise(action, US"msg:host:defer",
a7538db1
JH
701 addr->message
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))
707 : NULL);
708
709deliver_localpart = save_local;
710deliver_domain = save_domain;
d68218c7
JH
711router_name = transport_name = NULL;
712}
713#endif
714
0756eb3c
PH
715/*************************************************
716* Synchronize SMTP responses *
717*************************************************/
718
719/* This function is called from smtp_deliver() to receive SMTP responses from
720the server, and match them up with the commands to which they relate. When
721PIPELINING is not in use, this function is called after every command, and is
722therefore somewhat over-engineered, but it is simpler to use a single scheme
723that works both with and without PIPELINING instead of having two separate sets
724of code.
725
726The set of commands that are buffered up with pipelining may start with MAIL
727and may end with DATA; in between are RCPT commands that correspond to the
728addresses whose status is PENDING_DEFER. All other commands (STARTTLS, AUTH,
729etc.) are never buffered.
730
731Errors after MAIL or DATA abort the whole process leaving the response in the
732buffer. After MAIL, pending responses are flushed, and the original command is
733re-instated in big_buffer for error messages. For RCPT commands, the remote is
734permitted to reject some recipient addresses while accepting others. However
735certain errors clearly abort the whole process. Set the value in
736transport_return to PENDING_OK if the address is accepted. If there is a
737subsequent general error, it will get reset accordingly. If not, it will get
738converted to OK at the end.
739
740Arguments:
df5b41e3 741 sx smtp connection context
48c7f9e2 742 count the number of responses to read
48c7f9e2
PH
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
0756eb3c
PH
746
747Returns: 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
754*/
755
756static int
df5b41e3 757sync_responses(smtp_context * sx, int count, int pending_DATA)
0756eb3c 758{
df5b41e3 759address_item *addr = sx->sync_addr;
e9166683
JH
760smtp_transport_options_block *ob =
761 (smtp_transport_options_block *)sx->tblock->options_block;
0756eb3c
PH
762int yield = 0;
763
764/* Handle the response for a MAIL command. On error, reinstate the original
765command in big_buffer for error message use, and flush any further pending
766responses before returning, except after I/O errors and timeouts. */
767
df5b41e3 768if (sx->pending_MAIL)
0756eb3c
PH
769 {
770 count--;
e9166683
JH
771 if (!smtp_read_response(&sx->inblock, sx->buffer, sizeof(sx->buffer),
772 '2', ob->command_timeout))
0756eb3c 773 {
e027f545 774 DEBUG(D_transport) debug_printf("bad response for MAIL\n");
0756eb3c 775 Ustrcpy(big_buffer, mail_command); /* Fits, because it came from there! */
df5b41e3 776 if (errno == 0 && sx->buffer[0] != 0)
0756eb3c
PH
777 {
778 uschar flushbuffer[4096];
e97957bc 779 int save_errno = 0;
df5b41e3 780 if (sx->buffer[0] == '4')
e97957bc
PH
781 {
782 save_errno = ERRNO_MAIL4XX;
df5b41e3 783 addr->more_errno |= ((sx->buffer[1] - '0')*10 + sx->buffer[2] - '0') << 8;
e97957bc 784 }
0756eb3c
PH
785 while (count-- > 0)
786 {
df5b41e3 787 if (!smtp_read_response(&sx->inblock, flushbuffer, sizeof(flushbuffer),
e9166683 788 '2', ob->command_timeout)
0756eb3c
PH
789 && (errno != 0 || flushbuffer[0] == 0))
790 break;
791 }
e97957bc 792 errno = save_errno;
0756eb3c 793 }
c562fd30
JH
794
795 if (pending_DATA) count--; /* Number of RCPT responses to come */
796 while (count-- > 0) /* Mark any pending addrs with the host used */
797 {
798 while (addr->transport_return != PENDING_DEFER) addr = addr->next;
df5b41e3 799 addr->host_used = sx->host;
c562fd30
JH
800 addr = addr->next;
801 }
0756eb3c
PH
802 return -3;
803 }
804 }
805
806if (pending_DATA) count--; /* Number of RCPT responses to come */
807
808/* Read and handle the required number of RCPT responses, matching each one up
809with an address by scanning for the next address whose status is PENDING_DEFER.
810*/
811
812while (count-- > 0)
813 {
4c2471ca
JH
814 while (addr->transport_return != PENDING_DEFER)
815 if (!(addr = addr->next))
816 return -2;
0756eb3c
PH
817
818 /* The address was accepted */
df5b41e3 819 addr->host_used = sx->host;
0756eb3c 820
e9166683
JH
821 if (smtp_read_response(&sx->inblock, sx->buffer, sizeof(sx->buffer),
822 '2', ob->command_timeout))
0756eb3c
PH
823 {
824 yield |= 1;
825 addr->transport_return = PENDING_OK;
826
827 /* If af_dr_retry_exists is set, there was a routing delay on this address;
09945f1e
PH
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. */
0756eb3c
PH
830
831 if (testflag(addr, af_dr_retry_exists))
09945f1e
PH
832 {
833 uschar *altkey = string_sprintf("%s:<%s>", addr->address_retry_key,
834 sender_address);
835 retry_add_item(addr, altkey, rf_delete);
0756eb3c 836 retry_add_item(addr, addr->address_retry_key, rf_delete);
09945f1e 837 }
0756eb3c
PH
838 }
839
840 /* Timeout while reading the response */
841
842 else if (errno == ETIMEDOUT)
843 {
c562fd30 844 uschar *message = string_sprintf("SMTP timeout after RCPT TO:<%s>",
e9166683 845 transport_rcpt_address(addr, sx->tblock->rcpt_include_affixes));
df5b41e3 846 set_errno_nohost(sx->first_addr, ETIMEDOUT, message, DEFER, FALSE);
0756eb3c 847 retry_add_item(addr, addr->address_retry_key, 0);
f6c332bd 848 update_waiting = FALSE;
0756eb3c
PH
849 return -1;
850 }
851
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
855 makes sense. */
856
df5b41e3 857 else if (errno != 0 || sx->buffer[0] == 0)
0756eb3c
PH
858 {
859 string_format(big_buffer, big_buffer_size, "RCPT TO:<%s>",
df5b41e3 860 transport_rcpt_address(addr, sx->tblock->rcpt_include_affixes));
0756eb3c
PH
861 return -2;
862 }
863
864 /* Handle SMTP permanent and temporary response codes. */
865
866 else
867 {
868 addr->message =
447d236c 869 string_sprintf("SMTP error from remote mail server after RCPT TO:<%s>: "
df5b41e3
JH
870 "%s", transport_rcpt_address(addr, sx->tblock->rcpt_include_affixes),
871 string_printing(sx->buffer));
447d236c 872 setflag(addr, af_pass_message);
e9166683
JH
873 if (!sx->verify)
874 msglog_line(sx->host, addr->message);
0756eb3c
PH
875
876 /* The response was 5xx */
877
df5b41e3 878 if (sx->buffer[0] == '5')
0756eb3c
PH
879 {
880 addr->transport_return = FAIL;
881 yield |= 2;
882 }
883
884 /* The response was 4xx */
885
886 else
887 {
0756eb3c
PH
888 addr->transport_return = DEFER;
889 addr->basic_errno = ERRNO_RCPT4XX;
df5b41e3 890 addr->more_errno |= ((sx->buffer[1] - '0')*10 + sx->buffer[2] - '0') << 8;
0756eb3c 891
e9166683
JH
892 if (!sx->verify)
893 {
0cbf2b82 894#ifndef DISABLE_EVENT
e9166683
JH
895 event_defer_errno = addr->more_errno;
896 msg_event_raise(US"msg:rcpt:host:defer", addr);
5ef5dd52
JB
897#endif
898
e9166683
JH
899 /* Log temporary errors if there are more hosts to be tried.
900 If not, log this last one in the == line. */
0756eb3c 901
e9166683
JH
902 if (sx->host->next)
903 log_write(0, LOG_MAIN, "H=%s [%s]: %s",
904 sx->host->name, sx->host->address, addr->message);
0756eb3c 905
0cbf2b82 906#ifndef DISABLE_EVENT
e9166683
JH
907 else
908 msg_event_raise(US"msg:rcpt:defer", addr);
5ef5dd52
JB
909#endif
910
e9166683
JH
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. */
0756eb3c 913
e9166683 914 update_waiting = FALSE;
0756eb3c 915
e9166683
JH
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
918 to the retry key. */
0756eb3c 919
e9166683
JH
920 retry_add_item(addr,
921 ob->address_retry_include_sender
922 ? string_sprintf("%s:<%s>", addr->address_retry_key, sender_address)
923 : addr->address_retry_key,
924 0);
925 }
0756eb3c
PH
926 }
927 }
928 } /* Loop for next RCPT response */
929
930/* Update where to start at for the next block of responses, unless we
931have already handled all the addresses. */
932
e9166683 933if (addr) sx->sync_addr = addr->next;
0756eb3c
PH
934
935/* Handle a response to DATA. If we have not had any good recipients, either
936previously or in this block, the response is ignored. */
937
938if (pending_DATA != 0 &&
e9166683
JH
939 !smtp_read_response(&sx->inblock, sx->buffer, sizeof(sx->buffer),
940 '3', ob->command_timeout))
0756eb3c
PH
941 {
942 int code;
943 uschar *msg;
447d236c 944 BOOL pass_message;
e97957bc
PH
945 if (pending_DATA > 0 || (yield & 1) != 0)
946 {
df5b41e3 947 if (errno == 0 && sx->buffer[0] == '4')
e97957bc
PH
948 {
949 errno = ERRNO_DATA4XX;
df5b41e3 950 sx->first_addr->more_errno |= ((sx->buffer[1] - '0')*10 + sx->buffer[2] - '0') << 8;
e97957bc
PH
951 }
952 return -3;
953 }
df5b41e3 954 (void)check_response(sx->host, &errno, 0, sx->buffer, &code, &msg, &pass_message);
0756eb3c
PH
955 DEBUG(D_transport) debug_printf("%s\nerror for DATA ignored: pipelining "
956 "is in use and there were no good recipients\n", msg);
957 }
958
959/* All responses read and handled; MAIL (if present) received 2xx and DATA (if
960present) received 3xx. If any RCPTs were handled and yielded anything other
961than 4xx, yield will be set non-zero. */
962
963return yield;
964}
965
966
967
fcc8e047
JH
968/* Do the client side of smtp-level authentication */
969/*
970Arguments:
971 buffer EHLO response from server (gets overwritten)
972 addrlist chain of potential addresses to deliver
973 host host to deliver to
974 ob transport options
975 ibp, obp comms channel control blocks
976
977Returns:
978 OK Success, or failed (but not required): global "smtp_authenticated" set
979 DEFER Failed authentication (and was required)
980 ERROR Internal problem
981
982 FAIL_SEND Failed communications - transmit
983 FAIL - response
984*/
985
986int
987smtp_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)
990{
a7538db1
JH
991int require_auth;
992uschar *fail_reason = US"server did not advertise AUTH support";
fcc8e047 993
a7538db1
JH
994smtp_authenticated = FALSE;
995client_authenticator = client_authenticated_id = client_authenticated_sender = NULL;
5130845b 996require_auth = verify_check_given_host(&ob->hosts_require_auth, host);
fcc8e047 997
a7538db1
JH
998if (is_esmtp && !regex_AUTH) regex_AUTH =
999 regex_must_compile(US"\\n250[\\s\\-]AUTH\\s+([\\-\\w\\s]+)(?:\\n|$)",
1000 FALSE, TRUE);
fcc8e047 1001
a7538db1
JH
1002if (is_esmtp && regex_match_and_setup(regex_AUTH, buffer, 0, -1))
1003 {
1004 uschar *names = string_copyn(expand_nstring[1], expand_nlength[1]);
1005 expand_nmax = -1; /* reset */
fcc8e047 1006
a7538db1
JH
1007 /* Must not do this check until after we have saved the result of the
1008 regex match above. */
fcc8e047 1009
a7538db1 1010 if (require_auth == OK ||
5130845b 1011 verify_check_given_host(&ob->hosts_try_auth, host) == OK)
a7538db1
JH
1012 {
1013 auth_instance *au;
1014 fail_reason = US"no common mechanisms were found";
fcc8e047 1015
a7538db1 1016 DEBUG(D_transport) debug_printf("scanning authentication mechanisms\n");
fcc8e047 1017
a7538db1
JH
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.
1022 */
fcc8e047 1023
cab0c277 1024 for (au = auths; !smtp_authenticated && au; au = au->next)
a7538db1
JH
1025 {
1026 uschar *p = names;
1027 if (!au->client ||
1028 (au->client_condition != NULL &&
1029 !expand_check_condition(au->client_condition, au->name,
1030 US"client authenticator")))
1031 {
1032 DEBUG(D_transport) debug_printf("skipping %s authenticator: %s\n",
1033 au->name,
1034 (au->client)? "client_condition is false" :
1035 "not configured as a client");
1036 continue;
1037 }
fcc8e047 1038
a7538db1 1039 /* Loop to scan supported server mechanisms */
fcc8e047 1040
cab0c277 1041 while (*p)
a7538db1
JH
1042 {
1043 int rc;
1044 int len = Ustrlen(au->public_name);
1045 while (isspace(*p)) p++;
fcc8e047 1046
a7538db1
JH
1047 if (strncmpic(au->public_name, p, len) != 0 ||
1048 (p[len] != 0 && !isspace(p[len])))
1049 {
1050 while (*p != 0 && !isspace(*p)) p++;
1051 continue;
1052 }
fcc8e047 1053
a7538db1
JH
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. */
fcc8e047 1057
a7538db1
JH
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",
1064 au->name, rc);
fcc8e047 1065
a7538db1
JH
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. */
fcc8e047 1070
a7538db1
JH
1071 switch(rc)
1072 {
1073 case OK:
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);
1078 break;
1079
1080 /* Failure after writing a command */
1081
1082 case FAIL_SEND:
1083 return FAIL_SEND;
1084
1085 /* Failure after reading a response */
1086
1087 case FAIL:
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);
1091 break;
1092
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. */
1098
1099 case CANCELLED:
1100 if (*buffer != 0)
1101 log_write(0, LOG_MAIN, "%s authenticator cancelled "
1102 "authentication H=%s [%s] %s", au->name, host->name,
1103 host->address, buffer);
1104 break;
1105
1106 /* Internal problem, message in buffer. */
1107
1108 case ERROR:
895fbaf2
JH
1109 set_errno_nohost(addrlist, ERRNO_AUTHPROB, string_copy(buffer),
1110 DEFER, FALSE);
a7538db1
JH
1111 return ERROR;
1112 }
fcc8e047 1113
a7538db1
JH
1114 break; /* If not authenticated, try next authenticator */
1115 } /* Loop for scanning supported server mechanisms */
1116 } /* Loop for further authenticators */
fcc8e047 1117 }
a7538db1 1118 }
fcc8e047 1119
a7538db1 1120/* If we haven't authenticated, but are required to, give up. */
fcc8e047 1121
a7538db1
JH
1122if (require_auth == OK && !smtp_authenticated)
1123 {
895fbaf2 1124 set_errno_nohost(addrlist, ERRNO_AUTHFAIL,
a7538db1 1125 string_sprintf("authentication required but %s", fail_reason), DEFER,
895fbaf2 1126 FALSE);
a7538db1
JH
1127 return DEFER;
1128 }
4d8d62b9 1129
a7538db1 1130return OK;
fcc8e047
JH
1131}
1132
1133
1134/* Construct AUTH appendix string for MAIL TO */
1135/*
1136Arguments
1137 buffer to build string
1138 addrlist chain of potential addresses to deliver
1139 ob transport options
1140
1141Globals smtp_authenticated
1142 client_authenticated_sender
1143Return True on error, otherwise buffer has (possibly empty) terminated string
1144*/
1145
1146BOOL
1147smtp_mail_auth_str(uschar *buffer, unsigned bufsize, address_item *addrlist,
1148 smtp_transport_options_block *ob)
1149{
1150uschar *local_authenticated_sender = authenticated_sender;
1151
1152#ifdef notdef
1153 debug_printf("smtp_mail_auth_str: as<%s> os<%s> SA<%s>\n", authenticated_sender, ob->authenticated_sender, smtp_authenticated?"Y":"N");
1154#endif
1155
1156if (ob->authenticated_sender != NULL)
1157 {
1158 uschar *new = expand_string(ob->authenticated_sender);
1159 if (new == NULL)
1160 {
1161 if (!expand_string_forcedfail)
1162 {
1163 uschar *message = string_sprintf("failed to expand "
1164 "authenticated_sender: %s", expand_string_message);
895fbaf2 1165 set_errno_nohost(addrlist, ERRNO_EXPANDFAIL, message, DEFER, FALSE);
fcc8e047
JH
1166 return TRUE;
1167 }
1168 }
1169 else if (new[0] != 0) local_authenticated_sender = new;
1170 }
1171
1172/* Add the authenticated sender address if present */
1173
1174if ((smtp_authenticated || ob->authenticated_sender_force) &&
1175 local_authenticated_sender != NULL)
1176 {
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);
1181 }
1182else
1183 *buffer= 0;
1184
1185return FALSE;
1186}
1187
1188
1189
0e66b3b6 1190#ifdef EXPERIMENTAL_DANE
2d5fdd53
JH
1191/* Lookup TLSA record for host/port.
1192Return: 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
1196*/
1197
0e66b3b6 1198int
4b0fe319 1199tlsa_lookup(const host_item * host, dns_answer * dnsa, BOOL dane_required)
0e66b3b6
JH
1200{
1201/* move this out to host.c given the similarity to dns_lookup() ? */
1202uschar buffer[300];
55414b25 1203const uschar * fullname = buffer;
58c30e47
JH
1204int rc;
1205BOOL sec;
0e66b3b6
JH
1206
1207/* TLSA lookup string */
1208(void)sprintf(CS buffer, "_%d._tcp.%.256s", host->port, host->name);
1209
58c30e47
JH
1210rc = dns_lookup(dnsa, buffer, T_TLSA, &fullname);
1211sec = dns_is_secure(dnsa);
1212DEBUG(D_transport)
1213 debug_printf("TLSA lookup ret %d %sDNSSEC\n", rc, sec ? "" : "not ");
1214
1215switch (rc)
0e66b3b6 1216 {
0e66b3b6 1217 case DNS_SUCCEED:
58c30e47 1218 if (sec) return OK;
2d5fdd53 1219
58c30e47
JH
1220 log_write(0, LOG_MAIN, "DANE error: TLSA lookup not DNSSEC");
1221 /*FALLTHROUGH*/
2d5fdd53
JH
1222 case DNS_AGAIN:
1223 return DEFER; /* just defer this TLS'd conn */
1224
ef3a1a30
JH
1225 case DNS_NODATA: /* no TLSA RR for this lookup */
1226 case DNS_NOMATCH: /* no records at all for this lookup */
6b524204 1227 return dane_required ? FAIL : FAIL_FORCED;
2d5fdd53
JH
1228
1229 default:
1230 case DNS_FAIL:
1231 return dane_required ? FAIL : DEFER;
0e66b3b6 1232 }
0e66b3b6
JH
1233}
1234#endif
1235
1236
a39bd74d
JB
1237
1238typedef struct smtp_compare_s
1239{
1240 uschar *current_sender_address;
1241 struct transport_instance *tblock;
1242} smtp_compare_t;
1243
d093f8e5
JH
1244
1245/* Create a unique string that identifies this message, it is based on
1246sender_address, helo_data and tls_certificate if enabled.
1247*/
a39bd74d
JB
1248
1249static uschar *
1250smtp_local_identity(uschar * sender, struct transport_instance * tblock)
1251{
1252address_item * addr1;
1253uschar * if1 = US"";
1254uschar * helo1 = US"";
1255#ifdef SUPPORT_TLS
1256uschar * tlsc1 = US"";
1257#endif
1258uschar * save_sender_address = sender_address;
1259uschar * local_identity = NULL;
1260smtp_transport_options_block * ob =
1261 (smtp_transport_options_block *)tblock->options_block;
1262
1263sender_address = sender;
1264
1265addr1 = deliver_make_addr (sender, TRUE);
1266deliver_set_expansions(addr1);
1267
1268if (ob->interface)
1269 if1 = expand_string(ob->interface);
1270
1271if (ob->helo_data)
1272 helo1 = expand_string(ob->helo_data);
1273
1274#ifdef SUPPORT_TLS
1275if (ob->tls_certificate)
1276 tlsc1 = expand_string(ob->tls_certificate);
1277local_identity = string_sprintf ("%s^%s^%s", if1, helo1, tlsc1);
1278#else
1279local_identity = string_sprintf ("%s^%s", if1, helo1);
1280#endif
1281
1282deliver_set_expansions(NULL);
1283sender_address = save_sender_address;
1284
1285return local_identity;
1286}
1287
1288
1289
1290/* This routine is a callback that is called from transport_check_waiting.
1291This function will evaluate the incoming message versus the previous
1292message. If the incoming message is using a different local identity then
1293we will veto this new message. */
1294
1295static BOOL
1296smtp_are_same_identities(uschar * message_id, smtp_compare_t * s_compare)
1297{
dadff1d4
HSHR
1298uschar * message_local_identity,
1299 * current_local_identity,
1300 * new_sender_address;
1301
1302current_local_identity =
a39bd74d 1303 smtp_local_identity(s_compare->current_sender_address, s_compare->tblock);
a39bd74d 1304
dadff1d4
HSHR
1305if (!(new_sender_address = deliver_get_sender_address(message_id)))
1306 return 0;
1307
1308message_local_identity =
1309 smtp_local_identity(new_sender_address, s_compare->tblock);
a39bd74d
JB
1310
1311return Ustrcmp(current_local_identity, message_local_identity) == 0;
1312}
1313
1314
1315
e9166683
JH
1316static uschar
1317ehlo_response(uschar * buf, uschar checks)
9094b84b 1318{
e9166683
JH
1319size_t bsize = Ustrlen(buf);
1320
9094b84b 1321#ifdef SUPPORT_TLS
14de8063 1322if ( checks & OPTION_TLS
ff5aac2b 1323 && pcre_exec(regex_STARTTLS, NULL, CS buf, bsize, 0, PCRE_EOPT, NULL, 0) < 0)
14de8063 1324 checks &= ~OPTION_TLS;
9094b84b
JH
1325#endif
1326
14de8063 1327if ( checks & OPTION_IGNQ
ff5aac2b
JH
1328 && pcre_exec(regex_IGNOREQUOTA, NULL, CS buf, bsize, 0,
1329 PCRE_EOPT, NULL, 0) < 0)
14de8063 1330 checks &= ~OPTION_IGNQ;
9094b84b 1331
14de8063 1332if ( checks & OPTION_CHUNKING
f98442df 1333 && pcre_exec(regex_CHUNKING, NULL, CS buf, bsize, 0, PCRE_EOPT, NULL, 0) < 0)
14de8063 1334 checks &= ~OPTION_CHUNKING;
f98442df 1335
9094b84b 1336#ifndef DISABLE_PRDR
14de8063 1337if ( checks & OPTION_PRDR
ff5aac2b 1338 && pcre_exec(regex_PRDR, NULL, CS buf, bsize, 0, PCRE_EOPT, NULL, 0) < 0)
14de8063 1339 checks &= ~OPTION_PRDR;
9094b84b
JH
1340#endif
1341
1342#ifdef SUPPORT_I18N
14de8063 1343if ( checks & OPTION_UTF8
ff5aac2b 1344 && pcre_exec(regex_UTF8, NULL, CS buf, bsize, 0, PCRE_EOPT, NULL, 0) < 0)
14de8063 1345 checks &= ~OPTION_UTF8;
9094b84b
JH
1346#endif
1347
14de8063 1348if ( checks & OPTION_DSN
ff5aac2b 1349 && pcre_exec(regex_DSN, NULL, CS buf, bsize, 0, PCRE_EOPT, NULL, 0) < 0)
14de8063 1350 checks &= ~OPTION_DSN;
9094b84b 1351
14de8063 1352if ( checks & OPTION_PIPE
ff5aac2b
JH
1353 && pcre_exec(regex_PIPELINING, NULL, CS buf, bsize, 0,
1354 PCRE_EOPT, NULL, 0) < 0)
14de8063 1355 checks &= ~OPTION_PIPE;
9094b84b 1356
14de8063 1357if ( checks & OPTION_SIZE
ff5aac2b 1358 && pcre_exec(regex_SIZE, NULL, CS buf, bsize, 0, PCRE_EOPT, NULL, 0) < 0)
14de8063 1359 checks &= ~OPTION_SIZE;
9094b84b
JH
1360
1361return checks;
1362}
1363
1364
6d5c916c
JH
1365
1366/* Callback for emitting a BDAT data chunk header.
6d5c916c 1367
e027f545
JH
1368If given a nonzero size, first flush any buffered SMTP commands
1369then emit the command.
1370
d2aa036b
JH
1371Reap previous SMTP command responses if requested, and always reap
1372the response from a previous BDAT command.
1373
1374Args:
1375 tctx transport context
1376 chunk_size value for SMTP BDAT command
1377 flags
1378 tc_chunk_last add LAST option to SMTP BDAT command
1379 tc_reap_prev reap response to previous SMTP commands
6d5c916c
JH
1380
1381Returns: OK or ERROR
1382*/
1383
1384static int
d2aa036b
JH
1385smtp_chunk_cmd_callback(transport_ctx * tctx, unsigned chunk_size,
1386 unsigned flags)
6d5c916c
JH
1387{
1388smtp_transport_options_block * ob =
1389 (smtp_transport_options_block *)(tctx->tblock->options_block);
e9166683 1390smtp_context * sx = tctx->smtp_context;
e027f545
JH
1391int cmd_count = 0;
1392int prev_cmd_count;
6d5c916c 1393
4e910c01
JH
1394/* Write SMTP chunk header command. If not reaping responses, note that
1395there may be more writes (like, the chunk data) done soon. */
6d5c916c 1396
e027f545 1397if (chunk_size > 0)
87cb4a16 1398 {
4e910c01
JH
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" : "")
e027f545 1402 ) < 0) return ERROR;
87cb4a16
JH
1403 if (flags & tc_chunk_last)
1404 data_command = string_copy(big_buffer); /* Save for later error message */
1405 }
e027f545 1406
e9166683 1407prev_cmd_count = cmd_count += sx->cmd_count;
6d5c916c 1408
e027f545 1409/* Reap responses for any previous, but not one we just emitted */
6d5c916c 1410
e027f545
JH
1411if (chunk_size > 0)
1412 prev_cmd_count--;
e9166683 1413if (sx->pending_BDAT)
e027f545 1414 prev_cmd_count--;
6d5c916c 1415
e027f545 1416if (flags & tc_reap_prev && prev_cmd_count > 0)
6d5c916c 1417 {
58fc5fb2
JH
1418 DEBUG(D_transport) debug_printf("look for %d responses"
1419 " for previous pipelined cmds\n", prev_cmd_count);
6d5c916c 1420
e9166683 1421 switch(sync_responses(sx, prev_cmd_count, 0))
e027f545
JH
1422 {
1423 case 1: /* 2xx (only) => OK */
e9166683
JH
1424 case 3: sx->good_RCPT = TRUE; /* 2xx & 5xx => OK & progress made */
1425 case 2: sx->completed_addr = TRUE; /* 5xx (only) => progress made */
e027f545
JH
1426 case 0: break; /* No 2xx or 5xx, but no probs */
1427
1428 case -1: /* Timeout on RCPT */
1429 default: return ERROR; /* I/O error, or any MAIL/DATA error */
1430 }
1431 cmd_count = 1;
e9166683 1432 if (!sx->pending_BDAT)
e027f545 1433 pipelining_active = FALSE;
6d5c916c 1434 }
e027f545 1435
58fc5fb2 1436/* Reap response for an outstanding BDAT */
e027f545 1437
e9166683 1438if (sx->pending_BDAT)
e027f545 1439 {
58fc5fb2
JH
1440 DEBUG(D_transport) debug_printf("look for one response for BDAT\n");
1441
e9166683 1442 if (!smtp_read_response(&sx->inblock, sx->buffer, sizeof(sx->buffer), '2',
e027f545
JH
1443 ob->command_timeout))
1444 {
e9166683 1445 if (errno == 0 && sx->buffer[0] == '4')
e027f545
JH
1446 {
1447 errno = ERRNO_DATA4XX; /*XXX does this actually get used? */
36e55f49 1448 sx->addrlist->more_errno |=
e9166683 1449 ((sx->buffer[1] - '0')*10 + sx->buffer[2] - '0') << 8;
e027f545
JH
1450 }
1451 return ERROR;
1452 }
1453 cmd_count--;
e9166683 1454 sx->pending_BDAT = FALSE;
e027f545
JH
1455 pipelining_active = FALSE;
1456 }
1457else if (chunk_size > 0)
e9166683 1458 sx->pending_BDAT = TRUE;
e027f545
JH
1459
1460
e9166683 1461sx->cmd_count = cmd_count;
e027f545 1462return OK;
6d5c916c
JH
1463}
1464
1465
1466
0756eb3c 1467/*************************************************
d093f8e5 1468* Make connection for given message *
0756eb3c
PH
1469*************************************************/
1470
d093f8e5
JH
1471/*
1472Arguments:
1473 ctx connection context
d093f8e5
JH
1474 suppress_tls if TRUE, don't attempt a TLS connection - this is set for
1475 a second attempt after TLS initialization fails
d093f8e5
JH
1476
1477Returns: 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
1484 to expand
1485*/
1486int
e9166683 1487smtp_setup_conn(smtp_context * sx, BOOL suppress_tls)
d093f8e5
JH
1488{
1489#if defined(SUPPORT_TLS) && defined(EXPERIMENTAL_DANE)
1490dns_answer tlsa_dnsa;
1491#endif
1492BOOL pass_message = FALSE;
d093f8e5 1493uschar * message = NULL;
d093f8e5
JH
1494int yield = OK;
1495int rc;
1496
02b41d71 1497sx->ob = (smtp_transport_options_block *) sx->tblock->options_block;
d093f8e5
JH
1498
1499sx->lmtp = strcmpic(sx->ob->protocol, US"lmtp") == 0;
1500sx->smtps = strcmpic(sx->ob->protocol, US"smtps") == 0;
1501sx->ok = FALSE;
1502sx->send_rset = TRUE;
1503sx->send_quit = TRUE;
1504sx->setting_up = TRUE;
1505sx->esmtp = TRUE;
1506sx->esmtp_sent = FALSE;
59a286ef 1507#ifdef SUPPORT_I18N
d093f8e5 1508sx->utf8_needed = FALSE;
59a286ef 1509#endif
d093f8e5 1510sx->dsn_all_lasthop = TRUE;
59a286ef 1511#if defined(SUPPORT_TLS) && defined(EXPERIMENTAL_DANE)
d093f8e5
JH
1512sx->dane = FALSE;
1513sx->dane_required = verify_check_given_host(&sx->ob->hosts_require_dane, sx->host) == OK;
1514#endif
1515
1516if ((sx->max_rcpt = sx->tblock->max_addresses) == 0) sx->max_rcpt = 999999;
d093f8e5 1517sx->peer_offered = 0;
14de8063 1518sx->avoid_option = 0;
d093f8e5 1519sx->igquotstr = US"";
02b41d71 1520if (!sx->helo_data) sx->helo_data = sx->ob->helo_data;
d093f8e5
JH
1521#ifdef EXPERIMENTAL_DSN_INFO
1522sx->smtp_greeting = NULL;
1523sx->helo_response = NULL;
59a286ef
JH
1524#endif
1525
0756eb3c 1526smtp_command = US"initial connection";
d093f8e5 1527sx->buffer[0] = '\0';
0756eb3c
PH
1528
1529/* Set up the buffer for reading SMTP response packets. */
1530
d093f8e5
JH
1531sx->inblock.buffer = sx->inbuffer;
1532sx->inblock.buffersize = sizeof(sx->inbuffer);
1533sx->inblock.ptr = sx->inbuffer;
1534sx->inblock.ptrend = sx->inbuffer;
0756eb3c
PH
1535
1536/* Set up the buffer for holding SMTP commands while pipelining */
1537
d093f8e5
JH
1538sx->outblock.buffer = sx->outbuffer;
1539sx->outblock.buffersize = sizeof(sx->outbuffer);
1540sx->outblock.ptr = sx->outbuffer;
1541sx->outblock.cmd_count = 0;
1542sx->outblock.authenticating = FALSE;
0756eb3c 1543
6c512171
PH
1544/* Reset the parameters of a TLS session. */
1545
817d9f57
JH
1546tls_out.bits = 0;
1547tls_out.cipher = NULL; /* the one we may use for this transport */
9d1c15ef
JH
1548tls_out.ourcert = NULL;
1549tls_out.peercert = NULL;
817d9f57
JH
1550tls_out.peerdn = NULL;
1551#if defined(SUPPORT_TLS) && !defined(USE_GNUTLS)
1552tls_out.sni = NULL;
5b456975 1553#endif
018058b2 1554tls_out.ocsp = OCSP_NOT_REQ;
6c512171 1555
35aba663
JH
1556/* Flip the legacy TLS-related variables over to the outbound set in case
1557they're used in the context of the transport. Don't bother resetting
02b41d71
JH
1558afterward (when being used by a transport) as we're in a subprocess.
1559For verify, unflipped once the callout is dealt with */
35aba663
JH
1560
1561tls_modify_variables(&tls_out);
1562
061b7ebd 1563#ifndef SUPPORT_TLS
d093f8e5 1564if (sx->smtps)
061b7ebd 1565 {
d093f8e5 1566 set_errno_nohost(sx->addrlist, ERRNO_TLSFAILURE, US"TLS support not available",
895fbaf2 1567 DEFER, FALSE);
018058b2 1568 return ERROR;
061b7ebd
PP
1569 }
1570#endif
1571
0756eb3c
PH
1572/* Make a connection to the host if this isn't a continued delivery, and handle
1573the initial interaction and HELO/EHLO/LHLO. Connect timeout errors are handled
1574specially so they can be identified for retries. */
1575
58c30e47 1576if (!continue_hostname)
0756eb3c 1577 {
e9166683 1578 if (sx->verify)
02b41d71
JH
1579 HDEBUG(D_verify) debug_printf("interface=%s port=%d\n", sx->interface, sx->port);
1580
58c30e47 1581 /* Get the actual port the connection will use, into sx->host */
4311097e 1582
58c30e47 1583 smtp_port_for_connect(sx->host, sx->port);
0756eb3c 1584
0e66b3b6 1585#if defined(SUPPORT_TLS) && defined(EXPERIMENTAL_DANE)
58c30e47 1586 /* Do TLSA lookup for DANE */
0e66b3b6 1587 {
0e66b3b6
JH
1588 tls_out.dane_verified = FALSE;
1589 tls_out.tlsa_usage = 0;
1590
d093f8e5 1591 if (sx->host->dnssec == DS_YES)
0e66b3b6 1592 {
d093f8e5
JH
1593 if( sx->dane_required
1594 || verify_check_given_host(&sx->ob->hosts_try_dane, sx->host) == OK
0e66b3b6 1595 )
d093f8e5 1596 switch (rc = tlsa_lookup(sx->host, &tlsa_dnsa, sx->dane_required))
4b0fe319 1597 {
58c30e47
JH
1598 case OK: sx->dane = TRUE;
1599 sx->ob->tls_tempfail_tryclear = FALSE;
1600 break;
2d5fdd53 1601 case FAIL_FORCED: break;
d093f8e5 1602 default: set_errno_nohost(sx->addrlist, ERRNO_DNSDEFER,
2d5fdd53
JH
1603 string_sprintf("DANE error: tlsa lookup %s",
1604 rc == DEFER ? "DEFER" : "FAIL"),
1605 rc, FALSE);
1606 return rc;
4b0fe319 1607 }
0e66b3b6 1608 }
d093f8e5 1609 else if (sx->dane_required)
0e66b3b6 1610 {
d093f8e5
JH
1611 set_errno_nohost(sx->addrlist, ERRNO_DNSDEFER,
1612 string_sprintf("DANE error: %s lookup not DNSSEC", sx->host->name),
895fbaf2 1613 FAIL, FALSE);
4b0fe319 1614 return FAIL;
0e66b3b6 1615 }
0e66b3b6
JH
1616 }
1617#endif /*DANE*/
1618
58c30e47
JH
1619 /* Make the TCP connection */
1620
1621 sx->inblock.sock = sx->outblock.sock =
1622 smtp_connect(sx->host, sx->host_af, sx->interface,
1623 sx->ob->connect_timeout, sx->tblock);
1624
1625 if (sx->inblock.sock < 0)
1626 {
1627 uschar * msg = NULL;
1628 if (sx->verify)
1629 {
1630 msg = US strerror(errno);
1631 HDEBUG(D_verify) debug_printf("connect: %s\n", msg);
1632 }
1633 set_errno_nohost(sx->addrlist,
1634 errno == ETIMEDOUT ? ERRNO_CONNECTTIMEOUT : errno,
1635 sx->verify ? string_sprintf("could not connect: %s", msg)
1636 : NULL,
1637 DEFER, FALSE);
1638 sx->send_quit = FALSE;
1639 return DEFER;
1640 }
1641
41c7c167
PH
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. */
1645
02b41d71
JH
1646 if (sx->helo_data)
1647 if (!(sx->helo_data = expand_string(sx->helo_data)))
e9166683 1648 if (sx->verify)
02b41d71
JH
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);
1652
8c5d388a 1653#ifdef SUPPORT_I18N
d093f8e5 1654 if (sx->helo_data)
810d16ad 1655 {
02b41d71
JH
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)
e9166683 1660 if (sx->verify)
02b41d71
JH
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);
1664 else
1665 sx->helo_data = NULL;
810d16ad
JH
1666 }
1667#endif
41c7c167 1668
0756eb3c
PH
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. */
1672
d093f8e5 1673 if (!sx->smtps)
061b7ebd 1674 {
8d330698
JH
1675 BOOL good_response;
1676
1677#ifdef TCP_QUICKACK
d093f8e5 1678 (void) setsockopt(sx->inblock.sock, IPPROTO_TCP, TCP_QUICKACK, US &off, sizeof(off));
8d330698 1679#endif
d093f8e5
JH
1680 good_response = smtp_read_response(&sx->inblock, sx->buffer, sizeof(sx->buffer),
1681 '2', sx->ob->command_timeout);
895fbaf2 1682#ifdef EXPERIMENTAL_DSN_INFO
d093f8e5 1683 sx->smtp_greeting = string_copy(sx->buffer);
895fbaf2
JH
1684#endif
1685 if (!good_response) goto RESPONSE_FAILED;
0756eb3c 1686
0cbf2b82 1687#ifndef DISABLE_EVENT
b30275b8 1688 {
805c9d53 1689 uschar * s;
d093f8e5
JH
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);
b30275b8 1693 if (s)
a7538db1 1694 {
d093f8e5 1695 set_errno_nohost(sx->addrlist, ERRNO_EXPANDFAIL,
b30275b8 1696 string_sprintf("deferred by smtp:connect event expansion: %s", s),
895fbaf2 1697 DEFER, FALSE);
a7538db1
JH
1698 yield = DEFER;
1699 goto SEND_QUIT;
1700 }
b30275b8 1701 }
a7538db1
JH
1702#endif
1703
061b7ebd
PP
1704 /* Now check if the helo_data expansion went well, and sign off cleanly if
1705 it didn't. */
41c7c167 1706
d093f8e5 1707 if (!sx->helo_data)
061b7ebd 1708 {
d093f8e5 1709 message = string_sprintf("failed to expand helo_data: %s",
061b7ebd 1710 expand_string_message);
d093f8e5 1711 set_errno_nohost(sx->addrlist, ERRNO_EXPANDFAIL, message, DEFER, FALSE);
061b7ebd
PP
1712 yield = DEFER;
1713 goto SEND_QUIT;
1714 }
41c7c167
PH
1715 }
1716
0756eb3c 1717/** Debugging without sending a message
d093f8e5 1718sx->addrlist->transport_return = DEFER;
0756eb3c
PH
1719goto SEND_QUIT;
1720**/
1721
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. */
1724
1725 smtp_command = big_buffer;
1726
1727 /* Tell the remote who we are...
1728
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.
1735
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
1738 the TLS stuff.
1739
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.
1746
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. */
1751
d093f8e5 1752 sx->esmtp = verify_check_given_host(&sx->ob->hosts_avoid_esmtp, sx->host) != OK;
0756eb3c 1753
061b7ebd
PP
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. */
a7538db1 1757#ifdef SUPPORT_TLS
d093f8e5 1758 if (sx->smtps)
061b7ebd 1759 {
14de8063 1760 smtp_peer_options |= OPTION_TLS;
061b7ebd 1761 suppress_tls = FALSE;
d093f8e5 1762 sx->ob->tls_tempfail_tryclear = FALSE;
061b7ebd
PP
1763 smtp_command = US"SSL-on-connect";
1764 goto TLS_NEGOTIATE;
1765 }
a7538db1 1766#endif
061b7ebd 1767
d093f8e5 1768 if (sx->esmtp)
0756eb3c 1769 {
4e910c01 1770 if (smtp_write_command(&sx->outblock, SCMD_FLUSH, "%s %s\r\n",
d093f8e5 1771 sx->lmtp ? "LHLO" : "EHLO", sx->helo_data) < 0)
0756eb3c 1772 goto SEND_FAILED;
d093f8e5
JH
1773 sx->esmtp_sent = TRUE;
1774 if (!smtp_read_response(&sx->inblock, sx->buffer, sizeof(sx->buffer), '2',
1775 sx->ob->command_timeout))
0756eb3c 1776 {
d093f8e5 1777 if (errno != 0 || sx->buffer[0] == 0 || sx->lmtp)
895fbaf2
JH
1778 {
1779#ifdef EXPERIMENTAL_DSN_INFO
d093f8e5 1780 sx->helo_response = string_copy(sx->buffer);
895fbaf2
JH
1781#endif
1782 goto RESPONSE_FAILED;
1783 }
d093f8e5 1784 sx->esmtp = FALSE;
0756eb3c 1785 }
895fbaf2 1786#ifdef EXPERIMENTAL_DSN_INFO
d093f8e5 1787 sx->helo_response = string_copy(sx->buffer);
895fbaf2 1788#endif
0756eb3c
PH
1789 }
1790 else
0756eb3c
PH
1791 DEBUG(D_transport)
1792 debug_printf("not sending EHLO (host matches hosts_avoid_esmtp)\n");
0756eb3c 1793
d093f8e5 1794 if (!sx->esmtp)
0756eb3c 1795 {
895fbaf2 1796 BOOL good_response;
d093f8e5
JH
1797 int n = sizeof(sx->buffer);
1798 uschar * rsp = sx->buffer;
a57ce043 1799
d093f8e5
JH
1800 if (sx->esmtp_sent && (n = Ustrlen(sx->buffer)) < sizeof(sx->buffer)/2)
1801 { rsp = sx->buffer + n + 1; n = sizeof(sx->buffer) - n; }
895fbaf2 1802
4e910c01 1803 if (smtp_write_command(&sx->outblock, SCMD_FLUSH, "HELO %s\r\n", sx->helo_data) < 0)
0756eb3c 1804 goto SEND_FAILED;
d093f8e5
JH
1805 good_response = smtp_read_response(&sx->inblock, rsp, n,
1806 '2', sx->ob->command_timeout);
895fbaf2 1807#ifdef EXPERIMENTAL_DSN_INFO
d093f8e5 1808 sx->helo_response = string_copy(rsp);
895fbaf2 1809#endif
a57ce043
JH
1810 if (!good_response)
1811 {
1812 /* Handle special logging for a closed connection after HELO
1813 when had previously sent EHLO */
1814
d093f8e5 1815 if (rsp != sx->buffer && rsp[0] == 0 && (errno == 0 || errno == ECONNRESET))
a57ce043 1816 {
de6273b4
JH
1817 errno = ERRNO_SMTPCLOSED;
1818 goto EHLOHELO_FAILED;
a57ce043 1819 }
d093f8e5 1820 Ustrncpy(sx->buffer, rsp, sizeof(sx->buffer)/2);
a57ce043
JH
1821 goto RESPONSE_FAILED;
1822 }
0756eb3c
PH
1823 }
1824
14de8063 1825 sx->avoid_option = sx->peer_offered = smtp_peer_options = 0;
2d14f397 1826
d093f8e5 1827 if (sx->esmtp || sx->lmtp)
2d14f397 1828 {
e9166683 1829 sx->peer_offered = ehlo_response(sx->buffer,
14de8063 1830 OPTION_TLS /* others checked later */
9094b84b 1831 );
f1513293 1832
0756eb3c
PH
1833 /* Set tls_offered if the response to EHLO specifies support for STARTTLS. */
1834
a7538db1 1835#ifdef SUPPORT_TLS
14de8063 1836 smtp_peer_options |= sx->peer_offered & OPTION_TLS;
7ade712c 1837#endif
2d14f397 1838 }
0756eb3c
PH
1839 }
1840
57cc2785
JH
1841/* For continuing deliveries down the same channel, having re-exec'd the socket
1842is the standard input; for a socket held open from verify it is recorded
1843in 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).
1845Set up the pointer to where subsequent commands will be left, for
2d14f397 1846error messages. Note that smtp_peer_options will have been
0756eb3c
PH
1847set from the command line if they were set in the process that passed the
1848connection on. */
1849
895fbaf2 1850/*XXX continue case needs to propagate DSN_INFO, prob. in deliver.c
4c04137d 1851as the continue goes via transport_pass_socket() and doublefork and exec.
895fbaf2
JH
1852It does not wait. Unclear how we keep separate host's responses
1853separate - we could match up by host ip+port as a bodge. */
1854
0756eb3c
PH
1855else
1856 {
57cc2785
JH
1857 if (cutthrough.fd >= 0 && cutthrough.callout_hold_only)
1858 {
1859 sx->inblock.sock = sx->outblock.sock = cutthrough.fd;
1860 sx->host->port = sx->port = cutthrough.host.port;
1861 }
1862 else
1863 {
1864 sx->inblock.sock = sx->outblock.sock = 0; /* stdin */
a843a57e 1865 smtp_port_for_connect(sx->host, sx->port); /* Record the port that was used */
57cc2785 1866 }
0756eb3c 1867 smtp_command = big_buffer;
02b41d71 1868 sx->helo_data = NULL; /* ensure we re-expand ob->helo_data */
875512a3 1869
57cc2785
JH
1870 /* For a continued connection with TLS being proxied for us, or a
1871 held-open verify connection with TLS, nothing more to do. */
875512a3 1872
57cc2785
JH
1873 if ( continue_proxy_cipher
1874 || (cutthrough.fd >= 0 && cutthrough.callout_hold_only && cutthrough.is_tls)
1875 )
875512a3
JH
1876 {
1877 sx->peer_offered = smtp_peer_options;
14de8063 1878 pipelining_active = !!(smtp_peer_options & OPTION_PIPE);
57cc2785
JH
1879 HDEBUG(D_transport) debug_printf("continued connection, %s TLS\n",
1880 continue_proxy_cipher ? "proxied" : "verify conn with");
875512a3
JH
1881 return OK;
1882 }
1883 HDEBUG(D_transport) debug_printf("continued connection, no TLS\n");
0756eb3c
PH
1884 }
1885
1886/* If TLS is available on this connection, whether continued or not, attempt to
1887start up a TLS session, unless the host is in hosts_avoid_tls. If successful,
1888send another EHLO - the server may give a different answer in secure mode. We
1889use a separate buffer for reading the response to STARTTLS so that if it is
1890negative, the original EHLO data is available for subsequent analysis, should
1891the client not be required to use TLS. If the response is bad, copy the buffer
1892for error analysis. */
1893
1894#ifdef SUPPORT_TLS
14de8063 1895if ( smtp_peer_options & OPTION_TLS
5130845b 1896 && !suppress_tls
02b41d71 1897 && verify_check_given_host(&sx->ob->hosts_avoid_tls, sx->host) != OK
e9166683 1898 && ( !sx->verify
02b41d71
JH
1899 || verify_check_given_host(&sx->ob->hosts_verify_avoid_tls, sx->host) != OK
1900 ) )
0756eb3c
PH
1901 {
1902 uschar buffer2[4096];
4e910c01 1903 if (smtp_write_command(&sx->outblock, SCMD_FLUSH, "STARTTLS\r\n") < 0)
0756eb3c
PH
1904 goto SEND_FAILED;
1905
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). */
1912
d093f8e5
JH
1913 if (!smtp_read_response(&sx->inblock, buffer2, sizeof(buffer2), '2',
1914 sx->ob->command_timeout))
0756eb3c 1915 {
4b0fe319
JH
1916 if ( errno != 0
1917 || buffer2[0] == 0
d093f8e5 1918 || (buffer2[0] == '4' && !sx->ob->tls_tempfail_tryclear)
4b0fe319 1919 )
0dda4340 1920 {
d093f8e5 1921 Ustrncpy(sx->buffer, buffer2, sizeof(sx->buffer));
9e7e0f6a 1922 sx->buffer[sizeof(sx->buffer)-1] = '\0';
0756eb3c 1923 goto RESPONSE_FAILED;
0dda4340 1924 }
0756eb3c
PH
1925 }
1926
1927 /* STARTTLS accepted: try to negotiate a TLS session. */
1928
1929 else
061b7ebd 1930 TLS_NEGOTIATE:
0756eb3c 1931 {
d093f8e5 1932 address_item * addr;
cf0c6164
JH
1933 uschar * errstr;
1934 int rc = tls_client_start(sx->inblock.sock, sx->host, sx->addrlist, sx->tblock,
0e66b3b6 1935# ifdef EXPERIMENTAL_DANE
cf0c6164 1936 sx->dane ? &tlsa_dnsa : NULL,
0e66b3b6 1937# endif
cf0c6164 1938 &errstr);
0756eb3c
PH
1939
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. */
1943
1944 if (rc != OK)
1945 {
6ebd79ec 1946# ifdef EXPERIMENTAL_DANE
d093f8e5 1947 if (sx->dane) log_write(0, LOG_MAIN,
cf0c6164
JH
1948 "DANE attempt failed; TLS connection to %s [%s]: %s",
1949 sx->host->name, sx->host->address, errstr);
6ebd79ec
JH
1950# endif
1951
de6273b4 1952 errno = ERRNO_TLSFAILURE;
cf0c6164 1953 message = string_sprintf("TLS session: %s", errstr);
d093f8e5 1954 sx->send_quit = FALSE;
0756eb3c
PH
1955 goto TLS_FAILED;
1956 }
1957
1958 /* TLS session is set up */
1959
2d14f397 1960 smtp_peer_options_wrap = smtp_peer_options;
d093f8e5 1961 for (addr = sx->addrlist; addr; addr = addr->next)
5ca2a9a1
PH
1962 if (addr->transport_return == PENDING_DEFER)
1963 {
817d9f57 1964 addr->cipher = tls_out.cipher;
9d1c15ef
JH
1965 addr->ourcert = tls_out.ourcert;
1966 addr->peercert = tls_out.peercert;
817d9f57 1967 addr->peerdn = tls_out.peerdn;
018058b2 1968 addr->ocsp = tls_out.ocsp;
5ca2a9a1 1969 }
0756eb3c
PH
1970 }
1971 }
1972
061b7ebd
PP
1973/* if smtps, we'll have smtp_command set to something else; always safe to
1974reset it here. */
1975smtp_command = big_buffer;
1976
41c7c167
PH
1977/* If we started TLS, redo the EHLO/LHLO exchange over the secure channel. If
1978helo_data is null, we are dealing with a connection that was passed from
1979another process, and so we won't have expanded helo_data above. We have to
1980expand it here. $sending_ip_address and $sending_port are set up right at the
1981start of the Exim process (in exim.c). */
0756eb3c 1982
817d9f57 1983if (tls_out.active >= 0)
0756eb3c 1984 {
061b7ebd 1985 char *greeting_cmd;
895fbaf2
JH
1986 BOOL good_response;
1987
d093f8e5 1988 if (!sx->helo_data && !(sx->helo_data = expand_string(sx->ob->helo_data)))
41c7c167 1989 {
d093f8e5
JH
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);
1993 yield = DEFER;
1994 goto SEND_QUIT;
41c7c167
PH
1995 }
1996
0d0e4455 1997 /* For SMTPS we need to wait for the initial OK response. */
d093f8e5 1998 if (sx->smtps)
061b7ebd 1999 {
d093f8e5
JH
2000 good_response = smtp_read_response(&sx->inblock, sx->buffer, sizeof(sx->buffer),
2001 '2', sx->ob->command_timeout);
895fbaf2 2002#ifdef EXPERIMENTAL_DSN_INFO
d093f8e5 2003 sx->smtp_greeting = string_copy(sx->buffer);
895fbaf2
JH
2004#endif
2005 if (!good_response) goto RESPONSE_FAILED;
0d0e4455
PP
2006 }
2007
d093f8e5 2008 if (sx->esmtp)
0d0e4455
PP
2009 greeting_cmd = "EHLO";
2010 else
2011 {
2012 greeting_cmd = "HELO";
2013 DEBUG(D_transport)
2014 debug_printf("not sending EHLO (host matches hosts_avoid_esmtp)\n");
061b7ebd
PP
2015 }
2016
4e910c01 2017 if (smtp_write_command(&sx->outblock, SCMD_FLUSH, "%s %s\r\n",
d093f8e5 2018 sx->lmtp ? "LHLO" : greeting_cmd, sx->helo_data) < 0)
0756eb3c 2019 goto SEND_FAILED;
d093f8e5
JH
2020 good_response = smtp_read_response(&sx->inblock, sx->buffer, sizeof(sx->buffer),
2021 '2', sx->ob->command_timeout);
895fbaf2 2022#ifdef EXPERIMENTAL_DSN_INFO
d093f8e5 2023 sx->helo_response = string_copy(sx->buffer);
895fbaf2
JH
2024#endif
2025 if (!good_response) goto RESPONSE_FAILED;
2d14f397 2026 smtp_peer_options = 0;
0756eb3c
PH
2027 }
2028
2029/* If the host is required to use a secure channel, ensure that we
2030have one. */
2031
d093f8e5 2032else if ( sx->smtps
0e66b3b6 2033# ifdef EXPERIMENTAL_DANE
d093f8e5 2034 || sx->dane
0e66b3b6 2035# endif
d093f8e5 2036 || verify_check_given_host(&sx->ob->hosts_require_tls, sx->host) == OK
7a31d643 2037 )
0756eb3c 2038 {
de6273b4 2039 errno = ERRNO_TLSREQUIRED;
c562fd30 2040 message = string_sprintf("a TLS session is required, but %s",
14de8063 2041 smtp_peer_options & OPTION_TLS
2d14f397 2042 ? "an attempt to start TLS failed" : "the server did not offer TLS support");
0756eb3c
PH
2043 goto TLS_FAILED;
2044 }
0e66b3b6 2045#endif /*SUPPORT_TLS*/
0756eb3c
PH
2046
2047/* If TLS is active, we have just started it up and re-done the EHLO command,
2048so its response needs to be analyzed. If TLS is not active and this is a
2049continued session down a previously-used socket, we haven't just done EHLO, so
2050we skip this. */
2051
2052if (continue_hostname == NULL
a7538db1 2053#ifdef SUPPORT_TLS
817d9f57 2054 || tls_out.active >= 0
a7538db1 2055#endif
0756eb3c
PH
2056 )
2057 {
d093f8e5 2058 if (sx->esmtp || sx->lmtp)
2d14f397 2059 {
e9166683 2060 sx->peer_offered = ehlo_response(sx->buffer,
d093f8e5 2061 0 /* no TLS */
14de8063
JH
2062 | (sx->lmtp && sx->ob->lmtp_ignore_quota ? OPTION_IGNQ : 0)
2063 | OPTION_CHUNKING
2064 | OPTION_PRDR
9094b84b 2065#ifdef SUPPORT_I18N
14de8063 2066 | (sx->addrlist->prop.utf8_msg ? OPTION_UTF8 : 0)
d093f8e5
JH
2067 /*XXX if we hand peercaps on to continued-conn processes,
2068 must not depend on this addr */
9094b84b 2069#endif
14de8063
JH
2070 | OPTION_DSN
2071 | OPTION_PIPE
2072 | (sx->ob->size_addition >= 0 ? OPTION_SIZE : 0)
9094b84b
JH
2073 );
2074
2d14f397
JH
2075 /* Set for IGNOREQUOTA if the response to LHLO specifies support and the
2076 lmtp_ignore_quota option was set. */
f1513293 2077
14de8063 2078 sx->igquotstr = sx->peer_offered & OPTION_IGNQ ? US" IGNOREQUOTA" : US"";
f1513293 2079
2d14f397
JH
2080 /* If the response to EHLO specified support for the SIZE parameter, note
2081 this, provided size_addition is non-negative. */
f1513293 2082
14de8063 2083 smtp_peer_options |= sx->peer_offered & OPTION_SIZE;
0756eb3c 2084
2d14f397
JH
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. */
0756eb3c 2088
14de8063 2089 if ( sx->peer_offered & OPTION_PIPE
d093f8e5 2090 && verify_check_given_host(&sx->ob->hosts_avoid_pipelining, sx->host) != OK)
14de8063 2091 smtp_peer_options |= OPTION_PIPE;
0756eb3c 2092
2d14f397 2093 DEBUG(D_transport) debug_printf("%susing PIPELINING\n",
14de8063 2094 smtp_peer_options & OPTION_PIPE ? "" : "not ");
0756eb3c 2095
14de8063 2096 if ( sx->peer_offered & OPTION_CHUNKING
d093f8e5 2097 && verify_check_given_host(&sx->ob->hosts_try_chunking, sx->host) != OK)
14de8063 2098 sx->peer_offered &= ~OPTION_CHUNKING;
f98442df 2099
14de8063 2100 if (sx->peer_offered & OPTION_CHUNKING)
2d14f397 2101 {DEBUG(D_transport) debug_printf("CHUNKING usable\n");}
0756eb3c 2102
8ccd00b1 2103#ifndef DISABLE_PRDR
14de8063 2104 if ( sx->peer_offered & OPTION_PRDR
d093f8e5 2105 && verify_check_given_host(&sx->ob->hosts_try_prdr, sx->host) != OK)
14de8063 2106 sx->peer_offered &= ~OPTION_PRDR;
fd98a5c6 2107
14de8063 2108 if (sx->peer_offered & OPTION_PRDR)
2d14f397 2109 {DEBUG(D_transport) debug_printf("PRDR usable\n");}
fd98a5c6
JH
2110#endif
2111
2d14f397 2112 /* Note if the server supports DSN */
14de8063 2113 smtp_peer_options |= sx->peer_offered & OPTION_DSN;
2d14f397 2114 DEBUG(D_transport) debug_printf("%susing DSN\n",
14de8063 2115 sx->peer_offered & OPTION_DSN ? "" : "not ");
6c1c3d1d 2116
2d14f397
JH
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. */
0756eb3c 2121
d093f8e5
JH
2122 switch (yield = smtp_auth(sx->buffer, sizeof(sx->buffer), sx->addrlist, sx->host,
2123 sx->ob, sx->esmtp, &sx->inblock, &sx->outblock))
2d14f397
JH
2124 {
2125 default: goto SEND_QUIT;
2126 case OK: break;
2127 case FAIL_SEND: goto SEND_FAILED;
2128 case FAIL: goto RESPONSE_FAILED;
2129 }
0756eb3c
PH
2130 }
2131 }
14de8063 2132pipelining_active = !!(smtp_peer_options & OPTION_PIPE);
0756eb3c
PH
2133
2134/* The setting up of the SMTP call is now complete. Any subsequent errors are
2135message-specific. */
2136
d093f8e5 2137sx->setting_up = FALSE;
0756eb3c 2138
8c5d388a 2139#ifdef SUPPORT_I18N
d093f8e5 2140if (sx->addrlist->prop.utf8_msg)
9094b84b 2141 {
d093f8e5
JH
2142 sx->utf8_needed = !sx->addrlist->prop.utf8_downcvt
2143 && !sx->addrlist->prop.utf8_downcvt_maybe;
2144 DEBUG(D_transport) if (!sx->utf8_needed)
59a286ef 2145 debug_printf("utf8: %s downconvert\n",
d093f8e5 2146 sx->addrlist->prop.utf8_downcvt ? "mandatory" : "optional");
9094b84b
JH
2147 }
2148
7ade712c 2149/* If this is an international message we need the host to speak SMTPUTF8 */
14de8063 2150if (sx->utf8_needed && !(sx->peer_offered & OPTION_UTF8))
7ade712c
JH
2151 {
2152 errno = ERRNO_UTF8_FWD;
2153 goto RESPONSE_FAILED;
2154 }
2155#endif
2156
d093f8e5
JH
2157return OK;
2158
2159
2160 {
2161 int code;
d093f8e5
JH
2162
2163 RESPONSE_FAILED:
d093f8e5 2164 message = NULL;
de6273b4 2165 sx->send_quit = check_response(sx->host, &errno, sx->addrlist->more_errno,
d093f8e5
JH
2166 sx->buffer, &code, &message, &pass_message);
2167 goto FAILED;
d093f8e5
JH
2168
2169 SEND_FAILED:
d093f8e5
JH
2170 code = '4';
2171 message = US string_sprintf("send() to %s [%s] failed: %s",
829dd842 2172 sx->host->name, sx->host->address, strerror(errno));
d093f8e5
JH
2173 sx->send_quit = FALSE;
2174 goto FAILED;
d093f8e5
JH
2175
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
829dd842 2178 in message and errno, and setting_up will always be true. Treat as
d093f8e5
JH
2179 a temporary error. */
2180
de6273b4
JH
2181 EHLOHELO_FAILED:
2182 code = '4';
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;
2186 goto FAILED;
2187
d093f8e5
JH
2188#ifdef SUPPORT_TLS
2189 TLS_FAILED:
de6273b4
JH
2190 code = '4';
2191 goto FAILED;
d093f8e5
JH
2192#endif
2193
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
e69636bc
JH
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.
2200
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? */
d093f8e5 2207
de6273b4 2208FAILED:
d093f8e5 2209 sx->ok = FALSE; /* For when reached by GOTO */
e69636bc
JH
2210 set_errno(sx->addrlist, errno, message,
2211 sx->host->next
2212 ? DEFER
2213 : code == '5'
d093f8e5 2214#ifdef SUPPORT_I18N
e69636bc 2215 || errno == ERRNO_UTF8_FWD
d093f8e5 2216#endif
e69636bc
JH
2217 ? FAIL : DEFER,
2218 pass_message, sx->host
d093f8e5
JH
2219#ifdef EXPERIMENTAL_DSN_INFO
2220 , sx->smtp_greeting, sx->helo_response
2221#endif
2222 );
e69636bc 2223 yield = DEFER;
d093f8e5
JH
2224 }
2225
2226
2227SEND_QUIT:
2228
2229if (sx->send_quit)
4e910c01 2230 (void)smtp_write_command(&sx->outblock, SCMD_FLUSH, "QUIT\r\n");
d093f8e5 2231
d093f8e5
JH
2232#ifdef SUPPORT_TLS
2233tls_close(FALSE, TRUE);
2234#endif
2235
2236/* Close the socket, and return the appropriate value, first setting
2237works because the NULL setting is passed back to the calling process, and
2238remote_max_parallel is forced to 1 when delivering over an existing connection,
b7d3afcf 2239*/
d093f8e5 2240
e1d04f48 2241HDEBUG(D_transport|D_acl|D_v) debug_printf_indent(" SMTP(close)>>\n");
d093f8e5
JH
2242if (sx->send_quit)
2243 {
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 */
02b41d71 2248 sx->send_quit = FALSE;
d093f8e5
JH
2249 }
2250(void)close(sx->inblock.sock);
02b41d71 2251sx->inblock.sock = sx->outblock.sock = -1;
d093f8e5
JH
2252
2253#ifndef DISABLE_EVENT
2254(void) event_raise(sx->tblock->event_action, US"tcp:close", NULL);
2255#endif
2256
2257continue_transport = NULL;
2258continue_hostname = NULL;
2259return yield;
2260}
2261
2262
9be4572b
JH
2263
2264
2265/* Create the string of options that will be appended to the MAIL FROM:
2266in the connection context buffer */
2267
2268static int
2269build_mailcmd_options(smtp_context * sx, address_item * addrlist)
2270{
2271uschar * p = sx->buffer;
2272address_item * addr;
2273int address_count;
2274
2275*p = 0;
2276
14de8063 2277/* If we know the receiving MTA supports the SIZE qualification, and we know it,
9be4572b
JH
2278send it, adding something to the message size to allow for imprecision
2279and things that get added en route. Exim keeps the number of lines
2280in a message, so we can give an accurate value for the original message, but we
2281need some additional to handle added headers. (Double "." characters don't get
2282included in the count.) */
2283
14de8063
JH
2284if ( message_size > 0
2285 && sx->peer_offered & OPTION_SIZE && !(sx->avoid_option & OPTION_SIZE))
9be4572b 2286 {
328c5688
JH
2287/*XXX problem here under spool_files_wireformat?
2288Or just forget about lines? Or inflate by a fixed proportion? */
2289
9be4572b
JH
2290 sprintf(CS p, " SIZE=%d", message_size+message_linecount+sx->ob->size_addition);
2291 while (*p) p++;
2292 }
2293
2294#ifndef DISABLE_PRDR
2295/* If it supports Per-Recipient Data Reponses, and we have omre than one recipient,
2296request that */
2297
2298sx->prdr_active = FALSE;
14de8063 2299if (sx->peer_offered & OPTION_PRDR)
9be4572b
JH
2300 for (addr = addrlist; addr; addr = addr->next)
2301 if (addr->transport_return == PENDING_DEFER)
2302 {
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;
2308 break;
2309 }
2310 break;
2311 }
2312#endif
2313
2314#ifdef SUPPORT_I18N
2315/* If it supports internationalised messages, and this meesage need that,
2316request it */
2317
14de8063 2318if ( sx->peer_offered & OPTION_UTF8
9be4572b
JH
2319 && addrlist->prop.utf8_msg
2320 && !addrlist->prop.utf8_downcvt
2321 )
2322 Ustrcpy(p, " SMTPUTF8"), p += 9;
2323#endif
2324
2325/* check if all addresses have DSN-lasthop flag; do not send RET and ENVID if so */
2326for (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)
2329 {
2330 address_count++;
2331 if (!(addr->dsn_flags & rf_dsnlasthop))
2332 {
2333 sx->dsn_all_lasthop = FALSE;
2334 break;
2335 }
2336 }
2337
2338/* Add any DSN flags to the mail command */
2339
14de8063 2340if (sx->peer_offered & OPTION_DSN && !sx->dsn_all_lasthop)
9be4572b
JH
2341 {
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; }
2346
2347 if (dsn_envid)
2348 {
2349 string_format(p, sizeof(sx->buffer) - (p-sx->buffer), " ENVID=%s", dsn_envid);
2350 while (*p) p++;
2351 }
2352 }
2353
2354/* If an authenticated_sender override has been specified for this transport
2355instance, expand it. If the expansion is forced to fail, and there was already
2356an authenticated_sender for this message, the original value will be used.
2357Other expansion failures are serious. An empty result is ignored, but there is
2358otherwise no check - this feature is expected to be used with LMTP and other
2359cases where non-standard addresses (e.g. without domains) might be required. */
2360
2361if (smtp_mail_auth_str(p, sizeof(sx->buffer) - (p-sx->buffer), addrlist, sx->ob))
2362 return ERROR;
2363
2364return OK;
2365}
2366
2367
2368static void
2369build_rcptcmd_options(smtp_context * sx, const address_item * addr)
2370{
2371uschar * p = sx->buffer;
2372*p = 0;
2373
2374/* Add any DSN flags to the rcpt command */
2375
14de8063 2376if (sx->peer_offered & OPTION_DSN && !(addr->dsn_flags & rf_dsnlasthop))
9be4572b
JH
2377 {
2378 if (addr->dsn_flags & rf_dsnflags)
2379 {
2380 int i;
2381 BOOL first = TRUE;
2382
2383 Ustrcpy(p, " NOTIFY=");
2384 while (*p) p++;
2385 for (i = 0; i < nelem(rf_list); i++) if (addr->dsn_flags & rf_list[i])
2386 {
2387 if (!first) *p++ = ',';
2388 first = FALSE;
2389 Ustrcpy(p, rf_names[i]);
2390 while (*p) p++;
2391 }
2392 }
2393
2394 if (addr->dsn_orcpt)
2395 {
2396 string_format(p, sizeof(sx->buffer) - (p-sx->buffer), " ORCPT=%s",
2397 addr->dsn_orcpt);
2398 while (*p) p++;
2399 }
2400 }
2401}
2402
2403
d9c3c8ed
JH
2404
2405/*
2406Return:
e9166683
JH
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
2412 -5 transmit failed
d9c3c8ed
JH
2413 */
2414
2415int
2416smtp_write_mail_and_rcpt_cmds(smtp_context * sx, int * yield)
2417{
2418address_item * addr;
2419int address_count;
2420int rc;
2421
2422if (build_mailcmd_options(sx, sx->first_addr) != OK)
2423 {
2424 *yield = ERROR;
e9166683 2425 return -4;
d9c3c8ed
JH
2426 }
2427
2428/* From here until we send the DATA command, we can make use of PIPELINING
2429if the server host supports it. The code has to be able to check the responses
2430at any point, for when the buffer fills up, so we write it totally generally.
2431When PIPELINING is off, each command written reports that it has flushed the
2432buffer. */
2433
2434sx->pending_MAIL = TRUE; /* The block starts with MAIL */
2435
2436 {
2437 uschar * s = sx->from_addr;
2438#ifdef SUPPORT_I18N
2439 uschar * errstr = NULL;
2440
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. */
2444
2445 if ( sx->addrlist->prop.utf8_msg
14de8063 2446 && (sx->addrlist->prop.utf8_downcvt || !(sx->peer_offered & OPTION_UTF8))
d9c3c8ed
JH
2447 )
2448 {
2449 if (s = string_address_utf8_to_alabel(s, &errstr), errstr)
2450 {
2451 set_errno_nohost(sx->addrlist, ERRNO_EXPANDFAIL, errstr, DEFER, FALSE);
2452 *yield = ERROR;
e9166683 2453 return -4;
d9c3c8ed
JH
2454 }
2455 setflag(sx->addrlist, af_utf8_downcvt);
2456 }
2457#endif
2458
4e910c01 2459 rc = smtp_write_command(&sx->outblock, pipelining_active ? SCMD_BUFFER : SCMD_FLUSH,
d9c3c8ed
JH
2460 "MAIL FROM:<%s>%s\r\n", s, sx->buffer);
2461 }
2462
2463mail_command = string_copy(big_buffer); /* Save for later error message */
2464
2465switch(rc)
2466 {
2467 case -1: /* Transmission error */
e9166683 2468 return -5;
d9c3c8ed 2469
df5b41e3 2470 case +1: /* Cmd was sent */
d9c3c8ed
JH
2471 if (!smtp_read_response(&sx->inblock, sx->buffer, sizeof(sx->buffer), '2',
2472 sx->ob->command_timeout))
2473 {
2474 if (errno == 0 && sx->buffer[0] == '4')
2475 {
2476 errno = ERRNO_MAIL4XX;
2477 sx->addrlist->more_errno |= ((sx->buffer[1] - '0')*10 + sx->buffer[2] - '0') << 8;
2478 }
2479 return -1;
2480 }
2481 sx->pending_MAIL = FALSE;
2482 break;
e9166683
JH
2483
2484 /* otherwise zero: command queued for pipeline */
d9c3c8ed
JH
2485 }
2486
2487/* Pass over all the relevant recipient addresses for this host, which are the
2488ones that have status PENDING_DEFER. If we are using PIPELINING, we can send
2489several before we have to read the responses for those seen so far. This
2490checking is done by a subroutine because it also needs to be done at the end.
2491Send only up to max_rcpt addresses at a time, leaving next_addr pointing to
2492the next one if not all are sent.
2493
2494In the MUA wrapper situation, we want to flush the PIPELINING buffer for the
2495last address because we want to abort if any recipients have any kind of
2496problem, temporary or permanent. We know that all recipient addresses will have
2497the PENDING_DEFER status, because only one attempt is ever made, and we know
e9166683
JH
2498that max_rcpt will be large, so all addresses will be done at once.
2499
2500For verify we flush the pipeline after any (the only) rcpt address. */
d9c3c8ed
JH
2501
2502for (addr = sx->first_addr, address_count = 0;
2503 addr && address_count < sx->max_rcpt;
2504 addr = addr->next) if (addr->transport_return == PENDING_DEFER)
2505 {
2506 int count;
2507 BOOL no_flush;
2508 uschar * rcpt_addr;
2509
a2673768
JH
2510 if (tcp_out_fastopen && !tcp_out_fastopen_logged)
2511 setflag(addr, af_tcp_fastopen);
2512
14de8063 2513 addr->dsn_aware = sx->peer_offered & OPTION_DSN
d9c3c8ed
JH
2514 ? dsn_support_yes : dsn_support_no;
2515
2516 address_count++;
4c2471ca
JH
2517 no_flush = pipelining_active && !sx->verify
2518 && (!mua_wrapper || addr->next && address_count < sx->max_rcpt);
d9c3c8ed
JH
2519
2520 build_rcptcmd_options(sx, addr);
2521
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. */
2526
2527 rcpt_addr = transport_rcpt_address(addr, sx->tblock->rcpt_include_affixes);
2528
2529#ifdef SUPPORT_I18N
2530 if ( testflag(sx->addrlist, af_utf8_downcvt)
2531 && !(rcpt_addr = string_address_utf8_to_alabel(rcpt_addr, NULL))
2532 )
2533 {
2534 /*XXX could we use a per-address errstr here? Not fail the whole send? */
2535 errno = ERRNO_EXPANDFAIL;
e9166683 2536 return -5; /*XXX too harsh? */
d9c3c8ed
JH
2537 }
2538#endif
2539
4e910c01
JH
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);
d9c3c8ed 2542
e9166683 2543 if (count < 0) return -5;
d9c3c8ed
JH
2544 if (count > 0)
2545 {
df5b41e3 2546 switch(sync_responses(sx, count, 0))
d9c3c8ed
JH
2547 {
2548 case 3: sx->ok = TRUE; /* 2xx & 5xx => OK & progress made */
2549 case 2: sx->completed_addr = TRUE; /* 5xx (only) => progress made */
e9166683 2550 break;
d9c3c8ed
JH
2551
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 */
2556 break;
2557
e9166683
JH
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 */
d9c3c8ed
JH
2561 }
2562 sx->pending_MAIL = FALSE; /* Dealt with MAIL */
2563 }
2564 } /* Loop for next address */
2565
a2673768 2566tcp_out_fastopen_logged = TRUE;
d9c3c8ed
JH
2567sx->next_addr = addr;
2568return 0;
2569}
2570
2571
875512a3
JH
2572#ifdef SUPPORT_TLS
2573/*****************************************************
2574* Proxy TLS connection for another transport process *
2575******************************************************/
2576/*
57cc2785
JH
2577Use the given buffer as a staging area, and select on both the given fd
2578and the TLS'd client-fd for data to read (per the coding in ip_recv() and
875512a3
JH
2579fd_ready() this is legitimate). Do blocking full-size writes, and reads
2580under a timeout.
2581
2582Arguments:
57cc2785
JH
2583 buf space to use for buffering
2584 bufsiz size of buffer
875512a3
JH
2585 proxy_fd comms to proxied process
2586 timeout per-read timeout, seconds
2587*/
2588
57cc2785
JH
2589void
2590smtp_proxy_tls(uschar * buf, size_t bsize, int proxy_fd, int timeout)
875512a3 2591{
e47252f5 2592fd_set rfds, efds;
875512a3
JH
2593int max_fd = MAX(proxy_fd, tls_out.active) + 1;
2594int rc, i, fd_bits, nbytes;
2595
2596set_process_info("proxying TLS connection for continued transport");
e47252f5
JH
2597FD_ZERO(&rfds);
2598FD_SET(tls_out.active, &rfds);
2599FD_SET(proxy_fd, &rfds);
875512a3
JH
2600
2601for (fd_bits = 3; fd_bits; )
2602 {
2603 time_t time_left = timeout;
2604 time_t time_start = time(NULL);
2605
2606 /* wait for data */
e47252f5 2607 efds = rfds;
875512a3
JH
2608 do
2609 {
2610 struct timeval tv = { time_left, 0 };
2611
e47252f5
JH
2612 rc = select(max_fd,
2613 (SELECT_ARG2_TYPE *)&rfds, NULL, (SELECT_ARG2_TYPE *)&efds, &tv);
875512a3
JH
2614
2615 if (rc < 0 && errno == EINTR)
2616 if ((time_left -= time(NULL) - time_start) > 0) continue;
2617
2618 if (rc <= 0)
2619 {
2620 DEBUG(D_transport) if (rc == 0) debug_printf("%s: timed out\n", __FUNCTION__);
2621 return;
2622 }
e47252f5
JH
2623
2624 if (FD_ISSET(tls_out.active, &efds) || FD_ISSET(proxy_fd, &efds))
2625 {
2626 DEBUG(D_transport) debug_printf("select: exceptional cond on %s fd\n",
2627 FD_ISSET(proxy_fd, &efds) ? "proxy" : "tls");
2628 return;
2629 }
875512a3 2630 }
e47252f5 2631 while (rc < 0 || !(FD_ISSET(tls_out.active, &rfds) || FD_ISSET(proxy_fd, &rfds)));
875512a3
JH
2632
2633 /* handle inbound data */
e47252f5 2634 if (FD_ISSET(tls_out.active, &rfds))
57cc2785 2635 if ((rc = tls_read(FALSE, buf, bsize)) <= 0)
875512a3
JH
2636 {
2637 fd_bits &= ~1;
e47252f5 2638 FD_CLR(tls_out.active, &rfds);
875512a3 2639 shutdown(proxy_fd, SHUT_WR);
e47252f5 2640 timeout = 5;
875512a3
JH
2641 }
2642 else
2643 {
2644 for (nbytes = 0; rc - nbytes > 0; nbytes += i)
57cc2785 2645 if ((i = write(proxy_fd, buf + nbytes, rc - nbytes)) < 0) return;
875512a3
JH
2646 }
2647 else if (fd_bits & 1)
e47252f5 2648 FD_SET(tls_out.active, &rfds);
875512a3
JH
2649
2650 /* handle outbound data */
e47252f5 2651 if (FD_ISSET(proxy_fd, &rfds))
57cc2785 2652 if ((rc = read(proxy_fd, buf, bsize)) <= 0)
875512a3 2653 {
e47252f5
JH
2654 fd_bits = 0;
2655 tls_close(FALSE, TRUE);
875512a3
JH
2656 }
2657 else
2658 {
2659 for (nbytes = 0; rc - nbytes > 0; nbytes += i)
925ac8e4
JH
2660 if ((i = tls_write(FALSE, buf + nbytes, rc - nbytes, FALSE)) < 0)
2661 return;
875512a3
JH
2662 }
2663 else if (fd_bits & 2)
e47252f5 2664 FD_SET(proxy_fd, &rfds);
875512a3
JH
2665 }
2666}
2667#endif
2668
2669
d093f8e5
JH
2670/*************************************************
2671* Deliver address list to given host *
2672*************************************************/
2673
2674/* If continue_hostname is not null, we get here only when continuing to
2675deliver down an existing channel. The channel was passed as the standard
2676input. TLS is never active on a passed channel; the previous process always
2677closes it down before passing the connection on.
2678
2679Otherwise, we have to make a connection to the remote host, and do the
2680initial protocol exchange.
2681
2682When running as an MUA wrapper, if the sender or any recipient is rejected,
2683temporarily or permanently, we force failure for all recipients.
2684
2685Arguments:
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
a843a57e
JH
2693 defport default TCP/IP port to use if host does not specify, in host
2694 byte order
d093f8e5
JH
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
2703
2704Returns: 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
2713*/
2714
2715static int
a843a57e 2716smtp_deliver(address_item *addrlist, host_item *host, int host_af, int defport,
d093f8e5
JH
2717 uschar *interface, transport_instance *tblock,
2718 BOOL *message_defer, BOOL suppress_tls)
2719{
2720address_item *addr;
d093f8e5 2721int yield = OK;
d093f8e5
JH
2722int save_errno;
2723int rc;
32dfdf8b 2724struct timeval start_delivery_time;
d093f8e5 2725
d093f8e5
JH
2726BOOL pass_message = FALSE;
2727uschar *message = NULL;
2728uschar new_message_id[MESSAGE_ID_LENGTH + 1];
d093f8e5
JH
2729
2730smtp_context sx;
2731
32dfdf8b 2732gettimeofday(&start_delivery_time, NULL);
d093f8e5 2733suppress_tls = suppress_tls; /* stop compiler warning when no TLS support */
02b41d71 2734*message_defer = FALSE;
d093f8e5
JH
2735
2736sx.addrlist = addrlist;
2737sx.host = host;
2738sx.host_af = host_af,
a843a57e 2739sx.port = defport;
d093f8e5 2740sx.interface = interface;
02b41d71 2741sx.helo_data = NULL;
d093f8e5 2742sx.tblock = tblock;
e9166683 2743sx.verify = FALSE;
d093f8e5 2744
9be4572b
JH
2745/* Get the channel set up ready for a message (MAIL FROM being the next
2746SMTP command to send */
2747
e9166683 2748if ((rc = smtp_setup_conn(&sx, suppress_tls)) != OK)
d093f8e5
JH
2749 return rc;
2750
0756eb3c
PH
2751/* If there is a filter command specified for this transport, we can now
2752set it up. This cannot be done until the identify of the host is known. */
2753
e9166683 2754if (tblock->filter_command)
0756eb3c 2755 {
9b989985 2756 transport_filter_timeout = tblock->filter_timeout;
0756eb3c
PH
2757
2758 /* On failure, copy the error to all addresses, abandon the SMTP call, and
2759 yield ERROR. */
2760
36d295f1
JH
2761 if (!transport_set_up_command(&transport_filter_argv,
2762 tblock->filter_command, TRUE, DEFER, addrlist,
2763 string_sprintf("%.50s transport", tblock->name), NULL))
0756eb3c 2764 {
895fbaf2
JH
2765 set_errno_nohost(addrlist->next, addrlist->basic_errno, addrlist->message, DEFER,
2766 FALSE);
0756eb3c
PH
2767 yield = ERROR;
2768 goto SEND_QUIT;
2769 }
48f1c853
JH
2770
2771 if ( transport_filter_argv
2772 && *transport_filter_argv
2773 && **transport_filter_argv
14de8063 2774 && sx.peer_offered & OPTION_CHUNKING
48f1c853
JH
2775 )
2776 {
14de8063 2777 sx.peer_offered &= ~OPTION_CHUNKING;
48f1c853
JH
2778 DEBUG(D_transport) debug_printf("CHUNKING not usable due to transport filter\n");
2779 }
0756eb3c
PH
2780 }
2781
36d295f1 2782sx.first_addr = addrlist;
0756eb3c
PH
2783
2784/* For messages that have more than the maximum number of envelope recipients,
2785we want to send several transactions down the same SMTP connection. (See
2786comments in deliver.c as to how this reconciles, heuristically, with
2787remote_max_parallel.) This optimization was added to Exim after the following
2788code was already working. The simplest way to put it in without disturbing the
2789code was to use a goto to jump back to this point when there is another
2790transaction to handle. */
2791
2792SEND_MESSAGE:
d9c3c8ed 2793sx.from_addr = return_path;
36d295f1 2794sx.sync_addr = sx.first_addr;
d093f8e5
JH
2795sx.ok = FALSE;
2796sx.send_rset = TRUE;
d9c3c8ed 2797sx.completed_addr = FALSE;
0756eb3c
PH
2798
2799
57cc2785
JH
2800/* If we are a continued-connection-after-verify the MAIL and RCPT
2801commands were already sent; do not re-send but do mark the addrs as
2802having been accepted up to RCPT stage. A traditional cont-conn
2803always has a sequence number greater than one. */
6b62e899 2804
57cc2785 2805if (continue_hostname && continue_sequence == 1)
0756eb3c 2806 {
57cc2785 2807 address_item * addr;
0756eb3c 2808
57cc2785 2809 sx.peer_offered = smtp_peer_options;
d8b8dd15 2810 sx.pending_MAIL = FALSE;
57cc2785
JH
2811 sx.ok = TRUE;
2812 sx.next_addr = NULL;
0756eb3c 2813
57cc2785
JH
2814 for (addr = addrlist; addr; addr = addr->next)
2815 addr->transport_return = PENDING_OK;
2816 }
2817else
0756eb3c 2818 {
57cc2785
JH
2819 /* Initiate a message transfer. */
2820
2821 switch(smtp_write_mail_and_rcpt_cmds(&sx, &yield))
2822 {
2823 case 0: break;
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;
2828 }
2829
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
2832 RCPT. */
2833
2834 if (mua_wrapper)
2835 {
4c2471ca
JH
2836 address_item * a;
2837 unsigned cnt;
2838
2839 for (a = sx.first_addr, cnt = 0; a && cnt < sx.max_rcpt; a = a->next, cnt++)
2840 if (a->transport_return != PENDING_OK)
57cc2785
JH
2841 {
2842 /*XXX could we find a better errno than 0 here? */
4c2471ca
JH
2843 set_errno_nohost(addrlist, 0, a->message, FAIL,
2844 testflag(a, af_pass_message));
57cc2785
JH
2845 sx.ok = FALSE;
2846 break;
2847 }
2848 }
0756eb3c
PH
2849 }
2850
2851/* If ok is TRUE, we know we have got at least one good recipient, and must now
2852send DATA, but if it is FALSE (in the normal, non-wrapper case), we may still
2853have a good recipient buffered up if we are pipelining. We don't want to waste
2854time sending DATA needlessly, so we only send it if either ok is TRUE or if we
6d5c916c
JH
2855are pipelining. The responses are all handled by sync_responses().
2856If using CHUNKING, do not send a BDAT until we know how big a chunk we want
2857to send is. */
0756eb3c 2858
14de8063 2859if ( !(sx.peer_offered & OPTION_CHUNKING)
d093f8e5 2860 && (sx.ok || (pipelining_active && !mua_wrapper)))
0756eb3c 2861 {
4e910c01 2862 int count = smtp_write_command(&sx.outblock, SCMD_FLUSH, "DATA\r\n");
6d5c916c 2863
0756eb3c 2864 if (count < 0) goto SEND_FAILED;
df5b41e3 2865 switch(sync_responses(&sx, count, sx.ok ? +1 : -1))
0756eb3c 2866 {
d093f8e5 2867 case 3: sx.ok = TRUE; /* 2xx & 5xx => OK & progress made */
d9c3c8ed 2868 case 2: sx.completed_addr = TRUE; /* 5xx (only) => progress made */
0756eb3c
PH
2869 break;
2870
d093f8e5 2871 case 1: sx.ok = TRUE; /* 2xx (only) => OK, but if LMTP, */
d9c3c8ed 2872 if (!sx.lmtp) sx.completed_addr = TRUE; /* can't tell about progress yet */
0756eb3c
PH
2873 case 0: break; /* No 2xx or 5xx, but no probs */
2874
2875 case -1: goto END_OFF; /* Timeout on RCPT */
2876 default: goto RESPONSE_FAILED; /* I/O error, or any MAIL/DATA error */
2877 }
0d9fa8c0 2878 pipelining_active = FALSE;
87cb4a16 2879 data_command = string_copy(big_buffer); /* Save for later error message */
0756eb3c
PH
2880 }
2881
0756eb3c
PH
2882/* If there were no good recipients (but otherwise there have been no
2883problems), just set ok TRUE, since we have handled address-specific errors
2884already. Otherwise, it's OK to send the message. Use the check/escape mechanism
2885for handling the SMTP dot-handling protocol, flagging to apply to headers as
2886well 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.) */
2888
14de8063 2889if (!(sx.peer_offered & OPTION_CHUNKING) && !sx.ok)
6d5c916c
JH
2890 {
2891 /* Save the first address of the next batch. */
d9c3c8ed 2892 sx.first_addr = sx.next_addr;
6d5c916c 2893
d093f8e5 2894 sx.ok = TRUE;
6d5c916c 2895 }
ff5aac2b 2896else
0756eb3c 2897 {
6b46ecc6 2898 transport_ctx tctx = {
cab0c277 2899 {sx.inblock.sock},
6b46ecc6
JH
2900 tblock,
2901 addrlist,
2902 US".", US"..", /* Escaping strings */
65de12cc 2903 topt_use_crlf | topt_escape_headers
6b46ecc6
JH
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)
2909 };
2910
6d5c916c
JH
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. */
2915
14de8063 2916 if (sx.peer_offered & OPTION_CHUNKING)
59932f7d 2917 {
65de12cc 2918 tctx.check_string = tctx.escape_string = NULL;
6d5c916c
JH
2919 tctx.options |= topt_use_bdat;
2920 tctx.chunk_cb = smtp_chunk_cmd_callback;
e9166683
JH
2921 sx.pending_BDAT = FALSE;
2922 sx.good_RCPT = sx.ok;
2923 sx.cmd_count = 0;
2924 tctx.smtp_context = &sx;
59932f7d
JH
2925 }
2926 else
65de12cc 2927 tctx.options |= topt_end_dot;
59932f7d 2928
6d5c916c 2929 /* Save the first address of the next batch. */
d9c3c8ed 2930 sx.first_addr = sx.next_addr;
6d5c916c 2931
e027f545
JH
2932 /* Responses from CHUNKING commands go in buffer. Otherwise,
2933 there has not been a response. */
2934
d093f8e5 2935 sx.buffer[0] = 0;
e027f545 2936
0756eb3c 2937 sigalrm_seen = FALSE;
d093f8e5 2938 transport_write_timeout = sx.ob->data_timeout;
0756eb3c
PH
2939 smtp_command = US"sending data block"; /* For error messages */
2940 DEBUG(D_transport|D_v)
14de8063 2941 if (sx.peer_offered & OPTION_CHUNKING)
6d5c916c
JH
2942 debug_printf(" will write message using CHUNKING\n");
2943 else
2944 debug_printf(" SMTP>> writing message and terminating \".\"\n");
0756eb3c 2945 transport_count = 0;
a7538db1 2946
80a47a2c 2947#ifndef DISABLE_DKIM
42055a33 2948 sx.ok = dkim_transport_write_message(&tctx, &sx.ob->dkim, CUSS &message);
4cd12fe9 2949#else
42055a33 2950 sx.ok = transport_write_message(&tctx, 0);
4cd12fe9 2951#endif
0756eb3c
PH
2952
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. */
2957
2958 transport_write_timeout = 0; /* for subsequent transports */
2959
2960 /* Failure can either be some kind of I/O disaster (including timeout),
e027f545
JH
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. */
0756eb3c 2963
d093f8e5 2964 if (!sx.ok)
b9df1829
JH
2965 if (message) goto SEND_FAILED;
2966 else goto RESPONSE_FAILED;
0756eb3c
PH
2967
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
2972 flag above. */
2973
2974 smtp_command = US"end of data";
2975
14de8063 2976 if (sx.peer_offered & OPTION_CHUNKING && sx.cmd_count > 1)
6d5c916c
JH
2977 {
2978 /* Reap any outstanding MAIL & RCPT commands, but not a DATA-go-ahead */
e9166683 2979 switch(sync_responses(&sx, sx.cmd_count-1, 0))
6d5c916c 2980 {
d093f8e5 2981 case 3: sx.ok = TRUE; /* 2xx & 5xx => OK & progress made */
d9c3c8ed 2982 case 2: sx.completed_addr = TRUE; /* 5xx (only) => progress made */
6d5c916c
JH
2983 break;
2984
d093f8e5 2985 case 1: sx.ok = TRUE; /* 2xx (only) => OK, but if LMTP, */
d9c3c8ed 2986 if (!sx.lmtp) sx.completed_addr = TRUE; /* can't tell about progress yet */
6d5c916c
JH
2987 case 0: break; /* No 2xx or 5xx, but no probs */
2988
2989 case -1: goto END_OFF; /* Timeout on RCPT */
2990 default: goto RESPONSE_FAILED; /* I/O error, or any MAIL/DATA error */
2991 }
2992 }
2993
8ccd00b1 2994#ifndef DISABLE_PRDR
fd98a5c6
JH
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. */
d093f8e5 2999 if(sx.prdr_active)
fd98a5c6 3000 {
d093f8e5
JH
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])
e027f545 3004 {
d093f8e5
JH
3005 case '2': sx.prdr_active = FALSE;
3006 sx.ok = TRUE;
e027f545
JH
3007 break;
3008 case '4': errno = ERRNO_DATA4XX;
3009 addrlist->more_errno |=
d093f8e5 3010 ((sx.buffer[1] - '0')*10 + sx.buffer[2] - '0') << 8;
e027f545
JH
3011 break;
3012 }
fd98a5c6
JH
3013 }
3014 else
3015#endif
3016
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. */
0756eb3c 3019
d093f8e5 3020 if (!sx.lmtp)
e97957bc 3021 {
d093f8e5
JH
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')
e97957bc
PH
3025 {
3026 errno = ERRNO_DATA4XX;
d093f8e5 3027 addrlist->more_errno |= ((sx.buffer[1] - '0')*10 + sx.buffer[2] - '0') << 8;
e97957bc
PH
3028 }
3029 }
0756eb3c
PH
3030
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.
3035
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). */
3042
d093f8e5 3043 if (sx.ok)
0756eb3c
PH
3044 {
3045 int flag = '=';
32dfdf8b 3046 struct timeval delivery_time;
0756eb3c 3047 int len;
32dfdf8b 3048 uschar * conf = NULL;
0d9fa8c0 3049
32dfdf8b 3050 timesince(&delivery_time, &start_delivery_time);
d093f8e5 3051 sx.send_rset = FALSE;
0d9fa8c0 3052 pipelining_active = FALSE;
0756eb3c 3053
0756eb3c
PH
3054 /* Set up confirmation if needed - applies only to SMTP */
3055
d68218c7 3056 if (
0cbf2b82 3057#ifdef DISABLE_EVENT
6c6d6e48 3058 LOGGING(smtp_confirmation) &&
a7538db1 3059#endif
d093f8e5 3060 !sx.lmtp
d68218c7 3061 )
0756eb3c 3062 {
d093f8e5 3063 const uschar *s = string_printing(sx.buffer);
55414b25 3064 /* deconst cast ok here as string_printing was checked to have alloc'n'copied */
5903c6ff 3065 conf = (s == sx.buffer)? US string_copy(s) : US s;
0756eb3c
PH
3066 }
3067
fd98a5c6 3068 /* Process all transported addresses - for LMTP or PRDR, read a status for
0756eb3c
PH
3069 each one. */
3070
d9c3c8ed 3071 for (addr = addrlist; addr != sx.first_addr; addr = addr->next)
0756eb3c
PH
3072 {
3073 if (addr->transport_return != PENDING_OK) continue;
3074
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
75def545
PH
3077 address. For temporary errors, add a retry item for the address so that
3078 it doesn't get tried again too soon. */
0756eb3c 3079
8ccd00b1 3080#ifndef DISABLE_PRDR
d093f8e5 3081 if (sx.lmtp || sx.prdr_active)
fd98a5c6 3082#else
d093f8e5 3083 if (sx.lmtp)
fd98a5c6 3084#endif
0756eb3c 3085 {
d093f8e5
JH
3086 if (!smtp_read_response(&sx.inblock, sx.buffer, sizeof(sx.buffer), '2',
3087 sx.ob->final_timeout))
0756eb3c 3088 {
d093f8e5 3089 if (errno != 0 || sx.buffer[0] == 0) goto RESPONSE_FAILED;
fd98a5c6 3090 addr->message = string_sprintf(
8ccd00b1 3091#ifndef DISABLE_PRDR
d093f8e5 3092 "%s error after %s: %s", sx.prdr_active ? "PRDR":"LMTP",
fd98a5c6
JH
3093#else
3094 "LMTP error after %s: %s",
3095#endif
d093f8e5 3096 data_command, string_printing(sx.buffer));
75def545 3097 setflag(addr, af_pass_message); /* Allow message to go to user */
d093f8e5 3098 if (sx.buffer[0] == '5')
75def545
PH
3099 addr->transport_return = FAIL;
3100 else
3101 {
e97957bc 3102 errno = ERRNO_DATA4XX;
d093f8e5 3103 addr->more_errno |= ((sx.buffer[1] - '0')*10 + sx.buffer[2] - '0') << 8;
75def545 3104 addr->transport_return = DEFER;
8ccd00b1 3105#ifndef DISABLE_PRDR
d093f8e5 3106 if (!sx.prdr_active)
fd98a5c6
JH
3107#endif
3108 retry_add_item(addr, addr->address_retry_key, 0);
75def545 3109 }
0756eb3c
PH
3110 continue;
3111 }
d9c3c8ed 3112 sx.completed_addr = TRUE; /* NOW we can set this flag */
6c6d6e48 3113 if (LOGGING(smtp_confirmation))
c0ea85ab 3114 {
d093f8e5 3115 const uschar *s = string_printing(sx.buffer);
55414b25 3116 /* deconst cast ok here as string_printing was checked to have alloc'n'copied */
d093f8e5 3117 conf = (s == sx.buffer) ? US string_copy(s) : US s;
c0ea85ab 3118 }
0756eb3c
PH
3119 }
3120
3121 /* SMTP, or success return from LMTP for this address. Pass back the
2d280592 3122 actual host that was used. */
0756eb3c
PH
3123
3124 addr->transport_return = OK;
32dfdf8b
JH
3125 addr->more_errno = delivery_time.tv_sec;
3126 addr->delivery_usec = delivery_time.tv_usec;
d427a7f9 3127 addr->host_used = host;
0756eb3c
PH
3128 addr->special_action = flag;
3129 addr->message = conf;
8ccd00b1 3130#ifndef DISABLE_PRDR
7eb0e5d2 3131 if (sx.prdr_active) setflag(addr, af_prdr_used);
fd98a5c6 3132#endif
7eb0e5d2 3133 if (sx.peer_offered & OPTION_CHUNKING) setflag(addr, af_chunking_used);
0756eb3c
PH
3134 flag = '-';
3135
8ccd00b1 3136#ifndef DISABLE_PRDR
d093f8e5 3137 if (!sx.prdr_active)
fd98a5c6
JH
3138#endif
3139 {
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. */
4d8d62b9 3144
fd98a5c6 3145 if (testflag(addr, af_homonym))
d093f8e5 3146 sprintf(CS sx.buffer, "%.500s/%s\n", addr->unique + 3, tblock->name);
fd98a5c6 3147 else
d093f8e5 3148 sprintf(CS sx.buffer, "%.500s\n", addr->unique);
4d8d62b9 3149
6c454556 3150 DEBUG(D_deliver) debug_printf("S:journalling %s", sx.buffer);
d093f8e5
JH
3151 len = Ustrlen(CS sx.buffer);
3152 if (write(journal_fd, sx.buffer, len) != len)
fd98a5c6 3153 log_write(0, LOG_MAIN|LOG_PANIC, "failed to write journal for "
d093f8e5 3154 "%s: %s", sx.buffer, strerror(errno));
fd98a5c6 3155 }
0756eb3c
PH
3156 }
3157
8ccd00b1 3158#ifndef DISABLE_PRDR
d093f8e5 3159 if (sx.prdr_active)
fd98a5c6
JH
3160 {
3161 /* PRDR - get the final, overall response. For any non-success
3162 upgrade all the address statuses. */
d093f8e5
JH
3163 sx.ok = smtp_read_response(&sx.inblock, sx.buffer, sizeof(sx.buffer), '2',
3164 sx.ob->final_timeout);
3165 if (!sx.ok)
fd98a5c6 3166 {
d093f8e5 3167 if(errno == 0 && sx.buffer[0] == '4')
fd98a5c6
JH
3168 {
3169 errno = ERRNO_DATA4XX;
d093f8e5 3170 addrlist->more_errno |= ((sx.buffer[1] - '0')*10 + sx.buffer[2] - '0') << 8;
fd98a5c6 3171 }
d9c3c8ed 3172 for (addr = addrlist; addr != sx.first_addr; addr = addr->next)
d093f8e5 3173 if (sx.buffer[0] == '5' || addr->transport_return == OK)
fd98a5c6
JH
3174 addr->transport_return = PENDING_OK; /* allow set_errno action */
3175 goto RESPONSE_FAILED;
3176 }
3177
3178 /* Update the journal, or setup retry. */
d9c3c8ed 3179 for (addr = addrlist; addr != sx.first_addr; addr = addr->next)
fd98a5c6 3180 if (addr->transport_return == OK)
9be4572b
JH
3181 {
3182 if (testflag(addr, af_homonym))
3183 sprintf(CS sx.buffer, "%.500s/%s\n", addr->unique + 3, tblock->name);
3184 else
3185 sprintf(CS sx.buffer, "%.500s\n", addr->unique);
3186
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));
3192 }
3193 else if (addr->transport_return == DEFER)
3194 retry_add_item(addr, addr->address_retry_key, -2);
fd98a5c6
JH
3195 }
3196#endif
3197
0756eb3c
PH
3198 /* Ensure the journal file is pushed out to disk. */
3199
54fc8428 3200 if (EXIMfsync(journal_fd) < 0)
0756eb3c
PH
3201 log_write(0, LOG_MAIN|LOG_PANIC, "failed to fsync journal: %s",
3202 strerror(errno));
3203 }
3204 }
3205
3206
3207/* Handle general (not specific to one address) failures here. The value of ok
3208is used to skip over this code on the falling through case. A timeout causes a
3209deferral. Other errors may defer or fail according to the response code, and
3210may set up a special errno value, e.g. after connection chopped, which is
3211assumed if errno == 0 and there is no text in the buffer. If control reaches
3212here during the setting up phase (i.e. before MAIL FROM) then always defer, as
3213the problem is not related to this specific message. */
3214
d093f8e5 3215if (!sx.ok)
0756eb3c 3216 {
895fbaf2
JH
3217 int code, set_rc;
3218 uschar * set_message;
0756eb3c
PH
3219
3220 RESPONSE_FAILED:
895fbaf2
JH
3221 {
3222 save_errno = errno;
3223 message = NULL;
d093f8e5
JH
3224 sx.send_quit = check_response(host, &save_errno, addrlist->more_errno,
3225 sx.buffer, &code, &message, &pass_message);
895fbaf2
JH
3226 goto FAILED;
3227 }
0756eb3c
PH
3228
3229 SEND_FAILED:
895fbaf2
JH
3230 {
3231 save_errno = errno;
3232 code = '4';
b9df1829 3233 message = string_sprintf("send() to %s [%s] failed: %s",
c0ad8edf 3234 host->name, host->address, message ? message : US strerror(save_errno));
d093f8e5 3235 sx.send_quit = FALSE;
895fbaf2
JH
3236 goto FAILED;
3237 }
0756eb3c 3238
0756eb3c 3239 FAILED:
9be4572b
JH
3240 {
3241 BOOL message_error;
0756eb3c 3242
9be4572b
JH
3243 sx.ok = FALSE; /* For when reached by GOTO */
3244 set_message = message;
0756eb3c 3245
e97957bc 3246 /* We want to handle timeouts after MAIL or "." and loss of connection after
0756eb3c 3247 "." specially. They can indicate a problem with the sender address or with
e97957bc
PH
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. */
0756eb3c 3251
e97957bc
PH
3252 switch(save_errno)
3253 {
3254 case 0:
3255 case ERRNO_MAIL4XX:
3256 case ERRNO_DATA4XX:
250b6871
JH
3257 message_error = TRUE;
3258 break;
0756eb3c 3259
e97957bc 3260 case ETIMEDOUT:
250b6871
JH
3261 message_error = Ustrncmp(smtp_command,"MAIL",4) == 0 ||
3262 Ustrncmp(smtp_command,"end ",4) == 0;
3263 break;
e97957bc
PH
3264
3265 case ERRNO_SMTPCLOSED:
250b6871
JH
3266 message_error = Ustrncmp(smtp_command,"end ",4) == 0;
3267 break;
e97957bc
PH
3268
3269 default:
250b6871
JH
3270 message_error = FALSE;
3271 break;
e97957bc 3272 }
0756eb3c 3273
e97957bc 3274 /* Handle the cases that are treated as message errors. These are:
0756eb3c 3275
e97957bc
PH
3276 (a) negative response or timeout after MAIL
3277 (b) negative response after DATA
3278 (c) negative response or timeout or dropped connection after "."
250b6871 3279 (d) utf8 support required and not offered
0756eb3c 3280
e97957bc
PH
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. */
3289
3290 if (message_error)
0756eb3c 3291 {
e97957bc 3292 if (mua_wrapper) code = '5'; /* Force hard failure in wrapper mode */
e97957bc
PH
3293
3294 /* If there's an errno, the message contains just the identity of
3295 the host. */
3296
895fbaf2
JH
3297 if (code == '5')
3298 set_rc = FAIL;
3299 else /* Anything other than 5 is treated as temporary */
e97957bc 3300 {
895fbaf2 3301 set_rc = DEFER;
e97957bc
PH
3302 if (save_errno > 0)
3303 message = US string_sprintf("%s: %s", message, strerror(save_errno));
3304 if (host->next != NULL) log_write(0, LOG_MAIN, "%s", message);
c562fd30 3305 msglog_line(host, message);
e97957bc
PH
3306 *message_defer = TRUE;
3307 }
3308 }
3309
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
3314 hosts. */
3315
3316 else
3317 {
895fbaf2 3318 set_rc = DEFER;
e97957bc
PH
3319 yield = (save_errno == ERRNO_CHHEADER_FAIL ||
3320 save_errno == ERRNO_FILTER_FAIL)? ERROR : DEFER;
0756eb3c
PH
3321 }
3322 }
895fbaf2
JH
3323
3324 set_errno(addrlist, save_errno, set_message, set_rc, pass_message, host
3325#ifdef EXPERIMENTAL_DSN_INFO
d093f8e5 3326 , sx.smtp_greeting, sx.helo_response
895fbaf2
JH
3327#endif
3328 );
0756eb3c
PH
3329 }
3330
3331
3332/* If all has gone well, send_quit will be set TRUE, implying we can end the
3333SMTP session tidily. However, if there were too many addresses to send in one
3334message (indicated by first_addr being non-NULL) we want to carry on with the
3335rest of them. Also, it is desirable to send more than one message down the SMTP
3336connection if there are several waiting, provided we haven't already sent so
3337many as to hit the configured limit. The function transport_check_waiting looks
3338for a waiting message and returns its id. Then transport_pass_socket tries to
3339set up a continued delivery by passing the socket on to another process. The
3340variable send_rset is FALSE if a message has just been successfully transfered.
3341
3342If we are already sending down a continued channel, there may be further
3343addresses not yet delivered that are aimed at the same host, but which have not
3344been passed in this run of the transport. In this case, continue_more will be
3345true, and all we should do is send RSET if necessary, and return, leaving the
3346channel open.
3347
3348However, if no address was disposed of, i.e. all addresses got 4xx errors, we
3349do not want to continue with other messages down the same channel, because that
3350can lead to looping between two or more messages, all with the same,
3351temporarily failing address(es). [The retry information isn't updated yet, so
3352new processes keep on trying.] We probably also don't want to try more of this
3353message's addresses either.
3354
3355If we have started a TLS session, we have to end it before passing the
3356connection to a new process. However, not all servers can handle this (Exim
3357can), so we do not pass such a connection on if the host matches
3358hosts_nopass_tls. */
3359
3360DEBUG(D_transport)
3361 debug_printf("ok=%d send_quit=%d send_rset=%d continue_more=%d "
d093f8e5 3362 "yield=%d first_address is %sNULL\n", sx.ok, sx.send_quit,
d9c3c8ed 3363 sx.send_rset, continue_more, yield, sx.first_addr ? "not " : "");
0756eb3c 3364
d9c3c8ed 3365if (sx.completed_addr && sx.ok && sx.send_quit)
0756eb3c
PH
3366 {
3367 BOOL more;
a39bd74d
JB
3368 smtp_compare_t t_compare;
3369
3370 t_compare.tblock = tblock;
3371 t_compare.current_sender_address = sender_address;
3372
d9c3c8ed 3373 if ( sx.first_addr != NULL
5130845b 3374 || continue_more
875512a3
JH
3375 || (
3376#ifdef SUPPORT_TLS
5013d912 3377 ( tls_out.active < 0 && !continue_proxy_cipher
d093f8e5 3378 || verify_check_given_host(&sx.ob->hosts_nopass_tls, host) != OK
5130845b 3379 )
0756eb3c 3380 &&
875512a3 3381#endif
0756eb3c 3382 transport_check_waiting(tblock->name, host->name,
a39bd74d
JB
3383 tblock->connection_max_messages, new_message_id, &more,
3384 (oicf)smtp_are_same_identities, (void*)&t_compare)
5130845b 3385 ) )
0756eb3c
PH
3386 {
3387 uschar *msg;
447d236c 3388 BOOL pass_message;
0756eb3c 3389
d093f8e5 3390 if (sx.send_rset)
4e910c01 3391 if (! (sx.ok = smtp_write_command(&sx.outblock, SCMD_FLUSH, "RSET\r\n") >= 0))
0756eb3c
PH
3392 {
3393 msg = US string_sprintf("send() to %s [%s] failed: %s", host->name,
9e7e0f6a 3394 host->address, strerror(errno));
d093f8e5 3395 sx.send_quit = FALSE;
0756eb3c 3396 }
d093f8e5
JH
3397 else if (! (sx.ok = smtp_read_response(&sx.inblock, sx.buffer,
3398 sizeof(sx.buffer), '2', sx.ob->command_timeout)))
0756eb3c
PH
3399 {
3400 int code;
d093f8e5 3401 sx.send_quit = check_response(host, &errno, 0, sx.buffer, &code, &msg,
447d236c 3402 &pass_message);
d093f8e5 3403 if (!sx.send_quit)
0756eb3c 3404 {
c562fd30
JH
3405 DEBUG(D_transport) debug_printf("H=%s [%s] %s\n",
3406 host->name, host->address, msg);
0756eb3c
PH
3407 }
3408 }
0756eb3c
PH
3409
3410 /* Either RSET was not needed, or it succeeded */
3411
d093f8e5 3412 if (sx.ok)
0756eb3c 3413 {
875512a3
JH
3414 int pfd[2];
3415 int socket_fd = sx.inblock.sock;
3416
3417
3418 if (sx.first_addr != NULL) /* More addresses still to be sent */
0756eb3c
PH
3419 { /* in this run of the transport */
3420 continue_sequence++; /* Causes * in logging */
3421 goto SEND_MESSAGE;
3422 }
0756eb3c 3423
b7d3afcf
JH
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. */
3428
a7538db1 3429#ifdef SUPPORT_TLS
817d9f57 3430 if (tls_out.active >= 0)
b7d3afcf
JH
3431 if ( continue_more
3432 || verify_check_given_host(&sx.ob->hosts_noproxy_tls, host) == OK)
875512a3 3433 {
b7d3afcf
JH
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
3438 the socket on. */
875512a3
JH
3439
3440 tls_close(FALSE, TRUE);
3441 smtp_peer_options = smtp_peer_options_wrap;
3442 sx.ok = !sx.smtps
4e910c01 3443 && smtp_write_command(&sx.outblock, SCMD_FLUSH,
875512a3
JH
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);
b7d3afcf
JH
3447
3448 if (sx.ok && continue_more)
3449 return yield; /* More addresses for another run */
875512a3
JH
3450 }
3451 else
3452 {
3453 /* Set up a pipe for proxying TLS for the new transport process */
3454
14de8063 3455 smtp_peer_options |= OPTION_TLS;
fa18eebc 3456 if (sx.ok = (socketpair(AF_UNIX, SOCK_STREAM, 0, pfd) == 0))
875512a3
JH
3457 socket_fd = pfd[1];
3458 else
3459 set_errno(sx.first_addr, errno, US"internal allocation problem",
3460 DEFER, FALSE, host
3461# ifdef EXPERIMENTAL_DSN_INFO
3462 , sx.smtp_greeting, sx.helo_response
3463# endif
3464 );
3465 }
b7d3afcf 3466 else
a7538db1 3467#endif
b7d3afcf
JH
3468 if (continue_more)
3469 return yield; /* More addresses for another run */
0756eb3c 3470
4c04137d 3471 /* If the socket is successfully passed, we mustn't send QUIT (or
0756eb3c
PH
3472 indeed anything!) from here. */
3473
895fbaf2
JH
3474/*XXX DSN_INFO: assume likely to do new HELO; but for greet we'll want to
3475propagate it from the initial
3476*/
d093f8e5 3477 if (sx.ok && transport_pass_socket(tblock->name, host->name,
875512a3
JH
3478 host->address, new_message_id, socket_fd))
3479 {
d093f8e5 3480 sx.send_quit = FALSE;
875512a3
JH
3481
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. */
57cc2785 3486#ifdef SUPPORT_TLS
875512a3
JH
3487 if (tls_out.active >= 0)
3488 {
3489 int pid = fork();
3490 if (pid > 0) /* parent */
3491 {
b7d3afcf 3492 DEBUG(D_transport) debug_printf("proxy-proc inter-pid %d\n", pid);
e47252f5 3493 close(pfd[0]);
60272099 3494 waitpid(pid, NULL, 0);
875512a3
JH
3495 tls_close(FALSE, FALSE);
3496 (void)close(sx.inblock.sock);
3497 continue_transport = NULL;
3498 continue_hostname = NULL;
3499 return yield;
3500 }
60272099 3501 else if (pid == 0) /* child; fork again to disconnect totally */
875512a3 3502 {
e47252f5 3503 close(pfd[1]);
60272099 3504 if ((pid = fork()))
b7d3afcf
JH
3505 {
3506 DEBUG(D_transport) debug_printf("proxy-prox final-pid %d\n", pid);
60272099 3507 _exit(pid ? EXIT_FAILURE : EXIT_SUCCESS);
b7d3afcf 3508 }
57cc2785 3509 smtp_proxy_tls(sx.buffer, sizeof(sx.buffer), pfd[0], sx.ob->command_timeout);
875512a3
JH
3510 exim_exit(0);
3511 }
3512 }
57cc2785 3513#endif
875512a3 3514 }
0756eb3c
PH
3515 }
3516
3517 /* If RSET failed and there are addresses left, they get deferred. */
875512a3
JH
3518 else
3519 set_errno(sx.first_addr, errno, msg, DEFER, FALSE, host
895fbaf2 3520#ifdef EXPERIMENTAL_DSN_INFO
d093f8e5 3521 , sx.smtp_greeting, sx.helo_response
895fbaf2
JH
3522#endif
3523 );
0756eb3c
PH
3524 }
3525 }
3526
3527/* End off tidily with QUIT unless the connection has died or the socket has
3528been passed to another process. There has been discussion on the net about what
3529to do after sending QUIT. The wording of the RFC suggests that it is necessary
3530to wait for a response, but on the other hand, there isn't anything one can do
3531with an error response, other than log it. Exim used to do that. However,
3532further discussion suggested that it is positively advantageous not to wait for
3533the response, but to close the session immediately. This is supposed to move
3534the TCP/IP TIME_WAIT state from the server to the client, thereby removing some
3535load from the server. (Hosts that are both servers and clients may not see much
3536difference, of course.) Further discussion indicated that this was safe to do
3537on Unix systems which have decent implementations of TCP/IP that leave the
3538connection around for a while (TIME_WAIT) after the application has gone away.
3539This enables the response sent by the server to be properly ACKed rather than
3540timed out, as can happen on broken TCP/IP implementations on other OS.
3541
3542This change is being made on 31-Jul-98. After over a year of trouble-free
3543operation, the old commented-out code was removed on 17-Sep-99. */
3544
3545SEND_QUIT:
4e910c01 3546if (sx.send_quit) (void)smtp_write_command(&sx.outblock, SCMD_FLUSH, "QUIT\r\n");
0756eb3c
PH
3547
3548END_OFF:
3549
3550#ifdef SUPPORT_TLS
817d9f57 3551tls_close(FALSE, TRUE);
0756eb3c
PH
3552#endif
3553
3554/* Close the socket, and return the appropriate value, first setting
0756eb3c
PH
3555works because the NULL setting is passed back to the calling process, and
3556remote_max_parallel is forced to 1 when delivering over an existing connection,
3557
3558If all went well and continue_more is set, we shouldn't actually get here if
3559there are further addresses, as the return above will be taken. However,
3560writing RSET might have failed, or there may be other addresses whose hosts are
3561specified in the transports, and therefore not visible at top level, in which
3562case continue_more won't get set. */
3563
e1d04f48 3564HDEBUG(D_transport|D_acl|D_v) debug_printf_indent(" SMTP(close)>>\n");
d093f8e5 3565if (sx.send_quit)
60d10ce7 3566 {
d093f8e5
JH
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;)
5ddc9771 3570 rc--; /* drain socket */
60d10ce7 3571 }
d093f8e5 3572(void)close(sx.inblock.sock);
a7538db1 3573
0cbf2b82 3574#ifndef DISABLE_EVENT
774ef2d7 3575(void) event_raise(tblock->event_action, US"tcp:close", NULL);
a7538db1
JH
3576#endif
3577
0756eb3c
PH
3578continue_transport = NULL;
3579continue_hostname = NULL;
3580return yield;
3581}
3582
3583
3584
3585
3586/*************************************************
3587* Closedown entry point *
3588*************************************************/
3589
3590/* This function is called when exim is passed an open smtp channel
3591from another incarnation, but the message which it has been asked
3592to deliver no longer exists. The channel is on stdin.
3593
3594We might do fancy things like looking for another message to send down
3595the channel, but if the one we sought has gone, it has probably been
3596delivered by some other process that itself will seek further messages,
3597so just close down our connection.
3598
3599Argument: pointer to the transport instance block
3600Returns: nothing
3601*/
3602
3603void
3604smtp_transport_closedown(transport_instance *tblock)
3605{
3606smtp_transport_options_block *ob =
02b41d71 3607 (smtp_transport_options_block *)tblock->options_block;
0756eb3c
PH
3608smtp_inblock inblock;
3609smtp_outblock outblock;
3610uschar buffer[256];
3611uschar inbuffer[4096];
3612uschar outbuffer[16];
3613
3614inblock.sock = fileno(stdin);
3615inblock.buffer = inbuffer;
3616inblock.buffersize = sizeof(inbuffer);
3617inblock.ptr = inbuffer;
3618inblock.ptrend = inbuffer;
3619
3620outblock.sock = inblock.sock;
3621outblock.buffersize = sizeof(outbuffer);
3622outblock.buffer = outbuffer;
3623outblock.ptr = outbuffer;
3624outblock.cmd_count = 0;
3625outblock.authenticating = FALSE;
3626
4e910c01 3627(void)smtp_write_command(&outblock, SCMD_FLUSH, "QUIT\r\n");
0756eb3c
PH
3628(void)smtp_read_response(&inblock, buffer, sizeof(buffer), '2',
3629 ob->command_timeout);
f1e894f3 3630(void)close(inblock.sock);
0756eb3c
PH
3631}
3632
3633
3634
3635/*************************************************
3636* Prepare addresses for delivery *
3637*************************************************/
3638
3639/* This function is called to flush out error settings from previous delivery
3640attempts to other hosts. It also records whether we got here via an MX record
3641or not in the more_errno field of the address. We are interested only in
3642addresses that are still marked DEFER - others may have got delivered to a
3643previously considered IP address. Set their status to PENDING_DEFER to indicate
3644which ones are relevant this time.
3645
3646Arguments:
3647 addrlist the list of addresses
3648 host the host we are delivering to
3649
3650Returns: the first address for this delivery
3651*/
3652
3653static address_item *
3654prepare_addresses(address_item *addrlist, host_item *host)
3655{
3656address_item *first_addr = NULL;
3657address_item *addr;
7b4c8c1f 3658for (addr = addrlist; addr; addr = addr->next)
168dec3b
JH
3659 if (addr->transport_return == DEFER)
3660 {
7b4c8c1f 3661 if (!first_addr) first_addr = addr;
168dec3b
JH
3662 addr->transport_return = PENDING_DEFER;
3663 addr->basic_errno = 0;
3664 addr->more_errno = (host->mx >= 0)? 'M' : 'A';
3665 addr->message = NULL;
a7538db1 3666#ifdef SUPPORT_TLS
168dec3b
JH
3667 addr->cipher = NULL;
3668 addr->ourcert = NULL;
3669 addr->peercert = NULL;
3670 addr->peerdn = NULL;
3671 addr->ocsp = OCSP_NOT_REQ;
895fbaf2
JH
3672#endif
3673#ifdef EXPERIMENTAL_DSN_INFO
3674 addr->smtp_greeting = NULL;
3675 addr->helo_response = NULL;
a7538db1 3676#endif
168dec3b 3677 }
0756eb3c
PH
3678return first_addr;
3679}
3680
3681
3682
3683/*************************************************
3684* Main entry point *
3685*************************************************/
3686
3687/* See local README for interface details. As this is a remote transport, it is
3688given a chain of addresses to be delivered in one connection, if possible. It
3689always returns TRUE, indicating that each address has its own independent
3690status set, except if there is a setting up problem, in which case it returns
3691FALSE. */
3692
3693BOOL
3694smtp_transport_entry(
3695 transport_instance *tblock, /* data for this instantiation */
3696 address_item *addrlist) /* addresses we are working on */
3697{
3698int cutoff_retry;
a843a57e 3699int defport;
0756eb3c
PH
3700int hosts_defer = 0;
3701int hosts_fail = 0;
3702int hosts_looked_up = 0;
3703int hosts_retry = 0;
3704int hosts_serial = 0;
3705int hosts_total = 0;
8e669ac1 3706int total_hosts_tried = 0;
0756eb3c
PH
3707address_item *addr;
3708BOOL expired = TRUE;
0756eb3c
PH
3709uschar *expanded_hosts = NULL;
3710uschar *pistring;
3711uschar *tid = string_sprintf("%s transport", tblock->name);
3712smtp_transport_options_block *ob =
3713 (smtp_transport_options_block *)(tblock->options_block);
3714host_item *hostlist = addrlist->host_list;
3715host_item *host = NULL;
3716
3717DEBUG(D_transport)
3718 {
3719 debug_printf("%s transport entered\n", tblock->name);
7b4c8c1f 3720 for (addr = addrlist; addr; addr = addr->next)
0756eb3c 3721 debug_printf(" %s\n", addr->address);
7b4c8c1f
JH
3722 if (hostlist)
3723 {
3724 debug_printf("hostlist:\n");
3725 for (host = hostlist; host; host = host->next)
3726 debug_printf(" %s:%d\n", host->name, host->port);
3727 }
57cc2785
JH
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);
0756eb3c
PH
3732 }
3733
f6c332bd
PH
3734/* Set the flag requesting that these hosts be added to the waiting
3735database if the delivery fails temporarily or if we are running with
3736queue_smtp or a 2-stage queue run. This gets unset for certain
3737kinds of error, typically those that are specific to the message. */
3738
3739update_waiting = TRUE;
3740
0756eb3c
PH
3741/* If a host list is not defined for the addresses - they must all have the
3742same one in order to be passed to a single transport - or if the transport has
3743a host list with hosts_override set, use the host list supplied with the
3744transport. It is an error for this not to exist. */
3745
7b4c8c1f 3746if (!hostlist || (ob->hosts_override && ob->hosts))
0756eb3c 3747 {
7b4c8c1f 3748 if (!ob->hosts)
0756eb3c
PH
3749 {
3750 addrlist->message = string_sprintf("%s transport called with no hosts set",
3751 tblock->name);
3752 addrlist->transport_return = PANIC;
3753 return FALSE; /* Only top address has status */
3754 }
3755
3756 DEBUG(D_transport) debug_printf("using the transport's hosts: %s\n",
3757 ob->hosts);
3758
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. */
3766
7b4c8c1f 3767 if (!ob->hostlist)
0756eb3c
PH
3768 {
3769 uschar *s = ob->hosts;
3770
3771 if (Ustrchr(s, '$') != NULL)
3772 {
d427a7f9 3773 if (!(expanded_hosts = expand_string(s)))
0756eb3c
PH
3774 {
3775 addrlist->message = string_sprintf("failed to expand list of hosts "
3776 "\"%s\" in %s transport: %s", s, tblock->name, expand_string_message);
7b4c8c1f 3777 addrlist->transport_return = search_find_defer ? DEFER : PANIC;
0756eb3c
PH
3778 return FALSE; /* Only top address has status */
3779 }
3780 DEBUG(D_transport) debug_printf("expanded list of hosts \"%s\" to "
3781 "\"%s\"\n", s, expanded_hosts);
3782 s = expanded_hosts;
3783 }
3784 else
3785 if (ob->hosts_randomize) s = expanded_hosts = string_copy(s);
3786
3787 host_build_hostlist(&hostlist, s, ob->hosts_randomize);
3788
e276e04b 3789 /* Check that the expansion yielded something useful. */
7b4c8c1f 3790 if (!hostlist)
e276e04b
TF
3791 {
3792 addrlist->message =
3793 string_sprintf("%s transport has empty hosts setting", tblock->name);
3794 addrlist->transport_return = PANIC;
3795 return FALSE; /* Only top address has status */
3796 }
3797
0756eb3c
PH
3798 /* If there was no expansion of hosts, save the host list for
3799 next time. */
3800
d427a7f9 3801 if (!expanded_hosts) ob->hostlist = hostlist;
0756eb3c
PH
3802 }
3803
3804 /* This is not the first time this transport has been run in this delivery;
3805 the host list was built previously. */
3806
55414b25
JH
3807 else
3808 hostlist = ob->hostlist;
0756eb3c
PH
3809 }
3810
3811/* The host list was supplied with the address. If hosts_randomize is set, we
3812must sort it into a random order if it did not come from MX records and has not
3813already been randomized (but don't bother if continuing down an existing
3814connection). */
3815
7b4c8c1f 3816else if (ob->hosts_randomize && hostlist->mx == MX_NONE && !continue_hostname)
0756eb3c
PH
3817 {
3818 host_item *newlist = NULL;
7b4c8c1f 3819 while (hostlist)
0756eb3c
PH
3820 {
3821 host_item *h = hostlist;
3822 hostlist = hostlist->next;
3823
3824 h->sort_key = random_number(100);
3825
7b4c8c1f 3826 if (!newlist)
0756eb3c
PH
3827 {
3828 h->next = NULL;
3829 newlist = h;
3830 }
3831 else if (h->sort_key < newlist->sort_key)
3832 {
3833 h->next = newlist;
3834 newlist = h;
3835 }
3836 else
3837 {
3838 host_item *hh = newlist;
7b4c8c1f 3839 while (hh->next)
0756eb3c
PH
3840 {
3841 if (h->sort_key < hh->next->sort_key) break;
3842 hh = hh->next;
3843 }
3844 h->next = hh->next;
3845 hh->next = h;
3846 }
3847 }
3848
3849 hostlist = addrlist->host_list = newlist;
3850 }
3851
2d280592 3852/* Sort out the default port. */
0756eb3c 3853
a843a57e 3854if (!smtp_get_port(ob->port, addrlist, &defport, tid)) return FALSE;
0756eb3c 3855
0756eb3c
PH
3856/* For each host-plus-IP-address on the list:
3857
3858. If this is a continued delivery and the host isn't the one with the
3859 current connection, skip.
3860
3861. If the status is unusable (i.e. previously failed or retry checked), skip.
3862
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.
3867
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.
3872
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
3875 of the hosts loop.
3876
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.
3880
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.
3883
3884. If OK, add a "remove" retry item for this host/IPaddress, if any.
3885
3886. If fail to connect, or other defer state, add a retry item.
3887
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
533244af 3890 by hosts_max_try or hosts_max_try_hardlimit; otherwise return. Note that
8e669ac1
PH
3891 there is some fancy logic for hosts_max_try that means its limit can be
3892 overstepped in some circumstances.
0756eb3c
PH
3893
3894If we get to the end of the list, all hosts have deferred at least one address,
3895or not reached their retry times. If delay_after_cutoff is unset, it requests a
3896delivery attempt to those hosts whose last try was before the arrival time of
3897the current message. To cope with this, we have to go round the loop a second
3898time. After that, set the status and error data for any addresses that haven't
3899had it set already. */
3900
7b4c8c1f
JH
3901for (cutoff_retry = 0;
3902 expired && cutoff_retry < (ob->delay_after_cutoff ? 1 : 2);
0756eb3c
PH
3903 cutoff_retry++)
3904 {
3905 host_item *nexthost = NULL;
3906 int unexpired_hosts_tried = 0;
3907
3908 for (host = hostlist;
7b4c8c1f
JH
3909 host
3910 && unexpired_hosts_tried < ob->hosts_max_try
3911 && total_hosts_tried < ob->hosts_max_try_hardlimit;
0756eb3c
PH
3912 host = nexthost)
3913 {
3914 int rc;
3915 int host_af;
3916 uschar *rs;
0756eb3c
PH
3917 BOOL host_is_expired = FALSE;
3918 BOOL message_defer = FALSE;
0756eb3c
PH
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;
3925
9c4e8f60
PH
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). */
3929
3930 nexthost = host->next;
3931
0756eb3c
PH
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.
3938
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.
3942
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. */
3945
7b4c8c1f 3946 if (!host->address)
0756eb3c 3947 {
322050c2 3948 int new_port, flags;
7cd1141b 3949 host_item *hh;
0756eb3c
PH
3950
3951 if (host->status >= hstatus_unusable)
3952 {
3953 DEBUG(D_transport) debug_printf("%s has no address and is unusable - skipping\n",
3954 host->name);
3955 continue;
3956 }
3957
3958 DEBUG(D_transport) debug_printf("getting address for %s\n", host->name);
3959
7cd1141b
PH
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. */
3962
3963 new_port = host_item_get_port(host);
3964
3965 /* Count hosts looked up */
3966
0756eb3c
PH
3967 hosts_looked_up++;
3968
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. */
3971
322050c2
PH
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;
3975
7e66e54d 3976 if (ob->gethostbyname || string_is_ip_address(host->name, NULL) != 0)
55414b25 3977 rc = host_find_byname(host, NULL, flags, NULL, TRUE);
0756eb3c 3978 else
0756eb3c 3979 rc = host_find_bydns(host, NULL, flags, NULL, NULL, NULL,
7cd171b7 3980 &ob->dnssec, /* domains for request/require */
55414b25 3981 NULL, NULL);
0756eb3c 3982
7cd1141b
PH
3983 /* Update the host (and any additional blocks, resulting from
3984 multihoming) with a host-specific port, if any. */
3985
3986 for (hh = host; hh != nexthost; hh = hh->next) hh->port = new_port;
3987
0756eb3c
PH
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. */
3995
2546388c 3996 if (rc == HOST_FIND_AGAIN || rc == HOST_FIND_SECURITY || rc == HOST_FIND_FAILED)
0756eb3c
PH
3997 {
3998 retry_add_item(addrlist, string_sprintf("R:%s", host->name), 0);
3999 expired = FALSE;
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;
4004
7b4c8c1f 4005 for (addr = addrlist; addr; addr = addr->next)
0756eb3c
PH
4006 {
4007 if (addr->transport_return != DEFER) continue;
4008 addr->basic_errno = ERRNO_UNKNOWNHOST;
2546388c
JH
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",
4013 host->name);
0756eb3c
PH
4014 }
4015 continue;
4016 }
4017
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. */
4021
4022 if (rc == HOST_FOUND_LOCAL && !ob->allow_localhost)
4023 {
7b4c8c1f 4024 for (addr = addrlist; addr; addr = addr->next)
0756eb3c
PH
4025 {
4026 addr->basic_errno = 0;
4027 addr->message = string_sprintf("%s transport found host %s to be "
4028 "local", tblock->name, host->name);
4029 }
4030 goto END_TRANSPORT;
4031 }
4032 } /* End of block for IP address lookup */
4033
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
4038 twice. */
4039
7b4c8c1f
JH
4040 if ( continue_hostname
4041 && ( Ustrcmp(continue_hostname, host->name) != 0
4042 || Ustrcmp(continue_host_address, host->address) != 0
4043 ) )
0756eb3c
PH
4044 {
4045 expired = FALSE;
4046 continue; /* With next host */
4047 }
4048
9c4e8f60
PH
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. */
83364d30
PH
4051
4052 nexthost = host->next;
4053
0756eb3c
PH
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. */
4060
4061 if ((!deliver_force || queue_2stage) && (queue_smtp ||
55414b25
JH
4062 match_isinlist(addrlist->domain,
4063 (const uschar **)&queue_smtp_domains, 0,
cf39cf57 4064 &domainlist_anchor, NULL, MCL_DOMAIN, TRUE, NULL) == OK))
0756eb3c
PH
4065 {
4066 expired = FALSE;
7b4c8c1f
JH
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";
0756eb3c
PH
4070 continue; /* With next host */
4071 }
4072
4073 /* Count hosts being considered - purely for an intelligent comment
4074 if none are usable. */
4075
4076 hosts_total++;
4077
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. */
4081
4082 deliver_host = host->name;
4083 deliver_host_address = host->address;
783b385f
JH
4084 lookup_dnssec_authenticated = host->dnssec == DS_YES ? US"yes"
4085 : host->dnssec == DS_NO ? US"no"
4086 : US"";
0756eb3c 4087
7cd1141b
PH
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
4090 the default. */
4091
7b4c8c1f 4092 pistring = string_sprintf(":%d", host->port == PORT_NONE
a843a57e 4093 ? defport : host->port);
7cd1141b
PH
4094 if (Ustrcmp(pistring, ":25") == 0) pistring = US"";
4095
0756eb3c 4096 /* Select IPv4 or IPv6, and choose an outgoing interface. If the interface
6f6dedcc
JH
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. */
0756eb3c 4101
7b4c8c1f 4102 host_af = Ustrchr(host->address, ':') == NULL ? AF_INET : AF_INET6;
6f6dedcc
JH
4103 if ((rs = ob->interface) && *rs)
4104 {
4105 if (!smtp_get_interface(rs, host_af, addrlist, &interface, tid))
4106 return FALSE;
4107 pistring = string_sprintf("%s/%s", pistring, interface);
4108 }
0756eb3c
PH
4109
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. */
4113
4114 if (cutoff_retry == 0)
4115 {
9c695f6d 4116 BOOL incl_ip;
0756eb3c 4117 /* Ensure the status of the address is set by checking retry data if
9c695f6d 4118 necessary. There may be host-specific retry data (applicable to all
0756eb3c
PH
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. */
4122
9c695f6d
JH
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 */
4127
0756eb3c 4128 host_is_expired = retry_check_address(addrlist->domain, host, pistring,
9c695f6d 4129 incl_ip, &retry_host_key, &retry_message_key);
0756eb3c 4130
875512a3 4131 DEBUG(D_transport) debug_printf("%s [%s]%s retry-status = %s\n", host->name,
0756eb3c
PH
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)" : "?");
4136
4137 /* Skip this address if not usable at this time, noting if it wasn't
4138 actually expired, both locally and in the address. */
4139
4140 switch (host->status)
4141 {
4142 case hstatus_unusable:
7b4c8c1f
JH
4143 expired = FALSE;
4144 setflag(addrlist, af_retry_skipped);
4145 /* Fall through */
0756eb3c
PH
4146
4147 case hstatus_unusable_expired:
7b4c8c1f
JH
4148 switch (host->why)
4149 {
4150 case hwhy_retry: hosts_retry++; break;
4151 case hwhy_failed: hosts_fail++; break;
2546388c 4152 case hwhy_insecure:
7b4c8c1f
JH
4153 case hwhy_deferred: hosts_defer++; break;
4154 }
4155
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. */
4159
4160 if (retry_message_key) update_waiting = FALSE;
4161 continue; /* With the next host or IP address */
0756eb3c
PH
4162 }
4163 }
4164
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. */
4167
4168 else
4169 {
7b4c8c1f
JH
4170 if ( !host->address
4171 || host->status != hstatus_unusable_expired
32dfdf8b 4172 || host->last_try > received_time.tv_sec)
0756eb3c 4173 continue;
7b4c8c1f 4174 DEBUG(D_transport) debug_printf("trying expired host %s [%s]%s\n",
0756eb3c
PH
4175 host->name, host->address, pistring);
4176 host_is_expired = TRUE;
4177 }
4178
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.
4181 */
4182
4183 expired = FALSE;
4184
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. */
4190
7b4c8c1f
JH
4191 if ( !continue_hostname
4192 && verify_check_given_host(&ob->serialize_hosts, host) == OK)
0756eb3c
PH
4193 {
4194 serialize_key = string_sprintf("host-serialize-%s", host->name);
e8ae7214 4195 if (!enq_start(serialize_key, 1))
0756eb3c
PH
4196 {
4197 DEBUG(D_transport)
4198 debug_printf("skipping host %s because another Exim process "
4199 "is connected to it\n", host->name);
4200 hosts_serial++;
4201 continue;
4202 }
0756eb3c
PH
4203 }
4204
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. */
4211
4212 first_addr = prepare_addresses(addrlist, host);
4213
4214 DEBUG(D_transport) debug_printf("delivering %s to %s [%s] (%s%s)\n",
4215 message_id, host->name, host->address, addrlist->address,
7b4c8c1f 4216 addrlist->next ? ", ..." : "");
0756eb3c
PH
4217
4218 set_process_info("delivering %s to %s [%s] (%s%s)",
4219 message_id, host->name, host->address, addrlist->address,
7b4c8c1f 4220 addrlist->next ? ", ..." : "");
0756eb3c
PH
4221
4222 /* This is not for real; don't do the delivery. If there are
4223 any remaining hosts, list them. */
4224
4225 if (dont_deliver)
4226 {
4227 host_item *host2;
895fbaf2 4228 set_errno_nohost(addrlist, 0, NULL, OK, FALSE);
7b4c8c1f 4229 for (addr = addrlist; addr; addr = addr->next)
0756eb3c
PH
4230 {
4231 addr->host_used = host;
4232 addr->special_action = '*';
4233 addr->message = US"delivery bypassed by -N option";
4234 }
4235 DEBUG(D_transport)
4236 {
4237 debug_printf("*** delivery by %s transport bypassed by -N option\n"
4238 "*** host and remaining hosts:\n", tblock->name);
7b4c8c1f 4239 for (host2 = host; host2; host2 = host2->next)
0756eb3c 4240 debug_printf(" %s [%s]\n", host2->name,
7b4c8c1f 4241 host2->address ? host2->address : US"unset");
0756eb3c
PH
4242 }
4243 rc = OK;
4244 }
4245
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
8e669ac1 4248 is timed out, unless hosts_max_try_hardlimit (which protects against
533244af 4249 lunatic DNS configurations) is reached.
8e669ac1 4250
533244af
PH
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. */
0756eb3c
PH
4258
4259 else
4260 {
d427a7f9
JH
4261 host_item * thost;
4262 /* Make a copy of the host if it is local to this invocation
4263 of the transport. */
4264
4265 if (expanded_hosts)
4266 {
4267 thost = store_get(sizeof(host_item));
4268 *thost = *host;
4269 thost->name = string_copy(host->name);
4270 thost->address = string_copy(host->address);
4271 }
4272 else
4273 thost = host;
4274
0756eb3c
PH
4275 if (!host_is_expired && ++unexpired_hosts_tried >= ob->hosts_max_try)
4276 {
4277 host_item *h;
4278 DEBUG(D_transport)
4279 debug_printf("hosts_max_try limit reached with this host\n");
1a47b633
JH
4280 for (h = host; h; h = h->next) if (h->mx != host->mx)
4281 {
4282 nexthost = h;
4283 unexpired_hosts_tried--;
4284 DEBUG(D_transport) debug_printf("however, a higher MX host exists "
4285 "and will be tried\n");
4286 break;
4287 }
0756eb3c
PH
4288 }
4289
4290 /* Attempt the delivery. */
4291
533244af 4292 total_hosts_tried++;
a843a57e 4293 rc = smtp_deliver(addrlist, thost, host_af, defport, interface, tblock,
d427a7f9 4294 &message_defer, FALSE);
0756eb3c
PH
4295
4296 /* Yield is one of:
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
4303 */
4304
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. */
4310
7b4c8c1f
JH
4311 if (rc == DEFER && first_addr->basic_errno != ERRNO_AUTHFAIL
4312 && first_addr->basic_errno != ERRNO_TLSFAILURE)
0756eb3c
PH
4313 write_logs(first_addr, host);
4314
0cbf2b82 4315#ifndef DISABLE_EVENT
d68218c7 4316 if (rc == DEFER)
774ef2d7 4317 deferred_event_raise(first_addr, host);
a7538db1 4318#endif
d68218c7 4319
0756eb3c
PH
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().] */
4328
a7538db1 4329#ifdef SUPPORT_TLS
7a31d643
JH
4330 if ( rc == DEFER
4331 && first_addr->basic_errno == ERRNO_TLSFAILURE
4332 && ob->tls_tempfail_tryclear
5130845b 4333 && verify_check_given_host(&ob->hosts_require_tls, host) != OK
7a31d643 4334 )
0756eb3c 4335 {
cf0c6164
JH
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);
0756eb3c 4339 first_addr = prepare_addresses(addrlist, host);
a843a57e 4340 rc = smtp_deliver(addrlist, thost, host_af, defport, interface, tblock,
d427a7f9 4341 &message_defer, TRUE);
0756eb3c
PH
4342 if (rc == DEFER && first_addr->basic_errno != ERRNO_AUTHFAIL)
4343 write_logs(first_addr, host);
0cbf2b82 4344# ifndef DISABLE_EVENT
d68218c7 4345 if (rc == DEFER)
774ef2d7 4346 deferred_event_raise(first_addr, host);
a7538db1 4347# endif
0756eb3c 4348 }
a1bccd48 4349#endif /*SUPPORT_TLS*/
0756eb3c
PH
4350 }
4351
4352 /* Delivery attempt finished */
4353
7b4c8c1f
JH
4354 rs = rc == OK ? US"OK"
4355 : rc == DEFER ? US"DEFER"
4356 : rc == ERROR ? US"ERROR"
4357 : US"?";
0756eb3c
PH
4358
4359 set_process_info("delivering %s: just tried %s [%s] for %s%s: result %s",
4360 message_id, host->name, host->address, addrlist->address,
7b4c8c1f 4361 addrlist->next ? " (& others)" : "", rs);
0756eb3c
PH
4362
4363 /* Release serialization if set up */
4364
7b4c8c1f 4365 if (serialize_key) enq_end(serialize_key);
0756eb3c
PH
4366
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.) */
4374
7b4c8c1f 4375 if (rc == DEFER || retry_host_key)
0756eb3c 4376 {
7b4c8c1f
JH
4377 int delete_flag = rc != DEFER ? rf_delete : 0;
4378 if (!retry_host_key)
0756eb3c 4379 {
9c695f6d
JH
4380 BOOL incl_ip;
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 */
4385
7b4c8c1f
JH
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);
0756eb3c
PH
4389 }
4390
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. */
4400
7b4c8c1f 4401 if (delete_flag != 0 || !continue_hostname)
0756eb3c
PH
4402 retry_add_item(first_addr, retry_host_key, rf_host | delete_flag);
4403
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. */
4406
4407 if (rc == DEFER)
4408 {
7b4c8c1f
JH
4409 host->status = host_is_expired
4410 ? hstatus_unusable_expired : hstatus_unusable;
0756eb3c
PH
4411 host->why = hwhy_deferred;
4412 }
4413 }
4414
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
f6c332bd 4421 for specific hosts. */
0756eb3c 4422
7b4c8c1f 4423 if (message_defer || retry_message_key)
0756eb3c 4424 {
7b4c8c1f
JH
4425 int delete_flag = message_defer ? 0 : rf_delete;
4426 if (!retry_message_key)
0756eb3c 4427 {
9c695f6d
JH
4428 BOOL incl_ip;
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 */
4433
7b4c8c1f
JH
4434 retry_message_key = incl_ip
4435 ? string_sprintf("T:%S:%s%s:%s", host->name, host->address, pistring,
4436 message_id)
4437 : string_sprintf("T:%S%s:%s", host->name, pistring, message_id);
0756eb3c
PH
4438 }
4439 retry_add_item(addrlist, retry_message_key,
4440 rf_message | rf_host | delete_flag);
f6c332bd 4441 update_waiting = FALSE;
0756eb3c
PH
4442 }
4443
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. */
4447
4448 if (rc == OK)
4cea764f 4449 for (addr = addrlist; addr; addr = addr->next)
0756eb3c
PH
4450 if (addr->transport_return == DEFER)
4451 {
4452 some_deferred = TRUE;
4453 break;
4454 }
0756eb3c
PH
4455
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. */
4459
4460 if (rc == ERROR || (rc == OK && !some_deferred))
4461 {
4462 DEBUG(D_transport) debug_printf("Leaving %s transport\n", tblock->name);
4463 return TRUE; /* Each address has its status */
4464 }
4465
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. */
4470
7b4c8c1f 4471 if (continue_hostname) break;
0756eb3c
PH
4472
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
533244af 4479 out. NOTE: this does not apply to hosts_max_try_hardlimit. */
0756eb3c 4480
7b4c8c1f 4481 if ((rc == DEFER || some_deferred) && nexthost)
0756eb3c
PH
4482 {
4483 BOOL timedout;
4484 retry_config *retry = retry_find_config(host->name, NULL, 0, 0);
4485
7b4c8c1f 4486 if (retry && retry->rules)
0756eb3c
PH
4487 {
4488 retry_rule *last_rule;
4489 for (last_rule = retry->rules;
7b4c8c1f 4490 last_rule->next;
0756eb3c 4491 last_rule = last_rule->next);
32dfdf8b 4492 timedout = time(NULL) - received_time.tv_sec > last_rule->timeout;
0756eb3c
PH
4493 }
4494 else timedout = TRUE; /* No rule => timed out */
4495
4496 if (timedout)
4497 {
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");
4501 }
4502 }
4503 } /* End of loop for trying multiple hosts. */
4504
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. */
4508
4509 DEBUG(D_transport)
4510 {
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");
4514 }
4515 }
4516
4517
4518/* Get here if all IP addresses are skipped or defer at least one address. In
4519MUA wrapper mode, this will happen only for connection or other non-message-
4520specific failures. Force the delivery status for all addresses to FAIL. */
4521
4522if (mua_wrapper)
4523 {
7b4c8c1f 4524 for (addr = addrlist; addr; addr = addr->next)
0756eb3c
PH
4525 addr->transport_return = FAIL;
4526 goto END_TRANSPORT;
4527 }
4528
4529/* In the normal, non-wrapper case, add a standard message to each deferred
4530address if there hasn't been an error, that is, if it hasn't actually been
4531tried this time. The variable "expired" will be FALSE if any deliveries were
4532actually tried, or if there was at least one host that was not expired. That
4533is, it is TRUE only if no deliveries were tried and all hosts were expired. If
4534a delivery has been tried, an error code will be set, and the failing of the
4535message is handled by the retry code later.
4536
4537If queue_smtp is set, or this transport was called to send a subsequent message
4538down an existing TCP/IP connection, and something caused the host not to be
4539found, we end up here, but can detect these cases and handle them specially. */
4540
c3f2eb9a 4541for (addr = addrlist; addr; addr = addr->next)
0756eb3c
PH
4542 {
4543 /* If host is not NULL, it means that we stopped processing the host list
533244af
PH
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.
8e669ac1 4547 However, if we have hit hosts_max_try_hardlimit, we want to behave as if all
533244af 4548 hosts were tried. */
0756eb3c 4549
c3f2eb9a 4550 if (host)
533244af
PH
4551 if (total_hosts_tried >= ob->hosts_max_try_hardlimit)
4552 {
4553 DEBUG(D_transport)
4554 debug_printf("hosts_max_try_hardlimit reached: behave as if all "
4555 "hosts were tried\n");
4556 }
4557 else
8e669ac1 4558 {
533244af
PH
4559 DEBUG(D_transport)
4560 debug_printf("hosts_max_try limit caused some hosts to be skipped\n");
4561 setflag(addr, af_retry_skipped);
8e669ac1 4562 }
0756eb3c
PH
4563
4564 if (queue_smtp) /* no deliveries attempted */
4565 {
4566 addr->transport_return = DEFER;
4567 addr->basic_errno = 0;
4568 addr->message = US"SMTP delivery explicitly queued";
4569 }
4570
c3f2eb9a
JH
4571 else if ( addr->transport_return == DEFER
4572 && (addr->basic_errno == ERRNO_UNKNOWNERROR || addr->basic_errno == 0)
4573 && !addr->message
4574 )
0756eb3c
PH
4575 {
4576 addr->basic_errno = ERRNO_HRETRY;
c3f2eb9a 4577 if (continue_hostname)
0756eb3c 4578 addr->message = US"no host found for existing SMTP connection";
0756eb3c
PH
4579 else if (expired)
4580 {
fffffe4c 4581 setflag(addr, af_pass_message); /* This is not a security risk */
c3f2eb9a
JH
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");
0756eb3c
PH
4588
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. */
4591
c3f2eb9a 4592 if (addr->host_list == addr->fallback_hosts || !addr->fallback_hosts)
0756eb3c
PH
4593 addr->transport_return = FAIL;
4594 }
4595 else
4596 {
93a680e4 4597 const char * s;
0756eb3c 4598 if (hosts_retry == hosts_total)
93a680e4 4599 s = "retry time not reached for any host%s";
0756eb3c 4600 else if (hosts_fail == hosts_total)
93a680e4 4601 s = "all host address lookups%s failed permanently";
0756eb3c 4602 else if (hosts_defer == hosts_total)
93a680e4 4603 s = "all host address lookups%s failed temporarily";
0756eb3c 4604 else if (hosts_serial == hosts_total)
93a680e4 4605 s = "connection limit reached for all hosts%s";
0756eb3c 4606 else if (hosts_fail+hosts_defer == hosts_total)
93a680e4 4607 s = "all host address lookups%s failed";
3cf01803 4608 else
93a680e4 4609 s = "some host address lookups failed and retry time "
3cf01803
JH
4610 "not reached for other hosts or connection limit reached%s";
4611
4612 addr->message = string_sprintf(s,
4613 addr->domain ? string_sprintf(" for '%s'", addr->domain) : US"");
0756eb3c
PH
4614 }
4615 }
4616 }
4617
4618/* Update the database which keeps information about which messages are waiting
f6c332bd
PH
4619for which hosts to become available. For some message-specific errors, the
4620update_waiting flag is turned off because we don't want follow-on deliveries in
ea722490 4621those cases. If this transport instance is explicitly limited to one message
8b260705
PP
4622per connection then follow-on deliveries are not possible and there's no need
4623to create/update the per-transport wait-<transport_name> database. */
0756eb3c 4624
ea722490
JH
4625if (update_waiting && tblock->connection_max_messages != 1)
4626 transport_update_waiting(hostlist, tblock->name);
0756eb3c
PH
4627
4628END_TRANSPORT:
4629
4630DEBUG(D_transport) debug_printf("Leaving %s transport\n", tblock->name);
4631
4632return TRUE; /* Each address has its status */
4633}
4634
d185889f 4635#endif /*!MACRO_PREDEF*/
578897ea
JH
4636/* vi: aw ai sw=2
4637*/
0756eb3c 4638/* End of transport/smtp.c */