xref: /freebsd/contrib/unbound/iterator/iterator.c (revision 13ec1e3155c7e9bf037b12af186351b7fa9b9450)
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)) {
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 	if(iq->depth == ie->max_dependency_depth)
1835 		return 0;
1836 	if(iq->depth > 0 && iq->target_count &&
1837 		iq->target_count[1] > MAX_TARGET_COUNT) {
1838 		char s[LDNS_MAX_DOMAINLEN+1];
1839 		dname_str(qstate->qinfo.qname, s);
1840 		verbose(VERB_QUERY, "request %s has exceeded the maximum "
1841 			"number of glue fetches %d", s, iq->target_count[1]);
1842 		return 0;
1843 	}
1844 	if(iq->dp_target_count > MAX_DP_TARGET_COUNT) {
1845 		char s[LDNS_MAX_DOMAINLEN+1];
1846 		dname_str(qstate->qinfo.qname, s);
1847 		verbose(VERB_QUERY, "request %s has exceeded the maximum "
1848 			"number of glue fetches %d to a single delegation point",
1849 			s, iq->dp_target_count);
1850 		return 0;
1851 	}
1852 
1853 	iter_mark_cycle_targets(qstate, iq->dp);
1854 	missing = (int)delegpt_count_missing_targets(iq->dp);
1855 	log_assert(maxtargets != 0); /* that would not be useful */
1856 
1857 	/* Generate target requests. Basically, any missing targets
1858 	 * are queried for here, regardless if it is necessary to do
1859 	 * so to continue processing. */
1860 	if(maxtargets < 0 || maxtargets > missing)
1861 		toget = missing;
1862 	else	toget = maxtargets;
1863 	if(toget == 0) {
1864 		*num = 0;
1865 		return 1;
1866 	}
1867 	/* select 'toget' items from the total of 'missing' items */
1868 	log_assert(toget <= missing);
1869 
1870 	/* loop over missing targets */
1871 	for(ns = iq->dp->nslist; ns; ns = ns->next) {
1872 		if(ns->resolved)
1873 			continue;
1874 
1875 		/* randomly select this item with probability toget/missing */
1876 		if(!iter_ns_probability(qstate->env->rnd, toget, missing)) {
1877 			/* do not select this one, next; select toget number
1878 			 * of items from a list one less in size */
1879 			missing --;
1880 			continue;
1881 		}
1882 
1883 		if(ie->supports_ipv6 && !ns->got6) {
1884 			/* Send the AAAA request. */
1885 			if(!generate_target_query(qstate, iq, id,
1886 				ns->name, ns->namelen,
1887 				LDNS_RR_TYPE_AAAA, iq->qchase.qclass)) {
1888 				*num = query_count;
1889 				if(query_count > 0)
1890 					qstate->ext_state[id] = module_wait_subquery;
1891 				return 0;
1892 			}
1893 			query_count++;
1894 		}
1895 		/* Send the A request. */
1896 		if(ie->supports_ipv4 && !ns->got4) {
1897 			if(!generate_target_query(qstate, iq, id,
1898 				ns->name, ns->namelen,
1899 				LDNS_RR_TYPE_A, iq->qchase.qclass)) {
1900 				*num = query_count;
1901 				if(query_count > 0)
1902 					qstate->ext_state[id] = module_wait_subquery;
1903 				return 0;
1904 			}
1905 			query_count++;
1906 		}
1907 
1908 		/* mark this target as in progress. */
1909 		ns->resolved = 1;
1910 		missing--;
1911 		toget--;
1912 		if(toget == 0)
1913 			break;
1914 	}
1915 	*num = query_count;
1916 	if(query_count > 0)
1917 		qstate->ext_state[id] = module_wait_subquery;
1918 
1919 	return 1;
1920 }
1921 
1922 /**
1923  * Called by processQueryTargets when it would like extra targets to query
1924  * but it seems to be out of options.  At last resort some less appealing
1925  * options are explored.  If there are no more options, the result is SERVFAIL
1926  *
1927  * @param qstate: query state.
1928  * @param iq: iterator query state.
1929  * @param ie: iterator shared global environment.
1930  * @param id: module id.
1931  * @return true if the event requires more request processing immediately,
1932  *         false if not.
1933  */
1934 static int
1935 processLastResort(struct module_qstate* qstate, struct iter_qstate* iq,
1936 	struct iter_env* ie, int id)
1937 {
1938 	struct delegpt_ns* ns;
1939 	int query_count = 0;
1940 	verbose(VERB_ALGO, "No more query targets, attempting last resort");
1941 	log_assert(iq->dp);
1942 
1943 	if(!can_have_last_resort(qstate->env, iq->dp->name, iq->dp->namelen,
1944 		iq->qchase.qclass, NULL)) {
1945 		/* fail -- no more targets, no more hope of targets, no hope
1946 		 * of a response. */
1947 		errinf(qstate, "all the configured stub or forward servers failed,");
1948 		errinf_dname(qstate, "at zone", iq->dp->name);
1949 		errinf_reply(qstate, iq);
1950 		verbose(VERB_QUERY, "configured stub or forward servers failed -- returning SERVFAIL");
1951 		return error_response_cache(qstate, id, LDNS_RCODE_SERVFAIL);
1952 	}
1953 	if(!iq->dp->has_parent_side_NS && dname_is_root(iq->dp->name)) {
1954 		struct delegpt* p = hints_lookup_root(qstate->env->hints,
1955 			iq->qchase.qclass);
1956 		if(p) {
1957 			struct delegpt_addr* a;
1958 			iq->chase_flags &= ~BIT_RD; /* go to authorities */
1959 			for(ns = p->nslist; ns; ns=ns->next) {
1960 				(void)delegpt_add_ns(iq->dp, qstate->region,
1961 					ns->name, ns->lame, ns->tls_auth_name,
1962 					ns->port);
1963 			}
1964 			for(a = p->target_list; a; a=a->next_target) {
1965 				(void)delegpt_add_addr(iq->dp, qstate->region,
1966 					&a->addr, a->addrlen, a->bogus,
1967 					a->lame, a->tls_auth_name, -1, NULL);
1968 			}
1969 		}
1970 		iq->dp->has_parent_side_NS = 1;
1971 	} else if(!iq->dp->has_parent_side_NS) {
1972 		if(!iter_lookup_parent_NS_from_cache(qstate->env, iq->dp,
1973 			qstate->region, &qstate->qinfo)
1974 			|| !iq->dp->has_parent_side_NS) {
1975 			/* if: malloc failure in lookup go up to try */
1976 			/* if: no parent NS in cache - go up one level */
1977 			verbose(VERB_ALGO, "try to grab parent NS");
1978 			iq->store_parent_NS = iq->dp;
1979 			iq->chase_flags &= ~BIT_RD; /* go to authorities */
1980 			iq->deleg_msg = NULL;
1981 			iq->refetch_glue = 1;
1982 			iq->query_restart_count++;
1983 			iq->sent_count = 0;
1984 			iq->dp_target_count = 0;
1985 			if(qstate->env->cfg->qname_minimisation)
1986 				iq->minimisation_state = INIT_MINIMISE_STATE;
1987 			return next_state(iq, INIT_REQUEST_STATE);
1988 		}
1989 	}
1990 	/* see if that makes new names available */
1991 	if(!cache_fill_missing(qstate->env, iq->qchase.qclass,
1992 		qstate->region, iq->dp))
1993 		log_err("out of memory in cache_fill_missing");
1994 	if(iq->dp->usable_list) {
1995 		verbose(VERB_ALGO, "try parent-side-name, w. glue from cache");
1996 		return next_state(iq, QUERYTARGETS_STATE);
1997 	}
1998 	/* try to fill out parent glue from cache */
1999 	if(iter_lookup_parent_glue_from_cache(qstate->env, iq->dp,
2000 		qstate->region, &qstate->qinfo)) {
2001 		/* got parent stuff from cache, see if we can continue */
2002 		verbose(VERB_ALGO, "try parent-side glue from cache");
2003 		return next_state(iq, QUERYTARGETS_STATE);
2004 	}
2005 	/* query for an extra name added by the parent-NS record */
2006 	if(delegpt_count_missing_targets(iq->dp) > 0) {
2007 		int qs = 0;
2008 		verbose(VERB_ALGO, "try parent-side target name");
2009 		if(!query_for_targets(qstate, iq, ie, id, 1, &qs)) {
2010 			errinf(qstate, "could not fetch nameserver");
2011 			errinf_dname(qstate, "at zone", iq->dp->name);
2012 			return error_response(qstate, id, LDNS_RCODE_SERVFAIL);
2013 		}
2014 		iq->num_target_queries += qs;
2015 		target_count_increase(iq, qs);
2016 		if(qs != 0) {
2017 			qstate->ext_state[id] = module_wait_subquery;
2018 			return 0; /* and wait for them */
2019 		}
2020 	}
2021 	if(iq->depth == ie->max_dependency_depth) {
2022 		verbose(VERB_QUERY, "maxdepth and need more nameservers, fail");
2023 		errinf(qstate, "cannot fetch more nameservers because at max dependency depth");
2024 		return error_response_cache(qstate, id, LDNS_RCODE_SERVFAIL);
2025 	}
2026 	if(iq->depth > 0 && iq->target_count &&
2027 		iq->target_count[1] > MAX_TARGET_COUNT) {
2028 		char s[LDNS_MAX_DOMAINLEN+1];
2029 		dname_str(qstate->qinfo.qname, s);
2030 		verbose(VERB_QUERY, "request %s has exceeded the maximum "
2031 			"number of glue fetches %d", s, iq->target_count[1]);
2032 		errinf(qstate, "exceeded the maximum number of glue fetches");
2033 		return error_response_cache(qstate, id, LDNS_RCODE_SERVFAIL);
2034 	}
2035 	/* mark cycle targets for parent-side lookups */
2036 	iter_mark_pside_cycle_targets(qstate, iq->dp);
2037 	/* see if we can issue queries to get nameserver addresses */
2038 	/* this lookup is not randomized, but sequential. */
2039 	for(ns = iq->dp->nslist; ns; ns = ns->next) {
2040 		/* if this nameserver is at a delegation point, but that
2041 		 * delegation point is a stub and we cannot go higher, skip*/
2042 		if( ((ie->supports_ipv6 && !ns->done_pside6) ||
2043 		    (ie->supports_ipv4 && !ns->done_pside4)) &&
2044 		    !can_have_last_resort(qstate->env, ns->name, ns->namelen,
2045 			iq->qchase.qclass, NULL)) {
2046 			log_nametypeclass(VERB_ALGO, "cannot pside lookup ns "
2047 				"because it is also a stub/forward,",
2048 				ns->name, LDNS_RR_TYPE_NS, iq->qchase.qclass);
2049 			if(ie->supports_ipv6) ns->done_pside6 = 1;
2050 			if(ie->supports_ipv4) ns->done_pside4 = 1;
2051 			continue;
2052 		}
2053 		/* query for parent-side A and AAAA for nameservers */
2054 		if(ie->supports_ipv6 && !ns->done_pside6) {
2055 			/* Send the AAAA request. */
2056 			if(!generate_parentside_target_query(qstate, iq, id,
2057 				ns->name, ns->namelen,
2058 				LDNS_RR_TYPE_AAAA, iq->qchase.qclass)) {
2059 				errinf_dname(qstate, "could not generate nameserver AAAA lookup for", ns->name);
2060 				return error_response(qstate, id,
2061 					LDNS_RCODE_SERVFAIL);
2062 			}
2063 			ns->done_pside6 = 1;
2064 			query_count++;
2065 		}
2066 		if(ie->supports_ipv4 && !ns->done_pside4) {
2067 			/* Send the A request. */
2068 			if(!generate_parentside_target_query(qstate, iq, id,
2069 				ns->name, ns->namelen,
2070 				LDNS_RR_TYPE_A, iq->qchase.qclass)) {
2071 				errinf_dname(qstate, "could not generate nameserver A lookup for", ns->name);
2072 				return error_response(qstate, id,
2073 					LDNS_RCODE_SERVFAIL);
2074 			}
2075 			ns->done_pside4 = 1;
2076 			query_count++;
2077 		}
2078 		if(query_count != 0) { /* suspend to await results */
2079 			verbose(VERB_ALGO, "try parent-side glue lookup");
2080 			iq->num_target_queries += query_count;
2081 			target_count_increase(iq, query_count);
2082 			qstate->ext_state[id] = module_wait_subquery;
2083 			return 0;
2084 		}
2085 	}
2086 
2087 	/* if this was a parent-side glue query itself, then store that
2088 	 * failure in cache. */
2089 	if(!qstate->no_cache_store && iq->query_for_pside_glue
2090 		&& !iq->pside_glue)
2091 			iter_store_parentside_neg(qstate->env, &qstate->qinfo,
2092 				iq->deleg_msg?iq->deleg_msg->rep:
2093 				(iq->response?iq->response->rep:NULL));
2094 
2095 	errinf(qstate, "all servers for this domain failed,");
2096 	errinf_dname(qstate, "at zone", iq->dp->name);
2097 	errinf_reply(qstate, iq);
2098 	verbose(VERB_QUERY, "out of query targets -- returning SERVFAIL");
2099 	/* fail -- no more targets, no more hope of targets, no hope
2100 	 * of a response. */
2101 	return error_response_cache(qstate, id, LDNS_RCODE_SERVFAIL);
2102 }
2103 
2104 /**
2105  * Try to find the NS record set that will resolve a qtype DS query. Due
2106  * to grandparent/grandchild reasons we did not get a proper lookup right
2107  * away.  We need to create type NS queries until we get the right parent
2108  * for this lookup.  We remove labels from the query to find the right point.
2109  * If we end up at the old dp name, then there is no solution.
2110  *
2111  * @param qstate: query state.
2112  * @param iq: iterator query state.
2113  * @param id: module id.
2114  * @return true if the event requires more immediate processing, false if
2115  *         not. This is generally only true when forwarding the request to
2116  *         the final state (i.e., on answer).
2117  */
2118 static int
2119 processDSNSFind(struct module_qstate* qstate, struct iter_qstate* iq, int id)
2120 {
2121 	struct module_qstate* subq = NULL;
2122 	verbose(VERB_ALGO, "processDSNSFind");
2123 
2124 	if(!iq->dsns_point) {
2125 		/* initialize */
2126 		iq->dsns_point = iq->qchase.qname;
2127 		iq->dsns_point_len = iq->qchase.qname_len;
2128 	}
2129 	/* robustcheck for internal error: we are not underneath the dp */
2130 	if(!dname_subdomain_c(iq->dsns_point, iq->dp->name)) {
2131 		errinf_dname(qstate, "for DS query parent-child nameserver search the query is not under the zone", iq->dp->name);
2132 		return error_response_cache(qstate, id, LDNS_RCODE_SERVFAIL);
2133 	}
2134 
2135 	/* go up one (more) step, until we hit the dp, if so, end */
2136 	dname_remove_label(&iq->dsns_point, &iq->dsns_point_len);
2137 	if(query_dname_compare(iq->dsns_point, iq->dp->name) == 0) {
2138 		/* there was no inbetween nameserver, use the old delegation
2139 		 * point again.  And this time, because dsns_point is nonNULL
2140 		 * we are going to accept the (bad) result */
2141 		iq->state = QUERYTARGETS_STATE;
2142 		return 1;
2143 	}
2144 	iq->state = DSNS_FIND_STATE;
2145 
2146 	/* spawn NS lookup (validation not needed, this is for DS lookup) */
2147 	log_nametypeclass(VERB_ALGO, "fetch nameservers",
2148 		iq->dsns_point, LDNS_RR_TYPE_NS, iq->qchase.qclass);
2149 	if(!generate_sub_request(iq->dsns_point, iq->dsns_point_len,
2150 		LDNS_RR_TYPE_NS, iq->qchase.qclass, qstate, id, iq,
2151 		INIT_REQUEST_STATE, FINISHED_STATE, &subq, 0, 0)) {
2152 		errinf_dname(qstate, "for DS query parent-child nameserver search, could not generate NS lookup for", iq->dsns_point);
2153 		return error_response_cache(qstate, id, LDNS_RCODE_SERVFAIL);
2154 	}
2155 
2156 	return 0;
2157 }
2158 
2159 /**
2160  * This is the request event state where the request will be sent to one of
2161  * its current query targets. This state also handles issuing target lookup
2162  * queries for missing target IP addresses. Queries typically iterate on
2163  * this state, both when they are just trying different targets for a given
2164  * delegation point, and when they change delegation points. This state
2165  * roughly corresponds to RFC 1034 algorithm steps 3 and 4.
2166  *
2167  * @param qstate: query state.
2168  * @param iq: iterator query state.
2169  * @param ie: iterator shared global environment.
2170  * @param id: module id.
2171  * @return true if the event requires more request processing immediately,
2172  *         false if not. This state only returns true when it is generating
2173  *         a SERVFAIL response because the query has hit a dead end.
2174  */
2175 static int
2176 processQueryTargets(struct module_qstate* qstate, struct iter_qstate* iq,
2177 	struct iter_env* ie, int id)
2178 {
2179 	int tf_policy;
2180 	struct delegpt_addr* target;
2181 	struct outbound_entry* outq;
2182 	int auth_fallback = 0;
2183 	uint8_t* qout_orig = NULL;
2184 	size_t qout_orig_len = 0;
2185 	int sq_check_ratelimit = 1;
2186 	int sq_was_ratelimited = 0;
2187 
2188 	/* NOTE: a request will encounter this state for each target it
2189 	 * needs to send a query to. That is, at least one per referral,
2190 	 * more if some targets timeout or return throwaway answers. */
2191 
2192 	log_query_info(VERB_QUERY, "processQueryTargets:", &qstate->qinfo);
2193 	verbose(VERB_ALGO, "processQueryTargets: targetqueries %d, "
2194 		"currentqueries %d sentcount %d", iq->num_target_queries,
2195 		iq->num_current_queries, iq->sent_count);
2196 
2197 	/* Make sure that we haven't run away */
2198 	/* FIXME: is this check even necessary? */
2199 	if(iq->referral_count > MAX_REFERRAL_COUNT) {
2200 		verbose(VERB_QUERY, "request has exceeded the maximum "
2201 			"number of referrrals with %d", iq->referral_count);
2202 		errinf(qstate, "exceeded the maximum of referrals");
2203 		return error_response(qstate, id, LDNS_RCODE_SERVFAIL);
2204 	}
2205 	if(iq->sent_count > MAX_SENT_COUNT) {
2206 		verbose(VERB_QUERY, "request has exceeded the maximum "
2207 			"number of sends with %d", iq->sent_count);
2208 		errinf(qstate, "exceeded the maximum number of sends");
2209 		return error_response(qstate, id, LDNS_RCODE_SERVFAIL);
2210 	}
2211 	if(iq->target_count && iq->target_count[2] > MAX_TARGET_NX) {
2212 		verbose(VERB_QUERY, "request has exceeded the maximum "
2213 			" number of nxdomain nameserver lookups with %d",
2214 			iq->target_count[2]);
2215 		errinf(qstate, "exceeded the maximum nameserver nxdomains");
2216 		return error_response(qstate, id, LDNS_RCODE_SERVFAIL);
2217 	}
2218 
2219 	/* Make sure we have a delegation point, otherwise priming failed
2220 	 * or another failure occurred */
2221 	if(!iq->dp) {
2222 		verbose(VERB_QUERY, "Failed to get a delegation, giving up");
2223 		errinf(qstate, "failed to get a delegation (eg. prime failure)");
2224 		return error_response(qstate, id, LDNS_RCODE_SERVFAIL);
2225 	}
2226 	if(!ie->supports_ipv6)
2227 		delegpt_no_ipv6(iq->dp);
2228 	if(!ie->supports_ipv4)
2229 		delegpt_no_ipv4(iq->dp);
2230 	delegpt_log(VERB_ALGO, iq->dp);
2231 
2232 	if(iq->num_current_queries>0) {
2233 		/* already busy answering a query, this restart is because
2234 		 * more delegpt addrs became available, wait for existing
2235 		 * query. */
2236 		verbose(VERB_ALGO, "woke up, but wait for outstanding query");
2237 		qstate->ext_state[id] = module_wait_reply;
2238 		return 0;
2239 	}
2240 
2241 	if(iq->minimisation_state == INIT_MINIMISE_STATE
2242 		&& !(iq->chase_flags & BIT_RD)) {
2243 		/* (Re)set qinfo_out to (new) delegation point, except when
2244 		 * qinfo_out is already a subdomain of dp. This happens when
2245 		 * increasing by more than one label at once (QNAMEs with more
2246 		 * than MAX_MINIMISE_COUNT labels). */
2247 		if(!(iq->qinfo_out.qname_len
2248 			&& dname_subdomain_c(iq->qchase.qname,
2249 				iq->qinfo_out.qname)
2250 			&& dname_subdomain_c(iq->qinfo_out.qname,
2251 				iq->dp->name))) {
2252 			iq->qinfo_out.qname = iq->dp->name;
2253 			iq->qinfo_out.qname_len = iq->dp->namelen;
2254 			iq->qinfo_out.qtype = LDNS_RR_TYPE_A;
2255 			iq->qinfo_out.qclass = iq->qchase.qclass;
2256 			iq->qinfo_out.local_alias = NULL;
2257 			iq->minimise_count = 0;
2258 		}
2259 
2260 		iq->minimisation_state = MINIMISE_STATE;
2261 	}
2262 	if(iq->minimisation_state == MINIMISE_STATE) {
2263 		int qchaselabs = dname_count_labels(iq->qchase.qname);
2264 		int labdiff = qchaselabs -
2265 			dname_count_labels(iq->qinfo_out.qname);
2266 
2267 		qout_orig = iq->qinfo_out.qname;
2268 		qout_orig_len = iq->qinfo_out.qname_len;
2269 		iq->qinfo_out.qname = iq->qchase.qname;
2270 		iq->qinfo_out.qname_len = iq->qchase.qname_len;
2271 		iq->minimise_count++;
2272 		iq->timeout_count = 0;
2273 
2274 		iter_dec_attempts(iq->dp, 1, ie->outbound_msg_retry);
2275 
2276 		/* Limit number of iterations for QNAMEs with more
2277 		 * than MAX_MINIMISE_COUNT labels. Send first MINIMISE_ONE_LAB
2278 		 * labels of QNAME always individually.
2279 		 */
2280 		if(qchaselabs > MAX_MINIMISE_COUNT && labdiff > 1 &&
2281 			iq->minimise_count > MINIMISE_ONE_LAB) {
2282 			if(iq->minimise_count < MAX_MINIMISE_COUNT) {
2283 				int multilabs = qchaselabs - 1 -
2284 					MINIMISE_ONE_LAB;
2285 				int extralabs = multilabs /
2286 					MINIMISE_MULTIPLE_LABS;
2287 
2288 				if (MAX_MINIMISE_COUNT - iq->minimise_count >=
2289 					multilabs % MINIMISE_MULTIPLE_LABS)
2290 					/* Default behaviour is to add 1 label
2291 					 * every iteration. Therefore, decrement
2292 					 * the extralabs by 1 */
2293 					extralabs--;
2294 				if (extralabs < labdiff)
2295 					labdiff -= extralabs;
2296 				else
2297 					labdiff = 1;
2298 			}
2299 			/* Last minimised iteration, send all labels with
2300 			 * QTYPE=NS */
2301 			else
2302 				labdiff = 1;
2303 		}
2304 
2305 		if(labdiff > 1) {
2306 			verbose(VERB_QUERY, "removing %d labels", labdiff-1);
2307 			dname_remove_labels(&iq->qinfo_out.qname,
2308 				&iq->qinfo_out.qname_len,
2309 				labdiff-1);
2310 		}
2311 		if(labdiff < 1 || (labdiff < 2
2312 			&& (iq->qchase.qtype == LDNS_RR_TYPE_DS
2313 			|| iq->qchase.qtype == LDNS_RR_TYPE_A)))
2314 			/* Stop minimising this query, resolve "as usual" */
2315 			iq->minimisation_state = DONOT_MINIMISE_STATE;
2316 		else if(!qstate->no_cache_lookup) {
2317 			struct dns_msg* msg = dns_cache_lookup(qstate->env,
2318 				iq->qinfo_out.qname, iq->qinfo_out.qname_len,
2319 				iq->qinfo_out.qtype, iq->qinfo_out.qclass,
2320 				qstate->query_flags, qstate->region,
2321 				qstate->env->scratch, 0, iq->dp->name,
2322 				iq->dp->namelen);
2323 			if(msg && FLAGS_GET_RCODE(msg->rep->flags) ==
2324 				LDNS_RCODE_NOERROR)
2325 				/* no need to send query if it is already
2326 				 * cached as NOERROR */
2327 				return 1;
2328 			if(msg && FLAGS_GET_RCODE(msg->rep->flags) ==
2329 				LDNS_RCODE_NXDOMAIN &&
2330 				qstate->env->need_to_validate &&
2331 				qstate->env->cfg->harden_below_nxdomain) {
2332 				if(msg->rep->security == sec_status_secure) {
2333 					iq->response = msg;
2334 					return final_state(iq);
2335 				}
2336 				if(msg->rep->security == sec_status_unchecked) {
2337 					struct module_qstate* subq = NULL;
2338 					if(!generate_sub_request(
2339 						iq->qinfo_out.qname,
2340 						iq->qinfo_out.qname_len,
2341 						iq->qinfo_out.qtype,
2342 						iq->qinfo_out.qclass,
2343 						qstate, id, iq,
2344 						INIT_REQUEST_STATE,
2345 						FINISHED_STATE, &subq, 1, 1))
2346 						verbose(VERB_ALGO,
2347 						"could not validate NXDOMAIN "
2348 						"response");
2349 				}
2350 			}
2351 			if(msg && FLAGS_GET_RCODE(msg->rep->flags) ==
2352 				LDNS_RCODE_NXDOMAIN) {
2353 				/* return and add a label in the next
2354 				 * minimisation iteration.
2355 				 */
2356 				return 1;
2357 			}
2358 		}
2359 	}
2360 	if(iq->minimisation_state == SKIP_MINIMISE_STATE) {
2361 		if(iq->timeout_count < MAX_MINIMISE_TIMEOUT_COUNT)
2362 			/* Do not increment qname, continue incrementing next
2363 			 * iteration */
2364 			iq->minimisation_state = MINIMISE_STATE;
2365 		else if(!qstate->env->cfg->qname_minimisation_strict)
2366 			/* Too many time-outs detected for this QNAME and QTYPE.
2367 			 * We give up, disable QNAME minimisation. */
2368 			iq->minimisation_state = DONOT_MINIMISE_STATE;
2369 	}
2370 	if(iq->minimisation_state == DONOT_MINIMISE_STATE)
2371 		iq->qinfo_out = iq->qchase;
2372 
2373 	/* now find an answer to this query */
2374 	/* see if authority zones have an answer */
2375 	/* now we know the dp, we can check the auth zone for locally hosted
2376 	 * contents */
2377 	if(!iq->auth_zone_avoid && qstate->blacklist) {
2378 		if(auth_zones_can_fallback(qstate->env->auth_zones,
2379 			iq->dp->name, iq->dp->namelen, iq->qinfo_out.qclass)) {
2380 			/* if cache is blacklisted and this zone allows us
2381 			 * to fallback to the internet, then do so, and
2382 			 * fetch results from the internet servers */
2383 			iq->auth_zone_avoid = 1;
2384 		}
2385 	}
2386 	if(iq->auth_zone_avoid) {
2387 		iq->auth_zone_avoid = 0;
2388 		auth_fallback = 1;
2389 	} else if(auth_zones_lookup(qstate->env->auth_zones, &iq->qinfo_out,
2390 		qstate->region, &iq->response, &auth_fallback, iq->dp->name,
2391 		iq->dp->namelen)) {
2392 		/* use this as a response to be processed by the iterator */
2393 		if(verbosity >= VERB_ALGO) {
2394 			log_dns_msg("msg from auth zone",
2395 				&iq->response->qinfo, iq->response->rep);
2396 		}
2397 		if((iq->chase_flags&BIT_RD) && !(iq->response->rep->flags&BIT_AA)) {
2398 			verbose(VERB_ALGO, "forwarder, ignoring referral from auth zone");
2399 		} else {
2400 			lock_rw_wrlock(&qstate->env->auth_zones->lock);
2401 			qstate->env->auth_zones->num_query_up++;
2402 			lock_rw_unlock(&qstate->env->auth_zones->lock);
2403 			iq->num_current_queries++;
2404 			iq->chase_to_rd = 0;
2405 			iq->dnssec_lame_query = 0;
2406 			iq->auth_zone_response = 1;
2407 			return next_state(iq, QUERY_RESP_STATE);
2408 		}
2409 	}
2410 	iq->auth_zone_response = 0;
2411 	if(auth_fallback == 0) {
2412 		/* like we got servfail from the auth zone lookup, and
2413 		 * no internet fallback */
2414 		verbose(VERB_ALGO, "auth zone lookup failed, no fallback,"
2415 			" servfail");
2416 		errinf(qstate, "auth zone lookup failed, fallback is off");
2417 		return error_response(qstate, id, LDNS_RCODE_SERVFAIL);
2418 	}
2419 	if(iq->dp->auth_dp) {
2420 		/* we wanted to fallback, but had no delegpt, only the
2421 		 * auth zone generated delegpt, create an actual one */
2422 		iq->auth_zone_avoid = 1;
2423 		return next_state(iq, INIT_REQUEST_STATE);
2424 	}
2425 	/* but mostly, fallback==1 (like, when no such auth zone exists)
2426 	 * and we continue with lookups */
2427 
2428 	tf_policy = 0;
2429 	/* < not <=, because although the array is large enough for <=, the
2430 	 * generated query will immediately be discarded due to depth and
2431 	 * that servfail is cached, which is not good as opportunism goes. */
2432 	if(iq->depth < ie->max_dependency_depth
2433 		&& iq->num_target_queries == 0
2434 		&& (!iq->target_count || iq->target_count[2]==0)
2435 		&& iq->sent_count < TARGET_FETCH_STOP) {
2436 		tf_policy = ie->target_fetch_policy[iq->depth];
2437 	}
2438 
2439 	/* if in 0x20 fallback get as many targets as possible */
2440 	if(iq->caps_fallback) {
2441 		int extra = 0;
2442 		size_t naddr, nres, navail;
2443 		if(!query_for_targets(qstate, iq, ie, id, -1, &extra)) {
2444 			errinf(qstate, "could not fetch nameservers for 0x20 fallback");
2445 			return error_response(qstate, id, LDNS_RCODE_SERVFAIL);
2446 		}
2447 		iq->num_target_queries += extra;
2448 		target_count_increase(iq, extra);
2449 		if(iq->num_target_queries > 0) {
2450 			/* wait to get all targets, we want to try em */
2451 			verbose(VERB_ALGO, "wait for all targets for fallback");
2452 			qstate->ext_state[id] = module_wait_reply;
2453 			/* undo qname minimise step because we'll get back here
2454 			 * to do it again */
2455 			if(qout_orig && iq->minimise_count > 0) {
2456 				iq->minimise_count--;
2457 				iq->qinfo_out.qname = qout_orig;
2458 				iq->qinfo_out.qname_len = qout_orig_len;
2459 			}
2460 			return 0;
2461 		}
2462 		/* did we do enough fallback queries already? */
2463 		delegpt_count_addr(iq->dp, &naddr, &nres, &navail);
2464 		/* the current caps_server is the number of fallbacks sent.
2465 		 * the original query is one that matched too, so we have
2466 		 * caps_server+1 number of matching queries now */
2467 		if(iq->caps_server+1 >= naddr*3 ||
2468 			iq->caps_server*2+2 >= MAX_SENT_COUNT) {
2469 			/* *2 on sentcount check because ipv6 may fail */
2470 			/* we're done, process the response */
2471 			verbose(VERB_ALGO, "0x20 fallback had %d responses "
2472 				"match for %d wanted, done.",
2473 				(int)iq->caps_server+1, (int)naddr*3);
2474 			iq->response = iq->caps_response;
2475 			iq->caps_fallback = 0;
2476 			iter_dec_attempts(iq->dp, 3, ie->outbound_msg_retry); /* space for fallback */
2477 			iq->num_current_queries++; /* RespState decrements it*/
2478 			iq->referral_count++; /* make sure we don't loop */
2479 			iq->sent_count = 0;
2480 			iq->dp_target_count = 0;
2481 			iq->state = QUERY_RESP_STATE;
2482 			return 1;
2483 		}
2484 		verbose(VERB_ALGO, "0x20 fallback number %d",
2485 			(int)iq->caps_server);
2486 
2487 	/* if there is a policy to fetch missing targets
2488 	 * opportunistically, do it. we rely on the fact that once a
2489 	 * query (or queries) for a missing name have been issued,
2490 	 * they will not show up again. */
2491 	} else if(tf_policy != 0) {
2492 		int extra = 0;
2493 		verbose(VERB_ALGO, "attempt to get extra %d targets",
2494 			tf_policy);
2495 		(void)query_for_targets(qstate, iq, ie, id, tf_policy, &extra);
2496 		/* errors ignored, these targets are not strictly necessary for
2497 		 * this result, we do not have to reply with SERVFAIL */
2498 		iq->num_target_queries += extra;
2499 		target_count_increase(iq, extra);
2500 	}
2501 
2502 	/* Add the current set of unused targets to our queue. */
2503 	delegpt_add_unused_targets(iq->dp);
2504 
2505 	if(qstate->env->auth_zones) {
2506 		/* apply rpz triggers at query time */
2507 		struct dns_msg* forged_response = rpz_callback_from_iterator_module(qstate, iq);
2508 		if(forged_response != NULL) {
2509 			qstate->ext_state[id] = module_finished;
2510 			qstate->return_rcode = LDNS_RCODE_NOERROR;
2511 			qstate->return_msg = forged_response;
2512 			iq->response = forged_response;
2513 			next_state(iq, FINISHED_STATE);
2514 			if(!iter_prepend(iq, qstate->return_msg, qstate->region)) {
2515 				log_err("rpz, prepend rrsets: out of memory");
2516 				return error_response(qstate, id, LDNS_RCODE_SERVFAIL);
2517 			}
2518 			return 0;
2519 		}
2520 	}
2521 
2522 	/* Select the next usable target, filtering out unsuitable targets. */
2523 	target = iter_server_selection(ie, qstate->env, iq->dp,
2524 		iq->dp->name, iq->dp->namelen, iq->qchase.qtype,
2525 		&iq->dnssec_lame_query, &iq->chase_to_rd,
2526 		iq->num_target_queries, qstate->blacklist,
2527 		qstate->prefetch_leeway);
2528 
2529 	/* If no usable target was selected... */
2530 	if(!target) {
2531 		/* Here we distinguish between three states: generate a new
2532 		 * target query, just wait, or quit (with a SERVFAIL).
2533 		 * We have the following information: number of active
2534 		 * target queries, number of active current queries,
2535 		 * the presence of missing targets at this delegation
2536 		 * point, and the given query target policy. */
2537 
2538 		/* Check for the wait condition. If this is true, then
2539 		 * an action must be taken. */
2540 		if(iq->num_target_queries==0 && iq->num_current_queries==0) {
2541 			/* If there is nothing to wait for, then we need
2542 			 * to distinguish between generating (a) new target
2543 			 * query, or failing. */
2544 			if(delegpt_count_missing_targets(iq->dp) > 0) {
2545 				int qs = 0;
2546 				verbose(VERB_ALGO, "querying for next "
2547 					"missing target");
2548 				if(!query_for_targets(qstate, iq, ie, id,
2549 					1, &qs)) {
2550 					errinf(qstate, "could not fetch nameserver");
2551 					errinf_dname(qstate, "at zone", iq->dp->name);
2552 					return error_response(qstate, id,
2553 						LDNS_RCODE_SERVFAIL);
2554 				}
2555 				if(qs == 0 &&
2556 				   delegpt_count_missing_targets(iq->dp) == 0){
2557 					/* it looked like there were missing
2558 					 * targets, but they did not turn up.
2559 					 * Try the bad choices again (if any),
2560 					 * when we get back here missing==0,
2561 					 * so this is not a loop. */
2562 					return 1;
2563 				}
2564 				iq->num_target_queries += qs;
2565 				target_count_increase(iq, qs);
2566 			}
2567 			/* Since a target query might have been made, we
2568 			 * need to check again. */
2569 			if(iq->num_target_queries == 0) {
2570 				/* if in capsforid fallback, instead of last
2571 				 * resort, we agree with the current reply
2572 				 * we have (if any) (our count of addrs bad)*/
2573 				if(iq->caps_fallback && iq->caps_reply) {
2574 					/* we're done, process the response */
2575 					verbose(VERB_ALGO, "0x20 fallback had %d responses, "
2576 						"but no more servers except "
2577 						"last resort, done.",
2578 						(int)iq->caps_server+1);
2579 					iq->response = iq->caps_response;
2580 					iq->caps_fallback = 0;
2581 					iter_dec_attempts(iq->dp, 3, ie->outbound_msg_retry); /* space for fallback */
2582 					iq->num_current_queries++; /* RespState decrements it*/
2583 					iq->referral_count++; /* make sure we don't loop */
2584 					iq->sent_count = 0;
2585 					iq->dp_target_count = 0;
2586 					iq->state = QUERY_RESP_STATE;
2587 					return 1;
2588 				}
2589 				return processLastResort(qstate, iq, ie, id);
2590 			}
2591 		}
2592 
2593 		/* otherwise, we have no current targets, so submerge
2594 		 * until one of the target or direct queries return. */
2595 		if(iq->num_target_queries>0 && iq->num_current_queries>0) {
2596 			verbose(VERB_ALGO, "no current targets -- waiting "
2597 				"for %d targets to resolve or %d outstanding"
2598 				" queries to respond", iq->num_target_queries,
2599 				iq->num_current_queries);
2600 			qstate->ext_state[id] = module_wait_reply;
2601 		} else if(iq->num_target_queries>0) {
2602 			verbose(VERB_ALGO, "no current targets -- waiting "
2603 				"for %d targets to resolve.",
2604 				iq->num_target_queries);
2605 			qstate->ext_state[id] = module_wait_subquery;
2606 		} else {
2607 			verbose(VERB_ALGO, "no current targets -- waiting "
2608 				"for %d outstanding queries to respond.",
2609 				iq->num_current_queries);
2610 			qstate->ext_state[id] = module_wait_reply;
2611 		}
2612 		/* undo qname minimise step because we'll get back here
2613 		 * to do it again */
2614 		if(qout_orig && iq->minimise_count > 0) {
2615 			iq->minimise_count--;
2616 			iq->qinfo_out.qname = qout_orig;
2617 			iq->qinfo_out.qname_len = qout_orig_len;
2618 		}
2619 		return 0;
2620 	}
2621 
2622 	/* Do not check ratelimit for forwarding queries or if we already got a
2623 	 * pass. */
2624 	sq_check_ratelimit = (!(iq->chase_flags & BIT_RD) && !iq->ratelimit_ok);
2625 	/* We have a valid target. */
2626 	if(verbosity >= VERB_QUERY) {
2627 		log_query_info(VERB_QUERY, "sending query:", &iq->qinfo_out);
2628 		log_name_addr(VERB_QUERY, "sending to target:", iq->dp->name,
2629 			&target->addr, target->addrlen);
2630 		verbose(VERB_ALGO, "dnssec status: %s%s",
2631 			iq->dnssec_expected?"expected": "not expected",
2632 			iq->dnssec_lame_query?" but lame_query anyway": "");
2633 	}
2634 	fptr_ok(fptr_whitelist_modenv_send_query(qstate->env->send_query));
2635 	outq = (*qstate->env->send_query)(&iq->qinfo_out,
2636 		iq->chase_flags | (iq->chase_to_rd?BIT_RD:0),
2637 		/* unset CD if to forwarder(RD set) and not dnssec retry
2638 		 * (blacklist nonempty) and no trust-anchors are configured
2639 		 * above the qname or on the first attempt when dnssec is on */
2640 		EDNS_DO| ((iq->chase_to_rd||(iq->chase_flags&BIT_RD)!=0)&&
2641 		!qstate->blacklist&&(!iter_qname_indicates_dnssec(qstate->env,
2642 		&iq->qinfo_out)||target->attempts==1)?0:BIT_CD),
2643 		iq->dnssec_expected, iq->caps_fallback || is_caps_whitelisted(
2644 		ie, iq), sq_check_ratelimit, &target->addr, target->addrlen,
2645 		iq->dp->name, iq->dp->namelen,
2646 		(iq->dp->tcp_upstream || qstate->env->cfg->tcp_upstream),
2647 		(iq->dp->ssl_upstream || qstate->env->cfg->ssl_upstream),
2648 		target->tls_auth_name, qstate, &sq_was_ratelimited);
2649 	if(!outq) {
2650 		if(sq_was_ratelimited) {
2651 			lock_basic_lock(&ie->queries_ratelimit_lock);
2652 			ie->num_queries_ratelimited++;
2653 			lock_basic_unlock(&ie->queries_ratelimit_lock);
2654 			verbose(VERB_ALGO, "query exceeded ratelimits");
2655 			qstate->was_ratelimited = 1;
2656 			errinf_dname(qstate, "exceeded ratelimit for zone",
2657 				iq->dp->name);
2658 			return error_response(qstate, id, LDNS_RCODE_SERVFAIL);
2659 		}
2660 		log_addr(VERB_QUERY, "error sending query to auth server",
2661 			&target->addr, target->addrlen);
2662 		if(qstate->env->cfg->qname_minimisation)
2663 			iq->minimisation_state = SKIP_MINIMISE_STATE;
2664 		return next_state(iq, QUERYTARGETS_STATE);
2665 	}
2666 	outbound_list_insert(&iq->outlist, outq);
2667 	iq->num_current_queries++;
2668 	iq->sent_count++;
2669 	qstate->ext_state[id] = module_wait_reply;
2670 
2671 	return 0;
2672 }
2673 
2674 /** find NS rrset in given list */
2675 static struct ub_packed_rrset_key*
2676 find_NS(struct reply_info* rep, size_t from, size_t to)
2677 {
2678 	size_t i;
2679 	for(i=from; i<to; i++) {
2680 		if(ntohs(rep->rrsets[i]->rk.type) == LDNS_RR_TYPE_NS)
2681 			return rep->rrsets[i];
2682 	}
2683 	return NULL;
2684 }
2685 
2686 
2687 /**
2688  * Process the query response. All queries end up at this state first. This
2689  * process generally consists of analyzing the response and routing the
2690  * event to the next state (either bouncing it back to a request state, or
2691  * terminating the processing for this event).
2692  *
2693  * @param qstate: query state.
2694  * @param iq: iterator query state.
2695  * @param ie: iterator shared global environment.
2696  * @param id: module id.
2697  * @return true if the event requires more immediate processing, false if
2698  *         not. This is generally only true when forwarding the request to
2699  *         the final state (i.e., on answer).
2700  */
2701 static int
2702 processQueryResponse(struct module_qstate* qstate, struct iter_qstate* iq,
2703 	struct iter_env* ie, int id)
2704 {
2705 	int dnsseclame = 0;
2706 	enum response_type type;
2707 
2708 	iq->num_current_queries--;
2709 
2710 	if(!inplace_cb_query_response_call(qstate->env, qstate, iq->response))
2711 		log_err("unable to call query_response callback");
2712 
2713 	if(iq->response == NULL) {
2714 		/* Don't increment qname when QNAME minimisation is enabled */
2715 		if(qstate->env->cfg->qname_minimisation) {
2716 			iq->minimisation_state = SKIP_MINIMISE_STATE;
2717 		}
2718 		iq->timeout_count++;
2719 		iq->chase_to_rd = 0;
2720 		iq->dnssec_lame_query = 0;
2721 		verbose(VERB_ALGO, "query response was timeout");
2722 		return next_state(iq, QUERYTARGETS_STATE);
2723 	}
2724 	iq->timeout_count = 0;
2725 	type = response_type_from_server(
2726 		(int)((iq->chase_flags&BIT_RD) || iq->chase_to_rd),
2727 		iq->response, &iq->qinfo_out, iq->dp);
2728 	iq->chase_to_rd = 0;
2729 	if(type == RESPONSE_TYPE_REFERRAL && (iq->chase_flags&BIT_RD) &&
2730 		!iq->auth_zone_response) {
2731 		/* When forwarding (RD bit is set), we handle referrals
2732 		 * differently. No queries should be sent elsewhere */
2733 		type = RESPONSE_TYPE_ANSWER;
2734 	}
2735 	if(!qstate->env->cfg->disable_dnssec_lame_check && iq->dnssec_expected
2736                 && !iq->dnssec_lame_query &&
2737 		!(iq->chase_flags&BIT_RD)
2738 		&& iq->sent_count < DNSSEC_LAME_DETECT_COUNT
2739 		&& type != RESPONSE_TYPE_LAME
2740 		&& type != RESPONSE_TYPE_REC_LAME
2741 		&& type != RESPONSE_TYPE_THROWAWAY
2742 		&& type != RESPONSE_TYPE_UNTYPED) {
2743 		/* a possible answer, see if it is missing DNSSEC */
2744 		/* but not when forwarding, so we dont mark fwder lame */
2745 		if(!iter_msg_has_dnssec(iq->response)) {
2746 			/* Mark this address as dnsseclame in this dp,
2747 			 * because that will make serverselection disprefer
2748 			 * it, but also, once it is the only final option,
2749 			 * use dnssec-lame-bypass if it needs to query there.*/
2750 			if(qstate->reply) {
2751 				struct delegpt_addr* a = delegpt_find_addr(
2752 					iq->dp, &qstate->reply->addr,
2753 					qstate->reply->addrlen);
2754 				if(a) a->dnsseclame = 1;
2755 			}
2756 			/* test the answer is from the zone we expected,
2757 		 	 * otherwise, (due to parent,child on same server), we
2758 		 	 * might mark the server,zone lame inappropriately */
2759 			if(!iter_msg_from_zone(iq->response, iq->dp, type,
2760 				iq->qchase.qclass))
2761 				qstate->reply = NULL;
2762 			type = RESPONSE_TYPE_LAME;
2763 			dnsseclame = 1;
2764 		}
2765 	} else iq->dnssec_lame_query = 0;
2766 	/* see if referral brings us close to the target */
2767 	if(type == RESPONSE_TYPE_REFERRAL) {
2768 		struct ub_packed_rrset_key* ns = find_NS(
2769 			iq->response->rep, iq->response->rep->an_numrrsets,
2770 			iq->response->rep->an_numrrsets
2771 			+ iq->response->rep->ns_numrrsets);
2772 		if(!ns) ns = find_NS(iq->response->rep, 0,
2773 				iq->response->rep->an_numrrsets);
2774 		if(!ns || !dname_strict_subdomain_c(ns->rk.dname, iq->dp->name)
2775 			|| !dname_subdomain_c(iq->qchase.qname, ns->rk.dname)){
2776 			verbose(VERB_ALGO, "bad referral, throwaway");
2777 			type = RESPONSE_TYPE_THROWAWAY;
2778 		} else
2779 			iter_scrub_ds(iq->response, ns, iq->dp->name);
2780 	} else iter_scrub_ds(iq->response, NULL, NULL);
2781 	if(type == RESPONSE_TYPE_THROWAWAY &&
2782 		FLAGS_GET_RCODE(iq->response->rep->flags) == LDNS_RCODE_YXDOMAIN) {
2783 		/* YXDOMAIN is a permanent error, no need to retry */
2784 		type = RESPONSE_TYPE_ANSWER;
2785 	}
2786 	if(type == RESPONSE_TYPE_CNAME && iq->response->rep->an_numrrsets >= 1
2787 		&& ntohs(iq->response->rep->rrsets[0]->rk.type) == LDNS_RR_TYPE_DNAME) {
2788 		uint8_t* sname = NULL;
2789 		size_t snamelen = 0;
2790 		get_cname_target(iq->response->rep->rrsets[0], &sname,
2791 			&snamelen);
2792 		if(snamelen && dname_subdomain_c(sname, iq->response->rep->rrsets[0]->rk.dname)) {
2793 			/* DNAME to a subdomain loop; do not recurse */
2794 			type = RESPONSE_TYPE_ANSWER;
2795 		}
2796 	} else if(type == RESPONSE_TYPE_CNAME &&
2797 		iq->qchase.qtype == LDNS_RR_TYPE_CNAME &&
2798 		iq->minimisation_state == MINIMISE_STATE &&
2799 		query_dname_compare(iq->qchase.qname, iq->qinfo_out.qname) == 0) {
2800 		/* The minimised query for full QTYPE and hidden QTYPE can be
2801 		 * classified as CNAME response type, even when the original
2802 		 * QTYPE=CNAME. This should be treated as answer response type.
2803 		 */
2804 		type = RESPONSE_TYPE_ANSWER;
2805 	}
2806 
2807 	/* handle each of the type cases */
2808 	if(type == RESPONSE_TYPE_ANSWER) {
2809 		/* ANSWER type responses terminate the query algorithm,
2810 		 * so they sent on their */
2811 		if(verbosity >= VERB_DETAIL) {
2812 			verbose(VERB_DETAIL, "query response was %s",
2813 				FLAGS_GET_RCODE(iq->response->rep->flags)
2814 				==LDNS_RCODE_NXDOMAIN?"NXDOMAIN ANSWER":
2815 				(iq->response->rep->an_numrrsets?"ANSWER":
2816 				"nodata ANSWER"));
2817 		}
2818 		/* if qtype is DS, check we have the right level of answer,
2819 		 * like grandchild answer but we need the middle, reject it */
2820 		if(iq->qchase.qtype == LDNS_RR_TYPE_DS && !iq->dsns_point
2821 			&& !(iq->chase_flags&BIT_RD)
2822 			&& iter_ds_toolow(iq->response, iq->dp)
2823 			&& iter_dp_cangodown(&iq->qchase, iq->dp)) {
2824 			/* close down outstanding requests to be discarded */
2825 			outbound_list_clear(&iq->outlist);
2826 			iq->num_current_queries = 0;
2827 			fptr_ok(fptr_whitelist_modenv_detach_subs(
2828 				qstate->env->detach_subs));
2829 			(*qstate->env->detach_subs)(qstate);
2830 			iq->num_target_queries = 0;
2831 			return processDSNSFind(qstate, iq, id);
2832 		}
2833 		if(!qstate->no_cache_store)
2834 			iter_dns_store(qstate->env, &iq->response->qinfo,
2835 				iq->response->rep, 0, qstate->prefetch_leeway,
2836 				iq->dp&&iq->dp->has_parent_side_NS,
2837 				qstate->region, qstate->query_flags);
2838 		/* close down outstanding requests to be discarded */
2839 		outbound_list_clear(&iq->outlist);
2840 		iq->num_current_queries = 0;
2841 		fptr_ok(fptr_whitelist_modenv_detach_subs(
2842 			qstate->env->detach_subs));
2843 		(*qstate->env->detach_subs)(qstate);
2844 		iq->num_target_queries = 0;
2845 		if(qstate->reply)
2846 			sock_list_insert(&qstate->reply_origin,
2847 				&qstate->reply->addr, qstate->reply->addrlen,
2848 				qstate->region);
2849 		if(iq->minimisation_state != DONOT_MINIMISE_STATE
2850 			&& !(iq->chase_flags & BIT_RD)) {
2851 			if(FLAGS_GET_RCODE(iq->response->rep->flags) !=
2852 				LDNS_RCODE_NOERROR) {
2853 				if(qstate->env->cfg->qname_minimisation_strict) {
2854 					if(FLAGS_GET_RCODE(iq->response->rep->flags) ==
2855 						LDNS_RCODE_NXDOMAIN) {
2856 						iter_scrub_nxdomain(iq->response);
2857 						return final_state(iq);
2858 					}
2859 					return error_response(qstate, id,
2860 						LDNS_RCODE_SERVFAIL);
2861 				}
2862 				/* Best effort qname-minimisation.
2863 				 * Stop minimising and send full query when
2864 				 * RCODE is not NOERROR. */
2865 				iq->minimisation_state = DONOT_MINIMISE_STATE;
2866 			}
2867 			if(FLAGS_GET_RCODE(iq->response->rep->flags) ==
2868 				LDNS_RCODE_NXDOMAIN) {
2869 				/* Stop resolving when NXDOMAIN is DNSSEC
2870 				 * signed. Based on assumption that nameservers
2871 				 * serving signed zones do not return NXDOMAIN
2872 				 * for empty-non-terminals. */
2873 				if(iq->dnssec_expected)
2874 					return final_state(iq);
2875 				/* Make subrequest to validate intermediate
2876 				 * NXDOMAIN if harden-below-nxdomain is
2877 				 * enabled. */
2878 				if(qstate->env->cfg->harden_below_nxdomain &&
2879 					qstate->env->need_to_validate) {
2880 					struct module_qstate* subq = NULL;
2881 					log_query_info(VERB_QUERY,
2882 						"schedule NXDOMAIN validation:",
2883 						&iq->response->qinfo);
2884 					if(!generate_sub_request(
2885 						iq->response->qinfo.qname,
2886 						iq->response->qinfo.qname_len,
2887 						iq->response->qinfo.qtype,
2888 						iq->response->qinfo.qclass,
2889 						qstate, id, iq,
2890 						INIT_REQUEST_STATE,
2891 						FINISHED_STATE, &subq, 1, 1))
2892 						verbose(VERB_ALGO,
2893 						"could not validate NXDOMAIN "
2894 						"response");
2895 				}
2896 			}
2897 			return next_state(iq, QUERYTARGETS_STATE);
2898 		}
2899 		return final_state(iq);
2900 	} else if(type == RESPONSE_TYPE_REFERRAL) {
2901 		/* REFERRAL type responses get a reset of the
2902 		 * delegation point, and back to the QUERYTARGETS_STATE. */
2903 		verbose(VERB_DETAIL, "query response was REFERRAL");
2904 
2905 		/* if hardened, only store referral if we asked for it */
2906 		if(!qstate->no_cache_store &&
2907 		(!qstate->env->cfg->harden_referral_path ||
2908 		    (  qstate->qinfo.qtype == LDNS_RR_TYPE_NS
2909 			&& (qstate->query_flags&BIT_RD)
2910 			&& !(qstate->query_flags&BIT_CD)
2911 			   /* we know that all other NS rrsets are scrubbed
2912 			    * away, thus on referral only one is left.
2913 			    * see if that equals the query name... */
2914 			&& ( /* auth section, but sometimes in answer section*/
2915 			  reply_find_rrset_section_ns(iq->response->rep,
2916 				iq->qchase.qname, iq->qchase.qname_len,
2917 				LDNS_RR_TYPE_NS, iq->qchase.qclass)
2918 			  || reply_find_rrset_section_an(iq->response->rep,
2919 				iq->qchase.qname, iq->qchase.qname_len,
2920 				LDNS_RR_TYPE_NS, iq->qchase.qclass)
2921 			  )
2922 		    ))) {
2923 			/* Store the referral under the current query */
2924 			/* no prefetch-leeway, since its not the answer */
2925 			iter_dns_store(qstate->env, &iq->response->qinfo,
2926 				iq->response->rep, 1, 0, 0, NULL, 0);
2927 			if(iq->store_parent_NS)
2928 				iter_store_parentside_NS(qstate->env,
2929 					iq->response->rep);
2930 			if(qstate->env->neg_cache)
2931 				val_neg_addreferral(qstate->env->neg_cache,
2932 					iq->response->rep, iq->dp->name);
2933 		}
2934 		/* store parent-side-in-zone-glue, if directly queried for */
2935 		if(!qstate->no_cache_store && iq->query_for_pside_glue
2936 			&& !iq->pside_glue) {
2937 				iq->pside_glue = reply_find_rrset(iq->response->rep,
2938 					iq->qchase.qname, iq->qchase.qname_len,
2939 					iq->qchase.qtype, iq->qchase.qclass);
2940 				if(iq->pside_glue) {
2941 					log_rrset_key(VERB_ALGO, "found parent-side "
2942 						"glue", iq->pside_glue);
2943 					iter_store_parentside_rrset(qstate->env,
2944 						iq->pside_glue);
2945 				}
2946 		}
2947 
2948 		/* Reset the event state, setting the current delegation
2949 		 * point to the referral. */
2950 		iq->deleg_msg = iq->response;
2951 		iq->dp = delegpt_from_message(iq->response, qstate->region);
2952 		if (qstate->env->cfg->qname_minimisation)
2953 			iq->minimisation_state = INIT_MINIMISE_STATE;
2954 		if(!iq->dp) {
2955 			errinf(qstate, "malloc failure, for delegation point");
2956 			return error_response(qstate, id, LDNS_RCODE_SERVFAIL);
2957 		}
2958 		if(!cache_fill_missing(qstate->env, iq->qchase.qclass,
2959 			qstate->region, iq->dp)) {
2960 			errinf(qstate, "malloc failure, copy extra info into delegation point");
2961 			return error_response(qstate, id, LDNS_RCODE_SERVFAIL);
2962 		}
2963 		if(iq->store_parent_NS && query_dname_compare(iq->dp->name,
2964 			iq->store_parent_NS->name) == 0)
2965 			iter_merge_retry_counts(iq->dp, iq->store_parent_NS,
2966 				ie->outbound_msg_retry);
2967 		delegpt_log(VERB_ALGO, iq->dp);
2968 		/* Count this as a referral. */
2969 		iq->referral_count++;
2970 		iq->sent_count = 0;
2971 		iq->dp_target_count = 0;
2972 		/* see if the next dp is a trust anchor, or a DS was sent
2973 		 * along, indicating dnssec is expected for next zone */
2974 		iq->dnssec_expected = iter_indicates_dnssec(qstate->env,
2975 			iq->dp, iq->response, iq->qchase.qclass);
2976 		/* if dnssec, validating then also fetch the key for the DS */
2977 		if(iq->dnssec_expected && qstate->env->cfg->prefetch_key &&
2978 			!(qstate->query_flags&BIT_CD))
2979 			generate_dnskey_prefetch(qstate, iq, id);
2980 
2981 		/* spawn off NS and addr to auth servers for the NS we just
2982 		 * got in the referral. This gets authoritative answer
2983 		 * (answer section trust level) rrset.
2984 		 * right after, we detach the subs, answer goes to cache. */
2985 		if(qstate->env->cfg->harden_referral_path)
2986 			generate_ns_check(qstate, iq, id);
2987 
2988 		/* stop current outstanding queries.
2989 		 * FIXME: should the outstanding queries be waited for and
2990 		 * handled? Say by a subquery that inherits the outbound_entry.
2991 		 */
2992 		outbound_list_clear(&iq->outlist);
2993 		iq->num_current_queries = 0;
2994 		fptr_ok(fptr_whitelist_modenv_detach_subs(
2995 			qstate->env->detach_subs));
2996 		(*qstate->env->detach_subs)(qstate);
2997 		iq->num_target_queries = 0;
2998 		iq->response = NULL;
2999 		iq->fail_reply = NULL;
3000 		verbose(VERB_ALGO, "cleared outbound list for next round");
3001 		return next_state(iq, QUERYTARGETS_STATE);
3002 	} else if(type == RESPONSE_TYPE_CNAME) {
3003 		uint8_t* sname = NULL;
3004 		size_t snamelen = 0;
3005 		/* CNAME type responses get a query restart (i.e., get a
3006 		 * reset of the query state and go back to INIT_REQUEST_STATE).
3007 		 */
3008 		verbose(VERB_DETAIL, "query response was CNAME");
3009 		if(verbosity >= VERB_ALGO)
3010 			log_dns_msg("cname msg", &iq->response->qinfo,
3011 				iq->response->rep);
3012 		/* if qtype is DS, check we have the right level of answer,
3013 		 * like grandchild answer but we need the middle, reject it */
3014 		if(iq->qchase.qtype == LDNS_RR_TYPE_DS && !iq->dsns_point
3015 			&& !(iq->chase_flags&BIT_RD)
3016 			&& iter_ds_toolow(iq->response, iq->dp)
3017 			&& iter_dp_cangodown(&iq->qchase, iq->dp)) {
3018 			outbound_list_clear(&iq->outlist);
3019 			iq->num_current_queries = 0;
3020 			fptr_ok(fptr_whitelist_modenv_detach_subs(
3021 				qstate->env->detach_subs));
3022 			(*qstate->env->detach_subs)(qstate);
3023 			iq->num_target_queries = 0;
3024 			return processDSNSFind(qstate, iq, id);
3025 		}
3026 		/* Process the CNAME response. */
3027 		if(!handle_cname_response(qstate, iq, iq->response,
3028 			&sname, &snamelen)) {
3029 			errinf(qstate, "malloc failure, CNAME info");
3030 			return error_response(qstate, id, LDNS_RCODE_SERVFAIL);
3031 		}
3032 		/* cache the CNAME response under the current query */
3033 		/* NOTE : set referral=1, so that rrsets get stored but not
3034 		 * the partial query answer (CNAME only). */
3035 		/* prefetchleeway applied because this updates answer parts */
3036 		if(!qstate->no_cache_store)
3037 			iter_dns_store(qstate->env, &iq->response->qinfo,
3038 				iq->response->rep, 1, qstate->prefetch_leeway,
3039 				iq->dp&&iq->dp->has_parent_side_NS, NULL,
3040 				qstate->query_flags);
3041 		/* set the current request's qname to the new value. */
3042 		iq->qchase.qname = sname;
3043 		iq->qchase.qname_len = snamelen;
3044 		if(qstate->env->auth_zones) {
3045 			/* apply rpz qname triggers after cname */
3046 			struct dns_msg* forged_response =
3047 				rpz_callback_from_iterator_cname(qstate, iq);
3048 			while(forged_response && reply_find_rrset_section_an(
3049 				forged_response->rep, iq->qchase.qname,
3050 				iq->qchase.qname_len, LDNS_RR_TYPE_CNAME,
3051 				iq->qchase.qclass)) {
3052 				/* another cname to follow */
3053 				if(!handle_cname_response(qstate, iq, forged_response,
3054 					&sname, &snamelen)) {
3055 					errinf(qstate, "malloc failure, CNAME info");
3056 					return error_response(qstate, id, LDNS_RCODE_SERVFAIL);
3057 				}
3058 				iq->qchase.qname = sname;
3059 				iq->qchase.qname_len = snamelen;
3060 				forged_response =
3061 					rpz_callback_from_iterator_cname(qstate, iq);
3062 			}
3063 			if(forged_response != NULL) {
3064 				qstate->ext_state[id] = module_finished;
3065 				qstate->return_rcode = LDNS_RCODE_NOERROR;
3066 				qstate->return_msg = forged_response;
3067 				iq->response = forged_response;
3068 				next_state(iq, FINISHED_STATE);
3069 				if(!iter_prepend(iq, qstate->return_msg, qstate->region)) {
3070 					log_err("rpz after cname, prepend rrsets: out of memory");
3071 					return error_response(qstate, id, LDNS_RCODE_SERVFAIL);
3072 				}
3073 				qstate->return_msg->qinfo = qstate->qinfo;
3074 				return 0;
3075 			}
3076 		}
3077 		/* Clear the query state, since this is a query restart. */
3078 		iq->deleg_msg = NULL;
3079 		iq->dp = NULL;
3080 		iq->dsns_point = NULL;
3081 		iq->auth_zone_response = 0;
3082 		iq->sent_count = 0;
3083 		iq->dp_target_count = 0;
3084 		if(iq->minimisation_state != MINIMISE_STATE)
3085 			/* Only count as query restart when it is not an extra
3086 			 * query as result of qname minimisation. */
3087 			iq->query_restart_count++;
3088 		if(qstate->env->cfg->qname_minimisation)
3089 			iq->minimisation_state = INIT_MINIMISE_STATE;
3090 
3091 		/* stop current outstanding queries.
3092 		 * FIXME: should the outstanding queries be waited for and
3093 		 * handled? Say by a subquery that inherits the outbound_entry.
3094 		 */
3095 		outbound_list_clear(&iq->outlist);
3096 		iq->num_current_queries = 0;
3097 		fptr_ok(fptr_whitelist_modenv_detach_subs(
3098 			qstate->env->detach_subs));
3099 		(*qstate->env->detach_subs)(qstate);
3100 		iq->num_target_queries = 0;
3101 		if(qstate->reply)
3102 			sock_list_insert(&qstate->reply_origin,
3103 				&qstate->reply->addr, qstate->reply->addrlen,
3104 				qstate->region);
3105 		verbose(VERB_ALGO, "cleared outbound list for query restart");
3106 		/* go to INIT_REQUEST_STATE for new qname. */
3107 		return next_state(iq, INIT_REQUEST_STATE);
3108 	} else if(type == RESPONSE_TYPE_LAME) {
3109 		/* Cache the LAMEness. */
3110 		verbose(VERB_DETAIL, "query response was %sLAME",
3111 			dnsseclame?"DNSSEC ":"");
3112 		if(!dname_subdomain_c(iq->qchase.qname, iq->dp->name)) {
3113 			log_err("mark lame: mismatch in qname and dpname");
3114 			/* throwaway this reply below */
3115 		} else if(qstate->reply) {
3116 			/* need addr for lameness cache, but we may have
3117 			 * gotten this from cache, so test to be sure */
3118 			if(!infra_set_lame(qstate->env->infra_cache,
3119 				&qstate->reply->addr, qstate->reply->addrlen,
3120 				iq->dp->name, iq->dp->namelen,
3121 				*qstate->env->now, dnsseclame, 0,
3122 				iq->qchase.qtype))
3123 				log_err("mark host lame: out of memory");
3124 		}
3125 	} else if(type == RESPONSE_TYPE_REC_LAME) {
3126 		/* Cache the LAMEness. */
3127 		verbose(VERB_DETAIL, "query response REC_LAME: "
3128 			"recursive but not authoritative server");
3129 		if(!dname_subdomain_c(iq->qchase.qname, iq->dp->name)) {
3130 			log_err("mark rec_lame: mismatch in qname and dpname");
3131 			/* throwaway this reply below */
3132 		} else if(qstate->reply) {
3133 			/* need addr for lameness cache, but we may have
3134 			 * gotten this from cache, so test to be sure */
3135 			verbose(VERB_DETAIL, "mark as REC_LAME");
3136 			if(!infra_set_lame(qstate->env->infra_cache,
3137 				&qstate->reply->addr, qstate->reply->addrlen,
3138 				iq->dp->name, iq->dp->namelen,
3139 				*qstate->env->now, 0, 1, iq->qchase.qtype))
3140 				log_err("mark host lame: out of memory");
3141 		}
3142 	} else if(type == RESPONSE_TYPE_THROWAWAY) {
3143 		/* LAME and THROWAWAY responses are handled the same way.
3144 		 * In this case, the event is just sent directly back to
3145 		 * the QUERYTARGETS_STATE without resetting anything,
3146 		 * because, clearly, the next target must be tried. */
3147 		verbose(VERB_DETAIL, "query response was THROWAWAY");
3148 	} else {
3149 		log_warn("A query response came back with an unknown type: %d",
3150 			(int)type);
3151 	}
3152 
3153 	/* LAME, THROWAWAY and "unknown" all end up here.
3154 	 * Recycle to the QUERYTARGETS state to hopefully try a
3155 	 * different target. */
3156 	if (qstate->env->cfg->qname_minimisation &&
3157 		!qstate->env->cfg->qname_minimisation_strict)
3158 		iq->minimisation_state = DONOT_MINIMISE_STATE;
3159 	if(iq->auth_zone_response) {
3160 		/* can we fallback? */
3161 		iq->auth_zone_response = 0;
3162 		if(!auth_zones_can_fallback(qstate->env->auth_zones,
3163 			iq->dp->name, iq->dp->namelen, qstate->qinfo.qclass)) {
3164 			verbose(VERB_ALGO, "auth zone response bad, and no"
3165 				" fallback possible, servfail");
3166 			errinf_dname(qstate, "response is bad, no fallback, "
3167 				"for auth zone", iq->dp->name);
3168 			return error_response(qstate, id, LDNS_RCODE_SERVFAIL);
3169 		}
3170 		verbose(VERB_ALGO, "auth zone response was bad, "
3171 			"fallback enabled");
3172 		iq->auth_zone_avoid = 1;
3173 		if(iq->dp->auth_dp) {
3174 			/* we are using a dp for the auth zone, with no
3175 			 * nameservers, get one first */
3176 			iq->dp = NULL;
3177 			return next_state(iq, INIT_REQUEST_STATE);
3178 		}
3179 	}
3180 	return next_state(iq, QUERYTARGETS_STATE);
3181 }
3182 
3183 /**
3184  * Return priming query results to interested super querystates.
3185  *
3186  * Sets the delegation point and delegation message (not nonRD queries).
3187  * This is a callback from walk_supers.
3188  *
3189  * @param qstate: priming query state that finished.
3190  * @param id: module id.
3191  * @param forq: the qstate for which priming has been done.
3192  */
3193 static void
3194 prime_supers(struct module_qstate* qstate, int id, struct module_qstate* forq)
3195 {
3196 	struct iter_qstate* foriq = (struct iter_qstate*)forq->minfo[id];
3197 	struct delegpt* dp = NULL;
3198 
3199 	log_assert(qstate->is_priming || foriq->wait_priming_stub);
3200 	log_assert(qstate->return_rcode == LDNS_RCODE_NOERROR);
3201 	/* Convert our response to a delegation point */
3202 	dp = delegpt_from_message(qstate->return_msg, forq->region);
3203 	if(!dp) {
3204 		/* if there is no convertible delegation point, then
3205 		 * the ANSWER type was (presumably) a negative answer. */
3206 		verbose(VERB_ALGO, "prime response was not a positive "
3207 			"ANSWER; failing");
3208 		foriq->dp = NULL;
3209 		foriq->state = QUERYTARGETS_STATE;
3210 		return;
3211 	}
3212 
3213 	log_query_info(VERB_DETAIL, "priming successful for", &qstate->qinfo);
3214 	delegpt_log(VERB_ALGO, dp);
3215 	foriq->dp = dp;
3216 	foriq->deleg_msg = dns_copy_msg(qstate->return_msg, forq->region);
3217 	if(!foriq->deleg_msg) {
3218 		log_err("copy prime response: out of memory");
3219 		foriq->dp = NULL;
3220 		foriq->state = QUERYTARGETS_STATE;
3221 		return;
3222 	}
3223 
3224 	/* root priming responses go to init stage 2, priming stub
3225 	 * responses to to stage 3. */
3226 	if(foriq->wait_priming_stub) {
3227 		foriq->state = INIT_REQUEST_3_STATE;
3228 		foriq->wait_priming_stub = 0;
3229 	} else	foriq->state = INIT_REQUEST_2_STATE;
3230 	/* because we are finished, the parent will be reactivated */
3231 }
3232 
3233 /**
3234  * This handles the response to a priming query. This is used to handle both
3235  * root and stub priming responses. This is basically the equivalent of the
3236  * QUERY_RESP_STATE, but will not handle CNAME responses and will treat
3237  * REFERRALs as ANSWERS. It will also update and reactivate the originating
3238  * event.
3239  *
3240  * @param qstate: query state.
3241  * @param id: module id.
3242  * @return true if the event needs more immediate processing, false if not.
3243  *         This state always returns false.
3244  */
3245 static int
3246 processPrimeResponse(struct module_qstate* qstate, int id)
3247 {
3248 	struct iter_qstate* iq = (struct iter_qstate*)qstate->minfo[id];
3249 	enum response_type type;
3250 	iq->response->rep->flags &= ~(BIT_RD|BIT_RA); /* ignore rec-lame */
3251 	type = response_type_from_server(
3252 		(int)((iq->chase_flags&BIT_RD) || iq->chase_to_rd),
3253 		iq->response, &iq->qchase, iq->dp);
3254 	if(type == RESPONSE_TYPE_ANSWER) {
3255 		qstate->return_rcode = LDNS_RCODE_NOERROR;
3256 		qstate->return_msg = iq->response;
3257 	} else {
3258 		errinf(qstate, "prime response did not get an answer");
3259 		errinf_dname(qstate, "for", qstate->qinfo.qname);
3260 		qstate->return_rcode = LDNS_RCODE_SERVFAIL;
3261 		qstate->return_msg = NULL;
3262 	}
3263 
3264 	/* validate the root or stub after priming (if enabled).
3265 	 * This is the same query as the prime query, but with validation.
3266 	 * Now that we are primed, the additional queries that validation
3267 	 * may need can be resolved. */
3268 	if(qstate->env->cfg->harden_referral_path) {
3269 		struct module_qstate* subq = NULL;
3270 		log_nametypeclass(VERB_ALGO, "schedule prime validation",
3271 			qstate->qinfo.qname, qstate->qinfo.qtype,
3272 			qstate->qinfo.qclass);
3273 		if(!generate_sub_request(qstate->qinfo.qname,
3274 			qstate->qinfo.qname_len, qstate->qinfo.qtype,
3275 			qstate->qinfo.qclass, qstate, id, iq,
3276 			INIT_REQUEST_STATE, FINISHED_STATE, &subq, 1, 0)) {
3277 			verbose(VERB_ALGO, "could not generate prime check");
3278 		}
3279 		generate_a_aaaa_check(qstate, iq, id);
3280 	}
3281 
3282 	/* This event is finished. */
3283 	qstate->ext_state[id] = module_finished;
3284 	return 0;
3285 }
3286 
3287 /**
3288  * Do final processing on responses to target queries. Events reach this
3289  * state after the iterative resolution algorithm terminates. This state is
3290  * responsible for reactivating the original event, and housekeeping related
3291  * to received target responses (caching, updating the current delegation
3292  * point, etc).
3293  * Callback from walk_supers for every super state that is interested in
3294  * the results from this query.
3295  *
3296  * @param qstate: query state.
3297  * @param id: module id.
3298  * @param forq: super query state.
3299  */
3300 static void
3301 processTargetResponse(struct module_qstate* qstate, int id,
3302 	struct module_qstate* forq)
3303 {
3304 	struct iter_env* ie = (struct iter_env*)qstate->env->modinfo[id];
3305 	struct iter_qstate* iq = (struct iter_qstate*)qstate->minfo[id];
3306 	struct iter_qstate* foriq = (struct iter_qstate*)forq->minfo[id];
3307 	struct ub_packed_rrset_key* rrset;
3308 	struct delegpt_ns* dpns;
3309 	log_assert(qstate->return_rcode == LDNS_RCODE_NOERROR);
3310 
3311 	foriq->state = QUERYTARGETS_STATE;
3312 	log_query_info(VERB_ALGO, "processTargetResponse", &qstate->qinfo);
3313 	log_query_info(VERB_ALGO, "processTargetResponse super", &forq->qinfo);
3314 
3315 	/* Tell the originating event that this target query has finished
3316 	 * (regardless if it succeeded or not). */
3317 	foriq->num_target_queries--;
3318 
3319 	/* check to see if parent event is still interested (in orig name).  */
3320 	if(!foriq->dp) {
3321 		verbose(VERB_ALGO, "subq: parent not interested, was reset");
3322 		return; /* not interested anymore */
3323 	}
3324 	dpns = delegpt_find_ns(foriq->dp, qstate->qinfo.qname,
3325 			qstate->qinfo.qname_len);
3326 	if(!dpns) {
3327 		/* If not interested, just stop processing this event */
3328 		verbose(VERB_ALGO, "subq: parent not interested anymore");
3329 		/* could be because parent was jostled out of the cache,
3330 		   and a new identical query arrived, that does not want it*/
3331 		return;
3332 	}
3333 
3334 	/* if iq->query_for_pside_glue then add the pside_glue (marked lame) */
3335 	if(iq->pside_glue) {
3336 		/* if the pside_glue is NULL, then it could not be found,
3337 		 * the done_pside is already set when created and a cache
3338 		 * entry created in processFinished so nothing to do here */
3339 		log_rrset_key(VERB_ALGO, "add parentside glue to dp",
3340 			iq->pside_glue);
3341 		if(!delegpt_add_rrset(foriq->dp, forq->region,
3342 			iq->pside_glue, 1, NULL))
3343 			log_err("out of memory adding pside glue");
3344 	}
3345 
3346 	/* This response is relevant to the current query, so we
3347 	 * add (attempt to add, anyway) this target(s) and reactivate
3348 	 * the original event.
3349 	 * NOTE: we could only look for the AnswerRRset if the
3350 	 * response type was ANSWER. */
3351 	rrset = reply_find_answer_rrset(&iq->qchase, qstate->return_msg->rep);
3352 	if(rrset) {
3353 		int additions = 0;
3354 		/* if CNAMEs have been followed - add new NS to delegpt. */
3355 		/* BTW. RFC 1918 says NS should not have got CNAMEs. Robust. */
3356 		if(!delegpt_find_ns(foriq->dp, rrset->rk.dname,
3357 			rrset->rk.dname_len)) {
3358 			/* if dpns->lame then set newcname ns lame too */
3359 			if(!delegpt_add_ns(foriq->dp, forq->region,
3360 				rrset->rk.dname, dpns->lame, dpns->tls_auth_name,
3361 				dpns->port))
3362 				log_err("out of memory adding cnamed-ns");
3363 		}
3364 		/* if dpns->lame then set the address(es) lame too */
3365 		if(!delegpt_add_rrset(foriq->dp, forq->region, rrset,
3366 			dpns->lame, &additions))
3367 			log_err("out of memory adding targets");
3368 		if(!additions) {
3369 			/* no new addresses, increase the nxns counter, like
3370 			 * this could be a list of wildcards with no new
3371 			 * addresses */
3372 			target_count_increase_nx(foriq, 1);
3373 		}
3374 		verbose(VERB_ALGO, "added target response");
3375 		delegpt_log(VERB_ALGO, foriq->dp);
3376 	} else {
3377 		verbose(VERB_ALGO, "iterator TargetResponse failed");
3378 		delegpt_mark_neg(dpns, qstate->qinfo.qtype);
3379 		dpns->resolved = 1; /* fail the target */
3380 		if((dpns->got4 == 2 || !ie->supports_ipv4) &&
3381 			(dpns->got6 == 2 || !ie->supports_ipv6))
3382 			target_count_increase_nx(foriq, 1);
3383 	}
3384 }
3385 
3386 /**
3387  * Process response for DS NS Find queries, that attempt to find the delegation
3388  * point where we ask the DS query from.
3389  *
3390  * @param qstate: query state.
3391  * @param id: module id.
3392  * @param forq: super query state.
3393  */
3394 static void
3395 processDSNSResponse(struct module_qstate* qstate, int id,
3396 	struct module_qstate* forq)
3397 {
3398 	struct iter_qstate* foriq = (struct iter_qstate*)forq->minfo[id];
3399 
3400 	/* if the finished (iq->response) query has no NS set: continue
3401 	 * up to look for the right dp; nothing to change, do DPNSstate */
3402 	if(qstate->return_rcode != LDNS_RCODE_NOERROR)
3403 		return; /* seek further */
3404 	/* find the NS RRset (without allowing CNAMEs) */
3405 	if(!reply_find_rrset(qstate->return_msg->rep, qstate->qinfo.qname,
3406 		qstate->qinfo.qname_len, LDNS_RR_TYPE_NS,
3407 		qstate->qinfo.qclass)){
3408 		return; /* seek further */
3409 	}
3410 
3411 	/* else, store as DP and continue at querytargets */
3412 	foriq->state = QUERYTARGETS_STATE;
3413 	foriq->dp = delegpt_from_message(qstate->return_msg, forq->region);
3414 	if(!foriq->dp) {
3415 		log_err("out of memory in dsns dp alloc");
3416 		errinf(qstate, "malloc failure, in DS search");
3417 		return; /* dp==NULL in QUERYTARGETS makes SERVFAIL */
3418 	}
3419 	/* success, go query the querytargets in the new dp (and go down) */
3420 }
3421 
3422 /**
3423  * Process response for qclass=ANY queries for a particular class.
3424  * Append to result or error-exit.
3425  *
3426  * @param qstate: query state.
3427  * @param id: module id.
3428  * @param forq: super query state.
3429  */
3430 static void
3431 processClassResponse(struct module_qstate* qstate, int id,
3432 	struct module_qstate* forq)
3433 {
3434 	struct iter_qstate* foriq = (struct iter_qstate*)forq->minfo[id];
3435 	struct dns_msg* from = qstate->return_msg;
3436 	log_query_info(VERB_ALGO, "processClassResponse", &qstate->qinfo);
3437 	log_query_info(VERB_ALGO, "processClassResponse super", &forq->qinfo);
3438 	if(qstate->return_rcode != LDNS_RCODE_NOERROR) {
3439 		/* cause servfail for qclass ANY query */
3440 		foriq->response = NULL;
3441 		foriq->state = FINISHED_STATE;
3442 		return;
3443 	}
3444 	/* append result */
3445 	if(!foriq->response) {
3446 		/* allocate the response: copy RCODE, sec_state */
3447 		foriq->response = dns_copy_msg(from, forq->region);
3448 		if(!foriq->response) {
3449 			log_err("malloc failed for qclass ANY response");
3450 			foriq->state = FINISHED_STATE;
3451 			return;
3452 		}
3453 		foriq->response->qinfo.qclass = forq->qinfo.qclass;
3454 		/* qclass ANY does not receive the AA flag on replies */
3455 		foriq->response->rep->authoritative = 0;
3456 	} else {
3457 		struct dns_msg* to = foriq->response;
3458 		/* add _from_ this response _to_ existing collection */
3459 		/* if there are records, copy RCODE */
3460 		/* lower sec_state if this message is lower */
3461 		if(from->rep->rrset_count != 0) {
3462 			size_t n = from->rep->rrset_count+to->rep->rrset_count;
3463 			struct ub_packed_rrset_key** dest, **d;
3464 			/* copy appropriate rcode */
3465 			to->rep->flags = from->rep->flags;
3466 			/* copy rrsets */
3467 			if(from->rep->rrset_count > RR_COUNT_MAX ||
3468 				to->rep->rrset_count > RR_COUNT_MAX) {
3469 				log_err("malloc failed (too many rrsets) in collect ANY");
3470 				foriq->state = FINISHED_STATE;
3471 				return; /* integer overflow protection */
3472 			}
3473 			dest = regional_alloc(forq->region, sizeof(dest[0])*n);
3474 			if(!dest) {
3475 				log_err("malloc failed in collect ANY");
3476 				foriq->state = FINISHED_STATE;
3477 				return;
3478 			}
3479 			d = dest;
3480 			/* copy AN */
3481 			memcpy(dest, to->rep->rrsets, to->rep->an_numrrsets
3482 				* sizeof(dest[0]));
3483 			dest += to->rep->an_numrrsets;
3484 			memcpy(dest, from->rep->rrsets, from->rep->an_numrrsets
3485 				* sizeof(dest[0]));
3486 			dest += from->rep->an_numrrsets;
3487 			/* copy NS */
3488 			memcpy(dest, to->rep->rrsets+to->rep->an_numrrsets,
3489 				to->rep->ns_numrrsets * sizeof(dest[0]));
3490 			dest += to->rep->ns_numrrsets;
3491 			memcpy(dest, from->rep->rrsets+from->rep->an_numrrsets,
3492 				from->rep->ns_numrrsets * sizeof(dest[0]));
3493 			dest += from->rep->ns_numrrsets;
3494 			/* copy AR */
3495 			memcpy(dest, to->rep->rrsets+to->rep->an_numrrsets+
3496 				to->rep->ns_numrrsets,
3497 				to->rep->ar_numrrsets * sizeof(dest[0]));
3498 			dest += to->rep->ar_numrrsets;
3499 			memcpy(dest, from->rep->rrsets+from->rep->an_numrrsets+
3500 				from->rep->ns_numrrsets,
3501 				from->rep->ar_numrrsets * sizeof(dest[0]));
3502 			/* update counts */
3503 			to->rep->rrsets = d;
3504 			to->rep->an_numrrsets += from->rep->an_numrrsets;
3505 			to->rep->ns_numrrsets += from->rep->ns_numrrsets;
3506 			to->rep->ar_numrrsets += from->rep->ar_numrrsets;
3507 			to->rep->rrset_count = n;
3508 		}
3509 		if(from->rep->security < to->rep->security) /* lowest sec */
3510 			to->rep->security = from->rep->security;
3511 		if(from->rep->qdcount != 0) /* insert qd if appropriate */
3512 			to->rep->qdcount = from->rep->qdcount;
3513 		if(from->rep->ttl < to->rep->ttl) /* use smallest TTL */
3514 			to->rep->ttl = from->rep->ttl;
3515 		if(from->rep->prefetch_ttl < to->rep->prefetch_ttl)
3516 			to->rep->prefetch_ttl = from->rep->prefetch_ttl;
3517 		if(from->rep->serve_expired_ttl < to->rep->serve_expired_ttl)
3518 			to->rep->serve_expired_ttl = from->rep->serve_expired_ttl;
3519 	}
3520 	/* are we done? */
3521 	foriq->num_current_queries --;
3522 	if(foriq->num_current_queries == 0)
3523 		foriq->state = FINISHED_STATE;
3524 }
3525 
3526 /**
3527  * Collect class ANY responses and make them into one response.  This
3528  * state is started and it creates queries for all classes (that have
3529  * root hints).  The answers are then collected.
3530  *
3531  * @param qstate: query state.
3532  * @param id: module id.
3533  * @return true if the event needs more immediate processing, false if not.
3534  */
3535 static int
3536 processCollectClass(struct module_qstate* qstate, int id)
3537 {
3538 	struct iter_qstate* iq = (struct iter_qstate*)qstate->minfo[id];
3539 	struct module_qstate* subq;
3540 	/* If qchase.qclass == 0 then send out queries for all classes.
3541 	 * Otherwise, do nothing (wait for all answers to arrive and the
3542 	 * processClassResponse to put them together, and that moves us
3543 	 * towards the Finished state when done. */
3544 	if(iq->qchase.qclass == 0) {
3545 		uint16_t c = 0;
3546 		iq->qchase.qclass = LDNS_RR_CLASS_ANY;
3547 		while(iter_get_next_root(qstate->env->hints,
3548 			qstate->env->fwds, &c)) {
3549 			/* generate query for this class */
3550 			log_nametypeclass(VERB_ALGO, "spawn collect query",
3551 				qstate->qinfo.qname, qstate->qinfo.qtype, c);
3552 			if(!generate_sub_request(qstate->qinfo.qname,
3553 				qstate->qinfo.qname_len, qstate->qinfo.qtype,
3554 				c, qstate, id, iq, INIT_REQUEST_STATE,
3555 				FINISHED_STATE, &subq,
3556 				(int)!(qstate->query_flags&BIT_CD), 0)) {
3557 				errinf(qstate, "could not generate class ANY"
3558 					" lookup query");
3559 				return error_response(qstate, id,
3560 					LDNS_RCODE_SERVFAIL);
3561 			}
3562 			/* ignore subq, no special init required */
3563 			iq->num_current_queries ++;
3564 			if(c == 0xffff)
3565 				break;
3566 			else c++;
3567 		}
3568 		/* if no roots are configured at all, return */
3569 		if(iq->num_current_queries == 0) {
3570 			verbose(VERB_ALGO, "No root hints or fwds, giving up "
3571 				"on qclass ANY");
3572 			return error_response(qstate, id, LDNS_RCODE_REFUSED);
3573 		}
3574 		/* return false, wait for queries to return */
3575 	}
3576 	/* if woke up here because of an answer, wait for more answers */
3577 	return 0;
3578 }
3579 
3580 /**
3581  * This handles the final state for first-tier responses (i.e., responses to
3582  * externally generated queries).
3583  *
3584  * @param qstate: query state.
3585  * @param iq: iterator query state.
3586  * @param id: module id.
3587  * @return true if the event needs more processing, false if not. Since this
3588  *         is the final state for an event, it always returns false.
3589  */
3590 static int
3591 processFinished(struct module_qstate* qstate, struct iter_qstate* iq,
3592 	int id)
3593 {
3594 	log_query_info(VERB_QUERY, "finishing processing for",
3595 		&qstate->qinfo);
3596 
3597 	/* store negative cache element for parent side glue. */
3598 	if(!qstate->no_cache_store && iq->query_for_pside_glue
3599 		&& !iq->pside_glue)
3600 			iter_store_parentside_neg(qstate->env, &qstate->qinfo,
3601 				iq->deleg_msg?iq->deleg_msg->rep:
3602 				(iq->response?iq->response->rep:NULL));
3603 	if(!iq->response) {
3604 		verbose(VERB_ALGO, "No response is set, servfail");
3605 		errinf(qstate, "(no response found at query finish)");
3606 		return error_response(qstate, id, LDNS_RCODE_SERVFAIL);
3607 	}
3608 
3609 	/* Make sure that the RA flag is set (since the presence of
3610 	 * this module means that recursion is available) */
3611 	iq->response->rep->flags |= BIT_RA;
3612 
3613 	/* Clear the AA flag */
3614 	/* FIXME: does this action go here or in some other module? */
3615 	iq->response->rep->flags &= ~BIT_AA;
3616 
3617 	/* make sure QR flag is on */
3618 	iq->response->rep->flags |= BIT_QR;
3619 
3620 	/* we have finished processing this query */
3621 	qstate->ext_state[id] = module_finished;
3622 
3623 	/* TODO:  we are using a private TTL, trim the response. */
3624 	/* if (mPrivateTTL > 0){IterUtils.setPrivateTTL(resp, mPrivateTTL); } */
3625 
3626 	/* prepend any items we have accumulated */
3627 	if(iq->an_prepend_list || iq->ns_prepend_list) {
3628 		if(!iter_prepend(iq, iq->response, qstate->region)) {
3629 			log_err("prepend rrsets: out of memory");
3630 			return error_response(qstate, id, LDNS_RCODE_SERVFAIL);
3631 		}
3632 		/* reset the query name back */
3633 		iq->response->qinfo = qstate->qinfo;
3634 		/* the security state depends on the combination */
3635 		iq->response->rep->security = sec_status_unchecked;
3636 		/* store message with the finished prepended items,
3637 		 * but only if we did recursion. The nonrecursion referral
3638 		 * from cache does not need to be stored in the msg cache. */
3639 		if(!qstate->no_cache_store && qstate->query_flags&BIT_RD) {
3640 			iter_dns_store(qstate->env, &qstate->qinfo,
3641 				iq->response->rep, 0, qstate->prefetch_leeway,
3642 				iq->dp&&iq->dp->has_parent_side_NS,
3643 				qstate->region, qstate->query_flags);
3644 		}
3645 	}
3646 	qstate->return_rcode = LDNS_RCODE_NOERROR;
3647 	qstate->return_msg = iq->response;
3648 	return 0;
3649 }
3650 
3651 /*
3652  * Return priming query results to interested super querystates.
3653  *
3654  * Sets the delegation point and delegation message (not nonRD queries).
3655  * This is a callback from walk_supers.
3656  *
3657  * @param qstate: query state that finished.
3658  * @param id: module id.
3659  * @param super: the qstate to inform.
3660  */
3661 void
3662 iter_inform_super(struct module_qstate* qstate, int id,
3663 	struct module_qstate* super)
3664 {
3665 	if(!qstate->is_priming && super->qinfo.qclass == LDNS_RR_CLASS_ANY)
3666 		processClassResponse(qstate, id, super);
3667 	else if(super->qinfo.qtype == LDNS_RR_TYPE_DS && ((struct iter_qstate*)
3668 		super->minfo[id])->state == DSNS_FIND_STATE)
3669 		processDSNSResponse(qstate, id, super);
3670 	else if(qstate->return_rcode != LDNS_RCODE_NOERROR)
3671 		error_supers(qstate, id, super);
3672 	else if(qstate->is_priming)
3673 		prime_supers(qstate, id, super);
3674 	else	processTargetResponse(qstate, id, super);
3675 }
3676 
3677 /**
3678  * Handle iterator state.
3679  * Handle events. This is the real processing loop for events, responsible
3680  * for moving events through the various states. If a processing method
3681  * returns true, then it will be advanced to the next state. If false, then
3682  * processing will stop.
3683  *
3684  * @param qstate: query state.
3685  * @param ie: iterator shared global environment.
3686  * @param iq: iterator query state.
3687  * @param id: module id.
3688  */
3689 static void
3690 iter_handle(struct module_qstate* qstate, struct iter_qstate* iq,
3691 	struct iter_env* ie, int id)
3692 {
3693 	int cont = 1;
3694 	while(cont) {
3695 		verbose(VERB_ALGO, "iter_handle processing q with state %s",
3696 			iter_state_to_string(iq->state));
3697 		switch(iq->state) {
3698 			case INIT_REQUEST_STATE:
3699 				cont = processInitRequest(qstate, iq, ie, id);
3700 				break;
3701 			case INIT_REQUEST_2_STATE:
3702 				cont = processInitRequest2(qstate, iq, id);
3703 				break;
3704 			case INIT_REQUEST_3_STATE:
3705 				cont = processInitRequest3(qstate, iq, id);
3706 				break;
3707 			case QUERYTARGETS_STATE:
3708 				cont = processQueryTargets(qstate, iq, ie, id);
3709 				break;
3710 			case QUERY_RESP_STATE:
3711 				cont = processQueryResponse(qstate, iq, ie, id);
3712 				break;
3713 			case PRIME_RESP_STATE:
3714 				cont = processPrimeResponse(qstate, id);
3715 				break;
3716 			case COLLECT_CLASS_STATE:
3717 				cont = processCollectClass(qstate, id);
3718 				break;
3719 			case DSNS_FIND_STATE:
3720 				cont = processDSNSFind(qstate, iq, id);
3721 				break;
3722 			case FINISHED_STATE:
3723 				cont = processFinished(qstate, iq, id);
3724 				break;
3725 			default:
3726 				log_warn("iterator: invalid state: %d",
3727 					iq->state);
3728 				cont = 0;
3729 				break;
3730 		}
3731 	}
3732 }
3733 
3734 /**
3735  * This is the primary entry point for processing request events. Note that
3736  * this method should only be used by external modules.
3737  * @param qstate: query state.
3738  * @param ie: iterator shared global environment.
3739  * @param iq: iterator query state.
3740  * @param id: module id.
3741  */
3742 static void
3743 process_request(struct module_qstate* qstate, struct iter_qstate* iq,
3744 	struct iter_env* ie, int id)
3745 {
3746 	/* external requests start in the INIT state, and finish using the
3747 	 * FINISHED state. */
3748 	iq->state = INIT_REQUEST_STATE;
3749 	iq->final_state = FINISHED_STATE;
3750 	verbose(VERB_ALGO, "process_request: new external request event");
3751 	iter_handle(qstate, iq, ie, id);
3752 }
3753 
3754 /** process authoritative server reply */
3755 static void
3756 process_response(struct module_qstate* qstate, struct iter_qstate* iq,
3757 	struct iter_env* ie, int id, struct outbound_entry* outbound,
3758 	enum module_ev event)
3759 {
3760 	struct msg_parse* prs;
3761 	struct edns_data edns;
3762 	sldns_buffer* pkt;
3763 
3764 	verbose(VERB_ALGO, "process_response: new external response event");
3765 	iq->response = NULL;
3766 	iq->state = QUERY_RESP_STATE;
3767 	if(event == module_event_noreply || event == module_event_error) {
3768 		if(event == module_event_noreply && iq->timeout_count >= 3 &&
3769 			qstate->env->cfg->use_caps_bits_for_id &&
3770 			!iq->caps_fallback && !is_caps_whitelisted(ie, iq)) {
3771 			/* start fallback */
3772 			iq->caps_fallback = 1;
3773 			iq->caps_server = 0;
3774 			iq->caps_reply = NULL;
3775 			iq->caps_response = NULL;
3776 			iq->caps_minimisation_state = DONOT_MINIMISE_STATE;
3777 			iq->state = QUERYTARGETS_STATE;
3778 			iq->num_current_queries--;
3779 			/* need fresh attempts for the 0x20 fallback, if
3780 			 * that was the cause for the failure */
3781 			iter_dec_attempts(iq->dp, 3, ie->outbound_msg_retry);
3782 			verbose(VERB_DETAIL, "Capsforid: timeouts, starting fallback");
3783 			goto handle_it;
3784 		}
3785 		goto handle_it;
3786 	}
3787 	if( (event != module_event_reply && event != module_event_capsfail)
3788 		|| !qstate->reply) {
3789 		log_err("Bad event combined with response");
3790 		outbound_list_remove(&iq->outlist, outbound);
3791 		errinf(qstate, "module iterator received wrong internal event with a response message");
3792 		(void)error_response(qstate, id, LDNS_RCODE_SERVFAIL);
3793 		return;
3794 	}
3795 
3796 	/* parse message */
3797 	iq->fail_reply = qstate->reply;
3798 	prs = (struct msg_parse*)regional_alloc(qstate->env->scratch,
3799 		sizeof(struct msg_parse));
3800 	if(!prs) {
3801 		log_err("out of memory on incoming message");
3802 		/* like packet got dropped */
3803 		goto handle_it;
3804 	}
3805 	memset(prs, 0, sizeof(*prs));
3806 	memset(&edns, 0, sizeof(edns));
3807 	pkt = qstate->reply->c->buffer;
3808 	sldns_buffer_set_position(pkt, 0);
3809 	if(parse_packet(pkt, prs, qstate->env->scratch) != LDNS_RCODE_NOERROR) {
3810 		verbose(VERB_ALGO, "parse error on reply packet");
3811 		iq->parse_failures++;
3812 		goto handle_it;
3813 	}
3814 	/* edns is not examined, but removed from message to help cache */
3815 	if(parse_extract_edns_from_response_msg(prs, &edns, qstate->env->scratch) !=
3816 		LDNS_RCODE_NOERROR) {
3817 		iq->parse_failures++;
3818 		goto handle_it;
3819 	}
3820 
3821 	/* Copy the edns options we may got from the back end */
3822 	if(edns.opt_list_in) {
3823 		qstate->edns_opts_back_in = edns_opt_copy_region(edns.opt_list_in,
3824 			qstate->region);
3825 		if(!qstate->edns_opts_back_in) {
3826 			log_err("out of memory on incoming message");
3827 			/* like packet got dropped */
3828 			goto handle_it;
3829 		}
3830 		if(!inplace_cb_edns_back_parsed_call(qstate->env, qstate)) {
3831 			log_err("unable to call edns_back_parsed callback");
3832 			goto handle_it;
3833 		}
3834 	}
3835 
3836 	/* remove CD-bit, we asked for in case we handle validation ourself */
3837 	prs->flags &= ~BIT_CD;
3838 
3839 	/* normalize and sanitize: easy to delete items from linked lists */
3840 	if(!scrub_message(pkt, prs, &iq->qinfo_out, iq->dp->name,
3841 		qstate->env->scratch, qstate->env, ie)) {
3842 		/* if 0x20 enabled, start fallback, but we have no message */
3843 		if(event == module_event_capsfail && !iq->caps_fallback) {
3844 			iq->caps_fallback = 1;
3845 			iq->caps_server = 0;
3846 			iq->caps_reply = NULL;
3847 			iq->caps_response = NULL;
3848 			iq->caps_minimisation_state = DONOT_MINIMISE_STATE;
3849 			iq->state = QUERYTARGETS_STATE;
3850 			iq->num_current_queries--;
3851 			verbose(VERB_DETAIL, "Capsforid: scrub failed, starting fallback with no response");
3852 		}
3853 		iq->scrub_failures++;
3854 		goto handle_it;
3855 	}
3856 
3857 	/* allocate response dns_msg in region */
3858 	iq->response = dns_alloc_msg(pkt, prs, qstate->region);
3859 	if(!iq->response)
3860 		goto handle_it;
3861 	log_query_info(VERB_DETAIL, "response for", &qstate->qinfo);
3862 	log_name_addr(VERB_DETAIL, "reply from", iq->dp->name,
3863 		&qstate->reply->addr, qstate->reply->addrlen);
3864 	if(verbosity >= VERB_ALGO)
3865 		log_dns_msg("incoming scrubbed packet:", &iq->response->qinfo,
3866 			iq->response->rep);
3867 
3868 	if(event == module_event_capsfail || iq->caps_fallback) {
3869 		if(qstate->env->cfg->qname_minimisation &&
3870 			iq->minimisation_state != DONOT_MINIMISE_STATE) {
3871 			/* Skip QNAME minimisation for next query, since that
3872 			 * one has to match the current query. */
3873 			iq->minimisation_state = SKIP_MINIMISE_STATE;
3874 		}
3875 		/* for fallback we care about main answer, not additionals */
3876 		/* removing that makes comparison more likely to succeed */
3877 		caps_strip_reply(iq->response->rep);
3878 
3879 		if(iq->caps_fallback &&
3880 			iq->caps_minimisation_state != iq->minimisation_state) {
3881 			/* QNAME minimisation state has changed, restart caps
3882 			 * fallback. */
3883 			iq->caps_fallback = 0;
3884 		}
3885 
3886 		if(!iq->caps_fallback) {
3887 			/* start fallback */
3888 			iq->caps_fallback = 1;
3889 			iq->caps_server = 0;
3890 			iq->caps_reply = iq->response->rep;
3891 			iq->caps_response = iq->response;
3892 			iq->caps_minimisation_state = iq->minimisation_state;
3893 			iq->state = QUERYTARGETS_STATE;
3894 			iq->num_current_queries--;
3895 			verbose(VERB_DETAIL, "Capsforid: starting fallback");
3896 			goto handle_it;
3897 		} else {
3898 			/* check if reply is the same, otherwise, fail */
3899 			if(!iq->caps_reply) {
3900 				iq->caps_reply = iq->response->rep;
3901 				iq->caps_response = iq->response;
3902 				iq->caps_server = -1; /*become zero at ++,
3903 				so that we start the full set of trials */
3904 			} else if(caps_failed_rcode(iq->caps_reply) &&
3905 				!caps_failed_rcode(iq->response->rep)) {
3906 				/* prefer to upgrade to non-SERVFAIL */
3907 				iq->caps_reply = iq->response->rep;
3908 				iq->caps_response = iq->response;
3909 			} else if(!caps_failed_rcode(iq->caps_reply) &&
3910 				caps_failed_rcode(iq->response->rep)) {
3911 				/* if we have non-SERVFAIL as answer then
3912 				 * we can ignore SERVFAILs for the equality
3913 				 * comparison */
3914 				/* no instructions here, skip other else */
3915 			} else if(caps_failed_rcode(iq->caps_reply) &&
3916 				caps_failed_rcode(iq->response->rep)) {
3917 				/* failure is same as other failure in fallbk*/
3918 				/* no instructions here, skip other else */
3919 			} else if(!reply_equal(iq->response->rep, iq->caps_reply,
3920 				qstate->env->scratch)) {
3921 				verbose(VERB_DETAIL, "Capsforid fallback: "
3922 					"getting different replies, failed");
3923 				outbound_list_remove(&iq->outlist, outbound);
3924 				errinf(qstate, "0x20 failed, then got different replies in fallback");
3925 				(void)error_response(qstate, id,
3926 					LDNS_RCODE_SERVFAIL);
3927 				return;
3928 			}
3929 			/* continue the fallback procedure at next server */
3930 			iq->caps_server++;
3931 			iq->state = QUERYTARGETS_STATE;
3932 			iq->num_current_queries--;
3933 			verbose(VERB_DETAIL, "Capsforid: reply is equal. "
3934 				"go to next fallback");
3935 			goto handle_it;
3936 		}
3937 	}
3938 	iq->caps_fallback = 0; /* if we were in fallback, 0x20 is OK now */
3939 
3940 handle_it:
3941 	outbound_list_remove(&iq->outlist, outbound);
3942 	iter_handle(qstate, iq, ie, id);
3943 }
3944 
3945 void
3946 iter_operate(struct module_qstate* qstate, enum module_ev event, int id,
3947 	struct outbound_entry* outbound)
3948 {
3949 	struct iter_env* ie = (struct iter_env*)qstate->env->modinfo[id];
3950 	struct iter_qstate* iq = (struct iter_qstate*)qstate->minfo[id];
3951 	verbose(VERB_QUERY, "iterator[module %d] operate: extstate:%s event:%s",
3952 		id, strextstate(qstate->ext_state[id]), strmodulevent(event));
3953 	if(iq) log_query_info(VERB_QUERY, "iterator operate: query",
3954 		&qstate->qinfo);
3955 	if(iq && qstate->qinfo.qname != iq->qchase.qname)
3956 		log_query_info(VERB_QUERY, "iterator operate: chased to",
3957 			&iq->qchase);
3958 
3959 	/* perform iterator state machine */
3960 	if((event == module_event_new || event == module_event_pass) &&
3961 		iq == NULL) {
3962 		if(!iter_new(qstate, id)) {
3963 			errinf(qstate, "malloc failure, new iterator module allocation");
3964 			(void)error_response(qstate, id, LDNS_RCODE_SERVFAIL);
3965 			return;
3966 		}
3967 		iq = (struct iter_qstate*)qstate->minfo[id];
3968 		process_request(qstate, iq, ie, id);
3969 		return;
3970 	}
3971 	if(iq && event == module_event_pass) {
3972 		iter_handle(qstate, iq, ie, id);
3973 		return;
3974 	}
3975 	if(iq && outbound) {
3976 		process_response(qstate, iq, ie, id, outbound, event);
3977 		return;
3978 	}
3979 	if(event == module_event_error) {
3980 		verbose(VERB_ALGO, "got called with event error, giving up");
3981 		errinf(qstate, "iterator module got the error event");
3982 		(void)error_response(qstate, id, LDNS_RCODE_SERVFAIL);
3983 		return;
3984 	}
3985 
3986 	log_err("bad event for iterator");
3987 	errinf(qstate, "iterator module received wrong event");
3988 	(void)error_response(qstate, id, LDNS_RCODE_SERVFAIL);
3989 }
3990 
3991 void
3992 iter_clear(struct module_qstate* qstate, int id)
3993 {
3994 	struct iter_qstate* iq;
3995 	if(!qstate)
3996 		return;
3997 	iq = (struct iter_qstate*)qstate->minfo[id];
3998 	if(iq) {
3999 		outbound_list_clear(&iq->outlist);
4000 		if(iq->target_count && --iq->target_count[0] == 0)
4001 			free(iq->target_count);
4002 		iq->num_current_queries = 0;
4003 	}
4004 	qstate->minfo[id] = NULL;
4005 }
4006 
4007 size_t
4008 iter_get_mem(struct module_env* env, int id)
4009 {
4010 	struct iter_env* ie = (struct iter_env*)env->modinfo[id];
4011 	if(!ie)
4012 		return 0;
4013 	return sizeof(*ie) + sizeof(int)*((size_t)ie->max_dependency_depth+1)
4014 		+ donotq_get_mem(ie->donotq) + priv_get_mem(ie->priv);
4015 }
4016 
4017 /**
4018  * The iterator function block
4019  */
4020 static struct module_func_block iter_block = {
4021 	"iterator",
4022 	&iter_init, &iter_deinit, &iter_operate, &iter_inform_super,
4023 	&iter_clear, &iter_get_mem
4024 };
4025 
4026 struct module_func_block*
4027 iter_get_funcblock(void)
4028 {
4029 	return &iter_block;
4030 }
4031 
4032 const char*
4033 iter_state_to_string(enum iter_state state)
4034 {
4035 	switch (state)
4036 	{
4037 	case INIT_REQUEST_STATE :
4038 		return "INIT REQUEST STATE";
4039 	case INIT_REQUEST_2_STATE :
4040 		return "INIT REQUEST STATE (stage 2)";
4041 	case INIT_REQUEST_3_STATE:
4042 		return "INIT REQUEST STATE (stage 3)";
4043 	case QUERYTARGETS_STATE :
4044 		return "QUERY TARGETS STATE";
4045 	case PRIME_RESP_STATE :
4046 		return "PRIME RESPONSE STATE";
4047 	case COLLECT_CLASS_STATE :
4048 		return "COLLECT CLASS STATE";
4049 	case DSNS_FIND_STATE :
4050 		return "DSNS FIND STATE";
4051 	case QUERY_RESP_STATE :
4052 		return "QUERY RESPONSE STATE";
4053 	case FINISHED_STATE :
4054 		return "FINISHED RESPONSE STATE";
4055 	default :
4056 		return "UNKNOWN ITER STATE";
4057 	}
4058 }
4059 
4060 int
4061 iter_state_is_responsestate(enum iter_state s)
4062 {
4063 	switch(s) {
4064 		case INIT_REQUEST_STATE :
4065 		case INIT_REQUEST_2_STATE :
4066 		case INIT_REQUEST_3_STATE :
4067 		case QUERYTARGETS_STATE :
4068 		case COLLECT_CLASS_STATE :
4069 			return 0;
4070 		default:
4071 			break;
4072 	}
4073 	return 1;
4074 }
4075