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