OpenSSL: Fix memory leak during multi-message connections using STARTTLS
[exim.git] / src / src / verify.c
CommitLineData
059ec3d9
PH
1/*************************************************
2* Exim - an Internet mail transport agent *
3*************************************************/
4
f9ba5e22 5/* Copyright (c) University of Cambridge 1995 - 2018 */
059ec3d9
PH
6/* See the file NOTICE for conditions of use and distribution. */
7
8/* Functions concerned with verifying things. The original code for callout
9caching was contributed by Kevin Fleming (but I hacked it around a bit). */
10
11
12#include "exim.h"
817d9f57 13#include "transports/smtp.h"
059ec3d9 14
e4bdf652
JH
15#define CUTTHROUGH_CMD_TIMEOUT 30 /* timeout for cutthrough-routing calls */
16#define CUTTHROUGH_DATA_TIMEOUT 60 /* timeout for cutthrough-routing calls */
817d9f57
JH
17static smtp_outblock ctblock;
18uschar ctbuffer[8192];
19
059ec3d9
PH
20
21/* Structure for caching DNSBL lookups */
22
23typedef struct dnsbl_cache_block {
14b3c5bc 24 time_t expiry;
059ec3d9
PH
25 dns_address *rhs;
26 uschar *text;
27 int rc;
28 BOOL text_set;
29} dnsbl_cache_block;
30
31
32/* Anchor for DNSBL cache */
33
34static tree_node *dnsbl_cache = NULL;
35
36
431b7361
PH
37/* Bits for match_type in one_check_dnsbl() */
38
39#define MT_NOT 1
40#define MT_ALL 2
41
57cc2785 42static uschar cutthrough_response(int, char, uschar **, int);
431b7361 43
8d330698 44
059ec3d9
PH
45
46/*************************************************
47* Retrieve a callout cache record *
48*************************************************/
49
50/* If a record exists, check whether it has expired.
51
52Arguments:
53 dbm_file an open hints file
54 key the record key
55 type "address" or "domain"
56 positive_expire expire time for positive records
57 negative_expire expire time for negative records
58
59Returns: the cache record if a non-expired one exists, else NULL
60*/
61
62static dbdata_callout_cache *
55414b25 63get_callout_cache_record(open_db *dbm_file, const uschar *key, uschar *type,
059ec3d9
PH
64 int positive_expire, int negative_expire)
65{
66BOOL negative;
67int length, expire;
68time_t now;
69dbdata_callout_cache *cache_record;
70
b6323c75 71if (!(cache_record = dbfn_read_with_length(dbm_file, key, &length)))
059ec3d9 72 {
6f4d5ad3 73 HDEBUG(D_verify) debug_printf("callout cache: no %s record found for %s\n", type, key);
059ec3d9
PH
74 return NULL;
75 }
76
77/* We treat a record as "negative" if its result field is not positive, or if
78it is a domain record and the postmaster field is negative. */
79
80negative = cache_record->result != ccache_accept ||
81 (type[0] == 'd' && cache_record->postmaster_result == ccache_reject);
82expire = negative? negative_expire : positive_expire;
83now = time(NULL);
84
85if (now - cache_record->time_stamp > expire)
86 {
6f4d5ad3 87 HDEBUG(D_verify) debug_printf("callout cache: %s record expired for %s\n", type, key);
059ec3d9
PH
88 return NULL;
89 }
90
91/* If this is a non-reject domain record, check for the obsolete format version
92that doesn't have the postmaster and random timestamps, by looking at the
93length. If so, copy it to a new-style block, replicating the record's
94timestamp. Then check the additional timestamps. (There's no point wasting
95effort if connections are rejected.) */
96
97if (type[0] == 'd' && cache_record->result != ccache_reject)
98 {
99 if (length == sizeof(dbdata_callout_cache_obs))
100 {
101 dbdata_callout_cache *new = store_get(sizeof(dbdata_callout_cache));
102 memcpy(new, cache_record, length);
103 new->postmaster_stamp = new->random_stamp = new->time_stamp;
104 cache_record = new;
105 }
106
107 if (now - cache_record->postmaster_stamp > expire)
108 cache_record->postmaster_result = ccache_unknown;
109
110 if (now - cache_record->random_stamp > expire)
111 cache_record->random_result = ccache_unknown;
112 }
113
6f4d5ad3 114HDEBUG(D_verify) debug_printf("callout cache: found %s record for %s\n", type, key);
059ec3d9
PH
115return cache_record;
116}
117
118
119
707ee5b1
JH
120/* Check the callout cache.
121Options * pm_mailfrom may be modified by cache partial results.
059ec3d9 122
707ee5b1 123Return: TRUE if result found
059ec3d9
PH
124*/
125
707ee5b1
JH
126static BOOL
127cached_callout_lookup(address_item * addr, uschar * address_key,
128 uschar * from_address, int * opt_ptr, uschar ** pm_ptr,
129 int * yield, uschar ** failure_ptr,
130 dbdata_callout_cache * new_domain_record, int * old_domain_res)
059ec3d9 131{
707ee5b1 132int options = *opt_ptr;
059ec3d9
PH
133open_db dbblock;
134open_db *dbm_file = NULL;
059ec3d9
PH
135
136/* Open the callout cache database, it it exists, for reading only at this
137stage, unless caching has been disabled. */
138
8b9476ba 139if (options & vopt_callout_no_cache)
059ec3d9
PH
140 {
141 HDEBUG(D_verify) debug_printf("callout cache: disabled by no_cache\n");
142 }
707ee5b1 143else if (!(dbm_file = dbfn_open(US"callout", O_RDWR, &dbblock, FALSE)))
059ec3d9
PH
144 {
145 HDEBUG(D_verify) debug_printf("callout cache: not available\n");
146 }
707ee5b1 147else
059ec3d9 148 {
707ee5b1
JH
149 /* If a cache database is available see if we can avoid the need to do an
150 actual callout by making use of previously-obtained data. */
151
152 dbdata_callout_cache_address * cache_address_record;
153 dbdata_callout_cache * cache_record = get_callout_cache_record(dbm_file,
154 addr->domain, US"domain",
155 callout_cache_domain_positive_expire, callout_cache_domain_negative_expire);
059ec3d9
PH
156
157 /* If an unexpired cache record was found for this domain, see if the callout
158 process can be short-circuited. */
159
ff5929e3 160 if (cache_record)
059ec3d9 161 {
2b1c6e3a
PH
162 /* In most cases, if an early command (up to and including MAIL FROM:<>)
163 was rejected, there is no point carrying on. The callout fails. However, if
164 we are doing a recipient verification with use_sender or use_postmaster
165 set, a previous failure of MAIL FROM:<> doesn't count, because this time we
166 will be using a non-empty sender. We have to remember this situation so as
167 not to disturb the cached domain value if this whole verification succeeds
168 (we don't want it turning into "accept"). */
169
707ee5b1 170 *old_domain_res = cache_record->result;
2b1c6e3a 171
707ee5b1
JH
172 if ( cache_record->result == ccache_reject
173 || *from_address == 0 && cache_record->result == ccache_reject_mfnull)
059ec3d9
PH
174 {
175 setflag(addr, af_verify_nsfail);
176 HDEBUG(D_verify)
707ee5b1
JH
177 debug_printf("callout cache: domain gave initial rejection, or "
178 "does not accept HELO or MAIL FROM:<>\n");
059ec3d9
PH
179 setflag(addr, af_verify_nsfail);
180 addr->user_message = US"(result of an earlier callout reused).";
707ee5b1 181 *yield = FAIL;
8e669ac1 182 *failure_ptr = US"mail";
707ee5b1
JH
183 dbfn_close(dbm_file);
184 return TRUE;
059ec3d9
PH
185 }
186
187 /* If a previous check on a "random" local part was accepted, we assume
188 that the server does not do any checking on local parts. There is therefore
189 no point in doing the callout, because it will always be successful. If a
190 random check previously failed, arrange not to do it again, but preserve
191 the data in the new record. If a random check is required but hasn't been
192 done, skip the remaining cache processing. */
193
8b9476ba 194 if (options & vopt_callout_random) switch(cache_record->random_result)
059ec3d9
PH
195 {
196 case ccache_accept:
8b9476ba
JH
197 HDEBUG(D_verify)
198 debug_printf("callout cache: domain accepts random addresses\n");
707ee5b1
JH
199 dbfn_close(dbm_file);
200 return TRUE; /* Default yield is OK */
059ec3d9
PH
201
202 case ccache_reject:
8b9476ba
JH
203 HDEBUG(D_verify)
204 debug_printf("callout cache: domain rejects random addresses\n");
707ee5b1
JH
205 *opt_ptr = options & ~vopt_callout_random;
206 new_domain_record->random_result = ccache_reject;
207 new_domain_record->random_stamp = cache_record->random_stamp;
8b9476ba 208 break;
059ec3d9
PH
209
210 default:
8b9476ba
JH
211 HDEBUG(D_verify)
212 debug_printf("callout cache: need to check random address handling "
213 "(not cached or cache expired)\n");
707ee5b1
JH
214 dbfn_close(dbm_file);
215 return FALSE;
059ec3d9
PH
216 }
217
218 /* If a postmaster check is requested, but there was a previous failure,
219 there is again no point in carrying on. If a postmaster check is required,
220 but has not been done before, we are going to have to do a callout, so skip
221 remaining cache processing. */
222
707ee5b1 223 if (*pm_ptr)
059ec3d9
PH
224 {
225 if (cache_record->postmaster_result == ccache_reject)
707ee5b1
JH
226 {
227 setflag(addr, af_verify_pmfail);
228 HDEBUG(D_verify)
229 debug_printf("callout cache: domain does not accept "
230 "RCPT TO:<postmaster@domain>\n");
231 *yield = FAIL;
232 *failure_ptr = US"postmaster";
233 setflag(addr, af_verify_pmfail);
234 addr->user_message = US"(result of earlier verification reused).";
235 dbfn_close(dbm_file);
236 return TRUE;
237 }
059ec3d9 238 if (cache_record->postmaster_result == ccache_unknown)
707ee5b1
JH
239 {
240 HDEBUG(D_verify)
241 debug_printf("callout cache: need to check RCPT "
242 "TO:<postmaster@domain> (not cached or cache expired)\n");
243 dbfn_close(dbm_file);
244 return FALSE;
245 }
059ec3d9
PH
246
247 /* If cache says OK, set pm_mailfrom NULL to prevent a redundant
248 postmaster check if the address itself has to be checked. Also ensure
249 that the value in the cache record is preserved (with its old timestamp).
250 */
251
252 HDEBUG(D_verify) debug_printf("callout cache: domain accepts RCPT "
707ee5b1
JH
253 "TO:<postmaster@domain>\n");
254 *pm_ptr = NULL;
255 new_domain_record->postmaster_result = ccache_accept;
256 new_domain_record->postmaster_stamp = cache_record->postmaster_stamp;
059ec3d9
PH
257 }
258 }
259
260 /* We can't give a result based on information about the domain. See if there
261 is an unexpired cache record for this specific address (combined with the
262 sender address if we are doing a recipient callout with a non-empty sender).
263 */
264
707ee5b1
JH
265 if (!(cache_address_record = (dbdata_callout_cache_address *)
266 get_callout_cache_record(dbm_file, address_key, US"address",
267 callout_cache_positive_expire, callout_cache_negative_expire)))
268 {
269 dbfn_close(dbm_file);
270 return FALSE;
271 }
059ec3d9 272
707ee5b1 273 if (cache_address_record->result == ccache_accept)
059ec3d9 274 {
707ee5b1
JH
275 HDEBUG(D_verify)
276 debug_printf("callout cache: address record is positive\n");
277 }
278 else
279 {
280 HDEBUG(D_verify)
281 debug_printf("callout cache: address record is negative\n");
282 addr->user_message = US"Previous (cached) callout verification failure";
283 *failure_ptr = US"recipient";
284 *yield = FAIL;
059ec3d9
PH
285 }
286
287 /* Close the cache database while we actually do the callout for real. */
288
059ec3d9 289 dbfn_close(dbm_file);
707ee5b1
JH
290 return TRUE;
291 }
292return FALSE;
293}
294
295
296/* Write results to callout cache
297*/
298static void
299cache_callout_write(dbdata_callout_cache * dom_rec, const uschar * domain,
300 int done, dbdata_callout_cache_address * addr_rec, uschar * address_key)
301{
302open_db dbblock;
303open_db *dbm_file = NULL;
304
305/* If we get here with done == TRUE, a successful callout happened, and yield
306will be set OK or FAIL according to the response to the RCPT command.
307Otherwise, we looped through the hosts but couldn't complete the business.
308However, there may be domain-specific information to cache in both cases.
309
310The value of the result field in the new_domain record is ccache_unknown if
311there was an error before or with MAIL FROM:, and errno was not zero,
312implying some kind of I/O error. We don't want to write the cache in that case.
313Otherwise the value is ccache_accept, ccache_reject, or ccache_reject_mfnull. */
314
315if (dom_rec->result != ccache_unknown)
316 if (!(dbm_file = dbfn_open(US"callout", O_RDWR|O_CREAT, &dbblock, FALSE)))
317 {
318 HDEBUG(D_verify) debug_printf("callout cache: not available\n");
319 }
320 else
321 {
322 (void)dbfn_write(dbm_file, domain, dom_rec,
323 (int)sizeof(dbdata_callout_cache));
324 HDEBUG(D_verify) debug_printf("wrote callout cache domain record for %s:\n"
325 " result=%d postmaster=%d random=%d\n",
326 domain,
327 dom_rec->result,
328 dom_rec->postmaster_result,
329 dom_rec->random_result);
330 }
331
332/* If a definite result was obtained for the callout, cache it unless caching
333is disabled. */
334
335if (done && addr_rec->result != ccache_unknown)
336 {
337 if (!dbm_file)
338 dbm_file = dbfn_open(US"callout", O_RDWR|O_CREAT, &dbblock, FALSE);
339 if (!dbm_file)
340 {
341 HDEBUG(D_verify) debug_printf("no callout cache available\n");
342 }
343 else
344 {
345 (void)dbfn_write(dbm_file, address_key, addr_rec,
346 (int)sizeof(dbdata_callout_cache_address));
347 HDEBUG(D_verify) debug_printf("wrote %s callout cache address record for %s\n",
348 addr_rec->result == ccache_accept ? "positive" : "negative",
349 address_key);
350 }
351 }
352
353if (dbm_file) dbfn_close(dbm_file);
354}
355
356
c4c940fd
JH
357/* Cutthrough-multi. If the existing cached cutthrough connection matches
358the one we would make for a subsequent recipient, use it. Send the RCPT TO
359and check the result, nonpipelined as it may be wanted immediately for
360recipient-verification.
361
362It seems simpler to deal with this case separately from the main callout loop.
363We will need to remember it has sent, or not, so that rcpt-acl tail code
364can do it there for the non-rcpt-verify case. For this we keep an addresscount.
365
366Return: TRUE for a definitive result for the recipient
367*/
368static int
369cutthrough_multi(address_item * addr, host_item * host_list,
370 transport_feedback * tf, int * yield)
371{
372BOOL done = FALSE;
373host_item * host;
374
375if (addr->transport == cutthrough.addr.transport)
376 for (host = host_list; host; host = host->next)
377 if (Ustrcmp(host->address, cutthrough.host.address) == 0)
378 {
379 int host_af;
380 uschar *interface = NULL; /* Outgoing interface to use; NULL => any */
381 int port = 25;
382
383 deliver_host = host->name;
384 deliver_host_address = host->address;
385 deliver_host_port = host->port;
386 deliver_domain = addr->domain;
387 transport_name = addr->transport->name;
388
57cc2785 389 host_af = Ustrchr(host->address, ':') ? AF_INET6 : AF_INET;
c4c940fd 390
f83a760f
JH
391 if ( !smtp_get_interface(tf->interface, host_af, addr, &interface,
392 US"callout")
393 || !smtp_get_port(tf->port, addr, &port, US"callout")
394 )
c4c940fd
JH
395 log_write(0, LOG_MAIN|LOG_PANIC, "<%s>: %s", addr->address,
396 addr->message);
397
f83a760f
JH
398 smtp_port_for_connect(host, port);
399
c4c940fd
JH
400 if ( ( interface == cutthrough.interface
401 || ( interface
402 && cutthrough.interface
403 && Ustrcmp(interface, cutthrough.interface) == 0
404 ) )
f83a760f 405 && host->port == cutthrough.host.port
c4c940fd
JH
406 )
407 {
408 uschar * resp = NULL;
409
410 /* Match! Send the RCPT TO, set done from the response */
411 done =
4e910c01 412 smtp_write_command(&ctblock, SCMD_FLUSH, "RCPT TO:<%.1000s>\r\n",
c4c940fd
JH
413 transport_rcpt_address(addr,
414 addr->transport->rcpt_include_affixes)) >= 0 &&
57cc2785 415 cutthrough_response(cutthrough.fd, '2', &resp, CUTTHROUGH_DATA_TIMEOUT) == '2';
c4c940fd
JH
416
417 /* This would go horribly wrong if a callout fail was ignored by ACL.
418 We punt by abandoning cutthrough on a reject, like the
419 first-rcpt does. */
420
421 if (done)
422 {
423 address_item * na = store_get(sizeof(address_item));
424 *na = cutthrough.addr;
425 cutthrough.addr = *addr;
426 cutthrough.addr.host_used = &cutthrough.host;
427 cutthrough.addr.next = na;
428
429 cutthrough.nrcpt++;
430 }
431 else
432 {
57cc2785 433 cancel_cutthrough_connection(TRUE, US"recipient rejected");
c4c940fd
JH
434 if (!resp || errno == ETIMEDOUT)
435 {
436 HDEBUG(D_verify) debug_printf("SMTP timeout\n");
437 }
438 else if (errno == 0)
439 {
440 if (*resp == 0)
441 Ustrcpy(resp, US"connection dropped");
442
443 addr->message =
e9166683
JH
444 string_sprintf("response to \"%s\" was: %s",
445 big_buffer, string_printing(resp));
c4c940fd
JH
446
447 addr->user_message =
448 string_sprintf("Callout verification failed:\n%s", resp);
449
450 /* Hard rejection ends the process */
451
452 if (resp[0] == '5') /* Address rejected */
453 {
454 *yield = FAIL;
455 done = TRUE;
456 }
457 }
458 }
459 }
460 break; /* host_list */
461 }
462if (!done)
57cc2785 463 cancel_cutthrough_connection(TRUE, US"incompatible connection");
c4c940fd
JH
464return done;
465}
466
467
707ee5b1
JH
468/*************************************************
469* Do callout verification for an address *
470*************************************************/
471
472/* This function is called from verify_address() when the address has routed to
473a host list, and a callout has been requested. Callouts are expensive; that is
474why a cache is used to improve the efficiency.
475
476Arguments:
477 addr the address that's been routed
478 host_list the list of hosts to try
479 tf the transport feedback block
480
481 ifstring "interface" option from transport, or NULL
482 portstring "port" option from transport, or NULL
483 protocolstring "protocol" option from transport, or NULL
484 callout the per-command callout timeout
485 callout_overall the overall callout timeout (if < 0 use 4*callout)
486 callout_connect the callout connection timeout (if < 0 use callout)
487 options the verification options - these bits are used:
488 vopt_is_recipient => this is a recipient address
489 vopt_callout_no_cache => don't use callout cache
490 vopt_callout_fullpm => if postmaster check, do full one
491 vopt_callout_random => do the "random" thing
492 vopt_callout_recipsender => use real sender for recipient
493 vopt_callout_recippmaster => use postmaster for recipient
57cc2785 494 vopt_callout_hold => lazy close connection
707ee5b1
JH
495 se_mailfrom MAIL FROM address for sender verify; NULL => ""
496 pm_mailfrom if non-NULL, do the postmaster check with this sender
497
498Returns: OK/FAIL/DEFER
499*/
500
501static int
502do_callout(address_item *addr, host_item *host_list, transport_feedback *tf,
503 int callout, int callout_overall, int callout_connect, int options,
504 uschar *se_mailfrom, uschar *pm_mailfrom)
505{
506int yield = OK;
507int old_domain_cache_result = ccache_accept;
508BOOL done = FALSE;
509uschar *address_key;
510uschar *from_address;
511uschar *random_local_part = NULL;
512const uschar *save_deliver_domain = deliver_domain;
513uschar **failure_ptr = options & vopt_is_recipient
514 ? &recipient_verify_failure : &sender_verify_failure;
515dbdata_callout_cache new_domain_record;
516dbdata_callout_cache_address new_address_record;
707ee5b1
JH
517time_t callout_start_time;
518
519new_domain_record.result = ccache_unknown;
520new_domain_record.postmaster_result = ccache_unknown;
521new_domain_record.random_result = ccache_unknown;
522
523memset(&new_address_record, 0, sizeof(new_address_record));
524
525/* For a recipient callout, the key used for the address cache record must
526include the sender address if we are using the real sender in the callout,
527because that may influence the result of the callout. */
528
529if (options & vopt_is_recipient)
530 if (options & vopt_callout_recipsender)
531 {
532 from_address = sender_address;
533 address_key = string_sprintf("%s/<%s>", addr->address, sender_address);
534 if (cutthrough.delivery) options |= vopt_callout_no_cache;
535 }
536 else if (options & vopt_callout_recippmaster)
537 {
538 from_address = string_sprintf("postmaster@%s", qualify_domain_sender);
539 address_key = string_sprintf("%s/<postmaster@%s>", addr->address,
540 qualify_domain_sender);
541 }
542 else
543 {
544 from_address = US"";
545 address_key = addr->address;
546 }
547
548/* For a sender callout, we must adjust the key if the mailfrom address is not
549empty. */
550
551else
552 {
553 from_address = se_mailfrom ? se_mailfrom : US"";
554 address_key = *from_address
555 ? string_sprintf("%s/<%s>", addr->address, from_address) : addr->address;
059ec3d9
PH
556 }
557
707ee5b1
JH
558if (cached_callout_lookup(addr, address_key, from_address,
559 &options, &pm_mailfrom, &yield, failure_ptr,
560 &new_domain_record, &old_domain_cache_result))
57cc2785
JH
561 {
562 cancel_cutthrough_connection(TRUE, US"cache-hit");
707ee5b1 563 goto END_CALLOUT;
57cc2785 564 }
707ee5b1 565
193e3acd 566if (!addr->transport)
059ec3d9 567 {
193e3acd 568 HDEBUG(D_verify) debug_printf("cannot callout via null transport\n");
059ec3d9 569 }
6681531a
HSHR
570else if (Ustrcmp(addr->transport->driver_name, "smtp") != 0)
571 log_write(0, LOG_MAIN|LOG_PANIC|LOG_CONFIG_FOR, "callout transport '%s': %s is non-smtp",
572 addr->transport->name, addr->transport->driver_name);
193e3acd
JH
573else
574 {
575 smtp_transport_options_block *ob =
9d9c3746 576 (smtp_transport_options_block *)addr->transport->options_block;
c4c940fd 577 host_item * host;
059ec3d9 578
193e3acd
JH
579 /* The information wasn't available in the cache, so we have to do a real
580 callout and save the result in the cache for next time, unless no_cache is set,
581 or unless we have a previously cached negative random result. If we are to test
582 with a random local part, ensure that such a local part is available. If not,
4c04137d 583 log the fact, but carry on without randomising. */
059ec3d9 584
707ee5b1 585 if (options & vopt_callout_random && callout_random_local_part)
65f1c92a 586 if (!(random_local_part = expand_string(callout_random_local_part)))
193e3acd
JH
587 log_write(0, LOG_MAIN|LOG_PANIC, "failed to expand "
588 "callout_random_local_part: %s", expand_string_message);
059ec3d9 589
193e3acd
JH
590 /* Default the connect and overall callout timeouts if not set, and record the
591 time we are starting so that we can enforce it. */
4c590bd1 592
193e3acd
JH
593 if (callout_overall < 0) callout_overall = 4 * callout;
594 if (callout_connect < 0) callout_connect = callout;
595 callout_start_time = time(NULL);
4c590bd1 596
193e3acd
JH
597 /* Before doing a real callout, if this is an SMTP connection, flush the SMTP
598 output because a callout might take some time. When PIPELINING is active and
599 there are many recipients, the total time for doing lots of callouts can add up
600 and cause the client to time out. So in this case we forgo the PIPELINING
601 optimization. */
817d9f57 602
ff5929e3 603 if (smtp_out && !disable_callout_flush) mac_smtp_fflush();
059ec3d9 604
c4c940fd
JH
605 clearflag(addr, af_verify_pmfail); /* postmaster callout flag */
606 clearflag(addr, af_verify_nsfail); /* null sender callout flag */
607
5032d1cf
JH
608/* cutthrough-multi: if a nonfirst rcpt has the same routing as the first,
609and we are holding a cutthrough conn open, we can just append the rcpt to
610that conn for verification purposes (and later delivery also). Simplest
c4c940fd 611coding means skipping this whole loop and doing the append separately. */
5032d1cf
JH
612
613 /* Can we re-use an open cutthrough connection? */
614 if ( cutthrough.fd >= 0
615 && (options & (vopt_callout_recipsender | vopt_callout_recippmaster))
616 == vopt_callout_recipsender
617 && !random_local_part
618 && !pm_mailfrom
619 )
c4c940fd 620 done = cutthrough_multi(addr, host_list, tf, &yield);
5032d1cf 621
c4c940fd
JH
622 /* If we did not use a cached connection, make connections to the hosts
623 and do real callouts. The list of hosts is passed in as an argument. */
059ec3d9 624
ff5929e3 625 for (host = host_list; host && !done; host = host->next)
059ec3d9 626 {
193e3acd
JH
627 int host_af;
628 int port = 25;
193e3acd 629 uschar *interface = NULL; /* Outgoing interface to use; NULL => any */
02b41d71 630 smtp_context sx;
193e3acd 631
ff5929e3 632 if (!host->address)
193e3acd
JH
633 {
634 DEBUG(D_verify) debug_printf("no IP address for host name %s: skipping\n",
635 host->name);
636 continue;
637 }
059ec3d9 638
193e3acd 639 /* Check the overall callout timeout */
059ec3d9 640
193e3acd
JH
641 if (time(NULL) - callout_start_time >= callout_overall)
642 {
643 HDEBUG(D_verify) debug_printf("overall timeout for callout exceeded\n");
644 break;
645 }
059ec3d9 646
193e3acd 647 /* Set IPv4 or IPv6 */
059ec3d9 648
e9166683 649 host_af = Ustrchr(host->address, ':') ? AF_INET6 : AF_INET;
de3a88fb 650
193e3acd
JH
651 /* Expand and interpret the interface and port strings. The latter will not
652 be used if there is a host-specific port (e.g. from a manualroute router).
653 This has to be delayed till now, because they may expand differently for
654 different hosts. If there's a failure, log it, but carry on with the
655 defaults. */
de3a88fb 656
193e3acd
JH
657 deliver_host = host->name;
658 deliver_host_address = host->address;
a7538db1 659 deliver_host_port = host->port;
193e3acd 660 deliver_domain = addr->domain;
aec45841 661 transport_name = addr->transport->name;
059ec3d9 662
6f6dedcc 663 if ( !smtp_get_interface(tf->interface, host_af, addr, &interface,
bf7aabb4
JH
664 US"callout")
665 || !smtp_get_port(tf->port, addr, &port, US"callout")
666 )
193e3acd
JH
667 log_write(0, LOG_MAIN|LOG_PANIC, "<%s>: %s", addr->address,
668 addr->message);
059ec3d9 669
02b41d71
JH
670 sx.addrlist = addr;
671 sx.host = host;
672 sx.host_af = host_af,
673 sx.port = port;
674 sx.interface = interface;
675 sx.helo_data = tf->helo_data;
676 sx.tblock = addr->transport;
e9166683 677 sx.verify = TRUE;
02b41d71
JH
678
679tls_retry_connection:
680 /* Set the address state so that errors are recorded in it */
681
682 addr->transport_return = PENDING_DEFER;
683 ob->connect_timeout = callout_connect;
684 ob->command_timeout = callout;
685
686 /* Get the channel set up ready for a message (MAIL FROM being the next
687 SMTP command to send. If we tried TLS but it failed, try again without
688 if permitted */
689
f10e3ea3
JH
690 yield = smtp_setup_conn(&sx, FALSE);
691#ifdef SUPPORT_TLS
692 if ( yield == DEFER
02b41d71
JH
693 && addr->basic_errno == ERRNO_TLSFAILURE
694 && ob->tls_tempfail_tryclear
695 && verify_check_given_host(&ob->hosts_require_tls, host) != OK
696 )
193e3acd 697 {
cf0c6164
JH
698 log_write(0, LOG_MAIN,
699 "%s: callout unencrypted to %s [%s] (not in hosts_require_tls)",
700 addr->message, host->name, host->address);
e9166683
JH
701 addr->transport_return = PENDING_DEFER;
702 yield = smtp_setup_conn(&sx, TRUE);
02b41d71 703 }
f10e3ea3 704#endif
02b41d71
JH
705 if (yield != OK)
706 {
02b41d71 707 errno = addr->basic_errno;
aec45841 708 transport_name = NULL;
193e3acd
JH
709 deliver_host = deliver_host_address = NULL;
710 deliver_domain = save_deliver_domain;
bf7aabb4 711
02b41d71
JH
712 /* Failure to accept HELO is cached; this blocks the whole domain for all
713 senders. I/O errors and defer responses are not cached. */
770747fd 714
02b41d71 715 if (yield == FAIL && (errno == 0 || errno == ERRNO_SMTPCLOSED))
a7538db1 716 {
02b41d71
JH
717 setflag(addr, af_verify_nsfail);
718 new_domain_record.result = ccache_reject;
719 done = TRUE;
a7538db1 720 }
193e3acd 721 else
02b41d71
JH
722 done = FALSE;
723 goto no_conn;
3c8b3577 724 }
9bfc60eb 725
02b41d71
JH
726 /* If we needed to authenticate, smtp_setup_conn() did that. Copy
727 the AUTH info for logging */
fcc8e047 728
02b41d71
JH
729 addr->authenticator = client_authenticator;
730 addr->auth_id = client_authenticated_id;
b4a2b536 731
e9166683
JH
732 sx.from_addr = from_address;
733 sx.first_addr = sx.sync_addr = addr;
734 sx.ok = FALSE; /*XXX these 3 last might not be needed for verify? */
735 sx.send_rset = TRUE;
736 sx.completed_addr = FALSE;
b4a2b536 737
cf0c6164 738 new_domain_record.result = old_domain_cache_result == ccache_reject_mfnull
e9166683 739 ? ccache_reject_mfnull : ccache_accept;
c4c940fd 740
e9166683
JH
741 /* Do the random local part check first. Temporarily replace the recipient
742 with the "random" value */
02b41d71 743
e9166683 744 if (random_local_part)
059ec3d9 745 {
e9166683 746 uschar * main_address = addr->address;
921dfc11
JH
747 const uschar * rcpt_domain = addr->domain;
748
8c5d388a 749#ifdef SUPPORT_I18N
921dfc11
JH
750 uschar * errstr = NULL;
751 if ( testflag(addr, af_utf8_downcvt)
752 && (rcpt_domain = string_domain_utf8_to_alabel(rcpt_domain,
753 &errstr), errstr)
754 )
755 {
756 addr->message = errstr;
757 errno = ERRNO_EXPANDFAIL;
758 setflag(addr, af_verify_nsfail);
759 done = FALSE;
760 rcpt_domain = US""; /*XXX errorhandling! */
761 }
762#endif
763
57cc2785
JH
764 /* This would be ok for 1st rcpt of a cutthrough (the case handled here;
765 subsequents are done in cutthrough_multi()), but no way to
766 handle a subsequent because of the RSET vaporising the MAIL FROM.
767 So refuse to support any. Most cutthrough use will not involve
768 random_local_part, so no loss. */
769 cancel_cutthrough_connection(TRUE, US"random-recipient");
059ec3d9 770
e9166683
JH
771 addr->address = string_sprintf("%s@%.1000s",
772 random_local_part, rcpt_domain);
773 done = FALSE;
902fbd69
JH
774
775 /* If accepted, we aren't going to do any further tests below.
776 Otherwise, cache a real negative response, and get back to the right
777 state to send RCPT. Unless there's some problem such as a dropped
778 connection, we expect to succeed, because the commands succeeded above.
779 However, some servers drop the connection after responding to an
780 invalid recipient, so on (any) error we drop and remake the connection.
781 XXX We don't care about that for postmaster_full. Should we?
782
783 XXX could we add another flag to the context, and have the common
784 code emit the RSET too? Even pipelined after the RCPT...
785 Then the main-verify call could use it if there's to be a subsequent
786 postmaster-verify.
787 The sync_responses() would need to be taught about it and we'd
788 need another return code filtering out to here.
14de8063
JH
789
790 Avoid using a SIZE option on the MAIL for all randon-rcpt checks.
902fbd69
JH
791 */
792
14de8063
JH
793 sx.avoid_option = OPTION_SIZE;
794
a65c4156
JH
795 /* Remember when we last did a random test */
796 new_domain_record.random_stamp = time(NULL);
797
e9166683
JH
798 if (smtp_write_mail_and_rcpt_cmds(&sx, &yield) == 0)
799 switch(addr->transport_return)
800 {
b6323c75 801 case PENDING_OK: /* random was accepted, unfortunately */
e9166683 802 new_domain_record.random_result = ccache_accept;
b6323c75 803 yield = OK; /* Only usable verify result we can return */
fae8970d
JH
804 done = TRUE;
805 goto no_conn;
b6323c75 806 case FAIL: /* rejected: the preferred result */
e9166683 807 new_domain_record.random_result = ccache_reject;
14de8063 808 sx.avoid_option = 0;
193e3acd 809
e9166683 810 /* Between each check, issue RSET, because some servers accept only
902fbd69
JH
811 one recipient after MAIL FROM:<>.
812 XXX We don't care about that for postmaster_full. Should we? */
193e3acd 813
e9166683 814 if ((done =
4e910c01 815 smtp_write_command(&sx.outblock, SCMD_FLUSH, "RSET\r\n") >= 0 &&
e9166683
JH
816 smtp_read_response(&sx.inblock, sx.buffer, sizeof(sx.buffer),
817 '2', callout)))
818 break;
65f1c92a 819
65f1c92a 820 HDEBUG(D_acl|D_v)
e1d04f48 821 debug_printf_indent("problem after random/rset/mfrom; reopen conn\n");
65f1c92a
JH
822 random_local_part = NULL;
823#ifdef SUPPORT_TLS
dec766a1 824 tls_close(FALSE, TLS_SHUTDOWN_NOWAIT);
65f1c92a 825#endif
e1d04f48 826 HDEBUG(D_transport|D_acl|D_v) debug_printf_indent(" SMTP(close)>>\n");
02b41d71 827 (void)close(sx.inblock.sock);
e9166683 828 sx.inblock.sock = sx.outblock.sock = -1;
0cbf2b82 829#ifndef DISABLE_EVENT
65f1c92a
JH
830 (void) event_raise(addr->transport->event_action,
831 US"tcp:close", NULL);
832#endif
a65c4156
JH
833 addr->address = main_address;
834 addr->transport_return = PENDING_DEFER;
835 sx.first_addr = sx.sync_addr = addr;
836 sx.ok = FALSE;
837 sx.send_rset = TRUE;
838 sx.completed_addr = FALSE;
65f1c92a 839 goto tls_retry_connection;
b6323c75
JH
840 case DEFER: /* 4xx response to random */
841 break; /* Just to be clear. ccache_unknown, !done. */
e9166683 842 }
059ec3d9 843
e9166683
JH
844 /* Re-setup for main verify, or for the error message when failing */
845 addr->address = main_address;
846 addr->transport_return = PENDING_DEFER;
847 sx.first_addr = sx.sync_addr = addr;
848 sx.ok = FALSE;
849 sx.send_rset = TRUE;
850 sx.completed_addr = FALSE;
851 }
852 else
853 done = TRUE;
921dfc11 854
14de8063
JH
855 /* Main verify. For rcpt-verify use SIZE if we know it and we're not cacheing;
856 for sndr-verify never use it. */
e9166683
JH
857
858 if (done)
859 {
14de8063
JH
860 if (!(options & vopt_is_recipient && options & vopt_callout_no_cache))
861 sx.avoid_option = OPTION_SIZE;
862
e9166683
JH
863 done = FALSE;
864 switch(smtp_write_mail_and_rcpt_cmds(&sx, &yield))
865 {
866 case 0: switch(addr->transport_return) /* ok so far */
867 {
868 case PENDING_OK: done = TRUE;
869 new_address_record.result = ccache_accept;
870 break;
14de8063 871 case FAIL: done = TRUE;
e9166683
JH
872 yield = FAIL;
873 *failure_ptr = US"recipient";
874 new_address_record.result = ccache_reject;
875 break;
14de8063 876 default: break;
e9166683
JH
877 }
878 break;
879
880 case -1: /* MAIL response error */
881 *failure_ptr = US"mail";
882 if (errno == 0 && sx.buffer[0] == '5')
883 {
884 setflag(addr, af_verify_nsfail);
885 if (from_address[0] == 0)
886 new_domain_record.result = ccache_reject_mfnull;
887 }
888 break;
889 /* non-MAIL read i/o error */
890 /* non-MAIL response timeout */
891 /* internal error; channel still usable */
892 default: break; /* transmit failed */
893 }
894 }
895
896 addr->auth_sndr = client_authenticated_sender;
897
898 deliver_host = deliver_host_address = NULL;
899 deliver_domain = save_deliver_domain;
900
901 /* Do postmaster check if requested; if a full check is required, we
902 check for RCPT TO:<postmaster> (no domain) in accordance with RFC 821. */
903
904 if (done && pm_mailfrom)
905 {
906 /* Could possibly shift before main verify, just above, and be ok
907 for cutthrough. But no way to handle a subsequent rcpt, so just
908 refuse any */
57cc2785 909 cancel_cutthrough_connection(TRUE, US"postmaster verify");
e1d04f48 910 HDEBUG(D_acl|D_v) debug_printf_indent("Cutthrough cancelled by presence of postmaster verify\n");
e9166683 911
4e910c01 912 done = smtp_write_command(&sx.outblock, SCMD_FLUSH, "RSET\r\n") >= 0
e9166683
JH
913 && smtp_read_response(&sx.inblock, sx.buffer,
914 sizeof(sx.buffer), '2', callout);
915
916 if (done)
917 {
918 uschar * main_address = addr->address;
919
920 /*XXX oops, affixes */
921 addr->address = string_sprintf("postmaster@%.1000s", addr->domain);
922 addr->transport_return = PENDING_DEFER;
923
924 sx.from_addr = pm_mailfrom;
925 sx.first_addr = sx.sync_addr = addr;
926 sx.ok = FALSE;
927 sx.send_rset = TRUE;
928 sx.completed_addr = FALSE;
14de8063 929 sx.avoid_option = OPTION_SIZE;
e9166683
JH
930
931 if( smtp_write_mail_and_rcpt_cmds(&sx, &yield) == 0
932 && addr->transport_return == PENDING_OK
933 )
934 done = TRUE;
921dfc11 935 else
e9166683 936 done = (options & vopt_callout_fullpm) != 0
4e910c01 937 && smtp_write_command(&sx.outblock, SCMD_FLUSH,
e9166683
JH
938 "RCPT TO:<postmaster>\r\n") >= 0
939 && smtp_read_response(&sx.inblock, sx.buffer,
940 sizeof(sx.buffer), '2', callout);
921dfc11 941
e9166683 942 /* Sort out the cache record */
2a4be8f9 943
e9166683
JH
944 new_domain_record.postmaster_stamp = time(NULL);
945
946 if (done)
947 new_domain_record.postmaster_result = ccache_accept;
948 else if (errno == 0 && sx.buffer[0] == '5')
949 {
950 *failure_ptr = US"postmaster";
951 setflag(addr, af_verify_pmfail);
952 new_domain_record.postmaster_result = ccache_reject;
953 }
954
955 addr->address = main_address;
956 }
957 }
193e3acd
JH
958 /* For any failure of the main check, other than a negative response, we just
959 close the connection and carry on. We can identify a negative response by the
960 fact that errno is zero. For I/O errors it will be non-zero
2a4be8f9 961
193e3acd
JH
962 Set up different error texts for logging and for sending back to the caller
963 as an SMTP response. Log in all cases, using a one-line format. For sender
964 callouts, give a full response to the caller, but for recipient callouts,
965 don't give the IP address because this may be an internal host whose identity
966 is not to be widely broadcast. */
2a4be8f9 967
02b41d71 968no_conn:
e9166683 969 switch(errno)
193e3acd 970 {
02b41d71
JH
971 case ETIMEDOUT:
972 HDEBUG(D_verify) debug_printf("SMTP timeout\n");
973 sx.send_quit = FALSE;
974 break;
975
8c5d388a 976#ifdef SUPPORT_I18N
02b41d71 977 case ERRNO_UTF8_FWD:
9bfc60eb
JH
978 {
979 extern int acl_where; /* src/acl.c */
980 errno = 0;
981 addr->message = string_sprintf(
e9166683 982 "response to \"EHLO\" did not include SMTPUTF8");
02b41d71
JH
983 addr->user_message = acl_where == ACL_WHERE_RCPT
984 ? US"533 no support for internationalised mailbox name"
9bfc60eb
JH
985 : US"550 mailbox unavailable";
986 yield = FAIL;
987 done = TRUE;
988 }
02b41d71 989 break;
9bfc60eb 990#endif
02b41d71
JH
991 case ECONNREFUSED:
992 sx.send_quit = FALSE;
993 break;
2a4be8f9 994
02b41d71 995 case 0:
e9166683 996 if (*sx.buffer == 0) Ustrcpy(sx.buffer, US"connection dropped");
059ec3d9 997
e9166683 998 /*XXX test here is ugly; seem to have a split of responsibility for
b6323c75 999 building this message. Need to rationalise. Where is it done
e9166683
JH
1000 before here, and when not?
1001 Not == 5xx resp to MAIL on main-verify
1002 */
1003 if (!addr->message) addr->message =
1004 string_sprintf("response to \"%s\" was: %s",
1005 big_buffer, string_printing(sx.buffer));
02b41d71
JH
1006
1007 addr->user_message = options & vopt_is_recipient
e9166683 1008 ? string_sprintf("Callout verification failed:\n%s", sx.buffer)
02b41d71 1009 : string_sprintf("Called: %s\nSent: %s\nResponse: %s",
e9166683 1010 host->address, big_buffer, sx.buffer);
059ec3d9 1011
02b41d71 1012 /* Hard rejection ends the process */
193e3acd 1013
e9166683 1014 if (sx.buffer[0] == '5') /* Address rejected */
02b41d71
JH
1015 {
1016 yield = FAIL;
1017 done = TRUE;
1018 }
1019 break;
193e3acd 1020 }
059ec3d9 1021
193e3acd
JH
1022 /* End the SMTP conversation and close the connection. */
1023
4c04137d 1024 /* Cutthrough - on a successful connect and recipient-verify with
5032d1cf 1025 use-sender and we are 1st rcpt and have no cutthrough conn so far
57cc2785
JH
1026 here is where we want to leave the conn open. Ditto for a lazy-close
1027 verify. */
1028
1029 if ( (cutthrough.delivery || options & vopt_callout_hold)
5032d1cf 1030 && rcpt_count == 1
193e3acd
JH
1031 && done
1032 && yield == OK
98c82a3d
JH
1033 && (options & (vopt_callout_recipsender|vopt_callout_recippmaster|vopt_success_on_redirect))
1034 == vopt_callout_recipsender
193e3acd
JH
1035 && !random_local_part
1036 && !pm_mailfrom
5032d1cf 1037 && cutthrough.fd < 0
02b41d71 1038 && !sx.lmtp
193e3acd 1039 )
059ec3d9 1040 {
57cc2785
JH
1041 HDEBUG(D_acl|D_v) debug_printf_indent("holding verify callout open for %s\n",
1042 cutthrough.delivery
1043 ? "cutthrough delivery" : "potential further verifies and delivery");
1044
1045 cutthrough.callout_hold_only = !cutthrough.delivery;
1046 cutthrough.is_tls = tls_out.active >= 0;
1047 cutthrough.fd = sx.outblock.sock; /* We assume no buffer in use in the outblock */
1048 cutthrough.nrcpt = 1;
1049 cutthrough.transport = addr->transport->name;
1050 cutthrough.interface = interface;
1051 cutthrough.snd_port = sending_port;
1052 cutthrough.peer_options = smtp_peer_options;
1053 cutthrough.host = *host;
1054 {
1055 int oldpool = store_pool;
1056 store_pool = POOL_PERM;
1057 cutthrough.snd_ip = string_copy(sending_ip_address);
1058 cutthrough.host.name = string_copy(host->name);
1059 cutthrough.host.address = string_copy(host->address);
1060 store_pool = oldpool;
1061 }
1062 cutthrough.addr = *addr; /* Save the address_item for later logging */
1063 cutthrough.addr.next = NULL;
5032d1cf 1064 cutthrough.addr.host_used = &cutthrough.host;
193e3acd 1065 if (addr->parent)
5032d1cf
JH
1066 *(cutthrough.addr.parent = store_get(sizeof(address_item))) =
1067 *addr->parent;
193e3acd
JH
1068 ctblock.buffer = ctbuffer;
1069 ctblock.buffersize = sizeof(ctbuffer);
1070 ctblock.ptr = ctbuffer;
1071 /* ctblock.cmd_count = 0; ctblock.authenticating = FALSE; */
5032d1cf 1072 ctblock.sock = cutthrough.fd;
059ec3d9 1073 }
193e3acd 1074 else
059ec3d9 1075 {
57cc2785 1076 /* Ensure no cutthrough on multiple verifies that were incompatible */
193e3acd 1077 if (options & vopt_callout_recipsender)
57cc2785 1078 cancel_cutthrough_connection(TRUE, US"not usable for cutthrough");
02b41d71 1079 if (sx.send_quit)
2760b518 1080 {
4e910c01 1081 (void) smtp_write_command(&sx.outblock, SCMD_FLUSH, "QUIT\r\n");
059ec3d9 1082
2760b518 1083 /* Wait a short time for response, and discard it */
e9166683 1084 smtp_read_response(&sx.inblock, sx.buffer, sizeof(sx.buffer),
2760b518
JH
1085 '2', 1);
1086 }
1087
02b41d71
JH
1088 if (sx.inblock.sock >= 0)
1089 {
a7538db1 1090#ifdef SUPPORT_TLS
dec766a1 1091 tls_close(FALSE, TLS_SHUTDOWN_NOWAIT);
a7538db1 1092#endif
e1d04f48 1093 HDEBUG(D_transport|D_acl|D_v) debug_printf_indent(" SMTP(close)>>\n");
02b41d71
JH
1094 (void)close(sx.inblock.sock);
1095 sx.inblock.sock = sx.outblock.sock = -1;
0cbf2b82 1096#ifndef DISABLE_EVENT
02b41d71 1097 (void) event_raise(addr->transport->event_action, US"tcp:close", NULL);
a7538db1 1098#endif
02b41d71 1099 }
059ec3d9 1100 }
059ec3d9 1101
e9166683
JH
1102 if (!done || yield != OK)
1103 addr->message = string_sprintf("%s [%s] : %s", host->name, host->address,
1104 addr->message);
193e3acd
JH
1105 } /* Loop through all hosts, while !done */
1106 }
059ec3d9
PH
1107
1108/* If we get here with done == TRUE, a successful callout happened, and yield
1109will be set OK or FAIL according to the response to the RCPT command.
1110Otherwise, we looped through the hosts but couldn't complete the business.
707ee5b1 1111However, there may be domain-specific information to cache in both cases. */
059ec3d9 1112
707ee5b1
JH
1113if (!(options & vopt_callout_no_cache))
1114 cache_callout_write(&new_domain_record, addr->domain,
1115 done, &new_address_record, address_key);
059ec3d9
PH
1116
1117/* Failure to connect to any host, or any response other than 2xx or 5xx is a
1118temporary error. If there was only one host, and a response was received, leave
1119it alone if supplying details. Otherwise, give a generic response. */
1120
707ee5b1 1121if (!done)
059ec3d9 1122 {
ff5929e3 1123 uschar * dullmsg = string_sprintf("Could not complete %s verify callout",
8b9476ba 1124 options & vopt_is_recipient ? "recipient" : "sender");
059ec3d9
PH
1125 yield = DEFER;
1126
02b41d71
JH
1127 addr->message = host_list->next || !addr->message
1128 ? dullmsg : string_sprintf("%s: %s", dullmsg, addr->message);
059ec3d9 1129
ff5929e3
JH
1130 addr->user_message = smtp_return_error_details
1131 ? string_sprintf("%s for <%s>.\n"
059ec3d9
PH
1132 "The mail server(s) for the domain may be temporarily unreachable, or\n"
1133 "they may be permanently unreachable from this server. In the latter case,\n%s",
1134 dullmsg, addr->address,
8b9476ba 1135 options & vopt_is_recipient
ff5929e3 1136 ? "the address will never be accepted."
8b9476ba
JH
1137 : "you need to change the address or create an MX record for its domain\n"
1138 "if it is supposed to be generally accessible from the Internet.\n"
ff5929e3
JH
1139 "Talk to your mail administrator for details.")
1140 : dullmsg;
059ec3d9
PH
1141
1142 /* Force a specific error code */
1143
1144 addr->basic_errno = ERRNO_CALLOUTDEFER;
1145 }
1146
1147/* Come here from within the cache-reading code on fast-track exit. */
1148
1149END_CALLOUT:
02b41d71 1150tls_modify_variables(&tls_in);
059ec3d9
PH
1151return yield;
1152}
1153
1154
1155
817d9f57
JH
1156/* Called after recipient-acl to get a cutthrough connection open when
1157 one was requested and a recipient-verify wasn't subsequently done.
1158*/
f9334a28 1159int
e4bdf652
JH
1160open_cutthrough_connection( address_item * addr )
1161{
1162address_item addr2;
f9334a28 1163int rc;
e4bdf652
JH
1164
1165/* Use a recipient-verify-callout to set up the cutthrough connection. */
1166/* We must use a copy of the address for verification, because it might
1167get rewritten. */
1168
1169addr2 = *addr;
e1d04f48 1170HDEBUG(D_acl) debug_printf_indent("----------- %s cutthrough setup ------------\n",
5032d1cf 1171 rcpt_count > 1 ? "more" : "start");
ff5929e3 1172rc = verify_address(&addr2, NULL,
e4bdf652
JH
1173 vopt_is_recipient | vopt_callout_recipsender | vopt_callout_no_cache,
1174 CUTTHROUGH_CMD_TIMEOUT, -1, -1,
1175 NULL, NULL, NULL);
ff5929e3
JH
1176addr->message = addr2.message;
1177addr->user_message = addr2.user_message;
e1d04f48 1178HDEBUG(D_acl) debug_printf_indent("----------- end cutthrough setup ------------\n");
f9334a28 1179return rc;
e4bdf652
JH
1180}
1181
1182
e4bdf652 1183
817d9f57
JH
1184/* Send given number of bytes from the buffer */
1185static BOOL
1186cutthrough_send(int n)
e4bdf652 1187{
5032d1cf 1188if(cutthrough.fd < 0)
817d9f57 1189 return TRUE;
e4bdf652 1190
817d9f57
JH
1191if(
1192#ifdef SUPPORT_TLS
925ac8e4 1193 tls_out.active == cutthrough.fd ? tls_write(FALSE, ctblock.buffer, n, FALSE) :
817d9f57 1194#endif
5032d1cf 1195 send(cutthrough.fd, ctblock.buffer, n, 0) > 0
817d9f57
JH
1196 )
1197{
1198 transport_count += n;
1199 ctblock.ptr= ctblock.buffer;
1200 return TRUE;
1201}
e4bdf652 1202
e1d04f48 1203HDEBUG(D_transport|D_acl) debug_printf_indent("cutthrough_send failed: %s\n", strerror(errno));
817d9f57 1204return FALSE;
e4bdf652
JH
1205}
1206
1207
1208
817d9f57
JH
1209static BOOL
1210_cutthrough_puts(uschar * cp, int n)
1211{
1212while(n--)
1213 {
1214 if(ctblock.ptr >= ctblock.buffer+ctblock.buffersize)
1215 if(!cutthrough_send(ctblock.buffersize))
1216 return FALSE;
1217
1218 *ctblock.ptr++ = *cp++;
1219 }
1220return TRUE;
1221}
1222
1223/* Buffered output of counted data block. Return boolean success */
57cc2785 1224static BOOL
e4bdf652
JH
1225cutthrough_puts(uschar * cp, int n)
1226{
5032d1cf 1227if (cutthrough.fd < 0) return TRUE;
817d9f57 1228if (_cutthrough_puts(cp, n)) return TRUE;
57cc2785 1229cancel_cutthrough_connection(TRUE, US"transmit failed");
817d9f57
JH
1230return FALSE;
1231}
e4bdf652 1232
6851a9c5 1233void
57cc2785
JH
1234cutthrough_data_puts(uschar * cp, int n)
1235{
6851a9c5 1236if (cutthrough.delivery) (void) cutthrough_puts(cp, n);
78a3bbd5 1237return;
57cc2785
JH
1238}
1239
e4bdf652 1240
817d9f57 1241static BOOL
5032d1cf 1242_cutthrough_flush_send(void)
817d9f57 1243{
57cc2785 1244int n = ctblock.ptr - ctblock.buffer;
e4bdf652 1245
817d9f57
JH
1246if(n>0)
1247 if(!cutthrough_send(n))
1248 return FALSE;
1249return TRUE;
e4bdf652
JH
1250}
1251
817d9f57
JH
1252
1253/* Send out any bufferred output. Return boolean success. */
e4bdf652 1254BOOL
5032d1cf 1255cutthrough_flush_send(void)
e4bdf652 1256{
817d9f57 1257if (_cutthrough_flush_send()) return TRUE;
57cc2785 1258cancel_cutthrough_connection(TRUE, US"transmit failed");
e4bdf652
JH
1259return FALSE;
1260}
1261
1262
57cc2785 1263static BOOL
5032d1cf 1264cutthrough_put_nl(void)
e4bdf652
JH
1265{
1266return cutthrough_puts(US"\r\n", 2);
1267}
1268
1269
6851a9c5 1270void
57cc2785
JH
1271cutthrough_data_put_nl(void)
1272{
6851a9c5 1273cutthrough_data_puts(US"\r\n", 2);
57cc2785
JH
1274}
1275
1276
e4bdf652
JH
1277/* Get and check response from cutthrough target */
1278static uschar
57cc2785 1279cutthrough_response(int fd, char expect, uschar ** copy, int timeout)
e4bdf652
JH
1280{
1281smtp_inblock inblock;
1282uschar inbuffer[4096];
1283uschar responsebuffer[4096];
1284
1285inblock.buffer = inbuffer;
1286inblock.buffersize = sizeof(inbuffer);
1287inblock.ptr = inbuffer;
1288inblock.ptrend = inbuffer;
57cc2785 1289inblock.sock = fd;
817d9f57 1290/* this relies on (inblock.sock == tls_out.active) */
2760b518 1291if(!smtp_read_response(&inblock, responsebuffer, sizeof(responsebuffer), expect, timeout))
57cc2785 1292 cancel_cutthrough_connection(TRUE, US"target timeout on read");
e4bdf652 1293
57cc2785 1294if(copy)
e4bdf652
JH
1295 {
1296 uschar * cp;
5032d1cf 1297 *copy = cp = string_copy(responsebuffer);
e4bdf652
JH
1298 /* Trim the trailing end of line */
1299 cp += Ustrlen(responsebuffer);
1300 if(cp > *copy && cp[-1] == '\n') *--cp = '\0';
1301 if(cp > *copy && cp[-1] == '\r') *--cp = '\0';
1302 }
1303
1304return responsebuffer[0];
1305}
1306
1307
1308/* Negotiate dataphase with the cutthrough target, returning success boolean */
1309BOOL
5032d1cf 1310cutthrough_predata(void)
e4bdf652 1311{
57cc2785 1312if(cutthrough.fd < 0 || cutthrough.callout_hold_only)
e4bdf652
JH
1313 return FALSE;
1314
e1d04f48 1315HDEBUG(D_transport|D_acl|D_v) debug_printf_indent(" SMTP>> DATA\n");
817d9f57
JH
1316cutthrough_puts(US"DATA\r\n", 6);
1317cutthrough_flush_send();
e4bdf652
JH
1318
1319/* Assume nothing buffered. If it was it gets ignored. */
57cc2785 1320return cutthrough_response(cutthrough.fd, '3', NULL, CUTTHROUGH_DATA_TIMEOUT) == '3';
e4bdf652
JH
1321}
1322
1323
42055a33 1324/* tctx arg only to match write_chunk() */
511a6c14 1325static BOOL
42055a33 1326cutthrough_write_chunk(transport_ctx * tctx, uschar * s, int len)
511a6c14
JH
1327{
1328uschar * s2;
1329while(s && (s2 = Ustrchr(s, '\n')))
1330 {
1331 if(!cutthrough_puts(s, s2-s) || !cutthrough_put_nl())
1332 return FALSE;
1333 s = s2+1;
1334 }
1335return TRUE;
1336}
1337
1338
e4bdf652 1339/* Buffered send of headers. Return success boolean. */
817d9f57 1340/* Expands newlines to wire format (CR,NL). */
e4bdf652 1341/* Also sends header-terminating blank line. */
e4bdf652 1342BOOL
5032d1cf 1343cutthrough_headers_send(void)
e4bdf652 1344{
6d5c916c
JH
1345transport_ctx tctx;
1346
57cc2785 1347if(cutthrough.fd < 0 || cutthrough.callout_hold_only)
e4bdf652
JH
1348 return FALSE;
1349
511a6c14
JH
1350/* We share a routine with the mainline transport to handle header add/remove/rewrites,
1351 but having a separate buffered-output function (for now)
1352*/
e1d04f48 1353HDEBUG(D_acl) debug_printf_indent("----------- start cutthrough headers send -----------\n");
e4bdf652 1354
42055a33 1355tctx.u.fd = cutthrough.fd;
6d5c916c
JH
1356tctx.tblock = cutthrough.addr.transport;
1357tctx.addr = &cutthrough.addr;
1358tctx.check_string = US".";
1359tctx.escape_string = US"..";
328c5688 1360/*XXX check under spool_files_wireformat. Might be irrelevant */
6d5c916c
JH
1361tctx.options = topt_use_crlf;
1362
42055a33 1363if (!transport_headers_send(&tctx, &cutthrough_write_chunk))
511a6c14
JH
1364 return FALSE;
1365
e1d04f48 1366HDEBUG(D_acl) debug_printf_indent("----------- done cutthrough headers send ------------\n");
511a6c14 1367return TRUE;
817d9f57
JH
1368}
1369
1370
1371static void
78a3bbd5 1372close_cutthrough_connection(const uschar * why)
817d9f57 1373{
57cc2785
JH
1374int fd = cutthrough.fd;
1375if(fd >= 0)
817d9f57
JH
1376 {
1377 /* We could be sending this after a bunch of data, but that is ok as
1378 the only way to cancel the transfer in dataphase is to drop the tcp
1379 conn before the final dot.
1380 */
1381 ctblock.ptr = ctbuffer;
e1d04f48 1382 HDEBUG(D_transport|D_acl|D_v) debug_printf_indent(" SMTP>> QUIT\n");
817d9f57
JH
1383 _cutthrough_puts(US"QUIT\r\n", 6); /* avoid recursion */
1384 _cutthrough_flush_send();
57cc2785 1385 cutthrough.fd = -1; /* avoid recursion via read timeout */
06fdb9f7 1386 cutthrough.nrcpt = 0; /* permit re-cutthrough on subsequent message */
2760b518
JH
1387
1388 /* Wait a short time for response, and discard it */
57cc2785 1389 cutthrough_response(fd, '2', NULL, 1);
817d9f57 1390
57cc2785 1391#ifdef SUPPORT_TLS
dec766a1 1392 tls_close(FALSE, TLS_SHUTDOWN_NOWAIT);
57cc2785 1393#endif
e1d04f48 1394 HDEBUG(D_transport|D_acl|D_v) debug_printf_indent(" SMTP(close)>>\n");
57cc2785 1395 (void)close(fd);
e1d04f48 1396 HDEBUG(D_acl) debug_printf_indent("----------- cutthrough shutdown (%s) ------------\n", why);
817d9f57
JH
1397 }
1398ctblock.ptr = ctbuffer;
e4bdf652
JH
1399}
1400
817d9f57 1401void
57cc2785
JH
1402cancel_cutthrough_connection(BOOL close_noncutthrough_verifies, const uschar * why)
1403{
1404if (cutthrough.delivery || close_noncutthrough_verifies)
1405 close_cutthrough_connection(why);
1406cutthrough.delivery = cutthrough.callout_hold_only = FALSE;
1407}
1408
1409
1410void
1411release_cutthrough_connection(const uschar * why)
817d9f57 1412{
5ea5d64c 1413if (cutthrough.fd < 0) return;
57cc2785
JH
1414HDEBUG(D_acl) debug_printf_indent("release cutthrough conn: %s\n", why);
1415cutthrough.fd = -1;
1416cutthrough.delivery = cutthrough.callout_hold_only = FALSE;
817d9f57
JH
1417}
1418
1419
1420
e4bdf652
JH
1421
1422/* Have senders final-dot. Send one to cutthrough target, and grab the response.
1423 Log an OK response as a transmission.
817d9f57 1424 Close the connection.
e4bdf652 1425 Return smtp response-class digit.
e4bdf652
JH
1426*/
1427uschar *
5032d1cf 1428cutthrough_finaldot(void)
e4bdf652 1429{
5032d1cf
JH
1430uschar res;
1431address_item * addr;
e1d04f48 1432HDEBUG(D_transport|D_acl|D_v) debug_printf_indent(" SMTP>> .\n");
e4bdf652
JH
1433
1434/* Assume data finshed with new-line */
5032d1cf
JH
1435if( !cutthrough_puts(US".", 1)
1436 || !cutthrough_put_nl()
1437 || !cutthrough_flush_send()
1438 )
1439 return cutthrough.addr.message;
e4bdf652 1440
57cc2785 1441res = cutthrough_response(cutthrough.fd, '2', &cutthrough.addr.message, CUTTHROUGH_DATA_TIMEOUT);
5032d1cf 1442for (addr = &cutthrough.addr; addr; addr = addr->next)
817d9f57 1443 {
5032d1cf
JH
1444 addr->message = cutthrough.addr.message;
1445 switch(res)
1446 {
1447 case '2':
1448 delivery_log(LOG_MAIN, addr, (int)'>', NULL);
78a3bbd5 1449 close_cutthrough_connection(US"delivered");
5032d1cf 1450 break;
817d9f57 1451
5032d1cf
JH
1452 case '4':
1453 delivery_log(LOG_MAIN, addr, 0,
1454 US"tmp-reject from cutthrough after DATA:");
1455 break;
e4bdf652 1456
5032d1cf
JH
1457 case '5':
1458 delivery_log(LOG_MAIN|LOG_REJECT, addr, 0,
1459 US"rejected after DATA:");
1460 break;
e4bdf652 1461
5032d1cf
JH
1462 default:
1463 break;
1464 }
817d9f57 1465 }
5032d1cf 1466return cutthrough.addr.message;
e4bdf652
JH
1467}
1468
1469
817d9f57 1470
059ec3d9
PH
1471/*************************************************
1472* Copy error to toplevel address *
1473*************************************************/
1474
1475/* This function is used when a verify fails or defers, to ensure that the
1476failure or defer information is in the original toplevel address. This applies
1477when an address is redirected to a single new address, and the failure or
1478deferral happens to the child address.
1479
1480Arguments:
1481 vaddr the verify address item
1482 addr the final address item
1483 yield FAIL or DEFER
1484
1485Returns: the value of YIELD
1486*/
1487
1488static int
1489copy_error(address_item *vaddr, address_item *addr, int yield)
1490{
1491if (addr != vaddr)
1492 {
1493 vaddr->message = addr->message;
1494 vaddr->user_message = addr->user_message;
1495 vaddr->basic_errno = addr->basic_errno;
1496 vaddr->more_errno = addr->more_errno;
d43cbe25 1497 vaddr->prop.address_data = addr->prop.address_data;
42855d71 1498 copyflag(vaddr, addr, af_pass_message);
059ec3d9
PH
1499 }
1500return yield;
1501}
1502
1503
1504
1505
ce552449
NM
1506/**************************************************
1507* printf that automatically handles TLS if needed *
1508***************************************************/
1509
1510/* This function is used by verify_address() as a substitute for all fprintf()
1511calls; a direct fprintf() will not produce output in a TLS SMTP session, such
1512as a response to an EXPN command. smtp_in.c makes smtp_printf available but
1513that assumes that we always use the smtp_out FILE* when not using TLS or the
1514ssl buffer when we are. Instead we take a FILE* parameter and check to see if
1515that is smtp_out; if so, smtp_printf() with TLS support, otherwise regular
1516fprintf().
1517
1518Arguments:
1519 f the candidate FILE* to write to
1520 format format string
1521 ... optional arguments
1522
1523Returns:
1524 nothing
1525*/
1526
1527static void PRINTF_FUNCTION(2,3)
1ba28e2b 1528respond_printf(FILE *f, const char *format, ...)
ce552449
NM
1529{
1530va_list ap;
1531
1532va_start(ap, format);
1533if (smtp_out && (f == smtp_out))
925ac8e4 1534 smtp_vprintf(format, FALSE, ap);
ce552449 1535else
513afc6a 1536 vfprintf(f, format, ap);
ce552449
NM
1537va_end(ap);
1538}
1539
1540
1541
059ec3d9
PH
1542/*************************************************
1543* Verify an email address *
1544*************************************************/
1545
1546/* This function is used both for verification (-bv and at other times) and
1547address testing (-bt), which is indicated by address_test_mode being set.
1548
1549Arguments:
1550 vaddr contains the address to verify; the next field in this block
1551 must be NULL
1552 f if not NULL, write the result to this file
1553 options various option bits:
1554 vopt_fake_sender => this sender verify is not for the real
1555 sender (it was verify=sender=xxxx or an address from a
1556 header line) - rewriting must not change sender_address
1557 vopt_is_recipient => this is a recipient address, otherwise
1558 it's a sender address - this affects qualification and
1559 rewriting and messages from callouts
1560 vopt_qualify => qualify an unqualified address; else error
1561 vopt_expn => called from SMTP EXPN command
eafd343b
TK
1562 vopt_success_on_redirect => when a new address is generated
1563 the verification instantly succeeds
059ec3d9
PH
1564
1565 These ones are used by do_callout() -- the options variable
1566 is passed to it.
1567
2a4be8f9 1568 vopt_callout_fullpm => if postmaster check, do full one
059ec3d9
PH
1569 vopt_callout_no_cache => don't use callout cache
1570 vopt_callout_random => do the "random" thing
1571 vopt_callout_recipsender => use real sender for recipient
1572 vopt_callout_recippmaster => use postmaster for recipient
1573
1574 callout if > 0, specifies that callout is required, and gives timeout
4deaf07d 1575 for individual commands
059ec3d9
PH
1576 callout_overall if > 0, gives overall timeout for the callout function;
1577 if < 0, a default is used (see do_callout())
8e669ac1 1578 callout_connect the connection timeout for callouts
059ec3d9
PH
1579 se_mailfrom when callout is requested to verify a sender, use this
1580 in MAIL FROM; NULL => ""
1581 pm_mailfrom when callout is requested, if non-NULL, do the postmaster
1582 thing and use this as the sender address (may be "")
1583
1584 routed if not NULL, set TRUE if routing succeeded, so we can
1585 distinguish between routing failed and callout failed
1586
1587Returns: OK address verified
1588 FAIL address failed to verify
1589 DEFER can't tell at present
1590*/
1591
1592int
1593verify_address(address_item *vaddr, FILE *f, int options, int callout,
8e669ac1 1594 int callout_overall, int callout_connect, uschar *se_mailfrom,
4deaf07d 1595 uschar *pm_mailfrom, BOOL *routed)
059ec3d9
PH
1596{
1597BOOL allok = TRUE;
1598BOOL full_info = (f == NULL)? FALSE : (debug_selector != 0);
059ec3d9 1599BOOL expn = (options & vopt_expn) != 0;
eafd343b 1600BOOL success_on_redirect = (options & vopt_success_on_redirect) != 0;
059ec3d9
PH
1601int i;
1602int yield = OK;
1603int verify_type = expn? v_expn :
1604 address_test_mode? v_none :
8b9476ba 1605 options & vopt_is_recipient? v_recipient : v_sender;
059ec3d9
PH
1606address_item *addr_list;
1607address_item *addr_new = NULL;
1608address_item *addr_remote = NULL;
1609address_item *addr_local = NULL;
1610address_item *addr_succeed = NULL;
8b9476ba
JH
1611uschar **failure_ptr = options & vopt_is_recipient
1612 ? &recipient_verify_failure : &sender_verify_failure;
059ec3d9
PH
1613uschar *ko_prefix, *cr;
1614uschar *address = vaddr->address;
1615uschar *save_sender;
1616uschar null_sender[] = { 0 }; /* Ensure writeable memory */
1617
2c7db3f5
PH
1618/* Clear, just in case */
1619
1620*failure_ptr = NULL;
1621
059ec3d9
PH
1622/* Set up a prefix and suffix for error message which allow us to use the same
1623output statements both in EXPN mode (where an SMTP response is needed) and when
1624debugging with an output file. */
1625
1626if (expn)
1627 {
1628 ko_prefix = US"553 ";
1629 cr = US"\r";
1630 }
1631else ko_prefix = cr = US"";
1632
1633/* Add qualify domain if permitted; otherwise an unqualified address fails. */
1634
1635if (parse_find_at(address) == NULL)
1636 {
1637 if ((options & vopt_qualify) == 0)
1638 {
1639 if (f != NULL)
ce552449
NM
1640 respond_printf(f, "%sA domain is required for \"%s\"%s\n",
1641 ko_prefix, address, cr);
8e669ac1 1642 *failure_ptr = US"qualify";
059ec3d9
PH
1643 return FAIL;
1644 }
8b9476ba 1645 address = rewrite_address_qualify(address, options & vopt_is_recipient);
059ec3d9
PH
1646 }
1647
1648DEBUG(D_verify)
1649 {
1650 debug_printf(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\n");
1651 debug_printf("%s %s\n", address_test_mode? "Testing" : "Verifying", address);
1652 }
1653
1654/* Rewrite and report on it. Clear the domain and local part caches - these
1655may have been set by domains and local part tests during an ACL. */
1656
1657if (global_rewrite_rules != NULL)
1658 {
1659 uschar *old = address;
8b9476ba 1660 address = rewrite_address(address, options & vopt_is_recipient, FALSE,
059ec3d9
PH
1661 global_rewrite_rules, rewrite_existflags);
1662 if (address != old)
1663 {
1664 for (i = 0; i < (MAX_NAMED_LIST * 2)/32; i++) vaddr->localpart_cache[i] = 0;
1665 for (i = 0; i < (MAX_NAMED_LIST * 2)/32; i++) vaddr->domain_cache[i] = 0;
1666 if (f != NULL && !expn) fprintf(f, "Address rewritten as: %s\n", address);
1667 }
1668 }
1669
1670/* If this is the real sender address, we must update sender_address at
1671this point, because it may be referred to in the routers. */
1672
1673if ((options & (vopt_fake_sender|vopt_is_recipient)) == 0)
1674 sender_address = address;
1675
1676/* If the address was rewritten to <> no verification can be done, and we have
1677to return OK. This rewriting is permitted only for sender addresses; for other
1678addresses, such rewriting fails. */
1679
1680if (address[0] == 0) return OK;
1681
d9b2312b
JH
1682/* Flip the legacy TLS-related variables over to the outbound set in case
1683they're used in the context of a transport used by verification. Reset them
ea90b718 1684at exit from this routine (so no returns allowed from here on). */
d9b2312b 1685
35aba663 1686tls_modify_variables(&tls_out);
d9b2312b 1687
059ec3d9
PH
1688/* Save a copy of the sender address for re-instating if we change it to <>
1689while verifying a sender address (a nice bit of self-reference there). */
1690
1691save_sender = sender_address;
1692
ea90b718
JH
1693/* Observability variable for router/transport use */
1694
8b9476ba 1695verify_mode = options & vopt_is_recipient ? US"R" : US"S";
ea90b718 1696
059ec3d9
PH
1697/* Update the address structure with the possibly qualified and rewritten
1698address. Set it up as the starting address on the chain of new addresses. */
1699
1700vaddr->address = address;
1701addr_new = vaddr;
1702
1703/* We need a loop, because an address can generate new addresses. We must also
1704cope with generated pipes and files at the top level. (See also the code and
1705comment in deliver.c.) However, it is usually the case that the router for
1706user's .forward files has its verify flag turned off.
1707
1708If an address generates more than one child, the loop is used only when
1709full_info is set, and this can only be set locally. Remote enquiries just get
1710information about the top level address, not anything that it generated. */
1711
ea90b718 1712while (addr_new)
059ec3d9
PH
1713 {
1714 int rc;
1715 address_item *addr = addr_new;
1716
1717 addr_new = addr->next;
1718 addr->next = NULL;
1719
1720 DEBUG(D_verify)
1721 {
1722 debug_printf(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\n");
1723 debug_printf("Considering %s\n", addr->address);
1724 }
1725
1726 /* Handle generated pipe, file or reply addresses. We don't get these
1727 when handling EXPN, as it does only one level of expansion. */
1728
1729 if (testflag(addr, af_pfr))
1730 {
1731 allok = FALSE;
1732 if (f != NULL)
1733 {
1734 BOOL allow;
1735
1736 if (addr->address[0] == '>')
1737 {
1738 allow = testflag(addr, af_allow_reply);
1739 fprintf(f, "%s -> mail %s", addr->parent->address, addr->address + 1);
1740 }
1741 else
1742 {
1743 allow = (addr->address[0] == '|')?
1744 testflag(addr, af_allow_pipe) : testflag(addr, af_allow_file);
1745 fprintf(f, "%s -> %s", addr->parent->address, addr->address);
1746 }
1747
1748 if (addr->basic_errno == ERRNO_BADTRANSPORT)
1749 fprintf(f, "\n*** Error in setting up pipe, file, or autoreply:\n"
1750 "%s\n", addr->message);
1751 else if (allow)
1752 fprintf(f, "\n transport = %s\n", addr->transport->name);
1753 else
1754 fprintf(f, " *** forbidden ***\n");
1755 }
1756 continue;
1757 }
1758
1759 /* Just in case some router parameter refers to it. */
1760
2f682e45
JH
1761 return_path = addr->prop.errors_address
1762 ? addr->prop.errors_address : sender_address;
059ec3d9
PH
1763
1764 /* Split the address into domain and local part, handling the %-hack if
1765 necessary, and then route it. While routing a sender address, set
1766 $sender_address to <> because that is what it will be if we were trying to
1767 send a bounce to the sender. */
1768
2f682e45 1769 if (routed) *routed = FALSE;
059ec3d9
PH
1770 if ((rc = deliver_split_address(addr)) == OK)
1771 {
8b9476ba 1772 if (!(options & vopt_is_recipient)) sender_address = null_sender;
059ec3d9
PH
1773 rc = route_address(addr, &addr_local, &addr_remote, &addr_new,
1774 &addr_succeed, verify_type);
1775 sender_address = save_sender; /* Put back the real sender */
1776 }
1777
1778 /* If routing an address succeeded, set the flag that remembers, for use when
1779 an ACL cached a sender verify (in case a callout fails). Then if routing set
1780 up a list of hosts or the transport has a host list, and the callout option
1781 is set, and we aren't in a host checking run, do the callout verification,
1782 and set another flag that notes that a callout happened. */
1783
1784 if (rc == OK)
1785 {
2f682e45 1786 if (routed) *routed = TRUE;
059ec3d9
PH
1787 if (callout > 0)
1788 {
08f3b11b 1789 transport_instance * tp;
2f682e45 1790 host_item * host_list = addr->host_list;
059ec3d9 1791
26da7e20
PH
1792 /* Make up some data for use in the case where there is no remote
1793 transport. */
1794
1795 transport_feedback tf = {
f2ed27cf
JH
1796 .interface = NULL, /* interface (=> any) */
1797 .port = US"smtp",
1798 .protocol = US"smtp",
1799 .hosts = NULL,
1800 .helo_data = US"$smtp_active_hostname",
1801 .hosts_override = FALSE,
1802 .hosts_randomize = FALSE,
1803 .gethostbyname = FALSE,
1804 .qualify_single = TRUE,
1805 .search_parents = FALSE
26da7e20 1806 };
059ec3d9
PH
1807
1808 /* If verification yielded a remote transport, we want to use that
1809 transport's options, so as to mimic what would happen if we were really
1810 sending a message to this address. */
1811
08f3b11b 1812 if ((tp = addr->transport) && !tp->info->local)
059ec3d9 1813 {
08f3b11b 1814 (void)(tp->setup)(tp, addr, &tf, 0, 0, NULL);
059ec3d9
PH
1815
1816 /* If the transport has hosts and the router does not, or if the
1817 transport is configured to override the router's hosts, we must build a
1818 host list of the transport's hosts, and find the IP addresses */
1819
2f682e45 1820 if (tf.hosts && (!host_list || tf.hosts_override))
059ec3d9
PH
1821 {
1822 uschar *s;
55414b25 1823 const uschar *save_deliver_domain = deliver_domain;
750af86e 1824 uschar *save_deliver_localpart = deliver_localpart;
059ec3d9
PH
1825
1826 host_list = NULL; /* Ignore the router's hosts */
1827
1828 deliver_domain = addr->domain;
1829 deliver_localpart = addr->local_part;
1830 s = expand_string(tf.hosts);
750af86e
PH
1831 deliver_domain = save_deliver_domain;
1832 deliver_localpart = save_deliver_localpart;
059ec3d9 1833
2f682e45 1834 if (!s)
059ec3d9
PH
1835 {
1836 log_write(0, LOG_MAIN|LOG_PANIC, "failed to expand list of hosts "
1837 "\"%s\" in %s transport for callout: %s", tf.hosts,
08f3b11b 1838 tp->name, expand_string_message);
059ec3d9
PH
1839 }
1840 else
1841 {
322050c2 1842 int flags;
d8ef3577 1843 host_item *host, *nexthost;
059ec3d9
PH
1844 host_build_hostlist(&host_list, s, tf.hosts_randomize);
1845
1846 /* Just ignore failures to find a host address. If we don't manage
8e669ac1
PH
1847 to find any addresses, the callout will defer. Note that more than
1848 one address may be found for a single host, which will result in
1849 additional host items being inserted into the chain. Hence we must
d8ef3577 1850 save the next host first. */
059ec3d9 1851
66387a73 1852 flags = HOST_FIND_BY_A | HOST_FIND_BY_AAAA;
322050c2
PH
1853 if (tf.qualify_single) flags |= HOST_FIND_QUALIFY_SINGLE;
1854 if (tf.search_parents) flags |= HOST_FIND_SEARCH_PARENTS;
1855
2f682e45 1856 for (host = host_list; host; host = nexthost)
059ec3d9 1857 {
d8ef3577 1858 nexthost = host->next;
8e669ac1 1859 if (tf.gethostbyname ||
7e66e54d 1860 string_is_ip_address(host->name, NULL) != 0)
55414b25 1861 (void)host_find_byname(host, NULL, flags, NULL, TRUE);
059ec3d9 1862 else
9d9c3746 1863 {
7cd171b7 1864 dnssec_domains * dnssec_domains = NULL;
08f3b11b 1865 if (Ustrcmp(tp->driver_name, "smtp") == 0)
9d9c3746
JH
1866 {
1867 smtp_transport_options_block * ob =
08f3b11b 1868 (smtp_transport_options_block *) tp->options_block;
7cd171b7 1869 dnssec_domains = &ob->dnssec;
9d9c3746
JH
1870 }
1871
2546388c 1872 (void) host_find_bydns(host, NULL, flags, NULL, NULL, NULL,
7cd171b7 1873 dnssec_domains, NULL, NULL);
9d9c3746 1874 }
059ec3d9
PH
1875 }
1876 }
1877 }
1878 }
1879
8e669ac1 1880 /* Can only do a callout if we have at least one host! If the callout
2c7db3f5 1881 fails, it will have set ${sender,recipient}_verify_failure. */
059ec3d9 1882
2f682e45 1883 if (host_list)
059ec3d9
PH
1884 {
1885 HDEBUG(D_verify) debug_printf("Attempting full verification using callout\n");
1886 if (host_checking && !host_checking_callout)
1887 {
1888 HDEBUG(D_verify)
1889 debug_printf("... callout omitted by default when host testing\n"
1890 "(Use -bhc if you want the callouts to happen.)\n");
1891 }
1892 else
1893 {
4ed8d31a
JH
1894#ifdef SUPPORT_TLS
1895 deliver_set_expansions(addr);
1896#endif
059ec3d9 1897 rc = do_callout(addr, host_list, &tf, callout, callout_overall,
4deaf07d 1898 callout_connect, options, se_mailfrom, pm_mailfrom);
059ec3d9
PH
1899 }
1900 }
1901 else
1902 {
1903 HDEBUG(D_verify) debug_printf("Cannot do callout: neither router nor "
1904 "transport provided a host list\n");
1905 }
1906 }
1907 }
8e669ac1 1908
2c7db3f5 1909 /* Otherwise, any failure is a routing failure */
8e669ac1
PH
1910
1911 else *failure_ptr = US"route";
059ec3d9
PH
1912
1913 /* A router may return REROUTED if it has set up a child address as a result
1914 of a change of domain name (typically from widening). In this case we always
1915 want to continue to verify the new child. */
1916
1917 if (rc == REROUTED) continue;
8e669ac1 1918
059ec3d9
PH
1919 /* Handle hard failures */
1920
1921 if (rc == FAIL)
1922 {
1923 allok = FALSE;
2f682e45 1924 if (f)
059ec3d9 1925 {
e6f6568e
PH
1926 address_item *p = addr->parent;
1927
ce552449 1928 respond_printf(f, "%s%s %s", ko_prefix,
2f682e45
JH
1929 full_info ? addr->address : address,
1930 address_test_mode ? "is undeliverable" : "failed to verify");
059ec3d9
PH
1931 if (!expn && admin_user)
1932 {
1933 if (addr->basic_errno > 0)
ce552449 1934 respond_printf(f, ": %s", strerror(addr->basic_errno));
2f682e45 1935 if (addr->message)
ce552449 1936 respond_printf(f, ": %s", addr->message);
e6f6568e
PH
1937 }
1938
1939 /* Show parents iff doing full info */
1940
2f682e45 1941 if (full_info) while (p)
e6f6568e 1942 {
ce552449 1943 respond_printf(f, "%s\n <-- %s", cr, p->address);
e6f6568e 1944 p = p->parent;
059ec3d9 1945 }
ce552449 1946 respond_printf(f, "%s\n", cr);
059ec3d9 1947 }
57cc2785 1948 cancel_cutthrough_connection(TRUE, US"routing hard fail");
059ec3d9 1949
d9b2312b 1950 if (!full_info)
2f682e45 1951 {
d9b2312b
JH
1952 yield = copy_error(vaddr, addr, FAIL);
1953 goto out;
2f682e45
JH
1954 }
1955 yield = FAIL;
059ec3d9
PH
1956 }
1957
1958 /* Soft failure */
1959
1960 else if (rc == DEFER)
1961 {
1962 allok = FALSE;
2f682e45 1963 if (f)
059ec3d9 1964 {
e6f6568e 1965 address_item *p = addr->parent;
ce552449 1966 respond_printf(f, "%s%s cannot be resolved at this time", ko_prefix,
322050c2 1967 full_info? addr->address : address);
059ec3d9
PH
1968 if (!expn && admin_user)
1969 {
1970 if (addr->basic_errno > 0)
ce552449 1971 respond_printf(f, ": %s", strerror(addr->basic_errno));
2f682e45 1972 if (addr->message)
ce552449 1973 respond_printf(f, ": %s", addr->message);
059ec3d9 1974 else if (addr->basic_errno <= 0)
ce552449 1975 respond_printf(f, ": unknown error");
059ec3d9
PH
1976 }
1977
e6f6568e
PH
1978 /* Show parents iff doing full info */
1979
2f682e45 1980 if (full_info) while (p)
e6f6568e 1981 {
ce552449 1982 respond_printf(f, "%s\n <-- %s", cr, p->address);
e6f6568e
PH
1983 p = p->parent;
1984 }
ce552449 1985 respond_printf(f, "%s\n", cr);
059ec3d9 1986 }
57cc2785 1987 cancel_cutthrough_connection(TRUE, US"routing soft fail");
e4bdf652 1988
d9b2312b
JH
1989 if (!full_info)
1990 {
1991 yield = copy_error(vaddr, addr, DEFER);
1992 goto out;
1993 }
2f682e45 1994 if (yield == OK) yield = DEFER;
059ec3d9
PH
1995 }
1996
1997 /* If we are handling EXPN, we do not want to continue to route beyond
e6f6568e 1998 the top level (whose address is in "address"). */
059ec3d9
PH
1999
2000 else if (expn)
2001 {
2002 uschar *ok_prefix = US"250-";
2f682e45
JH
2003
2004 if (!addr_new)
2005 if (!addr_local && !addr_remote)
ce552449 2006 respond_printf(f, "250 mail to <%s> is discarded\r\n", address);
059ec3d9 2007 else
ce552449 2008 respond_printf(f, "250 <%s>\r\n", address);
2f682e45
JH
2009
2010 else do
059ec3d9
PH
2011 {
2012 address_item *addr2 = addr_new;
2013 addr_new = addr2->next;
2f682e45 2014 if (!addr_new) ok_prefix = US"250 ";
ce552449 2015 respond_printf(f, "%s<%s>\r\n", ok_prefix, addr2->address);
2f682e45 2016 } while (addr_new);
d9b2312b
JH
2017 yield = OK;
2018 goto out;
059ec3d9
PH
2019 }
2020
2021 /* Successful routing other than EXPN. */
2022
2023 else
2024 {
2025 /* Handle successful routing when short info wanted. Otherwise continue for
2026 other (generated) addresses. Short info is the operational case. Full info
2027 can be requested only when debug_selector != 0 and a file is supplied.
2028
2029 There is a conflict between the use of aliasing as an alternate email
2030 address, and as a sort of mailing list. If an alias turns the incoming
2031 address into just one address (e.g. J.Caesar->jc44) you may well want to
2032 carry on verifying the generated address to ensure it is valid when
2033 checking incoming mail. If aliasing generates multiple addresses, you
2034 probably don't want to do this. Exim therefore treats the generation of
2035 just a single new address as a special case, and continues on to verify the
2036 generated address. */
2037
2f682e45
JH
2038 if ( !full_info /* Stop if short info wanted AND */
2039 && ( ( !addr_new /* No new address OR */
2040 || addr_new->next /* More than one new address OR */
2041 || testflag(addr_new, af_pfr) /* New address is pfr */
2042 )
2043 || /* OR */
2044 ( addr_new /* At least one new address AND */
2045 && success_on_redirect /* success_on_redirect is set */
2046 ) )
2047 )
059ec3d9 2048 {
2f682e45
JH
2049 if (f) fprintf(f, "%s %s\n",
2050 address, address_test_mode ? "is deliverable" : "verified");
059ec3d9
PH
2051
2052 /* If we have carried on to verify a child address, we want the value
2053 of $address_data to be that of the child */
2054
d43cbe25 2055 vaddr->prop.address_data = addr->prop.address_data;
98c82a3d
JH
2056
2057 /* If stopped because more than one new address, cannot cutthrough */
2058
2059 if (addr_new && addr_new->next)
57cc2785 2060 cancel_cutthrough_connection(TRUE, US"multiple addresses from routing");
98c82a3d 2061
d9b2312b
JH
2062 yield = OK;
2063 goto out;
059ec3d9
PH
2064 }
2065 }
2066 } /* Loop for generated addresses */
2067
2068/* Display the full results of the successful routing, including any generated
2069addresses. Control gets here only when full_info is set, which requires f not
2070to be NULL, and this occurs only when a top-level verify is called with the
2071debugging switch on.
2072
2073If there are no local and no remote addresses, and there were no pipes, files,
2074or autoreplies, and there were no errors or deferments, the message is to be
2075discarded, usually because of the use of :blackhole: in an alias file. */
2076
2f682e45 2077if (allok && !addr_local && !addr_remote)
dbcef0ea 2078 {
059ec3d9 2079 fprintf(f, "mail to %s is discarded\n", address);
d9b2312b 2080 goto out;
dbcef0ea 2081 }
059ec3d9 2082
dbcef0ea 2083for (addr_list = addr_local, i = 0; i < 2; addr_list = addr_remote, i++)
08f3b11b 2084 while (addr_list)
059ec3d9
PH
2085 {
2086 address_item *addr = addr_list;
2087 address_item *p = addr->parent;
08f3b11b
JH
2088 transport_instance * tp = addr->transport;
2089
059ec3d9
PH
2090 addr_list = addr->next;
2091
2092 fprintf(f, "%s", CS addr->address);
384152a6 2093#ifdef EXPERIMENTAL_SRS
d43cbe25
JH
2094 if(addr->prop.srs_sender)
2095 fprintf(f, " [srs = %s]", addr->prop.srs_sender);
384152a6 2096#endif
dbcef0ea
PH
2097
2098 /* If the address is a duplicate, show something about it. */
2099
2100 if (!testflag(addr, af_pfr))
2101 {
2102 tree_node *tnode;
08f3b11b 2103 if ((tnode = tree_search(tree_duplicates, addr->unique)))
dbcef0ea
PH
2104 fprintf(f, " [duplicate, would not be delivered]");
2105 else tree_add_duplicate(addr->unique, addr);
2106 }
2107
2108 /* Now show its parents */
2109
08f3b11b 2110 for (p = addr->parent; p; p = p->parent)
059ec3d9 2111 fprintf(f, "\n <-- %s", p->address);
059ec3d9
PH
2112 fprintf(f, "\n ");
2113
2114 /* Show router, and transport */
2115
08f3b11b
JH
2116 fprintf(f, "router = %s, transport = %s\n",
2117 addr->router->name, tp ? tp->name : US"unset");
059ec3d9
PH
2118
2119 /* Show any hosts that are set up by a router unless the transport
2120 is going to override them; fiddle a bit to get a nice format. */
2121
08f3b11b 2122 if (addr->host_list && tp && !tp->overrides_hosts)
059ec3d9
PH
2123 {
2124 host_item *h;
2125 int maxlen = 0;
2126 int maxaddlen = 0;
08f3b11b
JH
2127 for (h = addr->host_list; h; h = h->next)
2128 { /* get max lengths of host names, addrs */
059ec3d9
PH
2129 int len = Ustrlen(h->name);
2130 if (len > maxlen) maxlen = len;
08f3b11b 2131 len = h->address ? Ustrlen(h->address) : 7;
059ec3d9
PH
2132 if (len > maxaddlen) maxaddlen = len;
2133 }
08f3b11b
JH
2134 for (h = addr->host_list; h; h = h->next)
2135 {
2136 fprintf(f, " host %-*s ", maxlen, h->name);
2137
2138 if (h->address)
2139 fprintf(f, "[%s%-*c", h->address, maxaddlen+1 - Ustrlen(h->address), ']');
2140 else if (tp->info->local)
2141 fprintf(f, " %-*s ", maxaddlen, ""); /* Omit [unknown] for local */
2142 else
2143 fprintf(f, "[%s%-*c", "unknown", maxaddlen+1 - 7, ']');
2144
2145 if (h->mx >= 0) fprintf(f, " MX=%d", h->mx);
059ec3d9 2146 if (h->port != PORT_NONE) fprintf(f, " port=%d", h->port);
08f3b11b
JH
2147 if (running_in_test_harness && h->dnssec == DS_YES) fputs(" AD", f);
2148 if (h->status == hstatus_unusable) fputs(" ** unusable **", f);
2149 fputc('\n', f);
059ec3d9
PH
2150 }
2151 }
2152 }
059ec3d9 2153
d9b2312b 2154/* Yield will be DEFER or FAIL if any one address has, only for full_info (which is
2c7db3f5
PH
2155the -bv or -bt case). */
2156
d9b2312b 2157out:
ea90b718 2158verify_mode = NULL;
35aba663 2159tls_modify_variables(&tls_in);
d9b2312b 2160
8e669ac1 2161return yield;
059ec3d9
PH
2162}
2163
2164
2165
2166
2167/*************************************************
2168* Check headers for syntax errors *
2169*************************************************/
2170
2171/* This function checks those header lines that contain addresses, and verifies
db57e575 2172that all the addresses therein are 5322-syntactially correct.
059ec3d9
PH
2173
2174Arguments:
2175 msgptr where to put an error message
2176
2177Returns: OK
2178 FAIL
2179*/
2180
2181int
2182verify_check_headers(uschar **msgptr)
2183{
2184header_line *h;
2185uschar *colon, *s;
1eccaa59 2186int yield = OK;
059ec3d9 2187
db57e575 2188for (h = header_list; h && yield == OK; h = h->next)
059ec3d9
PH
2189 {
2190 if (h->type != htype_from &&
2191 h->type != htype_reply_to &&
2192 h->type != htype_sender &&
2193 h->type != htype_to &&
2194 h->type != htype_cc &&
2195 h->type != htype_bcc)
2196 continue;
2197
2198 colon = Ustrchr(h->text, ':');
2199 s = colon + 1;
2200 while (isspace(*s)) s++;
2201
1eccaa59
PH
2202 /* Loop for multiple addresses in the header, enabling group syntax. Note
2203 that we have to reset this after the header has been scanned. */
059ec3d9 2204
1eccaa59 2205 parse_allow_group = TRUE;
059ec3d9 2206
db57e575 2207 while (*s)
059ec3d9
PH
2208 {
2209 uschar *ss = parse_find_address_end(s, FALSE);
2210 uschar *recipient, *errmess;
2211 int terminator = *ss;
2212 int start, end, domain;
2213
2214 /* Temporarily terminate the string at this point, and extract the
1eccaa59 2215 operative address within, allowing group syntax. */
059ec3d9
PH
2216
2217 *ss = 0;
2218 recipient = parse_extract_address(s,&errmess,&start,&end,&domain,FALSE);
2219 *ss = terminator;
2220
2221 /* Permit an unqualified address only if the message is local, or if the
2222 sending host is configured to be permitted to send them. */
2223
db57e575 2224 if (recipient && !domain)
059ec3d9
PH
2225 {
2226 if (h->type == htype_from || h->type == htype_sender)
2227 {
2228 if (!allow_unqualified_sender) recipient = NULL;
2229 }
2230 else
2231 {
2232 if (!allow_unqualified_recipient) recipient = NULL;
2233 }
2234 if (recipient == NULL) errmess = US"unqualified address not permitted";
2235 }
2236
2237 /* It's an error if no address could be extracted, except for the special
2238 case of an empty address. */
2239
db57e575 2240 if (!recipient && Ustrcmp(errmess, "empty address") != 0)
059ec3d9
PH
2241 {
2242 uschar *verb = US"is";
2243 uschar *t = ss;
1ab95fa6 2244 uschar *tt = colon;
059ec3d9
PH
2245 int len;
2246
2247 /* Arrange not to include any white space at the end in the
1ab95fa6 2248 error message or the header name. */
059ec3d9
PH
2249
2250 while (t > s && isspace(t[-1])) t--;
1ab95fa6 2251 while (tt > h->text && isspace(tt[-1])) tt--;
059ec3d9 2252
1ab95fa6 2253 /* Add the address that failed to the error message, since in a
059ec3d9
PH
2254 header with very many addresses it is sometimes hard to spot
2255 which one is at fault. However, limit the amount of address to
2256 quote - cases have been seen where, for example, a missing double
2257 quote in a humungous To: header creates an "address" that is longer
2258 than string_sprintf can handle. */
2259
2260 len = t - s;
2261 if (len > 1024)
2262 {
2263 len = 1024;
2264 verb = US"begins";
2265 }
2266
55414b25
JH
2267 /* deconst cast ok as we're passing a non-const to string_printing() */
2268 *msgptr = US string_printing(
1ab95fa6 2269 string_sprintf("%s: failing address in \"%.*s:\" header %s: %.*s",
bb07bcd3 2270 errmess, (int)(tt - h->text), h->text, verb, len, s));
059ec3d9 2271
1eccaa59
PH
2272 yield = FAIL;
2273 break; /* Out of address loop */
059ec3d9
PH
2274 }
2275
2276 /* Advance to the next address */
2277
db57e575 2278 s = ss + (terminator ? 1 : 0);
059ec3d9
PH
2279 while (isspace(*s)) s++;
2280 } /* Next address */
059ec3d9 2281
1eccaa59
PH
2282 parse_allow_group = FALSE;
2283 parse_found_group = FALSE;
2284 } /* Next header unless yield has been set FALSE */
2285
2286return yield;
059ec3d9
PH
2287}
2288
2289
770747fd
MFM
2290/*************************************************
2291* Check header names for 8-bit characters *
2292*************************************************/
2293
4c04137d 2294/* This function checks for invalid characters in header names. See
770747fd
MFM
2295RFC 5322, 2.2. and RFC 6532, 3.
2296
2297Arguments:
2298 msgptr where to put an error message
2299
2300Returns: OK
2301 FAIL
2302*/
2303
2304int
2305verify_check_header_names_ascii(uschar **msgptr)
2306{
2307header_line *h;
2308uschar *colon, *s;
2309
57cc2785 2310for (h = header_list; h; h = h->next)
770747fd 2311 {
57cc2785
JH
2312 colon = Ustrchr(h->text, ':');
2313 for(s = h->text; s < colon; s++)
2314 if ((*s < 33) || (*s > 126))
2315 {
2316 *msgptr = string_sprintf("Invalid character in header \"%.*s\" found",
2317 colon - h->text, h->text);
2318 return FAIL;
2319 }
770747fd
MFM
2320 }
2321return OK;
2322}
059ec3d9 2323
1c41c9cc
PH
2324/*************************************************
2325* Check for blind recipients *
2326*************************************************/
2327
2328/* This function checks that every (envelope) recipient is mentioned in either
2329the To: or Cc: header lines, thus detecting blind carbon copies.
2330
2331There are two ways of scanning that could be used: either scan the header lines
2332and tick off the recipients, or scan the recipients and check the header lines.
2333The original proposed patch did the former, but I have chosen to do the latter,
2334because (a) it requires no memory and (b) will use fewer resources when there
2335are many addresses in To: and/or Cc: and only one or two envelope recipients.
2336
2337Arguments: none
2338Returns: OK if there are no blind recipients
2339 FAIL if there is at least one blind recipient
2340*/
2341
2342int
2343verify_check_notblind(void)
2344{
2345int i;
2346for (i = 0; i < recipients_count; i++)
2347 {
2348 header_line *h;
2349 BOOL found = FALSE;
2350 uschar *address = recipients_list[i].address;
2351
2352 for (h = header_list; !found && h != NULL; h = h->next)
2353 {
2354 uschar *colon, *s;
2355
2356 if (h->type != htype_to && h->type != htype_cc) continue;
2357
2358 colon = Ustrchr(h->text, ':');
2359 s = colon + 1;
2360 while (isspace(*s)) s++;
2361
1eccaa59
PH
2362 /* Loop for multiple addresses in the header, enabling group syntax. Note
2363 that we have to reset this after the header has been scanned. */
1c41c9cc 2364
1eccaa59 2365 parse_allow_group = TRUE;
1c41c9cc
PH
2366
2367 while (*s != 0)
2368 {
2369 uschar *ss = parse_find_address_end(s, FALSE);
2370 uschar *recipient,*errmess;
2371 int terminator = *ss;
2372 int start, end, domain;
2373
2374 /* Temporarily terminate the string at this point, and extract the
1eccaa59 2375 operative address within, allowing group syntax. */
1c41c9cc
PH
2376
2377 *ss = 0;
2378 recipient = parse_extract_address(s,&errmess,&start,&end,&domain,FALSE);
2379 *ss = terminator;
2380
2381 /* If we found a valid recipient that has a domain, compare it with the
2382 envelope recipient. Local parts are compared case-sensitively, domains
2383 case-insensitively. By comparing from the start with length "domain", we
2384 include the "@" at the end, which ensures that we are comparing the whole
2385 local part of each address. */
2386
2387 if (recipient != NULL && domain != 0)
2388 {
2389 found = Ustrncmp(recipient, address, domain) == 0 &&
2390 strcmpic(recipient + domain, address + domain) == 0;
2391 if (found) break;
2392 }
2393
2394 /* Advance to the next address */
2395
2396 s = ss + (terminator? 1:0);
2397 while (isspace(*s)) s++;
2398 } /* Next address */
1eccaa59
PH
2399
2400 parse_allow_group = FALSE;
2401 parse_found_group = FALSE;
1c41c9cc
PH
2402 } /* Next header (if found is false) */
2403
2404 if (!found) return FAIL;
2405 } /* Next recipient */
2406
2407return OK;
2408}
2409
2410
059ec3d9
PH
2411
2412/*************************************************
2413* Find if verified sender *
2414*************************************************/
2415
2416/* Usually, just a single address is verified as the sender of the message.
2417However, Exim can be made to verify other addresses as well (often related in
2418some way), and this is useful in some environments. There may therefore be a
2419chain of such addresses that have previously been tested. This function finds
2420whether a given address is on the chain.
2421
2422Arguments: the address to be verified
2423Returns: pointer to an address item, or NULL
2424*/
2425
2426address_item *
2427verify_checked_sender(uschar *sender)
2428{
2429address_item *addr;
2430for (addr = sender_verified_list; addr != NULL; addr = addr->next)
2431 if (Ustrcmp(sender, addr->address) == 0) break;
2432return addr;
2433}
2434
2435
2436
2437
2438
2439/*************************************************
2440* Get valid header address *
2441*************************************************/
2442
2443/* Scan the originator headers of the message, looking for an address that
2444verifies successfully. RFC 822 says:
2445
2446 o The "Sender" field mailbox should be sent notices of
2447 any problems in transport or delivery of the original
2448 messages. If there is no "Sender" field, then the
2449 "From" field mailbox should be used.
2450
2451 o If the "Reply-To" field exists, then the reply should
2452 go to the addresses indicated in that field and not to
2453 the address(es) indicated in the "From" field.
2454
2455So we check a Sender field if there is one, else a Reply_to field, else a From
2456field. As some strange messages may have more than one of these fields,
2457especially if they are resent- fields, check all of them if there is more than
2458one.
2459
2460Arguments:
2461 user_msgptr points to where to put a user error message
2462 log_msgptr points to where to put a log error message
2463 callout timeout for callout check (passed to verify_address())
2464 callout_overall overall callout timeout (ditto)
8e669ac1 2465 callout_connect connect callout timeout (ditto)
059ec3d9
PH
2466 se_mailfrom mailfrom for verify; NULL => ""
2467 pm_mailfrom sender for pm callout check (passed to verify_address())
2468 options callout options (passed to verify_address())
8e669ac1 2469 verrno where to put the address basic_errno
059ec3d9
PH
2470
2471If log_msgptr is set to something without setting user_msgptr, the caller
2472normally uses log_msgptr for both things.
2473
2474Returns: result of the verification attempt: OK, FAIL, or DEFER;
2475 FAIL is given if no appropriate headers are found
2476*/
2477
2478int
2479verify_check_header_address(uschar **user_msgptr, uschar **log_msgptr,
8e669ac1 2480 int callout, int callout_overall, int callout_connect, uschar *se_mailfrom,
fe5b5d0b 2481 uschar *pm_mailfrom, int options, int *verrno)
059ec3d9
PH
2482{
2483static int header_types[] = { htype_sender, htype_reply_to, htype_from };
1eccaa59 2484BOOL done = FALSE;
059ec3d9
PH
2485int yield = FAIL;
2486int i;
2487
1eccaa59 2488for (i = 0; i < 3 && !done; i++)
059ec3d9
PH
2489 {
2490 header_line *h;
1eccaa59 2491 for (h = header_list; h != NULL && !done; h = h->next)
059ec3d9
PH
2492 {
2493 int terminator, new_ok;
2494 uschar *s, *ss, *endname;
2495
2496 if (h->type != header_types[i]) continue;
2497 s = endname = Ustrchr(h->text, ':') + 1;
2498
1eccaa59
PH
2499 /* Scan the addresses in the header, enabling group syntax. Note that we
2500 have to reset this after the header has been scanned. */
2501
2502 parse_allow_group = TRUE;
2503
059ec3d9
PH
2504 while (*s != 0)
2505 {
2506 address_item *vaddr;
2507
2508 while (isspace(*s) || *s == ',') s++;
2509 if (*s == 0) break; /* End of header */
2510
2511 ss = parse_find_address_end(s, FALSE);
2512
2513 /* The terminator is a comma or end of header, but there may be white
2514 space preceding it (including newline for the last address). Move back
2515 past any white space so we can check against any cached envelope sender
2516 address verifications. */
2517
2518 while (isspace(ss[-1])) ss--;
2519 terminator = *ss;
2520 *ss = 0;
2521
2522 HDEBUG(D_verify) debug_printf("verifying %.*s header address %s\n",
2523 (int)(endname - h->text), h->text, s);
2524
2525 /* See if we have already verified this address as an envelope sender,
2526 and if so, use the previous answer. */
2527
2528 vaddr = verify_checked_sender(s);
2529
2530 if (vaddr != NULL && /* Previously checked */
2531 (callout <= 0 || /* No callout needed; OR */
2532 vaddr->special_action > 256)) /* Callout was done */
2533 {
2534 new_ok = vaddr->special_action & 255;
2535 HDEBUG(D_verify) debug_printf("previously checked as envelope sender\n");
2536 *ss = terminator; /* Restore shortened string */
2537 }
2538
2539 /* Otherwise we run the verification now. We must restore the shortened
2540 string before running the verification, so the headers are correct, in
2541 case there is any rewriting. */
2542
2543 else
2544 {
2545 int start, end, domain;
1eccaa59
PH
2546 uschar *address = parse_extract_address(s, log_msgptr, &start, &end,
2547 &domain, FALSE);
059ec3d9
PH
2548
2549 *ss = terminator;
2550
1eccaa59
PH
2551 /* If we found an empty address, just carry on with the next one, but
2552 kill the message. */
2553
2554 if (address == NULL && Ustrcmp(*log_msgptr, "empty address") == 0)
2555 {
2556 *log_msgptr = NULL;
2557 s = ss;
2558 continue;
2559 }
2560
059ec3d9
PH
2561 /* If verification failed because of a syntax error, fail this
2562 function, and ensure that the failing address gets added to the error
2563 message. */
2564
2565 if (address == NULL)
2566 {
2567 new_ok = FAIL;
1eccaa59
PH
2568 while (ss > s && isspace(ss[-1])) ss--;
2569 *log_msgptr = string_sprintf("syntax error in '%.*s' header when "
2570 "scanning for sender: %s in \"%.*s\"",
bb07bcd3 2571 (int)(endname - h->text), h->text, *log_msgptr, (int)(ss - s), s);
1eccaa59
PH
2572 yield = FAIL;
2573 done = TRUE;
2574 break;
059ec3d9
PH
2575 }
2576
2f6603e1 2577 /* Else go ahead with the sender verification. But it isn't *the*
059ec3d9
PH
2578 sender of the message, so set vopt_fake_sender to stop sender_address
2579 being replaced after rewriting or qualification. */
2580
2581 else
2582 {
2583 vaddr = deliver_make_addr(address, FALSE);
2584 new_ok = verify_address(vaddr, NULL, options | vopt_fake_sender,
8e669ac1 2585 callout, callout_overall, callout_connect, se_mailfrom,
4deaf07d 2586 pm_mailfrom, NULL);
059ec3d9
PH
2587 }
2588 }
2589
2590 /* We now have the result, either newly found, or cached. If we are
2591 giving out error details, set a specific user error. This means that the
2592 last of these will be returned to the user if all three fail. We do not
2593 set a log message - the generic one below will be used. */
2594
fe5b5d0b 2595 if (new_ok != OK)
059ec3d9 2596 {
8e669ac1 2597 *verrno = vaddr->basic_errno;
fe5b5d0b 2598 if (smtp_return_error_details)
fe5b5d0b
PH
2599 *user_msgptr = string_sprintf("Rejected after DATA: "
2600 "could not verify \"%.*s\" header address\n%s: %s",
bb07bcd3 2601 (int)(endname - h->text), h->text, vaddr->address, vaddr->message);
8e669ac1 2602 }
059ec3d9
PH
2603
2604 /* Success or defer */
2605
1eccaa59
PH
2606 if (new_ok == OK)
2607 {
2608 yield = OK;
2609 done = TRUE;
2610 break;
2611 }
2612
059ec3d9
PH
2613 if (new_ok == DEFER) yield = DEFER;
2614
2615 /* Move on to any more addresses in the header */
2616
2617 s = ss;
1eccaa59
PH
2618 } /* Next address */
2619
2620 parse_allow_group = FALSE;
2621 parse_found_group = FALSE;
2622 } /* Next header, unless done */
2623 } /* Next header type unless done */
059ec3d9
PH
2624
2625if (yield == FAIL && *log_msgptr == NULL)
2626 *log_msgptr = US"there is no valid sender in any header line";
2627
2628if (yield == DEFER && *log_msgptr == NULL)
2629 *log_msgptr = US"all attempts to verify a sender in a header line deferred";
2630
2631return yield;
2632}
2633
2634
2635
2636
2637/*************************************************
2638* Get RFC 1413 identification *
2639*************************************************/
2640
2641/* Attempt to get an id from the sending machine via the RFC 1413 protocol. If
2642the timeout is set to zero, then the query is not done. There may also be lists
2643of hosts and nets which are exempt. To guard against malefactors sending
2644non-printing characters which could, for example, disrupt a message's headers,
2645make sure the string consists of printing characters only.
2646
2647Argument:
2648 port the port to connect to; usually this is IDENT_PORT (113), but when
2649 running in the test harness with -bh a different value is used.
2650
2651Returns: nothing
2652
2653Side effect: any received ident value is put in sender_ident (NULL otherwise)
2654*/
2655
2656void
2657verify_get_ident(int port)
2658{
2659int sock, host_af, qlen;
2660int received_sender_port, received_interface_port, n;
2661uschar *p;
44e6c20c 2662blob early_data;
059ec3d9
PH
2663uschar buffer[2048];
2664
2665/* Default is no ident. Check whether we want to do an ident check for this
2666host. */
2667
2668sender_ident = NULL;
2669if (rfc1413_query_timeout <= 0 || verify_check_host(&rfc1413_hosts) != OK)
2670 return;
2671
2672DEBUG(D_ident) debug_printf("doing ident callback\n");
2673
2674/* Set up a connection to the ident port of the remote host. Bind the local end
2675to the incoming interface address. If the sender host address is an IPv6
2676address, the incoming interface address will also be IPv6. */
2677
fb05276a
JH
2678host_af = Ustrchr(sender_host_address, ':') == NULL ? AF_INET : AF_INET6;
2679if ((sock = ip_socket(SOCK_STREAM, host_af)) < 0) return;
059ec3d9
PH
2680
2681if (ip_bind(sock, host_af, interface_address, 0) < 0)
2682 {
2683 DEBUG(D_ident) debug_printf("bind socket for ident failed: %s\n",
2684 strerror(errno));
2685 goto END_OFF;
2686 }
2687
44e6c20c
JH
2688/* Construct and send the query. */
2689
2690qlen = snprintf(CS buffer, sizeof(buffer), "%d , %d\r\n",
2691 sender_host_port, interface_port);
2692early_data.data = buffer;
2693early_data.len = qlen;
2694
fb05276a 2695if (ip_connect(sock, host_af, sender_host_address, port,
44e6c20c 2696 rfc1413_query_timeout, &early_data) < 0)
059ec3d9 2697 {
6c6d6e48 2698 if (errno == ETIMEDOUT && LOGGING(ident_timeout))
059ec3d9
PH
2699 log_write(0, LOG_MAIN, "ident connection to %s timed out",
2700 sender_host_address);
059ec3d9 2701 else
059ec3d9
PH
2702 DEBUG(D_ident) debug_printf("ident connection to %s failed: %s\n",
2703 sender_host_address, strerror(errno));
059ec3d9
PH
2704 goto END_OFF;
2705 }
2706
059ec3d9
PH
2707/* Read a response line. We put it into the rest of the buffer, using several
2708recv() calls if necessary. */
2709
2710p = buffer + qlen;
2711
2712for (;;)
2713 {
2714 uschar *pp;
2715 int count;
2716 int size = sizeof(buffer) - (p - buffer);
2717
2718 if (size <= 0) goto END_OFF; /* Buffer filled without seeing \n. */
2719 count = ip_recv(sock, p, size, rfc1413_query_timeout);
2720 if (count <= 0) goto END_OFF; /* Read error or EOF */
2721
2722 /* Scan what we just read, to see if we have reached the terminating \r\n. Be
2723 generous, and accept a plain \n terminator as well. The only illegal
2724 character is 0. */
2725
2726 for (pp = p; pp < p + count; pp++)
2727 {
2728 if (*pp == 0) goto END_OFF; /* Zero octet not allowed */
2729 if (*pp == '\n')
2730 {
2731 if (pp[-1] == '\r') pp--;
2732 *pp = 0;
2733 goto GOT_DATA; /* Break out of both loops */
2734 }
2735 }
2736
2737 /* Reached the end of the data without finding \n. Let the loop continue to
2738 read some more, if there is room. */
2739
2740 p = pp;
2741 }
2742
2743GOT_DATA:
2744
2745/* We have received a line of data. Check it carefully. It must start with the
2746same two port numbers that we sent, followed by data as defined by the RFC. For
2747example,
2748
2749 12345 , 25 : USERID : UNIX :root
2750
2751However, the amount of white space may be different to what we sent. In the
2752"osname" field there may be several sub-fields, comma separated. The data we
2753actually want to save follows the third colon. Some systems put leading spaces
2754in it - we discard those. */
2755
2756if (sscanf(CS buffer + qlen, "%d , %d%n", &received_sender_port,
2757 &received_interface_port, &n) != 2 ||
2758 received_sender_port != sender_host_port ||
2759 received_interface_port != interface_port)
2760 goto END_OFF;
2761
2762p = buffer + qlen + n;
2763while(isspace(*p)) p++;
2764if (*p++ != ':') goto END_OFF;
2765while(isspace(*p)) p++;
2766if (Ustrncmp(p, "USERID", 6) != 0) goto END_OFF;
2767p += 6;
2768while(isspace(*p)) p++;
2769if (*p++ != ':') goto END_OFF;
2770while (*p != 0 && *p != ':') p++;
2771if (*p++ == 0) goto END_OFF;
2772while(isspace(*p)) p++;
2773if (*p == 0) goto END_OFF;
2774
2775/* The rest of the line is the data we want. We turn it into printing
2776characters when we save it, so that it cannot mess up the format of any logging
2777or Received: lines into which it gets inserted. We keep a maximum of 127
55414b25 2778characters. The deconst cast is ok as we fed a nonconst to string_printing() */
059ec3d9 2779
55414b25 2780sender_ident = US string_printing(string_copyn(p, 127));
059ec3d9
PH
2781DEBUG(D_ident) debug_printf("sender_ident = %s\n", sender_ident);
2782
2783END_OFF:
f1e894f3 2784(void)close(sock);
059ec3d9
PH
2785return;
2786}
2787
2788
2789
2790
2791/*************************************************
2792* Match host to a single host-list item *
2793*************************************************/
2794
2795/* This function compares a host (name or address) against a single item
2796from a host list. The host name gets looked up if it is needed and is not
2797already known. The function is called from verify_check_this_host() via
2798match_check_list(), which is why most of its arguments are in a single block.
2799
2800Arguments:
2801 arg the argument block (see below)
2802 ss the host-list item
2803 valueptr where to pass back looked up data, or NULL
2804 error for error message when returning ERROR
2805
2806The block contains:
32d668a5
PH
2807 host_name (a) the host name, or
2808 (b) NULL, implying use sender_host_name and
2809 sender_host_aliases, looking them up if required, or
2810 (c) the empty string, meaning that only IP address matches
2811 are permitted
059ec3d9
PH
2812 host_address the host address
2813 host_ipv4 the IPv4 address taken from an IPv6 one
2814
2815Returns: OK matched
2816 FAIL did not match
2817 DEFER lookup deferred
32d668a5
PH
2818 ERROR (a) failed to find the host name or IP address, or
2819 (b) unknown lookup type specified, or
2820 (c) host name encountered when only IP addresses are
2821 being matched
059ec3d9
PH
2822*/
2823
32d668a5 2824int
55414b25 2825check_host(void *arg, const uschar *ss, const uschar **valueptr, uschar **error)
059ec3d9
PH
2826{
2827check_host_block *cb = (check_host_block *)arg;
32d668a5 2828int mlen = -1;
059ec3d9 2829int maskoffset;
32d668a5 2830BOOL iplookup = FALSE;
059ec3d9 2831BOOL isquery = FALSE;
32d668a5 2832BOOL isiponly = cb->host_name != NULL && cb->host_name[0] == 0;
55414b25 2833const uschar *t;
32d668a5 2834uschar *semicolon;
059ec3d9
PH
2835uschar **aliases;
2836
2837/* Optimize for the special case when the pattern is "*". */
2838
2839if (*ss == '*' && ss[1] == 0) return OK;
2840
2841/* If the pattern is empty, it matches only in the case when there is no host -
2842this can occur in ACL checking for SMTP input using the -bs option. In this
2843situation, the host address is the empty string. */
2844
2845if (cb->host_address[0] == 0) return (*ss == 0)? OK : FAIL;
2846if (*ss == 0) return FAIL;
2847
32d668a5
PH
2848/* If the pattern is precisely "@" then match against the primary host name,
2849provided that host name matching is permitted; if it's "@[]" match against the
2850local host's IP addresses. */
059ec3d9
PH
2851
2852if (*ss == '@')
2853 {
32d668a5
PH
2854 if (ss[1] == 0)
2855 {
2856 if (isiponly) return ERROR;
2857 ss = primary_hostname;
2858 }
059ec3d9
PH
2859 else if (Ustrcmp(ss, "@[]") == 0)
2860 {
2861 ip_address_item *ip;
2862 for (ip = host_find_interfaces(); ip != NULL; ip = ip->next)
2863 if (Ustrcmp(ip->address, cb->host_address) == 0) return OK;
2864 return FAIL;
2865 }
2866 }
2867
2868/* If the pattern is an IP address, optionally followed by a bitmask count, do
4c04137d 2869a (possibly masked) comparison with the current IP address. */
059ec3d9 2870
7e66e54d 2871if (string_is_ip_address(ss, &maskoffset) != 0)
059ec3d9
PH
2872 return (host_is_in_net(cb->host_address, ss, maskoffset)? OK : FAIL);
2873
1688f43b
PH
2874/* The pattern is not an IP address. A common error that people make is to omit
2875one component of an IPv4 address, either by accident, or believing that, for
2876example, 1.2.3/24 is the same as 1.2.3.0/24, or 1.2.3 is the same as 1.2.3.0,
2877which it isn't. (Those applications that do accept 1.2.3 as an IP address
2878interpret it as 1.2.0.3 because the final component becomes 16-bit - this is an
2879ancient specification.) To aid in debugging these cases, we give a specific
2880error if the pattern contains only digits and dots or contains a slash preceded
2881only by digits and dots (a slash at the start indicates a file name and of
2882course slashes may be present in lookups, but not preceded only by digits and
2883dots). */
2884
2885for (t = ss; isdigit(*t) || *t == '.'; t++);
2886if (*t == 0 || (*t == '/' && t != ss))
2887 {
2888 *error = US"malformed IPv4 address or address mask";
2889 return ERROR;
2890 }
2891
32d668a5 2892/* See if there is a semicolon in the pattern */
059ec3d9 2893
32d668a5
PH
2894semicolon = Ustrchr(ss, ';');
2895
2896/* If we are doing an IP address only match, then all lookups must be IP
df199fec 2897address lookups, even if there is no "net-". */
32d668a5
PH
2898
2899if (isiponly)
059ec3d9 2900 {
32d668a5
PH
2901 iplookup = semicolon != NULL;
2902 }
059ec3d9 2903
32d668a5 2904/* Otherwise, if the item is of the form net[n]-lookup;<file|query> then it is
df199fec
PH
2905a lookup on a masked IP network, in textual form. We obey this code even if we
2906have already set iplookup, so as to skip over the "net-" prefix and to set the
2907mask length. The net- stuff really only applies to single-key lookups where the
2908key is implicit. For query-style lookups the key is specified in the query.
2909From release 4.30, the use of net- for query style is no longer needed, but we
2910retain it for backward compatibility. */
2911
2912if (Ustrncmp(ss, "net", 3) == 0 && semicolon != NULL)
32d668a5
PH
2913 {
2914 mlen = 0;
2915 for (t = ss + 3; isdigit(*t); t++) mlen = mlen * 10 + *t - '0';
2916 if (mlen == 0 && t == ss+3) mlen = -1; /* No mask supplied */
2917 iplookup = (*t++ == '-');
2918 }
1688f43b 2919else t = ss;
059ec3d9 2920
32d668a5 2921/* Do the IP address lookup if that is indeed what we have */
059ec3d9 2922
32d668a5
PH
2923if (iplookup)
2924 {
2925 int insize;
2926 int search_type;
2927 int incoming[4];
2928 void *handle;
2929 uschar *filename, *key, *result;
2930 uschar buffer[64];
059ec3d9 2931
32d668a5 2932 /* Find the search type */
059ec3d9 2933
32d668a5 2934 search_type = search_findtype(t, semicolon - t);
059ec3d9 2935
32d668a5
PH
2936 if (search_type < 0) log_write(0, LOG_MAIN|LOG_PANIC_DIE, "%s",
2937 search_error_message);
059ec3d9 2938
13b685f9
PH
2939 /* Adjust parameters for the type of lookup. For a query-style lookup, there
2940 is no file name, and the "key" is just the query. For query-style with a file
2941 name, we have to fish the file off the start of the query. For a single-key
2942 lookup, the key is the current IP address, masked appropriately, and
2943 reconverted to text form, with the mask appended. For IPv6 addresses, specify
6a3bceb1
PH
2944 dot separators instead of colons, except when the lookup type is "iplsearch".
2945 */
059ec3d9 2946
13b685f9
PH
2947 if (mac_islookup(search_type, lookup_absfilequery))
2948 {
2949 filename = semicolon + 1;
2950 key = filename;
2951 while (*key != 0 && !isspace(*key)) key++;
2952 filename = string_copyn(filename, key - filename);
2953 while (isspace(*key)) key++;
2954 }
2955 else if (mac_islookup(search_type, lookup_querystyle))
32d668a5
PH
2956 {
2957 filename = NULL;
2958 key = semicolon + 1;
2959 }
6a3bceb1 2960 else /* Single-key style */
32d668a5 2961 {
e6d225ae 2962 int sep = (Ustrcmp(lookup_list[search_type]->name, "iplsearch") == 0)?
6a3bceb1 2963 ':' : '.';
32d668a5
PH
2964 insize = host_aton(cb->host_address, incoming);
2965 host_mask(insize, incoming, mlen);
6a3bceb1 2966 (void)host_nmtoa(insize, incoming, mlen, buffer, sep);
32d668a5
PH
2967 key = buffer;
2968 filename = semicolon + 1;
059ec3d9 2969 }
32d668a5
PH
2970
2971 /* Now do the actual lookup; note that there is no search_close() because
2972 of the caching arrangements. */
2973
d4ff61d1
JH
2974 if (!(handle = search_open(filename, search_type, 0, NULL, NULL)))
2975 log_write(0, LOG_MAIN|LOG_PANIC_DIE, "%s", search_error_message);
2976
32d668a5
PH
2977 result = search_find(handle, filename, key, -1, NULL, 0, 0, NULL);
2978 if (valueptr != NULL) *valueptr = result;
2979 return (result != NULL)? OK : search_find_defer? DEFER: FAIL;
059ec3d9
PH
2980 }
2981
2982/* The pattern is not an IP address or network reference of any kind. That is,
32d668a5
PH
2983it is a host name pattern. If this is an IP only match, there's an error in the
2984host list. */
2985
2986if (isiponly)
2987 {
2988 *error = US"cannot match host name in match_ip list";
2989 return ERROR;
2990 }
2991
2992/* Check the characters of the pattern to see if they comprise only letters,
2993digits, full stops, and hyphens (the constituents of domain names). Allow
2994underscores, as they are all too commonly found. Sigh. Also, if
2995allow_utf8_domains is set, allow top-bit characters. */
059ec3d9
PH
2996
2997for (t = ss; *t != 0; t++)
2998 if (!isalnum(*t) && *t != '.' && *t != '-' && *t != '_' &&
2999 (!allow_utf8_domains || *t < 128)) break;
3000
3001/* If the pattern is a complete domain name, with no fancy characters, look up
3002its IP address and match against that. Note that a multi-homed host will add
3003items to the chain. */
3004
3005if (*t == 0)
3006 {
3007 int rc;
3008 host_item h;
3009 h.next = NULL;
3010 h.name = ss;
3011 h.address = NULL;
3012 h.mx = MX_NONE;
9b8fadde 3013
1f155f8e
JH
3014 /* Using byname rather than bydns here means we cannot determine dnssec
3015 status. On the other hand it is unclear how that could be either
3016 propagated up or enforced. */
3017
322050c2 3018 rc = host_find_byname(&h, NULL, HOST_FIND_QUALIFY_SINGLE, NULL, FALSE);
059ec3d9
PH
3019 if (rc == HOST_FOUND || rc == HOST_FOUND_LOCAL)
3020 {
3021 host_item *hh;
3022 for (hh = &h; hh != NULL; hh = hh->next)
3023 {
96776534 3024 if (host_is_in_net(hh->address, cb->host_address, 0)) return OK;
059ec3d9
PH
3025 }
3026 return FAIL;
3027 }
3028 if (rc == HOST_FIND_AGAIN) return DEFER;
3029 *error = string_sprintf("failed to find IP address for %s", ss);
3030 return ERROR;
3031 }
3032
3033/* Almost all subsequent comparisons require the host name, and can be done
3034using the general string matching function. When this function is called for
3035outgoing hosts, the name is always given explicitly. If it is NULL, it means we
3036must use sender_host_name and its aliases, looking them up if necessary. */
3037
3038if (cb->host_name != NULL) /* Explicit host name given */
3039 return match_check_string(cb->host_name, ss, -1, TRUE, TRUE, TRUE,
3040 valueptr);
3041
3042/* Host name not given; in principle we need the sender host name and its
3043aliases. However, for query-style lookups, we do not need the name if the
3044query does not contain $sender_host_name. From release 4.23, a reference to
3045$sender_host_name causes it to be looked up, so we don't need to do the lookup
3046on spec. */
3047
3048if ((semicolon = Ustrchr(ss, ';')) != NULL)
3049 {
55414b25 3050 const uschar *affix;
059ec3d9
PH
3051 int partial, affixlen, starflags, id;
3052
3053 *semicolon = 0;
3054 id = search_findtype_partial(ss, &partial, &affix, &affixlen, &starflags);
3055 *semicolon=';';
3056
3057 if (id < 0) /* Unknown lookup type */
3058 {
3059 log_write(0, LOG_MAIN|LOG_PANIC, "%s in host list item \"%s\"",
3060 search_error_message, ss);
3061 return DEFER;
3062 }
13b685f9 3063 isquery = mac_islookup(id, lookup_querystyle|lookup_absfilequery);
059ec3d9
PH
3064 }
3065
3066if (isquery)
3067 {
3068 switch(match_check_string(US"", ss, -1, TRUE, TRUE, TRUE, valueptr))
3069 {
3070 case OK: return OK;
3071 case DEFER: return DEFER;
3072 default: return FAIL;
3073 }
3074 }
3075
3076/* Not a query-style lookup; must ensure the host name is present, and then we
3077do a check on the name and all its aliases. */
3078
2d0dc929 3079if (!sender_host_name)
059ec3d9
PH
3080 {
3081 HDEBUG(D_host_lookup)
3082 debug_printf("sender host name required, to match against %s\n", ss);
3083 if (host_lookup_failed || host_name_lookup() != OK)
3084 {
3085 *error = string_sprintf("failed to find host name for %s",
3086 sender_host_address);;
3087 return ERROR;
3088 }
3089 host_build_sender_fullhost();
3090 }
3091
3092/* Match on the sender host name, using the general matching function */
3093
2d0dc929 3094switch(match_check_string(sender_host_name, ss, -1, TRUE, TRUE, TRUE, valueptr))
059ec3d9
PH
3095 {
3096 case OK: return OK;
3097 case DEFER: return DEFER;
3098 }
3099
3100/* If there are aliases, try matching on them. */
3101
3102aliases = sender_host_aliases;
2d0dc929 3103while (*aliases)
059ec3d9
PH
3104 switch(match_check_string(*aliases++, ss, -1, TRUE, TRUE, TRUE, valueptr))
3105 {
3106 case OK: return OK;
3107 case DEFER: return DEFER;
3108 }
059ec3d9
PH
3109return FAIL;
3110}
3111
3112
3113
3114
3115/*************************************************
3116* Check a specific host matches a host list *
3117*************************************************/
3118
3119/* This function is passed a host list containing items in a number of
3120different formats and the identity of a host. Its job is to determine whether
3121the given host is in the set of hosts defined by the list. The host name is
3122passed as a pointer so that it can be looked up if needed and not already
3123known. This is commonly the case when called from verify_check_host() to check
3124an incoming connection. When called from elsewhere the host name should usually
3125be set.
3126
3127This function is now just a front end to match_check_list(), which runs common
3128code for scanning a list. We pass it the check_host() function to perform a
3129single test.
3130
3131Arguments:
3132 listptr pointer to the host list
3133 cache_bits pointer to cache for named lists, or NULL
3134 host_name the host name or NULL, implying use sender_host_name and
3135 sender_host_aliases, looking them up if required
3136 host_address the IP address
3137 valueptr if not NULL, data from a lookup is passed back here
3138
3139Returns: OK if the host is in the defined set
3140 FAIL if the host is not in the defined set,
3141 DEFER if a data lookup deferred (not a host lookup)
3142
3143If the host name was needed in order to make a comparison, and could not be
3144determined from the IP address, the result is FAIL unless the item
3145"+allow_unknown" was met earlier in the list, in which case OK is returned. */
3146
3147int
55414b25
JH
3148verify_check_this_host(const uschar **listptr, unsigned int *cache_bits,
3149 const uschar *host_name, const uschar *host_address, const uschar **valueptr)
059ec3d9 3150{
d4eb88df 3151int rc;
059ec3d9 3152unsigned int *local_cache_bits = cache_bits;
55414b25 3153const uschar *save_host_address = deliver_host_address;
0ab63f3d 3154check_host_block cb = { .host_name = host_name, .host_address = host_address };
059ec3d9 3155
0ab63f3d 3156if (valueptr) *valueptr = NULL;
059ec3d9
PH
3157
3158/* If the host address starts off ::ffff: it is an IPv6 address in
3159IPv4-compatible mode. Find the IPv4 part for checking against IPv4
3160addresses. */
3161
0ab63f3d
JH
3162cb.host_ipv4 = Ustrncmp(host_address, "::ffff:", 7) == 0
3163 ? host_address + 7 : host_address;
059ec3d9 3164
8e669ac1
PH
3165/* During the running of the check, put the IP address into $host_address. In
3166the case of calls from the smtp transport, it will already be there. However,
3167in other calls (e.g. when testing ignore_target_hosts), it won't. Just to be on
d4eb88df
PH
3168the safe side, any existing setting is preserved, though as I write this
3169(November 2004) I can't see any cases where it is actually needed. */
3170
3171deliver_host_address = host_address;
3172rc = match_check_list(
3173 listptr, /* the list */
3174 0, /* separator character */
3175 &hostlist_anchor, /* anchor pointer */
3176 &local_cache_bits, /* cache pointer */
3177 check_host, /* function for testing */
3178 &cb, /* argument for function */
3179 MCL_HOST, /* type of check */
8e669ac1 3180 (host_address == sender_host_address)?
d4eb88df
PH
3181 US"host" : host_address, /* text for debugging */
3182 valueptr); /* where to pass back data */
3183deliver_host_address = save_host_address;
8e669ac1 3184return rc;
059ec3d9
PH
3185}
3186
3187
3188
3189
5130845b
JH
3190/*************************************************
3191* Check the given host item matches a list *
3192*************************************************/
3193int
3194verify_check_given_host(uschar **listptr, host_item *host)
3195{
55414b25 3196return verify_check_this_host(CUSS listptr, NULL, host->name, host->address, NULL);
5130845b
JH
3197}
3198
059ec3d9
PH
3199/*************************************************
3200* Check the remote host matches a list *
3201*************************************************/
3202
3203/* This is a front end to verify_check_this_host(), created because checking
3204the remote host is a common occurrence. With luck, a good compiler will spot
3205the tail recursion and optimize it. If there's no host address, this is
3206command-line SMTP input - check against an empty string for the address.
3207
3208Arguments:
3209 listptr pointer to the host list
3210
3211Returns: the yield of verify_check_this_host(),
3212 i.e. OK, FAIL, or DEFER
3213*/
3214
3215int
3216verify_check_host(uschar **listptr)
3217{
55414b25 3218return verify_check_this_host(CUSS listptr, sender_host_cache, NULL,
059ec3d9
PH
3219 (sender_host_address == NULL)? US"" : sender_host_address, NULL);
3220}
3221
3222
3223
3224
3225
3226/*************************************************
83e029d5 3227* Invert an IP address *
059ec3d9
PH
3228*************************************************/
3229
83e029d5
PP
3230/* Originally just used for DNS xBL lists, now also used for the
3231reverse_ip expansion operator.
3232
059ec3d9
PH
3233Arguments:
3234 buffer where to put the answer
3235 address the address to invert
3236*/
3237
83e029d5 3238void
059ec3d9
PH
3239invert_address(uschar *buffer, uschar *address)
3240{
3241int bin[4];
3242uschar *bptr = buffer;
3243
3244/* If this is an IPv4 address mapped into IPv6 format, adjust the pointer
3245to the IPv4 part only. */
3246
3247if (Ustrncmp(address, "::ffff:", 7) == 0) address += 7;
3248
3249/* Handle IPv4 address: when HAVE_IPV6 is false, the result of host_aton() is
3250always 1. */
3251
3252if (host_aton(address, bin) == 1)
3253 {
3254 int i;
3255 int x = bin[0];
3256 for (i = 0; i < 4; i++)
3257 {
3258 sprintf(CS bptr, "%d.", x & 255);
3259 while (*bptr) bptr++;
3260 x >>= 8;
3261 }
3262 }
3263
3264/* Handle IPv6 address. Actually, as far as I know, there are no IPv6 addresses
3265in any DNS black lists, and the format in which they will be looked up is
3266unknown. This is just a guess. */
3267
3268#if HAVE_IPV6
3269else
3270 {
3271 int i, j;
3272 for (j = 3; j >= 0; j--)
3273 {
3274 int x = bin[j];
3275 for (i = 0; i < 8; i++)
3276 {
3277 sprintf(CS bptr, "%x.", x & 15);
3278 while (*bptr) bptr++;
3279 x >>= 4;
3280 }
3281 }
3282 }
3283#endif
d6f6e0dc
PH
3284
3285/* Remove trailing period -- this is needed so that both arbitrary
3286dnsbl keydomains and inverted addresses may be combined with the
3287same format string, "%s.%s" */
3288
3289*(--bptr) = 0;
059ec3d9
PH
3290}
3291
3292
3293
0bcb2a0e
PH
3294/*************************************************
3295* Perform a single dnsbl lookup *
3296*************************************************/
3297
d6f6e0dc
PH
3298/* This function is called from verify_check_dnsbl() below. It is also called
3299recursively from within itself when domain and domain_txt are different
3300pointers, in order to get the TXT record from the alternate domain.
0bcb2a0e
PH
3301
3302Arguments:
d6f6e0dc
PH
3303 domain the outer dnsbl domain
3304 domain_txt alternate domain to lookup TXT record on success; when the
3305 same domain is to be used, domain_txt == domain (that is,
3306 the pointers must be identical, not just the text)
8e669ac1 3307 keydomain the current keydomain (for debug message)
d6f6e0dc
PH
3308 prepend subdomain to lookup (like keydomain, but
3309 reversed if IP address)
3310 iplist the list of matching IP addresses, or NULL for "any"
8e669ac1 3311 bitmask true if bitmask matching is wanted
431b7361
PH
3312 match_type condition for 'succeed' result
3313 0 => Any RR in iplist (=)
3314 1 => No RR in iplist (!=)
3315 2 => All RRs in iplist (==)
3316 3 => Some RRs not in iplist (!==)
3317 the two bits are defined as MT_NOT and MT_ALL
8e669ac1 3318 defer_return what to return for a defer
0bcb2a0e
PH
3319
3320Returns: OK if lookup succeeded
3321 FAIL if not
3322*/
3323
3324static int
d6f6e0dc 3325one_check_dnsbl(uschar *domain, uschar *domain_txt, uschar *keydomain,
431b7361 3326 uschar *prepend, uschar *iplist, BOOL bitmask, int match_type,
d6f6e0dc 3327 int defer_return)
8e669ac1 3328{
0bcb2a0e
PH
3329dns_answer dnsa;
3330dns_scan dnss;
3331tree_node *t;
3332dnsbl_cache_block *cb;
3333int old_pool = store_pool;
d6f6e0dc
PH
3334uschar query[256]; /* DNS domain max length */
3335
3336/* Construct the specific query domainname */
3337
3338if (!string_format(query, sizeof(query), "%s.%s", prepend, domain))
3339 {
3340 log_write(0, LOG_MAIN|LOG_PANIC, "dnslist query is too long "
3341 "(ignored): %s...", query);
3342 return FAIL;
3343 }
0bcb2a0e
PH
3344
3345/* Look for this query in the cache. */
3346
14b3c5bc
JH
3347if ( (t = tree_search(dnsbl_cache, query))
3348 && (cb = t->data.ptr)->expiry > time(NULL)
3349 )
3350
3351/* Previous lookup was cached */
3352
3353 {
3354 HDEBUG(D_dnsbl) debug_printf("using result of previous DNS lookup\n");
3355 }
0bcb2a0e
PH
3356
3357/* If not cached from a previous lookup, we must do a DNS lookup, and
3358cache the result in permanent memory. */
3359
14b3c5bc 3360else
0bcb2a0e 3361 {
e162fc97 3362 uint ttl = 3600;
14b3c5bc 3363
0bcb2a0e
PH
3364 store_pool = POOL_PERM;
3365
14b3c5bc
JH
3366 if (t)
3367 {
3368 HDEBUG(D_dnsbl) debug_printf("cached data found but past valid time; ");
3369 }
0bcb2a0e 3370
14b3c5bc
JH
3371 else
3372 { /* Set up a tree entry to cache the lookup */
3373 t = store_get(sizeof(tree_node) + Ustrlen(query));
3374 Ustrcpy(t->name, query);
3375 t->data.ptr = cb = store_get(sizeof(dnsbl_cache_block));
3376 (void)tree_insertnode(&dnsbl_cache, t);
3377 }
0bcb2a0e 3378
4c04137d 3379 /* Do the DNS lookup . */
0bcb2a0e
PH
3380
3381 HDEBUG(D_dnsbl) debug_printf("new DNS lookup for %s\n", query);
3382 cb->rc = dns_basic_lookup(&dnsa, query, T_A);
3383 cb->text_set = FALSE;
3384 cb->text = NULL;
3385 cb->rhs = NULL;
3386
3387 /* If the lookup succeeded, cache the RHS address. The code allows for
3388 more than one address - this was for complete generality and the possible
3389 use of A6 records. However, A6 records have been reduced to experimental
3390 status (August 2001) and may die out. So they may never get used at all,
3391 let alone in dnsbl records. However, leave the code here, just in case.
3392
3393 Quite apart from one A6 RR generating multiple addresses, there are DNS
3394 lists that return more than one A record, so we must handle multiple
e162fc97
JH
3395 addresses generated in that way as well.
3396
3397 Mark the cache entry with the "now" plus the minimum of the address TTLs,
3398 or some suitably far-future time if none were found. */
0bcb2a0e
PH
3399
3400 if (cb->rc == DNS_SUCCEED)
3401 {
3402 dns_record *rr;
3403 dns_address **addrp = &(cb->rhs);
3404 for (rr = dns_next_rr(&dnsa, &dnss, RESET_ANSWERS);
e1a3f32f 3405 rr;
0bcb2a0e 3406 rr = dns_next_rr(&dnsa, &dnss, RESET_NEXT))
0bcb2a0e
PH
3407 if (rr->type == T_A)
3408 {
3409 dns_address *da = dns_address_from_rr(&dnsa, rr);
e1a3f32f 3410 if (da)
0bcb2a0e
PH
3411 {
3412 *addrp = da;
2d0dc929
JH
3413 while (da->next) da = da->next;
3414 addrp = &da->next;
14b3c5bc 3415 if (ttl > rr->ttl) ttl = rr->ttl;
0bcb2a0e
PH
3416 }
3417 }
0bcb2a0e
PH
3418
3419 /* If we didn't find any A records, change the return code. This can
3420 happen when there is a CNAME record but there are no A records for what
3421 it points to. */
3422
2d0dc929 3423 if (!cb->rhs) cb->rc = DNS_NODATA;
0bcb2a0e
PH
3424 }
3425
14b3c5bc 3426 cb->expiry = time(NULL)+ttl;
0bcb2a0e
PH
3427 store_pool = old_pool;
3428 }
3429
0bcb2a0e
PH
3430/* We now have the result of the DNS lookup, either newly done, or cached
3431from a previous call. If the lookup succeeded, check against the address
3432list if there is one. This may be a positive equality list (introduced by
3433"="), a negative equality list (introduced by "!="), a positive bitmask
3434list (introduced by "&"), or a negative bitmask list (introduced by "!&").*/
3435
3436if (cb->rc == DNS_SUCCEED)
3437 {
3438 dns_address *da = NULL;
3439 uschar *addlist = cb->rhs->address;
3440
3441 /* For A and AAAA records, there may be multiple addresses from multiple
3442 records. For A6 records (currently not expected to be used) there may be
3443 multiple addresses from a single record. */
3444
2d0dc929 3445 for (da = cb->rhs->next; da; da = da->next)
0bcb2a0e
PH
3446 addlist = string_sprintf("%s, %s", addlist, da->address);
3447
3448 HDEBUG(D_dnsbl) debug_printf("DNS lookup for %s succeeded (yielding %s)\n",
3449 query, addlist);
3450
3451 /* Address list check; this can be either for equality, or via a bitmask.
3452 In the latter case, all the bits must match. */
3453
2d0dc929 3454 if (iplist)
0bcb2a0e 3455 {
2d0dc929 3456 for (da = cb->rhs; da; da = da->next)
0bcb2a0e 3457 {
431b7361
PH
3458 int ipsep = ',';
3459 uschar ip[46];
55414b25 3460 const uschar *ptr = iplist;
431b7361
PH
3461 uschar *res;
3462
0bcb2a0e 3463 /* Handle exact matching */
431b7361 3464
0bcb2a0e 3465 if (!bitmask)
2d0dc929
JH
3466 {
3467 while ((res = string_nextinlist(&ptr, &ipsep, ip, sizeof(ip))))
3468 if (Ustrcmp(CS da->address, ip) == 0)
3469 break;
3470 }
431b7361 3471
0bcb2a0e 3472 /* Handle bitmask matching */
431b7361 3473
0bcb2a0e
PH
3474 else
3475 {
3476 int address[4];
3477 int mask = 0;
3478
3479 /* At present, all known DNS blocking lists use A records, with
3480 IPv4 addresses on the RHS encoding the information they return. I
3481 wonder if this will linger on as the last vestige of IPv4 when IPv6
3482 is ubiquitous? Anyway, for now we use paranoia code to completely
3483 ignore IPv6 addresses. The default mask is 0, which always matches.
3484 We change this only for IPv4 addresses in the list. */
3485
431b7361 3486 if (host_aton(da->address, address) == 1) mask = address[0];
0bcb2a0e
PH
3487
3488 /* Scan the returned addresses, skipping any that are IPv6 */
3489
2d0dc929 3490 while ((res = string_nextinlist(&ptr, &ipsep, ip, sizeof(ip))))
0bcb2a0e 3491 {
431b7361
PH
3492 if (host_aton(ip, address) != 1) continue;
3493 if ((address[0] & mask) == address[0]) break;
0bcb2a0e
PH
3494 }
3495 }
3496
431b7361
PH
3497 /* If either
3498
3499 (a) An IP address in an any ('=') list matched, or
3500 (b) No IP address in an all ('==') list matched
0bcb2a0e 3501
431b7361
PH
3502 then we're done searching. */
3503
3504 if (((match_type & MT_ALL) != 0) == (res == NULL)) break;
0bcb2a0e
PH
3505 }
3506
431b7361 3507 /* If da == NULL, either
0bcb2a0e 3508
431b7361
PH
3509 (a) No IP address in an any ('=') list matched, or
3510 (b) An IP address in an all ('==') list didn't match
0bcb2a0e 3511
431b7361
PH
3512 so behave as if the DNSBL lookup had not succeeded, i.e. the host is not on
3513 the list. */
0bcb2a0e 3514
431b7361 3515 if ((match_type == MT_NOT || match_type == MT_ALL) != (da == NULL))
0bcb2a0e
PH
3516 {
3517 HDEBUG(D_dnsbl)
3518 {
431b7361
PH
3519 uschar *res = NULL;
3520 switch(match_type)
3521 {
3522 case 0:
2d0dc929 3523 res = US"was no match"; break;
431b7361 3524 case MT_NOT:
2d0dc929 3525 res = US"was an exclude match"; break;
431b7361 3526 case MT_ALL:
2d0dc929 3527 res = US"was an IP address that did not match"; break;
431b7361 3528 case MT_NOT|MT_ALL:
2d0dc929 3529 res = US"were no IP addresses that did not match"; break;
431b7361 3530 }
0bcb2a0e 3531 debug_printf("=> but we are not accepting this block class because\n");
431b7361
PH
3532 debug_printf("=> there %s for %s%c%s\n",
3533 res,
3534 ((match_type & MT_ALL) == 0)? "" : "=",
3535 bitmask? '&' : '=', iplist);
0bcb2a0e 3536 }
8e669ac1 3537 return FAIL;
0bcb2a0e
PH
3538 }
3539 }
3540
d6f6e0dc
PH
3541 /* Either there was no IP list, or the record matched, implying that the
3542 domain is on the list. We now want to find a corresponding TXT record. If an
3543 alternate domain is specified for the TXT record, call this function
3544 recursively to look that up; this has the side effect of re-checking that
3545 there is indeed an A record at the alternate domain. */
3546
3547 if (domain_txt != domain)
3548 return one_check_dnsbl(domain_txt, domain_txt, keydomain, prepend, NULL,
431b7361 3549 FALSE, match_type, defer_return);
d6f6e0dc
PH
3550
3551 /* If there is no alternate domain, look up a TXT record in the main domain
3552 if it has not previously been cached. */
0bcb2a0e
PH
3553
3554 if (!cb->text_set)
3555 {
3556 cb->text_set = TRUE;
3557 if (dns_basic_lookup(&dnsa, query, T_TXT) == DNS_SUCCEED)
3558 {
3559 dns_record *rr;
3560 for (rr = dns_next_rr(&dnsa, &dnss, RESET_ANSWERS);
2d0dc929 3561 rr;
0bcb2a0e
PH
3562 rr = dns_next_rr(&dnsa, &dnss, RESET_NEXT))
3563 if (rr->type == T_TXT) break;
2d0dc929 3564 if (rr)
0bcb2a0e
PH
3565 {
3566 int len = (rr->data)[0];
3567 if (len > 511) len = 127;
3568 store_pool = POOL_PERM;
2d0dc929 3569 cb->text = string_sprintf("%.*s", len, CUS (rr->data+1));
0bcb2a0e
PH
3570 store_pool = old_pool;
3571 }
3572 }
3573 }
3574
3575 dnslist_value = addlist;
3576 dnslist_text = cb->text;
3577 return OK;
3578 }
3579
3580/* There was a problem with the DNS lookup */
3581
3582if (cb->rc != DNS_NOMATCH && cb->rc != DNS_NODATA)
3583 {
3584 log_write(L_dnslist_defer, LOG_MAIN,
3585 "DNS list lookup defer (probably timeout) for %s: %s", query,
3586 (defer_return == OK)? US"assumed in list" :
3587 (defer_return == FAIL)? US"assumed not in list" :
3588 US"returned DEFER");
3589 return defer_return;
3590 }
3591
3592/* No entry was found in the DNS; continue for next domain */
3593
3594HDEBUG(D_dnsbl)
3595 {
3596 debug_printf("DNS lookup for %s failed\n", query);
3597 debug_printf("=> that means %s is not listed at %s\n",
3598 keydomain, domain);
3599 }
3600
3601return FAIL;
3602}
3603
3604
3605
3606
059ec3d9
PH
3607/*************************************************
3608* Check host against DNS black lists *
3609*************************************************/
3610
3611/* This function runs checks against a list of DNS black lists, until one
3612matches. Each item on the list can be of the form
3613
3614 domain=ip-address/key
3615
3616The domain is the right-most domain that is used for the query, for example,
3617blackholes.mail-abuse.org. If the IP address is present, there is a match only
3618if the DNS lookup returns a matching IP address. Several addresses may be
3619given, comma-separated, for example: x.y.z=127.0.0.1,127.0.0.2.
3620
3621If no key is given, what is looked up in the domain is the inverted IP address
3622of the current client host. If a key is given, it is used to construct the
d6f6e0dc 3623domain for the lookup. For example:
059ec3d9
PH
3624
3625 dsn.rfc-ignorant.org/$sender_address_domain
3626
3627After finding a match in the DNS, the domain is placed in $dnslist_domain, and
3628then we check for a TXT record for an error message, and if found, save its
3629value in $dnslist_text. We also cache everything in a tree, to optimize
3630multiple lookups.
3631
d6f6e0dc
PH
3632The TXT record is normally looked up in the same domain as the A record, but
3633when many lists are combined in a single DNS domain, this will not be a very
3634specific message. It is possible to specify a different domain for looking up
3635TXT records; this is given before the main domain, comma-separated. For
3636example:
3637
3638 dnslists = http.dnsbl.sorbs.net,dnsbl.sorbs.net=127.0.0.2 : \
3639 socks.dnsbl.sorbs.net,dnsbl.sorbs.net=127.0.0.3
3640
3641The caching ensures that only one lookup in dnsbl.sorbs.net is done.
3642
059ec3d9
PH
3643Note: an address for testing RBL is 192.203.178.39
3644Note: an address for testing DUL is 192.203.178.4
3645Note: a domain for testing RFCI is example.tld.dsn.rfc-ignorant.org
3646
3647Arguments:
379ba7d0 3648 where the acl type
059ec3d9 3649 listptr the domain/address/data list
379ba7d0 3650 log_msgptr log message on error
059ec3d9
PH
3651
3652Returns: OK successful lookup (i.e. the address is on the list), or
3653 lookup deferred after +include_unknown
3654 FAIL name not found, or no data found for the given type, or
3655 lookup deferred after +exclude_unknown (default)
3656 DEFER lookup failure, if +defer_unknown was set
3657*/
3658
3659int
379ba7d0 3660verify_check_dnsbl(int where, const uschar ** listptr, uschar ** log_msgptr)
059ec3d9
PH
3661{
3662int sep = 0;
3663int defer_return = FAIL;
55414b25 3664const uschar *list = *listptr;
059ec3d9
PH
3665uschar *domain;
3666uschar *s;
3667uschar buffer[1024];
059ec3d9
PH
3668uschar revadd[128]; /* Long enough for IPv6 address */
3669
3670/* Indicate that the inverted IP address is not yet set up */
3671
3672revadd[0] = 0;
3673
0bcb2a0e
PH
3674/* In case this is the first time the DNS resolver is being used. */
3675
8c51eead 3676dns_init(FALSE, FALSE, FALSE); /*XXX dnssec? */
0bcb2a0e 3677
059ec3d9
PH
3678/* Loop through all the domains supplied, until something matches */
3679
3680while ((domain = string_nextinlist(&list, &sep, buffer, sizeof(buffer))) != NULL)
3681 {
0bcb2a0e 3682 int rc;
059ec3d9 3683 BOOL bitmask = FALSE;
431b7361 3684 int match_type = 0;
d6f6e0dc
PH
3685 uschar *domain_txt;
3686 uschar *comma;
059ec3d9
PH
3687 uschar *iplist;
3688 uschar *key;
059ec3d9
PH
3689
3690 HDEBUG(D_dnsbl) debug_printf("DNS list check: %s\n", domain);
3691
3692 /* Deal with special values that change the behaviour on defer */
3693
3694 if (domain[0] == '+')
3695 {
3696 if (strcmpic(domain, US"+include_unknown") == 0) defer_return = OK;
3697 else if (strcmpic(domain, US"+exclude_unknown") == 0) defer_return = FAIL;
3698 else if (strcmpic(domain, US"+defer_unknown") == 0) defer_return = DEFER;
3699 else
3700 log_write(0, LOG_MAIN|LOG_PANIC, "unknown item in dnslist (ignored): %s",
3701 domain);
3702 continue;
3703 }
3704
3705 /* See if there's explicit data to be looked up */
3706
379ba7d0 3707 if ((key = Ustrchr(domain, '/'))) *key++ = 0;
059ec3d9
PH
3708
3709 /* See if there's a list of addresses supplied after the domain name. This is
431b7361
PH
3710 introduced by an = or a & character; if preceded by = we require all matches
3711 and if preceded by ! we invert the result. */
059ec3d9 3712
379ba7d0 3713 if (!(iplist = Ustrchr(domain, '=')))
059ec3d9
PH
3714 {
3715 bitmask = TRUE;
3716 iplist = Ustrchr(domain, '&');
3717 }
3718
379ba7d0 3719 if (iplist) /* Found either = or & */
059ec3d9 3720 {
431b7361 3721 if (iplist > domain && iplist[-1] == '!') /* Handle preceding ! */
059ec3d9 3722 {
431b7361 3723 match_type |= MT_NOT;
059ec3d9
PH
3724 iplist[-1] = 0;
3725 }
431b7361
PH
3726
3727 *iplist++ = 0; /* Terminate domain, move on */
3728
3729 /* If we found = (bitmask == FALSE), check for == or =& */
3730
3731 if (!bitmask && (*iplist == '=' || *iplist == '&'))
3732 {
3733 bitmask = *iplist++ == '&';
3734 match_type |= MT_ALL;
3735 }
059ec3d9
PH
3736 }
3737
379ba7d0 3738
d6f6e0dc
PH
3739 /* If there is a comma in the domain, it indicates that a second domain for
3740 looking up TXT records is provided, before the main domain. Otherwise we must
3741 set domain_txt == domain. */
3742
3743 domain_txt = domain;
3744 comma = Ustrchr(domain, ',');
3745 if (comma != NULL)
3746 {
3747 *comma++ = 0;
3748 domain = comma;
3749 }
3750
059ec3d9
PH
3751 /* Check that what we have left is a sensible domain name. There is no reason
3752 why these domains should in fact use the same syntax as hosts and email
3753 domains, but in practice they seem to. However, there is little point in
3754 actually causing an error here, because that would no doubt hold up incoming
3755 mail. Instead, I'll just log it. */
3756
3757 for (s = domain; *s != 0; s++)
3758 {
09dcaba9 3759 if (!isalnum(*s) && *s != '-' && *s != '.' && *s != '_')
059ec3d9
PH
3760 {
3761 log_write(0, LOG_MAIN, "dnslists domain \"%s\" contains "
3762 "strange characters - is this right?", domain);
3763 break;
3764 }
3765 }
3766
d6f6e0dc
PH
3767 /* Check the alternate domain if present */
3768
3769 if (domain_txt != domain) for (s = domain_txt; *s != 0; s++)
3770 {
09dcaba9 3771 if (!isalnum(*s) && *s != '-' && *s != '.' && *s != '_')
d6f6e0dc
PH
3772 {
3773 log_write(0, LOG_MAIN, "dnslists domain \"%s\" contains "
3774 "strange characters - is this right?", domain_txt);
3775 break;
3776 }
3777 }
3778
8e669ac1 3779 /* If there is no key string, construct the query by adding the domain name
0bcb2a0e 3780 onto the inverted host address, and perform a single DNS lookup. */
8e669ac1 3781
059ec3d9
PH
3782 if (key == NULL)
3783 {
379ba7d0
JH
3784 if (where == ACL_WHERE_NOTSMTP_START || where == ACL_WHERE_NOTSMTP)
3785 {
3786 *log_msgptr = string_sprintf
3787 ("cannot test auto-keyed dnslists condition in %s ACL",
3788 acl_wherenames[where]);
3789 return ERROR;
3790 }
059ec3d9
PH
3791 if (sender_host_address == NULL) return FAIL; /* can never match */
3792 if (revadd[0] == 0) invert_address(revadd, sender_host_address);
d6f6e0dc 3793 rc = one_check_dnsbl(domain, domain_txt, sender_host_address, revadd,
431b7361 3794 iplist, bitmask, match_type, defer_return);
0bcb2a0e
PH
3795 if (rc == OK)
3796 {
d6f6e0dc 3797 dnslist_domain = string_copy(domain_txt);
93655c46 3798 dnslist_matched = string_copy(sender_host_address);
8e669ac1 3799 HDEBUG(D_dnsbl) debug_printf("=> that means %s is listed at %s\n",
d6f6e0dc 3800 sender_host_address, dnslist_domain);
0bcb2a0e 3801 }
0bcb2a0e 3802 if (rc != FAIL) return rc; /* OK or DEFER */
059ec3d9 3803 }
8e669ac1
PH
3804
3805 /* If there is a key string, it can be a list of domains or IP addresses to
0bcb2a0e 3806 be concatenated with the main domain. */
8e669ac1 3807
059ec3d9
PH
3808 else
3809 {
0bcb2a0e 3810 int keysep = 0;
8e669ac1
PH
3811 BOOL defer = FALSE;
3812 uschar *keydomain;
0bcb2a0e 3813 uschar keybuffer[256];
d6f6e0dc 3814 uschar keyrevadd[128];
8e669ac1 3815
55414b25 3816 while ((keydomain = string_nextinlist(CUSS &key, &keysep, keybuffer,
0bcb2a0e 3817 sizeof(keybuffer))) != NULL)
8e669ac1 3818 {
d6f6e0dc
PH
3819 uschar *prepend = keydomain;
3820
7e66e54d 3821 if (string_is_ip_address(keydomain, NULL) != 0)
059ec3d9 3822 {
0bcb2a0e 3823 invert_address(keyrevadd, keydomain);
d6f6e0dc 3824 prepend = keyrevadd;
059ec3d9 3825 }
8e669ac1 3826
d6f6e0dc 3827 rc = one_check_dnsbl(domain, domain_txt, keydomain, prepend, iplist,
431b7361 3828 bitmask, match_type, defer_return);
8e669ac1 3829
0bcb2a0e 3830 if (rc == OK)
059ec3d9 3831 {
d6f6e0dc 3832 dnslist_domain = string_copy(domain_txt);
93655c46 3833 dnslist_matched = string_copy(keydomain);
8e669ac1 3834 HDEBUG(D_dnsbl) debug_printf("=> that means %s is listed at %s\n",
d6f6e0dc 3835 keydomain, dnslist_domain);
8e669ac1 3836 return OK;
059ec3d9 3837 }
8e669ac1 3838
c38d6da9
PH
3839 /* If the lookup deferred, remember this fact. We keep trying the rest
3840 of the list to see if we get a useful result, and if we don't, we return
3841 DEFER at the end. */
059ec3d9 3842
c38d6da9 3843 if (rc == DEFER) defer = TRUE;
0bcb2a0e 3844 } /* continue with next keystring domain/address */
c38d6da9
PH
3845
3846 if (defer) return DEFER;
8e669ac1 3847 }
0bcb2a0e 3848 } /* continue with next dnsdb outer domain */
059ec3d9
PH
3849
3850return FAIL;
3851}
3852
511a6c14
JH
3853/* vi: aw ai sw=2
3854*/
059ec3d9 3855/* End of verify.c */