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