1238106Sdes/*
2238106Sdes * iterator/iterator.c - iterative resolver DNS query response module
3238106Sdes *
4238106Sdes * Copyright (c) 2007, NLnet Labs. All rights reserved.
5238106Sdes *
6238106Sdes * This software is open source.
7238106Sdes *
8238106Sdes * Redistribution and use in source and binary forms, with or without
9238106Sdes * modification, are permitted provided that the following conditions
10238106Sdes * are met:
11238106Sdes *
12238106Sdes * Redistributions of source code must retain the above copyright notice,
13238106Sdes * this list of conditions and the following disclaimer.
14238106Sdes *
15238106Sdes * Redistributions in binary form must reproduce the above copyright notice,
16238106Sdes * this list of conditions and the following disclaimer in the documentation
17238106Sdes * and/or other materials provided with the distribution.
18238106Sdes *
19238106Sdes * Neither the name of the NLNET LABS nor the names of its contributors may
20238106Sdes * be used to endorse or promote products derived from this software without
21238106Sdes * specific prior written permission.
22238106Sdes *
23238106Sdes * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
24269257Sdes * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
25269257Sdes * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
26269257Sdes * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
27269257Sdes * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
28269257Sdes * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
29269257Sdes * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
30269257Sdes * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
31269257Sdes * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
32269257Sdes * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
33269257Sdes * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
34238106Sdes */
35238106Sdes
36238106Sdes/**
37238106Sdes * \file
38238106Sdes *
39238106Sdes * This file contains a module that performs recusive iterative DNS query
40238106Sdes * processing.
41238106Sdes */
42238106Sdes
43238106Sdes#include "config.h"
44238106Sdes#include "iterator/iterator.h"
45238106Sdes#include "iterator/iter_utils.h"
46238106Sdes#include "iterator/iter_hints.h"
47238106Sdes#include "iterator/iter_fwd.h"
48238106Sdes#include "iterator/iter_donotq.h"
49238106Sdes#include "iterator/iter_delegpt.h"
50238106Sdes#include "iterator/iter_resptype.h"
51238106Sdes#include "iterator/iter_scrub.h"
52238106Sdes#include "iterator/iter_priv.h"
53238106Sdes#include "validator/val_neg.h"
54238106Sdes#include "services/cache/dns.h"
55238106Sdes#include "services/cache/infra.h"
56238106Sdes#include "util/module.h"
57238106Sdes#include "util/netevent.h"
58238106Sdes#include "util/net_help.h"
59238106Sdes#include "util/regional.h"
60238106Sdes#include "util/data/dname.h"
61238106Sdes#include "util/data/msgencode.h"
62238106Sdes#include "util/fptr_wlist.h"
63238106Sdes#include "util/config_file.h"
64291767Sdes#include "util/random.h"
65291767Sdes#include "sldns/rrdef.h"
66291767Sdes#include "sldns/wire2str.h"
67294190Sdes#include "sldns/str2wire.h"
68291767Sdes#include "sldns/parseutil.h"
69291767Sdes#include "sldns/sbuffer.h"
70238106Sdes
71238106Sdesint
72238106Sdesiter_init(struct module_env* env, int id)
73238106Sdes{
74238106Sdes	struct iter_env* iter_env = (struct iter_env*)calloc(1,
75238106Sdes		sizeof(struct iter_env));
76238106Sdes	if(!iter_env) {
77238106Sdes		log_err("malloc failure");
78238106Sdes		return 0;
79238106Sdes	}
80238106Sdes	env->modinfo[id] = (void*)iter_env;
81238106Sdes	if(!iter_apply_cfg(iter_env, env->cfg)) {
82238106Sdes		log_err("iterator: could not apply configuration settings.");
83238106Sdes		return 0;
84238106Sdes	}
85294190Sdes	if(env->cfg->qname_minimisation) {
86294190Sdes		uint8_t dname[LDNS_MAX_DOMAINLEN+1];
87294190Sdes		size_t len = sizeof(dname);
88294190Sdes		if(sldns_str2wire_dname_buf("ip6.arpa.", dname, &len) != 0) {
89294190Sdes			log_err("ip6.arpa. parse error");
90294190Sdes			return 0;
91294190Sdes		}
92294190Sdes		iter_env->ip6arpa_dname = (uint8_t*)malloc(len);
93294190Sdes		if(!iter_env->ip6arpa_dname) {
94294190Sdes			log_err("malloc failure");
95294190Sdes			return 0;
96294190Sdes		}
97294190Sdes		memcpy(iter_env->ip6arpa_dname, dname, len);
98294190Sdes	}
99294190Sdes
100238106Sdes	return 1;
101238106Sdes}
102238106Sdes
103291767Sdes/** delete caps_whitelist element */
104291767Sdesstatic void
105291767Sdescaps_free(struct rbnode_t* n, void* ATTR_UNUSED(d))
106291767Sdes{
107291767Sdes	if(n) {
108291767Sdes		free(((struct name_tree_node*)n)->name);
109291767Sdes		free(n);
110291767Sdes	}
111291767Sdes}
112291767Sdes
113238106Sdesvoid
114238106Sdesiter_deinit(struct module_env* env, int id)
115238106Sdes{
116238106Sdes	struct iter_env* iter_env;
117238106Sdes	if(!env || !env->modinfo[id])
118238106Sdes		return;
119238106Sdes	iter_env = (struct iter_env*)env->modinfo[id];
120294190Sdes	free(iter_env->ip6arpa_dname);
121238106Sdes	free(iter_env->target_fetch_policy);
122238106Sdes	priv_delete(iter_env->priv);
123238106Sdes	donotq_delete(iter_env->donotq);
124291767Sdes	if(iter_env->caps_white) {
125291767Sdes		traverse_postorder(iter_env->caps_white, caps_free, NULL);
126291767Sdes		free(iter_env->caps_white);
127291767Sdes	}
128238106Sdes	free(iter_env);
129238106Sdes	env->modinfo[id] = NULL;
130238106Sdes}
131238106Sdes
132238106Sdes/** new query for iterator */
133238106Sdesstatic int
134238106Sdesiter_new(struct module_qstate* qstate, int id)
135238106Sdes{
136238106Sdes	struct iter_qstate* iq = (struct iter_qstate*)regional_alloc(
137238106Sdes		qstate->region, sizeof(struct iter_qstate));
138238106Sdes	qstate->minfo[id] = iq;
139238106Sdes	if(!iq)
140238106Sdes		return 0;
141238106Sdes	memset(iq, 0, sizeof(*iq));
142238106Sdes	iq->state = INIT_REQUEST_STATE;
143238106Sdes	iq->final_state = FINISHED_STATE;
144238106Sdes	iq->an_prepend_list = NULL;
145238106Sdes	iq->an_prepend_last = NULL;
146238106Sdes	iq->ns_prepend_list = NULL;
147238106Sdes	iq->ns_prepend_last = NULL;
148238106Sdes	iq->dp = NULL;
149238106Sdes	iq->depth = 0;
150238106Sdes	iq->num_target_queries = 0;
151238106Sdes	iq->num_current_queries = 0;
152238106Sdes	iq->query_restart_count = 0;
153238106Sdes	iq->referral_count = 0;
154238106Sdes	iq->sent_count = 0;
155291767Sdes	iq->ratelimit_ok = 0;
156275853Sdelphij	iq->target_count = NULL;
157238106Sdes	iq->wait_priming_stub = 0;
158238106Sdes	iq->refetch_glue = 0;
159238106Sdes	iq->dnssec_expected = 0;
160238106Sdes	iq->dnssec_lame_query = 0;
161238106Sdes	iq->chase_flags = qstate->query_flags;
162238106Sdes	/* Start with the (current) qname. */
163238106Sdes	iq->qchase = qstate->qinfo;
164238106Sdes	outbound_list_init(&iq->outlist);
165294190Sdes	if (qstate->env->cfg->qname_minimisation)
166294190Sdes		iq->minimisation_state = INIT_MINIMISE_STATE;
167294190Sdes	else
168294190Sdes		iq->minimisation_state = DONOT_MINIMISE_STATE;
169294190Sdes
170294190Sdes	memset(&iq->qinfo_out, 0, sizeof(struct query_info));
171238106Sdes	return 1;
172238106Sdes}
173238106Sdes
174238106Sdes/**
175238106Sdes * Transition to the next state. This can be used to advance a currently
176238106Sdes * processing event. It cannot be used to reactivate a forEvent.
177238106Sdes *
178238106Sdes * @param iq: iterator query state
179238106Sdes * @param nextstate The state to transition to.
180238106Sdes * @return true. This is so this can be called as the return value for the
181238106Sdes *         actual process*State() methods. (Transitioning to the next state
182238106Sdes *         implies further processing).
183238106Sdes */
184238106Sdesstatic int
185238106Sdesnext_state(struct iter_qstate* iq, enum iter_state nextstate)
186238106Sdes{
187238106Sdes	/* If transitioning to a "response" state, make sure that there is a
188238106Sdes	 * response */
189238106Sdes	if(iter_state_is_responsestate(nextstate)) {
190238106Sdes		if(iq->response == NULL) {
191238106Sdes			log_err("transitioning to response state sans "
192238106Sdes				"response.");
193238106Sdes		}
194238106Sdes	}
195238106Sdes	iq->state = nextstate;
196238106Sdes	return 1;
197238106Sdes}
198238106Sdes
199238106Sdes/**
200238106Sdes * Transition an event to its final state. Final states always either return
201238106Sdes * a result up the module chain, or reactivate a dependent event. Which
202294190Sdes * final state to transition to is set in the module state for the event when
203238106Sdes * it was created, and depends on the original purpose of the event.
204238106Sdes *
205238106Sdes * The response is stored in the qstate->buf buffer.
206238106Sdes *
207238106Sdes * @param iq: iterator query state
208238106Sdes * @return false. This is so this method can be used as the return value for
209238106Sdes *         the processState methods. (Transitioning to the final state
210238106Sdes */
211238106Sdesstatic int
212238106Sdesfinal_state(struct iter_qstate* iq)
213238106Sdes{
214238106Sdes	return next_state(iq, iq->final_state);
215238106Sdes}
216238106Sdes
217238106Sdes/**
218238106Sdes * Callback routine to handle errors in parent query states
219238106Sdes * @param qstate: query state that failed.
220238106Sdes * @param id: module id.
221238106Sdes * @param super: super state.
222238106Sdes */
223238106Sdesstatic void
224238106Sdeserror_supers(struct module_qstate* qstate, int id, struct module_qstate* super)
225238106Sdes{
226238106Sdes	struct iter_qstate* super_iq = (struct iter_qstate*)super->minfo[id];
227238106Sdes
228238106Sdes	if(qstate->qinfo.qtype == LDNS_RR_TYPE_A ||
229238106Sdes		qstate->qinfo.qtype == LDNS_RR_TYPE_AAAA) {
230238106Sdes		/* mark address as failed. */
231238106Sdes		struct delegpt_ns* dpns = NULL;
232238106Sdes		if(super_iq->dp)
233238106Sdes			dpns = delegpt_find_ns(super_iq->dp,
234238106Sdes				qstate->qinfo.qname, qstate->qinfo.qname_len);
235238106Sdes		if(!dpns) {
236238106Sdes			/* not interested */
237238106Sdes			verbose(VERB_ALGO, "subq error, but not interested");
238238106Sdes			log_query_info(VERB_ALGO, "superq", &super->qinfo);
239238106Sdes			if(super_iq->dp)
240238106Sdes				delegpt_log(VERB_ALGO, super_iq->dp);
241238106Sdes			log_assert(0);
242238106Sdes			return;
243238106Sdes		} else {
244238106Sdes			/* see if the failure did get (parent-lame) info */
245238106Sdes			if(!cache_fill_missing(super->env,
246238106Sdes				super_iq->qchase.qclass, super->region,
247238106Sdes				super_iq->dp))
248238106Sdes				log_err("out of memory adding missing");
249238106Sdes		}
250238106Sdes		dpns->resolved = 1; /* mark as failed */
251238106Sdes		super_iq->num_target_queries--;
252238106Sdes	}
253238106Sdes	if(qstate->qinfo.qtype == LDNS_RR_TYPE_NS) {
254238106Sdes		/* prime failed to get delegation */
255238106Sdes		super_iq->dp = NULL;
256238106Sdes	}
257238106Sdes	/* evaluate targets again */
258238106Sdes	super_iq->state = QUERYTARGETS_STATE;
259238106Sdes	/* super becomes runnable, and will process this change */
260238106Sdes}
261238106Sdes
262238106Sdes/**
263238106Sdes * Return an error to the client
264238106Sdes * @param qstate: our query state
265238106Sdes * @param id: module id
266238106Sdes * @param rcode: error code (DNS errcode).
267238106Sdes * @return: 0 for use by caller, to make notation easy, like:
268238106Sdes * 	return error_response(..).
269238106Sdes */
270238106Sdesstatic int
271238106Sdeserror_response(struct module_qstate* qstate, int id, int rcode)
272238106Sdes{
273238106Sdes	verbose(VERB_QUERY, "return error response %s",
274269257Sdes		sldns_lookup_by_id(sldns_rcodes, rcode)?
275269257Sdes		sldns_lookup_by_id(sldns_rcodes, rcode)->name:"??");
276238106Sdes	qstate->return_rcode = rcode;
277238106Sdes	qstate->return_msg = NULL;
278238106Sdes	qstate->ext_state[id] = module_finished;
279238106Sdes	return 0;
280238106Sdes}
281238106Sdes
282238106Sdes/**
283238106Sdes * Return an error to the client and cache the error code in the
284238106Sdes * message cache (so per qname, qtype, qclass).
285238106Sdes * @param qstate: our query state
286238106Sdes * @param id: module id
287238106Sdes * @param rcode: error code (DNS errcode).
288238106Sdes * @return: 0 for use by caller, to make notation easy, like:
289238106Sdes * 	return error_response(..).
290238106Sdes */
291238106Sdesstatic int
292238106Sdeserror_response_cache(struct module_qstate* qstate, int id, int rcode)
293238106Sdes{
294238106Sdes	/* store in cache */
295238106Sdes	struct reply_info err;
296285206Sdes	if(qstate->prefetch_leeway > NORR_TTL) {
297285206Sdes		verbose(VERB_ALGO, "error response for prefetch in cache");
298285206Sdes		/* attempt to adjust the cache entry prefetch */
299285206Sdes		if(dns_cache_prefetch_adjust(qstate->env, &qstate->qinfo,
300285206Sdes			NORR_TTL, qstate->query_flags))
301285206Sdes			return error_response(qstate, id, rcode);
302285206Sdes		/* if that fails (not in cache), fall through to store err */
303285206Sdes	}
304238106Sdes	memset(&err, 0, sizeof(err));
305238106Sdes	err.flags = (uint16_t)(BIT_QR | BIT_RA);
306238106Sdes	FLAGS_SET_RCODE(err.flags, rcode);
307238106Sdes	err.qdcount = 1;
308238106Sdes	err.ttl = NORR_TTL;
309238106Sdes	err.prefetch_ttl = PREFETCH_TTL_CALC(err.ttl);
310238106Sdes	/* do not waste time trying to validate this servfail */
311238106Sdes	err.security = sec_status_indeterminate;
312238106Sdes	verbose(VERB_ALGO, "store error response in message cache");
313285206Sdes	iter_dns_store(qstate->env, &qstate->qinfo, &err, 0, 0, 0, NULL,
314285206Sdes		qstate->query_flags);
315238106Sdes	return error_response(qstate, id, rcode);
316238106Sdes}
317238106Sdes
318238106Sdes/** check if prepend item is duplicate item */
319238106Sdesstatic int
320238106Sdesprepend_is_duplicate(struct ub_packed_rrset_key** sets, size_t to,
321238106Sdes	struct ub_packed_rrset_key* dup)
322238106Sdes{
323238106Sdes	size_t i;
324238106Sdes	for(i=0; i<to; i++) {
325238106Sdes		if(sets[i]->rk.type == dup->rk.type &&
326238106Sdes			sets[i]->rk.rrset_class == dup->rk.rrset_class &&
327238106Sdes			sets[i]->rk.dname_len == dup->rk.dname_len &&
328238106Sdes			query_dname_compare(sets[i]->rk.dname, dup->rk.dname)
329238106Sdes			== 0)
330238106Sdes			return 1;
331238106Sdes	}
332238106Sdes	return 0;
333238106Sdes}
334238106Sdes
335238106Sdes/** prepend the prepend list in the answer and authority section of dns_msg */
336238106Sdesstatic int
337238106Sdesiter_prepend(struct iter_qstate* iq, struct dns_msg* msg,
338238106Sdes	struct regional* region)
339238106Sdes{
340238106Sdes	struct iter_prep_list* p;
341238106Sdes	struct ub_packed_rrset_key** sets;
342238106Sdes	size_t num_an = 0, num_ns = 0;;
343238106Sdes	for(p = iq->an_prepend_list; p; p = p->next)
344238106Sdes		num_an++;
345238106Sdes	for(p = iq->ns_prepend_list; p; p = p->next)
346238106Sdes		num_ns++;
347238106Sdes	if(num_an + num_ns == 0)
348238106Sdes		return 1;
349238106Sdes	verbose(VERB_ALGO, "prepending %d rrsets", (int)num_an + (int)num_ns);
350291767Sdes	if(num_an > RR_COUNT_MAX || num_ns > RR_COUNT_MAX ||
351291767Sdes		msg->rep->rrset_count > RR_COUNT_MAX) return 0; /* overflow */
352238106Sdes	sets = regional_alloc(region, (num_an+num_ns+msg->rep->rrset_count) *
353238106Sdes		sizeof(struct ub_packed_rrset_key*));
354238106Sdes	if(!sets)
355238106Sdes		return 0;
356238106Sdes	/* ANSWER section */
357238106Sdes	num_an = 0;
358238106Sdes	for(p = iq->an_prepend_list; p; p = p->next) {
359238106Sdes		sets[num_an++] = p->rrset;
360238106Sdes	}
361238106Sdes	memcpy(sets+num_an, msg->rep->rrsets, msg->rep->an_numrrsets *
362238106Sdes		sizeof(struct ub_packed_rrset_key*));
363238106Sdes	/* AUTH section */
364238106Sdes	num_ns = 0;
365238106Sdes	for(p = iq->ns_prepend_list; p; p = p->next) {
366238106Sdes		if(prepend_is_duplicate(sets+msg->rep->an_numrrsets+num_an,
367238106Sdes			num_ns, p->rrset) || prepend_is_duplicate(
368238106Sdes			msg->rep->rrsets+msg->rep->an_numrrsets,
369238106Sdes			msg->rep->ns_numrrsets, p->rrset))
370238106Sdes			continue;
371238106Sdes		sets[msg->rep->an_numrrsets + num_an + num_ns++] = p->rrset;
372238106Sdes	}
373238106Sdes	memcpy(sets + num_an + msg->rep->an_numrrsets + num_ns,
374238106Sdes		msg->rep->rrsets + msg->rep->an_numrrsets,
375238106Sdes		(msg->rep->ns_numrrsets + msg->rep->ar_numrrsets) *
376238106Sdes		sizeof(struct ub_packed_rrset_key*));
377238106Sdes
378238106Sdes	/* NXDOMAIN rcode can stay if we prepended DNAME/CNAMEs, because
379238106Sdes	 * this is what recursors should give. */
380238106Sdes	msg->rep->rrset_count += num_an + num_ns;
381238106Sdes	msg->rep->an_numrrsets += num_an;
382238106Sdes	msg->rep->ns_numrrsets += num_ns;
383238106Sdes	msg->rep->rrsets = sets;
384238106Sdes	return 1;
385238106Sdes}
386238106Sdes
387238106Sdes/**
388238106Sdes * Add rrset to ANSWER prepend list
389238106Sdes * @param qstate: query state.
390238106Sdes * @param iq: iterator query state.
391238106Sdes * @param rrset: rrset to add.
392238106Sdes * @return false on failure (malloc).
393238106Sdes */
394238106Sdesstatic int
395238106Sdesiter_add_prepend_answer(struct module_qstate* qstate, struct iter_qstate* iq,
396238106Sdes	struct ub_packed_rrset_key* rrset)
397238106Sdes{
398238106Sdes	struct iter_prep_list* p = (struct iter_prep_list*)regional_alloc(
399238106Sdes		qstate->region, sizeof(struct iter_prep_list));
400238106Sdes	if(!p)
401238106Sdes		return 0;
402238106Sdes	p->rrset = rrset;
403238106Sdes	p->next = NULL;
404238106Sdes	/* add at end */
405238106Sdes	if(iq->an_prepend_last)
406238106Sdes		iq->an_prepend_last->next = p;
407238106Sdes	else	iq->an_prepend_list = p;
408238106Sdes	iq->an_prepend_last = p;
409238106Sdes	return 1;
410238106Sdes}
411238106Sdes
412238106Sdes/**
413238106Sdes * Add rrset to AUTHORITY prepend list
414238106Sdes * @param qstate: query state.
415238106Sdes * @param iq: iterator query state.
416238106Sdes * @param rrset: rrset to add.
417238106Sdes * @return false on failure (malloc).
418238106Sdes */
419238106Sdesstatic int
420238106Sdesiter_add_prepend_auth(struct module_qstate* qstate, struct iter_qstate* iq,
421238106Sdes	struct ub_packed_rrset_key* rrset)
422238106Sdes{
423238106Sdes	struct iter_prep_list* p = (struct iter_prep_list*)regional_alloc(
424238106Sdes		qstate->region, sizeof(struct iter_prep_list));
425238106Sdes	if(!p)
426238106Sdes		return 0;
427238106Sdes	p->rrset = rrset;
428238106Sdes	p->next = NULL;
429238106Sdes	/* add at end */
430238106Sdes	if(iq->ns_prepend_last)
431238106Sdes		iq->ns_prepend_last->next = p;
432238106Sdes	else	iq->ns_prepend_list = p;
433238106Sdes	iq->ns_prepend_last = p;
434238106Sdes	return 1;
435238106Sdes}
436238106Sdes
437238106Sdes/**
438238106Sdes * Given a CNAME response (defined as a response containing a CNAME or DNAME
439238106Sdes * that does not answer the request), process the response, modifying the
440238106Sdes * state as necessary. This follows the CNAME/DNAME chain and returns the
441238106Sdes * final query name.
442238106Sdes *
443238106Sdes * sets the new query name, after following the CNAME/DNAME chain.
444238106Sdes * @param qstate: query state.
445238106Sdes * @param iq: iterator query state.
446238106Sdes * @param msg: the response.
447238106Sdes * @param mname: returned target new query name.
448238106Sdes * @param mname_len: length of mname.
449238106Sdes * @return false on (malloc) error.
450238106Sdes */
451238106Sdesstatic int
452238106Sdeshandle_cname_response(struct module_qstate* qstate, struct iter_qstate* iq,
453238106Sdes        struct dns_msg* msg, uint8_t** mname, size_t* mname_len)
454238106Sdes{
455238106Sdes	size_t i;
456238106Sdes	/* Start with the (current) qname. */
457238106Sdes	*mname = iq->qchase.qname;
458238106Sdes	*mname_len = iq->qchase.qname_len;
459238106Sdes
460238106Sdes	/* Iterate over the ANSWER rrsets in order, looking for CNAMEs and
461238106Sdes	 * DNAMES. */
462238106Sdes	for(i=0; i<msg->rep->an_numrrsets; i++) {
463238106Sdes		struct ub_packed_rrset_key* r = msg->rep->rrsets[i];
464238106Sdes		/* If there is a (relevant) DNAME, add it to the list.
465238106Sdes		 * We always expect there to be CNAME that was generated
466238106Sdes		 * by this DNAME following, so we don't process the DNAME
467238106Sdes		 * directly.  */
468238106Sdes		if(ntohs(r->rk.type) == LDNS_RR_TYPE_DNAME &&
469238106Sdes			dname_strict_subdomain_c(*mname, r->rk.dname)) {
470238106Sdes			if(!iter_add_prepend_answer(qstate, iq, r))
471238106Sdes				return 0;
472238106Sdes			continue;
473238106Sdes		}
474238106Sdes
475238106Sdes		if(ntohs(r->rk.type) == LDNS_RR_TYPE_CNAME &&
476238106Sdes			query_dname_compare(*mname, r->rk.dname) == 0) {
477238106Sdes			/* Add this relevant CNAME rrset to the prepend list.*/
478238106Sdes			if(!iter_add_prepend_answer(qstate, iq, r))
479238106Sdes				return 0;
480238106Sdes			get_cname_target(r, mname, mname_len);
481238106Sdes		}
482238106Sdes
483238106Sdes		/* Other rrsets in the section are ignored. */
484238106Sdes	}
485238106Sdes	/* add authority rrsets to authority prepend, for wildcarded CNAMEs */
486238106Sdes	for(i=msg->rep->an_numrrsets; i<msg->rep->an_numrrsets +
487238106Sdes		msg->rep->ns_numrrsets; i++) {
488238106Sdes		struct ub_packed_rrset_key* r = msg->rep->rrsets[i];
489238106Sdes		/* only add NSEC/NSEC3, as they may be needed for validation */
490238106Sdes		if(ntohs(r->rk.type) == LDNS_RR_TYPE_NSEC ||
491238106Sdes			ntohs(r->rk.type) == LDNS_RR_TYPE_NSEC3) {
492238106Sdes			if(!iter_add_prepend_auth(qstate, iq, r))
493238106Sdes				return 0;
494238106Sdes		}
495238106Sdes	}
496238106Sdes	return 1;
497238106Sdes}
498238106Sdes
499291767Sdes/** see if target name is caps-for-id whitelisted */
500291767Sdesstatic int
501291767Sdesis_caps_whitelisted(struct iter_env* ie, struct iter_qstate* iq)
502291767Sdes{
503291767Sdes	if(!ie->caps_white) return 0; /* no whitelist, or no capsforid */
504291767Sdes	return name_tree_lookup(ie->caps_white, iq->qchase.qname,
505291767Sdes		iq->qchase.qname_len, dname_count_labels(iq->qchase.qname),
506291767Sdes		iq->qchase.qclass) != NULL;
507291767Sdes}
508291767Sdes
509275853Sdelphij/** create target count structure for this query */
510275853Sdelphijstatic void
511275853Sdelphijtarget_count_create(struct iter_qstate* iq)
512275853Sdelphij{
513275853Sdelphij	if(!iq->target_count) {
514275853Sdelphij		iq->target_count = (int*)calloc(2, sizeof(int));
515275853Sdelphij		/* if calloc fails we simply do not track this number */
516275853Sdelphij		if(iq->target_count)
517275853Sdelphij			iq->target_count[0] = 1;
518275853Sdelphij	}
519275853Sdelphij}
520275853Sdelphij
521275853Sdelphijstatic void
522275853Sdelphijtarget_count_increase(struct iter_qstate* iq, int num)
523275853Sdelphij{
524275853Sdelphij	target_count_create(iq);
525275853Sdelphij	if(iq->target_count)
526275853Sdelphij		iq->target_count[1] += num;
527275853Sdelphij}
528275853Sdelphij
529238106Sdes/**
530238106Sdes * Generate a subrequest.
531238106Sdes * Generate a local request event. Local events are tied to this module, and
532294190Sdes * have a corresponding (first tier) event that is waiting for this event to
533238106Sdes * resolve to continue.
534238106Sdes *
535238106Sdes * @param qname The query name for this request.
536238106Sdes * @param qnamelen length of qname
537238106Sdes * @param qtype The query type for this request.
538238106Sdes * @param qclass The query class for this request.
539238106Sdes * @param qstate The event that is generating this event.
540238106Sdes * @param id: module id.
541238106Sdes * @param iq: The iterator state that is generating this event.
542238106Sdes * @param initial_state The initial response state (normally this
543238106Sdes *          is QUERY_RESP_STATE, unless it is known that the request won't
544238106Sdes *          need iterative processing
545238106Sdes * @param finalstate The final state for the response to this request.
546238106Sdes * @param subq_ret: if newly allocated, the subquerystate, or NULL if it does
547238106Sdes * 	not need initialisation.
548238106Sdes * @param v: if true, validation is done on the subquery.
549238106Sdes * @return false on error (malloc).
550238106Sdes */
551238106Sdesstatic int
552238106Sdesgenerate_sub_request(uint8_t* qname, size_t qnamelen, uint16_t qtype,
553238106Sdes	uint16_t qclass, struct module_qstate* qstate, int id,
554238106Sdes	struct iter_qstate* iq, enum iter_state initial_state,
555238106Sdes	enum iter_state finalstate, struct module_qstate** subq_ret, int v)
556238106Sdes{
557238106Sdes	struct module_qstate* subq = NULL;
558238106Sdes	struct iter_qstate* subiq = NULL;
559238106Sdes	uint16_t qflags = 0; /* OPCODE QUERY, no flags */
560238106Sdes	struct query_info qinf;
561238106Sdes	int prime = (finalstate == PRIME_RESP_STATE)?1:0;
562285206Sdes	int valrec = 0;
563238106Sdes	qinf.qname = qname;
564238106Sdes	qinf.qname_len = qnamelen;
565238106Sdes	qinf.qtype = qtype;
566238106Sdes	qinf.qclass = qclass;
567238106Sdes
568238106Sdes	/* RD should be set only when sending the query back through the INIT
569238106Sdes	 * state. */
570238106Sdes	if(initial_state == INIT_REQUEST_STATE)
571238106Sdes		qflags |= BIT_RD;
572238106Sdes	/* We set the CD flag so we can send this through the "head" of
573238106Sdes	 * the resolution chain, which might have a validator. We are
574238106Sdes	 * uninterested in validating things not on the direct resolution
575238106Sdes	 * path.  */
576285206Sdes	if(!v) {
577238106Sdes		qflags |= BIT_CD;
578285206Sdes		valrec = 1;
579285206Sdes	}
580238106Sdes
581238106Sdes	/* attach subquery, lookup existing or make a new one */
582238106Sdes	fptr_ok(fptr_whitelist_modenv_attach_sub(qstate->env->attach_sub));
583285206Sdes	if(!(*qstate->env->attach_sub)(qstate, &qinf, qflags, prime, valrec,
584285206Sdes		&subq)) {
585238106Sdes		return 0;
586238106Sdes	}
587238106Sdes	*subq_ret = subq;
588238106Sdes	if(subq) {
589238106Sdes		/* initialise the new subquery */
590238106Sdes		subq->curmod = id;
591238106Sdes		subq->ext_state[id] = module_state_initial;
592238106Sdes		subq->minfo[id] = regional_alloc(subq->region,
593238106Sdes			sizeof(struct iter_qstate));
594238106Sdes		if(!subq->minfo[id]) {
595238106Sdes			log_err("init subq: out of memory");
596238106Sdes			fptr_ok(fptr_whitelist_modenv_kill_sub(
597238106Sdes				qstate->env->kill_sub));
598238106Sdes			(*qstate->env->kill_sub)(subq);
599238106Sdes			return 0;
600238106Sdes		}
601238106Sdes		subiq = (struct iter_qstate*)subq->minfo[id];
602238106Sdes		memset(subiq, 0, sizeof(*subiq));
603238106Sdes		subiq->num_target_queries = 0;
604275853Sdelphij		target_count_create(iq);
605275853Sdelphij		subiq->target_count = iq->target_count;
606275853Sdelphij		if(iq->target_count)
607275853Sdelphij			iq->target_count[0] ++; /* extra reference */
608238106Sdes		subiq->num_current_queries = 0;
609238106Sdes		subiq->depth = iq->depth+1;
610238106Sdes		outbound_list_init(&subiq->outlist);
611238106Sdes		subiq->state = initial_state;
612238106Sdes		subiq->final_state = finalstate;
613238106Sdes		subiq->qchase = subq->qinfo;
614238106Sdes		subiq->chase_flags = subq->query_flags;
615238106Sdes		subiq->refetch_glue = 0;
616294190Sdes		if(qstate->env->cfg->qname_minimisation)
617294190Sdes			subiq->minimisation_state = INIT_MINIMISE_STATE;
618294190Sdes		else
619294190Sdes			subiq->minimisation_state = DONOT_MINIMISE_STATE;
620294190Sdes		memset(&subiq->qinfo_out, 0, sizeof(struct query_info));
621238106Sdes	}
622238106Sdes	return 1;
623238106Sdes}
624238106Sdes
625238106Sdes/**
626238106Sdes * Generate and send a root priming request.
627238106Sdes * @param qstate: the qtstate that triggered the need to prime.
628238106Sdes * @param iq: iterator query state.
629238106Sdes * @param id: module id.
630238106Sdes * @param qclass: the class to prime.
631238106Sdes * @return 0 on failure
632238106Sdes */
633238106Sdesstatic int
634238106Sdesprime_root(struct module_qstate* qstate, struct iter_qstate* iq, int id,
635238106Sdes	uint16_t qclass)
636238106Sdes{
637238106Sdes	struct delegpt* dp;
638238106Sdes	struct module_qstate* subq;
639238106Sdes	verbose(VERB_DETAIL, "priming . %s NS",
640269257Sdes		sldns_lookup_by_id(sldns_rr_classes, (int)qclass)?
641269257Sdes		sldns_lookup_by_id(sldns_rr_classes, (int)qclass)->name:"??");
642238106Sdes	dp = hints_lookup_root(qstate->env->hints, qclass);
643238106Sdes	if(!dp) {
644238106Sdes		verbose(VERB_ALGO, "Cannot prime due to lack of hints");
645238106Sdes		return 0;
646238106Sdes	}
647238106Sdes	/* Priming requests start at the QUERYTARGETS state, skipping
648238106Sdes	 * the normal INIT state logic (which would cause an infloop). */
649238106Sdes	if(!generate_sub_request((uint8_t*)"\000", 1, LDNS_RR_TYPE_NS,
650238106Sdes		qclass, qstate, id, iq, QUERYTARGETS_STATE, PRIME_RESP_STATE,
651238106Sdes		&subq, 0)) {
652238106Sdes		verbose(VERB_ALGO, "could not prime root");
653238106Sdes		return 0;
654238106Sdes	}
655238106Sdes	if(subq) {
656238106Sdes		struct iter_qstate* subiq =
657238106Sdes			(struct iter_qstate*)subq->minfo[id];
658238106Sdes		/* Set the initial delegation point to the hint.
659238106Sdes		 * copy dp, it is now part of the root prime query.
660238106Sdes		 * dp was part of in the fixed hints structure. */
661238106Sdes		subiq->dp = delegpt_copy(dp, subq->region);
662238106Sdes		if(!subiq->dp) {
663238106Sdes			log_err("out of memory priming root, copydp");
664238106Sdes			fptr_ok(fptr_whitelist_modenv_kill_sub(
665238106Sdes				qstate->env->kill_sub));
666238106Sdes			(*qstate->env->kill_sub)(subq);
667238106Sdes			return 0;
668238106Sdes		}
669238106Sdes		/* there should not be any target queries. */
670238106Sdes		subiq->num_target_queries = 0;
671238106Sdes		subiq->dnssec_expected = iter_indicates_dnssec(
672238106Sdes			qstate->env, subiq->dp, NULL, subq->qinfo.qclass);
673238106Sdes	}
674238106Sdes
675238106Sdes	/* this module stops, our submodule starts, and does the query. */
676238106Sdes	qstate->ext_state[id] = module_wait_subquery;
677238106Sdes	return 1;
678238106Sdes}
679238106Sdes
680238106Sdes/**
681238106Sdes * Generate and process a stub priming request. This method tests for the
682238106Sdes * need to prime a stub zone, so it is safe to call for every request.
683238106Sdes *
684238106Sdes * @param qstate: the qtstate that triggered the need to prime.
685238106Sdes * @param iq: iterator query state.
686238106Sdes * @param id: module id.
687238106Sdes * @param qname: request name.
688238106Sdes * @param qclass: request class.
689238106Sdes * @return true if a priming subrequest was made, false if not. The will only
690238106Sdes *         issue a priming request if it detects an unprimed stub.
691238106Sdes *         Uses value of 2 to signal during stub-prime in root-prime situation
692238106Sdes *         that a noprime-stub is available and resolution can continue.
693238106Sdes */
694238106Sdesstatic int
695238106Sdesprime_stub(struct module_qstate* qstate, struct iter_qstate* iq, int id,
696238106Sdes	uint8_t* qname, uint16_t qclass)
697238106Sdes{
698238106Sdes	/* Lookup the stub hint. This will return null if the stub doesn't
699238106Sdes	 * need to be re-primed. */
700238106Sdes	struct iter_hints_stub* stub;
701238106Sdes	struct delegpt* stub_dp;
702238106Sdes	struct module_qstate* subq;
703238106Sdes
704238106Sdes	if(!qname) return 0;
705238106Sdes	stub = hints_lookup_stub(qstate->env->hints, qname, qclass, iq->dp);
706238106Sdes	/* The stub (if there is one) does not need priming. */
707238106Sdes	if(!stub)
708238106Sdes		return 0;
709238106Sdes	stub_dp = stub->dp;
710238106Sdes
711238106Sdes	/* is it a noprime stub (always use) */
712238106Sdes	if(stub->noprime) {
713238106Sdes		int r = 0;
714238106Sdes		if(iq->dp == NULL) r = 2;
715238106Sdes		/* copy the dp out of the fixed hints structure, so that
716238106Sdes		 * it can be changed when servicing this query */
717238106Sdes		iq->dp = delegpt_copy(stub_dp, qstate->region);
718238106Sdes		if(!iq->dp) {
719238106Sdes			log_err("out of memory priming stub");
720238106Sdes			(void)error_response(qstate, id, LDNS_RCODE_SERVFAIL);
721238106Sdes			return 1; /* return 1 to make module stop, with error */
722238106Sdes		}
723238106Sdes		log_nametypeclass(VERB_DETAIL, "use stub", stub_dp->name,
724238106Sdes			LDNS_RR_TYPE_NS, qclass);
725238106Sdes		return r;
726238106Sdes	}
727238106Sdes
728238106Sdes	/* Otherwise, we need to (re)prime the stub. */
729238106Sdes	log_nametypeclass(VERB_DETAIL, "priming stub", stub_dp->name,
730238106Sdes		LDNS_RR_TYPE_NS, qclass);
731238106Sdes
732238106Sdes	/* Stub priming events start at the QUERYTARGETS state to avoid the
733238106Sdes	 * redundant INIT state processing. */
734238106Sdes	if(!generate_sub_request(stub_dp->name, stub_dp->namelen,
735238106Sdes		LDNS_RR_TYPE_NS, qclass, qstate, id, iq,
736238106Sdes		QUERYTARGETS_STATE, PRIME_RESP_STATE, &subq, 0)) {
737238106Sdes		verbose(VERB_ALGO, "could not prime stub");
738238106Sdes		(void)error_response(qstate, id, LDNS_RCODE_SERVFAIL);
739238106Sdes		return 1; /* return 1 to make module stop, with error */
740238106Sdes	}
741238106Sdes	if(subq) {
742238106Sdes		struct iter_qstate* subiq =
743238106Sdes			(struct iter_qstate*)subq->minfo[id];
744238106Sdes
745238106Sdes		/* Set the initial delegation point to the hint. */
746238106Sdes		/* make copy to avoid use of stub dp by different qs/threads */
747238106Sdes		subiq->dp = delegpt_copy(stub_dp, subq->region);
748238106Sdes		if(!subiq->dp) {
749238106Sdes			log_err("out of memory priming stub, copydp");
750238106Sdes			fptr_ok(fptr_whitelist_modenv_kill_sub(
751238106Sdes				qstate->env->kill_sub));
752238106Sdes			(*qstate->env->kill_sub)(subq);
753238106Sdes			(void)error_response(qstate, id, LDNS_RCODE_SERVFAIL);
754238106Sdes			return 1; /* return 1 to make module stop, with error */
755238106Sdes		}
756238106Sdes		/* there should not be any target queries -- although there
757238106Sdes		 * wouldn't be anyway, since stub hints never have
758238106Sdes		 * missing targets. */
759238106Sdes		subiq->num_target_queries = 0;
760238106Sdes		subiq->wait_priming_stub = 1;
761238106Sdes		subiq->dnssec_expected = iter_indicates_dnssec(
762238106Sdes			qstate->env, subiq->dp, NULL, subq->qinfo.qclass);
763238106Sdes	}
764238106Sdes
765238106Sdes	/* this module stops, our submodule starts, and does the query. */
766238106Sdes	qstate->ext_state[id] = module_wait_subquery;
767238106Sdes	return 1;
768238106Sdes}
769238106Sdes
770238106Sdes/**
771238106Sdes * Generate A and AAAA checks for glue that is in-zone for the referral
772238106Sdes * we just got to obtain authoritative information on the adresses.
773238106Sdes *
774238106Sdes * @param qstate: the qtstate that triggered the need to prime.
775238106Sdes * @param iq: iterator query state.
776238106Sdes * @param id: module id.
777238106Sdes */
778238106Sdesstatic void
779238106Sdesgenerate_a_aaaa_check(struct module_qstate* qstate, struct iter_qstate* iq,
780238106Sdes	int id)
781238106Sdes{
782238106Sdes	struct iter_env* ie = (struct iter_env*)qstate->env->modinfo[id];
783238106Sdes	struct module_qstate* subq;
784238106Sdes	size_t i;
785238106Sdes	struct reply_info* rep = iq->response->rep;
786238106Sdes	struct ub_packed_rrset_key* s;
787238106Sdes	log_assert(iq->dp);
788238106Sdes
789238106Sdes	if(iq->depth == ie->max_dependency_depth)
790238106Sdes		return;
791238106Sdes	/* walk through additional, and check if in-zone,
792238106Sdes	 * only relevant A, AAAA are left after scrub anyway */
793238106Sdes	for(i=rep->an_numrrsets+rep->ns_numrrsets; i<rep->rrset_count; i++) {
794238106Sdes		s = rep->rrsets[i];
795238106Sdes		/* check *ALL* addresses that are transmitted in additional*/
796238106Sdes		/* is it an address ? */
797238106Sdes		if( !(ntohs(s->rk.type)==LDNS_RR_TYPE_A ||
798238106Sdes			ntohs(s->rk.type)==LDNS_RR_TYPE_AAAA)) {
799238106Sdes			continue;
800238106Sdes		}
801238106Sdes		/* is this query the same as the A/AAAA check for it */
802238106Sdes		if(qstate->qinfo.qtype == ntohs(s->rk.type) &&
803238106Sdes			qstate->qinfo.qclass == ntohs(s->rk.rrset_class) &&
804238106Sdes			query_dname_compare(qstate->qinfo.qname,
805238106Sdes				s->rk.dname)==0 &&
806238106Sdes			(qstate->query_flags&BIT_RD) &&
807238106Sdes			!(qstate->query_flags&BIT_CD))
808238106Sdes			continue;
809238106Sdes
810238106Sdes		/* generate subrequest for it */
811238106Sdes		log_nametypeclass(VERB_ALGO, "schedule addr fetch",
812238106Sdes			s->rk.dname, ntohs(s->rk.type),
813238106Sdes			ntohs(s->rk.rrset_class));
814238106Sdes		if(!generate_sub_request(s->rk.dname, s->rk.dname_len,
815238106Sdes			ntohs(s->rk.type), ntohs(s->rk.rrset_class),
816238106Sdes			qstate, id, iq,
817238106Sdes			INIT_REQUEST_STATE, FINISHED_STATE, &subq, 1)) {
818238106Sdes			verbose(VERB_ALGO, "could not generate addr check");
819238106Sdes			return;
820238106Sdes		}
821238106Sdes		/* ignore subq - not need for more init */
822238106Sdes	}
823238106Sdes}
824238106Sdes
825238106Sdes/**
826238106Sdes * Generate a NS check request to obtain authoritative information
827238106Sdes * on an NS rrset.
828238106Sdes *
829238106Sdes * @param qstate: the qtstate that triggered the need to prime.
830238106Sdes * @param iq: iterator query state.
831238106Sdes * @param id: module id.
832238106Sdes */
833238106Sdesstatic void
834238106Sdesgenerate_ns_check(struct module_qstate* qstate, struct iter_qstate* iq, int id)
835238106Sdes{
836238106Sdes	struct iter_env* ie = (struct iter_env*)qstate->env->modinfo[id];
837238106Sdes	struct module_qstate* subq;
838238106Sdes	log_assert(iq->dp);
839238106Sdes
840238106Sdes	if(iq->depth == ie->max_dependency_depth)
841238106Sdes		return;
842238106Sdes	/* is this query the same as the nscheck? */
843238106Sdes	if(qstate->qinfo.qtype == LDNS_RR_TYPE_NS &&
844238106Sdes		query_dname_compare(iq->dp->name, qstate->qinfo.qname)==0 &&
845238106Sdes		(qstate->query_flags&BIT_RD) && !(qstate->query_flags&BIT_CD)){
846238106Sdes		/* spawn off A, AAAA queries for in-zone glue to check */
847238106Sdes		generate_a_aaaa_check(qstate, iq, id);
848238106Sdes		return;
849238106Sdes	}
850238106Sdes
851238106Sdes	log_nametypeclass(VERB_ALGO, "schedule ns fetch",
852238106Sdes		iq->dp->name, LDNS_RR_TYPE_NS, iq->qchase.qclass);
853238106Sdes	if(!generate_sub_request(iq->dp->name, iq->dp->namelen,
854238106Sdes		LDNS_RR_TYPE_NS, iq->qchase.qclass, qstate, id, iq,
855238106Sdes		INIT_REQUEST_STATE, FINISHED_STATE, &subq, 1)) {
856238106Sdes		verbose(VERB_ALGO, "could not generate ns check");
857238106Sdes		return;
858238106Sdes	}
859238106Sdes	if(subq) {
860238106Sdes		struct iter_qstate* subiq =
861238106Sdes			(struct iter_qstate*)subq->minfo[id];
862238106Sdes
863238106Sdes		/* make copy to avoid use of stub dp by different qs/threads */
864238106Sdes		/* refetch glue to start higher up the tree */
865238106Sdes		subiq->refetch_glue = 1;
866238106Sdes		subiq->dp = delegpt_copy(iq->dp, subq->region);
867238106Sdes		if(!subiq->dp) {
868238106Sdes			log_err("out of memory generating ns check, copydp");
869238106Sdes			fptr_ok(fptr_whitelist_modenv_kill_sub(
870238106Sdes				qstate->env->kill_sub));
871238106Sdes			(*qstate->env->kill_sub)(subq);
872238106Sdes			return;
873238106Sdes		}
874238106Sdes	}
875238106Sdes}
876238106Sdes
877238106Sdes/**
878238106Sdes * Generate a DNSKEY prefetch query to get the DNSKEY for the DS record we
879238106Sdes * just got in a referral (where we have dnssec_expected, thus have trust
880238106Sdes * anchors above it).  Note that right after calling this routine the
881238106Sdes * iterator detached subqueries (because of following the referral), and thus
882238106Sdes * the DNSKEY query becomes detached, its return stored in the cache for
883238106Sdes * later lookup by the validator.  This cache lookup by the validator avoids
884238106Sdes * the roundtrip incurred by the DNSKEY query.  The DNSKEY query is now
885238106Sdes * performed at about the same time the original query is sent to the domain,
886238106Sdes * thus the two answers are likely to be returned at about the same time,
887238106Sdes * saving a roundtrip from the validated lookup.
888238106Sdes *
889238106Sdes * @param qstate: the qtstate that triggered the need to prime.
890238106Sdes * @param iq: iterator query state.
891238106Sdes * @param id: module id.
892238106Sdes */
893238106Sdesstatic void
894238106Sdesgenerate_dnskey_prefetch(struct module_qstate* qstate,
895238106Sdes	struct iter_qstate* iq, int id)
896238106Sdes{
897238106Sdes	struct module_qstate* subq;
898238106Sdes	log_assert(iq->dp);
899238106Sdes
900238106Sdes	/* is this query the same as the prefetch? */
901238106Sdes	if(qstate->qinfo.qtype == LDNS_RR_TYPE_DNSKEY &&
902238106Sdes		query_dname_compare(iq->dp->name, qstate->qinfo.qname)==0 &&
903238106Sdes		(qstate->query_flags&BIT_RD) && !(qstate->query_flags&BIT_CD)){
904238106Sdes		return;
905238106Sdes	}
906238106Sdes
907238106Sdes	/* if the DNSKEY is in the cache this lookup will stop quickly */
908238106Sdes	log_nametypeclass(VERB_ALGO, "schedule dnskey prefetch",
909238106Sdes		iq->dp->name, LDNS_RR_TYPE_DNSKEY, iq->qchase.qclass);
910238106Sdes	if(!generate_sub_request(iq->dp->name, iq->dp->namelen,
911238106Sdes		LDNS_RR_TYPE_DNSKEY, iq->qchase.qclass, qstate, id, iq,
912238106Sdes		INIT_REQUEST_STATE, FINISHED_STATE, &subq, 0)) {
913238106Sdes		/* we'll be slower, but it'll work */
914238106Sdes		verbose(VERB_ALGO, "could not generate dnskey prefetch");
915238106Sdes		return;
916238106Sdes	}
917238106Sdes	if(subq) {
918238106Sdes		struct iter_qstate* subiq =
919238106Sdes			(struct iter_qstate*)subq->minfo[id];
920238106Sdes		/* this qstate has the right delegation for the dnskey lookup*/
921238106Sdes		/* make copy to avoid use of stub dp by different qs/threads */
922238106Sdes		subiq->dp = delegpt_copy(iq->dp, subq->region);
923238106Sdes		/* if !subiq->dp, it'll start from the cache, no problem */
924238106Sdes	}
925238106Sdes}
926238106Sdes
927238106Sdes/**
928238106Sdes * See if the query needs forwarding.
929238106Sdes *
930238106Sdes * @param qstate: query state.
931238106Sdes * @param iq: iterator query state.
932238106Sdes * @return true if the request is forwarded, false if not.
933238106Sdes * 	If returns true but, iq->dp is NULL then a malloc failure occurred.
934238106Sdes */
935238106Sdesstatic int
936238106Sdesforward_request(struct module_qstate* qstate, struct iter_qstate* iq)
937238106Sdes{
938238106Sdes	struct delegpt* dp;
939238106Sdes	uint8_t* delname = iq->qchase.qname;
940238106Sdes	size_t delnamelen = iq->qchase.qname_len;
941238106Sdes	if(iq->refetch_glue) {
942238106Sdes		delname = iq->dp->name;
943238106Sdes		delnamelen = iq->dp->namelen;
944238106Sdes	}
945238106Sdes	/* strip one label off of DS query to lookup higher for it */
946238106Sdes	if( (iq->qchase.qtype == LDNS_RR_TYPE_DS || iq->refetch_glue)
947238106Sdes		&& !dname_is_root(iq->qchase.qname))
948238106Sdes		dname_remove_label(&delname, &delnamelen);
949238106Sdes	dp = forwards_lookup(qstate->env->fwds, delname, iq->qchase.qclass);
950238106Sdes	if(!dp)
951238106Sdes		return 0;
952238106Sdes	/* send recursion desired to forward addr */
953238106Sdes	iq->chase_flags |= BIT_RD;
954238106Sdes	iq->dp = delegpt_copy(dp, qstate->region);
955238106Sdes	/* iq->dp checked by caller */
956238106Sdes	verbose(VERB_ALGO, "forwarding request");
957238106Sdes	return 1;
958238106Sdes}
959238106Sdes
960238106Sdes/**
961238106Sdes * Process the initial part of the request handling. This state roughly
962238106Sdes * corresponds to resolver algorithms steps 1 (find answer in cache) and 2
963238106Sdes * (find the best servers to ask).
964238106Sdes *
965238106Sdes * Note that all requests start here, and query restarts revisit this state.
966238106Sdes *
967238106Sdes * This state either generates: 1) a response, from cache or error, 2) a
968238106Sdes * priming event, or 3) forwards the request to the next state (init2,
969238106Sdes * generally).
970238106Sdes *
971238106Sdes * @param qstate: query state.
972238106Sdes * @param iq: iterator query state.
973238106Sdes * @param ie: iterator shared global environment.
974238106Sdes * @param id: module id.
975238106Sdes * @return true if the event needs more request processing immediately,
976238106Sdes *         false if not.
977238106Sdes */
978238106Sdesstatic int
979238106SdesprocessInitRequest(struct module_qstate* qstate, struct iter_qstate* iq,
980238106Sdes	struct iter_env* ie, int id)
981238106Sdes{
982238106Sdes	uint8_t* delname;
983238106Sdes	size_t delnamelen;
984238106Sdes	struct dns_msg* msg;
985238106Sdes
986238106Sdes	log_query_info(VERB_DETAIL, "resolving", &qstate->qinfo);
987238106Sdes	/* check effort */
988238106Sdes
989238106Sdes	/* We enforce a maximum number of query restarts. This is primarily a
990238106Sdes	 * cheap way to prevent CNAME loops. */
991238106Sdes	if(iq->query_restart_count > MAX_RESTART_COUNT) {
992238106Sdes		verbose(VERB_QUERY, "request has exceeded the maximum number"
993238106Sdes			" of query restarts with %d", iq->query_restart_count);
994238106Sdes		return error_response(qstate, id, LDNS_RCODE_SERVFAIL);
995238106Sdes	}
996238106Sdes
997238106Sdes	/* We enforce a maximum recursion/dependency depth -- in general,
998238106Sdes	 * this is unnecessary for dependency loops (although it will
999238106Sdes	 * catch those), but it provides a sensible limit to the amount
1000238106Sdes	 * of work required to answer a given query. */
1001238106Sdes	verbose(VERB_ALGO, "request has dependency depth of %d", iq->depth);
1002238106Sdes	if(iq->depth > ie->max_dependency_depth) {
1003238106Sdes		verbose(VERB_QUERY, "request has exceeded the maximum "
1004238106Sdes			"dependency depth with depth of %d", iq->depth);
1005238106Sdes		return error_response(qstate, id, LDNS_RCODE_SERVFAIL);
1006238106Sdes	}
1007238106Sdes
1008238106Sdes	/* If the request is qclass=ANY, setup to generate each class */
1009238106Sdes	if(qstate->qinfo.qclass == LDNS_RR_CLASS_ANY) {
1010238106Sdes		iq->qchase.qclass = 0;
1011238106Sdes		return next_state(iq, COLLECT_CLASS_STATE);
1012238106Sdes	}
1013238106Sdes
1014238106Sdes	/* Resolver Algorithm Step 1 -- Look for the answer in local data. */
1015238106Sdes
1016238106Sdes	/* This either results in a query restart (CNAME cache response), a
1017238106Sdes	 * terminating response (ANSWER), or a cache miss (null). */
1018238106Sdes
1019238106Sdes	if(qstate->blacklist) {
1020238106Sdes		/* if cache, or anything else, was blacklisted then
1021238106Sdes		 * getting older results from cache is a bad idea, no cache */
1022238106Sdes		verbose(VERB_ALGO, "cache blacklisted, going to the network");
1023238106Sdes		msg = NULL;
1024238106Sdes	} else {
1025238106Sdes		msg = dns_cache_lookup(qstate->env, iq->qchase.qname,
1026238106Sdes			iq->qchase.qname_len, iq->qchase.qtype,
1027285206Sdes			iq->qchase.qclass, qstate->query_flags,
1028285206Sdes			qstate->region, qstate->env->scratch);
1029238106Sdes		if(!msg && qstate->env->neg_cache) {
1030238106Sdes			/* lookup in negative cache; may result in
1031238106Sdes			 * NOERROR/NODATA or NXDOMAIN answers that need validation */
1032238106Sdes			msg = val_neg_getmsg(qstate->env->neg_cache, &iq->qchase,
1033238106Sdes				qstate->region, qstate->env->rrset_cache,
1034238106Sdes				qstate->env->scratch_buffer,
1035238106Sdes				*qstate->env->now, 1/*add SOA*/, NULL);
1036238106Sdes		}
1037238106Sdes		/* item taken from cache does not match our query name, thus
1038238106Sdes		 * security needs to be re-examined later */
1039238106Sdes		if(msg && query_dname_compare(qstate->qinfo.qname,
1040238106Sdes			iq->qchase.qname) != 0)
1041238106Sdes			msg->rep->security = sec_status_unchecked;
1042238106Sdes	}
1043238106Sdes	if(msg) {
1044238106Sdes		/* handle positive cache response */
1045238106Sdes		enum response_type type = response_type_from_cache(msg,
1046238106Sdes			&iq->qchase);
1047238106Sdes		if(verbosity >= VERB_ALGO) {
1048238106Sdes			log_dns_msg("msg from cache lookup", &msg->qinfo,
1049238106Sdes				msg->rep);
1050238106Sdes			verbose(VERB_ALGO, "msg ttl is %d, prefetch ttl %d",
1051238106Sdes				(int)msg->rep->ttl,
1052238106Sdes				(int)msg->rep->prefetch_ttl);
1053238106Sdes		}
1054238106Sdes
1055238106Sdes		if(type == RESPONSE_TYPE_CNAME) {
1056238106Sdes			uint8_t* sname = 0;
1057238106Sdes			size_t slen = 0;
1058238106Sdes			verbose(VERB_ALGO, "returning CNAME response from "
1059238106Sdes				"cache");
1060238106Sdes			if(!handle_cname_response(qstate, iq, msg,
1061238106Sdes				&sname, &slen))
1062238106Sdes				return error_response(qstate, id,
1063238106Sdes					LDNS_RCODE_SERVFAIL);
1064238106Sdes			iq->qchase.qname = sname;
1065238106Sdes			iq->qchase.qname_len = slen;
1066238106Sdes			/* This *is* a query restart, even if it is a cheap
1067238106Sdes			 * one. */
1068238106Sdes			iq->dp = NULL;
1069238106Sdes			iq->refetch_glue = 0;
1070238106Sdes			iq->query_restart_count++;
1071238106Sdes			iq->sent_count = 0;
1072238106Sdes			sock_list_insert(&qstate->reply_origin, NULL, 0, qstate->region);
1073294190Sdes			if(qstate->env->cfg->qname_minimisation)
1074294190Sdes				iq->minimisation_state = INIT_MINIMISE_STATE;
1075238106Sdes			return next_state(iq, INIT_REQUEST_STATE);
1076238106Sdes		}
1077238106Sdes
1078238106Sdes		/* if from cache, NULL, else insert 'cache IP' len=0 */
1079238106Sdes		if(qstate->reply_origin)
1080238106Sdes			sock_list_insert(&qstate->reply_origin, NULL, 0, qstate->region);
1081238106Sdes		/* it is an answer, response, to final state */
1082238106Sdes		verbose(VERB_ALGO, "returning answer from cache.");
1083238106Sdes		iq->response = msg;
1084238106Sdes		return final_state(iq);
1085238106Sdes	}
1086238106Sdes
1087238106Sdes	/* attempt to forward the request */
1088238106Sdes	if(forward_request(qstate, iq))
1089238106Sdes	{
1090238106Sdes		if(!iq->dp) {
1091238106Sdes			log_err("alloc failure for forward dp");
1092238106Sdes			return error_response(qstate, id, LDNS_RCODE_SERVFAIL);
1093238106Sdes		}
1094238106Sdes		iq->refetch_glue = 0;
1095294190Sdes		iq->minimisation_state = DONOT_MINIMISE_STATE;
1096238106Sdes		/* the request has been forwarded.
1097238106Sdes		 * forwarded requests need to be immediately sent to the
1098238106Sdes		 * next state, QUERYTARGETS. */
1099238106Sdes		return next_state(iq, QUERYTARGETS_STATE);
1100238106Sdes	}
1101238106Sdes
1102238106Sdes	/* Resolver Algorithm Step 2 -- find the "best" servers. */
1103238106Sdes
1104238106Sdes	/* first, adjust for DS queries. To avoid the grandparent problem,
1105238106Sdes	 * we just look for the closest set of server to the parent of qname.
1106238106Sdes	 * When re-fetching glue we also need to ask the parent.
1107238106Sdes	 */
1108238106Sdes	if(iq->refetch_glue) {
1109238106Sdes		if(!iq->dp) {
1110238106Sdes			log_err("internal or malloc fail: no dp for refetch");
1111238106Sdes			return error_response(qstate, id, LDNS_RCODE_SERVFAIL);
1112238106Sdes		}
1113238106Sdes		delname = iq->dp->name;
1114238106Sdes		delnamelen = iq->dp->namelen;
1115238106Sdes	} else {
1116238106Sdes		delname = iq->qchase.qname;
1117238106Sdes		delnamelen = iq->qchase.qname_len;
1118238106Sdes	}
1119238106Sdes	if(iq->qchase.qtype == LDNS_RR_TYPE_DS || iq->refetch_glue ||
1120238106Sdes	   (iq->qchase.qtype == LDNS_RR_TYPE_NS && qstate->prefetch_leeway)) {
1121238106Sdes		/* remove first label from delname, root goes to hints,
1122238106Sdes		 * but only to fetch glue, not for qtype=DS. */
1123238106Sdes		/* also when prefetching an NS record, fetch it again from
1124238106Sdes		 * its parent, just as if it expired, so that you do not
1125238106Sdes		 * get stuck on an older nameserver that gives old NSrecords */
1126238106Sdes		if(dname_is_root(delname) && (iq->refetch_glue ||
1127238106Sdes			(iq->qchase.qtype == LDNS_RR_TYPE_NS &&
1128238106Sdes			qstate->prefetch_leeway)))
1129238106Sdes			delname = NULL; /* go to root priming */
1130238106Sdes		else 	dname_remove_label(&delname, &delnamelen);
1131238106Sdes	}
1132238106Sdes	/* delname is the name to lookup a delegation for. If NULL rootprime */
1133238106Sdes	while(1) {
1134238106Sdes
1135238106Sdes		/* Lookup the delegation in the cache. If null, then the
1136238106Sdes		 * cache needs to be primed for the qclass. */
1137238106Sdes		if(delname)
1138238106Sdes		     iq->dp = dns_cache_find_delegation(qstate->env, delname,
1139238106Sdes			delnamelen, iq->qchase.qtype, iq->qchase.qclass,
1140238106Sdes			qstate->region, &iq->deleg_msg,
1141238106Sdes			*qstate->env->now+qstate->prefetch_leeway);
1142238106Sdes		else iq->dp = NULL;
1143238106Sdes
1144238106Sdes		/* If the cache has returned nothing, then we have a
1145238106Sdes		 * root priming situation. */
1146238106Sdes		if(iq->dp == NULL) {
1147238106Sdes			/* if there is a stub, then no root prime needed */
1148238106Sdes			int r = prime_stub(qstate, iq, id, delname,
1149238106Sdes				iq->qchase.qclass);
1150238106Sdes			if(r == 2)
1151238106Sdes				break; /* got noprime-stub-zone, continue */
1152238106Sdes			else if(r)
1153238106Sdes				return 0; /* stub prime request made */
1154238106Sdes			if(forwards_lookup_root(qstate->env->fwds,
1155238106Sdes				iq->qchase.qclass)) {
1156238106Sdes				/* forward zone root, no root prime needed */
1157238106Sdes				/* fill in some dp - safety belt */
1158238106Sdes				iq->dp = hints_lookup_root(qstate->env->hints,
1159238106Sdes					iq->qchase.qclass);
1160238106Sdes				if(!iq->dp) {
1161238106Sdes					log_err("internal error: no hints dp");
1162238106Sdes					return error_response(qstate, id,
1163238106Sdes						LDNS_RCODE_SERVFAIL);
1164238106Sdes				}
1165238106Sdes				iq->dp = delegpt_copy(iq->dp, qstate->region);
1166238106Sdes				if(!iq->dp) {
1167238106Sdes					log_err("out of memory in safety belt");
1168238106Sdes					return error_response(qstate, id,
1169238106Sdes						LDNS_RCODE_SERVFAIL);
1170238106Sdes				}
1171238106Sdes				return next_state(iq, INIT_REQUEST_2_STATE);
1172238106Sdes			}
1173238106Sdes			/* Note that the result of this will set a new
1174238106Sdes			 * DelegationPoint based on the result of priming. */
1175238106Sdes			if(!prime_root(qstate, iq, id, iq->qchase.qclass))
1176238106Sdes				return error_response(qstate, id,
1177238106Sdes					LDNS_RCODE_REFUSED);
1178238106Sdes
1179238106Sdes			/* priming creates and sends a subordinate query, with
1180238106Sdes			 * this query as the parent. So further processing for
1181238106Sdes			 * this event will stop until reactivated by the
1182238106Sdes			 * results of priming. */
1183238106Sdes			return 0;
1184238106Sdes		}
1185291767Sdes		if(!iq->ratelimit_ok && qstate->prefetch_leeway)
1186291767Sdes			iq->ratelimit_ok = 1; /* allow prefetches, this keeps
1187291767Sdes			otherwise valid data in the cache */
1188291767Sdes		if(!iq->ratelimit_ok && infra_ratelimit_exceeded(
1189291767Sdes			qstate->env->infra_cache, iq->dp->name,
1190291767Sdes			iq->dp->namelen, *qstate->env->now)) {
1191291767Sdes			/* and increment the rate, so that the rate for time
1192291767Sdes			 * now will also exceed the rate, keeping cache fresh */
1193291767Sdes			(void)infra_ratelimit_inc(qstate->env->infra_cache,
1194291767Sdes				iq->dp->name, iq->dp->namelen,
1195291767Sdes				*qstate->env->now);
1196291767Sdes			/* see if we are passed through with slip factor */
1197291767Sdes			if(qstate->env->cfg->ratelimit_factor != 0 &&
1198291767Sdes				ub_random_max(qstate->env->rnd,
1199291767Sdes				    qstate->env->cfg->ratelimit_factor) == 1) {
1200291767Sdes				iq->ratelimit_ok = 1;
1201291767Sdes				log_nametypeclass(VERB_ALGO, "ratelimit allowed through for "
1202291767Sdes					"delegation point", iq->dp->name,
1203291767Sdes					LDNS_RR_TYPE_NS, LDNS_RR_CLASS_IN);
1204291767Sdes			} else {
1205291767Sdes				log_nametypeclass(VERB_ALGO, "ratelimit exceeded with "
1206291767Sdes					"delegation point", iq->dp->name,
1207291767Sdes					LDNS_RR_TYPE_NS, LDNS_RR_CLASS_IN);
1208291767Sdes				return error_response(qstate, id, LDNS_RCODE_SERVFAIL);
1209291767Sdes			}
1210291767Sdes		}
1211238106Sdes
1212238106Sdes		/* see if this dp not useless.
1213238106Sdes		 * It is useless if:
1214238106Sdes		 *	o all NS items are required glue.
1215238106Sdes		 *	  or the query is for NS item that is required glue.
1216238106Sdes		 *	o no addresses are provided.
1217238106Sdes		 *	o RD qflag is on.
1218238106Sdes		 * Instead, go up one level, and try to get even further
1219238106Sdes		 * If the root was useless, use safety belt information.
1220238106Sdes		 * Only check cache returns, because replies for servers
1221238106Sdes		 * could be useless but lead to loops (bumping into the
1222238106Sdes		 * same server reply) if useless-checked.
1223238106Sdes		 */
1224238106Sdes		if(iter_dp_is_useless(&qstate->qinfo, qstate->query_flags,
1225238106Sdes			iq->dp)) {
1226238106Sdes			if(dname_is_root(iq->dp->name)) {
1227238106Sdes				/* use safety belt */
1228238106Sdes				verbose(VERB_QUERY, "Cache has root NS but "
1229238106Sdes				"no addresses. Fallback to the safety belt.");
1230238106Sdes				iq->dp = hints_lookup_root(qstate->env->hints,
1231238106Sdes					iq->qchase.qclass);
1232238106Sdes				/* note deleg_msg is from previous lookup,
1233238106Sdes				 * but RD is on, so it is not used */
1234238106Sdes				if(!iq->dp) {
1235238106Sdes					log_err("internal error: no hints dp");
1236238106Sdes					return error_response(qstate, id,
1237238106Sdes						LDNS_RCODE_REFUSED);
1238238106Sdes				}
1239238106Sdes				iq->dp = delegpt_copy(iq->dp, qstate->region);
1240238106Sdes				if(!iq->dp) {
1241238106Sdes					log_err("out of memory in safety belt");
1242238106Sdes					return error_response(qstate, id,
1243238106Sdes						LDNS_RCODE_SERVFAIL);
1244238106Sdes				}
1245238106Sdes				break;
1246238106Sdes			} else {
1247238106Sdes				verbose(VERB_ALGO,
1248238106Sdes					"cache delegation was useless:");
1249238106Sdes				delegpt_log(VERB_ALGO, iq->dp);
1250238106Sdes				/* go up */
1251238106Sdes				delname = iq->dp->name;
1252238106Sdes				delnamelen = iq->dp->namelen;
1253238106Sdes				dname_remove_label(&delname, &delnamelen);
1254238106Sdes			}
1255238106Sdes		} else break;
1256238106Sdes	}
1257238106Sdes
1258238106Sdes	verbose(VERB_ALGO, "cache delegation returns delegpt");
1259238106Sdes	delegpt_log(VERB_ALGO, iq->dp);
1260238106Sdes
1261238106Sdes	/* Otherwise, set the current delegation point and move on to the
1262238106Sdes	 * next state. */
1263238106Sdes	return next_state(iq, INIT_REQUEST_2_STATE);
1264238106Sdes}
1265238106Sdes
1266238106Sdes/**
1267238106Sdes * Process the second part of the initial request handling. This state
1268238106Sdes * basically exists so that queries that generate root priming events have
1269238106Sdes * the same init processing as ones that do not. Request events that reach
1270238106Sdes * this state must have a valid currentDelegationPoint set.
1271238106Sdes *
1272238106Sdes * This part is primarly handling stub zone priming. Events that reach this
1273238106Sdes * state must have a current delegation point.
1274238106Sdes *
1275238106Sdes * @param qstate: query state.
1276238106Sdes * @param iq: iterator query state.
1277238106Sdes * @param id: module id.
1278238106Sdes * @return true if the event needs more request processing immediately,
1279238106Sdes *         false if not.
1280238106Sdes */
1281238106Sdesstatic int
1282238106SdesprocessInitRequest2(struct module_qstate* qstate, struct iter_qstate* iq,
1283238106Sdes	int id)
1284238106Sdes{
1285238106Sdes	uint8_t* delname;
1286238106Sdes	size_t delnamelen;
1287238106Sdes	log_query_info(VERB_QUERY, "resolving (init part 2): ",
1288238106Sdes		&qstate->qinfo);
1289238106Sdes
1290238106Sdes	if(iq->refetch_glue) {
1291238106Sdes		if(!iq->dp) {
1292238106Sdes			log_err("internal or malloc fail: no dp for refetch");
1293238106Sdes			return error_response(qstate, id, LDNS_RCODE_SERVFAIL);
1294238106Sdes		}
1295238106Sdes		delname = iq->dp->name;
1296238106Sdes		delnamelen = iq->dp->namelen;
1297238106Sdes	} else {
1298238106Sdes		delname = iq->qchase.qname;
1299238106Sdes		delnamelen = iq->qchase.qname_len;
1300238106Sdes	}
1301238106Sdes	if(iq->qchase.qtype == LDNS_RR_TYPE_DS || iq->refetch_glue) {
1302238106Sdes		if(!dname_is_root(delname))
1303238106Sdes			dname_remove_label(&delname, &delnamelen);
1304238106Sdes		iq->refetch_glue = 0; /* if CNAME causes restart, no refetch */
1305238106Sdes	}
1306238106Sdes	/* Check to see if we need to prime a stub zone. */
1307238106Sdes	if(prime_stub(qstate, iq, id, delname, iq->qchase.qclass)) {
1308238106Sdes		/* A priming sub request was made */
1309238106Sdes		return 0;
1310238106Sdes	}
1311238106Sdes
1312238106Sdes	/* most events just get forwarded to the next state. */
1313238106Sdes	return next_state(iq, INIT_REQUEST_3_STATE);
1314238106Sdes}
1315238106Sdes
1316238106Sdes/**
1317238106Sdes * Process the third part of the initial request handling. This state exists
1318238106Sdes * as a separate state so that queries that generate stub priming events
1319238106Sdes * will get the tail end of the init process but not repeat the stub priming
1320238106Sdes * check.
1321238106Sdes *
1322238106Sdes * @param qstate: query state.
1323238106Sdes * @param iq: iterator query state.
1324238106Sdes * @param id: module id.
1325238106Sdes * @return true, advancing the event to the QUERYTARGETS_STATE.
1326238106Sdes */
1327238106Sdesstatic int
1328238106SdesprocessInitRequest3(struct module_qstate* qstate, struct iter_qstate* iq,
1329238106Sdes	int id)
1330238106Sdes{
1331238106Sdes	log_query_info(VERB_QUERY, "resolving (init part 3): ",
1332238106Sdes		&qstate->qinfo);
1333238106Sdes	/* if the cache reply dp equals a validation anchor or msg has DS,
1334238106Sdes	 * then DNSSEC RRSIGs are expected in the reply */
1335238106Sdes	iq->dnssec_expected = iter_indicates_dnssec(qstate->env, iq->dp,
1336238106Sdes		iq->deleg_msg, iq->qchase.qclass);
1337238106Sdes
1338238106Sdes	/* If the RD flag wasn't set, then we just finish with the
1339238106Sdes	 * cached referral as the response. */
1340238106Sdes	if(!(qstate->query_flags & BIT_RD)) {
1341238106Sdes		iq->response = iq->deleg_msg;
1342269257Sdes		if(verbosity >= VERB_ALGO && iq->response)
1343238106Sdes			log_dns_msg("no RD requested, using delegation msg",
1344238106Sdes				&iq->response->qinfo, iq->response->rep);
1345238106Sdes		if(qstate->reply_origin)
1346238106Sdes			sock_list_insert(&qstate->reply_origin, NULL, 0, qstate->region);
1347238106Sdes		return final_state(iq);
1348238106Sdes	}
1349238106Sdes	/* After this point, unset the RD flag -- this query is going to
1350238106Sdes	 * be sent to an auth. server. */
1351238106Sdes	iq->chase_flags &= ~BIT_RD;
1352238106Sdes
1353238106Sdes	/* if dnssec expected, fetch key for the trust-anchor or cached-DS */
1354238106Sdes	if(iq->dnssec_expected && qstate->env->cfg->prefetch_key &&
1355238106Sdes		!(qstate->query_flags&BIT_CD)) {
1356238106Sdes		generate_dnskey_prefetch(qstate, iq, id);
1357238106Sdes		fptr_ok(fptr_whitelist_modenv_detach_subs(
1358238106Sdes			qstate->env->detach_subs));
1359238106Sdes		(*qstate->env->detach_subs)(qstate);
1360238106Sdes	}
1361238106Sdes
1362238106Sdes	/* Jump to the next state. */
1363238106Sdes	return next_state(iq, QUERYTARGETS_STATE);
1364238106Sdes}
1365238106Sdes
1366238106Sdes/**
1367238106Sdes * Given a basic query, generate a parent-side "target" query.
1368238106Sdes * These are subordinate queries for missing delegation point target addresses,
1369238106Sdes * for which only the parent of the delegation provides correct IP addresses.
1370238106Sdes *
1371238106Sdes * @param qstate: query state.
1372238106Sdes * @param iq: iterator query state.
1373238106Sdes * @param id: module id.
1374238106Sdes * @param name: target qname.
1375238106Sdes * @param namelen: target qname length.
1376238106Sdes * @param qtype: target qtype (either A or AAAA).
1377238106Sdes * @param qclass: target qclass.
1378238106Sdes * @return true on success, false on failure.
1379238106Sdes */
1380238106Sdesstatic int
1381238106Sdesgenerate_parentside_target_query(struct module_qstate* qstate,
1382238106Sdes	struct iter_qstate* iq, int id, uint8_t* name, size_t namelen,
1383238106Sdes	uint16_t qtype, uint16_t qclass)
1384238106Sdes{
1385238106Sdes	struct module_qstate* subq;
1386238106Sdes	if(!generate_sub_request(name, namelen, qtype, qclass, qstate,
1387238106Sdes		id, iq, INIT_REQUEST_STATE, FINISHED_STATE, &subq, 0))
1388238106Sdes		return 0;
1389238106Sdes	if(subq) {
1390238106Sdes		struct iter_qstate* subiq =
1391238106Sdes			(struct iter_qstate*)subq->minfo[id];
1392238106Sdes		/* blacklist the cache - we want to fetch parent stuff */
1393238106Sdes		sock_list_insert(&subq->blacklist, NULL, 0, subq->region);
1394238106Sdes		subiq->query_for_pside_glue = 1;
1395238106Sdes		if(dname_subdomain_c(name, iq->dp->name)) {
1396238106Sdes			subiq->dp = delegpt_copy(iq->dp, subq->region);
1397238106Sdes			subiq->dnssec_expected = iter_indicates_dnssec(
1398238106Sdes				qstate->env, subiq->dp, NULL,
1399238106Sdes				subq->qinfo.qclass);
1400238106Sdes			subiq->refetch_glue = 1;
1401238106Sdes		} else {
1402238106Sdes			subiq->dp = dns_cache_find_delegation(qstate->env,
1403238106Sdes				name, namelen, qtype, qclass, subq->region,
1404238106Sdes				&subiq->deleg_msg,
1405238106Sdes				*qstate->env->now+subq->prefetch_leeway);
1406238106Sdes			/* if no dp, then it's from root, refetch unneeded */
1407238106Sdes			if(subiq->dp) {
1408238106Sdes				subiq->dnssec_expected = iter_indicates_dnssec(
1409238106Sdes					qstate->env, subiq->dp, NULL,
1410238106Sdes					subq->qinfo.qclass);
1411238106Sdes				subiq->refetch_glue = 1;
1412238106Sdes			}
1413238106Sdes		}
1414238106Sdes	}
1415238106Sdes	log_nametypeclass(VERB_QUERY, "new pside target", name, qtype, qclass);
1416238106Sdes	return 1;
1417238106Sdes}
1418238106Sdes
1419238106Sdes/**
1420238106Sdes * Given a basic query, generate a "target" query. These are subordinate
1421238106Sdes * queries for missing delegation point target addresses.
1422238106Sdes *
1423238106Sdes * @param qstate: query state.
1424238106Sdes * @param iq: iterator query state.
1425238106Sdes * @param id: module id.
1426238106Sdes * @param name: target qname.
1427238106Sdes * @param namelen: target qname length.
1428238106Sdes * @param qtype: target qtype (either A or AAAA).
1429238106Sdes * @param qclass: target qclass.
1430238106Sdes * @return true on success, false on failure.
1431238106Sdes */
1432238106Sdesstatic int
1433238106Sdesgenerate_target_query(struct module_qstate* qstate, struct iter_qstate* iq,
1434238106Sdes        int id, uint8_t* name, size_t namelen, uint16_t qtype, uint16_t qclass)
1435238106Sdes{
1436238106Sdes	struct module_qstate* subq;
1437238106Sdes	if(!generate_sub_request(name, namelen, qtype, qclass, qstate,
1438238106Sdes		id, iq, INIT_REQUEST_STATE, FINISHED_STATE, &subq, 0))
1439238106Sdes		return 0;
1440238106Sdes	log_nametypeclass(VERB_QUERY, "new target", name, qtype, qclass);
1441238106Sdes	return 1;
1442238106Sdes}
1443238106Sdes
1444238106Sdes/**
1445238106Sdes * Given an event at a certain state, generate zero or more target queries
1446238106Sdes * for it's current delegation point.
1447238106Sdes *
1448238106Sdes * @param qstate: query state.
1449238106Sdes * @param iq: iterator query state.
1450238106Sdes * @param ie: iterator shared global environment.
1451238106Sdes * @param id: module id.
1452238106Sdes * @param maxtargets: The maximum number of targets to query for.
1453238106Sdes *	if it is negative, there is no maximum number of targets.
1454238106Sdes * @param num: returns the number of queries generated and processed,
1455238106Sdes *	which may be zero if there were no missing targets.
1456238106Sdes * @return false on error.
1457238106Sdes */
1458238106Sdesstatic int
1459238106Sdesquery_for_targets(struct module_qstate* qstate, struct iter_qstate* iq,
1460238106Sdes        struct iter_env* ie, int id, int maxtargets, int* num)
1461238106Sdes{
1462238106Sdes	int query_count = 0;
1463238106Sdes	struct delegpt_ns* ns;
1464238106Sdes	int missing;
1465238106Sdes	int toget = 0;
1466238106Sdes
1467238106Sdes	if(iq->depth == ie->max_dependency_depth)
1468238106Sdes		return 0;
1469275853Sdelphij	if(iq->depth > 0 && iq->target_count &&
1470275853Sdelphij		iq->target_count[1] > MAX_TARGET_COUNT) {
1471285206Sdes		char s[LDNS_MAX_DOMAINLEN+1];
1472285206Sdes		dname_str(qstate->qinfo.qname, s);
1473285206Sdes		verbose(VERB_QUERY, "request %s has exceeded the maximum "
1474285206Sdes			"number of glue fetches %d", s, iq->target_count[1]);
1475275853Sdelphij		return 0;
1476275853Sdelphij	}
1477238106Sdes
1478238106Sdes	iter_mark_cycle_targets(qstate, iq->dp);
1479238106Sdes	missing = (int)delegpt_count_missing_targets(iq->dp);
1480238106Sdes	log_assert(maxtargets != 0); /* that would not be useful */
1481238106Sdes
1482238106Sdes	/* Generate target requests. Basically, any missing targets
1483238106Sdes	 * are queried for here, regardless if it is necessary to do
1484238106Sdes	 * so to continue processing. */
1485238106Sdes	if(maxtargets < 0 || maxtargets > missing)
1486238106Sdes		toget = missing;
1487238106Sdes	else	toget = maxtargets;
1488238106Sdes	if(toget == 0) {
1489238106Sdes		*num = 0;
1490238106Sdes		return 1;
1491238106Sdes	}
1492238106Sdes	/* select 'toget' items from the total of 'missing' items */
1493238106Sdes	log_assert(toget <= missing);
1494238106Sdes
1495238106Sdes	/* loop over missing targets */
1496238106Sdes	for(ns = iq->dp->nslist; ns; ns = ns->next) {
1497238106Sdes		if(ns->resolved)
1498238106Sdes			continue;
1499238106Sdes
1500238106Sdes		/* randomly select this item with probability toget/missing */
1501238106Sdes		if(!iter_ns_probability(qstate->env->rnd, toget, missing)) {
1502238106Sdes			/* do not select this one, next; select toget number
1503238106Sdes			 * of items from a list one less in size */
1504238106Sdes			missing --;
1505238106Sdes			continue;
1506238106Sdes		}
1507238106Sdes
1508238106Sdes		if(ie->supports_ipv6 && !ns->got6) {
1509238106Sdes			/* Send the AAAA request. */
1510238106Sdes			if(!generate_target_query(qstate, iq, id,
1511238106Sdes				ns->name, ns->namelen,
1512238106Sdes				LDNS_RR_TYPE_AAAA, iq->qchase.qclass)) {
1513238106Sdes				*num = query_count;
1514238106Sdes				if(query_count > 0)
1515238106Sdes					qstate->ext_state[id] = module_wait_subquery;
1516238106Sdes				return 0;
1517238106Sdes			}
1518238106Sdes			query_count++;
1519238106Sdes		}
1520238106Sdes		/* Send the A request. */
1521238106Sdes		if(ie->supports_ipv4 && !ns->got4) {
1522238106Sdes			if(!generate_target_query(qstate, iq, id,
1523238106Sdes				ns->name, ns->namelen,
1524238106Sdes				LDNS_RR_TYPE_A, iq->qchase.qclass)) {
1525238106Sdes				*num = query_count;
1526238106Sdes				if(query_count > 0)
1527238106Sdes					qstate->ext_state[id] = module_wait_subquery;
1528238106Sdes				return 0;
1529238106Sdes			}
1530238106Sdes			query_count++;
1531238106Sdes		}
1532238106Sdes
1533238106Sdes		/* mark this target as in progress. */
1534238106Sdes		ns->resolved = 1;
1535238106Sdes		missing--;
1536238106Sdes		toget--;
1537238106Sdes		if(toget == 0)
1538238106Sdes			break;
1539238106Sdes	}
1540238106Sdes	*num = query_count;
1541238106Sdes	if(query_count > 0)
1542238106Sdes		qstate->ext_state[id] = module_wait_subquery;
1543238106Sdes
1544238106Sdes	return 1;
1545238106Sdes}
1546238106Sdes
1547269257Sdes/** see if last resort is possible - does config allow queries to parent */
1548269257Sdesstatic int
1549269257Sdescan_have_last_resort(struct module_env* env, struct delegpt* dp,
1550269257Sdes	struct iter_qstate* iq)
1551269257Sdes{
1552269257Sdes	struct delegpt* fwddp;
1553269257Sdes	struct iter_hints_stub* stub;
1554269257Sdes	/* do not process a last resort (the parent side) if a stub
1555269257Sdes	 * or forward is configured, because we do not want to go 'above'
1556269257Sdes	 * the configured servers */
1557269257Sdes	if(!dname_is_root(dp->name) && (stub = (struct iter_hints_stub*)
1558269257Sdes		name_tree_find(&env->hints->tree, dp->name, dp->namelen,
1559269257Sdes		dp->namelabs, iq->qchase.qclass)) &&
1560269257Sdes		/* has_parent side is turned off for stub_first, where we
1561269257Sdes		 * are allowed to go to the parent */
1562269257Sdes		stub->dp->has_parent_side_NS) {
1563269257Sdes		verbose(VERB_QUERY, "configured stub servers failed -- returning SERVFAIL");
1564269257Sdes		return 0;
1565269257Sdes	}
1566269257Sdes	if((fwddp = forwards_find(env->fwds, dp->name, iq->qchase.qclass)) &&
1567269257Sdes		/* has_parent_side is turned off for forward_first, where
1568269257Sdes		 * we are allowed to go to the parent */
1569269257Sdes		fwddp->has_parent_side_NS) {
1570269257Sdes		verbose(VERB_QUERY, "configured forward servers failed -- returning SERVFAIL");
1571269257Sdes		return 0;
1572269257Sdes	}
1573269257Sdes	return 1;
1574269257Sdes}
1575269257Sdes
1576238106Sdes/**
1577238106Sdes * Called by processQueryTargets when it would like extra targets to query
1578238106Sdes * but it seems to be out of options.  At last resort some less appealing
1579238106Sdes * options are explored.  If there are no more options, the result is SERVFAIL
1580238106Sdes *
1581238106Sdes * @param qstate: query state.
1582238106Sdes * @param iq: iterator query state.
1583238106Sdes * @param ie: iterator shared global environment.
1584238106Sdes * @param id: module id.
1585238106Sdes * @return true if the event requires more request processing immediately,
1586238106Sdes *         false if not.
1587238106Sdes */
1588238106Sdesstatic int
1589238106SdesprocessLastResort(struct module_qstate* qstate, struct iter_qstate* iq,
1590238106Sdes	struct iter_env* ie, int id)
1591238106Sdes{
1592238106Sdes	struct delegpt_ns* ns;
1593238106Sdes	int query_count = 0;
1594238106Sdes	verbose(VERB_ALGO, "No more query targets, attempting last resort");
1595238106Sdes	log_assert(iq->dp);
1596238106Sdes
1597269257Sdes	if(!can_have_last_resort(qstate->env, iq->dp, iq)) {
1598269257Sdes		/* fail -- no more targets, no more hope of targets, no hope
1599269257Sdes		 * of a response. */
1600269257Sdes		return error_response_cache(qstate, id, LDNS_RCODE_SERVFAIL);
1601269257Sdes	}
1602249141Sdes	if(!iq->dp->has_parent_side_NS && dname_is_root(iq->dp->name)) {
1603249141Sdes		struct delegpt* p = hints_lookup_root(qstate->env->hints,
1604249141Sdes			iq->qchase.qclass);
1605249141Sdes		if(p) {
1606249141Sdes			struct delegpt_ns* ns;
1607249141Sdes			struct delegpt_addr* a;
1608249141Sdes			iq->chase_flags &= ~BIT_RD; /* go to authorities */
1609249141Sdes			for(ns = p->nslist; ns; ns=ns->next) {
1610249141Sdes				(void)delegpt_add_ns(iq->dp, qstate->region,
1611269257Sdes					ns->name, ns->lame);
1612249141Sdes			}
1613249141Sdes			for(a = p->target_list; a; a=a->next_target) {
1614249141Sdes				(void)delegpt_add_addr(iq->dp, qstate->region,
1615249141Sdes					&a->addr, a->addrlen, a->bogus,
1616249141Sdes					a->lame);
1617249141Sdes			}
1618249141Sdes		}
1619249141Sdes		iq->dp->has_parent_side_NS = 1;
1620249141Sdes	} else if(!iq->dp->has_parent_side_NS) {
1621238106Sdes		if(!iter_lookup_parent_NS_from_cache(qstate->env, iq->dp,
1622238106Sdes			qstate->region, &qstate->qinfo)
1623238106Sdes			|| !iq->dp->has_parent_side_NS) {
1624238106Sdes			/* if: malloc failure in lookup go up to try */
1625238106Sdes			/* if: no parent NS in cache - go up one level */
1626238106Sdes			verbose(VERB_ALGO, "try to grab parent NS");
1627238106Sdes			iq->store_parent_NS = iq->dp;
1628249141Sdes			iq->chase_flags &= ~BIT_RD; /* go to authorities */
1629238106Sdes			iq->deleg_msg = NULL;
1630238106Sdes			iq->refetch_glue = 1;
1631238106Sdes			iq->query_restart_count++;
1632238106Sdes			iq->sent_count = 0;
1633294190Sdes			if(qstate->env->cfg->qname_minimisation)
1634294190Sdes				iq->minimisation_state = INIT_MINIMISE_STATE;
1635238106Sdes			return next_state(iq, INIT_REQUEST_STATE);
1636238106Sdes		}
1637238106Sdes	}
1638238106Sdes	/* see if that makes new names available */
1639238106Sdes	if(!cache_fill_missing(qstate->env, iq->qchase.qclass,
1640238106Sdes		qstate->region, iq->dp))
1641238106Sdes		log_err("out of memory in cache_fill_missing");
1642238106Sdes	if(iq->dp->usable_list) {
1643238106Sdes		verbose(VERB_ALGO, "try parent-side-name, w. glue from cache");
1644238106Sdes		return next_state(iq, QUERYTARGETS_STATE);
1645238106Sdes	}
1646238106Sdes	/* try to fill out parent glue from cache */
1647238106Sdes	if(iter_lookup_parent_glue_from_cache(qstate->env, iq->dp,
1648238106Sdes		qstate->region, &qstate->qinfo)) {
1649238106Sdes		/* got parent stuff from cache, see if we can continue */
1650238106Sdes		verbose(VERB_ALGO, "try parent-side glue from cache");
1651238106Sdes		return next_state(iq, QUERYTARGETS_STATE);
1652238106Sdes	}
1653238106Sdes	/* query for an extra name added by the parent-NS record */
1654238106Sdes	if(delegpt_count_missing_targets(iq->dp) > 0) {
1655238106Sdes		int qs = 0;
1656238106Sdes		verbose(VERB_ALGO, "try parent-side target name");
1657238106Sdes		if(!query_for_targets(qstate, iq, ie, id, 1, &qs)) {
1658238106Sdes			return error_response(qstate, id, LDNS_RCODE_SERVFAIL);
1659238106Sdes		}
1660238106Sdes		iq->num_target_queries += qs;
1661275853Sdelphij		target_count_increase(iq, qs);
1662238106Sdes		if(qs != 0) {
1663238106Sdes			qstate->ext_state[id] = module_wait_subquery;
1664238106Sdes			return 0; /* and wait for them */
1665238106Sdes		}
1666238106Sdes	}
1667238106Sdes	if(iq->depth == ie->max_dependency_depth) {
1668238106Sdes		verbose(VERB_QUERY, "maxdepth and need more nameservers, fail");
1669238106Sdes		return error_response_cache(qstate, id, LDNS_RCODE_SERVFAIL);
1670238106Sdes	}
1671275853Sdelphij	if(iq->depth > 0 && iq->target_count &&
1672275853Sdelphij		iq->target_count[1] > MAX_TARGET_COUNT) {
1673285206Sdes		char s[LDNS_MAX_DOMAINLEN+1];
1674285206Sdes		dname_str(qstate->qinfo.qname, s);
1675285206Sdes		verbose(VERB_QUERY, "request %s has exceeded the maximum "
1676285206Sdes			"number of glue fetches %d", s, iq->target_count[1]);
1677275853Sdelphij		return error_response_cache(qstate, id, LDNS_RCODE_SERVFAIL);
1678275853Sdelphij	}
1679238106Sdes	/* mark cycle targets for parent-side lookups */
1680238106Sdes	iter_mark_pside_cycle_targets(qstate, iq->dp);
1681238106Sdes	/* see if we can issue queries to get nameserver addresses */
1682238106Sdes	/* this lookup is not randomized, but sequential. */
1683238106Sdes	for(ns = iq->dp->nslist; ns; ns = ns->next) {
1684238106Sdes		/* query for parent-side A and AAAA for nameservers */
1685238106Sdes		if(ie->supports_ipv6 && !ns->done_pside6) {
1686238106Sdes			/* Send the AAAA request. */
1687238106Sdes			if(!generate_parentside_target_query(qstate, iq, id,
1688238106Sdes				ns->name, ns->namelen,
1689238106Sdes				LDNS_RR_TYPE_AAAA, iq->qchase.qclass))
1690238106Sdes				return error_response(qstate, id,
1691238106Sdes					LDNS_RCODE_SERVFAIL);
1692238106Sdes			ns->done_pside6 = 1;
1693238106Sdes			query_count++;
1694238106Sdes		}
1695238106Sdes		if(ie->supports_ipv4 && !ns->done_pside4) {
1696238106Sdes			/* Send the A request. */
1697238106Sdes			if(!generate_parentside_target_query(qstate, iq, id,
1698238106Sdes				ns->name, ns->namelen,
1699238106Sdes				LDNS_RR_TYPE_A, iq->qchase.qclass))
1700238106Sdes				return error_response(qstate, id,
1701238106Sdes					LDNS_RCODE_SERVFAIL);
1702238106Sdes			ns->done_pside4 = 1;
1703238106Sdes			query_count++;
1704238106Sdes		}
1705238106Sdes		if(query_count != 0) { /* suspend to await results */
1706238106Sdes			verbose(VERB_ALGO, "try parent-side glue lookup");
1707238106Sdes			iq->num_target_queries += query_count;
1708275853Sdelphij			target_count_increase(iq, query_count);
1709238106Sdes			qstate->ext_state[id] = module_wait_subquery;
1710238106Sdes			return 0;
1711238106Sdes		}
1712238106Sdes	}
1713238106Sdes
1714238106Sdes	/* if this was a parent-side glue query itself, then store that
1715238106Sdes	 * failure in cache. */
1716238106Sdes	if(iq->query_for_pside_glue && !iq->pside_glue)
1717238106Sdes		iter_store_parentside_neg(qstate->env, &qstate->qinfo,
1718238106Sdes			iq->deleg_msg?iq->deleg_msg->rep:
1719238106Sdes			(iq->response?iq->response->rep:NULL));
1720238106Sdes
1721238106Sdes	verbose(VERB_QUERY, "out of query targets -- returning SERVFAIL");
1722238106Sdes	/* fail -- no more targets, no more hope of targets, no hope
1723238106Sdes	 * of a response. */
1724238106Sdes	return error_response_cache(qstate, id, LDNS_RCODE_SERVFAIL);
1725238106Sdes}
1726238106Sdes
1727238106Sdes/**
1728238106Sdes * Try to find the NS record set that will resolve a qtype DS query. Due
1729238106Sdes * to grandparent/grandchild reasons we did not get a proper lookup right
1730238106Sdes * away.  We need to create type NS queries until we get the right parent
1731238106Sdes * for this lookup.  We remove labels from the query to find the right point.
1732238106Sdes * If we end up at the old dp name, then there is no solution.
1733238106Sdes *
1734238106Sdes * @param qstate: query state.
1735238106Sdes * @param iq: iterator query state.
1736238106Sdes * @param id: module id.
1737238106Sdes * @return true if the event requires more immediate processing, false if
1738238106Sdes *         not. This is generally only true when forwarding the request to
1739238106Sdes *         the final state (i.e., on answer).
1740238106Sdes */
1741238106Sdesstatic int
1742249141SdesprocessDSNSFind(struct module_qstate* qstate, struct iter_qstate* iq, int id)
1743238106Sdes{
1744238106Sdes	struct module_qstate* subq = NULL;
1745238106Sdes	verbose(VERB_ALGO, "processDSNSFind");
1746238106Sdes
1747238106Sdes	if(!iq->dsns_point) {
1748238106Sdes		/* initialize */
1749238106Sdes		iq->dsns_point = iq->qchase.qname;
1750238106Sdes		iq->dsns_point_len = iq->qchase.qname_len;
1751238106Sdes	}
1752238106Sdes	/* robustcheck for internal error: we are not underneath the dp */
1753238106Sdes	if(!dname_subdomain_c(iq->dsns_point, iq->dp->name)) {
1754238106Sdes		return error_response_cache(qstate, id, LDNS_RCODE_SERVFAIL);
1755238106Sdes	}
1756238106Sdes
1757238106Sdes	/* go up one (more) step, until we hit the dp, if so, end */
1758238106Sdes	dname_remove_label(&iq->dsns_point, &iq->dsns_point_len);
1759238106Sdes	if(query_dname_compare(iq->dsns_point, iq->dp->name) == 0) {
1760238106Sdes		/* there was no inbetween nameserver, use the old delegation
1761238106Sdes		 * point again.  And this time, because dsns_point is nonNULL
1762238106Sdes		 * we are going to accept the (bad) result */
1763238106Sdes		iq->state = QUERYTARGETS_STATE;
1764238106Sdes		return 1;
1765238106Sdes	}
1766238106Sdes	iq->state = DSNS_FIND_STATE;
1767238106Sdes
1768238106Sdes	/* spawn NS lookup (validation not needed, this is for DS lookup) */
1769238106Sdes	log_nametypeclass(VERB_ALGO, "fetch nameservers",
1770238106Sdes		iq->dsns_point, LDNS_RR_TYPE_NS, iq->qchase.qclass);
1771238106Sdes	if(!generate_sub_request(iq->dsns_point, iq->dsns_point_len,
1772238106Sdes		LDNS_RR_TYPE_NS, iq->qchase.qclass, qstate, id, iq,
1773238106Sdes		INIT_REQUEST_STATE, FINISHED_STATE, &subq, 0)) {
1774238106Sdes		return error_response_cache(qstate, id, LDNS_RCODE_SERVFAIL);
1775238106Sdes	}
1776238106Sdes
1777238106Sdes	return 0;
1778238106Sdes}
1779238106Sdes
1780238106Sdes/**
1781238106Sdes * This is the request event state where the request will be sent to one of
1782238106Sdes * its current query targets. This state also handles issuing target lookup
1783238106Sdes * queries for missing target IP addresses. Queries typically iterate on
1784238106Sdes * this state, both when they are just trying different targets for a given
1785238106Sdes * delegation point, and when they change delegation points. This state
1786238106Sdes * roughly corresponds to RFC 1034 algorithm steps 3 and 4.
1787238106Sdes *
1788238106Sdes * @param qstate: query state.
1789238106Sdes * @param iq: iterator query state.
1790238106Sdes * @param ie: iterator shared global environment.
1791238106Sdes * @param id: module id.
1792238106Sdes * @return true if the event requires more request processing immediately,
1793238106Sdes *         false if not. This state only returns true when it is generating
1794238106Sdes *         a SERVFAIL response because the query has hit a dead end.
1795238106Sdes */
1796238106Sdesstatic int
1797238106SdesprocessQueryTargets(struct module_qstate* qstate, struct iter_qstate* iq,
1798238106Sdes	struct iter_env* ie, int id)
1799238106Sdes{
1800238106Sdes	int tf_policy;
1801238106Sdes	struct delegpt_addr* target;
1802238106Sdes	struct outbound_entry* outq;
1803238106Sdes
1804238106Sdes	/* NOTE: a request will encounter this state for each target it
1805238106Sdes	 * needs to send a query to. That is, at least one per referral,
1806238106Sdes	 * more if some targets timeout or return throwaway answers. */
1807238106Sdes
1808238106Sdes	log_query_info(VERB_QUERY, "processQueryTargets:", &qstate->qinfo);
1809238106Sdes	verbose(VERB_ALGO, "processQueryTargets: targetqueries %d, "
1810238106Sdes		"currentqueries %d sentcount %d", iq->num_target_queries,
1811238106Sdes		iq->num_current_queries, iq->sent_count);
1812238106Sdes
1813238106Sdes	/* Make sure that we haven't run away */
1814238106Sdes	/* FIXME: is this check even necessary? */
1815238106Sdes	if(iq->referral_count > MAX_REFERRAL_COUNT) {
1816238106Sdes		verbose(VERB_QUERY, "request has exceeded the maximum "
1817238106Sdes			"number of referrrals with %d", iq->referral_count);
1818238106Sdes		return error_response(qstate, id, LDNS_RCODE_SERVFAIL);
1819238106Sdes	}
1820238106Sdes	if(iq->sent_count > MAX_SENT_COUNT) {
1821238106Sdes		verbose(VERB_QUERY, "request has exceeded the maximum "
1822238106Sdes			"number of sends with %d", iq->sent_count);
1823238106Sdes		return error_response(qstate, id, LDNS_RCODE_SERVFAIL);
1824238106Sdes	}
1825238106Sdes
1826238106Sdes	/* Make sure we have a delegation point, otherwise priming failed
1827238106Sdes	 * or another failure occurred */
1828238106Sdes	if(!iq->dp) {
1829238106Sdes		verbose(VERB_QUERY, "Failed to get a delegation, giving up");
1830238106Sdes		return error_response(qstate, id, LDNS_RCODE_SERVFAIL);
1831238106Sdes	}
1832238106Sdes	if(!ie->supports_ipv6)
1833238106Sdes		delegpt_no_ipv6(iq->dp);
1834238106Sdes	if(!ie->supports_ipv4)
1835238106Sdes		delegpt_no_ipv4(iq->dp);
1836238106Sdes	delegpt_log(VERB_ALGO, iq->dp);
1837238106Sdes
1838238106Sdes	if(iq->num_current_queries>0) {
1839238106Sdes		/* already busy answering a query, this restart is because
1840238106Sdes		 * more delegpt addrs became available, wait for existing
1841238106Sdes		 * query. */
1842238106Sdes		verbose(VERB_ALGO, "woke up, but wait for outstanding query");
1843238106Sdes		qstate->ext_state[id] = module_wait_reply;
1844238106Sdes		return 0;
1845238106Sdes	}
1846238106Sdes
1847238106Sdes	tf_policy = 0;
1848238106Sdes	/* < not <=, because although the array is large enough for <=, the
1849238106Sdes	 * generated query will immediately be discarded due to depth and
1850238106Sdes	 * that servfail is cached, which is not good as opportunism goes. */
1851238106Sdes	if(iq->depth < ie->max_dependency_depth
1852238106Sdes		&& iq->sent_count < TARGET_FETCH_STOP) {
1853238106Sdes		tf_policy = ie->target_fetch_policy[iq->depth];
1854238106Sdes	}
1855238106Sdes
1856238106Sdes	/* if in 0x20 fallback get as many targets as possible */
1857238106Sdes	if(iq->caps_fallback) {
1858238106Sdes		int extra = 0;
1859238106Sdes		size_t naddr, nres, navail;
1860238106Sdes		if(!query_for_targets(qstate, iq, ie, id, -1, &extra)) {
1861238106Sdes			return error_response(qstate, id, LDNS_RCODE_SERVFAIL);
1862238106Sdes		}
1863238106Sdes		iq->num_target_queries += extra;
1864275853Sdelphij		target_count_increase(iq, extra);
1865238106Sdes		if(iq->num_target_queries > 0) {
1866238106Sdes			/* wait to get all targets, we want to try em */
1867238106Sdes			verbose(VERB_ALGO, "wait for all targets for fallback");
1868238106Sdes			qstate->ext_state[id] = module_wait_reply;
1869238106Sdes			return 0;
1870238106Sdes		}
1871238106Sdes		/* did we do enough fallback queries already? */
1872238106Sdes		delegpt_count_addr(iq->dp, &naddr, &nres, &navail);
1873238106Sdes		/* the current caps_server is the number of fallbacks sent.
1874238106Sdes		 * the original query is one that matched too, so we have
1875238106Sdes		 * caps_server+1 number of matching queries now */
1876238106Sdes		if(iq->caps_server+1 >= naddr*3 ||
1877291767Sdes			iq->caps_server*2+2 >= MAX_SENT_COUNT) {
1878291767Sdes			/* *2 on sentcount check because ipv6 may fail */
1879238106Sdes			/* we're done, process the response */
1880238106Sdes			verbose(VERB_ALGO, "0x20 fallback had %d responses "
1881238106Sdes				"match for %d wanted, done.",
1882238106Sdes				(int)iq->caps_server+1, (int)naddr*3);
1883291767Sdes			iq->response = iq->caps_response;
1884238106Sdes			iq->caps_fallback = 0;
1885238106Sdes			iter_dec_attempts(iq->dp, 3); /* space for fallback */
1886238106Sdes			iq->num_current_queries++; /* RespState decrements it*/
1887238106Sdes			iq->referral_count++; /* make sure we don't loop */
1888238106Sdes			iq->sent_count = 0;
1889238106Sdes			iq->state = QUERY_RESP_STATE;
1890238106Sdes			return 1;
1891238106Sdes		}
1892238106Sdes		verbose(VERB_ALGO, "0x20 fallback number %d",
1893238106Sdes			(int)iq->caps_server);
1894238106Sdes
1895238106Sdes	/* if there is a policy to fetch missing targets
1896238106Sdes	 * opportunistically, do it. we rely on the fact that once a
1897238106Sdes	 * query (or queries) for a missing name have been issued,
1898238106Sdes	 * they will not show up again. */
1899238106Sdes	} else if(tf_policy != 0) {
1900238106Sdes		int extra = 0;
1901238106Sdes		verbose(VERB_ALGO, "attempt to get extra %d targets",
1902238106Sdes			tf_policy);
1903238106Sdes		(void)query_for_targets(qstate, iq, ie, id, tf_policy, &extra);
1904238106Sdes		/* errors ignored, these targets are not strictly necessary for
1905238106Sdes		 * this result, we do not have to reply with SERVFAIL */
1906238106Sdes		iq->num_target_queries += extra;
1907275853Sdelphij		target_count_increase(iq, extra);
1908238106Sdes	}
1909238106Sdes
1910238106Sdes	/* Add the current set of unused targets to our queue. */
1911238106Sdes	delegpt_add_unused_targets(iq->dp);
1912238106Sdes
1913238106Sdes	/* Select the next usable target, filtering out unsuitable targets. */
1914238106Sdes	target = iter_server_selection(ie, qstate->env, iq->dp,
1915238106Sdes		iq->dp->name, iq->dp->namelen, iq->qchase.qtype,
1916238106Sdes		&iq->dnssec_lame_query, &iq->chase_to_rd,
1917238106Sdes		iq->num_target_queries, qstate->blacklist);
1918238106Sdes
1919238106Sdes	/* If no usable target was selected... */
1920238106Sdes	if(!target) {
1921238106Sdes		/* Here we distinguish between three states: generate a new
1922238106Sdes		 * target query, just wait, or quit (with a SERVFAIL).
1923238106Sdes		 * We have the following information: number of active
1924238106Sdes		 * target queries, number of active current queries,
1925238106Sdes		 * the presence of missing targets at this delegation
1926238106Sdes		 * point, and the given query target policy. */
1927238106Sdes
1928238106Sdes		/* Check for the wait condition. If this is true, then
1929238106Sdes		 * an action must be taken. */
1930238106Sdes		if(iq->num_target_queries==0 && iq->num_current_queries==0) {
1931238106Sdes			/* If there is nothing to wait for, then we need
1932238106Sdes			 * to distinguish between generating (a) new target
1933238106Sdes			 * query, or failing. */
1934238106Sdes			if(delegpt_count_missing_targets(iq->dp) > 0) {
1935238106Sdes				int qs = 0;
1936238106Sdes				verbose(VERB_ALGO, "querying for next "
1937238106Sdes					"missing target");
1938238106Sdes				if(!query_for_targets(qstate, iq, ie, id,
1939238106Sdes					1, &qs)) {
1940238106Sdes					return error_response(qstate, id,
1941238106Sdes						LDNS_RCODE_SERVFAIL);
1942238106Sdes				}
1943238106Sdes				if(qs == 0 &&
1944238106Sdes				   delegpt_count_missing_targets(iq->dp) == 0){
1945238106Sdes					/* it looked like there were missing
1946238106Sdes					 * targets, but they did not turn up.
1947238106Sdes					 * Try the bad choices again (if any),
1948238106Sdes					 * when we get back here missing==0,
1949238106Sdes					 * so this is not a loop. */
1950238106Sdes					return 1;
1951238106Sdes				}
1952238106Sdes				iq->num_target_queries += qs;
1953275853Sdelphij				target_count_increase(iq, qs);
1954238106Sdes			}
1955238106Sdes			/* Since a target query might have been made, we
1956238106Sdes			 * need to check again. */
1957238106Sdes			if(iq->num_target_queries == 0) {
1958291767Sdes				/* if in capsforid fallback, instead of last
1959291767Sdes				 * resort, we agree with the current reply
1960291767Sdes				 * we have (if any) (our count of addrs bad)*/
1961291767Sdes				if(iq->caps_fallback && iq->caps_reply) {
1962291767Sdes					/* we're done, process the response */
1963291767Sdes					verbose(VERB_ALGO, "0x20 fallback had %d responses, "
1964291767Sdes						"but no more servers except "
1965291767Sdes						"last resort, done.",
1966291767Sdes						(int)iq->caps_server+1);
1967291767Sdes					iq->response = iq->caps_response;
1968291767Sdes					iq->caps_fallback = 0;
1969291767Sdes					iter_dec_attempts(iq->dp, 3); /* space for fallback */
1970291767Sdes					iq->num_current_queries++; /* RespState decrements it*/
1971291767Sdes					iq->referral_count++; /* make sure we don't loop */
1972291767Sdes					iq->sent_count = 0;
1973291767Sdes					iq->state = QUERY_RESP_STATE;
1974291767Sdes					return 1;
1975291767Sdes				}
1976238106Sdes				return processLastResort(qstate, iq, ie, id);
1977238106Sdes			}
1978238106Sdes		}
1979238106Sdes
1980238106Sdes		/* otherwise, we have no current targets, so submerge
1981238106Sdes		 * until one of the target or direct queries return. */
1982238106Sdes		if(iq->num_target_queries>0 && iq->num_current_queries>0) {
1983238106Sdes			verbose(VERB_ALGO, "no current targets -- waiting "
1984238106Sdes				"for %d targets to resolve or %d outstanding"
1985238106Sdes				" queries to respond", iq->num_target_queries,
1986238106Sdes				iq->num_current_queries);
1987238106Sdes			qstate->ext_state[id] = module_wait_reply;
1988238106Sdes		} else if(iq->num_target_queries>0) {
1989238106Sdes			verbose(VERB_ALGO, "no current targets -- waiting "
1990238106Sdes				"for %d targets to resolve.",
1991238106Sdes				iq->num_target_queries);
1992238106Sdes			qstate->ext_state[id] = module_wait_subquery;
1993238106Sdes		} else {
1994238106Sdes			verbose(VERB_ALGO, "no current targets -- waiting "
1995238106Sdes				"for %d outstanding queries to respond.",
1996238106Sdes				iq->num_current_queries);
1997238106Sdes			qstate->ext_state[id] = module_wait_reply;
1998238106Sdes		}
1999238106Sdes		return 0;
2000238106Sdes	}
2001238106Sdes
2002291767Sdes	/* if not forwarding, check ratelimits per delegationpoint name */
2003291767Sdes	if(!(iq->chase_flags & BIT_RD) && !iq->ratelimit_ok) {
2004291767Sdes		if(!infra_ratelimit_inc(qstate->env->infra_cache, iq->dp->name,
2005291767Sdes			iq->dp->namelen, *qstate->env->now)) {
2006291767Sdes			verbose(VERB_ALGO, "query exceeded ratelimits");
2007291767Sdes			return error_response(qstate, id, LDNS_RCODE_SERVFAIL);
2008291767Sdes		}
2009291767Sdes	}
2010291767Sdes
2011294190Sdes	if(iq->minimisation_state == INIT_MINIMISE_STATE) {
2012294190Sdes		/* (Re)set qinfo_out to (new) delegation point, except
2013294190Sdes 		 * when qinfo_out is already a subdomain of dp. This happens
2014294190Sdes		 * when resolving ip6.arpa dnames. */
2015294190Sdes		if(!(iq->qinfo_out.qname_len
2016294190Sdes			&& dname_subdomain_c(iq->qchase.qname,
2017294190Sdes				iq->qinfo_out.qname)
2018294190Sdes			&& dname_subdomain_c(iq->qinfo_out.qname,
2019294190Sdes				iq->dp->name))) {
2020294190Sdes			iq->qinfo_out.qname = iq->dp->name;
2021294190Sdes			iq->qinfo_out.qname_len = iq->dp->namelen;
2022294190Sdes			iq->qinfo_out.qtype = LDNS_RR_TYPE_NS;
2023294190Sdes			iq->qinfo_out.qclass = iq->qchase.qclass;
2024294190Sdes		}
2025294190Sdes
2026294190Sdes		iq->minimisation_state = MINIMISE_STATE;
2027294190Sdes	}
2028294190Sdes	if(iq->minimisation_state == MINIMISE_STATE) {
2029294190Sdes		int labdiff = dname_count_labels(iq->qchase.qname) -
2030294190Sdes			dname_count_labels(iq->qinfo_out.qname);
2031294190Sdes
2032294190Sdes		iq->qinfo_out.qname = iq->qchase.qname;
2033294190Sdes		iq->qinfo_out.qname_len = iq->qchase.qname_len;
2034294190Sdes
2035294190Sdes		/* Special treatment for ip6.arpa lookups.
2036294190Sdes		 * Reverse IPv6 dname has 34 labels, increment the IP part
2037294190Sdes		 * (usually first 32 labels) by 8 labels (7 more than the
2038294190Sdes		 * default 1 label increment). */
2039294190Sdes		if(labdiff <= 32 &&
2040294190Sdes			dname_subdomain_c(iq->qchase.qname, ie->ip6arpa_dname)) {
2041294190Sdes			labdiff -= 7;
2042294190Sdes			/* Small chance of zone cut after first label. Stop
2043294190Sdes			 * minimising */
2044294190Sdes			if(labdiff <= 1)
2045294190Sdes				labdiff = 0;
2046294190Sdes		}
2047294190Sdes
2048294190Sdes		if(labdiff > 1) {
2049294190Sdes			verbose(VERB_QUERY, "removing %d labels", labdiff-1);
2050294190Sdes			dname_remove_labels(&iq->qinfo_out.qname,
2051294190Sdes				&iq->qinfo_out.qname_len,
2052294190Sdes				labdiff-1);
2053294190Sdes		}
2054294190Sdes		if(labdiff < 1 ||
2055294190Sdes			(labdiff < 2 && iq->qchase.qtype == LDNS_RR_TYPE_DS))
2056294190Sdes			/* Stop minimising this query, resolve "as usual" */
2057294190Sdes			iq->minimisation_state = DONOT_MINIMISE_STATE;
2058294190Sdes		else {
2059294190Sdes			struct dns_msg* msg = dns_cache_lookup(qstate->env,
2060294190Sdes				iq->qinfo_out.qname, iq->qinfo_out.qname_len,
2061294190Sdes				iq->qinfo_out.qtype, iq->qinfo_out.qclass,
2062294190Sdes				qstate->query_flags, qstate->region,
2063294190Sdes				qstate->env->scratch);
2064294190Sdes			if(msg && msg->rep->an_numrrsets == 0
2065294190Sdes				&& FLAGS_GET_RCODE(msg->rep->flags) ==
2066294190Sdes				LDNS_RCODE_NOERROR)
2067294190Sdes				/* no need to send query if it is already
2068294190Sdes				 * cached as NOERROR/NODATA */
2069294190Sdes				return 1;
2070294190Sdes		}
2071294190Sdes
2072294190Sdes	}
2073294190Sdes	if(iq->minimisation_state == SKIP_MINIMISE_STATE)
2074294190Sdes		/* Do not increment qname, continue incrementing next
2075294190Sdes		 * iteration */
2076294190Sdes		iq->minimisation_state = MINIMISE_STATE;
2077294190Sdes	if(iq->minimisation_state == DONOT_MINIMISE_STATE)
2078294190Sdes		iq->qinfo_out = iq->qchase;
2079294190Sdes
2080238106Sdes	/* We have a valid target. */
2081238106Sdes	if(verbosity >= VERB_QUERY) {
2082294190Sdes		log_query_info(VERB_QUERY, "sending query:", &iq->qinfo_out);
2083238106Sdes		log_name_addr(VERB_QUERY, "sending to target:", iq->dp->name,
2084238106Sdes			&target->addr, target->addrlen);
2085238106Sdes		verbose(VERB_ALGO, "dnssec status: %s%s",
2086238106Sdes			iq->dnssec_expected?"expected": "not expected",
2087238106Sdes			iq->dnssec_lame_query?" but lame_query anyway": "");
2088238106Sdes	}
2089238106Sdes	fptr_ok(fptr_whitelist_modenv_send_query(qstate->env->send_query));
2090238106Sdes	outq = (*qstate->env->send_query)(
2091294190Sdes		iq->qinfo_out.qname, iq->qinfo_out.qname_len,
2092294190Sdes		iq->qinfo_out.qtype, iq->qinfo_out.qclass,
2093238106Sdes		iq->chase_flags | (iq->chase_to_rd?BIT_RD:0), EDNS_DO|BIT_CD,
2094291767Sdes		iq->dnssec_expected, iq->caps_fallback || is_caps_whitelisted(
2095291767Sdes		ie, iq), &target->addr, target->addrlen, iq->dp->name,
2096291767Sdes		iq->dp->namelen, qstate);
2097238106Sdes	if(!outq) {
2098238106Sdes		log_addr(VERB_DETAIL, "error sending query to auth server",
2099238106Sdes			&target->addr, target->addrlen);
2100291767Sdes		if(!(iq->chase_flags & BIT_RD) && !iq->ratelimit_ok)
2101291767Sdes		    infra_ratelimit_dec(qstate->env->infra_cache, iq->dp->name,
2102291767Sdes			iq->dp->namelen, *qstate->env->now);
2103238106Sdes		return next_state(iq, QUERYTARGETS_STATE);
2104238106Sdes	}
2105238106Sdes	outbound_list_insert(&iq->outlist, outq);
2106238106Sdes	iq->num_current_queries++;
2107238106Sdes	iq->sent_count++;
2108238106Sdes	qstate->ext_state[id] = module_wait_reply;
2109238106Sdes
2110238106Sdes	return 0;
2111238106Sdes}
2112238106Sdes
2113238106Sdes/** find NS rrset in given list */
2114238106Sdesstatic struct ub_packed_rrset_key*
2115238106Sdesfind_NS(struct reply_info* rep, size_t from, size_t to)
2116238106Sdes{
2117238106Sdes	size_t i;
2118238106Sdes	for(i=from; i<to; i++) {
2119238106Sdes		if(ntohs(rep->rrsets[i]->rk.type) == LDNS_RR_TYPE_NS)
2120238106Sdes			return rep->rrsets[i];
2121238106Sdes	}
2122238106Sdes	return NULL;
2123238106Sdes}
2124238106Sdes
2125238106Sdes
2126238106Sdes/**
2127238106Sdes * Process the query response. All queries end up at this state first. This
2128238106Sdes * process generally consists of analyzing the response and routing the
2129238106Sdes * event to the next state (either bouncing it back to a request state, or
2130238106Sdes * terminating the processing for this event).
2131238106Sdes *
2132238106Sdes * @param qstate: query state.
2133238106Sdes * @param iq: iterator query state.
2134238106Sdes * @param id: module id.
2135238106Sdes * @return true if the event requires more immediate processing, false if
2136238106Sdes *         not. This is generally only true when forwarding the request to
2137238106Sdes *         the final state (i.e., on answer).
2138238106Sdes */
2139238106Sdesstatic int
2140238106SdesprocessQueryResponse(struct module_qstate* qstate, struct iter_qstate* iq,
2141238106Sdes	int id)
2142238106Sdes{
2143238106Sdes	int dnsseclame = 0;
2144238106Sdes	enum response_type type;
2145238106Sdes	iq->num_current_queries--;
2146238106Sdes	if(iq->response == NULL) {
2147294190Sdes		/* Don't increment qname when QNAME minimisation is enabled */
2148294190Sdes		if (qstate->env->cfg->qname_minimisation)
2149294190Sdes			iq->minimisation_state = SKIP_MINIMISE_STATE;
2150238106Sdes		iq->chase_to_rd = 0;
2151238106Sdes		iq->dnssec_lame_query = 0;
2152238106Sdes		verbose(VERB_ALGO, "query response was timeout");
2153238106Sdes		return next_state(iq, QUERYTARGETS_STATE);
2154238106Sdes	}
2155238106Sdes	type = response_type_from_server(
2156238106Sdes		(int)((iq->chase_flags&BIT_RD) || iq->chase_to_rd),
2157238106Sdes		iq->response, &iq->qchase, iq->dp);
2158238106Sdes	iq->chase_to_rd = 0;
2159238106Sdes	if(type == RESPONSE_TYPE_REFERRAL && (iq->chase_flags&BIT_RD)) {
2160238106Sdes		/* When forwarding (RD bit is set), we handle referrals
2161238106Sdes		 * differently. No queries should be sent elsewhere */
2162238106Sdes		type = RESPONSE_TYPE_ANSWER;
2163238106Sdes	}
2164238106Sdes	if(iq->dnssec_expected && !iq->dnssec_lame_query &&
2165238106Sdes		!(iq->chase_flags&BIT_RD)
2166238106Sdes		&& type != RESPONSE_TYPE_LAME
2167238106Sdes		&& type != RESPONSE_TYPE_REC_LAME
2168238106Sdes		&& type != RESPONSE_TYPE_THROWAWAY
2169238106Sdes		&& type != RESPONSE_TYPE_UNTYPED) {
2170238106Sdes		/* a possible answer, see if it is missing DNSSEC */
2171238106Sdes		/* but not when forwarding, so we dont mark fwder lame */
2172269257Sdes		if(!iter_msg_has_dnssec(iq->response)) {
2173269257Sdes			/* Mark this address as dnsseclame in this dp,
2174269257Sdes			 * because that will make serverselection disprefer
2175269257Sdes			 * it, but also, once it is the only final option,
2176269257Sdes			 * use dnssec-lame-bypass if it needs to query there.*/
2177269257Sdes			if(qstate->reply) {
2178269257Sdes				struct delegpt_addr* a = delegpt_find_addr(
2179269257Sdes					iq->dp, &qstate->reply->addr,
2180269257Sdes					qstate->reply->addrlen);
2181269257Sdes				if(a) a->dnsseclame = 1;
2182269257Sdes			}
2183269257Sdes			/* test the answer is from the zone we expected,
2184269257Sdes		 	 * otherwise, (due to parent,child on same server), we
2185269257Sdes		 	 * might mark the server,zone lame inappropriately */
2186269257Sdes			if(!iter_msg_from_zone(iq->response, iq->dp, type,
2187269257Sdes				iq->qchase.qclass))
2188269257Sdes				qstate->reply = NULL;
2189238106Sdes			type = RESPONSE_TYPE_LAME;
2190238106Sdes			dnsseclame = 1;
2191238106Sdes		}
2192238106Sdes	} else iq->dnssec_lame_query = 0;
2193238106Sdes	/* see if referral brings us close to the target */
2194238106Sdes	if(type == RESPONSE_TYPE_REFERRAL) {
2195238106Sdes		struct ub_packed_rrset_key* ns = find_NS(
2196238106Sdes			iq->response->rep, iq->response->rep->an_numrrsets,
2197238106Sdes			iq->response->rep->an_numrrsets
2198238106Sdes			+ iq->response->rep->ns_numrrsets);
2199238106Sdes		if(!ns) ns = find_NS(iq->response->rep, 0,
2200238106Sdes				iq->response->rep->an_numrrsets);
2201238106Sdes		if(!ns || !dname_strict_subdomain_c(ns->rk.dname, iq->dp->name)
2202238106Sdes			|| !dname_subdomain_c(iq->qchase.qname, ns->rk.dname)){
2203238106Sdes			verbose(VERB_ALGO, "bad referral, throwaway");
2204238106Sdes			type = RESPONSE_TYPE_THROWAWAY;
2205238106Sdes		} else
2206238106Sdes			iter_scrub_ds(iq->response, ns, iq->dp->name);
2207238106Sdes	} else iter_scrub_ds(iq->response, NULL, NULL);
2208238106Sdes
2209238106Sdes	/* handle each of the type cases */
2210238106Sdes	if(type == RESPONSE_TYPE_ANSWER) {
2211238106Sdes		/* ANSWER type responses terminate the query algorithm,
2212238106Sdes		 * so they sent on their */
2213238106Sdes		if(verbosity >= VERB_DETAIL) {
2214238106Sdes			verbose(VERB_DETAIL, "query response was %s",
2215238106Sdes				FLAGS_GET_RCODE(iq->response->rep->flags)
2216238106Sdes				==LDNS_RCODE_NXDOMAIN?"NXDOMAIN ANSWER":
2217238106Sdes				(iq->response->rep->an_numrrsets?"ANSWER":
2218238106Sdes				"nodata ANSWER"));
2219238106Sdes		}
2220238106Sdes		/* if qtype is DS, check we have the right level of answer,
2221238106Sdes		 * like grandchild answer but we need the middle, reject it */
2222238106Sdes		if(iq->qchase.qtype == LDNS_RR_TYPE_DS && !iq->dsns_point
2223238106Sdes			&& !(iq->chase_flags&BIT_RD)
2224238106Sdes			&& iter_ds_toolow(iq->response, iq->dp)
2225249141Sdes			&& iter_dp_cangodown(&iq->qchase, iq->dp)) {
2226249141Sdes			/* close down outstanding requests to be discarded */
2227249141Sdes			outbound_list_clear(&iq->outlist);
2228249141Sdes			iq->num_current_queries = 0;
2229249141Sdes			fptr_ok(fptr_whitelist_modenv_detach_subs(
2230249141Sdes				qstate->env->detach_subs));
2231249141Sdes			(*qstate->env->detach_subs)(qstate);
2232249141Sdes			iq->num_target_queries = 0;
2233238106Sdes			return processDSNSFind(qstate, iq, id);
2234249141Sdes		}
2235249141Sdes		iter_dns_store(qstate->env, &iq->response->qinfo,
2236238106Sdes			iq->response->rep, 0, qstate->prefetch_leeway,
2237238106Sdes			iq->dp&&iq->dp->has_parent_side_NS,
2238285206Sdes			qstate->region, qstate->query_flags);
2239238106Sdes		/* close down outstanding requests to be discarded */
2240238106Sdes		outbound_list_clear(&iq->outlist);
2241238106Sdes		iq->num_current_queries = 0;
2242238106Sdes		fptr_ok(fptr_whitelist_modenv_detach_subs(
2243238106Sdes			qstate->env->detach_subs));
2244238106Sdes		(*qstate->env->detach_subs)(qstate);
2245238106Sdes		iq->num_target_queries = 0;
2246238106Sdes		if(qstate->reply)
2247238106Sdes			sock_list_insert(&qstate->reply_origin,
2248238106Sdes				&qstate->reply->addr, qstate->reply->addrlen,
2249238106Sdes				qstate->region);
2250294190Sdes		if(iq->minimisation_state != DONOT_MINIMISE_STATE) {
2251294190Sdes			/* Best effort qname-minimisation.
2252294190Sdes			 * Stop minimising and send full query when RCODE
2253294190Sdes			 * is not NOERROR */
2254294190Sdes			if(FLAGS_GET_RCODE(iq->response->rep->flags) !=
2255294190Sdes				LDNS_RCODE_NOERROR)
2256294190Sdes				iq->minimisation_state = DONOT_MINIMISE_STATE;
2257294190Sdes			return next_state(iq, QUERYTARGETS_STATE);
2258294190Sdes		}
2259238106Sdes		return final_state(iq);
2260238106Sdes	} else if(type == RESPONSE_TYPE_REFERRAL) {
2261238106Sdes		/* REFERRAL type responses get a reset of the
2262238106Sdes		 * delegation point, and back to the QUERYTARGETS_STATE. */
2263238106Sdes		verbose(VERB_DETAIL, "query response was REFERRAL");
2264238106Sdes
2265291767Sdes		if(!(iq->chase_flags & BIT_RD) && !iq->ratelimit_ok) {
2266291767Sdes			/* we have a referral, no ratelimit, we can send
2267291767Sdes			 * our queries to the given name */
2268291767Sdes			infra_ratelimit_dec(qstate->env->infra_cache,
2269291767Sdes				iq->dp->name, iq->dp->namelen,
2270291767Sdes				*qstate->env->now);
2271291767Sdes		}
2272291767Sdes
2273238106Sdes		/* if hardened, only store referral if we asked for it */
2274238106Sdes		if(!qstate->env->cfg->harden_referral_path ||
2275238106Sdes		    (  qstate->qinfo.qtype == LDNS_RR_TYPE_NS
2276238106Sdes			&& (qstate->query_flags&BIT_RD)
2277238106Sdes			&& !(qstate->query_flags&BIT_CD)
2278238106Sdes			   /* we know that all other NS rrsets are scrubbed
2279238106Sdes			    * away, thus on referral only one is left.
2280238106Sdes			    * see if that equals the query name... */
2281238106Sdes			&& ( /* auth section, but sometimes in answer section*/
2282238106Sdes			  reply_find_rrset_section_ns(iq->response->rep,
2283238106Sdes				iq->qchase.qname, iq->qchase.qname_len,
2284238106Sdes				LDNS_RR_TYPE_NS, iq->qchase.qclass)
2285238106Sdes			  || reply_find_rrset_section_an(iq->response->rep,
2286238106Sdes				iq->qchase.qname, iq->qchase.qname_len,
2287238106Sdes				LDNS_RR_TYPE_NS, iq->qchase.qclass)
2288238106Sdes			  )
2289238106Sdes		    )) {
2290238106Sdes			/* Store the referral under the current query */
2291238106Sdes			/* no prefetch-leeway, since its not the answer */
2292249141Sdes			iter_dns_store(qstate->env, &iq->response->qinfo,
2293285206Sdes				iq->response->rep, 1, 0, 0, NULL, 0);
2294238106Sdes			if(iq->store_parent_NS)
2295238106Sdes				iter_store_parentside_NS(qstate->env,
2296238106Sdes					iq->response->rep);
2297238106Sdes			if(qstate->env->neg_cache)
2298238106Sdes				val_neg_addreferral(qstate->env->neg_cache,
2299238106Sdes					iq->response->rep, iq->dp->name);
2300238106Sdes		}
2301238106Sdes		/* store parent-side-in-zone-glue, if directly queried for */
2302238106Sdes		if(iq->query_for_pside_glue && !iq->pside_glue) {
2303238106Sdes			iq->pside_glue = reply_find_rrset(iq->response->rep,
2304238106Sdes				iq->qchase.qname, iq->qchase.qname_len,
2305238106Sdes				iq->qchase.qtype, iq->qchase.qclass);
2306238106Sdes			if(iq->pside_glue) {
2307238106Sdes				log_rrset_key(VERB_ALGO, "found parent-side "
2308238106Sdes					"glue", iq->pside_glue);
2309238106Sdes				iter_store_parentside_rrset(qstate->env,
2310238106Sdes					iq->pside_glue);
2311238106Sdes			}
2312238106Sdes		}
2313238106Sdes
2314238106Sdes		/* Reset the event state, setting the current delegation
2315238106Sdes		 * point to the referral. */
2316238106Sdes		iq->deleg_msg = iq->response;
2317238106Sdes		iq->dp = delegpt_from_message(iq->response, qstate->region);
2318294190Sdes		if (qstate->env->cfg->qname_minimisation)
2319294190Sdes			iq->minimisation_state = INIT_MINIMISE_STATE;
2320238106Sdes		if(!iq->dp)
2321238106Sdes			return error_response(qstate, id, LDNS_RCODE_SERVFAIL);
2322238106Sdes		if(!cache_fill_missing(qstate->env, iq->qchase.qclass,
2323238106Sdes			qstate->region, iq->dp))
2324238106Sdes			return error_response(qstate, id, LDNS_RCODE_SERVFAIL);
2325238106Sdes		if(iq->store_parent_NS && query_dname_compare(iq->dp->name,
2326238106Sdes			iq->store_parent_NS->name) == 0)
2327238106Sdes			iter_merge_retry_counts(iq->dp, iq->store_parent_NS);
2328238106Sdes		delegpt_log(VERB_ALGO, iq->dp);
2329238106Sdes		/* Count this as a referral. */
2330238106Sdes		iq->referral_count++;
2331238106Sdes		iq->sent_count = 0;
2332238106Sdes		/* see if the next dp is a trust anchor, or a DS was sent
2333238106Sdes		 * along, indicating dnssec is expected for next zone */
2334238106Sdes		iq->dnssec_expected = iter_indicates_dnssec(qstate->env,
2335238106Sdes			iq->dp, iq->response, iq->qchase.qclass);
2336238106Sdes		/* if dnssec, validating then also fetch the key for the DS */
2337238106Sdes		if(iq->dnssec_expected && qstate->env->cfg->prefetch_key &&
2338238106Sdes			!(qstate->query_flags&BIT_CD))
2339238106Sdes			generate_dnskey_prefetch(qstate, iq, id);
2340238106Sdes
2341238106Sdes		/* spawn off NS and addr to auth servers for the NS we just
2342238106Sdes		 * got in the referral. This gets authoritative answer
2343238106Sdes		 * (answer section trust level) rrset.
2344238106Sdes		 * right after, we detach the subs, answer goes to cache. */
2345238106Sdes		if(qstate->env->cfg->harden_referral_path)
2346238106Sdes			generate_ns_check(qstate, iq, id);
2347238106Sdes
2348238106Sdes		/* stop current outstanding queries.
2349238106Sdes		 * FIXME: should the outstanding queries be waited for and
2350238106Sdes		 * handled? Say by a subquery that inherits the outbound_entry.
2351238106Sdes		 */
2352238106Sdes		outbound_list_clear(&iq->outlist);
2353238106Sdes		iq->num_current_queries = 0;
2354238106Sdes		fptr_ok(fptr_whitelist_modenv_detach_subs(
2355238106Sdes			qstate->env->detach_subs));
2356238106Sdes		(*qstate->env->detach_subs)(qstate);
2357238106Sdes		iq->num_target_queries = 0;
2358238106Sdes		verbose(VERB_ALGO, "cleared outbound list for next round");
2359238106Sdes		return next_state(iq, QUERYTARGETS_STATE);
2360238106Sdes	} else if(type == RESPONSE_TYPE_CNAME) {
2361238106Sdes		uint8_t* sname = NULL;
2362238106Sdes		size_t snamelen = 0;
2363238106Sdes		/* CNAME type responses get a query restart (i.e., get a
2364238106Sdes		 * reset of the query state and go back to INIT_REQUEST_STATE).
2365238106Sdes		 */
2366238106Sdes		verbose(VERB_DETAIL, "query response was CNAME");
2367238106Sdes		if(verbosity >= VERB_ALGO)
2368238106Sdes			log_dns_msg("cname msg", &iq->response->qinfo,
2369238106Sdes				iq->response->rep);
2370238106Sdes		/* if qtype is DS, check we have the right level of answer,
2371238106Sdes		 * like grandchild answer but we need the middle, reject it */
2372238106Sdes		if(iq->qchase.qtype == LDNS_RR_TYPE_DS && !iq->dsns_point
2373238106Sdes			&& !(iq->chase_flags&BIT_RD)
2374238106Sdes			&& iter_ds_toolow(iq->response, iq->dp)
2375249141Sdes			&& iter_dp_cangodown(&iq->qchase, iq->dp)) {
2376249141Sdes			outbound_list_clear(&iq->outlist);
2377249141Sdes			iq->num_current_queries = 0;
2378249141Sdes			fptr_ok(fptr_whitelist_modenv_detach_subs(
2379249141Sdes				qstate->env->detach_subs));
2380249141Sdes			(*qstate->env->detach_subs)(qstate);
2381249141Sdes			iq->num_target_queries = 0;
2382238106Sdes			return processDSNSFind(qstate, iq, id);
2383249141Sdes		}
2384238106Sdes		/* Process the CNAME response. */
2385238106Sdes		if(!handle_cname_response(qstate, iq, iq->response,
2386238106Sdes			&sname, &snamelen))
2387238106Sdes			return error_response(qstate, id, LDNS_RCODE_SERVFAIL);
2388238106Sdes		/* cache the CNAME response under the current query */
2389238106Sdes		/* NOTE : set referral=1, so that rrsets get stored but not
2390238106Sdes		 * the partial query answer (CNAME only). */
2391238106Sdes		/* prefetchleeway applied because this updates answer parts */
2392249141Sdes		iter_dns_store(qstate->env, &iq->response->qinfo,
2393238106Sdes			iq->response->rep, 1, qstate->prefetch_leeway,
2394285206Sdes			iq->dp&&iq->dp->has_parent_side_NS, NULL,
2395285206Sdes			qstate->query_flags);
2396238106Sdes		/* set the current request's qname to the new value. */
2397238106Sdes		iq->qchase.qname = sname;
2398238106Sdes		iq->qchase.qname_len = snamelen;
2399294190Sdes		if (qstate->env->cfg->qname_minimisation)
2400294190Sdes			iq->minimisation_state = INIT_MINIMISE_STATE;
2401238106Sdes		/* Clear the query state, since this is a query restart. */
2402238106Sdes		iq->deleg_msg = NULL;
2403238106Sdes		iq->dp = NULL;
2404238106Sdes		iq->dsns_point = NULL;
2405238106Sdes		/* Note the query restart. */
2406238106Sdes		iq->query_restart_count++;
2407238106Sdes		iq->sent_count = 0;
2408238106Sdes
2409238106Sdes		/* stop current outstanding queries.
2410238106Sdes		 * FIXME: should the outstanding queries be waited for and
2411238106Sdes		 * handled? Say by a subquery that inherits the outbound_entry.
2412238106Sdes		 */
2413238106Sdes		outbound_list_clear(&iq->outlist);
2414238106Sdes		iq->num_current_queries = 0;
2415238106Sdes		fptr_ok(fptr_whitelist_modenv_detach_subs(
2416238106Sdes			qstate->env->detach_subs));
2417238106Sdes		(*qstate->env->detach_subs)(qstate);
2418238106Sdes		iq->num_target_queries = 0;
2419238106Sdes		if(qstate->reply)
2420238106Sdes			sock_list_insert(&qstate->reply_origin,
2421238106Sdes				&qstate->reply->addr, qstate->reply->addrlen,
2422238106Sdes				qstate->region);
2423238106Sdes		verbose(VERB_ALGO, "cleared outbound list for query restart");
2424238106Sdes		/* go to INIT_REQUEST_STATE for new qname. */
2425238106Sdes		return next_state(iq, INIT_REQUEST_STATE);
2426238106Sdes	} else if(type == RESPONSE_TYPE_LAME) {
2427238106Sdes		/* Cache the LAMEness. */
2428238106Sdes		verbose(VERB_DETAIL, "query response was %sLAME",
2429238106Sdes			dnsseclame?"DNSSEC ":"");
2430238106Sdes		if(!dname_subdomain_c(iq->qchase.qname, iq->dp->name)) {
2431238106Sdes			log_err("mark lame: mismatch in qname and dpname");
2432238106Sdes			/* throwaway this reply below */
2433238106Sdes		} else if(qstate->reply) {
2434238106Sdes			/* need addr for lameness cache, but we may have
2435238106Sdes			 * gotten this from cache, so test to be sure */
2436238106Sdes			if(!infra_set_lame(qstate->env->infra_cache,
2437238106Sdes				&qstate->reply->addr, qstate->reply->addrlen,
2438238106Sdes				iq->dp->name, iq->dp->namelen,
2439238106Sdes				*qstate->env->now, dnsseclame, 0,
2440238106Sdes				iq->qchase.qtype))
2441238106Sdes				log_err("mark host lame: out of memory");
2442269257Sdes		}
2443238106Sdes	} else if(type == RESPONSE_TYPE_REC_LAME) {
2444238106Sdes		/* Cache the LAMEness. */
2445238106Sdes		verbose(VERB_DETAIL, "query response REC_LAME: "
2446238106Sdes			"recursive but not authoritative server");
2447238106Sdes		if(!dname_subdomain_c(iq->qchase.qname, iq->dp->name)) {
2448238106Sdes			log_err("mark rec_lame: mismatch in qname and dpname");
2449238106Sdes			/* throwaway this reply below */
2450238106Sdes		} else if(qstate->reply) {
2451238106Sdes			/* need addr for lameness cache, but we may have
2452238106Sdes			 * gotten this from cache, so test to be sure */
2453238106Sdes			verbose(VERB_DETAIL, "mark as REC_LAME");
2454238106Sdes			if(!infra_set_lame(qstate->env->infra_cache,
2455238106Sdes				&qstate->reply->addr, qstate->reply->addrlen,
2456238106Sdes				iq->dp->name, iq->dp->namelen,
2457238106Sdes				*qstate->env->now, 0, 1, iq->qchase.qtype))
2458238106Sdes				log_err("mark host lame: out of memory");
2459238106Sdes		}
2460238106Sdes	} else if(type == RESPONSE_TYPE_THROWAWAY) {
2461238106Sdes		/* LAME and THROWAWAY responses are handled the same way.
2462238106Sdes		 * In this case, the event is just sent directly back to
2463238106Sdes		 * the QUERYTARGETS_STATE without resetting anything,
2464238106Sdes		 * because, clearly, the next target must be tried. */
2465238106Sdes		verbose(VERB_DETAIL, "query response was THROWAWAY");
2466238106Sdes	} else {
2467238106Sdes		log_warn("A query response came back with an unknown type: %d",
2468238106Sdes			(int)type);
2469238106Sdes	}
2470238106Sdes
2471238106Sdes	/* LAME, THROWAWAY and "unknown" all end up here.
2472238106Sdes	 * Recycle to the QUERYTARGETS state to hopefully try a
2473238106Sdes	 * different target. */
2474294190Sdes	if (qstate->env->cfg->qname_minimisation)
2475294190Sdes		iq->minimisation_state = DONOT_MINIMISE_STATE;
2476238106Sdes	return next_state(iq, QUERYTARGETS_STATE);
2477238106Sdes}
2478238106Sdes
2479238106Sdes/**
2480285206Sdes * Return priming query results to interested super querystates.
2481238106Sdes *
2482238106Sdes * Sets the delegation point and delegation message (not nonRD queries).
2483238106Sdes * This is a callback from walk_supers.
2484238106Sdes *
2485238106Sdes * @param qstate: priming query state that finished.
2486238106Sdes * @param id: module id.
2487238106Sdes * @param forq: the qstate for which priming has been done.
2488238106Sdes */
2489238106Sdesstatic void
2490238106Sdesprime_supers(struct module_qstate* qstate, int id, struct module_qstate* forq)
2491238106Sdes{
2492238106Sdes	struct iter_qstate* foriq = (struct iter_qstate*)forq->minfo[id];
2493238106Sdes	struct delegpt* dp = NULL;
2494238106Sdes
2495238106Sdes	log_assert(qstate->is_priming || foriq->wait_priming_stub);
2496238106Sdes	log_assert(qstate->return_rcode == LDNS_RCODE_NOERROR);
2497238106Sdes	/* Convert our response to a delegation point */
2498238106Sdes	dp = delegpt_from_message(qstate->return_msg, forq->region);
2499238106Sdes	if(!dp) {
2500238106Sdes		/* if there is no convertable delegation point, then
2501238106Sdes		 * the ANSWER type was (presumably) a negative answer. */
2502238106Sdes		verbose(VERB_ALGO, "prime response was not a positive "
2503238106Sdes			"ANSWER; failing");
2504238106Sdes		foriq->dp = NULL;
2505238106Sdes		foriq->state = QUERYTARGETS_STATE;
2506238106Sdes		return;
2507238106Sdes	}
2508238106Sdes
2509238106Sdes	log_query_info(VERB_DETAIL, "priming successful for", &qstate->qinfo);
2510238106Sdes	delegpt_log(VERB_ALGO, dp);
2511238106Sdes	foriq->dp = dp;
2512238106Sdes	foriq->deleg_msg = dns_copy_msg(qstate->return_msg, forq->region);
2513238106Sdes	if(!foriq->deleg_msg) {
2514238106Sdes		log_err("copy prime response: out of memory");
2515238106Sdes		foriq->dp = NULL;
2516238106Sdes		foriq->state = QUERYTARGETS_STATE;
2517238106Sdes		return;
2518238106Sdes	}
2519238106Sdes
2520238106Sdes	/* root priming responses go to init stage 2, priming stub
2521238106Sdes	 * responses to to stage 3. */
2522238106Sdes	if(foriq->wait_priming_stub) {
2523238106Sdes		foriq->state = INIT_REQUEST_3_STATE;
2524238106Sdes		foriq->wait_priming_stub = 0;
2525238106Sdes	} else	foriq->state = INIT_REQUEST_2_STATE;
2526238106Sdes	/* because we are finished, the parent will be reactivated */
2527238106Sdes}
2528238106Sdes
2529238106Sdes/**
2530238106Sdes * This handles the response to a priming query. This is used to handle both
2531238106Sdes * root and stub priming responses. This is basically the equivalent of the
2532238106Sdes * QUERY_RESP_STATE, but will not handle CNAME responses and will treat
2533238106Sdes * REFERRALs as ANSWERS. It will also update and reactivate the originating
2534238106Sdes * event.
2535238106Sdes *
2536238106Sdes * @param qstate: query state.
2537238106Sdes * @param id: module id.
2538238106Sdes * @return true if the event needs more immediate processing, false if not.
2539238106Sdes *         This state always returns false.
2540238106Sdes */
2541238106Sdesstatic int
2542238106SdesprocessPrimeResponse(struct module_qstate* qstate, int id)
2543238106Sdes{
2544238106Sdes	struct iter_qstate* iq = (struct iter_qstate*)qstate->minfo[id];
2545238106Sdes	enum response_type type;
2546238106Sdes	iq->response->rep->flags &= ~(BIT_RD|BIT_RA); /* ignore rec-lame */
2547238106Sdes	type = response_type_from_server(
2548238106Sdes		(int)((iq->chase_flags&BIT_RD) || iq->chase_to_rd),
2549238106Sdes		iq->response, &iq->qchase, iq->dp);
2550238106Sdes	if(type == RESPONSE_TYPE_ANSWER) {
2551238106Sdes		qstate->return_rcode = LDNS_RCODE_NOERROR;
2552238106Sdes		qstate->return_msg = iq->response;
2553238106Sdes	} else {
2554238106Sdes		qstate->return_rcode = LDNS_RCODE_SERVFAIL;
2555238106Sdes		qstate->return_msg = NULL;
2556238106Sdes	}
2557238106Sdes
2558238106Sdes	/* validate the root or stub after priming (if enabled).
2559238106Sdes	 * This is the same query as the prime query, but with validation.
2560238106Sdes	 * Now that we are primed, the additional queries that validation
2561238106Sdes	 * may need can be resolved, such as DLV. */
2562238106Sdes	if(qstate->env->cfg->harden_referral_path) {
2563238106Sdes		struct module_qstate* subq = NULL;
2564238106Sdes		log_nametypeclass(VERB_ALGO, "schedule prime validation",
2565238106Sdes			qstate->qinfo.qname, qstate->qinfo.qtype,
2566238106Sdes			qstate->qinfo.qclass);
2567238106Sdes		if(!generate_sub_request(qstate->qinfo.qname,
2568238106Sdes			qstate->qinfo.qname_len, qstate->qinfo.qtype,
2569238106Sdes			qstate->qinfo.qclass, qstate, id, iq,
2570238106Sdes			INIT_REQUEST_STATE, FINISHED_STATE, &subq, 1)) {
2571238106Sdes			verbose(VERB_ALGO, "could not generate prime check");
2572238106Sdes		}
2573238106Sdes		generate_a_aaaa_check(qstate, iq, id);
2574238106Sdes	}
2575238106Sdes
2576238106Sdes	/* This event is finished. */
2577238106Sdes	qstate->ext_state[id] = module_finished;
2578238106Sdes	return 0;
2579238106Sdes}
2580238106Sdes
2581238106Sdes/**
2582238106Sdes * Do final processing on responses to target queries. Events reach this
2583238106Sdes * state after the iterative resolution algorithm terminates. This state is
2584238106Sdes * responsible for reactiving the original event, and housekeeping related
2585238106Sdes * to received target responses (caching, updating the current delegation
2586238106Sdes * point, etc).
2587238106Sdes * Callback from walk_supers for every super state that is interested in
2588238106Sdes * the results from this query.
2589238106Sdes *
2590238106Sdes * @param qstate: query state.
2591238106Sdes * @param id: module id.
2592238106Sdes * @param forq: super query state.
2593238106Sdes */
2594238106Sdesstatic void
2595238106SdesprocessTargetResponse(struct module_qstate* qstate, int id,
2596238106Sdes	struct module_qstate* forq)
2597238106Sdes{
2598238106Sdes	struct iter_qstate* iq = (struct iter_qstate*)qstate->minfo[id];
2599238106Sdes	struct iter_qstate* foriq = (struct iter_qstate*)forq->minfo[id];
2600238106Sdes	struct ub_packed_rrset_key* rrset;
2601238106Sdes	struct delegpt_ns* dpns;
2602238106Sdes	log_assert(qstate->return_rcode == LDNS_RCODE_NOERROR);
2603238106Sdes
2604238106Sdes	foriq->state = QUERYTARGETS_STATE;
2605238106Sdes	log_query_info(VERB_ALGO, "processTargetResponse", &qstate->qinfo);
2606238106Sdes	log_query_info(VERB_ALGO, "processTargetResponse super", &forq->qinfo);
2607238106Sdes
2608238106Sdes	/* check to see if parent event is still interested (in orig name).  */
2609238106Sdes	if(!foriq->dp) {
2610238106Sdes		verbose(VERB_ALGO, "subq: parent not interested, was reset");
2611238106Sdes		return; /* not interested anymore */
2612238106Sdes	}
2613238106Sdes	dpns = delegpt_find_ns(foriq->dp, qstate->qinfo.qname,
2614238106Sdes			qstate->qinfo.qname_len);
2615238106Sdes	if(!dpns) {
2616238106Sdes		/* If not interested, just stop processing this event */
2617238106Sdes		verbose(VERB_ALGO, "subq: parent not interested anymore");
2618238106Sdes		/* could be because parent was jostled out of the cache,
2619238106Sdes		   and a new identical query arrived, that does not want it*/
2620238106Sdes		return;
2621238106Sdes	}
2622238106Sdes
2623238106Sdes	/* Tell the originating event that this target query has finished
2624238106Sdes	 * (regardless if it succeeded or not). */
2625238106Sdes	foriq->num_target_queries--;
2626238106Sdes
2627238106Sdes	/* if iq->query_for_pside_glue then add the pside_glue (marked lame) */
2628238106Sdes	if(iq->pside_glue) {
2629238106Sdes		/* if the pside_glue is NULL, then it could not be found,
2630238106Sdes		 * the done_pside is already set when created and a cache
2631238106Sdes		 * entry created in processFinished so nothing to do here */
2632238106Sdes		log_rrset_key(VERB_ALGO, "add parentside glue to dp",
2633238106Sdes			iq->pside_glue);
2634238106Sdes		if(!delegpt_add_rrset(foriq->dp, forq->region,
2635238106Sdes			iq->pside_glue, 1))
2636238106Sdes			log_err("out of memory adding pside glue");
2637238106Sdes	}
2638238106Sdes
2639238106Sdes	/* This response is relevant to the current query, so we
2640238106Sdes	 * add (attempt to add, anyway) this target(s) and reactivate
2641238106Sdes	 * the original event.
2642238106Sdes	 * NOTE: we could only look for the AnswerRRset if the
2643238106Sdes	 * response type was ANSWER. */
2644238106Sdes	rrset = reply_find_answer_rrset(&iq->qchase, qstate->return_msg->rep);
2645238106Sdes	if(rrset) {
2646238106Sdes		/* if CNAMEs have been followed - add new NS to delegpt. */
2647238106Sdes		/* BTW. RFC 1918 says NS should not have got CNAMEs. Robust. */
2648238106Sdes		if(!delegpt_find_ns(foriq->dp, rrset->rk.dname,
2649238106Sdes			rrset->rk.dname_len)) {
2650238106Sdes			/* if dpns->lame then set newcname ns lame too */
2651238106Sdes			if(!delegpt_add_ns(foriq->dp, forq->region,
2652269257Sdes				rrset->rk.dname, dpns->lame))
2653238106Sdes				log_err("out of memory adding cnamed-ns");
2654238106Sdes		}
2655238106Sdes		/* if dpns->lame then set the address(es) lame too */
2656238106Sdes		if(!delegpt_add_rrset(foriq->dp, forq->region, rrset,
2657269257Sdes			dpns->lame))
2658238106Sdes			log_err("out of memory adding targets");
2659238106Sdes		verbose(VERB_ALGO, "added target response");
2660238106Sdes		delegpt_log(VERB_ALGO, foriq->dp);
2661238106Sdes	} else {
2662238106Sdes		verbose(VERB_ALGO, "iterator TargetResponse failed");
2663238106Sdes		dpns->resolved = 1; /* fail the target */
2664238106Sdes	}
2665238106Sdes}
2666238106Sdes
2667238106Sdes/**
2668238106Sdes * Process response for DS NS Find queries, that attempt to find the delegation
2669238106Sdes * point where we ask the DS query from.
2670238106Sdes *
2671238106Sdes * @param qstate: query state.
2672238106Sdes * @param id: module id.
2673238106Sdes * @param forq: super query state.
2674238106Sdes */
2675238106Sdesstatic void
2676238106SdesprocessDSNSResponse(struct module_qstate* qstate, int id,
2677238106Sdes	struct module_qstate* forq)
2678238106Sdes{
2679238106Sdes	struct iter_qstate* foriq = (struct iter_qstate*)forq->minfo[id];
2680238106Sdes
2681238106Sdes	/* if the finished (iq->response) query has no NS set: continue
2682238106Sdes	 * up to look for the right dp; nothing to change, do DPNSstate */
2683238106Sdes	if(qstate->return_rcode != LDNS_RCODE_NOERROR)
2684238106Sdes		return; /* seek further */
2685238106Sdes	/* find the NS RRset (without allowing CNAMEs) */
2686238106Sdes	if(!reply_find_rrset(qstate->return_msg->rep, qstate->qinfo.qname,
2687238106Sdes		qstate->qinfo.qname_len, LDNS_RR_TYPE_NS,
2688238106Sdes		qstate->qinfo.qclass)){
2689238106Sdes		return; /* seek further */
2690238106Sdes	}
2691238106Sdes
2692238106Sdes	/* else, store as DP and continue at querytargets */
2693238106Sdes	foriq->state = QUERYTARGETS_STATE;
2694238106Sdes	foriq->dp = delegpt_from_message(qstate->return_msg, forq->region);
2695238106Sdes	if(!foriq->dp) {
2696238106Sdes		log_err("out of memory in dsns dp alloc");
2697238106Sdes		return; /* dp==NULL in QUERYTARGETS makes SERVFAIL */
2698238106Sdes	}
2699238106Sdes	/* success, go query the querytargets in the new dp (and go down) */
2700238106Sdes}
2701238106Sdes
2702238106Sdes/**
2703238106Sdes * Process response for qclass=ANY queries for a particular class.
2704238106Sdes * Append to result or error-exit.
2705238106Sdes *
2706238106Sdes * @param qstate: query state.
2707238106Sdes * @param id: module id.
2708238106Sdes * @param forq: super query state.
2709238106Sdes */
2710238106Sdesstatic void
2711238106SdesprocessClassResponse(struct module_qstate* qstate, int id,
2712238106Sdes	struct module_qstate* forq)
2713238106Sdes{
2714238106Sdes	struct iter_qstate* foriq = (struct iter_qstate*)forq->minfo[id];
2715238106Sdes	struct dns_msg* from = qstate->return_msg;
2716238106Sdes	log_query_info(VERB_ALGO, "processClassResponse", &qstate->qinfo);
2717238106Sdes	log_query_info(VERB_ALGO, "processClassResponse super", &forq->qinfo);
2718238106Sdes	if(qstate->return_rcode != LDNS_RCODE_NOERROR) {
2719238106Sdes		/* cause servfail for qclass ANY query */
2720238106Sdes		foriq->response = NULL;
2721238106Sdes		foriq->state = FINISHED_STATE;
2722238106Sdes		return;
2723238106Sdes	}
2724238106Sdes	/* append result */
2725238106Sdes	if(!foriq->response) {
2726238106Sdes		/* allocate the response: copy RCODE, sec_state */
2727238106Sdes		foriq->response = dns_copy_msg(from, forq->region);
2728238106Sdes		if(!foriq->response) {
2729238106Sdes			log_err("malloc failed for qclass ANY response");
2730238106Sdes			foriq->state = FINISHED_STATE;
2731238106Sdes			return;
2732238106Sdes		}
2733238106Sdes		foriq->response->qinfo.qclass = forq->qinfo.qclass;
2734238106Sdes		/* qclass ANY does not receive the AA flag on replies */
2735238106Sdes		foriq->response->rep->authoritative = 0;
2736238106Sdes	} else {
2737238106Sdes		struct dns_msg* to = foriq->response;
2738238106Sdes		/* add _from_ this response _to_ existing collection */
2739238106Sdes		/* if there are records, copy RCODE */
2740238106Sdes		/* lower sec_state if this message is lower */
2741238106Sdes		if(from->rep->rrset_count != 0) {
2742238106Sdes			size_t n = from->rep->rrset_count+to->rep->rrset_count;
2743238106Sdes			struct ub_packed_rrset_key** dest, **d;
2744238106Sdes			/* copy appropriate rcode */
2745238106Sdes			to->rep->flags = from->rep->flags;
2746238106Sdes			/* copy rrsets */
2747291767Sdes			if(from->rep->rrset_count > RR_COUNT_MAX ||
2748291767Sdes				to->rep->rrset_count > RR_COUNT_MAX) {
2749291767Sdes				log_err("malloc failed (too many rrsets) in collect ANY");
2750291767Sdes				foriq->state = FINISHED_STATE;
2751291767Sdes				return; /* integer overflow protection */
2752291767Sdes			}
2753238106Sdes			dest = regional_alloc(forq->region, sizeof(dest[0])*n);
2754238106Sdes			if(!dest) {
2755238106Sdes				log_err("malloc failed in collect ANY");
2756238106Sdes				foriq->state = FINISHED_STATE;
2757238106Sdes				return;
2758238106Sdes			}
2759238106Sdes			d = dest;
2760238106Sdes			/* copy AN */
2761238106Sdes			memcpy(dest, to->rep->rrsets, to->rep->an_numrrsets
2762238106Sdes				* sizeof(dest[0]));
2763238106Sdes			dest += to->rep->an_numrrsets;
2764238106Sdes			memcpy(dest, from->rep->rrsets, from->rep->an_numrrsets
2765238106Sdes				* sizeof(dest[0]));
2766238106Sdes			dest += from->rep->an_numrrsets;
2767238106Sdes			/* copy NS */
2768238106Sdes			memcpy(dest, to->rep->rrsets+to->rep->an_numrrsets,
2769238106Sdes				to->rep->ns_numrrsets * sizeof(dest[0]));
2770238106Sdes			dest += to->rep->ns_numrrsets;
2771238106Sdes			memcpy(dest, from->rep->rrsets+from->rep->an_numrrsets,
2772238106Sdes				from->rep->ns_numrrsets * sizeof(dest[0]));
2773238106Sdes			dest += from->rep->ns_numrrsets;
2774238106Sdes			/* copy AR */
2775238106Sdes			memcpy(dest, to->rep->rrsets+to->rep->an_numrrsets+
2776238106Sdes				to->rep->ns_numrrsets,
2777238106Sdes				to->rep->ar_numrrsets * sizeof(dest[0]));
2778238106Sdes			dest += to->rep->ar_numrrsets;
2779238106Sdes			memcpy(dest, from->rep->rrsets+from->rep->an_numrrsets+
2780238106Sdes				from->rep->ns_numrrsets,
2781238106Sdes				from->rep->ar_numrrsets * sizeof(dest[0]));
2782238106Sdes			/* update counts */
2783238106Sdes			to->rep->rrsets = d;
2784238106Sdes			to->rep->an_numrrsets += from->rep->an_numrrsets;
2785238106Sdes			to->rep->ns_numrrsets += from->rep->ns_numrrsets;
2786238106Sdes			to->rep->ar_numrrsets += from->rep->ar_numrrsets;
2787238106Sdes			to->rep->rrset_count = n;
2788238106Sdes		}
2789238106Sdes		if(from->rep->security < to->rep->security) /* lowest sec */
2790238106Sdes			to->rep->security = from->rep->security;
2791238106Sdes		if(from->rep->qdcount != 0) /* insert qd if appropriate */
2792238106Sdes			to->rep->qdcount = from->rep->qdcount;
2793238106Sdes		if(from->rep->ttl < to->rep->ttl) /* use smallest TTL */
2794238106Sdes			to->rep->ttl = from->rep->ttl;
2795238106Sdes		if(from->rep->prefetch_ttl < to->rep->prefetch_ttl)
2796238106Sdes			to->rep->prefetch_ttl = from->rep->prefetch_ttl;
2797238106Sdes	}
2798238106Sdes	/* are we done? */
2799238106Sdes	foriq->num_current_queries --;
2800238106Sdes	if(foriq->num_current_queries == 0)
2801238106Sdes		foriq->state = FINISHED_STATE;
2802238106Sdes}
2803238106Sdes
2804238106Sdes/**
2805238106Sdes * Collect class ANY responses and make them into one response.  This
2806238106Sdes * state is started and it creates queries for all classes (that have
2807238106Sdes * root hints).  The answers are then collected.
2808238106Sdes *
2809238106Sdes * @param qstate: query state.
2810238106Sdes * @param id: module id.
2811238106Sdes * @return true if the event needs more immediate processing, false if not.
2812238106Sdes */
2813238106Sdesstatic int
2814238106SdesprocessCollectClass(struct module_qstate* qstate, int id)
2815238106Sdes{
2816238106Sdes	struct iter_qstate* iq = (struct iter_qstate*)qstate->minfo[id];
2817238106Sdes	struct module_qstate* subq;
2818238106Sdes	/* If qchase.qclass == 0 then send out queries for all classes.
2819238106Sdes	 * Otherwise, do nothing (wait for all answers to arrive and the
2820238106Sdes	 * processClassResponse to put them together, and that moves us
2821238106Sdes	 * towards the Finished state when done. */
2822238106Sdes	if(iq->qchase.qclass == 0) {
2823238106Sdes		uint16_t c = 0;
2824238106Sdes		iq->qchase.qclass = LDNS_RR_CLASS_ANY;
2825238106Sdes		while(iter_get_next_root(qstate->env->hints,
2826238106Sdes			qstate->env->fwds, &c)) {
2827238106Sdes			/* generate query for this class */
2828238106Sdes			log_nametypeclass(VERB_ALGO, "spawn collect query",
2829238106Sdes				qstate->qinfo.qname, qstate->qinfo.qtype, c);
2830238106Sdes			if(!generate_sub_request(qstate->qinfo.qname,
2831238106Sdes				qstate->qinfo.qname_len, qstate->qinfo.qtype,
2832238106Sdes				c, qstate, id, iq, INIT_REQUEST_STATE,
2833238106Sdes				FINISHED_STATE, &subq,
2834238106Sdes				(int)!(qstate->query_flags&BIT_CD))) {
2835238106Sdes				return error_response(qstate, id,
2836238106Sdes					LDNS_RCODE_SERVFAIL);
2837238106Sdes			}
2838238106Sdes			/* ignore subq, no special init required */
2839238106Sdes			iq->num_current_queries ++;
2840238106Sdes			if(c == 0xffff)
2841238106Sdes				break;
2842238106Sdes			else c++;
2843238106Sdes		}
2844238106Sdes		/* if no roots are configured at all, return */
2845238106Sdes		if(iq->num_current_queries == 0) {
2846238106Sdes			verbose(VERB_ALGO, "No root hints or fwds, giving up "
2847238106Sdes				"on qclass ANY");
2848238106Sdes			return error_response(qstate, id, LDNS_RCODE_REFUSED);
2849238106Sdes		}
2850238106Sdes		/* return false, wait for queries to return */
2851238106Sdes	}
2852238106Sdes	/* if woke up here because of an answer, wait for more answers */
2853238106Sdes	return 0;
2854238106Sdes}
2855238106Sdes
2856238106Sdes/**
2857238106Sdes * This handles the final state for first-tier responses (i.e., responses to
2858238106Sdes * externally generated queries).
2859238106Sdes *
2860238106Sdes * @param qstate: query state.
2861238106Sdes * @param iq: iterator query state.
2862238106Sdes * @param id: module id.
2863238106Sdes * @return true if the event needs more processing, false if not. Since this
2864238106Sdes *         is the final state for an event, it always returns false.
2865238106Sdes */
2866238106Sdesstatic int
2867238106SdesprocessFinished(struct module_qstate* qstate, struct iter_qstate* iq,
2868238106Sdes	int id)
2869238106Sdes{
2870238106Sdes	log_query_info(VERB_QUERY, "finishing processing for",
2871238106Sdes		&qstate->qinfo);
2872238106Sdes
2873238106Sdes	/* store negative cache element for parent side glue. */
2874238106Sdes	if(iq->query_for_pside_glue && !iq->pside_glue)
2875238106Sdes		iter_store_parentside_neg(qstate->env, &qstate->qinfo,
2876238106Sdes			iq->deleg_msg?iq->deleg_msg->rep:
2877238106Sdes			(iq->response?iq->response->rep:NULL));
2878238106Sdes	if(!iq->response) {
2879238106Sdes		verbose(VERB_ALGO, "No response is set, servfail");
2880238106Sdes		return error_response(qstate, id, LDNS_RCODE_SERVFAIL);
2881238106Sdes	}
2882238106Sdes
2883238106Sdes	/* Make sure that the RA flag is set (since the presence of
2884238106Sdes	 * this module means that recursion is available) */
2885238106Sdes	iq->response->rep->flags |= BIT_RA;
2886238106Sdes
2887238106Sdes	/* Clear the AA flag */
2888238106Sdes	/* FIXME: does this action go here or in some other module? */
2889238106Sdes	iq->response->rep->flags &= ~BIT_AA;
2890238106Sdes
2891238106Sdes	/* make sure QR flag is on */
2892238106Sdes	iq->response->rep->flags |= BIT_QR;
2893238106Sdes
2894238106Sdes	/* we have finished processing this query */
2895238106Sdes	qstate->ext_state[id] = module_finished;
2896238106Sdes
2897238106Sdes	/* TODO:  we are using a private TTL, trim the response. */
2898238106Sdes	/* if (mPrivateTTL > 0){IterUtils.setPrivateTTL(resp, mPrivateTTL); } */
2899238106Sdes
2900238106Sdes	/* prepend any items we have accumulated */
2901238106Sdes	if(iq->an_prepend_list || iq->ns_prepend_list) {
2902238106Sdes		if(!iter_prepend(iq, iq->response, qstate->region)) {
2903238106Sdes			log_err("prepend rrsets: out of memory");
2904238106Sdes			return error_response(qstate, id, LDNS_RCODE_SERVFAIL);
2905238106Sdes		}
2906238106Sdes		/* reset the query name back */
2907238106Sdes		iq->response->qinfo = qstate->qinfo;
2908238106Sdes		/* the security state depends on the combination */
2909238106Sdes		iq->response->rep->security = sec_status_unchecked;
2910238106Sdes		/* store message with the finished prepended items,
2911238106Sdes		 * but only if we did recursion. The nonrecursion referral
2912238106Sdes		 * from cache does not need to be stored in the msg cache. */
2913238106Sdes		if(qstate->query_flags&BIT_RD) {
2914249141Sdes			iter_dns_store(qstate->env, &qstate->qinfo,
2915238106Sdes				iq->response->rep, 0, qstate->prefetch_leeway,
2916238106Sdes				iq->dp&&iq->dp->has_parent_side_NS,
2917285206Sdes				qstate->region, qstate->query_flags);
2918238106Sdes		}
2919238106Sdes	}
2920238106Sdes	qstate->return_rcode = LDNS_RCODE_NOERROR;
2921238106Sdes	qstate->return_msg = iq->response;
2922238106Sdes	return 0;
2923238106Sdes}
2924238106Sdes
2925238106Sdes/*
2926238106Sdes * Return priming query results to interestes super querystates.
2927238106Sdes *
2928238106Sdes * Sets the delegation point and delegation message (not nonRD queries).
2929238106Sdes * This is a callback from walk_supers.
2930238106Sdes *
2931238106Sdes * @param qstate: query state that finished.
2932238106Sdes * @param id: module id.
2933238106Sdes * @param super: the qstate to inform.
2934238106Sdes */
2935238106Sdesvoid
2936238106Sdesiter_inform_super(struct module_qstate* qstate, int id,
2937238106Sdes	struct module_qstate* super)
2938238106Sdes{
2939238106Sdes	if(!qstate->is_priming && super->qinfo.qclass == LDNS_RR_CLASS_ANY)
2940238106Sdes		processClassResponse(qstate, id, super);
2941238106Sdes	else if(super->qinfo.qtype == LDNS_RR_TYPE_DS && ((struct iter_qstate*)
2942238106Sdes		super->minfo[id])->state == DSNS_FIND_STATE)
2943238106Sdes		processDSNSResponse(qstate, id, super);
2944238106Sdes	else if(qstate->return_rcode != LDNS_RCODE_NOERROR)
2945238106Sdes		error_supers(qstate, id, super);
2946238106Sdes	else if(qstate->is_priming)
2947238106Sdes		prime_supers(qstate, id, super);
2948238106Sdes	else	processTargetResponse(qstate, id, super);
2949238106Sdes}
2950238106Sdes
2951238106Sdes/**
2952238106Sdes * Handle iterator state.
2953238106Sdes * Handle events. This is the real processing loop for events, responsible
2954238106Sdes * for moving events through the various states. If a processing method
2955238106Sdes * returns true, then it will be advanced to the next state. If false, then
2956238106Sdes * processing will stop.
2957238106Sdes *
2958238106Sdes * @param qstate: query state.
2959238106Sdes * @param ie: iterator shared global environment.
2960238106Sdes * @param iq: iterator query state.
2961238106Sdes * @param id: module id.
2962238106Sdes */
2963238106Sdesstatic void
2964238106Sdesiter_handle(struct module_qstate* qstate, struct iter_qstate* iq,
2965238106Sdes	struct iter_env* ie, int id)
2966238106Sdes{
2967238106Sdes	int cont = 1;
2968238106Sdes	while(cont) {
2969238106Sdes		verbose(VERB_ALGO, "iter_handle processing q with state %s",
2970238106Sdes			iter_state_to_string(iq->state));
2971238106Sdes		switch(iq->state) {
2972238106Sdes			case INIT_REQUEST_STATE:
2973238106Sdes				cont = processInitRequest(qstate, iq, ie, id);
2974238106Sdes				break;
2975238106Sdes			case INIT_REQUEST_2_STATE:
2976238106Sdes				cont = processInitRequest2(qstate, iq, id);
2977238106Sdes				break;
2978238106Sdes			case INIT_REQUEST_3_STATE:
2979238106Sdes				cont = processInitRequest3(qstate, iq, id);
2980238106Sdes				break;
2981238106Sdes			case QUERYTARGETS_STATE:
2982238106Sdes				cont = processQueryTargets(qstate, iq, ie, id);
2983238106Sdes				break;
2984238106Sdes			case QUERY_RESP_STATE:
2985238106Sdes				cont = processQueryResponse(qstate, iq, id);
2986238106Sdes				break;
2987238106Sdes			case PRIME_RESP_STATE:
2988238106Sdes				cont = processPrimeResponse(qstate, id);
2989238106Sdes				break;
2990238106Sdes			case COLLECT_CLASS_STATE:
2991238106Sdes				cont = processCollectClass(qstate, id);
2992238106Sdes				break;
2993238106Sdes			case DSNS_FIND_STATE:
2994238106Sdes				cont = processDSNSFind(qstate, iq, id);
2995238106Sdes				break;
2996238106Sdes			case FINISHED_STATE:
2997238106Sdes				cont = processFinished(qstate, iq, id);
2998238106Sdes				break;
2999238106Sdes			default:
3000238106Sdes				log_warn("iterator: invalid state: %d",
3001238106Sdes					iq->state);
3002238106Sdes				cont = 0;
3003238106Sdes				break;
3004238106Sdes		}
3005238106Sdes	}
3006238106Sdes}
3007238106Sdes
3008238106Sdes/**
3009238106Sdes * This is the primary entry point for processing request events. Note that
3010238106Sdes * this method should only be used by external modules.
3011238106Sdes * @param qstate: query state.
3012238106Sdes * @param ie: iterator shared global environment.
3013238106Sdes * @param iq: iterator query state.
3014238106Sdes * @param id: module id.
3015238106Sdes */
3016238106Sdesstatic void
3017238106Sdesprocess_request(struct module_qstate* qstate, struct iter_qstate* iq,
3018238106Sdes	struct iter_env* ie, int id)
3019238106Sdes{
3020238106Sdes	/* external requests start in the INIT state, and finish using the
3021238106Sdes	 * FINISHED state. */
3022238106Sdes	iq->state = INIT_REQUEST_STATE;
3023238106Sdes	iq->final_state = FINISHED_STATE;
3024238106Sdes	verbose(VERB_ALGO, "process_request: new external request event");
3025238106Sdes	iter_handle(qstate, iq, ie, id);
3026238106Sdes}
3027238106Sdes
3028238106Sdes/** process authoritative server reply */
3029238106Sdesstatic void
3030238106Sdesprocess_response(struct module_qstate* qstate, struct iter_qstate* iq,
3031238106Sdes	struct iter_env* ie, int id, struct outbound_entry* outbound,
3032238106Sdes	enum module_ev event)
3033238106Sdes{
3034238106Sdes	struct msg_parse* prs;
3035238106Sdes	struct edns_data edns;
3036269257Sdes	sldns_buffer* pkt;
3037238106Sdes
3038238106Sdes	verbose(VERB_ALGO, "process_response: new external response event");
3039238106Sdes	iq->response = NULL;
3040238106Sdes	iq->state = QUERY_RESP_STATE;
3041238106Sdes	if(event == module_event_noreply || event == module_event_error) {
3042285206Sdes		if(event == module_event_noreply && iq->sent_count >= 3 &&
3043285206Sdes			qstate->env->cfg->use_caps_bits_for_id &&
3044285206Sdes			!iq->caps_fallback) {
3045285206Sdes			/* start fallback */
3046285206Sdes			iq->caps_fallback = 1;
3047285206Sdes			iq->caps_server = 0;
3048285206Sdes			iq->caps_reply = NULL;
3049291767Sdes			iq->caps_response = NULL;
3050285206Sdes			iq->state = QUERYTARGETS_STATE;
3051285206Sdes			iq->num_current_queries--;
3052285206Sdes			/* need fresh attempts for the 0x20 fallback, if
3053285206Sdes			 * that was the cause for the failure */
3054285206Sdes			iter_dec_attempts(iq->dp, 3);
3055285206Sdes			verbose(VERB_DETAIL, "Capsforid: timeouts, starting fallback");
3056285206Sdes			goto handle_it;
3057285206Sdes		}
3058238106Sdes		goto handle_it;
3059238106Sdes	}
3060238106Sdes	if( (event != module_event_reply && event != module_event_capsfail)
3061238106Sdes		|| !qstate->reply) {
3062238106Sdes		log_err("Bad event combined with response");
3063238106Sdes		outbound_list_remove(&iq->outlist, outbound);
3064238106Sdes		(void)error_response(qstate, id, LDNS_RCODE_SERVFAIL);
3065238106Sdes		return;
3066238106Sdes	}
3067238106Sdes
3068238106Sdes	/* parse message */
3069238106Sdes	prs = (struct msg_parse*)regional_alloc(qstate->env->scratch,
3070238106Sdes		sizeof(struct msg_parse));
3071238106Sdes	if(!prs) {
3072238106Sdes		log_err("out of memory on incoming message");
3073238106Sdes		/* like packet got dropped */
3074238106Sdes		goto handle_it;
3075238106Sdes	}
3076238106Sdes	memset(prs, 0, sizeof(*prs));
3077238106Sdes	memset(&edns, 0, sizeof(edns));
3078238106Sdes	pkt = qstate->reply->c->buffer;
3079269257Sdes	sldns_buffer_set_position(pkt, 0);
3080238106Sdes	if(parse_packet(pkt, prs, qstate->env->scratch) != LDNS_RCODE_NOERROR) {
3081238106Sdes		verbose(VERB_ALGO, "parse error on reply packet");
3082238106Sdes		goto handle_it;
3083238106Sdes	}
3084238106Sdes	/* edns is not examined, but removed from message to help cache */
3085238106Sdes	if(parse_extract_edns(prs, &edns) != LDNS_RCODE_NOERROR)
3086238106Sdes		goto handle_it;
3087238106Sdes	/* remove CD-bit, we asked for in case we handle validation ourself */
3088238106Sdes	prs->flags &= ~BIT_CD;
3089238106Sdes
3090238106Sdes	/* normalize and sanitize: easy to delete items from linked lists */
3091294190Sdes	if(!scrub_message(pkt, prs, &iq->qinfo_out, iq->dp->name,
3092291767Sdes		qstate->env->scratch, qstate->env, ie)) {
3093291767Sdes		/* if 0x20 enabled, start fallback, but we have no message */
3094291767Sdes		if(event == module_event_capsfail && !iq->caps_fallback) {
3095291767Sdes			iq->caps_fallback = 1;
3096291767Sdes			iq->caps_server = 0;
3097291767Sdes			iq->caps_reply = NULL;
3098291767Sdes			iq->caps_response = NULL;
3099291767Sdes			iq->state = QUERYTARGETS_STATE;
3100291767Sdes			iq->num_current_queries--;
3101291767Sdes			verbose(VERB_DETAIL, "Capsforid: scrub failed, starting fallback with no response");
3102291767Sdes		}
3103238106Sdes		goto handle_it;
3104291767Sdes	}
3105238106Sdes
3106238106Sdes	/* allocate response dns_msg in region */
3107238106Sdes	iq->response = dns_alloc_msg(pkt, prs, qstate->region);
3108238106Sdes	if(!iq->response)
3109238106Sdes		goto handle_it;
3110238106Sdes	log_query_info(VERB_DETAIL, "response for", &qstate->qinfo);
3111238106Sdes	log_name_addr(VERB_DETAIL, "reply from", iq->dp->name,
3112238106Sdes		&qstate->reply->addr, qstate->reply->addrlen);
3113238106Sdes	if(verbosity >= VERB_ALGO)
3114238106Sdes		log_dns_msg("incoming scrubbed packet:", &iq->response->qinfo,
3115238106Sdes			iq->response->rep);
3116238106Sdes
3117285206Sdes	if(event == module_event_capsfail || iq->caps_fallback) {
3118285206Sdes		/* for fallback we care about main answer, not additionals */
3119285206Sdes		/* removing that makes comparison more likely to succeed */
3120285206Sdes		caps_strip_reply(iq->response->rep);
3121238106Sdes		if(!iq->caps_fallback) {
3122238106Sdes			/* start fallback */
3123238106Sdes			iq->caps_fallback = 1;
3124238106Sdes			iq->caps_server = 0;
3125238106Sdes			iq->caps_reply = iq->response->rep;
3126291767Sdes			iq->caps_response = iq->response;
3127238106Sdes			iq->state = QUERYTARGETS_STATE;
3128238106Sdes			iq->num_current_queries--;
3129238106Sdes			verbose(VERB_DETAIL, "Capsforid: starting fallback");
3130238106Sdes			goto handle_it;
3131238106Sdes		} else {
3132238106Sdes			/* check if reply is the same, otherwise, fail */
3133285206Sdes			if(!iq->caps_reply) {
3134285206Sdes				iq->caps_reply = iq->response->rep;
3135291767Sdes				iq->caps_response = iq->response;
3136285206Sdes				iq->caps_server = -1; /*become zero at ++,
3137285206Sdes				so that we start the full set of trials */
3138291767Sdes			} else if(caps_failed_rcode(iq->caps_reply) &&
3139291767Sdes				!caps_failed_rcode(iq->response->rep)) {
3140291767Sdes				/* prefer to upgrade to non-SERVFAIL */
3141291767Sdes				iq->caps_reply = iq->response->rep;
3142291767Sdes				iq->caps_response = iq->response;
3143291767Sdes			} else if(!caps_failed_rcode(iq->caps_reply) &&
3144291767Sdes				caps_failed_rcode(iq->response->rep)) {
3145291767Sdes				/* if we have non-SERVFAIL as answer then
3146291767Sdes				 * we can ignore SERVFAILs for the equality
3147291767Sdes				 * comparison */
3148291767Sdes				/* no instructions here, skip other else */
3149291767Sdes			} else if(caps_failed_rcode(iq->caps_reply) &&
3150291767Sdes				caps_failed_rcode(iq->response->rep)) {
3151291767Sdes				/* failure is same as other failure in fallbk*/
3152291767Sdes				/* no instructions here, skip other else */
3153285206Sdes			} else if(!reply_equal(iq->response->rep, iq->caps_reply,
3154269257Sdes				qstate->env->scratch)) {
3155238106Sdes				verbose(VERB_DETAIL, "Capsforid fallback: "
3156238106Sdes					"getting different replies, failed");
3157238106Sdes				outbound_list_remove(&iq->outlist, outbound);
3158238106Sdes				(void)error_response(qstate, id,
3159238106Sdes					LDNS_RCODE_SERVFAIL);
3160238106Sdes				return;
3161238106Sdes			}
3162238106Sdes			/* continue the fallback procedure at next server */
3163238106Sdes			iq->caps_server++;
3164238106Sdes			iq->state = QUERYTARGETS_STATE;
3165238106Sdes			iq->num_current_queries--;
3166238106Sdes			verbose(VERB_DETAIL, "Capsforid: reply is equal. "
3167238106Sdes				"go to next fallback");
3168238106Sdes			goto handle_it;
3169238106Sdes		}
3170238106Sdes	}
3171238106Sdes	iq->caps_fallback = 0; /* if we were in fallback, 0x20 is OK now */
3172238106Sdes
3173238106Sdeshandle_it:
3174238106Sdes	outbound_list_remove(&iq->outlist, outbound);
3175238106Sdes	iter_handle(qstate, iq, ie, id);
3176238106Sdes}
3177238106Sdes
3178238106Sdesvoid
3179238106Sdesiter_operate(struct module_qstate* qstate, enum module_ev event, int id,
3180238106Sdes	struct outbound_entry* outbound)
3181238106Sdes{
3182238106Sdes	struct iter_env* ie = (struct iter_env*)qstate->env->modinfo[id];
3183238106Sdes	struct iter_qstate* iq = (struct iter_qstate*)qstate->minfo[id];
3184238106Sdes	verbose(VERB_QUERY, "iterator[module %d] operate: extstate:%s event:%s",
3185238106Sdes		id, strextstate(qstate->ext_state[id]), strmodulevent(event));
3186238106Sdes	if(iq) log_query_info(VERB_QUERY, "iterator operate: query",
3187238106Sdes		&qstate->qinfo);
3188238106Sdes	if(iq && qstate->qinfo.qname != iq->qchase.qname)
3189238106Sdes		log_query_info(VERB_QUERY, "iterator operate: chased to",
3190238106Sdes			&iq->qchase);
3191238106Sdes
3192238106Sdes	/* perform iterator state machine */
3193238106Sdes	if((event == module_event_new || event == module_event_pass) &&
3194238106Sdes		iq == NULL) {
3195238106Sdes		if(!iter_new(qstate, id)) {
3196238106Sdes			(void)error_response(qstate, id, LDNS_RCODE_SERVFAIL);
3197238106Sdes			return;
3198238106Sdes		}
3199238106Sdes		iq = (struct iter_qstate*)qstate->minfo[id];
3200238106Sdes		process_request(qstate, iq, ie, id);
3201238106Sdes		return;
3202238106Sdes	}
3203238106Sdes	if(iq && event == module_event_pass) {
3204238106Sdes		iter_handle(qstate, iq, ie, id);
3205238106Sdes		return;
3206238106Sdes	}
3207238106Sdes	if(iq && outbound) {
3208238106Sdes		process_response(qstate, iq, ie, id, outbound, event);
3209238106Sdes		return;
3210238106Sdes	}
3211238106Sdes	if(event == module_event_error) {
3212238106Sdes		verbose(VERB_ALGO, "got called with event error, giving up");
3213238106Sdes		(void)error_response(qstate, id, LDNS_RCODE_SERVFAIL);
3214238106Sdes		return;
3215238106Sdes	}
3216238106Sdes
3217238106Sdes	log_err("bad event for iterator");
3218238106Sdes	(void)error_response(qstate, id, LDNS_RCODE_SERVFAIL);
3219238106Sdes}
3220238106Sdes
3221238106Sdesvoid
3222238106Sdesiter_clear(struct module_qstate* qstate, int id)
3223238106Sdes{
3224238106Sdes	struct iter_qstate* iq;
3225238106Sdes	if(!qstate)
3226238106Sdes		return;
3227238106Sdes	iq = (struct iter_qstate*)qstate->minfo[id];
3228238106Sdes	if(iq) {
3229238106Sdes		outbound_list_clear(&iq->outlist);
3230275853Sdelphij		if(iq->target_count && --iq->target_count[0] == 0)
3231275853Sdelphij			free(iq->target_count);
3232238106Sdes		iq->num_current_queries = 0;
3233238106Sdes	}
3234238106Sdes	qstate->minfo[id] = NULL;
3235238106Sdes}
3236238106Sdes
3237238106Sdessize_t
3238238106Sdesiter_get_mem(struct module_env* env, int id)
3239238106Sdes{
3240238106Sdes	struct iter_env* ie = (struct iter_env*)env->modinfo[id];
3241238106Sdes	if(!ie)
3242238106Sdes		return 0;
3243238106Sdes	return sizeof(*ie) + sizeof(int)*((size_t)ie->max_dependency_depth+1)
3244238106Sdes		+ donotq_get_mem(ie->donotq) + priv_get_mem(ie->priv);
3245238106Sdes}
3246238106Sdes
3247238106Sdes/**
3248238106Sdes * The iterator function block
3249238106Sdes */
3250238106Sdesstatic struct module_func_block iter_block = {
3251238106Sdes	"iterator",
3252238106Sdes	&iter_init, &iter_deinit, &iter_operate, &iter_inform_super,
3253238106Sdes	&iter_clear, &iter_get_mem
3254238106Sdes};
3255238106Sdes
3256238106Sdesstruct module_func_block*
3257238106Sdesiter_get_funcblock(void)
3258238106Sdes{
3259238106Sdes	return &iter_block;
3260238106Sdes}
3261238106Sdes
3262238106Sdesconst char*
3263238106Sdesiter_state_to_string(enum iter_state state)
3264238106Sdes{
3265238106Sdes	switch (state)
3266238106Sdes	{
3267238106Sdes	case INIT_REQUEST_STATE :
3268238106Sdes		return "INIT REQUEST STATE";
3269238106Sdes	case INIT_REQUEST_2_STATE :
3270238106Sdes		return "INIT REQUEST STATE (stage 2)";
3271238106Sdes	case INIT_REQUEST_3_STATE:
3272238106Sdes		return "INIT REQUEST STATE (stage 3)";
3273238106Sdes	case QUERYTARGETS_STATE :
3274238106Sdes		return "QUERY TARGETS STATE";
3275238106Sdes	case PRIME_RESP_STATE :
3276238106Sdes		return "PRIME RESPONSE STATE";
3277238106Sdes	case COLLECT_CLASS_STATE :
3278238106Sdes		return "COLLECT CLASS STATE";
3279238106Sdes	case DSNS_FIND_STATE :
3280238106Sdes		return "DSNS FIND STATE";
3281238106Sdes	case QUERY_RESP_STATE :
3282238106Sdes		return "QUERY RESPONSE STATE";
3283238106Sdes	case FINISHED_STATE :
3284238106Sdes		return "FINISHED RESPONSE STATE";
3285238106Sdes	default :
3286238106Sdes		return "UNKNOWN ITER STATE";
3287238106Sdes	}
3288238106Sdes}
3289238106Sdes
3290238106Sdesint
3291238106Sdesiter_state_is_responsestate(enum iter_state s)
3292238106Sdes{
3293238106Sdes	switch(s) {
3294238106Sdes		case INIT_REQUEST_STATE :
3295238106Sdes		case INIT_REQUEST_2_STATE :
3296238106Sdes		case INIT_REQUEST_3_STATE :
3297238106Sdes		case QUERYTARGETS_STATE :
3298238106Sdes		case COLLECT_CLASS_STATE :
3299238106Sdes			return 0;
3300238106Sdes		default:
3301238106Sdes			break;
3302238106Sdes	}
3303238106Sdes	return 1;
3304238106Sdes}
3305