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