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