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