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