xref: /freebsd/contrib/unbound/iterator/iterator.c (revision 96190b4fef3b4a0cc3ca0606b0c4e3e69a5e6717)
1 /*
2  * iterator/iterator.c - iterative resolver DNS query response module
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 a module that performs recursive iterative DNS query
40  * processing.
41  */
42 
43 #include "config.h"
44 #include "iterator/iterator.h"
45 #include "iterator/iter_utils.h"
46 #include "iterator/iter_hints.h"
47 #include "iterator/iter_fwd.h"
48 #include "iterator/iter_donotq.h"
49 #include "iterator/iter_delegpt.h"
50 #include "iterator/iter_resptype.h"
51 #include "iterator/iter_scrub.h"
52 #include "iterator/iter_priv.h"
53 #include "validator/val_neg.h"
54 #include "services/cache/dns.h"
55 #include "services/cache/rrset.h"
56 #include "services/cache/infra.h"
57 #include "services/authzone.h"
58 #include "util/module.h"
59 #include "util/netevent.h"
60 #include "util/net_help.h"
61 #include "util/regional.h"
62 #include "util/data/dname.h"
63 #include "util/data/msgencode.h"
64 #include "util/fptr_wlist.h"
65 #include "util/config_file.h"
66 #include "util/random.h"
67 #include "sldns/rrdef.h"
68 #include "sldns/wire2str.h"
69 #include "sldns/str2wire.h"
70 #include "sldns/parseutil.h"
71 #include "sldns/sbuffer.h"
72 
73 /* in msec */
74 int UNKNOWN_SERVER_NICENESS = 376;
75 /* in msec */
76 int USEFUL_SERVER_TOP_TIMEOUT = 120000;
77 /* Equals USEFUL_SERVER_TOP_TIMEOUT*4 */
78 int BLACKLIST_PENALTY = (120000*4);
79 
80 static void target_count_increase_nx(struct iter_qstate* iq, int num);
81 
82 int
83 iter_init(struct module_env* env, int id)
84 {
85 	struct iter_env* iter_env = (struct iter_env*)calloc(1,
86 		sizeof(struct iter_env));
87 	if(!iter_env) {
88 		log_err("malloc failure");
89 		return 0;
90 	}
91 	env->modinfo[id] = (void*)iter_env;
92 
93 	lock_basic_init(&iter_env->queries_ratelimit_lock);
94 	lock_protect(&iter_env->queries_ratelimit_lock,
95 			&iter_env->num_queries_ratelimited,
96 		sizeof(iter_env->num_queries_ratelimited));
97 
98 	if(!iter_apply_cfg(iter_env, env->cfg)) {
99 		log_err("iterator: could not apply configuration settings.");
100 		return 0;
101 	}
102 
103 	return 1;
104 }
105 
106 /** delete caps_whitelist element */
107 static void
108 caps_free(struct rbnode_type* n, void* ATTR_UNUSED(d))
109 {
110 	if(n) {
111 		free(((struct name_tree_node*)n)->name);
112 		free(n);
113 	}
114 }
115 
116 void
117 iter_deinit(struct module_env* env, int id)
118 {
119 	struct iter_env* iter_env;
120 	if(!env || !env->modinfo[id])
121 		return;
122 	iter_env = (struct iter_env*)env->modinfo[id];
123 	lock_basic_destroy(&iter_env->queries_ratelimit_lock);
124 	free(iter_env->target_fetch_policy);
125 	priv_delete(iter_env->priv);
126 	donotq_delete(iter_env->donotq);
127 	if(iter_env->caps_white) {
128 		traverse_postorder(iter_env->caps_white, caps_free, NULL);
129 		free(iter_env->caps_white);
130 	}
131 	free(iter_env);
132 	env->modinfo[id] = NULL;
133 }
134 
135 /** new query for iterator */
136 static int
137 iter_new(struct module_qstate* qstate, int id)
138 {
139 	struct iter_qstate* iq = (struct iter_qstate*)regional_alloc(
140 		qstate->region, sizeof(struct iter_qstate));
141 	qstate->minfo[id] = iq;
142 	if(!iq)
143 		return 0;
144 	memset(iq, 0, sizeof(*iq));
145 	iq->state = INIT_REQUEST_STATE;
146 	iq->final_state = FINISHED_STATE;
147 	iq->an_prepend_list = NULL;
148 	iq->an_prepend_last = NULL;
149 	iq->ns_prepend_list = NULL;
150 	iq->ns_prepend_last = NULL;
151 	iq->dp = NULL;
152 	iq->depth = 0;
153 	iq->num_target_queries = 0;
154 	iq->num_current_queries = 0;
155 	iq->query_restart_count = 0;
156 	iq->referral_count = 0;
157 	iq->sent_count = 0;
158 	iq->ratelimit_ok = 0;
159 	iq->target_count = NULL;
160 	iq->dp_target_count = 0;
161 	iq->wait_priming_stub = 0;
162 	iq->refetch_glue = 0;
163 	iq->dnssec_expected = 0;
164 	iq->dnssec_lame_query = 0;
165 	iq->chase_flags = qstate->query_flags;
166 	/* Start with the (current) qname. */
167 	iq->qchase = qstate->qinfo;
168 	outbound_list_init(&iq->outlist);
169 	iq->minimise_count = 0;
170 	iq->timeout_count = 0;
171 	if (qstate->env->cfg->qname_minimisation)
172 		iq->minimisation_state = INIT_MINIMISE_STATE;
173 	else
174 		iq->minimisation_state = DONOT_MINIMISE_STATE;
175 
176 	memset(&iq->qinfo_out, 0, sizeof(struct query_info));
177 	return 1;
178 }
179 
180 /**
181  * Transition to the next state. This can be used to advance a currently
182  * processing event. It cannot be used to reactivate a forEvent.
183  *
184  * @param iq: iterator query state
185  * @param nextstate The state to transition to.
186  * @return true. This is so this can be called as the return value for the
187  *         actual process*State() methods. (Transitioning to the next state
188  *         implies further processing).
189  */
190 static int
191 next_state(struct iter_qstate* iq, enum iter_state nextstate)
192 {
193 	/* If transitioning to a "response" state, make sure that there is a
194 	 * response */
195 	if(iter_state_is_responsestate(nextstate)) {
196 		if(iq->response == NULL) {
197 			log_err("transitioning to response state sans "
198 				"response.");
199 		}
200 	}
201 	iq->state = nextstate;
202 	return 1;
203 }
204 
205 /**
206  * Transition an event to its final state. Final states always either return
207  * a result up the module chain, or reactivate a dependent event. Which
208  * final state to transition to is set in the module state for the event when
209  * it was created, and depends on the original purpose of the event.
210  *
211  * The response is stored in the qstate->buf buffer.
212  *
213  * @param iq: iterator query state
214  * @return false. This is so this method can be used as the return value for
215  *         the processState methods. (Transitioning to the final state
216  */
217 static int
218 final_state(struct iter_qstate* iq)
219 {
220 	return next_state(iq, iq->final_state);
221 }
222 
223 /**
224  * Callback routine to handle errors in parent query states
225  * @param qstate: query state that failed.
226  * @param id: module id.
227  * @param super: super state.
228  */
229 static void
230 error_supers(struct module_qstate* qstate, int id, struct module_qstate* super)
231 {
232 	struct iter_env* ie = (struct iter_env*)qstate->env->modinfo[id];
233 	struct iter_qstate* super_iq = (struct iter_qstate*)super->minfo[id];
234 
235 	if(qstate->qinfo.qtype == LDNS_RR_TYPE_A ||
236 		qstate->qinfo.qtype == LDNS_RR_TYPE_AAAA) {
237 		/* mark address as failed. */
238 		struct delegpt_ns* dpns = NULL;
239 		super_iq->num_target_queries--;
240 		if(super_iq->dp)
241 			dpns = delegpt_find_ns(super_iq->dp,
242 				qstate->qinfo.qname, qstate->qinfo.qname_len);
243 		if(!dpns) {
244 			/* not interested */
245 			/* this can happen, for eg. qname minimisation asked
246 			 * for an NXDOMAIN to be validated, and used qtype
247 			 * A for that, and the error of that, the name, is
248 			 * not listed in super_iq->dp */
249 			verbose(VERB_ALGO, "subq error, but not interested");
250 			log_query_info(VERB_ALGO, "superq", &super->qinfo);
251 			return;
252 		} else {
253 			/* see if the failure did get (parent-lame) info */
254 			if(!cache_fill_missing(super->env, super_iq->qchase.qclass,
255 				super->region, super_iq->dp))
256 				log_err("out of memory adding missing");
257 		}
258 		delegpt_mark_neg(dpns, qstate->qinfo.qtype);
259 		if((dpns->got4 == 2 || (!ie->supports_ipv4 && !ie->use_nat64)) &&
260 			(dpns->got6 == 2 || !ie->supports_ipv6)) {
261 			dpns->resolved = 1; /* mark as failed */
262 			target_count_increase_nx(super_iq, 1);
263 		}
264 	}
265 	if(qstate->qinfo.qtype == LDNS_RR_TYPE_NS) {
266 		/* prime failed to get delegation */
267 		super_iq->dp = NULL;
268 	}
269 	/* evaluate targets again */
270 	super_iq->state = QUERYTARGETS_STATE;
271 	/* super becomes runnable, and will process this change */
272 }
273 
274 /**
275  * Return an error to the client
276  * @param qstate: our query state
277  * @param id: module id
278  * @param rcode: error code (DNS errcode).
279  * @return: 0 for use by caller, to make notation easy, like:
280  * 	return error_response(..).
281  */
282 static int
283 error_response(struct module_qstate* qstate, int id, int rcode)
284 {
285 	verbose(VERB_QUERY, "return error response %s",
286 		sldns_lookup_by_id(sldns_rcodes, rcode)?
287 		sldns_lookup_by_id(sldns_rcodes, rcode)->name:"??");
288 	qstate->return_rcode = rcode;
289 	qstate->return_msg = NULL;
290 	qstate->ext_state[id] = module_finished;
291 	return 0;
292 }
293 
294 /**
295  * Return an error to the client and cache the error code in the
296  * message cache (so per qname, qtype, qclass).
297  * @param qstate: our query state
298  * @param id: module id
299  * @param rcode: error code (DNS errcode).
300  * @return: 0 for use by caller, to make notation easy, like:
301  * 	return error_response(..).
302  */
303 static int
304 error_response_cache(struct module_qstate* qstate, int id, int rcode)
305 {
306 	struct reply_info err;
307 	struct msgreply_entry* msg;
308 	if(qstate->no_cache_store) {
309 		return error_response(qstate, id, rcode);
310 	}
311 	if(qstate->prefetch_leeway > NORR_TTL) {
312 		verbose(VERB_ALGO, "error response for prefetch in cache");
313 		/* attempt to adjust the cache entry prefetch */
314 		if(dns_cache_prefetch_adjust(qstate->env, &qstate->qinfo,
315 			NORR_TTL, qstate->query_flags))
316 			return error_response(qstate, id, rcode);
317 		/* if that fails (not in cache), fall through to store err */
318 	}
319 	if((msg=msg_cache_lookup(qstate->env,
320 		qstate->qinfo.qname, qstate->qinfo.qname_len,
321 		qstate->qinfo.qtype, qstate->qinfo.qclass,
322 		qstate->query_flags, 0,
323 		qstate->env->cfg->serve_expired_ttl_reset)) != NULL) {
324 		struct reply_info* rep = (struct reply_info*)msg->entry.data;
325 		if(qstate->env->cfg->serve_expired &&
326 			qstate->env->cfg->serve_expired_ttl_reset && rep &&
327 			*qstate->env->now + qstate->env->cfg->serve_expired_ttl
328 			> rep->serve_expired_ttl) {
329 			verbose(VERB_ALGO, "reset serve-expired-ttl for "
330 				"response in cache");
331 			rep->serve_expired_ttl = *qstate->env->now +
332 				qstate->env->cfg->serve_expired_ttl;
333 		}
334 		if(rep && (FLAGS_GET_RCODE(rep->flags) ==
335 			LDNS_RCODE_NOERROR ||
336 			FLAGS_GET_RCODE(rep->flags) ==
337 			LDNS_RCODE_NXDOMAIN ||
338 			FLAGS_GET_RCODE(rep->flags) ==
339 			LDNS_RCODE_YXDOMAIN) &&
340 			(qstate->env->cfg->serve_expired ||
341 			*qstate->env->now <= rep->ttl)) {
342 			/* we have a good entry, don't overwrite */
343 			lock_rw_unlock(&msg->entry.lock);
344 			return error_response(qstate, id, rcode);
345 		}
346 		lock_rw_unlock(&msg->entry.lock);
347 		/* nothing interesting is cached (already error response or
348 		 * expired good record when we don't serve expired), so this
349 		 * servfail cache entry is useful (stops waste of time on this
350 		 * servfail NORR_TTL) */
351 	}
352 	/* store in cache */
353 	memset(&err, 0, sizeof(err));
354 	err.flags = (uint16_t)(BIT_QR | BIT_RA);
355 	FLAGS_SET_RCODE(err.flags, rcode);
356 	err.qdcount = 1;
357 	err.ttl = NORR_TTL;
358 	err.prefetch_ttl = PREFETCH_TTL_CALC(err.ttl);
359 	err.serve_expired_ttl = NORR_TTL;
360 	/* do not waste time trying to validate this servfail */
361 	err.security = sec_status_indeterminate;
362 	verbose(VERB_ALGO, "store error response in message cache");
363 	iter_dns_store(qstate->env, &qstate->qinfo, &err, 0, 0, 0, NULL,
364 		qstate->query_flags, qstate->qstarttime);
365 	return error_response(qstate, id, rcode);
366 }
367 
368 /** check if prepend item is duplicate item */
369 static int
370 prepend_is_duplicate(struct ub_packed_rrset_key** sets, size_t to,
371 	struct ub_packed_rrset_key* dup)
372 {
373 	size_t i;
374 	for(i=0; i<to; i++) {
375 		if(sets[i]->rk.type == dup->rk.type &&
376 			sets[i]->rk.rrset_class == dup->rk.rrset_class &&
377 			sets[i]->rk.dname_len == dup->rk.dname_len &&
378 			query_dname_compare(sets[i]->rk.dname, dup->rk.dname)
379 			== 0)
380 			return 1;
381 	}
382 	return 0;
383 }
384 
385 /** prepend the prepend list in the answer and authority section of dns_msg */
386 static int
387 iter_prepend(struct iter_qstate* iq, struct dns_msg* msg,
388 	struct regional* region)
389 {
390 	struct iter_prep_list* p;
391 	struct ub_packed_rrset_key** sets;
392 	size_t num_an = 0, num_ns = 0;;
393 	for(p = iq->an_prepend_list; p; p = p->next)
394 		num_an++;
395 	for(p = iq->ns_prepend_list; p; p = p->next)
396 		num_ns++;
397 	if(num_an + num_ns == 0)
398 		return 1;
399 	verbose(VERB_ALGO, "prepending %d rrsets", (int)num_an + (int)num_ns);
400 	if(num_an > RR_COUNT_MAX || num_ns > RR_COUNT_MAX ||
401 		msg->rep->rrset_count > RR_COUNT_MAX) return 0; /* overflow */
402 	sets = regional_alloc(region, (num_an+num_ns+msg->rep->rrset_count) *
403 		sizeof(struct ub_packed_rrset_key*));
404 	if(!sets)
405 		return 0;
406 	/* ANSWER section */
407 	num_an = 0;
408 	for(p = iq->an_prepend_list; p; p = p->next) {
409 		sets[num_an++] = p->rrset;
410 		if(ub_packed_rrset_ttl(p->rrset) < msg->rep->ttl)
411 			msg->rep->ttl = ub_packed_rrset_ttl(p->rrset);
412 	}
413 	memcpy(sets+num_an, msg->rep->rrsets, msg->rep->an_numrrsets *
414 		sizeof(struct ub_packed_rrset_key*));
415 	/* AUTH section */
416 	num_ns = 0;
417 	for(p = iq->ns_prepend_list; p; p = p->next) {
418 		if(prepend_is_duplicate(sets+msg->rep->an_numrrsets+num_an,
419 			num_ns, p->rrset) || prepend_is_duplicate(
420 			msg->rep->rrsets+msg->rep->an_numrrsets,
421 			msg->rep->ns_numrrsets, p->rrset))
422 			continue;
423 		sets[msg->rep->an_numrrsets + num_an + num_ns++] = p->rrset;
424 		if(ub_packed_rrset_ttl(p->rrset) < msg->rep->ttl)
425 			msg->rep->ttl = ub_packed_rrset_ttl(p->rrset);
426 	}
427 	memcpy(sets + num_an + msg->rep->an_numrrsets + num_ns,
428 		msg->rep->rrsets + msg->rep->an_numrrsets,
429 		(msg->rep->ns_numrrsets + msg->rep->ar_numrrsets) *
430 		sizeof(struct ub_packed_rrset_key*));
431 
432 	/* NXDOMAIN rcode can stay if we prepended DNAME/CNAMEs, because
433 	 * this is what recursors should give. */
434 	msg->rep->rrset_count += num_an + num_ns;
435 	msg->rep->an_numrrsets += num_an;
436 	msg->rep->ns_numrrsets += num_ns;
437 	msg->rep->rrsets = sets;
438 	return 1;
439 }
440 
441 /**
442  * Find rrset in ANSWER prepend list.
443  * to avoid duplicate DNAMEs when a DNAME is traversed twice.
444  * @param iq: iterator query state.
445  * @param rrset: rrset to add.
446  * @return false if not found
447  */
448 static int
449 iter_find_rrset_in_prepend_answer(struct iter_qstate* iq,
450 	struct ub_packed_rrset_key* rrset)
451 {
452 	struct iter_prep_list* p = iq->an_prepend_list;
453 	while(p) {
454 		if(ub_rrset_compare(p->rrset, rrset) == 0 &&
455 			rrsetdata_equal((struct packed_rrset_data*)p->rrset
456 			->entry.data, (struct packed_rrset_data*)rrset
457 			->entry.data))
458 			return 1;
459 		p = p->next;
460 	}
461 	return 0;
462 }
463 
464 /**
465  * Add rrset to ANSWER prepend list
466  * @param qstate: query state.
467  * @param iq: iterator query state.
468  * @param rrset: rrset to add.
469  * @return false on failure (malloc).
470  */
471 static int
472 iter_add_prepend_answer(struct module_qstate* qstate, struct iter_qstate* iq,
473 	struct ub_packed_rrset_key* rrset)
474 {
475 	struct iter_prep_list* p = (struct iter_prep_list*)regional_alloc(
476 		qstate->region, sizeof(struct iter_prep_list));
477 	if(!p)
478 		return 0;
479 	p->rrset = rrset;
480 	p->next = NULL;
481 	/* add at end */
482 	if(iq->an_prepend_last)
483 		iq->an_prepend_last->next = p;
484 	else	iq->an_prepend_list = p;
485 	iq->an_prepend_last = p;
486 	return 1;
487 }
488 
489 /**
490  * Add rrset to AUTHORITY prepend list
491  * @param qstate: query state.
492  * @param iq: iterator query state.
493  * @param rrset: rrset to add.
494  * @return false on failure (malloc).
495  */
496 static int
497 iter_add_prepend_auth(struct module_qstate* qstate, struct iter_qstate* iq,
498 	struct ub_packed_rrset_key* rrset)
499 {
500 	struct iter_prep_list* p = (struct iter_prep_list*)regional_alloc(
501 		qstate->region, sizeof(struct iter_prep_list));
502 	if(!p)
503 		return 0;
504 	p->rrset = rrset;
505 	p->next = NULL;
506 	/* add at end */
507 	if(iq->ns_prepend_last)
508 		iq->ns_prepend_last->next = p;
509 	else	iq->ns_prepend_list = p;
510 	iq->ns_prepend_last = p;
511 	return 1;
512 }
513 
514 /**
515  * Given a CNAME response (defined as a response containing a CNAME or DNAME
516  * that does not answer the request), process the response, modifying the
517  * state as necessary. This follows the CNAME/DNAME chain and returns the
518  * final query name.
519  *
520  * sets the new query name, after following the CNAME/DNAME chain.
521  * @param qstate: query state.
522  * @param iq: iterator query state.
523  * @param msg: the response.
524  * @param mname: returned target new query name.
525  * @param mname_len: length of mname.
526  * @return false on (malloc) error.
527  */
528 static int
529 handle_cname_response(struct module_qstate* qstate, struct iter_qstate* iq,
530         struct dns_msg* msg, uint8_t** mname, size_t* mname_len)
531 {
532 	size_t i;
533 	/* Start with the (current) qname. */
534 	*mname = iq->qchase.qname;
535 	*mname_len = iq->qchase.qname_len;
536 
537 	/* Iterate over the ANSWER rrsets in order, looking for CNAMEs and
538 	 * DNAMES. */
539 	for(i=0; i<msg->rep->an_numrrsets; i++) {
540 		struct ub_packed_rrset_key* r = msg->rep->rrsets[i];
541 		/* If there is a (relevant) DNAME, add it to the list.
542 		 * We always expect there to be CNAME that was generated
543 		 * by this DNAME following, so we don't process the DNAME
544 		 * directly.  */
545 		if(ntohs(r->rk.type) == LDNS_RR_TYPE_DNAME &&
546 			dname_strict_subdomain_c(*mname, r->rk.dname) &&
547 			!iter_find_rrset_in_prepend_answer(iq, r)) {
548 			if(!iter_add_prepend_answer(qstate, iq, r))
549 				return 0;
550 			continue;
551 		}
552 
553 		if(ntohs(r->rk.type) == LDNS_RR_TYPE_CNAME &&
554 			query_dname_compare(*mname, r->rk.dname) == 0 &&
555 			!iter_find_rrset_in_prepend_answer(iq, r)) {
556 			/* Add this relevant CNAME rrset to the prepend list.*/
557 			if(!iter_add_prepend_answer(qstate, iq, r))
558 				return 0;
559 			get_cname_target(r, mname, mname_len);
560 		}
561 
562 		/* Other rrsets in the section are ignored. */
563 	}
564 	/* add authority rrsets to authority prepend, for wildcarded CNAMEs */
565 	for(i=msg->rep->an_numrrsets; i<msg->rep->an_numrrsets +
566 		msg->rep->ns_numrrsets; i++) {
567 		struct ub_packed_rrset_key* r = msg->rep->rrsets[i];
568 		/* only add NSEC/NSEC3, as they may be needed for validation */
569 		if(ntohs(r->rk.type) == LDNS_RR_TYPE_NSEC ||
570 			ntohs(r->rk.type) == LDNS_RR_TYPE_NSEC3) {
571 			if(!iter_add_prepend_auth(qstate, iq, r))
572 				return 0;
573 		}
574 	}
575 	return 1;
576 }
577 
578 /** fill fail address for later recovery */
579 static void
580 fill_fail_addr(struct iter_qstate* iq, struct sockaddr_storage* addr,
581 	socklen_t addrlen)
582 {
583 	if(addrlen == 0) {
584 		iq->fail_addr_type = 0;
585 		return;
586 	}
587 	if(((struct sockaddr_in*)addr)->sin_family == AF_INET) {
588 		iq->fail_addr_type = 4;
589 		memcpy(&iq->fail_addr.in,
590 			&((struct sockaddr_in*)addr)->sin_addr,
591 			sizeof(iq->fail_addr.in));
592 	}
593 #ifdef AF_INET6
594 	else if(((struct sockaddr_in*)addr)->sin_family == AF_INET6) {
595 		iq->fail_addr_type = 6;
596 		memcpy(&iq->fail_addr.in6,
597 			&((struct sockaddr_in6*)addr)->sin6_addr,
598 			sizeof(iq->fail_addr.in6));
599 	}
600 #endif
601 	else {
602 		iq->fail_addr_type = 0;
603 	}
604 }
605 
606 /** print fail addr to string */
607 static void
608 print_fail_addr(struct iter_qstate* iq, char* buf, size_t len)
609 {
610 	if(iq->fail_addr_type == 4) {
611 		if(inet_ntop(AF_INET, &iq->fail_addr.in, buf,
612 			(socklen_t)len) == 0)
613 			(void)strlcpy(buf, "(inet_ntop error)", len);
614 	}
615 #ifdef AF_INET6
616 	else if(iq->fail_addr_type == 6) {
617 		if(inet_ntop(AF_INET6, &iq->fail_addr.in6, buf,
618 			(socklen_t)len) == 0)
619 			(void)strlcpy(buf, "(inet_ntop error)", len);
620 	}
621 #endif
622 	else
623 		(void)strlcpy(buf, "", len);
624 }
625 
626 /** add response specific error information for log servfail */
627 static void
628 errinf_reply(struct module_qstate* qstate, struct iter_qstate* iq)
629 {
630 	if(qstate->env->cfg->val_log_level < 2 && !qstate->env->cfg->log_servfail)
631 		return;
632 	if((qstate->reply && qstate->reply->remote_addrlen != 0) ||
633 		(iq->fail_addr_type != 0)) {
634 		char from[256], frm[512];
635 		if(qstate->reply && qstate->reply->remote_addrlen != 0)
636 			addr_to_str(&qstate->reply->remote_addr,
637 				qstate->reply->remote_addrlen, from,
638 				sizeof(from));
639 		else
640 			print_fail_addr(iq, from, sizeof(from));
641 		snprintf(frm, sizeof(frm), "from %s", from);
642 		errinf(qstate, frm);
643 	}
644 	if(iq->scrub_failures || iq->parse_failures) {
645 		if(iq->scrub_failures)
646 			errinf(qstate, "upstream response failed scrub");
647 		if(iq->parse_failures)
648 			errinf(qstate, "could not parse upstream response");
649 	} else if(iq->response == NULL && iq->timeout_count != 0) {
650 		errinf(qstate, "upstream server timeout");
651 	} else if(iq->response == NULL) {
652 		errinf(qstate, "no server to query");
653 		if(iq->dp) {
654 			if(iq->dp->target_list == NULL)
655 				errinf(qstate, "no addresses for nameservers");
656 			else	errinf(qstate, "nameserver addresses not usable");
657 			if(iq->dp->nslist == NULL)
658 				errinf(qstate, "have no nameserver names");
659 			if(iq->dp->bogus)
660 				errinf(qstate, "NS record was dnssec bogus");
661 		}
662 	}
663 	if(iq->response && iq->response->rep) {
664 		if(FLAGS_GET_RCODE(iq->response->rep->flags) != 0) {
665 			char rcode[256], rc[32];
666 			(void)sldns_wire2str_rcode_buf(
667 				FLAGS_GET_RCODE(iq->response->rep->flags),
668 				rc, sizeof(rc));
669 			snprintf(rcode, sizeof(rcode), "got %s", rc);
670 			errinf(qstate, rcode);
671 		} else {
672 			/* rcode NOERROR */
673 			if(iq->response->rep->an_numrrsets == 0) {
674 				errinf(qstate, "nodata answer");
675 			}
676 		}
677 	}
678 }
679 
680 /** see if last resort is possible - does config allow queries to parent */
681 static int
682 can_have_last_resort(struct module_env* env, uint8_t* nm, size_t ATTR_UNUSED(nmlen),
683 	uint16_t qclass, int* have_dp, struct delegpt** retdp,
684 	struct regional* region)
685 {
686 	struct delegpt* dp = NULL;
687 	int nolock = 0;
688 	/* do not process a last resort (the parent side) if a stub
689 	 * or forward is configured, because we do not want to go 'above'
690 	 * the configured servers */
691 	if(!dname_is_root(nm) &&
692 		(dp = hints_find(env->hints, nm, qclass, nolock)) &&
693 		/* has_parent side is turned off for stub_first, where we
694 		 * are allowed to go to the parent */
695 		dp->has_parent_side_NS) {
696 		if(retdp) *retdp = delegpt_copy(dp, region);
697 		lock_rw_unlock(&env->hints->lock);
698 		if(have_dp) *have_dp = 1;
699 		return 0;
700 	}
701 	if(dp) {
702 		lock_rw_unlock(&env->hints->lock);
703 		dp = NULL;
704 	}
705 	if((dp = forwards_find(env->fwds, nm, qclass, nolock)) &&
706 		/* has_parent_side is turned off for forward_first, where
707 		 * we are allowed to go to the parent */
708 		dp->has_parent_side_NS) {
709 		if(retdp) *retdp = delegpt_copy(dp, region);
710 		lock_rw_unlock(&env->fwds->lock);
711 		if(have_dp) *have_dp = 1;
712 		return 0;
713 	}
714 	/* lock_() calls are macros that could be nothing, surround in {} */
715 	if(dp) { lock_rw_unlock(&env->fwds->lock); }
716 	return 1;
717 }
718 
719 /** see if target name is caps-for-id whitelisted */
720 static int
721 is_caps_whitelisted(struct iter_env* ie, struct iter_qstate* iq)
722 {
723 	if(!ie->caps_white) return 0; /* no whitelist, or no capsforid */
724 	return name_tree_lookup(ie->caps_white, iq->qchase.qname,
725 		iq->qchase.qname_len, dname_count_labels(iq->qchase.qname),
726 		iq->qchase.qclass) != NULL;
727 }
728 
729 /**
730  * Create target count structure for this query. This is always explicitly
731  * created for the parent query.
732  */
733 static void
734 target_count_create(struct iter_qstate* iq)
735 {
736 	if(!iq->target_count) {
737 		iq->target_count = (int*)calloc(TARGET_COUNT_MAX, sizeof(int));
738 		/* if calloc fails we simply do not track this number */
739 		if(iq->target_count) {
740 			iq->target_count[TARGET_COUNT_REF] = 1;
741 			iq->nxns_dp = (uint8_t**)calloc(1, sizeof(uint8_t*));
742 		}
743 	}
744 }
745 
746 static void
747 target_count_increase(struct iter_qstate* iq, int num)
748 {
749 	target_count_create(iq);
750 	if(iq->target_count)
751 		iq->target_count[TARGET_COUNT_QUERIES] += num;
752 	iq->dp_target_count++;
753 }
754 
755 static void
756 target_count_increase_nx(struct iter_qstate* iq, int num)
757 {
758 	target_count_create(iq);
759 	if(iq->target_count)
760 		iq->target_count[TARGET_COUNT_NX] += num;
761 }
762 
763 static void
764 target_count_increase_global_quota(struct iter_qstate* iq, int num)
765 {
766 	target_count_create(iq);
767 	if(iq->target_count)
768 		iq->target_count[TARGET_COUNT_GLOBAL_QUOTA] += num;
769 }
770 
771 /**
772  * Generate a subrequest.
773  * Generate a local request event. Local events are tied to this module, and
774  * have a corresponding (first tier) event that is waiting for this event to
775  * resolve to continue.
776  *
777  * @param qname The query name for this request.
778  * @param qnamelen length of qname
779  * @param qtype The query type for this request.
780  * @param qclass The query class for this request.
781  * @param qstate The event that is generating this event.
782  * @param id: module id.
783  * @param iq: The iterator state that is generating this event.
784  * @param initial_state The initial response state (normally this
785  *          is QUERY_RESP_STATE, unless it is known that the request won't
786  *          need iterative processing
787  * @param finalstate The final state for the response to this request.
788  * @param subq_ret: if newly allocated, the subquerystate, or NULL if it does
789  * 	not need initialisation.
790  * @param v: if true, validation is done on the subquery.
791  * @param detached: true if this qstate should not attach to the subquery
792  * @return false on error (malloc).
793  */
794 static int
795 generate_sub_request(uint8_t* qname, size_t qnamelen, uint16_t qtype,
796 	uint16_t qclass, struct module_qstate* qstate, int id,
797 	struct iter_qstate* iq, enum iter_state initial_state,
798 	enum iter_state finalstate, struct module_qstate** subq_ret, int v,
799 	int detached)
800 {
801 	struct module_qstate* subq = NULL;
802 	struct iter_qstate* subiq = NULL;
803 	uint16_t qflags = 0; /* OPCODE QUERY, no flags */
804 	struct query_info qinf;
805 	int prime = (finalstate == PRIME_RESP_STATE)?1:0;
806 	int valrec = 0;
807 	qinf.qname = qname;
808 	qinf.qname_len = qnamelen;
809 	qinf.qtype = qtype;
810 	qinf.qclass = qclass;
811 	qinf.local_alias = NULL;
812 
813 	/* RD should be set only when sending the query back through the INIT
814 	 * state. */
815 	if(initial_state == INIT_REQUEST_STATE)
816 		qflags |= BIT_RD;
817 	/* We set the CD flag so we can send this through the "head" of
818 	 * the resolution chain, which might have a validator. We are
819 	 * uninterested in validating things not on the direct resolution
820 	 * path.  */
821 	if(!v) {
822 		qflags |= BIT_CD;
823 		valrec = 1;
824 	}
825 
826 	if(detached) {
827 		struct mesh_state* sub = NULL;
828 		fptr_ok(fptr_whitelist_modenv_add_sub(
829 			qstate->env->add_sub));
830 		if(!(*qstate->env->add_sub)(qstate, &qinf,
831 			qflags, prime, valrec, &subq, &sub)){
832 			return 0;
833 		}
834 	}
835 	else {
836 		/* attach subquery, lookup existing or make a new one */
837 		fptr_ok(fptr_whitelist_modenv_attach_sub(
838 			qstate->env->attach_sub));
839 		if(!(*qstate->env->attach_sub)(qstate, &qinf, qflags, prime,
840 			valrec, &subq)) {
841 			return 0;
842 		}
843 	}
844 	*subq_ret = subq;
845 	if(subq) {
846 		/* initialise the new subquery */
847 		subq->curmod = id;
848 		subq->ext_state[id] = module_state_initial;
849 		subq->minfo[id] = regional_alloc(subq->region,
850 			sizeof(struct iter_qstate));
851 		if(!subq->minfo[id]) {
852 			log_err("init subq: out of memory");
853 			fptr_ok(fptr_whitelist_modenv_kill_sub(
854 				qstate->env->kill_sub));
855 			(*qstate->env->kill_sub)(subq);
856 			return 0;
857 		}
858 		subiq = (struct iter_qstate*)subq->minfo[id];
859 		memset(subiq, 0, sizeof(*subiq));
860 		subiq->num_target_queries = 0;
861 		target_count_create(iq);
862 		subiq->target_count = iq->target_count;
863 		if(iq->target_count) {
864 			iq->target_count[TARGET_COUNT_REF] ++; /* extra reference */
865 			subiq->nxns_dp = iq->nxns_dp;
866 		}
867 		subiq->dp_target_count = 0;
868 		subiq->num_current_queries = 0;
869 		subiq->depth = iq->depth+1;
870 		outbound_list_init(&subiq->outlist);
871 		subiq->state = initial_state;
872 		subiq->final_state = finalstate;
873 		subiq->qchase = subq->qinfo;
874 		subiq->chase_flags = subq->query_flags;
875 		subiq->refetch_glue = 0;
876 		if(qstate->env->cfg->qname_minimisation)
877 			subiq->minimisation_state = INIT_MINIMISE_STATE;
878 		else
879 			subiq->minimisation_state = DONOT_MINIMISE_STATE;
880 		memset(&subiq->qinfo_out, 0, sizeof(struct query_info));
881 	}
882 	return 1;
883 }
884 
885 /**
886  * Generate and send a root priming request.
887  * @param qstate: the qtstate that triggered the need to prime.
888  * @param iq: iterator query state.
889  * @param id: module id.
890  * @param qclass: the class to prime.
891  * @return 0 on failure
892  */
893 static int
894 prime_root(struct module_qstate* qstate, struct iter_qstate* iq, int id,
895 	uint16_t qclass)
896 {
897 	struct delegpt* dp;
898 	struct module_qstate* subq;
899 	int nolock = 0;
900 	verbose(VERB_DETAIL, "priming . %s NS",
901 		sldns_lookup_by_id(sldns_rr_classes, (int)qclass)?
902 		sldns_lookup_by_id(sldns_rr_classes, (int)qclass)->name:"??");
903 	dp = hints_find_root(qstate->env->hints, qclass, nolock);
904 	if(!dp) {
905 		verbose(VERB_ALGO, "Cannot prime due to lack of hints");
906 		return 0;
907 	}
908 	/* Priming requests start at the QUERYTARGETS state, skipping
909 	 * the normal INIT state logic (which would cause an infloop). */
910 	if(!generate_sub_request((uint8_t*)"\000", 1, LDNS_RR_TYPE_NS,
911 		qclass, qstate, id, iq, QUERYTARGETS_STATE, PRIME_RESP_STATE,
912 		&subq, 0, 0)) {
913 		lock_rw_unlock(&qstate->env->hints->lock);
914 		verbose(VERB_ALGO, "could not prime root");
915 		return 0;
916 	}
917 	if(subq) {
918 		struct iter_qstate* subiq =
919 			(struct iter_qstate*)subq->minfo[id];
920 		/* Set the initial delegation point to the hint.
921 		 * copy dp, it is now part of the root prime query.
922 		 * dp was part of in the fixed hints structure. */
923 		subiq->dp = delegpt_copy(dp, subq->region);
924 		lock_rw_unlock(&qstate->env->hints->lock);
925 		if(!subiq->dp) {
926 			log_err("out of memory priming root, copydp");
927 			fptr_ok(fptr_whitelist_modenv_kill_sub(
928 				qstate->env->kill_sub));
929 			(*qstate->env->kill_sub)(subq);
930 			return 0;
931 		}
932 		/* there should not be any target queries. */
933 		subiq->num_target_queries = 0;
934 		subiq->dnssec_expected = iter_indicates_dnssec(
935 			qstate->env, subiq->dp, NULL, subq->qinfo.qclass);
936 	} else {
937 		lock_rw_unlock(&qstate->env->hints->lock);
938 	}
939 
940 	/* this module stops, our submodule starts, and does the query. */
941 	qstate->ext_state[id] = module_wait_subquery;
942 	return 1;
943 }
944 
945 /**
946  * Generate and process a stub priming request. This method tests for the
947  * need to prime a stub zone, so it is safe to call for every request.
948  *
949  * @param qstate: the qtstate that triggered the need to prime.
950  * @param iq: iterator query state.
951  * @param id: module id.
952  * @param qname: request name.
953  * @param qclass: request class.
954  * @return true if a priming subrequest was made, false if not. The will only
955  *         issue a priming request if it detects an unprimed stub.
956  *         Uses value of 2 to signal during stub-prime in root-prime situation
957  *         that a noprime-stub is available and resolution can continue.
958  */
959 static int
960 prime_stub(struct module_qstate* qstate, struct iter_qstate* iq, int id,
961 	uint8_t* qname, uint16_t qclass)
962 {
963 	/* Lookup the stub hint. This will return null if the stub doesn't
964 	 * need to be re-primed. */
965 	struct iter_hints_stub* stub;
966 	struct delegpt* stub_dp;
967 	struct module_qstate* subq;
968 	int nolock = 0;
969 
970 	if(!qname) return 0;
971 	stub = hints_lookup_stub(qstate->env->hints, qname, qclass, iq->dp,
972 		nolock);
973 	/* The stub (if there is one) does not need priming. */
974 	if(!stub) return 0;
975 	stub_dp = stub->dp;
976 	/* if we have an auth_zone dp, and stub is equal, don't prime stub
977 	 * yet, unless we want to fallback and avoid the auth_zone */
978 	if(!iq->auth_zone_avoid && iq->dp && iq->dp->auth_dp &&
979 		query_dname_compare(iq->dp->name, stub_dp->name) == 0) {
980 		lock_rw_unlock(&qstate->env->hints->lock);
981 		return 0;
982 	}
983 
984 	/* is it a noprime stub (always use) */
985 	if(stub->noprime) {
986 		int r = 0;
987 		if(iq->dp == NULL) r = 2;
988 		/* copy the dp out of the fixed hints structure, so that
989 		 * it can be changed when servicing this query */
990 		iq->dp = delegpt_copy(stub_dp, qstate->region);
991 		lock_rw_unlock(&qstate->env->hints->lock);
992 		if(!iq->dp) {
993 			log_err("out of memory priming stub");
994 			errinf(qstate, "malloc failure, priming stub");
995 			(void)error_response(qstate, id, LDNS_RCODE_SERVFAIL);
996 			return 1; /* return 1 to make module stop, with error */
997 		}
998 		log_nametypeclass(VERB_DETAIL, "use stub", iq->dp->name,
999 			LDNS_RR_TYPE_NS, qclass);
1000 		return r;
1001 	}
1002 
1003 	/* Otherwise, we need to (re)prime the stub. */
1004 	log_nametypeclass(VERB_DETAIL, "priming stub", stub_dp->name,
1005 		LDNS_RR_TYPE_NS, qclass);
1006 
1007 	/* Stub priming events start at the QUERYTARGETS state to avoid the
1008 	 * redundant INIT state processing. */
1009 	if(!generate_sub_request(stub_dp->name, stub_dp->namelen,
1010 		LDNS_RR_TYPE_NS, qclass, qstate, id, iq,
1011 		QUERYTARGETS_STATE, PRIME_RESP_STATE, &subq, 0, 0)) {
1012 		lock_rw_unlock(&qstate->env->hints->lock);
1013 		verbose(VERB_ALGO, "could not prime stub");
1014 		errinf(qstate, "could not generate lookup for stub prime");
1015 		(void)error_response(qstate, id, LDNS_RCODE_SERVFAIL);
1016 		return 1; /* return 1 to make module stop, with error */
1017 	}
1018 	if(subq) {
1019 		struct iter_qstate* subiq =
1020 			(struct iter_qstate*)subq->minfo[id];
1021 
1022 		/* Set the initial delegation point to the hint. */
1023 		/* make copy to avoid use of stub dp by different qs/threads */
1024 		subiq->dp = delegpt_copy(stub_dp, subq->region);
1025 		lock_rw_unlock(&qstate->env->hints->lock);
1026 		if(!subiq->dp) {
1027 			log_err("out of memory priming stub, copydp");
1028 			fptr_ok(fptr_whitelist_modenv_kill_sub(
1029 				qstate->env->kill_sub));
1030 			(*qstate->env->kill_sub)(subq);
1031 			errinf(qstate, "malloc failure, in stub prime");
1032 			(void)error_response(qstate, id, LDNS_RCODE_SERVFAIL);
1033 			return 1; /* return 1 to make module stop, with error */
1034 		}
1035 		/* there should not be any target queries -- although there
1036 		 * wouldn't be anyway, since stub hints never have
1037 		 * missing targets. */
1038 		subiq->num_target_queries = 0;
1039 		subiq->wait_priming_stub = 1;
1040 		subiq->dnssec_expected = iter_indicates_dnssec(
1041 			qstate->env, subiq->dp, NULL, subq->qinfo.qclass);
1042 	} else {
1043 		lock_rw_unlock(&qstate->env->hints->lock);
1044 	}
1045 
1046 	/* this module stops, our submodule starts, and does the query. */
1047 	qstate->ext_state[id] = module_wait_subquery;
1048 	return 1;
1049 }
1050 
1051 /**
1052  * Generate a delegation point for an auth zone (unless cached dp is better)
1053  * false on alloc failure.
1054  */
1055 static int
1056 auth_zone_delegpt(struct module_qstate* qstate, struct iter_qstate* iq,
1057 	uint8_t* delname, size_t delnamelen)
1058 {
1059 	struct auth_zone* z;
1060 	if(iq->auth_zone_avoid)
1061 		return 1;
1062 	if(!delname) {
1063 		delname = iq->qchase.qname;
1064 		delnamelen = iq->qchase.qname_len;
1065 	}
1066 	lock_rw_rdlock(&qstate->env->auth_zones->lock);
1067 	z = auth_zones_find_zone(qstate->env->auth_zones, delname, delnamelen,
1068 		qstate->qinfo.qclass);
1069 	if(!z) {
1070 		lock_rw_unlock(&qstate->env->auth_zones->lock);
1071 		return 1;
1072 	}
1073 	lock_rw_rdlock(&z->lock);
1074 	lock_rw_unlock(&qstate->env->auth_zones->lock);
1075 	if(z->for_upstream) {
1076 		if(iq->dp && query_dname_compare(z->name, iq->dp->name) == 0
1077 			&& iq->dp->auth_dp && qstate->blacklist &&
1078 			z->fallback_enabled) {
1079 			/* cache is blacklisted and fallback, and we
1080 			 * already have an auth_zone dp */
1081 			if(verbosity>=VERB_ALGO) {
1082 				char buf[255+1];
1083 				dname_str(z->name, buf);
1084 				verbose(VERB_ALGO, "auth_zone %s "
1085 				  "fallback because cache blacklisted",
1086 				  buf);
1087 			}
1088 			lock_rw_unlock(&z->lock);
1089 			iq->dp = NULL;
1090 			return 1;
1091 		}
1092 		if(iq->dp==NULL || dname_subdomain_c(z->name, iq->dp->name)) {
1093 			struct delegpt* dp;
1094 			if(qstate->blacklist && z->fallback_enabled) {
1095 				/* cache is blacklisted because of a DNSSEC
1096 				 * validation failure, and the zone allows
1097 				 * fallback to the internet, query there. */
1098 				if(verbosity>=VERB_ALGO) {
1099 					char buf[255+1];
1100 					dname_str(z->name, buf);
1101 					verbose(VERB_ALGO, "auth_zone %s "
1102 					  "fallback because cache blacklisted",
1103 					  buf);
1104 				}
1105 				lock_rw_unlock(&z->lock);
1106 				return 1;
1107 			}
1108 			dp = (struct delegpt*)regional_alloc_zero(
1109 				qstate->region, sizeof(*dp));
1110 			if(!dp) {
1111 				log_err("alloc failure");
1112 				if(z->fallback_enabled) {
1113 					lock_rw_unlock(&z->lock);
1114 					return 1; /* just fallback */
1115 				}
1116 				lock_rw_unlock(&z->lock);
1117 				errinf(qstate, "malloc failure");
1118 				return 0;
1119 			}
1120 			dp->name = regional_alloc_init(qstate->region,
1121 				z->name, z->namelen);
1122 			if(!dp->name) {
1123 				log_err("alloc failure");
1124 				if(z->fallback_enabled) {
1125 					lock_rw_unlock(&z->lock);
1126 					return 1; /* just fallback */
1127 				}
1128 				lock_rw_unlock(&z->lock);
1129 				errinf(qstate, "malloc failure");
1130 				return 0;
1131 			}
1132 			dp->namelen = z->namelen;
1133 			dp->namelabs = z->namelabs;
1134 			dp->auth_dp = 1;
1135 			iq->dp = dp;
1136 		}
1137 	}
1138 
1139 	lock_rw_unlock(&z->lock);
1140 	return 1;
1141 }
1142 
1143 /**
1144  * Generate A and AAAA checks for glue that is in-zone for the referral
1145  * we just got to obtain authoritative information on the addresses.
1146  *
1147  * @param qstate: the qtstate that triggered the need to prime.
1148  * @param iq: iterator query state.
1149  * @param id: module id.
1150  */
1151 static void
1152 generate_a_aaaa_check(struct module_qstate* qstate, struct iter_qstate* iq,
1153 	int id)
1154 {
1155 	struct iter_env* ie = (struct iter_env*)qstate->env->modinfo[id];
1156 	struct module_qstate* subq;
1157 	size_t i;
1158 	struct reply_info* rep = iq->response->rep;
1159 	struct ub_packed_rrset_key* s;
1160 	log_assert(iq->dp);
1161 
1162 	if(iq->depth == ie->max_dependency_depth)
1163 		return;
1164 	/* walk through additional, and check if in-zone,
1165 	 * only relevant A, AAAA are left after scrub anyway */
1166 	for(i=rep->an_numrrsets+rep->ns_numrrsets; i<rep->rrset_count; i++) {
1167 		s = rep->rrsets[i];
1168 		/* check *ALL* addresses that are transmitted in additional*/
1169 		/* is it an address ? */
1170 		if( !(ntohs(s->rk.type)==LDNS_RR_TYPE_A ||
1171 			ntohs(s->rk.type)==LDNS_RR_TYPE_AAAA)) {
1172 			continue;
1173 		}
1174 		/* is this query the same as the A/AAAA check for it */
1175 		if(qstate->qinfo.qtype == ntohs(s->rk.type) &&
1176 			qstate->qinfo.qclass == ntohs(s->rk.rrset_class) &&
1177 			query_dname_compare(qstate->qinfo.qname,
1178 				s->rk.dname)==0 &&
1179 			(qstate->query_flags&BIT_RD) &&
1180 			!(qstate->query_flags&BIT_CD))
1181 			continue;
1182 
1183 		/* generate subrequest for it */
1184 		log_nametypeclass(VERB_ALGO, "schedule addr fetch",
1185 			s->rk.dname, ntohs(s->rk.type),
1186 			ntohs(s->rk.rrset_class));
1187 		if(!generate_sub_request(s->rk.dname, s->rk.dname_len,
1188 			ntohs(s->rk.type), ntohs(s->rk.rrset_class),
1189 			qstate, id, iq,
1190 			INIT_REQUEST_STATE, FINISHED_STATE, &subq, 1, 0)) {
1191 			verbose(VERB_ALGO, "could not generate addr check");
1192 			return;
1193 		}
1194 		/* ignore subq - not need for more init */
1195 	}
1196 }
1197 
1198 /**
1199  * Generate a NS check request to obtain authoritative information
1200  * on an NS rrset.
1201  *
1202  * @param qstate: the qstate that triggered the need to prime.
1203  * @param iq: iterator query state.
1204  * @param id: module id.
1205  */
1206 static void
1207 generate_ns_check(struct module_qstate* qstate, struct iter_qstate* iq, int id)
1208 {
1209 	struct iter_env* ie = (struct iter_env*)qstate->env->modinfo[id];
1210 	struct module_qstate* subq;
1211 	log_assert(iq->dp);
1212 
1213 	if(iq->depth == ie->max_dependency_depth)
1214 		return;
1215 	if(!can_have_last_resort(qstate->env, iq->dp->name, iq->dp->namelen,
1216 		iq->qchase.qclass, NULL, NULL, NULL))
1217 		return;
1218 	/* is this query the same as the nscheck? */
1219 	if(qstate->qinfo.qtype == LDNS_RR_TYPE_NS &&
1220 		query_dname_compare(iq->dp->name, qstate->qinfo.qname)==0 &&
1221 		(qstate->query_flags&BIT_RD) && !(qstate->query_flags&BIT_CD)){
1222 		/* spawn off A, AAAA queries for in-zone glue to check */
1223 		generate_a_aaaa_check(qstate, iq, id);
1224 		return;
1225 	}
1226 	/* no need to get the NS record for DS, it is above the zonecut */
1227 	if(qstate->qinfo.qtype == LDNS_RR_TYPE_DS)
1228 		return;
1229 
1230 	log_nametypeclass(VERB_ALGO, "schedule ns fetch",
1231 		iq->dp->name, LDNS_RR_TYPE_NS, iq->qchase.qclass);
1232 	if(!generate_sub_request(iq->dp->name, iq->dp->namelen,
1233 		LDNS_RR_TYPE_NS, iq->qchase.qclass, qstate, id, iq,
1234 		INIT_REQUEST_STATE, FINISHED_STATE, &subq, 1, 0)) {
1235 		verbose(VERB_ALGO, "could not generate ns check");
1236 		return;
1237 	}
1238 	if(subq) {
1239 		struct iter_qstate* subiq =
1240 			(struct iter_qstate*)subq->minfo[id];
1241 
1242 		/* make copy to avoid use of stub dp by different qs/threads */
1243 		/* refetch glue to start higher up the tree */
1244 		subiq->refetch_glue = 1;
1245 		subiq->dp = delegpt_copy(iq->dp, subq->region);
1246 		if(!subiq->dp) {
1247 			log_err("out of memory generating ns check, copydp");
1248 			fptr_ok(fptr_whitelist_modenv_kill_sub(
1249 				qstate->env->kill_sub));
1250 			(*qstate->env->kill_sub)(subq);
1251 			return;
1252 		}
1253 	}
1254 }
1255 
1256 /**
1257  * Generate a DNSKEY prefetch query to get the DNSKEY for the DS record we
1258  * just got in a referral (where we have dnssec_expected, thus have trust
1259  * anchors above it).  Note that right after calling this routine the
1260  * iterator detached subqueries (because of following the referral), and thus
1261  * the DNSKEY query becomes detached, its return stored in the cache for
1262  * later lookup by the validator.  This cache lookup by the validator avoids
1263  * the roundtrip incurred by the DNSKEY query.  The DNSKEY query is now
1264  * performed at about the same time the original query is sent to the domain,
1265  * thus the two answers are likely to be returned at about the same time,
1266  * saving a roundtrip from the validated lookup.
1267  *
1268  * @param qstate: the qtstate that triggered the need to prime.
1269  * @param iq: iterator query state.
1270  * @param id: module id.
1271  */
1272 static void
1273 generate_dnskey_prefetch(struct module_qstate* qstate,
1274 	struct iter_qstate* iq, int id)
1275 {
1276 	struct module_qstate* subq;
1277 	log_assert(iq->dp);
1278 
1279 	/* is this query the same as the prefetch? */
1280 	if(qstate->qinfo.qtype == LDNS_RR_TYPE_DNSKEY &&
1281 		query_dname_compare(iq->dp->name, qstate->qinfo.qname)==0 &&
1282 		(qstate->query_flags&BIT_RD) && !(qstate->query_flags&BIT_CD)){
1283 		return;
1284 	}
1285 	/* we do not generate this prefetch when the query list is full,
1286 	 * the query is fetched, if needed, when the validator wants it.
1287 	 * At that time the validator waits for it, after spawning it.
1288 	 * This means there is one state that uses cpu and a socket, the
1289 	 * spawned while this one waits, and not several at the same time,
1290 	 * if we had created the lookup here. And this helps to keep
1291 	 * the total load down, but the query still succeeds to resolve. */
1292 	if(mesh_jostle_exceeded(qstate->env->mesh))
1293 		return;
1294 
1295 	/* if the DNSKEY is in the cache this lookup will stop quickly */
1296 	log_nametypeclass(VERB_ALGO, "schedule dnskey prefetch",
1297 		iq->dp->name, LDNS_RR_TYPE_DNSKEY, iq->qchase.qclass);
1298 	if(!generate_sub_request(iq->dp->name, iq->dp->namelen,
1299 		LDNS_RR_TYPE_DNSKEY, iq->qchase.qclass, qstate, id, iq,
1300 		INIT_REQUEST_STATE, FINISHED_STATE, &subq, 0, 0)) {
1301 		/* we'll be slower, but it'll work */
1302 		verbose(VERB_ALGO, "could not generate dnskey prefetch");
1303 		return;
1304 	}
1305 	if(subq) {
1306 		struct iter_qstate* subiq =
1307 			(struct iter_qstate*)subq->minfo[id];
1308 		/* this qstate has the right delegation for the dnskey lookup*/
1309 		/* make copy to avoid use of stub dp by different qs/threads */
1310 		subiq->dp = delegpt_copy(iq->dp, subq->region);
1311 		/* if !subiq->dp, it'll start from the cache, no problem */
1312 	}
1313 }
1314 
1315 /**
1316  * See if the query needs forwarding.
1317  *
1318  * @param qstate: query state.
1319  * @param iq: iterator query state.
1320  * @return true if the request is forwarded, false if not.
1321  * 	If returns true but, iq->dp is NULL then a malloc failure occurred.
1322  */
1323 static int
1324 forward_request(struct module_qstate* qstate, struct iter_qstate* iq)
1325 {
1326 	struct delegpt* dp;
1327 	uint8_t* delname = iq->qchase.qname;
1328 	size_t delnamelen = iq->qchase.qname_len;
1329 	int nolock = 0;
1330 	if(iq->refetch_glue && iq->dp) {
1331 		delname = iq->dp->name;
1332 		delnamelen = iq->dp->namelen;
1333 	}
1334 	/* strip one label off of DS query to lookup higher for it */
1335 	if( (iq->qchase.qtype == LDNS_RR_TYPE_DS || iq->refetch_glue)
1336 		&& !dname_is_root(iq->qchase.qname))
1337 		dname_remove_label(&delname, &delnamelen);
1338 	dp = forwards_lookup(qstate->env->fwds, delname, iq->qchase.qclass,
1339 		nolock);
1340 	if(!dp) return 0;
1341 	/* send recursion desired to forward addr */
1342 	iq->chase_flags |= BIT_RD;
1343 	iq->dp = delegpt_copy(dp, qstate->region);
1344 	lock_rw_unlock(&qstate->env->fwds->lock);
1345 	/* iq->dp checked by caller */
1346 	verbose(VERB_ALGO, "forwarding request");
1347 	return 1;
1348 }
1349 
1350 /**
1351  * Process the initial part of the request handling. This state roughly
1352  * corresponds to resolver algorithms steps 1 (find answer in cache) and 2
1353  * (find the best servers to ask).
1354  *
1355  * Note that all requests start here, and query restarts revisit this state.
1356  *
1357  * This state either generates: 1) a response, from cache or error, 2) a
1358  * priming event, or 3) forwards the request to the next state (init2,
1359  * generally).
1360  *
1361  * @param qstate: query state.
1362  * @param iq: iterator query state.
1363  * @param ie: iterator shared global environment.
1364  * @param id: module id.
1365  * @return true if the event needs more request processing immediately,
1366  *         false if not.
1367  */
1368 static int
1369 processInitRequest(struct module_qstate* qstate, struct iter_qstate* iq,
1370 	struct iter_env* ie, int id)
1371 {
1372 	uint8_t dpname_storage[LDNS_MAX_DOMAINLEN+1];
1373 	uint8_t* delname, *dpname=NULL;
1374 	size_t delnamelen, dpnamelen=0;
1375 	struct dns_msg* msg = NULL;
1376 
1377 	log_query_info(VERB_DETAIL, "resolving", &qstate->qinfo);
1378 	/* check effort */
1379 
1380 	/* We enforce a maximum number of query restarts. This is primarily a
1381 	 * cheap way to prevent CNAME loops. */
1382 	if(iq->query_restart_count > ie->max_query_restarts) {
1383 		verbose(VERB_QUERY, "request has exceeded the maximum number"
1384 			" of query restarts with %d", iq->query_restart_count);
1385 		errinf(qstate, "request has exceeded the maximum number "
1386 			"restarts (eg. indirections)");
1387 		if(iq->qchase.qname)
1388 			errinf_dname(qstate, "stop at", iq->qchase.qname);
1389 		return error_response_cache(qstate, id, LDNS_RCODE_SERVFAIL);
1390 	}
1391 
1392 	/* We enforce a maximum recursion/dependency depth -- in general,
1393 	 * this is unnecessary for dependency loops (although it will
1394 	 * catch those), but it provides a sensible limit to the amount
1395 	 * of work required to answer a given query. */
1396 	verbose(VERB_ALGO, "request has dependency depth of %d", iq->depth);
1397 	if(iq->depth > ie->max_dependency_depth) {
1398 		verbose(VERB_QUERY, "request has exceeded the maximum "
1399 			"dependency depth with depth of %d", iq->depth);
1400 		errinf(qstate, "request has exceeded the maximum dependency "
1401 			"depth (eg. nameserver lookup recursion)");
1402 		return error_response(qstate, id, LDNS_RCODE_SERVFAIL);
1403 	}
1404 
1405 	/* If the request is qclass=ANY, setup to generate each class */
1406 	if(qstate->qinfo.qclass == LDNS_RR_CLASS_ANY) {
1407 		iq->qchase.qclass = 0;
1408 		return next_state(iq, COLLECT_CLASS_STATE);
1409 	}
1410 
1411 	/*
1412 	 * If we are restricted by a forward-zone or a stub-zone, we
1413 	 * can't re-fetch glue for this delegation point.
1414 	 * we won’t try to re-fetch glue if the iq->dp is null.
1415 	 */
1416 	if (iq->refetch_glue &&
1417 	        iq->dp &&
1418 	        !can_have_last_resort(qstate->env, iq->dp->name,
1419 	             iq->dp->namelen, iq->qchase.qclass, NULL, NULL, NULL)) {
1420 	    iq->refetch_glue = 0;
1421 	}
1422 
1423 	/* Resolver Algorithm Step 1 -- Look for the answer in local data. */
1424 
1425 	/* This either results in a query restart (CNAME cache response), a
1426 	 * terminating response (ANSWER), or a cache miss (null). */
1427 
1428 	/* Check RPZ for override */
1429 	if(qstate->env->auth_zones) {
1430 		/* apply rpz qname triggers, like after cname */
1431 		struct dns_msg* forged_response =
1432 			rpz_callback_from_iterator_cname(qstate, iq);
1433 		if(forged_response) {
1434 			uint8_t* sname = 0;
1435 			size_t slen = 0;
1436 			int count = 0;
1437 			while(forged_response && reply_find_rrset_section_an(
1438 				forged_response->rep, iq->qchase.qname,
1439 				iq->qchase.qname_len, LDNS_RR_TYPE_CNAME,
1440 				iq->qchase.qclass) &&
1441 				iq->qchase.qtype != LDNS_RR_TYPE_CNAME &&
1442 				count++ < ie->max_query_restarts) {
1443 				/* another cname to follow */
1444 				if(!handle_cname_response(qstate, iq, forged_response,
1445 					&sname, &slen)) {
1446 					errinf(qstate, "malloc failure, CNAME info");
1447 					return error_response(qstate, id, LDNS_RCODE_SERVFAIL);
1448 				}
1449 				iq->qchase.qname = sname;
1450 				iq->qchase.qname_len = slen;
1451 				forged_response =
1452 					rpz_callback_from_iterator_cname(qstate, iq);
1453 			}
1454 			if(forged_response != NULL) {
1455 				qstate->ext_state[id] = module_finished;
1456 				qstate->return_rcode = LDNS_RCODE_NOERROR;
1457 				qstate->return_msg = forged_response;
1458 				iq->response = forged_response;
1459 				next_state(iq, FINISHED_STATE);
1460 				if(!iter_prepend(iq, qstate->return_msg, qstate->region)) {
1461 					log_err("rpz: after cached cname, prepend rrsets: out of memory");
1462 					return error_response(qstate, id, LDNS_RCODE_SERVFAIL);
1463 				}
1464 				qstate->return_msg->qinfo = qstate->qinfo;
1465 				return 0;
1466 			}
1467 			/* Follow the CNAME response */
1468 			iq->dp = NULL;
1469 			iq->refetch_glue = 0;
1470 			iq->query_restart_count++;
1471 			iq->sent_count = 0;
1472 			iq->dp_target_count = 0;
1473 			sock_list_insert(&qstate->reply_origin, NULL, 0, qstate->region);
1474 			if(qstate->env->cfg->qname_minimisation)
1475 				iq->minimisation_state = INIT_MINIMISE_STATE;
1476 			return next_state(iq, INIT_REQUEST_STATE);
1477 		}
1478 	}
1479 
1480 	if (iter_stub_fwd_no_cache(qstate, &iq->qchase, &dpname, &dpnamelen,
1481 		dpname_storage, sizeof(dpname_storage))) {
1482 		/* Asked to not query cache. */
1483 		verbose(VERB_ALGO, "no-cache set, going to the network");
1484 		qstate->no_cache_lookup = 1;
1485 		qstate->no_cache_store = 1;
1486 		msg = NULL;
1487 	} else if(qstate->blacklist) {
1488 		/* if cache, or anything else, was blacklisted then
1489 		 * getting older results from cache is a bad idea, no cache */
1490 		verbose(VERB_ALGO, "cache blacklisted, going to the network");
1491 		msg = NULL;
1492 	} else if(!qstate->no_cache_lookup) {
1493 		msg = dns_cache_lookup(qstate->env, iq->qchase.qname,
1494 			iq->qchase.qname_len, iq->qchase.qtype,
1495 			iq->qchase.qclass, qstate->query_flags,
1496 			qstate->region, qstate->env->scratch, 0, dpname,
1497 			dpnamelen);
1498 		if(!msg && qstate->env->neg_cache &&
1499 			iter_qname_indicates_dnssec(qstate->env, &iq->qchase)) {
1500 			/* lookup in negative cache; may result in
1501 			 * NOERROR/NODATA or NXDOMAIN answers that need validation */
1502 			msg = val_neg_getmsg(qstate->env->neg_cache, &iq->qchase,
1503 				qstate->region, qstate->env->rrset_cache,
1504 				qstate->env->scratch_buffer,
1505 				*qstate->env->now, 1/*add SOA*/, NULL,
1506 				qstate->env->cfg);
1507 		}
1508 		/* item taken from cache does not match our query name, thus
1509 		 * security needs to be re-examined later */
1510 		if(msg && query_dname_compare(qstate->qinfo.qname,
1511 			iq->qchase.qname) != 0)
1512 			msg->rep->security = sec_status_unchecked;
1513 	}
1514 	if(msg) {
1515 		/* handle positive cache response */
1516 		enum response_type type = response_type_from_cache(msg,
1517 			&iq->qchase);
1518 		if(verbosity >= VERB_ALGO) {
1519 			log_dns_msg("msg from cache lookup", &msg->qinfo,
1520 				msg->rep);
1521 			verbose(VERB_ALGO, "msg ttl is %d, prefetch ttl %d",
1522 				(int)msg->rep->ttl,
1523 				(int)msg->rep->prefetch_ttl);
1524 		}
1525 
1526 		if(type == RESPONSE_TYPE_CNAME) {
1527 			uint8_t* sname = 0;
1528 			size_t slen = 0;
1529 			verbose(VERB_ALGO, "returning CNAME response from "
1530 				"cache");
1531 			if(!handle_cname_response(qstate, iq, msg,
1532 				&sname, &slen)) {
1533 				errinf(qstate, "failed to prepend CNAME "
1534 					"components, malloc failure");
1535 				return error_response(qstate, id,
1536 					LDNS_RCODE_SERVFAIL);
1537 			}
1538 			iq->qchase.qname = sname;
1539 			iq->qchase.qname_len = slen;
1540 			/* This *is* a query restart, even if it is a cheap
1541 			 * one. */
1542 			iq->dp = NULL;
1543 			iq->refetch_glue = 0;
1544 			iq->query_restart_count++;
1545 			iq->sent_count = 0;
1546 			iq->dp_target_count = 0;
1547 			sock_list_insert(&qstate->reply_origin, NULL, 0, qstate->region);
1548 			if(qstate->env->cfg->qname_minimisation)
1549 				iq->minimisation_state = INIT_MINIMISE_STATE;
1550 			return next_state(iq, INIT_REQUEST_STATE);
1551 		}
1552 		/* if from cache, NULL, else insert 'cache IP' len=0 */
1553 		if(qstate->reply_origin)
1554 			sock_list_insert(&qstate->reply_origin, NULL, 0, qstate->region);
1555 		if(FLAGS_GET_RCODE(msg->rep->flags) == LDNS_RCODE_SERVFAIL)
1556 			errinf(qstate, "SERVFAIL in cache");
1557 		/* it is an answer, response, to final state */
1558 		verbose(VERB_ALGO, "returning answer from cache.");
1559 		iq->response = msg;
1560 		return final_state(iq);
1561 	}
1562 
1563 	/* attempt to forward the request */
1564 	if(forward_request(qstate, iq))
1565 	{
1566 		if(!iq->dp) {
1567 			log_err("alloc failure for forward dp");
1568 			errinf(qstate, "malloc failure for forward zone");
1569 			return error_response(qstate, id, LDNS_RCODE_SERVFAIL);
1570 		}
1571 		if(!cache_fill_missing(qstate->env, iq->qchase.qclass,
1572 			qstate->region, iq->dp)) {
1573 			errinf(qstate, "malloc failure, copy extra info into delegation point");
1574 			return error_response(qstate, id, LDNS_RCODE_SERVFAIL);
1575 		}
1576 		if((qstate->query_flags&BIT_RD)==0) {
1577 			/* If the server accepts RD=0 queries and forwards
1578 			 * with RD=1, then if the server is listed as an NS
1579 			 * entry, it starts query loops. Stop that loop by
1580 			 * disallowing the query. The RD=0 was previously used
1581 			 * to check the cache with allow_snoop. For stubs,
1582 			 * the iterator pass would have primed the stub and
1583 			 * then cached information can be used for further
1584 			 * queries. */
1585 			verbose(VERB_ALGO, "cannot forward RD=0 query, to stop query loops");
1586 			errinf(qstate, "cannot forward RD=0 query");
1587 			return error_response(qstate, id, LDNS_RCODE_SERVFAIL);
1588 		}
1589 		iq->refetch_glue = 0;
1590 		iq->minimisation_state = DONOT_MINIMISE_STATE;
1591 		/* the request has been forwarded.
1592 		 * forwarded requests need to be immediately sent to the
1593 		 * next state, QUERYTARGETS. */
1594 		return next_state(iq, QUERYTARGETS_STATE);
1595 	}
1596 
1597 	/* Resolver Algorithm Step 2 -- find the "best" servers. */
1598 
1599 	/* first, adjust for DS queries. To avoid the grandparent problem,
1600 	 * we just look for the closest set of server to the parent of qname.
1601 	 * When re-fetching glue we also need to ask the parent.
1602 	 */
1603 	if(iq->refetch_glue) {
1604 		if(!iq->dp) {
1605 			log_err("internal or malloc fail: no dp for refetch");
1606 			errinf(qstate, "malloc failure, for delegation info");
1607 			return error_response(qstate, id, LDNS_RCODE_SERVFAIL);
1608 		}
1609 		delname = iq->dp->name;
1610 		delnamelen = iq->dp->namelen;
1611 	} else {
1612 		delname = iq->qchase.qname;
1613 		delnamelen = iq->qchase.qname_len;
1614 	}
1615 	if(iq->qchase.qtype == LDNS_RR_TYPE_DS || iq->refetch_glue ||
1616 	   (iq->qchase.qtype == LDNS_RR_TYPE_NS && qstate->prefetch_leeway
1617 	   && can_have_last_resort(qstate->env, delname, delnamelen, iq->qchase.qclass, NULL, NULL, NULL))) {
1618 		/* remove first label from delname, root goes to hints,
1619 		 * but only to fetch glue, not for qtype=DS. */
1620 		/* also when prefetching an NS record, fetch it again from
1621 		 * its parent, just as if it expired, so that you do not
1622 		 * get stuck on an older nameserver that gives old NSrecords */
1623 		if(dname_is_root(delname) && (iq->refetch_glue ||
1624 			(iq->qchase.qtype == LDNS_RR_TYPE_NS &&
1625 			qstate->prefetch_leeway)))
1626 			delname = NULL; /* go to root priming */
1627 		else 	dname_remove_label(&delname, &delnamelen);
1628 	}
1629 	/* delname is the name to lookup a delegation for. If NULL rootprime */
1630 	while(1) {
1631 
1632 		/* Lookup the delegation in the cache. If null, then the
1633 		 * cache needs to be primed for the qclass. */
1634 		if(delname)
1635 		     iq->dp = dns_cache_find_delegation(qstate->env, delname,
1636 			delnamelen, iq->qchase.qtype, iq->qchase.qclass,
1637 			qstate->region, &iq->deleg_msg,
1638 			*qstate->env->now+qstate->prefetch_leeway, 1,
1639 			dpname, dpnamelen);
1640 		else iq->dp = NULL;
1641 
1642 		/* If the cache has returned nothing, then we have a
1643 		 * root priming situation. */
1644 		if(iq->dp == NULL) {
1645 			int r;
1646 			int nolock = 0;
1647 			/* if under auth zone, no prime needed */
1648 			if(!auth_zone_delegpt(qstate, iq, delname, delnamelen))
1649 				return error_response(qstate, id,
1650 					LDNS_RCODE_SERVFAIL);
1651 			if(iq->dp) /* use auth zone dp */
1652 				return next_state(iq, INIT_REQUEST_2_STATE);
1653 			/* if there is a stub, then no root prime needed */
1654 			r = prime_stub(qstate, iq, id, delname,
1655 				iq->qchase.qclass);
1656 			if(r == 2)
1657 				break; /* got noprime-stub-zone, continue */
1658 			else if(r)
1659 				return 0; /* stub prime request made */
1660 			if(forwards_lookup_root(qstate->env->fwds,
1661 				iq->qchase.qclass, nolock)) {
1662 				lock_rw_unlock(&qstate->env->fwds->lock);
1663 				/* forward zone root, no root prime needed */
1664 				/* fill in some dp - safety belt */
1665 				iq->dp = hints_find_root(qstate->env->hints,
1666 					iq->qchase.qclass, nolock);
1667 				if(!iq->dp) {
1668 					log_err("internal error: no hints dp");
1669 					errinf(qstate, "no hints for this class");
1670 					return error_response_cache(qstate, id,
1671 						LDNS_RCODE_SERVFAIL);
1672 				}
1673 				iq->dp = delegpt_copy(iq->dp, qstate->region);
1674 				lock_rw_unlock(&qstate->env->hints->lock);
1675 				if(!iq->dp) {
1676 					log_err("out of memory in safety belt");
1677 					errinf(qstate, "malloc failure, in safety belt");
1678 					return error_response(qstate, id,
1679 						LDNS_RCODE_SERVFAIL);
1680 				}
1681 				return next_state(iq, INIT_REQUEST_2_STATE);
1682 			}
1683 			/* Note that the result of this will set a new
1684 			 * DelegationPoint based on the result of priming. */
1685 			if(!prime_root(qstate, iq, id, iq->qchase.qclass))
1686 				return error_response(qstate, id,
1687 					LDNS_RCODE_REFUSED);
1688 
1689 			/* priming creates and sends a subordinate query, with
1690 			 * this query as the parent. So further processing for
1691 			 * this event will stop until reactivated by the
1692 			 * results of priming. */
1693 			return 0;
1694 		}
1695 		if(!iq->ratelimit_ok && qstate->prefetch_leeway)
1696 			iq->ratelimit_ok = 1; /* allow prefetches, this keeps
1697 			otherwise valid data in the cache */
1698 
1699 		/* see if this dp not useless.
1700 		 * It is useless if:
1701 		 *	o all NS items are required glue.
1702 		 *	  or the query is for NS item that is required glue.
1703 		 *	o no addresses are provided.
1704 		 *	o RD qflag is on.
1705 		 * Instead, go up one level, and try to get even further
1706 		 * If the root was useless, use safety belt information.
1707 		 * Only check cache returns, because replies for servers
1708 		 * could be useless but lead to loops (bumping into the
1709 		 * same server reply) if useless-checked.
1710 		 */
1711 		if(iter_dp_is_useless(&qstate->qinfo, qstate->query_flags,
1712 			iq->dp, ie->supports_ipv4, ie->supports_ipv6,
1713 			ie->use_nat64)) {
1714 			int have_dp = 0;
1715 			if(!can_have_last_resort(qstate->env, iq->dp->name, iq->dp->namelen, iq->qchase.qclass, &have_dp, &iq->dp, qstate->region)) {
1716 				if(have_dp) {
1717 					verbose(VERB_QUERY, "cache has stub "
1718 						"or fwd but no addresses, "
1719 						"fallback to config");
1720 					if(have_dp && !iq->dp) {
1721 						log_err("out of memory in "
1722 							"stub/fwd fallback");
1723 						errinf(qstate, "malloc failure, for fallback to config");
1724 						return error_response(qstate,
1725 						    id, LDNS_RCODE_SERVFAIL);
1726 					}
1727 					break;
1728 				}
1729 				verbose(VERB_ALGO, "useless dp "
1730 					"but cannot go up, servfail");
1731 				delegpt_log(VERB_ALGO, iq->dp);
1732 				errinf(qstate, "no useful nameservers, "
1733 					"and cannot go up");
1734 				errinf_dname(qstate, "for zone", iq->dp->name);
1735 				return error_response(qstate, id,
1736 					LDNS_RCODE_SERVFAIL);
1737 			}
1738 			if(dname_is_root(iq->dp->name)) {
1739 				/* use safety belt */
1740 				int nolock = 0;
1741 				verbose(VERB_QUERY, "Cache has root NS but "
1742 				"no addresses. Fallback to the safety belt.");
1743 				iq->dp = hints_find_root(qstate->env->hints,
1744 					iq->qchase.qclass, nolock);
1745 				/* note deleg_msg is from previous lookup,
1746 				 * but RD is on, so it is not used */
1747 				if(!iq->dp) {
1748 					log_err("internal error: no hints dp");
1749 					return error_response(qstate, id,
1750 						LDNS_RCODE_REFUSED);
1751 				}
1752 				iq->dp = delegpt_copy(iq->dp, qstate->region);
1753 				lock_rw_unlock(&qstate->env->hints->lock);
1754 				if(!iq->dp) {
1755 					log_err("out of memory in safety belt");
1756 					errinf(qstate, "malloc failure, in safety belt, for root");
1757 					return error_response(qstate, id,
1758 						LDNS_RCODE_SERVFAIL);
1759 				}
1760 				break;
1761 			} else {
1762 				verbose(VERB_ALGO,
1763 					"cache delegation was useless:");
1764 				delegpt_log(VERB_ALGO, iq->dp);
1765 				/* go up */
1766 				delname = iq->dp->name;
1767 				delnamelen = iq->dp->namelen;
1768 				dname_remove_label(&delname, &delnamelen);
1769 			}
1770 		} else break;
1771 	}
1772 
1773 	verbose(VERB_ALGO, "cache delegation returns delegpt");
1774 	delegpt_log(VERB_ALGO, iq->dp);
1775 
1776 	/* Otherwise, set the current delegation point and move on to the
1777 	 * next state. */
1778 	return next_state(iq, INIT_REQUEST_2_STATE);
1779 }
1780 
1781 /**
1782  * Process the second part of the initial request handling. This state
1783  * basically exists so that queries that generate root priming events have
1784  * the same init processing as ones that do not. Request events that reach
1785  * this state must have a valid currentDelegationPoint set.
1786  *
1787  * This part is primarily handling stub zone priming. Events that reach this
1788  * state must have a current delegation point.
1789  *
1790  * @param qstate: query state.
1791  * @param iq: iterator query state.
1792  * @param id: module id.
1793  * @return true if the event needs more request processing immediately,
1794  *         false if not.
1795  */
1796 static int
1797 processInitRequest2(struct module_qstate* qstate, struct iter_qstate* iq,
1798 	int id)
1799 {
1800 	uint8_t* delname;
1801 	size_t delnamelen;
1802 	log_query_info(VERB_QUERY, "resolving (init part 2): ",
1803 		&qstate->qinfo);
1804 
1805 	delname = iq->qchase.qname;
1806 	delnamelen = iq->qchase.qname_len;
1807 	if(iq->refetch_glue) {
1808 		struct iter_hints_stub* stub;
1809 		int nolock = 0;
1810 		if(!iq->dp) {
1811 			log_err("internal or malloc fail: no dp for refetch");
1812 			errinf(qstate, "malloc failure, no delegation info");
1813 			return error_response(qstate, id, LDNS_RCODE_SERVFAIL);
1814 		}
1815 		/* Do not send queries above stub, do not set delname to dp if
1816 		 * this is above stub without stub-first. */
1817 		stub = hints_lookup_stub(
1818 			qstate->env->hints, iq->qchase.qname, iq->qchase.qclass,
1819 			iq->dp, nolock);
1820 		if(!stub || !stub->dp->has_parent_side_NS ||
1821 			dname_subdomain_c(iq->dp->name, stub->dp->name)) {
1822 			delname = iq->dp->name;
1823 			delnamelen = iq->dp->namelen;
1824 		}
1825 		/* lock_() calls are macros that could be nothing, surround in {} */
1826 		if(stub) { lock_rw_unlock(&qstate->env->hints->lock); }
1827 	}
1828 	if(iq->qchase.qtype == LDNS_RR_TYPE_DS || iq->refetch_glue) {
1829 		if(!dname_is_root(delname))
1830 			dname_remove_label(&delname, &delnamelen);
1831 		iq->refetch_glue = 0; /* if CNAME causes restart, no refetch */
1832 	}
1833 
1834 	/* see if we have an auth zone to answer from, improves dp from cache
1835 	 * (if any dp from cache) with auth zone dp, if that is lower */
1836 	if(!auth_zone_delegpt(qstate, iq, delname, delnamelen))
1837 		return error_response(qstate, id, LDNS_RCODE_SERVFAIL);
1838 
1839 	/* Check to see if we need to prime a stub zone. */
1840 	if(prime_stub(qstate, iq, id, delname, iq->qchase.qclass)) {
1841 		/* A priming sub request was made */
1842 		return 0;
1843 	}
1844 
1845 	/* most events just get forwarded to the next state. */
1846 	return next_state(iq, INIT_REQUEST_3_STATE);
1847 }
1848 
1849 /**
1850  * Process the third part of the initial request handling. This state exists
1851  * as a separate state so that queries that generate stub priming events
1852  * will get the tail end of the init process but not repeat the stub priming
1853  * check.
1854  *
1855  * @param qstate: query state.
1856  * @param iq: iterator query state.
1857  * @param id: module id.
1858  * @return true, advancing the event to the QUERYTARGETS_STATE.
1859  */
1860 static int
1861 processInitRequest3(struct module_qstate* qstate, struct iter_qstate* iq,
1862 	int id)
1863 {
1864 	log_query_info(VERB_QUERY, "resolving (init part 3): ",
1865 		&qstate->qinfo);
1866 	/* if the cache reply dp equals a validation anchor or msg has DS,
1867 	 * then DNSSEC RRSIGs are expected in the reply */
1868 	iq->dnssec_expected = iter_indicates_dnssec(qstate->env, iq->dp,
1869 		iq->deleg_msg, iq->qchase.qclass);
1870 
1871 	/* If the RD flag wasn't set, then we just finish with the
1872 	 * cached referral as the response. */
1873 	if(!(qstate->query_flags & BIT_RD) && iq->deleg_msg) {
1874 		iq->response = iq->deleg_msg;
1875 		if(verbosity >= VERB_ALGO && iq->response)
1876 			log_dns_msg("no RD requested, using delegation msg",
1877 				&iq->response->qinfo, iq->response->rep);
1878 		if(qstate->reply_origin)
1879 			sock_list_insert(&qstate->reply_origin, NULL, 0, qstate->region);
1880 		return final_state(iq);
1881 	}
1882 	/* After this point, unset the RD flag -- this query is going to
1883 	 * be sent to an auth. server. */
1884 	iq->chase_flags &= ~BIT_RD;
1885 
1886 	/* if dnssec expected, fetch key for the trust-anchor or cached-DS */
1887 	if(iq->dnssec_expected && qstate->env->cfg->prefetch_key &&
1888 		!(qstate->query_flags&BIT_CD)) {
1889 		generate_dnskey_prefetch(qstate, iq, id);
1890 		fptr_ok(fptr_whitelist_modenv_detach_subs(
1891 			qstate->env->detach_subs));
1892 		(*qstate->env->detach_subs)(qstate);
1893 	}
1894 
1895 	/* Jump to the next state. */
1896 	return next_state(iq, QUERYTARGETS_STATE);
1897 }
1898 
1899 /**
1900  * Given a basic query, generate a parent-side "target" query.
1901  * These are subordinate queries for missing delegation point target addresses,
1902  * for which only the parent of the delegation provides correct IP addresses.
1903  *
1904  * @param qstate: query state.
1905  * @param iq: iterator query state.
1906  * @param id: module id.
1907  * @param name: target qname.
1908  * @param namelen: target qname length.
1909  * @param qtype: target qtype (either A or AAAA).
1910  * @param qclass: target qclass.
1911  * @return true on success, false on failure.
1912  */
1913 static int
1914 generate_parentside_target_query(struct module_qstate* qstate,
1915 	struct iter_qstate* iq, int id, uint8_t* name, size_t namelen,
1916 	uint16_t qtype, uint16_t qclass)
1917 {
1918 	struct module_qstate* subq;
1919 	if(!generate_sub_request(name, namelen, qtype, qclass, qstate,
1920 		id, iq, INIT_REQUEST_STATE, FINISHED_STATE, &subq, 0, 0))
1921 		return 0;
1922 	if(subq) {
1923 		struct iter_qstate* subiq =
1924 			(struct iter_qstate*)subq->minfo[id];
1925 		/* blacklist the cache - we want to fetch parent stuff */
1926 		sock_list_insert(&subq->blacklist, NULL, 0, subq->region);
1927 		subiq->query_for_pside_glue = 1;
1928 		if(dname_subdomain_c(name, iq->dp->name)) {
1929 			subiq->dp = delegpt_copy(iq->dp, subq->region);
1930 			subiq->dnssec_expected = iter_indicates_dnssec(
1931 				qstate->env, subiq->dp, NULL,
1932 				subq->qinfo.qclass);
1933 			subiq->refetch_glue = 1;
1934 		} else {
1935 			subiq->dp = dns_cache_find_delegation(qstate->env,
1936 				name, namelen, qtype, qclass, subq->region,
1937 				&subiq->deleg_msg,
1938 				*qstate->env->now+subq->prefetch_leeway,
1939 				1, NULL, 0);
1940 			/* if no dp, then it's from root, refetch unneeded */
1941 			if(subiq->dp) {
1942 				subiq->dnssec_expected = iter_indicates_dnssec(
1943 					qstate->env, subiq->dp, NULL,
1944 					subq->qinfo.qclass);
1945 				subiq->refetch_glue = 1;
1946 			}
1947 		}
1948 	}
1949 	log_nametypeclass(VERB_QUERY, "new pside target", name, qtype, qclass);
1950 	return 1;
1951 }
1952 
1953 /**
1954  * Given a basic query, generate a "target" query. These are subordinate
1955  * queries for missing delegation point target addresses.
1956  *
1957  * @param qstate: query state.
1958  * @param iq: iterator query state.
1959  * @param id: module id.
1960  * @param name: target qname.
1961  * @param namelen: target qname length.
1962  * @param qtype: target qtype (either A or AAAA).
1963  * @param qclass: target qclass.
1964  * @return true on success, false on failure.
1965  */
1966 static int
1967 generate_target_query(struct module_qstate* qstate, struct iter_qstate* iq,
1968         int id, uint8_t* name, size_t namelen, uint16_t qtype, uint16_t qclass)
1969 {
1970 	struct module_qstate* subq;
1971 	if(!generate_sub_request(name, namelen, qtype, qclass, qstate,
1972 		id, iq, INIT_REQUEST_STATE, FINISHED_STATE, &subq, 0, 0))
1973 		return 0;
1974 	log_nametypeclass(VERB_QUERY, "new target", name, qtype, qclass);
1975 	return 1;
1976 }
1977 
1978 /**
1979  * Given an event at a certain state, generate zero or more target queries
1980  * for it's current delegation point.
1981  *
1982  * @param qstate: query state.
1983  * @param iq: iterator query state.
1984  * @param ie: iterator shared global environment.
1985  * @param id: module id.
1986  * @param maxtargets: The maximum number of targets to query for.
1987  *	if it is negative, there is no maximum number of targets.
1988  * @param num: returns the number of queries generated and processed,
1989  *	which may be zero if there were no missing targets.
1990  * @return 0 on success, nonzero on error. 1 means temporary failure and
1991  * 	2 means the failure can be cached.
1992  */
1993 static int
1994 query_for_targets(struct module_qstate* qstate, struct iter_qstate* iq,
1995         struct iter_env* ie, int id, int maxtargets, int* num)
1996 {
1997 	int query_count = 0;
1998 	struct delegpt_ns* ns;
1999 	int missing;
2000 	int toget = 0;
2001 
2002 	iter_mark_cycle_targets(qstate, iq->dp);
2003 	missing = (int)delegpt_count_missing_targets(iq->dp, NULL);
2004 	log_assert(maxtargets != 0); /* that would not be useful */
2005 
2006 	/* Generate target requests. Basically, any missing targets
2007 	 * are queried for here, regardless if it is necessary to do
2008 	 * so to continue processing. */
2009 	if(maxtargets < 0 || maxtargets > missing)
2010 		toget = missing;
2011 	else	toget = maxtargets;
2012 	if(toget == 0) {
2013 		*num = 0;
2014 		return 0;
2015 	}
2016 
2017 	/* now that we are sure that a target query is going to be made,
2018 	 * check the limits. */
2019 	if(iq->depth == ie->max_dependency_depth)
2020 		return 1;
2021 	if(iq->depth > 0 && iq->target_count &&
2022 		iq->target_count[TARGET_COUNT_QUERIES] > MAX_TARGET_COUNT) {
2023 		char s[LDNS_MAX_DOMAINLEN+1];
2024 		dname_str(qstate->qinfo.qname, s);
2025 		verbose(VERB_QUERY, "request %s has exceeded the maximum "
2026 			"number of glue fetches %d", s,
2027 			iq->target_count[TARGET_COUNT_QUERIES]);
2028 		return 2;
2029 	}
2030 	if(iq->dp_target_count > MAX_DP_TARGET_COUNT) {
2031 		char s[LDNS_MAX_DOMAINLEN+1];
2032 		dname_str(qstate->qinfo.qname, s);
2033 		verbose(VERB_QUERY, "request %s has exceeded the maximum "
2034 			"number of glue fetches %d to a single delegation point",
2035 			s, iq->dp_target_count);
2036 		return 2;
2037 	}
2038 
2039 	/* select 'toget' items from the total of 'missing' items */
2040 	log_assert(toget <= missing);
2041 
2042 	/* loop over missing targets */
2043 	for(ns = iq->dp->nslist; ns; ns = ns->next) {
2044 		if(ns->resolved)
2045 			continue;
2046 
2047 		/* randomly select this item with probability toget/missing */
2048 		if(!iter_ns_probability(qstate->env->rnd, toget, missing)) {
2049 			/* do not select this one, next; select toget number
2050 			 * of items from a list one less in size */
2051 			missing --;
2052 			continue;
2053 		}
2054 
2055 		if(ie->supports_ipv6 &&
2056 			((ns->lame && !ns->done_pside6) ||
2057 			(!ns->lame && !ns->got6))) {
2058 			/* Send the AAAA request. */
2059 			if(!generate_target_query(qstate, iq, id,
2060 				ns->name, ns->namelen,
2061 				LDNS_RR_TYPE_AAAA, iq->qchase.qclass)) {
2062 				*num = query_count;
2063 				if(query_count > 0)
2064 					qstate->ext_state[id] = module_wait_subquery;
2065 				return 1;
2066 			}
2067 			query_count++;
2068 			/* If the mesh query list is full, exit the loop here.
2069 			 * This makes the routine spawn one query at a time,
2070 			 * and this means there is no query state load
2071 			 * increase, because the spawned state uses cpu and a
2072 			 * socket while this state waits for that spawned
2073 			 * state. Next time we can look up further targets */
2074 			if(mesh_jostle_exceeded(qstate->env->mesh)) {
2075 				/* If no ip4 query is possible, that makes
2076 				 * this ns resolved. */
2077 				if(!((ie->supports_ipv4 || ie->use_nat64) &&
2078 					((ns->lame && !ns->done_pside4) ||
2079 					(!ns->lame && !ns->got4)))) {
2080 					ns->resolved = 1;
2081 				}
2082 				break;
2083 			}
2084 		}
2085 		/* Send the A request. */
2086 		if((ie->supports_ipv4 || ie->use_nat64) &&
2087 			((ns->lame && !ns->done_pside4) ||
2088 			(!ns->lame && !ns->got4))) {
2089 			if(!generate_target_query(qstate, iq, id,
2090 				ns->name, ns->namelen,
2091 				LDNS_RR_TYPE_A, iq->qchase.qclass)) {
2092 				*num = query_count;
2093 				if(query_count > 0)
2094 					qstate->ext_state[id] = module_wait_subquery;
2095 				return 1;
2096 			}
2097 			query_count++;
2098 			/* If the mesh query list is full, exit the loop. */
2099 			if(mesh_jostle_exceeded(qstate->env->mesh)) {
2100 				/* With the ip6 query already checked for,
2101 				 * this makes the ns resolved. It is no longer
2102 				 * a missing target. */
2103 				ns->resolved = 1;
2104 				break;
2105 			}
2106 		}
2107 
2108 		/* mark this target as in progress. */
2109 		ns->resolved = 1;
2110 		missing--;
2111 		toget--;
2112 		if(toget == 0)
2113 			break;
2114 	}
2115 	*num = query_count;
2116 	if(query_count > 0)
2117 		qstate->ext_state[id] = module_wait_subquery;
2118 
2119 	return 0;
2120 }
2121 
2122 /**
2123  * Called by processQueryTargets when it would like extra targets to query
2124  * but it seems to be out of options.  At last resort some less appealing
2125  * options are explored.  If there are no more options, the result is SERVFAIL
2126  *
2127  * @param qstate: query state.
2128  * @param iq: iterator query state.
2129  * @param ie: iterator shared global environment.
2130  * @param id: module id.
2131  * @return true if the event requires more request processing immediately,
2132  *         false if not.
2133  */
2134 static int
2135 processLastResort(struct module_qstate* qstate, struct iter_qstate* iq,
2136 	struct iter_env* ie, int id)
2137 {
2138 	struct delegpt_ns* ns;
2139 	int query_count = 0;
2140 	verbose(VERB_ALGO, "No more query targets, attempting last resort");
2141 	log_assert(iq->dp);
2142 
2143 	if(!can_have_last_resort(qstate->env, iq->dp->name, iq->dp->namelen,
2144 		iq->qchase.qclass, NULL, NULL, NULL)) {
2145 		/* fail -- no more targets, no more hope of targets, no hope
2146 		 * of a response. */
2147 		errinf(qstate, "all the configured stub or forward servers failed,");
2148 		errinf_dname(qstate, "at zone", iq->dp->name);
2149 		errinf_reply(qstate, iq);
2150 		verbose(VERB_QUERY, "configured stub or forward servers failed -- returning SERVFAIL");
2151 		return error_response_cache(qstate, id, LDNS_RCODE_SERVFAIL);
2152 	}
2153 	if(!iq->dp->has_parent_side_NS && dname_is_root(iq->dp->name)) {
2154 		struct delegpt* dp;
2155 		int nolock = 0;
2156 		dp = hints_find_root(qstate->env->hints,
2157 			iq->qchase.qclass, nolock);
2158 		if(dp) {
2159 			struct delegpt_addr* a;
2160 			iq->chase_flags &= ~BIT_RD; /* go to authorities */
2161 			for(ns = dp->nslist; ns; ns=ns->next) {
2162 				(void)delegpt_add_ns(iq->dp, qstate->region,
2163 					ns->name, ns->lame, ns->tls_auth_name,
2164 					ns->port);
2165 			}
2166 			for(a = dp->target_list; a; a=a->next_target) {
2167 				(void)delegpt_add_addr(iq->dp, qstate->region,
2168 					&a->addr, a->addrlen, a->bogus,
2169 					a->lame, a->tls_auth_name, -1, NULL);
2170 			}
2171 			lock_rw_unlock(&qstate->env->hints->lock);
2172 		}
2173 		iq->dp->has_parent_side_NS = 1;
2174 	} else if(!iq->dp->has_parent_side_NS) {
2175 		if(!iter_lookup_parent_NS_from_cache(qstate->env, iq->dp,
2176 			qstate->region, &qstate->qinfo)
2177 			|| !iq->dp->has_parent_side_NS) {
2178 			/* if: malloc failure in lookup go up to try */
2179 			/* if: no parent NS in cache - go up one level */
2180 			verbose(VERB_ALGO, "try to grab parent NS");
2181 			iq->store_parent_NS = iq->dp;
2182 			iq->chase_flags &= ~BIT_RD; /* go to authorities */
2183 			iq->deleg_msg = NULL;
2184 			iq->refetch_glue = 1;
2185 			iq->query_restart_count++;
2186 			iq->sent_count = 0;
2187 			iq->dp_target_count = 0;
2188 			if(qstate->env->cfg->qname_minimisation)
2189 				iq->minimisation_state = INIT_MINIMISE_STATE;
2190 			return next_state(iq, INIT_REQUEST_STATE);
2191 		}
2192 	}
2193 	/* see if that makes new names available */
2194 	if(!cache_fill_missing(qstate->env, iq->qchase.qclass,
2195 		qstate->region, iq->dp))
2196 		log_err("out of memory in cache_fill_missing");
2197 	if(iq->dp->usable_list) {
2198 		verbose(VERB_ALGO, "try parent-side-name, w. glue from cache");
2199 		return next_state(iq, QUERYTARGETS_STATE);
2200 	}
2201 	/* try to fill out parent glue from cache */
2202 	if(iter_lookup_parent_glue_from_cache(qstate->env, iq->dp,
2203 		qstate->region, &qstate->qinfo)) {
2204 		/* got parent stuff from cache, see if we can continue */
2205 		verbose(VERB_ALGO, "try parent-side glue from cache");
2206 		return next_state(iq, QUERYTARGETS_STATE);
2207 	}
2208 	/* query for an extra name added by the parent-NS record */
2209 	if(delegpt_count_missing_targets(iq->dp, NULL) > 0) {
2210 		int qs = 0, ret;
2211 		verbose(VERB_ALGO, "try parent-side target name");
2212 		if((ret=query_for_targets(qstate, iq, ie, id, 1, &qs))!=0) {
2213 			errinf(qstate, "could not fetch nameserver");
2214 			errinf_dname(qstate, "at zone", iq->dp->name);
2215 			if(ret == 1)
2216 				return error_response(qstate, id, LDNS_RCODE_SERVFAIL);
2217 			return error_response_cache(qstate, id, LDNS_RCODE_SERVFAIL);
2218 		}
2219 		iq->num_target_queries += qs;
2220 		target_count_increase(iq, qs);
2221 		if(qs != 0) {
2222 			qstate->ext_state[id] = module_wait_subquery;
2223 			return 0; /* and wait for them */
2224 		}
2225 	}
2226 	if(iq->depth == ie->max_dependency_depth) {
2227 		verbose(VERB_QUERY, "maxdepth and need more nameservers, fail");
2228 		errinf(qstate, "cannot fetch more nameservers because at max dependency depth");
2229 		return error_response_cache(qstate, id, LDNS_RCODE_SERVFAIL);
2230 	}
2231 	if(iq->depth > 0 && iq->target_count &&
2232 		iq->target_count[TARGET_COUNT_QUERIES] > MAX_TARGET_COUNT) {
2233 		char s[LDNS_MAX_DOMAINLEN+1];
2234 		dname_str(qstate->qinfo.qname, s);
2235 		verbose(VERB_QUERY, "request %s has exceeded the maximum "
2236 			"number of glue fetches %d", s,
2237 			iq->target_count[TARGET_COUNT_QUERIES]);
2238 		errinf(qstate, "exceeded the maximum number of glue fetches");
2239 		return error_response_cache(qstate, id, LDNS_RCODE_SERVFAIL);
2240 	}
2241 	/* mark cycle targets for parent-side lookups */
2242 	iter_mark_pside_cycle_targets(qstate, iq->dp);
2243 	/* see if we can issue queries to get nameserver addresses */
2244 	/* this lookup is not randomized, but sequential. */
2245 	for(ns = iq->dp->nslist; ns; ns = ns->next) {
2246 		/* if this nameserver is at a delegation point, but that
2247 		 * delegation point is a stub and we cannot go higher, skip*/
2248 		if( ((ie->supports_ipv6 && !ns->done_pside6) ||
2249 		    ((ie->supports_ipv4 || ie->use_nat64) && !ns->done_pside4)) &&
2250 		    !can_have_last_resort(qstate->env, ns->name, ns->namelen,
2251 			iq->qchase.qclass, NULL, NULL, NULL)) {
2252 			log_nametypeclass(VERB_ALGO, "cannot pside lookup ns "
2253 				"because it is also a stub/forward,",
2254 				ns->name, LDNS_RR_TYPE_NS, iq->qchase.qclass);
2255 			if(ie->supports_ipv6) ns->done_pside6 = 1;
2256 			if(ie->supports_ipv4 || ie->use_nat64) ns->done_pside4 = 1;
2257 			continue;
2258 		}
2259 		/* query for parent-side A and AAAA for nameservers */
2260 		if(ie->supports_ipv6 && !ns->done_pside6) {
2261 			/* Send the AAAA request. */
2262 			if(!generate_parentside_target_query(qstate, iq, id,
2263 				ns->name, ns->namelen,
2264 				LDNS_RR_TYPE_AAAA, iq->qchase.qclass)) {
2265 				errinf_dname(qstate, "could not generate nameserver AAAA lookup for", ns->name);
2266 				return error_response(qstate, id,
2267 					LDNS_RCODE_SERVFAIL);
2268 			}
2269 			ns->done_pside6 = 1;
2270 			query_count++;
2271 			if(mesh_jostle_exceeded(qstate->env->mesh)) {
2272 				/* Wait for the lookup; do not spawn multiple
2273 				 * lookups at a time. */
2274 				verbose(VERB_ALGO, "try parent-side glue lookup");
2275 				iq->num_target_queries += query_count;
2276 				target_count_increase(iq, query_count);
2277 				qstate->ext_state[id] = module_wait_subquery;
2278 				return 0;
2279 			}
2280 		}
2281 		if((ie->supports_ipv4 || ie->use_nat64) && !ns->done_pside4) {
2282 			/* Send the A request. */
2283 			if(!generate_parentside_target_query(qstate, iq, id,
2284 				ns->name, ns->namelen,
2285 				LDNS_RR_TYPE_A, iq->qchase.qclass)) {
2286 				errinf_dname(qstate, "could not generate nameserver A lookup for", ns->name);
2287 				return error_response(qstate, id,
2288 					LDNS_RCODE_SERVFAIL);
2289 			}
2290 			ns->done_pside4 = 1;
2291 			query_count++;
2292 		}
2293 		if(query_count != 0) { /* suspend to await results */
2294 			verbose(VERB_ALGO, "try parent-side glue lookup");
2295 			iq->num_target_queries += query_count;
2296 			target_count_increase(iq, query_count);
2297 			qstate->ext_state[id] = module_wait_subquery;
2298 			return 0;
2299 		}
2300 	}
2301 
2302 	/* if this was a parent-side glue query itself, then store that
2303 	 * failure in cache. */
2304 	if(!qstate->no_cache_store && iq->query_for_pside_glue
2305 		&& !iq->pside_glue)
2306 			iter_store_parentside_neg(qstate->env, &qstate->qinfo,
2307 				iq->deleg_msg?iq->deleg_msg->rep:
2308 				(iq->response?iq->response->rep:NULL));
2309 
2310 	errinf(qstate, "all servers for this domain failed,");
2311 	errinf_dname(qstate, "at zone", iq->dp->name);
2312 	errinf_reply(qstate, iq);
2313 	verbose(VERB_QUERY, "out of query targets -- returning SERVFAIL");
2314 	/* fail -- no more targets, no more hope of targets, no hope
2315 	 * of a response. */
2316 	return error_response_cache(qstate, id, LDNS_RCODE_SERVFAIL);
2317 }
2318 
2319 /**
2320  * Try to find the NS record set that will resolve a qtype DS query. Due
2321  * to grandparent/grandchild reasons we did not get a proper lookup right
2322  * away.  We need to create type NS queries until we get the right parent
2323  * for this lookup.  We remove labels from the query to find the right point.
2324  * If we end up at the old dp name, then there is no solution.
2325  *
2326  * @param qstate: query state.
2327  * @param iq: iterator query state.
2328  * @param id: module id.
2329  * @return true if the event requires more immediate processing, false if
2330  *         not. This is generally only true when forwarding the request to
2331  *         the final state (i.e., on answer).
2332  */
2333 static int
2334 processDSNSFind(struct module_qstate* qstate, struct iter_qstate* iq, int id)
2335 {
2336 	struct module_qstate* subq = NULL;
2337 	verbose(VERB_ALGO, "processDSNSFind");
2338 
2339 	if(!iq->dsns_point) {
2340 		/* initialize */
2341 		iq->dsns_point = iq->qchase.qname;
2342 		iq->dsns_point_len = iq->qchase.qname_len;
2343 	}
2344 	/* robustcheck for internal error: we are not underneath the dp */
2345 	if(!dname_subdomain_c(iq->dsns_point, iq->dp->name)) {
2346 		errinf_dname(qstate, "for DS query parent-child nameserver search the query is not under the zone", iq->dp->name);
2347 		return error_response_cache(qstate, id, LDNS_RCODE_SERVFAIL);
2348 	}
2349 
2350 	/* go up one (more) step, until we hit the dp, if so, end */
2351 	dname_remove_label(&iq->dsns_point, &iq->dsns_point_len);
2352 	if(query_dname_compare(iq->dsns_point, iq->dp->name) == 0) {
2353 		/* there was no inbetween nameserver, use the old delegation
2354 		 * point again.  And this time, because dsns_point is nonNULL
2355 		 * we are going to accept the (bad) result */
2356 		iq->state = QUERYTARGETS_STATE;
2357 		return 1;
2358 	}
2359 	iq->state = DSNS_FIND_STATE;
2360 
2361 	/* spawn NS lookup (validation not needed, this is for DS lookup) */
2362 	log_nametypeclass(VERB_ALGO, "fetch nameservers",
2363 		iq->dsns_point, LDNS_RR_TYPE_NS, iq->qchase.qclass);
2364 	if(!generate_sub_request(iq->dsns_point, iq->dsns_point_len,
2365 		LDNS_RR_TYPE_NS, iq->qchase.qclass, qstate, id, iq,
2366 		INIT_REQUEST_STATE, FINISHED_STATE, &subq, 0, 0)) {
2367 		errinf_dname(qstate, "for DS query parent-child nameserver search, could not generate NS lookup for", iq->dsns_point);
2368 		return error_response_cache(qstate, id, LDNS_RCODE_SERVFAIL);
2369 	}
2370 
2371 	return 0;
2372 }
2373 
2374 /**
2375  * Check if we wait responses for sent queries and update the iterator's
2376  * external state.
2377  */
2378 static void
2379 check_waiting_queries(struct iter_qstate* iq, struct module_qstate* qstate,
2380 	int id)
2381 {
2382 	if(iq->num_target_queries>0 && iq->num_current_queries>0) {
2383 		verbose(VERB_ALGO, "waiting for %d targets to "
2384 			"resolve or %d outstanding queries to "
2385 			"respond", iq->num_target_queries,
2386 			iq->num_current_queries);
2387 		qstate->ext_state[id] = module_wait_reply;
2388 	} else if(iq->num_target_queries>0) {
2389 		verbose(VERB_ALGO, "waiting for %d targets to "
2390 			"resolve", iq->num_target_queries);
2391 		qstate->ext_state[id] = module_wait_subquery;
2392 	} else {
2393 		verbose(VERB_ALGO, "waiting for %d "
2394 			"outstanding queries to respond",
2395 			iq->num_current_queries);
2396 		qstate->ext_state[id] = module_wait_reply;
2397 	}
2398 }
2399 
2400 /**
2401  * This is the request event state where the request will be sent to one of
2402  * its current query targets. This state also handles issuing target lookup
2403  * queries for missing target IP addresses. Queries typically iterate on
2404  * this state, both when they are just trying different targets for a given
2405  * delegation point, and when they change delegation points. This state
2406  * roughly corresponds to RFC 1034 algorithm steps 3 and 4.
2407  *
2408  * @param qstate: query state.
2409  * @param iq: iterator query state.
2410  * @param ie: iterator shared global environment.
2411  * @param id: module id.
2412  * @return true if the event requires more request processing immediately,
2413  *         false if not. This state only returns true when it is generating
2414  *         a SERVFAIL response because the query has hit a dead end.
2415  */
2416 static int
2417 processQueryTargets(struct module_qstate* qstate, struct iter_qstate* iq,
2418 	struct iter_env* ie, int id)
2419 {
2420 	int tf_policy;
2421 	struct delegpt_addr* target;
2422 	struct outbound_entry* outq;
2423 	struct sockaddr_storage real_addr;
2424 	socklen_t real_addrlen;
2425 	int auth_fallback = 0;
2426 	uint8_t* qout_orig = NULL;
2427 	size_t qout_orig_len = 0;
2428 	int sq_check_ratelimit = 1;
2429 	int sq_was_ratelimited = 0;
2430 	int can_do_promisc = 0;
2431 
2432 	/* NOTE: a request will encounter this state for each target it
2433 	 * needs to send a query to. That is, at least one per referral,
2434 	 * more if some targets timeout or return throwaway answers. */
2435 
2436 	log_query_info(VERB_QUERY, "processQueryTargets:", &qstate->qinfo);
2437 	verbose(VERB_ALGO, "processQueryTargets: targetqueries %d, "
2438 		"currentqueries %d sentcount %d", iq->num_target_queries,
2439 		iq->num_current_queries, iq->sent_count);
2440 
2441 	/* Make sure that we haven't run away */
2442 	if(iq->referral_count > MAX_REFERRAL_COUNT) {
2443 		verbose(VERB_QUERY, "request has exceeded the maximum "
2444 			"number of referrrals with %d", iq->referral_count);
2445 		errinf(qstate, "exceeded the maximum of referrals");
2446 		return error_response_cache(qstate, id, LDNS_RCODE_SERVFAIL);
2447 	}
2448 	if(iq->sent_count > ie->max_sent_count) {
2449 		verbose(VERB_QUERY, "request has exceeded the maximum "
2450 			"number of sends with %d", iq->sent_count);
2451 		errinf(qstate, "exceeded the maximum number of sends");
2452 		return error_response_cache(qstate, id, LDNS_RCODE_SERVFAIL);
2453 	}
2454 
2455 	/* Check if we reached MAX_TARGET_NX limit without a fallback activation. */
2456 	if(iq->target_count && !*iq->nxns_dp &&
2457 		iq->target_count[TARGET_COUNT_NX] > MAX_TARGET_NX) {
2458 		struct delegpt_ns* ns;
2459 		/* If we can wait for resolution, do so. */
2460 		if(iq->num_target_queries>0 || iq->num_current_queries>0) {
2461 			check_waiting_queries(iq, qstate, id);
2462 			return 0;
2463 		}
2464 		verbose(VERB_ALGO, "request has exceeded the maximum "
2465 			"number of nxdomain nameserver lookups (%d) with %d",
2466 			MAX_TARGET_NX, iq->target_count[TARGET_COUNT_NX]);
2467 		/* Check for dp because we require one below */
2468 		if(!iq->dp) {
2469 			verbose(VERB_QUERY, "Failed to get a delegation, "
2470 				"giving up");
2471 			errinf(qstate, "failed to get a delegation (eg. prime "
2472 				"failure)");
2473 			return error_response(qstate, id, LDNS_RCODE_SERVFAIL);
2474 		}
2475 		/* We reached the limit but we already have parent side
2476 		 * information; stop resolution */
2477 		if(iq->dp->has_parent_side_NS) {
2478 			verbose(VERB_ALGO, "parent-side information is "
2479 				"already present for the delegation point, no "
2480 				"fallback possible");
2481 			errinf(qstate, "exceeded the maximum nameserver nxdomains");
2482 			return error_response_cache(qstate, id, LDNS_RCODE_SERVFAIL);
2483 		}
2484 		verbose(VERB_ALGO, "initiating parent-side fallback for "
2485 			"nxdomain nameserver lookups");
2486 		/* Mark all the current NSes as resolved to allow for parent
2487 		 * fallback */
2488 		for(ns=iq->dp->nslist; ns; ns=ns->next) {
2489 			ns->resolved = 1;
2490 		}
2491 		/* Note the delegation point that triggered the NXNS fallback;
2492 		 * no reason for shared queries to keep trying there.
2493 		 * This also marks the fallback activation. */
2494 		*iq->nxns_dp = malloc(iq->dp->namelen);
2495 		if(!*iq->nxns_dp) {
2496 			verbose(VERB_ALGO, "out of memory while initiating "
2497 				"fallback");
2498 			errinf(qstate, "exceeded the maximum nameserver "
2499 				"nxdomains (malloc)");
2500 			return error_response(qstate, id, LDNS_RCODE_SERVFAIL);
2501 		}
2502 		memcpy(*iq->nxns_dp, iq->dp->name, iq->dp->namelen);
2503 	} else if(iq->target_count && *iq->nxns_dp) {
2504 		/* Handle the NXNS fallback case. */
2505 		/* If we can wait for resolution, do so. */
2506 		if(iq->num_target_queries>0 || iq->num_current_queries>0) {
2507 			check_waiting_queries(iq, qstate, id);
2508 			return 0;
2509 		}
2510 		/* Check for dp because we require one below */
2511 		if(!iq->dp) {
2512 			verbose(VERB_QUERY, "Failed to get a delegation, "
2513 				"giving up");
2514 			errinf(qstate, "failed to get a delegation (eg. prime "
2515 				"failure)");
2516 			return error_response(qstate, id, LDNS_RCODE_SERVFAIL);
2517 		}
2518 
2519 		if(iq->target_count[TARGET_COUNT_NX] > MAX_TARGET_NX_FALLBACK) {
2520 			verbose(VERB_ALGO, "request has exceeded the maximum "
2521 				"number of fallback nxdomain nameserver "
2522 				"lookups (%d) with %d", MAX_TARGET_NX_FALLBACK,
2523 				iq->target_count[TARGET_COUNT_NX]);
2524 			errinf(qstate, "exceeded the maximum nameserver nxdomains");
2525 			return error_response_cache(qstate, id, LDNS_RCODE_SERVFAIL);
2526 		}
2527 
2528 		if(!iq->dp->has_parent_side_NS) {
2529 			struct delegpt_ns* ns;
2530 			if(!dname_canonical_compare(*iq->nxns_dp, iq->dp->name)) {
2531 				verbose(VERB_ALGO, "this delegation point "
2532 					"initiated the fallback, marking the "
2533 					"nslist as resolved");
2534 				for(ns=iq->dp->nslist; ns; ns=ns->next) {
2535 					ns->resolved = 1;
2536 				}
2537 			}
2538 		}
2539 	}
2540 
2541 	/* Make sure we have a delegation point, otherwise priming failed
2542 	 * or another failure occurred */
2543 	if(!iq->dp) {
2544 		verbose(VERB_QUERY, "Failed to get a delegation, giving up");
2545 		errinf(qstate, "failed to get a delegation (eg. prime failure)");
2546 		return error_response(qstate, id, LDNS_RCODE_SERVFAIL);
2547 	}
2548 	if(!ie->supports_ipv6)
2549 		delegpt_no_ipv6(iq->dp);
2550 	if(!ie->supports_ipv4 && !ie->use_nat64)
2551 		delegpt_no_ipv4(iq->dp);
2552 	delegpt_log(VERB_ALGO, iq->dp);
2553 
2554 	if(iq->num_current_queries>0) {
2555 		/* already busy answering a query, this restart is because
2556 		 * more delegpt addrs became available, wait for existing
2557 		 * query. */
2558 		verbose(VERB_ALGO, "woke up, but wait for outstanding query");
2559 		qstate->ext_state[id] = module_wait_reply;
2560 		return 0;
2561 	}
2562 
2563 	if(iq->minimisation_state == INIT_MINIMISE_STATE
2564 		&& !(iq->chase_flags & BIT_RD)) {
2565 		/* (Re)set qinfo_out to (new) delegation point, except when
2566 		 * qinfo_out is already a subdomain of dp. This happens when
2567 		 * increasing by more than one label at once (QNAMEs with more
2568 		 * than MAX_MINIMISE_COUNT labels). */
2569 		if(!(iq->qinfo_out.qname_len
2570 			&& dname_subdomain_c(iq->qchase.qname,
2571 				iq->qinfo_out.qname)
2572 			&& dname_subdomain_c(iq->qinfo_out.qname,
2573 				iq->dp->name))) {
2574 			iq->qinfo_out.qname = iq->dp->name;
2575 			iq->qinfo_out.qname_len = iq->dp->namelen;
2576 			iq->qinfo_out.qtype = LDNS_RR_TYPE_A;
2577 			iq->qinfo_out.qclass = iq->qchase.qclass;
2578 			iq->qinfo_out.local_alias = NULL;
2579 			iq->minimise_count = 0;
2580 		}
2581 
2582 		iq->minimisation_state = MINIMISE_STATE;
2583 	}
2584 	if(iq->minimisation_state == MINIMISE_STATE) {
2585 		int qchaselabs = dname_count_labels(iq->qchase.qname);
2586 		int labdiff = qchaselabs -
2587 			dname_count_labels(iq->qinfo_out.qname);
2588 
2589 		qout_orig = iq->qinfo_out.qname;
2590 		qout_orig_len = iq->qinfo_out.qname_len;
2591 		iq->qinfo_out.qname = iq->qchase.qname;
2592 		iq->qinfo_out.qname_len = iq->qchase.qname_len;
2593 		iq->minimise_count++;
2594 		iq->timeout_count = 0;
2595 
2596 		iter_dec_attempts(iq->dp, 1, ie->outbound_msg_retry);
2597 
2598 		/* Limit number of iterations for QNAMEs with more
2599 		 * than MAX_MINIMISE_COUNT labels. Send first MINIMISE_ONE_LAB
2600 		 * labels of QNAME always individually.
2601 		 */
2602 		if(qchaselabs > MAX_MINIMISE_COUNT && labdiff > 1 &&
2603 			iq->minimise_count > MINIMISE_ONE_LAB) {
2604 			if(iq->minimise_count < MAX_MINIMISE_COUNT) {
2605 				int multilabs = qchaselabs - 1 -
2606 					MINIMISE_ONE_LAB;
2607 				int extralabs = multilabs /
2608 					MINIMISE_MULTIPLE_LABS;
2609 
2610 				if (MAX_MINIMISE_COUNT - iq->minimise_count >=
2611 					multilabs % MINIMISE_MULTIPLE_LABS)
2612 					/* Default behaviour is to add 1 label
2613 					 * every iteration. Therefore, decrement
2614 					 * the extralabs by 1 */
2615 					extralabs--;
2616 				if (extralabs < labdiff)
2617 					labdiff -= extralabs;
2618 				else
2619 					labdiff = 1;
2620 			}
2621 			/* Last minimised iteration, send all labels with
2622 			 * QTYPE=NS */
2623 			else
2624 				labdiff = 1;
2625 		}
2626 
2627 		if(labdiff > 1) {
2628 			verbose(VERB_QUERY, "removing %d labels", labdiff-1);
2629 			dname_remove_labels(&iq->qinfo_out.qname,
2630 				&iq->qinfo_out.qname_len,
2631 				labdiff-1);
2632 		}
2633 		if(labdiff < 1 || (labdiff < 2
2634 			&& (iq->qchase.qtype == LDNS_RR_TYPE_DS
2635 			|| iq->qchase.qtype == LDNS_RR_TYPE_A)))
2636 			/* Stop minimising this query, resolve "as usual" */
2637 			iq->minimisation_state = DONOT_MINIMISE_STATE;
2638 		else if(!qstate->no_cache_lookup) {
2639 			struct dns_msg* msg = dns_cache_lookup(qstate->env,
2640 				iq->qinfo_out.qname, iq->qinfo_out.qname_len,
2641 				iq->qinfo_out.qtype, iq->qinfo_out.qclass,
2642 				qstate->query_flags, qstate->region,
2643 				qstate->env->scratch, 0, iq->dp->name,
2644 				iq->dp->namelen);
2645 			if(msg && FLAGS_GET_RCODE(msg->rep->flags) ==
2646 				LDNS_RCODE_NOERROR)
2647 				/* no need to send query if it is already
2648 				 * cached as NOERROR */
2649 				return 1;
2650 			if(msg && FLAGS_GET_RCODE(msg->rep->flags) ==
2651 				LDNS_RCODE_NXDOMAIN &&
2652 				qstate->env->need_to_validate &&
2653 				qstate->env->cfg->harden_below_nxdomain) {
2654 				if(msg->rep->security == sec_status_secure) {
2655 					iq->response = msg;
2656 					return final_state(iq);
2657 				}
2658 				if(msg->rep->security == sec_status_unchecked) {
2659 					struct module_qstate* subq = NULL;
2660 					if(!generate_sub_request(
2661 						iq->qinfo_out.qname,
2662 						iq->qinfo_out.qname_len,
2663 						iq->qinfo_out.qtype,
2664 						iq->qinfo_out.qclass,
2665 						qstate, id, iq,
2666 						INIT_REQUEST_STATE,
2667 						FINISHED_STATE, &subq, 1, 1))
2668 						verbose(VERB_ALGO,
2669 						"could not validate NXDOMAIN "
2670 						"response");
2671 				}
2672 			}
2673 			if(msg && FLAGS_GET_RCODE(msg->rep->flags) ==
2674 				LDNS_RCODE_NXDOMAIN) {
2675 				/* return and add a label in the next
2676 				 * minimisation iteration.
2677 				 */
2678 				return 1;
2679 			}
2680 		}
2681 	}
2682 	if(iq->minimisation_state == SKIP_MINIMISE_STATE) {
2683 		if(iq->timeout_count < MAX_MINIMISE_TIMEOUT_COUNT)
2684 			/* Do not increment qname, continue incrementing next
2685 			 * iteration */
2686 			iq->minimisation_state = MINIMISE_STATE;
2687 		else if(!qstate->env->cfg->qname_minimisation_strict)
2688 			/* Too many time-outs detected for this QNAME and QTYPE.
2689 			 * We give up, disable QNAME minimisation. */
2690 			iq->minimisation_state = DONOT_MINIMISE_STATE;
2691 	}
2692 	if(iq->minimisation_state == DONOT_MINIMISE_STATE)
2693 		iq->qinfo_out = iq->qchase;
2694 
2695 	/* now find an answer to this query */
2696 	/* see if authority zones have an answer */
2697 	/* now we know the dp, we can check the auth zone for locally hosted
2698 	 * contents */
2699 	if(!iq->auth_zone_avoid && qstate->blacklist) {
2700 		if(auth_zones_can_fallback(qstate->env->auth_zones,
2701 			iq->dp->name, iq->dp->namelen, iq->qinfo_out.qclass)) {
2702 			/* if cache is blacklisted and this zone allows us
2703 			 * to fallback to the internet, then do so, and
2704 			 * fetch results from the internet servers */
2705 			iq->auth_zone_avoid = 1;
2706 		}
2707 	}
2708 	if(iq->auth_zone_avoid) {
2709 		iq->auth_zone_avoid = 0;
2710 		auth_fallback = 1;
2711 	} else if(auth_zones_lookup(qstate->env->auth_zones, &iq->qinfo_out,
2712 		qstate->region, &iq->response, &auth_fallback, iq->dp->name,
2713 		iq->dp->namelen)) {
2714 		/* use this as a response to be processed by the iterator */
2715 		if(verbosity >= VERB_ALGO) {
2716 			log_dns_msg("msg from auth zone",
2717 				&iq->response->qinfo, iq->response->rep);
2718 		}
2719 		if((iq->chase_flags&BIT_RD) && !(iq->response->rep->flags&BIT_AA)) {
2720 			verbose(VERB_ALGO, "forwarder, ignoring referral from auth zone");
2721 		} else {
2722 			lock_rw_wrlock(&qstate->env->auth_zones->lock);
2723 			qstate->env->auth_zones->num_query_up++;
2724 			lock_rw_unlock(&qstate->env->auth_zones->lock);
2725 			iq->num_current_queries++;
2726 			iq->chase_to_rd = 0;
2727 			iq->dnssec_lame_query = 0;
2728 			iq->auth_zone_response = 1;
2729 			return next_state(iq, QUERY_RESP_STATE);
2730 		}
2731 	}
2732 	iq->auth_zone_response = 0;
2733 	if(auth_fallback == 0) {
2734 		/* like we got servfail from the auth zone lookup, and
2735 		 * no internet fallback */
2736 		verbose(VERB_ALGO, "auth zone lookup failed, no fallback,"
2737 			" servfail");
2738 		errinf(qstate, "auth zone lookup failed, fallback is off");
2739 		return error_response_cache(qstate, id, LDNS_RCODE_SERVFAIL);
2740 	}
2741 	if(iq->dp->auth_dp) {
2742 		/* we wanted to fallback, but had no delegpt, only the
2743 		 * auth zone generated delegpt, create an actual one */
2744 		iq->auth_zone_avoid = 1;
2745 		return next_state(iq, INIT_REQUEST_STATE);
2746 	}
2747 	/* but mostly, fallback==1 (like, when no such auth zone exists)
2748 	 * and we continue with lookups */
2749 
2750 	tf_policy = 0;
2751 	/* < not <=, because although the array is large enough for <=, the
2752 	 * generated query will immediately be discarded due to depth and
2753 	 * that servfail is cached, which is not good as opportunism goes. */
2754 	if(iq->depth < ie->max_dependency_depth
2755 		&& iq->num_target_queries == 0
2756 		&& (!iq->target_count || iq->target_count[TARGET_COUNT_NX]==0)
2757 		&& iq->sent_count < TARGET_FETCH_STOP) {
2758 		can_do_promisc = 1;
2759 	}
2760 	/* if the mesh query list is full, then do not waste cpu and sockets to
2761 	 * fetch promiscuous targets. They can be looked up when needed. */
2762 	if(can_do_promisc && !mesh_jostle_exceeded(qstate->env->mesh)) {
2763 		tf_policy = ie->target_fetch_policy[iq->depth];
2764 	}
2765 
2766 	/* if in 0x20 fallback get as many targets as possible */
2767 	if(iq->caps_fallback) {
2768 		int extra = 0, ret;
2769 		size_t naddr, nres, navail;
2770 		if((ret=query_for_targets(qstate, iq, ie, id, -1, &extra))!=0) {
2771 			errinf(qstate, "could not fetch nameservers for 0x20 fallback");
2772 			if(ret == 1)
2773 				return error_response(qstate, id, LDNS_RCODE_SERVFAIL);
2774 			return error_response_cache(qstate, id, LDNS_RCODE_SERVFAIL);
2775 		}
2776 		iq->num_target_queries += extra;
2777 		target_count_increase(iq, extra);
2778 		if(iq->num_target_queries > 0) {
2779 			/* wait to get all targets, we want to try em */
2780 			verbose(VERB_ALGO, "wait for all targets for fallback");
2781 			qstate->ext_state[id] = module_wait_reply;
2782 			/* undo qname minimise step because we'll get back here
2783 			 * to do it again */
2784 			if(qout_orig && iq->minimise_count > 0) {
2785 				iq->minimise_count--;
2786 				iq->qinfo_out.qname = qout_orig;
2787 				iq->qinfo_out.qname_len = qout_orig_len;
2788 			}
2789 			return 0;
2790 		}
2791 		/* did we do enough fallback queries already? */
2792 		delegpt_count_addr(iq->dp, &naddr, &nres, &navail);
2793 		/* the current caps_server is the number of fallbacks sent.
2794 		 * the original query is one that matched too, so we have
2795 		 * caps_server+1 number of matching queries now */
2796 		if(iq->caps_server+1 >= naddr*3 ||
2797 			iq->caps_server*2+2 >= (size_t)ie->max_sent_count) {
2798 			/* *2 on sentcount check because ipv6 may fail */
2799 			/* we're done, process the response */
2800 			verbose(VERB_ALGO, "0x20 fallback had %d responses "
2801 				"match for %d wanted, done.",
2802 				(int)iq->caps_server+1, (int)naddr*3);
2803 			iq->response = iq->caps_response;
2804 			iq->caps_fallback = 0;
2805 			iter_dec_attempts(iq->dp, 3, ie->outbound_msg_retry); /* space for fallback */
2806 			iq->num_current_queries++; /* RespState decrements it*/
2807 			iq->referral_count++; /* make sure we don't loop */
2808 			iq->sent_count = 0;
2809 			iq->dp_target_count = 0;
2810 			iq->state = QUERY_RESP_STATE;
2811 			return 1;
2812 		}
2813 		verbose(VERB_ALGO, "0x20 fallback number %d",
2814 			(int)iq->caps_server);
2815 
2816 	/* if there is a policy to fetch missing targets
2817 	 * opportunistically, do it. we rely on the fact that once a
2818 	 * query (or queries) for a missing name have been issued,
2819 	 * they will not show up again. */
2820 	} else if(tf_policy != 0) {
2821 		int extra = 0;
2822 		verbose(VERB_ALGO, "attempt to get extra %d targets",
2823 			tf_policy);
2824 		(void)query_for_targets(qstate, iq, ie, id, tf_policy, &extra);
2825 		/* errors ignored, these targets are not strictly necessary for
2826 		 * this result, we do not have to reply with SERVFAIL */
2827 		iq->num_target_queries += extra;
2828 		target_count_increase(iq, extra);
2829 	}
2830 
2831 	/* Add the current set of unused targets to our queue. */
2832 	delegpt_add_unused_targets(iq->dp);
2833 
2834 	if(qstate->env->auth_zones) {
2835 		uint8_t* sname = NULL;
2836 		size_t snamelen = 0;
2837 		/* apply rpz triggers at query time; nameserver IP and dname */
2838 		struct dns_msg* forged_response_after_cname;
2839 		struct dns_msg* forged_response = rpz_callback_from_iterator_module(qstate, iq);
2840 		int count = 0;
2841 		while(forged_response && reply_find_rrset_section_an(
2842 			forged_response->rep, iq->qchase.qname,
2843 			iq->qchase.qname_len, LDNS_RR_TYPE_CNAME,
2844 			iq->qchase.qclass) &&
2845 			iq->qchase.qtype != LDNS_RR_TYPE_CNAME &&
2846 			count++ < ie->max_query_restarts) {
2847 			/* another cname to follow */
2848 			if(!handle_cname_response(qstate, iq, forged_response,
2849 				&sname, &snamelen)) {
2850 				errinf(qstate, "malloc failure, CNAME info");
2851 				return error_response(qstate, id, LDNS_RCODE_SERVFAIL);
2852 			}
2853 			iq->qchase.qname = sname;
2854 			iq->qchase.qname_len = snamelen;
2855 			forged_response_after_cname =
2856 				rpz_callback_from_iterator_cname(qstate, iq);
2857 			if(forged_response_after_cname) {
2858 				forged_response = forged_response_after_cname;
2859 			} else {
2860 				/* Follow the CNAME with a query restart */
2861 				iq->deleg_msg = NULL;
2862 				iq->dp = NULL;
2863 				iq->dsns_point = NULL;
2864 				iq->auth_zone_response = 0;
2865 				iq->refetch_glue = 0;
2866 				iq->query_restart_count++;
2867 				iq->sent_count = 0;
2868 				iq->dp_target_count = 0;
2869 				if(qstate->env->cfg->qname_minimisation)
2870 					iq->minimisation_state = INIT_MINIMISE_STATE;
2871 				outbound_list_clear(&iq->outlist);
2872 				iq->num_current_queries = 0;
2873 				fptr_ok(fptr_whitelist_modenv_detach_subs(
2874 					qstate->env->detach_subs));
2875 				(*qstate->env->detach_subs)(qstate);
2876 				iq->num_target_queries = 0;
2877 				return next_state(iq, INIT_REQUEST_STATE);
2878 			}
2879 		}
2880 		if(forged_response != NULL) {
2881 			qstate->ext_state[id] = module_finished;
2882 			qstate->return_rcode = LDNS_RCODE_NOERROR;
2883 			qstate->return_msg = forged_response;
2884 			iq->response = forged_response;
2885 			next_state(iq, FINISHED_STATE);
2886 			if(!iter_prepend(iq, qstate->return_msg, qstate->region)) {
2887 				log_err("rpz: prepend rrsets: out of memory");
2888 				return error_response(qstate, id, LDNS_RCODE_SERVFAIL);
2889 			}
2890 			return 0;
2891 		}
2892 	}
2893 
2894 	/* Select the next usable target, filtering out unsuitable targets. */
2895 	target = iter_server_selection(ie, qstate->env, iq->dp,
2896 		iq->dp->name, iq->dp->namelen, iq->qchase.qtype,
2897 		&iq->dnssec_lame_query, &iq->chase_to_rd,
2898 		iq->num_target_queries, qstate->blacklist,
2899 		qstate->prefetch_leeway);
2900 
2901 	/* If no usable target was selected... */
2902 	if(!target) {
2903 		/* Here we distinguish between three states: generate a new
2904 		 * target query, just wait, or quit (with a SERVFAIL).
2905 		 * We have the following information: number of active
2906 		 * target queries, number of active current queries,
2907 		 * the presence of missing targets at this delegation
2908 		 * point, and the given query target policy. */
2909 
2910 		/* Check for the wait condition. If this is true, then
2911 		 * an action must be taken. */
2912 		if(iq->num_target_queries==0 && iq->num_current_queries==0) {
2913 			/* If there is nothing to wait for, then we need
2914 			 * to distinguish between generating (a) new target
2915 			 * query, or failing. */
2916 			if(delegpt_count_missing_targets(iq->dp, NULL) > 0) {
2917 				int qs = 0, ret;
2918 				verbose(VERB_ALGO, "querying for next "
2919 					"missing target");
2920 				if((ret=query_for_targets(qstate, iq, ie, id,
2921 					1, &qs))!=0) {
2922 					errinf(qstate, "could not fetch nameserver");
2923 					errinf_dname(qstate, "at zone", iq->dp->name);
2924 					if(ret == 1)
2925 						return error_response(qstate, id,
2926 							LDNS_RCODE_SERVFAIL);
2927 					return error_response_cache(qstate, id,
2928 						LDNS_RCODE_SERVFAIL);
2929 				}
2930 				if(qs == 0 &&
2931 				   delegpt_count_missing_targets(iq->dp, NULL) == 0){
2932 					/* it looked like there were missing
2933 					 * targets, but they did not turn up.
2934 					 * Try the bad choices again (if any),
2935 					 * when we get back here missing==0,
2936 					 * so this is not a loop. */
2937 					return 1;
2938 				}
2939 				if(qs == 0) {
2940 					/* There should be targets now, and
2941 					 * if there are not, it should not
2942 					 * wait for no targets. Stop it from
2943 					 * waiting forever, or looping to
2944 					 * here, as a safeguard. */
2945 					errinf(qstate, "could not generate nameserver lookups");
2946 					errinf_dname(qstate, "at zone", iq->dp->name);
2947 					return error_response(qstate, id,
2948 						LDNS_RCODE_SERVFAIL);
2949 				}
2950 				iq->num_target_queries += qs;
2951 				target_count_increase(iq, qs);
2952 			}
2953 			/* Since a target query might have been made, we
2954 			 * need to check again. */
2955 			if(iq->num_target_queries == 0) {
2956 				/* if in capsforid fallback, instead of last
2957 				 * resort, we agree with the current reply
2958 				 * we have (if any) (our count of addrs bad)*/
2959 				if(iq->caps_fallback && iq->caps_reply) {
2960 					/* we're done, process the response */
2961 					verbose(VERB_ALGO, "0x20 fallback had %d responses, "
2962 						"but no more servers except "
2963 						"last resort, done.",
2964 						(int)iq->caps_server+1);
2965 					iq->response = iq->caps_response;
2966 					iq->caps_fallback = 0;
2967 					iter_dec_attempts(iq->dp, 3, ie->outbound_msg_retry); /* space for fallback */
2968 					iq->num_current_queries++; /* RespState decrements it*/
2969 					iq->referral_count++; /* make sure we don't loop */
2970 					iq->sent_count = 0;
2971 					iq->dp_target_count = 0;
2972 					iq->state = QUERY_RESP_STATE;
2973 					return 1;
2974 				}
2975 				return processLastResort(qstate, iq, ie, id);
2976 			}
2977 		}
2978 
2979 		/* otherwise, we have no current targets, so submerge
2980 		 * until one of the target or direct queries return. */
2981 		verbose(VERB_ALGO, "no current targets");
2982 		check_waiting_queries(iq, qstate, id);
2983 		/* undo qname minimise step because we'll get back here
2984 		 * to do it again */
2985 		if(qout_orig && iq->minimise_count > 0) {
2986 			iq->minimise_count--;
2987 			iq->qinfo_out.qname = qout_orig;
2988 			iq->qinfo_out.qname_len = qout_orig_len;
2989 		}
2990 		return 0;
2991 	}
2992 
2993 	/* We have a target. We could have created promiscuous target
2994 	 * queries but we are currently under pressure (mesh_jostle_exceeded).
2995 	 * If we are configured to allow promiscuous target queries and haven't
2996 	 * gone out to the network for a target query for this delegation, then
2997 	 * it is possible to slip in a promiscuous one with a 1/10 chance. */
2998 	if(can_do_promisc && tf_policy == 0 && iq->depth == 0
2999 		&& iq->depth < ie->max_dependency_depth
3000 		&& ie->target_fetch_policy[iq->depth] != 0
3001 		&& iq->dp_target_count == 0
3002 		&& !ub_random_max(qstate->env->rnd, 10)) {
3003 		int extra = 0;
3004 		verbose(VERB_ALGO, "available target exists in cache but "
3005 			"attempt to get extra 1 target");
3006 		(void)query_for_targets(qstate, iq, ie, id, 1, &extra);
3007 		/* errors ignored, these targets are not strictly necessary for
3008 		* this result, we do not have to reply with SERVFAIL */
3009 		if(extra > 0) {
3010 			iq->num_target_queries += extra;
3011 			target_count_increase(iq, extra);
3012 			check_waiting_queries(iq, qstate, id);
3013 			/* undo qname minimise step because we'll get back here
3014 			 * to do it again */
3015 			if(qout_orig && iq->minimise_count > 0) {
3016 				iq->minimise_count--;
3017 				iq->qinfo_out.qname = qout_orig;
3018 				iq->qinfo_out.qname_len = qout_orig_len;
3019 			}
3020 			return 0;
3021 		}
3022 	}
3023 
3024 	target_count_increase_global_quota(iq, 1);
3025 	if(iq->target_count && iq->target_count[TARGET_COUNT_GLOBAL_QUOTA]
3026 		> MAX_GLOBAL_QUOTA) {
3027 		char s[LDNS_MAX_DOMAINLEN+1];
3028 		dname_str(qstate->qinfo.qname, s);
3029 		verbose(VERB_QUERY, "request %s has exceeded the maximum "
3030 			"global quota on number of upstream queries %d", s,
3031 			iq->target_count[TARGET_COUNT_GLOBAL_QUOTA]);
3032 		return error_response_cache(qstate, id, LDNS_RCODE_SERVFAIL);
3033 	}
3034 
3035 	/* Do not check ratelimit for forwarding queries or if we already got a
3036 	 * pass. */
3037 	sq_check_ratelimit = (!(iq->chase_flags & BIT_RD) && !iq->ratelimit_ok);
3038 	/* We have a valid target. */
3039 	if(verbosity >= VERB_QUERY) {
3040 		log_query_info(VERB_QUERY, "sending query:", &iq->qinfo_out);
3041 		log_name_addr(VERB_QUERY, "sending to target:", iq->dp->name,
3042 			&target->addr, target->addrlen);
3043 		verbose(VERB_ALGO, "dnssec status: %s%s",
3044 			iq->dnssec_expected?"expected": "not expected",
3045 			iq->dnssec_lame_query?" but lame_query anyway": "");
3046 	}
3047 
3048 	real_addr = target->addr;
3049 	real_addrlen = target->addrlen;
3050 
3051 	if(ie->use_nat64 && target->addr.ss_family == AF_INET) {
3052 		addr_to_nat64(&target->addr, &ie->nat64_prefix_addr,
3053 			ie->nat64_prefix_addrlen, ie->nat64_prefix_net,
3054 			&real_addr, &real_addrlen);
3055 		log_name_addr(VERB_QUERY, "applied NAT64:",
3056 			iq->dp->name, &real_addr, real_addrlen);
3057 	}
3058 
3059 	fptr_ok(fptr_whitelist_modenv_send_query(qstate->env->send_query));
3060 	outq = (*qstate->env->send_query)(&iq->qinfo_out,
3061 		iq->chase_flags | (iq->chase_to_rd?BIT_RD:0),
3062 		/* unset CD if to forwarder(RD set) and not dnssec retry
3063 		 * (blacklist nonempty) and no trust-anchors are configured
3064 		 * above the qname or on the first attempt when dnssec is on */
3065 		(qstate->env->cfg->disable_edns_do?0:EDNS_DO)|
3066 		((iq->chase_to_rd||(iq->chase_flags&BIT_RD)!=0)&&
3067 		!qstate->blacklist&&(!iter_qname_indicates_dnssec(qstate->env,
3068 		&iq->qinfo_out)||target->attempts==1)?0:BIT_CD),
3069 		iq->dnssec_expected, iq->caps_fallback || is_caps_whitelisted(
3070 		ie, iq), sq_check_ratelimit, &real_addr, real_addrlen,
3071 		iq->dp->name, iq->dp->namelen,
3072 		(iq->dp->tcp_upstream || qstate->env->cfg->tcp_upstream),
3073 		(iq->dp->ssl_upstream || qstate->env->cfg->ssl_upstream),
3074 		target->tls_auth_name, qstate, &sq_was_ratelimited);
3075 	if(!outq) {
3076 		if(sq_was_ratelimited) {
3077 			lock_basic_lock(&ie->queries_ratelimit_lock);
3078 			ie->num_queries_ratelimited++;
3079 			lock_basic_unlock(&ie->queries_ratelimit_lock);
3080 			verbose(VERB_ALGO, "query exceeded ratelimits");
3081 			qstate->was_ratelimited = 1;
3082 			errinf_dname(qstate, "exceeded ratelimit for zone",
3083 				iq->dp->name);
3084 			return error_response_cache(qstate, id, LDNS_RCODE_SERVFAIL);
3085 		}
3086 		log_addr(VERB_QUERY, "error sending query to auth server",
3087 			&real_addr, real_addrlen);
3088 		if(qstate->env->cfg->qname_minimisation)
3089 			iq->minimisation_state = SKIP_MINIMISE_STATE;
3090 		return next_state(iq, QUERYTARGETS_STATE);
3091 	}
3092 	outbound_list_insert(&iq->outlist, outq);
3093 	iq->num_current_queries++;
3094 	iq->sent_count++;
3095 	qstate->ext_state[id] = module_wait_reply;
3096 
3097 	return 0;
3098 }
3099 
3100 /** find NS rrset in given list */
3101 static struct ub_packed_rrset_key*
3102 find_NS(struct reply_info* rep, size_t from, size_t to)
3103 {
3104 	size_t i;
3105 	for(i=from; i<to; i++) {
3106 		if(ntohs(rep->rrsets[i]->rk.type) == LDNS_RR_TYPE_NS)
3107 			return rep->rrsets[i];
3108 	}
3109 	return NULL;
3110 }
3111 
3112 
3113 /**
3114  * Process the query response. All queries end up at this state first. This
3115  * process generally consists of analyzing the response and routing the
3116  * event to the next state (either bouncing it back to a request state, or
3117  * terminating the processing for this event).
3118  *
3119  * @param qstate: query state.
3120  * @param iq: iterator query state.
3121  * @param ie: iterator shared global environment.
3122  * @param id: module id.
3123  * @return true if the event requires more immediate processing, false if
3124  *         not. This is generally only true when forwarding the request to
3125  *         the final state (i.e., on answer).
3126  */
3127 static int
3128 processQueryResponse(struct module_qstate* qstate, struct iter_qstate* iq,
3129 	struct iter_env* ie, int id)
3130 {
3131 	int dnsseclame = 0, origtypecname = 0, orig_empty_nodata_found;
3132 	enum response_type type;
3133 
3134 	iq->num_current_queries--;
3135 
3136 	if(!inplace_cb_query_response_call(qstate->env, qstate, iq->response))
3137 		log_err("unable to call query_response callback");
3138 
3139 	if(iq->response == NULL) {
3140 		/* Don't increment qname when QNAME minimisation is enabled */
3141 		if(qstate->env->cfg->qname_minimisation) {
3142 			iq->minimisation_state = SKIP_MINIMISE_STATE;
3143 		}
3144 		iq->timeout_count++;
3145 		iq->chase_to_rd = 0;
3146 		iq->dnssec_lame_query = 0;
3147 		verbose(VERB_ALGO, "query response was timeout");
3148 		return next_state(iq, QUERYTARGETS_STATE);
3149 	}
3150 	iq->timeout_count = 0;
3151 	orig_empty_nodata_found = iq->empty_nodata_found;
3152 	type = response_type_from_server(
3153 		(int)((iq->chase_flags&BIT_RD) || iq->chase_to_rd),
3154 		iq->response, &iq->qinfo_out, iq->dp, &iq->empty_nodata_found);
3155 	iq->chase_to_rd = 0;
3156 	/* remove TC flag, if this is erroneously set by TCP upstream */
3157 	iq->response->rep->flags &= ~BIT_TC;
3158 	if(orig_empty_nodata_found != iq->empty_nodata_found &&
3159 		iq->empty_nodata_found < EMPTY_NODATA_RETRY_COUNT) {
3160 		/* try to search at another server */
3161 		if(qstate->reply) {
3162 			struct delegpt_addr* a = delegpt_find_addr(
3163 				iq->dp, &qstate->reply->remote_addr,
3164 				qstate->reply->remote_addrlen);
3165 			/* make selection disprefer it */
3166 			if(a) a->lame = 1;
3167 		}
3168 		return next_state(iq, QUERYTARGETS_STATE);
3169 	}
3170 	if(type == RESPONSE_TYPE_REFERRAL && (iq->chase_flags&BIT_RD) &&
3171 		!iq->auth_zone_response) {
3172 		/* When forwarding (RD bit is set), we handle referrals
3173 		 * differently. No queries should be sent elsewhere */
3174 		type = RESPONSE_TYPE_ANSWER;
3175 	}
3176 	if(!qstate->env->cfg->disable_dnssec_lame_check && iq->dnssec_expected
3177                 && !iq->dnssec_lame_query &&
3178 		!(iq->chase_flags&BIT_RD)
3179 		&& iq->sent_count < DNSSEC_LAME_DETECT_COUNT
3180 		&& type != RESPONSE_TYPE_LAME
3181 		&& type != RESPONSE_TYPE_REC_LAME
3182 		&& type != RESPONSE_TYPE_THROWAWAY
3183 		&& type != RESPONSE_TYPE_UNTYPED) {
3184 		/* a possible answer, see if it is missing DNSSEC */
3185 		/* but not when forwarding, so we dont mark fwder lame */
3186 		if(!iter_msg_has_dnssec(iq->response)) {
3187 			/* Mark this address as dnsseclame in this dp,
3188 			 * because that will make serverselection disprefer
3189 			 * it, but also, once it is the only final option,
3190 			 * use dnssec-lame-bypass if it needs to query there.*/
3191 			if(qstate->reply) {
3192 				struct delegpt_addr* a = delegpt_find_addr(
3193 					iq->dp, &qstate->reply->remote_addr,
3194 					qstate->reply->remote_addrlen);
3195 				if(a) a->dnsseclame = 1;
3196 			}
3197 			/* test the answer is from the zone we expected,
3198 		 	 * otherwise, (due to parent,child on same server), we
3199 		 	 * might mark the server,zone lame inappropriately */
3200 			if(!iter_msg_from_zone(iq->response, iq->dp, type,
3201 				iq->qchase.qclass))
3202 				qstate->reply = NULL;
3203 			type = RESPONSE_TYPE_LAME;
3204 			dnsseclame = 1;
3205 		}
3206 	} else iq->dnssec_lame_query = 0;
3207 	/* see if referral brings us close to the target */
3208 	if(type == RESPONSE_TYPE_REFERRAL) {
3209 		struct ub_packed_rrset_key* ns = find_NS(
3210 			iq->response->rep, iq->response->rep->an_numrrsets,
3211 			iq->response->rep->an_numrrsets
3212 			+ iq->response->rep->ns_numrrsets);
3213 		if(!ns) ns = find_NS(iq->response->rep, 0,
3214 				iq->response->rep->an_numrrsets);
3215 		if(!ns || !dname_strict_subdomain_c(ns->rk.dname, iq->dp->name)
3216 			|| !dname_subdomain_c(iq->qchase.qname, ns->rk.dname)){
3217 			verbose(VERB_ALGO, "bad referral, throwaway");
3218 			type = RESPONSE_TYPE_THROWAWAY;
3219 		} else
3220 			iter_scrub_ds(iq->response, ns, iq->dp->name);
3221 	} else iter_scrub_ds(iq->response, NULL, NULL);
3222 	if(type == RESPONSE_TYPE_THROWAWAY &&
3223 		FLAGS_GET_RCODE(iq->response->rep->flags) == LDNS_RCODE_YXDOMAIN) {
3224 		/* YXDOMAIN is a permanent error, no need to retry */
3225 		type = RESPONSE_TYPE_ANSWER;
3226 	}
3227 	if(type == RESPONSE_TYPE_CNAME)
3228 		origtypecname = 1;
3229 	if(type == RESPONSE_TYPE_CNAME && iq->response->rep->an_numrrsets >= 1
3230 		&& ntohs(iq->response->rep->rrsets[0]->rk.type) == LDNS_RR_TYPE_DNAME) {
3231 		uint8_t* sname = NULL;
3232 		size_t snamelen = 0;
3233 		get_cname_target(iq->response->rep->rrsets[0], &sname,
3234 			&snamelen);
3235 		if(snamelen && dname_subdomain_c(sname, iq->response->rep->rrsets[0]->rk.dname)) {
3236 			/* DNAME to a subdomain loop; do not recurse */
3237 			type = RESPONSE_TYPE_ANSWER;
3238 		}
3239 	}
3240 	if(type == RESPONSE_TYPE_CNAME &&
3241 		iq->qchase.qtype == LDNS_RR_TYPE_CNAME &&
3242 		iq->minimisation_state == MINIMISE_STATE &&
3243 		query_dname_compare(iq->qchase.qname, iq->qinfo_out.qname) == 0) {
3244 		/* The minimised query for full QTYPE and hidden QTYPE can be
3245 		 * classified as CNAME response type, even when the original
3246 		 * QTYPE=CNAME. This should be treated as answer response type.
3247 		 */
3248 		type = RESPONSE_TYPE_ANSWER;
3249 	}
3250 
3251 	/* handle each of the type cases */
3252 	if(type == RESPONSE_TYPE_ANSWER) {
3253 		/* ANSWER type responses terminate the query algorithm,
3254 		 * so they sent on their */
3255 		if(verbosity >= VERB_DETAIL) {
3256 			verbose(VERB_DETAIL, "query response was %s",
3257 				FLAGS_GET_RCODE(iq->response->rep->flags)
3258 				==LDNS_RCODE_NXDOMAIN?"NXDOMAIN ANSWER":
3259 				(iq->response->rep->an_numrrsets?"ANSWER":
3260 				"nodata ANSWER"));
3261 		}
3262 		/* if qtype is DS, check we have the right level of answer,
3263 		 * like grandchild answer but we need the middle, reject it */
3264 		if(iq->qchase.qtype == LDNS_RR_TYPE_DS && !iq->dsns_point
3265 			&& !(iq->chase_flags&BIT_RD)
3266 			&& iter_ds_toolow(iq->response, iq->dp)
3267 			&& iter_dp_cangodown(&iq->qchase, iq->dp)) {
3268 			/* close down outstanding requests to be discarded */
3269 			outbound_list_clear(&iq->outlist);
3270 			iq->num_current_queries = 0;
3271 			fptr_ok(fptr_whitelist_modenv_detach_subs(
3272 				qstate->env->detach_subs));
3273 			(*qstate->env->detach_subs)(qstate);
3274 			iq->num_target_queries = 0;
3275 			return processDSNSFind(qstate, iq, id);
3276 		}
3277 		if(!qstate->no_cache_store)
3278 			iter_dns_store(qstate->env, &iq->response->qinfo,
3279 				iq->response->rep,
3280 				iq->qchase.qtype != iq->response->qinfo.qtype,
3281 				qstate->prefetch_leeway,
3282 				iq->dp&&iq->dp->has_parent_side_NS,
3283 				qstate->region, qstate->query_flags,
3284 				qstate->qstarttime);
3285 		/* close down outstanding requests to be discarded */
3286 		outbound_list_clear(&iq->outlist);
3287 		iq->num_current_queries = 0;
3288 		fptr_ok(fptr_whitelist_modenv_detach_subs(
3289 			qstate->env->detach_subs));
3290 		(*qstate->env->detach_subs)(qstate);
3291 		iq->num_target_queries = 0;
3292 		if(qstate->reply)
3293 			sock_list_insert(&qstate->reply_origin,
3294 				&qstate->reply->remote_addr,
3295 				qstate->reply->remote_addrlen, qstate->region);
3296 		if(iq->minimisation_state != DONOT_MINIMISE_STATE
3297 			&& !(iq->chase_flags & BIT_RD)) {
3298 			if(FLAGS_GET_RCODE(iq->response->rep->flags) !=
3299 				LDNS_RCODE_NOERROR) {
3300 				if(qstate->env->cfg->qname_minimisation_strict) {
3301 					if(FLAGS_GET_RCODE(iq->response->rep->flags) ==
3302 						LDNS_RCODE_NXDOMAIN) {
3303 						iter_scrub_nxdomain(iq->response);
3304 						return final_state(iq);
3305 					}
3306 					return error_response_cache(qstate, id,
3307 						LDNS_RCODE_SERVFAIL);
3308 				}
3309 				/* Best effort qname-minimisation.
3310 				 * Stop minimising and send full query when
3311 				 * RCODE is not NOERROR. */
3312 				iq->minimisation_state = DONOT_MINIMISE_STATE;
3313 			}
3314 			if(FLAGS_GET_RCODE(iq->response->rep->flags) ==
3315 				LDNS_RCODE_NXDOMAIN && !origtypecname) {
3316 				/* Stop resolving when NXDOMAIN is DNSSEC
3317 				 * signed. Based on assumption that nameservers
3318 				 * serving signed zones do not return NXDOMAIN
3319 				 * for empty-non-terminals. */
3320 				/* If this response is actually a CNAME type,
3321 				 * the nxdomain rcode may not be for the qname,
3322 				 * and so it is not the final response. */
3323 				if(iq->dnssec_expected)
3324 					return final_state(iq);
3325 				/* Make subrequest to validate intermediate
3326 				 * NXDOMAIN if harden-below-nxdomain is
3327 				 * enabled. */
3328 				if(qstate->env->cfg->harden_below_nxdomain &&
3329 					qstate->env->need_to_validate) {
3330 					struct module_qstate* subq = NULL;
3331 					log_query_info(VERB_QUERY,
3332 						"schedule NXDOMAIN validation:",
3333 						&iq->response->qinfo);
3334 					if(!generate_sub_request(
3335 						iq->response->qinfo.qname,
3336 						iq->response->qinfo.qname_len,
3337 						iq->response->qinfo.qtype,
3338 						iq->response->qinfo.qclass,
3339 						qstate, id, iq,
3340 						INIT_REQUEST_STATE,
3341 						FINISHED_STATE, &subq, 1, 1))
3342 						verbose(VERB_ALGO,
3343 						"could not validate NXDOMAIN "
3344 						"response");
3345 				}
3346 			}
3347 			return next_state(iq, QUERYTARGETS_STATE);
3348 		}
3349 		return final_state(iq);
3350 	} else if(type == RESPONSE_TYPE_REFERRAL) {
3351 		struct delegpt* old_dp = NULL;
3352 		/* REFERRAL type responses get a reset of the
3353 		 * delegation point, and back to the QUERYTARGETS_STATE. */
3354 		verbose(VERB_DETAIL, "query response was REFERRAL");
3355 
3356 		/* if hardened, only store referral if we asked for it */
3357 		if(!qstate->no_cache_store &&
3358 		(!qstate->env->cfg->harden_referral_path ||
3359 		    (  qstate->qinfo.qtype == LDNS_RR_TYPE_NS
3360 			&& (qstate->query_flags&BIT_RD)
3361 			&& !(qstate->query_flags&BIT_CD)
3362 			   /* we know that all other NS rrsets are scrubbed
3363 			    * away, thus on referral only one is left.
3364 			    * see if that equals the query name... */
3365 			&& ( /* auth section, but sometimes in answer section*/
3366 			  reply_find_rrset_section_ns(iq->response->rep,
3367 				iq->qchase.qname, iq->qchase.qname_len,
3368 				LDNS_RR_TYPE_NS, iq->qchase.qclass)
3369 			  || reply_find_rrset_section_an(iq->response->rep,
3370 				iq->qchase.qname, iq->qchase.qname_len,
3371 				LDNS_RR_TYPE_NS, iq->qchase.qclass)
3372 			  )
3373 		    ))) {
3374 			/* Store the referral under the current query */
3375 			/* no prefetch-leeway, since its not the answer */
3376 			iter_dns_store(qstate->env, &iq->response->qinfo,
3377 				iq->response->rep, 1, 0, 0, NULL, 0,
3378 				qstate->qstarttime);
3379 			if(iq->store_parent_NS)
3380 				iter_store_parentside_NS(qstate->env,
3381 					iq->response->rep);
3382 			if(qstate->env->neg_cache)
3383 				val_neg_addreferral(qstate->env->neg_cache,
3384 					iq->response->rep, iq->dp->name);
3385 		}
3386 		/* store parent-side-in-zone-glue, if directly queried for */
3387 		if(!qstate->no_cache_store && iq->query_for_pside_glue
3388 			&& !iq->pside_glue) {
3389 				iq->pside_glue = reply_find_rrset(iq->response->rep,
3390 					iq->qchase.qname, iq->qchase.qname_len,
3391 					iq->qchase.qtype, iq->qchase.qclass);
3392 				if(iq->pside_glue) {
3393 					log_rrset_key(VERB_ALGO, "found parent-side "
3394 						"glue", iq->pside_glue);
3395 					iter_store_parentside_rrset(qstate->env,
3396 						iq->pside_glue);
3397 				}
3398 		}
3399 
3400 		/* Reset the event state, setting the current delegation
3401 		 * point to the referral. */
3402 		iq->deleg_msg = iq->response;
3403 		/* Keep current delegation point for label comparison */
3404 		old_dp = iq->dp;
3405 		iq->dp = delegpt_from_message(iq->response, qstate->region);
3406 		if (qstate->env->cfg->qname_minimisation)
3407 			iq->minimisation_state = INIT_MINIMISE_STATE;
3408 		if(!iq->dp) {
3409 			errinf(qstate, "malloc failure, for delegation point");
3410 			return error_response(qstate, id, LDNS_RCODE_SERVFAIL);
3411 		}
3412 		if(old_dp->namelabs + 1 < iq->dp->namelabs) {
3413 			/* We got a grandchild delegation (more than one label
3414 			 * difference) than expected. Check for in-between
3415 			 * delegations in the cache and remove them.
3416 			 * They could prove problematic when they expire
3417 			 * and rrset_expired_above() encounters them during
3418 			 * delegation cache lookups. */
3419 			uint8_t* qname = iq->dp->name;
3420 			size_t qnamelen = iq->dp->namelen;
3421 			rrset_cache_remove_above(qstate->env->rrset_cache,
3422 				&qname, &qnamelen, LDNS_RR_TYPE_NS,
3423 				iq->qchase.qclass, *qstate->env->now,
3424 				old_dp->name, old_dp->namelen);
3425 		}
3426 		if(!cache_fill_missing(qstate->env, iq->qchase.qclass,
3427 			qstate->region, iq->dp)) {
3428 			errinf(qstate, "malloc failure, copy extra info into delegation point");
3429 			return error_response(qstate, id, LDNS_RCODE_SERVFAIL);
3430 		}
3431 		if(iq->store_parent_NS && query_dname_compare(iq->dp->name,
3432 			iq->store_parent_NS->name) == 0)
3433 			iter_merge_retry_counts(iq->dp, iq->store_parent_NS,
3434 				ie->outbound_msg_retry);
3435 		delegpt_log(VERB_ALGO, iq->dp);
3436 		/* Count this as a referral. */
3437 		iq->referral_count++;
3438 		iq->sent_count = 0;
3439 		iq->dp_target_count = 0;
3440 		/* see if the next dp is a trust anchor, or a DS was sent
3441 		 * along, indicating dnssec is expected for next zone */
3442 		iq->dnssec_expected = iter_indicates_dnssec(qstate->env,
3443 			iq->dp, iq->response, iq->qchase.qclass);
3444 		/* if dnssec, validating then also fetch the key for the DS */
3445 		if(iq->dnssec_expected && qstate->env->cfg->prefetch_key &&
3446 			!(qstate->query_flags&BIT_CD))
3447 			generate_dnskey_prefetch(qstate, iq, id);
3448 
3449 		/* spawn off NS and addr to auth servers for the NS we just
3450 		 * got in the referral. This gets authoritative answer
3451 		 * (answer section trust level) rrset.
3452 		 * right after, we detach the subs, answer goes to cache. */
3453 		if(qstate->env->cfg->harden_referral_path)
3454 			generate_ns_check(qstate, iq, id);
3455 
3456 		/* stop current outstanding queries.
3457 		 * FIXME: should the outstanding queries be waited for and
3458 		 * handled? Say by a subquery that inherits the outbound_entry.
3459 		 */
3460 		outbound_list_clear(&iq->outlist);
3461 		iq->num_current_queries = 0;
3462 		fptr_ok(fptr_whitelist_modenv_detach_subs(
3463 			qstate->env->detach_subs));
3464 		(*qstate->env->detach_subs)(qstate);
3465 		iq->num_target_queries = 0;
3466 		iq->response = NULL;
3467 		iq->fail_addr_type = 0;
3468 		verbose(VERB_ALGO, "cleared outbound list for next round");
3469 		return next_state(iq, QUERYTARGETS_STATE);
3470 	} else if(type == RESPONSE_TYPE_CNAME) {
3471 		uint8_t* sname = NULL;
3472 		size_t snamelen = 0;
3473 		/* CNAME type responses get a query restart (i.e., get a
3474 		 * reset of the query state and go back to INIT_REQUEST_STATE).
3475 		 */
3476 		verbose(VERB_DETAIL, "query response was CNAME");
3477 		if(verbosity >= VERB_ALGO)
3478 			log_dns_msg("cname msg", &iq->response->qinfo,
3479 				iq->response->rep);
3480 		/* if qtype is DS, check we have the right level of answer,
3481 		 * like grandchild answer but we need the middle, reject it */
3482 		if(iq->qchase.qtype == LDNS_RR_TYPE_DS && !iq->dsns_point
3483 			&& !(iq->chase_flags&BIT_RD)
3484 			&& iter_ds_toolow(iq->response, iq->dp)
3485 			&& iter_dp_cangodown(&iq->qchase, iq->dp)) {
3486 			outbound_list_clear(&iq->outlist);
3487 			iq->num_current_queries = 0;
3488 			fptr_ok(fptr_whitelist_modenv_detach_subs(
3489 				qstate->env->detach_subs));
3490 			(*qstate->env->detach_subs)(qstate);
3491 			iq->num_target_queries = 0;
3492 			return processDSNSFind(qstate, iq, id);
3493 		}
3494 		/* Process the CNAME response. */
3495 		if(!handle_cname_response(qstate, iq, iq->response,
3496 			&sname, &snamelen)) {
3497 			errinf(qstate, "malloc failure, CNAME info");
3498 			return error_response(qstate, id, LDNS_RCODE_SERVFAIL);
3499 		}
3500 		/* cache the CNAME response under the current query */
3501 		/* NOTE : set referral=1, so that rrsets get stored but not
3502 		 * the partial query answer (CNAME only). */
3503 		/* prefetchleeway applied because this updates answer parts */
3504 		if(!qstate->no_cache_store)
3505 			iter_dns_store(qstate->env, &iq->response->qinfo,
3506 				iq->response->rep, 1, qstate->prefetch_leeway,
3507 				iq->dp&&iq->dp->has_parent_side_NS, NULL,
3508 				qstate->query_flags, qstate->qstarttime);
3509 		/* set the current request's qname to the new value. */
3510 		iq->qchase.qname = sname;
3511 		iq->qchase.qname_len = snamelen;
3512 		if(qstate->env->auth_zones) {
3513 			/* apply rpz qname triggers after cname */
3514 			struct dns_msg* forged_response =
3515 				rpz_callback_from_iterator_cname(qstate, iq);
3516 			int count = 0;
3517 			while(forged_response && reply_find_rrset_section_an(
3518 				forged_response->rep, iq->qchase.qname,
3519 				iq->qchase.qname_len, LDNS_RR_TYPE_CNAME,
3520 				iq->qchase.qclass) &&
3521 				iq->qchase.qtype != LDNS_RR_TYPE_CNAME &&
3522 				count++ < ie->max_query_restarts) {
3523 				/* another cname to follow */
3524 				if(!handle_cname_response(qstate, iq, forged_response,
3525 					&sname, &snamelen)) {
3526 					errinf(qstate, "malloc failure, CNAME info");
3527 					return error_response(qstate, id, LDNS_RCODE_SERVFAIL);
3528 				}
3529 				iq->qchase.qname = sname;
3530 				iq->qchase.qname_len = snamelen;
3531 				forged_response =
3532 					rpz_callback_from_iterator_cname(qstate, iq);
3533 			}
3534 			if(forged_response != NULL) {
3535 				qstate->ext_state[id] = module_finished;
3536 				qstate->return_rcode = LDNS_RCODE_NOERROR;
3537 				qstate->return_msg = forged_response;
3538 				iq->response = forged_response;
3539 				next_state(iq, FINISHED_STATE);
3540 				if(!iter_prepend(iq, qstate->return_msg, qstate->region)) {
3541 					log_err("rpz: after cname, prepend rrsets: out of memory");
3542 					return error_response(qstate, id, LDNS_RCODE_SERVFAIL);
3543 				}
3544 				qstate->return_msg->qinfo = qstate->qinfo;
3545 				return 0;
3546 			}
3547 		}
3548 		/* Clear the query state, since this is a query restart. */
3549 		iq->deleg_msg = NULL;
3550 		iq->dp = NULL;
3551 		iq->dsns_point = NULL;
3552 		iq->auth_zone_response = 0;
3553 		iq->sent_count = 0;
3554 		iq->dp_target_count = 0;
3555 		if(iq->minimisation_state != MINIMISE_STATE)
3556 			/* Only count as query restart when it is not an extra
3557 			 * query as result of qname minimisation. */
3558 			iq->query_restart_count++;
3559 		if(qstate->env->cfg->qname_minimisation)
3560 			iq->minimisation_state = INIT_MINIMISE_STATE;
3561 
3562 		/* stop current outstanding queries.
3563 		 * FIXME: should the outstanding queries be waited for and
3564 		 * handled? Say by a subquery that inherits the outbound_entry.
3565 		 */
3566 		outbound_list_clear(&iq->outlist);
3567 		iq->num_current_queries = 0;
3568 		fptr_ok(fptr_whitelist_modenv_detach_subs(
3569 			qstate->env->detach_subs));
3570 		(*qstate->env->detach_subs)(qstate);
3571 		iq->num_target_queries = 0;
3572 		if(qstate->reply)
3573 			sock_list_insert(&qstate->reply_origin,
3574 				&qstate->reply->remote_addr,
3575 				qstate->reply->remote_addrlen, qstate->region);
3576 		verbose(VERB_ALGO, "cleared outbound list for query restart");
3577 		/* go to INIT_REQUEST_STATE for new qname. */
3578 		return next_state(iq, INIT_REQUEST_STATE);
3579 	} else if(type == RESPONSE_TYPE_LAME) {
3580 		/* Cache the LAMEness. */
3581 		verbose(VERB_DETAIL, "query response was %sLAME",
3582 			dnsseclame?"DNSSEC ":"");
3583 		if(!dname_subdomain_c(iq->qchase.qname, iq->dp->name)) {
3584 			log_err("mark lame: mismatch in qname and dpname");
3585 			/* throwaway this reply below */
3586 		} else if(qstate->reply) {
3587 			/* need addr for lameness cache, but we may have
3588 			 * gotten this from cache, so test to be sure */
3589 			if(!infra_set_lame(qstate->env->infra_cache,
3590 				&qstate->reply->remote_addr,
3591 				qstate->reply->remote_addrlen,
3592 				iq->dp->name, iq->dp->namelen,
3593 				*qstate->env->now, dnsseclame, 0,
3594 				iq->qchase.qtype))
3595 				log_err("mark host lame: out of memory");
3596 		}
3597 	} else if(type == RESPONSE_TYPE_REC_LAME) {
3598 		/* Cache the LAMEness. */
3599 		verbose(VERB_DETAIL, "query response REC_LAME: "
3600 			"recursive but not authoritative server");
3601 		if(!dname_subdomain_c(iq->qchase.qname, iq->dp->name)) {
3602 			log_err("mark rec_lame: mismatch in qname and dpname");
3603 			/* throwaway this reply below */
3604 		} else if(qstate->reply) {
3605 			/* need addr for lameness cache, but we may have
3606 			 * gotten this from cache, so test to be sure */
3607 			verbose(VERB_DETAIL, "mark as REC_LAME");
3608 			if(!infra_set_lame(qstate->env->infra_cache,
3609 				&qstate->reply->remote_addr,
3610 				qstate->reply->remote_addrlen,
3611 				iq->dp->name, iq->dp->namelen,
3612 				*qstate->env->now, 0, 1, iq->qchase.qtype))
3613 				log_err("mark host lame: out of memory");
3614 		}
3615 	} else if(type == RESPONSE_TYPE_THROWAWAY) {
3616 		/* LAME and THROWAWAY responses are handled the same way.
3617 		 * In this case, the event is just sent directly back to
3618 		 * the QUERYTARGETS_STATE without resetting anything,
3619 		 * because, clearly, the next target must be tried. */
3620 		verbose(VERB_DETAIL, "query response was THROWAWAY");
3621 	} else {
3622 		log_warn("A query response came back with an unknown type: %d",
3623 			(int)type);
3624 	}
3625 
3626 	/* LAME, THROWAWAY and "unknown" all end up here.
3627 	 * Recycle to the QUERYTARGETS state to hopefully try a
3628 	 * different target. */
3629 	if (qstate->env->cfg->qname_minimisation &&
3630 		!qstate->env->cfg->qname_minimisation_strict)
3631 		iq->minimisation_state = DONOT_MINIMISE_STATE;
3632 	if(iq->auth_zone_response) {
3633 		/* can we fallback? */
3634 		iq->auth_zone_response = 0;
3635 		if(!auth_zones_can_fallback(qstate->env->auth_zones,
3636 			iq->dp->name, iq->dp->namelen, qstate->qinfo.qclass)) {
3637 			verbose(VERB_ALGO, "auth zone response bad, and no"
3638 				" fallback possible, servfail");
3639 			errinf_dname(qstate, "response is bad, no fallback, "
3640 				"for auth zone", iq->dp->name);
3641 			return error_response_cache(qstate, id, LDNS_RCODE_SERVFAIL);
3642 		}
3643 		verbose(VERB_ALGO, "auth zone response was bad, "
3644 			"fallback enabled");
3645 		iq->auth_zone_avoid = 1;
3646 		if(iq->dp->auth_dp) {
3647 			/* we are using a dp for the auth zone, with no
3648 			 * nameservers, get one first */
3649 			iq->dp = NULL;
3650 			return next_state(iq, INIT_REQUEST_STATE);
3651 		}
3652 	}
3653 	return next_state(iq, QUERYTARGETS_STATE);
3654 }
3655 
3656 /**
3657  * Return priming query results to interested super querystates.
3658  *
3659  * Sets the delegation point and delegation message (not nonRD queries).
3660  * This is a callback from walk_supers.
3661  *
3662  * @param qstate: priming query state that finished.
3663  * @param id: module id.
3664  * @param forq: the qstate for which priming has been done.
3665  */
3666 static void
3667 prime_supers(struct module_qstate* qstate, int id, struct module_qstate* forq)
3668 {
3669 	struct iter_qstate* foriq = (struct iter_qstate*)forq->minfo[id];
3670 	struct delegpt* dp = NULL;
3671 
3672 	log_assert(qstate->is_priming || foriq->wait_priming_stub);
3673 	log_assert(qstate->return_rcode == LDNS_RCODE_NOERROR);
3674 	/* Convert our response to a delegation point */
3675 	dp = delegpt_from_message(qstate->return_msg, forq->region);
3676 	if(!dp) {
3677 		/* if there is no convertible delegation point, then
3678 		 * the ANSWER type was (presumably) a negative answer. */
3679 		verbose(VERB_ALGO, "prime response was not a positive "
3680 			"ANSWER; failing");
3681 		foriq->dp = NULL;
3682 		foriq->state = QUERYTARGETS_STATE;
3683 		return;
3684 	}
3685 
3686 	log_query_info(VERB_DETAIL, "priming successful for", &qstate->qinfo);
3687 	delegpt_log(VERB_ALGO, dp);
3688 	foriq->dp = dp;
3689 	foriq->deleg_msg = dns_copy_msg(qstate->return_msg, forq->region);
3690 	if(!foriq->deleg_msg) {
3691 		log_err("copy prime response: out of memory");
3692 		foriq->dp = NULL;
3693 		foriq->state = QUERYTARGETS_STATE;
3694 		return;
3695 	}
3696 
3697 	/* root priming responses go to init stage 2, priming stub
3698 	 * responses to to stage 3. */
3699 	if(foriq->wait_priming_stub) {
3700 		foriq->state = INIT_REQUEST_3_STATE;
3701 		foriq->wait_priming_stub = 0;
3702 	} else	foriq->state = INIT_REQUEST_2_STATE;
3703 	/* because we are finished, the parent will be reactivated */
3704 }
3705 
3706 /**
3707  * This handles the response to a priming query. This is used to handle both
3708  * root and stub priming responses. This is basically the equivalent of the
3709  * QUERY_RESP_STATE, but will not handle CNAME responses and will treat
3710  * REFERRALs as ANSWERS. It will also update and reactivate the originating
3711  * event.
3712  *
3713  * @param qstate: query state.
3714  * @param id: module id.
3715  * @return true if the event needs more immediate processing, false if not.
3716  *         This state always returns false.
3717  */
3718 static int
3719 processPrimeResponse(struct module_qstate* qstate, int id)
3720 {
3721 	struct iter_qstate* iq = (struct iter_qstate*)qstate->minfo[id];
3722 	enum response_type type;
3723 	iq->response->rep->flags &= ~(BIT_RD|BIT_RA); /* ignore rec-lame */
3724 	type = response_type_from_server(
3725 		(int)((iq->chase_flags&BIT_RD) || iq->chase_to_rd),
3726 		iq->response, &iq->qchase, iq->dp, NULL);
3727 	if(type == RESPONSE_TYPE_ANSWER) {
3728 		qstate->return_rcode = LDNS_RCODE_NOERROR;
3729 		qstate->return_msg = iq->response;
3730 	} else {
3731 		errinf(qstate, "prime response did not get an answer");
3732 		errinf_dname(qstate, "for", qstate->qinfo.qname);
3733 		qstate->return_rcode = LDNS_RCODE_SERVFAIL;
3734 		qstate->return_msg = NULL;
3735 	}
3736 
3737 	/* validate the root or stub after priming (if enabled).
3738 	 * This is the same query as the prime query, but with validation.
3739 	 * Now that we are primed, the additional queries that validation
3740 	 * may need can be resolved. */
3741 	if(qstate->env->cfg->harden_referral_path) {
3742 		struct module_qstate* subq = NULL;
3743 		log_nametypeclass(VERB_ALGO, "schedule prime validation",
3744 			qstate->qinfo.qname, qstate->qinfo.qtype,
3745 			qstate->qinfo.qclass);
3746 		if(!generate_sub_request(qstate->qinfo.qname,
3747 			qstate->qinfo.qname_len, qstate->qinfo.qtype,
3748 			qstate->qinfo.qclass, qstate, id, iq,
3749 			INIT_REQUEST_STATE, FINISHED_STATE, &subq, 1, 0)) {
3750 			verbose(VERB_ALGO, "could not generate prime check");
3751 		}
3752 		generate_a_aaaa_check(qstate, iq, id);
3753 	}
3754 
3755 	/* This event is finished. */
3756 	qstate->ext_state[id] = module_finished;
3757 	return 0;
3758 }
3759 
3760 /**
3761  * Do final processing on responses to target queries. Events reach this
3762  * state after the iterative resolution algorithm terminates. This state is
3763  * responsible for reactivating the original event, and housekeeping related
3764  * to received target responses (caching, updating the current delegation
3765  * point, etc).
3766  * Callback from walk_supers for every super state that is interested in
3767  * the results from this query.
3768  *
3769  * @param qstate: query state.
3770  * @param id: module id.
3771  * @param forq: super query state.
3772  */
3773 static void
3774 processTargetResponse(struct module_qstate* qstate, int id,
3775 	struct module_qstate* forq)
3776 {
3777 	struct iter_env* ie = (struct iter_env*)qstate->env->modinfo[id];
3778 	struct iter_qstate* iq = (struct iter_qstate*)qstate->minfo[id];
3779 	struct iter_qstate* foriq = (struct iter_qstate*)forq->minfo[id];
3780 	struct ub_packed_rrset_key* rrset;
3781 	struct delegpt_ns* dpns;
3782 	log_assert(qstate->return_rcode == LDNS_RCODE_NOERROR);
3783 
3784 	foriq->state = QUERYTARGETS_STATE;
3785 	log_query_info(VERB_ALGO, "processTargetResponse", &qstate->qinfo);
3786 	log_query_info(VERB_ALGO, "processTargetResponse super", &forq->qinfo);
3787 
3788 	/* Tell the originating event that this target query has finished
3789 	 * (regardless if it succeeded or not). */
3790 	foriq->num_target_queries--;
3791 
3792 	/* check to see if parent event is still interested (in orig name).  */
3793 	if(!foriq->dp) {
3794 		verbose(VERB_ALGO, "subq: parent not interested, was reset");
3795 		return; /* not interested anymore */
3796 	}
3797 	dpns = delegpt_find_ns(foriq->dp, qstate->qinfo.qname,
3798 			qstate->qinfo.qname_len);
3799 	if(!dpns) {
3800 		/* If not interested, just stop processing this event */
3801 		verbose(VERB_ALGO, "subq: parent not interested anymore");
3802 		/* could be because parent was jostled out of the cache,
3803 		   and a new identical query arrived, that does not want it*/
3804 		return;
3805 	}
3806 
3807 	/* if iq->query_for_pside_glue then add the pside_glue (marked lame) */
3808 	if(iq->pside_glue) {
3809 		/* if the pside_glue is NULL, then it could not be found,
3810 		 * the done_pside is already set when created and a cache
3811 		 * entry created in processFinished so nothing to do here */
3812 		log_rrset_key(VERB_ALGO, "add parentside glue to dp",
3813 			iq->pside_glue);
3814 		if(!delegpt_add_rrset(foriq->dp, forq->region,
3815 			iq->pside_glue, 1, NULL))
3816 			log_err("out of memory adding pside glue");
3817 	}
3818 
3819 	/* This response is relevant to the current query, so we
3820 	 * add (attempt to add, anyway) this target(s) and reactivate
3821 	 * the original event.
3822 	 * NOTE: we could only look for the AnswerRRset if the
3823 	 * response type was ANSWER. */
3824 	rrset = reply_find_answer_rrset(&iq->qchase, qstate->return_msg->rep);
3825 	if(rrset) {
3826 		int additions = 0;
3827 		/* if CNAMEs have been followed - add new NS to delegpt. */
3828 		/* BTW. RFC 1918 says NS should not have got CNAMEs. Robust. */
3829 		if(!delegpt_find_ns(foriq->dp, rrset->rk.dname,
3830 			rrset->rk.dname_len)) {
3831 			/* if dpns->lame then set newcname ns lame too */
3832 			if(!delegpt_add_ns(foriq->dp, forq->region,
3833 				rrset->rk.dname, dpns->lame, dpns->tls_auth_name,
3834 				dpns->port))
3835 				log_err("out of memory adding cnamed-ns");
3836 		}
3837 		/* if dpns->lame then set the address(es) lame too */
3838 		if(!delegpt_add_rrset(foriq->dp, forq->region, rrset,
3839 			dpns->lame, &additions))
3840 			log_err("out of memory adding targets");
3841 		if(!additions) {
3842 			/* no new addresses, increase the nxns counter, like
3843 			 * this could be a list of wildcards with no new
3844 			 * addresses */
3845 			target_count_increase_nx(foriq, 1);
3846 		}
3847 		verbose(VERB_ALGO, "added target response");
3848 		delegpt_log(VERB_ALGO, foriq->dp);
3849 	} else {
3850 		verbose(VERB_ALGO, "iterator TargetResponse failed");
3851 		delegpt_mark_neg(dpns, qstate->qinfo.qtype);
3852 		if((dpns->got4 == 2 || (!ie->supports_ipv4 && !ie->use_nat64)) &&
3853 			(dpns->got6 == 2 || !ie->supports_ipv6)) {
3854 			dpns->resolved = 1; /* fail the target */
3855 			/* do not count cached answers */
3856 			if(qstate->reply_origin && qstate->reply_origin->len != 0) {
3857 				target_count_increase_nx(foriq, 1);
3858 			}
3859 		}
3860 	}
3861 }
3862 
3863 /**
3864  * Process response for DS NS Find queries, that attempt to find the delegation
3865  * point where we ask the DS query from.
3866  *
3867  * @param qstate: query state.
3868  * @param id: module id.
3869  * @param forq: super query state.
3870  */
3871 static void
3872 processDSNSResponse(struct module_qstate* qstate, int id,
3873 	struct module_qstate* forq)
3874 {
3875 	struct iter_qstate* foriq = (struct iter_qstate*)forq->minfo[id];
3876 
3877 	/* if the finished (iq->response) query has no NS set: continue
3878 	 * up to look for the right dp; nothing to change, do DPNSstate */
3879 	if(qstate->return_rcode != LDNS_RCODE_NOERROR)
3880 		return; /* seek further */
3881 	/* find the NS RRset (without allowing CNAMEs) */
3882 	if(!reply_find_rrset(qstate->return_msg->rep, qstate->qinfo.qname,
3883 		qstate->qinfo.qname_len, LDNS_RR_TYPE_NS,
3884 		qstate->qinfo.qclass)){
3885 		return; /* seek further */
3886 	}
3887 
3888 	/* else, store as DP and continue at querytargets */
3889 	foriq->state = QUERYTARGETS_STATE;
3890 	foriq->dp = delegpt_from_message(qstate->return_msg, forq->region);
3891 	if(!foriq->dp) {
3892 		log_err("out of memory in dsns dp alloc");
3893 		errinf(qstate, "malloc failure, in DS search");
3894 		return; /* dp==NULL in QUERYTARGETS makes SERVFAIL */
3895 	}
3896 	/* success, go query the querytargets in the new dp (and go down) */
3897 }
3898 
3899 /**
3900  * Process response for qclass=ANY queries for a particular class.
3901  * Append to result or error-exit.
3902  *
3903  * @param qstate: query state.
3904  * @param id: module id.
3905  * @param forq: super query state.
3906  */
3907 static void
3908 processClassResponse(struct module_qstate* qstate, int id,
3909 	struct module_qstate* forq)
3910 {
3911 	struct iter_qstate* foriq = (struct iter_qstate*)forq->minfo[id];
3912 	struct dns_msg* from = qstate->return_msg;
3913 	log_query_info(VERB_ALGO, "processClassResponse", &qstate->qinfo);
3914 	log_query_info(VERB_ALGO, "processClassResponse super", &forq->qinfo);
3915 	if(qstate->return_rcode != LDNS_RCODE_NOERROR) {
3916 		/* cause servfail for qclass ANY query */
3917 		foriq->response = NULL;
3918 		foriq->state = FINISHED_STATE;
3919 		return;
3920 	}
3921 	/* append result */
3922 	if(!foriq->response) {
3923 		/* allocate the response: copy RCODE, sec_state */
3924 		foriq->response = dns_copy_msg(from, forq->region);
3925 		if(!foriq->response) {
3926 			log_err("malloc failed for qclass ANY response");
3927 			foriq->state = FINISHED_STATE;
3928 			return;
3929 		}
3930 		foriq->response->qinfo.qclass = forq->qinfo.qclass;
3931 		/* qclass ANY does not receive the AA flag on replies */
3932 		foriq->response->rep->authoritative = 0;
3933 	} else {
3934 		struct dns_msg* to = foriq->response;
3935 		/* add _from_ this response _to_ existing collection */
3936 		/* if there are records, copy RCODE */
3937 		/* lower sec_state if this message is lower */
3938 		if(from->rep->rrset_count != 0) {
3939 			size_t n = from->rep->rrset_count+to->rep->rrset_count;
3940 			struct ub_packed_rrset_key** dest, **d;
3941 			/* copy appropriate rcode */
3942 			to->rep->flags = from->rep->flags;
3943 			/* copy rrsets */
3944 			if(from->rep->rrset_count > RR_COUNT_MAX ||
3945 				to->rep->rrset_count > RR_COUNT_MAX) {
3946 				log_err("malloc failed (too many rrsets) in collect ANY");
3947 				foriq->state = FINISHED_STATE;
3948 				return; /* integer overflow protection */
3949 			}
3950 			dest = regional_alloc(forq->region, sizeof(dest[0])*n);
3951 			if(!dest) {
3952 				log_err("malloc failed in collect ANY");
3953 				foriq->state = FINISHED_STATE;
3954 				return;
3955 			}
3956 			d = dest;
3957 			/* copy AN */
3958 			memcpy(dest, to->rep->rrsets, to->rep->an_numrrsets
3959 				* sizeof(dest[0]));
3960 			dest += to->rep->an_numrrsets;
3961 			memcpy(dest, from->rep->rrsets, from->rep->an_numrrsets
3962 				* sizeof(dest[0]));
3963 			dest += from->rep->an_numrrsets;
3964 			/* copy NS */
3965 			memcpy(dest, to->rep->rrsets+to->rep->an_numrrsets,
3966 				to->rep->ns_numrrsets * sizeof(dest[0]));
3967 			dest += to->rep->ns_numrrsets;
3968 			memcpy(dest, from->rep->rrsets+from->rep->an_numrrsets,
3969 				from->rep->ns_numrrsets * sizeof(dest[0]));
3970 			dest += from->rep->ns_numrrsets;
3971 			/* copy AR */
3972 			memcpy(dest, to->rep->rrsets+to->rep->an_numrrsets+
3973 				to->rep->ns_numrrsets,
3974 				to->rep->ar_numrrsets * sizeof(dest[0]));
3975 			dest += to->rep->ar_numrrsets;
3976 			memcpy(dest, from->rep->rrsets+from->rep->an_numrrsets+
3977 				from->rep->ns_numrrsets,
3978 				from->rep->ar_numrrsets * sizeof(dest[0]));
3979 			/* update counts */
3980 			to->rep->rrsets = d;
3981 			to->rep->an_numrrsets += from->rep->an_numrrsets;
3982 			to->rep->ns_numrrsets += from->rep->ns_numrrsets;
3983 			to->rep->ar_numrrsets += from->rep->ar_numrrsets;
3984 			to->rep->rrset_count = n;
3985 		}
3986 		if(from->rep->security < to->rep->security) /* lowest sec */
3987 			to->rep->security = from->rep->security;
3988 		if(from->rep->qdcount != 0) /* insert qd if appropriate */
3989 			to->rep->qdcount = from->rep->qdcount;
3990 		if(from->rep->ttl < to->rep->ttl) /* use smallest TTL */
3991 			to->rep->ttl = from->rep->ttl;
3992 		if(from->rep->prefetch_ttl < to->rep->prefetch_ttl)
3993 			to->rep->prefetch_ttl = from->rep->prefetch_ttl;
3994 		if(from->rep->serve_expired_ttl < to->rep->serve_expired_ttl)
3995 			to->rep->serve_expired_ttl = from->rep->serve_expired_ttl;
3996 	}
3997 	/* are we done? */
3998 	foriq->num_current_queries --;
3999 	if(foriq->num_current_queries == 0)
4000 		foriq->state = FINISHED_STATE;
4001 }
4002 
4003 /**
4004  * Collect class ANY responses and make them into one response.  This
4005  * state is started and it creates queries for all classes (that have
4006  * root hints).  The answers are then collected.
4007  *
4008  * @param qstate: query state.
4009  * @param id: module id.
4010  * @return true if the event needs more immediate processing, false if not.
4011  */
4012 static int
4013 processCollectClass(struct module_qstate* qstate, int id)
4014 {
4015 	struct iter_qstate* iq = (struct iter_qstate*)qstate->minfo[id];
4016 	struct module_qstate* subq;
4017 	/* If qchase.qclass == 0 then send out queries for all classes.
4018 	 * Otherwise, do nothing (wait for all answers to arrive and the
4019 	 * processClassResponse to put them together, and that moves us
4020 	 * towards the Finished state when done. */
4021 	if(iq->qchase.qclass == 0) {
4022 		uint16_t c = 0;
4023 		iq->qchase.qclass = LDNS_RR_CLASS_ANY;
4024 		while(iter_get_next_root(qstate->env->hints,
4025 			qstate->env->fwds, &c)) {
4026 			/* generate query for this class */
4027 			log_nametypeclass(VERB_ALGO, "spawn collect query",
4028 				qstate->qinfo.qname, qstate->qinfo.qtype, c);
4029 			if(!generate_sub_request(qstate->qinfo.qname,
4030 				qstate->qinfo.qname_len, qstate->qinfo.qtype,
4031 				c, qstate, id, iq, INIT_REQUEST_STATE,
4032 				FINISHED_STATE, &subq,
4033 				(int)!(qstate->query_flags&BIT_CD), 0)) {
4034 				errinf(qstate, "could not generate class ANY"
4035 					" lookup query");
4036 				return error_response(qstate, id,
4037 					LDNS_RCODE_SERVFAIL);
4038 			}
4039 			/* ignore subq, no special init required */
4040 			iq->num_current_queries ++;
4041 			if(c == 0xffff)
4042 				break;
4043 			else c++;
4044 		}
4045 		/* if no roots are configured at all, return */
4046 		if(iq->num_current_queries == 0) {
4047 			verbose(VERB_ALGO, "No root hints or fwds, giving up "
4048 				"on qclass ANY");
4049 			return error_response_cache(qstate, id, LDNS_RCODE_REFUSED);
4050 		}
4051 		/* return false, wait for queries to return */
4052 	}
4053 	/* if woke up here because of an answer, wait for more answers */
4054 	return 0;
4055 }
4056 
4057 /**
4058  * This handles the final state for first-tier responses (i.e., responses to
4059  * externally generated queries).
4060  *
4061  * @param qstate: query state.
4062  * @param iq: iterator query state.
4063  * @param id: module id.
4064  * @return true if the event needs more processing, false if not. Since this
4065  *         is the final state for an event, it always returns false.
4066  */
4067 static int
4068 processFinished(struct module_qstate* qstate, struct iter_qstate* iq,
4069 	int id)
4070 {
4071 	log_query_info(VERB_QUERY, "finishing processing for",
4072 		&qstate->qinfo);
4073 
4074 	/* store negative cache element for parent side glue. */
4075 	if(!qstate->no_cache_store && iq->query_for_pside_glue
4076 		&& !iq->pside_glue)
4077 			iter_store_parentside_neg(qstate->env, &qstate->qinfo,
4078 				iq->deleg_msg?iq->deleg_msg->rep:
4079 				(iq->response?iq->response->rep:NULL));
4080 	if(!iq->response) {
4081 		verbose(VERB_ALGO, "No response is set, servfail");
4082 		errinf(qstate, "(no response found at query finish)");
4083 		return error_response(qstate, id, LDNS_RCODE_SERVFAIL);
4084 	}
4085 
4086 	/* Make sure that the RA flag is set (since the presence of
4087 	 * this module means that recursion is available) */
4088 	iq->response->rep->flags |= BIT_RA;
4089 
4090 	/* Clear the AA flag */
4091 	/* FIXME: does this action go here or in some other module? */
4092 	iq->response->rep->flags &= ~BIT_AA;
4093 
4094 	/* make sure QR flag is on */
4095 	iq->response->rep->flags |= BIT_QR;
4096 
4097 	/* explicitly set the EDE string to NULL */
4098 	iq->response->rep->reason_bogus_str = NULL;
4099 	if((qstate->env->cfg->val_log_level >= 2 ||
4100 		qstate->env->cfg->log_servfail) && qstate->errinf &&
4101 		!qstate->env->cfg->val_log_squelch) {
4102 		char* err_str = errinf_to_str_misc(qstate);
4103 		if(err_str) {
4104 			verbose(VERB_ALGO, "iterator EDE: %s", err_str);
4105 			iq->response->rep->reason_bogus_str = err_str;
4106 		}
4107 	}
4108 
4109 	/* we have finished processing this query */
4110 	qstate->ext_state[id] = module_finished;
4111 
4112 	/* TODO:  we are using a private TTL, trim the response. */
4113 	/* if (mPrivateTTL > 0){IterUtils.setPrivateTTL(resp, mPrivateTTL); } */
4114 
4115 	/* prepend any items we have accumulated */
4116 	if(iq->an_prepend_list || iq->ns_prepend_list) {
4117 		if(!iter_prepend(iq, iq->response, qstate->region)) {
4118 			log_err("prepend rrsets: out of memory");
4119 			return error_response(qstate, id, LDNS_RCODE_SERVFAIL);
4120 		}
4121 		/* reset the query name back */
4122 		iq->response->qinfo = qstate->qinfo;
4123 		/* the security state depends on the combination */
4124 		iq->response->rep->security = sec_status_unchecked;
4125 		/* store message with the finished prepended items,
4126 		 * but only if we did recursion. The nonrecursion referral
4127 		 * from cache does not need to be stored in the msg cache. */
4128 		if(!qstate->no_cache_store && qstate->query_flags&BIT_RD) {
4129 			iter_dns_store(qstate->env, &qstate->qinfo,
4130 				iq->response->rep, 0, qstate->prefetch_leeway,
4131 				iq->dp&&iq->dp->has_parent_side_NS,
4132 				qstate->region, qstate->query_flags,
4133 				qstate->qstarttime);
4134 		}
4135 	}
4136 	qstate->return_rcode = LDNS_RCODE_NOERROR;
4137 	qstate->return_msg = iq->response;
4138 	return 0;
4139 }
4140 
4141 /*
4142  * Return priming query results to interested super querystates.
4143  *
4144  * Sets the delegation point and delegation message (not nonRD queries).
4145  * This is a callback from walk_supers.
4146  *
4147  * @param qstate: query state that finished.
4148  * @param id: module id.
4149  * @param super: the qstate to inform.
4150  */
4151 void
4152 iter_inform_super(struct module_qstate* qstate, int id,
4153 	struct module_qstate* super)
4154 {
4155 	if(!qstate->is_priming && super->qinfo.qclass == LDNS_RR_CLASS_ANY)
4156 		processClassResponse(qstate, id, super);
4157 	else if(super->qinfo.qtype == LDNS_RR_TYPE_DS && ((struct iter_qstate*)
4158 		super->minfo[id])->state == DSNS_FIND_STATE)
4159 		processDSNSResponse(qstate, id, super);
4160 	else if(qstate->return_rcode != LDNS_RCODE_NOERROR)
4161 		error_supers(qstate, id, super);
4162 	else if(qstate->is_priming)
4163 		prime_supers(qstate, id, super);
4164 	else	processTargetResponse(qstate, id, super);
4165 }
4166 
4167 /**
4168  * Handle iterator state.
4169  * Handle events. This is the real processing loop for events, responsible
4170  * for moving events through the various states. If a processing method
4171  * returns true, then it will be advanced to the next state. If false, then
4172  * processing will stop.
4173  *
4174  * @param qstate: query state.
4175  * @param ie: iterator shared global environment.
4176  * @param iq: iterator query state.
4177  * @param id: module id.
4178  */
4179 static void
4180 iter_handle(struct module_qstate* qstate, struct iter_qstate* iq,
4181 	struct iter_env* ie, int id)
4182 {
4183 	int cont = 1;
4184 	while(cont) {
4185 		verbose(VERB_ALGO, "iter_handle processing q with state %s",
4186 			iter_state_to_string(iq->state));
4187 		switch(iq->state) {
4188 			case INIT_REQUEST_STATE:
4189 				cont = processInitRequest(qstate, iq, ie, id);
4190 				break;
4191 			case INIT_REQUEST_2_STATE:
4192 				cont = processInitRequest2(qstate, iq, id);
4193 				break;
4194 			case INIT_REQUEST_3_STATE:
4195 				cont = processInitRequest3(qstate, iq, id);
4196 				break;
4197 			case QUERYTARGETS_STATE:
4198 				cont = processQueryTargets(qstate, iq, ie, id);
4199 				break;
4200 			case QUERY_RESP_STATE:
4201 				cont = processQueryResponse(qstate, iq, ie, id);
4202 				break;
4203 			case PRIME_RESP_STATE:
4204 				cont = processPrimeResponse(qstate, id);
4205 				break;
4206 			case COLLECT_CLASS_STATE:
4207 				cont = processCollectClass(qstate, id);
4208 				break;
4209 			case DSNS_FIND_STATE:
4210 				cont = processDSNSFind(qstate, iq, id);
4211 				break;
4212 			case FINISHED_STATE:
4213 				cont = processFinished(qstate, iq, id);
4214 				break;
4215 			default:
4216 				log_warn("iterator: invalid state: %d",
4217 					iq->state);
4218 				cont = 0;
4219 				break;
4220 		}
4221 	}
4222 }
4223 
4224 /**
4225  * This is the primary entry point for processing request events. Note that
4226  * this method should only be used by external modules.
4227  * @param qstate: query state.
4228  * @param ie: iterator shared global environment.
4229  * @param iq: iterator query state.
4230  * @param id: module id.
4231  */
4232 static void
4233 process_request(struct module_qstate* qstate, struct iter_qstate* iq,
4234 	struct iter_env* ie, int id)
4235 {
4236 	/* external requests start in the INIT state, and finish using the
4237 	 * FINISHED state. */
4238 	iq->state = INIT_REQUEST_STATE;
4239 	iq->final_state = FINISHED_STATE;
4240 	verbose(VERB_ALGO, "process_request: new external request event");
4241 	iter_handle(qstate, iq, ie, id);
4242 }
4243 
4244 /** process authoritative server reply */
4245 static void
4246 process_response(struct module_qstate* qstate, struct iter_qstate* iq,
4247 	struct iter_env* ie, int id, struct outbound_entry* outbound,
4248 	enum module_ev event)
4249 {
4250 	struct msg_parse* prs;
4251 	struct edns_data edns;
4252 	sldns_buffer* pkt;
4253 
4254 	verbose(VERB_ALGO, "process_response: new external response event");
4255 	iq->response = NULL;
4256 	iq->state = QUERY_RESP_STATE;
4257 	if(event == module_event_noreply || event == module_event_error) {
4258 		if(event == module_event_noreply && iq->timeout_count >= 3 &&
4259 			qstate->env->cfg->use_caps_bits_for_id &&
4260 			!iq->caps_fallback && !is_caps_whitelisted(ie, iq)) {
4261 			/* start fallback */
4262 			iq->caps_fallback = 1;
4263 			iq->caps_server = 0;
4264 			iq->caps_reply = NULL;
4265 			iq->caps_response = NULL;
4266 			iq->caps_minimisation_state = DONOT_MINIMISE_STATE;
4267 			iq->state = QUERYTARGETS_STATE;
4268 			iq->num_current_queries--;
4269 			/* need fresh attempts for the 0x20 fallback, if
4270 			 * that was the cause for the failure */
4271 			iter_dec_attempts(iq->dp, 3, ie->outbound_msg_retry);
4272 			verbose(VERB_DETAIL, "Capsforid: timeouts, starting fallback");
4273 			goto handle_it;
4274 		}
4275 		goto handle_it;
4276 	}
4277 	if( (event != module_event_reply && event != module_event_capsfail)
4278 		|| !qstate->reply) {
4279 		log_err("Bad event combined with response");
4280 		outbound_list_remove(&iq->outlist, outbound);
4281 		errinf(qstate, "module iterator received wrong internal event with a response message");
4282 		(void)error_response(qstate, id, LDNS_RCODE_SERVFAIL);
4283 		return;
4284 	}
4285 
4286 	/* parse message */
4287 	fill_fail_addr(iq, &qstate->reply->remote_addr,
4288 		qstate->reply->remote_addrlen);
4289 	prs = (struct msg_parse*)regional_alloc(qstate->env->scratch,
4290 		sizeof(struct msg_parse));
4291 	if(!prs) {
4292 		log_err("out of memory on incoming message");
4293 		/* like packet got dropped */
4294 		goto handle_it;
4295 	}
4296 	memset(prs, 0, sizeof(*prs));
4297 	memset(&edns, 0, sizeof(edns));
4298 	pkt = qstate->reply->c->buffer;
4299 	sldns_buffer_set_position(pkt, 0);
4300 	if(parse_packet(pkt, prs, qstate->env->scratch) != LDNS_RCODE_NOERROR) {
4301 		verbose(VERB_ALGO, "parse error on reply packet");
4302 		iq->parse_failures++;
4303 		goto handle_it;
4304 	}
4305 	/* edns is not examined, but removed from message to help cache */
4306 	if(parse_extract_edns_from_response_msg(prs, &edns, qstate->env->scratch) !=
4307 		LDNS_RCODE_NOERROR) {
4308 		iq->parse_failures++;
4309 		goto handle_it;
4310 	}
4311 
4312 	/* Copy the edns options we may got from the back end */
4313 	if(edns.opt_list_in) {
4314 		qstate->edns_opts_back_in = edns_opt_copy_region(edns.opt_list_in,
4315 			qstate->region);
4316 		if(!qstate->edns_opts_back_in) {
4317 			log_err("out of memory on incoming message");
4318 			/* like packet got dropped */
4319 			goto handle_it;
4320 		}
4321 	}
4322 	if(!inplace_cb_edns_back_parsed_call(qstate->env, qstate)) {
4323 		log_err("unable to call edns_back_parsed callback");
4324 		goto handle_it;
4325 	}
4326 
4327 	/* remove CD-bit, we asked for in case we handle validation ourself */
4328 	prs->flags &= ~BIT_CD;
4329 
4330 	/* normalize and sanitize: easy to delete items from linked lists */
4331 	if(!scrub_message(pkt, prs, &iq->qinfo_out, iq->dp->name,
4332 		qstate->env->scratch, qstate->env, qstate, ie)) {
4333 		/* if 0x20 enabled, start fallback, but we have no message */
4334 		if(event == module_event_capsfail && !iq->caps_fallback) {
4335 			iq->caps_fallback = 1;
4336 			iq->caps_server = 0;
4337 			iq->caps_reply = NULL;
4338 			iq->caps_response = NULL;
4339 			iq->caps_minimisation_state = DONOT_MINIMISE_STATE;
4340 			iq->state = QUERYTARGETS_STATE;
4341 			iq->num_current_queries--;
4342 			verbose(VERB_DETAIL, "Capsforid: scrub failed, starting fallback with no response");
4343 		}
4344 		iq->scrub_failures++;
4345 		goto handle_it;
4346 	}
4347 
4348 	/* allocate response dns_msg in region */
4349 	iq->response = dns_alloc_msg(pkt, prs, qstate->region);
4350 	if(!iq->response)
4351 		goto handle_it;
4352 	log_query_info(VERB_DETAIL, "response for", &qstate->qinfo);
4353 	log_name_addr(VERB_DETAIL, "reply from", iq->dp->name,
4354 		&qstate->reply->remote_addr, qstate->reply->remote_addrlen);
4355 	if(verbosity >= VERB_ALGO)
4356 		log_dns_msg("incoming scrubbed packet:", &iq->response->qinfo,
4357 			iq->response->rep);
4358 
4359 	if(event == module_event_capsfail || iq->caps_fallback) {
4360 		if(qstate->env->cfg->qname_minimisation &&
4361 			iq->minimisation_state != DONOT_MINIMISE_STATE) {
4362 			/* Skip QNAME minimisation for next query, since that
4363 			 * one has to match the current query. */
4364 			iq->minimisation_state = SKIP_MINIMISE_STATE;
4365 		}
4366 		/* for fallback we care about main answer, not additionals */
4367 		/* removing that makes comparison more likely to succeed */
4368 		caps_strip_reply(iq->response->rep);
4369 
4370 		if(iq->caps_fallback &&
4371 			iq->caps_minimisation_state != iq->minimisation_state) {
4372 			/* QNAME minimisation state has changed, restart caps
4373 			 * fallback. */
4374 			iq->caps_fallback = 0;
4375 		}
4376 
4377 		if(!iq->caps_fallback) {
4378 			/* start fallback */
4379 			iq->caps_fallback = 1;
4380 			iq->caps_server = 0;
4381 			iq->caps_reply = iq->response->rep;
4382 			iq->caps_response = iq->response;
4383 			iq->caps_minimisation_state = iq->minimisation_state;
4384 			iq->state = QUERYTARGETS_STATE;
4385 			iq->num_current_queries--;
4386 			verbose(VERB_DETAIL, "Capsforid: starting fallback");
4387 			goto handle_it;
4388 		} else {
4389 			/* check if reply is the same, otherwise, fail */
4390 			if(!iq->caps_reply) {
4391 				iq->caps_reply = iq->response->rep;
4392 				iq->caps_response = iq->response;
4393 				iq->caps_server = -1; /*become zero at ++,
4394 				so that we start the full set of trials */
4395 			} else if(caps_failed_rcode(iq->caps_reply) &&
4396 				!caps_failed_rcode(iq->response->rep)) {
4397 				/* prefer to upgrade to non-SERVFAIL */
4398 				iq->caps_reply = iq->response->rep;
4399 				iq->caps_response = iq->response;
4400 			} else if(!caps_failed_rcode(iq->caps_reply) &&
4401 				caps_failed_rcode(iq->response->rep)) {
4402 				/* if we have non-SERVFAIL as answer then
4403 				 * we can ignore SERVFAILs for the equality
4404 				 * comparison */
4405 				/* no instructions here, skip other else */
4406 			} else if(caps_failed_rcode(iq->caps_reply) &&
4407 				caps_failed_rcode(iq->response->rep)) {
4408 				/* failure is same as other failure in fallbk*/
4409 				/* no instructions here, skip other else */
4410 			} else if(!reply_equal(iq->response->rep, iq->caps_reply,
4411 				qstate->env->scratch)) {
4412 				verbose(VERB_DETAIL, "Capsforid fallback: "
4413 					"getting different replies, failed");
4414 				outbound_list_remove(&iq->outlist, outbound);
4415 				errinf(qstate, "0x20 failed, then got different replies in fallback");
4416 				(void)error_response_cache(qstate, id,
4417 					LDNS_RCODE_SERVFAIL);
4418 				return;
4419 			}
4420 			/* continue the fallback procedure at next server */
4421 			iq->caps_server++;
4422 			iq->state = QUERYTARGETS_STATE;
4423 			iq->num_current_queries--;
4424 			verbose(VERB_DETAIL, "Capsforid: reply is equal. "
4425 				"go to next fallback");
4426 			goto handle_it;
4427 		}
4428 	}
4429 	iq->caps_fallback = 0; /* if we were in fallback, 0x20 is OK now */
4430 
4431 handle_it:
4432 	outbound_list_remove(&iq->outlist, outbound);
4433 	iter_handle(qstate, iq, ie, id);
4434 }
4435 
4436 void
4437 iter_operate(struct module_qstate* qstate, enum module_ev event, int id,
4438 	struct outbound_entry* outbound)
4439 {
4440 	struct iter_env* ie = (struct iter_env*)qstate->env->modinfo[id];
4441 	struct iter_qstate* iq = (struct iter_qstate*)qstate->minfo[id];
4442 	verbose(VERB_QUERY, "iterator[module %d] operate: extstate:%s event:%s",
4443 		id, strextstate(qstate->ext_state[id]), strmodulevent(event));
4444 	if(iq) log_query_info(VERB_QUERY, "iterator operate: query",
4445 		&qstate->qinfo);
4446 	if(iq && qstate->qinfo.qname != iq->qchase.qname)
4447 		log_query_info(VERB_QUERY, "iterator operate: chased to",
4448 			&iq->qchase);
4449 
4450 	/* perform iterator state machine */
4451 	if((event == module_event_new || event == module_event_pass) &&
4452 		iq == NULL) {
4453 		if(!iter_new(qstate, id)) {
4454 			errinf(qstate, "malloc failure, new iterator module allocation");
4455 			(void)error_response(qstate, id, LDNS_RCODE_SERVFAIL);
4456 			return;
4457 		}
4458 		iq = (struct iter_qstate*)qstate->minfo[id];
4459 		process_request(qstate, iq, ie, id);
4460 		return;
4461 	}
4462 	if(iq && event == module_event_pass) {
4463 		iter_handle(qstate, iq, ie, id);
4464 		return;
4465 	}
4466 	if(iq && outbound) {
4467 		process_response(qstate, iq, ie, id, outbound, event);
4468 		return;
4469 	}
4470 	if(event == module_event_error) {
4471 		verbose(VERB_ALGO, "got called with event error, giving up");
4472 		errinf(qstate, "iterator module got the error event");
4473 		(void)error_response(qstate, id, LDNS_RCODE_SERVFAIL);
4474 		return;
4475 	}
4476 
4477 	log_err("bad event for iterator");
4478 	errinf(qstate, "iterator module received wrong event");
4479 	(void)error_response(qstate, id, LDNS_RCODE_SERVFAIL);
4480 }
4481 
4482 void
4483 iter_clear(struct module_qstate* qstate, int id)
4484 {
4485 	struct iter_qstate* iq;
4486 	if(!qstate)
4487 		return;
4488 	iq = (struct iter_qstate*)qstate->minfo[id];
4489 	if(iq) {
4490 		outbound_list_clear(&iq->outlist);
4491 		if(iq->target_count && --iq->target_count[TARGET_COUNT_REF] == 0) {
4492 			free(iq->target_count);
4493 			if(*iq->nxns_dp) free(*iq->nxns_dp);
4494 			free(iq->nxns_dp);
4495 		}
4496 		iq->num_current_queries = 0;
4497 	}
4498 	qstate->minfo[id] = NULL;
4499 }
4500 
4501 size_t
4502 iter_get_mem(struct module_env* env, int id)
4503 {
4504 	struct iter_env* ie = (struct iter_env*)env->modinfo[id];
4505 	if(!ie)
4506 		return 0;
4507 	return sizeof(*ie) + sizeof(int)*((size_t)ie->max_dependency_depth+1)
4508 		+ donotq_get_mem(ie->donotq) + priv_get_mem(ie->priv);
4509 }
4510 
4511 /**
4512  * The iterator function block
4513  */
4514 static struct module_func_block iter_block = {
4515 	"iterator",
4516 	NULL, NULL, &iter_init, &iter_deinit, &iter_operate,
4517 	&iter_inform_super, &iter_clear, &iter_get_mem
4518 };
4519 
4520 struct module_func_block*
4521 iter_get_funcblock(void)
4522 {
4523 	return &iter_block;
4524 }
4525 
4526 const char*
4527 iter_state_to_string(enum iter_state state)
4528 {
4529 	switch (state)
4530 	{
4531 	case INIT_REQUEST_STATE :
4532 		return "INIT REQUEST STATE";
4533 	case INIT_REQUEST_2_STATE :
4534 		return "INIT REQUEST STATE (stage 2)";
4535 	case INIT_REQUEST_3_STATE:
4536 		return "INIT REQUEST STATE (stage 3)";
4537 	case QUERYTARGETS_STATE :
4538 		return "QUERY TARGETS STATE";
4539 	case PRIME_RESP_STATE :
4540 		return "PRIME RESPONSE STATE";
4541 	case COLLECT_CLASS_STATE :
4542 		return "COLLECT CLASS STATE";
4543 	case DSNS_FIND_STATE :
4544 		return "DSNS FIND STATE";
4545 	case QUERY_RESP_STATE :
4546 		return "QUERY RESPONSE STATE";
4547 	case FINISHED_STATE :
4548 		return "FINISHED RESPONSE STATE";
4549 	default :
4550 		return "UNKNOWN ITER STATE";
4551 	}
4552 }
4553 
4554 int
4555 iter_state_is_responsestate(enum iter_state s)
4556 {
4557 	switch(s) {
4558 		case INIT_REQUEST_STATE :
4559 		case INIT_REQUEST_2_STATE :
4560 		case INIT_REQUEST_3_STATE :
4561 		case QUERYTARGETS_STATE :
4562 		case COLLECT_CLASS_STATE :
4563 			return 0;
4564 		default:
4565 			break;
4566 	}
4567 	return 1;
4568 }
4569