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