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