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