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"
64269257Sdes#include "ldns/rrdef.h"
65269257Sdes#include "ldns/wire2str.h"
66269257Sdes#include "ldns/parseutil.h"
67269257Sdes#include "ldns/sbuffer.h"
68238106Sdes
69238106Sdesint
70238106Sdesiter_init(struct module_env* env, int id)
71238106Sdes{
72238106Sdes	struct iter_env* iter_env = (struct iter_env*)calloc(1,
73238106Sdes		sizeof(struct iter_env));
74238106Sdes	if(!iter_env) {
75238106Sdes		log_err("malloc failure");
76238106Sdes		return 0;
77238106Sdes	}
78238106Sdes	env->modinfo[id] = (void*)iter_env;
79238106Sdes	if(!iter_apply_cfg(iter_env, env->cfg)) {
80238106Sdes		log_err("iterator: could not apply configuration settings.");
81238106Sdes		return 0;
82238106Sdes	}
83238106Sdes	return 1;
84238106Sdes}
85238106Sdes
86238106Sdesvoid
87238106Sdesiter_deinit(struct module_env* env, int id)
88238106Sdes{
89238106Sdes	struct iter_env* iter_env;
90238106Sdes	if(!env || !env->modinfo[id])
91238106Sdes		return;
92238106Sdes	iter_env = (struct iter_env*)env->modinfo[id];
93238106Sdes	free(iter_env->target_fetch_policy);
94238106Sdes	priv_delete(iter_env->priv);
95238106Sdes	donotq_delete(iter_env->donotq);
96238106Sdes	free(iter_env);
97238106Sdes	env->modinfo[id] = NULL;
98238106Sdes}
99238106Sdes
100238106Sdes/** new query for iterator */
101238106Sdesstatic int
102238106Sdesiter_new(struct module_qstate* qstate, int id)
103238106Sdes{
104238106Sdes	struct iter_qstate* iq = (struct iter_qstate*)regional_alloc(
105238106Sdes		qstate->region, sizeof(struct iter_qstate));
106238106Sdes	qstate->minfo[id] = iq;
107238106Sdes	if(!iq)
108238106Sdes		return 0;
109238106Sdes	memset(iq, 0, sizeof(*iq));
110238106Sdes	iq->state = INIT_REQUEST_STATE;
111238106Sdes	iq->final_state = FINISHED_STATE;
112238106Sdes	iq->an_prepend_list = NULL;
113238106Sdes	iq->an_prepend_last = NULL;
114238106Sdes	iq->ns_prepend_list = NULL;
115238106Sdes	iq->ns_prepend_last = NULL;
116238106Sdes	iq->dp = NULL;
117238106Sdes	iq->depth = 0;
118238106Sdes	iq->num_target_queries = 0;
119238106Sdes	iq->num_current_queries = 0;
120238106Sdes	iq->query_restart_count = 0;
121238106Sdes	iq->referral_count = 0;
122238106Sdes	iq->sent_count = 0;
123275854Sdelphij	iq->target_count = NULL;
124238106Sdes	iq->wait_priming_stub = 0;
125238106Sdes	iq->refetch_glue = 0;
126238106Sdes	iq->dnssec_expected = 0;
127238106Sdes	iq->dnssec_lame_query = 0;
128238106Sdes	iq->chase_flags = qstate->query_flags;
129238106Sdes	/* Start with the (current) qname. */
130238106Sdes	iq->qchase = qstate->qinfo;
131238106Sdes	outbound_list_init(&iq->outlist);
132238106Sdes	return 1;
133238106Sdes}
134238106Sdes
135238106Sdes/**
136238106Sdes * Transition to the next state. This can be used to advance a currently
137238106Sdes * processing event. It cannot be used to reactivate a forEvent.
138238106Sdes *
139238106Sdes * @param iq: iterator query state
140238106Sdes * @param nextstate The state to transition to.
141238106Sdes * @return true. This is so this can be called as the return value for the
142238106Sdes *         actual process*State() methods. (Transitioning to the next state
143238106Sdes *         implies further processing).
144238106Sdes */
145238106Sdesstatic int
146238106Sdesnext_state(struct iter_qstate* iq, enum iter_state nextstate)
147238106Sdes{
148238106Sdes	/* If transitioning to a "response" state, make sure that there is a
149238106Sdes	 * response */
150238106Sdes	if(iter_state_is_responsestate(nextstate)) {
151238106Sdes		if(iq->response == NULL) {
152238106Sdes			log_err("transitioning to response state sans "
153238106Sdes				"response.");
154238106Sdes		}
155238106Sdes	}
156238106Sdes	iq->state = nextstate;
157238106Sdes	return 1;
158238106Sdes}
159238106Sdes
160238106Sdes/**
161238106Sdes * Transition an event to its final state. Final states always either return
162238106Sdes * a result up the module chain, or reactivate a dependent event. Which
163238106Sdes * final state to transtion to is set in the module state for the event when
164238106Sdes * it was created, and depends on the original purpose of the event.
165238106Sdes *
166238106Sdes * The response is stored in the qstate->buf buffer.
167238106Sdes *
168238106Sdes * @param iq: iterator query state
169238106Sdes * @return false. This is so this method can be used as the return value for
170238106Sdes *         the processState methods. (Transitioning to the final state
171238106Sdes */
172238106Sdesstatic int
173238106Sdesfinal_state(struct iter_qstate* iq)
174238106Sdes{
175238106Sdes	return next_state(iq, iq->final_state);
176238106Sdes}
177238106Sdes
178238106Sdes/**
179238106Sdes * Callback routine to handle errors in parent query states
180238106Sdes * @param qstate: query state that failed.
181238106Sdes * @param id: module id.
182238106Sdes * @param super: super state.
183238106Sdes */
184238106Sdesstatic void
185238106Sdeserror_supers(struct module_qstate* qstate, int id, struct module_qstate* super)
186238106Sdes{
187238106Sdes	struct iter_qstate* super_iq = (struct iter_qstate*)super->minfo[id];
188238106Sdes
189238106Sdes	if(qstate->qinfo.qtype == LDNS_RR_TYPE_A ||
190238106Sdes		qstate->qinfo.qtype == LDNS_RR_TYPE_AAAA) {
191238106Sdes		/* mark address as failed. */
192238106Sdes		struct delegpt_ns* dpns = NULL;
193238106Sdes		if(super_iq->dp)
194238106Sdes			dpns = delegpt_find_ns(super_iq->dp,
195238106Sdes				qstate->qinfo.qname, qstate->qinfo.qname_len);
196238106Sdes		if(!dpns) {
197238106Sdes			/* not interested */
198238106Sdes			verbose(VERB_ALGO, "subq error, but not interested");
199238106Sdes			log_query_info(VERB_ALGO, "superq", &super->qinfo);
200238106Sdes			if(super_iq->dp)
201238106Sdes				delegpt_log(VERB_ALGO, super_iq->dp);
202238106Sdes			log_assert(0);
203238106Sdes			return;
204238106Sdes		} else {
205238106Sdes			/* see if the failure did get (parent-lame) info */
206238106Sdes			if(!cache_fill_missing(super->env,
207238106Sdes				super_iq->qchase.qclass, super->region,
208238106Sdes				super_iq->dp))
209238106Sdes				log_err("out of memory adding missing");
210238106Sdes		}
211238106Sdes		dpns->resolved = 1; /* mark as failed */
212238106Sdes		super_iq->num_target_queries--;
213238106Sdes	}
214238106Sdes	if(qstate->qinfo.qtype == LDNS_RR_TYPE_NS) {
215238106Sdes		/* prime failed to get delegation */
216238106Sdes		super_iq->dp = NULL;
217238106Sdes	}
218238106Sdes	/* evaluate targets again */
219238106Sdes	super_iq->state = QUERYTARGETS_STATE;
220238106Sdes	/* super becomes runnable, and will process this change */
221238106Sdes}
222238106Sdes
223238106Sdes/**
224238106Sdes * Return an error to the client
225238106Sdes * @param qstate: our query state
226238106Sdes * @param id: module id
227238106Sdes * @param rcode: error code (DNS errcode).
228238106Sdes * @return: 0 for use by caller, to make notation easy, like:
229238106Sdes * 	return error_response(..).
230238106Sdes */
231238106Sdesstatic int
232238106Sdeserror_response(struct module_qstate* qstate, int id, int rcode)
233238106Sdes{
234238106Sdes	verbose(VERB_QUERY, "return error response %s",
235269257Sdes		sldns_lookup_by_id(sldns_rcodes, rcode)?
236269257Sdes		sldns_lookup_by_id(sldns_rcodes, rcode)->name:"??");
237238106Sdes	qstate->return_rcode = rcode;
238238106Sdes	qstate->return_msg = NULL;
239238106Sdes	qstate->ext_state[id] = module_finished;
240238106Sdes	return 0;
241238106Sdes}
242238106Sdes
243238106Sdes/**
244238106Sdes * Return an error to the client and cache the error code in the
245238106Sdes * message cache (so per qname, qtype, qclass).
246238106Sdes * @param qstate: our query state
247238106Sdes * @param id: module id
248238106Sdes * @param rcode: error code (DNS errcode).
249238106Sdes * @return: 0 for use by caller, to make notation easy, like:
250238106Sdes * 	return error_response(..).
251238106Sdes */
252238106Sdesstatic int
253238106Sdeserror_response_cache(struct module_qstate* qstate, int id, int rcode)
254238106Sdes{
255238106Sdes	/* store in cache */
256238106Sdes	struct reply_info err;
257238106Sdes	memset(&err, 0, sizeof(err));
258238106Sdes	err.flags = (uint16_t)(BIT_QR | BIT_RA);
259238106Sdes	FLAGS_SET_RCODE(err.flags, rcode);
260238106Sdes	err.qdcount = 1;
261238106Sdes	err.ttl = NORR_TTL;
262238106Sdes	err.prefetch_ttl = PREFETCH_TTL_CALC(err.ttl);
263238106Sdes	/* do not waste time trying to validate this servfail */
264238106Sdes	err.security = sec_status_indeterminate;
265238106Sdes	verbose(VERB_ALGO, "store error response in message cache");
266249141Sdes	iter_dns_store(qstate->env, &qstate->qinfo, &err, 0, 0, 0, NULL);
267238106Sdes	return error_response(qstate, id, rcode);
268238106Sdes}
269238106Sdes
270238106Sdes/** check if prepend item is duplicate item */
271238106Sdesstatic int
272238106Sdesprepend_is_duplicate(struct ub_packed_rrset_key** sets, size_t to,
273238106Sdes	struct ub_packed_rrset_key* dup)
274238106Sdes{
275238106Sdes	size_t i;
276238106Sdes	for(i=0; i<to; i++) {
277238106Sdes		if(sets[i]->rk.type == dup->rk.type &&
278238106Sdes			sets[i]->rk.rrset_class == dup->rk.rrset_class &&
279238106Sdes			sets[i]->rk.dname_len == dup->rk.dname_len &&
280238106Sdes			query_dname_compare(sets[i]->rk.dname, dup->rk.dname)
281238106Sdes			== 0)
282238106Sdes			return 1;
283238106Sdes	}
284238106Sdes	return 0;
285238106Sdes}
286238106Sdes
287238106Sdes/** prepend the prepend list in the answer and authority section of dns_msg */
288238106Sdesstatic int
289238106Sdesiter_prepend(struct iter_qstate* iq, struct dns_msg* msg,
290238106Sdes	struct regional* region)
291238106Sdes{
292238106Sdes	struct iter_prep_list* p;
293238106Sdes	struct ub_packed_rrset_key** sets;
294238106Sdes	size_t num_an = 0, num_ns = 0;;
295238106Sdes	for(p = iq->an_prepend_list; p; p = p->next)
296238106Sdes		num_an++;
297238106Sdes	for(p = iq->ns_prepend_list; p; p = p->next)
298238106Sdes		num_ns++;
299238106Sdes	if(num_an + num_ns == 0)
300238106Sdes		return 1;
301238106Sdes	verbose(VERB_ALGO, "prepending %d rrsets", (int)num_an + (int)num_ns);
302238106Sdes	sets = regional_alloc(region, (num_an+num_ns+msg->rep->rrset_count) *
303238106Sdes		sizeof(struct ub_packed_rrset_key*));
304238106Sdes	if(!sets)
305238106Sdes		return 0;
306238106Sdes	/* ANSWER section */
307238106Sdes	num_an = 0;
308238106Sdes	for(p = iq->an_prepend_list; p; p = p->next) {
309238106Sdes		sets[num_an++] = p->rrset;
310238106Sdes	}
311238106Sdes	memcpy(sets+num_an, msg->rep->rrsets, msg->rep->an_numrrsets *
312238106Sdes		sizeof(struct ub_packed_rrset_key*));
313238106Sdes	/* AUTH section */
314238106Sdes	num_ns = 0;
315238106Sdes	for(p = iq->ns_prepend_list; p; p = p->next) {
316238106Sdes		if(prepend_is_duplicate(sets+msg->rep->an_numrrsets+num_an,
317238106Sdes			num_ns, p->rrset) || prepend_is_duplicate(
318238106Sdes			msg->rep->rrsets+msg->rep->an_numrrsets,
319238106Sdes			msg->rep->ns_numrrsets, p->rrset))
320238106Sdes			continue;
321238106Sdes		sets[msg->rep->an_numrrsets + num_an + num_ns++] = p->rrset;
322238106Sdes	}
323238106Sdes	memcpy(sets + num_an + msg->rep->an_numrrsets + num_ns,
324238106Sdes		msg->rep->rrsets + msg->rep->an_numrrsets,
325238106Sdes		(msg->rep->ns_numrrsets + msg->rep->ar_numrrsets) *
326238106Sdes		sizeof(struct ub_packed_rrset_key*));
327238106Sdes
328238106Sdes	/* NXDOMAIN rcode can stay if we prepended DNAME/CNAMEs, because
329238106Sdes	 * this is what recursors should give. */
330238106Sdes	msg->rep->rrset_count += num_an + num_ns;
331238106Sdes	msg->rep->an_numrrsets += num_an;
332238106Sdes	msg->rep->ns_numrrsets += num_ns;
333238106Sdes	msg->rep->rrsets = sets;
334238106Sdes	return 1;
335238106Sdes}
336238106Sdes
337238106Sdes/**
338238106Sdes * Add rrset to ANSWER prepend list
339238106Sdes * @param qstate: query state.
340238106Sdes * @param iq: iterator query state.
341238106Sdes * @param rrset: rrset to add.
342238106Sdes * @return false on failure (malloc).
343238106Sdes */
344238106Sdesstatic int
345238106Sdesiter_add_prepend_answer(struct module_qstate* qstate, struct iter_qstate* iq,
346238106Sdes	struct ub_packed_rrset_key* rrset)
347238106Sdes{
348238106Sdes	struct iter_prep_list* p = (struct iter_prep_list*)regional_alloc(
349238106Sdes		qstate->region, sizeof(struct iter_prep_list));
350238106Sdes	if(!p)
351238106Sdes		return 0;
352238106Sdes	p->rrset = rrset;
353238106Sdes	p->next = NULL;
354238106Sdes	/* add at end */
355238106Sdes	if(iq->an_prepend_last)
356238106Sdes		iq->an_prepend_last->next = p;
357238106Sdes	else	iq->an_prepend_list = p;
358238106Sdes	iq->an_prepend_last = p;
359238106Sdes	return 1;
360238106Sdes}
361238106Sdes
362238106Sdes/**
363238106Sdes * Add rrset to AUTHORITY prepend list
364238106Sdes * @param qstate: query state.
365238106Sdes * @param iq: iterator query state.
366238106Sdes * @param rrset: rrset to add.
367238106Sdes * @return false on failure (malloc).
368238106Sdes */
369238106Sdesstatic int
370238106Sdesiter_add_prepend_auth(struct module_qstate* qstate, struct iter_qstate* iq,
371238106Sdes	struct ub_packed_rrset_key* rrset)
372238106Sdes{
373238106Sdes	struct iter_prep_list* p = (struct iter_prep_list*)regional_alloc(
374238106Sdes		qstate->region, sizeof(struct iter_prep_list));
375238106Sdes	if(!p)
376238106Sdes		return 0;
377238106Sdes	p->rrset = rrset;
378238106Sdes	p->next = NULL;
379238106Sdes	/* add at end */
380238106Sdes	if(iq->ns_prepend_last)
381238106Sdes		iq->ns_prepend_last->next = p;
382238106Sdes	else	iq->ns_prepend_list = p;
383238106Sdes	iq->ns_prepend_last = p;
384238106Sdes	return 1;
385238106Sdes}
386238106Sdes
387238106Sdes/**
388238106Sdes * Given a CNAME response (defined as a response containing a CNAME or DNAME
389238106Sdes * that does not answer the request), process the response, modifying the
390238106Sdes * state as necessary. This follows the CNAME/DNAME chain and returns the
391238106Sdes * final query name.
392238106Sdes *
393238106Sdes * sets the new query name, after following the CNAME/DNAME chain.
394238106Sdes * @param qstate: query state.
395238106Sdes * @param iq: iterator query state.
396238106Sdes * @param msg: the response.
397238106Sdes * @param mname: returned target new query name.
398238106Sdes * @param mname_len: length of mname.
399238106Sdes * @return false on (malloc) error.
400238106Sdes */
401238106Sdesstatic int
402238106Sdeshandle_cname_response(struct module_qstate* qstate, struct iter_qstate* iq,
403238106Sdes        struct dns_msg* msg, uint8_t** mname, size_t* mname_len)
404238106Sdes{
405238106Sdes	size_t i;
406238106Sdes	/* Start with the (current) qname. */
407238106Sdes	*mname = iq->qchase.qname;
408238106Sdes	*mname_len = iq->qchase.qname_len;
409238106Sdes
410238106Sdes	/* Iterate over the ANSWER rrsets in order, looking for CNAMEs and
411238106Sdes	 * DNAMES. */
412238106Sdes	for(i=0; i<msg->rep->an_numrrsets; i++) {
413238106Sdes		struct ub_packed_rrset_key* r = msg->rep->rrsets[i];
414238106Sdes		/* If there is a (relevant) DNAME, add it to the list.
415238106Sdes		 * We always expect there to be CNAME that was generated
416238106Sdes		 * by this DNAME following, so we don't process the DNAME
417238106Sdes		 * directly.  */
418238106Sdes		if(ntohs(r->rk.type) == LDNS_RR_TYPE_DNAME &&
419238106Sdes			dname_strict_subdomain_c(*mname, r->rk.dname)) {
420238106Sdes			if(!iter_add_prepend_answer(qstate, iq, r))
421238106Sdes				return 0;
422238106Sdes			continue;
423238106Sdes		}
424238106Sdes
425238106Sdes		if(ntohs(r->rk.type) == LDNS_RR_TYPE_CNAME &&
426238106Sdes			query_dname_compare(*mname, r->rk.dname) == 0) {
427238106Sdes			/* Add this relevant CNAME rrset to the prepend list.*/
428238106Sdes			if(!iter_add_prepend_answer(qstate, iq, r))
429238106Sdes				return 0;
430238106Sdes			get_cname_target(r, mname, mname_len);
431238106Sdes		}
432238106Sdes
433238106Sdes		/* Other rrsets in the section are ignored. */
434238106Sdes	}
435238106Sdes	/* add authority rrsets to authority prepend, for wildcarded CNAMEs */
436238106Sdes	for(i=msg->rep->an_numrrsets; i<msg->rep->an_numrrsets +
437238106Sdes		msg->rep->ns_numrrsets; i++) {
438238106Sdes		struct ub_packed_rrset_key* r = msg->rep->rrsets[i];
439238106Sdes		/* only add NSEC/NSEC3, as they may be needed for validation */
440238106Sdes		if(ntohs(r->rk.type) == LDNS_RR_TYPE_NSEC ||
441238106Sdes			ntohs(r->rk.type) == LDNS_RR_TYPE_NSEC3) {
442238106Sdes			if(!iter_add_prepend_auth(qstate, iq, r))
443238106Sdes				return 0;
444238106Sdes		}
445238106Sdes	}
446238106Sdes	return 1;
447238106Sdes}
448238106Sdes
449275854Sdelphij/** create target count structure for this query */
450275854Sdelphijstatic void
451275854Sdelphijtarget_count_create(struct iter_qstate* iq)
452275854Sdelphij{
453275854Sdelphij	if(!iq->target_count) {
454275854Sdelphij		iq->target_count = (int*)calloc(2, sizeof(int));
455275854Sdelphij		/* if calloc fails we simply do not track this number */
456275854Sdelphij		if(iq->target_count)
457275854Sdelphij			iq->target_count[0] = 1;
458275854Sdelphij	}
459275854Sdelphij}
460275854Sdelphij
461275854Sdelphijstatic void
462275854Sdelphijtarget_count_increase(struct iter_qstate* iq, int num)
463275854Sdelphij{
464275854Sdelphij	target_count_create(iq);
465275854Sdelphij	if(iq->target_count)
466275854Sdelphij		iq->target_count[1] += num;
467275854Sdelphij}
468275854Sdelphij
469238106Sdes/**
470238106Sdes * Generate a subrequest.
471238106Sdes * Generate a local request event. Local events are tied to this module, and
472238106Sdes * have a correponding (first tier) event that is waiting for this event to
473238106Sdes * resolve to continue.
474238106Sdes *
475238106Sdes * @param qname The query name for this request.
476238106Sdes * @param qnamelen length of qname
477238106Sdes * @param qtype The query type for this request.
478238106Sdes * @param qclass The query class for this request.
479238106Sdes * @param qstate The event that is generating this event.
480238106Sdes * @param id: module id.
481238106Sdes * @param iq: The iterator state that is generating this event.
482238106Sdes * @param initial_state The initial response state (normally this
483238106Sdes *          is QUERY_RESP_STATE, unless it is known that the request won't
484238106Sdes *          need iterative processing
485238106Sdes * @param finalstate The final state for the response to this request.
486238106Sdes * @param subq_ret: if newly allocated, the subquerystate, or NULL if it does
487238106Sdes * 	not need initialisation.
488238106Sdes * @param v: if true, validation is done on the subquery.
489238106Sdes * @return false on error (malloc).
490238106Sdes */
491238106Sdesstatic int
492238106Sdesgenerate_sub_request(uint8_t* qname, size_t qnamelen, uint16_t qtype,
493238106Sdes	uint16_t qclass, struct module_qstate* qstate, int id,
494238106Sdes	struct iter_qstate* iq, enum iter_state initial_state,
495238106Sdes	enum iter_state finalstate, struct module_qstate** subq_ret, int v)
496238106Sdes{
497238106Sdes	struct module_qstate* subq = NULL;
498238106Sdes	struct iter_qstate* subiq = NULL;
499238106Sdes	uint16_t qflags = 0; /* OPCODE QUERY, no flags */
500238106Sdes	struct query_info qinf;
501238106Sdes	int prime = (finalstate == PRIME_RESP_STATE)?1:0;
502238106Sdes	qinf.qname = qname;
503238106Sdes	qinf.qname_len = qnamelen;
504238106Sdes	qinf.qtype = qtype;
505238106Sdes	qinf.qclass = qclass;
506238106Sdes
507238106Sdes	/* RD should be set only when sending the query back through the INIT
508238106Sdes	 * state. */
509238106Sdes	if(initial_state == INIT_REQUEST_STATE)
510238106Sdes		qflags |= BIT_RD;
511238106Sdes	/* We set the CD flag so we can send this through the "head" of
512238106Sdes	 * the resolution chain, which might have a validator. We are
513238106Sdes	 * uninterested in validating things not on the direct resolution
514238106Sdes	 * path.  */
515238106Sdes	if(!v)
516238106Sdes		qflags |= BIT_CD;
517238106Sdes
518238106Sdes	/* attach subquery, lookup existing or make a new one */
519238106Sdes	fptr_ok(fptr_whitelist_modenv_attach_sub(qstate->env->attach_sub));
520238106Sdes	if(!(*qstate->env->attach_sub)(qstate, &qinf, qflags, prime, &subq)) {
521238106Sdes		return 0;
522238106Sdes	}
523238106Sdes	*subq_ret = subq;
524238106Sdes	if(subq) {
525238106Sdes		/* initialise the new subquery */
526238106Sdes		subq->curmod = id;
527238106Sdes		subq->ext_state[id] = module_state_initial;
528238106Sdes		subq->minfo[id] = regional_alloc(subq->region,
529238106Sdes			sizeof(struct iter_qstate));
530238106Sdes		if(!subq->minfo[id]) {
531238106Sdes			log_err("init subq: out of memory");
532238106Sdes			fptr_ok(fptr_whitelist_modenv_kill_sub(
533238106Sdes				qstate->env->kill_sub));
534238106Sdes			(*qstate->env->kill_sub)(subq);
535238106Sdes			return 0;
536238106Sdes		}
537238106Sdes		subiq = (struct iter_qstate*)subq->minfo[id];
538238106Sdes		memset(subiq, 0, sizeof(*subiq));
539238106Sdes		subiq->num_target_queries = 0;
540275854Sdelphij		target_count_create(iq);
541275854Sdelphij		subiq->target_count = iq->target_count;
542275854Sdelphij		if(iq->target_count)
543275854Sdelphij			iq->target_count[0] ++; /* extra reference */
544238106Sdes		subiq->num_current_queries = 0;
545238106Sdes		subiq->depth = iq->depth+1;
546238106Sdes		outbound_list_init(&subiq->outlist);
547238106Sdes		subiq->state = initial_state;
548238106Sdes		subiq->final_state = finalstate;
549238106Sdes		subiq->qchase = subq->qinfo;
550238106Sdes		subiq->chase_flags = subq->query_flags;
551238106Sdes		subiq->refetch_glue = 0;
552238106Sdes	}
553238106Sdes	return 1;
554238106Sdes}
555238106Sdes
556238106Sdes/**
557238106Sdes * Generate and send a root priming request.
558238106Sdes * @param qstate: the qtstate that triggered the need to prime.
559238106Sdes * @param iq: iterator query state.
560238106Sdes * @param id: module id.
561238106Sdes * @param qclass: the class to prime.
562238106Sdes * @return 0 on failure
563238106Sdes */
564238106Sdesstatic int
565238106Sdesprime_root(struct module_qstate* qstate, struct iter_qstate* iq, int id,
566238106Sdes	uint16_t qclass)
567238106Sdes{
568238106Sdes	struct delegpt* dp;
569238106Sdes	struct module_qstate* subq;
570238106Sdes	verbose(VERB_DETAIL, "priming . %s NS",
571269257Sdes		sldns_lookup_by_id(sldns_rr_classes, (int)qclass)?
572269257Sdes		sldns_lookup_by_id(sldns_rr_classes, (int)qclass)->name:"??");
573238106Sdes	dp = hints_lookup_root(qstate->env->hints, qclass);
574238106Sdes	if(!dp) {
575238106Sdes		verbose(VERB_ALGO, "Cannot prime due to lack of hints");
576238106Sdes		return 0;
577238106Sdes	}
578238106Sdes	/* Priming requests start at the QUERYTARGETS state, skipping
579238106Sdes	 * the normal INIT state logic (which would cause an infloop). */
580238106Sdes	if(!generate_sub_request((uint8_t*)"\000", 1, LDNS_RR_TYPE_NS,
581238106Sdes		qclass, qstate, id, iq, QUERYTARGETS_STATE, PRIME_RESP_STATE,
582238106Sdes		&subq, 0)) {
583238106Sdes		verbose(VERB_ALGO, "could not prime root");
584238106Sdes		return 0;
585238106Sdes	}
586238106Sdes	if(subq) {
587238106Sdes		struct iter_qstate* subiq =
588238106Sdes			(struct iter_qstate*)subq->minfo[id];
589238106Sdes		/* Set the initial delegation point to the hint.
590238106Sdes		 * copy dp, it is now part of the root prime query.
591238106Sdes		 * dp was part of in the fixed hints structure. */
592238106Sdes		subiq->dp = delegpt_copy(dp, subq->region);
593238106Sdes		if(!subiq->dp) {
594238106Sdes			log_err("out of memory priming root, copydp");
595238106Sdes			fptr_ok(fptr_whitelist_modenv_kill_sub(
596238106Sdes				qstate->env->kill_sub));
597238106Sdes			(*qstate->env->kill_sub)(subq);
598238106Sdes			return 0;
599238106Sdes		}
600238106Sdes		/* there should not be any target queries. */
601238106Sdes		subiq->num_target_queries = 0;
602238106Sdes		subiq->dnssec_expected = iter_indicates_dnssec(
603238106Sdes			qstate->env, subiq->dp, NULL, subq->qinfo.qclass);
604238106Sdes	}
605238106Sdes
606238106Sdes	/* this module stops, our submodule starts, and does the query. */
607238106Sdes	qstate->ext_state[id] = module_wait_subquery;
608238106Sdes	return 1;
609238106Sdes}
610238106Sdes
611238106Sdes/**
612238106Sdes * Generate and process a stub priming request. This method tests for the
613238106Sdes * need to prime a stub zone, so it is safe to call for every request.
614238106Sdes *
615238106Sdes * @param qstate: the qtstate that triggered the need to prime.
616238106Sdes * @param iq: iterator query state.
617238106Sdes * @param id: module id.
618238106Sdes * @param qname: request name.
619238106Sdes * @param qclass: request class.
620238106Sdes * @return true if a priming subrequest was made, false if not. The will only
621238106Sdes *         issue a priming request if it detects an unprimed stub.
622238106Sdes *         Uses value of 2 to signal during stub-prime in root-prime situation
623238106Sdes *         that a noprime-stub is available and resolution can continue.
624238106Sdes */
625238106Sdesstatic int
626238106Sdesprime_stub(struct module_qstate* qstate, struct iter_qstate* iq, int id,
627238106Sdes	uint8_t* qname, uint16_t qclass)
628238106Sdes{
629238106Sdes	/* Lookup the stub hint. This will return null if the stub doesn't
630238106Sdes	 * need to be re-primed. */
631238106Sdes	struct iter_hints_stub* stub;
632238106Sdes	struct delegpt* stub_dp;
633238106Sdes	struct module_qstate* subq;
634238106Sdes
635238106Sdes	if(!qname) return 0;
636238106Sdes	stub = hints_lookup_stub(qstate->env->hints, qname, qclass, iq->dp);
637238106Sdes	/* The stub (if there is one) does not need priming. */
638238106Sdes	if(!stub)
639238106Sdes		return 0;
640238106Sdes	stub_dp = stub->dp;
641238106Sdes
642238106Sdes	/* is it a noprime stub (always use) */
643238106Sdes	if(stub->noprime) {
644238106Sdes		int r = 0;
645238106Sdes		if(iq->dp == NULL) r = 2;
646238106Sdes		/* copy the dp out of the fixed hints structure, so that
647238106Sdes		 * it can be changed when servicing this query */
648238106Sdes		iq->dp = delegpt_copy(stub_dp, qstate->region);
649238106Sdes		if(!iq->dp) {
650238106Sdes			log_err("out of memory priming stub");
651238106Sdes			(void)error_response(qstate, id, LDNS_RCODE_SERVFAIL);
652238106Sdes			return 1; /* return 1 to make module stop, with error */
653238106Sdes		}
654238106Sdes		log_nametypeclass(VERB_DETAIL, "use stub", stub_dp->name,
655238106Sdes			LDNS_RR_TYPE_NS, qclass);
656238106Sdes		return r;
657238106Sdes	}
658238106Sdes
659238106Sdes	/* Otherwise, we need to (re)prime the stub. */
660238106Sdes	log_nametypeclass(VERB_DETAIL, "priming stub", stub_dp->name,
661238106Sdes		LDNS_RR_TYPE_NS, qclass);
662238106Sdes
663238106Sdes	/* Stub priming events start at the QUERYTARGETS state to avoid the
664238106Sdes	 * redundant INIT state processing. */
665238106Sdes	if(!generate_sub_request(stub_dp->name, stub_dp->namelen,
666238106Sdes		LDNS_RR_TYPE_NS, qclass, qstate, id, iq,
667238106Sdes		QUERYTARGETS_STATE, PRIME_RESP_STATE, &subq, 0)) {
668238106Sdes		verbose(VERB_ALGO, "could not prime stub");
669238106Sdes		(void)error_response(qstate, id, LDNS_RCODE_SERVFAIL);
670238106Sdes		return 1; /* return 1 to make module stop, with error */
671238106Sdes	}
672238106Sdes	if(subq) {
673238106Sdes		struct iter_qstate* subiq =
674238106Sdes			(struct iter_qstate*)subq->minfo[id];
675238106Sdes
676238106Sdes		/* Set the initial delegation point to the hint. */
677238106Sdes		/* make copy to avoid use of stub dp by different qs/threads */
678238106Sdes		subiq->dp = delegpt_copy(stub_dp, subq->region);
679238106Sdes		if(!subiq->dp) {
680238106Sdes			log_err("out of memory priming stub, copydp");
681238106Sdes			fptr_ok(fptr_whitelist_modenv_kill_sub(
682238106Sdes				qstate->env->kill_sub));
683238106Sdes			(*qstate->env->kill_sub)(subq);
684238106Sdes			(void)error_response(qstate, id, LDNS_RCODE_SERVFAIL);
685238106Sdes			return 1; /* return 1 to make module stop, with error */
686238106Sdes		}
687238106Sdes		/* there should not be any target queries -- although there
688238106Sdes		 * wouldn't be anyway, since stub hints never have
689238106Sdes		 * missing targets. */
690238106Sdes		subiq->num_target_queries = 0;
691238106Sdes		subiq->wait_priming_stub = 1;
692238106Sdes		subiq->dnssec_expected = iter_indicates_dnssec(
693238106Sdes			qstate->env, subiq->dp, NULL, subq->qinfo.qclass);
694238106Sdes	}
695238106Sdes
696238106Sdes	/* this module stops, our submodule starts, and does the query. */
697238106Sdes	qstate->ext_state[id] = module_wait_subquery;
698238106Sdes	return 1;
699238106Sdes}
700238106Sdes
701238106Sdes/**
702238106Sdes * Generate A and AAAA checks for glue that is in-zone for the referral
703238106Sdes * we just got to obtain authoritative information on the adresses.
704238106Sdes *
705238106Sdes * @param qstate: the qtstate that triggered the need to prime.
706238106Sdes * @param iq: iterator query state.
707238106Sdes * @param id: module id.
708238106Sdes */
709238106Sdesstatic void
710238106Sdesgenerate_a_aaaa_check(struct module_qstate* qstate, struct iter_qstate* iq,
711238106Sdes	int id)
712238106Sdes{
713238106Sdes	struct iter_env* ie = (struct iter_env*)qstate->env->modinfo[id];
714238106Sdes	struct module_qstate* subq;
715238106Sdes	size_t i;
716238106Sdes	struct reply_info* rep = iq->response->rep;
717238106Sdes	struct ub_packed_rrset_key* s;
718238106Sdes	log_assert(iq->dp);
719238106Sdes
720238106Sdes	if(iq->depth == ie->max_dependency_depth)
721238106Sdes		return;
722238106Sdes	/* walk through additional, and check if in-zone,
723238106Sdes	 * only relevant A, AAAA are left after scrub anyway */
724238106Sdes	for(i=rep->an_numrrsets+rep->ns_numrrsets; i<rep->rrset_count; i++) {
725238106Sdes		s = rep->rrsets[i];
726238106Sdes		/* check *ALL* addresses that are transmitted in additional*/
727238106Sdes		/* is it an address ? */
728238106Sdes		if( !(ntohs(s->rk.type)==LDNS_RR_TYPE_A ||
729238106Sdes			ntohs(s->rk.type)==LDNS_RR_TYPE_AAAA)) {
730238106Sdes			continue;
731238106Sdes		}
732238106Sdes		/* is this query the same as the A/AAAA check for it */
733238106Sdes		if(qstate->qinfo.qtype == ntohs(s->rk.type) &&
734238106Sdes			qstate->qinfo.qclass == ntohs(s->rk.rrset_class) &&
735238106Sdes			query_dname_compare(qstate->qinfo.qname,
736238106Sdes				s->rk.dname)==0 &&
737238106Sdes			(qstate->query_flags&BIT_RD) &&
738238106Sdes			!(qstate->query_flags&BIT_CD))
739238106Sdes			continue;
740238106Sdes
741238106Sdes		/* generate subrequest for it */
742238106Sdes		log_nametypeclass(VERB_ALGO, "schedule addr fetch",
743238106Sdes			s->rk.dname, ntohs(s->rk.type),
744238106Sdes			ntohs(s->rk.rrset_class));
745238106Sdes		if(!generate_sub_request(s->rk.dname, s->rk.dname_len,
746238106Sdes			ntohs(s->rk.type), ntohs(s->rk.rrset_class),
747238106Sdes			qstate, id, iq,
748238106Sdes			INIT_REQUEST_STATE, FINISHED_STATE, &subq, 1)) {
749238106Sdes			verbose(VERB_ALGO, "could not generate addr check");
750238106Sdes			return;
751238106Sdes		}
752238106Sdes		/* ignore subq - not need for more init */
753238106Sdes	}
754238106Sdes}
755238106Sdes
756238106Sdes/**
757238106Sdes * Generate a NS check request to obtain authoritative information
758238106Sdes * on an NS rrset.
759238106Sdes *
760238106Sdes * @param qstate: the qtstate that triggered the need to prime.
761238106Sdes * @param iq: iterator query state.
762238106Sdes * @param id: module id.
763238106Sdes */
764238106Sdesstatic void
765238106Sdesgenerate_ns_check(struct module_qstate* qstate, struct iter_qstate* iq, int id)
766238106Sdes{
767238106Sdes	struct iter_env* ie = (struct iter_env*)qstate->env->modinfo[id];
768238106Sdes	struct module_qstate* subq;
769238106Sdes	log_assert(iq->dp);
770238106Sdes
771238106Sdes	if(iq->depth == ie->max_dependency_depth)
772238106Sdes		return;
773238106Sdes	/* is this query the same as the nscheck? */
774238106Sdes	if(qstate->qinfo.qtype == LDNS_RR_TYPE_NS &&
775238106Sdes		query_dname_compare(iq->dp->name, qstate->qinfo.qname)==0 &&
776238106Sdes		(qstate->query_flags&BIT_RD) && !(qstate->query_flags&BIT_CD)){
777238106Sdes		/* spawn off A, AAAA queries for in-zone glue to check */
778238106Sdes		generate_a_aaaa_check(qstate, iq, id);
779238106Sdes		return;
780238106Sdes	}
781238106Sdes
782238106Sdes	log_nametypeclass(VERB_ALGO, "schedule ns fetch",
783238106Sdes		iq->dp->name, LDNS_RR_TYPE_NS, iq->qchase.qclass);
784238106Sdes	if(!generate_sub_request(iq->dp->name, iq->dp->namelen,
785238106Sdes		LDNS_RR_TYPE_NS, iq->qchase.qclass, qstate, id, iq,
786238106Sdes		INIT_REQUEST_STATE, FINISHED_STATE, &subq, 1)) {
787238106Sdes		verbose(VERB_ALGO, "could not generate ns check");
788238106Sdes		return;
789238106Sdes	}
790238106Sdes	if(subq) {
791238106Sdes		struct iter_qstate* subiq =
792238106Sdes			(struct iter_qstate*)subq->minfo[id];
793238106Sdes
794238106Sdes		/* make copy to avoid use of stub dp by different qs/threads */
795238106Sdes		/* refetch glue to start higher up the tree */
796238106Sdes		subiq->refetch_glue = 1;
797238106Sdes		subiq->dp = delegpt_copy(iq->dp, subq->region);
798238106Sdes		if(!subiq->dp) {
799238106Sdes			log_err("out of memory generating ns check, copydp");
800238106Sdes			fptr_ok(fptr_whitelist_modenv_kill_sub(
801238106Sdes				qstate->env->kill_sub));
802238106Sdes			(*qstate->env->kill_sub)(subq);
803238106Sdes			return;
804238106Sdes		}
805238106Sdes	}
806238106Sdes}
807238106Sdes
808238106Sdes/**
809238106Sdes * Generate a DNSKEY prefetch query to get the DNSKEY for the DS record we
810238106Sdes * just got in a referral (where we have dnssec_expected, thus have trust
811238106Sdes * anchors above it).  Note that right after calling this routine the
812238106Sdes * iterator detached subqueries (because of following the referral), and thus
813238106Sdes * the DNSKEY query becomes detached, its return stored in the cache for
814238106Sdes * later lookup by the validator.  This cache lookup by the validator avoids
815238106Sdes * the roundtrip incurred by the DNSKEY query.  The DNSKEY query is now
816238106Sdes * performed at about the same time the original query is sent to the domain,
817238106Sdes * thus the two answers are likely to be returned at about the same time,
818238106Sdes * saving a roundtrip from the validated lookup.
819238106Sdes *
820238106Sdes * @param qstate: the qtstate that triggered the need to prime.
821238106Sdes * @param iq: iterator query state.
822238106Sdes * @param id: module id.
823238106Sdes */
824238106Sdesstatic void
825238106Sdesgenerate_dnskey_prefetch(struct module_qstate* qstate,
826238106Sdes	struct iter_qstate* iq, int id)
827238106Sdes{
828238106Sdes	struct module_qstate* subq;
829238106Sdes	log_assert(iq->dp);
830238106Sdes
831238106Sdes	/* is this query the same as the prefetch? */
832238106Sdes	if(qstate->qinfo.qtype == LDNS_RR_TYPE_DNSKEY &&
833238106Sdes		query_dname_compare(iq->dp->name, qstate->qinfo.qname)==0 &&
834238106Sdes		(qstate->query_flags&BIT_RD) && !(qstate->query_flags&BIT_CD)){
835238106Sdes		return;
836238106Sdes	}
837238106Sdes
838238106Sdes	/* if the DNSKEY is in the cache this lookup will stop quickly */
839238106Sdes	log_nametypeclass(VERB_ALGO, "schedule dnskey prefetch",
840238106Sdes		iq->dp->name, LDNS_RR_TYPE_DNSKEY, iq->qchase.qclass);
841238106Sdes	if(!generate_sub_request(iq->dp->name, iq->dp->namelen,
842238106Sdes		LDNS_RR_TYPE_DNSKEY, iq->qchase.qclass, qstate, id, iq,
843238106Sdes		INIT_REQUEST_STATE, FINISHED_STATE, &subq, 0)) {
844238106Sdes		/* we'll be slower, but it'll work */
845238106Sdes		verbose(VERB_ALGO, "could not generate dnskey prefetch");
846238106Sdes		return;
847238106Sdes	}
848238106Sdes	if(subq) {
849238106Sdes		struct iter_qstate* subiq =
850238106Sdes			(struct iter_qstate*)subq->minfo[id];
851238106Sdes		/* this qstate has the right delegation for the dnskey lookup*/
852238106Sdes		/* make copy to avoid use of stub dp by different qs/threads */
853238106Sdes		subiq->dp = delegpt_copy(iq->dp, subq->region);
854238106Sdes		/* if !subiq->dp, it'll start from the cache, no problem */
855238106Sdes	}
856238106Sdes}
857238106Sdes
858238106Sdes/**
859238106Sdes * See if the query needs forwarding.
860238106Sdes *
861238106Sdes * @param qstate: query state.
862238106Sdes * @param iq: iterator query state.
863238106Sdes * @return true if the request is forwarded, false if not.
864238106Sdes * 	If returns true but, iq->dp is NULL then a malloc failure occurred.
865238106Sdes */
866238106Sdesstatic int
867238106Sdesforward_request(struct module_qstate* qstate, struct iter_qstate* iq)
868238106Sdes{
869238106Sdes	struct delegpt* dp;
870238106Sdes	uint8_t* delname = iq->qchase.qname;
871238106Sdes	size_t delnamelen = iq->qchase.qname_len;
872238106Sdes	if(iq->refetch_glue) {
873238106Sdes		delname = iq->dp->name;
874238106Sdes		delnamelen = iq->dp->namelen;
875238106Sdes	}
876238106Sdes	/* strip one label off of DS query to lookup higher for it */
877238106Sdes	if( (iq->qchase.qtype == LDNS_RR_TYPE_DS || iq->refetch_glue)
878238106Sdes		&& !dname_is_root(iq->qchase.qname))
879238106Sdes		dname_remove_label(&delname, &delnamelen);
880238106Sdes	dp = forwards_lookup(qstate->env->fwds, delname, iq->qchase.qclass);
881238106Sdes	if(!dp)
882238106Sdes		return 0;
883238106Sdes	/* send recursion desired to forward addr */
884238106Sdes	iq->chase_flags |= BIT_RD;
885238106Sdes	iq->dp = delegpt_copy(dp, qstate->region);
886238106Sdes	/* iq->dp checked by caller */
887238106Sdes	verbose(VERB_ALGO, "forwarding request");
888238106Sdes	return 1;
889238106Sdes}
890238106Sdes
891238106Sdes/**
892238106Sdes * Process the initial part of the request handling. This state roughly
893238106Sdes * corresponds to resolver algorithms steps 1 (find answer in cache) and 2
894238106Sdes * (find the best servers to ask).
895238106Sdes *
896238106Sdes * Note that all requests start here, and query restarts revisit this state.
897238106Sdes *
898238106Sdes * This state either generates: 1) a response, from cache or error, 2) a
899238106Sdes * priming event, or 3) forwards the request to the next state (init2,
900238106Sdes * generally).
901238106Sdes *
902238106Sdes * @param qstate: query state.
903238106Sdes * @param iq: iterator query state.
904238106Sdes * @param ie: iterator shared global environment.
905238106Sdes * @param id: module id.
906238106Sdes * @return true if the event needs more request processing immediately,
907238106Sdes *         false if not.
908238106Sdes */
909238106Sdesstatic int
910238106SdesprocessInitRequest(struct module_qstate* qstate, struct iter_qstate* iq,
911238106Sdes	struct iter_env* ie, int id)
912238106Sdes{
913238106Sdes	uint8_t* delname;
914238106Sdes	size_t delnamelen;
915238106Sdes	struct dns_msg* msg;
916238106Sdes
917238106Sdes	log_query_info(VERB_DETAIL, "resolving", &qstate->qinfo);
918238106Sdes	/* check effort */
919238106Sdes
920238106Sdes	/* We enforce a maximum number of query restarts. This is primarily a
921238106Sdes	 * cheap way to prevent CNAME loops. */
922238106Sdes	if(iq->query_restart_count > MAX_RESTART_COUNT) {
923238106Sdes		verbose(VERB_QUERY, "request has exceeded the maximum number"
924238106Sdes			" of query restarts with %d", iq->query_restart_count);
925238106Sdes		return error_response(qstate, id, LDNS_RCODE_SERVFAIL);
926238106Sdes	}
927238106Sdes
928238106Sdes	/* We enforce a maximum recursion/dependency depth -- in general,
929238106Sdes	 * this is unnecessary for dependency loops (although it will
930238106Sdes	 * catch those), but it provides a sensible limit to the amount
931238106Sdes	 * of work required to answer a given query. */
932238106Sdes	verbose(VERB_ALGO, "request has dependency depth of %d", iq->depth);
933238106Sdes	if(iq->depth > ie->max_dependency_depth) {
934238106Sdes		verbose(VERB_QUERY, "request has exceeded the maximum "
935238106Sdes			"dependency depth with depth of %d", iq->depth);
936238106Sdes		return error_response(qstate, id, LDNS_RCODE_SERVFAIL);
937238106Sdes	}
938238106Sdes
939238106Sdes	/* If the request is qclass=ANY, setup to generate each class */
940238106Sdes	if(qstate->qinfo.qclass == LDNS_RR_CLASS_ANY) {
941238106Sdes		iq->qchase.qclass = 0;
942238106Sdes		return next_state(iq, COLLECT_CLASS_STATE);
943238106Sdes	}
944238106Sdes
945238106Sdes	/* Resolver Algorithm Step 1 -- Look for the answer in local data. */
946238106Sdes
947238106Sdes	/* This either results in a query restart (CNAME cache response), a
948238106Sdes	 * terminating response (ANSWER), or a cache miss (null). */
949238106Sdes
950238106Sdes	if(qstate->blacklist) {
951238106Sdes		/* if cache, or anything else, was blacklisted then
952238106Sdes		 * getting older results from cache is a bad idea, no cache */
953238106Sdes		verbose(VERB_ALGO, "cache blacklisted, going to the network");
954238106Sdes		msg = NULL;
955238106Sdes	} else {
956238106Sdes		msg = dns_cache_lookup(qstate->env, iq->qchase.qname,
957238106Sdes			iq->qchase.qname_len, iq->qchase.qtype,
958238106Sdes			iq->qchase.qclass, qstate->region, qstate->env->scratch);
959238106Sdes		if(!msg && qstate->env->neg_cache) {
960238106Sdes			/* lookup in negative cache; may result in
961238106Sdes			 * NOERROR/NODATA or NXDOMAIN answers that need validation */
962238106Sdes			msg = val_neg_getmsg(qstate->env->neg_cache, &iq->qchase,
963238106Sdes				qstate->region, qstate->env->rrset_cache,
964238106Sdes				qstate->env->scratch_buffer,
965238106Sdes				*qstate->env->now, 1/*add SOA*/, NULL);
966238106Sdes		}
967238106Sdes		/* item taken from cache does not match our query name, thus
968238106Sdes		 * security needs to be re-examined later */
969238106Sdes		if(msg && query_dname_compare(qstate->qinfo.qname,
970238106Sdes			iq->qchase.qname) != 0)
971238106Sdes			msg->rep->security = sec_status_unchecked;
972238106Sdes	}
973238106Sdes	if(msg) {
974238106Sdes		/* handle positive cache response */
975238106Sdes		enum response_type type = response_type_from_cache(msg,
976238106Sdes			&iq->qchase);
977238106Sdes		if(verbosity >= VERB_ALGO) {
978238106Sdes			log_dns_msg("msg from cache lookup", &msg->qinfo,
979238106Sdes				msg->rep);
980238106Sdes			verbose(VERB_ALGO, "msg ttl is %d, prefetch ttl %d",
981238106Sdes				(int)msg->rep->ttl,
982238106Sdes				(int)msg->rep->prefetch_ttl);
983238106Sdes		}
984238106Sdes
985238106Sdes		if(type == RESPONSE_TYPE_CNAME) {
986238106Sdes			uint8_t* sname = 0;
987238106Sdes			size_t slen = 0;
988238106Sdes			verbose(VERB_ALGO, "returning CNAME response from "
989238106Sdes				"cache");
990238106Sdes			if(!handle_cname_response(qstate, iq, msg,
991238106Sdes				&sname, &slen))
992238106Sdes				return error_response(qstate, id,
993238106Sdes					LDNS_RCODE_SERVFAIL);
994238106Sdes			iq->qchase.qname = sname;
995238106Sdes			iq->qchase.qname_len = slen;
996238106Sdes			/* This *is* a query restart, even if it is a cheap
997238106Sdes			 * one. */
998238106Sdes			iq->dp = NULL;
999238106Sdes			iq->refetch_glue = 0;
1000238106Sdes			iq->query_restart_count++;
1001238106Sdes			iq->sent_count = 0;
1002238106Sdes			sock_list_insert(&qstate->reply_origin, NULL, 0, qstate->region);
1003238106Sdes			return next_state(iq, INIT_REQUEST_STATE);
1004238106Sdes		}
1005238106Sdes
1006238106Sdes		/* if from cache, NULL, else insert 'cache IP' len=0 */
1007238106Sdes		if(qstate->reply_origin)
1008238106Sdes			sock_list_insert(&qstate->reply_origin, NULL, 0, qstate->region);
1009238106Sdes		/* it is an answer, response, to final state */
1010238106Sdes		verbose(VERB_ALGO, "returning answer from cache.");
1011238106Sdes		iq->response = msg;
1012238106Sdes		return final_state(iq);
1013238106Sdes	}
1014238106Sdes
1015238106Sdes	/* attempt to forward the request */
1016238106Sdes	if(forward_request(qstate, iq))
1017238106Sdes	{
1018238106Sdes		if(!iq->dp) {
1019238106Sdes			log_err("alloc failure for forward dp");
1020238106Sdes			return error_response(qstate, id, LDNS_RCODE_SERVFAIL);
1021238106Sdes		}
1022238106Sdes		iq->refetch_glue = 0;
1023238106Sdes		/* the request has been forwarded.
1024238106Sdes		 * forwarded requests need to be immediately sent to the
1025238106Sdes		 * next state, QUERYTARGETS. */
1026238106Sdes		return next_state(iq, QUERYTARGETS_STATE);
1027238106Sdes	}
1028238106Sdes
1029238106Sdes	/* Resolver Algorithm Step 2 -- find the "best" servers. */
1030238106Sdes
1031238106Sdes	/* first, adjust for DS queries. To avoid the grandparent problem,
1032238106Sdes	 * we just look for the closest set of server to the parent of qname.
1033238106Sdes	 * When re-fetching glue we also need to ask the parent.
1034238106Sdes	 */
1035238106Sdes	if(iq->refetch_glue) {
1036238106Sdes		if(!iq->dp) {
1037238106Sdes			log_err("internal or malloc fail: no dp for refetch");
1038238106Sdes			return error_response(qstate, id, LDNS_RCODE_SERVFAIL);
1039238106Sdes		}
1040238106Sdes		delname = iq->dp->name;
1041238106Sdes		delnamelen = iq->dp->namelen;
1042238106Sdes	} else {
1043238106Sdes		delname = iq->qchase.qname;
1044238106Sdes		delnamelen = iq->qchase.qname_len;
1045238106Sdes	}
1046238106Sdes	if(iq->qchase.qtype == LDNS_RR_TYPE_DS || iq->refetch_glue ||
1047238106Sdes	   (iq->qchase.qtype == LDNS_RR_TYPE_NS && qstate->prefetch_leeway)) {
1048238106Sdes		/* remove first label from delname, root goes to hints,
1049238106Sdes		 * but only to fetch glue, not for qtype=DS. */
1050238106Sdes		/* also when prefetching an NS record, fetch it again from
1051238106Sdes		 * its parent, just as if it expired, so that you do not
1052238106Sdes		 * get stuck on an older nameserver that gives old NSrecords */
1053238106Sdes		if(dname_is_root(delname) && (iq->refetch_glue ||
1054238106Sdes			(iq->qchase.qtype == LDNS_RR_TYPE_NS &&
1055238106Sdes			qstate->prefetch_leeway)))
1056238106Sdes			delname = NULL; /* go to root priming */
1057238106Sdes		else 	dname_remove_label(&delname, &delnamelen);
1058238106Sdes	}
1059238106Sdes	/* delname is the name to lookup a delegation for. If NULL rootprime */
1060238106Sdes	while(1) {
1061238106Sdes
1062238106Sdes		/* Lookup the delegation in the cache. If null, then the
1063238106Sdes		 * cache needs to be primed for the qclass. */
1064238106Sdes		if(delname)
1065238106Sdes		     iq->dp = dns_cache_find_delegation(qstate->env, delname,
1066238106Sdes			delnamelen, iq->qchase.qtype, iq->qchase.qclass,
1067238106Sdes			qstate->region, &iq->deleg_msg,
1068238106Sdes			*qstate->env->now+qstate->prefetch_leeway);
1069238106Sdes		else iq->dp = NULL;
1070238106Sdes
1071238106Sdes		/* If the cache has returned nothing, then we have a
1072238106Sdes		 * root priming situation. */
1073238106Sdes		if(iq->dp == NULL) {
1074238106Sdes			/* if there is a stub, then no root prime needed */
1075238106Sdes			int r = prime_stub(qstate, iq, id, delname,
1076238106Sdes				iq->qchase.qclass);
1077238106Sdes			if(r == 2)
1078238106Sdes				break; /* got noprime-stub-zone, continue */
1079238106Sdes			else if(r)
1080238106Sdes				return 0; /* stub prime request made */
1081238106Sdes			if(forwards_lookup_root(qstate->env->fwds,
1082238106Sdes				iq->qchase.qclass)) {
1083238106Sdes				/* forward zone root, no root prime needed */
1084238106Sdes				/* fill in some dp - safety belt */
1085238106Sdes				iq->dp = hints_lookup_root(qstate->env->hints,
1086238106Sdes					iq->qchase.qclass);
1087238106Sdes				if(!iq->dp) {
1088238106Sdes					log_err("internal error: no hints dp");
1089238106Sdes					return error_response(qstate, id,
1090238106Sdes						LDNS_RCODE_SERVFAIL);
1091238106Sdes				}
1092238106Sdes				iq->dp = delegpt_copy(iq->dp, qstate->region);
1093238106Sdes				if(!iq->dp) {
1094238106Sdes					log_err("out of memory in safety belt");
1095238106Sdes					return error_response(qstate, id,
1096238106Sdes						LDNS_RCODE_SERVFAIL);
1097238106Sdes				}
1098238106Sdes				return next_state(iq, INIT_REQUEST_2_STATE);
1099238106Sdes			}
1100238106Sdes			/* Note that the result of this will set a new
1101238106Sdes			 * DelegationPoint based on the result of priming. */
1102238106Sdes			if(!prime_root(qstate, iq, id, iq->qchase.qclass))
1103238106Sdes				return error_response(qstate, id,
1104238106Sdes					LDNS_RCODE_REFUSED);
1105238106Sdes
1106238106Sdes			/* priming creates and sends a subordinate query, with
1107238106Sdes			 * this query as the parent. So further processing for
1108238106Sdes			 * this event will stop until reactivated by the
1109238106Sdes			 * results of priming. */
1110238106Sdes			return 0;
1111238106Sdes		}
1112238106Sdes
1113238106Sdes		/* see if this dp not useless.
1114238106Sdes		 * It is useless if:
1115238106Sdes		 *	o all NS items are required glue.
1116238106Sdes		 *	  or the query is for NS item that is required glue.
1117238106Sdes		 *	o no addresses are provided.
1118238106Sdes		 *	o RD qflag is on.
1119238106Sdes		 * Instead, go up one level, and try to get even further
1120238106Sdes		 * If the root was useless, use safety belt information.
1121238106Sdes		 * Only check cache returns, because replies for servers
1122238106Sdes		 * could be useless but lead to loops (bumping into the
1123238106Sdes		 * same server reply) if useless-checked.
1124238106Sdes		 */
1125238106Sdes		if(iter_dp_is_useless(&qstate->qinfo, qstate->query_flags,
1126238106Sdes			iq->dp)) {
1127238106Sdes			if(dname_is_root(iq->dp->name)) {
1128238106Sdes				/* use safety belt */
1129238106Sdes				verbose(VERB_QUERY, "Cache has root NS but "
1130238106Sdes				"no addresses. Fallback to the safety belt.");
1131238106Sdes				iq->dp = hints_lookup_root(qstate->env->hints,
1132238106Sdes					iq->qchase.qclass);
1133238106Sdes				/* note deleg_msg is from previous lookup,
1134238106Sdes				 * but RD is on, so it is not used */
1135238106Sdes				if(!iq->dp) {
1136238106Sdes					log_err("internal error: no hints dp");
1137238106Sdes					return error_response(qstate, id,
1138238106Sdes						LDNS_RCODE_REFUSED);
1139238106Sdes				}
1140238106Sdes				iq->dp = delegpt_copy(iq->dp, qstate->region);
1141238106Sdes				if(!iq->dp) {
1142238106Sdes					log_err("out of memory in safety belt");
1143238106Sdes					return error_response(qstate, id,
1144238106Sdes						LDNS_RCODE_SERVFAIL);
1145238106Sdes				}
1146238106Sdes				break;
1147238106Sdes			} else {
1148238106Sdes				verbose(VERB_ALGO,
1149238106Sdes					"cache delegation was useless:");
1150238106Sdes				delegpt_log(VERB_ALGO, iq->dp);
1151238106Sdes				/* go up */
1152238106Sdes				delname = iq->dp->name;
1153238106Sdes				delnamelen = iq->dp->namelen;
1154238106Sdes				dname_remove_label(&delname, &delnamelen);
1155238106Sdes			}
1156238106Sdes		} else break;
1157238106Sdes	}
1158238106Sdes
1159238106Sdes	verbose(VERB_ALGO, "cache delegation returns delegpt");
1160238106Sdes	delegpt_log(VERB_ALGO, iq->dp);
1161238106Sdes
1162238106Sdes	/* Otherwise, set the current delegation point and move on to the
1163238106Sdes	 * next state. */
1164238106Sdes	return next_state(iq, INIT_REQUEST_2_STATE);
1165238106Sdes}
1166238106Sdes
1167238106Sdes/**
1168238106Sdes * Process the second part of the initial request handling. This state
1169238106Sdes * basically exists so that queries that generate root priming events have
1170238106Sdes * the same init processing as ones that do not. Request events that reach
1171238106Sdes * this state must have a valid currentDelegationPoint set.
1172238106Sdes *
1173238106Sdes * This part is primarly handling stub zone priming. Events that reach this
1174238106Sdes * state must have a current delegation point.
1175238106Sdes *
1176238106Sdes * @param qstate: query state.
1177238106Sdes * @param iq: iterator query state.
1178238106Sdes * @param id: module id.
1179238106Sdes * @return true if the event needs more request processing immediately,
1180238106Sdes *         false if not.
1181238106Sdes */
1182238106Sdesstatic int
1183238106SdesprocessInitRequest2(struct module_qstate* qstate, struct iter_qstate* iq,
1184238106Sdes	int id)
1185238106Sdes{
1186238106Sdes	uint8_t* delname;
1187238106Sdes	size_t delnamelen;
1188238106Sdes	log_query_info(VERB_QUERY, "resolving (init part 2): ",
1189238106Sdes		&qstate->qinfo);
1190238106Sdes
1191238106Sdes	if(iq->refetch_glue) {
1192238106Sdes		if(!iq->dp) {
1193238106Sdes			log_err("internal or malloc fail: no dp for refetch");
1194238106Sdes			return error_response(qstate, id, LDNS_RCODE_SERVFAIL);
1195238106Sdes		}
1196238106Sdes		delname = iq->dp->name;
1197238106Sdes		delnamelen = iq->dp->namelen;
1198238106Sdes	} else {
1199238106Sdes		delname = iq->qchase.qname;
1200238106Sdes		delnamelen = iq->qchase.qname_len;
1201238106Sdes	}
1202238106Sdes	if(iq->qchase.qtype == LDNS_RR_TYPE_DS || iq->refetch_glue) {
1203238106Sdes		if(!dname_is_root(delname))
1204238106Sdes			dname_remove_label(&delname, &delnamelen);
1205238106Sdes		iq->refetch_glue = 0; /* if CNAME causes restart, no refetch */
1206238106Sdes	}
1207238106Sdes	/* Check to see if we need to prime a stub zone. */
1208238106Sdes	if(prime_stub(qstate, iq, id, delname, iq->qchase.qclass)) {
1209238106Sdes		/* A priming sub request was made */
1210238106Sdes		return 0;
1211238106Sdes	}
1212238106Sdes
1213238106Sdes	/* most events just get forwarded to the next state. */
1214238106Sdes	return next_state(iq, INIT_REQUEST_3_STATE);
1215238106Sdes}
1216238106Sdes
1217238106Sdes/**
1218238106Sdes * Process the third part of the initial request handling. This state exists
1219238106Sdes * as a separate state so that queries that generate stub priming events
1220238106Sdes * will get the tail end of the init process but not repeat the stub priming
1221238106Sdes * check.
1222238106Sdes *
1223238106Sdes * @param qstate: query state.
1224238106Sdes * @param iq: iterator query state.
1225238106Sdes * @param id: module id.
1226238106Sdes * @return true, advancing the event to the QUERYTARGETS_STATE.
1227238106Sdes */
1228238106Sdesstatic int
1229238106SdesprocessInitRequest3(struct module_qstate* qstate, struct iter_qstate* iq,
1230238106Sdes	int id)
1231238106Sdes{
1232238106Sdes	log_query_info(VERB_QUERY, "resolving (init part 3): ",
1233238106Sdes		&qstate->qinfo);
1234238106Sdes	/* if the cache reply dp equals a validation anchor or msg has DS,
1235238106Sdes	 * then DNSSEC RRSIGs are expected in the reply */
1236238106Sdes	iq->dnssec_expected = iter_indicates_dnssec(qstate->env, iq->dp,
1237238106Sdes		iq->deleg_msg, iq->qchase.qclass);
1238238106Sdes
1239238106Sdes	/* If the RD flag wasn't set, then we just finish with the
1240238106Sdes	 * cached referral as the response. */
1241238106Sdes	if(!(qstate->query_flags & BIT_RD)) {
1242238106Sdes		iq->response = iq->deleg_msg;
1243269257Sdes		if(verbosity >= VERB_ALGO && iq->response)
1244238106Sdes			log_dns_msg("no RD requested, using delegation msg",
1245238106Sdes				&iq->response->qinfo, iq->response->rep);
1246238106Sdes		if(qstate->reply_origin)
1247238106Sdes			sock_list_insert(&qstate->reply_origin, NULL, 0, qstate->region);
1248238106Sdes		return final_state(iq);
1249238106Sdes	}
1250238106Sdes	/* After this point, unset the RD flag -- this query is going to
1251238106Sdes	 * be sent to an auth. server. */
1252238106Sdes	iq->chase_flags &= ~BIT_RD;
1253238106Sdes
1254238106Sdes	/* if dnssec expected, fetch key for the trust-anchor or cached-DS */
1255238106Sdes	if(iq->dnssec_expected && qstate->env->cfg->prefetch_key &&
1256238106Sdes		!(qstate->query_flags&BIT_CD)) {
1257238106Sdes		generate_dnskey_prefetch(qstate, iq, id);
1258238106Sdes		fptr_ok(fptr_whitelist_modenv_detach_subs(
1259238106Sdes			qstate->env->detach_subs));
1260238106Sdes		(*qstate->env->detach_subs)(qstate);
1261238106Sdes	}
1262238106Sdes
1263238106Sdes	/* Jump to the next state. */
1264238106Sdes	return next_state(iq, QUERYTARGETS_STATE);
1265238106Sdes}
1266238106Sdes
1267238106Sdes/**
1268238106Sdes * Given a basic query, generate a parent-side "target" query.
1269238106Sdes * These are subordinate queries for missing delegation point target addresses,
1270238106Sdes * for which only the parent of the delegation provides correct IP addresses.
1271238106Sdes *
1272238106Sdes * @param qstate: query state.
1273238106Sdes * @param iq: iterator query state.
1274238106Sdes * @param id: module id.
1275238106Sdes * @param name: target qname.
1276238106Sdes * @param namelen: target qname length.
1277238106Sdes * @param qtype: target qtype (either A or AAAA).
1278238106Sdes * @param qclass: target qclass.
1279238106Sdes * @return true on success, false on failure.
1280238106Sdes */
1281238106Sdesstatic int
1282238106Sdesgenerate_parentside_target_query(struct module_qstate* qstate,
1283238106Sdes	struct iter_qstate* iq, int id, uint8_t* name, size_t namelen,
1284238106Sdes	uint16_t qtype, uint16_t qclass)
1285238106Sdes{
1286238106Sdes	struct module_qstate* subq;
1287238106Sdes	if(!generate_sub_request(name, namelen, qtype, qclass, qstate,
1288238106Sdes		id, iq, INIT_REQUEST_STATE, FINISHED_STATE, &subq, 0))
1289238106Sdes		return 0;
1290238106Sdes	if(subq) {
1291238106Sdes		struct iter_qstate* subiq =
1292238106Sdes			(struct iter_qstate*)subq->minfo[id];
1293238106Sdes		/* blacklist the cache - we want to fetch parent stuff */
1294238106Sdes		sock_list_insert(&subq->blacklist, NULL, 0, subq->region);
1295238106Sdes		subiq->query_for_pside_glue = 1;
1296238106Sdes		if(dname_subdomain_c(name, iq->dp->name)) {
1297238106Sdes			subiq->dp = delegpt_copy(iq->dp, subq->region);
1298238106Sdes			subiq->dnssec_expected = iter_indicates_dnssec(
1299238106Sdes				qstate->env, subiq->dp, NULL,
1300238106Sdes				subq->qinfo.qclass);
1301238106Sdes			subiq->refetch_glue = 1;
1302238106Sdes		} else {
1303238106Sdes			subiq->dp = dns_cache_find_delegation(qstate->env,
1304238106Sdes				name, namelen, qtype, qclass, subq->region,
1305238106Sdes				&subiq->deleg_msg,
1306238106Sdes				*qstate->env->now+subq->prefetch_leeway);
1307238106Sdes			/* if no dp, then it's from root, refetch unneeded */
1308238106Sdes			if(subiq->dp) {
1309238106Sdes				subiq->dnssec_expected = iter_indicates_dnssec(
1310238106Sdes					qstate->env, subiq->dp, NULL,
1311238106Sdes					subq->qinfo.qclass);
1312238106Sdes				subiq->refetch_glue = 1;
1313238106Sdes			}
1314238106Sdes		}
1315238106Sdes	}
1316238106Sdes	log_nametypeclass(VERB_QUERY, "new pside target", name, qtype, qclass);
1317238106Sdes	return 1;
1318238106Sdes}
1319238106Sdes
1320238106Sdes/**
1321238106Sdes * Given a basic query, generate a "target" query. These are subordinate
1322238106Sdes * queries for missing delegation point target addresses.
1323238106Sdes *
1324238106Sdes * @param qstate: query state.
1325238106Sdes * @param iq: iterator query state.
1326238106Sdes * @param id: module id.
1327238106Sdes * @param name: target qname.
1328238106Sdes * @param namelen: target qname length.
1329238106Sdes * @param qtype: target qtype (either A or AAAA).
1330238106Sdes * @param qclass: target qclass.
1331238106Sdes * @return true on success, false on failure.
1332238106Sdes */
1333238106Sdesstatic int
1334238106Sdesgenerate_target_query(struct module_qstate* qstate, struct iter_qstate* iq,
1335238106Sdes        int id, uint8_t* name, size_t namelen, uint16_t qtype, uint16_t qclass)
1336238106Sdes{
1337238106Sdes	struct module_qstate* subq;
1338238106Sdes	if(!generate_sub_request(name, namelen, qtype, qclass, qstate,
1339238106Sdes		id, iq, INIT_REQUEST_STATE, FINISHED_STATE, &subq, 0))
1340238106Sdes		return 0;
1341238106Sdes	log_nametypeclass(VERB_QUERY, "new target", name, qtype, qclass);
1342238106Sdes	return 1;
1343238106Sdes}
1344238106Sdes
1345238106Sdes/**
1346238106Sdes * Given an event at a certain state, generate zero or more target queries
1347238106Sdes * for it's current delegation point.
1348238106Sdes *
1349238106Sdes * @param qstate: query state.
1350238106Sdes * @param iq: iterator query state.
1351238106Sdes * @param ie: iterator shared global environment.
1352238106Sdes * @param id: module id.
1353238106Sdes * @param maxtargets: The maximum number of targets to query for.
1354238106Sdes *	if it is negative, there is no maximum number of targets.
1355238106Sdes * @param num: returns the number of queries generated and processed,
1356238106Sdes *	which may be zero if there were no missing targets.
1357238106Sdes * @return false on error.
1358238106Sdes */
1359238106Sdesstatic int
1360238106Sdesquery_for_targets(struct module_qstate* qstate, struct iter_qstate* iq,
1361238106Sdes        struct iter_env* ie, int id, int maxtargets, int* num)
1362238106Sdes{
1363238106Sdes	int query_count = 0;
1364238106Sdes	struct delegpt_ns* ns;
1365238106Sdes	int missing;
1366238106Sdes	int toget = 0;
1367238106Sdes
1368238106Sdes	if(iq->depth == ie->max_dependency_depth)
1369238106Sdes		return 0;
1370275854Sdelphij	if(iq->depth > 0 && iq->target_count &&
1371275854Sdelphij		iq->target_count[1] > MAX_TARGET_COUNT) {
1372275854Sdelphij		verbose(VERB_QUERY, "request has exceeded the maximum "
1373275854Sdelphij			"number of glue fetches %d", iq->target_count[1]);
1374275854Sdelphij		return 0;
1375275854Sdelphij	}
1376238106Sdes
1377238106Sdes	iter_mark_cycle_targets(qstate, iq->dp);
1378238106Sdes	missing = (int)delegpt_count_missing_targets(iq->dp);
1379238106Sdes	log_assert(maxtargets != 0); /* that would not be useful */
1380238106Sdes
1381238106Sdes	/* Generate target requests. Basically, any missing targets
1382238106Sdes	 * are queried for here, regardless if it is necessary to do
1383238106Sdes	 * so to continue processing. */
1384238106Sdes	if(maxtargets < 0 || maxtargets > missing)
1385238106Sdes		toget = missing;
1386238106Sdes	else	toget = maxtargets;
1387238106Sdes	if(toget == 0) {
1388238106Sdes		*num = 0;
1389238106Sdes		return 1;
1390238106Sdes	}
1391238106Sdes	/* select 'toget' items from the total of 'missing' items */
1392238106Sdes	log_assert(toget <= missing);
1393238106Sdes
1394238106Sdes	/* loop over missing targets */
1395238106Sdes	for(ns = iq->dp->nslist; ns; ns = ns->next) {
1396238106Sdes		if(ns->resolved)
1397238106Sdes			continue;
1398238106Sdes
1399238106Sdes		/* randomly select this item with probability toget/missing */
1400238106Sdes		if(!iter_ns_probability(qstate->env->rnd, toget, missing)) {
1401238106Sdes			/* do not select this one, next; select toget number
1402238106Sdes			 * of items from a list one less in size */
1403238106Sdes			missing --;
1404238106Sdes			continue;
1405238106Sdes		}
1406238106Sdes
1407238106Sdes		if(ie->supports_ipv6 && !ns->got6) {
1408238106Sdes			/* Send the AAAA request. */
1409238106Sdes			if(!generate_target_query(qstate, iq, id,
1410238106Sdes				ns->name, ns->namelen,
1411238106Sdes				LDNS_RR_TYPE_AAAA, iq->qchase.qclass)) {
1412238106Sdes				*num = query_count;
1413238106Sdes				if(query_count > 0)
1414238106Sdes					qstate->ext_state[id] = module_wait_subquery;
1415238106Sdes				return 0;
1416238106Sdes			}
1417238106Sdes			query_count++;
1418238106Sdes		}
1419238106Sdes		/* Send the A request. */
1420238106Sdes		if(ie->supports_ipv4 && !ns->got4) {
1421238106Sdes			if(!generate_target_query(qstate, iq, id,
1422238106Sdes				ns->name, ns->namelen,
1423238106Sdes				LDNS_RR_TYPE_A, iq->qchase.qclass)) {
1424238106Sdes				*num = query_count;
1425238106Sdes				if(query_count > 0)
1426238106Sdes					qstate->ext_state[id] = module_wait_subquery;
1427238106Sdes				return 0;
1428238106Sdes			}
1429238106Sdes			query_count++;
1430238106Sdes		}
1431238106Sdes
1432238106Sdes		/* mark this target as in progress. */
1433238106Sdes		ns->resolved = 1;
1434238106Sdes		missing--;
1435238106Sdes		toget--;
1436238106Sdes		if(toget == 0)
1437238106Sdes			break;
1438238106Sdes	}
1439238106Sdes	*num = query_count;
1440238106Sdes	if(query_count > 0)
1441238106Sdes		qstate->ext_state[id] = module_wait_subquery;
1442238106Sdes
1443238106Sdes	return 1;
1444238106Sdes}
1445238106Sdes
1446269257Sdes/** see if last resort is possible - does config allow queries to parent */
1447269257Sdesstatic int
1448269257Sdescan_have_last_resort(struct module_env* env, struct delegpt* dp,
1449269257Sdes	struct iter_qstate* iq)
1450269257Sdes{
1451269257Sdes	struct delegpt* fwddp;
1452269257Sdes	struct iter_hints_stub* stub;
1453269257Sdes	/* do not process a last resort (the parent side) if a stub
1454269257Sdes	 * or forward is configured, because we do not want to go 'above'
1455269257Sdes	 * the configured servers */
1456269257Sdes	if(!dname_is_root(dp->name) && (stub = (struct iter_hints_stub*)
1457269257Sdes		name_tree_find(&env->hints->tree, dp->name, dp->namelen,
1458269257Sdes		dp->namelabs, iq->qchase.qclass)) &&
1459269257Sdes		/* has_parent side is turned off for stub_first, where we
1460269257Sdes		 * are allowed to go to the parent */
1461269257Sdes		stub->dp->has_parent_side_NS) {
1462269257Sdes		verbose(VERB_QUERY, "configured stub servers failed -- returning SERVFAIL");
1463269257Sdes		return 0;
1464269257Sdes	}
1465269257Sdes	if((fwddp = forwards_find(env->fwds, dp->name, iq->qchase.qclass)) &&
1466269257Sdes		/* has_parent_side is turned off for forward_first, where
1467269257Sdes		 * we are allowed to go to the parent */
1468269257Sdes		fwddp->has_parent_side_NS) {
1469269257Sdes		verbose(VERB_QUERY, "configured forward servers failed -- returning SERVFAIL");
1470269257Sdes		return 0;
1471269257Sdes	}
1472269257Sdes	return 1;
1473269257Sdes}
1474269257Sdes
1475238106Sdes/**
1476238106Sdes * Called by processQueryTargets when it would like extra targets to query
1477238106Sdes * but it seems to be out of options.  At last resort some less appealing
1478238106Sdes * options are explored.  If there are no more options, the result is SERVFAIL
1479238106Sdes *
1480238106Sdes * @param qstate: query state.
1481238106Sdes * @param iq: iterator query state.
1482238106Sdes * @param ie: iterator shared global environment.
1483238106Sdes * @param id: module id.
1484238106Sdes * @return true if the event requires more request processing immediately,
1485238106Sdes *         false if not.
1486238106Sdes */
1487238106Sdesstatic int
1488238106SdesprocessLastResort(struct module_qstate* qstate, struct iter_qstate* iq,
1489238106Sdes	struct iter_env* ie, int id)
1490238106Sdes{
1491238106Sdes	struct delegpt_ns* ns;
1492238106Sdes	int query_count = 0;
1493238106Sdes	verbose(VERB_ALGO, "No more query targets, attempting last resort");
1494238106Sdes	log_assert(iq->dp);
1495238106Sdes
1496269257Sdes	if(!can_have_last_resort(qstate->env, iq->dp, iq)) {
1497269257Sdes		/* fail -- no more targets, no more hope of targets, no hope
1498269257Sdes		 * of a response. */
1499269257Sdes		return error_response_cache(qstate, id, LDNS_RCODE_SERVFAIL);
1500269257Sdes	}
1501249141Sdes	if(!iq->dp->has_parent_side_NS && dname_is_root(iq->dp->name)) {
1502249141Sdes		struct delegpt* p = hints_lookup_root(qstate->env->hints,
1503249141Sdes			iq->qchase.qclass);
1504249141Sdes		if(p) {
1505249141Sdes			struct delegpt_ns* ns;
1506249141Sdes			struct delegpt_addr* a;
1507249141Sdes			iq->chase_flags &= ~BIT_RD; /* go to authorities */
1508249141Sdes			for(ns = p->nslist; ns; ns=ns->next) {
1509249141Sdes				(void)delegpt_add_ns(iq->dp, qstate->region,
1510269257Sdes					ns->name, ns->lame);
1511249141Sdes			}
1512249141Sdes			for(a = p->target_list; a; a=a->next_target) {
1513249141Sdes				(void)delegpt_add_addr(iq->dp, qstate->region,
1514249141Sdes					&a->addr, a->addrlen, a->bogus,
1515249141Sdes					a->lame);
1516249141Sdes			}
1517249141Sdes		}
1518249141Sdes		iq->dp->has_parent_side_NS = 1;
1519249141Sdes	} else if(!iq->dp->has_parent_side_NS) {
1520238106Sdes		if(!iter_lookup_parent_NS_from_cache(qstate->env, iq->dp,
1521238106Sdes			qstate->region, &qstate->qinfo)
1522238106Sdes			|| !iq->dp->has_parent_side_NS) {
1523238106Sdes			/* if: malloc failure in lookup go up to try */
1524238106Sdes			/* if: no parent NS in cache - go up one level */
1525238106Sdes			verbose(VERB_ALGO, "try to grab parent NS");
1526238106Sdes			iq->store_parent_NS = iq->dp;
1527249141Sdes			iq->chase_flags &= ~BIT_RD; /* go to authorities */
1528238106Sdes			iq->deleg_msg = NULL;
1529238106Sdes			iq->refetch_glue = 1;
1530238106Sdes			iq->query_restart_count++;
1531238106Sdes			iq->sent_count = 0;
1532238106Sdes			return next_state(iq, INIT_REQUEST_STATE);
1533238106Sdes		}
1534238106Sdes	}
1535238106Sdes	/* see if that makes new names available */
1536238106Sdes	if(!cache_fill_missing(qstate->env, iq->qchase.qclass,
1537238106Sdes		qstate->region, iq->dp))
1538238106Sdes		log_err("out of memory in cache_fill_missing");
1539238106Sdes	if(iq->dp->usable_list) {
1540238106Sdes		verbose(VERB_ALGO, "try parent-side-name, w. glue from cache");
1541238106Sdes		return next_state(iq, QUERYTARGETS_STATE);
1542238106Sdes	}
1543238106Sdes	/* try to fill out parent glue from cache */
1544238106Sdes	if(iter_lookup_parent_glue_from_cache(qstate->env, iq->dp,
1545238106Sdes		qstate->region, &qstate->qinfo)) {
1546238106Sdes		/* got parent stuff from cache, see if we can continue */
1547238106Sdes		verbose(VERB_ALGO, "try parent-side glue from cache");
1548238106Sdes		return next_state(iq, QUERYTARGETS_STATE);
1549238106Sdes	}
1550238106Sdes	/* query for an extra name added by the parent-NS record */
1551238106Sdes	if(delegpt_count_missing_targets(iq->dp) > 0) {
1552238106Sdes		int qs = 0;
1553238106Sdes		verbose(VERB_ALGO, "try parent-side target name");
1554238106Sdes		if(!query_for_targets(qstate, iq, ie, id, 1, &qs)) {
1555238106Sdes			return error_response(qstate, id, LDNS_RCODE_SERVFAIL);
1556238106Sdes		}
1557238106Sdes		iq->num_target_queries += qs;
1558275854Sdelphij		target_count_increase(iq, qs);
1559238106Sdes		if(qs != 0) {
1560238106Sdes			qstate->ext_state[id] = module_wait_subquery;
1561238106Sdes			return 0; /* and wait for them */
1562238106Sdes		}
1563238106Sdes	}
1564238106Sdes	if(iq->depth == ie->max_dependency_depth) {
1565238106Sdes		verbose(VERB_QUERY, "maxdepth and need more nameservers, fail");
1566238106Sdes		return error_response_cache(qstate, id, LDNS_RCODE_SERVFAIL);
1567238106Sdes	}
1568275854Sdelphij	if(iq->depth > 0 && iq->target_count &&
1569275854Sdelphij		iq->target_count[1] > MAX_TARGET_COUNT) {
1570275854Sdelphij		verbose(VERB_QUERY, "request has exceeded the maximum "
1571275854Sdelphij			"number of glue fetches %d", iq->target_count[1]);
1572275854Sdelphij		return error_response_cache(qstate, id, LDNS_RCODE_SERVFAIL);
1573275854Sdelphij	}
1574238106Sdes	/* mark cycle targets for parent-side lookups */
1575238106Sdes	iter_mark_pside_cycle_targets(qstate, iq->dp);
1576238106Sdes	/* see if we can issue queries to get nameserver addresses */
1577238106Sdes	/* this lookup is not randomized, but sequential. */
1578238106Sdes	for(ns = iq->dp->nslist; ns; ns = ns->next) {
1579238106Sdes		/* query for parent-side A and AAAA for nameservers */
1580238106Sdes		if(ie->supports_ipv6 && !ns->done_pside6) {
1581238106Sdes			/* Send the AAAA request. */
1582238106Sdes			if(!generate_parentside_target_query(qstate, iq, id,
1583238106Sdes				ns->name, ns->namelen,
1584238106Sdes				LDNS_RR_TYPE_AAAA, iq->qchase.qclass))
1585238106Sdes				return error_response(qstate, id,
1586238106Sdes					LDNS_RCODE_SERVFAIL);
1587238106Sdes			ns->done_pside6 = 1;
1588238106Sdes			query_count++;
1589238106Sdes		}
1590238106Sdes		if(ie->supports_ipv4 && !ns->done_pside4) {
1591238106Sdes			/* Send the A request. */
1592238106Sdes			if(!generate_parentside_target_query(qstate, iq, id,
1593238106Sdes				ns->name, ns->namelen,
1594238106Sdes				LDNS_RR_TYPE_A, iq->qchase.qclass))
1595238106Sdes				return error_response(qstate, id,
1596238106Sdes					LDNS_RCODE_SERVFAIL);
1597238106Sdes			ns->done_pside4 = 1;
1598238106Sdes			query_count++;
1599238106Sdes		}
1600238106Sdes		if(query_count != 0) { /* suspend to await results */
1601238106Sdes			verbose(VERB_ALGO, "try parent-side glue lookup");
1602238106Sdes			iq->num_target_queries += query_count;
1603275854Sdelphij			target_count_increase(iq, query_count);
1604238106Sdes			qstate->ext_state[id] = module_wait_subquery;
1605238106Sdes			return 0;
1606238106Sdes		}
1607238106Sdes	}
1608238106Sdes
1609238106Sdes	/* if this was a parent-side glue query itself, then store that
1610238106Sdes	 * failure in cache. */
1611238106Sdes	if(iq->query_for_pside_glue && !iq->pside_glue)
1612238106Sdes		iter_store_parentside_neg(qstate->env, &qstate->qinfo,
1613238106Sdes			iq->deleg_msg?iq->deleg_msg->rep:
1614238106Sdes			(iq->response?iq->response->rep:NULL));
1615238106Sdes
1616238106Sdes	verbose(VERB_QUERY, "out of query targets -- returning SERVFAIL");
1617238106Sdes	/* fail -- no more targets, no more hope of targets, no hope
1618238106Sdes	 * of a response. */
1619238106Sdes	return error_response_cache(qstate, id, LDNS_RCODE_SERVFAIL);
1620238106Sdes}
1621238106Sdes
1622238106Sdes/**
1623238106Sdes * Try to find the NS record set that will resolve a qtype DS query. Due
1624238106Sdes * to grandparent/grandchild reasons we did not get a proper lookup right
1625238106Sdes * away.  We need to create type NS queries until we get the right parent
1626238106Sdes * for this lookup.  We remove labels from the query to find the right point.
1627238106Sdes * If we end up at the old dp name, then there is no solution.
1628238106Sdes *
1629238106Sdes * @param qstate: query state.
1630238106Sdes * @param iq: iterator query state.
1631238106Sdes * @param id: module id.
1632238106Sdes * @return true if the event requires more immediate processing, false if
1633238106Sdes *         not. This is generally only true when forwarding the request to
1634238106Sdes *         the final state (i.e., on answer).
1635238106Sdes */
1636238106Sdesstatic int
1637249141SdesprocessDSNSFind(struct module_qstate* qstate, struct iter_qstate* iq, int id)
1638238106Sdes{
1639238106Sdes	struct module_qstate* subq = NULL;
1640238106Sdes	verbose(VERB_ALGO, "processDSNSFind");
1641238106Sdes
1642238106Sdes	if(!iq->dsns_point) {
1643238106Sdes		/* initialize */
1644238106Sdes		iq->dsns_point = iq->qchase.qname;
1645238106Sdes		iq->dsns_point_len = iq->qchase.qname_len;
1646238106Sdes	}
1647238106Sdes	/* robustcheck for internal error: we are not underneath the dp */
1648238106Sdes	if(!dname_subdomain_c(iq->dsns_point, iq->dp->name)) {
1649238106Sdes		return error_response_cache(qstate, id, LDNS_RCODE_SERVFAIL);
1650238106Sdes	}
1651238106Sdes
1652238106Sdes	/* go up one (more) step, until we hit the dp, if so, end */
1653238106Sdes	dname_remove_label(&iq->dsns_point, &iq->dsns_point_len);
1654238106Sdes	if(query_dname_compare(iq->dsns_point, iq->dp->name) == 0) {
1655238106Sdes		/* there was no inbetween nameserver, use the old delegation
1656238106Sdes		 * point again.  And this time, because dsns_point is nonNULL
1657238106Sdes		 * we are going to accept the (bad) result */
1658238106Sdes		iq->state = QUERYTARGETS_STATE;
1659238106Sdes		return 1;
1660238106Sdes	}
1661238106Sdes	iq->state = DSNS_FIND_STATE;
1662238106Sdes
1663238106Sdes	/* spawn NS lookup (validation not needed, this is for DS lookup) */
1664238106Sdes	log_nametypeclass(VERB_ALGO, "fetch nameservers",
1665238106Sdes		iq->dsns_point, LDNS_RR_TYPE_NS, iq->qchase.qclass);
1666238106Sdes	if(!generate_sub_request(iq->dsns_point, iq->dsns_point_len,
1667238106Sdes		LDNS_RR_TYPE_NS, iq->qchase.qclass, qstate, id, iq,
1668238106Sdes		INIT_REQUEST_STATE, FINISHED_STATE, &subq, 0)) {
1669238106Sdes		return error_response_cache(qstate, id, LDNS_RCODE_SERVFAIL);
1670238106Sdes	}
1671238106Sdes
1672238106Sdes	return 0;
1673238106Sdes}
1674238106Sdes
1675238106Sdes/**
1676238106Sdes * This is the request event state where the request will be sent to one of
1677238106Sdes * its current query targets. This state also handles issuing target lookup
1678238106Sdes * queries for missing target IP addresses. Queries typically iterate on
1679238106Sdes * this state, both when they are just trying different targets for a given
1680238106Sdes * delegation point, and when they change delegation points. This state
1681238106Sdes * roughly corresponds to RFC 1034 algorithm steps 3 and 4.
1682238106Sdes *
1683238106Sdes * @param qstate: query state.
1684238106Sdes * @param iq: iterator query state.
1685238106Sdes * @param ie: iterator shared global environment.
1686238106Sdes * @param id: module id.
1687238106Sdes * @return true if the event requires more request processing immediately,
1688238106Sdes *         false if not. This state only returns true when it is generating
1689238106Sdes *         a SERVFAIL response because the query has hit a dead end.
1690238106Sdes */
1691238106Sdesstatic int
1692238106SdesprocessQueryTargets(struct module_qstate* qstate, struct iter_qstate* iq,
1693238106Sdes	struct iter_env* ie, int id)
1694238106Sdes{
1695238106Sdes	int tf_policy;
1696238106Sdes	struct delegpt_addr* target;
1697238106Sdes	struct outbound_entry* outq;
1698238106Sdes
1699238106Sdes	/* NOTE: a request will encounter this state for each target it
1700238106Sdes	 * needs to send a query to. That is, at least one per referral,
1701238106Sdes	 * more if some targets timeout or return throwaway answers. */
1702238106Sdes
1703238106Sdes	log_query_info(VERB_QUERY, "processQueryTargets:", &qstate->qinfo);
1704238106Sdes	verbose(VERB_ALGO, "processQueryTargets: targetqueries %d, "
1705238106Sdes		"currentqueries %d sentcount %d", iq->num_target_queries,
1706238106Sdes		iq->num_current_queries, iq->sent_count);
1707238106Sdes
1708238106Sdes	/* Make sure that we haven't run away */
1709238106Sdes	/* FIXME: is this check even necessary? */
1710238106Sdes	if(iq->referral_count > MAX_REFERRAL_COUNT) {
1711238106Sdes		verbose(VERB_QUERY, "request has exceeded the maximum "
1712238106Sdes			"number of referrrals with %d", iq->referral_count);
1713238106Sdes		return error_response(qstate, id, LDNS_RCODE_SERVFAIL);
1714238106Sdes	}
1715238106Sdes	if(iq->sent_count > MAX_SENT_COUNT) {
1716238106Sdes		verbose(VERB_QUERY, "request has exceeded the maximum "
1717238106Sdes			"number of sends with %d", iq->sent_count);
1718238106Sdes		return error_response(qstate, id, LDNS_RCODE_SERVFAIL);
1719238106Sdes	}
1720238106Sdes
1721238106Sdes	/* Make sure we have a delegation point, otherwise priming failed
1722238106Sdes	 * or another failure occurred */
1723238106Sdes	if(!iq->dp) {
1724238106Sdes		verbose(VERB_QUERY, "Failed to get a delegation, giving up");
1725238106Sdes		return error_response(qstate, id, LDNS_RCODE_SERVFAIL);
1726238106Sdes	}
1727238106Sdes	if(!ie->supports_ipv6)
1728238106Sdes		delegpt_no_ipv6(iq->dp);
1729238106Sdes	if(!ie->supports_ipv4)
1730238106Sdes		delegpt_no_ipv4(iq->dp);
1731238106Sdes	delegpt_log(VERB_ALGO, iq->dp);
1732238106Sdes
1733238106Sdes	if(iq->num_current_queries>0) {
1734238106Sdes		/* already busy answering a query, this restart is because
1735238106Sdes		 * more delegpt addrs became available, wait for existing
1736238106Sdes		 * query. */
1737238106Sdes		verbose(VERB_ALGO, "woke up, but wait for outstanding query");
1738238106Sdes		qstate->ext_state[id] = module_wait_reply;
1739238106Sdes		return 0;
1740238106Sdes	}
1741238106Sdes
1742238106Sdes	tf_policy = 0;
1743238106Sdes	/* < not <=, because although the array is large enough for <=, the
1744238106Sdes	 * generated query will immediately be discarded due to depth and
1745238106Sdes	 * that servfail is cached, which is not good as opportunism goes. */
1746238106Sdes	if(iq->depth < ie->max_dependency_depth
1747238106Sdes		&& iq->sent_count < TARGET_FETCH_STOP) {
1748238106Sdes		tf_policy = ie->target_fetch_policy[iq->depth];
1749238106Sdes	}
1750238106Sdes
1751238106Sdes	/* if in 0x20 fallback get as many targets as possible */
1752238106Sdes	if(iq->caps_fallback) {
1753238106Sdes		int extra = 0;
1754238106Sdes		size_t naddr, nres, navail;
1755238106Sdes		if(!query_for_targets(qstate, iq, ie, id, -1, &extra)) {
1756238106Sdes			return error_response(qstate, id, LDNS_RCODE_SERVFAIL);
1757238106Sdes		}
1758238106Sdes		iq->num_target_queries += extra;
1759275854Sdelphij		target_count_increase(iq, extra);
1760238106Sdes		if(iq->num_target_queries > 0) {
1761238106Sdes			/* wait to get all targets, we want to try em */
1762238106Sdes			verbose(VERB_ALGO, "wait for all targets for fallback");
1763238106Sdes			qstate->ext_state[id] = module_wait_reply;
1764238106Sdes			return 0;
1765238106Sdes		}
1766238106Sdes		/* did we do enough fallback queries already? */
1767238106Sdes		delegpt_count_addr(iq->dp, &naddr, &nres, &navail);
1768238106Sdes		/* the current caps_server is the number of fallbacks sent.
1769238106Sdes		 * the original query is one that matched too, so we have
1770238106Sdes		 * caps_server+1 number of matching queries now */
1771238106Sdes		if(iq->caps_server+1 >= naddr*3 ||
1772238106Sdes			iq->caps_server+1 >= MAX_SENT_COUNT) {
1773238106Sdes			/* we're done, process the response */
1774238106Sdes			verbose(VERB_ALGO, "0x20 fallback had %d responses "
1775238106Sdes				"match for %d wanted, done.",
1776238106Sdes				(int)iq->caps_server+1, (int)naddr*3);
1777238106Sdes			iq->caps_fallback = 0;
1778238106Sdes			iter_dec_attempts(iq->dp, 3); /* space for fallback */
1779238106Sdes			iq->num_current_queries++; /* RespState decrements it*/
1780238106Sdes			iq->referral_count++; /* make sure we don't loop */
1781238106Sdes			iq->sent_count = 0;
1782238106Sdes			iq->state = QUERY_RESP_STATE;
1783238106Sdes			return 1;
1784238106Sdes		}
1785238106Sdes		verbose(VERB_ALGO, "0x20 fallback number %d",
1786238106Sdes			(int)iq->caps_server);
1787238106Sdes
1788238106Sdes	/* if there is a policy to fetch missing targets
1789238106Sdes	 * opportunistically, do it. we rely on the fact that once a
1790238106Sdes	 * query (or queries) for a missing name have been issued,
1791238106Sdes	 * they will not show up again. */
1792238106Sdes	} else if(tf_policy != 0) {
1793238106Sdes		int extra = 0;
1794238106Sdes		verbose(VERB_ALGO, "attempt to get extra %d targets",
1795238106Sdes			tf_policy);
1796238106Sdes		(void)query_for_targets(qstate, iq, ie, id, tf_policy, &extra);
1797238106Sdes		/* errors ignored, these targets are not strictly necessary for
1798238106Sdes		 * this result, we do not have to reply with SERVFAIL */
1799238106Sdes		iq->num_target_queries += extra;
1800275854Sdelphij		target_count_increase(iq, extra);
1801238106Sdes	}
1802238106Sdes
1803238106Sdes	/* Add the current set of unused targets to our queue. */
1804238106Sdes	delegpt_add_unused_targets(iq->dp);
1805238106Sdes
1806238106Sdes	/* Select the next usable target, filtering out unsuitable targets. */
1807238106Sdes	target = iter_server_selection(ie, qstate->env, iq->dp,
1808238106Sdes		iq->dp->name, iq->dp->namelen, iq->qchase.qtype,
1809238106Sdes		&iq->dnssec_lame_query, &iq->chase_to_rd,
1810238106Sdes		iq->num_target_queries, qstate->blacklist);
1811238106Sdes
1812238106Sdes	/* If no usable target was selected... */
1813238106Sdes	if(!target) {
1814238106Sdes		/* Here we distinguish between three states: generate a new
1815238106Sdes		 * target query, just wait, or quit (with a SERVFAIL).
1816238106Sdes		 * We have the following information: number of active
1817238106Sdes		 * target queries, number of active current queries,
1818238106Sdes		 * the presence of missing targets at this delegation
1819238106Sdes		 * point, and the given query target policy. */
1820238106Sdes
1821238106Sdes		/* Check for the wait condition. If this is true, then
1822238106Sdes		 * an action must be taken. */
1823238106Sdes		if(iq->num_target_queries==0 && iq->num_current_queries==0) {
1824238106Sdes			/* If there is nothing to wait for, then we need
1825238106Sdes			 * to distinguish between generating (a) new target
1826238106Sdes			 * query, or failing. */
1827238106Sdes			if(delegpt_count_missing_targets(iq->dp) > 0) {
1828238106Sdes				int qs = 0;
1829238106Sdes				verbose(VERB_ALGO, "querying for next "
1830238106Sdes					"missing target");
1831238106Sdes				if(!query_for_targets(qstate, iq, ie, id,
1832238106Sdes					1, &qs)) {
1833238106Sdes					return error_response(qstate, id,
1834238106Sdes						LDNS_RCODE_SERVFAIL);
1835238106Sdes				}
1836238106Sdes				if(qs == 0 &&
1837238106Sdes				   delegpt_count_missing_targets(iq->dp) == 0){
1838238106Sdes					/* it looked like there were missing
1839238106Sdes					 * targets, but they did not turn up.
1840238106Sdes					 * Try the bad choices again (if any),
1841238106Sdes					 * when we get back here missing==0,
1842238106Sdes					 * so this is not a loop. */
1843238106Sdes					return 1;
1844238106Sdes				}
1845238106Sdes				iq->num_target_queries += qs;
1846275854Sdelphij				target_count_increase(iq, qs);
1847238106Sdes			}
1848238106Sdes			/* Since a target query might have been made, we
1849238106Sdes			 * need to check again. */
1850238106Sdes			if(iq->num_target_queries == 0) {
1851238106Sdes				return processLastResort(qstate, iq, ie, id);
1852238106Sdes			}
1853238106Sdes		}
1854238106Sdes
1855238106Sdes		/* otherwise, we have no current targets, so submerge
1856238106Sdes		 * until one of the target or direct queries return. */
1857238106Sdes		if(iq->num_target_queries>0 && iq->num_current_queries>0) {
1858238106Sdes			verbose(VERB_ALGO, "no current targets -- waiting "
1859238106Sdes				"for %d targets to resolve or %d outstanding"
1860238106Sdes				" queries to respond", iq->num_target_queries,
1861238106Sdes				iq->num_current_queries);
1862238106Sdes			qstate->ext_state[id] = module_wait_reply;
1863238106Sdes		} else if(iq->num_target_queries>0) {
1864238106Sdes			verbose(VERB_ALGO, "no current targets -- waiting "
1865238106Sdes				"for %d targets to resolve.",
1866238106Sdes				iq->num_target_queries);
1867238106Sdes			qstate->ext_state[id] = module_wait_subquery;
1868238106Sdes		} else {
1869238106Sdes			verbose(VERB_ALGO, "no current targets -- waiting "
1870238106Sdes				"for %d outstanding queries to respond.",
1871238106Sdes				iq->num_current_queries);
1872238106Sdes			qstate->ext_state[id] = module_wait_reply;
1873238106Sdes		}
1874238106Sdes		return 0;
1875238106Sdes	}
1876238106Sdes
1877238106Sdes	/* We have a valid target. */
1878238106Sdes	if(verbosity >= VERB_QUERY) {
1879238106Sdes		log_query_info(VERB_QUERY, "sending query:", &iq->qchase);
1880238106Sdes		log_name_addr(VERB_QUERY, "sending to target:", iq->dp->name,
1881238106Sdes			&target->addr, target->addrlen);
1882238106Sdes		verbose(VERB_ALGO, "dnssec status: %s%s",
1883238106Sdes			iq->dnssec_expected?"expected": "not expected",
1884238106Sdes			iq->dnssec_lame_query?" but lame_query anyway": "");
1885238106Sdes	}
1886238106Sdes	fptr_ok(fptr_whitelist_modenv_send_query(qstate->env->send_query));
1887238106Sdes	outq = (*qstate->env->send_query)(
1888238106Sdes		iq->qchase.qname, iq->qchase.qname_len,
1889238106Sdes		iq->qchase.qtype, iq->qchase.qclass,
1890238106Sdes		iq->chase_flags | (iq->chase_to_rd?BIT_RD:0), EDNS_DO|BIT_CD,
1891238106Sdes		iq->dnssec_expected, &target->addr, target->addrlen,
1892238106Sdes		iq->dp->name, iq->dp->namelen, qstate);
1893238106Sdes	if(!outq) {
1894238106Sdes		log_addr(VERB_DETAIL, "error sending query to auth server",
1895238106Sdes			&target->addr, target->addrlen);
1896238106Sdes		return next_state(iq, QUERYTARGETS_STATE);
1897238106Sdes	}
1898238106Sdes	outbound_list_insert(&iq->outlist, outq);
1899238106Sdes	iq->num_current_queries++;
1900238106Sdes	iq->sent_count++;
1901238106Sdes	qstate->ext_state[id] = module_wait_reply;
1902238106Sdes
1903238106Sdes	return 0;
1904238106Sdes}
1905238106Sdes
1906238106Sdes/** find NS rrset in given list */
1907238106Sdesstatic struct ub_packed_rrset_key*
1908238106Sdesfind_NS(struct reply_info* rep, size_t from, size_t to)
1909238106Sdes{
1910238106Sdes	size_t i;
1911238106Sdes	for(i=from; i<to; i++) {
1912238106Sdes		if(ntohs(rep->rrsets[i]->rk.type) == LDNS_RR_TYPE_NS)
1913238106Sdes			return rep->rrsets[i];
1914238106Sdes	}
1915238106Sdes	return NULL;
1916238106Sdes}
1917238106Sdes
1918238106Sdes
1919238106Sdes/**
1920238106Sdes * Process the query response. All queries end up at this state first. This
1921238106Sdes * process generally consists of analyzing the response and routing the
1922238106Sdes * event to the next state (either bouncing it back to a request state, or
1923238106Sdes * terminating the processing for this event).
1924238106Sdes *
1925238106Sdes * @param qstate: query state.
1926238106Sdes * @param iq: iterator query state.
1927238106Sdes * @param id: module id.
1928238106Sdes * @return true if the event requires more immediate processing, false if
1929238106Sdes *         not. This is generally only true when forwarding the request to
1930238106Sdes *         the final state (i.e., on answer).
1931238106Sdes */
1932238106Sdesstatic int
1933238106SdesprocessQueryResponse(struct module_qstate* qstate, struct iter_qstate* iq,
1934238106Sdes	int id)
1935238106Sdes{
1936238106Sdes	int dnsseclame = 0;
1937238106Sdes	enum response_type type;
1938238106Sdes	iq->num_current_queries--;
1939238106Sdes	if(iq->response == NULL) {
1940238106Sdes		iq->chase_to_rd = 0;
1941238106Sdes		iq->dnssec_lame_query = 0;
1942238106Sdes		verbose(VERB_ALGO, "query response was timeout");
1943238106Sdes		return next_state(iq, QUERYTARGETS_STATE);
1944238106Sdes	}
1945238106Sdes	type = response_type_from_server(
1946238106Sdes		(int)((iq->chase_flags&BIT_RD) || iq->chase_to_rd),
1947238106Sdes		iq->response, &iq->qchase, iq->dp);
1948238106Sdes	iq->chase_to_rd = 0;
1949238106Sdes	if(type == RESPONSE_TYPE_REFERRAL && (iq->chase_flags&BIT_RD)) {
1950238106Sdes		/* When forwarding (RD bit is set), we handle referrals
1951238106Sdes		 * differently. No queries should be sent elsewhere */
1952238106Sdes		type = RESPONSE_TYPE_ANSWER;
1953238106Sdes	}
1954238106Sdes	if(iq->dnssec_expected && !iq->dnssec_lame_query &&
1955238106Sdes		!(iq->chase_flags&BIT_RD)
1956238106Sdes		&& type != RESPONSE_TYPE_LAME
1957238106Sdes		&& type != RESPONSE_TYPE_REC_LAME
1958238106Sdes		&& type != RESPONSE_TYPE_THROWAWAY
1959238106Sdes		&& type != RESPONSE_TYPE_UNTYPED) {
1960238106Sdes		/* a possible answer, see if it is missing DNSSEC */
1961238106Sdes		/* but not when forwarding, so we dont mark fwder lame */
1962269257Sdes		if(!iter_msg_has_dnssec(iq->response)) {
1963269257Sdes			/* Mark this address as dnsseclame in this dp,
1964269257Sdes			 * because that will make serverselection disprefer
1965269257Sdes			 * it, but also, once it is the only final option,
1966269257Sdes			 * use dnssec-lame-bypass if it needs to query there.*/
1967269257Sdes			if(qstate->reply) {
1968269257Sdes				struct delegpt_addr* a = delegpt_find_addr(
1969269257Sdes					iq->dp, &qstate->reply->addr,
1970269257Sdes					qstate->reply->addrlen);
1971269257Sdes				if(a) a->dnsseclame = 1;
1972269257Sdes			}
1973269257Sdes			/* test the answer is from the zone we expected,
1974269257Sdes		 	 * otherwise, (due to parent,child on same server), we
1975269257Sdes		 	 * might mark the server,zone lame inappropriately */
1976269257Sdes			if(!iter_msg_from_zone(iq->response, iq->dp, type,
1977269257Sdes				iq->qchase.qclass))
1978269257Sdes				qstate->reply = NULL;
1979238106Sdes			type = RESPONSE_TYPE_LAME;
1980238106Sdes			dnsseclame = 1;
1981238106Sdes		}
1982238106Sdes	} else iq->dnssec_lame_query = 0;
1983238106Sdes	/* see if referral brings us close to the target */
1984238106Sdes	if(type == RESPONSE_TYPE_REFERRAL) {
1985238106Sdes		struct ub_packed_rrset_key* ns = find_NS(
1986238106Sdes			iq->response->rep, iq->response->rep->an_numrrsets,
1987238106Sdes			iq->response->rep->an_numrrsets
1988238106Sdes			+ iq->response->rep->ns_numrrsets);
1989238106Sdes		if(!ns) ns = find_NS(iq->response->rep, 0,
1990238106Sdes				iq->response->rep->an_numrrsets);
1991238106Sdes		if(!ns || !dname_strict_subdomain_c(ns->rk.dname, iq->dp->name)
1992238106Sdes			|| !dname_subdomain_c(iq->qchase.qname, ns->rk.dname)){
1993238106Sdes			verbose(VERB_ALGO, "bad referral, throwaway");
1994238106Sdes			type = RESPONSE_TYPE_THROWAWAY;
1995238106Sdes		} else
1996238106Sdes			iter_scrub_ds(iq->response, ns, iq->dp->name);
1997238106Sdes	} else iter_scrub_ds(iq->response, NULL, NULL);
1998238106Sdes
1999238106Sdes	/* handle each of the type cases */
2000238106Sdes	if(type == RESPONSE_TYPE_ANSWER) {
2001238106Sdes		/* ANSWER type responses terminate the query algorithm,
2002238106Sdes		 * so they sent on their */
2003238106Sdes		if(verbosity >= VERB_DETAIL) {
2004238106Sdes			verbose(VERB_DETAIL, "query response was %s",
2005238106Sdes				FLAGS_GET_RCODE(iq->response->rep->flags)
2006238106Sdes				==LDNS_RCODE_NXDOMAIN?"NXDOMAIN ANSWER":
2007238106Sdes				(iq->response->rep->an_numrrsets?"ANSWER":
2008238106Sdes				"nodata ANSWER"));
2009238106Sdes		}
2010238106Sdes		/* if qtype is DS, check we have the right level of answer,
2011238106Sdes		 * like grandchild answer but we need the middle, reject it */
2012238106Sdes		if(iq->qchase.qtype == LDNS_RR_TYPE_DS && !iq->dsns_point
2013238106Sdes			&& !(iq->chase_flags&BIT_RD)
2014238106Sdes			&& iter_ds_toolow(iq->response, iq->dp)
2015249141Sdes			&& iter_dp_cangodown(&iq->qchase, iq->dp)) {
2016249141Sdes			/* close down outstanding requests to be discarded */
2017249141Sdes			outbound_list_clear(&iq->outlist);
2018249141Sdes			iq->num_current_queries = 0;
2019249141Sdes			fptr_ok(fptr_whitelist_modenv_detach_subs(
2020249141Sdes				qstate->env->detach_subs));
2021249141Sdes			(*qstate->env->detach_subs)(qstate);
2022249141Sdes			iq->num_target_queries = 0;
2023238106Sdes			return processDSNSFind(qstate, iq, id);
2024249141Sdes		}
2025249141Sdes		iter_dns_store(qstate->env, &iq->response->qinfo,
2026238106Sdes			iq->response->rep, 0, qstate->prefetch_leeway,
2027238106Sdes			iq->dp&&iq->dp->has_parent_side_NS,
2028249141Sdes			qstate->region);
2029238106Sdes		/* close down outstanding requests to be discarded */
2030238106Sdes		outbound_list_clear(&iq->outlist);
2031238106Sdes		iq->num_current_queries = 0;
2032238106Sdes		fptr_ok(fptr_whitelist_modenv_detach_subs(
2033238106Sdes			qstate->env->detach_subs));
2034238106Sdes		(*qstate->env->detach_subs)(qstate);
2035238106Sdes		iq->num_target_queries = 0;
2036238106Sdes		if(qstate->reply)
2037238106Sdes			sock_list_insert(&qstate->reply_origin,
2038238106Sdes				&qstate->reply->addr, qstate->reply->addrlen,
2039238106Sdes				qstate->region);
2040238106Sdes		return final_state(iq);
2041238106Sdes	} else if(type == RESPONSE_TYPE_REFERRAL) {
2042238106Sdes		/* REFERRAL type responses get a reset of the
2043238106Sdes		 * delegation point, and back to the QUERYTARGETS_STATE. */
2044238106Sdes		verbose(VERB_DETAIL, "query response was REFERRAL");
2045238106Sdes
2046238106Sdes		/* if hardened, only store referral if we asked for it */
2047238106Sdes		if(!qstate->env->cfg->harden_referral_path ||
2048238106Sdes		    (  qstate->qinfo.qtype == LDNS_RR_TYPE_NS
2049238106Sdes			&& (qstate->query_flags&BIT_RD)
2050238106Sdes			&& !(qstate->query_flags&BIT_CD)
2051238106Sdes			   /* we know that all other NS rrsets are scrubbed
2052238106Sdes			    * away, thus on referral only one is left.
2053238106Sdes			    * see if that equals the query name... */
2054238106Sdes			&& ( /* auth section, but sometimes in answer section*/
2055238106Sdes			  reply_find_rrset_section_ns(iq->response->rep,
2056238106Sdes				iq->qchase.qname, iq->qchase.qname_len,
2057238106Sdes				LDNS_RR_TYPE_NS, iq->qchase.qclass)
2058238106Sdes			  || reply_find_rrset_section_an(iq->response->rep,
2059238106Sdes				iq->qchase.qname, iq->qchase.qname_len,
2060238106Sdes				LDNS_RR_TYPE_NS, iq->qchase.qclass)
2061238106Sdes			  )
2062238106Sdes		    )) {
2063238106Sdes			/* Store the referral under the current query */
2064238106Sdes			/* no prefetch-leeway, since its not the answer */
2065249141Sdes			iter_dns_store(qstate->env, &iq->response->qinfo,
2066249141Sdes				iq->response->rep, 1, 0, 0, NULL);
2067238106Sdes			if(iq->store_parent_NS)
2068238106Sdes				iter_store_parentside_NS(qstate->env,
2069238106Sdes					iq->response->rep);
2070238106Sdes			if(qstate->env->neg_cache)
2071238106Sdes				val_neg_addreferral(qstate->env->neg_cache,
2072238106Sdes					iq->response->rep, iq->dp->name);
2073238106Sdes		}
2074238106Sdes		/* store parent-side-in-zone-glue, if directly queried for */
2075238106Sdes		if(iq->query_for_pside_glue && !iq->pside_glue) {
2076238106Sdes			iq->pside_glue = reply_find_rrset(iq->response->rep,
2077238106Sdes				iq->qchase.qname, iq->qchase.qname_len,
2078238106Sdes				iq->qchase.qtype, iq->qchase.qclass);
2079238106Sdes			if(iq->pside_glue) {
2080238106Sdes				log_rrset_key(VERB_ALGO, "found parent-side "
2081238106Sdes					"glue", iq->pside_glue);
2082238106Sdes				iter_store_parentside_rrset(qstate->env,
2083238106Sdes					iq->pside_glue);
2084238106Sdes			}
2085238106Sdes		}
2086238106Sdes
2087238106Sdes		/* Reset the event state, setting the current delegation
2088238106Sdes		 * point to the referral. */
2089238106Sdes		iq->deleg_msg = iq->response;
2090238106Sdes		iq->dp = delegpt_from_message(iq->response, qstate->region);
2091238106Sdes		if(!iq->dp)
2092238106Sdes			return error_response(qstate, id, LDNS_RCODE_SERVFAIL);
2093238106Sdes		if(!cache_fill_missing(qstate->env, iq->qchase.qclass,
2094238106Sdes			qstate->region, iq->dp))
2095238106Sdes			return error_response(qstate, id, LDNS_RCODE_SERVFAIL);
2096238106Sdes		if(iq->store_parent_NS && query_dname_compare(iq->dp->name,
2097238106Sdes			iq->store_parent_NS->name) == 0)
2098238106Sdes			iter_merge_retry_counts(iq->dp, iq->store_parent_NS);
2099238106Sdes		delegpt_log(VERB_ALGO, iq->dp);
2100238106Sdes		/* Count this as a referral. */
2101238106Sdes		iq->referral_count++;
2102238106Sdes		iq->sent_count = 0;
2103238106Sdes		/* see if the next dp is a trust anchor, or a DS was sent
2104238106Sdes		 * along, indicating dnssec is expected for next zone */
2105238106Sdes		iq->dnssec_expected = iter_indicates_dnssec(qstate->env,
2106238106Sdes			iq->dp, iq->response, iq->qchase.qclass);
2107238106Sdes		/* if dnssec, validating then also fetch the key for the DS */
2108238106Sdes		if(iq->dnssec_expected && qstate->env->cfg->prefetch_key &&
2109238106Sdes			!(qstate->query_flags&BIT_CD))
2110238106Sdes			generate_dnskey_prefetch(qstate, iq, id);
2111238106Sdes
2112238106Sdes		/* spawn off NS and addr to auth servers for the NS we just
2113238106Sdes		 * got in the referral. This gets authoritative answer
2114238106Sdes		 * (answer section trust level) rrset.
2115238106Sdes		 * right after, we detach the subs, answer goes to cache. */
2116238106Sdes		if(qstate->env->cfg->harden_referral_path)
2117238106Sdes			generate_ns_check(qstate, iq, id);
2118238106Sdes
2119238106Sdes		/* stop current outstanding queries.
2120238106Sdes		 * FIXME: should the outstanding queries be waited for and
2121238106Sdes		 * handled? Say by a subquery that inherits the outbound_entry.
2122238106Sdes		 */
2123238106Sdes		outbound_list_clear(&iq->outlist);
2124238106Sdes		iq->num_current_queries = 0;
2125238106Sdes		fptr_ok(fptr_whitelist_modenv_detach_subs(
2126238106Sdes			qstate->env->detach_subs));
2127238106Sdes		(*qstate->env->detach_subs)(qstate);
2128238106Sdes		iq->num_target_queries = 0;
2129238106Sdes		verbose(VERB_ALGO, "cleared outbound list for next round");
2130238106Sdes		return next_state(iq, QUERYTARGETS_STATE);
2131238106Sdes	} else if(type == RESPONSE_TYPE_CNAME) {
2132238106Sdes		uint8_t* sname = NULL;
2133238106Sdes		size_t snamelen = 0;
2134238106Sdes		/* CNAME type responses get a query restart (i.e., get a
2135238106Sdes		 * reset of the query state and go back to INIT_REQUEST_STATE).
2136238106Sdes		 */
2137238106Sdes		verbose(VERB_DETAIL, "query response was CNAME");
2138238106Sdes		if(verbosity >= VERB_ALGO)
2139238106Sdes			log_dns_msg("cname msg", &iq->response->qinfo,
2140238106Sdes				iq->response->rep);
2141238106Sdes		/* if qtype is DS, check we have the right level of answer,
2142238106Sdes		 * like grandchild answer but we need the middle, reject it */
2143238106Sdes		if(iq->qchase.qtype == LDNS_RR_TYPE_DS && !iq->dsns_point
2144238106Sdes			&& !(iq->chase_flags&BIT_RD)
2145238106Sdes			&& iter_ds_toolow(iq->response, iq->dp)
2146249141Sdes			&& iter_dp_cangodown(&iq->qchase, iq->dp)) {
2147249141Sdes			outbound_list_clear(&iq->outlist);
2148249141Sdes			iq->num_current_queries = 0;
2149249141Sdes			fptr_ok(fptr_whitelist_modenv_detach_subs(
2150249141Sdes				qstate->env->detach_subs));
2151249141Sdes			(*qstate->env->detach_subs)(qstate);
2152249141Sdes			iq->num_target_queries = 0;
2153238106Sdes			return processDSNSFind(qstate, iq, id);
2154249141Sdes		}
2155238106Sdes		/* Process the CNAME response. */
2156238106Sdes		if(!handle_cname_response(qstate, iq, iq->response,
2157238106Sdes			&sname, &snamelen))
2158238106Sdes			return error_response(qstate, id, LDNS_RCODE_SERVFAIL);
2159238106Sdes		/* cache the CNAME response under the current query */
2160238106Sdes		/* NOTE : set referral=1, so that rrsets get stored but not
2161238106Sdes		 * the partial query answer (CNAME only). */
2162238106Sdes		/* prefetchleeway applied because this updates answer parts */
2163249141Sdes		iter_dns_store(qstate->env, &iq->response->qinfo,
2164238106Sdes			iq->response->rep, 1, qstate->prefetch_leeway,
2165249141Sdes			iq->dp&&iq->dp->has_parent_side_NS, NULL);
2166238106Sdes		/* set the current request's qname to the new value. */
2167238106Sdes		iq->qchase.qname = sname;
2168238106Sdes		iq->qchase.qname_len = snamelen;
2169238106Sdes		/* Clear the query state, since this is a query restart. */
2170238106Sdes		iq->deleg_msg = NULL;
2171238106Sdes		iq->dp = NULL;
2172238106Sdes		iq->dsns_point = NULL;
2173238106Sdes		/* Note the query restart. */
2174238106Sdes		iq->query_restart_count++;
2175238106Sdes		iq->sent_count = 0;
2176238106Sdes
2177238106Sdes		/* stop current outstanding queries.
2178238106Sdes		 * FIXME: should the outstanding queries be waited for and
2179238106Sdes		 * handled? Say by a subquery that inherits the outbound_entry.
2180238106Sdes		 */
2181238106Sdes		outbound_list_clear(&iq->outlist);
2182238106Sdes		iq->num_current_queries = 0;
2183238106Sdes		fptr_ok(fptr_whitelist_modenv_detach_subs(
2184238106Sdes			qstate->env->detach_subs));
2185238106Sdes		(*qstate->env->detach_subs)(qstate);
2186238106Sdes		iq->num_target_queries = 0;
2187238106Sdes		if(qstate->reply)
2188238106Sdes			sock_list_insert(&qstate->reply_origin,
2189238106Sdes				&qstate->reply->addr, qstate->reply->addrlen,
2190238106Sdes				qstate->region);
2191238106Sdes		verbose(VERB_ALGO, "cleared outbound list for query restart");
2192238106Sdes		/* go to INIT_REQUEST_STATE for new qname. */
2193238106Sdes		return next_state(iq, INIT_REQUEST_STATE);
2194238106Sdes	} else if(type == RESPONSE_TYPE_LAME) {
2195238106Sdes		/* Cache the LAMEness. */
2196238106Sdes		verbose(VERB_DETAIL, "query response was %sLAME",
2197238106Sdes			dnsseclame?"DNSSEC ":"");
2198238106Sdes		if(!dname_subdomain_c(iq->qchase.qname, iq->dp->name)) {
2199238106Sdes			log_err("mark lame: mismatch in qname and dpname");
2200238106Sdes			/* throwaway this reply below */
2201238106Sdes		} else if(qstate->reply) {
2202238106Sdes			/* need addr for lameness cache, but we may have
2203238106Sdes			 * gotten this from cache, so test to be sure */
2204238106Sdes			if(!infra_set_lame(qstate->env->infra_cache,
2205238106Sdes				&qstate->reply->addr, qstate->reply->addrlen,
2206238106Sdes				iq->dp->name, iq->dp->namelen,
2207238106Sdes				*qstate->env->now, dnsseclame, 0,
2208238106Sdes				iq->qchase.qtype))
2209238106Sdes				log_err("mark host lame: out of memory");
2210269257Sdes		}
2211238106Sdes	} else if(type == RESPONSE_TYPE_REC_LAME) {
2212238106Sdes		/* Cache the LAMEness. */
2213238106Sdes		verbose(VERB_DETAIL, "query response REC_LAME: "
2214238106Sdes			"recursive but not authoritative server");
2215238106Sdes		if(!dname_subdomain_c(iq->qchase.qname, iq->dp->name)) {
2216238106Sdes			log_err("mark rec_lame: mismatch in qname and dpname");
2217238106Sdes			/* throwaway this reply below */
2218238106Sdes		} else if(qstate->reply) {
2219238106Sdes			/* need addr for lameness cache, but we may have
2220238106Sdes			 * gotten this from cache, so test to be sure */
2221238106Sdes			verbose(VERB_DETAIL, "mark as REC_LAME");
2222238106Sdes			if(!infra_set_lame(qstate->env->infra_cache,
2223238106Sdes				&qstate->reply->addr, qstate->reply->addrlen,
2224238106Sdes				iq->dp->name, iq->dp->namelen,
2225238106Sdes				*qstate->env->now, 0, 1, iq->qchase.qtype))
2226238106Sdes				log_err("mark host lame: out of memory");
2227238106Sdes		}
2228238106Sdes	} else if(type == RESPONSE_TYPE_THROWAWAY) {
2229238106Sdes		/* LAME and THROWAWAY responses are handled the same way.
2230238106Sdes		 * In this case, the event is just sent directly back to
2231238106Sdes		 * the QUERYTARGETS_STATE without resetting anything,
2232238106Sdes		 * because, clearly, the next target must be tried. */
2233238106Sdes		verbose(VERB_DETAIL, "query response was THROWAWAY");
2234238106Sdes	} else {
2235238106Sdes		log_warn("A query response came back with an unknown type: %d",
2236238106Sdes			(int)type);
2237238106Sdes	}
2238238106Sdes
2239238106Sdes	/* LAME, THROWAWAY and "unknown" all end up here.
2240238106Sdes	 * Recycle to the QUERYTARGETS state to hopefully try a
2241238106Sdes	 * different target. */
2242238106Sdes	return next_state(iq, QUERYTARGETS_STATE);
2243238106Sdes}
2244238106Sdes
2245238106Sdes/**
2246238106Sdes * Return priming query results to interestes super querystates.
2247238106Sdes *
2248238106Sdes * Sets the delegation point and delegation message (not nonRD queries).
2249238106Sdes * This is a callback from walk_supers.
2250238106Sdes *
2251238106Sdes * @param qstate: priming query state that finished.
2252238106Sdes * @param id: module id.
2253238106Sdes * @param forq: the qstate for which priming has been done.
2254238106Sdes */
2255238106Sdesstatic void
2256238106Sdesprime_supers(struct module_qstate* qstate, int id, struct module_qstate* forq)
2257238106Sdes{
2258238106Sdes	struct iter_qstate* foriq = (struct iter_qstate*)forq->minfo[id];
2259238106Sdes	struct delegpt* dp = NULL;
2260238106Sdes
2261238106Sdes	log_assert(qstate->is_priming || foriq->wait_priming_stub);
2262238106Sdes	log_assert(qstate->return_rcode == LDNS_RCODE_NOERROR);
2263238106Sdes	/* Convert our response to a delegation point */
2264238106Sdes	dp = delegpt_from_message(qstate->return_msg, forq->region);
2265238106Sdes	if(!dp) {
2266238106Sdes		/* if there is no convertable delegation point, then
2267238106Sdes		 * the ANSWER type was (presumably) a negative answer. */
2268238106Sdes		verbose(VERB_ALGO, "prime response was not a positive "
2269238106Sdes			"ANSWER; failing");
2270238106Sdes		foriq->dp = NULL;
2271238106Sdes		foriq->state = QUERYTARGETS_STATE;
2272238106Sdes		return;
2273238106Sdes	}
2274238106Sdes
2275238106Sdes	log_query_info(VERB_DETAIL, "priming successful for", &qstate->qinfo);
2276238106Sdes	delegpt_log(VERB_ALGO, dp);
2277238106Sdes	foriq->dp = dp;
2278238106Sdes	foriq->deleg_msg = dns_copy_msg(qstate->return_msg, forq->region);
2279238106Sdes	if(!foriq->deleg_msg) {
2280238106Sdes		log_err("copy prime response: out of memory");
2281238106Sdes		foriq->dp = NULL;
2282238106Sdes		foriq->state = QUERYTARGETS_STATE;
2283238106Sdes		return;
2284238106Sdes	}
2285238106Sdes
2286238106Sdes	/* root priming responses go to init stage 2, priming stub
2287238106Sdes	 * responses to to stage 3. */
2288238106Sdes	if(foriq->wait_priming_stub) {
2289238106Sdes		foriq->state = INIT_REQUEST_3_STATE;
2290238106Sdes		foriq->wait_priming_stub = 0;
2291238106Sdes	} else	foriq->state = INIT_REQUEST_2_STATE;
2292238106Sdes	/* because we are finished, the parent will be reactivated */
2293238106Sdes}
2294238106Sdes
2295238106Sdes/**
2296238106Sdes * This handles the response to a priming query. This is used to handle both
2297238106Sdes * root and stub priming responses. This is basically the equivalent of the
2298238106Sdes * QUERY_RESP_STATE, but will not handle CNAME responses and will treat
2299238106Sdes * REFERRALs as ANSWERS. It will also update and reactivate the originating
2300238106Sdes * event.
2301238106Sdes *
2302238106Sdes * @param qstate: query state.
2303238106Sdes * @param id: module id.
2304238106Sdes * @return true if the event needs more immediate processing, false if not.
2305238106Sdes *         This state always returns false.
2306238106Sdes */
2307238106Sdesstatic int
2308238106SdesprocessPrimeResponse(struct module_qstate* qstate, int id)
2309238106Sdes{
2310238106Sdes	struct iter_qstate* iq = (struct iter_qstate*)qstate->minfo[id];
2311238106Sdes	enum response_type type;
2312238106Sdes	iq->response->rep->flags &= ~(BIT_RD|BIT_RA); /* ignore rec-lame */
2313238106Sdes	type = response_type_from_server(
2314238106Sdes		(int)((iq->chase_flags&BIT_RD) || iq->chase_to_rd),
2315238106Sdes		iq->response, &iq->qchase, iq->dp);
2316238106Sdes	if(type == RESPONSE_TYPE_ANSWER) {
2317238106Sdes		qstate->return_rcode = LDNS_RCODE_NOERROR;
2318238106Sdes		qstate->return_msg = iq->response;
2319238106Sdes	} else {
2320238106Sdes		qstate->return_rcode = LDNS_RCODE_SERVFAIL;
2321238106Sdes		qstate->return_msg = NULL;
2322238106Sdes	}
2323238106Sdes
2324238106Sdes	/* validate the root or stub after priming (if enabled).
2325238106Sdes	 * This is the same query as the prime query, but with validation.
2326238106Sdes	 * Now that we are primed, the additional queries that validation
2327238106Sdes	 * may need can be resolved, such as DLV. */
2328238106Sdes	if(qstate->env->cfg->harden_referral_path) {
2329238106Sdes		struct module_qstate* subq = NULL;
2330238106Sdes		log_nametypeclass(VERB_ALGO, "schedule prime validation",
2331238106Sdes			qstate->qinfo.qname, qstate->qinfo.qtype,
2332238106Sdes			qstate->qinfo.qclass);
2333238106Sdes		if(!generate_sub_request(qstate->qinfo.qname,
2334238106Sdes			qstate->qinfo.qname_len, qstate->qinfo.qtype,
2335238106Sdes			qstate->qinfo.qclass, qstate, id, iq,
2336238106Sdes			INIT_REQUEST_STATE, FINISHED_STATE, &subq, 1)) {
2337238106Sdes			verbose(VERB_ALGO, "could not generate prime check");
2338238106Sdes		}
2339238106Sdes		generate_a_aaaa_check(qstate, iq, id);
2340238106Sdes	}
2341238106Sdes
2342238106Sdes	/* This event is finished. */
2343238106Sdes	qstate->ext_state[id] = module_finished;
2344238106Sdes	return 0;
2345238106Sdes}
2346238106Sdes
2347238106Sdes/**
2348238106Sdes * Do final processing on responses to target queries. Events reach this
2349238106Sdes * state after the iterative resolution algorithm terminates. This state is
2350238106Sdes * responsible for reactiving the original event, and housekeeping related
2351238106Sdes * to received target responses (caching, updating the current delegation
2352238106Sdes * point, etc).
2353238106Sdes * Callback from walk_supers for every super state that is interested in
2354238106Sdes * the results from this query.
2355238106Sdes *
2356238106Sdes * @param qstate: query state.
2357238106Sdes * @param id: module id.
2358238106Sdes * @param forq: super query state.
2359238106Sdes */
2360238106Sdesstatic void
2361238106SdesprocessTargetResponse(struct module_qstate* qstate, int id,
2362238106Sdes	struct module_qstate* forq)
2363238106Sdes{
2364238106Sdes	struct iter_qstate* iq = (struct iter_qstate*)qstate->minfo[id];
2365238106Sdes	struct iter_qstate* foriq = (struct iter_qstate*)forq->minfo[id];
2366238106Sdes	struct ub_packed_rrset_key* rrset;
2367238106Sdes	struct delegpt_ns* dpns;
2368238106Sdes	log_assert(qstate->return_rcode == LDNS_RCODE_NOERROR);
2369238106Sdes
2370238106Sdes	foriq->state = QUERYTARGETS_STATE;
2371238106Sdes	log_query_info(VERB_ALGO, "processTargetResponse", &qstate->qinfo);
2372238106Sdes	log_query_info(VERB_ALGO, "processTargetResponse super", &forq->qinfo);
2373238106Sdes
2374238106Sdes	/* check to see if parent event is still interested (in orig name).  */
2375238106Sdes	if(!foriq->dp) {
2376238106Sdes		verbose(VERB_ALGO, "subq: parent not interested, was reset");
2377238106Sdes		return; /* not interested anymore */
2378238106Sdes	}
2379238106Sdes	dpns = delegpt_find_ns(foriq->dp, qstate->qinfo.qname,
2380238106Sdes			qstate->qinfo.qname_len);
2381238106Sdes	if(!dpns) {
2382238106Sdes		/* If not interested, just stop processing this event */
2383238106Sdes		verbose(VERB_ALGO, "subq: parent not interested anymore");
2384238106Sdes		/* could be because parent was jostled out of the cache,
2385238106Sdes		   and a new identical query arrived, that does not want it*/
2386238106Sdes		return;
2387238106Sdes	}
2388238106Sdes
2389238106Sdes	/* Tell the originating event that this target query has finished
2390238106Sdes	 * (regardless if it succeeded or not). */
2391238106Sdes	foriq->num_target_queries--;
2392238106Sdes
2393238106Sdes	/* if iq->query_for_pside_glue then add the pside_glue (marked lame) */
2394238106Sdes	if(iq->pside_glue) {
2395238106Sdes		/* if the pside_glue is NULL, then it could not be found,
2396238106Sdes		 * the done_pside is already set when created and a cache
2397238106Sdes		 * entry created in processFinished so nothing to do here */
2398238106Sdes		log_rrset_key(VERB_ALGO, "add parentside glue to dp",
2399238106Sdes			iq->pside_glue);
2400238106Sdes		if(!delegpt_add_rrset(foriq->dp, forq->region,
2401238106Sdes			iq->pside_glue, 1))
2402238106Sdes			log_err("out of memory adding pside glue");
2403238106Sdes	}
2404238106Sdes
2405238106Sdes	/* This response is relevant to the current query, so we
2406238106Sdes	 * add (attempt to add, anyway) this target(s) and reactivate
2407238106Sdes	 * the original event.
2408238106Sdes	 * NOTE: we could only look for the AnswerRRset if the
2409238106Sdes	 * response type was ANSWER. */
2410238106Sdes	rrset = reply_find_answer_rrset(&iq->qchase, qstate->return_msg->rep);
2411238106Sdes	if(rrset) {
2412238106Sdes		/* if CNAMEs have been followed - add new NS to delegpt. */
2413238106Sdes		/* BTW. RFC 1918 says NS should not have got CNAMEs. Robust. */
2414238106Sdes		if(!delegpt_find_ns(foriq->dp, rrset->rk.dname,
2415238106Sdes			rrset->rk.dname_len)) {
2416238106Sdes			/* if dpns->lame then set newcname ns lame too */
2417238106Sdes			if(!delegpt_add_ns(foriq->dp, forq->region,
2418269257Sdes				rrset->rk.dname, dpns->lame))
2419238106Sdes				log_err("out of memory adding cnamed-ns");
2420238106Sdes		}
2421238106Sdes		/* if dpns->lame then set the address(es) lame too */
2422238106Sdes		if(!delegpt_add_rrset(foriq->dp, forq->region, rrset,
2423269257Sdes			dpns->lame))
2424238106Sdes			log_err("out of memory adding targets");
2425238106Sdes		verbose(VERB_ALGO, "added target response");
2426238106Sdes		delegpt_log(VERB_ALGO, foriq->dp);
2427238106Sdes	} else {
2428238106Sdes		verbose(VERB_ALGO, "iterator TargetResponse failed");
2429238106Sdes		dpns->resolved = 1; /* fail the target */
2430238106Sdes	}
2431238106Sdes}
2432238106Sdes
2433238106Sdes/**
2434238106Sdes * Process response for DS NS Find queries, that attempt to find the delegation
2435238106Sdes * point where we ask the DS query from.
2436238106Sdes *
2437238106Sdes * @param qstate: query state.
2438238106Sdes * @param id: module id.
2439238106Sdes * @param forq: super query state.
2440238106Sdes */
2441238106Sdesstatic void
2442238106SdesprocessDSNSResponse(struct module_qstate* qstate, int id,
2443238106Sdes	struct module_qstate* forq)
2444238106Sdes{
2445238106Sdes	struct iter_qstate* foriq = (struct iter_qstate*)forq->minfo[id];
2446238106Sdes
2447238106Sdes	/* if the finished (iq->response) query has no NS set: continue
2448238106Sdes	 * up to look for the right dp; nothing to change, do DPNSstate */
2449238106Sdes	if(qstate->return_rcode != LDNS_RCODE_NOERROR)
2450238106Sdes		return; /* seek further */
2451238106Sdes	/* find the NS RRset (without allowing CNAMEs) */
2452238106Sdes	if(!reply_find_rrset(qstate->return_msg->rep, qstate->qinfo.qname,
2453238106Sdes		qstate->qinfo.qname_len, LDNS_RR_TYPE_NS,
2454238106Sdes		qstate->qinfo.qclass)){
2455238106Sdes		return; /* seek further */
2456238106Sdes	}
2457238106Sdes
2458238106Sdes	/* else, store as DP and continue at querytargets */
2459238106Sdes	foriq->state = QUERYTARGETS_STATE;
2460238106Sdes	foriq->dp = delegpt_from_message(qstate->return_msg, forq->region);
2461238106Sdes	if(!foriq->dp) {
2462238106Sdes		log_err("out of memory in dsns dp alloc");
2463238106Sdes		return; /* dp==NULL in QUERYTARGETS makes SERVFAIL */
2464238106Sdes	}
2465238106Sdes	/* success, go query the querytargets in the new dp (and go down) */
2466238106Sdes}
2467238106Sdes
2468238106Sdes/**
2469238106Sdes * Process response for qclass=ANY queries for a particular class.
2470238106Sdes * Append to result or error-exit.
2471238106Sdes *
2472238106Sdes * @param qstate: query state.
2473238106Sdes * @param id: module id.
2474238106Sdes * @param forq: super query state.
2475238106Sdes */
2476238106Sdesstatic void
2477238106SdesprocessClassResponse(struct module_qstate* qstate, int id,
2478238106Sdes	struct module_qstate* forq)
2479238106Sdes{
2480238106Sdes	struct iter_qstate* foriq = (struct iter_qstate*)forq->minfo[id];
2481238106Sdes	struct dns_msg* from = qstate->return_msg;
2482238106Sdes	log_query_info(VERB_ALGO, "processClassResponse", &qstate->qinfo);
2483238106Sdes	log_query_info(VERB_ALGO, "processClassResponse super", &forq->qinfo);
2484238106Sdes	if(qstate->return_rcode != LDNS_RCODE_NOERROR) {
2485238106Sdes		/* cause servfail for qclass ANY query */
2486238106Sdes		foriq->response = NULL;
2487238106Sdes		foriq->state = FINISHED_STATE;
2488238106Sdes		return;
2489238106Sdes	}
2490238106Sdes	/* append result */
2491238106Sdes	if(!foriq->response) {
2492238106Sdes		/* allocate the response: copy RCODE, sec_state */
2493238106Sdes		foriq->response = dns_copy_msg(from, forq->region);
2494238106Sdes		if(!foriq->response) {
2495238106Sdes			log_err("malloc failed for qclass ANY response");
2496238106Sdes			foriq->state = FINISHED_STATE;
2497238106Sdes			return;
2498238106Sdes		}
2499238106Sdes		foriq->response->qinfo.qclass = forq->qinfo.qclass;
2500238106Sdes		/* qclass ANY does not receive the AA flag on replies */
2501238106Sdes		foriq->response->rep->authoritative = 0;
2502238106Sdes	} else {
2503238106Sdes		struct dns_msg* to = foriq->response;
2504238106Sdes		/* add _from_ this response _to_ existing collection */
2505238106Sdes		/* if there are records, copy RCODE */
2506238106Sdes		/* lower sec_state if this message is lower */
2507238106Sdes		if(from->rep->rrset_count != 0) {
2508238106Sdes			size_t n = from->rep->rrset_count+to->rep->rrset_count;
2509238106Sdes			struct ub_packed_rrset_key** dest, **d;
2510238106Sdes			/* copy appropriate rcode */
2511238106Sdes			to->rep->flags = from->rep->flags;
2512238106Sdes			/* copy rrsets */
2513238106Sdes			dest = regional_alloc(forq->region, sizeof(dest[0])*n);
2514238106Sdes			if(!dest) {
2515238106Sdes				log_err("malloc failed in collect ANY");
2516238106Sdes				foriq->state = FINISHED_STATE;
2517238106Sdes				return;
2518238106Sdes			}
2519238106Sdes			d = dest;
2520238106Sdes			/* copy AN */
2521238106Sdes			memcpy(dest, to->rep->rrsets, to->rep->an_numrrsets
2522238106Sdes				* sizeof(dest[0]));
2523238106Sdes			dest += to->rep->an_numrrsets;
2524238106Sdes			memcpy(dest, from->rep->rrsets, from->rep->an_numrrsets
2525238106Sdes				* sizeof(dest[0]));
2526238106Sdes			dest += from->rep->an_numrrsets;
2527238106Sdes			/* copy NS */
2528238106Sdes			memcpy(dest, to->rep->rrsets+to->rep->an_numrrsets,
2529238106Sdes				to->rep->ns_numrrsets * sizeof(dest[0]));
2530238106Sdes			dest += to->rep->ns_numrrsets;
2531238106Sdes			memcpy(dest, from->rep->rrsets+from->rep->an_numrrsets,
2532238106Sdes				from->rep->ns_numrrsets * sizeof(dest[0]));
2533238106Sdes			dest += from->rep->ns_numrrsets;
2534238106Sdes			/* copy AR */
2535238106Sdes			memcpy(dest, to->rep->rrsets+to->rep->an_numrrsets+
2536238106Sdes				to->rep->ns_numrrsets,
2537238106Sdes				to->rep->ar_numrrsets * sizeof(dest[0]));
2538238106Sdes			dest += to->rep->ar_numrrsets;
2539238106Sdes			memcpy(dest, from->rep->rrsets+from->rep->an_numrrsets+
2540238106Sdes				from->rep->ns_numrrsets,
2541238106Sdes				from->rep->ar_numrrsets * sizeof(dest[0]));
2542238106Sdes			/* update counts */
2543238106Sdes			to->rep->rrsets = d;
2544238106Sdes			to->rep->an_numrrsets += from->rep->an_numrrsets;
2545238106Sdes			to->rep->ns_numrrsets += from->rep->ns_numrrsets;
2546238106Sdes			to->rep->ar_numrrsets += from->rep->ar_numrrsets;
2547238106Sdes			to->rep->rrset_count = n;
2548238106Sdes		}
2549238106Sdes		if(from->rep->security < to->rep->security) /* lowest sec */
2550238106Sdes			to->rep->security = from->rep->security;
2551238106Sdes		if(from->rep->qdcount != 0) /* insert qd if appropriate */
2552238106Sdes			to->rep->qdcount = from->rep->qdcount;
2553238106Sdes		if(from->rep->ttl < to->rep->ttl) /* use smallest TTL */
2554238106Sdes			to->rep->ttl = from->rep->ttl;
2555238106Sdes		if(from->rep->prefetch_ttl < to->rep->prefetch_ttl)
2556238106Sdes			to->rep->prefetch_ttl = from->rep->prefetch_ttl;
2557238106Sdes	}
2558238106Sdes	/* are we done? */
2559238106Sdes	foriq->num_current_queries --;
2560238106Sdes	if(foriq->num_current_queries == 0)
2561238106Sdes		foriq->state = FINISHED_STATE;
2562238106Sdes}
2563238106Sdes
2564238106Sdes/**
2565238106Sdes * Collect class ANY responses and make them into one response.  This
2566238106Sdes * state is started and it creates queries for all classes (that have
2567238106Sdes * root hints).  The answers are then collected.
2568238106Sdes *
2569238106Sdes * @param qstate: query state.
2570238106Sdes * @param id: module id.
2571238106Sdes * @return true if the event needs more immediate processing, false if not.
2572238106Sdes */
2573238106Sdesstatic int
2574238106SdesprocessCollectClass(struct module_qstate* qstate, int id)
2575238106Sdes{
2576238106Sdes	struct iter_qstate* iq = (struct iter_qstate*)qstate->minfo[id];
2577238106Sdes	struct module_qstate* subq;
2578238106Sdes	/* If qchase.qclass == 0 then send out queries for all classes.
2579238106Sdes	 * Otherwise, do nothing (wait for all answers to arrive and the
2580238106Sdes	 * processClassResponse to put them together, and that moves us
2581238106Sdes	 * towards the Finished state when done. */
2582238106Sdes	if(iq->qchase.qclass == 0) {
2583238106Sdes		uint16_t c = 0;
2584238106Sdes		iq->qchase.qclass = LDNS_RR_CLASS_ANY;
2585238106Sdes		while(iter_get_next_root(qstate->env->hints,
2586238106Sdes			qstate->env->fwds, &c)) {
2587238106Sdes			/* generate query for this class */
2588238106Sdes			log_nametypeclass(VERB_ALGO, "spawn collect query",
2589238106Sdes				qstate->qinfo.qname, qstate->qinfo.qtype, c);
2590238106Sdes			if(!generate_sub_request(qstate->qinfo.qname,
2591238106Sdes				qstate->qinfo.qname_len, qstate->qinfo.qtype,
2592238106Sdes				c, qstate, id, iq, INIT_REQUEST_STATE,
2593238106Sdes				FINISHED_STATE, &subq,
2594238106Sdes				(int)!(qstate->query_flags&BIT_CD))) {
2595238106Sdes				return error_response(qstate, id,
2596238106Sdes					LDNS_RCODE_SERVFAIL);
2597238106Sdes			}
2598238106Sdes			/* ignore subq, no special init required */
2599238106Sdes			iq->num_current_queries ++;
2600238106Sdes			if(c == 0xffff)
2601238106Sdes				break;
2602238106Sdes			else c++;
2603238106Sdes		}
2604238106Sdes		/* if no roots are configured at all, return */
2605238106Sdes		if(iq->num_current_queries == 0) {
2606238106Sdes			verbose(VERB_ALGO, "No root hints or fwds, giving up "
2607238106Sdes				"on qclass ANY");
2608238106Sdes			return error_response(qstate, id, LDNS_RCODE_REFUSED);
2609238106Sdes		}
2610238106Sdes		/* return false, wait for queries to return */
2611238106Sdes	}
2612238106Sdes	/* if woke up here because of an answer, wait for more answers */
2613238106Sdes	return 0;
2614238106Sdes}
2615238106Sdes
2616238106Sdes/**
2617238106Sdes * This handles the final state for first-tier responses (i.e., responses to
2618238106Sdes * externally generated queries).
2619238106Sdes *
2620238106Sdes * @param qstate: query state.
2621238106Sdes * @param iq: iterator query state.
2622238106Sdes * @param id: module id.
2623238106Sdes * @return true if the event needs more processing, false if not. Since this
2624238106Sdes *         is the final state for an event, it always returns false.
2625238106Sdes */
2626238106Sdesstatic int
2627238106SdesprocessFinished(struct module_qstate* qstate, struct iter_qstate* iq,
2628238106Sdes	int id)
2629238106Sdes{
2630238106Sdes	log_query_info(VERB_QUERY, "finishing processing for",
2631238106Sdes		&qstate->qinfo);
2632238106Sdes
2633238106Sdes	/* store negative cache element for parent side glue. */
2634238106Sdes	if(iq->query_for_pside_glue && !iq->pside_glue)
2635238106Sdes		iter_store_parentside_neg(qstate->env, &qstate->qinfo,
2636238106Sdes			iq->deleg_msg?iq->deleg_msg->rep:
2637238106Sdes			(iq->response?iq->response->rep:NULL));
2638238106Sdes	if(!iq->response) {
2639238106Sdes		verbose(VERB_ALGO, "No response is set, servfail");
2640238106Sdes		return error_response(qstate, id, LDNS_RCODE_SERVFAIL);
2641238106Sdes	}
2642238106Sdes
2643238106Sdes	/* Make sure that the RA flag is set (since the presence of
2644238106Sdes	 * this module means that recursion is available) */
2645238106Sdes	iq->response->rep->flags |= BIT_RA;
2646238106Sdes
2647238106Sdes	/* Clear the AA flag */
2648238106Sdes	/* FIXME: does this action go here or in some other module? */
2649238106Sdes	iq->response->rep->flags &= ~BIT_AA;
2650238106Sdes
2651238106Sdes	/* make sure QR flag is on */
2652238106Sdes	iq->response->rep->flags |= BIT_QR;
2653238106Sdes
2654238106Sdes	/* we have finished processing this query */
2655238106Sdes	qstate->ext_state[id] = module_finished;
2656238106Sdes
2657238106Sdes	/* TODO:  we are using a private TTL, trim the response. */
2658238106Sdes	/* if (mPrivateTTL > 0){IterUtils.setPrivateTTL(resp, mPrivateTTL); } */
2659238106Sdes
2660238106Sdes	/* prepend any items we have accumulated */
2661238106Sdes	if(iq->an_prepend_list || iq->ns_prepend_list) {
2662238106Sdes		if(!iter_prepend(iq, iq->response, qstate->region)) {
2663238106Sdes			log_err("prepend rrsets: out of memory");
2664238106Sdes			return error_response(qstate, id, LDNS_RCODE_SERVFAIL);
2665238106Sdes		}
2666238106Sdes		/* reset the query name back */
2667238106Sdes		iq->response->qinfo = qstate->qinfo;
2668238106Sdes		/* the security state depends on the combination */
2669238106Sdes		iq->response->rep->security = sec_status_unchecked;
2670238106Sdes		/* store message with the finished prepended items,
2671238106Sdes		 * but only if we did recursion. The nonrecursion referral
2672238106Sdes		 * from cache does not need to be stored in the msg cache. */
2673238106Sdes		if(qstate->query_flags&BIT_RD) {
2674249141Sdes			iter_dns_store(qstate->env, &qstate->qinfo,
2675238106Sdes				iq->response->rep, 0, qstate->prefetch_leeway,
2676238106Sdes				iq->dp&&iq->dp->has_parent_side_NS,
2677249141Sdes				qstate->region);
2678238106Sdes		}
2679238106Sdes	}
2680238106Sdes	qstate->return_rcode = LDNS_RCODE_NOERROR;
2681238106Sdes	qstate->return_msg = iq->response;
2682238106Sdes	return 0;
2683238106Sdes}
2684238106Sdes
2685238106Sdes/*
2686238106Sdes * Return priming query results to interestes super querystates.
2687238106Sdes *
2688238106Sdes * Sets the delegation point and delegation message (not nonRD queries).
2689238106Sdes * This is a callback from walk_supers.
2690238106Sdes *
2691238106Sdes * @param qstate: query state that finished.
2692238106Sdes * @param id: module id.
2693238106Sdes * @param super: the qstate to inform.
2694238106Sdes */
2695238106Sdesvoid
2696238106Sdesiter_inform_super(struct module_qstate* qstate, int id,
2697238106Sdes	struct module_qstate* super)
2698238106Sdes{
2699238106Sdes	if(!qstate->is_priming && super->qinfo.qclass == LDNS_RR_CLASS_ANY)
2700238106Sdes		processClassResponse(qstate, id, super);
2701238106Sdes	else if(super->qinfo.qtype == LDNS_RR_TYPE_DS && ((struct iter_qstate*)
2702238106Sdes		super->minfo[id])->state == DSNS_FIND_STATE)
2703238106Sdes		processDSNSResponse(qstate, id, super);
2704238106Sdes	else if(qstate->return_rcode != LDNS_RCODE_NOERROR)
2705238106Sdes		error_supers(qstate, id, super);
2706238106Sdes	else if(qstate->is_priming)
2707238106Sdes		prime_supers(qstate, id, super);
2708238106Sdes	else	processTargetResponse(qstate, id, super);
2709238106Sdes}
2710238106Sdes
2711238106Sdes/**
2712238106Sdes * Handle iterator state.
2713238106Sdes * Handle events. This is the real processing loop for events, responsible
2714238106Sdes * for moving events through the various states. If a processing method
2715238106Sdes * returns true, then it will be advanced to the next state. If false, then
2716238106Sdes * processing will stop.
2717238106Sdes *
2718238106Sdes * @param qstate: query state.
2719238106Sdes * @param ie: iterator shared global environment.
2720238106Sdes * @param iq: iterator query state.
2721238106Sdes * @param id: module id.
2722238106Sdes */
2723238106Sdesstatic void
2724238106Sdesiter_handle(struct module_qstate* qstate, struct iter_qstate* iq,
2725238106Sdes	struct iter_env* ie, int id)
2726238106Sdes{
2727238106Sdes	int cont = 1;
2728238106Sdes	while(cont) {
2729238106Sdes		verbose(VERB_ALGO, "iter_handle processing q with state %s",
2730238106Sdes			iter_state_to_string(iq->state));
2731238106Sdes		switch(iq->state) {
2732238106Sdes			case INIT_REQUEST_STATE:
2733238106Sdes				cont = processInitRequest(qstate, iq, ie, id);
2734238106Sdes				break;
2735238106Sdes			case INIT_REQUEST_2_STATE:
2736238106Sdes				cont = processInitRequest2(qstate, iq, id);
2737238106Sdes				break;
2738238106Sdes			case INIT_REQUEST_3_STATE:
2739238106Sdes				cont = processInitRequest3(qstate, iq, id);
2740238106Sdes				break;
2741238106Sdes			case QUERYTARGETS_STATE:
2742238106Sdes				cont = processQueryTargets(qstate, iq, ie, id);
2743238106Sdes				break;
2744238106Sdes			case QUERY_RESP_STATE:
2745238106Sdes				cont = processQueryResponse(qstate, iq, id);
2746238106Sdes				break;
2747238106Sdes			case PRIME_RESP_STATE:
2748238106Sdes				cont = processPrimeResponse(qstate, id);
2749238106Sdes				break;
2750238106Sdes			case COLLECT_CLASS_STATE:
2751238106Sdes				cont = processCollectClass(qstate, id);
2752238106Sdes				break;
2753238106Sdes			case DSNS_FIND_STATE:
2754238106Sdes				cont = processDSNSFind(qstate, iq, id);
2755238106Sdes				break;
2756238106Sdes			case FINISHED_STATE:
2757238106Sdes				cont = processFinished(qstate, iq, id);
2758238106Sdes				break;
2759238106Sdes			default:
2760238106Sdes				log_warn("iterator: invalid state: %d",
2761238106Sdes					iq->state);
2762238106Sdes				cont = 0;
2763238106Sdes				break;
2764238106Sdes		}
2765238106Sdes	}
2766238106Sdes}
2767238106Sdes
2768238106Sdes/**
2769238106Sdes * This is the primary entry point for processing request events. Note that
2770238106Sdes * this method should only be used by external modules.
2771238106Sdes * @param qstate: query state.
2772238106Sdes * @param ie: iterator shared global environment.
2773238106Sdes * @param iq: iterator query state.
2774238106Sdes * @param id: module id.
2775238106Sdes */
2776238106Sdesstatic void
2777238106Sdesprocess_request(struct module_qstate* qstate, struct iter_qstate* iq,
2778238106Sdes	struct iter_env* ie, int id)
2779238106Sdes{
2780238106Sdes	/* external requests start in the INIT state, and finish using the
2781238106Sdes	 * FINISHED state. */
2782238106Sdes	iq->state = INIT_REQUEST_STATE;
2783238106Sdes	iq->final_state = FINISHED_STATE;
2784238106Sdes	verbose(VERB_ALGO, "process_request: new external request event");
2785238106Sdes	iter_handle(qstate, iq, ie, id);
2786238106Sdes}
2787238106Sdes
2788238106Sdes/** process authoritative server reply */
2789238106Sdesstatic void
2790238106Sdesprocess_response(struct module_qstate* qstate, struct iter_qstate* iq,
2791238106Sdes	struct iter_env* ie, int id, struct outbound_entry* outbound,
2792238106Sdes	enum module_ev event)
2793238106Sdes{
2794238106Sdes	struct msg_parse* prs;
2795238106Sdes	struct edns_data edns;
2796269257Sdes	sldns_buffer* pkt;
2797238106Sdes
2798238106Sdes	verbose(VERB_ALGO, "process_response: new external response event");
2799238106Sdes	iq->response = NULL;
2800238106Sdes	iq->state = QUERY_RESP_STATE;
2801238106Sdes	if(event == module_event_noreply || event == module_event_error) {
2802238106Sdes		goto handle_it;
2803238106Sdes	}
2804238106Sdes	if( (event != module_event_reply && event != module_event_capsfail)
2805238106Sdes		|| !qstate->reply) {
2806238106Sdes		log_err("Bad event combined with response");
2807238106Sdes		outbound_list_remove(&iq->outlist, outbound);
2808238106Sdes		(void)error_response(qstate, id, LDNS_RCODE_SERVFAIL);
2809238106Sdes		return;
2810238106Sdes	}
2811238106Sdes
2812238106Sdes	/* parse message */
2813238106Sdes	prs = (struct msg_parse*)regional_alloc(qstate->env->scratch,
2814238106Sdes		sizeof(struct msg_parse));
2815238106Sdes	if(!prs) {
2816238106Sdes		log_err("out of memory on incoming message");
2817238106Sdes		/* like packet got dropped */
2818238106Sdes		goto handle_it;
2819238106Sdes	}
2820238106Sdes	memset(prs, 0, sizeof(*prs));
2821238106Sdes	memset(&edns, 0, sizeof(edns));
2822238106Sdes	pkt = qstate->reply->c->buffer;
2823269257Sdes	sldns_buffer_set_position(pkt, 0);
2824238106Sdes	if(parse_packet(pkt, prs, qstate->env->scratch) != LDNS_RCODE_NOERROR) {
2825238106Sdes		verbose(VERB_ALGO, "parse error on reply packet");
2826238106Sdes		goto handle_it;
2827238106Sdes	}
2828238106Sdes	/* edns is not examined, but removed from message to help cache */
2829238106Sdes	if(parse_extract_edns(prs, &edns) != LDNS_RCODE_NOERROR)
2830238106Sdes		goto handle_it;
2831238106Sdes	/* remove CD-bit, we asked for in case we handle validation ourself */
2832238106Sdes	prs->flags &= ~BIT_CD;
2833238106Sdes
2834238106Sdes	/* normalize and sanitize: easy to delete items from linked lists */
2835238106Sdes	if(!scrub_message(pkt, prs, &iq->qchase, iq->dp->name,
2836238106Sdes		qstate->env->scratch, qstate->env, ie))
2837238106Sdes		goto handle_it;
2838238106Sdes
2839238106Sdes	/* allocate response dns_msg in region */
2840238106Sdes	iq->response = dns_alloc_msg(pkt, prs, qstate->region);
2841238106Sdes	if(!iq->response)
2842238106Sdes		goto handle_it;
2843238106Sdes	log_query_info(VERB_DETAIL, "response for", &qstate->qinfo);
2844238106Sdes	log_name_addr(VERB_DETAIL, "reply from", iq->dp->name,
2845238106Sdes		&qstate->reply->addr, qstate->reply->addrlen);
2846238106Sdes	if(verbosity >= VERB_ALGO)
2847238106Sdes		log_dns_msg("incoming scrubbed packet:", &iq->response->qinfo,
2848238106Sdes			iq->response->rep);
2849238106Sdes
2850238106Sdes	if(event == module_event_capsfail) {
2851238106Sdes		if(!iq->caps_fallback) {
2852238106Sdes			/* start fallback */
2853238106Sdes			iq->caps_fallback = 1;
2854238106Sdes			iq->caps_server = 0;
2855238106Sdes			iq->caps_reply = iq->response->rep;
2856238106Sdes			iq->state = QUERYTARGETS_STATE;
2857238106Sdes			iq->num_current_queries--;
2858238106Sdes			verbose(VERB_DETAIL, "Capsforid: starting fallback");
2859238106Sdes			goto handle_it;
2860238106Sdes		} else {
2861238106Sdes			/* check if reply is the same, otherwise, fail */
2862238106Sdes			if(!reply_equal(iq->response->rep, iq->caps_reply,
2863269257Sdes				qstate->env->scratch)) {
2864238106Sdes				verbose(VERB_DETAIL, "Capsforid fallback: "
2865238106Sdes					"getting different replies, failed");
2866238106Sdes				outbound_list_remove(&iq->outlist, outbound);
2867238106Sdes				(void)error_response(qstate, id,
2868238106Sdes					LDNS_RCODE_SERVFAIL);
2869238106Sdes				return;
2870238106Sdes			}
2871238106Sdes			/* continue the fallback procedure at next server */
2872238106Sdes			iq->caps_server++;
2873238106Sdes			iq->state = QUERYTARGETS_STATE;
2874238106Sdes			iq->num_current_queries--;
2875238106Sdes			verbose(VERB_DETAIL, "Capsforid: reply is equal. "
2876238106Sdes				"go to next fallback");
2877238106Sdes			goto handle_it;
2878238106Sdes		}
2879238106Sdes	}
2880238106Sdes	iq->caps_fallback = 0; /* if we were in fallback, 0x20 is OK now */
2881238106Sdes
2882238106Sdeshandle_it:
2883238106Sdes	outbound_list_remove(&iq->outlist, outbound);
2884238106Sdes	iter_handle(qstate, iq, ie, id);
2885238106Sdes}
2886238106Sdes
2887238106Sdesvoid
2888238106Sdesiter_operate(struct module_qstate* qstate, enum module_ev event, int id,
2889238106Sdes	struct outbound_entry* outbound)
2890238106Sdes{
2891238106Sdes	struct iter_env* ie = (struct iter_env*)qstate->env->modinfo[id];
2892238106Sdes	struct iter_qstate* iq = (struct iter_qstate*)qstate->minfo[id];
2893238106Sdes	verbose(VERB_QUERY, "iterator[module %d] operate: extstate:%s event:%s",
2894238106Sdes		id, strextstate(qstate->ext_state[id]), strmodulevent(event));
2895238106Sdes	if(iq) log_query_info(VERB_QUERY, "iterator operate: query",
2896238106Sdes		&qstate->qinfo);
2897238106Sdes	if(iq && qstate->qinfo.qname != iq->qchase.qname)
2898238106Sdes		log_query_info(VERB_QUERY, "iterator operate: chased to",
2899238106Sdes			&iq->qchase);
2900238106Sdes
2901238106Sdes	/* perform iterator state machine */
2902238106Sdes	if((event == module_event_new || event == module_event_pass) &&
2903238106Sdes		iq == NULL) {
2904238106Sdes		if(!iter_new(qstate, id)) {
2905238106Sdes			(void)error_response(qstate, id, LDNS_RCODE_SERVFAIL);
2906238106Sdes			return;
2907238106Sdes		}
2908238106Sdes		iq = (struct iter_qstate*)qstate->minfo[id];
2909238106Sdes		process_request(qstate, iq, ie, id);
2910238106Sdes		return;
2911238106Sdes	}
2912238106Sdes	if(iq && event == module_event_pass) {
2913238106Sdes		iter_handle(qstate, iq, ie, id);
2914238106Sdes		return;
2915238106Sdes	}
2916238106Sdes	if(iq && outbound) {
2917238106Sdes		process_response(qstate, iq, ie, id, outbound, event);
2918238106Sdes		return;
2919238106Sdes	}
2920238106Sdes	if(event == module_event_error) {
2921238106Sdes		verbose(VERB_ALGO, "got called with event error, giving up");
2922238106Sdes		(void)error_response(qstate, id, LDNS_RCODE_SERVFAIL);
2923238106Sdes		return;
2924238106Sdes	}
2925238106Sdes
2926238106Sdes	log_err("bad event for iterator");
2927238106Sdes	(void)error_response(qstate, id, LDNS_RCODE_SERVFAIL);
2928238106Sdes}
2929238106Sdes
2930238106Sdesvoid
2931238106Sdesiter_clear(struct module_qstate* qstate, int id)
2932238106Sdes{
2933238106Sdes	struct iter_qstate* iq;
2934238106Sdes	if(!qstate)
2935238106Sdes		return;
2936238106Sdes	iq = (struct iter_qstate*)qstate->minfo[id];
2937238106Sdes	if(iq) {
2938238106Sdes		outbound_list_clear(&iq->outlist);
2939275854Sdelphij		if(iq->target_count && --iq->target_count[0] == 0)
2940275854Sdelphij			free(iq->target_count);
2941238106Sdes		iq->num_current_queries = 0;
2942238106Sdes	}
2943238106Sdes	qstate->minfo[id] = NULL;
2944238106Sdes}
2945238106Sdes
2946238106Sdessize_t
2947238106Sdesiter_get_mem(struct module_env* env, int id)
2948238106Sdes{
2949238106Sdes	struct iter_env* ie = (struct iter_env*)env->modinfo[id];
2950238106Sdes	if(!ie)
2951238106Sdes		return 0;
2952238106Sdes	return sizeof(*ie) + sizeof(int)*((size_t)ie->max_dependency_depth+1)
2953238106Sdes		+ donotq_get_mem(ie->donotq) + priv_get_mem(ie->priv);
2954238106Sdes}
2955238106Sdes
2956238106Sdes/**
2957238106Sdes * The iterator function block
2958238106Sdes */
2959238106Sdesstatic struct module_func_block iter_block = {
2960238106Sdes	"iterator",
2961238106Sdes	&iter_init, &iter_deinit, &iter_operate, &iter_inform_super,
2962238106Sdes	&iter_clear, &iter_get_mem
2963238106Sdes};
2964238106Sdes
2965238106Sdesstruct module_func_block*
2966238106Sdesiter_get_funcblock(void)
2967238106Sdes{
2968238106Sdes	return &iter_block;
2969238106Sdes}
2970238106Sdes
2971238106Sdesconst char*
2972238106Sdesiter_state_to_string(enum iter_state state)
2973238106Sdes{
2974238106Sdes	switch (state)
2975238106Sdes	{
2976238106Sdes	case INIT_REQUEST_STATE :
2977238106Sdes		return "INIT REQUEST STATE";
2978238106Sdes	case INIT_REQUEST_2_STATE :
2979238106Sdes		return "INIT REQUEST STATE (stage 2)";
2980238106Sdes	case INIT_REQUEST_3_STATE:
2981238106Sdes		return "INIT REQUEST STATE (stage 3)";
2982238106Sdes	case QUERYTARGETS_STATE :
2983238106Sdes		return "QUERY TARGETS STATE";
2984238106Sdes	case PRIME_RESP_STATE :
2985238106Sdes		return "PRIME RESPONSE STATE";
2986238106Sdes	case COLLECT_CLASS_STATE :
2987238106Sdes		return "COLLECT CLASS STATE";
2988238106Sdes	case DSNS_FIND_STATE :
2989238106Sdes		return "DSNS FIND STATE";
2990238106Sdes	case QUERY_RESP_STATE :
2991238106Sdes		return "QUERY RESPONSE STATE";
2992238106Sdes	case FINISHED_STATE :
2993238106Sdes		return "FINISHED RESPONSE STATE";
2994238106Sdes	default :
2995238106Sdes		return "UNKNOWN ITER STATE";
2996238106Sdes	}
2997238106Sdes}
2998238106Sdes
2999238106Sdesint
3000238106Sdesiter_state_is_responsestate(enum iter_state s)
3001238106Sdes{
3002238106Sdes	switch(s) {
3003238106Sdes		case INIT_REQUEST_STATE :
3004238106Sdes		case INIT_REQUEST_2_STATE :
3005238106Sdes		case INIT_REQUEST_3_STATE :
3006238106Sdes		case QUERYTARGETS_STATE :
3007238106Sdes		case COLLECT_CLASS_STATE :
3008238106Sdes			return 0;
3009238106Sdes		default:
3010238106Sdes			break;
3011238106Sdes	}
3012238106Sdes	return 1;
3013238106Sdes}
3014