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