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