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