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