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