xref: /freebsd/contrib/unbound/iterator/iter_utils.c (revision a4adfaf712694ce7923d5309cf87d0cd2a598953)
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 "services/outside_network.h"
54 #include "util/net_help.h"
55 #include "util/module.h"
56 #include "util/log.h"
57 #include "util/config_file.h"
58 #include "util/regional.h"
59 #include "util/data/msgparse.h"
60 #include "util/data/dname.h"
61 #include "util/random.h"
62 #include "util/fptr_wlist.h"
63 #include "validator/val_anchor.h"
64 #include "validator/val_kcache.h"
65 #include "validator/val_kentry.h"
66 #include "validator/val_utils.h"
67 #include "validator/val_sigcrypt.h"
68 #include "sldns/sbuffer.h"
69 #include "sldns/str2wire.h"
70 
71 /** time when nameserver glue is said to be 'recent' */
72 #define SUSPICION_RECENT_EXPIRY 86400
73 /** penalty to validation failed blacklisted IPs */
74 #define BLACKLIST_PENALTY (USEFUL_SERVER_TOP_TIMEOUT*4)
75 
76 /** fillup fetch policy array */
77 static void
78 fetch_fill(struct iter_env* ie, const char* str)
79 {
80 	char* s = (char*)str, *e;
81 	int i;
82 	for(i=0; i<ie->max_dependency_depth+1; i++) {
83 		ie->target_fetch_policy[i] = strtol(s, &e, 10);
84 		if(s == e)
85 			fatal_exit("cannot parse fetch policy number %s", s);
86 		s = e;
87 	}
88 }
89 
90 /** Read config string that represents the target fetch policy */
91 static int
92 read_fetch_policy(struct iter_env* ie, const char* str)
93 {
94 	int count = cfg_count_numbers(str);
95 	if(count < 1) {
96 		log_err("Cannot parse target fetch policy: \"%s\"", str);
97 		return 0;
98 	}
99 	ie->max_dependency_depth = count - 1;
100 	ie->target_fetch_policy = (int*)calloc(
101 		(size_t)ie->max_dependency_depth+1, sizeof(int));
102 	if(!ie->target_fetch_policy) {
103 		log_err("alloc fetch policy: out of memory");
104 		return 0;
105 	}
106 	fetch_fill(ie, str);
107 	return 1;
108 }
109 
110 /** apply config caps whitelist items to name tree */
111 static int
112 caps_white_apply_cfg(rbtree_type* ntree, struct config_file* cfg)
113 {
114 	struct config_strlist* p;
115 	for(p=cfg->caps_whitelist; p; p=p->next) {
116 		struct name_tree_node* n;
117 		size_t len;
118 		uint8_t* nm = sldns_str2wire_dname(p->str, &len);
119 		if(!nm) {
120 			log_err("could not parse %s", p->str);
121 			return 0;
122 		}
123 		n = (struct name_tree_node*)calloc(1, sizeof(*n));
124 		if(!n) {
125 			log_err("out of memory");
126 			free(nm);
127 			return 0;
128 		}
129 		n->node.key = n;
130 		n->name = nm;
131 		n->len = len;
132 		n->labs = dname_count_labels(nm);
133 		n->dclass = LDNS_RR_CLASS_IN;
134 		if(!name_tree_insert(ntree, n, nm, len, n->labs, n->dclass)) {
135 			/* duplicate element ignored, idempotent */
136 			free(n->name);
137 			free(n);
138 		}
139 	}
140 	name_tree_init_parents(ntree);
141 	return 1;
142 }
143 
144 int
145 iter_apply_cfg(struct iter_env* iter_env, struct config_file* cfg)
146 {
147 	int i;
148 	/* target fetch policy */
149 	if(!read_fetch_policy(iter_env, cfg->target_fetch_policy))
150 		return 0;
151 	for(i=0; i<iter_env->max_dependency_depth+1; i++)
152 		verbose(VERB_QUERY, "target fetch policy for level %d is %d",
153 			i, iter_env->target_fetch_policy[i]);
154 
155 	if(!iter_env->donotq)
156 		iter_env->donotq = donotq_create();
157 	if(!iter_env->donotq || !donotq_apply_cfg(iter_env->donotq, cfg)) {
158 		log_err("Could not set donotqueryaddresses");
159 		return 0;
160 	}
161 	if(!iter_env->priv)
162 		iter_env->priv = priv_create();
163 	if(!iter_env->priv || !priv_apply_cfg(iter_env->priv, cfg)) {
164 		log_err("Could not set private addresses");
165 		return 0;
166 	}
167 	if(cfg->caps_whitelist) {
168 		if(!iter_env->caps_white)
169 			iter_env->caps_white = rbtree_create(name_tree_compare);
170 		if(!iter_env->caps_white || !caps_white_apply_cfg(
171 			iter_env->caps_white, cfg)) {
172 			log_err("Could not set capsforid whitelist");
173 			return 0;
174 		}
175 
176 	}
177 	iter_env->supports_ipv6 = cfg->do_ip6;
178 	iter_env->supports_ipv4 = cfg->do_ip4;
179 	iter_env->outbound_msg_retry = cfg->outbound_msg_retry;
180 	return 1;
181 }
182 
183 /** filter out unsuitable targets
184  * @param iter_env: iterator environment with ipv6-support flag.
185  * @param env: module environment with infra cache.
186  * @param name: zone name
187  * @param namelen: length of name
188  * @param qtype: query type (host order).
189  * @param now: current time
190  * @param a: address in delegation point we are examining.
191  * @return an integer that signals the target suitability.
192  *	as follows:
193  *	-1: The address should be omitted from the list.
194  *	    Because:
195  *		o The address is bogus (DNSSEC validation failure).
196  *		o Listed as donotquery
197  *		o is ipv6 but no ipv6 support (in operating system).
198  *		o is ipv4 but no ipv4 support (in operating system).
199  *		o is lame
200  *	Otherwise, an rtt in milliseconds.
201  *	0 .. USEFUL_SERVER_TOP_TIMEOUT-1
202  *		The roundtrip time timeout estimate. less than 2 minutes.
203  *		Note that util/rtt.c has a MIN_TIMEOUT of 50 msec, thus
204  *		values 0 .. 49 are not used, unless that is changed.
205  *	USEFUL_SERVER_TOP_TIMEOUT
206  *		This value exactly is given for unresponsive blacklisted.
207  *	USEFUL_SERVER_TOP_TIMEOUT+1
208  *		For non-blacklisted servers: huge timeout, but has traffic.
209  *	USEFUL_SERVER_TOP_TIMEOUT*1 ..
210  *		parent-side lame servers get this penalty. A dispreferential
211  *		server. (lame in delegpt).
212  *	USEFUL_SERVER_TOP_TIMEOUT*2 ..
213  *		dnsseclame servers get penalty
214  *	USEFUL_SERVER_TOP_TIMEOUT*3 ..
215  *		recursion lame servers get penalty
216  *	UNKNOWN_SERVER_NICENESS
217  *		If no information is known about the server, this is
218  *		returned. 376 msec or so.
219  *	+BLACKLIST_PENALTY (of USEFUL_TOP_TIMEOUT*4) for dnssec failed IPs.
220  *
221  * When a final value is chosen that is dnsseclame ; dnsseclameness checking
222  * is turned off (so we do not discard the reply).
223  * When a final value is chosen that is recursionlame; RD bit is set on query.
224  * Because of the numbers this means recursionlame also have dnssec lameness
225  * checking turned off.
226  */
227 static int
228 iter_filter_unsuitable(struct iter_env* iter_env, struct module_env* env,
229 	uint8_t* name, size_t namelen, uint16_t qtype, time_t now,
230 	struct delegpt_addr* a)
231 {
232 	int rtt, lame, reclame, dnsseclame;
233 	if(a->bogus)
234 		return -1; /* address of server is bogus */
235 	if(donotq_lookup(iter_env->donotq, &a->addr, a->addrlen)) {
236 		log_addr(VERB_ALGO, "skip addr on the donotquery list",
237 			&a->addr, a->addrlen);
238 		return -1; /* server is on the donotquery list */
239 	}
240 	if(!iter_env->supports_ipv6 && addr_is_ip6(&a->addr, a->addrlen)) {
241 		return -1; /* there is no ip6 available */
242 	}
243 	if(!iter_env->supports_ipv4 && !addr_is_ip6(&a->addr, a->addrlen)) {
244 		return -1; /* there is no ip4 available */
245 	}
246 	/* check lameness - need zone , class info */
247 	if(infra_get_lame_rtt(env->infra_cache, &a->addr, a->addrlen,
248 		name, namelen, qtype, &lame, &dnsseclame, &reclame,
249 		&rtt, now)) {
250 		log_addr(VERB_ALGO, "servselect", &a->addr, a->addrlen);
251 		verbose(VERB_ALGO, "   rtt=%d%s%s%s%s", rtt,
252 			lame?" LAME":"",
253 			dnsseclame?" DNSSEC_LAME":"",
254 			reclame?" REC_LAME":"",
255 			a->lame?" ADDR_LAME":"");
256 		if(lame)
257 			return -1; /* server is lame */
258 		else if(rtt >= USEFUL_SERVER_TOP_TIMEOUT)
259 			/* server is unresponsive,
260 			 * we used to return TOP_TIMEOUT, but fairly useless,
261 			 * because if == TOP_TIMEOUT is dropped because
262 			 * blacklisted later, instead, remove it here, so
263 			 * other choices (that are not blacklisted) can be
264 			 * tried */
265 			return -1;
266 		/* select remainder from worst to best */
267 		else if(reclame)
268 			return rtt+USEFUL_SERVER_TOP_TIMEOUT*3; /* nonpref */
269 		else if(dnsseclame || a->dnsseclame)
270 			return rtt+USEFUL_SERVER_TOP_TIMEOUT*2; /* nonpref */
271 		else if(a->lame)
272 			return rtt+USEFUL_SERVER_TOP_TIMEOUT+1; /* nonpref */
273 		else	return rtt;
274 	}
275 	/* no server information present */
276 	if(a->dnsseclame)
277 		return UNKNOWN_SERVER_NICENESS+USEFUL_SERVER_TOP_TIMEOUT*2; /* nonpref */
278 	else if(a->lame)
279 		return USEFUL_SERVER_TOP_TIMEOUT+1+UNKNOWN_SERVER_NICENESS; /* nonpref */
280 	return UNKNOWN_SERVER_NICENESS;
281 }
282 
283 /** lookup RTT information, and also store fastest rtt (if any) */
284 static int
285 iter_fill_rtt(struct iter_env* iter_env, struct module_env* env,
286 	uint8_t* name, size_t namelen, uint16_t qtype, time_t now,
287 	struct delegpt* dp, int* best_rtt, struct sock_list* blacklist,
288 	size_t* num_suitable_results)
289 {
290 	int got_it = 0;
291 	struct delegpt_addr* a;
292 	*num_suitable_results = 0;
293 
294 	if(dp->bogus)
295 		return 0; /* NS bogus, all bogus, nothing found */
296 	for(a=dp->result_list; a; a = a->next_result) {
297 		a->sel_rtt = iter_filter_unsuitable(iter_env, env,
298 			name, namelen, qtype, now, a);
299 		if(a->sel_rtt != -1) {
300 			if(sock_list_find(blacklist, &a->addr, a->addrlen))
301 				a->sel_rtt += BLACKLIST_PENALTY;
302 
303 			if(!got_it) {
304 				*best_rtt = a->sel_rtt;
305 				got_it = 1;
306 			} else if(a->sel_rtt < *best_rtt) {
307 				*best_rtt = a->sel_rtt;
308 			}
309 			(*num_suitable_results)++;
310 		}
311 	}
312 	return got_it;
313 }
314 
315 /** compare two rtts, return -1, 0 or 1 */
316 static int
317 rtt_compare(const void* x, const void* y)
318 {
319 	if(*(int*)x == *(int*)y)
320 		return 0;
321 	if(*(int*)x > *(int*)y)
322 		return 1;
323 	return -1;
324 }
325 
326 /** get RTT for the Nth fastest server */
327 static int
328 nth_rtt(struct delegpt_addr* result_list, size_t num_results, size_t n)
329 {
330 	int rtt_band;
331 	size_t i;
332 	int* rtt_list, *rtt_index;
333 
334 	if(num_results < 1 || n >= num_results) {
335 		return -1;
336 	}
337 
338 	rtt_list = calloc(num_results, sizeof(int));
339 	if(!rtt_list) {
340 		log_err("malloc failure: allocating rtt_list");
341 		return -1;
342 	}
343 	rtt_index = rtt_list;
344 
345 	for(i=0; i<num_results && result_list; i++) {
346 		if(result_list->sel_rtt != -1) {
347 			*rtt_index = result_list->sel_rtt;
348 			rtt_index++;
349 		}
350 		result_list=result_list->next_result;
351 	}
352 	qsort(rtt_list, num_results, sizeof(*rtt_list), rtt_compare);
353 
354 	log_assert(n > 0);
355 	rtt_band = rtt_list[n-1];
356 	free(rtt_list);
357 
358 	return rtt_band;
359 }
360 
361 /** filter the address list, putting best targets at front,
362  * returns number of best targets (or 0, no suitable targets) */
363 static int
364 iter_filter_order(struct iter_env* iter_env, struct module_env* env,
365 	uint8_t* name, size_t namelen, uint16_t qtype, time_t now,
366 	struct delegpt* dp, int* selected_rtt, int open_target,
367 	struct sock_list* blacklist, time_t prefetch)
368 {
369 	int got_num = 0, low_rtt = 0, swap_to_front, rtt_band = RTT_BAND, nth;
370 	size_t num_results;
371 	struct delegpt_addr* a, *n, *prev=NULL;
372 
373 	/* fillup sel_rtt and find best rtt in the bunch */
374 	got_num = iter_fill_rtt(iter_env, env, name, namelen, qtype, now, dp,
375 		&low_rtt, blacklist, &num_results);
376 	if(got_num == 0)
377 		return 0;
378 	if(low_rtt >= USEFUL_SERVER_TOP_TIMEOUT &&
379 		(delegpt_count_missing_targets(dp) > 0 || open_target > 0)) {
380 		verbose(VERB_ALGO, "Bad choices, trying to get more choice");
381 		return 0; /* we want more choice. The best choice is a bad one.
382 			     return 0 to force the caller to fetch more */
383 	}
384 
385 	if(env->cfg->fast_server_permil != 0 && prefetch == 0 &&
386 		num_results > env->cfg->fast_server_num &&
387 		ub_random_max(env->rnd, 1000) < env->cfg->fast_server_permil) {
388 		/* the query is not prefetch, but for a downstream client,
389 		 * there are more servers available then the fastest N we want
390 		 * to choose from. Limit our choice to the fastest servers. */
391 		nth = nth_rtt(dp->result_list, num_results,
392 			env->cfg->fast_server_num);
393 		if(nth > 0) {
394 			rtt_band = nth - low_rtt;
395 			if(rtt_band > RTT_BAND)
396 				rtt_band = RTT_BAND;
397 		}
398 	}
399 
400 	got_num = 0;
401 	a = dp->result_list;
402 	while(a) {
403 		/* skip unsuitable targets */
404 		if(a->sel_rtt == -1) {
405 			prev = a;
406 			a = a->next_result;
407 			continue;
408 		}
409 		/* classify the server address and determine what to do */
410 		swap_to_front = 0;
411 		if(a->sel_rtt >= low_rtt && a->sel_rtt - low_rtt <= rtt_band) {
412 			got_num++;
413 			swap_to_front = 1;
414 		} else if(a->sel_rtt<low_rtt && low_rtt-a->sel_rtt<=rtt_band) {
415 			got_num++;
416 			swap_to_front = 1;
417 		}
418 		/* swap to front if necessary, or move to next result */
419 		if(swap_to_front && prev) {
420 			n = a->next_result;
421 			prev->next_result = n;
422 			a->next_result = dp->result_list;
423 			dp->result_list = a;
424 			a = n;
425 		} else {
426 			prev = a;
427 			a = a->next_result;
428 		}
429 	}
430 	*selected_rtt = low_rtt;
431 
432 	if (env->cfg->prefer_ip6) {
433 		int got_num6 = 0;
434 		int low_rtt6 = 0;
435 		int i;
436 		int attempt = -1; /* filter to make sure addresses have
437 		  less attempts on them than the first, to force round
438 		  robin when all the IPv6 addresses fail */
439 		int num4ok = 0; /* number ip4 at low attempt count */
440 		int num4_lowrtt = 0;
441 		prev = NULL;
442 		a = dp->result_list;
443 		for(i = 0; i < got_num; i++) {
444 			if(!a) break; /* robustness */
445 			swap_to_front = 0;
446 			if(a->addr.ss_family != AF_INET6 && attempt == -1) {
447 				/* if we only have ip4 at low attempt count,
448 				 * then ip6 is failing, and we need to
449 				 * select one of the remaining IPv4 addrs */
450 				attempt = a->attempts;
451 				num4ok++;
452 				num4_lowrtt = a->sel_rtt;
453 			} else if(a->addr.ss_family != AF_INET6 && attempt == a->attempts) {
454 				num4ok++;
455 				if(num4_lowrtt == 0 || a->sel_rtt < num4_lowrtt) {
456 					num4_lowrtt = a->sel_rtt;
457 				}
458 			}
459 			if(a->addr.ss_family == AF_INET6) {
460 				if(attempt == -1) {
461 					attempt = a->attempts;
462 				} else if(a->attempts > attempt) {
463 					break;
464 				}
465 				got_num6++;
466 				swap_to_front = 1;
467 				if(low_rtt6 == 0 || a->sel_rtt < low_rtt6) {
468 					low_rtt6 = a->sel_rtt;
469 				}
470 			}
471 			/* swap to front if IPv6, or move to next result */
472 			if(swap_to_front && prev) {
473 				n = a->next_result;
474 				prev->next_result = n;
475 				a->next_result = dp->result_list;
476 				dp->result_list = a;
477 				a = n;
478 			} else {
479 				prev = a;
480 				a = a->next_result;
481 			}
482 		}
483 		if(got_num6 > 0) {
484 			got_num = got_num6;
485 			*selected_rtt = low_rtt6;
486 		} else if(num4ok > 0) {
487 			got_num = num4ok;
488 			*selected_rtt = num4_lowrtt;
489 		}
490 	} else if (env->cfg->prefer_ip4) {
491 		int got_num4 = 0;
492 		int low_rtt4 = 0;
493 		int i;
494 		int attempt = -1; /* filter to make sure addresses have
495 		  less attempts on them than the first, to force round
496 		  robin when all the IPv4 addresses fail */
497 		int num6ok = 0; /* number ip6 at low attempt count */
498 		int num6_lowrtt = 0;
499 		prev = NULL;
500 		a = dp->result_list;
501 		for(i = 0; i < got_num; i++) {
502 			if(!a) break; /* robustness */
503 			swap_to_front = 0;
504 			if(a->addr.ss_family != AF_INET && attempt == -1) {
505 				/* if we only have ip6 at low attempt count,
506 				 * then ip4 is failing, and we need to
507 				 * select one of the remaining IPv6 addrs */
508 				attempt = a->attempts;
509 				num6ok++;
510 				num6_lowrtt = a->sel_rtt;
511 			} else if(a->addr.ss_family != AF_INET && attempt == a->attempts) {
512 				num6ok++;
513 				if(num6_lowrtt == 0 || a->sel_rtt < num6_lowrtt) {
514 					num6_lowrtt = a->sel_rtt;
515 				}
516 			}
517 			if(a->addr.ss_family == AF_INET) {
518 				if(attempt == -1) {
519 					attempt = a->attempts;
520 				} else if(a->attempts > attempt) {
521 					break;
522 				}
523 				got_num4++;
524 				swap_to_front = 1;
525 				if(low_rtt4 == 0 || a->sel_rtt < low_rtt4) {
526 					low_rtt4 = a->sel_rtt;
527 				}
528 			}
529 			/* swap to front if IPv4, or move to next result */
530 			if(swap_to_front && prev) {
531 				n = a->next_result;
532 				prev->next_result = n;
533 				a->next_result = dp->result_list;
534 				dp->result_list = a;
535 				a = n;
536 			} else {
537 				prev = a;
538 				a = a->next_result;
539 			}
540 		}
541 		if(got_num4 > 0) {
542 			got_num = got_num4;
543 			*selected_rtt = low_rtt4;
544 		} else if(num6ok > 0) {
545 			got_num = num6ok;
546 			*selected_rtt = num6_lowrtt;
547 		}
548 	}
549 	return got_num;
550 }
551 
552 struct delegpt_addr*
553 iter_server_selection(struct iter_env* iter_env,
554 	struct module_env* env, struct delegpt* dp,
555 	uint8_t* name, size_t namelen, uint16_t qtype, int* dnssec_lame,
556 	int* chase_to_rd, int open_target, struct sock_list* blacklist,
557 	time_t prefetch)
558 {
559 	int sel;
560 	int selrtt;
561 	struct delegpt_addr* a, *prev;
562 	int num = iter_filter_order(iter_env, env, name, namelen, qtype,
563 		*env->now, dp, &selrtt, open_target, blacklist, prefetch);
564 
565 	if(num == 0)
566 		return NULL;
567 	verbose(VERB_ALGO, "selrtt %d", selrtt);
568 	if(selrtt > BLACKLIST_PENALTY) {
569 		if(selrtt-BLACKLIST_PENALTY > USEFUL_SERVER_TOP_TIMEOUT*3) {
570 			verbose(VERB_ALGO, "chase to "
571 				"blacklisted recursion lame server");
572 			*chase_to_rd = 1;
573 		}
574 		if(selrtt-BLACKLIST_PENALTY > USEFUL_SERVER_TOP_TIMEOUT*2) {
575 			verbose(VERB_ALGO, "chase to "
576 				"blacklisted dnssec lame server");
577 			*dnssec_lame = 1;
578 		}
579 	} else {
580 		if(selrtt > USEFUL_SERVER_TOP_TIMEOUT*3) {
581 			verbose(VERB_ALGO, "chase to recursion lame server");
582 			*chase_to_rd = 1;
583 		}
584 		if(selrtt > USEFUL_SERVER_TOP_TIMEOUT*2) {
585 			verbose(VERB_ALGO, "chase to dnssec lame server");
586 			*dnssec_lame = 1;
587 		}
588 		if(selrtt == USEFUL_SERVER_TOP_TIMEOUT) {
589 			verbose(VERB_ALGO, "chase to blacklisted lame server");
590 			return NULL;
591 		}
592 	}
593 
594 	if(num == 1) {
595 		a = dp->result_list;
596 		if(++a->attempts < iter_env->outbound_msg_retry)
597 			return a;
598 		dp->result_list = a->next_result;
599 		return a;
600 	}
601 
602 	/* randomly select a target from the list */
603 	log_assert(num > 1);
604 	/* grab secure random number, to pick unexpected server.
605 	 * also we need it to be threadsafe. */
606 	sel = ub_random_max(env->rnd, num);
607 	a = dp->result_list;
608 	prev = NULL;
609 	while(sel > 0 && a) {
610 		prev = a;
611 		a = a->next_result;
612 		sel--;
613 	}
614 	if(!a)  /* robustness */
615 		return NULL;
616 	if(++a->attempts < iter_env->outbound_msg_retry)
617 		return a;
618 	/* remove it from the delegation point result list */
619 	if(prev)
620 		prev->next_result = a->next_result;
621 	else	dp->result_list = a->next_result;
622 	return a;
623 }
624 
625 struct dns_msg*
626 dns_alloc_msg(sldns_buffer* pkt, struct msg_parse* msg,
627 	struct regional* region)
628 {
629 	struct dns_msg* m = (struct dns_msg*)regional_alloc(region,
630 		sizeof(struct dns_msg));
631 	if(!m)
632 		return NULL;
633 	memset(m, 0, sizeof(*m));
634 	if(!parse_create_msg(pkt, msg, NULL, &m->qinfo, &m->rep, region)) {
635 		log_err("malloc failure: allocating incoming dns_msg");
636 		return NULL;
637 	}
638 	return m;
639 }
640 
641 struct dns_msg*
642 dns_copy_msg(struct dns_msg* from, struct regional* region)
643 {
644 	struct dns_msg* m = (struct dns_msg*)regional_alloc(region,
645 		sizeof(struct dns_msg));
646 	if(!m)
647 		return NULL;
648 	m->qinfo = from->qinfo;
649 	if(!(m->qinfo.qname = regional_alloc_init(region, from->qinfo.qname,
650 		from->qinfo.qname_len)))
651 		return NULL;
652 	if(!(m->rep = reply_info_copy(from->rep, NULL, region)))
653 		return NULL;
654 	return m;
655 }
656 
657 void
658 iter_dns_store(struct module_env* env, struct query_info* msgqinf,
659 	struct reply_info* msgrep, int is_referral, time_t leeway, int pside,
660 	struct regional* region, uint16_t flags)
661 {
662 	if(!dns_cache_store(env, msgqinf, msgrep, is_referral, leeway,
663 		pside, region, flags))
664 		log_err("out of memory: cannot store data in cache");
665 }
666 
667 int
668 iter_ns_probability(struct ub_randstate* rnd, int n, int m)
669 {
670 	int sel;
671 	if(n == m) /* 100% chance */
672 		return 1;
673 	/* we do not need secure random numbers here, but
674 	 * we do need it to be threadsafe, so we use this */
675 	sel = ub_random_max(rnd, m);
676 	return (sel < n);
677 }
678 
679 /** detect dependency cycle for query and target */
680 static int
681 causes_cycle(struct module_qstate* qstate, uint8_t* name, size_t namelen,
682 	uint16_t t, uint16_t c)
683 {
684 	struct query_info qinf;
685 	qinf.qname = name;
686 	qinf.qname_len = namelen;
687 	qinf.qtype = t;
688 	qinf.qclass = c;
689 	qinf.local_alias = NULL;
690 	fptr_ok(fptr_whitelist_modenv_detect_cycle(
691 		qstate->env->detect_cycle));
692 	return (*qstate->env->detect_cycle)(qstate, &qinf,
693 		(uint16_t)(BIT_RD|BIT_CD), qstate->is_priming,
694 		qstate->is_valrec);
695 }
696 
697 void
698 iter_mark_cycle_targets(struct module_qstate* qstate, struct delegpt* dp)
699 {
700 	struct delegpt_ns* ns;
701 	for(ns = dp->nslist; ns; ns = ns->next) {
702 		if(ns->resolved)
703 			continue;
704 		/* see if this ns as target causes dependency cycle */
705 		if(causes_cycle(qstate, ns->name, ns->namelen,
706 			LDNS_RR_TYPE_AAAA, qstate->qinfo.qclass) ||
707 		   causes_cycle(qstate, ns->name, ns->namelen,
708 			LDNS_RR_TYPE_A, qstate->qinfo.qclass)) {
709 			log_nametypeclass(VERB_QUERY, "skipping target due "
710 			 	"to dependency cycle (harden-glue: no may "
711 				"fix some of the cycles)",
712 				ns->name, LDNS_RR_TYPE_A,
713 				qstate->qinfo.qclass);
714 			ns->resolved = 1;
715 		}
716 	}
717 }
718 
719 void
720 iter_mark_pside_cycle_targets(struct module_qstate* qstate, struct delegpt* dp)
721 {
722 	struct delegpt_ns* ns;
723 	for(ns = dp->nslist; ns; ns = ns->next) {
724 		if(ns->done_pside4 && ns->done_pside6)
725 			continue;
726 		/* see if this ns as target causes dependency cycle */
727 		if(causes_cycle(qstate, ns->name, ns->namelen,
728 			LDNS_RR_TYPE_A, qstate->qinfo.qclass)) {
729 			log_nametypeclass(VERB_QUERY, "skipping target due "
730 			 	"to dependency cycle", ns->name,
731 				LDNS_RR_TYPE_A, qstate->qinfo.qclass);
732 			ns->done_pside4 = 1;
733 		}
734 		if(causes_cycle(qstate, ns->name, ns->namelen,
735 			LDNS_RR_TYPE_AAAA, qstate->qinfo.qclass)) {
736 			log_nametypeclass(VERB_QUERY, "skipping target due "
737 			 	"to dependency cycle", ns->name,
738 				LDNS_RR_TYPE_AAAA, qstate->qinfo.qclass);
739 			ns->done_pside6 = 1;
740 		}
741 	}
742 }
743 
744 int
745 iter_dp_is_useless(struct query_info* qinfo, uint16_t qflags,
746 	struct delegpt* dp, int supports_ipv4, int supports_ipv6)
747 {
748 	struct delegpt_ns* ns;
749 	struct delegpt_addr* a;
750 	/* check:
751 	 *      o RD qflag is on.
752 	 *      o no addresses are provided.
753 	 *      o all NS items are required glue.
754 	 * OR
755 	 *      o RD qflag is on.
756 	 *      o no addresses are provided.
757 	 *      o the query is for one of the nameservers in dp,
758 	 *        and that nameserver is a glue-name for this dp.
759 	 */
760 	if(!(qflags&BIT_RD))
761 		return 0;
762 	/* either available or unused targets,
763 	 * if they exist, the dp is not useless. */
764 	for(a = dp->usable_list; a; a = a->next_usable) {
765 		if(!addr_is_ip6(&a->addr, a->addrlen) && supports_ipv4)
766 			return 0;
767 		else if(addr_is_ip6(&a->addr, a->addrlen) && supports_ipv6)
768 			return 0;
769 	}
770 	for(a = dp->result_list; a; a = a->next_result) {
771 		if(!addr_is_ip6(&a->addr, a->addrlen) && supports_ipv4)
772 			return 0;
773 		else if(addr_is_ip6(&a->addr, a->addrlen) && supports_ipv6)
774 			return 0;
775 	}
776 
777 	/* see if query is for one of the nameservers, which is glue */
778 	if( ((qinfo->qtype == LDNS_RR_TYPE_A && supports_ipv4) ||
779 		(qinfo->qtype == LDNS_RR_TYPE_AAAA && supports_ipv6)) &&
780 		dname_subdomain_c(qinfo->qname, dp->name) &&
781 		delegpt_find_ns(dp, qinfo->qname, qinfo->qname_len))
782 		return 1;
783 
784 	for(ns = dp->nslist; ns; ns = ns->next) {
785 		if(ns->resolved) /* skip failed targets */
786 			continue;
787 		if(!dname_subdomain_c(ns->name, dp->name))
788 			return 0; /* one address is not required glue */
789 	}
790 	return 1;
791 }
792 
793 int
794 iter_qname_indicates_dnssec(struct module_env* env, struct query_info *qinfo)
795 {
796 	struct trust_anchor* a;
797 	if(!env || !env->anchors || !qinfo || !qinfo->qname)
798 		return 0;
799 	/* a trust anchor exists above the name? */
800 	if((a=anchors_lookup(env->anchors, qinfo->qname, qinfo->qname_len,
801 		qinfo->qclass))) {
802 		if(a->numDS == 0 && a->numDNSKEY == 0) {
803 			/* insecure trust point */
804 			lock_basic_unlock(&a->lock);
805 			return 0;
806 		}
807 		lock_basic_unlock(&a->lock);
808 		return 1;
809 	}
810 	/* no trust anchor above it. */
811 	return 0;
812 }
813 
814 int
815 iter_indicates_dnssec(struct module_env* env, struct delegpt* dp,
816         struct dns_msg* msg, uint16_t dclass)
817 {
818 	struct trust_anchor* a;
819 	/* information not available, !env->anchors can be common */
820 	if(!env || !env->anchors || !dp || !dp->name)
821 		return 0;
822 	/* a trust anchor exists with this name, RRSIGs expected */
823 	if((a=anchor_find(env->anchors, dp->name, dp->namelabs, dp->namelen,
824 		dclass))) {
825 		if(a->numDS == 0 && a->numDNSKEY == 0) {
826 			/* insecure trust point */
827 			lock_basic_unlock(&a->lock);
828 			return 0;
829 		}
830 		lock_basic_unlock(&a->lock);
831 		return 1;
832 	}
833 	/* see if DS rrset was given, in AUTH section */
834 	if(msg && msg->rep &&
835 		reply_find_rrset_section_ns(msg->rep, dp->name, dp->namelen,
836 		LDNS_RR_TYPE_DS, dclass))
837 		return 1;
838 	/* look in key cache */
839 	if(env->key_cache) {
840 		struct key_entry_key* kk = key_cache_obtain(env->key_cache,
841 			dp->name, dp->namelen, dclass, env->scratch, *env->now);
842 		if(kk) {
843 			if(query_dname_compare(kk->name, dp->name) == 0) {
844 			  if(key_entry_isgood(kk) || key_entry_isbad(kk)) {
845 				regional_free_all(env->scratch);
846 				return 1;
847 			  } else if(key_entry_isnull(kk)) {
848 				regional_free_all(env->scratch);
849 				return 0;
850 			  }
851 			}
852 			regional_free_all(env->scratch);
853 		}
854 	}
855 	return 0;
856 }
857 
858 int
859 iter_msg_has_dnssec(struct dns_msg* msg)
860 {
861 	size_t i;
862 	if(!msg || !msg->rep)
863 		return 0;
864 	for(i=0; i<msg->rep->an_numrrsets + msg->rep->ns_numrrsets; i++) {
865 		if(((struct packed_rrset_data*)msg->rep->rrsets[i]->
866 			entry.data)->rrsig_count > 0)
867 			return 1;
868 	}
869 	/* empty message has no DNSSEC info, with DNSSEC the reply is
870 	 * not empty (NSEC) */
871 	return 0;
872 }
873 
874 int iter_msg_from_zone(struct dns_msg* msg, struct delegpt* dp,
875         enum response_type type, uint16_t dclass)
876 {
877 	if(!msg || !dp || !msg->rep || !dp->name)
878 		return 0;
879 	/* SOA RRset - always from reply zone */
880 	if(reply_find_rrset_section_an(msg->rep, dp->name, dp->namelen,
881 		LDNS_RR_TYPE_SOA, dclass) ||
882 	   reply_find_rrset_section_ns(msg->rep, dp->name, dp->namelen,
883 		LDNS_RR_TYPE_SOA, dclass))
884 		return 1;
885 	if(type == RESPONSE_TYPE_REFERRAL) {
886 		size_t i;
887 		/* if it adds a single label, i.e. we expect .com,
888 		 * and referral to example.com. NS ... , then origin zone
889 		 * is .com. For a referral to sub.example.com. NS ... then
890 		 * we do not know, since example.com. may be in between. */
891 		for(i=0; i<msg->rep->an_numrrsets+msg->rep->ns_numrrsets;
892 			i++) {
893 			struct ub_packed_rrset_key* s = msg->rep->rrsets[i];
894 			if(ntohs(s->rk.type) == LDNS_RR_TYPE_NS &&
895 				ntohs(s->rk.rrset_class) == dclass) {
896 				int l = dname_count_labels(s->rk.dname);
897 				if(l == dp->namelabs + 1 &&
898 					dname_strict_subdomain(s->rk.dname,
899 					l, dp->name, dp->namelabs))
900 					return 1;
901 			}
902 		}
903 		return 0;
904 	}
905 	log_assert(type==RESPONSE_TYPE_ANSWER || type==RESPONSE_TYPE_CNAME);
906 	/* not a referral, and not lame delegation (upwards), so,
907 	 * any NS rrset must be from the zone itself */
908 	if(reply_find_rrset_section_an(msg->rep, dp->name, dp->namelen,
909 		LDNS_RR_TYPE_NS, dclass) ||
910 	   reply_find_rrset_section_ns(msg->rep, dp->name, dp->namelen,
911 		LDNS_RR_TYPE_NS, dclass))
912 		return 1;
913 	/* a DNSKEY set is expected at the zone apex as well */
914 	/* this is for 'minimal responses' for DNSKEYs */
915 	if(reply_find_rrset_section_an(msg->rep, dp->name, dp->namelen,
916 		LDNS_RR_TYPE_DNSKEY, dclass))
917 		return 1;
918 	return 0;
919 }
920 
921 /**
922  * check equality of two rrsets
923  * @param k1: rrset
924  * @param k2: rrset
925  * @return true if equal
926  */
927 static int
928 rrset_equal(struct ub_packed_rrset_key* k1, struct ub_packed_rrset_key* k2)
929 {
930 	struct packed_rrset_data* d1 = (struct packed_rrset_data*)
931 		k1->entry.data;
932 	struct packed_rrset_data* d2 = (struct packed_rrset_data*)
933 		k2->entry.data;
934 	size_t i, t;
935 	if(k1->rk.dname_len != k2->rk.dname_len ||
936 		k1->rk.flags != k2->rk.flags ||
937 		k1->rk.type != k2->rk.type ||
938 		k1->rk.rrset_class != k2->rk.rrset_class ||
939 		query_dname_compare(k1->rk.dname, k2->rk.dname) != 0)
940 		return 0;
941 	if(	/* do not check ttl: d1->ttl != d2->ttl || */
942 		d1->count != d2->count ||
943 		d1->rrsig_count != d2->rrsig_count ||
944 		d1->trust != d2->trust ||
945 		d1->security != d2->security)
946 		return 0;
947 	t = d1->count + d1->rrsig_count;
948 	for(i=0; i<t; i++) {
949 		if(d1->rr_len[i] != d2->rr_len[i] ||
950 			/* no ttl check: d1->rr_ttl[i] != d2->rr_ttl[i] ||*/
951 			memcmp(d1->rr_data[i], d2->rr_data[i],
952 				d1->rr_len[i]) != 0)
953 			return 0;
954 	}
955 	return 1;
956 }
957 
958 /** compare rrsets and sort canonically.  Compares rrset name, type, class.
959  * return 0 if equal, +1 if x > y, and -1 if x < y.
960  */
961 static int
962 rrset_canonical_sort_cmp(const void* x, const void* y)
963 {
964 	struct ub_packed_rrset_key* rrx = *(struct ub_packed_rrset_key**)x;
965 	struct ub_packed_rrset_key* rry = *(struct ub_packed_rrset_key**)y;
966 	int r = dname_canonical_compare(rrx->rk.dname, rry->rk.dname);
967 	if(r != 0)
968 		return r;
969 	if(rrx->rk.type != rry->rk.type) {
970 		if(ntohs(rrx->rk.type) > ntohs(rry->rk.type))
971 			return 1;
972 		else	return -1;
973 	}
974 	if(rrx->rk.rrset_class != rry->rk.rrset_class) {
975 		if(ntohs(rrx->rk.rrset_class) > ntohs(rry->rk.rrset_class))
976 			return 1;
977 		else	return -1;
978 	}
979 	return 0;
980 }
981 
982 int
983 reply_equal(struct reply_info* p, struct reply_info* q, struct regional* region)
984 {
985 	size_t i;
986 	struct ub_packed_rrset_key** sorted_p, **sorted_q;
987 	if(p->flags != q->flags ||
988 		p->qdcount != q->qdcount ||
989 		/* do not check TTL, this may differ */
990 		/*
991 		p->ttl != q->ttl ||
992 		p->prefetch_ttl != q->prefetch_ttl ||
993 		*/
994 		p->security != q->security ||
995 		p->an_numrrsets != q->an_numrrsets ||
996 		p->ns_numrrsets != q->ns_numrrsets ||
997 		p->ar_numrrsets != q->ar_numrrsets ||
998 		p->rrset_count != q->rrset_count)
999 		return 0;
1000 	/* sort the rrsets in the authority and additional sections before
1001 	 * compare, the query and answer sections are ordered in the sequence
1002 	 * they should have (eg. one after the other for aliases). */
1003 	sorted_p = (struct ub_packed_rrset_key**)regional_alloc_init(
1004 		region, p->rrsets, sizeof(*sorted_p)*p->rrset_count);
1005 	if(!sorted_p) return 0;
1006 	log_assert(p->an_numrrsets + p->ns_numrrsets + p->ar_numrrsets <=
1007 		p->rrset_count);
1008 	qsort(sorted_p + p->an_numrrsets, p->ns_numrrsets,
1009 		sizeof(*sorted_p), rrset_canonical_sort_cmp);
1010 	qsort(sorted_p + p->an_numrrsets + p->ns_numrrsets, p->ar_numrrsets,
1011 		sizeof(*sorted_p), rrset_canonical_sort_cmp);
1012 
1013 	sorted_q = (struct ub_packed_rrset_key**)regional_alloc_init(
1014 		region, q->rrsets, sizeof(*sorted_q)*q->rrset_count);
1015 	if(!sorted_q) {
1016 		regional_free_all(region);
1017 		return 0;
1018 	}
1019 	log_assert(q->an_numrrsets + q->ns_numrrsets + q->ar_numrrsets <=
1020 		q->rrset_count);
1021 	qsort(sorted_q + q->an_numrrsets, q->ns_numrrsets,
1022 		sizeof(*sorted_q), rrset_canonical_sort_cmp);
1023 	qsort(sorted_q + q->an_numrrsets + q->ns_numrrsets, q->ar_numrrsets,
1024 		sizeof(*sorted_q), rrset_canonical_sort_cmp);
1025 
1026 	/* compare the rrsets */
1027 	for(i=0; i<p->rrset_count; i++) {
1028 		if(!rrset_equal(sorted_p[i], sorted_q[i])) {
1029 			if(!rrset_canonical_equal(region, sorted_p[i],
1030 				sorted_q[i])) {
1031 				regional_free_all(region);
1032 				return 0;
1033 			}
1034 		}
1035 	}
1036 	regional_free_all(region);
1037 	return 1;
1038 }
1039 
1040 void
1041 caps_strip_reply(struct reply_info* rep)
1042 {
1043 	size_t i;
1044 	if(!rep) return;
1045 	/* see if message is a referral, in which case the additional and
1046 	 * NS record cannot be removed */
1047 	/* referrals have the AA flag unset (strict check, not elsewhere in
1048 	 * unbound, but for 0x20 this is very convenient). */
1049 	if(!(rep->flags&BIT_AA))
1050 		return;
1051 	/* remove the additional section from the reply */
1052 	if(rep->ar_numrrsets != 0) {
1053 		verbose(VERB_ALGO, "caps fallback: removing additional section");
1054 		rep->rrset_count -= rep->ar_numrrsets;
1055 		rep->ar_numrrsets = 0;
1056 	}
1057 	/* is there an NS set in the authority section to remove? */
1058 	/* the failure case (Cisco firewalls) only has one rrset in authsec */
1059 	for(i=rep->an_numrrsets; i<rep->an_numrrsets+rep->ns_numrrsets; i++) {
1060 		struct ub_packed_rrset_key* s = rep->rrsets[i];
1061 		if(ntohs(s->rk.type) == LDNS_RR_TYPE_NS) {
1062 			/* remove NS rrset and break from loop (loop limits
1063 			 * have changed) */
1064 			/* move last rrset into this position (there is no
1065 			 * additional section any more) */
1066 			verbose(VERB_ALGO, "caps fallback: removing NS rrset");
1067 			if(i < rep->rrset_count-1)
1068 				rep->rrsets[i]=rep->rrsets[rep->rrset_count-1];
1069 			rep->rrset_count --;
1070 			rep->ns_numrrsets --;
1071 			break;
1072 		}
1073 	}
1074 }
1075 
1076 int caps_failed_rcode(struct reply_info* rep)
1077 {
1078 	return !(FLAGS_GET_RCODE(rep->flags) == LDNS_RCODE_NOERROR ||
1079 		FLAGS_GET_RCODE(rep->flags) == LDNS_RCODE_NXDOMAIN);
1080 }
1081 
1082 void
1083 iter_store_parentside_rrset(struct module_env* env,
1084 	struct ub_packed_rrset_key* rrset)
1085 {
1086 	struct rrset_ref ref;
1087 	rrset = packed_rrset_copy_alloc(rrset, env->alloc, *env->now);
1088 	if(!rrset) {
1089 		log_err("malloc failure in store_parentside_rrset");
1090 		return;
1091 	}
1092 	rrset->rk.flags |= PACKED_RRSET_PARENT_SIDE;
1093 	rrset->entry.hash = rrset_key_hash(&rrset->rk);
1094 	ref.key = rrset;
1095 	ref.id = rrset->id;
1096 	/* ignore ret: if it was in the cache, ref updated */
1097 	(void)rrset_cache_update(env->rrset_cache, &ref, env->alloc, *env->now);
1098 }
1099 
1100 /** fetch NS record from reply, if any */
1101 static struct ub_packed_rrset_key*
1102 reply_get_NS_rrset(struct reply_info* rep)
1103 {
1104 	size_t i;
1105 	for(i=0; i<rep->rrset_count; i++) {
1106 		if(rep->rrsets[i]->rk.type == htons(LDNS_RR_TYPE_NS)) {
1107 			return rep->rrsets[i];
1108 		}
1109 	}
1110 	return NULL;
1111 }
1112 
1113 void
1114 iter_store_parentside_NS(struct module_env* env, struct reply_info* rep)
1115 {
1116 	struct ub_packed_rrset_key* rrset = reply_get_NS_rrset(rep);
1117 	if(rrset) {
1118 		log_rrset_key(VERB_ALGO, "store parent-side NS", rrset);
1119 		iter_store_parentside_rrset(env, rrset);
1120 	}
1121 }
1122 
1123 void iter_store_parentside_neg(struct module_env* env,
1124         struct query_info* qinfo, struct reply_info* rep)
1125 {
1126 	/* TTL: NS from referral in iq->deleg_msg,
1127 	 *      or first RR from iq->response,
1128 	 *      or servfail5secs if !iq->response */
1129 	time_t ttl = NORR_TTL;
1130 	struct ub_packed_rrset_key* neg;
1131 	struct packed_rrset_data* newd;
1132 	if(rep) {
1133 		struct ub_packed_rrset_key* rrset = reply_get_NS_rrset(rep);
1134 		if(!rrset && rep->rrset_count != 0) rrset = rep->rrsets[0];
1135 		if(rrset) ttl = ub_packed_rrset_ttl(rrset);
1136 	}
1137 	/* create empty rrset to store */
1138 	neg = (struct ub_packed_rrset_key*)regional_alloc(env->scratch,
1139 	                sizeof(struct ub_packed_rrset_key));
1140 	if(!neg) {
1141 		log_err("out of memory in store_parentside_neg");
1142 		return;
1143 	}
1144 	memset(&neg->entry, 0, sizeof(neg->entry));
1145 	neg->entry.key = neg;
1146 	neg->rk.type = htons(qinfo->qtype);
1147 	neg->rk.rrset_class = htons(qinfo->qclass);
1148 	neg->rk.flags = 0;
1149 	neg->rk.dname = regional_alloc_init(env->scratch, qinfo->qname,
1150 		qinfo->qname_len);
1151 	if(!neg->rk.dname) {
1152 		log_err("out of memory in store_parentside_neg");
1153 		return;
1154 	}
1155 	neg->rk.dname_len = qinfo->qname_len;
1156 	neg->entry.hash = rrset_key_hash(&neg->rk);
1157 	newd = (struct packed_rrset_data*)regional_alloc_zero(env->scratch,
1158 		sizeof(struct packed_rrset_data) + sizeof(size_t) +
1159 		sizeof(uint8_t*) + sizeof(time_t) + sizeof(uint16_t));
1160 	if(!newd) {
1161 		log_err("out of memory in store_parentside_neg");
1162 		return;
1163 	}
1164 	neg->entry.data = newd;
1165 	newd->ttl = ttl;
1166 	/* entry must have one RR, otherwise not valid in cache.
1167 	 * put in one RR with empty rdata: those are ignored as nameserver */
1168 	newd->count = 1;
1169 	newd->rrsig_count = 0;
1170 	newd->trust = rrset_trust_ans_noAA;
1171 	newd->rr_len = (size_t*)((uint8_t*)newd +
1172 		sizeof(struct packed_rrset_data));
1173 	newd->rr_len[0] = 0 /* zero len rdata */ + sizeof(uint16_t);
1174 	packed_rrset_ptr_fixup(newd);
1175 	newd->rr_ttl[0] = newd->ttl;
1176 	sldns_write_uint16(newd->rr_data[0], 0 /* zero len rdata */);
1177 	/* store it */
1178 	log_rrset_key(VERB_ALGO, "store parent-side negative", neg);
1179 	iter_store_parentside_rrset(env, neg);
1180 }
1181 
1182 int
1183 iter_lookup_parent_NS_from_cache(struct module_env* env, struct delegpt* dp,
1184 	struct regional* region, struct query_info* qinfo)
1185 {
1186 	struct ub_packed_rrset_key* akey;
1187 	akey = rrset_cache_lookup(env->rrset_cache, dp->name,
1188 		dp->namelen, LDNS_RR_TYPE_NS, qinfo->qclass,
1189 		PACKED_RRSET_PARENT_SIDE, *env->now, 0);
1190 	if(akey) {
1191 		log_rrset_key(VERB_ALGO, "found parent-side NS in cache", akey);
1192 		dp->has_parent_side_NS = 1;
1193 		/* and mark the new names as lame */
1194 		if(!delegpt_rrset_add_ns(dp, region, akey, 1)) {
1195 			lock_rw_unlock(&akey->entry.lock);
1196 			return 0;
1197 		}
1198 		lock_rw_unlock(&akey->entry.lock);
1199 	}
1200 	return 1;
1201 }
1202 
1203 int iter_lookup_parent_glue_from_cache(struct module_env* env,
1204         struct delegpt* dp, struct regional* region, struct query_info* qinfo)
1205 {
1206 	struct ub_packed_rrset_key* akey;
1207 	struct delegpt_ns* ns;
1208 	size_t num = delegpt_count_targets(dp);
1209 	for(ns = dp->nslist; ns; ns = ns->next) {
1210 		/* get cached parentside A */
1211 		akey = rrset_cache_lookup(env->rrset_cache, ns->name,
1212 			ns->namelen, LDNS_RR_TYPE_A, qinfo->qclass,
1213 			PACKED_RRSET_PARENT_SIDE, *env->now, 0);
1214 		if(akey) {
1215 			log_rrset_key(VERB_ALGO, "found parent-side", akey);
1216 			ns->done_pside4 = 1;
1217 			/* a negative-cache-element has no addresses it adds */
1218 			if(!delegpt_add_rrset_A(dp, region, akey, 1, NULL))
1219 				log_err("malloc failure in lookup_parent_glue");
1220 			lock_rw_unlock(&akey->entry.lock);
1221 		}
1222 		/* get cached parentside AAAA */
1223 		akey = rrset_cache_lookup(env->rrset_cache, ns->name,
1224 			ns->namelen, LDNS_RR_TYPE_AAAA, qinfo->qclass,
1225 			PACKED_RRSET_PARENT_SIDE, *env->now, 0);
1226 		if(akey) {
1227 			log_rrset_key(VERB_ALGO, "found parent-side", akey);
1228 			ns->done_pside6 = 1;
1229 			/* a negative-cache-element has no addresses it adds */
1230 			if(!delegpt_add_rrset_AAAA(dp, region, akey, 1, NULL))
1231 				log_err("malloc failure in lookup_parent_glue");
1232 			lock_rw_unlock(&akey->entry.lock);
1233 		}
1234 	}
1235 	/* see if new (but lame) addresses have become available */
1236 	return delegpt_count_targets(dp) != num;
1237 }
1238 
1239 int
1240 iter_get_next_root(struct iter_hints* hints, struct iter_forwards* fwd,
1241 	uint16_t* c)
1242 {
1243 	uint16_t c1 = *c, c2 = *c;
1244 	int r1 = hints_next_root(hints, &c1);
1245 	int r2 = forwards_next_root(fwd, &c2);
1246 	if(!r1 && !r2) /* got none, end of list */
1247 		return 0;
1248 	else if(!r1) /* got one, return that */
1249 		*c = c2;
1250 	else if(!r2)
1251 		*c = c1;
1252 	else if(c1 < c2) /* got both take smallest */
1253 		*c = c1;
1254 	else	*c = c2;
1255 	return 1;
1256 }
1257 
1258 void
1259 iter_scrub_ds(struct dns_msg* msg, struct ub_packed_rrset_key* ns, uint8_t* z)
1260 {
1261 	/* Only the DS record for the delegation itself is expected.
1262 	 * We allow DS for everything between the bailiwick and the
1263 	 * zonecut, thus DS records must be at or above the zonecut.
1264 	 * And the DS records must be below the server authority zone.
1265 	 * The answer section is already scrubbed. */
1266 	size_t i = msg->rep->an_numrrsets;
1267 	while(i < (msg->rep->an_numrrsets + msg->rep->ns_numrrsets)) {
1268 		struct ub_packed_rrset_key* s = msg->rep->rrsets[i];
1269 		if(ntohs(s->rk.type) == LDNS_RR_TYPE_DS &&
1270 			(!ns || !dname_subdomain_c(ns->rk.dname, s->rk.dname)
1271 			|| query_dname_compare(z, s->rk.dname) == 0)) {
1272 			log_nametypeclass(VERB_ALGO, "removing irrelevant DS",
1273 				s->rk.dname, ntohs(s->rk.type),
1274 				ntohs(s->rk.rrset_class));
1275 			memmove(msg->rep->rrsets+i, msg->rep->rrsets+i+1,
1276 				sizeof(struct ub_packed_rrset_key*) *
1277 				(msg->rep->rrset_count-i-1));
1278 			msg->rep->ns_numrrsets--;
1279 			msg->rep->rrset_count--;
1280 			/* stay at same i, but new record */
1281 			continue;
1282 		}
1283 		i++;
1284 	}
1285 }
1286 
1287 void
1288 iter_scrub_nxdomain(struct dns_msg* msg)
1289 {
1290 	if(msg->rep->an_numrrsets == 0)
1291 		return;
1292 
1293 	memmove(msg->rep->rrsets, msg->rep->rrsets+msg->rep->an_numrrsets,
1294 		sizeof(struct ub_packed_rrset_key*) *
1295 		(msg->rep->rrset_count-msg->rep->an_numrrsets));
1296 	msg->rep->rrset_count -= msg->rep->an_numrrsets;
1297 	msg->rep->an_numrrsets = 0;
1298 }
1299 
1300 void iter_dec_attempts(struct delegpt* dp, int d, int outbound_msg_retry)
1301 {
1302 	struct delegpt_addr* a;
1303 	for(a=dp->target_list; a; a = a->next_target) {
1304 		if(a->attempts >= outbound_msg_retry) {
1305 			/* add back to result list */
1306 			a->next_result = dp->result_list;
1307 			dp->result_list = a;
1308 		}
1309 		if(a->attempts > d)
1310 			a->attempts -= d;
1311 		else a->attempts = 0;
1312 	}
1313 }
1314 
1315 void iter_merge_retry_counts(struct delegpt* dp, struct delegpt* old,
1316 	int outbound_msg_retry)
1317 {
1318 	struct delegpt_addr* a, *o, *prev;
1319 	for(a=dp->target_list; a; a = a->next_target) {
1320 		o = delegpt_find_addr(old, &a->addr, a->addrlen);
1321 		if(o) {
1322 			log_addr(VERB_ALGO, "copy attempt count previous dp",
1323 				&a->addr, a->addrlen);
1324 			a->attempts = o->attempts;
1325 		}
1326 	}
1327 	prev = NULL;
1328 	a = dp->usable_list;
1329 	while(a) {
1330 		if(a->attempts >= outbound_msg_retry) {
1331 			log_addr(VERB_ALGO, "remove from usable list dp",
1332 				&a->addr, a->addrlen);
1333 			/* remove from result list */
1334 			if(prev)
1335 				prev->next_usable = a->next_usable;
1336 			else	dp->usable_list = a->next_usable;
1337 			/* prev stays the same */
1338 			a = a->next_usable;
1339 			continue;
1340 		}
1341 		prev = a;
1342 		a = a->next_usable;
1343 	}
1344 }
1345 
1346 int
1347 iter_ds_toolow(struct dns_msg* msg, struct delegpt* dp)
1348 {
1349 	/* if for query example.com, there is example.com SOA or a subdomain
1350 	 * of example.com, then we are too low and need to fetch NS. */
1351 	size_t i;
1352 	/* if we have a DNAME or CNAME we are probably wrong */
1353 	/* if we have a qtype DS in the answer section, its fine */
1354 	for(i=0; i < msg->rep->an_numrrsets; i++) {
1355 		struct ub_packed_rrset_key* s = msg->rep->rrsets[i];
1356 		if(ntohs(s->rk.type) == LDNS_RR_TYPE_DNAME ||
1357 			ntohs(s->rk.type) == LDNS_RR_TYPE_CNAME) {
1358 			/* not the right answer, maybe too low, check the
1359 			 * RRSIG signer name (if there is any) for a hint
1360 			 * that it is from the dp zone anyway */
1361 			uint8_t* sname;
1362 			size_t slen;
1363 			val_find_rrset_signer(s, &sname, &slen);
1364 			if(sname && query_dname_compare(dp->name, sname)==0)
1365 				return 0; /* it is fine, from the right dp */
1366 			return 1;
1367 		}
1368 		if(ntohs(s->rk.type) == LDNS_RR_TYPE_DS)
1369 			return 0; /* fine, we have a DS record */
1370 	}
1371 	for(i=msg->rep->an_numrrsets;
1372 		i < msg->rep->an_numrrsets + msg->rep->ns_numrrsets; i++) {
1373 		struct ub_packed_rrset_key* s = msg->rep->rrsets[i];
1374 		if(ntohs(s->rk.type) == LDNS_RR_TYPE_SOA) {
1375 			if(dname_subdomain_c(s->rk.dname, msg->qinfo.qname))
1376 				return 1; /* point is too low */
1377 			if(query_dname_compare(s->rk.dname, dp->name)==0)
1378 				return 0; /* right dp */
1379 		}
1380 		if(ntohs(s->rk.type) == LDNS_RR_TYPE_NSEC ||
1381 			ntohs(s->rk.type) == LDNS_RR_TYPE_NSEC3) {
1382 			uint8_t* sname;
1383 			size_t slen;
1384 			val_find_rrset_signer(s, &sname, &slen);
1385 			if(sname && query_dname_compare(dp->name, sname)==0)
1386 				return 0; /* it is fine, from the right dp */
1387 			return 1;
1388 		}
1389 	}
1390 	/* we do not know */
1391 	return 1;
1392 }
1393 
1394 int iter_dp_cangodown(struct query_info* qinfo, struct delegpt* dp)
1395 {
1396 	/* no delegation point, do not see how we can go down,
1397 	 * robust check, it should really exist */
1398 	if(!dp) return 0;
1399 
1400 	/* see if dp equals the qname, then we cannot go down further */
1401 	if(query_dname_compare(qinfo->qname, dp->name) == 0)
1402 		return 0;
1403 	/* if dp is one label above the name we also cannot go down further */
1404 	if(dname_count_labels(qinfo->qname) == dp->namelabs+1)
1405 		return 0;
1406 	return 1;
1407 }
1408 
1409 int
1410 iter_stub_fwd_no_cache(struct module_qstate *qstate, struct query_info *qinf,
1411 	uint8_t** retdpname, size_t* retdpnamelen)
1412 {
1413 	struct iter_hints_stub *stub;
1414 	struct delegpt *dp;
1415 
1416 	/* Check for stub. */
1417 	stub = hints_lookup_stub(qstate->env->hints, qinf->qname,
1418 	    qinf->qclass, NULL);
1419 	dp = forwards_lookup(qstate->env->fwds, qinf->qname, qinf->qclass);
1420 
1421 	/* see if forward or stub is more pertinent */
1422 	if(stub && stub->dp && dp) {
1423 		if(dname_strict_subdomain(dp->name, dp->namelabs,
1424 			stub->dp->name, stub->dp->namelabs)) {
1425 			stub = NULL; /* ignore stub, forward is lower */
1426 		} else {
1427 			dp = NULL; /* ignore forward, stub is lower */
1428 		}
1429 	}
1430 
1431 	/* check stub */
1432 	if (stub != NULL && stub->dp != NULL) {
1433 		if(stub->dp->no_cache) {
1434 			char qname[255+1];
1435 			char dpname[255+1];
1436 			dname_str(qinf->qname, qname);
1437 			dname_str(stub->dp->name, dpname);
1438 			verbose(VERB_ALGO, "stub for %s %s has no_cache", qname, dpname);
1439 		}
1440 		if(retdpname) {
1441 			*retdpname = stub->dp->name;
1442 			*retdpnamelen = stub->dp->namelen;
1443 		}
1444 		return (stub->dp->no_cache);
1445 	}
1446 
1447 	/* Check for forward. */
1448 	if (dp) {
1449 		if(dp->no_cache) {
1450 			char qname[255+1];
1451 			char dpname[255+1];
1452 			dname_str(qinf->qname, qname);
1453 			dname_str(dp->name, dpname);
1454 			verbose(VERB_ALGO, "forward for %s %s has no_cache", qname, dpname);
1455 		}
1456 		if(retdpname) {
1457 			*retdpname = dp->name;
1458 			*retdpnamelen = dp->namelen;
1459 		}
1460 		return (dp->no_cache);
1461 	}
1462 	if(retdpname) {
1463 		*retdpname = NULL;
1464 		*retdpnamelen = 0;
1465 	}
1466 	return 0;
1467 }
1468 
1469 void iterator_set_ip46_support(struct module_stack* mods,
1470 	struct module_env* env, struct outside_network* outnet)
1471 {
1472 	int m = modstack_find(mods, "iterator");
1473 	struct iter_env* ie = NULL;
1474 	if(m == -1)
1475 		return;
1476 	ie = (struct iter_env*)env->modinfo[m];
1477 	if(outnet->pending == NULL)
1478 		return; /* we are in testbound, no rbtree for UDP */
1479 	if(outnet->num_ip4 == 0)
1480 		ie->supports_ipv4 = 0;
1481 	if(outnet->num_ip6 == 0)
1482 		ie->supports_ipv6 = 0;
1483 }
1484