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