Use writev(2) when sending delivery status to the parent
[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", 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;
3