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