Update DANE draft docs
[exim.git] / src / src / transports / smtp.c
1 /*************************************************
2 * Exim - an Internet mail transport agent *
3 *************************************************/
4
5 /* Copyright (c) University of Cambridge 1995 - 2014 */
6 /* See the file NOTICE for conditions of use and distribution. */
7
8 #include "../exim.h"
9 #include "smtp.h"
10
11 #define PENDING 256
12 #define PENDING_DEFER (PENDING + DEFER)
13 #define PENDING_OK (PENDING + OK)
14
15
16 /* Options specific to the smtp transport. This transport also supports LMTP
17 over TCP/IP. The options must be in alphabetic order (note that "_" comes
18 before the lower case letters). Some live in the transport_instance block so as
19 to be publicly visible; these are flagged with opt_public. */
20
21 optionlist smtp_transport_options[] = {
22 { "address_retry_include_sender", opt_bool,
23 (void *)offsetof(smtp_transport_options_block, address_retry_include_sender) },
24 { "allow_localhost", opt_bool,
25 (void *)offsetof(smtp_transport_options_block, allow_localhost) },
26 { "authenticated_sender", opt_stringptr,
27 (void *)offsetof(smtp_transport_options_block, authenticated_sender) },
28 { "authenticated_sender_force", opt_bool,
29 (void *)offsetof(smtp_transport_options_block, authenticated_sender_force) },
30 { "command_timeout", opt_time,
31 (void *)offsetof(smtp_transport_options_block, command_timeout) },
32 { "connect_timeout", opt_time,
33 (void *)offsetof(smtp_transport_options_block, connect_timeout) },
34 { "connection_max_messages", opt_int | opt_public,
35 (void *)offsetof(transport_instance, connection_max_messages) },
36 { "data_timeout", opt_time,
37 (void *)offsetof(smtp_transport_options_block, data_timeout) },
38 { "delay_after_cutoff", opt_bool,
39 (void *)offsetof(smtp_transport_options_block, delay_after_cutoff) },
40 #ifndef DISABLE_DKIM
41 { "dkim_canon", opt_stringptr,
42 (void *)offsetof(smtp_transport_options_block, dkim_canon) },
43 { "dkim_domain", opt_stringptr,
44 (void *)offsetof(smtp_transport_options_block, dkim_domain) },
45 { "dkim_private_key", opt_stringptr,
46 (void *)offsetof(smtp_transport_options_block, dkim_private_key) },
47 { "dkim_selector", opt_stringptr,
48 (void *)offsetof(smtp_transport_options_block, dkim_selector) },
49 { "dkim_sign_headers", opt_stringptr,
50 (void *)offsetof(smtp_transport_options_block, dkim_sign_headers) },
51 { "dkim_strict", opt_stringptr,
52 (void *)offsetof(smtp_transport_options_block, dkim_strict) },
53 #endif
54 { "dns_qualify_single", opt_bool,
55 (void *)offsetof(smtp_transport_options_block, dns_qualify_single) },
56 { "dns_search_parents", opt_bool,
57 (void *)offsetof(smtp_transport_options_block, dns_search_parents) },
58 { "dnssec_request_domains", opt_stringptr,
59 (void *)offsetof(smtp_transport_options_block, dnssec_request_domains) },
60 { "dnssec_require_domains", opt_stringptr,
61 (void *)offsetof(smtp_transport_options_block, dnssec_require_domains) },
62 { "dscp", opt_stringptr,
63 (void *)offsetof(smtp_transport_options_block, dscp) },
64 { "fallback_hosts", opt_stringptr,
65 (void *)offsetof(smtp_transport_options_block, fallback_hosts) },
66 { "final_timeout", opt_time,
67 (void *)offsetof(smtp_transport_options_block, final_timeout) },
68 { "gethostbyname", opt_bool,
69 (void *)offsetof(smtp_transport_options_block, gethostbyname) },
70 #ifdef SUPPORT_TLS
71 /* These are no longer honoured, as of Exim 4.80; for now, we silently
72 ignore; 4.83 will warn, and a later-still release will remove
73 these options, so that using them becomes an error. */
74 { "gnutls_require_kx", opt_stringptr,
75 (void *)offsetof(smtp_transport_options_block, gnutls_require_kx) },
76 { "gnutls_require_mac", opt_stringptr,
77 (void *)offsetof(smtp_transport_options_block, gnutls_require_mac) },
78 { "gnutls_require_protocols", opt_stringptr,
79 (void *)offsetof(smtp_transport_options_block, gnutls_require_proto) },
80 #endif
81 { "helo_data", opt_stringptr,
82 (void *)offsetof(smtp_transport_options_block, helo_data) },
83 { "hosts", opt_stringptr,
84 (void *)offsetof(smtp_transport_options_block, hosts) },
85 { "hosts_avoid_esmtp", opt_stringptr,
86 (void *)offsetof(smtp_transport_options_block, hosts_avoid_esmtp) },
87 { "hosts_avoid_pipelining", opt_stringptr,
88 (void *)offsetof(smtp_transport_options_block, hosts_avoid_pipelining) },
89 #ifdef SUPPORT_TLS
90 { "hosts_avoid_tls", opt_stringptr,
91 (void *)offsetof(smtp_transport_options_block, hosts_avoid_tls) },
92 #endif
93 { "hosts_max_try", opt_int,
94 (void *)offsetof(smtp_transport_options_block, hosts_max_try) },
95 { "hosts_max_try_hardlimit", opt_int,
96 (void *)offsetof(smtp_transport_options_block, hosts_max_try_hardlimit) },
97 #ifdef SUPPORT_TLS
98 { "hosts_nopass_tls", opt_stringptr,
99 (void *)offsetof(smtp_transport_options_block, hosts_nopass_tls) },
100 #endif
101 { "hosts_override", opt_bool,
102 (void *)offsetof(smtp_transport_options_block, hosts_override) },
103 { "hosts_randomize", opt_bool,
104 (void *)offsetof(smtp_transport_options_block, hosts_randomize) },
105 #if defined(SUPPORT_TLS) && !defined(DISABLE_OCSP)
106 { "hosts_request_ocsp", opt_stringptr,
107 (void *)offsetof(smtp_transport_options_block, hosts_request_ocsp) },
108 #endif
109 { "hosts_require_auth", opt_stringptr,
110 (void *)offsetof(smtp_transport_options_block, hosts_require_auth) },
111 #ifdef SUPPORT_TLS
112 # ifdef EXPERIMENTAL_DANE
113 { "hosts_require_dane", opt_stringptr,
114 (void *)offsetof(smtp_transport_options_block, hosts_require_dane) },
115 # endif
116 # ifndef DISABLE_OCSP
117 { "hosts_require_ocsp", opt_stringptr,
118 (void *)offsetof(smtp_transport_options_block, hosts_require_ocsp) },
119 # endif
120 { "hosts_require_tls", opt_stringptr,
121 (void *)offsetof(smtp_transport_options_block, hosts_require_tls) },
122 #endif
123 { "hosts_try_auth", opt_stringptr,
124 (void *)offsetof(smtp_transport_options_block, hosts_try_auth) },
125 #if defined(SUPPORT_TLS) && defined(EXPERIMENTAL_DANE)
126 { "hosts_try_dane", opt_stringptr,
127 (void *)offsetof(smtp_transport_options_block, hosts_try_dane) },
128 #endif
129 #ifndef DISABLE_PRDR
130 { "hosts_try_prdr", opt_stringptr,
131 (void *)offsetof(smtp_transport_options_block, hosts_try_prdr) },
132 #endif
133 #ifdef SUPPORT_TLS
134 { "hosts_verify_avoid_tls", opt_stringptr,
135 (void *)offsetof(smtp_transport_options_block, hosts_verify_avoid_tls) },
136 #endif
137 { "interface", opt_stringptr,
138 (void *)offsetof(smtp_transport_options_block, interface) },
139 { "keepalive", opt_bool,
140 (void *)offsetof(smtp_transport_options_block, keepalive) },
141 { "lmtp_ignore_quota", opt_bool,
142 (void *)offsetof(smtp_transport_options_block, lmtp_ignore_quota) },
143 { "max_rcpt", opt_int | opt_public,
144 (void *)offsetof(transport_instance, max_addresses) },
145 { "multi_domain", opt_bool | opt_public,
146 (void *)offsetof(transport_instance, multi_domain) },
147 { "port", opt_stringptr,
148 (void *)offsetof(smtp_transport_options_block, port) },
149 { "protocol", opt_stringptr,
150 (void *)offsetof(smtp_transport_options_block, protocol) },
151 { "retry_include_ip_address", opt_bool,
152 (void *)offsetof(smtp_transport_options_block, retry_include_ip_address) },
153 { "serialize_hosts", opt_stringptr,
154 (void *)offsetof(smtp_transport_options_block, serialize_hosts) },
155 { "size_addition", opt_int,
156 (void *)offsetof(smtp_transport_options_block, size_addition) }
157 #ifdef SUPPORT_TLS
158 ,{ "tls_certificate", opt_stringptr,
159 (void *)offsetof(smtp_transport_options_block, tls_certificate) },
160 { "tls_crl", opt_stringptr,
161 (void *)offsetof(smtp_transport_options_block, tls_crl) },
162 { "tls_dh_min_bits", opt_int,
163 (void *)offsetof(smtp_transport_options_block, tls_dh_min_bits) },
164 { "tls_privatekey", opt_stringptr,
165 (void *)offsetof(smtp_transport_options_block, tls_privatekey) },
166 { "tls_require_ciphers", opt_stringptr,
167 (void *)offsetof(smtp_transport_options_block, tls_require_ciphers) },
168 { "tls_sni", opt_stringptr,
169 (void *)offsetof(smtp_transport_options_block, tls_sni) },
170 { "tls_tempfail_tryclear", opt_bool,
171 (void *)offsetof(smtp_transport_options_block, tls_tempfail_tryclear) },
172 { "tls_try_verify_hosts", opt_stringptr,
173 (void *)offsetof(smtp_transport_options_block, tls_try_verify_hosts) },
174 #ifdef EXPERIMENTAL_CERTNAMES
175 { "tls_verify_cert_hostnames", opt_stringptr,
176 (void *)offsetof(smtp_transport_options_block,tls_verify_cert_hostnames)},
177 #endif
178 { "tls_verify_certificates", opt_stringptr,
179 (void *)offsetof(smtp_transport_options_block, tls_verify_certificates) },
180 { "tls_verify_hosts", opt_stringptr,
181 (void *)offsetof(smtp_transport_options_block, tls_verify_hosts) }
182 #endif
183 #ifdef EXPERIMENTAL_TPDA
184 ,{ "tpda_host_defer_action", opt_stringptr,
185 (void *)offsetof(smtp_transport_options_block, tpda_host_defer_action) },
186 #endif
187 };
188
189 /* Size of the options list. An extern variable has to be used so that its
190 address can appear in the tables drtables.c. */
191
192 int smtp_transport_options_count =
193 sizeof(smtp_transport_options)/sizeof(optionlist);
194
195 /* Default private options block for the smtp transport. */
196
197 smtp_transport_options_block smtp_transport_option_defaults = {
198 NULL, /* hosts */
199 NULL, /* fallback_hosts */
200 NULL, /* hostlist */
201 NULL, /* fallback_hostlist */
202 NULL, /* authenticated_sender */
203 US"$primary_hostname", /* helo_data */
204 NULL, /* interface */
205 NULL, /* port */
206 US"smtp", /* protocol */
207 NULL, /* DSCP */
208 NULL, /* serialize_hosts */
209 NULL, /* hosts_try_auth */
210 NULL, /* hosts_require_auth */
211 #ifdef EXPERIMENTAL_DANE
212 NULL, /* hosts_try_dane */
213 NULL, /* hosts_require_dane */
214 #endif
215 #ifndef DISABLE_PRDR
216 NULL, /* hosts_try_prdr */
217 #endif
218 #ifndef DISABLE_OCSP
219 US"*", /* hosts_request_ocsp (except under DANE) */
220 NULL, /* hosts_require_ocsp */
221 #endif
222 NULL, /* hosts_require_tls */
223 NULL, /* hosts_avoid_tls */
224 US"*", /* hosts_verify_avoid_tls */
225 NULL, /* hosts_avoid_pipelining */
226 NULL, /* hosts_avoid_esmtp */
227 NULL, /* hosts_nopass_tls */
228 5*60, /* command_timeout */
229 5*60, /* connect_timeout; shorter system default overrides */
230 5*60, /* data timeout */
231 10*60, /* final timeout */
232 1024, /* size_addition */
233 5, /* hosts_max_try */
234 50, /* hosts_max_try_hardlimit */
235 TRUE, /* address_retry_include_sender */
236 FALSE, /* allow_localhost */
237 FALSE, /* authenticated_sender_force */
238 FALSE, /* gethostbyname */
239 TRUE, /* dns_qualify_single */
240 FALSE, /* dns_search_parents */
241 NULL, /* dnssec_request_domains */
242 NULL, /* dnssec_require_domains */
243 TRUE, /* delay_after_cutoff */
244 FALSE, /* hosts_override */
245 FALSE, /* hosts_randomize */
246 TRUE, /* keepalive */
247 FALSE, /* lmtp_ignore_quota */
248 TRUE /* retry_include_ip_address */
249 #ifdef SUPPORT_TLS
250 ,NULL, /* tls_certificate */
251 NULL, /* tls_crl */
252 NULL, /* tls_privatekey */
253 NULL, /* tls_require_ciphers */
254 NULL, /* gnutls_require_kx */
255 NULL, /* gnutls_require_mac */
256 NULL, /* gnutls_require_proto */
257 NULL, /* tls_sni */
258 NULL, /* tls_verify_certificates */
259 EXIM_CLIENT_DH_DEFAULT_MIN_BITS,
260 /* tls_dh_min_bits */
261 TRUE, /* tls_tempfail_tryclear */
262 NULL, /* tls_verify_hosts */
263 NULL /* tls_try_verify_hosts */
264 # ifdef EXPERIMENTAL_CERTNAMES
265 ,NULL /* tls_verify_cert_hostnames */
266 # endif
267 #endif
268 #ifndef DISABLE_DKIM
269 ,NULL, /* dkim_canon */
270 NULL, /* dkim_domain */
271 NULL, /* dkim_private_key */
272 NULL, /* dkim_selector */
273 NULL, /* dkim_sign_headers */
274 NULL /* dkim_strict */
275 #endif
276 #ifdef EXPERIMENTAL_TPDA
277 ,NULL /* tpda_host_defer_action */
278 #endif
279 };
280
281 #ifdef EXPERIMENTAL_DSN
282 /* some DSN flags for use later */
283
284 static int rf_list[] = {rf_notify_never, rf_notify_success,
285 rf_notify_failure, rf_notify_delay };
286
287 static uschar *rf_names[] = { "NEVER", "SUCCESS", "FAILURE", "DELAY" };
288 #endif
289
290
291
292 /* Local statics */
293
294 static uschar *smtp_command; /* Points to last cmd for error messages */
295 static uschar *mail_command; /* Points to MAIL cmd for error messages */
296 static BOOL update_waiting; /* TRUE to update the "wait" database */
297
298
299 /*************************************************
300 * Setup entry point *
301 *************************************************/
302
303 /* This function is called when the transport is about to be used,
304 but before running it in a sub-process. It is used for two things:
305
306 (1) To set the fallback host list in addresses, when delivering.
307 (2) To pass back the interface, port, protocol, and other options, for use
308 during callout verification.
309
310 Arguments:
311 tblock pointer to the transport instance block
312 addrlist list of addresses about to be transported
313 tf if not NULL, pointer to block in which to return options
314 uid the uid that will be set (not used)
315 gid the gid that will be set (not used)
316 errmsg place for error message (not used)
317
318 Returns: OK always (FAIL, DEFER not used)
319 */
320
321 static int
322 smtp_transport_setup(transport_instance *tblock, address_item *addrlist,
323 transport_feedback *tf, uid_t uid, gid_t gid, uschar **errmsg)
324 {
325 smtp_transport_options_block *ob =
326 (smtp_transport_options_block *)(tblock->options_block);
327
328 errmsg = errmsg; /* Keep picky compilers happy */
329 uid = uid;
330 gid = gid;
331
332 /* Pass back options if required. This interface is getting very messy. */
333
334 if (tf != NULL)
335 {
336 tf->interface = ob->interface;
337 tf->port = ob->port;
338 tf->protocol = ob->protocol;
339 tf->hosts = ob->hosts;
340 tf->hosts_override = ob->hosts_override;
341 tf->hosts_randomize = ob->hosts_randomize;
342 tf->gethostbyname = ob->gethostbyname;
343 tf->qualify_single = ob->dns_qualify_single;
344 tf->search_parents = ob->dns_search_parents;
345 tf->helo_data = ob->helo_data;
346 }
347
348 /* Set the fallback host list for all the addresses that don't have fallback
349 host lists, provided that the local host wasn't present in the original host
350 list. */
351
352 if (!testflag(addrlist, af_local_host_removed))
353 {
354 for (; addrlist != NULL; addrlist = addrlist->next)
355 if (addrlist->fallback_hosts == NULL)
356 addrlist->fallback_hosts = ob->fallback_hostlist;
357 }
358
359 return OK;
360 }
361
362
363
364 /*************************************************
365 * Initialization entry point *
366 *************************************************/
367
368 /* Called for each instance, after its options have been read, to
369 enable consistency checks to be done, or anything else that needs
370 to be set up.
371
372 Argument: pointer to the transport instance block
373 Returns: nothing
374 */
375
376 void
377 smtp_transport_init(transport_instance *tblock)
378 {
379 smtp_transport_options_block *ob =
380 (smtp_transport_options_block *)(tblock->options_block);
381
382 /* Retry_use_local_part defaults FALSE if unset */
383
384 if (tblock->retry_use_local_part == TRUE_UNSET)
385 tblock->retry_use_local_part = FALSE;
386
387 /* Set the default port according to the protocol */
388
389 if (ob->port == NULL)
390 ob->port = (strcmpic(ob->protocol, US"lmtp") == 0)? US"lmtp" :
391 (strcmpic(ob->protocol, US"smtps") == 0)? US"smtps" : US"smtp";
392
393 /* Set up the setup entry point, to be called before subprocesses for this
394 transport. */
395
396 tblock->setup = smtp_transport_setup;
397
398 /* Complain if any of the timeouts are zero. */
399
400 if (ob->command_timeout <= 0 || ob->data_timeout <= 0 ||
401 ob->final_timeout <= 0)
402 log_write(0, LOG_PANIC_DIE|LOG_CONFIG,
403 "command, data, or final timeout value is zero for %s transport",
404 tblock->name);
405
406 /* If hosts_override is set and there are local hosts, set the global
407 flag that stops verify from showing router hosts. */
408
409 if (ob->hosts_override && ob->hosts != NULL) tblock->overrides_hosts = TRUE;
410
411 /* If there are any fallback hosts listed, build a chain of host items
412 for them, but do not do any lookups at this time. */
413
414 host_build_hostlist(&(ob->fallback_hostlist), ob->fallback_hosts, FALSE);
415
416 #ifdef SUPPORT_TLS
417 if ( ob->gnutls_require_kx
418 || ob->gnutls_require_mac
419 || ob->gnutls_require_proto)
420 log_write(0, LOG_MAIN, "WARNING: smtp transport options"
421 " gnutls_require_kx, gnutls_require_mac and gnutls_require_protocols"
422 " are obsolete\n");
423 #endif
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
435 status means that an address is not currently being processed.
436
437 Arguments:
438 addrlist points to a chain of addresses
439 errno_value to put in each address's errno field
440 msg to put in each address's message field
441 rc to put in each address's transport_return field
442 pass_message if TRUE, set the "pass message" flag in the address
443
444 If errno_value has the special value ERRNO_CONNECTTIMEOUT, ETIMEDOUT is put in
445 the errno field, and RTEF_CTOUT is ORed into the more_errno field, to indicate
446 this particular type of timeout.
447
448 Returns: nothing
449 */
450
451 static void
452 set_errno(address_item *addrlist, int errno_value, uschar *msg, int rc,
453 BOOL pass_message)
454 {
455 address_item *addr;
456 int orvalue = 0;
457 if (errno_value == ERRNO_CONNECTTIMEOUT)
458 {
459 errno_value = ETIMEDOUT;
460 orvalue = RTEF_CTOUT;
461 }
462 for (addr = addrlist; addr != NULL; addr = addr->next)
463 {
464 if (addr->transport_return < PENDING) continue;
465 addr->basic_errno = errno_value;
466 addr->more_errno |= orvalue;
467 if (msg != NULL)
468 {
469 addr->message = msg;
470 if (pass_message) setflag(addr, af_pass_message);
471 }
472 addr->transport_return = rc;
473 }
474 }
475
476
477
478 /*************************************************
479 * Check an SMTP response *
480 *************************************************/
481
482 /* This function is given an errno code and the SMTP response buffer
483 to analyse, together with the host identification for generating messages. It
484 sets an appropriate message and puts the first digit of the response code into
485 the yield variable. If no response was actually read, a suitable digit is
486 chosen.
487
488 Arguments:
489 host the current host, to get its name for messages
490 errno_value pointer to the errno value
491 more_errno from the top address for use with ERRNO_FILTER_FAIL
492 buffer the SMTP response buffer
493 yield where to put a one-digit SMTP response code
494 message where to put an errror message
495 pass_message set TRUE if message is an SMTP response
496
497 Returns: TRUE if an SMTP "QUIT" command should be sent, else FALSE
498 */
499
500 static BOOL check_response(host_item *host, int *errno_value, int more_errno,
501 uschar *buffer, int *yield, uschar **message, BOOL *pass_message)
502 {
503 uschar *pl = US"";
504
505 if (smtp_use_pipelining &&
506 (Ustrcmp(smtp_command, "MAIL") == 0 ||
507 Ustrcmp(smtp_command, "RCPT") == 0 ||
508 Ustrcmp(smtp_command, "DATA") == 0))
509 pl = US"pipelined ";
510
511 *yield = '4'; /* Default setting is to give a temporary error */
512
513 /* Handle response timeout */
514
515 if (*errno_value == ETIMEDOUT)
516 {
517 *message = US string_sprintf("SMTP timeout while connected to %s [%s] "
518 "after %s%s", host->name, host->address, pl, smtp_command);
519 if (transport_count > 0)
520 *message = US string_sprintf("%s (%d bytes written)", *message,
521 transport_count);
522 return FALSE;
523 }
524
525 /* Handle malformed SMTP response */
526
527 if (*errno_value == ERRNO_SMTPFORMAT)
528 {
529 uschar *malfresp = string_printing(buffer);
530 while (isspace(*malfresp)) malfresp++;
531 if (*malfresp == 0)
532 *message = string_sprintf("Malformed SMTP reply (an empty line) from "
533 "%s [%s] in response to %s%s", host->name, host->address, pl,
534 smtp_command);
535 else
536 *message = string_sprintf("Malformed SMTP reply from %s [%s] in response "
537 "to %s%s: %s", host->name, host->address, pl, smtp_command, malfresp);
538 return FALSE;
539 }
540
541 /* Handle a failed filter process error; can't send QUIT as we mustn't
542 end the DATA. */
543
544 if (*errno_value == ERRNO_FILTER_FAIL)
545 {
546 *message = US string_sprintf("transport filter process failed (%d)%s",
547 more_errno,
548 (more_errno == EX_EXECFAILED)? ": unable to execute command" : "");
549 return FALSE;
550 }
551
552 /* Handle a failed add_headers expansion; can't send QUIT as we mustn't
553 end the DATA. */
554
555 if (*errno_value == ERRNO_CHHEADER_FAIL)
556 {
557 *message =
558 US string_sprintf("failed to expand headers_add or headers_remove: %s",
559 expand_string_message);
560 return FALSE;
561 }
562
563 /* Handle failure to write a complete data block */
564
565 if (*errno_value == ERRNO_WRITEINCOMPLETE)
566 {
567 *message = US string_sprintf("failed to write a data block");
568 return FALSE;
569 }
570
571 /* Handle error responses from the remote mailer. */
572
573 if (buffer[0] != 0)
574 {
575 uschar *s = string_printing(buffer);
576 *message = US string_sprintf("SMTP error from remote mail server after %s%s: "
577 "host %s [%s]: %s", pl, smtp_command, host->name, host->address, s);
578 *pass_message = TRUE;
579 *yield = buffer[0];
580 return TRUE;
581 }
582
583 /* No data was read. If there is no errno, this must be the EOF (i.e.
584 connection closed) case, which causes deferral. An explicit connection reset
585 error has the same effect. Otherwise, put the host's identity in the message,
586 leaving the errno value to be interpreted as well. In all cases, we have to
587 assume the connection is now dead. */
588
589 if (*errno_value == 0 || *errno_value == ECONNRESET)
590 {
591 *errno_value = ERRNO_SMTPCLOSED;
592 *message = US string_sprintf("Remote host %s [%s] closed connection "
593 "in response to %s%s", host->name, host->address, pl, smtp_command);
594 }
595 else *message = US string_sprintf("%s [%s]", host->name, host->address);
596
597 return FALSE;
598 }
599
600
601
602 /*************************************************
603 * Write error message to logs *
604 *************************************************/
605
606 /* This writes to the main log and to the message log.
607
608 Arguments:
609 addr the address item containing error information
610 host the current host
611
612 Returns: nothing
613 */
614
615 static void
616 write_logs(address_item *addr, host_item *host)
617 {
618 if (addr->message != NULL)
619 {
620 uschar *message = addr->message;
621 if (addr->basic_errno > 0)
622 message = string_sprintf("%s: %s", message, strerror(addr->basic_errno));
623 log_write(0, LOG_MAIN, "%s", message);
624 deliver_msglog("%s %s\n", tod_stamp(tod_log), message);
625 }
626 else
627 {
628 uschar *msg =
629 ((log_extra_selector & LX_outgoing_port) != 0)?
630 string_sprintf("%s [%s]:%d", host->name, host->address,
631 (host->port == PORT_NONE)? 25 : host->port)
632 :
633 string_sprintf("%s [%s]", host->name, host->address);
634 log_write(0, LOG_MAIN, "%s %s", msg, strerror(addr->basic_errno));
635 deliver_msglog("%s %s %s\n", tod_stamp(tod_log), msg,
636 strerror(addr->basic_errno));
637 }
638 }
639
640
641
642 #ifdef EXPERIMENTAL_TPDA
643 /*************************************************
644 * Post-defer action *
645 *************************************************/
646
647 /* This expands an arbitrary per-transport string.
648 It might, for example, be used to write to the database log.
649
650 Arguments:
651 ob transport options block
652 addr the address item containing error information
653 host the current host
654
655 Returns: nothing
656 */
657
658 static void
659 tpda_deferred(smtp_transport_options_block *ob, address_item *addr, host_item *host)
660 {
661 uschar *action = ob->tpda_host_defer_action;
662 if (!action)
663 return;
664
665 tpda_delivery_ip = string_copy(host->address);
666 tpda_delivery_port = (host->port == PORT_NONE)? 25 : host->port;
667 tpda_delivery_fqdn = string_copy(host->name);
668 tpda_delivery_local_part = string_copy(addr->local_part);
669 tpda_delivery_domain = string_copy(addr->domain);
670 tpda_defer_errno = addr->basic_errno;
671
672 tpda_defer_errstr = addr->message
673 ? addr->basic_errno > 0
674 ? string_sprintf("%s: %s", addr->message, strerror(addr->basic_errno))
675 : string_copy(addr->message)
676 : addr->basic_errno > 0
677 ? string_copy(US strerror(addr->basic_errno))
678 : NULL;
679
680 DEBUG(D_transport)
681 debug_printf(" TPDA(host defer): tpda_host_defer_action=|%s| tpda_delivery_IP=%s\n",
682 action, tpda_delivery_ip);
683
684 router_name = addr->router->name;
685 transport_name = addr->transport->name;
686 if (!expand_string(action) && *expand_string_message)
687 log_write(0, LOG_MAIN|LOG_PANIC, "failed to expand tpda_defer_action in %s: %s\n",
688 transport_name, expand_string_message);
689 router_name = transport_name = NULL;
690 }
691 #endif
692
693
694
695 /*************************************************
696 * Synchronize SMTP responses *
697 *************************************************/
698
699 /* This function is called from smtp_deliver() to receive SMTP responses from
700 the server, and match them up with the commands to which they relate. When
701 PIPELINING is not in use, this function is called after every command, and is
702 therefore somewhat over-engineered, but it is simpler to use a single scheme
703 that works both with and without PIPELINING instead of having two separate sets
704 of code.
705
706 The set of commands that are buffered up with pipelining may start with MAIL
707 and may end with DATA; in between are RCPT commands that correspond to the
708 addresses whose status is PENDING_DEFER. All other commands (STARTTLS, AUTH,
709 etc.) are never buffered.
710
711 Errors after MAIL or DATA abort the whole process leaving the response in the
712 buffer. After MAIL, pending responses are flushed, and the original command is
713 re-instated in big_buffer for error messages. For RCPT commands, the remote is
714 permitted to reject some recipient addresses while accepting others. However
715 certain errors clearly abort the whole process. Set the value in
716 transport_return to PENDING_OK if the address is accepted. If there is a
717 subsequent general error, it will get reset accordingly. If not, it will get
718 converted to OK at the end.
719
720 Arguments:
721 addrlist the complete address list
722 include_affixes TRUE if affixes include in RCPT
723 sync_addr ptr to the ptr of the one to start scanning at (updated)
724 host the host we are connected to
725 count the number of responses to read
726 address_retry_
727 include_sender true if 4xx retry is to include the sender it its key
728 pending_MAIL true if the first response is for MAIL
729 pending_DATA 0 if last command sent was not DATA
730 +1 if previously had a good recipient
731 -1 if not previously had a good recipient
732 inblock incoming SMTP block
733 timeout timeout value
734 buffer buffer for reading response
735 buffsize size of buffer
736
737 Returns: 3 if at least one address had 2xx and one had 5xx
738 2 if at least one address had 5xx but none had 2xx
739 1 if at least one host had a 2xx response, but none had 5xx
740 0 no address had 2xx or 5xx but no errors (all 4xx, or just DATA)
741 -1 timeout while reading RCPT response
742 -2 I/O or other non-response error for RCPT
743 -3 DATA or MAIL failed - errno and buffer set
744 */
745
746 static int
747 sync_responses(address_item *addrlist, BOOL include_affixes,
748 address_item **sync_addr, host_item *host, int count,
749 BOOL address_retry_include_sender, BOOL pending_MAIL,
750 int pending_DATA, smtp_inblock *inblock, int timeout, uschar *buffer,
751 int buffsize)
752 {
753 address_item *addr = *sync_addr;
754 int yield = 0;
755
756 /* Handle the response for a MAIL command. On error, reinstate the original
757 command in big_buffer for error message use, and flush any further pending
758 responses before returning, except after I/O errors and timeouts. */
759
760 if (pending_MAIL)
761 {
762 count--;
763 if (!smtp_read_response(inblock, buffer, buffsize, '2', timeout))
764 {
765 Ustrcpy(big_buffer, mail_command); /* Fits, because it came from there! */
766 if (errno == 0 && buffer[0] != 0)
767 {
768 uschar flushbuffer[4096];
769 int save_errno = 0;
770 if (buffer[0] == '4')
771 {
772 save_errno = ERRNO_MAIL4XX;
773 addr->more_errno |= ((buffer[1] - '0')*10 + buffer[2] - '0') << 8;
774 }
775 while (count-- > 0)
776 {
777 if (!smtp_read_response(inblock, flushbuffer, sizeof(flushbuffer),
778 '2', timeout)
779 && (errno != 0 || flushbuffer[0] == 0))
780 break;
781 }
782 errno = save_errno;
783 }
784 return -3;
785 }
786 }
787
788 if (pending_DATA) count--; /* Number of RCPT responses to come */
789
790 /* Read and handle the required number of RCPT responses, matching each one up
791 with an address by scanning for the next address whose status is PENDING_DEFER.
792 */
793
794 while (count-- > 0)
795 {
796 while (addr->transport_return != PENDING_DEFER) addr = addr->next;
797
798 /* The address was accepted */
799
800 if (smtp_read_response(inblock, buffer, buffsize, '2', timeout))
801 {
802 yield |= 1;
803 addr->transport_return = PENDING_OK;
804
805 /* If af_dr_retry_exists is set, there was a routing delay on this address;
806 ensure that any address-specific retry record is expunged. We do this both
807 for the basic key and for the version that also includes the sender. */
808
809 if (testflag(addr, af_dr_retry_exists))
810 {
811 uschar *altkey = string_sprintf("%s:<%s>", addr->address_retry_key,
812 sender_address);
813 retry_add_item(addr, altkey, rf_delete);
814 retry_add_item(addr, addr->address_retry_key, rf_delete);
815 }
816 }
817
818 /* Timeout while reading the response */
819
820 else if (errno == ETIMEDOUT)
821 {
822 int save_errno = errno;
823 uschar *message = string_sprintf("SMTP timeout while connected to %s [%s] "
824 "after RCPT TO:<%s>", host->name, host->address,
825 transport_rcpt_address(addr, include_affixes));
826 set_errno(addrlist, save_errno, message, DEFER, FALSE);
827 retry_add_item(addr, addr->address_retry_key, 0);
828 update_waiting = FALSE;
829 return -1;
830 }
831
832 /* Handle other errors in obtaining an SMTP response by returning -1. This
833 will cause all the addresses to be deferred. Restore the SMTP command in
834 big_buffer for which we are checking the response, so the error message
835 makes sense. */
836
837 else if (errno != 0 || buffer[0] == 0)
838 {
839 string_format(big_buffer, big_buffer_size, "RCPT TO:<%s>",
840 transport_rcpt_address(addr, include_affixes));
841 return -2;
842 }
843
844 /* Handle SMTP permanent and temporary response codes. */
845
846 else
847 {
848 addr->message =
849 string_sprintf("SMTP error from remote mail server after RCPT TO:<%s>: "
850 "host %s [%s]: %s", transport_rcpt_address(addr, include_affixes),
851 host->name, host->address, string_printing(buffer));
852 setflag(addr, af_pass_message);
853 deliver_msglog("%s %s\n", tod_stamp(tod_log), addr->message);
854
855 /* The response was 5xx */
856
857 if (buffer[0] == '5')
858 {
859 addr->transport_return = FAIL;
860 yield |= 2;
861 }
862
863 /* The response was 4xx */
864
865 else
866 {
867 addr->transport_return = DEFER;
868 addr->basic_errno = ERRNO_RCPT4XX;
869 addr->more_errno |= ((buffer[1] - '0')*10 + buffer[2] - '0') << 8;
870
871 /* Log temporary errors if there are more hosts to be tried. */
872
873 if (host->next != NULL) log_write(0, LOG_MAIN, "%s", addr->message);
874
875 /* Do not put this message on the list of those waiting for specific
876 hosts, as otherwise it is likely to be tried too often. */
877
878 update_waiting = FALSE;
879
880 /* Add a retry item for the address so that it doesn't get tried again
881 too soon. If address_retry_include_sender is true, add the sender address
882 to the retry key. */
883
884 if (address_retry_include_sender)
885 {
886 uschar *altkey = string_sprintf("%s:<%s>", addr->address_retry_key,
887 sender_address);
888 retry_add_item(addr, altkey, 0);
889 }
890 else retry_add_item(addr, addr->address_retry_key, 0);
891 }
892 }
893 } /* Loop for next RCPT response */
894
895 /* Update where to start at for the next block of responses, unless we
896 have already handled all the addresses. */
897
898 if (addr != NULL) *sync_addr = addr->next;
899
900 /* Handle a response to DATA. If we have not had any good recipients, either
901 previously or in this block, the response is ignored. */
902
903 if (pending_DATA != 0 &&
904 !smtp_read_response(inblock, buffer, buffsize, '3', timeout))
905 {
906 int code;
907 uschar *msg;
908 BOOL pass_message;
909 if (pending_DATA > 0 || (yield & 1) != 0)
910 {
911 if (errno == 0 && buffer[0] == '4')
912 {
913 errno = ERRNO_DATA4XX;
914 addrlist->more_errno |= ((buffer[1] - '0')*10 + buffer[2] - '0') << 8;
915 }
916 return -3;
917 }
918 (void)check_response(host, &errno, 0, buffer, &code, &msg, &pass_message);
919 DEBUG(D_transport) debug_printf("%s\nerror for DATA ignored: pipelining "
920 "is in use and there were no good recipients\n", msg);
921 }
922
923 /* All responses read and handled; MAIL (if present) received 2xx and DATA (if
924 present) received 3xx. If any RCPTs were handled and yielded anything other
925 than 4xx, yield will be set non-zero. */
926
927 return yield;
928 }
929
930
931
932 /* Do the client side of smtp-level authentication */
933 /*
934 Arguments:
935 buffer EHLO response from server (gets overwritten)
936 addrlist chain of potential addresses to deliver
937 host host to deliver to
938 ob transport options
939 ibp, obp comms channel control blocks
940
941 Returns:
942 OK Success, or failed (but not required): global "smtp_authenticated" set
943 DEFER Failed authentication (and was required)
944 ERROR Internal problem
945
946 FAIL_SEND Failed communications - transmit
947 FAIL - response
948 */
949
950 int
951 smtp_auth(uschar *buffer, unsigned bufsize, address_item *addrlist, host_item *host,
952 smtp_transport_options_block *ob, BOOL is_esmtp,
953 smtp_inblock *ibp, smtp_outblock *obp)
954 {
955 int require_auth;
956 uschar *fail_reason = US"server did not advertise AUTH support";
957
958 smtp_authenticated = FALSE;
959 client_authenticator = client_authenticated_id = client_authenticated_sender = NULL;
960 require_auth = verify_check_this_host(&(ob->hosts_require_auth), NULL,
961 host->name, host->address, NULL);
962
963 if (is_esmtp && !regex_AUTH) regex_AUTH =
964 regex_must_compile(US"\\n250[\\s\\-]AUTH\\s+([\\-\\w\\s]+)(?:\\n|$)",
965 FALSE, TRUE);
966
967 if (is_esmtp && regex_match_and_setup(regex_AUTH, buffer, 0, -1))
968 {
969 uschar *names = string_copyn(expand_nstring[1], expand_nlength[1]);
970 expand_nmax = -1; /* reset */
971
972 /* Must not do this check until after we have saved the result of the
973 regex match above. */
974
975 if (require_auth == OK ||
976 verify_check_this_host(&(ob->hosts_try_auth), NULL, host->name,
977 host->address, NULL) == OK)
978 {
979 auth_instance *au;
980 fail_reason = US"no common mechanisms were found";
981
982 DEBUG(D_transport) debug_printf("scanning authentication mechanisms\n");
983
984 /* Scan the configured authenticators looking for one which is configured
985 for use as a client, which is not suppressed by client_condition, and
986 whose name matches an authentication mechanism supported by the server.
987 If one is found, attempt to authenticate by calling its client function.
988 */
989
990 for (au = auths; !smtp_authenticated && au != NULL; au = au->next)
991 {
992 uschar *p = names;
993 if (!au->client ||
994 (au->client_condition != NULL &&
995 !expand_check_condition(au->client_condition, au->name,
996 US"client authenticator")))
997 {
998 DEBUG(D_transport) debug_printf("skipping %s authenticator: %s\n",
999 au->name,
1000 (au->client)? "client_condition is false" :
1001 "not configured as a client");
1002 continue;
1003 }
1004
1005 /* Loop to scan supported server mechanisms */
1006
1007 while (*p != 0)
1008 {
1009 int rc;
1010 int len = Ustrlen(au->public_name);
1011 while (isspace(*p)) p++;
1012
1013 if (strncmpic(au->public_name, p, len) != 0 ||
1014 (p[len] != 0 && !isspace(p[len])))
1015 {
1016 while (*p != 0 && !isspace(*p)) p++;
1017 continue;
1018 }
1019
1020 /* Found data for a listed mechanism. Call its client entry. Set
1021 a flag in the outblock so that data is overwritten after sending so
1022 that reflections don't show it. */
1023
1024 fail_reason = US"authentication attempt(s) failed";
1025 obp->authenticating = TRUE;
1026 rc = (au->info->clientcode)(au, ibp, obp,
1027 ob->command_timeout, buffer, bufsize);
1028 obp->authenticating = FALSE;
1029 DEBUG(D_transport) debug_printf("%s authenticator yielded %d\n",
1030 au->name, rc);
1031
1032 /* A temporary authentication failure must hold up delivery to
1033 this host. After a permanent authentication failure, we carry on
1034 to try other authentication methods. If all fail hard, try to
1035 deliver the message unauthenticated unless require_auth was set. */
1036
1037 switch(rc)
1038 {
1039 case OK:
1040 smtp_authenticated = TRUE; /* stops the outer loop */
1041 client_authenticator = au->name;
1042 if (au->set_client_id != NULL)
1043 client_authenticated_id = expand_string(au->set_client_id);
1044 break;
1045
1046 /* Failure after writing a command */
1047
1048 case FAIL_SEND:
1049 return FAIL_SEND;
1050
1051 /* Failure after reading a response */
1052
1053 case FAIL:
1054 if (errno != 0 || buffer[0] != '5') return FAIL;
1055 log_write(0, LOG_MAIN, "%s authenticator failed H=%s [%s] %s",
1056 au->name, host->name, host->address, buffer);
1057 break;
1058
1059 /* Failure by some other means. In effect, the authenticator
1060 decided it wasn't prepared to handle this case. Typically this
1061 is the result of "fail" in an expansion string. Do we need to
1062 log anything here? Feb 2006: a message is now put in the buffer
1063 if logging is required. */
1064
1065 case CANCELLED:
1066 if (*buffer != 0)
1067 log_write(0, LOG_MAIN, "%s authenticator cancelled "
1068 "authentication H=%s [%s] %s", au->name, host->name,
1069 host->address, buffer);
1070 break;
1071
1072 /* Internal problem, message in buffer. */
1073
1074 case ERROR:
1075 set_errno(addrlist, 0, string_copy(buffer), DEFER, FALSE);
1076 return ERROR;
1077 }
1078
1079 break; /* If not authenticated, try next authenticator */
1080 } /* Loop for scanning supported server mechanisms */
1081 } /* Loop for further authenticators */
1082 }
1083 }
1084
1085 /* If we haven't authenticated, but are required to, give up. */
1086
1087 if (require_auth == OK && !smtp_authenticated)
1088 {
1089 set_errno(addrlist, ERRNO_AUTHFAIL,
1090 string_sprintf("authentication required but %s", fail_reason), DEFER,
1091 FALSE);
1092 return DEFER;
1093 }
1094
1095 return OK;
1096 }
1097
1098
1099 /* Construct AUTH appendix string for MAIL TO */
1100 /*
1101 Arguments
1102 buffer to build string
1103 addrlist chain of potential addresses to deliver
1104 ob transport options
1105
1106 Globals smtp_authenticated
1107 client_authenticated_sender
1108 Return True on error, otherwise buffer has (possibly empty) terminated string
1109 */
1110
1111 BOOL
1112 smtp_mail_auth_str(uschar *buffer, unsigned bufsize, address_item *addrlist,
1113 smtp_transport_options_block *ob)
1114 {
1115 uschar *local_authenticated_sender = authenticated_sender;
1116
1117 #ifdef notdef
1118 debug_printf("smtp_mail_auth_str: as<%s> os<%s> SA<%s>\n", authenticated_sender, ob->authenticated_sender, smtp_authenticated?"Y":"N");
1119 #endif
1120
1121 if (ob->authenticated_sender != NULL)
1122 {
1123 uschar *new = expand_string(ob->authenticated_sender);
1124 if (new == NULL)
1125 {
1126 if (!expand_string_forcedfail)
1127 {
1128 uschar *message = string_sprintf("failed to expand "
1129 "authenticated_sender: %s", expand_string_message);
1130 set_errno(addrlist, 0, message, DEFER, FALSE);
1131 return TRUE;
1132 }
1133 }
1134 else if (new[0] != 0) local_authenticated_sender = new;
1135 }
1136
1137 /* Add the authenticated sender address if present */
1138
1139 if ((smtp_authenticated || ob->authenticated_sender_force) &&
1140 local_authenticated_sender != NULL)
1141 {
1142 string_format(buffer, bufsize, " AUTH=%s",
1143 auth_xtextencode(local_authenticated_sender,
1144 Ustrlen(local_authenticated_sender)));
1145 client_authenticated_sender = string_copy(local_authenticated_sender);
1146 }
1147 else
1148 *buffer= 0;
1149
1150 return FALSE;
1151 }
1152
1153
1154
1155 /*************************************************
1156 * Deliver address list to given host *
1157 *************************************************/
1158
1159 /* If continue_hostname is not null, we get here only when continuing to
1160 deliver down an existing channel. The channel was passed as the standard
1161 input. TLS is never active on a passed channel; the previous process always
1162 closes it down before passing the connection on.
1163
1164 Otherwise, we have to make a connection to the remote host, and do the
1165 initial protocol exchange.
1166
1167 When running as an MUA wrapper, if the sender or any recipient is rejected,
1168 temporarily or permanently, we force failure for all recipients.
1169
1170 Arguments:
1171 addrlist chain of potential addresses to deliver; only those whose
1172 transport_return field is set to PENDING_DEFER are currently
1173 being processed; others should be skipped - they have either
1174 been delivered to an earlier host or IP address, or been
1175 failed by one of them.
1176 host host to deliver to
1177 host_af AF_INET or AF_INET6
1178 port default TCP/IP port to use, in host byte order
1179 interface interface to bind to, or NULL
1180 tblock transport instance block
1181 copy_host TRUE if host set in addr->host_used must be copied, because
1182 it is specific to this call of the transport
1183 message_defer set TRUE if yield is OK, but all addresses were deferred
1184 because of a non-recipient, non-host failure, that is, a
1185 4xx response to MAIL FROM, DATA, or ".". This is a defer
1186 that is specific to the message.
1187 suppress_tls if TRUE, don't attempt a TLS connection - this is set for
1188 a second attempt after TLS initialization fails
1189
1190 Returns: OK - the connection was made and the delivery attempted;
1191 the result for each address is in its data block.
1192 DEFER - the connection could not be made, or something failed
1193 while setting up the SMTP session, or there was a
1194 non-message-specific error, such as a timeout.
1195 ERROR - a filter command is specified for this transport,
1196 and there was a problem setting it up; OR helo_data
1197 or add_headers or authenticated_sender is specified
1198 for this transport, and the string failed to expand
1199 */
1200
1201 static int
1202 smtp_deliver(address_item *addrlist, host_item *host, int host_af, int port,
1203 uschar *interface, transport_instance *tblock, BOOL copy_host,
1204 BOOL *message_defer, BOOL suppress_tls)
1205 {
1206 address_item *addr;
1207 address_item *sync_addr;
1208 address_item *first_addr = addrlist;
1209 int yield = OK;
1210 int address_count;
1211 int save_errno;
1212 int rc;
1213 time_t start_delivery_time = time(NULL);
1214 smtp_transport_options_block *ob =
1215 (smtp_transport_options_block *)(tblock->options_block);
1216 BOOL lmtp = strcmpic(ob->protocol, US"lmtp") == 0;
1217 BOOL smtps = strcmpic(ob->protocol, US"smtps") == 0;
1218 BOOL ok = FALSE;
1219 BOOL send_rset = TRUE;
1220 BOOL send_quit = TRUE;
1221 BOOL setting_up = TRUE;
1222 BOOL completed_address = FALSE;
1223 BOOL esmtp = TRUE;
1224 BOOL pending_MAIL;
1225 BOOL pass_message = FALSE;
1226 #ifndef DISABLE_PRDR
1227 BOOL prdr_offered = FALSE;
1228 BOOL prdr_active;
1229 #endif
1230 #ifdef EXPERIMENTAL_DSN
1231 BOOL dsn_all_lasthop = TRUE;
1232 #endif
1233 smtp_inblock inblock;
1234 smtp_outblock outblock;
1235 int max_rcpt = tblock->max_addresses;
1236 uschar *igquotstr = US"";
1237 uschar *helo_data = NULL;
1238 uschar *message = NULL;
1239 uschar new_message_id[MESSAGE_ID_LENGTH + 1];
1240 uschar *p;
1241 uschar buffer[4096];
1242 uschar inbuffer[4096];
1243 uschar outbuffer[4096];
1244
1245 suppress_tls = suppress_tls; /* stop compiler warning when no TLS support */
1246
1247 *message_defer = FALSE;
1248 smtp_command = US"initial connection";
1249 if (max_rcpt == 0) max_rcpt = 999999;
1250
1251 /* Set up the buffer for reading SMTP response packets. */
1252
1253 inblock.buffer = inbuffer;
1254 inblock.buffersize = sizeof(inbuffer);
1255 inblock.ptr = inbuffer;
1256 inblock.ptrend = inbuffer;
1257
1258 /* Set up the buffer for holding SMTP commands while pipelining */
1259
1260 outblock.buffer = outbuffer;
1261 outblock.buffersize = sizeof(outbuffer);
1262 outblock.ptr = outbuffer;
1263 outblock.cmd_count = 0;
1264 outblock.authenticating = FALSE;
1265
1266 /* Reset the parameters of a TLS session. */
1267
1268 tls_out.bits = 0;
1269 tls_out.cipher = NULL; /* the one we may use for this transport */
1270 tls_out.ourcert = NULL;
1271 tls_out.peercert = NULL;
1272 tls_out.peerdn = NULL;
1273 #if defined(SUPPORT_TLS) && !defined(USE_GNUTLS)
1274 tls_out.sni = NULL;
1275 #endif
1276 tls_out.ocsp = OCSP_NOT_REQ;
1277
1278 /* Flip the legacy TLS-related variables over to the outbound set in case
1279 they're used in the context of the transport. Don't bother resetting
1280 afterward as we're in a subprocess. */
1281
1282 tls_modify_variables(&tls_out);
1283
1284 #ifndef SUPPORT_TLS
1285 if (smtps)
1286 {
1287 set_errno(addrlist, 0, US"TLS support not available", DEFER, FALSE);
1288 return ERROR;
1289 }
1290 #endif
1291
1292 /* Make a connection to the host if this isn't a continued delivery, and handle
1293 the initial interaction and HELO/EHLO/LHLO. Connect timeout errors are handled
1294 specially so they can be identified for retries. */
1295
1296 if (continue_hostname == NULL)
1297 {
1298 inblock.sock = outblock.sock =
1299 smtp_connect(host, host_af, port, interface, ob->connect_timeout,
1300 ob->keepalive, ob->dscp); /* This puts port into host->port */
1301
1302 if (inblock.sock < 0)
1303 {
1304 set_errno(addrlist, (errno == ETIMEDOUT)? ERRNO_CONNECTTIMEOUT : errno,
1305 NULL, DEFER, FALSE);
1306 return DEFER;
1307 }
1308
1309 /* Expand the greeting message while waiting for the initial response. (Makes
1310 sense if helo_data contains ${lookup dnsdb ...} stuff). The expansion is
1311 delayed till here so that $sending_interface and $sending_port are set. */
1312
1313 helo_data = expand_string(ob->helo_data);
1314
1315 /* The first thing is to wait for an initial OK response. The dreaded "goto"
1316 is nevertheless a reasonably clean way of programming this kind of logic,
1317 where you want to escape on any error. */
1318
1319 if (!smtps)
1320 {
1321 if (!smtp_read_response(&inblock, buffer, sizeof(buffer), '2',
1322 ob->command_timeout)) goto RESPONSE_FAILED;
1323
1324 /* Now check if the helo_data expansion went well, and sign off cleanly if
1325 it didn't. */
1326
1327 if (helo_data == NULL)
1328 {
1329 uschar *message = string_sprintf("failed to expand helo_data: %s",
1330 expand_string_message);
1331 set_errno(addrlist, 0, message, DEFER, FALSE);
1332 yield = DEFER;
1333 goto SEND_QUIT;
1334 }
1335 }
1336
1337 /** Debugging without sending a message
1338 addrlist->transport_return = DEFER;
1339 goto SEND_QUIT;
1340 **/
1341
1342 /* Errors that occur after this point follow an SMTP command, which is
1343 left in big_buffer by smtp_write_command() for use in error messages. */
1344
1345 smtp_command = big_buffer;
1346
1347 /* Tell the remote who we are...
1348
1349 February 1998: A convention has evolved that ESMTP-speaking MTAs include the
1350 string "ESMTP" in their greeting lines, so make Exim send EHLO if the
1351 greeting is of this form. The assumption was that the far end supports it
1352 properly... but experience shows that there are some that give 5xx responses,
1353 even though the banner includes "ESMTP" (there's a bloody-minded one that
1354 says "ESMTP not spoken here"). Cope with that case.
1355
1356 September 2000: Time has passed, and it seems reasonable now to always send
1357 EHLO at the start. It is also convenient to make the change while installing
1358 the TLS stuff.
1359
1360 July 2003: Joachim Wieland met a broken server that advertises "PIPELINING"
1361 but times out after sending MAIL FROM, RCPT TO and DATA all together. There
1362 would be no way to send out the mails, so there is now a host list
1363 "hosts_avoid_esmtp" that disables ESMTP for special hosts and solves the
1364 PIPELINING problem as well. Maybe it can also be useful to cure other
1365 problems with broken servers.
1366
1367 Exim originally sent "Helo" at this point and ran for nearly a year that way.
1368 Then somebody tried it with a Microsoft mailer... It seems that all other
1369 mailers use upper case for some reason (the RFC is quite clear about case
1370 independence) so, for peace of mind, I gave in. */
1371
1372 esmtp = verify_check_this_host(&(ob->hosts_avoid_esmtp), NULL,
1373 host->name, host->address, NULL) != OK;
1374
1375 /* Alas; be careful, since this goto is not an error-out, so conceivably
1376 we might set data between here and the target which we assume to exist
1377 and be usable. I can see this coming back to bite us. */
1378 #ifdef SUPPORT_TLS
1379 if (smtps)
1380 {
1381 tls_offered = TRUE;
1382 suppress_tls = FALSE;
1383 ob->tls_tempfail_tryclear = FALSE;
1384 smtp_command = US"SSL-on-connect";
1385 goto TLS_NEGOTIATE;
1386 }
1387 #endif
1388
1389 if (esmtp)
1390 {
1391 if (smtp_write_command(&outblock, FALSE, "%s %s\r\n",
1392 lmtp? "LHLO" : "EHLO", helo_data) < 0)
1393 goto SEND_FAILED;
1394 if (!smtp_read_response(&inblock, buffer, sizeof(buffer), '2',
1395 ob->command_timeout))
1396 {
1397 if (errno != 0 || buffer[0] == 0 || lmtp) goto RESPONSE_FAILED;
1398 esmtp = FALSE;
1399 }
1400 }
1401 else
1402 {
1403 DEBUG(D_transport)
1404 debug_printf("not sending EHLO (host matches hosts_avoid_esmtp)\n");
1405 }
1406
1407 if (!esmtp)
1408 {
1409 if (smtp_write_command(&outblock, FALSE, "HELO %s\r\n", helo_data) < 0)
1410 goto SEND_FAILED;
1411 if (!smtp_read_response(&inblock, buffer, sizeof(buffer), '2',
1412 ob->command_timeout)) goto RESPONSE_FAILED;
1413 }
1414
1415 /* Set IGNOREQUOTA if the response to LHLO specifies support and the
1416 lmtp_ignore_quota option was set. */
1417
1418 igquotstr = (lmtp && ob->lmtp_ignore_quota &&
1419 pcre_exec(regex_IGNOREQUOTA, NULL, CS buffer, Ustrlen(CS buffer), 0,
1420 PCRE_EOPT, NULL, 0) >= 0)? US" IGNOREQUOTA" : US"";
1421
1422 /* Set tls_offered if the response to EHLO specifies support for STARTTLS. */
1423
1424 #ifdef SUPPORT_TLS
1425 tls_offered = esmtp &&
1426 pcre_exec(regex_STARTTLS, NULL, CS buffer, Ustrlen(buffer), 0,
1427 PCRE_EOPT, NULL, 0) >= 0;
1428 #endif
1429
1430 #ifndef DISABLE_PRDR
1431 prdr_offered = esmtp &&
1432 (pcre_exec(regex_PRDR, NULL, CS buffer, Ustrlen(buffer), 0,
1433 PCRE_EOPT, NULL, 0) >= 0) &&
1434 (verify_check_this_host(&(ob->hosts_try_prdr), NULL, host->name,
1435 host->address, NULL) == OK);
1436
1437 if (prdr_offered)
1438 {DEBUG(D_transport) debug_printf("PRDR usable\n");}
1439 #endif
1440 }
1441
1442 /* For continuing deliveries down the same channel, the socket is the standard
1443 input, and we don't need to redo EHLO here (but may need to do so for TLS - see
1444 below). Set up the pointer to where subsequent commands will be left, for
1445 error messages. Note that smtp_use_size and smtp_use_pipelining will have been
1446 set from the command line if they were set in the process that passed the
1447 connection on. */
1448
1449 else
1450 {
1451 inblock.sock = outblock.sock = fileno(stdin);
1452 smtp_command = big_buffer;
1453 host->port = port; /* Record the port that was used */
1454 }
1455
1456 /* If TLS is available on this connection, whether continued or not, attempt to
1457 start up a TLS session, unless the host is in hosts_avoid_tls. If successful,
1458 send another EHLO - the server may give a different answer in secure mode. We
1459 use a separate buffer for reading the response to STARTTLS so that if it is
1460 negative, the original EHLO data is available for subsequent analysis, should
1461 the client not be required to use TLS. If the response is bad, copy the buffer
1462 for error analysis. */
1463
1464 #ifdef SUPPORT_TLS
1465 if (tls_offered && !suppress_tls &&
1466 verify_check_this_host(&(ob->hosts_avoid_tls), NULL, host->name,
1467 host->address, NULL) != OK)
1468 {
1469 uschar buffer2[4096];
1470 if (smtp_write_command(&outblock, FALSE, "STARTTLS\r\n") < 0)
1471 goto SEND_FAILED;
1472
1473 /* If there is an I/O error, transmission of this message is deferred. If
1474 there is a temporary rejection of STARRTLS and tls_tempfail_tryclear is
1475 false, we also defer. However, if there is a temporary rejection of STARTTLS
1476 and tls_tempfail_tryclear is true, or if there is an outright rejection of
1477 STARTTLS, we carry on. This means we will try to send the message in clear,
1478 unless the host is in hosts_require_tls (tested below). */
1479
1480 if (!smtp_read_response(&inblock, buffer2, sizeof(buffer2), '2',
1481 ob->command_timeout))
1482 {
1483 if (errno != 0 || buffer2[0] == 0 ||
1484 (buffer2[0] == '4' && !ob->tls_tempfail_tryclear))
1485 {
1486 Ustrncpy(buffer, buffer2, sizeof(buffer));
1487 goto RESPONSE_FAILED;
1488 }
1489 }
1490
1491 /* STARTTLS accepted: try to negotiate a TLS session. */
1492
1493 else
1494 TLS_NEGOTIATE:
1495 {
1496 int rc = tls_client_start(inblock.sock, host, addrlist, ob);
1497
1498 /* TLS negotiation failed; give an error. From outside, this function may
1499 be called again to try in clear on a new connection, if the options permit
1500 it for this host. */
1501
1502 if (rc != OK)
1503 {
1504 save_errno = ERRNO_TLSFAILURE;
1505 message = US"failure while setting up TLS session";
1506 send_quit = FALSE;
1507 goto TLS_FAILED;
1508 }
1509
1510 /* TLS session is set up */
1511
1512 for (addr = addrlist; addr != NULL; addr = addr->next)
1513 {
1514 if (addr->transport_return == PENDING_DEFER)
1515 {
1516 addr->cipher = tls_out.cipher;
1517 addr->ourcert = tls_out.ourcert;
1518 addr->peercert = tls_out.peercert;
1519 addr->peerdn = tls_out.peerdn;
1520 addr->ocsp = tls_out.ocsp;
1521 }
1522 }
1523 }
1524 }
1525
1526 /* if smtps, we'll have smtp_command set to something else; always safe to
1527 reset it here. */
1528 smtp_command = big_buffer;
1529
1530 /* If we started TLS, redo the EHLO/LHLO exchange over the secure channel. If
1531 helo_data is null, we are dealing with a connection that was passed from
1532 another process, and so we won't have expanded helo_data above. We have to
1533 expand it here. $sending_ip_address and $sending_port are set up right at the
1534 start of the Exim process (in exim.c). */
1535
1536 if (tls_out.active >= 0)
1537 {
1538 char *greeting_cmd;
1539 if (helo_data == NULL)
1540 {
1541 helo_data = expand_string(ob->helo_data);
1542 if (helo_data == NULL)
1543 {
1544 uschar *message = string_sprintf("failed to expand helo_data: %s",
1545 expand_string_message);
1546 set_errno(addrlist, 0, message, DEFER, FALSE);
1547 yield = DEFER;
1548 goto SEND_QUIT;
1549 }
1550 }
1551
1552 /* For SMTPS we need to wait for the initial OK response. */
1553 if (smtps)
1554 {
1555 if (!smtp_read_response(&inblock, buffer, sizeof(buffer), '2',
1556 ob->command_timeout)) goto RESPONSE_FAILED;
1557 }
1558
1559 if (esmtp)
1560 greeting_cmd = "EHLO";
1561 else
1562 {
1563 greeting_cmd = "HELO";
1564 DEBUG(D_transport)
1565 debug_printf("not sending EHLO (host matches hosts_avoid_esmtp)\n");
1566 }
1567
1568 if (smtp_write_command(&outblock, FALSE, "%s %s\r\n",
1569 lmtp? "LHLO" : greeting_cmd, helo_data) < 0)
1570 goto SEND_FAILED;
1571 if (!smtp_read_response(&inblock, buffer, sizeof(buffer), '2',
1572 ob->command_timeout))
1573 goto RESPONSE_FAILED;
1574 }
1575
1576 /* If the host is required to use a secure channel, ensure that we
1577 have one. */
1578
1579 else if ( verify_check_this_host(&(ob->hosts_require_tls), NULL, host->name,
1580 host->address, NULL) == OK
1581 #ifdef EXPERIMENTAL_DANE
1582 || verify_check_this_host(&(ob->hosts_require_dane), NULL, host->name,
1583 host->address, NULL) == OK
1584 #endif
1585 )
1586 {
1587 save_errno = ERRNO_TLSREQUIRED;
1588 message = string_sprintf("a TLS session is required for %s [%s], but %s",
1589 host->name, host->address,
1590 tls_offered? "an attempt to start TLS failed" :
1591 "the server did not offer TLS support");
1592 goto TLS_FAILED;
1593 }
1594 #endif
1595
1596 /* If TLS is active, we have just started it up and re-done the EHLO command,
1597 so its response needs to be analyzed. If TLS is not active and this is a
1598 continued session down a previously-used socket, we haven't just done EHLO, so
1599 we skip this. */
1600
1601 if (continue_hostname == NULL
1602 #ifdef SUPPORT_TLS
1603 || tls_out.active >= 0
1604 #endif
1605 )
1606 {
1607 /* Set for IGNOREQUOTA if the response to LHLO specifies support and the
1608 lmtp_ignore_quota option was set. */
1609
1610 igquotstr = (lmtp && ob->lmtp_ignore_quota &&
1611 pcre_exec(regex_IGNOREQUOTA, NULL, CS buffer, Ustrlen(CS buffer), 0,
1612 PCRE_EOPT, NULL, 0) >= 0)? US" IGNOREQUOTA" : US"";
1613
1614 /* If the response to EHLO specified support for the SIZE parameter, note
1615 this, provided size_addition is non-negative. */
1616
1617 smtp_use_size = esmtp && ob->size_addition >= 0 &&
1618 pcre_exec(regex_SIZE, NULL, CS buffer, Ustrlen(CS buffer), 0,
1619 PCRE_EOPT, NULL, 0) >= 0;
1620
1621 /* Note whether the server supports PIPELINING. If hosts_avoid_esmtp matched
1622 the current host, esmtp will be false, so PIPELINING can never be used. If
1623 the current host matches hosts_avoid_pipelining, don't do it. */
1624
1625 smtp_use_pipelining = esmtp &&
1626 verify_check_this_host(&(ob->hosts_avoid_pipelining), NULL, host->name,
1627 host->address, NULL) != OK &&
1628 pcre_exec(regex_PIPELINING, NULL, CS buffer, Ustrlen(CS buffer), 0,
1629 PCRE_EOPT, NULL, 0) >= 0;
1630
1631 DEBUG(D_transport) debug_printf("%susing PIPELINING\n",
1632 smtp_use_pipelining? "" : "not ");
1633
1634 #ifndef DISABLE_PRDR
1635 prdr_offered = esmtp &&
1636 pcre_exec(regex_PRDR, NULL, CS buffer, Ustrlen(CS buffer), 0,
1637 PCRE_EOPT, NULL, 0) >= 0 &&
1638 verify_check_this_host(&(ob->hosts_try_prdr), NULL, host->name,
1639 host->address, NULL) == OK;
1640
1641 if (prdr_offered)
1642 {DEBUG(D_transport) debug_printf("PRDR usable\n");}
1643 #endif
1644
1645 #ifdef EXPERIMENTAL_DSN
1646 /* Note if the server supports DSN */
1647 smtp_use_dsn = esmtp && pcre_exec(regex_DSN, NULL, CS buffer, (int)Ustrlen(CS buffer), 0,
1648 PCRE_EOPT, NULL, 0) >= 0;
1649 DEBUG(D_transport) debug_printf("use_dsn=%d\n", smtp_use_dsn);
1650 #endif
1651
1652 /* Note if the response to EHLO specifies support for the AUTH extension.
1653 If it has, check that this host is one we want to authenticate to, and do
1654 the business. The host name and address must be available when the
1655 authenticator's client driver is running. */
1656
1657 switch (yield = smtp_auth(buffer, sizeof(buffer), addrlist, host,
1658 ob, esmtp, &inblock, &outblock))
1659 {
1660 default: goto SEND_QUIT;
1661 case OK: break;
1662 case FAIL_SEND: goto SEND_FAILED;
1663 case FAIL: goto RESPONSE_FAILED;
1664 }
1665 }
1666
1667 /* The setting up of the SMTP call is now complete. Any subsequent errors are
1668 message-specific. */
1669
1670 setting_up = FALSE;
1671
1672 /* If there is a filter command specified for this transport, we can now
1673 set it up. This cannot be done until the identify of the host is known. */
1674
1675 if (tblock->filter_command != NULL)
1676 {
1677 BOOL rc;
1678 uschar buffer[64];
1679 sprintf(CS buffer, "%.50s transport", tblock->name);
1680 rc = transport_set_up_command(&transport_filter_argv, tblock->filter_command,
1681 TRUE, DEFER, addrlist, buffer, NULL);
1682 transport_filter_timeout = tblock->filter_timeout;
1683
1684 /* On failure, copy the error to all addresses, abandon the SMTP call, and
1685 yield ERROR. */
1686
1687 if (!rc)
1688 {
1689 set_errno(addrlist->next, addrlist->basic_errno, addrlist->message, DEFER,
1690 FALSE);
1691 yield = ERROR;
1692 goto SEND_QUIT;
1693 }
1694 }
1695
1696
1697 /* For messages that have more than the maximum number of envelope recipients,
1698 we want to send several transactions down the same SMTP connection. (See
1699 comments in deliver.c as to how this reconciles, heuristically, with
1700 remote_max_parallel.) This optimization was added to Exim after the following
1701 code was already working. The simplest way to put it in without disturbing the
1702 code was to use a goto to jump back to this point when there is another
1703 transaction to handle. */
1704
1705 SEND_MESSAGE:
1706 sync_addr = first_addr;
1707 address_count = 0;
1708 ok = FALSE;
1709 send_rset = TRUE;
1710 completed_address = FALSE;
1711
1712
1713 /* Initiate a message transfer. If we know the receiving MTA supports the SIZE
1714 qualification, send it, adding something to the message size to allow for
1715 imprecision and things that get added en route. Exim keeps the number of lines
1716 in a message, so we can give an accurate value for the original message, but we
1717 need some additional to handle added headers. (Double "." characters don't get
1718 included in the count.) */
1719
1720 p = buffer;
1721 *p = 0;
1722
1723 if (smtp_use_size)
1724 {
1725 sprintf(CS p, " SIZE=%d", message_size+message_linecount+ob->size_addition);
1726 while (*p) p++;
1727 }
1728
1729 #ifndef DISABLE_PRDR
1730 prdr_active = FALSE;
1731 if (prdr_offered)
1732 {
1733 for (addr = first_addr; addr; addr = addr->next)
1734 if (addr->transport_return == PENDING_DEFER)
1735 {
1736 for (addr = addr->next; addr; addr = addr->next)
1737 if (addr->transport_return == PENDING_DEFER)
1738 { /* at least two recipients to send */
1739 prdr_active = TRUE;
1740 sprintf(CS p, " PRDR"); p += 5;
1741 goto prdr_is_active;
1742 }
1743 break;
1744 }
1745 }
1746 prdr_is_active:
1747 #endif
1748
1749 #ifdef EXPERIMENTAL_DSN
1750 /* check if all addresses have lasthop flag */
1751 /* do not send RET and ENVID if true */
1752 dsn_all_lasthop = TRUE;
1753 for (addr = first_addr;
1754 address_count < max_rcpt && addr != NULL;
1755 addr = addr->next)
1756 if ((addr->dsn_flags & rf_dsnlasthop) != 1)
1757 dsn_all_lasthop = FALSE;
1758
1759 /* Add any DSN flags to the mail command */
1760
1761 if ((smtp_use_dsn) && (dsn_all_lasthop == FALSE))
1762 {
1763 if (dsn_ret == dsn_ret_hdrs)
1764 {
1765 strcpy(p, " RET=HDRS");
1766 while (*p) p++;
1767 }
1768 else if (dsn_ret == dsn_ret_full)
1769 {
1770 strcpy(p, " RET=FULL");
1771 while (*p) p++;
1772 }
1773 if (dsn_envid != NULL)
1774 {
1775 string_format(p, sizeof(buffer) - (p-buffer), " ENVID=%s", dsn_envid);
1776 while (*p) p++;
1777 }
1778 }
1779 #endif
1780
1781 /* If an authenticated_sender override has been specified for this transport
1782 instance, expand it. If the expansion is forced to fail, and there was already
1783 an authenticated_sender for this message, the original value will be used.
1784 Other expansion failures are serious. An empty result is ignored, but there is
1785 otherwise no check - this feature is expected to be used with LMTP and other
1786 cases where non-standard addresses (e.g. without domains) might be required. */
1787
1788 if (smtp_mail_auth_str(p, sizeof(buffer) - (p-buffer), addrlist, ob))
1789 return ERROR;
1790
1791 /* From here until we send the DATA command, we can make use of PIPELINING
1792 if the server host supports it. The code has to be able to check the responses
1793 at any point, for when the buffer fills up, so we write it totally generally.
1794 When PIPELINING is off, each command written reports that it has flushed the
1795 buffer. */
1796
1797 pending_MAIL = TRUE; /* The block starts with MAIL */
1798
1799 rc = smtp_write_command(&outblock, smtp_use_pipelining,
1800 "MAIL FROM:<%s>%s\r\n", return_path, buffer);
1801 mail_command = string_copy(big_buffer); /* Save for later error message */
1802
1803 switch(rc)
1804 {
1805 case -1: /* Transmission error */
1806 goto SEND_FAILED;
1807
1808 case +1: /* Block was sent */
1809 if (!smtp_read_response(&inblock, buffer, sizeof(buffer), '2',
1810 ob->command_timeout))
1811 {
1812 if (errno == 0 && buffer[0] == '4')
1813 {
1814 errno = ERRNO_MAIL4XX;
1815 addrlist->more_errno |= ((buffer[1] - '0')*10 + buffer[2] - '0') << 8;
1816 }
1817 goto RESPONSE_FAILED;
1818 }
1819 pending_MAIL = FALSE;
1820 break;
1821 }
1822
1823 /* Pass over all the relevant recipient addresses for this host, which are the
1824 ones that have status PENDING_DEFER. If we are using PIPELINING, we can send
1825 several before we have to read the responses for those seen so far. This
1826 checking is done by a subroutine because it also needs to be done at the end.
1827 Send only up to max_rcpt addresses at a time, leaving first_addr pointing to
1828 the next one if not all are sent.
1829
1830 In the MUA wrapper situation, we want to flush the PIPELINING buffer for the
1831 last address because we want to abort if any recipients have any kind of
1832 problem, temporary or permanent. We know that all recipient addresses will have
1833 the PENDING_DEFER status, because only one attempt is ever made, and we know
1834 that max_rcpt will be large, so all addresses will be done at once. */
1835
1836 for (addr = first_addr;
1837 address_count < max_rcpt && addr != NULL;
1838 addr = addr->next)
1839 {
1840 int count;
1841 BOOL no_flush;
1842
1843 #ifdef EXPERIMENTAL_DSN
1844 if(smtp_use_dsn)
1845 addr->dsn_aware = dsn_support_yes;
1846 else
1847 addr->dsn_aware = dsn_support_no;
1848 #endif
1849
1850 if (addr->transport_return != PENDING_DEFER) continue;
1851
1852 address_count++;
1853 no_flush = smtp_use_pipelining && (!mua_wrapper || addr->next != NULL);
1854
1855 #ifdef EXPERIMENTAL_DSN
1856 /* Add any DSN flags to the rcpt command and add to the sent string */
1857
1858 p = buffer;
1859 *p = 0;
1860
1861 if ((smtp_use_dsn) && ((addr->dsn_flags & rf_dsnlasthop) != 1))
1862 {
1863 if ((addr->dsn_flags & rf_dsnflags) != 0)
1864 {
1865 int i;
1866 BOOL first = TRUE;
1867 strcpy(p, " NOTIFY=");
1868 while (*p) p++;
1869 for (i = 0; i < 4; i++)
1870 {
1871 if ((addr->dsn_flags & rf_list[i]) != 0)
1872 {
1873 if (!first) *p++ = ',';
1874 first = FALSE;
1875 strcpy(p, rf_names[i]);
1876 while (*p) p++;
1877 }
1878 }
1879 }
1880
1881 if (addr->dsn_orcpt != NULL) {
1882 string_format(p, sizeof(buffer) - (p-buffer), " ORCPT=%s",
1883 addr->dsn_orcpt);
1884 while (*p) p++;
1885 }
1886 }
1887 #endif
1888
1889
1890 /* Now send the RCPT command, and process outstanding responses when
1891 necessary. After a timeout on RCPT, we just end the function, leaving the
1892 yield as OK, because this error can often mean that there is a problem with
1893 just one address, so we don't want to delay the host. */
1894
1895 #ifdef EXPERIMENTAL_DSN
1896 count = smtp_write_command(&outblock, no_flush, "RCPT TO:<%s>%s%s\r\n",
1897 transport_rcpt_address(addr, tblock->rcpt_include_affixes), igquotstr, buffer);
1898 #else
1899 count = smtp_write_command(&outblock, no_flush, "RCPT TO:<%s>%s\r\n",
1900 transport_rcpt_address(addr, tblock->rcpt_include_affixes), igquotstr);
1901 #endif
1902
1903 if (count < 0) goto SEND_FAILED;
1904 if (count > 0)
1905 {
1906 switch(sync_responses(first_addr, tblock->rcpt_include_affixes,
1907 &sync_addr, host, count, ob->address_retry_include_sender,
1908 pending_MAIL, 0, &inblock, ob->command_timeout, buffer,
1909 sizeof(buffer)))
1910 {
1911 case 3: ok = TRUE; /* 2xx & 5xx => OK & progress made */
1912 case 2: completed_address = TRUE; /* 5xx (only) => progress made */
1913 break;
1914
1915 case 1: ok = TRUE; /* 2xx (only) => OK, but if LMTP, */
1916 if (!lmtp) completed_address = TRUE; /* can't tell about progress yet */
1917 case 0: /* No 2xx or 5xx, but no probs */
1918 break;
1919
1920 case -1: goto END_OFF; /* Timeout on RCPT */
1921 default: goto RESPONSE_FAILED; /* I/O error, or any MAIL error */
1922 }
1923 pending_MAIL = FALSE; /* Dealt with MAIL */
1924 }
1925 } /* Loop for next address */
1926
1927 /* If we are an MUA wrapper, abort if any RCPTs were rejected, either
1928 permanently or temporarily. We should have flushed and synced after the last
1929 RCPT. */
1930
1931 if (mua_wrapper)
1932 {
1933 address_item *badaddr;
1934 for (badaddr = first_addr; badaddr != NULL; badaddr = badaddr->next)
1935 {
1936 if (badaddr->transport_return != PENDING_OK) break;
1937 }
1938 if (badaddr != NULL)
1939 {
1940 set_errno(addrlist, 0, badaddr->message, FAIL,
1941 testflag(badaddr, af_pass_message));
1942 ok = FALSE;
1943 }
1944 }
1945
1946 /* If ok is TRUE, we know we have got at least one good recipient, and must now
1947 send DATA, but if it is FALSE (in the normal, non-wrapper case), we may still
1948 have a good recipient buffered up if we are pipelining. We don't want to waste
1949 time sending DATA needlessly, so we only send it if either ok is TRUE or if we
1950 are pipelining. The responses are all handled by sync_responses(). */
1951
1952 if (ok || (smtp_use_pipelining && !mua_wrapper))
1953 {
1954 int count = smtp_write_command(&outblock, FALSE, "DATA\r\n");
1955 if (count < 0) goto SEND_FAILED;
1956 switch(sync_responses(first_addr, tblock->rcpt_include_affixes, &sync_addr,
1957 host, count, ob->address_retry_include_sender, pending_MAIL,
1958 ok? +1 : -1, &inblock, ob->command_timeout, buffer, sizeof(buffer)))
1959 {
1960 case 3: ok = TRUE; /* 2xx & 5xx => OK & progress made */
1961 case 2: completed_address = TRUE; /* 5xx (only) => progress made */
1962 break;
1963
1964 case 1: ok = TRUE; /* 2xx (only) => OK, but if LMTP, */
1965 if (!lmtp) completed_address = TRUE; /* can't tell about progress yet */
1966 case 0: break; /* No 2xx or 5xx, but no probs */
1967
1968 case -1: goto END_OFF; /* Timeout on RCPT */
1969 default: goto RESPONSE_FAILED; /* I/O error, or any MAIL/DATA error */
1970 }
1971 }
1972
1973 /* Save the first address of the next batch. */
1974
1975 first_addr = addr;
1976
1977 /* If there were no good recipients (but otherwise there have been no
1978 problems), just set ok TRUE, since we have handled address-specific errors
1979 already. Otherwise, it's OK to send the message. Use the check/escape mechanism
1980 for handling the SMTP dot-handling protocol, flagging to apply to headers as
1981 well as body. Set the appropriate timeout value to be used for each chunk.
1982 (Haven't been able to make it work using select() for writing yet.) */
1983
1984 if (!ok) ok = TRUE; else
1985 {
1986 sigalrm_seen = FALSE;
1987 transport_write_timeout = ob->data_timeout;
1988 smtp_command = US"sending data block"; /* For error messages */
1989 DEBUG(D_transport|D_v)
1990 debug_printf(" SMTP>> writing message and terminating \".\"\n");
1991 transport_count = 0;
1992 #ifndef DISABLE_DKIM
1993 ok = dkim_transport_write_message(addrlist, inblock.sock,
1994 topt_use_crlf | topt_end_dot | topt_escape_headers |
1995 (tblock->body_only? topt_no_headers : 0) |
1996 (tblock->headers_only? topt_no_body : 0) |
1997 (tblock->return_path_add? topt_add_return_path : 0) |
1998 (tblock->delivery_date_add? topt_add_delivery_date : 0) |
1999 (tblock->envelope_to_add? topt_add_envelope_to : 0),
2000 0, /* No size limit */
2001 tblock->add_headers, tblock->remove_headers,
2002 US".", US"..", /* Escaping strings */
2003 tblock->rewrite_rules, tblock->rewrite_existflags,
2004 ob->dkim_private_key, ob->dkim_domain, ob->dkim_selector,
2005 ob->dkim_canon, ob->dkim_strict, ob->dkim_sign_headers
2006 );
2007 #else
2008 ok = transport_write_message(addrlist, inblock.sock,
2009 topt_use_crlf | topt_end_dot | topt_escape_headers |
2010 (tblock->body_only? topt_no_headers : 0) |
2011 (tblock->headers_only? topt_no_body : 0) |
2012 (tblock->return_path_add? topt_add_return_path : 0) |
2013 (tblock->delivery_date_add? topt_add_delivery_date : 0) |
2014 (tblock->envelope_to_add? topt_add_envelope_to : 0),
2015 0, /* No size limit */
2016 tblock->add_headers, tblock->remove_headers,
2017 US".", US"..", /* Escaping strings */
2018 tblock->rewrite_rules, tblock->rewrite_existflags);
2019 #endif
2020
2021 /* transport_write_message() uses write() because it is called from other
2022 places to write to non-sockets. This means that under some OS (e.g. Solaris)
2023 it can exit with "Broken pipe" as its error. This really means that the
2024 socket got closed at the far end. */
2025
2026 transport_write_timeout = 0; /* for subsequent transports */
2027
2028 /* Failure can either be some kind of I/O disaster (including timeout),
2029 or the failure of a transport filter or the expansion of added headers. */
2030
2031 if (!ok)
2032 {
2033 buffer[0] = 0; /* There hasn't been a response */
2034 goto RESPONSE_FAILED;
2035 }
2036
2037 /* We used to send the terminating "." explicitly here, but because of
2038 buffering effects at both ends of TCP/IP connections, you don't gain
2039 anything by keeping it separate, so it might as well go in the final
2040 data buffer for efficiency. This is now done by setting the topt_end_dot
2041 flag above. */
2042
2043 smtp_command = US"end of data";
2044
2045 #ifndef DISABLE_PRDR
2046 /* For PRDR we optionally get a partial-responses warning
2047 * followed by the individual responses, before going on with
2048 * the overall response. If we don't get the warning then deal
2049 * with per non-PRDR. */
2050 if(prdr_active)
2051 {
2052 ok = smtp_read_response(&inblock, buffer, sizeof(buffer), '3',
2053 ob->final_timeout);
2054 if (!ok && errno == 0)
2055 switch(buffer[0])
2056 {
2057 case '2': prdr_active = FALSE;
2058 ok = TRUE;
2059 break;
2060 case '4': errno = ERRNO_DATA4XX;
2061 addrlist->more_errno |= ((buffer[1] - '0')*10 + buffer[2] - '0') << 8;
2062 break;
2063 }
2064 }
2065 else
2066 #endif
2067
2068 /* For non-PRDR SMTP, we now read a single response that applies to the
2069 whole message. If it is OK, then all the addresses have been delivered. */
2070
2071 if (!lmtp)
2072 {
2073 ok = smtp_read_response(&inblock, buffer, sizeof(buffer), '2',
2074 ob->final_timeout);
2075 if (!ok && errno == 0 && buffer[0] == '4')
2076 {
2077 errno = ERRNO_DATA4XX;
2078 addrlist->more_errno |= ((buffer[1] - '0')*10 + buffer[2] - '0') << 8;
2079 }
2080 }
2081
2082 /* For LMTP, we get back a response for every RCPT command that we sent;
2083 some may be accepted and some rejected. For those that get a response, their
2084 status is fixed; any that are accepted have been handed over, even if later
2085 responses crash - at least, that's how I read RFC 2033.
2086
2087 If all went well, mark the recipient addresses as completed, record which
2088 host/IPaddress they were delivered to, and cut out RSET when sending another
2089 message down the same channel. Write the completed addresses to the journal
2090 now so that they are recorded in case there is a crash of hardware or
2091 software before the spool gets updated. Also record the final SMTP
2092 confirmation if needed (for SMTP only). */
2093
2094 if (ok)
2095 {
2096 int flag = '=';
2097 int delivery_time = (int)(time(NULL) - start_delivery_time);
2098 int len;
2099 host_item *thost;
2100 uschar *conf = NULL;
2101 send_rset = FALSE;
2102
2103 /* Make a copy of the host if it is local to this invocation
2104 of the transport. */
2105
2106 if (copy_host)
2107 {
2108 thost = store_get(sizeof(host_item));
2109 *thost = *host;
2110 thost->name = string_copy(host->name);
2111 thost->address = string_copy(host->address);
2112 }
2113 else thost = host;
2114
2115 /* Set up confirmation if needed - applies only to SMTP */
2116
2117 if (
2118 #ifndef EXPERIMENTAL_TPDA
2119 (log_extra_selector & LX_smtp_confirmation) != 0 &&
2120 #endif
2121 !lmtp
2122 )
2123 {
2124 uschar *s = string_printing(buffer);
2125 conf = (s == buffer)? (uschar *)string_copy(s) : s;
2126 }
2127
2128 /* Process all transported addresses - for LMTP or PRDR, read a status for
2129 each one. */
2130
2131 for (addr = addrlist; addr != first_addr; addr = addr->next)
2132 {
2133 if (addr->transport_return != PENDING_OK) continue;
2134
2135 /* LMTP - if the response fails badly (e.g. timeout), use it for all the
2136 remaining addresses. Otherwise, it's a return code for just the one
2137 address. For temporary errors, add a retry item for the address so that
2138 it doesn't get tried again too soon. */
2139
2140 #ifndef DISABLE_PRDR
2141 if (lmtp || prdr_active)
2142 #else
2143 if (lmtp)
2144 #endif
2145 {
2146 if (!smtp_read_response(&inblock, buffer, sizeof(buffer), '2',
2147 ob->final_timeout))
2148 {
2149 if (errno != 0 || buffer[0] == 0) goto RESPONSE_FAILED;
2150 addr->message = string_sprintf(
2151 #ifndef DISABLE_PRDR
2152 "%s error after %s: %s", prdr_active ? "PRDR":"LMTP",
2153 #else
2154 "LMTP error after %s: %s",
2155 #endif
2156 big_buffer, string_printing(buffer));
2157 setflag(addr, af_pass_message); /* Allow message to go to user */
2158 if (buffer[0] == '5')
2159 addr->transport_return = FAIL;
2160 else
2161 {
2162 errno = ERRNO_DATA4XX;
2163 addr->more_errno |= ((buffer[1] - '0')*10 + buffer[2] - '0') << 8;
2164 addr->transport_return = DEFER;
2165 #ifndef DISABLE_PRDR
2166 if (!prdr_active)
2167 #endif
2168 retry_add_item(addr, addr->address_retry_key, 0);
2169 }
2170 continue;
2171 }
2172 completed_address = TRUE; /* NOW we can set this flag */
2173 if ((log_extra_selector & LX_smtp_confirmation) != 0)
2174 {
2175 uschar *s = string_printing(buffer);
2176 conf = (s == buffer)? (uschar *)string_copy(s) : s;
2177 }
2178 }
2179
2180 /* SMTP, or success return from LMTP for this address. Pass back the
2181 actual host that was used. */
2182
2183 addr->transport_return = OK;
2184 addr->more_errno = delivery_time;
2185 addr->host_used = thost;
2186 addr->special_action = flag;
2187 addr->message = conf;
2188 #ifndef DISABLE_PRDR
2189 if (prdr_active) addr->flags |= af_prdr_used;
2190 #endif
2191 flag = '-';
2192
2193 #ifndef DISABLE_PRDR
2194 if (!prdr_active)
2195 #endif
2196 {
2197 /* Update the journal. For homonymic addresses, use the base address plus
2198 the transport name. See lots of comments in deliver.c about the reasons
2199 for the complications when homonyms are involved. Just carry on after
2200 write error, as it may prove possible to update the spool file later. */
2201
2202 if (testflag(addr, af_homonym))
2203 sprintf(CS buffer, "%.500s/%s\n", addr->unique + 3, tblock->name);
2204 else
2205 sprintf(CS buffer, "%.500s\n", addr->unique);
2206
2207 DEBUG(D_deliver) debug_printf("journalling %s", buffer);
2208 len = Ustrlen(CS buffer);
2209 if (write(journal_fd, buffer, len) != len)
2210 log_write(0, LOG_MAIN|LOG_PANIC, "failed to write journal for "
2211 "%s: %s", buffer, strerror(errno));
2212 }
2213 }
2214
2215 #ifndef DISABLE_PRDR
2216 if (prdr_active)
2217 {
2218 /* PRDR - get the final, overall response. For any non-success
2219 upgrade all the address statuses. */
2220 ok = smtp_read_response(&inblock, buffer, sizeof(buffer), '2',
2221 ob->final_timeout);
2222 if (!ok)
2223 {
2224 if(errno == 0 && buffer[0] == '4')
2225 {
2226 errno = ERRNO_DATA4XX;
2227 addrlist->more_errno |= ((buffer[1] - '0')*10 + buffer[2] - '0') << 8;
2228 }
2229 for (addr = addrlist; addr != first_addr; addr = addr->next)
2230 if (buffer[0] == '5' || addr->transport_return == OK)
2231 addr->transport_return = PENDING_OK; /* allow set_errno action */
2232 goto RESPONSE_FAILED;
2233 }
2234
2235 /* Update the journal, or setup retry. */
2236 for (addr = addrlist; addr != first_addr; addr = addr->next)
2237 if (addr->transport_return == OK)
2238 {
2239 if (testflag(addr, af_homonym))
2240 sprintf(CS buffer, "%.500s/%s\n", addr->unique + 3, tblock->name);
2241 else
2242 sprintf(CS buffer, "%.500s\n", addr->unique);
2243
2244 DEBUG(D_deliver) debug_printf("journalling(PRDR) %s", buffer);
2245 len = Ustrlen(CS buffer);
2246 if (write(journal_fd, buffer, len) != len)
2247 log_write(0, LOG_MAIN|LOG_PANIC, "failed to write journal for "
2248 "%s: %s", buffer, strerror(errno));
2249 }
2250 else if (addr->transport_return == DEFER)
2251 retry_add_item(addr, addr->address_retry_key, -2);
2252 }
2253 #endif
2254
2255 /* Ensure the journal file is pushed out to disk. */
2256
2257 if (EXIMfsync(journal_fd) < 0)
2258 log_write(0, LOG_MAIN|LOG_PANIC, "failed to fsync journal: %s",
2259 strerror(errno));
2260 }
2261 }
2262
2263
2264 /* Handle general (not specific to one address) failures here. The value of ok
2265 is used to skip over this code on the falling through case. A timeout causes a
2266 deferral. Other errors may defer or fail according to the response code, and
2267 may set up a special errno value, e.g. after connection chopped, which is
2268 assumed if errno == 0 and there is no text in the buffer. If control reaches
2269 here during the setting up phase (i.e. before MAIL FROM) then always defer, as
2270 the problem is not related to this specific message. */
2271
2272 if (!ok)
2273 {
2274 int code;
2275
2276 RESPONSE_FAILED:
2277 save_errno = errno;
2278 message = NULL;
2279 send_quit = check_response(host, &save_errno, addrlist->more_errno,
2280 buffer, &code, &message, &pass_message);
2281 goto FAILED;
2282
2283 SEND_FAILED:
2284 save_errno = errno;
2285 code = '4';
2286 message = US string_sprintf("send() to %s [%s] failed: %s",
2287 host->name, host->address, strerror(save_errno));
2288 send_quit = FALSE;
2289 goto FAILED;
2290
2291 /* This label is jumped to directly when a TLS negotiation has failed,
2292 or was not done for a host for which it is required. Values will be set
2293 in message and save_errno, and setting_up will always be true. Treat as
2294 a temporary error. */
2295
2296 #ifdef SUPPORT_TLS
2297 TLS_FAILED:
2298 code = '4';
2299 #endif
2300
2301 /* If the failure happened while setting up the call, see if the failure was
2302 a 5xx response (this will either be on connection, or following HELO - a 5xx
2303 after EHLO causes it to try HELO). If so, fail all addresses, as this host is
2304 never going to accept them. For other errors during setting up (timeouts or
2305 whatever), defer all addresses, and yield DEFER, so that the host is not
2306 tried again for a while. */
2307
2308 FAILED:
2309 ok = FALSE; /* For when reached by GOTO */
2310
2311 if (setting_up)
2312 {
2313 if (code == '5')
2314 {
2315 set_errno(addrlist, save_errno, message, FAIL, pass_message);
2316 }
2317 else
2318 {
2319 set_errno(addrlist, save_errno, message, DEFER, pass_message);
2320 yield = DEFER;
2321 }
2322 }
2323
2324 /* We want to handle timeouts after MAIL or "." and loss of connection after
2325 "." specially. They can indicate a problem with the sender address or with
2326 the contents of the message rather than a real error on the connection. These
2327 cases are treated in the same way as a 4xx response. This next bit of code
2328 does the classification. */
2329
2330 else
2331 {
2332 BOOL message_error;
2333
2334 switch(save_errno)
2335 {
2336 case 0:
2337 case ERRNO_MAIL4XX:
2338 case ERRNO_DATA4XX:
2339 message_error = TRUE;
2340 break;
2341
2342 case ETIMEDOUT:
2343 message_error = Ustrncmp(smtp_command,"MAIL",4) == 0 ||
2344 Ustrncmp(smtp_command,"end ",4) == 0;
2345 break;
2346
2347 case ERRNO_SMTPCLOSED:
2348 message_error = Ustrncmp(smtp_command,"end ",4) == 0;
2349 break;
2350
2351 default:
2352 message_error = FALSE;
2353 break;
2354 }
2355
2356 /* Handle the cases that are treated as message errors. These are:
2357
2358 (a) negative response or timeout after MAIL
2359 (b) negative response after DATA
2360 (c) negative response or timeout or dropped connection after "."
2361
2362 It won't be a negative response or timeout after RCPT, as that is dealt
2363 with separately above. The action in all cases is to set an appropriate
2364 error code for all the addresses, but to leave yield set to OK because the
2365 host itself has not failed. Of course, it might in practice have failed
2366 when we've had a timeout, but if so, we'll discover that at the next
2367 delivery attempt. For a temporary error, set the message_defer flag, and
2368 write to the logs for information if this is not the last host. The error
2369 for the last host will be logged as part of the address's log line. */
2370
2371 if (message_error)
2372 {
2373 if (mua_wrapper) code = '5'; /* Force hard failure in wrapper mode */
2374 set_errno(addrlist, save_errno, message, (code == '5')? FAIL : DEFER,
2375 pass_message);
2376
2377 /* If there's an errno, the message contains just the identity of
2378 the host. */
2379
2380 if (code != '5') /* Anything other than 5 is treated as temporary */
2381 {
2382 if (save_errno > 0)
2383 message = US string_sprintf("%s: %s", message, strerror(save_errno));
2384 if (host->next != NULL) log_write(0, LOG_MAIN, "%s", message);
2385 deliver_msglog("%s %s\n", tod_stamp(tod_log), message);
2386 *message_defer = TRUE;
2387 }
2388 }
2389
2390 /* Otherwise, we have an I/O error or a timeout other than after MAIL or
2391 ".", or some other transportation error. We defer all addresses and yield
2392 DEFER, except for the case of failed add_headers expansion, or a transport
2393 filter failure, when the yield should be ERROR, to stop it trying other
2394 hosts. */
2395
2396 else
2397 {
2398 yield = (save_errno == ERRNO_CHHEADER_FAIL ||
2399 save_errno == ERRNO_FILTER_FAIL)? ERROR : DEFER;
2400 set_errno(addrlist, save_errno, message, DEFER, pass_message);
2401 }
2402 }
2403 }
2404
2405
2406 /* If all has gone well, send_quit will be set TRUE, implying we can end the
2407 SMTP session tidily. However, if there were too many addresses to send in one
2408 message (indicated by first_addr being non-NULL) we want to carry on with the
2409 rest of them. Also, it is desirable to send more than one message down the SMTP
2410 connection if there are several waiting, provided we haven't already sent so
2411 many as to hit the configured limit. The function transport_check_waiting looks
2412 for a waiting message and returns its id. Then transport_pass_socket tries to
2413 set up a continued delivery by passing the socket on to another process. The
2414 variable send_rset is FALSE if a message has just been successfully transfered.
2415
2416 If we are already sending down a continued channel, there may be further
2417 addresses not yet delivered that are aimed at the same host, but which have not
2418 been passed in this run of the transport. In this case, continue_more will be
2419 true, and all we should do is send RSET if necessary, and return, leaving the
2420 channel open.
2421
2422 However, if no address was disposed of, i.e. all addresses got 4xx errors, we
2423 do not want to continue with other messages down the same channel, because that
2424 can lead to looping between two or more messages, all with the same,
2425 temporarily failing address(es). [The retry information isn't updated yet, so
2426 new processes keep on trying.] We probably also don't want to try more of this
2427 message's addresses either.
2428
2429 If we have started a TLS session, we have to end it before passing the
2430 connection to a new process. However, not all servers can handle this (Exim
2431 can), so we do not pass such a connection on if the host matches
2432 hosts_nopass_tls. */
2433
2434 DEBUG(D_transport)
2435 debug_printf("ok=%d send_quit=%d send_rset=%d continue_more=%d "
2436 "yield=%d first_address is %sNULL\n", ok, send_quit, send_rset,
2437 continue_more, yield, (first_addr == NULL)? "":"not ");
2438
2439 if (completed_address && ok && send_quit)
2440 {
2441 BOOL more;
2442 if (first_addr != NULL || continue_more ||
2443 (
2444 (tls_out.active < 0 ||
2445 verify_check_this_host(&(ob->hosts_nopass_tls), NULL, host->name,
2446 host->address, NULL) != OK)
2447 &&
2448 transport_check_waiting(tblock->name, host->name,
2449 tblock->connection_max_messages, new_message_id, &more)
2450 ))
2451 {
2452 uschar *msg;
2453 BOOL pass_message;
2454
2455 if (send_rset)
2456 {
2457 if (! (ok = smtp_write_command(&outblock, FALSE, "RSET\r\n") >= 0))
2458 {
2459 msg = US string_sprintf("send() to %s [%s] failed: %s", host->name,
2460 host->address, strerror(save_errno));
2461 send_quit = FALSE;
2462 }
2463 else if (! (ok = smtp_read_response(&inblock, buffer, sizeof(buffer), '2',
2464 ob->command_timeout)))
2465 {
2466 int code;
2467 send_quit = check_response(host, &errno, 0, buffer, &code, &msg,
2468 &pass_message);
2469 if (!send_quit)
2470 {
2471 DEBUG(D_transport) debug_printf("%s\n", msg);
2472 }
2473 }
2474 }
2475
2476 /* Either RSET was not needed, or it succeeded */
2477
2478 if (ok)
2479 {
2480 if (first_addr != NULL) /* More addresses still to be sent */
2481 { /* in this run of the transport */
2482 continue_sequence++; /* Causes * in logging */
2483 goto SEND_MESSAGE;
2484 }
2485 if (continue_more) return yield; /* More addresses for another run */
2486
2487 /* Pass the socket to a new Exim process. Before doing so, we must shut
2488 down TLS. Not all MTAs allow for the continuation of the SMTP session
2489 when TLS is shut down. We test for this by sending a new EHLO. If we
2490 don't get a good response, we don't attempt to pass the socket on. */
2491
2492 #ifdef SUPPORT_TLS
2493 if (tls_out.active >= 0)
2494 {
2495 tls_close(FALSE, TRUE);
2496 if (smtps)
2497 ok = FALSE;
2498 else
2499 ok = smtp_write_command(&outblock,FALSE,"EHLO %s\r\n",helo_data) >= 0 &&
2500 smtp_read_response(&inblock, buffer, sizeof(buffer), '2',
2501 ob->command_timeout);
2502 }
2503 #endif
2504
2505 /* If the socket is successfully passed, we musn't send QUIT (or
2506 indeed anything!) from here. */
2507
2508 if (ok && transport_pass_socket(tblock->name, host->name, host->address,
2509 new_message_id, inblock.sock))
2510 {
2511 send_quit = FALSE;
2512 }
2513 }
2514
2515 /* If RSET failed and there are addresses left, they get deferred. */
2516
2517 else set_errno(first_addr, errno, msg, DEFER, FALSE);
2518 }
2519 }
2520
2521 /* End off tidily with QUIT unless the connection has died or the socket has
2522 been passed to another process. There has been discussion on the net about what
2523 to do after sending QUIT. The wording of the RFC suggests that it is necessary
2524 to wait for a response, but on the other hand, there isn't anything one can do
2525 with an error response, other than log it. Exim used to do that. However,
2526 further discussion suggested that it is positively advantageous not to wait for
2527 the response, but to close the session immediately. This is supposed to move
2528 the TCP/IP TIME_WAIT state from the server to the client, thereby removing some
2529 load from the server. (Hosts that are both servers and clients may not see much
2530 difference, of course.) Further discussion indicated that this was safe to do
2531 on Unix systems which have decent implementations of TCP/IP that leave the
2532 connection around for a while (TIME_WAIT) after the application has gone away.
2533 This enables the response sent by the server to be properly ACKed rather than
2534 timed out, as can happen on broken TCP/IP implementations on other OS.
2535
2536 This change is being made on 31-Jul-98. After over a year of trouble-free
2537 operation, the old commented-out code was removed on 17-Sep-99. */
2538
2539 SEND_QUIT:
2540 if (send_quit) (void)smtp_write_command(&outblock, FALSE, "QUIT\r\n");
2541
2542 END_OFF:
2543
2544 #ifdef SUPPORT_TLS
2545 tls_close(FALSE, TRUE);
2546 #endif
2547
2548 /* Close the socket, and return the appropriate value, first setting
2549 works because the NULL setting is passed back to the calling process, and
2550 remote_max_parallel is forced to 1 when delivering over an existing connection,
2551
2552 If all went well and continue_more is set, we shouldn't actually get here if
2553 there are further addresses, as the return above will be taken. However,
2554 writing RSET might have failed, or there may be other addresses whose hosts are
2555 specified in the transports, and therefore not visible at top level, in which
2556 case continue_more won't get set. */
2557
2558 (void)close(inblock.sock);
2559 continue_transport = NULL;
2560 continue_hostname = NULL;
2561 return yield;
2562 }
2563
2564
2565
2566
2567 /*************************************************
2568 * Closedown entry point *
2569 *************************************************/
2570
2571 /* This function is called when exim is passed an open smtp channel
2572 from another incarnation, but the message which it has been asked
2573 to deliver no longer exists. The channel is on stdin.
2574
2575 We might do fancy things like looking for another message to send down
2576 the channel, but if the one we sought has gone, it has probably been
2577 delivered by some other process that itself will seek further messages,
2578 so just close down our connection.
2579
2580 Argument: pointer to the transport instance block
2581 Returns: nothing
2582 */
2583
2584 void
2585 smtp_transport_closedown(transport_instance *tblock)
2586 {
2587 smtp_transport_options_block *ob =
2588 (smtp_transport_options_block *)(tblock->options_block);
2589 smtp_inblock inblock;
2590 smtp_outblock outblock;
2591 uschar buffer[256];
2592 uschar inbuffer[4096];
2593 uschar outbuffer[16];
2594
2595 inblock.sock = fileno(stdin);
2596 inblock.buffer = inbuffer;
2597 inblock.buffersize = sizeof(inbuffer);
2598 inblock.ptr = inbuffer;
2599 inblock.ptrend = inbuffer;
2600
2601 outblock.sock = inblock.sock;
2602 outblock.buffersize = sizeof(outbuffer);
2603 outblock.buffer = outbuffer;
2604 outblock.ptr = outbuffer;
2605 outblock.cmd_count = 0;
2606 outblock.authenticating = FALSE;
2607
2608 (void)smtp_write_command(&outblock, FALSE, "QUIT\r\n");
2609 (void)smtp_read_response(&inblock, buffer, sizeof(buffer), '2',
2610 ob->command_timeout);
2611 (void)close(inblock.sock);
2612 }
2613
2614
2615
2616 /*************************************************
2617 * Prepare addresses for delivery *
2618 *************************************************/
2619
2620 /* This function is called to flush out error settings from previous delivery
2621 attempts to other hosts. It also records whether we got here via an MX record
2622 or not in the more_errno field of the address. We are interested only in
2623 addresses that are still marked DEFER - others may have got delivered to a
2624 previously considered IP address. Set their status to PENDING_DEFER to indicate
2625 which ones are relevant this time.
2626
2627 Arguments:
2628 addrlist the list of addresses
2629 host the host we are delivering to
2630
2631 Returns: the first address for this delivery
2632 */
2633
2634 static address_item *
2635 prepare_addresses(address_item *addrlist, host_item *host)
2636 {
2637 address_item *first_addr = NULL;
2638 address_item *addr;
2639 for (addr = addrlist; addr != NULL; addr = addr->next)
2640 {
2641 if (addr->transport_return != DEFER) continue;
2642 if (first_addr == NULL) first_addr = addr;
2643 addr->transport_return = PENDING_DEFER;
2644 addr->basic_errno = 0;
2645 addr->more_errno = (host->mx >= 0)? 'M' : 'A';
2646 addr->message = NULL;
2647 #ifdef SUPPORT_TLS
2648 addr->cipher = NULL;
2649 addr->ourcert = NULL;
2650 addr->peercert = NULL;
2651 addr->peerdn = NULL;
2652 addr->ocsp = OCSP_NOT_REQ;
2653 #endif
2654 }
2655 return first_addr;
2656 }
2657
2658
2659
2660 /*************************************************
2661 * Main entry point *
2662 *************************************************/
2663
2664 /* See local README for interface details. As this is a remote transport, it is
2665 given a chain of addresses to be delivered in one connection, if possible. It
2666 always returns TRUE, indicating that each address has its own independent
2667 status set, except if there is a setting up problem, in which case it returns
2668 FALSE. */
2669
2670 BOOL
2671 smtp_transport_entry(
2672 transport_instance *tblock, /* data for this instantiation */
2673 address_item *addrlist) /* addresses we are working on */
2674 {
2675 int cutoff_retry;
2676 int port;
2677 int hosts_defer = 0;
2678 int hosts_fail = 0;
2679 int hosts_looked_up = 0;
2680 int hosts_retry = 0;
2681 int hosts_serial = 0;
2682 int hosts_total = 0;
2683 int total_hosts_tried = 0;
2684 address_item *addr;
2685 BOOL expired = TRUE;
2686 BOOL continuing = continue_hostname != NULL;
2687 uschar *expanded_hosts = NULL;
2688 uschar *pistring;
2689 uschar *tid = string_sprintf("%s transport", tblock->name);
2690 smtp_transport_options_block *ob =
2691 (smtp_transport_options_block *)(tblock->options_block);
2692 host_item *hostlist = addrlist->host_list;
2693 host_item *host = NULL;
2694
2695 DEBUG(D_transport)
2696 {
2697 debug_printf("%s transport entered\n", tblock->name);
2698 for (addr = addrlist; addr != NULL; addr = addr->next)
2699 debug_printf(" %s\n", addr->address);
2700 if (continuing) debug_printf("already connected to %s [%s]\n",
2701 continue_hostname, continue_host_address);
2702 }
2703
2704 /* Set the flag requesting that these hosts be added to the waiting
2705 database if the delivery fails temporarily or if we are running with
2706 queue_smtp or a 2-stage queue run. This gets unset for certain
2707 kinds of error, typically those that are specific to the message. */
2708
2709 update_waiting = TRUE;
2710
2711 /* If a host list is not defined for the addresses - they must all have the
2712 same one in order to be passed to a single transport - or if the transport has
2713 a host list with hosts_override set, use the host list supplied with the
2714 transport. It is an error for this not to exist. */
2715
2716 if (hostlist == NULL || (ob->hosts_override && ob->hosts != NULL))
2717 {
2718 if (ob->hosts == NULL)
2719 {
2720 addrlist->message = string_sprintf("%s transport called with no hosts set",
2721 tblock->name);
2722 addrlist->transport_return = PANIC;
2723 return FALSE; /* Only top address has status */
2724 }
2725
2726 DEBUG(D_transport) debug_printf("using the transport's hosts: %s\n",
2727 ob->hosts);
2728
2729 /* If the transport's host list contains no '$' characters, and we are not
2730 randomizing, it is fixed and therefore a chain of hosts can be built once
2731 and for all, and remembered for subsequent use by other calls to this
2732 transport. If, on the other hand, the host list does contain '$', or we are
2733 randomizing its order, we have to rebuild it each time. In the fixed case,
2734 as the hosts string will never be used again, it doesn't matter that we
2735 replace all the : characters with zeros. */
2736
2737 if (ob->hostlist == NULL)
2738 {
2739 uschar *s = ob->hosts;
2740
2741 if (Ustrchr(s, '$') != NULL)
2742 {
2743 expanded_hosts = expand_string(s);
2744 if (expanded_hosts == NULL)
2745 {
2746 addrlist->message = string_sprintf("failed to expand list of hosts "
2747 "\"%s\" in %s transport: %s", s, tblock->name, expand_string_message);
2748 addrlist->transport_return = search_find_defer? DEFER : PANIC;
2749 return FALSE; /* Only top address has status */
2750 }
2751 DEBUG(D_transport) debug_printf("expanded list of hosts \"%s\" to "
2752 "\"%s\"\n", s, expanded_hosts);
2753 s = expanded_hosts;
2754 }
2755 else
2756 if (ob->hosts_randomize) s = expanded_hosts = string_copy(s);
2757
2758 host_build_hostlist(&hostlist, s, ob->hosts_randomize);
2759
2760 /* Check that the expansion yielded something useful. */
2761 if (hostlist == NULL)
2762 {
2763 addrlist->message =
2764 string_sprintf("%s transport has empty hosts setting", tblock->name);
2765 addrlist->transport_return = PANIC;
2766 return FALSE; /* Only top address has status */
2767 }
2768
2769 /* If there was no expansion of hosts, save the host list for
2770 next time. */
2771
2772 if (expanded_hosts == NULL) ob->hostlist = hostlist;
2773 }
2774
2775 /* This is not the first time this transport has been run in this delivery;
2776 the host list was built previously. */
2777
2778 else hostlist = ob->hostlist;
2779 }
2780
2781 /* The host list was supplied with the address. If hosts_randomize is set, we
2782 must sort it into a random order if it did not come from MX records and has not
2783 already been randomized (but don't bother if continuing down an existing
2784 connection). */
2785
2786 else if (ob->hosts_randomize && hostlist->mx == MX_NONE && !continuing)
2787 {
2788 host_item *newlist = NULL;
2789 while (hostlist != NULL)
2790 {
2791 host_item *h = hostlist;
2792 hostlist = hostlist->next;
2793
2794 h->sort_key = random_number(100);
2795
2796 if (newlist == NULL)
2797 {
2798 h->next = NULL;
2799 newlist = h;
2800 }
2801 else if (h->sort_key < newlist->sort_key)
2802 {
2803 h->next = newlist;
2804 newlist = h;
2805 }
2806 else
2807 {
2808 host_item *hh = newlist;
2809 while (hh->next != NULL)
2810 {
2811 if (h->sort_key < hh->next->sort_key) break;
2812 hh = hh->next;
2813 }
2814 h->next = hh->next;
2815 hh->next = h;
2816 }
2817 }
2818
2819 hostlist = addrlist->host_list = newlist;
2820 }
2821
2822
2823 /* Sort out the default port. */
2824
2825 if (!smtp_get_port(ob->port, addrlist, &port, tid)) return FALSE;
2826
2827
2828 /* For each host-plus-IP-address on the list:
2829
2830 . If this is a continued delivery and the host isn't the one with the
2831 current connection, skip.
2832
2833 . If the status is unusable (i.e. previously failed or retry checked), skip.
2834
2835 . If no IP address set, get the address, either by turning the name into
2836 an address, calling gethostbyname if gethostbyname is on, or by calling
2837 the DNS. The DNS may yield multiple addresses, in which case insert the
2838 extra ones into the list.
2839
2840 . Get the retry data if not previously obtained for this address and set the
2841 field which remembers the state of this address. Skip if the retry time is
2842 not reached. If not, remember whether retry data was found. The retry string
2843 contains both the name and the IP address.
2844
2845 . Scan the list of addresses and mark those whose status is DEFER as
2846 PENDING_DEFER. These are the only ones that will be processed in this cycle
2847 of the hosts loop.
2848
2849 . Make a delivery attempt - addresses marked PENDING_DEFER will be tried.
2850 Some addresses may be successfully delivered, others may fail, and yet
2851 others may get temporary errors and so get marked DEFER.
2852
2853 . The return from the delivery attempt is OK if a connection was made and a
2854 valid SMTP dialogue was completed. Otherwise it is DEFER.
2855
2856 . If OK, add a "remove" retry item for this host/IPaddress, if any.
2857
2858 . If fail to connect, or other defer state, add a retry item.
2859
2860 . If there are any addresses whose status is still DEFER, carry on to the
2861 next host/IPaddress, unless we have tried the number of hosts given
2862 by hosts_max_try or hosts_max_try_hardlimit; otherwise return. Note that
2863 there is some fancy logic for hosts_max_try that means its limit can be
2864 overstepped in some circumstances.
2865
2866 If we get to the end of the list, all hosts have deferred at least one address,
2867 or not reached their retry times. If delay_after_cutoff is unset, it requests a
2868 delivery attempt to those hosts whose last try was before the arrival time of
2869 the current message. To cope with this, we have to go round the loop a second
2870 time. After that, set the status and error data for any addresses that haven't
2871 had it set already. */
2872
2873 for (cutoff_retry = 0; expired &&
2874 cutoff_retry < ((ob->delay_after_cutoff)? 1 : 2);
2875 cutoff_retry++)
2876 {
2877 host_item *nexthost = NULL;
2878 int unexpired_hosts_tried = 0;
2879
2880 for (host = hostlist;
2881 host != NULL &&
2882 unexpired_hosts_tried < ob->hosts_max_try &&
2883 total_hosts_tried < ob->hosts_max_try_hardlimit;
2884 host = nexthost)
2885 {
2886 int rc;
2887 int host_af;
2888 uschar *rs;
2889 BOOL serialized = FALSE;
2890 BOOL host_is_expired = FALSE;
2891 BOOL message_defer = FALSE;
2892 BOOL ifchanges = FALSE;
2893 BOOL some_deferred = FALSE;
2894 address_item *first_addr = NULL;
2895 uschar *interface = NULL;
2896 uschar *retry_host_key = NULL;
2897 uschar *retry_message_key = NULL;
2898 uschar *serialize_key = NULL;
2899
2900 /* Default next host is next host. :-) But this can vary if the
2901 hosts_max_try limit is hit (see below). It may also be reset if a host
2902 address is looked up here (in case the host was multihomed). */
2903
2904 nexthost = host->next;
2905
2906 /* If the address hasn't yet been obtained from the host name, look it up
2907 now, unless the host is already marked as unusable. If it is marked as
2908 unusable, it means that the router was unable to find its IP address (in
2909 the DNS or wherever) OR we are in the 2nd time round the cutoff loop, and
2910 the lookup failed last time. We don't get this far if *all* MX records
2911 point to non-existent hosts; that is treated as a hard error.
2912
2913 We can just skip this host entirely. When the hosts came from the router,
2914 the address will timeout based on the other host(s); when the address is
2915 looked up below, there is an explicit retry record added.
2916
2917 Note that we mustn't skip unusable hosts if the address is not unset; they
2918 may be needed as expired hosts on the 2nd time round the cutoff loop. */
2919
2920 if (host->address == NULL)
2921 {
2922 int new_port, flags;
2923 host_item *hh;
2924 uschar *canonical_name;
2925
2926 if (host->status >= hstatus_unusable)
2927 {
2928 DEBUG(D_transport) debug_printf("%s has no address and is unusable - skipping\n",
2929 host->name);
2930 continue;
2931 }
2932
2933 DEBUG(D_transport) debug_printf("getting address for %s\n", host->name);
2934
2935 /* The host name is permitted to have an attached port. Find it, and
2936 strip it from the name. Just remember it for now. */
2937
2938 new_port = host_item_get_port(host);
2939
2940 /* Count hosts looked up */
2941
2942 hosts_looked_up++;
2943
2944 /* Find by name if so configured, or if it's an IP address. We don't
2945 just copy the IP address, because we need the test-for-local to happen. */
2946
2947 flags = HOST_FIND_BY_A;
2948 if (ob->dns_qualify_single) flags |= HOST_FIND_QUALIFY_SINGLE;
2949 if (ob->dns_search_parents) flags |= HOST_FIND_SEARCH_PARENTS;
2950
2951 if (ob->gethostbyname || string_is_ip_address(host->name, NULL) != 0)
2952 rc = host_find_byname(host, NULL, flags, &canonical_name, TRUE);
2953 else
2954 rc = host_find_bydns(host, NULL, flags, NULL, NULL, NULL,
2955 ob->dnssec_request_domains, ob->dnssec_require_domains,
2956 &canonical_name, NULL);
2957
2958 /* Update the host (and any additional blocks, resulting from
2959 multihoming) with a host-specific port, if any. */
2960
2961 for (hh = host; hh != nexthost; hh = hh->next) hh->port = new_port;
2962
2963 /* Failure to find the host at this time (usually DNS temporary failure)
2964 is really a kind of routing failure rather than a transport failure.
2965 Therefore we add a retry item of the routing kind, not to stop us trying
2966 to look this name up here again, but to ensure the address gets timed
2967 out if the failures go on long enough. A complete failure at this point
2968 commonly points to a configuration error, but the best action is still
2969 to carry on for the next host. */
2970
2971 if (rc == HOST_FIND_AGAIN || rc == HOST_FIND_FAILED)
2972 {
2973 retry_add_item(addrlist, string_sprintf("R:%s", host->name), 0);
2974 expired = FALSE;
2975 if (rc == HOST_FIND_AGAIN) hosts_defer++; else hosts_fail++;
2976 DEBUG(D_transport) debug_printf("rc = %s for %s\n", (rc == HOST_FIND_AGAIN)?
2977 "HOST_FIND_AGAIN" : "HOST_FIND_FAILED", host->name);
2978 host->status = hstatus_unusable;
2979
2980 for (addr = addrlist; addr != NULL; addr = addr->next)
2981 {
2982 if (addr->transport_return != DEFER) continue;
2983 addr->basic_errno = ERRNO_UNKNOWNHOST;
2984 addr->message =
2985 string_sprintf("failed to lookup IP address for %s", host->name);
2986 }
2987 continue;
2988 }
2989
2990 /* If the host is actually the local host, we may have a problem, or
2991 there may be some cunning configuration going on. In the problem case,
2992 log things and give up. The default transport status is already DEFER. */
2993
2994 if (rc == HOST_FOUND_LOCAL && !ob->allow_localhost)
2995 {
2996 for (addr = addrlist; addr != NULL; addr = addr->next)
2997 {
2998 addr->basic_errno = 0;
2999 addr->message = string_sprintf("%s transport found host %s to be "
3000 "local", tblock->name, host->name);
3001 }
3002 goto END_TRANSPORT;
3003 }
3004 } /* End of block for IP address lookup */
3005
3006 /* If this is a continued delivery, we are interested only in the host
3007 which matches the name of the existing open channel. The check is put
3008 here after the local host lookup, in case the name gets expanded as a
3009 result of the lookup. Set expired FALSE, to save the outer loop executing
3010 twice. */
3011
3012 if (continuing && (Ustrcmp(continue_hostname, host->name) != 0 ||
3013 Ustrcmp(continue_host_address, host->address) != 0))
3014 {
3015 expired = FALSE;
3016 continue; /* With next host */
3017 }
3018
3019 /* Reset the default next host in case a multihomed host whose addresses
3020 are not looked up till just above added to the host list. */
3021
3022 nexthost = host->next;
3023
3024 /* If queue_smtp is set (-odqs or the first part of a 2-stage run), or the
3025 domain is in queue_smtp_domains, we don't actually want to attempt any
3026 deliveries. When doing a queue run, queue_smtp_domains is always unset. If
3027 there is a lookup defer in queue_smtp_domains, proceed as if the domain
3028 were not in it. We don't want to hold up all SMTP deliveries! Except when
3029 doing a two-stage queue run, don't do this if forcing. */
3030
3031 if ((!deliver_force || queue_2stage) && (queue_smtp ||
3032 match_isinlist(addrlist->domain, &queue_smtp_domains, 0,
3033 &domainlist_anchor, NULL, MCL_DOMAIN, TRUE, NULL) == OK))
3034 {
3035 expired = FALSE;
3036 for (addr = addrlist; addr != NULL; addr = addr->next)
3037 {
3038 if (addr->transport_return != DEFER) continue;
3039 addr->message = US"domain matches queue_smtp_domains, or -odqs set";
3040 }
3041 continue; /* With next host */
3042 }
3043
3044 /* Count hosts being considered - purely for an intelligent comment
3045 if none are usable. */
3046
3047 hosts_total++;
3048
3049 /* Set $host and $host address now in case they are needed for the
3050 interface expansion or the serialize_hosts check; they remain set if an
3051 actual delivery happens. */
3052
3053 deliver_host = host->name;
3054 deliver_host_address = host->address;
3055 lookup_dnssec_authenticated = host->dnssec == DS_YES ? US"yes"
3056 : host->dnssec == DS_NO ? US"no"
3057 : US"";
3058
3059 /* Set up a string for adding to the retry key if the port number is not
3060 the standard SMTP port. A host may have its own port setting that overrides
3061 the default. */
3062
3063 pistring = string_sprintf(":%d", (host->port == PORT_NONE)?
3064 port : host->port);
3065 if (Ustrcmp(pistring, ":25") == 0) pistring = US"";
3066
3067 /* Select IPv4 or IPv6, and choose an outgoing interface. If the interface
3068 string changes upon expansion, we must add it to the key that is used for
3069 retries, because connections to the same host from a different interface
3070 should be treated separately. */
3071
3072 host_af = (Ustrchr(host->address, ':') == NULL)? AF_INET : AF_INET6;
3073 if (!smtp_get_interface(ob->interface, host_af, addrlist, &ifchanges,
3074 &interface, tid))
3075 return FALSE;
3076 if (ifchanges) pistring = string_sprintf("%s/%s", pistring, interface);
3077
3078 /* The first time round the outer loop, check the status of the host by
3079 inspecting the retry data. The second time round, we are interested only
3080 in expired hosts that haven't been tried since this message arrived. */
3081
3082 if (cutoff_retry == 0)
3083 {
3084 /* Ensure the status of the address is set by checking retry data if
3085 necessary. There maybe host-specific retry data (applicable to all
3086 messages) and also data for retries of a specific message at this host.
3087 If either of these retry records are actually read, the keys used are
3088 returned to save recomputing them later. */
3089
3090 host_is_expired = retry_check_address(addrlist->domain, host, pistring,
3091 ob->retry_include_ip_address, &retry_host_key, &retry_message_key);
3092
3093 DEBUG(D_transport) debug_printf("%s [%s]%s status = %s\n", host->name,
3094 (host->address == NULL)? US"" : host->address, pistring,
3095 (host->status == hstatus_usable)? "usable" :
3096 (host->status == hstatus_unusable)? "unusable" :
3097 (host->status == hstatus_unusable_expired)? "unusable (expired)" : "?");
3098
3099 /* Skip this address if not usable at this time, noting if it wasn't
3100 actually expired, both locally and in the address. */
3101
3102 switch (host->status)
3103 {
3104 case hstatus_unusable:
3105 expired = FALSE;
3106 setflag(addrlist, af_retry_skipped);
3107 /* Fall through */
3108
3109 case hstatus_unusable_expired:
3110 switch (host->why)
3111 {
3112 case hwhy_retry: hosts_retry++; break;
3113 case hwhy_failed: hosts_fail++; break;
3114 case hwhy_deferred: hosts_defer++; break;
3115 }
3116
3117 /* If there was a retry message key, implying that previously there
3118 was a message-specific defer, we don't want to update the list of
3119 messages waiting for these hosts. */
3120
3121 if (retry_message_key != NULL) update_waiting = FALSE;
3122 continue; /* With the next host or IP address */
3123 }
3124 }
3125
3126 /* Second time round the loop: if the address is set but expired, and
3127 the message is newer than the last try, let it through. */
3128
3129 else
3130 {
3131 if (host->address == NULL ||
3132 host->status != hstatus_unusable_expired ||
3133 host->last_try > received_time)
3134 continue;
3135 DEBUG(D_transport)
3136 debug_printf("trying expired host %s [%s]%s\n",
3137 host->name, host->address, pistring);
3138 host_is_expired = TRUE;
3139 }
3140
3141 /* Setting "expired=FALSE" doesn't actually mean not all hosts are expired;
3142 it remains TRUE only if all hosts are expired and none are actually tried.
3143 */
3144
3145 expired = FALSE;
3146
3147 /* If this host is listed as one to which access must be serialized,
3148 see if another Exim process has a connection to it, and if so, skip
3149 this host. If not, update the database to record our connection to it
3150 and remember this for later deletion. Do not do any of this if we are
3151 sending the message down a pre-existing connection. */
3152
3153 if (!continuing &&
3154 verify_check_this_host(&(ob->serialize_hosts), NULL, host->name,
3155 host->address, NULL) == OK)
3156 {
3157 serialize_key = string_sprintf("host-serialize-%s", host->name);
3158 if (!enq_start(serialize_key))
3159 {
3160 DEBUG(D_transport)
3161 debug_printf("skipping host %s because another Exim process "
3162 "is connected to it\n", host->name);
3163 hosts_serial++;
3164 continue;
3165 }
3166 serialized = TRUE;
3167 }
3168
3169 /* OK, we have an IP address that is not waiting for its retry time to
3170 arrive (it might be expired) OR (second time round the loop) we have an
3171 expired host that hasn't been tried since the message arrived. Have a go
3172 at delivering the message to it. First prepare the addresses by flushing
3173 out the result of previous attempts, and finding the first address that
3174 is still to be delivered. */
3175
3176 first_addr = prepare_addresses(addrlist, host);
3177
3178 DEBUG(D_transport) debug_printf("delivering %s to %s [%s] (%s%s)\n",
3179 message_id, host->name, host->address, addrlist->address,
3180 (addrlist->next == NULL)? "" : ", ...");
3181
3182 set_process_info("delivering %s to %s [%s] (%s%s)",
3183 message_id, host->name, host->address, addrlist->address,
3184 (addrlist->next == NULL)? "" : ", ...");
3185
3186 /* This is not for real; don't do the delivery. If there are
3187 any remaining hosts, list them. */
3188
3189 if (dont_deliver)
3190 {
3191 host_item *host2;
3192 set_errno(addrlist, 0, NULL, OK, FALSE);
3193 for (addr = addrlist; addr != NULL; addr = addr->next)
3194 {
3195 addr->host_used = host;
3196 addr->special_action = '*';
3197 addr->message = US"delivery bypassed by -N option";
3198 }
3199 DEBUG(D_transport)
3200 {
3201 debug_printf("*** delivery by %s transport bypassed by -N option\n"
3202 "*** host and remaining hosts:\n", tblock->name);
3203 for (host2 = host; host2 != NULL; host2 = host2->next)
3204 debug_printf(" %s [%s]\n", host2->name,
3205 (host2->address == NULL)? US"unset" : host2->address);
3206 }
3207 rc = OK;
3208 }
3209
3210 /* This is for real. If the host is expired, we don't count it for
3211 hosts_max_retry. This ensures that all hosts must expire before an address
3212 is timed out, unless hosts_max_try_hardlimit (which protects against
3213 lunatic DNS configurations) is reached.
3214
3215 If the host is not expired and we are about to hit the hosts_max_retry
3216 limit, check to see if there is a subsequent hosts with a different MX
3217 value. If so, make that the next host, and don't count this one. This is a
3218 heuristic to make sure that different MXs do get tried. With a normal kind
3219 of retry rule, they would get tried anyway when the earlier hosts were
3220 delayed, but if the domain has a "retry every time" type of rule - as is
3221 often used for the the very large ISPs, that won't happen. */
3222
3223 else
3224 {
3225 if (!host_is_expired && ++unexpired_hosts_tried >= ob->hosts_max_try)
3226 {
3227 host_item *h;
3228 DEBUG(D_transport)
3229 debug_printf("hosts_max_try limit reached with this host\n");
3230 for (h = host; h != NULL; h = h->next)
3231 if (h->mx != host->mx) break;
3232 if (h != NULL)
3233 {
3234 nexthost = h;
3235 unexpired_hosts_tried--;
3236 DEBUG(D_transport) debug_printf("however, a higher MX host exists "
3237 "and will be tried\n");
3238 }
3239 }
3240
3241 /* Attempt the delivery. */
3242
3243 total_hosts_tried++;
3244 rc = smtp_deliver(addrlist, host, host_af, port, interface, tblock,
3245 expanded_hosts != NULL, &message_defer, FALSE);
3246
3247 /* Yield is one of:
3248 OK => connection made, each address contains its result;
3249 message_defer is set for message-specific defers (when all
3250 recipients are marked defer)
3251 DEFER => there was a non-message-specific delivery problem;
3252 ERROR => there was a problem setting up the arguments for a filter,
3253 or there was a problem with expanding added headers
3254 */
3255
3256 /* If the result is not OK, there was a non-message-specific problem.
3257 If the result is DEFER, we need to write to the logs saying what happened
3258 for this particular host, except in the case of authentication and TLS
3259 failures, where the log has already been written. If all hosts defer a
3260 general message is written at the end. */
3261
3262 if (rc == DEFER && first_addr->basic_errno != ERRNO_AUTHFAIL &&
3263 first_addr->basic_errno != ERRNO_TLSFAILURE)
3264 write_logs(first_addr, host);
3265
3266 #ifdef EXPERIMENTAL_TPDA
3267 if (rc == DEFER)
3268 tpda_deferred(ob, first_addr, host);
3269 #endif
3270
3271 /* If STARTTLS was accepted, but there was a failure in setting up the
3272 TLS session (usually a certificate screwup), and the host is not in
3273 hosts_require_tls, and tls_tempfail_tryclear is true, try again, with
3274 TLS forcibly turned off. We have to start from scratch with a new SMTP
3275 connection. That's why the retry is done from here, not from within
3276 smtp_deliver(). [Rejections of STARTTLS itself don't screw up the
3277 session, so the in-clear transmission after those errors, if permitted,
3278 happens inside smtp_deliver().] */
3279
3280 #ifdef SUPPORT_TLS
3281 if ( rc == DEFER
3282 && first_addr->basic_errno == ERRNO_TLSFAILURE
3283 && ob->tls_tempfail_tryclear
3284 && verify_check_this_host(&(ob->hosts_require_tls), NULL, host->name,
3285 host->address, NULL) != OK
3286 #ifdef EXPERIMENTAL_DANE
3287 && verify_check_this_host(&(ob->hosts_require_dane), NULL, host->name,
3288 host->address, NULL) != OK
3289 #endif
3290 )
3291 {
3292 log_write(0, LOG_MAIN, "TLS session failure: delivering unencrypted "
3293 "to %s [%s] (not in hosts_require_tls)", host->name, host->address);
3294 first_addr = prepare_addresses(addrlist, host);
3295 rc = smtp_deliver(addrlist, host, host_af, port, interface, tblock,
3296 expanded_hosts != NULL, &message_defer, TRUE);
3297 if (rc == DEFER && first_addr->basic_errno != ERRNO_AUTHFAIL)
3298 write_logs(first_addr, host);
3299 #ifdef EXPERIMENTAL_TPDA
3300