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