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