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"*",
fd98a5c6 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,
f5d78688 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