xref: /freebsd/contrib/unbound/iterator/iterator.c (revision cc16dea626cf2fc80cde667ac4798065108e596c)
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 LIMITED
25  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
26  * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE
27  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
28  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
29  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
30  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
31  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
32  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
33  * POSSIBILITY OF SUCH DAMAGE.
34  */
35 
36 /**
37  * \file
38  *
39  * This file contains a module that performs recusive iterative DNS query
40  * processing.
41  */
42 
43 #include "config.h"
44 #include <ldns/ldns.h>
45 #include "iterator/iterator.h"
46 #include "iterator/iter_utils.h"
47 #include "iterator/iter_hints.h"
48 #include "iterator/iter_fwd.h"
49 #include "iterator/iter_donotq.h"
50 #include "iterator/iter_delegpt.h"
51 #include "iterator/iter_resptype.h"
52 #include "iterator/iter_scrub.h"
53 #include "iterator/iter_priv.h"
54 #include "validator/val_neg.h"
55 #include "services/cache/dns.h"
56 #include "services/cache/infra.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 
66 int
67 iter_init(struct module_env* env, int id)
68 {
69 	struct iter_env* iter_env = (struct iter_env*)calloc(1,
70 		sizeof(struct iter_env));
71 	if(!iter_env) {
72 		log_err("malloc failure");
73 		return 0;
74 	}
75 	env->modinfo[id] = (void*)iter_env;
76 	if(!iter_apply_cfg(iter_env, env->cfg)) {
77 		log_err("iterator: could not apply configuration settings.");
78 		return 0;
79 	}
80 	return 1;
81 }
82 
83 void
84 iter_deinit(struct module_env* env, int id)
85 {
86 	struct iter_env* iter_env;
87 	if(!env || !env->modinfo[id])
88 		return;
89 	iter_env = (struct iter_env*)env->modinfo[id];
90 	free(iter_env->target_fetch_policy);
91 	priv_delete(iter_env->priv);
92 	donotq_delete(iter_env->donotq);
93 	free(iter_env);
94 	env->modinfo[id] = NULL;
95 }
96 
97 /** new query for iterator */
98 static int
99 iter_new(struct module_qstate* qstate, int id)
100 {
101 	struct iter_qstate* iq = (struct iter_qstate*)regional_alloc(
102 		qstate->region, sizeof(struct iter_qstate));
103 	qstate->minfo[id] = iq;
104 	if(!iq)
105 		return 0;
106 	memset(iq, 0, sizeof(*iq));
107 	iq->state = INIT_REQUEST_STATE;
108 	iq->final_state = FINISHED_STATE;
109 	iq->an_prepend_list = NULL;
110 	iq->an_prepend_last = NULL;
111 	iq->ns_prepend_list = NULL;
112 	iq->ns_prepend_last = NULL;
113 	iq->dp = NULL;
114 	iq->depth = 0;
115 	iq->num_target_queries = 0;
116 	iq->num_current_queries = 0;
117 	iq->query_restart_count = 0;
118 	iq->referral_count = 0;
119 	iq->sent_count = 0;
120 	iq->wait_priming_stub = 0;
121 	iq->refetch_glue = 0;
122 	iq->dnssec_expected = 0;
123 	iq->dnssec_lame_query = 0;
124 	iq->chase_flags = qstate->query_flags;
125 	/* Start with the (current) qname. */
126 	iq->qchase = qstate->qinfo;
127 	outbound_list_init(&iq->outlist);
128 	return 1;
129 }
130 
131 /**
132  * Transition to the next state. This can be used to advance a currently
133  * processing event. It cannot be used to reactivate a forEvent.
134  *
135  * @param iq: iterator query state
136  * @param nextstate The state to transition to.
137  * @return true. This is so this can be called as the return value for the
138  *         actual process*State() methods. (Transitioning to the next state
139  *         implies further processing).
140  */
141 static int
142 next_state(struct iter_qstate* iq, enum iter_state nextstate)
143 {
144 	/* If transitioning to a "response" state, make sure that there is a
145 	 * response */
146 	if(iter_state_is_responsestate(nextstate)) {
147 		if(iq->response == NULL) {
148 			log_err("transitioning to response state sans "
149 				"response.");
150 		}
151 	}
152 	iq->state = nextstate;
153 	return 1;
154 }
155 
156 /**
157  * Transition an event to its final state. Final states always either return
158  * a result up the module chain, or reactivate a dependent event. Which
159  * final state to transtion to is set in the module state for the event when
160  * it was created, and depends on the original purpose of the event.
161  *
162  * The response is stored in the qstate->buf buffer.
163  *
164  * @param iq: iterator query state
165  * @return false. This is so this method can be used as the return value for
166  *         the processState methods. (Transitioning to the final state
167  */
168 static int
169 final_state(struct iter_qstate* iq)
170 {
171 	return next_state(iq, iq->final_state);
172 }
173 
174 /**
175  * Callback routine to handle errors in parent query states
176  * @param qstate: query state that failed.
177  * @param id: module id.
178  * @param super: super state.
179  */
180 static void
181 error_supers(struct module_qstate* qstate, int id, struct module_qstate* super)
182 {
183 	struct iter_qstate* super_iq = (struct iter_qstate*)super->minfo[id];
184 
185 	if(qstate->qinfo.qtype == LDNS_RR_TYPE_A ||
186 		qstate->qinfo.qtype == LDNS_RR_TYPE_AAAA) {
187 		/* mark address as failed. */
188 		struct delegpt_ns* dpns = NULL;
189 		if(super_iq->dp)
190 			dpns = delegpt_find_ns(super_iq->dp,
191 				qstate->qinfo.qname, qstate->qinfo.qname_len);
192 		if(!dpns) {
193 			/* not interested */
194 			verbose(VERB_ALGO, "subq error, but not interested");
195 			log_query_info(VERB_ALGO, "superq", &super->qinfo);
196 			if(super_iq->dp)
197 				delegpt_log(VERB_ALGO, super_iq->dp);
198 			log_assert(0);
199 			return;
200 		} else {
201 			/* see if the failure did get (parent-lame) info */
202 			if(!cache_fill_missing(super->env,
203 				super_iq->qchase.qclass, super->region,
204 				super_iq->dp))
205 				log_err("out of memory adding missing");
206 		}
207 		dpns->resolved = 1; /* mark as failed */
208 		super_iq->num_target_queries--;
209 	}
210 	if(qstate->qinfo.qtype == LDNS_RR_TYPE_NS) {
211 		/* prime failed to get delegation */
212 		super_iq->dp = NULL;
213 	}
214 	/* evaluate targets again */
215 	super_iq->state = QUERYTARGETS_STATE;
216 	/* super becomes runnable, and will process this change */
217 }
218 
219 /**
220  * Return an error to the client
221  * @param qstate: our query state
222  * @param id: module id
223  * @param rcode: error code (DNS errcode).
224  * @return: 0 for use by caller, to make notation easy, like:
225  * 	return error_response(..).
226  */
227 static int
228 error_response(struct module_qstate* qstate, int id, int rcode)
229 {
230 	verbose(VERB_QUERY, "return error response %s",
231 		ldns_lookup_by_id(ldns_rcodes, rcode)?
232 		ldns_lookup_by_id(ldns_rcodes, rcode)->name:"??");
233 	qstate->return_rcode = rcode;
234 	qstate->return_msg = NULL;
235 	qstate->ext_state[id] = module_finished;
236 	return 0;
237 }
238 
239 /**
240  * Return an error to the client and cache the error code in the
241  * message cache (so per qname, qtype, qclass).
242  * @param qstate: our query state
243  * @param id: module id
244  * @param rcode: error code (DNS errcode).
245  * @return: 0 for use by caller, to make notation easy, like:
246  * 	return error_response(..).
247  */
248 static int
249 error_response_cache(struct module_qstate* qstate, int id, int rcode)
250 {
251 	/* store in cache */
252 	struct reply_info err;
253 	memset(&err, 0, sizeof(err));
254 	err.flags = (uint16_t)(BIT_QR | BIT_RA);
255 	FLAGS_SET_RCODE(err.flags, rcode);
256 	err.qdcount = 1;
257 	err.ttl = NORR_TTL;
258 	err.prefetch_ttl = PREFETCH_TTL_CALC(err.ttl);
259 	/* do not waste time trying to validate this servfail */
260 	err.security = sec_status_indeterminate;
261 	verbose(VERB_ALGO, "store error response in message cache");
262 	iter_dns_store(qstate->env, &qstate->qinfo, &err, 0, 0, 0, NULL);
263 	return error_response(qstate, id, rcode);
264 }
265 
266 /** check if prepend item is duplicate item */
267 static int
268 prepend_is_duplicate(struct ub_packed_rrset_key** sets, size_t to,
269 	struct ub_packed_rrset_key* dup)
270 {
271 	size_t i;
272 	for(i=0; i<to; i++) {
273 		if(sets[i]->rk.type == dup->rk.type &&
274 			sets[i]->rk.rrset_class == dup->rk.rrset_class &&
275 			sets[i]->rk.dname_len == dup->rk.dname_len &&
276 			query_dname_compare(sets[i]->rk.dname, dup->rk.dname)
277 			== 0)
278 			return 1;
279 	}
280 	return 0;
281 }
282 
283 /** prepend the prepend list in the answer and authority section of dns_msg */
284 static int
285 iter_prepend(struct iter_qstate* iq, struct dns_msg* msg,
286 	struct regional* region)
287 {
288 	struct iter_prep_list* p;
289 	struct ub_packed_rrset_key** sets;
290 	size_t num_an = 0, num_ns = 0;;
291 	for(p = iq->an_prepend_list; p; p = p->next)
292 		num_an++;
293 	for(p = iq->ns_prepend_list; p; p = p->next)
294 		num_ns++;
295 	if(num_an + num_ns == 0)
296 		return 1;
297 	verbose(VERB_ALGO, "prepending %d rrsets", (int)num_an + (int)num_ns);
298 	sets = regional_alloc(region, (num_an+num_ns+msg->rep->rrset_count) *
299 		sizeof(struct ub_packed_rrset_key*));
300 	if(!sets)
301 		return 0;
302 	/* ANSWER section */
303 	num_an = 0;
304 	for(p = iq->an_prepend_list; p; p = p->next) {
305 		sets[num_an++] = p->rrset;
306 	}
307 	memcpy(sets+num_an, msg->rep->rrsets, msg->rep->an_numrrsets *
308 		sizeof(struct ub_packed_rrset_key*));
309 	/* AUTH section */
310 	num_ns = 0;
311 	for(p = iq->ns_prepend_list; p; p = p->next) {
312 		if(prepend_is_duplicate(sets+msg->rep->an_numrrsets+num_an,
313 			num_ns, p->rrset) || prepend_is_duplicate(
314 			msg->rep->rrsets+msg->rep->an_numrrsets,
315 			msg->rep->ns_numrrsets, p->rrset))
316 			continue;
317 		sets[msg->rep->an_numrrsets + num_an + num_ns++] = p->rrset;
318 	}
319 	memcpy(sets + num_an + msg->rep->an_numrrsets + num_ns,
320 		msg->rep->rrsets + msg->rep->an_numrrsets,
321 		(msg->rep->ns_numrrsets + msg->rep->ar_numrrsets) *
322 		sizeof(struct ub_packed_rrset_key*));
323 
324 	/* NXDOMAIN rcode can stay if we prepended DNAME/CNAMEs, because
325 	 * this is what recursors should give. */
326 	msg->rep->rrset_count += num_an + num_ns;
327 	msg->rep->an_numrrsets += num_an;
328 	msg->rep->ns_numrrsets += num_ns;
329 	msg->rep->rrsets = sets;
330 	return 1;
331 }
332 
333 /**
334  * Add rrset to ANSWER prepend list
335  * @param qstate: query state.
336  * @param iq: iterator query state.
337  * @param rrset: rrset to add.
338  * @return false on failure (malloc).
339  */
340 static int
341 iter_add_prepend_answer(struct module_qstate* qstate, struct iter_qstate* iq,
342 	struct ub_packed_rrset_key* rrset)
343 {
344 	struct iter_prep_list* p = (struct iter_prep_list*)regional_alloc(
345 		qstate->region, sizeof(struct iter_prep_list));
346 	if(!p)
347 		return 0;
348 	p->rrset = rrset;
349 	p->next = NULL;
350 	/* add at end */
351 	if(iq->an_prepend_last)
352 		iq->an_prepend_last->next = p;
353 	else	iq->an_prepend_list = p;
354 	iq->an_prepend_last = p;
355 	return 1;
356 }
357 
358 /**
359  * Add rrset to AUTHORITY prepend list
360  * @param qstate: query state.
361  * @param iq: iterator query state.
362  * @param rrset: rrset to add.
363  * @return false on failure (malloc).
364  */
365 static int
366 iter_add_prepend_auth(struct module_qstate* qstate, struct iter_qstate* iq,
367 	struct ub_packed_rrset_key* rrset)
368 {
369 	struct iter_prep_list* p = (struct iter_prep_list*)regional_alloc(
370 		qstate->region, sizeof(struct iter_prep_list));
371 	if(!p)
372 		return 0;
373 	p->rrset = rrset;
374 	p->next = NULL;
375 	/* add at end */
376 	if(iq->ns_prepend_last)
377 		iq->ns_prepend_last->next = p;
378 	else	iq->ns_prepend_list = p;
379 	iq->ns_prepend_last = p;
380 	return 1;
381 }
382 
383 /**
384  * Given a CNAME response (defined as a response containing a CNAME or DNAME
385  * that does not answer the request), process the response, modifying the
386  * state as necessary. This follows the CNAME/DNAME chain and returns the
387  * final query name.
388  *
389  * sets the new query name, after following the CNAME/DNAME chain.
390  * @param qstate: query state.
391  * @param iq: iterator query state.
392  * @param msg: the response.
393  * @param mname: returned target new query name.
394  * @param mname_len: length of mname.
395  * @return false on (malloc) error.
396  */
397 static int
398 handle_cname_response(struct module_qstate* qstate, struct iter_qstate* iq,
399         struct dns_msg* msg, uint8_t** mname, size_t* mname_len)
400 {
401 	size_t i;
402 	/* Start with the (current) qname. */
403 	*mname = iq->qchase.qname;
404 	*mname_len = iq->qchase.qname_len;
405 
406 	/* Iterate over the ANSWER rrsets in order, looking for CNAMEs and
407 	 * DNAMES. */
408 	for(i=0; i<msg->rep->an_numrrsets; i++) {
409 		struct ub_packed_rrset_key* r = msg->rep->rrsets[i];
410 		/* If there is a (relevant) DNAME, add it to the list.
411 		 * We always expect there to be CNAME that was generated
412 		 * by this DNAME following, so we don't process the DNAME
413 		 * directly.  */
414 		if(ntohs(r->rk.type) == LDNS_RR_TYPE_DNAME &&
415 			dname_strict_subdomain_c(*mname, r->rk.dname)) {
416 			if(!iter_add_prepend_answer(qstate, iq, r))
417 				return 0;
418 			continue;
419 		}
420 
421 		if(ntohs(r->rk.type) == LDNS_RR_TYPE_CNAME &&
422 			query_dname_compare(*mname, r->rk.dname) == 0) {
423 			/* Add this relevant CNAME rrset to the prepend list.*/
424 			if(!iter_add_prepend_answer(qstate, iq, r))
425 				return 0;
426 			get_cname_target(r, mname, mname_len);
427 		}
428 
429 		/* Other rrsets in the section are ignored. */
430 	}
431 	/* add authority rrsets to authority prepend, for wildcarded CNAMEs */
432 	for(i=msg->rep->an_numrrsets; i<msg->rep->an_numrrsets +
433 		msg->rep->ns_numrrsets; i++) {
434 		struct ub_packed_rrset_key* r = msg->rep->rrsets[i];
435 		/* only add NSEC/NSEC3, as they may be needed for validation */
436 		if(ntohs(r->rk.type) == LDNS_RR_TYPE_NSEC ||
437 			ntohs(r->rk.type) == LDNS_RR_TYPE_NSEC3) {
438 			if(!iter_add_prepend_auth(qstate, iq, r))
439 				return 0;
440 		}
441 	}
442 	return 1;
443 }
444 
445 /**
446  * Generate a subrequest.
447  * Generate a local request event. Local events are tied to this module, and
448  * have a correponding (first tier) event that is waiting for this event to
449  * resolve to continue.
450  *
451  * @param qname The query name for this request.
452  * @param qnamelen length of qname
453  * @param qtype The query type for this request.
454  * @param qclass The query class for this request.
455  * @param qstate The event that is generating this event.
456  * @param id: module id.
457  * @param iq: The iterator state that is generating this event.
458  * @param initial_state The initial response state (normally this
459  *          is QUERY_RESP_STATE, unless it is known that the request won't
460  *          need iterative processing
461  * @param finalstate The final state for the response to this request.
462  * @param subq_ret: if newly allocated, the subquerystate, or NULL if it does
463  * 	not need initialisation.
464  * @param v: if true, validation is done on the subquery.
465  * @return false on error (malloc).
466  */
467 static int
468 generate_sub_request(uint8_t* qname, size_t qnamelen, uint16_t qtype,
469 	uint16_t qclass, struct module_qstate* qstate, int id,
470 	struct iter_qstate* iq, enum iter_state initial_state,
471 	enum iter_state finalstate, struct module_qstate** subq_ret, int v)
472 {
473 	struct module_qstate* subq = NULL;
474 	struct iter_qstate* subiq = NULL;
475 	uint16_t qflags = 0; /* OPCODE QUERY, no flags */
476 	struct query_info qinf;
477 	int prime = (finalstate == PRIME_RESP_STATE)?1:0;
478 	qinf.qname = qname;
479 	qinf.qname_len = qnamelen;
480 	qinf.qtype = qtype;
481 	qinf.qclass = qclass;
482 
483 	/* RD should be set only when sending the query back through the INIT
484 	 * state. */
485 	if(initial_state == INIT_REQUEST_STATE)
486 		qflags |= BIT_RD;
487 	/* We set the CD flag so we can send this through the "head" of
488 	 * the resolution chain, which might have a validator. We are
489 	 * uninterested in validating things not on the direct resolution
490 	 * path.  */
491 	if(!v)
492 		qflags |= BIT_CD;
493 
494 	/* attach subquery, lookup existing or make a new one */
495 	fptr_ok(fptr_whitelist_modenv_attach_sub(qstate->env->attach_sub));
496 	if(!(*qstate->env->attach_sub)(qstate, &qinf, qflags, prime, &subq)) {
497 		return 0;
498 	}
499 	*subq_ret = subq;
500 	if(subq) {
501 		/* initialise the new subquery */
502 		subq->curmod = id;
503 		subq->ext_state[id] = module_state_initial;
504 		subq->minfo[id] = regional_alloc(subq->region,
505 			sizeof(struct iter_qstate));
506 		if(!subq->minfo[id]) {
507 			log_err("init subq: out of memory");
508 			fptr_ok(fptr_whitelist_modenv_kill_sub(
509 				qstate->env->kill_sub));
510 			(*qstate->env->kill_sub)(subq);
511 			return 0;
512 		}
513 		subiq = (struct iter_qstate*)subq->minfo[id];
514 		memset(subiq, 0, sizeof(*subiq));
515 		subiq->num_target_queries = 0;
516 		subiq->num_current_queries = 0;
517 		subiq->depth = iq->depth+1;
518 		outbound_list_init(&subiq->outlist);
519 		subiq->state = initial_state;
520 		subiq->final_state = finalstate;
521 		subiq->qchase = subq->qinfo;
522 		subiq->chase_flags = subq->query_flags;
523 		subiq->refetch_glue = 0;
524 	}
525 	return 1;
526 }
527 
528 /**
529  * Generate and send a root priming request.
530  * @param qstate: the qtstate that triggered the need to prime.
531  * @param iq: iterator query state.
532  * @param id: module id.
533  * @param qclass: the class to prime.
534  * @return 0 on failure
535  */
536 static int
537 prime_root(struct module_qstate* qstate, struct iter_qstate* iq, int id,
538 	uint16_t qclass)
539 {
540 	struct delegpt* dp;
541 	struct module_qstate* subq;
542 	verbose(VERB_DETAIL, "priming . %s NS",
543 		ldns_lookup_by_id(ldns_rr_classes, (int)qclass)?
544 		ldns_lookup_by_id(ldns_rr_classes, (int)qclass)->name:"??");
545 	dp = hints_lookup_root(qstate->env->hints, qclass);
546 	if(!dp) {
547 		verbose(VERB_ALGO, "Cannot prime due to lack of hints");
548 		return 0;
549 	}
550 	/* Priming requests start at the QUERYTARGETS state, skipping
551 	 * the normal INIT state logic (which would cause an infloop). */
552 	if(!generate_sub_request((uint8_t*)"\000", 1, LDNS_RR_TYPE_NS,
553 		qclass, qstate, id, iq, QUERYTARGETS_STATE, PRIME_RESP_STATE,
554 		&subq, 0)) {
555 		verbose(VERB_ALGO, "could not prime root");
556 		return 0;
557 	}
558 	if(subq) {
559 		struct iter_qstate* subiq =
560 			(struct iter_qstate*)subq->minfo[id];
561 		/* Set the initial delegation point to the hint.
562 		 * copy dp, it is now part of the root prime query.
563 		 * dp was part of in the fixed hints structure. */
564 		subiq->dp = delegpt_copy(dp, subq->region);
565 		if(!subiq->dp) {
566 			log_err("out of memory priming root, copydp");
567 			fptr_ok(fptr_whitelist_modenv_kill_sub(
568 				qstate->env->kill_sub));
569 			(*qstate->env->kill_sub)(subq);
570 			return 0;
571 		}
572 		/* there should not be any target queries. */
573 		subiq->num_target_queries = 0;
574 		subiq->dnssec_expected = iter_indicates_dnssec(
575 			qstate->env, subiq->dp, NULL, subq->qinfo.qclass);
576 	}
577 
578 	/* this module stops, our submodule starts, and does the query. */
579 	qstate->ext_state[id] = module_wait_subquery;
580 	return 1;
581 }
582 
583 /**
584  * Generate and process a stub priming request. This method tests for the
585  * need to prime a stub zone, so it is safe to call for every request.
586  *
587  * @param qstate: the qtstate that triggered the need to prime.
588  * @param iq: iterator query state.
589  * @param id: module id.
590  * @param qname: request name.
591  * @param qclass: request class.
592  * @return true if a priming subrequest was made, false if not. The will only
593  *         issue a priming request if it detects an unprimed stub.
594  *         Uses value of 2 to signal during stub-prime in root-prime situation
595  *         that a noprime-stub is available and resolution can continue.
596  */
597 static int
598 prime_stub(struct module_qstate* qstate, struct iter_qstate* iq, int id,
599 	uint8_t* qname, uint16_t qclass)
600 {
601 	/* Lookup the stub hint. This will return null if the stub doesn't
602 	 * need to be re-primed. */
603 	struct iter_hints_stub* stub;
604 	struct delegpt* stub_dp;
605 	struct module_qstate* subq;
606 
607 	if(!qname) return 0;
608 	stub = hints_lookup_stub(qstate->env->hints, qname, qclass, iq->dp);
609 	/* The stub (if there is one) does not need priming. */
610 	if(!stub)
611 		return 0;
612 	stub_dp = stub->dp;
613 
614 	/* is it a noprime stub (always use) */
615 	if(stub->noprime) {
616 		int r = 0;
617 		if(iq->dp == NULL) r = 2;
618 		/* copy the dp out of the fixed hints structure, so that
619 		 * it can be changed when servicing this query */
620 		iq->dp = delegpt_copy(stub_dp, qstate->region);
621 		if(!iq->dp) {
622 			log_err("out of memory priming stub");
623 			(void)error_response(qstate, id, LDNS_RCODE_SERVFAIL);
624 			return 1; /* return 1 to make module stop, with error */
625 		}
626 		log_nametypeclass(VERB_DETAIL, "use stub", stub_dp->name,
627 			LDNS_RR_TYPE_NS, qclass);
628 		return r;
629 	}
630 
631 	/* Otherwise, we need to (re)prime the stub. */
632 	log_nametypeclass(VERB_DETAIL, "priming stub", stub_dp->name,
633 		LDNS_RR_TYPE_NS, qclass);
634 
635 	/* Stub priming events start at the QUERYTARGETS state to avoid the
636 	 * redundant INIT state processing. */
637 	if(!generate_sub_request(stub_dp->name, stub_dp->namelen,
638 		LDNS_RR_TYPE_NS, qclass, qstate, id, iq,
639 		QUERYTARGETS_STATE, PRIME_RESP_STATE, &subq, 0)) {
640 		verbose(VERB_ALGO, "could not prime stub");
641 		(void)error_response(qstate, id, LDNS_RCODE_SERVFAIL);
642 		return 1; /* return 1 to make module stop, with error */
643 	}
644 	if(subq) {
645 		struct iter_qstate* subiq =
646 			(struct iter_qstate*)subq->minfo[id];
647 
648 		/* Set the initial delegation point to the hint. */
649 		/* make copy to avoid use of stub dp by different qs/threads */
650 		subiq->dp = delegpt_copy(stub_dp, subq->region);
651 		if(!subiq->dp) {
652 			log_err("out of memory priming stub, copydp");
653 			fptr_ok(fptr_whitelist_modenv_kill_sub(
654 				qstate->env->kill_sub));
655 			(*qstate->env->kill_sub)(subq);
656 			(void)error_response(qstate, id, LDNS_RCODE_SERVFAIL);
657 			return 1; /* return 1 to make module stop, with error */
658 		}
659 		/* there should not be any target queries -- although there
660 		 * wouldn't be anyway, since stub hints never have
661 		 * missing targets. */
662 		subiq->num_target_queries = 0;
663 		subiq->wait_priming_stub = 1;
664 		subiq->dnssec_expected = iter_indicates_dnssec(
665 			qstate->env, subiq->dp, NULL, subq->qinfo.qclass);
666 	}
667 
668 	/* this module stops, our submodule starts, and does the query. */
669 	qstate->ext_state[id] = module_wait_subquery;
670 	return 1;
671 }
672 
673 /**
674  * Generate A and AAAA checks for glue that is in-zone for the referral
675  * we just got to obtain authoritative information on the adresses.
676  *
677  * @param qstate: the qtstate that triggered the need to prime.
678  * @param iq: iterator query state.
679  * @param id: module id.
680  */
681 static void
682 generate_a_aaaa_check(struct module_qstate* qstate, struct iter_qstate* iq,
683 	int id)
684 {
685 	struct iter_env* ie = (struct iter_env*)qstate->env->modinfo[id];
686 	struct module_qstate* subq;
687 	size_t i;
688 	struct reply_info* rep = iq->response->rep;
689 	struct ub_packed_rrset_key* s;
690 	log_assert(iq->dp);
691 
692 	if(iq->depth == ie->max_dependency_depth)
693 		return;
694 	/* walk through additional, and check if in-zone,
695 	 * only relevant A, AAAA are left after scrub anyway */
696 	for(i=rep->an_numrrsets+rep->ns_numrrsets; i<rep->rrset_count; i++) {
697 		s = rep->rrsets[i];
698 		/* check *ALL* addresses that are transmitted in additional*/
699 		/* is it an address ? */
700 		if( !(ntohs(s->rk.type)==LDNS_RR_TYPE_A ||
701 			ntohs(s->rk.type)==LDNS_RR_TYPE_AAAA)) {
702 			continue;
703 		}
704 		/* is this query the same as the A/AAAA check for it */
705 		if(qstate->qinfo.qtype == ntohs(s->rk.type) &&
706 			qstate->qinfo.qclass == ntohs(s->rk.rrset_class) &&
707 			query_dname_compare(qstate->qinfo.qname,
708 				s->rk.dname)==0 &&
709 			(qstate->query_flags&BIT_RD) &&
710 			!(qstate->query_flags&BIT_CD))
711 			continue;
712 
713 		/* generate subrequest for it */
714 		log_nametypeclass(VERB_ALGO, "schedule addr fetch",
715 			s->rk.dname, ntohs(s->rk.type),
716 			ntohs(s->rk.rrset_class));
717 		if(!generate_sub_request(s->rk.dname, s->rk.dname_len,
718 			ntohs(s->rk.type), ntohs(s->rk.rrset_class),
719 			qstate, id, iq,
720 			INIT_REQUEST_STATE, FINISHED_STATE, &subq, 1)) {
721 			verbose(VERB_ALGO, "could not generate addr check");
722 			return;
723 		}
724 		/* ignore subq - not need for more init */
725 	}
726 }
727 
728 /**
729  * Generate a NS check request to obtain authoritative information
730  * on an NS rrset.
731  *
732  * @param qstate: the qtstate that triggered the need to prime.
733  * @param iq: iterator query state.
734  * @param id: module id.
735  */
736 static void
737 generate_ns_check(struct module_qstate* qstate, struct iter_qstate* iq, int id)
738 {
739 	struct iter_env* ie = (struct iter_env*)qstate->env->modinfo[id];
740 	struct module_qstate* subq;
741 	log_assert(iq->dp);
742 
743 	if(iq->depth == ie->max_dependency_depth)
744 		return;
745 	/* is this query the same as the nscheck? */
746 	if(qstate->qinfo.qtype == LDNS_RR_TYPE_NS &&
747 		query_dname_compare(iq->dp->name, qstate->qinfo.qname)==0 &&
748 		(qstate->query_flags&BIT_RD) && !(qstate->query_flags&BIT_CD)){
749 		/* spawn off A, AAAA queries for in-zone glue to check */
750 		generate_a_aaaa_check(qstate, iq, id);
751 		return;
752 	}
753 
754 	log_nametypeclass(VERB_ALGO, "schedule ns fetch",
755 		iq->dp->name, LDNS_RR_TYPE_NS, iq->qchase.qclass);
756 	if(!generate_sub_request(iq->dp->name, iq->dp->namelen,
757 		LDNS_RR_TYPE_NS, iq->qchase.qclass, qstate, id, iq,
758 		INIT_REQUEST_STATE, FINISHED_STATE, &subq, 1)) {
759 		verbose(VERB_ALGO, "could not generate ns check");
760 		return;
761 	}
762 	if(subq) {
763 		struct iter_qstate* subiq =
764 			(struct iter_qstate*)subq->minfo[id];
765 
766 		/* make copy to avoid use of stub dp by different qs/threads */
767 		/* refetch glue to start higher up the tree */
768 		subiq->refetch_glue = 1;
769 		subiq->dp = delegpt_copy(iq->dp, subq->region);
770 		if(!subiq->dp) {
771 			log_err("out of memory generating ns check, copydp");
772 			fptr_ok(fptr_whitelist_modenv_kill_sub(
773 				qstate->env->kill_sub));
774 			(*qstate->env->kill_sub)(subq);
775 			return;
776 		}
777 	}
778 }
779 
780 /**
781  * Generate a DNSKEY prefetch query to get the DNSKEY for the DS record we
782  * just got in a referral (where we have dnssec_expected, thus have trust
783  * anchors above it).  Note that right after calling this routine the
784  * iterator detached subqueries (because of following the referral), and thus
785  * the DNSKEY query becomes detached, its return stored in the cache for
786  * later lookup by the validator.  This cache lookup by the validator avoids
787  * the roundtrip incurred by the DNSKEY query.  The DNSKEY query is now
788  * performed at about the same time the original query is sent to the domain,
789  * thus the two answers are likely to be returned at about the same time,
790  * saving a roundtrip from the validated lookup.
791  *
792  * @param qstate: the qtstate that triggered the need to prime.
793  * @param iq: iterator query state.
794  * @param id: module id.
795  */
796 static void
797 generate_dnskey_prefetch(struct module_qstate* qstate,
798 	struct iter_qstate* iq, int id)
799 {
800 	struct module_qstate* subq;
801 	log_assert(iq->dp);
802 
803 	/* is this query the same as the prefetch? */
804 	if(qstate->qinfo.qtype == LDNS_RR_TYPE_DNSKEY &&
805 		query_dname_compare(iq->dp->name, qstate->qinfo.qname)==0 &&
806 		(qstate->query_flags&BIT_RD) && !(qstate->query_flags&BIT_CD)){
807 		return;
808 	}
809 
810 	/* if the DNSKEY is in the cache this lookup will stop quickly */
811 	log_nametypeclass(VERB_ALGO, "schedule dnskey prefetch",
812 		iq->dp->name, LDNS_RR_TYPE_DNSKEY, iq->qchase.qclass);
813 	if(!generate_sub_request(iq->dp->name, iq->dp->namelen,
814 		LDNS_RR_TYPE_DNSKEY, iq->qchase.qclass, qstate, id, iq,
815 		INIT_REQUEST_STATE, FINISHED_STATE, &subq, 0)) {
816 		/* we'll be slower, but it'll work */
817 		verbose(VERB_ALGO, "could not generate dnskey prefetch");
818 		return;
819 	}
820 	if(subq) {
821 		struct iter_qstate* subiq =
822 			(struct iter_qstate*)subq->minfo[id];
823 		/* this qstate has the right delegation for the dnskey lookup*/
824 		/* make copy to avoid use of stub dp by different qs/threads */
825 		subiq->dp = delegpt_copy(iq->dp, subq->region);
826 		/* if !subiq->dp, it'll start from the cache, no problem */
827 	}
828 }
829 
830 /**
831  * See if the query needs forwarding.
832  *
833  * @param qstate: query state.
834  * @param iq: iterator query state.
835  * @return true if the request is forwarded, false if not.
836  * 	If returns true but, iq->dp is NULL then a malloc failure occurred.
837  */
838 static int
839 forward_request(struct module_qstate* qstate, struct iter_qstate* iq)
840 {
841 	struct delegpt* dp;
842 	uint8_t* delname = iq->qchase.qname;
843 	size_t delnamelen = iq->qchase.qname_len;
844 	if(iq->refetch_glue) {
845 		delname = iq->dp->name;
846 		delnamelen = iq->dp->namelen;
847 	}
848 	/* strip one label off of DS query to lookup higher for it */
849 	if( (iq->qchase.qtype == LDNS_RR_TYPE_DS || iq->refetch_glue)
850 		&& !dname_is_root(iq->qchase.qname))
851 		dname_remove_label(&delname, &delnamelen);
852 	dp = forwards_lookup(qstate->env->fwds, delname, iq->qchase.qclass);
853 	if(!dp)
854 		return 0;
855 	/* send recursion desired to forward addr */
856 	iq->chase_flags |= BIT_RD;
857 	iq->dp = delegpt_copy(dp, qstate->region);
858 	/* iq->dp checked by caller */
859 	verbose(VERB_ALGO, "forwarding request");
860 	return 1;
861 }
862 
863 /**
864  * Process the initial part of the request handling. This state roughly
865  * corresponds to resolver algorithms steps 1 (find answer in cache) and 2
866  * (find the best servers to ask).
867  *
868  * Note that all requests start here, and query restarts revisit this state.
869  *
870  * This state either generates: 1) a response, from cache or error, 2) a
871  * priming event, or 3) forwards the request to the next state (init2,
872  * generally).
873  *
874  * @param qstate: query state.
875  * @param iq: iterator query state.
876  * @param ie: iterator shared global environment.
877  * @param id: module id.
878  * @return true if the event needs more request processing immediately,
879  *         false if not.
880  */
881 static int
882 processInitRequest(struct module_qstate* qstate, struct iter_qstate* iq,
883 	struct iter_env* ie, int id)
884 {
885 	uint8_t* delname;
886 	size_t delnamelen;
887 	struct dns_msg* msg;
888 
889 	log_query_info(VERB_DETAIL, "resolving", &qstate->qinfo);
890 	/* check effort */
891 
892 	/* We enforce a maximum number of query restarts. This is primarily a
893 	 * cheap way to prevent CNAME loops. */
894 	if(iq->query_restart_count > MAX_RESTART_COUNT) {
895 		verbose(VERB_QUERY, "request has exceeded the maximum number"
896 			" of query restarts with %d", iq->query_restart_count);
897 		return error_response(qstate, id, LDNS_RCODE_SERVFAIL);
898 	}
899 
900 	/* We enforce a maximum recursion/dependency depth -- in general,
901 	 * this is unnecessary for dependency loops (although it will
902 	 * catch those), but it provides a sensible limit to the amount
903 	 * of work required to answer a given query. */
904 	verbose(VERB_ALGO, "request has dependency depth of %d", iq->depth);
905 	if(iq->depth > ie->max_dependency_depth) {
906 		verbose(VERB_QUERY, "request has exceeded the maximum "
907 			"dependency depth with depth of %d", iq->depth);
908 		return error_response(qstate, id, LDNS_RCODE_SERVFAIL);
909 	}
910 
911 	/* If the request is qclass=ANY, setup to generate each class */
912 	if(qstate->qinfo.qclass == LDNS_RR_CLASS_ANY) {
913 		iq->qchase.qclass = 0;
914 		return next_state(iq, COLLECT_CLASS_STATE);
915 	}
916 
917 	/* Resolver Algorithm Step 1 -- Look for the answer in local data. */
918 
919 	/* This either results in a query restart (CNAME cache response), a
920 	 * terminating response (ANSWER), or a cache miss (null). */
921 
922 	if(qstate->blacklist) {
923 		/* if cache, or anything else, was blacklisted then
924 		 * getting older results from cache is a bad idea, no cache */
925 		verbose(VERB_ALGO, "cache blacklisted, going to the network");
926 		msg = NULL;
927 	} else {
928 		msg = dns_cache_lookup(qstate->env, iq->qchase.qname,
929 			iq->qchase.qname_len, iq->qchase.qtype,
930 			iq->qchase.qclass, qstate->region, qstate->env->scratch);
931 		if(!msg && qstate->env->neg_cache) {
932 			/* lookup in negative cache; may result in
933 			 * NOERROR/NODATA or NXDOMAIN answers that need validation */
934 			msg = val_neg_getmsg(qstate->env->neg_cache, &iq->qchase,
935 				qstate->region, qstate->env->rrset_cache,
936 				qstate->env->scratch_buffer,
937 				*qstate->env->now, 1/*add SOA*/, NULL);
938 		}
939 		/* item taken from cache does not match our query name, thus
940 		 * security needs to be re-examined later */
941 		if(msg && query_dname_compare(qstate->qinfo.qname,
942 			iq->qchase.qname) != 0)
943 			msg->rep->security = sec_status_unchecked;
944 	}
945 	if(msg) {
946 		/* handle positive cache response */
947 		enum response_type type = response_type_from_cache(msg,
948 			&iq->qchase);
949 		if(verbosity >= VERB_ALGO) {
950 			log_dns_msg("msg from cache lookup", &msg->qinfo,
951 				msg->rep);
952 			verbose(VERB_ALGO, "msg ttl is %d, prefetch ttl %d",
953 				(int)msg->rep->ttl,
954 				(int)msg->rep->prefetch_ttl);
955 		}
956 
957 		if(type == RESPONSE_TYPE_CNAME) {
958 			uint8_t* sname = 0;
959 			size_t slen = 0;
960 			verbose(VERB_ALGO, "returning CNAME response from "
961 				"cache");
962 			if(!handle_cname_response(qstate, iq, msg,
963 				&sname, &slen))
964 				return error_response(qstate, id,
965 					LDNS_RCODE_SERVFAIL);
966 			iq->qchase.qname = sname;
967 			iq->qchase.qname_len = slen;
968 			/* This *is* a query restart, even if it is a cheap
969 			 * one. */
970 			iq->dp = NULL;
971 			iq->refetch_glue = 0;
972 			iq->query_restart_count++;
973 			iq->sent_count = 0;
974 			sock_list_insert(&qstate->reply_origin, NULL, 0, qstate->region);
975 			return next_state(iq, INIT_REQUEST_STATE);
976 		}
977 
978 		/* if from cache, NULL, else insert 'cache IP' len=0 */
979 		if(qstate->reply_origin)
980 			sock_list_insert(&qstate->reply_origin, NULL, 0, qstate->region);
981 		/* it is an answer, response, to final state */
982 		verbose(VERB_ALGO, "returning answer from cache.");
983 		iq->response = msg;
984 		return final_state(iq);
985 	}
986 
987 	/* attempt to forward the request */
988 	if(forward_request(qstate, iq))
989 	{
990 		if(!iq->dp) {
991 			log_err("alloc failure for forward dp");
992 			return error_response(qstate, id, LDNS_RCODE_SERVFAIL);
993 		}
994 		iq->refetch_glue = 0;
995 		/* the request has been forwarded.
996 		 * forwarded requests need to be immediately sent to the
997 		 * next state, QUERYTARGETS. */
998 		return next_state(iq, QUERYTARGETS_STATE);
999 	}
1000 
1001 	/* Resolver Algorithm Step 2 -- find the "best" servers. */
1002 
1003 	/* first, adjust for DS queries. To avoid the grandparent problem,
1004 	 * we just look for the closest set of server to the parent of qname.
1005 	 * When re-fetching glue we also need to ask the parent.
1006 	 */
1007 	if(iq->refetch_glue) {
1008 		if(!iq->dp) {
1009 			log_err("internal or malloc fail: no dp for refetch");
1010 			return error_response(qstate, id, LDNS_RCODE_SERVFAIL);
1011 		}
1012 		delname = iq->dp->name;
1013 		delnamelen = iq->dp->namelen;
1014 	} else {
1015 		delname = iq->qchase.qname;
1016 		delnamelen = iq->qchase.qname_len;
1017 	}
1018 	if(iq->qchase.qtype == LDNS_RR_TYPE_DS || iq->refetch_glue ||
1019 	   (iq->qchase.qtype == LDNS_RR_TYPE_NS && qstate->prefetch_leeway)) {
1020 		/* remove first label from delname, root goes to hints,
1021 		 * but only to fetch glue, not for qtype=DS. */
1022 		/* also when prefetching an NS record, fetch it again from
1023 		 * its parent, just as if it expired, so that you do not
1024 		 * get stuck on an older nameserver that gives old NSrecords */
1025 		if(dname_is_root(delname) && (iq->refetch_glue ||
1026 			(iq->qchase.qtype == LDNS_RR_TYPE_NS &&
1027 			qstate->prefetch_leeway)))
1028 			delname = NULL; /* go to root priming */
1029 		else 	dname_remove_label(&delname, &delnamelen);
1030 	}
1031 	/* delname is the name to lookup a delegation for. If NULL rootprime */
1032 	while(1) {
1033 
1034 		/* Lookup the delegation in the cache. If null, then the
1035 		 * cache needs to be primed for the qclass. */
1036 		if(delname)
1037 		     iq->dp = dns_cache_find_delegation(qstate->env, delname,
1038 			delnamelen, iq->qchase.qtype, iq->qchase.qclass,
1039 			qstate->region, &iq->deleg_msg,
1040 			*qstate->env->now+qstate->prefetch_leeway);
1041 		else iq->dp = NULL;
1042 
1043 		/* If the cache has returned nothing, then we have a
1044 		 * root priming situation. */
1045 		if(iq->dp == NULL) {
1046 			/* if there is a stub, then no root prime needed */
1047 			int r = prime_stub(qstate, iq, id, delname,
1048 				iq->qchase.qclass);
1049 			if(r == 2)
1050 				break; /* got noprime-stub-zone, continue */
1051 			else if(r)
1052 				return 0; /* stub prime request made */
1053 			if(forwards_lookup_root(qstate->env->fwds,
1054 				iq->qchase.qclass)) {
1055 				/* forward zone root, no root prime needed */
1056 				/* fill in some dp - safety belt */
1057 				iq->dp = hints_lookup_root(qstate->env->hints,
1058 					iq->qchase.qclass);
1059 				if(!iq->dp) {
1060 					log_err("internal error: no hints dp");
1061 					return error_response(qstate, id,
1062 						LDNS_RCODE_SERVFAIL);
1063 				}
1064 				iq->dp = delegpt_copy(iq->dp, qstate->region);
1065 				if(!iq->dp) {
1066 					log_err("out of memory in safety belt");
1067 					return error_response(qstate, id,
1068 						LDNS_RCODE_SERVFAIL);
1069 				}
1070 				return next_state(iq, INIT_REQUEST_2_STATE);
1071 			}
1072 			/* Note that the result of this will set a new
1073 			 * DelegationPoint based on the result of priming. */
1074 			if(!prime_root(qstate, iq, id, iq->qchase.qclass))
1075 				return error_response(qstate, id,
1076 					LDNS_RCODE_REFUSED);
1077 
1078 			/* priming creates and sends a subordinate query, with
1079 			 * this query as the parent. So further processing for
1080 			 * this event will stop until reactivated by the
1081 			 * results of priming. */
1082 			return 0;
1083 		}
1084 
1085 		/* see if this dp not useless.
1086 		 * It is useless if:
1087 		 *	o all NS items are required glue.
1088 		 *	  or the query is for NS item that is required glue.
1089 		 *	o no addresses are provided.
1090 		 *	o RD qflag is on.
1091 		 * Instead, go up one level, and try to get even further
1092 		 * If the root was useless, use safety belt information.
1093 		 * Only check cache returns, because replies for servers
1094 		 * could be useless but lead to loops (bumping into the
1095 		 * same server reply) if useless-checked.
1096 		 */
1097 		if(iter_dp_is_useless(&qstate->qinfo, qstate->query_flags,
1098 			iq->dp)) {
1099 			if(dname_is_root(iq->dp->name)) {
1100 				/* use safety belt */
1101 				verbose(VERB_QUERY, "Cache has root NS but "
1102 				"no addresses. Fallback to the safety belt.");
1103 				iq->dp = hints_lookup_root(qstate->env->hints,
1104 					iq->qchase.qclass);
1105 				/* note deleg_msg is from previous lookup,
1106 				 * but RD is on, so it is not used */
1107 				if(!iq->dp) {
1108 					log_err("internal error: no hints dp");
1109 					return error_response(qstate, id,
1110 						LDNS_RCODE_REFUSED);
1111 				}
1112 				iq->dp = delegpt_copy(iq->dp, qstate->region);
1113 				if(!iq->dp) {
1114 					log_err("out of memory in safety belt");
1115 					return error_response(qstate, id,
1116 						LDNS_RCODE_SERVFAIL);
1117 				}
1118 				break;
1119 			} else {
1120 				verbose(VERB_ALGO,
1121 					"cache delegation was useless:");
1122 				delegpt_log(VERB_ALGO, iq->dp);
1123 				/* go up */
1124 				delname = iq->dp->name;
1125 				delnamelen = iq->dp->namelen;
1126 				dname_remove_label(&delname, &delnamelen);
1127 			}
1128 		} else break;
1129 	}
1130 
1131 	verbose(VERB_ALGO, "cache delegation returns delegpt");
1132 	delegpt_log(VERB_ALGO, iq->dp);
1133 
1134 	/* Otherwise, set the current delegation point and move on to the
1135 	 * next state. */
1136 	return next_state(iq, INIT_REQUEST_2_STATE);
1137 }
1138 
1139 /**
1140  * Process the second part of the initial request handling. This state
1141  * basically exists so that queries that generate root priming events have
1142  * the same init processing as ones that do not. Request events that reach
1143  * this state must have a valid currentDelegationPoint set.
1144  *
1145  * This part is primarly handling stub zone priming. Events that reach this
1146  * state must have a current delegation point.
1147  *
1148  * @param qstate: query state.
1149  * @param iq: iterator query state.
1150  * @param id: module id.
1151  * @return true if the event needs more request processing immediately,
1152  *         false if not.
1153  */
1154 static int
1155 processInitRequest2(struct module_qstate* qstate, struct iter_qstate* iq,
1156 	int id)
1157 {
1158 	uint8_t* delname;
1159 	size_t delnamelen;
1160 	log_query_info(VERB_QUERY, "resolving (init part 2): ",
1161 		&qstate->qinfo);
1162 
1163 	if(iq->refetch_glue) {
1164 		if(!iq->dp) {
1165 			log_err("internal or malloc fail: no dp for refetch");
1166 			return error_response(qstate, id, LDNS_RCODE_SERVFAIL);
1167 		}
1168 		delname = iq->dp->name;
1169 		delnamelen = iq->dp->namelen;
1170 	} else {
1171 		delname = iq->qchase.qname;
1172 		delnamelen = iq->qchase.qname_len;
1173 	}
1174 	if(iq->qchase.qtype == LDNS_RR_TYPE_DS || iq->refetch_glue) {
1175 		if(!dname_is_root(delname))
1176 			dname_remove_label(&delname, &delnamelen);
1177 		iq->refetch_glue = 0; /* if CNAME causes restart, no refetch */
1178 	}
1179 	/* Check to see if we need to prime a stub zone. */
1180 	if(prime_stub(qstate, iq, id, delname, iq->qchase.qclass)) {
1181 		/* A priming sub request was made */
1182 		return 0;
1183 	}
1184 
1185 	/* most events just get forwarded to the next state. */
1186 	return next_state(iq, INIT_REQUEST_3_STATE);
1187 }
1188 
1189 /**
1190  * Process the third part of the initial request handling. This state exists
1191  * as a separate state so that queries that generate stub priming events
1192  * will get the tail end of the init process but not repeat the stub priming
1193  * check.
1194  *
1195  * @param qstate: query state.
1196  * @param iq: iterator query state.
1197  * @param id: module id.
1198  * @return true, advancing the event to the QUERYTARGETS_STATE.
1199  */
1200 static int
1201 processInitRequest3(struct module_qstate* qstate, struct iter_qstate* iq,
1202 	int id)
1203 {
1204 	log_query_info(VERB_QUERY, "resolving (init part 3): ",
1205 		&qstate->qinfo);
1206 	/* if the cache reply dp equals a validation anchor or msg has DS,
1207 	 * then DNSSEC RRSIGs are expected in the reply */
1208 	iq->dnssec_expected = iter_indicates_dnssec(qstate->env, iq->dp,
1209 		iq->deleg_msg, iq->qchase.qclass);
1210 
1211 	/* If the RD flag wasn't set, then we just finish with the
1212 	 * cached referral as the response. */
1213 	if(!(qstate->query_flags & BIT_RD)) {
1214 		iq->response = iq->deleg_msg;
1215 		if(verbosity >= VERB_ALGO)
1216 			log_dns_msg("no RD requested, using delegation msg",
1217 				&iq->response->qinfo, iq->response->rep);
1218 		if(qstate->reply_origin)
1219 			sock_list_insert(&qstate->reply_origin, NULL, 0, qstate->region);
1220 		return final_state(iq);
1221 	}
1222 	/* After this point, unset the RD flag -- this query is going to
1223 	 * be sent to an auth. server. */
1224 	iq->chase_flags &= ~BIT_RD;
1225 
1226 	/* if dnssec expected, fetch key for the trust-anchor or cached-DS */
1227 	if(iq->dnssec_expected && qstate->env->cfg->prefetch_key &&
1228 		!(qstate->query_flags&BIT_CD)) {
1229 		generate_dnskey_prefetch(qstate, iq, id);
1230 		fptr_ok(fptr_whitelist_modenv_detach_subs(
1231 			qstate->env->detach_subs));
1232 		(*qstate->env->detach_subs)(qstate);
1233 	}
1234 
1235 	/* Jump to the next state. */
1236 	return next_state(iq, QUERYTARGETS_STATE);
1237 }
1238 
1239 /**
1240  * Given a basic query, generate a parent-side "target" query.
1241  * These are subordinate queries for missing delegation point target addresses,
1242  * for which only the parent of the delegation provides correct IP addresses.
1243  *
1244  * @param qstate: query state.
1245  * @param iq: iterator query state.
1246  * @param id: module id.
1247  * @param name: target qname.
1248  * @param namelen: target qname length.
1249  * @param qtype: target qtype (either A or AAAA).
1250  * @param qclass: target qclass.
1251  * @return true on success, false on failure.
1252  */
1253 static int
1254 generate_parentside_target_query(struct module_qstate* qstate,
1255 	struct iter_qstate* iq, int id, uint8_t* name, size_t namelen,
1256 	uint16_t qtype, uint16_t qclass)
1257 {
1258 	struct module_qstate* subq;
1259 	if(!generate_sub_request(name, namelen, qtype, qclass, qstate,
1260 		id, iq, INIT_REQUEST_STATE, FINISHED_STATE, &subq, 0))
1261 		return 0;
1262 	if(subq) {
1263 		struct iter_qstate* subiq =
1264 			(struct iter_qstate*)subq->minfo[id];
1265 		/* blacklist the cache - we want to fetch parent stuff */
1266 		sock_list_insert(&subq->blacklist, NULL, 0, subq->region);
1267 		subiq->query_for_pside_glue = 1;
1268 		if(dname_subdomain_c(name, iq->dp->name)) {
1269 			subiq->dp = delegpt_copy(iq->dp, subq->region);
1270 			subiq->dnssec_expected = iter_indicates_dnssec(
1271 				qstate->env, subiq->dp, NULL,
1272 				subq->qinfo.qclass);
1273 			subiq->refetch_glue = 1;
1274 		} else {
1275 			subiq->dp = dns_cache_find_delegation(qstate->env,
1276 				name, namelen, qtype, qclass, subq->region,
1277 				&subiq->deleg_msg,
1278 				*qstate->env->now+subq->prefetch_leeway);
1279 			/* if no dp, then it's from root, refetch unneeded */
1280 			if(subiq->dp) {
1281 				subiq->dnssec_expected = iter_indicates_dnssec(
1282 					qstate->env, subiq->dp, NULL,
1283 					subq->qinfo.qclass);
1284 				subiq->refetch_glue = 1;
1285 			}
1286 		}
1287 	}
1288 	log_nametypeclass(VERB_QUERY, "new pside target", name, qtype, qclass);
1289 	return 1;
1290 }
1291 
1292 /**
1293  * Given a basic query, generate a "target" query. These are subordinate
1294  * queries for missing delegation point target addresses.
1295  *
1296  * @param qstate: query state.
1297  * @param iq: iterator query state.
1298  * @param id: module id.
1299  * @param name: target qname.
1300  * @param namelen: target qname length.
1301  * @param qtype: target qtype (either A or AAAA).
1302  * @param qclass: target qclass.
1303  * @return true on success, false on failure.
1304  */
1305 static int
1306 generate_target_query(struct module_qstate* qstate, struct iter_qstate* iq,
1307         int id, uint8_t* name, size_t namelen, uint16_t qtype, uint16_t qclass)
1308 {
1309 	struct module_qstate* subq;
1310 	if(!generate_sub_request(name, namelen, qtype, qclass, qstate,
1311 		id, iq, INIT_REQUEST_STATE, FINISHED_STATE, &subq, 0))
1312 		return 0;
1313 	log_nametypeclass(VERB_QUERY, "new target", name, qtype, qclass);
1314 	return 1;
1315 }
1316 
1317 /**
1318  * Given an event at a certain state, generate zero or more target queries
1319  * for it's current delegation point.
1320  *
1321  * @param qstate: query state.
1322  * @param iq: iterator query state.
1323  * @param ie: iterator shared global environment.
1324  * @param id: module id.
1325  * @param maxtargets: The maximum number of targets to query for.
1326  *	if it is negative, there is no maximum number of targets.
1327  * @param num: returns the number of queries generated and processed,
1328  *	which may be zero if there were no missing targets.
1329  * @return false on error.
1330  */
1331 static int
1332 query_for_targets(struct module_qstate* qstate, struct iter_qstate* iq,
1333         struct iter_env* ie, int id, int maxtargets, int* num)
1334 {
1335 	int query_count = 0;
1336 	struct delegpt_ns* ns;
1337 	int missing;
1338 	int toget = 0;
1339 
1340 	if(iq->depth == ie->max_dependency_depth)
1341 		return 0;
1342 
1343 	iter_mark_cycle_targets(qstate, iq->dp);
1344 	missing = (int)delegpt_count_missing_targets(iq->dp);
1345 	log_assert(maxtargets != 0); /* that would not be useful */
1346 
1347 	/* Generate target requests. Basically, any missing targets
1348 	 * are queried for here, regardless if it is necessary to do
1349 	 * so to continue processing. */
1350 	if(maxtargets < 0 || maxtargets > missing)
1351 		toget = missing;
1352 	else	toget = maxtargets;
1353 	if(toget == 0) {
1354 		*num = 0;
1355 		return 1;
1356 	}
1357 	/* select 'toget' items from the total of 'missing' items */
1358 	log_assert(toget <= missing);
1359 
1360 	/* loop over missing targets */
1361 	for(ns = iq->dp->nslist; ns; ns = ns->next) {
1362 		if(ns->resolved)
1363 			continue;
1364 
1365 		/* randomly select this item with probability toget/missing */
1366 		if(!iter_ns_probability(qstate->env->rnd, toget, missing)) {
1367 			/* do not select this one, next; select toget number
1368 			 * of items from a list one less in size */
1369 			missing --;
1370 			continue;
1371 		}
1372 
1373 		if(ie->supports_ipv6 && !ns->got6) {
1374 			/* Send the AAAA request. */
1375 			if(!generate_target_query(qstate, iq, id,
1376 				ns->name, ns->namelen,
1377 				LDNS_RR_TYPE_AAAA, iq->qchase.qclass)) {
1378 				*num = query_count;
1379 				if(query_count > 0)
1380 					qstate->ext_state[id] = module_wait_subquery;
1381 				return 0;
1382 			}
1383 			query_count++;
1384 		}
1385 		/* Send the A request. */
1386 		if(ie->supports_ipv4 && !ns->got4) {
1387 			if(!generate_target_query(qstate, iq, id,
1388 				ns->name, ns->namelen,
1389 				LDNS_RR_TYPE_A, iq->qchase.qclass)) {
1390 				*num = query_count;
1391 				if(query_count > 0)
1392 					qstate->ext_state[id] = module_wait_subquery;
1393 				return 0;
1394 			}
1395 			query_count++;
1396 		}
1397 
1398 		/* mark this target as in progress. */
1399 		ns->resolved = 1;
1400 		missing--;
1401 		toget--;
1402 		if(toget == 0)
1403 			break;
1404 	}
1405 	*num = query_count;
1406 	if(query_count > 0)
1407 		qstate->ext_state[id] = module_wait_subquery;
1408 
1409 	return 1;
1410 }
1411 
1412 /**
1413  * Called by processQueryTargets when it would like extra targets to query
1414  * but it seems to be out of options.  At last resort some less appealing
1415  * options are explored.  If there are no more options, the result is SERVFAIL
1416  *
1417  * @param qstate: query state.
1418  * @param iq: iterator query state.
1419  * @param ie: iterator shared global environment.
1420  * @param id: module id.
1421  * @return true if the event requires more request processing immediately,
1422  *         false if not.
1423  */
1424 static int
1425 processLastResort(struct module_qstate* qstate, struct iter_qstate* iq,
1426 	struct iter_env* ie, int id)
1427 {
1428 	struct delegpt_ns* ns;
1429 	int query_count = 0;
1430 	verbose(VERB_ALGO, "No more query targets, attempting last resort");
1431 	log_assert(iq->dp);
1432 
1433 	if(!iq->dp->has_parent_side_NS && dname_is_root(iq->dp->name)) {
1434 		struct delegpt* p = hints_lookup_root(qstate->env->hints,
1435 			iq->qchase.qclass);
1436 		if(p) {
1437 			struct delegpt_ns* ns;
1438 			struct delegpt_addr* a;
1439 			iq->chase_flags &= ~BIT_RD; /* go to authorities */
1440 			for(ns = p->nslist; ns; ns=ns->next) {
1441 				(void)delegpt_add_ns(iq->dp, qstate->region,
1442 					ns->name, (int)ns->lame);
1443 			}
1444 			for(a = p->target_list; a; a=a->next_target) {
1445 				(void)delegpt_add_addr(iq->dp, qstate->region,
1446 					&a->addr, a->addrlen, a->bogus,
1447 					a->lame);
1448 			}
1449 		}
1450 		iq->dp->has_parent_side_NS = 1;
1451 	} else if(!iq->dp->has_parent_side_NS) {
1452 		if(!iter_lookup_parent_NS_from_cache(qstate->env, iq->dp,
1453 			qstate->region, &qstate->qinfo)
1454 			|| !iq->dp->has_parent_side_NS) {
1455 			/* if: malloc failure in lookup go up to try */
1456 			/* if: no parent NS in cache - go up one level */
1457 			verbose(VERB_ALGO, "try to grab parent NS");
1458 			iq->store_parent_NS = iq->dp;
1459 			iq->chase_flags &= ~BIT_RD; /* go to authorities */
1460 			iq->deleg_msg = NULL;
1461 			iq->refetch_glue = 1;
1462 			iq->query_restart_count++;
1463 			iq->sent_count = 0;
1464 			return next_state(iq, INIT_REQUEST_STATE);
1465 		}
1466 	}
1467 	/* see if that makes new names available */
1468 	if(!cache_fill_missing(qstate->env, iq->qchase.qclass,
1469 		qstate->region, iq->dp))
1470 		log_err("out of memory in cache_fill_missing");
1471 	if(iq->dp->usable_list) {
1472 		verbose(VERB_ALGO, "try parent-side-name, w. glue from cache");
1473 		return next_state(iq, QUERYTARGETS_STATE);
1474 	}
1475 	/* try to fill out parent glue from cache */
1476 	if(iter_lookup_parent_glue_from_cache(qstate->env, iq->dp,
1477 		qstate->region, &qstate->qinfo)) {
1478 		/* got parent stuff from cache, see if we can continue */
1479 		verbose(VERB_ALGO, "try parent-side glue from cache");
1480 		return next_state(iq, QUERYTARGETS_STATE);
1481 	}
1482 	/* query for an extra name added by the parent-NS record */
1483 	if(delegpt_count_missing_targets(iq->dp) > 0) {
1484 		int qs = 0;
1485 		verbose(VERB_ALGO, "try parent-side target name");
1486 		if(!query_for_targets(qstate, iq, ie, id, 1, &qs)) {
1487 			return error_response(qstate, id, LDNS_RCODE_SERVFAIL);
1488 		}
1489 		iq->num_target_queries += qs;
1490 		if(qs != 0) {
1491 			qstate->ext_state[id] = module_wait_subquery;
1492 			return 0; /* and wait for them */
1493 		}
1494 	}
1495 	if(iq->depth == ie->max_dependency_depth) {
1496 		verbose(VERB_QUERY, "maxdepth and need more nameservers, fail");
1497 		return error_response_cache(qstate, id, LDNS_RCODE_SERVFAIL);
1498 	}
1499 	/* mark cycle targets for parent-side lookups */
1500 	iter_mark_pside_cycle_targets(qstate, iq->dp);
1501 	/* see if we can issue queries to get nameserver addresses */
1502 	/* this lookup is not randomized, but sequential. */
1503 	for(ns = iq->dp->nslist; ns; ns = ns->next) {
1504 		/* query for parent-side A and AAAA for nameservers */
1505 		if(ie->supports_ipv6 && !ns->done_pside6) {
1506 			/* Send the AAAA request. */
1507 			if(!generate_parentside_target_query(qstate, iq, id,
1508 				ns->name, ns->namelen,
1509 				LDNS_RR_TYPE_AAAA, iq->qchase.qclass))
1510 				return error_response(qstate, id,
1511 					LDNS_RCODE_SERVFAIL);
1512 			ns->done_pside6 = 1;
1513 			query_count++;
1514 		}
1515 		if(ie->supports_ipv4 && !ns->done_pside4) {
1516 			/* Send the A request. */
1517 			if(!generate_parentside_target_query(qstate, iq, id,
1518 				ns->name, ns->namelen,
1519 				LDNS_RR_TYPE_A, iq->qchase.qclass))
1520 				return error_response(qstate, id,
1521 					LDNS_RCODE_SERVFAIL);
1522 			ns->done_pside4 = 1;
1523 			query_count++;
1524 		}
1525 		if(query_count != 0) { /* suspend to await results */
1526 			verbose(VERB_ALGO, "try parent-side glue lookup");
1527 			iq->num_target_queries += query_count;
1528 			qstate->ext_state[id] = module_wait_subquery;
1529 			return 0;
1530 		}
1531 	}
1532 
1533 	/* if this was a parent-side glue query itself, then store that
1534 	 * failure in cache. */
1535 	if(iq->query_for_pside_glue && !iq->pside_glue)
1536 		iter_store_parentside_neg(qstate->env, &qstate->qinfo,
1537 			iq->deleg_msg?iq->deleg_msg->rep:
1538 			(iq->response?iq->response->rep:NULL));
1539 
1540 	verbose(VERB_QUERY, "out of query targets -- returning SERVFAIL");
1541 	/* fail -- no more targets, no more hope of targets, no hope
1542 	 * of a response. */
1543 	return error_response_cache(qstate, id, LDNS_RCODE_SERVFAIL);
1544 }
1545 
1546 /**
1547  * Try to find the NS record set that will resolve a qtype DS query. Due
1548  * to grandparent/grandchild reasons we did not get a proper lookup right
1549  * away.  We need to create type NS queries until we get the right parent
1550  * for this lookup.  We remove labels from the query to find the right point.
1551  * If we end up at the old dp name, then there is no solution.
1552  *
1553  * @param qstate: query state.
1554  * @param iq: iterator query state.
1555  * @param id: module id.
1556  * @return true if the event requires more immediate processing, false if
1557  *         not. This is generally only true when forwarding the request to
1558  *         the final state (i.e., on answer).
1559  */
1560 static int
1561 processDSNSFind(struct module_qstate* qstate, struct iter_qstate* iq, int id)
1562 {
1563 	struct module_qstate* subq = NULL;
1564 	verbose(VERB_ALGO, "processDSNSFind");
1565 
1566 	if(!iq->dsns_point) {
1567 		/* initialize */
1568 		iq->dsns_point = iq->qchase.qname;
1569 		iq->dsns_point_len = iq->qchase.qname_len;
1570 	}
1571 	/* robustcheck for internal error: we are not underneath the dp */
1572 	if(!dname_subdomain_c(iq->dsns_point, iq->dp->name)) {
1573 		return error_response_cache(qstate, id, LDNS_RCODE_SERVFAIL);
1574 	}
1575 
1576 	/* go up one (more) step, until we hit the dp, if so, end */
1577 	dname_remove_label(&iq->dsns_point, &iq->dsns_point_len);
1578 	if(query_dname_compare(iq->dsns_point, iq->dp->name) == 0) {
1579 		/* there was no inbetween nameserver, use the old delegation
1580 		 * point again.  And this time, because dsns_point is nonNULL
1581 		 * we are going to accept the (bad) result */
1582 		iq->state = QUERYTARGETS_STATE;
1583 		return 1;
1584 	}
1585 	iq->state = DSNS_FIND_STATE;
1586 
1587 	/* spawn NS lookup (validation not needed, this is for DS lookup) */
1588 	log_nametypeclass(VERB_ALGO, "fetch nameservers",
1589 		iq->dsns_point, LDNS_RR_TYPE_NS, iq->qchase.qclass);
1590 	if(!generate_sub_request(iq->dsns_point, iq->dsns_point_len,
1591 		LDNS_RR_TYPE_NS, iq->qchase.qclass, qstate, id, iq,
1592 		INIT_REQUEST_STATE, FINISHED_STATE, &subq, 0)) {
1593 		return error_response_cache(qstate, id, LDNS_RCODE_SERVFAIL);
1594 	}
1595 
1596 	return 0;
1597 }
1598 
1599 /**
1600  * This is the request event state where the request will be sent to one of
1601  * its current query targets. This state also handles issuing target lookup
1602  * queries for missing target IP addresses. Queries typically iterate on
1603  * this state, both when they are just trying different targets for a given
1604  * delegation point, and when they change delegation points. This state
1605  * roughly corresponds to RFC 1034 algorithm steps 3 and 4.
1606  *
1607  * @param qstate: query state.
1608  * @param iq: iterator query state.
1609  * @param ie: iterator shared global environment.
1610  * @param id: module id.
1611  * @return true if the event requires more request processing immediately,
1612  *         false if not. This state only returns true when it is generating
1613  *         a SERVFAIL response because the query has hit a dead end.
1614  */
1615 static int
1616 processQueryTargets(struct module_qstate* qstate, struct iter_qstate* iq,
1617 	struct iter_env* ie, int id)
1618 {
1619 	int tf_policy;
1620 	struct delegpt_addr* target;
1621 	struct outbound_entry* outq;
1622 
1623 	/* NOTE: a request will encounter this state for each target it
1624 	 * needs to send a query to. That is, at least one per referral,
1625 	 * more if some targets timeout or return throwaway answers. */
1626 
1627 	log_query_info(VERB_QUERY, "processQueryTargets:", &qstate->qinfo);
1628 	verbose(VERB_ALGO, "processQueryTargets: targetqueries %d, "
1629 		"currentqueries %d sentcount %d", iq->num_target_queries,
1630 		iq->num_current_queries, iq->sent_count);
1631 
1632 	/* Make sure that we haven't run away */
1633 	/* FIXME: is this check even necessary? */
1634 	if(iq->referral_count > MAX_REFERRAL_COUNT) {
1635 		verbose(VERB_QUERY, "request has exceeded the maximum "
1636 			"number of referrrals with %d", iq->referral_count);
1637 		return error_response(qstate, id, LDNS_RCODE_SERVFAIL);
1638 	}
1639 	if(iq->sent_count > MAX_SENT_COUNT) {
1640 		verbose(VERB_QUERY, "request has exceeded the maximum "
1641 			"number of sends with %d", iq->sent_count);
1642 		return error_response(qstate, id, LDNS_RCODE_SERVFAIL);
1643 	}
1644 
1645 	/* Make sure we have a delegation point, otherwise priming failed
1646 	 * or another failure occurred */
1647 	if(!iq->dp) {
1648 		verbose(VERB_QUERY, "Failed to get a delegation, giving up");
1649 		return error_response(qstate, id, LDNS_RCODE_SERVFAIL);
1650 	}
1651 	if(!ie->supports_ipv6)
1652 		delegpt_no_ipv6(iq->dp);
1653 	if(!ie->supports_ipv4)
1654 		delegpt_no_ipv4(iq->dp);
1655 	delegpt_log(VERB_ALGO, iq->dp);
1656 
1657 	if(iq->num_current_queries>0) {
1658 		/* already busy answering a query, this restart is because
1659 		 * more delegpt addrs became available, wait for existing
1660 		 * query. */
1661 		verbose(VERB_ALGO, "woke up, but wait for outstanding query");
1662 		qstate->ext_state[id] = module_wait_reply;
1663 		return 0;
1664 	}
1665 
1666 	tf_policy = 0;
1667 	/* < not <=, because although the array is large enough for <=, the
1668 	 * generated query will immediately be discarded due to depth and
1669 	 * that servfail is cached, which is not good as opportunism goes. */
1670 	if(iq->depth < ie->max_dependency_depth
1671 		&& iq->sent_count < TARGET_FETCH_STOP) {
1672 		tf_policy = ie->target_fetch_policy[iq->depth];
1673 	}
1674 
1675 	/* if in 0x20 fallback get as many targets as possible */
1676 	if(iq->caps_fallback) {
1677 		int extra = 0;
1678 		size_t naddr, nres, navail;
1679 		if(!query_for_targets(qstate, iq, ie, id, -1, &extra)) {
1680 			return error_response(qstate, id, LDNS_RCODE_SERVFAIL);
1681 		}
1682 		iq->num_target_queries += extra;
1683 		if(iq->num_target_queries > 0) {
1684 			/* wait to get all targets, we want to try em */
1685 			verbose(VERB_ALGO, "wait for all targets for fallback");
1686 			qstate->ext_state[id] = module_wait_reply;
1687 			return 0;
1688 		}
1689 		/* did we do enough fallback queries already? */
1690 		delegpt_count_addr(iq->dp, &naddr, &nres, &navail);
1691 		/* the current caps_server is the number of fallbacks sent.
1692 		 * the original query is one that matched too, so we have
1693 		 * caps_server+1 number of matching queries now */
1694 		if(iq->caps_server+1 >= naddr*3 ||
1695 			iq->caps_server+1 >= MAX_SENT_COUNT) {
1696 			/* we're done, process the response */
1697 			verbose(VERB_ALGO, "0x20 fallback had %d responses "
1698 				"match for %d wanted, done.",
1699 				(int)iq->caps_server+1, (int)naddr*3);
1700 			iq->caps_fallback = 0;
1701 			iter_dec_attempts(iq->dp, 3); /* space for fallback */
1702 			iq->num_current_queries++; /* RespState decrements it*/
1703 			iq->referral_count++; /* make sure we don't loop */
1704 			iq->sent_count = 0;
1705 			iq->state = QUERY_RESP_STATE;
1706 			return 1;
1707 		}
1708 		verbose(VERB_ALGO, "0x20 fallback number %d",
1709 			(int)iq->caps_server);
1710 
1711 	/* if there is a policy to fetch missing targets
1712 	 * opportunistically, do it. we rely on the fact that once a
1713 	 * query (or queries) for a missing name have been issued,
1714 	 * they will not show up again. */
1715 	} else if(tf_policy != 0) {
1716 		int extra = 0;
1717 		verbose(VERB_ALGO, "attempt to get extra %d targets",
1718 			tf_policy);
1719 		(void)query_for_targets(qstate, iq, ie, id, tf_policy, &extra);
1720 		/* errors ignored, these targets are not strictly necessary for
1721 		 * this result, we do not have to reply with SERVFAIL */
1722 		iq->num_target_queries += extra;
1723 	}
1724 
1725 	/* Add the current set of unused targets to our queue. */
1726 	delegpt_add_unused_targets(iq->dp);
1727 
1728 	/* Select the next usable target, filtering out unsuitable targets. */
1729 	target = iter_server_selection(ie, qstate->env, iq->dp,
1730 		iq->dp->name, iq->dp->namelen, iq->qchase.qtype,
1731 		&iq->dnssec_lame_query, &iq->chase_to_rd,
1732 		iq->num_target_queries, qstate->blacklist);
1733 
1734 	/* If no usable target was selected... */
1735 	if(!target) {
1736 		/* Here we distinguish between three states: generate a new
1737 		 * target query, just wait, or quit (with a SERVFAIL).
1738 		 * We have the following information: number of active
1739 		 * target queries, number of active current queries,
1740 		 * the presence of missing targets at this delegation
1741 		 * point, and the given query target policy. */
1742 
1743 		/* Check for the wait condition. If this is true, then
1744 		 * an action must be taken. */
1745 		if(iq->num_target_queries==0 && iq->num_current_queries==0) {
1746 			/* If there is nothing to wait for, then we need
1747 			 * to distinguish between generating (a) new target
1748 			 * query, or failing. */
1749 			if(delegpt_count_missing_targets(iq->dp) > 0) {
1750 				int qs = 0;
1751 				verbose(VERB_ALGO, "querying for next "
1752 					"missing target");
1753 				if(!query_for_targets(qstate, iq, ie, id,
1754 					1, &qs)) {
1755 					return error_response(qstate, id,
1756 						LDNS_RCODE_SERVFAIL);
1757 				}
1758 				if(qs == 0 &&
1759 				   delegpt_count_missing_targets(iq->dp) == 0){
1760 					/* it looked like there were missing
1761 					 * targets, but they did not turn up.
1762 					 * Try the bad choices again (if any),
1763 					 * when we get back here missing==0,
1764 					 * so this is not a loop. */
1765 					return 1;
1766 				}
1767 				iq->num_target_queries += qs;
1768 			}
1769 			/* Since a target query might have been made, we
1770 			 * need to check again. */
1771 			if(iq->num_target_queries == 0) {
1772 				return processLastResort(qstate, iq, ie, id);
1773 			}
1774 		}
1775 
1776 		/* otherwise, we have no current targets, so submerge
1777 		 * until one of the target or direct queries return. */
1778 		if(iq->num_target_queries>0 && iq->num_current_queries>0) {
1779 			verbose(VERB_ALGO, "no current targets -- waiting "
1780 				"for %d targets to resolve or %d outstanding"
1781 				" queries to respond", iq->num_target_queries,
1782 				iq->num_current_queries);
1783 			qstate->ext_state[id] = module_wait_reply;
1784 		} else if(iq->num_target_queries>0) {
1785 			verbose(VERB_ALGO, "no current targets -- waiting "
1786 				"for %d targets to resolve.",
1787 				iq->num_target_queries);
1788 			qstate->ext_state[id] = module_wait_subquery;
1789 		} else {
1790 			verbose(VERB_ALGO, "no current targets -- waiting "
1791 				"for %d outstanding queries to respond.",
1792 				iq->num_current_queries);
1793 			qstate->ext_state[id] = module_wait_reply;
1794 		}
1795 		return 0;
1796 	}
1797 
1798 	/* We have a valid target. */
1799 	if(verbosity >= VERB_QUERY) {
1800 		log_query_info(VERB_QUERY, "sending query:", &iq->qchase);
1801 		log_name_addr(VERB_QUERY, "sending to target:", iq->dp->name,
1802 			&target->addr, target->addrlen);
1803 		verbose(VERB_ALGO, "dnssec status: %s%s",
1804 			iq->dnssec_expected?"expected": "not expected",
1805 			iq->dnssec_lame_query?" but lame_query anyway": "");
1806 	}
1807 	fptr_ok(fptr_whitelist_modenv_send_query(qstate->env->send_query));
1808 	outq = (*qstate->env->send_query)(
1809 		iq->qchase.qname, iq->qchase.qname_len,
1810 		iq->qchase.qtype, iq->qchase.qclass,
1811 		iq->chase_flags | (iq->chase_to_rd?BIT_RD:0), EDNS_DO|BIT_CD,
1812 		iq->dnssec_expected, &target->addr, target->addrlen,
1813 		iq->dp->name, iq->dp->namelen, qstate);
1814 	if(!outq) {
1815 		log_addr(VERB_DETAIL, "error sending query to auth server",
1816 			&target->addr, target->addrlen);
1817 		return next_state(iq, QUERYTARGETS_STATE);
1818 	}
1819 	outbound_list_insert(&iq->outlist, outq);
1820 	iq->num_current_queries++;
1821 	iq->sent_count++;
1822 	qstate->ext_state[id] = module_wait_reply;
1823 
1824 	return 0;
1825 }
1826 
1827 /** find NS rrset in given list */
1828 static struct ub_packed_rrset_key*
1829 find_NS(struct reply_info* rep, size_t from, size_t to)
1830 {
1831 	size_t i;
1832 	for(i=from; i<to; i++) {
1833 		if(ntohs(rep->rrsets[i]->rk.type) == LDNS_RR_TYPE_NS)
1834 			return rep->rrsets[i];
1835 	}
1836 	return NULL;
1837 }
1838 
1839 
1840 /**
1841  * Process the query response. All queries end up at this state first. This
1842  * process generally consists of analyzing the response and routing the
1843  * event to the next state (either bouncing it back to a request state, or
1844  * terminating the processing for this event).
1845  *
1846  * @param qstate: query state.
1847  * @param iq: iterator query state.
1848  * @param id: module id.
1849  * @return true if the event requires more immediate processing, false if
1850  *         not. This is generally only true when forwarding the request to
1851  *         the final state (i.e., on answer).
1852  */
1853 static int
1854 processQueryResponse(struct module_qstate* qstate, struct iter_qstate* iq,
1855 	int id)
1856 {
1857 	int dnsseclame = 0;
1858 	enum response_type type;
1859 	iq->num_current_queries--;
1860 	if(iq->response == NULL) {
1861 		iq->chase_to_rd = 0;
1862 		iq->dnssec_lame_query = 0;
1863 		verbose(VERB_ALGO, "query response was timeout");
1864 		return next_state(iq, QUERYTARGETS_STATE);
1865 	}
1866 	type = response_type_from_server(
1867 		(int)((iq->chase_flags&BIT_RD) || iq->chase_to_rd),
1868 		iq->response, &iq->qchase, iq->dp);
1869 	iq->chase_to_rd = 0;
1870 	if(type == RESPONSE_TYPE_REFERRAL && (iq->chase_flags&BIT_RD)) {
1871 		/* When forwarding (RD bit is set), we handle referrals
1872 		 * differently. No queries should be sent elsewhere */
1873 		type = RESPONSE_TYPE_ANSWER;
1874 	}
1875 	if(iq->dnssec_expected && !iq->dnssec_lame_query &&
1876 		!(iq->chase_flags&BIT_RD)
1877 		&& type != RESPONSE_TYPE_LAME
1878 		&& type != RESPONSE_TYPE_REC_LAME
1879 		&& type != RESPONSE_TYPE_THROWAWAY
1880 		&& type != RESPONSE_TYPE_UNTYPED) {
1881 		/* a possible answer, see if it is missing DNSSEC */
1882 		/* but not when forwarding, so we dont mark fwder lame */
1883 		/* also make sure the answer is from the zone we expected,
1884 		 * otherwise, (due to parent,child on same server), we
1885 		 * might mark the server,zone lame inappropriately */
1886 		if(!iter_msg_has_dnssec(iq->response) &&
1887 			iter_msg_from_zone(iq->response, iq->dp, type,
1888 				iq->qchase.qclass)) {
1889 			type = RESPONSE_TYPE_LAME;
1890 			dnsseclame = 1;
1891 		}
1892 	} else iq->dnssec_lame_query = 0;
1893 	/* see if referral brings us close to the target */
1894 	if(type == RESPONSE_TYPE_REFERRAL) {
1895 		struct ub_packed_rrset_key* ns = find_NS(
1896 			iq->response->rep, iq->response->rep->an_numrrsets,
1897 			iq->response->rep->an_numrrsets
1898 			+ iq->response->rep->ns_numrrsets);
1899 		if(!ns) ns = find_NS(iq->response->rep, 0,
1900 				iq->response->rep->an_numrrsets);
1901 		if(!ns || !dname_strict_subdomain_c(ns->rk.dname, iq->dp->name)
1902 			|| !dname_subdomain_c(iq->qchase.qname, ns->rk.dname)){
1903 			verbose(VERB_ALGO, "bad referral, throwaway");
1904 			type = RESPONSE_TYPE_THROWAWAY;
1905 		} else
1906 			iter_scrub_ds(iq->response, ns, iq->dp->name);
1907 	} else iter_scrub_ds(iq->response, NULL, NULL);
1908 
1909 	/* handle each of the type cases */
1910 	if(type == RESPONSE_TYPE_ANSWER) {
1911 		/* ANSWER type responses terminate the query algorithm,
1912 		 * so they sent on their */
1913 		if(verbosity >= VERB_DETAIL) {
1914 			verbose(VERB_DETAIL, "query response was %s",
1915 				FLAGS_GET_RCODE(iq->response->rep->flags)
1916 				==LDNS_RCODE_NXDOMAIN?"NXDOMAIN ANSWER":
1917 				(iq->response->rep->an_numrrsets?"ANSWER":
1918 				"nodata ANSWER"));
1919 		}
1920 		/* if qtype is DS, check we have the right level of answer,
1921 		 * like grandchild answer but we need the middle, reject it */
1922 		if(iq->qchase.qtype == LDNS_RR_TYPE_DS && !iq->dsns_point
1923 			&& !(iq->chase_flags&BIT_RD)
1924 			&& iter_ds_toolow(iq->response, iq->dp)
1925 			&& iter_dp_cangodown(&iq->qchase, iq->dp)) {
1926 			/* close down outstanding requests to be discarded */
1927 			outbound_list_clear(&iq->outlist);
1928 			iq->num_current_queries = 0;
1929 			fptr_ok(fptr_whitelist_modenv_detach_subs(
1930 				qstate->env->detach_subs));
1931 			(*qstate->env->detach_subs)(qstate);
1932 			iq->num_target_queries = 0;
1933 			return processDSNSFind(qstate, iq, id);
1934 		}
1935 		iter_dns_store(qstate->env, &iq->response->qinfo,
1936 			iq->response->rep, 0, qstate->prefetch_leeway,
1937 			iq->dp&&iq->dp->has_parent_side_NS,
1938 			qstate->region);
1939 		/* close down outstanding requests to be discarded */
1940 		outbound_list_clear(&iq->outlist);
1941 		iq->num_current_queries = 0;
1942 		fptr_ok(fptr_whitelist_modenv_detach_subs(
1943 			qstate->env->detach_subs));
1944 		(*qstate->env->detach_subs)(qstate);
1945 		iq->num_target_queries = 0;
1946 		if(qstate->reply)
1947 			sock_list_insert(&qstate->reply_origin,
1948 				&qstate->reply->addr, qstate->reply->addrlen,
1949 				qstate->region);
1950 		return final_state(iq);
1951 	} else if(type == RESPONSE_TYPE_REFERRAL) {
1952 		/* REFERRAL type responses get a reset of the
1953 		 * delegation point, and back to the QUERYTARGETS_STATE. */
1954 		verbose(VERB_DETAIL, "query response was REFERRAL");
1955 
1956 		/* if hardened, only store referral if we asked for it */
1957 		if(!qstate->env->cfg->harden_referral_path ||
1958 		    (  qstate->qinfo.qtype == LDNS_RR_TYPE_NS
1959 			&& (qstate->query_flags&BIT_RD)
1960 			&& !(qstate->query_flags&BIT_CD)
1961 			   /* we know that all other NS rrsets are scrubbed
1962 			    * away, thus on referral only one is left.
1963 			    * see if that equals the query name... */
1964 			&& ( /* auth section, but sometimes in answer section*/
1965 			  reply_find_rrset_section_ns(iq->response->rep,
1966 				iq->qchase.qname, iq->qchase.qname_len,
1967 				LDNS_RR_TYPE_NS, iq->qchase.qclass)
1968 			  || reply_find_rrset_section_an(iq->response->rep,
1969 				iq->qchase.qname, iq->qchase.qname_len,
1970 				LDNS_RR_TYPE_NS, iq->qchase.qclass)
1971 			  )
1972 		    )) {
1973 			/* Store the referral under the current query */
1974 			/* no prefetch-leeway, since its not the answer */
1975 			iter_dns_store(qstate->env, &iq->response->qinfo,
1976 				iq->response->rep, 1, 0, 0, NULL);
1977 			if(iq->store_parent_NS)
1978 				iter_store_parentside_NS(qstate->env,
1979 					iq->response->rep);
1980 			if(qstate->env->neg_cache)
1981 				val_neg_addreferral(qstate->env->neg_cache,
1982 					iq->response->rep, iq->dp->name);
1983 		}
1984 		/* store parent-side-in-zone-glue, if directly queried for */
1985 		if(iq->query_for_pside_glue && !iq->pside_glue) {
1986 			iq->pside_glue = reply_find_rrset(iq->response->rep,
1987 				iq->qchase.qname, iq->qchase.qname_len,
1988 				iq->qchase.qtype, iq->qchase.qclass);
1989 			if(iq->pside_glue) {
1990 				log_rrset_key(VERB_ALGO, "found parent-side "
1991 					"glue", iq->pside_glue);
1992 				iter_store_parentside_rrset(qstate->env,
1993 					iq->pside_glue);
1994 			}
1995 		}
1996 
1997 		/* Reset the event state, setting the current delegation
1998 		 * point to the referral. */
1999 		iq->deleg_msg = iq->response;
2000 		iq->dp = delegpt_from_message(iq->response, qstate->region);
2001 		if(!iq->dp)
2002 			return error_response(qstate, id, LDNS_RCODE_SERVFAIL);
2003 		if(!cache_fill_missing(qstate->env, iq->qchase.qclass,
2004 			qstate->region, iq->dp))
2005 			return error_response(qstate, id, LDNS_RCODE_SERVFAIL);
2006 		if(iq->store_parent_NS && query_dname_compare(iq->dp->name,
2007 			iq->store_parent_NS->name) == 0)
2008 			iter_merge_retry_counts(iq->dp, iq->store_parent_NS);
2009 		delegpt_log(VERB_ALGO, iq->dp);
2010 		/* Count this as a referral. */
2011 		iq->referral_count++;
2012 		iq->sent_count = 0;
2013 		/* see if the next dp is a trust anchor, or a DS was sent
2014 		 * along, indicating dnssec is expected for next zone */
2015 		iq->dnssec_expected = iter_indicates_dnssec(qstate->env,
2016 			iq->dp, iq->response, iq->qchase.qclass);
2017 		/* if dnssec, validating then also fetch the key for the DS */
2018 		if(iq->dnssec_expected && qstate->env->cfg->prefetch_key &&
2019 			!(qstate->query_flags&BIT_CD))
2020 			generate_dnskey_prefetch(qstate, iq, id);
2021 
2022 		/* spawn off NS and addr to auth servers for the NS we just
2023 		 * got in the referral. This gets authoritative answer
2024 		 * (answer section trust level) rrset.
2025 		 * right after, we detach the subs, answer goes to cache. */
2026 		if(qstate->env->cfg->harden_referral_path)
2027 			generate_ns_check(qstate, iq, id);
2028 
2029 		/* stop current outstanding queries.
2030 		 * FIXME: should the outstanding queries be waited for and
2031 		 * handled? Say by a subquery that inherits the outbound_entry.
2032 		 */
2033 		outbound_list_clear(&iq->outlist);
2034 		iq->num_current_queries = 0;
2035 		fptr_ok(fptr_whitelist_modenv_detach_subs(
2036 			qstate->env->detach_subs));
2037 		(*qstate->env->detach_subs)(qstate);
2038 		iq->num_target_queries = 0;
2039 		verbose(VERB_ALGO, "cleared outbound list for next round");
2040 		return next_state(iq, QUERYTARGETS_STATE);
2041 	} else if(type == RESPONSE_TYPE_CNAME) {
2042 		uint8_t* sname = NULL;
2043 		size_t snamelen = 0;
2044 		/* CNAME type responses get a query restart (i.e., get a
2045 		 * reset of the query state and go back to INIT_REQUEST_STATE).
2046 		 */
2047 		verbose(VERB_DETAIL, "query response was CNAME");
2048 		if(verbosity >= VERB_ALGO)
2049 			log_dns_msg("cname msg", &iq->response->qinfo,
2050 				iq->response->rep);
2051 		/* if qtype is DS, check we have the right level of answer,
2052 		 * like grandchild answer but we need the middle, reject it */
2053 		if(iq->qchase.qtype == LDNS_RR_TYPE_DS && !iq->dsns_point
2054 			&& !(iq->chase_flags&BIT_RD)
2055 			&& iter_ds_toolow(iq->response, iq->dp)
2056 			&& iter_dp_cangodown(&iq->qchase, iq->dp)) {
2057 			outbound_list_clear(&iq->outlist);
2058 			iq->num_current_queries = 0;
2059 			fptr_ok(fptr_whitelist_modenv_detach_subs(
2060 				qstate->env->detach_subs));
2061 			(*qstate->env->detach_subs)(qstate);
2062 			iq->num_target_queries = 0;
2063 			return processDSNSFind(qstate, iq, id);
2064 		}
2065 		/* Process the CNAME response. */
2066 		if(!handle_cname_response(qstate, iq, iq->response,
2067 			&sname, &snamelen))
2068 			return error_response(qstate, id, LDNS_RCODE_SERVFAIL);
2069 		/* cache the CNAME response under the current query */
2070 		/* NOTE : set referral=1, so that rrsets get stored but not
2071 		 * the partial query answer (CNAME only). */
2072 		/* prefetchleeway applied because this updates answer parts */
2073 		iter_dns_store(qstate->env, &iq->response->qinfo,
2074 			iq->response->rep, 1, qstate->prefetch_leeway,
2075 			iq->dp&&iq->dp->has_parent_side_NS, NULL);
2076 		/* set the current request's qname to the new value. */
2077 		iq->qchase.qname = sname;
2078 		iq->qchase.qname_len = snamelen;
2079 		/* Clear the query state, since this is a query restart. */
2080 		iq->deleg_msg = NULL;
2081 		iq->dp = NULL;
2082 		iq->dsns_point = NULL;
2083 		/* Note the query restart. */
2084 		iq->query_restart_count++;
2085 		iq->sent_count = 0;
2086 
2087 		/* stop current outstanding queries.
2088 		 * FIXME: should the outstanding queries be waited for and
2089 		 * handled? Say by a subquery that inherits the outbound_entry.
2090 		 */
2091 		outbound_list_clear(&iq->outlist);
2092 		iq->num_current_queries = 0;
2093 		fptr_ok(fptr_whitelist_modenv_detach_subs(
2094 			qstate->env->detach_subs));
2095 		(*qstate->env->detach_subs)(qstate);
2096 		iq->num_target_queries = 0;
2097 		if(qstate->reply)
2098 			sock_list_insert(&qstate->reply_origin,
2099 				&qstate->reply->addr, qstate->reply->addrlen,
2100 				qstate->region);
2101 		verbose(VERB_ALGO, "cleared outbound list for query restart");
2102 		/* go to INIT_REQUEST_STATE for new qname. */
2103 		return next_state(iq, INIT_REQUEST_STATE);
2104 	} else if(type == RESPONSE_TYPE_LAME) {
2105 		/* Cache the LAMEness. */
2106 		verbose(VERB_DETAIL, "query response was %sLAME",
2107 			dnsseclame?"DNSSEC ":"");
2108 		if(!dname_subdomain_c(iq->qchase.qname, iq->dp->name)) {
2109 			log_err("mark lame: mismatch in qname and dpname");
2110 			/* throwaway this reply below */
2111 		} else if(qstate->reply) {
2112 			/* need addr for lameness cache, but we may have
2113 			 * gotten this from cache, so test to be sure */
2114 			if(!infra_set_lame(qstate->env->infra_cache,
2115 				&qstate->reply->addr, qstate->reply->addrlen,
2116 				iq->dp->name, iq->dp->namelen,
2117 				*qstate->env->now, dnsseclame, 0,
2118 				iq->qchase.qtype))
2119 				log_err("mark host lame: out of memory");
2120 		} else log_err("%slame response from cache",
2121 			dnsseclame?"DNSSEC ":"");
2122 	} else if(type == RESPONSE_TYPE_REC_LAME) {
2123 		/* Cache the LAMEness. */
2124 		verbose(VERB_DETAIL, "query response REC_LAME: "
2125 			"recursive but not authoritative server");
2126 		if(!dname_subdomain_c(iq->qchase.qname, iq->dp->name)) {
2127 			log_err("mark rec_lame: mismatch in qname and dpname");
2128 			/* throwaway this reply below */
2129 		} else if(qstate->reply) {
2130 			/* need addr for lameness cache, but we may have
2131 			 * gotten this from cache, so test to be sure */
2132 			verbose(VERB_DETAIL, "mark as REC_LAME");
2133 			if(!infra_set_lame(qstate->env->infra_cache,
2134 				&qstate->reply->addr, qstate->reply->addrlen,
2135 				iq->dp->name, iq->dp->namelen,
2136 				*qstate->env->now, 0, 1, iq->qchase.qtype))
2137 				log_err("mark host lame: out of memory");
2138 		}
2139 	} else if(type == RESPONSE_TYPE_THROWAWAY) {
2140 		/* LAME and THROWAWAY responses are handled the same way.
2141 		 * In this case, the event is just sent directly back to
2142 		 * the QUERYTARGETS_STATE without resetting anything,
2143 		 * because, clearly, the next target must be tried. */
2144 		verbose(VERB_DETAIL, "query response was THROWAWAY");
2145 	} else {
2146 		log_warn("A query response came back with an unknown type: %d",
2147 			(int)type);
2148 	}
2149 
2150 	/* LAME, THROWAWAY and "unknown" all end up here.
2151 	 * Recycle to the QUERYTARGETS state to hopefully try a
2152 	 * different target. */
2153 	return next_state(iq, QUERYTARGETS_STATE);
2154 }
2155 
2156 /**
2157  * Return priming query results to interestes super querystates.
2158  *
2159  * Sets the delegation point and delegation message (not nonRD queries).
2160  * This is a callback from walk_supers.
2161  *
2162  * @param qstate: priming query state that finished.
2163  * @param id: module id.
2164  * @param forq: the qstate for which priming has been done.
2165  */
2166 static void
2167 prime_supers(struct module_qstate* qstate, int id, struct module_qstate* forq)
2168 {
2169 	struct iter_qstate* foriq = (struct iter_qstate*)forq->minfo[id];
2170 	struct delegpt* dp = NULL;
2171 
2172 	log_assert(qstate->is_priming || foriq->wait_priming_stub);
2173 	log_assert(qstate->return_rcode == LDNS_RCODE_NOERROR);
2174 	/* Convert our response to a delegation point */
2175 	dp = delegpt_from_message(qstate->return_msg, forq->region);
2176 	if(!dp) {
2177 		/* if there is no convertable delegation point, then
2178 		 * the ANSWER type was (presumably) a negative answer. */
2179 		verbose(VERB_ALGO, "prime response was not a positive "
2180 			"ANSWER; failing");
2181 		foriq->dp = NULL;
2182 		foriq->state = QUERYTARGETS_STATE;
2183 		return;
2184 	}
2185 
2186 	log_query_info(VERB_DETAIL, "priming successful for", &qstate->qinfo);
2187 	delegpt_log(VERB_ALGO, dp);
2188 	foriq->dp = dp;
2189 	foriq->deleg_msg = dns_copy_msg(qstate->return_msg, forq->region);
2190 	if(!foriq->deleg_msg) {
2191 		log_err("copy prime response: out of memory");
2192 		foriq->dp = NULL;
2193 		foriq->state = QUERYTARGETS_STATE;
2194 		return;
2195 	}
2196 
2197 	/* root priming responses go to init stage 2, priming stub
2198 	 * responses to to stage 3. */
2199 	if(foriq->wait_priming_stub) {
2200 		foriq->state = INIT_REQUEST_3_STATE;
2201 		foriq->wait_priming_stub = 0;
2202 	} else	foriq->state = INIT_REQUEST_2_STATE;
2203 	/* because we are finished, the parent will be reactivated */
2204 }
2205 
2206 /**
2207  * This handles the response to a priming query. This is used to handle both
2208  * root and stub priming responses. This is basically the equivalent of the
2209  * QUERY_RESP_STATE, but will not handle CNAME responses and will treat
2210  * REFERRALs as ANSWERS. It will also update and reactivate the originating
2211  * event.
2212  *
2213  * @param qstate: query state.
2214  * @param id: module id.
2215  * @return true if the event needs more immediate processing, false if not.
2216  *         This state always returns false.
2217  */
2218 static int
2219 processPrimeResponse(struct module_qstate* qstate, int id)
2220 {
2221 	struct iter_qstate* iq = (struct iter_qstate*)qstate->minfo[id];
2222 	enum response_type type;
2223 	iq->response->rep->flags &= ~(BIT_RD|BIT_RA); /* ignore rec-lame */
2224 	type = response_type_from_server(
2225 		(int)((iq->chase_flags&BIT_RD) || iq->chase_to_rd),
2226 		iq->response, &iq->qchase, iq->dp);
2227 	if(type == RESPONSE_TYPE_ANSWER) {
2228 		qstate->return_rcode = LDNS_RCODE_NOERROR;
2229 		qstate->return_msg = iq->response;
2230 	} else {
2231 		qstate->return_rcode = LDNS_RCODE_SERVFAIL;
2232 		qstate->return_msg = NULL;
2233 	}
2234 
2235 	/* validate the root or stub after priming (if enabled).
2236 	 * This is the same query as the prime query, but with validation.
2237 	 * Now that we are primed, the additional queries that validation
2238 	 * may need can be resolved, such as DLV. */
2239 	if(qstate->env->cfg->harden_referral_path) {
2240 		struct module_qstate* subq = NULL;
2241 		log_nametypeclass(VERB_ALGO, "schedule prime validation",
2242 			qstate->qinfo.qname, qstate->qinfo.qtype,
2243 			qstate->qinfo.qclass);
2244 		if(!generate_sub_request(qstate->qinfo.qname,
2245 			qstate->qinfo.qname_len, qstate->qinfo.qtype,
2246 			qstate->qinfo.qclass, qstate, id, iq,
2247 			INIT_REQUEST_STATE, FINISHED_STATE, &subq, 1)) {
2248 			verbose(VERB_ALGO, "could not generate prime check");
2249 		}
2250 		generate_a_aaaa_check(qstate, iq, id);
2251 	}
2252 
2253 	/* This event is finished. */
2254 	qstate->ext_state[id] = module_finished;
2255 	return 0;
2256 }
2257 
2258 /**
2259  * Do final processing on responses to target queries. Events reach this
2260  * state after the iterative resolution algorithm terminates. This state is
2261  * responsible for reactiving the original event, and housekeeping related
2262  * to received target responses (caching, updating the current delegation
2263  * point, etc).
2264  * Callback from walk_supers for every super state that is interested in
2265  * the results from this query.
2266  *
2267  * @param qstate: query state.
2268  * @param id: module id.
2269  * @param forq: super query state.
2270  */
2271 static void
2272 processTargetResponse(struct module_qstate* qstate, int id,
2273 	struct module_qstate* forq)
2274 {
2275 	struct iter_qstate* iq = (struct iter_qstate*)qstate->minfo[id];
2276 	struct iter_qstate* foriq = (struct iter_qstate*)forq->minfo[id];
2277 	struct ub_packed_rrset_key* rrset;
2278 	struct delegpt_ns* dpns;
2279 	log_assert(qstate->return_rcode == LDNS_RCODE_NOERROR);
2280 
2281 	foriq->state = QUERYTARGETS_STATE;
2282 	log_query_info(VERB_ALGO, "processTargetResponse", &qstate->qinfo);
2283 	log_query_info(VERB_ALGO, "processTargetResponse super", &forq->qinfo);
2284 
2285 	/* check to see if parent event is still interested (in orig name).  */
2286 	if(!foriq->dp) {
2287 		verbose(VERB_ALGO, "subq: parent not interested, was reset");
2288 		return; /* not interested anymore */
2289 	}
2290 	dpns = delegpt_find_ns(foriq->dp, qstate->qinfo.qname,
2291 			qstate->qinfo.qname_len);
2292 	if(!dpns) {
2293 		/* If not interested, just stop processing this event */
2294 		verbose(VERB_ALGO, "subq: parent not interested anymore");
2295 		/* could be because parent was jostled out of the cache,
2296 		   and a new identical query arrived, that does not want it*/
2297 		return;
2298 	}
2299 
2300 	/* Tell the originating event that this target query has finished
2301 	 * (regardless if it succeeded or not). */
2302 	foriq->num_target_queries--;
2303 
2304 	/* if iq->query_for_pside_glue then add the pside_glue (marked lame) */
2305 	if(iq->pside_glue) {
2306 		/* if the pside_glue is NULL, then it could not be found,
2307 		 * the done_pside is already set when created and a cache
2308 		 * entry created in processFinished so nothing to do here */
2309 		log_rrset_key(VERB_ALGO, "add parentside glue to dp",
2310 			iq->pside_glue);
2311 		if(!delegpt_add_rrset(foriq->dp, forq->region,
2312 			iq->pside_glue, 1))
2313 			log_err("out of memory adding pside glue");
2314 	}
2315 
2316 	/* This response is relevant to the current query, so we
2317 	 * add (attempt to add, anyway) this target(s) and reactivate
2318 	 * the original event.
2319 	 * NOTE: we could only look for the AnswerRRset if the
2320 	 * response type was ANSWER. */
2321 	rrset = reply_find_answer_rrset(&iq->qchase, qstate->return_msg->rep);
2322 	if(rrset) {
2323 		/* if CNAMEs have been followed - add new NS to delegpt. */
2324 		/* BTW. RFC 1918 says NS should not have got CNAMEs. Robust. */
2325 		if(!delegpt_find_ns(foriq->dp, rrset->rk.dname,
2326 			rrset->rk.dname_len)) {
2327 			/* if dpns->lame then set newcname ns lame too */
2328 			if(!delegpt_add_ns(foriq->dp, forq->region,
2329 				rrset->rk.dname, (int)dpns->lame))
2330 				log_err("out of memory adding cnamed-ns");
2331 		}
2332 		/* if dpns->lame then set the address(es) lame too */
2333 		if(!delegpt_add_rrset(foriq->dp, forq->region, rrset,
2334 			(int)dpns->lame))
2335 			log_err("out of memory adding targets");
2336 		verbose(VERB_ALGO, "added target response");
2337 		delegpt_log(VERB_ALGO, foriq->dp);
2338 	} else {
2339 		verbose(VERB_ALGO, "iterator TargetResponse failed");
2340 		dpns->resolved = 1; /* fail the target */
2341 	}
2342 }
2343 
2344 /**
2345  * Process response for DS NS Find queries, that attempt to find the delegation
2346  * point where we ask the DS query from.
2347  *
2348  * @param qstate: query state.
2349  * @param id: module id.
2350  * @param forq: super query state.
2351  */
2352 static void
2353 processDSNSResponse(struct module_qstate* qstate, int id,
2354 	struct module_qstate* forq)
2355 {
2356 	struct iter_qstate* foriq = (struct iter_qstate*)forq->minfo[id];
2357 
2358 	/* if the finished (iq->response) query has no NS set: continue
2359 	 * up to look for the right dp; nothing to change, do DPNSstate */
2360 	if(qstate->return_rcode != LDNS_RCODE_NOERROR)
2361 		return; /* seek further */
2362 	/* find the NS RRset (without allowing CNAMEs) */
2363 	if(!reply_find_rrset(qstate->return_msg->rep, qstate->qinfo.qname,
2364 		qstate->qinfo.qname_len, LDNS_RR_TYPE_NS,
2365 		qstate->qinfo.qclass)){
2366 		return; /* seek further */
2367 	}
2368 
2369 	/* else, store as DP and continue at querytargets */
2370 	foriq->state = QUERYTARGETS_STATE;
2371 	foriq->dp = delegpt_from_message(qstate->return_msg, forq->region);
2372 	if(!foriq->dp) {
2373 		log_err("out of memory in dsns dp alloc");
2374 		return; /* dp==NULL in QUERYTARGETS makes SERVFAIL */
2375 	}
2376 	/* success, go query the querytargets in the new dp (and go down) */
2377 }
2378 
2379 /**
2380  * Process response for qclass=ANY queries for a particular class.
2381  * Append to result or error-exit.
2382  *
2383  * @param qstate: query state.
2384  * @param id: module id.
2385  * @param forq: super query state.
2386  */
2387 static void
2388 processClassResponse(struct module_qstate* qstate, int id,
2389 	struct module_qstate* forq)
2390 {
2391 	struct iter_qstate* foriq = (struct iter_qstate*)forq->minfo[id];
2392 	struct dns_msg* from = qstate->return_msg;
2393 	log_query_info(VERB_ALGO, "processClassResponse", &qstate->qinfo);
2394 	log_query_info(VERB_ALGO, "processClassResponse super", &forq->qinfo);
2395 	if(qstate->return_rcode != LDNS_RCODE_NOERROR) {
2396 		/* cause servfail for qclass ANY query */
2397 		foriq->response = NULL;
2398 		foriq->state = FINISHED_STATE;
2399 		return;
2400 	}
2401 	/* append result */
2402 	if(!foriq->response) {
2403 		/* allocate the response: copy RCODE, sec_state */
2404 		foriq->response = dns_copy_msg(from, forq->region);
2405 		if(!foriq->response) {
2406 			log_err("malloc failed for qclass ANY response");
2407 			foriq->state = FINISHED_STATE;
2408 			return;
2409 		}
2410 		foriq->response->qinfo.qclass = forq->qinfo.qclass;
2411 		/* qclass ANY does not receive the AA flag on replies */
2412 		foriq->response->rep->authoritative = 0;
2413 	} else {
2414 		struct dns_msg* to = foriq->response;
2415 		/* add _from_ this response _to_ existing collection */
2416 		/* if there are records, copy RCODE */
2417 		/* lower sec_state if this message is lower */
2418 		if(from->rep->rrset_count != 0) {
2419 			size_t n = from->rep->rrset_count+to->rep->rrset_count;
2420 			struct ub_packed_rrset_key** dest, **d;
2421 			/* copy appropriate rcode */
2422 			to->rep->flags = from->rep->flags;
2423 			/* copy rrsets */
2424 			dest = regional_alloc(forq->region, sizeof(dest[0])*n);
2425 			if(!dest) {
2426 				log_err("malloc failed in collect ANY");
2427 				foriq->state = FINISHED_STATE;
2428 				return;
2429 			}
2430 			d = dest;
2431 			/* copy AN */
2432 			memcpy(dest, to->rep->rrsets, to->rep->an_numrrsets
2433 				* sizeof(dest[0]));
2434 			dest += to->rep->an_numrrsets;
2435 			memcpy(dest, from->rep->rrsets, from->rep->an_numrrsets
2436 				* sizeof(dest[0]));
2437 			dest += from->rep->an_numrrsets;
2438 			/* copy NS */
2439 			memcpy(dest, to->rep->rrsets+to->rep->an_numrrsets,
2440 				to->rep->ns_numrrsets * sizeof(dest[0]));
2441 			dest += to->rep->ns_numrrsets;
2442 			memcpy(dest, from->rep->rrsets+from->rep->an_numrrsets,
2443 				from->rep->ns_numrrsets * sizeof(dest[0]));
2444 			dest += from->rep->ns_numrrsets;
2445 			/* copy AR */
2446 			memcpy(dest, to->rep->rrsets+to->rep->an_numrrsets+
2447 				to->rep->ns_numrrsets,
2448 				to->rep->ar_numrrsets * sizeof(dest[0]));
2449 			dest += to->rep->ar_numrrsets;
2450 			memcpy(dest, from->rep->rrsets+from->rep->an_numrrsets+
2451 				from->rep->ns_numrrsets,
2452 				from->rep->ar_numrrsets * sizeof(dest[0]));
2453 			/* update counts */
2454 			to->rep->rrsets = d;
2455 			to->rep->an_numrrsets += from->rep->an_numrrsets;
2456 			to->rep->ns_numrrsets += from->rep->ns_numrrsets;
2457 			to->rep->ar_numrrsets += from->rep->ar_numrrsets;
2458 			to->rep->rrset_count = n;
2459 		}
2460 		if(from->rep->security < to->rep->security) /* lowest sec */
2461 			to->rep->security = from->rep->security;
2462 		if(from->rep->qdcount != 0) /* insert qd if appropriate */
2463 			to->rep->qdcount = from->rep->qdcount;
2464 		if(from->rep->ttl < to->rep->ttl) /* use smallest TTL */
2465 			to->rep->ttl = from->rep->ttl;
2466 		if(from->rep->prefetch_ttl < to->rep->prefetch_ttl)
2467 			to->rep->prefetch_ttl = from->rep->prefetch_ttl;
2468 	}
2469 	/* are we done? */
2470 	foriq->num_current_queries --;
2471 	if(foriq->num_current_queries == 0)
2472 		foriq->state = FINISHED_STATE;
2473 }
2474 
2475 /**
2476  * Collect class ANY responses and make them into one response.  This
2477  * state is started and it creates queries for all classes (that have
2478  * root hints).  The answers are then collected.
2479  *
2480  * @param qstate: query state.
2481  * @param id: module id.
2482  * @return true if the event needs more immediate processing, false if not.
2483  */
2484 static int
2485 processCollectClass(struct module_qstate* qstate, int id)
2486 {
2487 	struct iter_qstate* iq = (struct iter_qstate*)qstate->minfo[id];
2488 	struct module_qstate* subq;
2489 	/* If qchase.qclass == 0 then send out queries for all classes.
2490 	 * Otherwise, do nothing (wait for all answers to arrive and the
2491 	 * processClassResponse to put them together, and that moves us
2492 	 * towards the Finished state when done. */
2493 	if(iq->qchase.qclass == 0) {
2494 		uint16_t c = 0;
2495 		iq->qchase.qclass = LDNS_RR_CLASS_ANY;
2496 		while(iter_get_next_root(qstate->env->hints,
2497 			qstate->env->fwds, &c)) {
2498 			/* generate query for this class */
2499 			log_nametypeclass(VERB_ALGO, "spawn collect query",
2500 				qstate->qinfo.qname, qstate->qinfo.qtype, c);
2501 			if(!generate_sub_request(qstate->qinfo.qname,
2502 				qstate->qinfo.qname_len, qstate->qinfo.qtype,
2503 				c, qstate, id, iq, INIT_REQUEST_STATE,
2504 				FINISHED_STATE, &subq,
2505 				(int)!(qstate->query_flags&BIT_CD))) {
2506 				return error_response(qstate, id,
2507 					LDNS_RCODE_SERVFAIL);
2508 			}
2509 			/* ignore subq, no special init required */
2510 			iq->num_current_queries ++;
2511 			if(c == 0xffff)
2512 				break;
2513 			else c++;
2514 		}
2515 		/* if no roots are configured at all, return */
2516 		if(iq->num_current_queries == 0) {
2517 			verbose(VERB_ALGO, "No root hints or fwds, giving up "
2518 				"on qclass ANY");
2519 			return error_response(qstate, id, LDNS_RCODE_REFUSED);
2520 		}
2521 		/* return false, wait for queries to return */
2522 	}
2523 	/* if woke up here because of an answer, wait for more answers */
2524 	return 0;
2525 }
2526 
2527 /**
2528  * This handles the final state for first-tier responses (i.e., responses to
2529  * externally generated queries).
2530  *
2531  * @param qstate: query state.
2532  * @param iq: iterator query state.
2533  * @param id: module id.
2534  * @return true if the event needs more processing, false if not. Since this
2535  *         is the final state for an event, it always returns false.
2536  */
2537 static int
2538 processFinished(struct module_qstate* qstate, struct iter_qstate* iq,
2539 	int id)
2540 {
2541 	log_query_info(VERB_QUERY, "finishing processing for",
2542 		&qstate->qinfo);
2543 
2544 	/* store negative cache element for parent side glue. */
2545 	if(iq->query_for_pside_glue && !iq->pside_glue)
2546 		iter_store_parentside_neg(qstate->env, &qstate->qinfo,
2547 			iq->deleg_msg?iq->deleg_msg->rep:
2548 			(iq->response?iq->response->rep:NULL));
2549 	if(!iq->response) {
2550 		verbose(VERB_ALGO, "No response is set, servfail");
2551 		return error_response(qstate, id, LDNS_RCODE_SERVFAIL);
2552 	}
2553 
2554 	/* Make sure that the RA flag is set (since the presence of
2555 	 * this module means that recursion is available) */
2556 	iq->response->rep->flags |= BIT_RA;
2557 
2558 	/* Clear the AA flag */
2559 	/* FIXME: does this action go here or in some other module? */
2560 	iq->response->rep->flags &= ~BIT_AA;
2561 
2562 	/* make sure QR flag is on */
2563 	iq->response->rep->flags |= BIT_QR;
2564 
2565 	/* we have finished processing this query */
2566 	qstate->ext_state[id] = module_finished;
2567 
2568 	/* TODO:  we are using a private TTL, trim the response. */
2569 	/* if (mPrivateTTL > 0){IterUtils.setPrivateTTL(resp, mPrivateTTL); } */
2570 
2571 	/* prepend any items we have accumulated */
2572 	if(iq->an_prepend_list || iq->ns_prepend_list) {
2573 		if(!iter_prepend(iq, iq->response, qstate->region)) {
2574 			log_err("prepend rrsets: out of memory");
2575 			return error_response(qstate, id, LDNS_RCODE_SERVFAIL);
2576 		}
2577 		/* reset the query name back */
2578 		iq->response->qinfo = qstate->qinfo;
2579 		/* the security state depends on the combination */
2580 		iq->response->rep->security = sec_status_unchecked;
2581 		/* store message with the finished prepended items,
2582 		 * but only if we did recursion. The nonrecursion referral
2583 		 * from cache does not need to be stored in the msg cache. */
2584 		if(qstate->query_flags&BIT_RD) {
2585 			iter_dns_store(qstate->env, &qstate->qinfo,
2586 				iq->response->rep, 0, qstate->prefetch_leeway,
2587 				iq->dp&&iq->dp->has_parent_side_NS,
2588 				qstate->region);
2589 		}
2590 	}
2591 	qstate->return_rcode = LDNS_RCODE_NOERROR;
2592 	qstate->return_msg = iq->response;
2593 	return 0;
2594 }
2595 
2596 /*
2597  * Return priming query results to interestes super querystates.
2598  *
2599  * Sets the delegation point and delegation message (not nonRD queries).
2600  * This is a callback from walk_supers.
2601  *
2602  * @param qstate: query state that finished.
2603  * @param id: module id.
2604  * @param super: the qstate to inform.
2605  */
2606 void
2607 iter_inform_super(struct module_qstate* qstate, int id,
2608 	struct module_qstate* super)
2609 {
2610 	if(!qstate->is_priming && super->qinfo.qclass == LDNS_RR_CLASS_ANY)
2611 		processClassResponse(qstate, id, super);
2612 	else if(super->qinfo.qtype == LDNS_RR_TYPE_DS && ((struct iter_qstate*)
2613 		super->minfo[id])->state == DSNS_FIND_STATE)
2614 		processDSNSResponse(qstate, id, super);
2615 	else if(qstate->return_rcode != LDNS_RCODE_NOERROR)
2616 		error_supers(qstate, id, super);
2617 	else if(qstate->is_priming)
2618 		prime_supers(qstate, id, super);
2619 	else	processTargetResponse(qstate, id, super);
2620 }
2621 
2622 /**
2623  * Handle iterator state.
2624  * Handle events. This is the real processing loop for events, responsible
2625  * for moving events through the various states. If a processing method
2626  * returns true, then it will be advanced to the next state. If false, then
2627  * processing will stop.
2628  *
2629  * @param qstate: query state.
2630  * @param ie: iterator shared global environment.
2631  * @param iq: iterator query state.
2632  * @param id: module id.
2633  */
2634 static void
2635 iter_handle(struct module_qstate* qstate, struct iter_qstate* iq,
2636 	struct iter_env* ie, int id)
2637 {
2638 	int cont = 1;
2639 	while(cont) {
2640 		verbose(VERB_ALGO, "iter_handle processing q with state %s",
2641 			iter_state_to_string(iq->state));
2642 		switch(iq->state) {
2643 			case INIT_REQUEST_STATE:
2644 				cont = processInitRequest(qstate, iq, ie, id);
2645 				break;
2646 			case INIT_REQUEST_2_STATE:
2647 				cont = processInitRequest2(qstate, iq, id);
2648 				break;
2649 			case INIT_REQUEST_3_STATE:
2650 				cont = processInitRequest3(qstate, iq, id);
2651 				break;
2652 			case QUERYTARGETS_STATE:
2653 				cont = processQueryTargets(qstate, iq, ie, id);
2654 				break;
2655 			case QUERY_RESP_STATE:
2656 				cont = processQueryResponse(qstate, iq, id);
2657 				break;
2658 			case PRIME_RESP_STATE:
2659 				cont = processPrimeResponse(qstate, id);
2660 				break;
2661 			case COLLECT_CLASS_STATE:
2662 				cont = processCollectClass(qstate, id);
2663 				break;
2664 			case DSNS_FIND_STATE:
2665 				cont = processDSNSFind(qstate, iq, id);
2666 				break;
2667 			case FINISHED_STATE:
2668 				cont = processFinished(qstate, iq, id);
2669 				break;
2670 			default:
2671 				log_warn("iterator: invalid state: %d",
2672 					iq->state);
2673 				cont = 0;
2674 				break;
2675 		}
2676 	}
2677 }
2678 
2679 /**
2680  * This is the primary entry point for processing request events. Note that
2681  * this method should only be used by external modules.
2682  * @param qstate: query state.
2683  * @param ie: iterator shared global environment.
2684  * @param iq: iterator query state.
2685  * @param id: module id.
2686  */
2687 static void
2688 process_request(struct module_qstate* qstate, struct iter_qstate* iq,
2689 	struct iter_env* ie, int id)
2690 {
2691 	/* external requests start in the INIT state, and finish using the
2692 	 * FINISHED state. */
2693 	iq->state = INIT_REQUEST_STATE;
2694 	iq->final_state = FINISHED_STATE;
2695 	verbose(VERB_ALGO, "process_request: new external request event");
2696 	iter_handle(qstate, iq, ie, id);
2697 }
2698 
2699 /** process authoritative server reply */
2700 static void
2701 process_response(struct module_qstate* qstate, struct iter_qstate* iq,
2702 	struct iter_env* ie, int id, struct outbound_entry* outbound,
2703 	enum module_ev event)
2704 {
2705 	struct msg_parse* prs;
2706 	struct edns_data edns;
2707 	ldns_buffer* pkt;
2708 
2709 	verbose(VERB_ALGO, "process_response: new external response event");
2710 	iq->response = NULL;
2711 	iq->state = QUERY_RESP_STATE;
2712 	if(event == module_event_noreply || event == module_event_error) {
2713 		goto handle_it;
2714 	}
2715 	if( (event != module_event_reply && event != module_event_capsfail)
2716 		|| !qstate->reply) {
2717 		log_err("Bad event combined with response");
2718 		outbound_list_remove(&iq->outlist, outbound);
2719 		(void)error_response(qstate, id, LDNS_RCODE_SERVFAIL);
2720 		return;
2721 	}
2722 
2723 	/* parse message */
2724 	prs = (struct msg_parse*)regional_alloc(qstate->env->scratch,
2725 		sizeof(struct msg_parse));
2726 	if(!prs) {
2727 		log_err("out of memory on incoming message");
2728 		/* like packet got dropped */
2729 		goto handle_it;
2730 	}
2731 	memset(prs, 0, sizeof(*prs));
2732 	memset(&edns, 0, sizeof(edns));
2733 	pkt = qstate->reply->c->buffer;
2734 	ldns_buffer_set_position(pkt, 0);
2735 	if(parse_packet(pkt, prs, qstate->env->scratch) != LDNS_RCODE_NOERROR) {
2736 		verbose(VERB_ALGO, "parse error on reply packet");
2737 		goto handle_it;
2738 	}
2739 	/* edns is not examined, but removed from message to help cache */
2740 	if(parse_extract_edns(prs, &edns) != LDNS_RCODE_NOERROR)
2741 		goto handle_it;
2742 	/* remove CD-bit, we asked for in case we handle validation ourself */
2743 	prs->flags &= ~BIT_CD;
2744 
2745 	/* normalize and sanitize: easy to delete items from linked lists */
2746 	if(!scrub_message(pkt, prs, &iq->qchase, iq->dp->name,
2747 		qstate->env->scratch, qstate->env, ie))
2748 		goto handle_it;
2749 
2750 	/* allocate response dns_msg in region */
2751 	iq->response = dns_alloc_msg(pkt, prs, qstate->region);
2752 	if(!iq->response)
2753 		goto handle_it;
2754 	log_query_info(VERB_DETAIL, "response for", &qstate->qinfo);
2755 	log_name_addr(VERB_DETAIL, "reply from", iq->dp->name,
2756 		&qstate->reply->addr, qstate->reply->addrlen);
2757 	if(verbosity >= VERB_ALGO)
2758 		log_dns_msg("incoming scrubbed packet:", &iq->response->qinfo,
2759 			iq->response->rep);
2760 
2761 	if(event == module_event_capsfail) {
2762 		if(!iq->caps_fallback) {
2763 			/* start fallback */
2764 			iq->caps_fallback = 1;
2765 			iq->caps_server = 0;
2766 			iq->caps_reply = iq->response->rep;
2767 			iq->state = QUERYTARGETS_STATE;
2768 			iq->num_current_queries--;
2769 			verbose(VERB_DETAIL, "Capsforid: starting fallback");
2770 			goto handle_it;
2771 		} else {
2772 			/* check if reply is the same, otherwise, fail */
2773 			if(!reply_equal(iq->response->rep, iq->caps_reply,
2774 				qstate->env->scratch_buffer)) {
2775 				verbose(VERB_DETAIL, "Capsforid fallback: "
2776 					"getting different replies, failed");
2777 				outbound_list_remove(&iq->outlist, outbound);
2778 				(void)error_response(qstate, id,
2779 					LDNS_RCODE_SERVFAIL);
2780 				return;
2781 			}
2782 			/* continue the fallback procedure at next server */
2783 			iq->caps_server++;
2784 			iq->state = QUERYTARGETS_STATE;
2785 			iq->num_current_queries--;
2786 			verbose(VERB_DETAIL, "Capsforid: reply is equal. "
2787 				"go to next fallback");
2788 			goto handle_it;
2789 		}
2790 	}
2791 	iq->caps_fallback = 0; /* if we were in fallback, 0x20 is OK now */
2792 
2793 handle_it:
2794 	outbound_list_remove(&iq->outlist, outbound);
2795 	iter_handle(qstate, iq, ie, id);
2796 }
2797 
2798 void
2799 iter_operate(struct module_qstate* qstate, enum module_ev event, int id,
2800 	struct outbound_entry* outbound)
2801 {
2802 	struct iter_env* ie = (struct iter_env*)qstate->env->modinfo[id];
2803 	struct iter_qstate* iq = (struct iter_qstate*)qstate->minfo[id];
2804 	verbose(VERB_QUERY, "iterator[module %d] operate: extstate:%s event:%s",
2805 		id, strextstate(qstate->ext_state[id]), strmodulevent(event));
2806 	if(iq) log_query_info(VERB_QUERY, "iterator operate: query",
2807 		&qstate->qinfo);
2808 	if(iq && qstate->qinfo.qname != iq->qchase.qname)
2809 		log_query_info(VERB_QUERY, "iterator operate: chased to",
2810 			&iq->qchase);
2811 
2812 	/* perform iterator state machine */
2813 	if((event == module_event_new || event == module_event_pass) &&
2814 		iq == NULL) {
2815 		if(!iter_new(qstate, id)) {
2816 			(void)error_response(qstate, id, LDNS_RCODE_SERVFAIL);
2817 			return;
2818 		}
2819 		iq = (struct iter_qstate*)qstate->minfo[id];
2820 		process_request(qstate, iq, ie, id);
2821 		return;
2822 	}
2823 	if(iq && event == module_event_pass) {
2824 		iter_handle(qstate, iq, ie, id);
2825 		return;
2826 	}
2827 	if(iq && outbound) {
2828 		process_response(qstate, iq, ie, id, outbound, event);
2829 		return;
2830 	}
2831 	if(event == module_event_error) {
2832 		verbose(VERB_ALGO, "got called with event error, giving up");
2833 		(void)error_response(qstate, id, LDNS_RCODE_SERVFAIL);
2834 		return;
2835 	}
2836 
2837 	log_err("bad event for iterator");
2838 	(void)error_response(qstate, id, LDNS_RCODE_SERVFAIL);
2839 }
2840 
2841 void
2842 iter_clear(struct module_qstate* qstate, int id)
2843 {
2844 	struct iter_qstate* iq;
2845 	if(!qstate)
2846 		return;
2847 	iq = (struct iter_qstate*)qstate->minfo[id];
2848 	if(iq) {
2849 		outbound_list_clear(&iq->outlist);
2850 		iq->num_current_queries = 0;
2851 	}
2852 	qstate->minfo[id] = NULL;
2853 }
2854 
2855 size_t
2856 iter_get_mem(struct module_env* env, int id)
2857 {
2858 	struct iter_env* ie = (struct iter_env*)env->modinfo[id];
2859 	if(!ie)
2860 		return 0;
2861 	return sizeof(*ie) + sizeof(int)*((size_t)ie->max_dependency_depth+1)
2862 		+ donotq_get_mem(ie->donotq) + priv_get_mem(ie->priv);
2863 }
2864 
2865 /**
2866  * The iterator function block
2867  */
2868 static struct module_func_block iter_block = {
2869 	"iterator",
2870 	&iter_init, &iter_deinit, &iter_operate, &iter_inform_super,
2871 	&iter_clear, &iter_get_mem
2872 };
2873 
2874 struct module_func_block*
2875 iter_get_funcblock(void)
2876 {
2877 	return &iter_block;
2878 }
2879 
2880 const char*
2881 iter_state_to_string(enum iter_state state)
2882 {
2883 	switch (state)
2884 	{
2885 	case INIT_REQUEST_STATE :
2886 		return "INIT REQUEST STATE";
2887 	case INIT_REQUEST_2_STATE :
2888 		return "INIT REQUEST STATE (stage 2)";
2889 	case INIT_REQUEST_3_STATE:
2890 		return "INIT REQUEST STATE (stage 3)";
2891 	case QUERYTARGETS_STATE :
2892 		return "QUERY TARGETS STATE";
2893 	case PRIME_RESP_STATE :
2894 		return "PRIME RESPONSE STATE";
2895 	case COLLECT_CLASS_STATE :
2896 		return "COLLECT CLASS STATE";
2897 	case DSNS_FIND_STATE :
2898 		return "DSNS FIND STATE";
2899 	case QUERY_RESP_STATE :
2900 		return "QUERY RESPONSE STATE";
2901 	case FINISHED_STATE :
2902 		return "FINISHED RESPONSE STATE";
2903 	default :
2904 		return "UNKNOWN ITER STATE";
2905 	}
2906 }
2907 
2908 int
2909 iter_state_is_responsestate(enum iter_state s)
2910 {
2911 	switch(s) {
2912 		case INIT_REQUEST_STATE :
2913 		case INIT_REQUEST_2_STATE :
2914 		case INIT_REQUEST_3_STATE :
2915 		case QUERYTARGETS_STATE :
2916 		case COLLECT_CLASS_STATE :
2917 			return 0;
2918 		default:
2919 			break;
2920 	}
2921 	return 1;
2922 }
2923