2 * iterator/iterator.c - iterative resolver DNS query response module
4 * Copyright (c) 2007, NLnet Labs. All rights reserved.
6 * This software is open source.
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions
12 * Redistributions of source code must retain the above copyright notice,
13 * this list of conditions and the following disclaimer.
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.
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.
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.
39 * This file contains a module that performs recusive iterative DNS query
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"
70 iter_init(struct module_env* env, int id)
72 struct iter_env* iter_env = (struct iter_env*)calloc(1,
73 sizeof(struct iter_env));
75 log_err("malloc failure");
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.");
87 iter_deinit(struct module_env* env, int id)
89 struct iter_env* iter_env;
90 if(!env || !env->modinfo[id])
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);
97 env->modinfo[id] = NULL;
100 /** new query for iterator */
102 iter_new(struct module_qstate* qstate, int id)
104 struct iter_qstate* iq = (struct iter_qstate*)regional_alloc(
105 qstate->region, sizeof(struct iter_qstate));
106 qstate->minfo[id] = iq;
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;
118 iq->num_target_queries = 0;
119 iq->num_current_queries = 0;
120 iq->query_restart_count = 0;
121 iq->referral_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);
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.
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).
146 next_state(struct iter_qstate* iq, enum iter_state nextstate)
148 /* If transitioning to a "response" state, make sure that there is a
150 if(iter_state_is_responsestate(nextstate)) {
151 if(iq->response == NULL) {
152 log_err("transitioning to response state sans "
156 iq->state = nextstate;
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.
166 * The response is stored in the qstate->buf buffer.
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
173 final_state(struct iter_qstate* iq)
175 return next_state(iq, iq->final_state);
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.
185 error_supers(struct module_qstate* qstate, int id, struct module_qstate* super)
187 struct iter_qstate* super_iq = (struct iter_qstate*)super->minfo[id];
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;
194 dpns = delegpt_find_ns(super_iq->dp,
195 qstate->qinfo.qname, qstate->qinfo.qname_len);
198 verbose(VERB_ALGO, "subq error, but not interested");
199 log_query_info(VERB_ALGO, "superq", &super->qinfo);
201 delegpt_log(VERB_ALGO, super_iq->dp);
205 /* see if the failure did get (parent-lame) info */
206 if(!cache_fill_missing(super->env,
207 super_iq->qchase.qclass, super->region,
209 log_err("out of memory adding missing");
211 dpns->resolved = 1; /* mark as failed */
212 super_iq->num_target_queries--;
214 if(qstate->qinfo.qtype == LDNS_RR_TYPE_NS) {
215 /* prime failed to get delegation */
218 /* evaluate targets again */
219 super_iq->state = QUERYTARGETS_STATE;
220 /* super becomes runnable, and will process this change */
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(..).
232 error_response(struct module_qstate* qstate, int id, int rcode)
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;
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(..).
253 error_response_cache(struct module_qstate* qstate, int id, int rcode)
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,
262 return error_response(qstate, id, rcode);
263 /* if that fails (not in cache), fall through to store err */
265 memset(&err, 0, sizeof(err));
266 err.flags = (uint16_t)(BIT_QR | BIT_RA);
267 FLAGS_SET_RCODE(err.flags, rcode);
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");
274 iter_dns_store(qstate->env, &qstate->qinfo, &err, 0, 0, 0, NULL);
275 return error_response(qstate, id, rcode);
278 /** check if prepend item is duplicate item */
280 prepend_is_duplicate(struct ub_packed_rrset_key** sets, size_t to,
281 struct ub_packed_rrset_key* dup)
284 for(i=0; i<to; i++) {
285 if(sets[i]->rk.type == dup->rk.type &&
286 sets[i]->rk.rrset_class == dup->rk.rrset_class &&
287 sets[i]->rk.dname_len == dup->rk.dname_len &&
288 query_dname_compare(sets[i]->rk.dname, dup->rk.dname)
295 /** prepend the prepend list in the answer and authority section of dns_msg */
297 iter_prepend(struct iter_qstate* iq, struct dns_msg* msg,
298 struct regional* region)
300 struct iter_prep_list* p;
301 struct ub_packed_rrset_key** sets;
302 size_t num_an = 0, num_ns = 0;;
303 for(p = iq->an_prepend_list; p; p = p->next)
305 for(p = iq->ns_prepend_list; p; p = p->next)
307 if(num_an + num_ns == 0)
309 verbose(VERB_ALGO, "prepending %d rrsets", (int)num_an + (int)num_ns);
310 sets = regional_alloc(region, (num_an+num_ns+msg->rep->rrset_count) *
311 sizeof(struct ub_packed_rrset_key*));
316 for(p = iq->an_prepend_list; p; p = p->next) {
317 sets[num_an++] = p->rrset;
319 memcpy(sets+num_an, msg->rep->rrsets, msg->rep->an_numrrsets *
320 sizeof(struct ub_packed_rrset_key*));
323 for(p = iq->ns_prepend_list; p; p = p->next) {
324 if(prepend_is_duplicate(sets+msg->rep->an_numrrsets+num_an,
325 num_ns, p->rrset) || prepend_is_duplicate(
326 msg->rep->rrsets+msg->rep->an_numrrsets,
327 msg->rep->ns_numrrsets, p->rrset))
329 sets[msg->rep->an_numrrsets + num_an + num_ns++] = p->rrset;
331 memcpy(sets + num_an + msg->rep->an_numrrsets + num_ns,
332 msg->rep->rrsets + msg->rep->an_numrrsets,
333 (msg->rep->ns_numrrsets + msg->rep->ar_numrrsets) *
334 sizeof(struct ub_packed_rrset_key*));
336 /* NXDOMAIN rcode can stay if we prepended DNAME/CNAMEs, because
337 * this is what recursors should give. */
338 msg->rep->rrset_count += num_an + num_ns;
339 msg->rep->an_numrrsets += num_an;
340 msg->rep->ns_numrrsets += num_ns;
341 msg->rep->rrsets = sets;
346 * Add rrset to ANSWER prepend list
347 * @param qstate: query state.
348 * @param iq: iterator query state.
349 * @param rrset: rrset to add.
350 * @return false on failure (malloc).
353 iter_add_prepend_answer(struct module_qstate* qstate, struct iter_qstate* iq,
354 struct ub_packed_rrset_key* rrset)
356 struct iter_prep_list* p = (struct iter_prep_list*)regional_alloc(
357 qstate->region, sizeof(struct iter_prep_list));
363 if(iq->an_prepend_last)
364 iq->an_prepend_last->next = p;
365 else iq->an_prepend_list = p;
366 iq->an_prepend_last = p;
371 * Add rrset to AUTHORITY prepend list
372 * @param qstate: query state.
373 * @param iq: iterator query state.
374 * @param rrset: rrset to add.
375 * @return false on failure (malloc).
378 iter_add_prepend_auth(struct module_qstate* qstate, struct iter_qstate* iq,
379 struct ub_packed_rrset_key* rrset)
381 struct iter_prep_list* p = (struct iter_prep_list*)regional_alloc(
382 qstate->region, sizeof(struct iter_prep_list));
388 if(iq->ns_prepend_last)
389 iq->ns_prepend_last->next = p;
390 else iq->ns_prepend_list = p;
391 iq->ns_prepend_last = p;
396 * Given a CNAME response (defined as a response containing a CNAME or DNAME
397 * that does not answer the request), process the response, modifying the
398 * state as necessary. This follows the CNAME/DNAME chain and returns the
401 * sets the new query name, after following the CNAME/DNAME chain.
402 * @param qstate: query state.
403 * @param iq: iterator query state.
404 * @param msg: the response.
405 * @param mname: returned target new query name.
406 * @param mname_len: length of mname.
407 * @return false on (malloc) error.
410 handle_cname_response(struct module_qstate* qstate, struct iter_qstate* iq,
411 struct dns_msg* msg, uint8_t** mname, size_t* mname_len)
414 /* Start with the (current) qname. */
415 *mname = iq->qchase.qname;
416 *mname_len = iq->qchase.qname_len;
418 /* Iterate over the ANSWER rrsets in order, looking for CNAMEs and
420 for(i=0; i<msg->rep->an_numrrsets; i++) {
421 struct ub_packed_rrset_key* r = msg->rep->rrsets[i];
422 /* If there is a (relevant) DNAME, add it to the list.
423 * We always expect there to be CNAME that was generated
424 * by this DNAME following, so we don't process the DNAME
426 if(ntohs(r->rk.type) == LDNS_RR_TYPE_DNAME &&
427 dname_strict_subdomain_c(*mname, r->rk.dname)) {
428 if(!iter_add_prepend_answer(qstate, iq, r))
433 if(ntohs(r->rk.type) == LDNS_RR_TYPE_CNAME &&
434 query_dname_compare(*mname, r->rk.dname) == 0) {
435 /* Add this relevant CNAME rrset to the prepend list.*/
436 if(!iter_add_prepend_answer(qstate, iq, r))
438 get_cname_target(r, mname, mname_len);
441 /* Other rrsets in the section are ignored. */
443 /* add authority rrsets to authority prepend, for wildcarded CNAMEs */
444 for(i=msg->rep->an_numrrsets; i<msg->rep->an_numrrsets +
445 msg->rep->ns_numrrsets; i++) {
446 struct ub_packed_rrset_key* r = msg->rep->rrsets[i];
447 /* only add NSEC/NSEC3, as they may be needed for validation */
448 if(ntohs(r->rk.type) == LDNS_RR_TYPE_NSEC ||
449 ntohs(r->rk.type) == LDNS_RR_TYPE_NSEC3) {
450 if(!iter_add_prepend_auth(qstate, iq, r))
457 /** create target count structure for this query */
459 target_count_create(struct iter_qstate* iq)
461 if(!iq->target_count) {
462 iq->target_count = (int*)calloc(2, sizeof(int));
463 /* if calloc fails we simply do not track this number */
465 iq->target_count[0] = 1;
470 target_count_increase(struct iter_qstate* iq, int num)
472 target_count_create(iq);
474 iq->target_count[1] += num;
478 * Generate a subrequest.
479 * Generate a local request event. Local events are tied to this module, and
480 * have a correponding (first tier) event that is waiting for this event to
481 * resolve to continue.
483 * @param qname The query name for this request.
484 * @param qnamelen length of qname
485 * @param qtype The query type for this request.
486 * @param qclass The query class for this request.
487 * @param qstate The event that is generating this event.
488 * @param id: module id.
489 * @param iq: The iterator state that is generating this event.
490 * @param initial_state The initial response state (normally this
491 * is QUERY_RESP_STATE, unless it is known that the request won't
492 * need iterative processing
493 * @param finalstate The final state for the response to this request.
494 * @param subq_ret: if newly allocated, the subquerystate, or NULL if it does
495 * not need initialisation.
496 * @param v: if true, validation is done on the subquery.
497 * @return false on error (malloc).
500 generate_sub_request(uint8_t* qname, size_t qnamelen, uint16_t qtype,
501 uint16_t qclass, struct module_qstate* qstate, int id,
502 struct iter_qstate* iq, enum iter_state initial_state,
503 enum iter_state finalstate, struct module_qstate** subq_ret, int v)
505 struct module_qstate* subq = NULL;
506 struct iter_qstate* subiq = NULL;
507 uint16_t qflags = 0; /* OPCODE QUERY, no flags */
508 struct query_info qinf;
509 int prime = (finalstate == PRIME_RESP_STATE)?1:0;
511 qinf.qname_len = qnamelen;
513 qinf.qclass = qclass;
515 /* RD should be set only when sending the query back through the INIT
517 if(initial_state == INIT_REQUEST_STATE)
519 /* We set the CD flag so we can send this through the "head" of
520 * the resolution chain, which might have a validator. We are
521 * uninterested in validating things not on the direct resolution
526 /* attach subquery, lookup existing or make a new one */
527 fptr_ok(fptr_whitelist_modenv_attach_sub(qstate->env->attach_sub));
528 if(!(*qstate->env->attach_sub)(qstate, &qinf, qflags, prime, &subq)) {
533 /* initialise the new subquery */
535 subq->ext_state[id] = module_state_initial;
536 subq->minfo[id] = regional_alloc(subq->region,
537 sizeof(struct iter_qstate));
538 if(!subq->minfo[id]) {
539 log_err("init subq: out of memory");
540 fptr_ok(fptr_whitelist_modenv_kill_sub(
541 qstate->env->kill_sub));
542 (*qstate->env->kill_sub)(subq);
545 subiq = (struct iter_qstate*)subq->minfo[id];
546 memset(subiq, 0, sizeof(*subiq));
547 subiq->num_target_queries = 0;
548 target_count_create(iq);
549 subiq->target_count = iq->target_count;
551 iq->target_count[0] ++; /* extra reference */
552 subiq->num_current_queries = 0;
553 subiq->depth = iq->depth+1;
554 outbound_list_init(&subiq->outlist);
555 subiq->state = initial_state;
556 subiq->final_state = finalstate;
557 subiq->qchase = subq->qinfo;
558 subiq->chase_flags = subq->query_flags;
559 subiq->refetch_glue = 0;
565 * Generate and send a root priming request.
566 * @param qstate: the qtstate that triggered the need to prime.
567 * @param iq: iterator query state.
568 * @param id: module id.
569 * @param qclass: the class to prime.
570 * @return 0 on failure
573 prime_root(struct module_qstate* qstate, struct iter_qstate* iq, int id,
577 struct module_qstate* subq;
578 verbose(VERB_DETAIL, "priming . %s NS",
579 sldns_lookup_by_id(sldns_rr_classes, (int)qclass)?
580 sldns_lookup_by_id(sldns_rr_classes, (int)qclass)->name:"??");
581 dp = hints_lookup_root(qstate->env->hints, qclass);
583 verbose(VERB_ALGO, "Cannot prime due to lack of hints");
586 /* Priming requests start at the QUERYTARGETS state, skipping
587 * the normal INIT state logic (which would cause an infloop). */
588 if(!generate_sub_request((uint8_t*)"\000", 1, LDNS_RR_TYPE_NS,
589 qclass, qstate, id, iq, QUERYTARGETS_STATE, PRIME_RESP_STATE,
591 verbose(VERB_ALGO, "could not prime root");
595 struct iter_qstate* subiq =
596 (struct iter_qstate*)subq->minfo[id];
597 /* Set the initial delegation point to the hint.
598 * copy dp, it is now part of the root prime query.
599 * dp was part of in the fixed hints structure. */
600 subiq->dp = delegpt_copy(dp, subq->region);
602 log_err("out of memory priming root, copydp");
603 fptr_ok(fptr_whitelist_modenv_kill_sub(
604 qstate->env->kill_sub));
605 (*qstate->env->kill_sub)(subq);
608 /* there should not be any target queries. */
609 subiq->num_target_queries = 0;
610 subiq->dnssec_expected = iter_indicates_dnssec(
611 qstate->env, subiq->dp, NULL, subq->qinfo.qclass);
614 /* this module stops, our submodule starts, and does the query. */
615 qstate->ext_state[id] = module_wait_subquery;
620 * Generate and process a stub priming request. This method tests for the
621 * need to prime a stub zone, so it is safe to call for every request.
623 * @param qstate: the qtstate that triggered the need to prime.
624 * @param iq: iterator query state.
625 * @param id: module id.
626 * @param qname: request name.
627 * @param qclass: request class.
628 * @return true if a priming subrequest was made, false if not. The will only
629 * issue a priming request if it detects an unprimed stub.
630 * Uses value of 2 to signal during stub-prime in root-prime situation
631 * that a noprime-stub is available and resolution can continue.
634 prime_stub(struct module_qstate* qstate, struct iter_qstate* iq, int id,
635 uint8_t* qname, uint16_t qclass)
637 /* Lookup the stub hint. This will return null if the stub doesn't
638 * need to be re-primed. */
639 struct iter_hints_stub* stub;
640 struct delegpt* stub_dp;
641 struct module_qstate* subq;
644 stub = hints_lookup_stub(qstate->env->hints, qname, qclass, iq->dp);
645 /* The stub (if there is one) does not need priming. */
650 /* is it a noprime stub (always use) */
653 if(iq->dp == NULL) r = 2;
654 /* copy the dp out of the fixed hints structure, so that
655 * it can be changed when servicing this query */
656 iq->dp = delegpt_copy(stub_dp, qstate->region);
658 log_err("out of memory priming stub");
659 (void)error_response(qstate, id, LDNS_RCODE_SERVFAIL);
660 return 1; /* return 1 to make module stop, with error */
662 log_nametypeclass(VERB_DETAIL, "use stub", stub_dp->name,
663 LDNS_RR_TYPE_NS, qclass);
667 /* Otherwise, we need to (re)prime the stub. */
668 log_nametypeclass(VERB_DETAIL, "priming stub", stub_dp->name,
669 LDNS_RR_TYPE_NS, qclass);
671 /* Stub priming events start at the QUERYTARGETS state to avoid the
672 * redundant INIT state processing. */
673 if(!generate_sub_request(stub_dp->name, stub_dp->namelen,
674 LDNS_RR_TYPE_NS, qclass, qstate, id, iq,
675 QUERYTARGETS_STATE, PRIME_RESP_STATE, &subq, 0)) {
676 verbose(VERB_ALGO, "could not prime stub");
677 (void)error_response(qstate, id, LDNS_RCODE_SERVFAIL);
678 return 1; /* return 1 to make module stop, with error */
681 struct iter_qstate* subiq =
682 (struct iter_qstate*)subq->minfo[id];
684 /* Set the initial delegation point to the hint. */
685 /* make copy to avoid use of stub dp by different qs/threads */
686 subiq->dp = delegpt_copy(stub_dp, subq->region);
688 log_err("out of memory priming stub, copydp");
689 fptr_ok(fptr_whitelist_modenv_kill_sub(
690 qstate->env->kill_sub));
691 (*qstate->env->kill_sub)(subq);
692 (void)error_response(qstate, id, LDNS_RCODE_SERVFAIL);
693 return 1; /* return 1 to make module stop, with error */
695 /* there should not be any target queries -- although there
696 * wouldn't be anyway, since stub hints never have
697 * missing targets. */
698 subiq->num_target_queries = 0;
699 subiq->wait_priming_stub = 1;
700 subiq->dnssec_expected = iter_indicates_dnssec(
701 qstate->env, subiq->dp, NULL, subq->qinfo.qclass);
704 /* this module stops, our submodule starts, and does the query. */
705 qstate->ext_state[id] = module_wait_subquery;
710 * Generate A and AAAA checks for glue that is in-zone for the referral
711 * we just got to obtain authoritative information on the adresses.
713 * @param qstate: the qtstate that triggered the need to prime.
714 * @param iq: iterator query state.
715 * @param id: module id.
718 generate_a_aaaa_check(struct module_qstate* qstate, struct iter_qstate* iq,
721 struct iter_env* ie = (struct iter_env*)qstate->env->modinfo[id];
722 struct module_qstate* subq;
724 struct reply_info* rep = iq->response->rep;
725 struct ub_packed_rrset_key* s;
728 if(iq->depth == ie->max_dependency_depth)
730 /* walk through additional, and check if in-zone,
731 * only relevant A, AAAA are left after scrub anyway */
732 for(i=rep->an_numrrsets+rep->ns_numrrsets; i<rep->rrset_count; i++) {
734 /* check *ALL* addresses that are transmitted in additional*/
735 /* is it an address ? */
736 if( !(ntohs(s->rk.type)==LDNS_RR_TYPE_A ||
737 ntohs(s->rk.type)==LDNS_RR_TYPE_AAAA)) {
740 /* is this query the same as the A/AAAA check for it */
741 if(qstate->qinfo.qtype == ntohs(s->rk.type) &&
742 qstate->qinfo.qclass == ntohs(s->rk.rrset_class) &&
743 query_dname_compare(qstate->qinfo.qname,
745 (qstate->query_flags&BIT_RD) &&
746 !(qstate->query_flags&BIT_CD))
749 /* generate subrequest for it */
750 log_nametypeclass(VERB_ALGO, "schedule addr fetch",
751 s->rk.dname, ntohs(s->rk.type),
752 ntohs(s->rk.rrset_class));
753 if(!generate_sub_request(s->rk.dname, s->rk.dname_len,
754 ntohs(s->rk.type), ntohs(s->rk.rrset_class),
756 INIT_REQUEST_STATE, FINISHED_STATE, &subq, 1)) {
757 verbose(VERB_ALGO, "could not generate addr check");
760 /* ignore subq - not need for more init */
765 * Generate a NS check request to obtain authoritative information
768 * @param qstate: the qtstate that triggered the need to prime.
769 * @param iq: iterator query state.
770 * @param id: module id.
773 generate_ns_check(struct module_qstate* qstate, struct iter_qstate* iq, int id)
775 struct iter_env* ie = (struct iter_env*)qstate->env->modinfo[id];
776 struct module_qstate* subq;
779 if(iq->depth == ie->max_dependency_depth)
781 /* is this query the same as the nscheck? */
782 if(qstate->qinfo.qtype == LDNS_RR_TYPE_NS &&
783 query_dname_compare(iq->dp->name, qstate->qinfo.qname)==0 &&
784 (qstate->query_flags&BIT_RD) && !(qstate->query_flags&BIT_CD)){
785 /* spawn off A, AAAA queries for in-zone glue to check */
786 generate_a_aaaa_check(qstate, iq, id);
790 log_nametypeclass(VERB_ALGO, "schedule ns fetch",
791 iq->dp->name, LDNS_RR_TYPE_NS, iq->qchase.qclass);
792 if(!generate_sub_request(iq->dp->name, iq->dp->namelen,
793 LDNS_RR_TYPE_NS, iq->qchase.qclass, qstate, id, iq,
794 INIT_REQUEST_STATE, FINISHED_STATE, &subq, 1)) {
795 verbose(VERB_ALGO, "could not generate ns check");
799 struct iter_qstate* subiq =
800 (struct iter_qstate*)subq->minfo[id];
802 /* make copy to avoid use of stub dp by different qs/threads */
803 /* refetch glue to start higher up the tree */
804 subiq->refetch_glue = 1;
805 subiq->dp = delegpt_copy(iq->dp, subq->region);
807 log_err("out of memory generating ns check, copydp");
808 fptr_ok(fptr_whitelist_modenv_kill_sub(
809 qstate->env->kill_sub));
810 (*qstate->env->kill_sub)(subq);
817 * Generate a DNSKEY prefetch query to get the DNSKEY for the DS record we
818 * just got in a referral (where we have dnssec_expected, thus have trust
819 * anchors above it). Note that right after calling this routine the
820 * iterator detached subqueries (because of following the referral), and thus
821 * the DNSKEY query becomes detached, its return stored in the cache for
822 * later lookup by the validator. This cache lookup by the validator avoids
823 * the roundtrip incurred by the DNSKEY query. The DNSKEY query is now
824 * performed at about the same time the original query is sent to the domain,
825 * thus the two answers are likely to be returned at about the same time,
826 * saving a roundtrip from the validated lookup.
828 * @param qstate: the qtstate that triggered the need to prime.
829 * @param iq: iterator query state.
830 * @param id: module id.
833 generate_dnskey_prefetch(struct module_qstate* qstate,
834 struct iter_qstate* iq, int id)
836 struct module_qstate* subq;
839 /* is this query the same as the prefetch? */
840 if(qstate->qinfo.qtype == LDNS_RR_TYPE_DNSKEY &&
841 query_dname_compare(iq->dp->name, qstate->qinfo.qname)==0 &&
842 (qstate->query_flags&BIT_RD) && !(qstate->query_flags&BIT_CD)){
846 /* if the DNSKEY is in the cache this lookup will stop quickly */
847 log_nametypeclass(VERB_ALGO, "schedule dnskey prefetch",
848 iq->dp->name, LDNS_RR_TYPE_DNSKEY, iq->qchase.qclass);
849 if(!generate_sub_request(iq->dp->name, iq->dp->namelen,
850 LDNS_RR_TYPE_DNSKEY, iq->qchase.qclass, qstate, id, iq,
851 INIT_REQUEST_STATE, FINISHED_STATE, &subq, 0)) {
852 /* we'll be slower, but it'll work */
853 verbose(VERB_ALGO, "could not generate dnskey prefetch");
857 struct iter_qstate* subiq =
858 (struct iter_qstate*)subq->minfo[id];
859 /* this qstate has the right delegation for the dnskey lookup*/
860 /* make copy to avoid use of stub dp by different qs/threads */
861 subiq->dp = delegpt_copy(iq->dp, subq->region);
862 /* if !subiq->dp, it'll start from the cache, no problem */
867 * See if the query needs forwarding.
869 * @param qstate: query state.
870 * @param iq: iterator query state.
871 * @return true if the request is forwarded, false if not.
872 * If returns true but, iq->dp is NULL then a malloc failure occurred.
875 forward_request(struct module_qstate* qstate, struct iter_qstate* iq)
878 uint8_t* delname = iq->qchase.qname;
879 size_t delnamelen = iq->qchase.qname_len;
880 if(iq->refetch_glue) {
881 delname = iq->dp->name;
882 delnamelen = iq->dp->namelen;
884 /* strip one label off of DS query to lookup higher for it */
885 if( (iq->qchase.qtype == LDNS_RR_TYPE_DS || iq->refetch_glue)
886 && !dname_is_root(iq->qchase.qname))
887 dname_remove_label(&delname, &delnamelen);
888 dp = forwards_lookup(qstate->env->fwds, delname, iq->qchase.qclass);
891 /* send recursion desired to forward addr */
892 iq->chase_flags |= BIT_RD;
893 iq->dp = delegpt_copy(dp, qstate->region);
894 /* iq->dp checked by caller */
895 verbose(VERB_ALGO, "forwarding request");
900 * Process the initial part of the request handling. This state roughly
901 * corresponds to resolver algorithms steps 1 (find answer in cache) and 2
902 * (find the best servers to ask).
904 * Note that all requests start here, and query restarts revisit this state.
906 * This state either generates: 1) a response, from cache or error, 2) a
907 * priming event, or 3) forwards the request to the next state (init2,
910 * @param qstate: query state.
911 * @param iq: iterator query state.
912 * @param ie: iterator shared global environment.
913 * @param id: module id.
914 * @return true if the event needs more request processing immediately,
918 processInitRequest(struct module_qstate* qstate, struct iter_qstate* iq,
919 struct iter_env* ie, int id)
925 log_query_info(VERB_DETAIL, "resolving", &qstate->qinfo);
928 /* We enforce a maximum number of query restarts. This is primarily a
929 * cheap way to prevent CNAME loops. */
930 if(iq->query_restart_count > MAX_RESTART_COUNT) {
931 verbose(VERB_QUERY, "request has exceeded the maximum number"
932 " of query restarts with %d", iq->query_restart_count);
933 return error_response(qstate, id, LDNS_RCODE_SERVFAIL);
936 /* We enforce a maximum recursion/dependency depth -- in general,
937 * this is unnecessary for dependency loops (although it will
938 * catch those), but it provides a sensible limit to the amount
939 * of work required to answer a given query. */
940 verbose(VERB_ALGO, "request has dependency depth of %d", iq->depth);
941 if(iq->depth > ie->max_dependency_depth) {
942 verbose(VERB_QUERY, "request has exceeded the maximum "
943 "dependency depth with depth of %d", iq->depth);
944 return error_response(qstate, id, LDNS_RCODE_SERVFAIL);
947 /* If the request is qclass=ANY, setup to generate each class */
948 if(qstate->qinfo.qclass == LDNS_RR_CLASS_ANY) {
949 iq->qchase.qclass = 0;
950 return next_state(iq, COLLECT_CLASS_STATE);
953 /* Resolver Algorithm Step 1 -- Look for the answer in local data. */
955 /* This either results in a query restart (CNAME cache response), a
956 * terminating response (ANSWER), or a cache miss (null). */
958 if(qstate->blacklist) {
959 /* if cache, or anything else, was blacklisted then
960 * getting older results from cache is a bad idea, no cache */
961 verbose(VERB_ALGO, "cache blacklisted, going to the network");
964 msg = dns_cache_lookup(qstate->env, iq->qchase.qname,
965 iq->qchase.qname_len, iq->qchase.qtype,
966 iq->qchase.qclass, qstate->region, qstate->env->scratch);
967 if(!msg && qstate->env->neg_cache) {
968 /* lookup in negative cache; may result in
969 * NOERROR/NODATA or NXDOMAIN answers that need validation */
970 msg = val_neg_getmsg(qstate->env->neg_cache, &iq->qchase,
971 qstate->region, qstate->env->rrset_cache,
972 qstate->env->scratch_buffer,
973 *qstate->env->now, 1/*add SOA*/, NULL);
975 /* item taken from cache does not match our query name, thus
976 * security needs to be re-examined later */
977 if(msg && query_dname_compare(qstate->qinfo.qname,
978 iq->qchase.qname) != 0)
979 msg->rep->security = sec_status_unchecked;
982 /* handle positive cache response */
983 enum response_type type = response_type_from_cache(msg,
985 if(verbosity >= VERB_ALGO) {
986 log_dns_msg("msg from cache lookup", &msg->qinfo,
988 verbose(VERB_ALGO, "msg ttl is %d, prefetch ttl %d",
990 (int)msg->rep->prefetch_ttl);
993 if(type == RESPONSE_TYPE_CNAME) {
996 verbose(VERB_ALGO, "returning CNAME response from "
998 if(!handle_cname_response(qstate, iq, msg,
1000 return error_response(qstate, id,
1001 LDNS_RCODE_SERVFAIL);
1002 iq->qchase.qname = sname;
1003 iq->qchase.qname_len = slen;
1004 /* This *is* a query restart, even if it is a cheap
1007 iq->refetch_glue = 0;
1008 iq->query_restart_count++;
1010 sock_list_insert(&qstate->reply_origin, NULL, 0, qstate->region);
1011 return next_state(iq, INIT_REQUEST_STATE);
1014 /* if from cache, NULL, else insert 'cache IP' len=0 */
1015 if(qstate->reply_origin)
1016 sock_list_insert(&qstate->reply_origin, NULL, 0, qstate->region);
1017 /* it is an answer, response, to final state */
1018 verbose(VERB_ALGO, "returning answer from cache.");
1020 return final_state(iq);
1023 /* attempt to forward the request */
1024 if(forward_request(qstate, iq))
1027 log_err("alloc failure for forward dp");
1028 return error_response(qstate, id, LDNS_RCODE_SERVFAIL);
1030 iq->refetch_glue = 0;
1031 /* the request has been forwarded.
1032 * forwarded requests need to be immediately sent to the
1033 * next state, QUERYTARGETS. */
1034 return next_state(iq, QUERYTARGETS_STATE);
1037 /* Resolver Algorithm Step 2 -- find the "best" servers. */
1039 /* first, adjust for DS queries. To avoid the grandparent problem,
1040 * we just look for the closest set of server to the parent of qname.
1041 * When re-fetching glue we also need to ask the parent.
1043 if(iq->refetch_glue) {
1045 log_err("internal or malloc fail: no dp for refetch");
1046 return error_response(qstate, id, LDNS_RCODE_SERVFAIL);
1048 delname = iq->dp->name;
1049 delnamelen = iq->dp->namelen;
1051 delname = iq->qchase.qname;
1052 delnamelen = iq->qchase.qname_len;
1054 if(iq->qchase.qtype == LDNS_RR_TYPE_DS || iq->refetch_glue ||
1055 (iq->qchase.qtype == LDNS_RR_TYPE_NS && qstate->prefetch_leeway)) {
1056 /* remove first label from delname, root goes to hints,
1057 * but only to fetch glue, not for qtype=DS. */
1058 /* also when prefetching an NS record, fetch it again from
1059 * its parent, just as if it expired, so that you do not
1060 * get stuck on an older nameserver that gives old NSrecords */
1061 if(dname_is_root(delname) && (iq->refetch_glue ||
1062 (iq->qchase.qtype == LDNS_RR_TYPE_NS &&
1063 qstate->prefetch_leeway)))
1064 delname = NULL; /* go to root priming */
1065 else dname_remove_label(&delname, &delnamelen);
1067 /* delname is the name to lookup a delegation for. If NULL rootprime */
1070 /* Lookup the delegation in the cache. If null, then the
1071 * cache needs to be primed for the qclass. */
1073 iq->dp = dns_cache_find_delegation(qstate->env, delname,
1074 delnamelen, iq->qchase.qtype, iq->qchase.qclass,
1075 qstate->region, &iq->deleg_msg,
1076 *qstate->env->now+qstate->prefetch_leeway);
1079 /* If the cache has returned nothing, then we have a
1080 * root priming situation. */
1081 if(iq->dp == NULL) {
1082 /* if there is a stub, then no root prime needed */
1083 int r = prime_stub(qstate, iq, id, delname,
1086 break; /* got noprime-stub-zone, continue */
1088 return 0; /* stub prime request made */
1089 if(forwards_lookup_root(qstate->env->fwds,
1090 iq->qchase.qclass)) {
1091 /* forward zone root, no root prime needed */
1092 /* fill in some dp - safety belt */
1093 iq->dp = hints_lookup_root(qstate->env->hints,
1096 log_err("internal error: no hints dp");
1097 return error_response(qstate, id,
1098 LDNS_RCODE_SERVFAIL);
1100 iq->dp = delegpt_copy(iq->dp, qstate->region);
1102 log_err("out of memory in safety belt");
1103 return error_response(qstate, id,
1104 LDNS_RCODE_SERVFAIL);
1106 return next_state(iq, INIT_REQUEST_2_STATE);
1108 /* Note that the result of this will set a new
1109 * DelegationPoint based on the result of priming. */
1110 if(!prime_root(qstate, iq, id, iq->qchase.qclass))
1111 return error_response(qstate, id,
1112 LDNS_RCODE_REFUSED);
1114 /* priming creates and sends a subordinate query, with
1115 * this query as the parent. So further processing for
1116 * this event will stop until reactivated by the
1117 * results of priming. */
1121 /* see if this dp not useless.
1123 * o all NS items are required glue.
1124 * or the query is for NS item that is required glue.
1125 * o no addresses are provided.
1127 * Instead, go up one level, and try to get even further
1128 * If the root was useless, use safety belt information.
1129 * Only check cache returns, because replies for servers
1130 * could be useless but lead to loops (bumping into the
1131 * same server reply) if useless-checked.
1133 if(iter_dp_is_useless(&qstate->qinfo, qstate->query_flags,
1135 if(dname_is_root(iq->dp->name)) {
1136 /* use safety belt */
1137 verbose(VERB_QUERY, "Cache has root NS but "
1138 "no addresses. Fallback to the safety belt.");
1139 iq->dp = hints_lookup_root(qstate->env->hints,
1141 /* note deleg_msg is from previous lookup,
1142 * but RD is on, so it is not used */
1144 log_err("internal error: no hints dp");
1145 return error_response(qstate, id,
1146 LDNS_RCODE_REFUSED);
1148 iq->dp = delegpt_copy(iq->dp, qstate->region);
1150 log_err("out of memory in safety belt");
1151 return error_response(qstate, id,
1152 LDNS_RCODE_SERVFAIL);
1157 "cache delegation was useless:");
1158 delegpt_log(VERB_ALGO, iq->dp);
1160 delname = iq->dp->name;
1161 delnamelen = iq->dp->namelen;
1162 dname_remove_label(&delname, &delnamelen);
1167 verbose(VERB_ALGO, "cache delegation returns delegpt");
1168 delegpt_log(VERB_ALGO, iq->dp);
1170 /* Otherwise, set the current delegation point and move on to the
1172 return next_state(iq, INIT_REQUEST_2_STATE);
1176 * Process the second part of the initial request handling. This state
1177 * basically exists so that queries that generate root priming events have
1178 * the same init processing as ones that do not. Request events that reach
1179 * this state must have a valid currentDelegationPoint set.
1181 * This part is primarly handling stub zone priming. Events that reach this
1182 * state must have a current delegation point.
1184 * @param qstate: query state.
1185 * @param iq: iterator query state.
1186 * @param id: module id.
1187 * @return true if the event needs more request processing immediately,
1191 processInitRequest2(struct module_qstate* qstate, struct iter_qstate* iq,
1196 log_query_info(VERB_QUERY, "resolving (init part 2): ",
1199 if(iq->refetch_glue) {
1201 log_err("internal or malloc fail: no dp for refetch");
1202 return error_response(qstate, id, LDNS_RCODE_SERVFAIL);
1204 delname = iq->dp->name;
1205 delnamelen = iq->dp->namelen;
1207 delname = iq->qchase.qname;
1208 delnamelen = iq->qchase.qname_len;
1210 if(iq->qchase.qtype == LDNS_RR_TYPE_DS || iq->refetch_glue) {
1211 if(!dname_is_root(delname))
1212 dname_remove_label(&delname, &delnamelen);
1213 iq->refetch_glue = 0; /* if CNAME causes restart, no refetch */
1215 /* Check to see if we need to prime a stub zone. */
1216 if(prime_stub(qstate, iq, id, delname, iq->qchase.qclass)) {
1217 /* A priming sub request was made */
1221 /* most events just get forwarded to the next state. */
1222 return next_state(iq, INIT_REQUEST_3_STATE);
1226 * Process the third part of the initial request handling. This state exists
1227 * as a separate state so that queries that generate stub priming events
1228 * will get the tail end of the init process but not repeat the stub priming
1231 * @param qstate: query state.
1232 * @param iq: iterator query state.
1233 * @param id: module id.
1234 * @return true, advancing the event to the QUERYTARGETS_STATE.
1237 processInitRequest3(struct module_qstate* qstate, struct iter_qstate* iq,
1240 log_query_info(VERB_QUERY, "resolving (init part 3): ",
1242 /* if the cache reply dp equals a validation anchor or msg has DS,
1243 * then DNSSEC RRSIGs are expected in the reply */
1244 iq->dnssec_expected = iter_indicates_dnssec(qstate->env, iq->dp,
1245 iq->deleg_msg, iq->qchase.qclass);
1247 /* If the RD flag wasn't set, then we just finish with the
1248 * cached referral as the response. */
1249 if(!(qstate->query_flags & BIT_RD)) {
1250 iq->response = iq->deleg_msg;
1251 if(verbosity >= VERB_ALGO && iq->response)
1252 log_dns_msg("no RD requested, using delegation msg",
1253 &iq->response->qinfo, iq->response->rep);
1254 if(qstate->reply_origin)
1255 sock_list_insert(&qstate->reply_origin, NULL, 0, qstate->region);
1256 return final_state(iq);
1258 /* After this point, unset the RD flag -- this query is going to
1259 * be sent to an auth. server. */
1260 iq->chase_flags &= ~BIT_RD;
1262 /* if dnssec expected, fetch key for the trust-anchor or cached-DS */
1263 if(iq->dnssec_expected && qstate->env->cfg->prefetch_key &&
1264 !(qstate->query_flags&BIT_CD)) {
1265 generate_dnskey_prefetch(qstate, iq, id);
1266 fptr_ok(fptr_whitelist_modenv_detach_subs(
1267 qstate->env->detach_subs));
1268 (*qstate->env->detach_subs)(qstate);
1271 /* Jump to the next state. */
1272 return next_state(iq, QUERYTARGETS_STATE);
1276 * Given a basic query, generate a parent-side "target" query.
1277 * These are subordinate queries for missing delegation point target addresses,
1278 * for which only the parent of the delegation provides correct IP addresses.
1280 * @param qstate: query state.
1281 * @param iq: iterator query state.
1282 * @param id: module id.
1283 * @param name: target qname.
1284 * @param namelen: target qname length.
1285 * @param qtype: target qtype (either A or AAAA).
1286 * @param qclass: target qclass.
1287 * @return true on success, false on failure.
1290 generate_parentside_target_query(struct module_qstate* qstate,
1291 struct iter_qstate* iq, int id, uint8_t* name, size_t namelen,
1292 uint16_t qtype, uint16_t qclass)
1294 struct module_qstate* subq;
1295 if(!generate_sub_request(name, namelen, qtype, qclass, qstate,
1296 id, iq, INIT_REQUEST_STATE, FINISHED_STATE, &subq, 0))
1299 struct iter_qstate* subiq =
1300 (struct iter_qstate*)subq->minfo[id];
1301 /* blacklist the cache - we want to fetch parent stuff */
1302 sock_list_insert(&subq->blacklist, NULL, 0, subq->region);
1303 subiq->query_for_pside_glue = 1;
1304 if(dname_subdomain_c(name, iq->dp->name)) {
1305 subiq->dp = delegpt_copy(iq->dp, subq->region);
1306 subiq->dnssec_expected = iter_indicates_dnssec(
1307 qstate->env, subiq->dp, NULL,
1308 subq->qinfo.qclass);
1309 subiq->refetch_glue = 1;
1311 subiq->dp = dns_cache_find_delegation(qstate->env,
1312 name, namelen, qtype, qclass, subq->region,
1314 *qstate->env->now+subq->prefetch_leeway);
1315 /* if no dp, then it's from root, refetch unneeded */
1317 subiq->dnssec_expected = iter_indicates_dnssec(
1318 qstate->env, subiq->dp, NULL,
1319 subq->qinfo.qclass);
1320 subiq->refetch_glue = 1;
1324 log_nametypeclass(VERB_QUERY, "new pside target", name, qtype, qclass);
1329 * Given a basic query, generate a "target" query. These are subordinate
1330 * queries for missing delegation point target addresses.
1332 * @param qstate: query state.
1333 * @param iq: iterator query state.
1334 * @param id: module id.
1335 * @param name: target qname.
1336 * @param namelen: target qname length.
1337 * @param qtype: target qtype (either A or AAAA).
1338 * @param qclass: target qclass.
1339 * @return true on success, false on failure.
1342 generate_target_query(struct module_qstate* qstate, struct iter_qstate* iq,
1343 int id, uint8_t* name, size_t namelen, uint16_t qtype, uint16_t qclass)
1345 struct module_qstate* subq;
1346 if(!generate_sub_request(name, namelen, qtype, qclass, qstate,
1347 id, iq, INIT_REQUEST_STATE, FINISHED_STATE, &subq, 0))
1349 log_nametypeclass(VERB_QUERY, "new target", name, qtype, qclass);
1354 * Given an event at a certain state, generate zero or more target queries
1355 * for it's current delegation point.
1357 * @param qstate: query state.
1358 * @param iq: iterator query state.
1359 * @param ie: iterator shared global environment.
1360 * @param id: module id.
1361 * @param maxtargets: The maximum number of targets to query for.
1362 * if it is negative, there is no maximum number of targets.
1363 * @param num: returns the number of queries generated and processed,
1364 * which may be zero if there were no missing targets.
1365 * @return false on error.
1368 query_for_targets(struct module_qstate* qstate, struct iter_qstate* iq,
1369 struct iter_env* ie, int id, int maxtargets, int* num)
1371 int query_count = 0;
1372 struct delegpt_ns* ns;
1376 if(iq->depth == ie->max_dependency_depth)
1378 if(iq->depth > 0 && iq->target_count &&
1379 iq->target_count[1] > MAX_TARGET_COUNT) {
1380 verbose(VERB_QUERY, "request has exceeded the maximum "
1381 "number of glue fetches %d", iq->target_count[1]);
1385 iter_mark_cycle_targets(qstate, iq->dp);
1386 missing = (int)delegpt_count_missing_targets(iq->dp);
1387 log_assert(maxtargets != 0); /* that would not be useful */
1389 /* Generate target requests. Basically, any missing targets
1390 * are queried for here, regardless if it is necessary to do
1391 * so to continue processing. */
1392 if(maxtargets < 0 || maxtargets > missing)
1394 else toget = maxtargets;
1399 /* select 'toget' items from the total of 'missing' items */
1400 log_assert(toget <= missing);
1402 /* loop over missing targets */
1403 for(ns = iq->dp->nslist; ns; ns = ns->next) {
1407 /* randomly select this item with probability toget/missing */
1408 if(!iter_ns_probability(qstate->env->rnd, toget, missing)) {
1409 /* do not select this one, next; select toget number
1410 * of items from a list one less in size */
1415 if(ie->supports_ipv6 && !ns->got6) {
1416 /* Send the AAAA request. */
1417 if(!generate_target_query(qstate, iq, id,
1418 ns->name, ns->namelen,
1419 LDNS_RR_TYPE_AAAA, iq->qchase.qclass)) {
1422 qstate->ext_state[id] = module_wait_subquery;
1427 /* Send the A request. */
1428 if(ie->supports_ipv4 && !ns->got4) {
1429 if(!generate_target_query(qstate, iq, id,
1430 ns->name, ns->namelen,
1431 LDNS_RR_TYPE_A, iq->qchase.qclass)) {
1434 qstate->ext_state[id] = module_wait_subquery;
1440 /* mark this target as in progress. */
1449 qstate->ext_state[id] = module_wait_subquery;
1454 /** see if last resort is possible - does config allow queries to parent */
1456 can_have_last_resort(struct module_env* env, struct delegpt* dp,
1457 struct iter_qstate* iq)
1459 struct delegpt* fwddp;
1460 struct iter_hints_stub* stub;
1461 /* do not process a last resort (the parent side) if a stub
1462 * or forward is configured, because we do not want to go 'above'
1463 * the configured servers */
1464 if(!dname_is_root(dp->name) && (stub = (struct iter_hints_stub*)
1465 name_tree_find(&env->hints->tree, dp->name, dp->namelen,
1466 dp->namelabs, iq->qchase.qclass)) &&
1467 /* has_parent side is turned off for stub_first, where we
1468 * are allowed to go to the parent */
1469 stub->dp->has_parent_side_NS) {
1470 verbose(VERB_QUERY, "configured stub servers failed -- returning SERVFAIL");
1473 if((fwddp = forwards_find(env->fwds, dp->name, iq->qchase.qclass)) &&
1474 /* has_parent_side is turned off for forward_first, where
1475 * we are allowed to go to the parent */
1476 fwddp->has_parent_side_NS) {
1477 verbose(VERB_QUERY, "configured forward servers failed -- returning SERVFAIL");
1484 * Called by processQueryTargets when it would like extra targets to query
1485 * but it seems to be out of options. At last resort some less appealing
1486 * options are explored. If there are no more options, the result is SERVFAIL
1488 * @param qstate: query state.
1489 * @param iq: iterator query state.
1490 * @param ie: iterator shared global environment.
1491 * @param id: module id.
1492 * @return true if the event requires more request processing immediately,
1496 processLastResort(struct module_qstate* qstate, struct iter_qstate* iq,
1497 struct iter_env* ie, int id)
1499 struct delegpt_ns* ns;
1500 int query_count = 0;
1501 verbose(VERB_ALGO, "No more query targets, attempting last resort");
1504 if(!can_have_last_resort(qstate->env, iq->dp, iq)) {
1505 /* fail -- no more targets, no more hope of targets, no hope
1507 return error_response_cache(qstate, id, LDNS_RCODE_SERVFAIL);
1509 if(!iq->dp->has_parent_side_NS && dname_is_root(iq->dp->name)) {
1510 struct delegpt* p = hints_lookup_root(qstate->env->hints,
1513 struct delegpt_ns* ns;
1514 struct delegpt_addr* a;
1515 iq->chase_flags &= ~BIT_RD; /* go to authorities */
1516 for(ns = p->nslist; ns; ns=ns->next) {
1517 (void)delegpt_add_ns(iq->dp, qstate->region,
1518 ns->name, ns->lame);
1520 for(a = p->target_list; a; a=a->next_target) {
1521 (void)delegpt_add_addr(iq->dp, qstate->region,
1522 &a->addr, a->addrlen, a->bogus,
1526 iq->dp->has_parent_side_NS = 1;
1527 } else if(!iq->dp->has_parent_side_NS) {
1528 if(!iter_lookup_parent_NS_from_cache(qstate->env, iq->dp,
1529 qstate->region, &qstate->qinfo)
1530 || !iq->dp->has_parent_side_NS) {
1531 /* if: malloc failure in lookup go up to try */
1532 /* if: no parent NS in cache - go up one level */
1533 verbose(VERB_ALGO, "try to grab parent NS");
1534 iq->store_parent_NS = iq->dp;
1535 iq->chase_flags &= ~BIT_RD; /* go to authorities */
1536 iq->deleg_msg = NULL;
1537 iq->refetch_glue = 1;
1538 iq->query_restart_count++;
1540 return next_state(iq, INIT_REQUEST_STATE);
1543 /* see if that makes new names available */
1544 if(!cache_fill_missing(qstate->env, iq->qchase.qclass,
1545 qstate->region, iq->dp))
1546 log_err("out of memory in cache_fill_missing");
1547 if(iq->dp->usable_list) {
1548 verbose(VERB_ALGO, "try parent-side-name, w. glue from cache");
1549 return next_state(iq, QUERYTARGETS_STATE);
1551 /* try to fill out parent glue from cache */
1552 if(iter_lookup_parent_glue_from_cache(qstate->env, iq->dp,
1553 qstate->region, &qstate->qinfo)) {
1554 /* got parent stuff from cache, see if we can continue */
1555 verbose(VERB_ALGO, "try parent-side glue from cache");
1556 return next_state(iq, QUERYTARGETS_STATE);
1558 /* query for an extra name added by the parent-NS record */
1559 if(delegpt_count_missing_targets(iq->dp) > 0) {
1561 verbose(VERB_ALGO, "try parent-side target name");
1562 if(!query_for_targets(qstate, iq, ie, id, 1, &qs)) {
1563 return error_response(qstate, id, LDNS_RCODE_SERVFAIL);
1565 iq->num_target_queries += qs;
1566 target_count_increase(iq, qs);
1568 qstate->ext_state[id] = module_wait_subquery;
1569 return 0; /* and wait for them */
1572 if(iq->depth == ie->max_dependency_depth) {
1573 verbose(VERB_QUERY, "maxdepth and need more nameservers, fail");
1574 return error_response_cache(qstate, id, LDNS_RCODE_SERVFAIL);
1576 if(iq->depth > 0 && iq->target_count &&
1577 iq->target_count[1] > MAX_TARGET_COUNT) {
1578 verbose(VERB_QUERY, "request has exceeded the maximum "
1579 "number of glue fetches %d", iq->target_count[1]);
1580 return error_response_cache(qstate, id, LDNS_RCODE_SERVFAIL);
1582 /* mark cycle targets for parent-side lookups */
1583 iter_mark_pside_cycle_targets(qstate, iq->dp);
1584 /* see if we can issue queries to get nameserver addresses */
1585 /* this lookup is not randomized, but sequential. */
1586 for(ns = iq->dp->nslist; ns; ns = ns->next) {
1587 /* query for parent-side A and AAAA for nameservers */
1588 if(ie->supports_ipv6 && !ns->done_pside6) {
1589 /* Send the AAAA request. */
1590 if(!generate_parentside_target_query(qstate, iq, id,
1591 ns->name, ns->namelen,
1592 LDNS_RR_TYPE_AAAA, iq->qchase.qclass))
1593 return error_response(qstate, id,
1594 LDNS_RCODE_SERVFAIL);
1595 ns->done_pside6 = 1;
1598 if(ie->supports_ipv4 && !ns->done_pside4) {
1599 /* Send the A request. */
1600 if(!generate_parentside_target_query(qstate, iq, id,
1601 ns->name, ns->namelen,
1602 LDNS_RR_TYPE_A, iq->qchase.qclass))
1603 return error_response(qstate, id,
1604 LDNS_RCODE_SERVFAIL);
1605 ns->done_pside4 = 1;
1608 if(query_count != 0) { /* suspend to await results */
1609 verbose(VERB_ALGO, "try parent-side glue lookup");
1610 iq->num_target_queries += query_count;
1611 target_count_increase(iq, query_count);
1612 qstate->ext_state[id] = module_wait_subquery;
1617 /* if this was a parent-side glue query itself, then store that
1618 * failure in cache. */
1619 if(iq->query_for_pside_glue && !iq->pside_glue)
1620 iter_store_parentside_neg(qstate->env, &qstate->qinfo,
1621 iq->deleg_msg?iq->deleg_msg->rep:
1622 (iq->response?iq->response->rep:NULL));
1624 verbose(VERB_QUERY, "out of query targets -- returning SERVFAIL");
1625 /* fail -- no more targets, no more hope of targets, no hope
1627 return error_response_cache(qstate, id, LDNS_RCODE_SERVFAIL);
1631 * Try to find the NS record set that will resolve a qtype DS query. Due
1632 * to grandparent/grandchild reasons we did not get a proper lookup right
1633 * away. We need to create type NS queries until we get the right parent
1634 * for this lookup. We remove labels from the query to find the right point.
1635 * If we end up at the old dp name, then there is no solution.
1637 * @param qstate: query state.
1638 * @param iq: iterator query state.
1639 * @param id: module id.
1640 * @return true if the event requires more immediate processing, false if
1641 * not. This is generally only true when forwarding the request to
1642 * the final state (i.e., on answer).
1645 processDSNSFind(struct module_qstate* qstate, struct iter_qstate* iq, int id)
1647 struct module_qstate* subq = NULL;
1648 verbose(VERB_ALGO, "processDSNSFind");
1650 if(!iq->dsns_point) {
1652 iq->dsns_point = iq->qchase.qname;
1653 iq->dsns_point_len = iq->qchase.qname_len;
1655 /* robustcheck for internal error: we are not underneath the dp */
1656 if(!dname_subdomain_c(iq->dsns_point, iq->dp->name)) {
1657 return error_response_cache(qstate, id, LDNS_RCODE_SERVFAIL);
1660 /* go up one (more) step, until we hit the dp, if so, end */
1661 dname_remove_label(&iq->dsns_point, &iq->dsns_point_len);
1662 if(query_dname_compare(iq->dsns_point, iq->dp->name) == 0) {
1663 /* there was no inbetween nameserver, use the old delegation
1664 * point again. And this time, because dsns_point is nonNULL
1665 * we are going to accept the (bad) result */
1666 iq->state = QUERYTARGETS_STATE;
1669 iq->state = DSNS_FIND_STATE;
1671 /* spawn NS lookup (validation not needed, this is for DS lookup) */
1672 log_nametypeclass(VERB_ALGO, "fetch nameservers",
1673 iq->dsns_point, LDNS_RR_TYPE_NS, iq->qchase.qclass);
1674 if(!generate_sub_request(iq->dsns_point, iq->dsns_point_len,
1675 LDNS_RR_TYPE_NS, iq->qchase.qclass, qstate, id, iq,
1676 INIT_REQUEST_STATE, FINISHED_STATE, &subq, 0)) {
1677 return error_response_cache(qstate, id, LDNS_RCODE_SERVFAIL);
1684 * This is the request event state where the request will be sent to one of
1685 * its current query targets. This state also handles issuing target lookup
1686 * queries for missing target IP addresses. Queries typically iterate on
1687 * this state, both when they are just trying different targets for a given
1688 * delegation point, and when they change delegation points. This state
1689 * roughly corresponds to RFC 1034 algorithm steps 3 and 4.
1691 * @param qstate: query state.
1692 * @param iq: iterator query state.
1693 * @param ie: iterator shared global environment.
1694 * @param id: module id.
1695 * @return true if the event requires more request processing immediately,
1696 * false if not. This state only returns true when it is generating
1697 * a SERVFAIL response because the query has hit a dead end.
1700 processQueryTargets(struct module_qstate* qstate, struct iter_qstate* iq,
1701 struct iter_env* ie, int id)
1704 struct delegpt_addr* target;
1705 struct outbound_entry* outq;
1707 /* NOTE: a request will encounter this state for each target it
1708 * needs to send a query to. That is, at least one per referral,
1709 * more if some targets timeout or return throwaway answers. */
1711 log_query_info(VERB_QUERY, "processQueryTargets:", &qstate->qinfo);
1712 verbose(VERB_ALGO, "processQueryTargets: targetqueries %d, "
1713 "currentqueries %d sentcount %d", iq->num_target_queries,
1714 iq->num_current_queries, iq->sent_count);
1716 /* Make sure that we haven't run away */
1717 /* FIXME: is this check even necessary? */
1718 if(iq->referral_count > MAX_REFERRAL_COUNT) {
1719 verbose(VERB_QUERY, "request has exceeded the maximum "
1720 "number of referrrals with %d", iq->referral_count);
1721 return error_response(qstate, id, LDNS_RCODE_SERVFAIL);
1723 if(iq->sent_count > MAX_SENT_COUNT) {
1724 verbose(VERB_QUERY, "request has exceeded the maximum "
1725 "number of sends with %d", iq->sent_count);
1726 return error_response(qstate, id, LDNS_RCODE_SERVFAIL);
1729 /* Make sure we have a delegation point, otherwise priming failed
1730 * or another failure occurred */
1732 verbose(VERB_QUERY, "Failed to get a delegation, giving up");
1733 return error_response(qstate, id, LDNS_RCODE_SERVFAIL);
1735 if(!ie->supports_ipv6)
1736 delegpt_no_ipv6(iq->dp);
1737 if(!ie->supports_ipv4)
1738 delegpt_no_ipv4(iq->dp);
1739 delegpt_log(VERB_ALGO, iq->dp);
1741 if(iq->num_current_queries>0) {
1742 /* already busy answering a query, this restart is because
1743 * more delegpt addrs became available, wait for existing
1745 verbose(VERB_ALGO, "woke up, but wait for outstanding query");
1746 qstate->ext_state[id] = module_wait_reply;
1751 /* < not <=, because although the array is large enough for <=, the
1752 * generated query will immediately be discarded due to depth and
1753 * that servfail is cached, which is not good as opportunism goes. */
1754 if(iq->depth < ie->max_dependency_depth
1755 && iq->sent_count < TARGET_FETCH_STOP) {
1756 tf_policy = ie->target_fetch_policy[iq->depth];
1759 /* if in 0x20 fallback get as many targets as possible */
1760 if(iq->caps_fallback) {
1762 size_t naddr, nres, navail;
1763 if(!query_for_targets(qstate, iq, ie, id, -1, &extra)) {
1764 return error_response(qstate, id, LDNS_RCODE_SERVFAIL);
1766 iq->num_target_queries += extra;
1767 target_count_increase(iq, extra);
1768 if(iq->num_target_queries > 0) {
1769 /* wait to get all targets, we want to try em */
1770 verbose(VERB_ALGO, "wait for all targets for fallback");
1771 qstate->ext_state[id] = module_wait_reply;
1774 /* did we do enough fallback queries already? */
1775 delegpt_count_addr(iq->dp, &naddr, &nres, &navail);
1776 /* the current caps_server is the number of fallbacks sent.
1777 * the original query is one that matched too, so we have
1778 * caps_server+1 number of matching queries now */
1779 if(iq->caps_server+1 >= naddr*3 ||
1780 iq->caps_server+1 >= MAX_SENT_COUNT) {
1781 /* we're done, process the response */
1782 verbose(VERB_ALGO, "0x20 fallback had %d responses "
1783 "match for %d wanted, done.",
1784 (int)iq->caps_server+1, (int)naddr*3);
1785 iq->caps_fallback = 0;
1786 iter_dec_attempts(iq->dp, 3); /* space for fallback */
1787 iq->num_current_queries++; /* RespState decrements it*/
1788 iq->referral_count++; /* make sure we don't loop */
1790 iq->state = QUERY_RESP_STATE;
1793 verbose(VERB_ALGO, "0x20 fallback number %d",
1794 (int)iq->caps_server);
1796 /* if there is a policy to fetch missing targets
1797 * opportunistically, do it. we rely on the fact that once a
1798 * query (or queries) for a missing name have been issued,
1799 * they will not show up again. */
1800 } else if(tf_policy != 0) {
1802 verbose(VERB_ALGO, "attempt to get extra %d targets",
1804 (void)query_for_targets(qstate, iq, ie, id, tf_policy, &extra);
1805 /* errors ignored, these targets are not strictly necessary for
1806 * this result, we do not have to reply with SERVFAIL */
1807 iq->num_target_queries += extra;
1808 target_count_increase(iq, extra);
1811 /* Add the current set of unused targets to our queue. */
1812 delegpt_add_unused_targets(iq->dp);
1814 /* Select the next usable target, filtering out unsuitable targets. */
1815 target = iter_server_selection(ie, qstate->env, iq->dp,
1816 iq->dp->name, iq->dp->namelen, iq->qchase.qtype,
1817 &iq->dnssec_lame_query, &iq->chase_to_rd,
1818 iq->num_target_queries, qstate->blacklist);
1820 /* If no usable target was selected... */
1822 /* Here we distinguish between three states: generate a new
1823 * target query, just wait, or quit (with a SERVFAIL).
1824 * We have the following information: number of active
1825 * target queries, number of active current queries,
1826 * the presence of missing targets at this delegation
1827 * point, and the given query target policy. */
1829 /* Check for the wait condition. If this is true, then
1830 * an action must be taken. */
1831 if(iq->num_target_queries==0 && iq->num_current_queries==0) {
1832 /* If there is nothing to wait for, then we need
1833 * to distinguish between generating (a) new target
1834 * query, or failing. */
1835 if(delegpt_count_missing_targets(iq->dp) > 0) {
1837 verbose(VERB_ALGO, "querying for next "
1839 if(!query_for_targets(qstate, iq, ie, id,
1841 return error_response(qstate, id,
1842 LDNS_RCODE_SERVFAIL);
1845 delegpt_count_missing_targets(iq->dp) == 0){
1846 /* it looked like there were missing
1847 * targets, but they did not turn up.
1848 * Try the bad choices again (if any),
1849 * when we get back here missing==0,
1850 * so this is not a loop. */
1853 iq->num_target_queries += qs;
1854 target_count_increase(iq, qs);
1856 /* Since a target query might have been made, we
1857 * need to check again. */
1858 if(iq->num_target_queries == 0) {
1859 return processLastResort(qstate, iq, ie, id);
1863 /* otherwise, we have no current targets, so submerge
1864 * until one of the target or direct queries return. */
1865 if(iq->num_target_queries>0 && iq->num_current_queries>0) {
1866 verbose(VERB_ALGO, "no current targets -- waiting "
1867 "for %d targets to resolve or %d outstanding"
1868 " queries to respond", iq->num_target_queries,
1869 iq->num_current_queries);
1870 qstate->ext_state[id] = module_wait_reply;
1871 } else if(iq->num_target_queries>0) {
1872 verbose(VERB_ALGO, "no current targets -- waiting "
1873 "for %d targets to resolve.",
1874 iq->num_target_queries);
1875 qstate->ext_state[id] = module_wait_subquery;
1877 verbose(VERB_ALGO, "no current targets -- waiting "
1878 "for %d outstanding queries to respond.",
1879 iq->num_current_queries);
1880 qstate->ext_state[id] = module_wait_reply;
1885 /* We have a valid target. */
1886 if(verbosity >= VERB_QUERY) {
1887 log_query_info(VERB_QUERY, "sending query:", &iq->qchase);
1888 log_name_addr(VERB_QUERY, "sending to target:", iq->dp->name,
1889 &target->addr, target->addrlen);
1890 verbose(VERB_ALGO, "dnssec status: %s%s",
1891 iq->dnssec_expected?"expected": "not expected",
1892 iq->dnssec_lame_query?" but lame_query anyway": "");
1894 fptr_ok(fptr_whitelist_modenv_send_query(qstate->env->send_query));
1895 outq = (*qstate->env->send_query)(
1896 iq->qchase.qname, iq->qchase.qname_len,
1897 iq->qchase.qtype, iq->qchase.qclass,
1898 iq->chase_flags | (iq->chase_to_rd?BIT_RD:0), EDNS_DO|BIT_CD,
1899 iq->dnssec_expected, iq->caps_fallback, &target->addr,
1900 target->addrlen, iq->dp->name, iq->dp->namelen, qstate);
1902 log_addr(VERB_DETAIL, "error sending query to auth server",
1903 &target->addr, target->addrlen);
1904 return next_state(iq, QUERYTARGETS_STATE);
1906 outbound_list_insert(&iq->outlist, outq);
1907 iq->num_current_queries++;
1909 qstate->ext_state[id] = module_wait_reply;
1914 /** find NS rrset in given list */
1915 static struct ub_packed_rrset_key*
1916 find_NS(struct reply_info* rep, size_t from, size_t to)
1919 for(i=from; i<to; i++) {
1920 if(ntohs(rep->rrsets[i]->rk.type) == LDNS_RR_TYPE_NS)
1921 return rep->rrsets[i];
1928 * Process the query response. All queries end up at this state first. This
1929 * process generally consists of analyzing the response and routing the
1930 * event to the next state (either bouncing it back to a request state, or
1931 * terminating the processing for this event).
1933 * @param qstate: query state.
1934 * @param iq: iterator query state.
1935 * @param id: module id.
1936 * @return true if the event requires more immediate processing, false if
1937 * not. This is generally only true when forwarding the request to
1938 * the final state (i.e., on answer).
1941 processQueryResponse(struct module_qstate* qstate, struct iter_qstate* iq,
1945 enum response_type type;
1946 iq->num_current_queries--;
1947 if(iq->response == NULL) {
1948 iq->chase_to_rd = 0;
1949 iq->dnssec_lame_query = 0;
1950 verbose(VERB_ALGO, "query response was timeout");
1951 return next_state(iq, QUERYTARGETS_STATE);
1953 type = response_type_from_server(
1954 (int)((iq->chase_flags&BIT_RD) || iq->chase_to_rd),
1955 iq->response, &iq->qchase, iq->dp);
1956 iq->chase_to_rd = 0;
1957 if(type == RESPONSE_TYPE_REFERRAL && (iq->chase_flags&BIT_RD)) {
1958 /* When forwarding (RD bit is set), we handle referrals
1959 * differently. No queries should be sent elsewhere */
1960 type = RESPONSE_TYPE_ANSWER;
1962 if(iq->dnssec_expected && !iq->dnssec_lame_query &&
1963 !(iq->chase_flags&BIT_RD)
1964 && type != RESPONSE_TYPE_LAME
1965 && type != RESPONSE_TYPE_REC_LAME
1966 && type != RESPONSE_TYPE_THROWAWAY
1967 && type != RESPONSE_TYPE_UNTYPED) {
1968 /* a possible answer, see if it is missing DNSSEC */
1969 /* but not when forwarding, so we dont mark fwder lame */
1970 if(!iter_msg_has_dnssec(iq->response)) {
1971 /* Mark this address as dnsseclame in this dp,
1972 * because that will make serverselection disprefer
1973 * it, but also, once it is the only final option,
1974 * use dnssec-lame-bypass if it needs to query there.*/
1976 struct delegpt_addr* a = delegpt_find_addr(
1977 iq->dp, &qstate->reply->addr,
1978 qstate->reply->addrlen);
1979 if(a) a->dnsseclame = 1;
1981 /* test the answer is from the zone we expected,
1982 * otherwise, (due to parent,child on same server), we
1983 * might mark the server,zone lame inappropriately */
1984 if(!iter_msg_from_zone(iq->response, iq->dp, type,
1986 qstate->reply = NULL;
1987 type = RESPONSE_TYPE_LAME;
1990 } else iq->dnssec_lame_query = 0;
1991 /* see if referral brings us close to the target */
1992 if(type == RESPONSE_TYPE_REFERRAL) {
1993 struct ub_packed_rrset_key* ns = find_NS(
1994 iq->response->rep, iq->response->rep->an_numrrsets,
1995 iq->response->rep->an_numrrsets
1996 + iq->response->rep->ns_numrrsets);
1997 if(!ns) ns = find_NS(iq->response->rep, 0,
1998 iq->response->rep->an_numrrsets);
1999 if(!ns || !dname_strict_subdomain_c(ns->rk.dname, iq->dp->name)
2000 || !dname_subdomain_c(iq->qchase.qname, ns->rk.dname)){
2001 verbose(VERB_ALGO, "bad referral, throwaway");
2002 type = RESPONSE_TYPE_THROWAWAY;
2004 iter_scrub_ds(iq->response, ns, iq->dp->name);
2005 } else iter_scrub_ds(iq->response, NULL, NULL);
2007 /* handle each of the type cases */
2008 if(type == RESPONSE_TYPE_ANSWER) {
2009 /* ANSWER type responses terminate the query algorithm,
2010 * so they sent on their */
2011 if(verbosity >= VERB_DETAIL) {
2012 verbose(VERB_DETAIL, "query response was %s",
2013 FLAGS_GET_RCODE(iq->response->rep->flags)
2014 ==LDNS_RCODE_NXDOMAIN?"NXDOMAIN ANSWER":
2015 (iq->response->rep->an_numrrsets?"ANSWER":
2018 /* if qtype is DS, check we have the right level of answer,
2019 * like grandchild answer but we need the middle, reject it */
2020 if(iq->qchase.qtype == LDNS_RR_TYPE_DS && !iq->dsns_point
2021 && !(iq->chase_flags&BIT_RD)
2022 && iter_ds_toolow(iq->response, iq->dp)
2023 && iter_dp_cangodown(&iq->qchase, iq->dp)) {
2024 /* close down outstanding requests to be discarded */
2025 outbound_list_clear(&iq->outlist);
2026 iq->num_current_queries = 0;
2027 fptr_ok(fptr_whitelist_modenv_detach_subs(
2028 qstate->env->detach_subs));
2029 (*qstate->env->detach_subs)(qstate);
2030 iq->num_target_queries = 0;
2031 return processDSNSFind(qstate, iq, id);
2033 iter_dns_store(qstate->env, &iq->response->qinfo,
2034 iq->response->rep, 0, qstate->prefetch_leeway,
2035 iq->dp&&iq->dp->has_parent_side_NS,
2037 /* close down outstanding requests to be discarded */
2038 outbound_list_clear(&iq->outlist);
2039 iq->num_current_queries = 0;
2040 fptr_ok(fptr_whitelist_modenv_detach_subs(
2041 qstate->env->detach_subs));
2042 (*qstate->env->detach_subs)(qstate);
2043 iq->num_target_queries = 0;
2045 sock_list_insert(&qstate->reply_origin,
2046 &qstate->reply->addr, qstate->reply->addrlen,
2048 return final_state(iq);
2049 } else if(type == RESPONSE_TYPE_REFERRAL) {
2050 /* REFERRAL type responses get a reset of the
2051 * delegation point, and back to the QUERYTARGETS_STATE. */
2052 verbose(VERB_DETAIL, "query response was REFERRAL");
2054 /* if hardened, only store referral if we asked for it */
2055 if(!qstate->env->cfg->harden_referral_path ||
2056 ( qstate->qinfo.qtype == LDNS_RR_TYPE_NS
2057 && (qstate->query_flags&BIT_RD)
2058 && !(qstate->query_flags&BIT_CD)
2059 /* we know that all other NS rrsets are scrubbed
2060 * away, thus on referral only one is left.
2061 * see if that equals the query name... */
2062 && ( /* auth section, but sometimes in answer section*/
2063 reply_find_rrset_section_ns(iq->response->rep,
2064 iq->qchase.qname, iq->qchase.qname_len,
2065 LDNS_RR_TYPE_NS, iq->qchase.qclass)
2066 || reply_find_rrset_section_an(iq->response->rep,
2067 iq->qchase.qname, iq->qchase.qname_len,
2068 LDNS_RR_TYPE_NS, iq->qchase.qclass)
2071 /* Store the referral under the current query */
2072 /* no prefetch-leeway, since its not the answer */
2073 iter_dns_store(qstate->env, &iq->response->qinfo,
2074 iq->response->rep, 1, 0, 0, NULL);
2075 if(iq->store_parent_NS)
2076 iter_store_parentside_NS(qstate->env,
2078 if(qstate->env->neg_cache)
2079 val_neg_addreferral(qstate->env->neg_cache,
2080 iq->response->rep, iq->dp->name);
2082 /* store parent-side-in-zone-glue, if directly queried for */
2083 if(iq->query_for_pside_glue && !iq->pside_glue) {
2084 iq->pside_glue = reply_find_rrset(iq->response->rep,
2085 iq->qchase.qname, iq->qchase.qname_len,
2086 iq->qchase.qtype, iq->qchase.qclass);
2087 if(iq->pside_glue) {
2088 log_rrset_key(VERB_ALGO, "found parent-side "
2089 "glue", iq->pside_glue);
2090 iter_store_parentside_rrset(qstate->env,
2095 /* Reset the event state, setting the current delegation
2096 * point to the referral. */
2097 iq->deleg_msg = iq->response;
2098 iq->dp = delegpt_from_message(iq->response, qstate->region);
2100 return error_response(qstate, id, LDNS_RCODE_SERVFAIL);
2101 if(!cache_fill_missing(qstate->env, iq->qchase.qclass,
2102 qstate->region, iq->dp))
2103 return error_response(qstate, id, LDNS_RCODE_SERVFAIL);
2104 if(iq->store_parent_NS && query_dname_compare(iq->dp->name,
2105 iq->store_parent_NS->name) == 0)
2106 iter_merge_retry_counts(iq->dp, iq->store_parent_NS);
2107 delegpt_log(VERB_ALGO, iq->dp);
2108 /* Count this as a referral. */
2109 iq->referral_count++;
2111 /* see if the next dp is a trust anchor, or a DS was sent
2112 * along, indicating dnssec is expected for next zone */
2113 iq->dnssec_expected = iter_indicates_dnssec(qstate->env,
2114 iq->dp, iq->response, iq->qchase.qclass);
2115 /* if dnssec, validating then also fetch the key for the DS */
2116 if(iq->dnssec_expected && qstate->env->cfg->prefetch_key &&
2117 !(qstate->query_flags&BIT_CD))
2118 generate_dnskey_prefetch(qstate, iq, id);
2120 /* spawn off NS and addr to auth servers for the NS we just
2121 * got in the referral. This gets authoritative answer
2122 * (answer section trust level) rrset.
2123 * right after, we detach the subs, answer goes to cache. */
2124 if(qstate->env->cfg->harden_referral_path)
2125 generate_ns_check(qstate, iq, id);
2127 /* stop current outstanding queries.
2128 * FIXME: should the outstanding queries be waited for and
2129 * handled? Say by a subquery that inherits the outbound_entry.
2131 outbound_list_clear(&iq->outlist);
2132 iq->num_current_queries = 0;
2133 fptr_ok(fptr_whitelist_modenv_detach_subs(
2134 qstate->env->detach_subs));
2135 (*qstate->env->detach_subs)(qstate);
2136 iq->num_target_queries = 0;
2137 verbose(VERB_ALGO, "cleared outbound list for next round");
2138 return next_state(iq, QUERYTARGETS_STATE);
2139 } else if(type == RESPONSE_TYPE_CNAME) {
2140 uint8_t* sname = NULL;
2141 size_t snamelen = 0;
2142 /* CNAME type responses get a query restart (i.e., get a
2143 * reset of the query state and go back to INIT_REQUEST_STATE).
2145 verbose(VERB_DETAIL, "query response was CNAME");
2146 if(verbosity >= VERB_ALGO)
2147 log_dns_msg("cname msg", &iq->response->qinfo,
2149 /* if qtype is DS, check we have the right level of answer,
2150 * like grandchild answer but we need the middle, reject it */
2151 if(iq->qchase.qtype == LDNS_RR_TYPE_DS && !iq->dsns_point
2152 && !(iq->chase_flags&BIT_RD)
2153 && iter_ds_toolow(iq->response, iq->dp)
2154 && iter_dp_cangodown(&iq->qchase, iq->dp)) {
2155 outbound_list_clear(&iq->outlist);
2156 iq->num_current_queries = 0;
2157 fptr_ok(fptr_whitelist_modenv_detach_subs(
2158 qstate->env->detach_subs));
2159 (*qstate->env->detach_subs)(qstate);
2160 iq->num_target_queries = 0;
2161 return processDSNSFind(qstate, iq, id);
2163 /* Process the CNAME response. */
2164 if(!handle_cname_response(qstate, iq, iq->response,
2166 return error_response(qstate, id, LDNS_RCODE_SERVFAIL);
2167 /* cache the CNAME response under the current query */
2168 /* NOTE : set referral=1, so that rrsets get stored but not
2169 * the partial query answer (CNAME only). */
2170 /* prefetchleeway applied because this updates answer parts */
2171 iter_dns_store(qstate->env, &iq->response->qinfo,
2172 iq->response->rep, 1, qstate->prefetch_leeway,
2173 iq->dp&&iq->dp->has_parent_side_NS, NULL);
2174 /* set the current request's qname to the new value. */
2175 iq->qchase.qname = sname;
2176 iq->qchase.qname_len = snamelen;
2177 /* Clear the query state, since this is a query restart. */
2178 iq->deleg_msg = NULL;
2180 iq->dsns_point = NULL;
2181 /* Note the query restart. */
2182 iq->query_restart_count++;
2185 /* stop current outstanding queries.
2186 * FIXME: should the outstanding queries be waited for and
2187 * handled? Say by a subquery that inherits the outbound_entry.
2189 outbound_list_clear(&iq->outlist);
2190 iq->num_current_queries = 0;
2191 fptr_ok(fptr_whitelist_modenv_detach_subs(
2192 qstate->env->detach_subs));
2193 (*qstate->env->detach_subs)(qstate);
2194 iq->num_target_queries = 0;
2196 sock_list_insert(&qstate->reply_origin,
2197 &qstate->reply->addr, qstate->reply->addrlen,
2199 verbose(VERB_ALGO, "cleared outbound list for query restart");
2200 /* go to INIT_REQUEST_STATE for new qname. */
2201 return next_state(iq, INIT_REQUEST_STATE);
2202 } else if(type == RESPONSE_TYPE_LAME) {
2203 /* Cache the LAMEness. */
2204 verbose(VERB_DETAIL, "query response was %sLAME",
2205 dnsseclame?"DNSSEC ":"");
2206 if(!dname_subdomain_c(iq->qchase.qname, iq->dp->name)) {
2207 log_err("mark lame: mismatch in qname and dpname");
2208 /* throwaway this reply below */
2209 } else if(qstate->reply) {
2210 /* need addr for lameness cache, but we may have
2211 * gotten this from cache, so test to be sure */
2212 if(!infra_set_lame(qstate->env->infra_cache,
2213 &qstate->reply->addr, qstate->reply->addrlen,
2214 iq->dp->name, iq->dp->namelen,
2215 *qstate->env->now, dnsseclame, 0,
2217 log_err("mark host lame: out of memory");
2219 } else if(type == RESPONSE_TYPE_REC_LAME) {
2220 /* Cache the LAMEness. */
2221 verbose(VERB_DETAIL, "query response REC_LAME: "
2222 "recursive but not authoritative server");
2223 if(!dname_subdomain_c(iq->qchase.qname, iq->dp->name)) {
2224 log_err("mark rec_lame: mismatch in qname and dpname");
2225 /* throwaway this reply below */
2226 } else if(qstate->reply) {
2227 /* need addr for lameness cache, but we may have
2228 * gotten this from cache, so test to be sure */
2229 verbose(VERB_DETAIL, "mark as REC_LAME");
2230 if(!infra_set_lame(qstate->env->infra_cache,
2231 &qstate->reply->addr, qstate->reply->addrlen,
2232 iq->dp->name, iq->dp->namelen,
2233 *qstate->env->now, 0, 1, iq->qchase.qtype))
2234 log_err("mark host lame: out of memory");
2236 } else if(type == RESPONSE_TYPE_THROWAWAY) {
2237 /* LAME and THROWAWAY responses are handled the same way.
2238 * In this case, the event is just sent directly back to
2239 * the QUERYTARGETS_STATE without resetting anything,
2240 * because, clearly, the next target must be tried. */
2241 verbose(VERB_DETAIL, "query response was THROWAWAY");
2243 log_warn("A query response came back with an unknown type: %d",
2247 /* LAME, THROWAWAY and "unknown" all end up here.
2248 * Recycle to the QUERYTARGETS state to hopefully try a
2249 * different target. */
2250 return next_state(iq, QUERYTARGETS_STATE);
2254 * Return priming query results to interestes super querystates.
2256 * Sets the delegation point and delegation message (not nonRD queries).
2257 * This is a callback from walk_supers.
2259 * @param qstate: priming query state that finished.
2260 * @param id: module id.
2261 * @param forq: the qstate for which priming has been done.
2264 prime_supers(struct module_qstate* qstate, int id, struct module_qstate* forq)
2266 struct iter_qstate* foriq = (struct iter_qstate*)forq->minfo[id];
2267 struct delegpt* dp = NULL;
2269 log_assert(qstate->is_priming || foriq->wait_priming_stub);
2270 log_assert(qstate->return_rcode == LDNS_RCODE_NOERROR);
2271 /* Convert our response to a delegation point */
2272 dp = delegpt_from_message(qstate->return_msg, forq->region);
2274 /* if there is no convertable delegation point, then
2275 * the ANSWER type was (presumably) a negative answer. */
2276 verbose(VERB_ALGO, "prime response was not a positive "
2279 foriq->state = QUERYTARGETS_STATE;
2283 log_query_info(VERB_DETAIL, "priming successful for", &qstate->qinfo);
2284 delegpt_log(VERB_ALGO, dp);
2286 foriq->deleg_msg = dns_copy_msg(qstate->return_msg, forq->region);
2287 if(!foriq->deleg_msg) {
2288 log_err("copy prime response: out of memory");
2290 foriq->state = QUERYTARGETS_STATE;
2294 /* root priming responses go to init stage 2, priming stub
2295 * responses to to stage 3. */
2296 if(foriq->wait_priming_stub) {
2297 foriq->state = INIT_REQUEST_3_STATE;
2298 foriq->wait_priming_stub = 0;
2299 } else foriq->state = INIT_REQUEST_2_STATE;
2300 /* because we are finished, the parent will be reactivated */
2304 * This handles the response to a priming query. This is used to handle both
2305 * root and stub priming responses. This is basically the equivalent of the
2306 * QUERY_RESP_STATE, but will not handle CNAME responses and will treat
2307 * REFERRALs as ANSWERS. It will also update and reactivate the originating
2310 * @param qstate: query state.
2311 * @param id: module id.
2312 * @return true if the event needs more immediate processing, false if not.
2313 * This state always returns false.
2316 processPrimeResponse(struct module_qstate* qstate, int id)
2318 struct iter_qstate* iq = (struct iter_qstate*)qstate->minfo[id];
2319 enum response_type type;
2320 iq->response->rep->flags &= ~(BIT_RD|BIT_RA); /* ignore rec-lame */
2321 type = response_type_from_server(
2322 (int)((iq->chase_flags&BIT_RD) || iq->chase_to_rd),
2323 iq->response, &iq->qchase, iq->dp);
2324 if(type == RESPONSE_TYPE_ANSWER) {
2325 qstate->return_rcode = LDNS_RCODE_NOERROR;
2326 qstate->return_msg = iq->response;
2328 qstate->return_rcode = LDNS_RCODE_SERVFAIL;
2329 qstate->return_msg = NULL;
2332 /* validate the root or stub after priming (if enabled).
2333 * This is the same query as the prime query, but with validation.
2334 * Now that we are primed, the additional queries that validation
2335 * may need can be resolved, such as DLV. */
2336 if(qstate->env->cfg->harden_referral_path) {
2337 struct module_qstate* subq = NULL;
2338 log_nametypeclass(VERB_ALGO, "schedule prime validation",
2339 qstate->qinfo.qname, qstate->qinfo.qtype,
2340 qstate->qinfo.qclass);
2341 if(!generate_sub_request(qstate->qinfo.qname,
2342 qstate->qinfo.qname_len, qstate->qinfo.qtype,
2343 qstate->qinfo.qclass, qstate, id, iq,
2344 INIT_REQUEST_STATE, FINISHED_STATE, &subq, 1)) {
2345 verbose(VERB_ALGO, "could not generate prime check");
2347 generate_a_aaaa_check(qstate, iq, id);
2350 /* This event is finished. */
2351 qstate->ext_state[id] = module_finished;
2356 * Do final processing on responses to target queries. Events reach this
2357 * state after the iterative resolution algorithm terminates. This state is
2358 * responsible for reactiving the original event, and housekeeping related
2359 * to received target responses (caching, updating the current delegation
2361 * Callback from walk_supers for every super state that is interested in
2362 * the results from this query.
2364 * @param qstate: query state.
2365 * @param id: module id.
2366 * @param forq: super query state.
2369 processTargetResponse(struct module_qstate* qstate, int id,
2370 struct module_qstate* forq)
2372 struct iter_qstate* iq = (struct iter_qstate*)qstate->minfo[id];
2373 struct iter_qstate* foriq = (struct iter_qstate*)forq->minfo[id];
2374 struct ub_packed_rrset_key* rrset;
2375 struct delegpt_ns* dpns;
2376 log_assert(qstate->return_rcode == LDNS_RCODE_NOERROR);
2378 foriq->state = QUERYTARGETS_STATE;
2379 log_query_info(VERB_ALGO, "processTargetResponse", &qstate->qinfo);
2380 log_query_info(VERB_ALGO, "processTargetResponse super", &forq->qinfo);
2382 /* check to see if parent event is still interested (in orig name). */
2384 verbose(VERB_ALGO, "subq: parent not interested, was reset");
2385 return; /* not interested anymore */
2387 dpns = delegpt_find_ns(foriq->dp, qstate->qinfo.qname,
2388 qstate->qinfo.qname_len);
2390 /* If not interested, just stop processing this event */
2391 verbose(VERB_ALGO, "subq: parent not interested anymore");
2392 /* could be because parent was jostled out of the cache,
2393 and a new identical query arrived, that does not want it*/
2397 /* Tell the originating event that this target query has finished
2398 * (regardless if it succeeded or not). */
2399 foriq->num_target_queries--;
2401 /* if iq->query_for_pside_glue then add the pside_glue (marked lame) */
2402 if(iq->pside_glue) {
2403 /* if the pside_glue is NULL, then it could not be found,
2404 * the done_pside is already set when created and a cache
2405 * entry created in processFinished so nothing to do here */
2406 log_rrset_key(VERB_ALGO, "add parentside glue to dp",
2408 if(!delegpt_add_rrset(foriq->dp, forq->region,
2410 log_err("out of memory adding pside glue");
2413 /* This response is relevant to the current query, so we
2414 * add (attempt to add, anyway) this target(s) and reactivate
2415 * the original event.
2416 * NOTE: we could only look for the AnswerRRset if the
2417 * response type was ANSWER. */
2418 rrset = reply_find_answer_rrset(&iq->qchase, qstate->return_msg->rep);
2420 /* if CNAMEs have been followed - add new NS to delegpt. */
2421 /* BTW. RFC 1918 says NS should not have got CNAMEs. Robust. */
2422 if(!delegpt_find_ns(foriq->dp, rrset->rk.dname,
2423 rrset->rk.dname_len)) {
2424 /* if dpns->lame then set newcname ns lame too */
2425 if(!delegpt_add_ns(foriq->dp, forq->region,
2426 rrset->rk.dname, dpns->lame))
2427 log_err("out of memory adding cnamed-ns");
2429 /* if dpns->lame then set the address(es) lame too */
2430 if(!delegpt_add_rrset(foriq->dp, forq->region, rrset,
2432 log_err("out of memory adding targets");
2433 verbose(VERB_ALGO, "added target response");
2434 delegpt_log(VERB_ALGO, foriq->dp);
2436 verbose(VERB_ALGO, "iterator TargetResponse failed");
2437 dpns->resolved = 1; /* fail the target */
2442 * Process response for DS NS Find queries, that attempt to find the delegation
2443 * point where we ask the DS query from.
2445 * @param qstate: query state.
2446 * @param id: module id.
2447 * @param forq: super query state.
2450 processDSNSResponse(struct module_qstate* qstate, int id,
2451 struct module_qstate* forq)
2453 struct iter_qstate* foriq = (struct iter_qstate*)forq->minfo[id];
2455 /* if the finished (iq->response) query has no NS set: continue
2456 * up to look for the right dp; nothing to change, do DPNSstate */
2457 if(qstate->return_rcode != LDNS_RCODE_NOERROR)
2458 return; /* seek further */
2459 /* find the NS RRset (without allowing CNAMEs) */
2460 if(!reply_find_rrset(qstate->return_msg->rep, qstate->qinfo.qname,
2461 qstate->qinfo.qname_len, LDNS_RR_TYPE_NS,
2462 qstate->qinfo.qclass)){
2463 return; /* seek further */
2466 /* else, store as DP and continue at querytargets */
2467 foriq->state = QUERYTARGETS_STATE;
2468 foriq->dp = delegpt_from_message(qstate->return_msg, forq->region);
2470 log_err("out of memory in dsns dp alloc");
2471 return; /* dp==NULL in QUERYTARGETS makes SERVFAIL */
2473 /* success, go query the querytargets in the new dp (and go down) */
2477 * Process response for qclass=ANY queries for a particular class.
2478 * Append to result or error-exit.
2480 * @param qstate: query state.
2481 * @param id: module id.
2482 * @param forq: super query state.
2485 processClassResponse(struct module_qstate* qstate, int id,
2486 struct module_qstate* forq)
2488 struct iter_qstate* foriq = (struct iter_qstate*)forq->minfo[id];
2489 struct dns_msg* from = qstate->return_msg;
2490 log_query_info(VERB_ALGO, "processClassResponse", &qstate->qinfo);
2491 log_query_info(VERB_ALGO, "processClassResponse super", &forq->qinfo);
2492 if(qstate->return_rcode != LDNS_RCODE_NOERROR) {
2493 /* cause servfail for qclass ANY query */
2494 foriq->response = NULL;
2495 foriq->state = FINISHED_STATE;
2499 if(!foriq->response) {
2500 /* allocate the response: copy RCODE, sec_state */
2501 foriq->response = dns_copy_msg(from, forq->region);
2502 if(!foriq->response) {
2503 log_err("malloc failed for qclass ANY response");
2504 foriq->state = FINISHED_STATE;
2507 foriq->response->qinfo.qclass = forq->qinfo.qclass;
2508 /* qclass ANY does not receive the AA flag on replies */
2509 foriq->response->rep->authoritative = 0;
2511 struct dns_msg* to = foriq->response;
2512 /* add _from_ this response _to_ existing collection */
2513 /* if there are records, copy RCODE */
2514 /* lower sec_state if this message is lower */
2515 if(from->rep->rrset_count != 0) {
2516 size_t n = from->rep->rrset_count+to->rep->rrset_count;
2517 struct ub_packed_rrset_key** dest, **d;
2518 /* copy appropriate rcode */
2519 to->rep->flags = from->rep->flags;
2521 dest = regional_alloc(forq->region, sizeof(dest[0])*n);
2523 log_err("malloc failed in collect ANY");
2524 foriq->state = FINISHED_STATE;
2529 memcpy(dest, to->rep->rrsets, to->rep->an_numrrsets
2531 dest += to->rep->an_numrrsets;
2532 memcpy(dest, from->rep->rrsets, from->rep->an_numrrsets
2534 dest += from->rep->an_numrrsets;
2536 memcpy(dest, to->rep->rrsets+to->rep->an_numrrsets,
2537 to->rep->ns_numrrsets * sizeof(dest[0]));
2538 dest += to->rep->ns_numrrsets;
2539 memcpy(dest, from->rep->rrsets+from->rep->an_numrrsets,
2540 from->rep->ns_numrrsets * sizeof(dest[0]));
2541 dest += from->rep->ns_numrrsets;
2543 memcpy(dest, to->rep->rrsets+to->rep->an_numrrsets+
2544 to->rep->ns_numrrsets,
2545 to->rep->ar_numrrsets * sizeof(dest[0]));
2546 dest += to->rep->ar_numrrsets;
2547 memcpy(dest, from->rep->rrsets+from->rep->an_numrrsets+
2548 from->rep->ns_numrrsets,
2549 from->rep->ar_numrrsets * sizeof(dest[0]));
2551 to->rep->rrsets = d;
2552 to->rep->an_numrrsets += from->rep->an_numrrsets;
2553 to->rep->ns_numrrsets += from->rep->ns_numrrsets;
2554 to->rep->ar_numrrsets += from->rep->ar_numrrsets;
2555 to->rep->rrset_count = n;
2557 if(from->rep->security < to->rep->security) /* lowest sec */
2558 to->rep->security = from->rep->security;
2559 if(from->rep->qdcount != 0) /* insert qd if appropriate */
2560 to->rep->qdcount = from->rep->qdcount;
2561 if(from->rep->ttl < to->rep->ttl) /* use smallest TTL */
2562 to->rep->ttl = from->rep->ttl;
2563 if(from->rep->prefetch_ttl < to->rep->prefetch_ttl)
2564 to->rep->prefetch_ttl = from->rep->prefetch_ttl;
2567 foriq->num_current_queries --;
2568 if(foriq->num_current_queries == 0)
2569 foriq->state = FINISHED_STATE;
2573 * Collect class ANY responses and make them into one response. This
2574 * state is started and it creates queries for all classes (that have
2575 * root hints). The answers are then collected.
2577 * @param qstate: query state.
2578 * @param id: module id.
2579 * @return true if the event needs more immediate processing, false if not.
2582 processCollectClass(struct module_qstate* qstate, int id)
2584 struct iter_qstate* iq = (struct iter_qstate*)qstate->minfo[id];
2585 struct module_qstate* subq;
2586 /* If qchase.qclass == 0 then send out queries for all classes.
2587 * Otherwise, do nothing (wait for all answers to arrive and the
2588 * processClassResponse to put them together, and that moves us
2589 * towards the Finished state when done. */
2590 if(iq->qchase.qclass == 0) {
2592 iq->qchase.qclass = LDNS_RR_CLASS_ANY;
2593 while(iter_get_next_root(qstate->env->hints,
2594 qstate->env->fwds, &c)) {
2595 /* generate query for this class */
2596 log_nametypeclass(VERB_ALGO, "spawn collect query",
2597 qstate->qinfo.qname, qstate->qinfo.qtype, c);
2598 if(!generate_sub_request(qstate->qinfo.qname,
2599 qstate->qinfo.qname_len, qstate->qinfo.qtype,
2600 c, qstate, id, iq, INIT_REQUEST_STATE,
2601 FINISHED_STATE, &subq,
2602 (int)!(qstate->query_flags&BIT_CD))) {
2603 return error_response(qstate, id,
2604 LDNS_RCODE_SERVFAIL);
2606 /* ignore subq, no special init required */
2607 iq->num_current_queries ++;
2612 /* if no roots are configured at all, return */
2613 if(iq->num_current_queries == 0) {
2614 verbose(VERB_ALGO, "No root hints or fwds, giving up "
2616 return error_response(qstate, id, LDNS_RCODE_REFUSED);
2618 /* return false, wait for queries to return */
2620 /* if woke up here because of an answer, wait for more answers */
2625 * This handles the final state for first-tier responses (i.e., responses to
2626 * externally generated queries).
2628 * @param qstate: query state.
2629 * @param iq: iterator query state.
2630 * @param id: module id.
2631 * @return true if the event needs more processing, false if not. Since this
2632 * is the final state for an event, it always returns false.
2635 processFinished(struct module_qstate* qstate, struct iter_qstate* iq,
2638 log_query_info(VERB_QUERY, "finishing processing for",
2641 /* store negative cache element for parent side glue. */
2642 if(iq->query_for_pside_glue && !iq->pside_glue)
2643 iter_store_parentside_neg(qstate->env, &qstate->qinfo,
2644 iq->deleg_msg?iq->deleg_msg->rep:
2645 (iq->response?iq->response->rep:NULL));
2647 verbose(VERB_ALGO, "No response is set, servfail");
2648 return error_response(qstate, id, LDNS_RCODE_SERVFAIL);
2651 /* Make sure that the RA flag is set (since the presence of
2652 * this module means that recursion is available) */
2653 iq->response->rep->flags |= BIT_RA;
2655 /* Clear the AA flag */
2656 /* FIXME: does this action go here or in some other module? */
2657 iq->response->rep->flags &= ~BIT_AA;
2659 /* make sure QR flag is on */
2660 iq->response->rep->flags |= BIT_QR;
2662 /* we have finished processing this query */
2663 qstate->ext_state[id] = module_finished;
2665 /* TODO: we are using a private TTL, trim the response. */
2666 /* if (mPrivateTTL > 0){IterUtils.setPrivateTTL(resp, mPrivateTTL); } */
2668 /* prepend any items we have accumulated */
2669 if(iq->an_prepend_list || iq->ns_prepend_list) {
2670 if(!iter_prepend(iq, iq->response, qstate->region)) {
2671 log_err("prepend rrsets: out of memory");
2672 return error_response(qstate, id, LDNS_RCODE_SERVFAIL);
2674 /* reset the query name back */
2675 iq->response->qinfo = qstate->qinfo;
2676 /* the security state depends on the combination */
2677 iq->response->rep->security = sec_status_unchecked;
2678 /* store message with the finished prepended items,
2679 * but only if we did recursion. The nonrecursion referral
2680 * from cache does not need to be stored in the msg cache. */
2681 if(qstate->query_flags&BIT_RD) {
2682 iter_dns_store(qstate->env, &qstate->qinfo,
2683 iq->response->rep, 0, qstate->prefetch_leeway,
2684 iq->dp&&iq->dp->has_parent_side_NS,
2688 qstate->return_rcode = LDNS_RCODE_NOERROR;
2689 qstate->return_msg = iq->response;
2694 * Return priming query results to interestes super querystates.
2696 * Sets the delegation point and delegation message (not nonRD queries).
2697 * This is a callback from walk_supers.
2699 * @param qstate: query state that finished.
2700 * @param id: module id.
2701 * @param super: the qstate to inform.
2704 iter_inform_super(struct module_qstate* qstate, int id,
2705 struct module_qstate* super)
2707 if(!qstate->is_priming && super->qinfo.qclass == LDNS_RR_CLASS_ANY)
2708 processClassResponse(qstate, id, super);
2709 else if(super->qinfo.qtype == LDNS_RR_TYPE_DS && ((struct iter_qstate*)
2710 super->minfo[id])->state == DSNS_FIND_STATE)
2711 processDSNSResponse(qstate, id, super);
2712 else if(qstate->return_rcode != LDNS_RCODE_NOERROR)
2713 error_supers(qstate, id, super);
2714 else if(qstate->is_priming)
2715 prime_supers(qstate, id, super);
2716 else processTargetResponse(qstate, id, super);
2720 * Handle iterator state.
2721 * Handle events. This is the real processing loop for events, responsible
2722 * for moving events through the various states. If a processing method
2723 * returns true, then it will be advanced to the next state. If false, then
2724 * processing will stop.
2726 * @param qstate: query state.
2727 * @param ie: iterator shared global environment.
2728 * @param iq: iterator query state.
2729 * @param id: module id.
2732 iter_handle(struct module_qstate* qstate, struct iter_qstate* iq,
2733 struct iter_env* ie, int id)
2737 verbose(VERB_ALGO, "iter_handle processing q with state %s",
2738 iter_state_to_string(iq->state));
2740 case INIT_REQUEST_STATE:
2741 cont = processInitRequest(qstate, iq, ie, id);
2743 case INIT_REQUEST_2_STATE:
2744 cont = processInitRequest2(qstate, iq, id);
2746 case INIT_REQUEST_3_STATE:
2747 cont = processInitRequest3(qstate, iq, id);
2749 case QUERYTARGETS_STATE:
2750 cont = processQueryTargets(qstate, iq, ie, id);
2752 case QUERY_RESP_STATE:
2753 cont = processQueryResponse(qstate, iq, id);
2755 case PRIME_RESP_STATE:
2756 cont = processPrimeResponse(qstate, id);
2758 case COLLECT_CLASS_STATE:
2759 cont = processCollectClass(qstate, id);
2761 case DSNS_FIND_STATE:
2762 cont = processDSNSFind(qstate, iq, id);
2764 case FINISHED_STATE:
2765 cont = processFinished(qstate, iq, id);
2768 log_warn("iterator: invalid state: %d",
2777 * This is the primary entry point for processing request events. Note that
2778 * this method should only be used by external modules.
2779 * @param qstate: query state.
2780 * @param ie: iterator shared global environment.
2781 * @param iq: iterator query state.
2782 * @param id: module id.
2785 process_request(struct module_qstate* qstate, struct iter_qstate* iq,
2786 struct iter_env* ie, int id)
2788 /* external requests start in the INIT state, and finish using the
2789 * FINISHED state. */
2790 iq->state = INIT_REQUEST_STATE;
2791 iq->final_state = FINISHED_STATE;
2792 verbose(VERB_ALGO, "process_request: new external request event");
2793 iter_handle(qstate, iq, ie, id);
2796 /** process authoritative server reply */
2798 process_response(struct module_qstate* qstate, struct iter_qstate* iq,
2799 struct iter_env* ie, int id, struct outbound_entry* outbound,
2800 enum module_ev event)
2802 struct msg_parse* prs;
2803 struct edns_data edns;
2806 verbose(VERB_ALGO, "process_response: new external response event");
2807 iq->response = NULL;
2808 iq->state = QUERY_RESP_STATE;
2809 if(event == module_event_noreply || event == module_event_error) {
2810 if(event == module_event_noreply && iq->sent_count >= 3 &&
2811 qstate->env->cfg->use_caps_bits_for_id &&
2812 !iq->caps_fallback) {
2813 /* start fallback */
2814 iq->caps_fallback = 1;
2815 iq->caps_server = 0;
2816 iq->caps_reply = NULL;
2817 iq->state = QUERYTARGETS_STATE;
2818 iq->num_current_queries--;
2819 /* need fresh attempts for the 0x20 fallback, if
2820 * that was the cause for the failure */
2821 iter_dec_attempts(iq->dp, 3);
2822 verbose(VERB_DETAIL, "Capsforid: timeouts, starting fallback");
2827 if( (event != module_event_reply && event != module_event_capsfail)
2828 || !qstate->reply) {
2829 log_err("Bad event combined with response");
2830 outbound_list_remove(&iq->outlist, outbound);
2831 (void)error_response(qstate, id, LDNS_RCODE_SERVFAIL);
2836 prs = (struct msg_parse*)regional_alloc(qstate->env->scratch,
2837 sizeof(struct msg_parse));
2839 log_err("out of memory on incoming message");
2840 /* like packet got dropped */
2843 memset(prs, 0, sizeof(*prs));
2844 memset(&edns, 0, sizeof(edns));
2845 pkt = qstate->reply->c->buffer;
2846 sldns_buffer_set_position(pkt, 0);
2847 if(parse_packet(pkt, prs, qstate->env->scratch) != LDNS_RCODE_NOERROR) {
2848 verbose(VERB_ALGO, "parse error on reply packet");
2851 /* edns is not examined, but removed from message to help cache */
2852 if(parse_extract_edns(prs, &edns) != LDNS_RCODE_NOERROR)
2854 /* remove CD-bit, we asked for in case we handle validation ourself */
2855 prs->flags &= ~BIT_CD;
2857 /* normalize and sanitize: easy to delete items from linked lists */
2858 if(!scrub_message(pkt, prs, &iq->qchase, iq->dp->name,
2859 qstate->env->scratch, qstate->env, ie))
2862 /* allocate response dns_msg in region */
2863 iq->response = dns_alloc_msg(pkt, prs, qstate->region);
2866 log_query_info(VERB_DETAIL, "response for", &qstate->qinfo);
2867 log_name_addr(VERB_DETAIL, "reply from", iq->dp->name,
2868 &qstate->reply->addr, qstate->reply->addrlen);
2869 if(verbosity >= VERB_ALGO)
2870 log_dns_msg("incoming scrubbed packet:", &iq->response->qinfo,
2873 if(event == module_event_capsfail || iq->caps_fallback) {
2874 if(!iq->caps_fallback) {
2875 /* start fallback */
2876 iq->caps_fallback = 1;
2877 iq->caps_server = 0;
2878 iq->caps_reply = iq->response->rep;
2879 iq->state = QUERYTARGETS_STATE;
2880 iq->num_current_queries--;
2881 verbose(VERB_DETAIL, "Capsforid: starting fallback");
2884 /* check if reply is the same, otherwise, fail */
2885 if(!iq->caps_reply) {
2886 iq->caps_reply = iq->response->rep;
2887 iq->caps_server = -1; /*become zero at ++,
2888 so that we start the full set of trials */
2889 } else if(!reply_equal(iq->response->rep, iq->caps_reply,
2890 qstate->env->scratch)) {
2891 verbose(VERB_DETAIL, "Capsforid fallback: "
2892 "getting different replies, failed");
2893 outbound_list_remove(&iq->outlist, outbound);
2894 (void)error_response(qstate, id,
2895 LDNS_RCODE_SERVFAIL);
2898 /* continue the fallback procedure at next server */
2900 iq->state = QUERYTARGETS_STATE;
2901 iq->num_current_queries--;
2902 verbose(VERB_DETAIL, "Capsforid: reply is equal. "
2903 "go to next fallback");
2907 iq->caps_fallback = 0; /* if we were in fallback, 0x20 is OK now */
2910 outbound_list_remove(&iq->outlist, outbound);
2911 iter_handle(qstate, iq, ie, id);
2915 iter_operate(struct module_qstate* qstate, enum module_ev event, int id,
2916 struct outbound_entry* outbound)
2918 struct iter_env* ie = (struct iter_env*)qstate->env->modinfo[id];
2919 struct iter_qstate* iq = (struct iter_qstate*)qstate->minfo[id];
2920 verbose(VERB_QUERY, "iterator[module %d] operate: extstate:%s event:%s",
2921 id, strextstate(qstate->ext_state[id]), strmodulevent(event));
2922 if(iq) log_query_info(VERB_QUERY, "iterator operate: query",
2924 if(iq && qstate->qinfo.qname != iq->qchase.qname)
2925 log_query_info(VERB_QUERY, "iterator operate: chased to",
2928 /* perform iterator state machine */
2929 if((event == module_event_new || event == module_event_pass) &&
2931 if(!iter_new(qstate, id)) {
2932 (void)error_response(qstate, id, LDNS_RCODE_SERVFAIL);
2935 iq = (struct iter_qstate*)qstate->minfo[id];
2936 process_request(qstate, iq, ie, id);
2939 if(iq && event == module_event_pass) {
2940 iter_handle(qstate, iq, ie, id);
2943 if(iq && outbound) {
2944 process_response(qstate, iq, ie, id, outbound, event);
2947 if(event == module_event_error) {
2948 verbose(VERB_ALGO, "got called with event error, giving up");
2949 (void)error_response(qstate, id, LDNS_RCODE_SERVFAIL);
2953 log_err("bad event for iterator");
2954 (void)error_response(qstate, id, LDNS_RCODE_SERVFAIL);
2958 iter_clear(struct module_qstate* qstate, int id)
2960 struct iter_qstate* iq;
2963 iq = (struct iter_qstate*)qstate->minfo[id];
2965 outbound_list_clear(&iq->outlist);
2966 if(iq->target_count && --iq->target_count[0] == 0)
2967 free(iq->target_count);
2968 iq->num_current_queries = 0;
2970 qstate->minfo[id] = NULL;
2974 iter_get_mem(struct module_env* env, int id)
2976 struct iter_env* ie = (struct iter_env*)env->modinfo[id];
2979 return sizeof(*ie) + sizeof(int)*((size_t)ie->max_dependency_depth+1)
2980 + donotq_get_mem(ie->donotq) + priv_get_mem(ie->priv);
2984 * The iterator function block
2986 static struct module_func_block iter_block = {
2988 &iter_init, &iter_deinit, &iter_operate, &iter_inform_super,
2989 &iter_clear, &iter_get_mem
2992 struct module_func_block*
2993 iter_get_funcblock(void)
2999 iter_state_to_string(enum iter_state state)
3003 case INIT_REQUEST_STATE :
3004 return "INIT REQUEST STATE";
3005 case INIT_REQUEST_2_STATE :
3006 return "INIT REQUEST STATE (stage 2)";
3007 case INIT_REQUEST_3_STATE:
3008 return "INIT REQUEST STATE (stage 3)";
3009 case QUERYTARGETS_STATE :
3010 return "QUERY TARGETS STATE";
3011 case PRIME_RESP_STATE :
3012 return "PRIME RESPONSE STATE";
3013 case COLLECT_CLASS_STATE :
3014 return "COLLECT CLASS STATE";
3015 case DSNS_FIND_STATE :
3016 return "DSNS FIND STATE";
3017 case QUERY_RESP_STATE :
3018 return "QUERY RESPONSE STATE";
3019 case FINISHED_STATE :
3020 return "FINISHED RESPONSE STATE";
3022 return "UNKNOWN ITER STATE";
3027 iter_state_is_responsestate(enum iter_state s)
3030 case INIT_REQUEST_STATE :
3031 case INIT_REQUEST_2_STATE :
3032 case INIT_REQUEST_3_STATE :
3033 case QUERYTARGETS_STATE :
3034 case COLLECT_CLASS_STATE :