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