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