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