xref: /freebsd/contrib/unbound/iterator/iter_utils.c (revision e8e8c939350bdf3c228a411caa9660c607c27a11)
1 /*
2  * iterator/iter_utils.c - iterative resolver module utility functions.
3  *
4  * Copyright (c) 2007, NLnet Labs. All rights reserved.
5  *
6  * This software is open source.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  *
12  * Redistributions of source code must retain the above copyright notice,
13  * this list of conditions and the following disclaimer.
14  *
15  * Redistributions in binary form must reproduce the above copyright notice,
16  * this list of conditions and the following disclaimer in the documentation
17  * and/or other materials provided with the distribution.
18  *
19  * Neither the name of the NLNET LABS nor the names of its contributors may
20  * be used to endorse or promote products derived from this software without
21  * specific prior written permission.
22  *
23  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
24  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
25  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
26  * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
27  * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
28  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
29  * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
30  * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
31  * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
32  * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
33  * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
34  */
35 
36 /**
37  * \file
38  *
39  * This file contains functions to assist the iterator module.
40  * Configuration options. Forward zones.
41  */
42 #include "config.h"
43 #include "iterator/iter_utils.h"
44 #include "iterator/iterator.h"
45 #include "iterator/iter_hints.h"
46 #include "iterator/iter_fwd.h"
47 #include "iterator/iter_donotq.h"
48 #include "iterator/iter_delegpt.h"
49 #include "iterator/iter_priv.h"
50 #include "services/cache/infra.h"
51 #include "services/cache/dns.h"
52 #include "services/cache/rrset.h"
53 #include "util/net_help.h"
54 #include "util/module.h"
55 #include "util/log.h"
56 #include "util/config_file.h"
57 #include "util/regional.h"
58 #include "util/data/msgparse.h"
59 #include "util/data/dname.h"
60 #include "util/random.h"
61 #include "util/fptr_wlist.h"
62 #include "validator/val_anchor.h"
63 #include "validator/val_kcache.h"
64 #include "validator/val_kentry.h"
65 #include "validator/val_utils.h"
66 #include "validator/val_sigcrypt.h"
67 #include "ldns/sbuffer.h"
68 
69 /** time when nameserver glue is said to be 'recent' */
70 #define SUSPICION_RECENT_EXPIRY 86400
71 /** penalty to validation failed blacklisted IPs */
72 #define BLACKLIST_PENALTY (USEFUL_SERVER_TOP_TIMEOUT*4)
73 
74 /** fillup fetch policy array */
75 static void
76 fetch_fill(struct iter_env* ie, const char* str)
77 {
78 	char* s = (char*)str, *e;
79 	int i;
80 	for(i=0; i<ie->max_dependency_depth+1; i++) {
81 		ie->target_fetch_policy[i] = strtol(s, &e, 10);
82 		if(s == e)
83 			fatal_exit("cannot parse fetch policy number %s", s);
84 		s = e;
85 	}
86 }
87 
88 /** Read config string that represents the target fetch policy */
89 static int
90 read_fetch_policy(struct iter_env* ie, const char* str)
91 {
92 	int count = cfg_count_numbers(str);
93 	if(count < 1) {
94 		log_err("Cannot parse target fetch policy: \"%s\"", str);
95 		return 0;
96 	}
97 	ie->max_dependency_depth = count - 1;
98 	ie->target_fetch_policy = (int*)calloc(
99 		(size_t)ie->max_dependency_depth+1, sizeof(int));
100 	if(!ie->target_fetch_policy) {
101 		log_err("alloc fetch policy: out of memory");
102 		return 0;
103 	}
104 	fetch_fill(ie, str);
105 	return 1;
106 }
107 
108 int
109 iter_apply_cfg(struct iter_env* iter_env, struct config_file* cfg)
110 {
111 	int i;
112 	/* target fetch policy */
113 	if(!read_fetch_policy(iter_env, cfg->target_fetch_policy))
114 		return 0;
115 	for(i=0; i<iter_env->max_dependency_depth+1; i++)
116 		verbose(VERB_QUERY, "target fetch policy for level %d is %d",
117 			i, iter_env->target_fetch_policy[i]);
118 
119 	if(!iter_env->donotq)
120 		iter_env->donotq = donotq_create();
121 	if(!iter_env->donotq || !donotq_apply_cfg(iter_env->donotq, cfg)) {
122 		log_err("Could not set donotqueryaddresses");
123 		return 0;
124 	}
125 	if(!iter_env->priv)
126 		iter_env->priv = priv_create();
127 	if(!iter_env->priv || !priv_apply_cfg(iter_env->priv, cfg)) {
128 		log_err("Could not set private addresses");
129 		return 0;
130 	}
131 	iter_env->supports_ipv6 = cfg->do_ip6;
132 	iter_env->supports_ipv4 = cfg->do_ip4;
133 	return 1;
134 }
135 
136 /** filter out unsuitable targets
137  * @param iter_env: iterator environment with ipv6-support flag.
138  * @param env: module environment with infra cache.
139  * @param name: zone name
140  * @param namelen: length of name
141  * @param qtype: query type (host order).
142  * @param now: current time
143  * @param a: address in delegation point we are examining.
144  * @return an integer that signals the target suitability.
145  *	as follows:
146  *	-1: The address should be omitted from the list.
147  *	    Because:
148  *		o The address is bogus (DNSSEC validation failure).
149  *		o Listed as donotquery
150  *		o is ipv6 but no ipv6 support (in operating system).
151  *		o is ipv4 but no ipv4 support (in operating system).
152  *		o is lame
153  *	Otherwise, an rtt in milliseconds.
154  *	0 .. USEFUL_SERVER_TOP_TIMEOUT-1
155  *		The roundtrip time timeout estimate. less than 2 minutes.
156  *		Note that util/rtt.c has a MIN_TIMEOUT of 50 msec, thus
157  *		values 0 .. 49 are not used, unless that is changed.
158  *	USEFUL_SERVER_TOP_TIMEOUT
159  *		This value exactly is given for unresponsive blacklisted.
160  *	USEFUL_SERVER_TOP_TIMEOUT+1
161  *		For non-blacklisted servers: huge timeout, but has traffic.
162  *	USEFUL_SERVER_TOP_TIMEOUT*1 ..
163  *		parent-side lame servers get this penalty. A dispreferential
164  *		server. (lame in delegpt).
165  *	USEFUL_SERVER_TOP_TIMEOUT*2 ..
166  *		dnsseclame servers get penalty
167  *	USEFUL_SERVER_TOP_TIMEOUT*3 ..
168  *		recursion lame servers get penalty
169  *	UNKNOWN_SERVER_NICENESS
170  *		If no information is known about the server, this is
171  *		returned. 376 msec or so.
172  *	+BLACKLIST_PENALTY (of USEFUL_TOP_TIMEOUT*4) for dnssec failed IPs.
173  *
174  * When a final value is chosen that is dnsseclame ; dnsseclameness checking
175  * is turned off (so we do not discard the reply).
176  * When a final value is chosen that is recursionlame; RD bit is set on query.
177  * Because of the numbers this means recursionlame also have dnssec lameness
178  * checking turned off.
179  */
180 static int
181 iter_filter_unsuitable(struct iter_env* iter_env, struct module_env* env,
182 	uint8_t* name, size_t namelen, uint16_t qtype, time_t now,
183 	struct delegpt_addr* a)
184 {
185 	int rtt, lame, reclame, dnsseclame;
186 	if(a->bogus)
187 		return -1; /* address of server is bogus */
188 	if(donotq_lookup(iter_env->donotq, &a->addr, a->addrlen)) {
189 		log_addr(VERB_ALGO, "skip addr on the donotquery list",
190 			&a->addr, a->addrlen);
191 		return -1; /* server is on the donotquery list */
192 	}
193 	if(!iter_env->supports_ipv6 && addr_is_ip6(&a->addr, a->addrlen)) {
194 		return -1; /* there is no ip6 available */
195 	}
196 	if(!iter_env->supports_ipv4 && !addr_is_ip6(&a->addr, a->addrlen)) {
197 		return -1; /* there is no ip4 available */
198 	}
199 	/* check lameness - need zone , class info */
200 	if(infra_get_lame_rtt(env->infra_cache, &a->addr, a->addrlen,
201 		name, namelen, qtype, &lame, &dnsseclame, &reclame,
202 		&rtt, now)) {
203 		log_addr(VERB_ALGO, "servselect", &a->addr, a->addrlen);
204 		verbose(VERB_ALGO, "   rtt=%d%s%s%s%s", rtt,
205 			lame?" LAME":"",
206 			dnsseclame?" DNSSEC_LAME":"",
207 			reclame?" REC_LAME":"",
208 			a->lame?" ADDR_LAME":"");
209 		if(lame)
210 			return -1; /* server is lame */
211 		else if(rtt >= USEFUL_SERVER_TOP_TIMEOUT)
212 			/* server is unresponsive,
213 			 * we used to return TOP_TIMOUT, but fairly useless,
214 			 * because if == TOP_TIMEOUT is dropped because
215 			 * blacklisted later, instead, remove it here, so
216 			 * other choices (that are not blacklisted) can be
217 			 * tried */
218 			return -1;
219 		/* select remainder from worst to best */
220 		else if(reclame)
221 			return rtt+USEFUL_SERVER_TOP_TIMEOUT*3; /* nonpref */
222 		else if(dnsseclame || a->dnsseclame)
223 			return rtt+USEFUL_SERVER_TOP_TIMEOUT*2; /* nonpref */
224 		else if(a->lame)
225 			return rtt+USEFUL_SERVER_TOP_TIMEOUT+1; /* nonpref */
226 		else	return rtt;
227 	}
228 	/* no server information present */
229 	if(a->dnsseclame)
230 		return UNKNOWN_SERVER_NICENESS+USEFUL_SERVER_TOP_TIMEOUT*2; /* nonpref */
231 	else if(a->lame)
232 		return USEFUL_SERVER_TOP_TIMEOUT+1+UNKNOWN_SERVER_NICENESS; /* nonpref */
233 	return UNKNOWN_SERVER_NICENESS;
234 }
235 
236 /** lookup RTT information, and also store fastest rtt (if any) */
237 static int
238 iter_fill_rtt(struct iter_env* iter_env, struct module_env* env,
239 	uint8_t* name, size_t namelen, uint16_t qtype, time_t now,
240 	struct delegpt* dp, int* best_rtt, struct sock_list* blacklist)
241 {
242 	int got_it = 0;
243 	struct delegpt_addr* a;
244 	if(dp->bogus)
245 		return 0; /* NS bogus, all bogus, nothing found */
246 	for(a=dp->result_list; a; a = a->next_result) {
247 		a->sel_rtt = iter_filter_unsuitable(iter_env, env,
248 			name, namelen, qtype, now, a);
249 		if(a->sel_rtt != -1) {
250 			if(sock_list_find(blacklist, &a->addr, a->addrlen))
251 				a->sel_rtt += BLACKLIST_PENALTY;
252 
253 			if(!got_it) {
254 				*best_rtt = a->sel_rtt;
255 				got_it = 1;
256 			} else if(a->sel_rtt < *best_rtt) {
257 				*best_rtt = a->sel_rtt;
258 			}
259 		}
260 	}
261 	return got_it;
262 }
263 
264 /** filter the addres list, putting best targets at front,
265  * returns number of best targets (or 0, no suitable targets) */
266 static int
267 iter_filter_order(struct iter_env* iter_env, struct module_env* env,
268 	uint8_t* name, size_t namelen, uint16_t qtype, time_t now,
269 	struct delegpt* dp, int* selected_rtt, int open_target,
270 	struct sock_list* blacklist)
271 {
272 	int got_num = 0, low_rtt = 0, swap_to_front;
273 	struct delegpt_addr* a, *n, *prev=NULL;
274 
275 	/* fillup sel_rtt and find best rtt in the bunch */
276 	got_num = iter_fill_rtt(iter_env, env, name, namelen, qtype, now, dp,
277 		&low_rtt, blacklist);
278 	if(got_num == 0)
279 		return 0;
280 	if(low_rtt >= USEFUL_SERVER_TOP_TIMEOUT &&
281 		(delegpt_count_missing_targets(dp) > 0 || open_target > 0)) {
282 		verbose(VERB_ALGO, "Bad choices, trying to get more choice");
283 		return 0; /* we want more choice. The best choice is a bad one.
284 			     return 0 to force the caller to fetch more */
285 	}
286 
287 	got_num = 0;
288 	a = dp->result_list;
289 	while(a) {
290 		/* skip unsuitable targets */
291 		if(a->sel_rtt == -1) {
292 			prev = a;
293 			a = a->next_result;
294 			continue;
295 		}
296 		/* classify the server address and determine what to do */
297 		swap_to_front = 0;
298 		if(a->sel_rtt >= low_rtt && a->sel_rtt - low_rtt <= RTT_BAND) {
299 			got_num++;
300 			swap_to_front = 1;
301 		} else if(a->sel_rtt<low_rtt && low_rtt-a->sel_rtt<=RTT_BAND) {
302 			got_num++;
303 			swap_to_front = 1;
304 		}
305 		/* swap to front if necessary, or move to next result */
306 		if(swap_to_front && prev) {
307 			n = a->next_result;
308 			prev->next_result = n;
309 			a->next_result = dp->result_list;
310 			dp->result_list = a;
311 			a = n;
312 		} else {
313 			prev = a;
314 			a = a->next_result;
315 		}
316 	}
317 	*selected_rtt = low_rtt;
318 	return got_num;
319 }
320 
321 struct delegpt_addr*
322 iter_server_selection(struct iter_env* iter_env,
323 	struct module_env* env, struct delegpt* dp,
324 	uint8_t* name, size_t namelen, uint16_t qtype, int* dnssec_lame,
325 	int* chase_to_rd, int open_target, struct sock_list* blacklist)
326 {
327 	int sel;
328 	int selrtt;
329 	struct delegpt_addr* a, *prev;
330 	int num = iter_filter_order(iter_env, env, name, namelen, qtype,
331 		*env->now, dp, &selrtt, open_target, blacklist);
332 
333 	if(num == 0)
334 		return NULL;
335 	verbose(VERB_ALGO, "selrtt %d", selrtt);
336 	if(selrtt > BLACKLIST_PENALTY) {
337 		if(selrtt-BLACKLIST_PENALTY > USEFUL_SERVER_TOP_TIMEOUT*3) {
338 			verbose(VERB_ALGO, "chase to "
339 				"blacklisted recursion lame server");
340 			*chase_to_rd = 1;
341 		}
342 		if(selrtt-BLACKLIST_PENALTY > USEFUL_SERVER_TOP_TIMEOUT*2) {
343 			verbose(VERB_ALGO, "chase to "
344 				"blacklisted dnssec lame server");
345 			*dnssec_lame = 1;
346 		}
347 	} else {
348 		if(selrtt > USEFUL_SERVER_TOP_TIMEOUT*3) {
349 			verbose(VERB_ALGO, "chase to recursion lame server");
350 			*chase_to_rd = 1;
351 		}
352 		if(selrtt > USEFUL_SERVER_TOP_TIMEOUT*2) {
353 			verbose(VERB_ALGO, "chase to dnssec lame server");
354 			*dnssec_lame = 1;
355 		}
356 		if(selrtt == USEFUL_SERVER_TOP_TIMEOUT) {
357 			verbose(VERB_ALGO, "chase to blacklisted lame server");
358 			return NULL;
359 		}
360 	}
361 
362 	if(num == 1) {
363 		a = dp->result_list;
364 		if(++a->attempts < OUTBOUND_MSG_RETRY)
365 			return a;
366 		dp->result_list = a->next_result;
367 		return a;
368 	}
369 
370 	/* randomly select a target from the list */
371 	log_assert(num > 1);
372 	/* grab secure random number, to pick unexpected server.
373 	 * also we need it to be threadsafe. */
374 	sel = ub_random_max(env->rnd, num);
375 	a = dp->result_list;
376 	prev = NULL;
377 	while(sel > 0 && a) {
378 		prev = a;
379 		a = a->next_result;
380 		sel--;
381 	}
382 	if(!a)  /* robustness */
383 		return NULL;
384 	if(++a->attempts < OUTBOUND_MSG_RETRY)
385 		return a;
386 	/* remove it from the delegation point result list */
387 	if(prev)
388 		prev->next_result = a->next_result;
389 	else	dp->result_list = a->next_result;
390 	return a;
391 }
392 
393 struct dns_msg*
394 dns_alloc_msg(sldns_buffer* pkt, struct msg_parse* msg,
395 	struct regional* region)
396 {
397 	struct dns_msg* m = (struct dns_msg*)regional_alloc(region,
398 		sizeof(struct dns_msg));
399 	if(!m)
400 		return NULL;
401 	memset(m, 0, sizeof(*m));
402 	if(!parse_create_msg(pkt, msg, NULL, &m->qinfo, &m->rep, region)) {
403 		log_err("malloc failure: allocating incoming dns_msg");
404 		return NULL;
405 	}
406 	return m;
407 }
408 
409 struct dns_msg*
410 dns_copy_msg(struct dns_msg* from, struct regional* region)
411 {
412 	struct dns_msg* m = (struct dns_msg*)regional_alloc(region,
413 		sizeof(struct dns_msg));
414 	if(!m)
415 		return NULL;
416 	m->qinfo = from->qinfo;
417 	if(!(m->qinfo.qname = regional_alloc_init(region, from->qinfo.qname,
418 		from->qinfo.qname_len)))
419 		return NULL;
420 	if(!(m->rep = reply_info_copy(from->rep, NULL, region)))
421 		return NULL;
422 	return m;
423 }
424 
425 void
426 iter_dns_store(struct module_env* env, struct query_info* msgqinf,
427 	struct reply_info* msgrep, int is_referral, time_t leeway, int pside,
428 	struct regional* region, uint16_t flags)
429 {
430 	if(!dns_cache_store(env, msgqinf, msgrep, is_referral, leeway,
431 		pside, region, flags))
432 		log_err("out of memory: cannot store data in cache");
433 }
434 
435 int
436 iter_ns_probability(struct ub_randstate* rnd, int n, int m)
437 {
438 	int sel;
439 	if(n == m) /* 100% chance */
440 		return 1;
441 	/* we do not need secure random numbers here, but
442 	 * we do need it to be threadsafe, so we use this */
443 	sel = ub_random_max(rnd, m);
444 	return (sel < n);
445 }
446 
447 /** detect dependency cycle for query and target */
448 static int
449 causes_cycle(struct module_qstate* qstate, uint8_t* name, size_t namelen,
450 	uint16_t t, uint16_t c)
451 {
452 	struct query_info qinf;
453 	qinf.qname = name;
454 	qinf.qname_len = namelen;
455 	qinf.qtype = t;
456 	qinf.qclass = c;
457 	fptr_ok(fptr_whitelist_modenv_detect_cycle(
458 		qstate->env->detect_cycle));
459 	return (*qstate->env->detect_cycle)(qstate, &qinf,
460 		(uint16_t)(BIT_RD|BIT_CD), qstate->is_priming,
461 		qstate->is_valrec);
462 }
463 
464 void
465 iter_mark_cycle_targets(struct module_qstate* qstate, struct delegpt* dp)
466 {
467 	struct delegpt_ns* ns;
468 	for(ns = dp->nslist; ns; ns = ns->next) {
469 		if(ns->resolved)
470 			continue;
471 		/* see if this ns as target causes dependency cycle */
472 		if(causes_cycle(qstate, ns->name, ns->namelen,
473 			LDNS_RR_TYPE_AAAA, qstate->qinfo.qclass) ||
474 		   causes_cycle(qstate, ns->name, ns->namelen,
475 			LDNS_RR_TYPE_A, qstate->qinfo.qclass)) {
476 			log_nametypeclass(VERB_QUERY, "skipping target due "
477 			 	"to dependency cycle (harden-glue: no may "
478 				"fix some of the cycles)",
479 				ns->name, LDNS_RR_TYPE_A,
480 				qstate->qinfo.qclass);
481 			ns->resolved = 1;
482 		}
483 	}
484 }
485 
486 void
487 iter_mark_pside_cycle_targets(struct module_qstate* qstate, struct delegpt* dp)
488 {
489 	struct delegpt_ns* ns;
490 	for(ns = dp->nslist; ns; ns = ns->next) {
491 		if(ns->done_pside4 && ns->done_pside6)
492 			continue;
493 		/* see if this ns as target causes dependency cycle */
494 		if(causes_cycle(qstate, ns->name, ns->namelen,
495 			LDNS_RR_TYPE_A, qstate->qinfo.qclass)) {
496 			log_nametypeclass(VERB_QUERY, "skipping target due "
497 			 	"to dependency cycle", ns->name,
498 				LDNS_RR_TYPE_A, qstate->qinfo.qclass);
499 			ns->done_pside4 = 1;
500 		}
501 		if(causes_cycle(qstate, ns->name, ns->namelen,
502 			LDNS_RR_TYPE_AAAA, qstate->qinfo.qclass)) {
503 			log_nametypeclass(VERB_QUERY, "skipping target due "
504 			 	"to dependency cycle", ns->name,
505 				LDNS_RR_TYPE_AAAA, qstate->qinfo.qclass);
506 			ns->done_pside6 = 1;
507 		}
508 	}
509 }
510 
511 int
512 iter_dp_is_useless(struct query_info* qinfo, uint16_t qflags,
513 	struct delegpt* dp)
514 {
515 	struct delegpt_ns* ns;
516 	/* check:
517 	 *      o RD qflag is on.
518 	 *      o no addresses are provided.
519 	 *      o all NS items are required glue.
520 	 * OR
521 	 *      o RD qflag is on.
522 	 *      o no addresses are provided.
523 	 *      o the query is for one of the nameservers in dp,
524 	 *        and that nameserver is a glue-name for this dp.
525 	 */
526 	if(!(qflags&BIT_RD))
527 		return 0;
528 	/* either available or unused targets */
529 	if(dp->usable_list || dp->result_list)
530 		return 0;
531 
532 	/* see if query is for one of the nameservers, which is glue */
533 	if( (qinfo->qtype == LDNS_RR_TYPE_A ||
534 		qinfo->qtype == LDNS_RR_TYPE_AAAA) &&
535 		dname_subdomain_c(qinfo->qname, dp->name) &&
536 		delegpt_find_ns(dp, qinfo->qname, qinfo->qname_len))
537 		return 1;
538 
539 	for(ns = dp->nslist; ns; ns = ns->next) {
540 		if(ns->resolved) /* skip failed targets */
541 			continue;
542 		if(!dname_subdomain_c(ns->name, dp->name))
543 			return 0; /* one address is not required glue */
544 	}
545 	return 1;
546 }
547 
548 int
549 iter_indicates_dnssec(struct module_env* env, struct delegpt* dp,
550         struct dns_msg* msg, uint16_t dclass)
551 {
552 	struct trust_anchor* a;
553 	/* information not available, !env->anchors can be common */
554 	if(!env || !env->anchors || !dp || !dp->name)
555 		return 0;
556 	/* a trust anchor exists with this name, RRSIGs expected */
557 	if((a=anchor_find(env->anchors, dp->name, dp->namelabs, dp->namelen,
558 		dclass))) {
559 		lock_basic_unlock(&a->lock);
560 		return 1;
561 	}
562 	/* see if DS rrset was given, in AUTH section */
563 	if(msg && msg->rep &&
564 		reply_find_rrset_section_ns(msg->rep, dp->name, dp->namelen,
565 		LDNS_RR_TYPE_DS, dclass))
566 		return 1;
567 	/* look in key cache */
568 	if(env->key_cache) {
569 		struct key_entry_key* kk = key_cache_obtain(env->key_cache,
570 			dp->name, dp->namelen, dclass, env->scratch, *env->now);
571 		if(kk) {
572 			if(query_dname_compare(kk->name, dp->name) == 0) {
573 			  if(key_entry_isgood(kk) || key_entry_isbad(kk)) {
574 				regional_free_all(env->scratch);
575 				return 1;
576 			  } else if(key_entry_isnull(kk)) {
577 				regional_free_all(env->scratch);
578 				return 0;
579 			  }
580 			}
581 			regional_free_all(env->scratch);
582 		}
583 	}
584 	return 0;
585 }
586 
587 int
588 iter_msg_has_dnssec(struct dns_msg* msg)
589 {
590 	size_t i;
591 	if(!msg || !msg->rep)
592 		return 0;
593 	for(i=0; i<msg->rep->an_numrrsets + msg->rep->ns_numrrsets; i++) {
594 		if(((struct packed_rrset_data*)msg->rep->rrsets[i]->
595 			entry.data)->rrsig_count > 0)
596 			return 1;
597 	}
598 	/* empty message has no DNSSEC info, with DNSSEC the reply is
599 	 * not empty (NSEC) */
600 	return 0;
601 }
602 
603 int iter_msg_from_zone(struct dns_msg* msg, struct delegpt* dp,
604         enum response_type type, uint16_t dclass)
605 {
606 	if(!msg || !dp || !msg->rep || !dp->name)
607 		return 0;
608 	/* SOA RRset - always from reply zone */
609 	if(reply_find_rrset_section_an(msg->rep, dp->name, dp->namelen,
610 		LDNS_RR_TYPE_SOA, dclass) ||
611 	   reply_find_rrset_section_ns(msg->rep, dp->name, dp->namelen,
612 		LDNS_RR_TYPE_SOA, dclass))
613 		return 1;
614 	if(type == RESPONSE_TYPE_REFERRAL) {
615 		size_t i;
616 		/* if it adds a single label, i.e. we expect .com,
617 		 * and referral to example.com. NS ... , then origin zone
618 		 * is .com. For a referral to sub.example.com. NS ... then
619 		 * we do not know, since example.com. may be in between. */
620 		for(i=0; i<msg->rep->an_numrrsets+msg->rep->ns_numrrsets;
621 			i++) {
622 			struct ub_packed_rrset_key* s = msg->rep->rrsets[i];
623 			if(ntohs(s->rk.type) == LDNS_RR_TYPE_NS &&
624 				ntohs(s->rk.rrset_class) == dclass) {
625 				int l = dname_count_labels(s->rk.dname);
626 				if(l == dp->namelabs + 1 &&
627 					dname_strict_subdomain(s->rk.dname,
628 					l, dp->name, dp->namelabs))
629 					return 1;
630 			}
631 		}
632 		return 0;
633 	}
634 	log_assert(type==RESPONSE_TYPE_ANSWER || type==RESPONSE_TYPE_CNAME);
635 	/* not a referral, and not lame delegation (upwards), so,
636 	 * any NS rrset must be from the zone itself */
637 	if(reply_find_rrset_section_an(msg->rep, dp->name, dp->namelen,
638 		LDNS_RR_TYPE_NS, dclass) ||
639 	   reply_find_rrset_section_ns(msg->rep, dp->name, dp->namelen,
640 		LDNS_RR_TYPE_NS, dclass))
641 		return 1;
642 	/* a DNSKEY set is expected at the zone apex as well */
643 	/* this is for 'minimal responses' for DNSKEYs */
644 	if(reply_find_rrset_section_an(msg->rep, dp->name, dp->namelen,
645 		LDNS_RR_TYPE_DNSKEY, dclass))
646 		return 1;
647 	return 0;
648 }
649 
650 /**
651  * check equality of two rrsets
652  * @param k1: rrset
653  * @param k2: rrset
654  * @return true if equal
655  */
656 static int
657 rrset_equal(struct ub_packed_rrset_key* k1, struct ub_packed_rrset_key* k2)
658 {
659 	struct packed_rrset_data* d1 = (struct packed_rrset_data*)
660 		k1->entry.data;
661 	struct packed_rrset_data* d2 = (struct packed_rrset_data*)
662 		k2->entry.data;
663 	size_t i, t;
664 	if(k1->rk.dname_len != k2->rk.dname_len ||
665 		k1->rk.flags != k2->rk.flags ||
666 		k1->rk.type != k2->rk.type ||
667 		k1->rk.rrset_class != k2->rk.rrset_class ||
668 		query_dname_compare(k1->rk.dname, k2->rk.dname) != 0)
669 		return 0;
670 	if(	/* do not check ttl: d1->ttl != d2->ttl || */
671 		d1->count != d2->count ||
672 		d1->rrsig_count != d2->rrsig_count ||
673 		d1->trust != d2->trust ||
674 		d1->security != d2->security)
675 		return 0;
676 	t = d1->count + d1->rrsig_count;
677 	for(i=0; i<t; i++) {
678 		if(d1->rr_len[i] != d2->rr_len[i] ||
679 			/* no ttl check: d1->rr_ttl[i] != d2->rr_ttl[i] ||*/
680 			memcmp(d1->rr_data[i], d2->rr_data[i],
681 				d1->rr_len[i]) != 0)
682 			return 0;
683 	}
684 	return 1;
685 }
686 
687 int
688 reply_equal(struct reply_info* p, struct reply_info* q, struct regional* region)
689 {
690 	size_t i;
691 	if(p->flags != q->flags ||
692 		p->qdcount != q->qdcount ||
693 		/* do not check TTL, this may differ */
694 		/*
695 		p->ttl != q->ttl ||
696 		p->prefetch_ttl != q->prefetch_ttl ||
697 		*/
698 		p->security != q->security ||
699 		p->an_numrrsets != q->an_numrrsets ||
700 		p->ns_numrrsets != q->ns_numrrsets ||
701 		p->ar_numrrsets != q->ar_numrrsets ||
702 		p->rrset_count != q->rrset_count)
703 		return 0;
704 	for(i=0; i<p->rrset_count; i++) {
705 		if(!rrset_equal(p->rrsets[i], q->rrsets[i])) {
706 			if(!rrset_canonical_equal(region, p->rrsets[i],
707 				q->rrsets[i])) {
708 				regional_free_all(region);
709 				return 0;
710 			}
711 			regional_free_all(region);
712 		}
713 	}
714 	return 1;
715 }
716 
717 void
718 caps_strip_reply(struct reply_info* rep)
719 {
720 	size_t i;
721 	if(!rep) return;
722 	/* see if message is a referral, in which case the additional and
723 	 * NS record cannot be removed */
724 	/* referrals have the AA flag unset (strict check, not elsewhere in
725 	 * unbound, but for 0x20 this is very convenient). */
726 	if(!(rep->flags&BIT_AA))
727 		return;
728 	/* remove the additional section from the reply */
729 	if(rep->ar_numrrsets != 0) {
730 		verbose(VERB_ALGO, "caps fallback: removing additional section");
731 		rep->rrset_count -= rep->ar_numrrsets;
732 		rep->ar_numrrsets = 0;
733 	}
734 	/* is there an NS set in the authority section to remove? */
735 	/* the failure case (Cisco firewalls) only has one rrset in authsec */
736 	for(i=rep->an_numrrsets; i<rep->an_numrrsets+rep->ns_numrrsets; i++) {
737 		struct ub_packed_rrset_key* s = rep->rrsets[i];
738 		if(ntohs(s->rk.type) == LDNS_RR_TYPE_NS) {
739 			/* remove NS rrset and break from loop (loop limits
740 			 * have changed) */
741 			/* move last rrset into this position (there is no
742 			 * additional section any more) */
743 			verbose(VERB_ALGO, "caps fallback: removing NS rrset");
744 			if(i < rep->rrset_count-1)
745 				rep->rrsets[i]=rep->rrsets[rep->rrset_count-1];
746 			rep->rrset_count --;
747 			rep->ns_numrrsets --;
748 			break;
749 		}
750 	}
751 }
752 
753 void
754 iter_store_parentside_rrset(struct module_env* env,
755 	struct ub_packed_rrset_key* rrset)
756 {
757 	struct rrset_ref ref;
758 	rrset = packed_rrset_copy_alloc(rrset, env->alloc, *env->now);
759 	if(!rrset) {
760 		log_err("malloc failure in store_parentside_rrset");
761 		return;
762 	}
763 	rrset->rk.flags |= PACKED_RRSET_PARENT_SIDE;
764 	rrset->entry.hash = rrset_key_hash(&rrset->rk);
765 	ref.key = rrset;
766 	ref.id = rrset->id;
767 	/* ignore ret: if it was in the cache, ref updated */
768 	(void)rrset_cache_update(env->rrset_cache, &ref, env->alloc, *env->now);
769 }
770 
771 /** fetch NS record from reply, if any */
772 static struct ub_packed_rrset_key*
773 reply_get_NS_rrset(struct reply_info* rep)
774 {
775 	size_t i;
776 	for(i=0; i<rep->rrset_count; i++) {
777 		if(rep->rrsets[i]->rk.type == htons(LDNS_RR_TYPE_NS)) {
778 			return rep->rrsets[i];
779 		}
780 	}
781 	return NULL;
782 }
783 
784 void
785 iter_store_parentside_NS(struct module_env* env, struct reply_info* rep)
786 {
787 	struct ub_packed_rrset_key* rrset = reply_get_NS_rrset(rep);
788 	if(rrset) {
789 		log_rrset_key(VERB_ALGO, "store parent-side NS", rrset);
790 		iter_store_parentside_rrset(env, rrset);
791 	}
792 }
793 
794 void iter_store_parentside_neg(struct module_env* env,
795         struct query_info* qinfo, struct reply_info* rep)
796 {
797 	/* TTL: NS from referral in iq->deleg_msg,
798 	 *      or first RR from iq->response,
799 	 *      or servfail5secs if !iq->response */
800 	time_t ttl = NORR_TTL;
801 	struct ub_packed_rrset_key* neg;
802 	struct packed_rrset_data* newd;
803 	if(rep) {
804 		struct ub_packed_rrset_key* rrset = reply_get_NS_rrset(rep);
805 		if(!rrset && rep->rrset_count != 0) rrset = rep->rrsets[0];
806 		if(rrset) ttl = ub_packed_rrset_ttl(rrset);
807 	}
808 	/* create empty rrset to store */
809 	neg = (struct ub_packed_rrset_key*)regional_alloc(env->scratch,
810 	                sizeof(struct ub_packed_rrset_key));
811 	if(!neg) {
812 		log_err("out of memory in store_parentside_neg");
813 		return;
814 	}
815 	memset(&neg->entry, 0, sizeof(neg->entry));
816 	neg->entry.key = neg;
817 	neg->rk.type = htons(qinfo->qtype);
818 	neg->rk.rrset_class = htons(qinfo->qclass);
819 	neg->rk.flags = 0;
820 	neg->rk.dname = regional_alloc_init(env->scratch, qinfo->qname,
821 		qinfo->qname_len);
822 	if(!neg->rk.dname) {
823 		log_err("out of memory in store_parentside_neg");
824 		return;
825 	}
826 	neg->rk.dname_len = qinfo->qname_len;
827 	neg->entry.hash = rrset_key_hash(&neg->rk);
828 	newd = (struct packed_rrset_data*)regional_alloc_zero(env->scratch,
829 		sizeof(struct packed_rrset_data) + sizeof(size_t) +
830 		sizeof(uint8_t*) + sizeof(time_t) + sizeof(uint16_t));
831 	if(!newd) {
832 		log_err("out of memory in store_parentside_neg");
833 		return;
834 	}
835 	neg->entry.data = newd;
836 	newd->ttl = ttl;
837 	/* entry must have one RR, otherwise not valid in cache.
838 	 * put in one RR with empty rdata: those are ignored as nameserver */
839 	newd->count = 1;
840 	newd->rrsig_count = 0;
841 	newd->trust = rrset_trust_ans_noAA;
842 	newd->rr_len = (size_t*)((uint8_t*)newd +
843 		sizeof(struct packed_rrset_data));
844 	newd->rr_len[0] = 0 /* zero len rdata */ + sizeof(uint16_t);
845 	packed_rrset_ptr_fixup(newd);
846 	newd->rr_ttl[0] = newd->ttl;
847 	sldns_write_uint16(newd->rr_data[0], 0 /* zero len rdata */);
848 	/* store it */
849 	log_rrset_key(VERB_ALGO, "store parent-side negative", neg);
850 	iter_store_parentside_rrset(env, neg);
851 }
852 
853 int
854 iter_lookup_parent_NS_from_cache(struct module_env* env, struct delegpt* dp,
855 	struct regional* region, struct query_info* qinfo)
856 {
857 	struct ub_packed_rrset_key* akey;
858 	akey = rrset_cache_lookup(env->rrset_cache, dp->name,
859 		dp->namelen, LDNS_RR_TYPE_NS, qinfo->qclass,
860 		PACKED_RRSET_PARENT_SIDE, *env->now, 0);
861 	if(akey) {
862 		log_rrset_key(VERB_ALGO, "found parent-side NS in cache", akey);
863 		dp->has_parent_side_NS = 1;
864 		/* and mark the new names as lame */
865 		if(!delegpt_rrset_add_ns(dp, region, akey, 1)) {
866 			lock_rw_unlock(&akey->entry.lock);
867 			return 0;
868 		}
869 		lock_rw_unlock(&akey->entry.lock);
870 	}
871 	return 1;
872 }
873 
874 int iter_lookup_parent_glue_from_cache(struct module_env* env,
875         struct delegpt* dp, struct regional* region, struct query_info* qinfo)
876 {
877 	struct ub_packed_rrset_key* akey;
878 	struct delegpt_ns* ns;
879 	size_t num = delegpt_count_targets(dp);
880 	for(ns = dp->nslist; ns; ns = ns->next) {
881 		/* get cached parentside A */
882 		akey = rrset_cache_lookup(env->rrset_cache, ns->name,
883 			ns->namelen, LDNS_RR_TYPE_A, qinfo->qclass,
884 			PACKED_RRSET_PARENT_SIDE, *env->now, 0);
885 		if(akey) {
886 			log_rrset_key(VERB_ALGO, "found parent-side", akey);
887 			ns->done_pside4 = 1;
888 			/* a negative-cache-element has no addresses it adds */
889 			if(!delegpt_add_rrset_A(dp, region, akey, 1))
890 				log_err("malloc failure in lookup_parent_glue");
891 			lock_rw_unlock(&akey->entry.lock);
892 		}
893 		/* get cached parentside AAAA */
894 		akey = rrset_cache_lookup(env->rrset_cache, ns->name,
895 			ns->namelen, LDNS_RR_TYPE_AAAA, qinfo->qclass,
896 			PACKED_RRSET_PARENT_SIDE, *env->now, 0);
897 		if(akey) {
898 			log_rrset_key(VERB_ALGO, "found parent-side", akey);
899 			ns->done_pside6 = 1;
900 			/* a negative-cache-element has no addresses it adds */
901 			if(!delegpt_add_rrset_AAAA(dp, region, akey, 1))
902 				log_err("malloc failure in lookup_parent_glue");
903 			lock_rw_unlock(&akey->entry.lock);
904 		}
905 	}
906 	/* see if new (but lame) addresses have become available */
907 	return delegpt_count_targets(dp) != num;
908 }
909 
910 int
911 iter_get_next_root(struct iter_hints* hints, struct iter_forwards* fwd,
912 	uint16_t* c)
913 {
914 	uint16_t c1 = *c, c2 = *c;
915 	int r1 = hints_next_root(hints, &c1);
916 	int r2 = forwards_next_root(fwd, &c2);
917 	if(!r1 && !r2) /* got none, end of list */
918 		return 0;
919 	else if(!r1) /* got one, return that */
920 		*c = c2;
921 	else if(!r2)
922 		*c = c1;
923 	else if(c1 < c2) /* got both take smallest */
924 		*c = c1;
925 	else	*c = c2;
926 	return 1;
927 }
928 
929 void
930 iter_scrub_ds(struct dns_msg* msg, struct ub_packed_rrset_key* ns, uint8_t* z)
931 {
932 	/* Only the DS record for the delegation itself is expected.
933 	 * We allow DS for everything between the bailiwick and the
934 	 * zonecut, thus DS records must be at or above the zonecut.
935 	 * And the DS records must be below the server authority zone.
936 	 * The answer section is already scrubbed. */
937 	size_t i = msg->rep->an_numrrsets;
938 	while(i < (msg->rep->an_numrrsets + msg->rep->ns_numrrsets)) {
939 		struct ub_packed_rrset_key* s = msg->rep->rrsets[i];
940 		if(ntohs(s->rk.type) == LDNS_RR_TYPE_DS &&
941 			(!ns || !dname_subdomain_c(ns->rk.dname, s->rk.dname)
942 			|| query_dname_compare(z, s->rk.dname) == 0)) {
943 			log_nametypeclass(VERB_ALGO, "removing irrelevant DS",
944 				s->rk.dname, ntohs(s->rk.type),
945 				ntohs(s->rk.rrset_class));
946 			memmove(msg->rep->rrsets+i, msg->rep->rrsets+i+1,
947 				sizeof(struct ub_packed_rrset_key*) *
948 				(msg->rep->rrset_count-i-1));
949 			msg->rep->ns_numrrsets--;
950 			msg->rep->rrset_count--;
951 			/* stay at same i, but new record */
952 			continue;
953 		}
954 		i++;
955 	}
956 }
957 
958 void iter_dec_attempts(struct delegpt* dp, int d)
959 {
960 	struct delegpt_addr* a;
961 	for(a=dp->target_list; a; a = a->next_target) {
962 		if(a->attempts >= OUTBOUND_MSG_RETRY) {
963 			/* add back to result list */
964 			a->next_result = dp->result_list;
965 			dp->result_list = a;
966 		}
967 		if(a->attempts > d)
968 			a->attempts -= d;
969 		else a->attempts = 0;
970 	}
971 }
972 
973 void iter_merge_retry_counts(struct delegpt* dp, struct delegpt* old)
974 {
975 	struct delegpt_addr* a, *o, *prev;
976 	for(a=dp->target_list; a; a = a->next_target) {
977 		o = delegpt_find_addr(old, &a->addr, a->addrlen);
978 		if(o) {
979 			log_addr(VERB_ALGO, "copy attempt count previous dp",
980 				&a->addr, a->addrlen);
981 			a->attempts = o->attempts;
982 		}
983 	}
984 	prev = NULL;
985 	a = dp->usable_list;
986 	while(a) {
987 		if(a->attempts >= OUTBOUND_MSG_RETRY) {
988 			log_addr(VERB_ALGO, "remove from usable list dp",
989 				&a->addr, a->addrlen);
990 			/* remove from result list */
991 			if(prev)
992 				prev->next_usable = a->next_usable;
993 			else	dp->usable_list = a->next_usable;
994 			/* prev stays the same */
995 			a = a->next_usable;
996 			continue;
997 		}
998 		prev = a;
999 		a = a->next_usable;
1000 	}
1001 }
1002 
1003 int
1004 iter_ds_toolow(struct dns_msg* msg, struct delegpt* dp)
1005 {
1006 	/* if for query example.com, there is example.com SOA or a subdomain
1007 	 * of example.com, then we are too low and need to fetch NS. */
1008 	size_t i;
1009 	/* if we have a DNAME or CNAME we are probably wrong */
1010 	/* if we have a qtype DS in the answer section, its fine */
1011 	for(i=0; i < msg->rep->an_numrrsets; i++) {
1012 		struct ub_packed_rrset_key* s = msg->rep->rrsets[i];
1013 		if(ntohs(s->rk.type) == LDNS_RR_TYPE_DNAME ||
1014 			ntohs(s->rk.type) == LDNS_RR_TYPE_CNAME) {
1015 			/* not the right answer, maybe too low, check the
1016 			 * RRSIG signer name (if there is any) for a hint
1017 			 * that it is from the dp zone anyway */
1018 			uint8_t* sname;
1019 			size_t slen;
1020 			val_find_rrset_signer(s, &sname, &slen);
1021 			if(sname && query_dname_compare(dp->name, sname)==0)
1022 				return 0; /* it is fine, from the right dp */
1023 			return 1;
1024 		}
1025 		if(ntohs(s->rk.type) == LDNS_RR_TYPE_DS)
1026 			return 0; /* fine, we have a DS record */
1027 	}
1028 	for(i=msg->rep->an_numrrsets;
1029 		i < msg->rep->an_numrrsets + msg->rep->ns_numrrsets; i++) {
1030 		struct ub_packed_rrset_key* s = msg->rep->rrsets[i];
1031 		if(ntohs(s->rk.type) == LDNS_RR_TYPE_SOA) {
1032 			if(dname_subdomain_c(s->rk.dname, msg->qinfo.qname))
1033 				return 1; /* point is too low */
1034 			if(query_dname_compare(s->rk.dname, dp->name)==0)
1035 				return 0; /* right dp */
1036 		}
1037 		if(ntohs(s->rk.type) == LDNS_RR_TYPE_NSEC ||
1038 			ntohs(s->rk.type) == LDNS_RR_TYPE_NSEC3) {
1039 			uint8_t* sname;
1040 			size_t slen;
1041 			val_find_rrset_signer(s, &sname, &slen);
1042 			if(sname && query_dname_compare(dp->name, sname)==0)
1043 				return 0; /* it is fine, from the right dp */
1044 			return 1;
1045 		}
1046 	}
1047 	/* we do not know */
1048 	return 1;
1049 }
1050 
1051 int iter_dp_cangodown(struct query_info* qinfo, struct delegpt* dp)
1052 {
1053 	/* no delegation point, do not see how we can go down,
1054 	 * robust check, it should really exist */
1055 	if(!dp) return 0;
1056 
1057 	/* see if dp equals the qname, then we cannot go down further */
1058 	if(query_dname_compare(qinfo->qname, dp->name) == 0)
1059 		return 0;
1060 	/* if dp is one label above the name we also cannot go down further */
1061 	if(dname_count_labels(qinfo->qname) == dp->namelabs+1)
1062 		return 0;
1063 	return 1;
1064 }
1065