xref: /openbsd-src/usr.sbin/unbound/iterator/iterator.c (revision 4c1e55dc91edd6e69ccc60ce855900fbc12cf34f)
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 LIMITED
25  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
26  * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE
27  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
28  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
29  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
30  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
31  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
32  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
33  * POSSIBILITY OF SUCH DAMAGE.
34  */
35 
36 /**
37  * \file
38  *
39  * This file contains a module that performs recusive iterative DNS query
40  * processing.
41  */
42 
43 #include "config.h"
44 #include <ldns/ldns.h>
45 #include "iterator/iterator.h"
46 #include "iterator/iter_utils.h"
47 #include "iterator/iter_hints.h"
48 #include "iterator/iter_fwd.h"
49 #include "iterator/iter_donotq.h"
50 #include "iterator/iter_delegpt.h"
51 #include "iterator/iter_resptype.h"
52 #include "iterator/iter_scrub.h"
53 #include "iterator/iter_priv.h"
54 #include "validator/val_neg.h"
55 #include "services/cache/dns.h"
56 #include "services/cache/infra.h"
57 #include "util/module.h"
58 #include "util/netevent.h"
59 #include "util/net_help.h"
60 #include "util/regional.h"
61 #include "util/data/dname.h"
62 #include "util/data/msgencode.h"
63 #include "util/fptr_wlist.h"
64 #include "util/config_file.h"
65 
66 int
67 iter_init(struct module_env* env, int id)
68 {
69 	struct iter_env* iter_env = (struct iter_env*)calloc(1,
70 		sizeof(struct iter_env));
71 	if(!iter_env) {
72 		log_err("malloc failure");
73 		return 0;
74 	}
75 	env->modinfo[id] = (void*)iter_env;
76 	if(!iter_apply_cfg(iter_env, env->cfg)) {
77 		log_err("iterator: could not apply configuration settings.");
78 		return 0;
79 	}
80 	return 1;
81 }
82 
83 void
84 iter_deinit(struct module_env* env, int id)
85 {
86 	struct iter_env* iter_env;
87 	if(!env || !env->modinfo[id])
88 		return;
89 	iter_env = (struct iter_env*)env->modinfo[id];
90 	free(iter_env->target_fetch_policy);
91 	priv_delete(iter_env->priv);
92 	hints_delete(iter_env->hints);
93 	donotq_delete(iter_env->donotq);
94 	free(iter_env);
95 	env->modinfo[id] = NULL;
96 }
97 
98 /** new query for iterator */
99 static int
100 iter_new(struct module_qstate* qstate, int id)
101 {
102 	struct iter_qstate* iq = (struct iter_qstate*)regional_alloc(
103 		qstate->region, sizeof(struct iter_qstate));
104 	qstate->minfo[id] = iq;
105 	if(!iq)
106 		return 0;
107 	memset(iq, 0, sizeof(*iq));
108 	iq->state = INIT_REQUEST_STATE;
109 	iq->final_state = FINISHED_STATE;
110 	iq->an_prepend_list = NULL;
111 	iq->an_prepend_last = NULL;
112 	iq->ns_prepend_list = NULL;
113 	iq->ns_prepend_last = NULL;
114 	iq->dp = NULL;
115 	iq->depth = 0;
116 	iq->num_target_queries = 0;
117 	iq->num_current_queries = 0;
118 	iq->query_restart_count = 0;
119 	iq->referral_count = 0;
120 	iq->sent_count = 0;
121 	iq->wait_priming_stub = 0;
122 	iq->refetch_glue = 0;
123 	iq->dnssec_expected = 0;
124 	iq->dnssec_lame_query = 0;
125 	iq->chase_flags = qstate->query_flags;
126 	/* Start with the (current) qname. */
127 	iq->qchase = qstate->qinfo;
128 	outbound_list_init(&iq->outlist);
129 	return 1;
130 }
131 
132 /**
133  * Transition to the next state. This can be used to advance a currently
134  * processing event. It cannot be used to reactivate a forEvent.
135  *
136  * @param iq: iterator query state
137  * @param nextstate The state to transition to.
138  * @return true. This is so this can be called as the return value for the
139  *         actual process*State() methods. (Transitioning to the next state
140  *         implies further processing).
141  */
142 static int
143 next_state(struct iter_qstate* iq, enum iter_state nextstate)
144 {
145 	/* If transitioning to a "response" state, make sure that there is a
146 	 * response */
147 	if(iter_state_is_responsestate(nextstate)) {
148 		if(iq->response == NULL) {
149 			log_err("transitioning to response state sans "
150 				"response.");
151 		}
152 	}
153 	iq->state = nextstate;
154 	return 1;
155 }
156 
157 /**
158  * Transition an event to its final state. Final states always either return
159  * a result up the module chain, or reactivate a dependent event. Which
160  * final state to transtion to is set in the module state for the event when
161  * it was created, and depends on the original purpose of the event.
162  *
163  * The response is stored in the qstate->buf buffer.
164  *
165  * @param iq: iterator query state
166  * @return false. This is so this method can be used as the return value for
167  *         the processState methods. (Transitioning to the final state
168  */
169 static int
170 final_state(struct iter_qstate* iq)
171 {
172 	return next_state(iq, iq->final_state);
173 }
174 
175 /**
176  * Callback routine to handle errors in parent query states
177  * @param qstate: query state that failed.
178  * @param id: module id.
179  * @param super: super state.
180  */
181 static void
182 error_supers(struct module_qstate* qstate, int id, struct module_qstate* super)
183 {
184 	struct iter_qstate* super_iq = (struct iter_qstate*)super->minfo[id];
185 
186 	if(qstate->qinfo.qtype == LDNS_RR_TYPE_A ||
187 		qstate->qinfo.qtype == LDNS_RR_TYPE_AAAA) {
188 		/* mark address as failed. */
189 		struct delegpt_ns* dpns = NULL;
190 		if(super_iq->dp)
191 			dpns = delegpt_find_ns(super_iq->dp,
192 				qstate->qinfo.qname, qstate->qinfo.qname_len);
193 		if(!dpns) {
194 			/* not interested */
195 			verbose(VERB_ALGO, "subq error, but not interested");
196 			log_query_info(VERB_ALGO, "superq", &super->qinfo);
197 			if(super_iq->dp)
198 				delegpt_log(VERB_ALGO, super_iq->dp);
199 			log_assert(0);
200 			return;
201 		} else {
202 			/* see if the failure did get (parent-lame) info */
203 			if(!cache_fill_missing(super->env,
204 				super_iq->qchase.qclass, super->region,
205 				super_iq->dp))
206 				log_err("out of memory adding missing");
207 		}
208 		dpns->resolved = 1; /* mark as failed */
209 		super_iq->num_target_queries--;
210 	}
211 	if(qstate->qinfo.qtype == LDNS_RR_TYPE_NS) {
212 		/* prime failed to get delegation */
213 		super_iq->dp = NULL;
214 	}
215 	/* evaluate targets again */
216 	super_iq->state = QUERYTARGETS_STATE;
217 	/* super becomes runnable, and will process this change */
218 }
219 
220 /**
221  * Return an error to the client
222  * @param qstate: our query state
223  * @param id: module id
224  * @param rcode: error code (DNS errcode).
225  * @return: 0 for use by caller, to make notation easy, like:
226  * 	return error_response(..).
227  */
228 static int
229 error_response(struct module_qstate* qstate, int id, int rcode)
230 {
231 	verbose(VERB_QUERY, "return error response %s",
232 		ldns_lookup_by_id(ldns_rcodes, rcode)?
233 		ldns_lookup_by_id(ldns_rcodes, rcode)->name:"??");
234 	qstate->return_rcode = rcode;
235 	qstate->return_msg = NULL;
236 	qstate->ext_state[id] = module_finished;
237 	return 0;
238 }
239 
240 /**
241  * Return an error to the client and cache the error code in the
242  * message cache (so per qname, qtype, qclass).
243  * @param qstate: our query state
244  * @param id: module id
245  * @param rcode: error code (DNS errcode).
246  * @return: 0 for use by caller, to make notation easy, like:
247  * 	return error_response(..).
248  */
249 static int
250 error_response_cache(struct module_qstate* qstate, int id, int rcode)
251 {
252 	/* store in cache */
253 	struct reply_info err;
254 	memset(&err, 0, sizeof(err));
255 	err.flags = (uint16_t)(BIT_QR | BIT_RA);
256 	FLAGS_SET_RCODE(err.flags, rcode);
257 	err.qdcount = 1;
258 	err.ttl = NORR_TTL;
259 	err.prefetch_ttl = PREFETCH_TTL_CALC(err.ttl);
260 	/* do not waste time trying to validate this servfail */
261 	err.security = sec_status_indeterminate;
262 	verbose(VERB_ALGO, "store error response in message cache");
263 	if(!iter_dns_store(qstate->env, &qstate->qinfo, &err, 0, 0, NULL)) {
264 		log_err("error_response_cache: could not store error (nomem)");
265 	}
266 	return error_response(qstate, id, rcode);
267 }
268 
269 /** check if prepend item is duplicate item */
270 static int
271 prepend_is_duplicate(struct ub_packed_rrset_key** sets, size_t to,
272 	struct ub_packed_rrset_key* dup)
273 {
274 	size_t i;
275 	for(i=0; i<to; i++) {
276 		if(sets[i]->rk.type == dup->rk.type &&
277 			sets[i]->rk.rrset_class == dup->rk.rrset_class &&
278 			sets[i]->rk.dname_len == dup->rk.dname_len &&
279 			query_dname_compare(sets[i]->rk.dname, dup->rk.dname)
280 			== 0)
281 			return 1;
282 	}
283 	return 0;
284 }
285 
286 /** prepend the prepend list in the answer and authority section of dns_msg */
287 static int
288 iter_prepend(struct iter_qstate* iq, struct dns_msg* msg,
289 	struct regional* region)
290 {
291 	struct iter_prep_list* p;
292 	struct ub_packed_rrset_key** sets;
293 	size_t num_an = 0, num_ns = 0;;
294 	for(p = iq->an_prepend_list; p; p = p->next)
295 		num_an++;
296 	for(p = iq->ns_prepend_list; p; p = p->next)
297 		num_ns++;
298 	if(num_an + num_ns == 0)
299 		return 1;
300 	verbose(VERB_ALGO, "prepending %d rrsets", (int)num_an + (int)num_ns);
301 	sets = regional_alloc(region, (num_an+num_ns+msg->rep->rrset_count) *
302 		sizeof(struct ub_packed_rrset_key*));
303 	if(!sets)
304 		return 0;
305 	/* ANSWER section */
306 	num_an = 0;
307 	for(p = iq->an_prepend_list; p; p = p->next) {
308 		sets[num_an++] = p->rrset;
309 	}
310 	memcpy(sets+num_an, msg->rep->rrsets, msg->rep->an_numrrsets *
311 		sizeof(struct ub_packed_rrset_key*));
312 	/* AUTH section */
313 	num_ns = 0;
314 	for(p = iq->ns_prepend_list; p; p = p->next) {
315 		if(prepend_is_duplicate(sets+msg->rep->an_numrrsets+num_an,
316 			num_ns, p->rrset) || prepend_is_duplicate(
317 			msg->rep->rrsets+msg->rep->an_numrrsets,
318 			msg->rep->ns_numrrsets, p->rrset))
319 			continue;
320 		sets[msg->rep->an_numrrsets + num_an + num_ns++] = p->rrset;
321 	}
322 	memcpy(sets + num_an + msg->rep->an_numrrsets + num_ns,
323 		msg->rep->rrsets + msg->rep->an_numrrsets,
324 		(msg->rep->ns_numrrsets + msg->rep->ar_numrrsets) *
325 		sizeof(struct ub_packed_rrset_key*));
326 
327 	/* NXDOMAIN rcode can stay if we prepended DNAME/CNAMEs, because
328 	 * this is what recursors should give. */
329 	msg->rep->rrset_count += num_an + num_ns;
330 	msg->rep->an_numrrsets += num_an;
331 	msg->rep->ns_numrrsets += num_ns;
332 	msg->rep->rrsets = sets;
333 	return 1;
334 }
335 
336 /**
337  * Add rrset to ANSWER prepend list
338  * @param qstate: query state.
339  * @param iq: iterator query state.
340  * @param rrset: rrset to add.
341  * @return false on failure (malloc).
342  */
343 static int
344 iter_add_prepend_answer(struct module_qstate* qstate, struct iter_qstate* iq,
345 	struct ub_packed_rrset_key* rrset)
346 {
347 	struct iter_prep_list* p = (struct iter_prep_list*)regional_alloc(
348 		qstate->region, sizeof(struct iter_prep_list));
349 	if(!p)
350 		return 0;
351 	p->rrset = rrset;
352 	p->next = NULL;
353 	/* add at end */
354 	if(iq->an_prepend_last)
355 		iq->an_prepend_last->next = p;
356 	else	iq->an_prepend_list = p;
357 	iq->an_prepend_last = p;
358 	return 1;
359 }
360 
361 /**
362  * Add rrset to AUTHORITY prepend list
363  * @param qstate: query state.
364  * @param iq: iterator query state.
365  * @param rrset: rrset to add.
366  * @return false on failure (malloc).
367  */
368 static int
369 iter_add_prepend_auth(struct module_qstate* qstate, struct iter_qstate* iq,
370 	struct ub_packed_rrset_key* rrset)
371 {
372 	struct iter_prep_list* p = (struct iter_prep_list*)regional_alloc(
373 		qstate->region, sizeof(struct iter_prep_list));
374 	if(!p)
375 		return 0;
376 	p->rrset = rrset;
377 	p->next = NULL;
378 	/* add at end */
379 	if(iq->ns_prepend_last)
380 		iq->ns_prepend_last->next = p;
381 	else	iq->ns_prepend_list = p;
382 	iq->ns_prepend_last = p;
383 	return 1;
384 }
385 
386 /**
387  * Given a CNAME response (defined as a response containing a CNAME or DNAME
388  * that does not answer the request), process the response, modifying the
389  * state as necessary. This follows the CNAME/DNAME chain and returns the
390  * final query name.
391  *
392  * sets the new query name, after following the CNAME/DNAME chain.
393  * @param qstate: query state.
394  * @param iq: iterator query state.
395  * @param msg: the response.
396  * @param mname: returned target new query name.
397  * @param mname_len: length of mname.
398  * @return false on (malloc) error.
399  */
400 static int
401 handle_cname_response(struct module_qstate* qstate, struct iter_qstate* iq,
402         struct dns_msg* msg, uint8_t** mname, size_t* mname_len)
403 {
404 	size_t i;
405 	/* Start with the (current) qname. */
406 	*mname = iq->qchase.qname;
407 	*mname_len = iq->qchase.qname_len;
408 
409 	/* Iterate over the ANSWER rrsets in order, looking for CNAMEs and
410 	 * DNAMES. */
411 	for(i=0; i<msg->rep->an_numrrsets; i++) {
412 		struct ub_packed_rrset_key* r = msg->rep->rrsets[i];
413 		/* If there is a (relevant) DNAME, add it to the list.
414 		 * We always expect there to be CNAME that was generated
415 		 * by this DNAME following, so we don't process the DNAME
416 		 * directly.  */
417 		if(ntohs(r->rk.type) == LDNS_RR_TYPE_DNAME &&
418 			dname_strict_subdomain_c(*mname, r->rk.dname)) {
419 			if(!iter_add_prepend_answer(qstate, iq, r))
420 				return 0;
421 			continue;
422 		}
423 
424 		if(ntohs(r->rk.type) == LDNS_RR_TYPE_CNAME &&
425 			query_dname_compare(*mname, r->rk.dname) == 0) {
426 			/* Add this relevant CNAME rrset to the prepend list.*/
427 			if(!iter_add_prepend_answer(qstate, iq, r))
428 				return 0;
429 			get_cname_target(r, mname, mname_len);
430 		}
431 
432 		/* Other rrsets in the section are ignored. */
433 	}
434 	/* add authority rrsets to authority prepend, for wildcarded CNAMEs */
435 	for(i=msg->rep->an_numrrsets; i<msg->rep->an_numrrsets +
436 		msg->rep->ns_numrrsets; i++) {
437 		struct ub_packed_rrset_key* r = msg->rep->rrsets[i];
438 		/* only add NSEC/NSEC3, as they may be needed for validation */
439 		if(ntohs(r->rk.type) == LDNS_RR_TYPE_NSEC ||
440 			ntohs(r->rk.type) == LDNS_RR_TYPE_NSEC3) {
441 			if(!iter_add_prepend_auth(qstate, iq, r))
442 				return 0;
443 		}
444 	}
445 	return 1;
446 }
447 
448 /**
449  * Generate a subrequest.
450  * Generate a local request event. Local events are tied to this module, and
451  * have a correponding (first tier) event that is waiting for this event to
452  * resolve to continue.
453  *
454  * @param qname The query name for this request.
455  * @param qnamelen length of qname
456  * @param qtype The query type for this request.
457  * @param qclass The query class for this request.
458  * @param qstate The event that is generating this event.
459  * @param id: module id.
460  * @param iq: The iterator state that is generating this event.
461  * @param initial_state The initial response state (normally this
462  *          is QUERY_RESP_STATE, unless it is known that the request won't
463  *          need iterative processing
464  * @param finalstate The final state for the response to this request.
465  * @param subq_ret: if newly allocated, the subquerystate, or NULL if it does
466  * 	not need initialisation.
467  * @param v: if true, validation is done on the subquery.
468  * @return false on error (malloc).
469  */
470 static int
471 generate_sub_request(uint8_t* qname, size_t qnamelen, uint16_t qtype,
472 	uint16_t qclass, struct module_qstate* qstate, int id,
473 	struct iter_qstate* iq, enum iter_state initial_state,
474 	enum iter_state finalstate, struct module_qstate** subq_ret, int v)
475 {
476 	struct module_qstate* subq = NULL;
477 	struct iter_qstate* subiq = NULL;
478 	uint16_t qflags = 0; /* OPCODE QUERY, no flags */
479 	struct query_info qinf;
480 	int prime = (finalstate == PRIME_RESP_STATE)?1:0;
481 	qinf.qname = qname;
482 	qinf.qname_len = qnamelen;
483 	qinf.qtype = qtype;
484 	qinf.qclass = qclass;
485 
486 	/* RD should be set only when sending the query back through the INIT
487 	 * state. */
488 	if(initial_state == INIT_REQUEST_STATE)
489 		qflags |= BIT_RD;
490 	/* We set the CD flag so we can send this through the "head" of
491 	 * the resolution chain, which might have a validator. We are
492 	 * uninterested in validating things not on the direct resolution
493 	 * path.  */
494 	if(!v)
495 		qflags |= BIT_CD;
496 
497 	/* attach subquery, lookup existing or make a new one */
498 	fptr_ok(fptr_whitelist_modenv_attach_sub(qstate->env->attach_sub));
499 	if(!(*qstate->env->attach_sub)(qstate, &qinf, qflags, prime, &subq)) {
500 		return 0;
501 	}
502 	*subq_ret = subq;
503 	if(subq) {
504 		/* initialise the new subquery */
505 		subq->curmod = id;
506 		subq->ext_state[id] = module_state_initial;
507 		subq->minfo[id] = regional_alloc(subq->region,
508 			sizeof(struct iter_qstate));
509 		if(!subq->minfo[id]) {
510 			log_err("init subq: out of memory");
511 			fptr_ok(fptr_whitelist_modenv_kill_sub(
512 				qstate->env->kill_sub));
513 			(*qstate->env->kill_sub)(subq);
514 			return 0;
515 		}
516 		subiq = (struct iter_qstate*)subq->minfo[id];
517 		memset(subiq, 0, sizeof(*subiq));
518 		subiq->num_target_queries = 0;
519 		subiq->num_current_queries = 0;
520 		subiq->depth = iq->depth+1;
521 		outbound_list_init(&subiq->outlist);
522 		subiq->state = initial_state;
523 		subiq->final_state = finalstate;
524 		subiq->qchase = subq->qinfo;
525 		subiq->chase_flags = subq->query_flags;
526 		subiq->refetch_glue = 0;
527 	}
528 	return 1;
529 }
530 
531 /**
532  * Generate and send a root priming request.
533  * @param qstate: the qtstate that triggered the need to prime.
534  * @param iq: iterator query state.
535  * @param ie: iterator global state.
536  * @param id: module id.
537  * @param qclass: the class to prime.
538  * @return 0 on failure
539  */
540 static int
541 prime_root(struct module_qstate* qstate, struct iter_qstate* iq,
542 	struct iter_env* ie, int id, uint16_t qclass)
543 {
544 	struct delegpt* dp;
545 	struct module_qstate* subq;
546 	verbose(VERB_DETAIL, "priming . %s NS",
547 		ldns_lookup_by_id(ldns_rr_classes, (int)qclass)?
548 		ldns_lookup_by_id(ldns_rr_classes, (int)qclass)->name:"??");
549 	dp = hints_lookup_root(ie->hints, qclass);
550 	if(!dp) {
551 		verbose(VERB_ALGO, "Cannot prime due to lack of hints");
552 		return 0;
553 	}
554 	/* Priming requests start at the QUERYTARGETS state, skipping
555 	 * the normal INIT state logic (which would cause an infloop). */
556 	if(!generate_sub_request((uint8_t*)"\000", 1, LDNS_RR_TYPE_NS,
557 		qclass, qstate, id, iq, QUERYTARGETS_STATE, PRIME_RESP_STATE,
558 		&subq, 0)) {
559 		verbose(VERB_ALGO, "could not prime root");
560 		return 0;
561 	}
562 	if(subq) {
563 		struct iter_qstate* subiq =
564 			(struct iter_qstate*)subq->minfo[id];
565 		/* Set the initial delegation point to the hint.
566 		 * copy dp, it is now part of the root prime query.
567 		 * dp was part of in the fixed hints structure. */
568 		subiq->dp = delegpt_copy(dp, subq->region);
569 		if(!subiq->dp) {
570 			log_err("out of memory priming root, copydp");
571 			fptr_ok(fptr_whitelist_modenv_kill_sub(
572 				qstate->env->kill_sub));
573 			(*qstate->env->kill_sub)(subq);
574 			return 0;
575 		}
576 		/* there should not be any target queries. */
577 		subiq->num_target_queries = 0;
578 		subiq->dnssec_expected = iter_indicates_dnssec(
579 			qstate->env, subiq->dp, NULL, subq->qinfo.qclass);
580 	}
581 
582 	/* this module stops, our submodule starts, and does the query. */
583 	qstate->ext_state[id] = module_wait_subquery;
584 	return 1;
585 }
586 
587 /**
588  * Generate and process a stub priming request. This method tests for the
589  * need to prime a stub zone, so it is safe to call for every request.
590  *
591  * @param qstate: the qtstate that triggered the need to prime.
592  * @param iq: iterator query state.
593  * @param ie: iterator global state.
594  * @param id: module id.
595  * @param q: request name.
596  * @return true if a priming subrequest was made, false if not. The will only
597  *         issue a priming request if it detects an unprimed stub.
598  *         Uses value of 2 to signal during stub-prime in root-prime situation
599  *         that a noprime-stub is available and resolution can continue.
600  */
601 static int
602 prime_stub(struct module_qstate* qstate, struct iter_qstate* iq,
603 	struct iter_env* ie, int id, struct query_info* q)
604 {
605 	/* Lookup the stub hint. This will return null if the stub doesn't
606 	 * need to be re-primed. */
607 	struct iter_hints_stub* stub;
608 	struct delegpt* stub_dp;
609 	struct module_qstate* subq;
610 	uint8_t* delname = q->qname;
611 	size_t delnamelen = q->qname_len;
612 
613 	if(q->qtype == LDNS_RR_TYPE_DS && !dname_is_root(q->qname))
614 		/* remove first label, but not for root */
615 		dname_remove_label(&delname, &delnamelen);
616 
617 	stub = hints_lookup_stub(ie->hints, delname, q->qclass, iq->dp);
618 	/* The stub (if there is one) does not need priming. */
619 	if(!stub)
620 		return 0;
621 	stub_dp = stub->dp;
622 
623 	/* is it a noprime stub (always use) */
624 	if(stub->noprime) {
625 		int r = 0;
626 		if(iq->dp == NULL) r = 2;
627 		/* copy the dp out of the fixed hints structure, so that
628 		 * it can be changed when servicing this query */
629 		iq->dp = delegpt_copy(stub_dp, qstate->region);
630 		if(!iq->dp) {
631 			log_err("out of memory priming stub");
632 			(void)error_response(qstate, id, LDNS_RCODE_SERVFAIL);
633 			return 1; /* return 1 to make module stop, with error */
634 		}
635 		log_nametypeclass(VERB_DETAIL, "use stub", stub_dp->name,
636 			LDNS_RR_TYPE_NS, q->qclass);
637 		return r;
638 	}
639 
640 	/* Otherwise, we need to (re)prime the stub. */
641 	log_nametypeclass(VERB_DETAIL, "priming stub", stub_dp->name,
642 		LDNS_RR_TYPE_NS, q->qclass);
643 
644 	/* Stub priming events start at the QUERYTARGETS state to avoid the
645 	 * redundant INIT state processing. */
646 	if(!generate_sub_request(stub_dp->name, stub_dp->namelen,
647 		LDNS_RR_TYPE_NS, q->qclass, qstate, id, iq,
648 		QUERYTARGETS_STATE, PRIME_RESP_STATE, &subq, 0)) {
649 		verbose(VERB_ALGO, "could not prime stub");
650 		(void)error_response(qstate, id, LDNS_RCODE_SERVFAIL);
651 		return 1; /* return 1 to make module stop, with error */
652 	}
653 	if(subq) {
654 		struct iter_qstate* subiq =
655 			(struct iter_qstate*)subq->minfo[id];
656 
657 		/* Set the initial delegation point to the hint. */
658 		/* make copy to avoid use of stub dp by different qs/threads */
659 		subiq->dp = delegpt_copy(stub_dp, subq->region);
660 		if(!subiq->dp) {
661 			log_err("out of memory priming stub, copydp");
662 			fptr_ok(fptr_whitelist_modenv_kill_sub(
663 				qstate->env->kill_sub));
664 			(*qstate->env->kill_sub)(subq);
665 			(void)error_response(qstate, id, LDNS_RCODE_SERVFAIL);
666 			return 1; /* return 1 to make module stop, with error */
667 		}
668 		/* there should not be any target queries -- although there
669 		 * wouldn't be anyway, since stub hints never have
670 		 * missing targets. */
671 		subiq->num_target_queries = 0;
672 		subiq->wait_priming_stub = 1;
673 		subiq->dnssec_expected = iter_indicates_dnssec(
674 			qstate->env, subiq->dp, NULL, subq->qinfo.qclass);
675 	}
676 
677 	/* this module stops, our submodule starts, and does the query. */
678 	qstate->ext_state[id] = module_wait_subquery;
679 	return 1;
680 }
681 
682 /**
683  * Generate A and AAAA checks for glue that is in-zone for the referral
684  * we just got to obtain authoritative information on the adresses.
685  *
686  * @param qstate: the qtstate that triggered the need to prime.
687  * @param iq: iterator query state.
688  * @param id: module id.
689  */
690 static void
691 generate_a_aaaa_check(struct module_qstate* qstate, struct iter_qstate* iq,
692 	int id)
693 {
694 	struct iter_env* ie = (struct iter_env*)qstate->env->modinfo[id];
695 	struct module_qstate* subq;
696 	size_t i;
697 	struct reply_info* rep = iq->response->rep;
698 	struct ub_packed_rrset_key* s;
699 	log_assert(iq->dp);
700 
701 	if(iq->depth == ie->max_dependency_depth)
702 		return;
703 	/* walk through additional, and check if in-zone,
704 	 * only relevant A, AAAA are left after scrub anyway */
705 	for(i=rep->an_numrrsets+rep->ns_numrrsets; i<rep->rrset_count; i++) {
706 		s = rep->rrsets[i];
707 		/* check *ALL* addresses that are transmitted in additional*/
708 		/* is it an address ? */
709 		if( !(ntohs(s->rk.type)==LDNS_RR_TYPE_A ||
710 			ntohs(s->rk.type)==LDNS_RR_TYPE_AAAA)) {
711 			continue;
712 		}
713 		/* is this query the same as the A/AAAA check for it */
714 		if(qstate->qinfo.qtype == ntohs(s->rk.type) &&
715 			qstate->qinfo.qclass == ntohs(s->rk.rrset_class) &&
716 			query_dname_compare(qstate->qinfo.qname,
717 				s->rk.dname)==0 &&
718 			(qstate->query_flags&BIT_RD) &&
719 			!(qstate->query_flags&BIT_CD))
720 			continue;
721 
722 		/* generate subrequest for it */
723 		log_nametypeclass(VERB_ALGO, "schedule addr fetch",
724 			s->rk.dname, ntohs(s->rk.type),
725 			ntohs(s->rk.rrset_class));
726 		if(!generate_sub_request(s->rk.dname, s->rk.dname_len,
727 			ntohs(s->rk.type), ntohs(s->rk.rrset_class),
728 			qstate, id, iq,
729 			INIT_REQUEST_STATE, FINISHED_STATE, &subq, 1)) {
730 			verbose(VERB_ALGO, "could not generate addr check");
731 			return;
732 		}
733 		/* ignore subq - not need for more init */
734 	}
735 }
736 
737 /**
738  * Generate a NS check request to obtain authoritative information
739  * on an NS rrset.
740  *
741  * @param qstate: the qtstate that triggered the need to prime.
742  * @param iq: iterator query state.
743  * @param id: module id.
744  */
745 static void
746 generate_ns_check(struct module_qstate* qstate, struct iter_qstate* iq, int id)
747 {
748 	struct iter_env* ie = (struct iter_env*)qstate->env->modinfo[id];
749 	struct module_qstate* subq;
750 	log_assert(iq->dp);
751 
752 	if(iq->depth == ie->max_dependency_depth)
753 		return;
754 	/* is this query the same as the nscheck? */
755 	if(qstate->qinfo.qtype == LDNS_RR_TYPE_NS &&
756 		query_dname_compare(iq->dp->name, qstate->qinfo.qname)==0 &&
757 		(qstate->query_flags&BIT_RD) && !(qstate->query_flags&BIT_CD)){
758 		/* spawn off A, AAAA queries for in-zone glue to check */
759 		generate_a_aaaa_check(qstate, iq, id);
760 		return;
761 	}
762 
763 	log_nametypeclass(VERB_ALGO, "schedule ns fetch",
764 		iq->dp->name, LDNS_RR_TYPE_NS, iq->qchase.qclass);
765 	if(!generate_sub_request(iq->dp->name, iq->dp->namelen,
766 		LDNS_RR_TYPE_NS, iq->qchase.qclass, qstate, id, iq,
767 		INIT_REQUEST_STATE, FINISHED_STATE, &subq, 1)) {
768 		verbose(VERB_ALGO, "could not generate ns check");
769 		return;
770 	}
771 	if(subq) {
772 		struct iter_qstate* subiq =
773 			(struct iter_qstate*)subq->minfo[id];
774 
775 		/* make copy to avoid use of stub dp by different qs/threads */
776 		/* refetch glue to start higher up the tree */
777 		subiq->refetch_glue = 1;
778 		subiq->dp = delegpt_copy(iq->dp, subq->region);
779 		if(!subiq->dp) {
780 			log_err("out of memory generating ns check, copydp");
781 			fptr_ok(fptr_whitelist_modenv_kill_sub(
782 				qstate->env->kill_sub));
783 			(*qstate->env->kill_sub)(subq);
784 			return;
785 		}
786 	}
787 }
788 
789 /**
790  * Generate a DNSKEY prefetch query to get the DNSKEY for the DS record we
791  * just got in a referral (where we have dnssec_expected, thus have trust
792  * anchors above it).  Note that right after calling this routine the
793  * iterator detached subqueries (because of following the referral), and thus
794  * the DNSKEY query becomes detached, its return stored in the cache for
795  * later lookup by the validator.  This cache lookup by the validator avoids
796  * the roundtrip incurred by the DNSKEY query.  The DNSKEY query is now
797  * performed at about the same time the original query is sent to the domain,
798  * thus the two answers are likely to be returned at about the same time,
799  * saving a roundtrip from the validated lookup.
800  *
801  * @param qstate: the qtstate that triggered the need to prime.
802  * @param iq: iterator query state.
803  * @param id: module id.
804  */
805 static void
806 generate_dnskey_prefetch(struct module_qstate* qstate,
807 	struct iter_qstate* iq, int id)
808 {
809 	struct module_qstate* subq;
810 	log_assert(iq->dp);
811 
812 	/* is this query the same as the prefetch? */
813 	if(qstate->qinfo.qtype == LDNS_RR_TYPE_DNSKEY &&
814 		query_dname_compare(iq->dp->name, qstate->qinfo.qname)==0 &&
815 		(qstate->query_flags&BIT_RD) && !(qstate->query_flags&BIT_CD)){
816 		return;
817 	}
818 
819 	/* if the DNSKEY is in the cache this lookup will stop quickly */
820 	log_nametypeclass(VERB_ALGO, "schedule dnskey prefetch",
821 		iq->dp->name, LDNS_RR_TYPE_DNSKEY, iq->qchase.qclass);
822 	if(!generate_sub_request(iq->dp->name, iq->dp->namelen,
823 		LDNS_RR_TYPE_DNSKEY, iq->qchase.qclass, qstate, id, iq,
824 		INIT_REQUEST_STATE, FINISHED_STATE, &subq, 0)) {
825 		/* we'll be slower, but it'll work */
826 		verbose(VERB_ALGO, "could not generate dnskey prefetch");
827 		return;
828 	}
829 	if(subq) {
830 		struct iter_qstate* subiq =
831 			(struct iter_qstate*)subq->minfo[id];
832 		/* this qstate has the right delegation for the dnskey lookup*/
833 		/* make copy to avoid use of stub dp by different qs/threads */
834 		subiq->dp = delegpt_copy(iq->dp, subq->region);
835 		/* if !subiq->dp, it'll start from the cache, no problem */
836 	}
837 }
838 
839 /**
840  * See if the query needs forwarding.
841  *
842  * @param qstate: query state.
843  * @param iq: iterator query state.
844  * @return true if the request is forwarded, false if not.
845  * 	If returns true but, iq->dp is NULL then a malloc failure occurred.
846  */
847 static int
848 forward_request(struct module_qstate* qstate, struct iter_qstate* iq)
849 {
850 	struct delegpt* dp;
851 	uint8_t* delname = iq->qchase.qname;
852 	size_t delnamelen = iq->qchase.qname_len;
853 	/* strip one label off of DS query to lookup higher for it */
854 	if(iq->qchase.qtype == LDNS_RR_TYPE_DS
855 		&& !dname_is_root(iq->qchase.qname))
856 		dname_remove_label(&delname, &delnamelen);
857 	dp = forwards_lookup(qstate->env->fwds, delname, iq->qchase.qclass);
858 	if(!dp)
859 		return 0;
860 	/* send recursion desired to forward addr */
861 	iq->chase_flags |= BIT_RD;
862 	iq->dp = delegpt_copy(dp, qstate->region);
863 	/* iq->dp checked by caller */
864 	verbose(VERB_ALGO, "forwarding request");
865 	return 1;
866 }
867 
868 /**
869  * Process the initial part of the request handling. This state roughly
870  * corresponds to resolver algorithms steps 1 (find answer in cache) and 2
871  * (find the best servers to ask).
872  *
873  * Note that all requests start here, and query restarts revisit this state.
874  *
875  * This state either generates: 1) a response, from cache or error, 2) a
876  * priming event, or 3) forwards the request to the next state (init2,
877  * generally).
878  *
879  * @param qstate: query state.
880  * @param iq: iterator query state.
881  * @param ie: iterator shared global environment.
882  * @param id: module id.
883  * @return true if the event needs more request processing immediately,
884  *         false if not.
885  */
886 static int
887 processInitRequest(struct module_qstate* qstate, struct iter_qstate* iq,
888 	struct iter_env* ie, int id)
889 {
890 	uint8_t* delname;
891 	size_t delnamelen;
892 	struct dns_msg* msg;
893 
894 	log_query_info(VERB_DETAIL, "resolving", &qstate->qinfo);
895 	/* check effort */
896 
897 	/* We enforce a maximum number of query restarts. This is primarily a
898 	 * cheap way to prevent CNAME loops. */
899 	if(iq->query_restart_count > MAX_RESTART_COUNT) {
900 		verbose(VERB_QUERY, "request has exceeded the maximum number"
901 			" of query restarts with %d", iq->query_restart_count);
902 		return error_response(qstate, id, LDNS_RCODE_SERVFAIL);
903 	}
904 
905 	/* We enforce a maximum recursion/dependency depth -- in general,
906 	 * this is unnecessary for dependency loops (although it will
907 	 * catch those), but it provides a sensible limit to the amount
908 	 * of work required to answer a given query. */
909 	verbose(VERB_ALGO, "request has dependency depth of %d", iq->depth);
910 	if(iq->depth > ie->max_dependency_depth) {
911 		verbose(VERB_QUERY, "request has exceeded the maximum "
912 			"dependency depth with depth of %d", iq->depth);
913 		return error_response(qstate, id, LDNS_RCODE_SERVFAIL);
914 	}
915 
916 	/* If the request is qclass=ANY, setup to generate each class */
917 	if(qstate->qinfo.qclass == LDNS_RR_CLASS_ANY) {
918 		iq->qchase.qclass = 0;
919 		return next_state(iq, COLLECT_CLASS_STATE);
920 	}
921 
922 	/* Resolver Algorithm Step 1 -- Look for the answer in local data. */
923 
924 	/* This either results in a query restart (CNAME cache response), a
925 	 * terminating response (ANSWER), or a cache miss (null). */
926 
927 	if(qstate->blacklist) {
928 		/* if cache, or anything else, was blacklisted then
929 		 * getting older results from cache is a bad idea, no cache */
930 		verbose(VERB_ALGO, "cache blacklisted, going to the network");
931 		msg = NULL;
932 	} else {
933 		msg = dns_cache_lookup(qstate->env, iq->qchase.qname,
934 			iq->qchase.qname_len, iq->qchase.qtype,
935 			iq->qchase.qclass, qstate->region, qstate->env->scratch);
936 		if(!msg && qstate->env->neg_cache) {
937 			/* lookup in negative cache; may result in
938 			 * NOERROR/NODATA or NXDOMAIN answers that need validation */
939 			msg = val_neg_getmsg(qstate->env->neg_cache, &iq->qchase,
940 				qstate->region, qstate->env->rrset_cache,
941 				qstate->env->scratch_buffer,
942 				*qstate->env->now, 1/*add SOA*/, NULL);
943 		}
944 		/* item taken from cache does not match our query name, thus
945 		 * security needs to be re-examined later */
946 		if(msg && query_dname_compare(qstate->qinfo.qname,
947 			iq->qchase.qname) != 0)
948 			msg->rep->security = sec_status_unchecked;
949 	}
950 	if(msg) {
951 		/* handle positive cache response */
952 		enum response_type type = response_type_from_cache(msg,
953 			&iq->qchase);
954 		if(verbosity >= VERB_ALGO) {
955 			log_dns_msg("msg from cache lookup", &msg->qinfo,
956 				msg->rep);
957 			verbose(VERB_ALGO, "msg ttl is %d, prefetch ttl %d",
958 				(int)msg->rep->ttl,
959 				(int)msg->rep->prefetch_ttl);
960 		}
961 
962 		if(type == RESPONSE_TYPE_CNAME) {
963 			uint8_t* sname = 0;
964 			size_t slen = 0;
965 			verbose(VERB_ALGO, "returning CNAME response from "
966 				"cache");
967 			if(!handle_cname_response(qstate, iq, msg,
968 				&sname, &slen))
969 				return error_response(qstate, id,
970 					LDNS_RCODE_SERVFAIL);
971 			iq->qchase.qname = sname;
972 			iq->qchase.qname_len = slen;
973 			/* This *is* a query restart, even if it is a cheap
974 			 * one. */
975 			iq->dp = NULL;
976 			iq->refetch_glue = 0;
977 			iq->query_restart_count++;
978 			iq->sent_count = 0;
979 			sock_list_insert(&qstate->reply_origin, NULL, 0, qstate->region);
980 			return next_state(iq, INIT_REQUEST_STATE);
981 		}
982 
983 		/* if from cache, NULL, else insert 'cache IP' len=0 */
984 		if(qstate->reply_origin)
985 			sock_list_insert(&qstate->reply_origin, NULL, 0, qstate->region);
986 		/* it is an answer, response, to final state */
987 		verbose(VERB_ALGO, "returning answer from cache.");
988 		iq->response = msg;
989 		return final_state(iq);
990 	}
991 
992 	/* attempt to forward the request */
993 	if(forward_request(qstate, iq))
994 	{
995 		if(!iq->dp) {
996 			log_err("alloc failure for forward dp");
997 			return error_response(qstate, id, LDNS_RCODE_SERVFAIL);
998 		}
999 		iq->refetch_glue = 0;
1000 		/* the request has been forwarded.
1001 		 * forwarded requests need to be immediately sent to the
1002 		 * next state, QUERYTARGETS. */
1003 		return next_state(iq, QUERYTARGETS_STATE);
1004 	}
1005 
1006 	/* Resolver Algorithm Step 2 -- find the "best" servers. */
1007 
1008 	/* first, adjust for DS queries. To avoid the grandparent problem,
1009 	 * we just look for the closest set of server to the parent of qname.
1010 	 * When re-fetching glue we also need to ask the parent.
1011 	 */
1012 	if(iq->refetch_glue) {
1013 		if(!iq->dp) {
1014 			log_err("internal or malloc fail: no dp for refetch");
1015 			return error_response(qstate, id, LDNS_RCODE_SERVFAIL);
1016 		}
1017 		delname = iq->dp->name;
1018 		delnamelen = iq->dp->namelen;
1019 	} else {
1020 		delname = iq->qchase.qname;
1021 		delnamelen = iq->qchase.qname_len;
1022 	}
1023 	if(iq->qchase.qtype == LDNS_RR_TYPE_DS || iq->refetch_glue ||
1024 	   (iq->qchase.qtype == LDNS_RR_TYPE_NS && qstate->prefetch_leeway)) {
1025 		/* remove first label from delname, root goes to hints,
1026 		 * but only to fetch glue, not for qtype=DS. */
1027 		/* also when prefetching an NS record, fetch it again from
1028 		 * its parent, just as if it expired, so that you do not
1029 		 * get stuck on an older nameserver that gives old NSrecords */
1030 		if(dname_is_root(delname) && (iq->refetch_glue ||
1031 			(iq->qchase.qtype == LDNS_RR_TYPE_NS &&
1032 			qstate->prefetch_leeway)))
1033 			delname = NULL; /* go to root priming */
1034 		else 	dname_remove_label(&delname, &delnamelen);
1035 		iq->refetch_glue = 0; /* if CNAME causes restart, no refetch */
1036 	}
1037 	/* delname is the name to lookup a delegation for. If NULL rootprime */
1038 	while(1) {
1039 
1040 		/* Lookup the delegation in the cache. If null, then the
1041 		 * cache needs to be primed for the qclass. */
1042 		if(delname)
1043 		     iq->dp = dns_cache_find_delegation(qstate->env, delname,
1044 			delnamelen, iq->qchase.qtype, iq->qchase.qclass,
1045 			qstate->region, &iq->deleg_msg, *qstate->env->now);
1046 		else iq->dp = NULL;
1047 
1048 		/* If the cache has returned nothing, then we have a
1049 		 * root priming situation. */
1050 		if(iq->dp == NULL) {
1051 			/* if there is a stub, then no root prime needed */
1052 			int r = prime_stub(qstate, iq, ie, id, &iq->qchase);
1053 			if(r == 2)
1054 				break; /* got noprime-stub-zone, continue */
1055 			else if(r)
1056 				return 0; /* stub prime request made */
1057 			if(forwards_lookup_root(qstate->env->fwds,
1058 				iq->qchase.qclass)) {
1059 				/* forward zone root, no root prime needed */
1060 				/* fill in some dp - safety belt */
1061 				iq->dp = hints_lookup_root(ie->hints,
1062 					iq->qchase.qclass);
1063 				if(!iq->dp) {
1064 					log_err("internal error: no hints dp");
1065 					return error_response(qstate, id,
1066 						LDNS_RCODE_SERVFAIL);
1067 				}
1068 				iq->dp = delegpt_copy(iq->dp, qstate->region);
1069 				if(!iq->dp) {
1070 					log_err("out of memory in safety belt");
1071 					return error_response(qstate, id,
1072 						LDNS_RCODE_SERVFAIL);
1073 				}
1074 				return next_state(iq, INIT_REQUEST_2_STATE);
1075 			}
1076 			/* Note that the result of this will set a new
1077 			 * DelegationPoint based on the result of priming. */
1078 			if(!prime_root(qstate, iq, ie, id, iq->qchase.qclass))
1079 				return error_response(qstate, id,
1080 					LDNS_RCODE_REFUSED);
1081 
1082 			/* priming creates and sends a subordinate query, with
1083 			 * this query as the parent. So further processing for
1084 			 * this event will stop until reactivated by the
1085 			 * results of priming. */
1086 			return 0;
1087 		}
1088 
1089 		/* see if this dp not useless.
1090 		 * It is useless if:
1091 		 *	o all NS items are required glue.
1092 		 *	  or the query is for NS item that is required glue.
1093 		 *	o no addresses are provided.
1094 		 *	o RD qflag is on.
1095 		 * Instead, go up one level, and try to get even further
1096 		 * If the root was useless, use safety belt information.
1097 		 * Only check cache returns, because replies for servers
1098 		 * could be useless but lead to loops (bumping into the
1099 		 * same server reply) if useless-checked.
1100 		 */
1101 		if(iter_dp_is_useless(&qstate->qinfo, qstate->query_flags,
1102 			iq->dp)) {
1103 			if(dname_is_root(iq->dp->name)) {
1104 				/* use safety belt */
1105 				verbose(VERB_QUERY, "Cache has root NS but "
1106 				"no addresses. Fallback to the safety belt.");
1107 				iq->dp = hints_lookup_root(ie->hints,
1108 					iq->qchase.qclass);
1109 				/* note deleg_msg is from previous lookup,
1110 				 * but RD is on, so it is not used */
1111 				if(!iq->dp) {
1112 					log_err("internal error: no hints dp");
1113 					return error_response(qstate, id,
1114 						LDNS_RCODE_REFUSED);
1115 				}
1116 				iq->dp = delegpt_copy(iq->dp, qstate->region);
1117 				if(!iq->dp) {
1118 					log_err("out of memory in safety belt");
1119 					return error_response(qstate, id,
1120 						LDNS_RCODE_SERVFAIL);
1121 				}
1122 				break;
1123 			} else {
1124 				verbose(VERB_ALGO,
1125 					"cache delegation was useless:");
1126 				delegpt_log(VERB_ALGO, iq->dp);
1127 				/* go up */
1128 				delname = iq->dp->name;
1129 				delnamelen = iq->dp->namelen;
1130 				dname_remove_label(&delname, &delnamelen);
1131 			}
1132 		} else break;
1133 	}
1134 
1135 	verbose(VERB_ALGO, "cache delegation returns delegpt");
1136 	delegpt_log(VERB_ALGO, iq->dp);
1137 
1138 	/* Otherwise, set the current delegation point and move on to the
1139 	 * next state. */
1140 	return next_state(iq, INIT_REQUEST_2_STATE);
1141 }
1142 
1143 /**
1144  * Process the second part of the initial request handling. This state
1145  * basically exists so that queries that generate root priming events have
1146  * the same init processing as ones that do not. Request events that reach
1147  * this state must have a valid currentDelegationPoint set.
1148  *
1149  * This part is primarly handling stub zone priming. Events that reach this
1150  * state must have a current delegation point.
1151  *
1152  * @param qstate: query state.
1153  * @param iq: iterator query state.
1154  * @param ie: iterator shared global environment.
1155  * @param id: module id.
1156  * @return true if the event needs more request processing immediately,
1157  *         false if not.
1158  */
1159 static int
1160 processInitRequest2(struct module_qstate* qstate, struct iter_qstate* iq,
1161 	struct iter_env* ie, int id)
1162 {
1163 	log_query_info(VERB_QUERY, "resolving (init part 2): ",
1164 		&qstate->qinfo);
1165 
1166 	/* Check to see if we need to prime a stub zone. */
1167 	if(prime_stub(qstate, iq, ie, id, &iq->qchase)) {
1168 		/* A priming sub request was made */
1169 		return 0;
1170 	}
1171 
1172 	/* most events just get forwarded to the next state. */
1173 	return next_state(iq, INIT_REQUEST_3_STATE);
1174 }
1175 
1176 /**
1177  * Process the third part of the initial request handling. This state exists
1178  * as a separate state so that queries that generate stub priming events
1179  * will get the tail end of the init process but not repeat the stub priming
1180  * check.
1181  *
1182  * @param qstate: query state.
1183  * @param iq: iterator query state.
1184  * @param id: module id.
1185  * @return true, advancing the event to the QUERYTARGETS_STATE.
1186  */
1187 static int
1188 processInitRequest3(struct module_qstate* qstate, struct iter_qstate* iq,
1189 	int id)
1190 {
1191 	log_query_info(VERB_QUERY, "resolving (init part 3): ",
1192 		&qstate->qinfo);
1193 	/* if the cache reply dp equals a validation anchor or msg has DS,
1194 	 * then DNSSEC RRSIGs are expected in the reply */
1195 	iq->dnssec_expected = iter_indicates_dnssec(qstate->env, iq->dp,
1196 		iq->deleg_msg, iq->qchase.qclass);
1197 
1198 	/* If the RD flag wasn't set, then we just finish with the
1199 	 * cached referral as the response. */
1200 	if(!(qstate->query_flags & BIT_RD)) {
1201 		iq->response = iq->deleg_msg;
1202 		if(verbosity >= VERB_ALGO)
1203 			log_dns_msg("no RD requested, using delegation msg",
1204 				&iq->response->qinfo, iq->response->rep);
1205 		if(qstate->reply_origin)
1206 			sock_list_insert(&qstate->reply_origin, NULL, 0, qstate->region);
1207 		return final_state(iq);
1208 	}
1209 	/* After this point, unset the RD flag -- this query is going to
1210 	 * be sent to an auth. server. */
1211 	iq->chase_flags &= ~BIT_RD;
1212 
1213 	/* if dnssec expected, fetch key for the trust-anchor or cached-DS */
1214 	if(iq->dnssec_expected && qstate->env->cfg->prefetch_key &&
1215 		!(qstate->query_flags&BIT_CD)) {
1216 		generate_dnskey_prefetch(qstate, iq, id);
1217 		fptr_ok(fptr_whitelist_modenv_detach_subs(
1218 			qstate->env->detach_subs));
1219 		(*qstate->env->detach_subs)(qstate);
1220 	}
1221 
1222 	/* Jump to the next state. */
1223 	return next_state(iq, QUERYTARGETS_STATE);
1224 }
1225 
1226 /**
1227  * Given a basic query, generate a parent-side "target" query.
1228  * These are subordinate queries for missing delegation point target addresses,
1229  * for which only the parent of the delegation provides correct IP addresses.
1230  *
1231  * @param qstate: query state.
1232  * @param iq: iterator query state.
1233  * @param id: module id.
1234  * @param name: target qname.
1235  * @param namelen: target qname length.
1236  * @param qtype: target qtype (either A or AAAA).
1237  * @param qclass: target qclass.
1238  * @return true on success, false on failure.
1239  */
1240 static int
1241 generate_parentside_target_query(struct module_qstate* qstate,
1242 	struct iter_qstate* iq, int id, uint8_t* name, size_t namelen,
1243 	uint16_t qtype, uint16_t qclass)
1244 {
1245 	struct module_qstate* subq;
1246 	if(!generate_sub_request(name, namelen, qtype, qclass, qstate,
1247 		id, iq, INIT_REQUEST_STATE, FINISHED_STATE, &subq, 0))
1248 		return 0;
1249 	if(subq) {
1250 		struct iter_qstate* subiq =
1251 			(struct iter_qstate*)subq->minfo[id];
1252 		/* blacklist the cache - we want to fetch parent stuff */
1253 		sock_list_insert(&subq->blacklist, NULL, 0, subq->region);
1254 		subiq->query_for_pside_glue = 1;
1255 		if(dname_subdomain_c(name, iq->dp->name)) {
1256 			subiq->dp = delegpt_copy(iq->dp, subq->region);
1257 			subiq->dnssec_expected = iter_indicates_dnssec(
1258 				qstate->env, subiq->dp, NULL,
1259 				subq->qinfo.qclass);
1260 			subiq->refetch_glue = 1;
1261 		} else {
1262 			subiq->dp = dns_cache_find_delegation(qstate->env,
1263 				name, namelen, qtype, qclass, subq->region,
1264 				&subiq->deleg_msg, *qstate->env->now);
1265 			/* if no dp, then it's from root, refetch unneeded */
1266 			if(subiq->dp) {
1267 				subiq->dnssec_expected = iter_indicates_dnssec(
1268 					qstate->env, subiq->dp, NULL,
1269 					subq->qinfo.qclass);
1270 				subiq->refetch_glue = 1;
1271 			}
1272 		}
1273 	}
1274 	log_nametypeclass(VERB_QUERY, "new pside target", name, qtype, qclass);
1275 	return 1;
1276 }
1277 
1278 /**
1279  * Given a basic query, generate a "target" query. These are subordinate
1280  * queries for missing delegation point target addresses.
1281  *
1282  * @param qstate: query state.
1283  * @param iq: iterator query state.
1284  * @param id: module id.
1285  * @param name: target qname.
1286  * @param namelen: target qname length.
1287  * @param qtype: target qtype (either A or AAAA).
1288  * @param qclass: target qclass.
1289  * @return true on success, false on failure.
1290  */
1291 static int
1292 generate_target_query(struct module_qstate* qstate, struct iter_qstate* iq,
1293         int id, uint8_t* name, size_t namelen, uint16_t qtype, uint16_t qclass)
1294 {
1295 	struct module_qstate* subq;
1296 	if(!generate_sub_request(name, namelen, qtype, qclass, qstate,
1297 		id, iq, INIT_REQUEST_STATE, FINISHED_STATE, &subq, 0))
1298 		return 0;
1299 	log_nametypeclass(VERB_QUERY, "new target", name, qtype, qclass);
1300 	return 1;
1301 }
1302 
1303 /**
1304  * Given an event at a certain state, generate zero or more target queries
1305  * for it's current delegation point.
1306  *
1307  * @param qstate: query state.
1308  * @param iq: iterator query state.
1309  * @param ie: iterator shared global environment.
1310  * @param id: module id.
1311  * @param maxtargets: The maximum number of targets to query for.
1312  *	if it is negative, there is no maximum number of targets.
1313  * @param num: returns the number of queries generated and processed,
1314  *	which may be zero if there were no missing targets.
1315  * @return false on error.
1316  */
1317 static int
1318 query_for_targets(struct module_qstate* qstate, struct iter_qstate* iq,
1319         struct iter_env* ie, int id, int maxtargets, int* num)
1320 {
1321 	int query_count = 0;
1322 	struct delegpt_ns* ns;
1323 	int missing;
1324 	int toget = 0;
1325 
1326 	if(iq->depth == ie->max_dependency_depth)
1327 		return 0;
1328 
1329 	iter_mark_cycle_targets(qstate, iq->dp);
1330 	missing = (int)delegpt_count_missing_targets(iq->dp);
1331 	log_assert(maxtargets != 0); /* that would not be useful */
1332 
1333 	/* Generate target requests. Basically, any missing targets
1334 	 * are queried for here, regardless if it is necessary to do
1335 	 * so to continue processing. */
1336 	if(maxtargets < 0 || maxtargets > missing)
1337 		toget = missing;
1338 	else	toget = maxtargets;
1339 	if(toget == 0) {
1340 		*num = 0;
1341 		return 1;
1342 	}
1343 	/* select 'toget' items from the total of 'missing' items */
1344 	log_assert(toget <= missing);
1345 
1346 	/* loop over missing targets */
1347 	for(ns = iq->dp->nslist; ns; ns = ns->next) {
1348 		if(ns->resolved)
1349 			continue;
1350 
1351 		/* randomly select this item with probability toget/missing */
1352 		if(!iter_ns_probability(qstate->env->rnd, toget, missing)) {
1353 			/* do not select this one, next; select toget number
1354 			 * of items from a list one less in size */
1355 			missing --;
1356 			continue;
1357 		}
1358 
1359 		if(ie->supports_ipv6 && !ns->got6) {
1360 			/* Send the AAAA request. */
1361 			if(!generate_target_query(qstate, iq, id,
1362 				ns->name, ns->namelen,
1363 				LDNS_RR_TYPE_AAAA, iq->qchase.qclass)) {
1364 				*num = query_count;
1365 				if(query_count > 0)
1366 					qstate->ext_state[id] = module_wait_subquery;
1367 				return 0;
1368 			}
1369 			query_count++;
1370 		}
1371 		/* Send the A request. */
1372 		if(ie->supports_ipv4 && !ns->got4) {
1373 			if(!generate_target_query(qstate, iq, id,
1374 				ns->name, ns->namelen,
1375 				LDNS_RR_TYPE_A, iq->qchase.qclass)) {
1376 				*num = query_count;
1377 				if(query_count > 0)
1378 					qstate->ext_state[id] = module_wait_subquery;
1379 				return 0;
1380 			}
1381 			query_count++;
1382 		}
1383 
1384 		/* mark this target as in progress. */
1385 		ns->resolved = 1;
1386 		missing--;
1387 		toget--;
1388 		if(toget == 0)
1389 			break;
1390 	}
1391 	*num = query_count;
1392 	if(query_count > 0)
1393 		qstate->ext_state[id] = module_wait_subquery;
1394 
1395 	return 1;
1396 }
1397 
1398 /**
1399  * Called by processQueryTargets when it would like extra targets to query
1400  * but it seems to be out of options.  At last resort some less appealing
1401  * options are explored.  If there are no more options, the result is SERVFAIL
1402  *
1403  * @param qstate: query state.
1404  * @param iq: iterator query state.
1405  * @param ie: iterator shared global environment.
1406  * @param id: module id.
1407  * @return true if the event requires more request processing immediately,
1408  *         false if not.
1409  */
1410 static int
1411 processLastResort(struct module_qstate* qstate, struct iter_qstate* iq,
1412 	struct iter_env* ie, int id)
1413 {
1414 	struct delegpt_ns* ns;
1415 	int query_count = 0;
1416 	verbose(VERB_ALGO, "No more query targets, attempting last resort");
1417 	log_assert(iq->dp);
1418 
1419 	if(!iq->dp->has_parent_side_NS) {
1420 		if(!iter_lookup_parent_NS_from_cache(qstate->env, iq->dp,
1421 			qstate->region, &qstate->qinfo)
1422 			|| !iq->dp->has_parent_side_NS) {
1423 			/* if: malloc failure in lookup go up to try */
1424 			/* if: no parent NS in cache - go up one level */
1425 			verbose(VERB_ALGO, "try to grab parent NS");
1426 			iq->store_parent_NS = iq->dp;
1427 			iq->deleg_msg = NULL;
1428 			iq->refetch_glue = 1;
1429 			iq->query_restart_count++;
1430 			iq->sent_count = 0;
1431 			return next_state(iq, INIT_REQUEST_STATE);
1432 		}
1433 	}
1434 	/* see if that makes new names available */
1435 	if(!cache_fill_missing(qstate->env, iq->qchase.qclass,
1436 		qstate->region, iq->dp))
1437 		log_err("out of memory in cache_fill_missing");
1438 	if(iq->dp->usable_list) {
1439 		verbose(VERB_ALGO, "try parent-side-name, w. glue from cache");
1440 		return next_state(iq, QUERYTARGETS_STATE);
1441 	}
1442 	/* try to fill out parent glue from cache */
1443 	if(iter_lookup_parent_glue_from_cache(qstate->env, iq->dp,
1444 		qstate->region, &qstate->qinfo)) {
1445 		/* got parent stuff from cache, see if we can continue */
1446 		verbose(VERB_ALGO, "try parent-side glue from cache");
1447 		return next_state(iq, QUERYTARGETS_STATE);
1448 	}
1449 	/* query for an extra name added by the parent-NS record */
1450 	if(delegpt_count_missing_targets(iq->dp) > 0) {
1451 		int qs = 0;
1452 		verbose(VERB_ALGO, "try parent-side target name");
1453 		if(!query_for_targets(qstate, iq, ie, id, 1, &qs)) {
1454 			return error_response(qstate, id, LDNS_RCODE_SERVFAIL);
1455 		}
1456 		iq->num_target_queries += qs;
1457 		if(qs != 0) {
1458 			qstate->ext_state[id] = module_wait_subquery;
1459 			return 0; /* and wait for them */
1460 		}
1461 	}
1462 	if(iq->depth == ie->max_dependency_depth) {
1463 		verbose(VERB_QUERY, "maxdepth and need more nameservers, fail");
1464 		return error_response_cache(qstate, id, LDNS_RCODE_SERVFAIL);
1465 	}
1466 	/* mark cycle targets for parent-side lookups */
1467 	iter_mark_pside_cycle_targets(qstate, iq->dp);
1468 	/* see if we can issue queries to get nameserver addresses */
1469 	/* this lookup is not randomized, but sequential. */
1470 	for(ns = iq->dp->nslist; ns; ns = ns->next) {
1471 		/* query for parent-side A and AAAA for nameservers */
1472 		if(ie->supports_ipv6 && !ns->done_pside6) {
1473 			/* Send the AAAA request. */
1474 			if(!generate_parentside_target_query(qstate, iq, id,
1475 				ns->name, ns->namelen,
1476 				LDNS_RR_TYPE_AAAA, iq->qchase.qclass))
1477 				return error_response(qstate, id,
1478 					LDNS_RCODE_SERVFAIL);
1479 			ns->done_pside6 = 1;
1480 			query_count++;
1481 		}
1482 		if(ie->supports_ipv4 && !ns->done_pside4) {
1483 			/* Send the A request. */
1484 			if(!generate_parentside_target_query(qstate, iq, id,
1485 				ns->name, ns->namelen,
1486 				LDNS_RR_TYPE_A, iq->qchase.qclass))
1487 				return error_response(qstate, id,
1488 					LDNS_RCODE_SERVFAIL);
1489 			ns->done_pside4 = 1;
1490 			query_count++;
1491 		}
1492 		if(query_count != 0) { /* suspend to await results */
1493 			verbose(VERB_ALGO, "try parent-side glue lookup");
1494 			iq->num_target_queries += query_count;
1495 			qstate->ext_state[id] = module_wait_subquery;
1496 			return 0;
1497 		}
1498 	}
1499 
1500 	/* if this was a parent-side glue query itself, then store that
1501 	 * failure in cache. */
1502 	if(iq->query_for_pside_glue && !iq->pside_glue)
1503 		iter_store_parentside_neg(qstate->env, &qstate->qinfo,
1504 			iq->deleg_msg?iq->deleg_msg->rep:
1505 			(iq->response?iq->response->rep:NULL));
1506 
1507 	verbose(VERB_QUERY, "out of query targets -- returning SERVFAIL");
1508 	/* fail -- no more targets, no more hope of targets, no hope
1509 	 * of a response. */
1510 	return error_response_cache(qstate, id, LDNS_RCODE_SERVFAIL);
1511 }
1512 
1513 /**
1514  * This is the request event state where the request will be sent to one of
1515  * its current query targets. This state also handles issuing target lookup
1516  * queries for missing target IP addresses. Queries typically iterate on
1517  * this state, both when they are just trying different targets for a given
1518  * delegation point, and when they change delegation points. This state
1519  * roughly corresponds to RFC 1034 algorithm steps 3 and 4.
1520  *
1521  * @param qstate: query state.
1522  * @param iq: iterator query state.
1523  * @param ie: iterator shared global environment.
1524  * @param id: module id.
1525  * @return true if the event requires more request processing immediately,
1526  *         false if not. This state only returns true when it is generating
1527  *         a SERVFAIL response because the query has hit a dead end.
1528  */
1529 static int
1530 processQueryTargets(struct module_qstate* qstate, struct iter_qstate* iq,
1531 	struct iter_env* ie, int id)
1532 {
1533 	int tf_policy;
1534 	struct delegpt_addr* target;
1535 	struct outbound_entry* outq;
1536 
1537 	/* NOTE: a request will encounter this state for each target it
1538 	 * needs to send a query to. That is, at least one per referral,
1539 	 * more if some targets timeout or return throwaway answers. */
1540 
1541 	log_query_info(VERB_QUERY, "processQueryTargets:", &qstate->qinfo);
1542 	verbose(VERB_ALGO, "processQueryTargets: targetqueries %d, "
1543 		"currentqueries %d sentcount %d", iq->num_target_queries,
1544 		iq->num_current_queries, iq->sent_count);
1545 
1546 	/* Make sure that we haven't run away */
1547 	/* FIXME: is this check even necessary? */
1548 	if(iq->referral_count > MAX_REFERRAL_COUNT) {
1549 		verbose(VERB_QUERY, "request has exceeded the maximum "
1550 			"number of referrrals with %d", iq->referral_count);
1551 		return error_response(qstate, id, LDNS_RCODE_SERVFAIL);
1552 	}
1553 	if(iq->sent_count > MAX_SENT_COUNT) {
1554 		verbose(VERB_QUERY, "request has exceeded the maximum "
1555 			"number of sends with %d", iq->sent_count);
1556 		return error_response(qstate, id, LDNS_RCODE_SERVFAIL);
1557 	}
1558 
1559 	/* Make sure we have a delegation point, otherwise priming failed
1560 	 * or another failure occurred */
1561 	if(!iq->dp) {
1562 		verbose(VERB_QUERY, "Failed to get a delegation, giving up");
1563 		return error_response(qstate, id, LDNS_RCODE_SERVFAIL);
1564 	}
1565 	if(!ie->supports_ipv6)
1566 		delegpt_no_ipv6(iq->dp);
1567 	if(!ie->supports_ipv4)
1568 		delegpt_no_ipv4(iq->dp);
1569 	delegpt_log(VERB_ALGO, iq->dp);
1570 
1571 	if(iq->num_current_queries>0) {
1572 		/* already busy answering a query, this restart is because
1573 		 * more delegpt addrs became available, wait for existing
1574 		 * query. */
1575 		verbose(VERB_ALGO, "woke up, but wait for outstanding query");
1576 		qstate->ext_state[id] = module_wait_reply;
1577 		return 0;
1578 	}
1579 
1580 	tf_policy = 0;
1581 	/* < not <=, because although the array is large enough for <=, the
1582 	 * generated query will immediately be discarded due to depth and
1583 	 * that servfail is cached, which is not good as opportunism goes. */
1584 	if(iq->depth < ie->max_dependency_depth
1585 		&& iq->sent_count < TARGET_FETCH_STOP) {
1586 		tf_policy = ie->target_fetch_policy[iq->depth];
1587 	}
1588 
1589 	/* if in 0x20 fallback get as many targets as possible */
1590 	if(iq->caps_fallback) {
1591 		int extra = 0;
1592 		size_t naddr, nres, navail;
1593 		if(!query_for_targets(qstate, iq, ie, id, -1, &extra)) {
1594 			return error_response(qstate, id, LDNS_RCODE_SERVFAIL);
1595 		}
1596 		iq->num_target_queries += extra;
1597 		if(iq->num_target_queries > 0) {
1598 			/* wait to get all targets, we want to try em */
1599 			verbose(VERB_ALGO, "wait for all targets for fallback");
1600 			qstate->ext_state[id] = module_wait_reply;
1601 			return 0;
1602 		}
1603 		/* did we do enough fallback queries already? */
1604 		delegpt_count_addr(iq->dp, &naddr, &nres, &navail);
1605 		/* the current caps_server is the number of fallbacks sent.
1606 		 * the original query is one that matched too, so we have
1607 		 * caps_server+1 number of matching queries now */
1608 		if(iq->caps_server+1 >= naddr*3 ||
1609 			iq->caps_server+1 >= MAX_SENT_COUNT) {
1610 			/* we're done, process the response */
1611 			verbose(VERB_ALGO, "0x20 fallback had %d responses "
1612 				"match for %d wanted, done.",
1613 				(int)iq->caps_server+1, (int)naddr*3);
1614 			iq->caps_fallback = 0;
1615 			iter_dec_attempts(iq->dp, 3); /* space for fallback */
1616 			iq->num_current_queries++; /* RespState decrements it*/
1617 			iq->referral_count++; /* make sure we don't loop */
1618 			iq->sent_count = 0;
1619 			iq->state = QUERY_RESP_STATE;
1620 			return 1;
1621 		}
1622 		verbose(VERB_ALGO, "0x20 fallback number %d",
1623 			(int)iq->caps_server);
1624 
1625 	/* if there is a policy to fetch missing targets
1626 	 * opportunistically, do it. we rely on the fact that once a
1627 	 * query (or queries) for a missing name have been issued,
1628 	 * they will not show up again. */
1629 	} else if(tf_policy != 0) {
1630 		int extra = 0;
1631 		verbose(VERB_ALGO, "attempt to get extra %d targets",
1632 			tf_policy);
1633 		(void)query_for_targets(qstate, iq, ie, id, tf_policy, &extra);
1634 		/* errors ignored, these targets are not strictly necessary for
1635 		 * this result, we do not have to reply with SERVFAIL */
1636 		iq->num_target_queries += extra;
1637 	}
1638 
1639 	/* Add the current set of unused targets to our queue. */
1640 	delegpt_add_unused_targets(iq->dp);
1641 
1642 	/* Select the next usable target, filtering out unsuitable targets. */
1643 	target = iter_server_selection(ie, qstate->env, iq->dp,
1644 		iq->dp->name, iq->dp->namelen, iq->qchase.qtype,
1645 		&iq->dnssec_lame_query, &iq->chase_to_rd,
1646 		iq->num_target_queries, qstate->blacklist);
1647 
1648 	/* If no usable target was selected... */
1649 	if(!target) {
1650 		/* Here we distinguish between three states: generate a new
1651 		 * target query, just wait, or quit (with a SERVFAIL).
1652 		 * We have the following information: number of active
1653 		 * target queries, number of active current queries,
1654 		 * the presence of missing targets at this delegation
1655 		 * point, and the given query target policy. */
1656 
1657 		/* Check for the wait condition. If this is true, then
1658 		 * an action must be taken. */
1659 		if(iq->num_target_queries==0 && iq->num_current_queries==0) {
1660 			/* If there is nothing to wait for, then we need
1661 			 * to distinguish between generating (a) new target
1662 			 * query, or failing. */
1663 			if(delegpt_count_missing_targets(iq->dp) > 0) {
1664 				int qs = 0;
1665 				verbose(VERB_ALGO, "querying for next "
1666 					"missing target");
1667 				if(!query_for_targets(qstate, iq, ie, id,
1668 					1, &qs)) {
1669 					return error_response(qstate, id,
1670 						LDNS_RCODE_SERVFAIL);
1671 				}
1672 				if(qs == 0 &&
1673 				   delegpt_count_missing_targets(iq->dp) == 0){
1674 					/* it looked like there were missing
1675 					 * targets, but they did not turn up.
1676 					 * Try the bad choices again (if any),
1677 					 * when we get back here missing==0,
1678 					 * so this is not a loop. */
1679 					return 1;
1680 				}
1681 				iq->num_target_queries += qs;
1682 			}
1683 			/* Since a target query might have been made, we
1684 			 * need to check again. */
1685 			if(iq->num_target_queries == 0) {
1686 				return processLastResort(qstate, iq, ie, id);
1687 			}
1688 		}
1689 
1690 		/* otherwise, we have no current targets, so submerge
1691 		 * until one of the target or direct queries return. */
1692 		if(iq->num_target_queries>0 && iq->num_current_queries>0) {
1693 			verbose(VERB_ALGO, "no current targets -- waiting "
1694 				"for %d targets to resolve or %d outstanding"
1695 				" queries to respond", iq->num_target_queries,
1696 				iq->num_current_queries);
1697 			qstate->ext_state[id] = module_wait_reply;
1698 		} else if(iq->num_target_queries>0) {
1699 			verbose(VERB_ALGO, "no current targets -- waiting "
1700 				"for %d targets to resolve.",
1701 				iq->num_target_queries);
1702 			qstate->ext_state[id] = module_wait_subquery;
1703 		} else {
1704 			verbose(VERB_ALGO, "no current targets -- waiting "
1705 				"for %d outstanding queries to respond.",
1706 				iq->num_current_queries);
1707 			qstate->ext_state[id] = module_wait_reply;
1708 		}
1709 		return 0;
1710 	}
1711 
1712 	/* We have a valid target. */
1713 	if(verbosity >= VERB_QUERY) {
1714 		log_query_info(VERB_QUERY, "sending query:", &iq->qchase);
1715 		log_name_addr(VERB_QUERY, "sending to target:", iq->dp->name,
1716 			&target->addr, target->addrlen);
1717 		verbose(VERB_ALGO, "dnssec status: %s%s",
1718 			iq->dnssec_expected?"expected": "not expected",
1719 			iq->dnssec_lame_query?" but lame_query anyway": "");
1720 	}
1721 	fptr_ok(fptr_whitelist_modenv_send_query(qstate->env->send_query));
1722 	outq = (*qstate->env->send_query)(
1723 		iq->qchase.qname, iq->qchase.qname_len,
1724 		iq->qchase.qtype, iq->qchase.qclass,
1725 		iq->chase_flags | (iq->chase_to_rd?BIT_RD:0), EDNS_DO|BIT_CD,
1726 		iq->dnssec_expected, &target->addr, target->addrlen,
1727 		iq->dp->name, iq->dp->namelen, qstate);
1728 	if(!outq) {
1729 		log_addr(VERB_DETAIL, "error sending query to auth server",
1730 			&target->addr, target->addrlen);
1731 		return next_state(iq, QUERYTARGETS_STATE);
1732 	}
1733 	outbound_list_insert(&iq->outlist, outq);
1734 	iq->num_current_queries++;
1735 	iq->sent_count++;
1736 	qstate->ext_state[id] = module_wait_reply;
1737 
1738 	return 0;
1739 }
1740 
1741 /** find NS rrset in given list */
1742 static struct ub_packed_rrset_key*
1743 find_NS(struct reply_info* rep, size_t from, size_t to)
1744 {
1745 	size_t i;
1746 	for(i=from; i<to; i++) {
1747 		if(ntohs(rep->rrsets[i]->rk.type) == LDNS_RR_TYPE_NS)
1748 			return rep->rrsets[i];
1749 	}
1750 	return NULL;
1751 }
1752 
1753 
1754 /**
1755  * Process the query response. All queries end up at this state first. This
1756  * process generally consists of analyzing the response and routing the
1757  * event to the next state (either bouncing it back to a request state, or
1758  * terminating the processing for this event).
1759  *
1760  * @param qstate: query state.
1761  * @param iq: iterator query state.
1762  * @param id: module id.
1763  * @return true if the event requires more immediate processing, false if
1764  *         not. This is generally only true when forwarding the request to
1765  *         the final state (i.e., on answer).
1766  */
1767 static int
1768 processQueryResponse(struct module_qstate* qstate, struct iter_qstate* iq,
1769 	int id)
1770 {
1771 	int dnsseclame = 0;
1772 	enum response_type type;
1773 	iq->num_current_queries--;
1774 	if(iq->response == NULL) {
1775 		iq->chase_to_rd = 0;
1776 		iq->dnssec_lame_query = 0;
1777 		verbose(VERB_ALGO, "query response was timeout");
1778 		return next_state(iq, QUERYTARGETS_STATE);
1779 	}
1780 	type = response_type_from_server(
1781 		(int)((iq->chase_flags&BIT_RD) || iq->chase_to_rd),
1782 		iq->response, &iq->qchase, iq->dp);
1783 	iq->chase_to_rd = 0;
1784 	if(type == RESPONSE_TYPE_REFERRAL && (iq->chase_flags&BIT_RD)) {
1785 		/* When forwarding (RD bit is set), we handle referrals
1786 		 * differently. No queries should be sent elsewhere */
1787 		type = RESPONSE_TYPE_ANSWER;
1788 	}
1789 	if(iq->dnssec_expected && !iq->dnssec_lame_query &&
1790 		!(iq->chase_flags&BIT_RD)
1791 		&& type != RESPONSE_TYPE_LAME
1792 		&& type != RESPONSE_TYPE_REC_LAME
1793 		&& type != RESPONSE_TYPE_THROWAWAY
1794 		&& type != RESPONSE_TYPE_UNTYPED) {
1795 		/* a possible answer, see if it is missing DNSSEC */
1796 		/* but not when forwarding, so we dont mark fwder lame */
1797 		/* also make sure the answer is from the zone we expected,
1798 		 * otherwise, (due to parent,child on same server), we
1799 		 * might mark the server,zone lame inappropriately */
1800 		if(!iter_msg_has_dnssec(iq->response) &&
1801 			iter_msg_from_zone(iq->response, iq->dp, type,
1802 				iq->qchase.qclass)) {
1803 			type = RESPONSE_TYPE_LAME;
1804 			dnsseclame = 1;
1805 		}
1806 	} else iq->dnssec_lame_query = 0;
1807 	/* see if referral brings us close to the target */
1808 	if(type == RESPONSE_TYPE_REFERRAL) {
1809 		struct ub_packed_rrset_key* ns = find_NS(
1810 			iq->response->rep, iq->response->rep->an_numrrsets,
1811 			iq->response->rep->an_numrrsets
1812 			+ iq->response->rep->ns_numrrsets);
1813 		if(!ns) ns = find_NS(iq->response->rep, 0,
1814 				iq->response->rep->an_numrrsets);
1815 		if(!ns || !dname_strict_subdomain_c(ns->rk.dname, iq->dp->name)
1816 			|| !dname_subdomain_c(iq->qchase.qname, ns->rk.dname)){
1817 			verbose(VERB_ALGO, "bad referral, throwaway");
1818 			type = RESPONSE_TYPE_THROWAWAY;
1819 		} else
1820 			iter_scrub_ds(iq->response, ns, iq->dp->name);
1821 	} else iter_scrub_ds(iq->response, NULL, NULL);
1822 
1823 	/* handle each of the type cases */
1824 	if(type == RESPONSE_TYPE_ANSWER) {
1825 		/* ANSWER type responses terminate the query algorithm,
1826 		 * so they sent on their */
1827 		if(verbosity >= VERB_DETAIL) {
1828 			verbose(VERB_DETAIL, "query response was %s",
1829 				FLAGS_GET_RCODE(iq->response->rep->flags)
1830 				==LDNS_RCODE_NXDOMAIN?"NXDOMAIN ANSWER":
1831 				(iq->response->rep->an_numrrsets?"ANSWER":
1832 				"nodata ANSWER"));
1833 		}
1834 		if(!iter_dns_store(qstate->env, &iq->response->qinfo,
1835 			iq->response->rep, 0, qstate->prefetch_leeway,
1836 			qstate->region))
1837 			return error_response(qstate, id, LDNS_RCODE_SERVFAIL);
1838 		/* close down outstanding requests to be discarded */
1839 		outbound_list_clear(&iq->outlist);
1840 		iq->num_current_queries = 0;
1841 		fptr_ok(fptr_whitelist_modenv_detach_subs(
1842 			qstate->env->detach_subs));
1843 		(*qstate->env->detach_subs)(qstate);
1844 		iq->num_target_queries = 0;
1845 		if(qstate->reply)
1846 			sock_list_insert(&qstate->reply_origin,
1847 				&qstate->reply->addr, qstate->reply->addrlen,
1848 				qstate->region);
1849 		return final_state(iq);
1850 	} else if(type == RESPONSE_TYPE_REFERRAL) {
1851 		/* REFERRAL type responses get a reset of the
1852 		 * delegation point, and back to the QUERYTARGETS_STATE. */
1853 		verbose(VERB_DETAIL, "query response was REFERRAL");
1854 
1855 		/* if hardened, only store referral if we asked for it */
1856 		if(!qstate->env->cfg->harden_referral_path ||
1857 		    (  qstate->qinfo.qtype == LDNS_RR_TYPE_NS
1858 			&& (qstate->query_flags&BIT_RD)
1859 			&& !(qstate->query_flags&BIT_CD)
1860 			   /* we know that all other NS rrsets are scrubbed
1861 			    * away, thus on referral only one is left.
1862 			    * see if that equals the query name... */
1863 			&& ( /* auth section, but sometimes in answer section*/
1864 			  reply_find_rrset_section_ns(iq->response->rep,
1865 				iq->qchase.qname, iq->qchase.qname_len,
1866 				LDNS_RR_TYPE_NS, iq->qchase.qclass)
1867 			  || reply_find_rrset_section_an(iq->response->rep,
1868 				iq->qchase.qname, iq->qchase.qname_len,
1869 				LDNS_RR_TYPE_NS, iq->qchase.qclass)
1870 			  )
1871 		    )) {
1872 			/* Store the referral under the current query */
1873 			/* no prefetch-leeway, since its not the answer */
1874 			if(!iter_dns_store(qstate->env, &iq->response->qinfo,
1875 				iq->response->rep, 1, 0, NULL))
1876 				return error_response(qstate, id,
1877 					LDNS_RCODE_SERVFAIL);
1878 			if(iq->store_parent_NS)
1879 				iter_store_parentside_NS(qstate->env,
1880 					iq->response->rep);
1881 			if(qstate->env->neg_cache)
1882 				val_neg_addreferral(qstate->env->neg_cache,
1883 					iq->response->rep, iq->dp->name);
1884 		}
1885 		/* store parent-side-in-zone-glue, if directly queried for */
1886 		if(iq->query_for_pside_glue && !iq->pside_glue) {
1887 			iq->pside_glue = reply_find_rrset(iq->response->rep,
1888 				iq->qchase.qname, iq->qchase.qname_len,
1889 				iq->qchase.qtype, iq->qchase.qclass);
1890 			if(iq->pside_glue) {
1891 				log_rrset_key(VERB_ALGO, "found parent-side "
1892 					"glue", iq->pside_glue);
1893 				iter_store_parentside_rrset(qstate->env,
1894 					iq->pside_glue);
1895 			}
1896 		}
1897 
1898 		/* Reset the event state, setting the current delegation
1899 		 * point to the referral. */
1900 		iq->deleg_msg = iq->response;
1901 		iq->dp = delegpt_from_message(iq->response, qstate->region);
1902 		if(!iq->dp)
1903 			return error_response(qstate, id, LDNS_RCODE_SERVFAIL);
1904 		if(!cache_fill_missing(qstate->env, iq->qchase.qclass,
1905 			qstate->region, iq->dp))
1906 			return error_response(qstate, id, LDNS_RCODE_SERVFAIL);
1907 		if(iq->store_parent_NS && query_dname_compare(iq->dp->name,
1908 			iq->store_parent_NS->name) == 0)
1909 			iter_merge_retry_counts(iq->dp, iq->store_parent_NS);
1910 		delegpt_log(VERB_ALGO, iq->dp);
1911 		/* Count this as a referral. */
1912 		iq->referral_count++;
1913 		iq->sent_count = 0;
1914 		/* see if the next dp is a trust anchor, or a DS was sent
1915 		 * along, indicating dnssec is expected for next zone */
1916 		iq->dnssec_expected = iter_indicates_dnssec(qstate->env,
1917 			iq->dp, iq->response, iq->qchase.qclass);
1918 		/* if dnssec, validating then also fetch the key for the DS */
1919 		if(iq->dnssec_expected && qstate->env->cfg->prefetch_key &&
1920 			!(qstate->query_flags&BIT_CD))
1921 			generate_dnskey_prefetch(qstate, iq, id);
1922 
1923 		/* spawn off NS and addr to auth servers for the NS we just
1924 		 * got in the referral. This gets authoritative answer
1925 		 * (answer section trust level) rrset.
1926 		 * right after, we detach the subs, answer goes to cache. */
1927 		if(qstate->env->cfg->harden_referral_path)
1928 			generate_ns_check(qstate, iq, id);
1929 
1930 		/* stop current outstanding queries.
1931 		 * FIXME: should the outstanding queries be waited for and
1932 		 * handled? Say by a subquery that inherits the outbound_entry.
1933 		 */
1934 		outbound_list_clear(&iq->outlist);
1935 		iq->num_current_queries = 0;
1936 		fptr_ok(fptr_whitelist_modenv_detach_subs(
1937 			qstate->env->detach_subs));
1938 		(*qstate->env->detach_subs)(qstate);
1939 		iq->num_target_queries = 0;
1940 		verbose(VERB_ALGO, "cleared outbound list for next round");
1941 		return next_state(iq, QUERYTARGETS_STATE);
1942 	} else if(type == RESPONSE_TYPE_CNAME) {
1943 		uint8_t* sname = NULL;
1944 		size_t snamelen = 0;
1945 		/* CNAME type responses get a query restart (i.e., get a
1946 		 * reset of the query state and go back to INIT_REQUEST_STATE).
1947 		 */
1948 		verbose(VERB_DETAIL, "query response was CNAME");
1949 		if(verbosity >= VERB_ALGO)
1950 			log_dns_msg("cname msg", &iq->response->qinfo,
1951 				iq->response->rep);
1952 		/* Process the CNAME response. */
1953 		if(!handle_cname_response(qstate, iq, iq->response,
1954 			&sname, &snamelen))
1955 			return error_response(qstate, id, LDNS_RCODE_SERVFAIL);
1956 		/* cache the CNAME response under the current query */
1957 		/* NOTE : set referral=1, so that rrsets get stored but not
1958 		 * the partial query answer (CNAME only). */
1959 		/* prefetchleeway applied because this updates answer parts */
1960 		if(!iter_dns_store(qstate->env, &iq->response->qinfo,
1961 			iq->response->rep, 1, qstate->prefetch_leeway, NULL))
1962 			return error_response(qstate, id, LDNS_RCODE_SERVFAIL);
1963 		/* set the current request's qname to the new value. */
1964 		iq->qchase.qname = sname;
1965 		iq->qchase.qname_len = snamelen;
1966 		/* Clear the query state, since this is a query restart. */
1967 		iq->deleg_msg = NULL;
1968 		iq->dp = NULL;
1969 		/* Note the query restart. */
1970 		iq->query_restart_count++;
1971 		iq->sent_count = 0;
1972 
1973 		/* stop current outstanding queries.
1974 		 * FIXME: should the outstanding queries be waited for and
1975 		 * handled? Say by a subquery that inherits the outbound_entry.
1976 		 */
1977 		outbound_list_clear(&iq->outlist);
1978 		iq->num_current_queries = 0;
1979 		fptr_ok(fptr_whitelist_modenv_detach_subs(
1980 			qstate->env->detach_subs));
1981 		(*qstate->env->detach_subs)(qstate);
1982 		iq->num_target_queries = 0;
1983 		if(qstate->reply)
1984 			sock_list_insert(&qstate->reply_origin,
1985 				&qstate->reply->addr, qstate->reply->addrlen,
1986 				qstate->region);
1987 		verbose(VERB_ALGO, "cleared outbound list for query restart");
1988 		/* go to INIT_REQUEST_STATE for new qname. */
1989 		return next_state(iq, INIT_REQUEST_STATE);
1990 	} else if(type == RESPONSE_TYPE_LAME) {
1991 		/* Cache the LAMEness. */
1992 		verbose(VERB_DETAIL, "query response was %sLAME",
1993 			dnsseclame?"DNSSEC ":"");
1994 		if(!dname_subdomain_c(iq->qchase.qname, iq->dp->name)) {
1995 			log_err("mark lame: mismatch in qname and dpname");
1996 			/* throwaway this reply below */
1997 		} else if(qstate->reply) {
1998 			/* need addr for lameness cache, but we may have
1999 			 * gotten this from cache, so test to be sure */
2000 			if(!infra_set_lame(qstate->env->infra_cache,
2001 				&qstate->reply->addr, qstate->reply->addrlen,
2002 				iq->dp->name, iq->dp->namelen,
2003 				*qstate->env->now, dnsseclame, 0,
2004 				iq->qchase.qtype))
2005 				log_err("mark host lame: out of memory");
2006 		} else log_err("%slame response from cache",
2007 			dnsseclame?"DNSSEC ":"");
2008 	} else if(type == RESPONSE_TYPE_REC_LAME) {
2009 		/* Cache the LAMEness. */
2010 		verbose(VERB_DETAIL, "query response REC_LAME: "
2011 			"recursive but not authoritative server");
2012 		if(!dname_subdomain_c(iq->qchase.qname, iq->dp->name)) {
2013 			log_err("mark rec_lame: mismatch in qname and dpname");
2014 			/* throwaway this reply below */
2015 		} else if(qstate->reply) {
2016 			/* need addr for lameness cache, but we may have
2017 			 * gotten this from cache, so test to be sure */
2018 			verbose(VERB_DETAIL, "mark as REC_LAME");
2019 			if(!infra_set_lame(qstate->env->infra_cache,
2020 				&qstate->reply->addr, qstate->reply->addrlen,
2021 				iq->dp->name, iq->dp->namelen,
2022 				*qstate->env->now, 0, 1, iq->qchase.qtype))
2023 				log_err("mark host lame: out of memory");
2024 		}
2025 	} else if(type == RESPONSE_TYPE_THROWAWAY) {
2026 		/* LAME and THROWAWAY responses are handled the same way.
2027 		 * In this case, the event is just sent directly back to
2028 		 * the QUERYTARGETS_STATE without resetting anything,
2029 		 * because, clearly, the next target must be tried. */
2030 		verbose(VERB_DETAIL, "query response was THROWAWAY");
2031 	} else {
2032 		log_warn("A query response came back with an unknown type: %d",
2033 			(int)type);
2034 	}
2035 
2036 	/* LAME, THROWAWAY and "unknown" all end up here.
2037 	 * Recycle to the QUERYTARGETS state to hopefully try a
2038 	 * different target. */
2039 	return next_state(iq, QUERYTARGETS_STATE);
2040 }
2041 
2042 /**
2043  * Return priming query results to interestes super querystates.
2044  *
2045  * Sets the delegation point and delegation message (not nonRD queries).
2046  * This is a callback from walk_supers.
2047  *
2048  * @param qstate: priming query state that finished.
2049  * @param id: module id.
2050  * @param forq: the qstate for which priming has been done.
2051  */
2052 static void
2053 prime_supers(struct module_qstate* qstate, int id, struct module_qstate* forq)
2054 {
2055 	struct iter_qstate* foriq = (struct iter_qstate*)forq->minfo[id];
2056 	struct delegpt* dp = NULL;
2057 
2058 	log_assert(qstate->is_priming || foriq->wait_priming_stub);
2059 	log_assert(qstate->return_rcode == LDNS_RCODE_NOERROR);
2060 	/* Convert our response to a delegation point */
2061 	dp = delegpt_from_message(qstate->return_msg, forq->region);
2062 	if(!dp) {
2063 		/* if there is no convertable delegation point, then
2064 		 * the ANSWER type was (presumably) a negative answer. */
2065 		verbose(VERB_ALGO, "prime response was not a positive "
2066 			"ANSWER; failing");
2067 		foriq->dp = NULL;
2068 		foriq->state = QUERYTARGETS_STATE;
2069 		return;
2070 	}
2071 
2072 	log_query_info(VERB_DETAIL, "priming successful for", &qstate->qinfo);
2073 	delegpt_log(VERB_ALGO, dp);
2074 	foriq->dp = dp;
2075 	foriq->deleg_msg = dns_copy_msg(qstate->return_msg, forq->region);
2076 	if(!foriq->deleg_msg) {
2077 		log_err("copy prime response: out of memory");
2078 		foriq->dp = NULL;
2079 		foriq->state = QUERYTARGETS_STATE;
2080 		return;
2081 	}
2082 
2083 	/* root priming responses go to init stage 2, priming stub
2084 	 * responses to to stage 3. */
2085 	if(foriq->wait_priming_stub) {
2086 		foriq->state = INIT_REQUEST_3_STATE;
2087 		foriq->wait_priming_stub = 0;
2088 	} else	foriq->state = INIT_REQUEST_2_STATE;
2089 	/* because we are finished, the parent will be reactivated */
2090 }
2091 
2092 /**
2093  * This handles the response to a priming query. This is used to handle both
2094  * root and stub priming responses. This is basically the equivalent of the
2095  * QUERY_RESP_STATE, but will not handle CNAME responses and will treat
2096  * REFERRALs as ANSWERS. It will also update and reactivate the originating
2097  * event.
2098  *
2099  * @param qstate: query state.
2100  * @param id: module id.
2101  * @return true if the event needs more immediate processing, false if not.
2102  *         This state always returns false.
2103  */
2104 static int
2105 processPrimeResponse(struct module_qstate* qstate, int id)
2106 {
2107 	struct iter_qstate* iq = (struct iter_qstate*)qstate->minfo[id];
2108 	enum response_type type;
2109 	iq->response->rep->flags &= ~(BIT_RD|BIT_RA); /* ignore rec-lame */
2110 	type = response_type_from_server(
2111 		(int)((iq->chase_flags&BIT_RD) || iq->chase_to_rd),
2112 		iq->response, &iq->qchase, iq->dp);
2113 	if(type == RESPONSE_TYPE_ANSWER) {
2114 		qstate->return_rcode = LDNS_RCODE_NOERROR;
2115 		qstate->return_msg = iq->response;
2116 	} else {
2117 		qstate->return_rcode = LDNS_RCODE_SERVFAIL;
2118 		qstate->return_msg = NULL;
2119 	}
2120 
2121 	/* validate the root or stub after priming (if enabled).
2122 	 * This is the same query as the prime query, but with validation.
2123 	 * Now that we are primed, the additional queries that validation
2124 	 * may need can be resolved, such as DLV. */
2125 	if(qstate->env->cfg->harden_referral_path) {
2126 		struct module_qstate* subq = NULL;
2127 		log_nametypeclass(VERB_ALGO, "schedule prime validation",
2128 			qstate->qinfo.qname, qstate->qinfo.qtype,
2129 			qstate->qinfo.qclass);
2130 		if(!generate_sub_request(qstate->qinfo.qname,
2131 			qstate->qinfo.qname_len, qstate->qinfo.qtype,
2132 			qstate->qinfo.qclass, qstate, id, iq,
2133 			INIT_REQUEST_STATE, FINISHED_STATE, &subq, 1)) {
2134 			verbose(VERB_ALGO, "could not generate prime check");
2135 		}
2136 		generate_a_aaaa_check(qstate, iq, id);
2137 	}
2138 
2139 	/* This event is finished. */
2140 	qstate->ext_state[id] = module_finished;
2141 	return 0;
2142 }
2143 
2144 /**
2145  * Do final processing on responses to target queries. Events reach this
2146  * state after the iterative resolution algorithm terminates. This state is
2147  * responsible for reactiving the original event, and housekeeping related
2148  * to received target responses (caching, updating the current delegation
2149  * point, etc).
2150  * Callback from walk_supers for every super state that is interested in
2151  * the results from this query.
2152  *
2153  * @param qstate: query state.
2154  * @param id: module id.
2155  * @param forq: super query state.
2156  */
2157 static void
2158 processTargetResponse(struct module_qstate* qstate, int id,
2159 	struct module_qstate* forq)
2160 {
2161 	struct iter_qstate* iq = (struct iter_qstate*)qstate->minfo[id];
2162 	struct iter_qstate* foriq = (struct iter_qstate*)forq->minfo[id];
2163 	struct ub_packed_rrset_key* rrset;
2164 	struct delegpt_ns* dpns;
2165 	log_assert(qstate->return_rcode == LDNS_RCODE_NOERROR);
2166 
2167 	foriq->state = QUERYTARGETS_STATE;
2168 	log_query_info(VERB_ALGO, "processTargetResponse", &qstate->qinfo);
2169 	log_query_info(VERB_ALGO, "processTargetResponse super", &forq->qinfo);
2170 
2171 	/* check to see if parent event is still interested (in orig name).  */
2172 	if(!foriq->dp) {
2173 		verbose(VERB_ALGO, "subq: parent not interested, was reset");
2174 		return; /* not interested anymore */
2175 	}
2176 	dpns = delegpt_find_ns(foriq->dp, qstate->qinfo.qname,
2177 			qstate->qinfo.qname_len);
2178 	if(!dpns) {
2179 		/* If not interested, just stop processing this event */
2180 		verbose(VERB_ALGO, "subq: parent not interested anymore");
2181 		/* could be because parent was jostled out of the cache,
2182 		   and a new identical query arrived, that does not want it*/
2183 		return;
2184 	}
2185 
2186 	/* Tell the originating event that this target query has finished
2187 	 * (regardless if it succeeded or not). */
2188 	foriq->num_target_queries--;
2189 
2190 	/* if iq->query_for_pside_glue then add the pside_glue (marked lame) */
2191 	if(iq->pside_glue) {
2192 		/* if the pside_glue is NULL, then it could not be found,
2193 		 * the done_pside is already set when created and a cache
2194 		 * entry created in processFinished so nothing to do here */
2195 		log_rrset_key(VERB_ALGO, "add parentside glue to dp",
2196 			iq->pside_glue);
2197 		if(!delegpt_add_rrset(foriq->dp, forq->region,
2198 			iq->pside_glue, 1))
2199 			log_err("out of memory adding pside glue");
2200 	}
2201 
2202 	/* This response is relevant to the current query, so we
2203 	 * add (attempt to add, anyway) this target(s) and reactivate
2204 	 * the original event.
2205 	 * NOTE: we could only look for the AnswerRRset if the
2206 	 * response type was ANSWER. */
2207 	rrset = reply_find_answer_rrset(&iq->qchase, qstate->return_msg->rep);
2208 	if(rrset) {
2209 		/* if CNAMEs have been followed - add new NS to delegpt. */
2210 		/* BTW. RFC 1918 says NS should not have got CNAMEs. Robust. */
2211 		if(!delegpt_find_ns(foriq->dp, rrset->rk.dname,
2212 			rrset->rk.dname_len)) {
2213 			/* if dpns->lame then set newcname ns lame too */
2214 			if(!delegpt_add_ns(foriq->dp, forq->region,
2215 				rrset->rk.dname, (int)dpns->lame))
2216 				log_err("out of memory adding cnamed-ns");
2217 		}
2218 		/* if dpns->lame then set the address(es) lame too */
2219 		if(!delegpt_add_rrset(foriq->dp, forq->region, rrset,
2220 			(int)dpns->lame))
2221 			log_err("out of memory adding targets");
2222 		verbose(VERB_ALGO, "added target response");
2223 		delegpt_log(VERB_ALGO, foriq->dp);
2224 	} else {
2225 		verbose(VERB_ALGO, "iterator TargetResponse failed");
2226 		dpns->resolved = 1; /* fail the target */
2227 	}
2228 }
2229 
2230 /**
2231  * Process response for qclass=ANY queries for a particular class.
2232  * Append to result or error-exit.
2233  *
2234  * @param qstate: query state.
2235  * @param id: module id.
2236  * @param forq: super query state.
2237  */
2238 static void
2239 processClassResponse(struct module_qstate* qstate, int id,
2240 	struct module_qstate* forq)
2241 {
2242 	struct iter_qstate* foriq = (struct iter_qstate*)forq->minfo[id];
2243 	struct dns_msg* from = qstate->return_msg;
2244 	log_query_info(VERB_ALGO, "processClassResponse", &qstate->qinfo);
2245 	log_query_info(VERB_ALGO, "processClassResponse super", &forq->qinfo);
2246 	if(qstate->return_rcode != LDNS_RCODE_NOERROR) {
2247 		/* cause servfail for qclass ANY query */
2248 		foriq->response = NULL;
2249 		foriq->state = FINISHED_STATE;
2250 		return;
2251 	}
2252 	/* append result */
2253 	if(!foriq->response) {
2254 		/* allocate the response: copy RCODE, sec_state */
2255 		foriq->response = dns_copy_msg(from, forq->region);
2256 		if(!foriq->response) {
2257 			log_err("malloc failed for qclass ANY response");
2258 			foriq->state = FINISHED_STATE;
2259 			return;
2260 		}
2261 		foriq->response->qinfo.qclass = forq->qinfo.qclass;
2262 		/* qclass ANY does not receive the AA flag on replies */
2263 		foriq->response->rep->authoritative = 0;
2264 	} else {
2265 		struct dns_msg* to = foriq->response;
2266 		/* add _from_ this response _to_ existing collection */
2267 		/* if there are records, copy RCODE */
2268 		/* lower sec_state if this message is lower */
2269 		if(from->rep->rrset_count != 0) {
2270 			size_t n = from->rep->rrset_count+to->rep->rrset_count;
2271 			struct ub_packed_rrset_key** dest, **d;
2272 			/* copy appropriate rcode */
2273 			to->rep->flags = from->rep->flags;
2274 			/* copy rrsets */
2275 			dest = regional_alloc(forq->region, sizeof(dest[0])*n);
2276 			if(!dest) {
2277 				log_err("malloc failed in collect ANY");
2278 				foriq->state = FINISHED_STATE;
2279 				return;
2280 			}
2281 			d = dest;
2282 			/* copy AN */
2283 			memcpy(dest, to->rep->rrsets, to->rep->an_numrrsets
2284 				* sizeof(dest[0]));
2285 			dest += to->rep->an_numrrsets;
2286 			memcpy(dest, from->rep->rrsets, from->rep->an_numrrsets
2287 				* sizeof(dest[0]));
2288 			dest += from->rep->an_numrrsets;
2289 			/* copy NS */
2290 			memcpy(dest, to->rep->rrsets+to->rep->an_numrrsets,
2291 				to->rep->ns_numrrsets * sizeof(dest[0]));
2292 			dest += to->rep->ns_numrrsets;
2293 			memcpy(dest, from->rep->rrsets+from->rep->an_numrrsets,
2294 				from->rep->ns_numrrsets * sizeof(dest[0]));
2295 			dest += from->rep->ns_numrrsets;
2296 			/* copy AR */
2297 			memcpy(dest, to->rep->rrsets+to->rep->an_numrrsets+
2298 				to->rep->ns_numrrsets,
2299 				to->rep->ar_numrrsets * sizeof(dest[0]));
2300 			dest += to->rep->ar_numrrsets;
2301 			memcpy(dest, from->rep->rrsets+from->rep->an_numrrsets+
2302 				from->rep->ns_numrrsets,
2303 				from->rep->ar_numrrsets * sizeof(dest[0]));
2304 			/* update counts */
2305 			to->rep->rrsets = d;
2306 			to->rep->an_numrrsets += from->rep->an_numrrsets;
2307 			to->rep->ns_numrrsets += from->rep->ns_numrrsets;
2308 			to->rep->ar_numrrsets += from->rep->ar_numrrsets;
2309 			to->rep->rrset_count = n;
2310 		}
2311 		if(from->rep->security < to->rep->security) /* lowest sec */
2312 			to->rep->security = from->rep->security;
2313 		if(from->rep->qdcount != 0) /* insert qd if appropriate */
2314 			to->rep->qdcount = from->rep->qdcount;
2315 		if(from->rep->ttl < to->rep->ttl) /* use smallest TTL */
2316 			to->rep->ttl = from->rep->ttl;
2317 		if(from->rep->prefetch_ttl < to->rep->prefetch_ttl)
2318 			to->rep->prefetch_ttl = from->rep->prefetch_ttl;
2319 	}
2320 	/* are we done? */
2321 	foriq->num_current_queries --;
2322 	if(foriq->num_current_queries == 0)
2323 		foriq->state = FINISHED_STATE;
2324 }
2325 
2326 /**
2327  * Collect class ANY responses and make them into one response.  This
2328  * state is started and it creates queries for all classes (that have
2329  * root hints).  The answers are then collected.
2330  *
2331  * @param qstate: query state.
2332  * @param id: module id.
2333  * @return true if the event needs more immediate processing, false if not.
2334  */
2335 static int
2336 processCollectClass(struct module_qstate* qstate, int id)
2337 {
2338 	struct iter_qstate* iq = (struct iter_qstate*)qstate->minfo[id];
2339 	struct iter_env* ie = (struct iter_env*)qstate->env->modinfo[id];
2340 	struct module_qstate* subq;
2341 	/* If qchase.qclass == 0 then send out queries for all classes.
2342 	 * Otherwise, do nothing (wait for all answers to arrive and the
2343 	 * processClassResponse to put them together, and that moves us
2344 	 * towards the Finished state when done. */
2345 	if(iq->qchase.qclass == 0) {
2346 		uint16_t c = 0;
2347 		iq->qchase.qclass = LDNS_RR_CLASS_ANY;
2348 		while(iter_get_next_root(ie->hints, qstate->env->fwds, &c)) {
2349 			/* generate query for this class */
2350 			log_nametypeclass(VERB_ALGO, "spawn collect query",
2351 				qstate->qinfo.qname, qstate->qinfo.qtype, c);
2352 			if(!generate_sub_request(qstate->qinfo.qname,
2353 				qstate->qinfo.qname_len, qstate->qinfo.qtype,
2354 				c, qstate, id, iq, INIT_REQUEST_STATE,
2355 				FINISHED_STATE, &subq,
2356 				(int)!(qstate->query_flags&BIT_CD))) {
2357 				return error_response(qstate, id,
2358 					LDNS_RCODE_SERVFAIL);
2359 			}
2360 			/* ignore subq, no special init required */
2361 			iq->num_current_queries ++;
2362 			if(c == 0xffff)
2363 				break;
2364 			else c++;
2365 		}
2366 		/* if no roots are configured at all, return */
2367 		if(iq->num_current_queries == 0) {
2368 			verbose(VERB_ALGO, "No root hints or fwds, giving up "
2369 				"on qclass ANY");
2370 			return error_response(qstate, id, LDNS_RCODE_REFUSED);
2371 		}
2372 		/* return false, wait for queries to return */
2373 	}
2374 	/* if woke up here because of an answer, wait for more answers */
2375 	return 0;
2376 }
2377 
2378 /**
2379  * This handles the final state for first-tier responses (i.e., responses to
2380  * externally generated queries).
2381  *
2382  * @param qstate: query state.
2383  * @param iq: iterator query state.
2384  * @param id: module id.
2385  * @return true if the event needs more processing, false if not. Since this
2386  *         is the final state for an event, it always returns false.
2387  */
2388 static int
2389 processFinished(struct module_qstate* qstate, struct iter_qstate* iq,
2390 	int id)
2391 {
2392 	log_query_info(VERB_QUERY, "finishing processing for",
2393 		&qstate->qinfo);
2394 
2395 	/* store negative cache element for parent side glue. */
2396 	if(iq->query_for_pside_glue && !iq->pside_glue)
2397 		iter_store_parentside_neg(qstate->env, &qstate->qinfo,
2398 			iq->deleg_msg?iq->deleg_msg->rep:
2399 			(iq->response?iq->response->rep:NULL));
2400 	if(!iq->response) {
2401 		verbose(VERB_ALGO, "No response is set, servfail");
2402 		return error_response(qstate, id, LDNS_RCODE_SERVFAIL);
2403 	}
2404 
2405 	/* Make sure that the RA flag is set (since the presence of
2406 	 * this module means that recursion is available) */
2407 	iq->response->rep->flags |= BIT_RA;
2408 
2409 	/* Clear the AA flag */
2410 	/* FIXME: does this action go here or in some other module? */
2411 	iq->response->rep->flags &= ~BIT_AA;
2412 
2413 	/* make sure QR flag is on */
2414 	iq->response->rep->flags |= BIT_QR;
2415 
2416 	/* we have finished processing this query */
2417 	qstate->ext_state[id] = module_finished;
2418 
2419 	/* TODO:  we are using a private TTL, trim the response. */
2420 	/* if (mPrivateTTL > 0){IterUtils.setPrivateTTL(resp, mPrivateTTL); } */
2421 
2422 	/* prepend any items we have accumulated */
2423 	if(iq->an_prepend_list || iq->ns_prepend_list) {
2424 		if(!iter_prepend(iq, iq->response, qstate->region)) {
2425 			log_err("prepend rrsets: out of memory");
2426 			return error_response(qstate, id, LDNS_RCODE_SERVFAIL);
2427 		}
2428 		/* reset the query name back */
2429 		iq->response->qinfo = qstate->qinfo;
2430 		/* the security state depends on the combination */
2431 		iq->response->rep->security = sec_status_unchecked;
2432 		/* store message with the finished prepended items,
2433 		 * but only if we did recursion. The nonrecursion referral
2434 		 * from cache does not need to be stored in the msg cache. */
2435 		if(qstate->query_flags&BIT_RD) {
2436 			if(!iter_dns_store(qstate->env, &qstate->qinfo,
2437 				iq->response->rep, 0, qstate->prefetch_leeway,
2438 				qstate->region))
2439 				return error_response(qstate, id,
2440 					LDNS_RCODE_SERVFAIL);
2441 		}
2442 	}
2443 	qstate->return_rcode = LDNS_RCODE_NOERROR;
2444 	qstate->return_msg = iq->response;
2445 	return 0;
2446 }
2447 
2448 /*
2449  * Return priming query results to interestes super querystates.
2450  *
2451  * Sets the delegation point and delegation message (not nonRD queries).
2452  * This is a callback from walk_supers.
2453  *
2454  * @param qstate: query state that finished.
2455  * @param id: module id.
2456  * @param super: the qstate to inform.
2457  */
2458 void
2459 iter_inform_super(struct module_qstate* qstate, int id,
2460 	struct module_qstate* super)
2461 {
2462 	if(!qstate->is_priming && super->qinfo.qclass == LDNS_RR_CLASS_ANY)
2463 		processClassResponse(qstate, id, super);
2464 	else if(qstate->return_rcode != LDNS_RCODE_NOERROR)
2465 		error_supers(qstate, id, super);
2466 	else if(qstate->is_priming)
2467 		prime_supers(qstate, id, super);
2468 	else	processTargetResponse(qstate, id, super);
2469 }
2470 
2471 /**
2472  * Handle iterator state.
2473  * Handle events. This is the real processing loop for events, responsible
2474  * for moving events through the various states. If a processing method
2475  * returns true, then it will be advanced to the next state. If false, then
2476  * processing will stop.
2477  *
2478  * @param qstate: query state.
2479  * @param ie: iterator shared global environment.
2480  * @param iq: iterator query state.
2481  * @param id: module id.
2482  */
2483 static void
2484 iter_handle(struct module_qstate* qstate, struct iter_qstate* iq,
2485 	struct iter_env* ie, int id)
2486 {
2487 	int cont = 1;
2488 	while(cont) {
2489 		verbose(VERB_ALGO, "iter_handle processing q with state %s",
2490 			iter_state_to_string(iq->state));
2491 		switch(iq->state) {
2492 			case INIT_REQUEST_STATE:
2493 				cont = processInitRequest(qstate, iq, ie, id);
2494 				break;
2495 			case INIT_REQUEST_2_STATE:
2496 				cont = processInitRequest2(qstate, iq, ie, id);
2497 				break;
2498 			case INIT_REQUEST_3_STATE:
2499 				cont = processInitRequest3(qstate, iq, id);
2500 				break;
2501 			case QUERYTARGETS_STATE:
2502 				cont = processQueryTargets(qstate, iq, ie, id);
2503 				break;
2504 			case QUERY_RESP_STATE:
2505 				cont = processQueryResponse(qstate, iq, id);
2506 				break;
2507 			case PRIME_RESP_STATE:
2508 				cont = processPrimeResponse(qstate, id);
2509 				break;
2510 			case COLLECT_CLASS_STATE:
2511 				cont = processCollectClass(qstate, id);
2512 				break;
2513 			case FINISHED_STATE:
2514 				cont = processFinished(qstate, iq, id);
2515 				break;
2516 			default:
2517 				log_warn("iterator: invalid state: %d",
2518 					iq->state);
2519 				cont = 0;
2520 				break;
2521 		}
2522 	}
2523 }
2524 
2525 /**
2526  * This is the primary entry point for processing request events. Note that
2527  * this method should only be used by external modules.
2528  * @param qstate: query state.
2529  * @param ie: iterator shared global environment.
2530  * @param iq: iterator query state.
2531  * @param id: module id.
2532  */
2533 static void
2534 process_request(struct module_qstate* qstate, struct iter_qstate* iq,
2535 	struct iter_env* ie, int id)
2536 {
2537 	/* external requests start in the INIT state, and finish using the
2538 	 * FINISHED state. */
2539 	iq->state = INIT_REQUEST_STATE;
2540 	iq->final_state = FINISHED_STATE;
2541 	verbose(VERB_ALGO, "process_request: new external request event");
2542 	iter_handle(qstate, iq, ie, id);
2543 }
2544 
2545 /** process authoritative server reply */
2546 static void
2547 process_response(struct module_qstate* qstate, struct iter_qstate* iq,
2548 	struct iter_env* ie, int id, struct outbound_entry* outbound,
2549 	enum module_ev event)
2550 {
2551 	struct msg_parse* prs;
2552 	struct edns_data edns;
2553 	ldns_buffer* pkt;
2554 
2555 	verbose(VERB_ALGO, "process_response: new external response event");
2556 	iq->response = NULL;
2557 	iq->state = QUERY_RESP_STATE;
2558 	if(event == module_event_noreply || event == module_event_error) {
2559 		goto handle_it;
2560 	}
2561 	if( (event != module_event_reply && event != module_event_capsfail)
2562 		|| !qstate->reply) {
2563 		log_err("Bad event combined with response");
2564 		outbound_list_remove(&iq->outlist, outbound);
2565 		(void)error_response(qstate, id, LDNS_RCODE_SERVFAIL);
2566 		return;
2567 	}
2568 
2569 	/* parse message */
2570 	prs = (struct msg_parse*)regional_alloc(qstate->env->scratch,
2571 		sizeof(struct msg_parse));
2572 	if(!prs) {
2573 		log_err("out of memory on incoming message");
2574 		/* like packet got dropped */
2575 		goto handle_it;
2576 	}
2577 	memset(prs, 0, sizeof(*prs));
2578 	memset(&edns, 0, sizeof(edns));
2579 	pkt = qstate->reply->c->buffer;
2580 	ldns_buffer_set_position(pkt, 0);
2581 	if(parse_packet(pkt, prs, qstate->env->scratch) != LDNS_RCODE_NOERROR) {
2582 		verbose(VERB_ALGO, "parse error on reply packet");
2583 		goto handle_it;
2584 	}
2585 	/* edns is not examined, but removed from message to help cache */
2586 	if(parse_extract_edns(prs, &edns) != LDNS_RCODE_NOERROR)
2587 		goto handle_it;
2588 	/* remove CD-bit, we asked for in case we handle validation ourself */
2589 	prs->flags &= ~BIT_CD;
2590 
2591 	/* normalize and sanitize: easy to delete items from linked lists */
2592 	if(!scrub_message(pkt, prs, &iq->qchase, iq->dp->name,
2593 		qstate->env->scratch, qstate->env, ie))
2594 		goto handle_it;
2595 
2596 	/* allocate response dns_msg in region */
2597 	iq->response = dns_alloc_msg(pkt, prs, qstate->region);
2598 	if(!iq->response)
2599 		goto handle_it;
2600 	log_query_info(VERB_DETAIL, "response for", &qstate->qinfo);
2601 	log_name_addr(VERB_DETAIL, "reply from", iq->dp->name,
2602 		&qstate->reply->addr, qstate->reply->addrlen);
2603 	if(verbosity >= VERB_ALGO)
2604 		log_dns_msg("incoming scrubbed packet:", &iq->response->qinfo,
2605 			iq->response->rep);
2606 
2607 	if(event == module_event_capsfail) {
2608 		if(!iq->caps_fallback) {
2609 			/* start fallback */
2610 			iq->caps_fallback = 1;
2611 			iq->caps_server = 0;
2612 			iq->caps_reply = iq->response->rep;
2613 			iq->state = QUERYTARGETS_STATE;
2614 			iq->num_current_queries--;
2615 			verbose(VERB_DETAIL, "Capsforid: starting fallback");
2616 			goto handle_it;
2617 		} else {
2618 			/* check if reply is the same, otherwise, fail */
2619 			if(!reply_equal(iq->response->rep, iq->caps_reply,
2620 				qstate->env->scratch_buffer)) {
2621 				verbose(VERB_DETAIL, "Capsforid fallback: "
2622 					"getting different replies, failed");
2623 				outbound_list_remove(&iq->outlist, outbound);
2624 				(void)error_response(qstate, id,
2625 					LDNS_RCODE_SERVFAIL);
2626 				return;
2627 			}
2628 			/* continue the fallback procedure at next server */
2629 			iq->caps_server++;
2630 			iq->state = QUERYTARGETS_STATE;
2631 			iq->num_current_queries--;
2632 			verbose(VERB_DETAIL, "Capsforid: reply is equal. "
2633 				"go to next fallback");
2634 			goto handle_it;
2635 		}
2636 	}
2637 	iq->caps_fallback = 0; /* if we were in fallback, 0x20 is OK now */
2638 
2639 handle_it:
2640 	outbound_list_remove(&iq->outlist, outbound);
2641 	iter_handle(qstate, iq, ie, id);
2642 }
2643 
2644 void
2645 iter_operate(struct module_qstate* qstate, enum module_ev event, int id,
2646 	struct outbound_entry* outbound)
2647 {
2648 	struct iter_env* ie = (struct iter_env*)qstate->env->modinfo[id];
2649 	struct iter_qstate* iq = (struct iter_qstate*)qstate->minfo[id];
2650 	verbose(VERB_QUERY, "iterator[module %d] operate: extstate:%s event:%s",
2651 		id, strextstate(qstate->ext_state[id]), strmodulevent(event));
2652 	if(iq) log_query_info(VERB_QUERY, "iterator operate: query",
2653 		&qstate->qinfo);
2654 	if(iq && qstate->qinfo.qname != iq->qchase.qname)
2655 		log_query_info(VERB_QUERY, "iterator operate: chased to",
2656 			&iq->qchase);
2657 
2658 	/* perform iterator state machine */
2659 	if((event == module_event_new || event == module_event_pass) &&
2660 		iq == NULL) {
2661 		if(!iter_new(qstate, id)) {
2662 			(void)error_response(qstate, id, LDNS_RCODE_SERVFAIL);
2663 			return;
2664 		}
2665 		iq = (struct iter_qstate*)qstate->minfo[id];
2666 		process_request(qstate, iq, ie, id);
2667 		return;
2668 	}
2669 	if(iq && event == module_event_pass) {
2670 		iter_handle(qstate, iq, ie, id);
2671 		return;
2672 	}
2673 	if(iq && outbound) {
2674 		process_response(qstate, iq, ie, id, outbound, event);
2675 		return;
2676 	}
2677 	if(event == module_event_error) {
2678 		verbose(VERB_ALGO, "got called with event error, giving up");
2679 		(void)error_response(qstate, id, LDNS_RCODE_SERVFAIL);
2680 		return;
2681 	}
2682 
2683 	log_err("bad event for iterator");
2684 	(void)error_response(qstate, id, LDNS_RCODE_SERVFAIL);
2685 }
2686 
2687 void
2688 iter_clear(struct module_qstate* qstate, int id)
2689 {
2690 	struct iter_qstate* iq;
2691 	if(!qstate)
2692 		return;
2693 	iq = (struct iter_qstate*)qstate->minfo[id];
2694 	if(iq) {
2695 		outbound_list_clear(&iq->outlist);
2696 		iq->num_current_queries = 0;
2697 	}
2698 	qstate->minfo[id] = NULL;
2699 }
2700 
2701 size_t
2702 iter_get_mem(struct module_env* env, int id)
2703 {
2704 	struct iter_env* ie = (struct iter_env*)env->modinfo[id];
2705 	if(!ie)
2706 		return 0;
2707 	return sizeof(*ie) + sizeof(int)*((size_t)ie->max_dependency_depth+1)
2708 		+ hints_get_mem(ie->hints) + donotq_get_mem(ie->donotq)
2709 		+ priv_get_mem(ie->priv);
2710 }
2711 
2712 /**
2713  * The iterator function block
2714  */
2715 static struct module_func_block iter_block = {
2716 	"iterator",
2717 	&iter_init, &iter_deinit, &iter_operate, &iter_inform_super,
2718 	&iter_clear, &iter_get_mem
2719 };
2720 
2721 struct module_func_block*
2722 iter_get_funcblock(void)
2723 {
2724 	return &iter_block;
2725 }
2726 
2727 const char*
2728 iter_state_to_string(enum iter_state state)
2729 {
2730 	switch (state)
2731 	{
2732 	case INIT_REQUEST_STATE :
2733 		return "INIT REQUEST STATE";
2734 	case INIT_REQUEST_2_STATE :
2735 		return "INIT REQUEST STATE (stage 2)";
2736 	case INIT_REQUEST_3_STATE:
2737 		return "INIT REQUEST STATE (stage 3)";
2738 	case QUERYTARGETS_STATE :
2739 		return "QUERY TARGETS STATE";
2740 	case PRIME_RESP_STATE :
2741 		return "PRIME RESPONSE STATE";
2742 	case COLLECT_CLASS_STATE :
2743 		return "COLLECT CLASS STATE";
2744 	case QUERY_RESP_STATE :
2745 		return "QUERY RESPONSE STATE";
2746 	case FINISHED_STATE :
2747 		return "FINISHED RESPONSE STATE";
2748 	default :
2749 		return "UNKNOWN ITER STATE";
2750 	}
2751 }
2752 
2753 int
2754 iter_state_is_responsestate(enum iter_state s)
2755 {
2756 	switch(s) {
2757 		case INIT_REQUEST_STATE :
2758 		case INIT_REQUEST_2_STATE :
2759 		case INIT_REQUEST_3_STATE :
2760 		case QUERYTARGETS_STATE :
2761 		case COLLECT_CLASS_STATE :
2762 			return 0;
2763 		default:
2764 			break;
2765 	}
2766 	return 1;
2767 }
2768