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