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