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 "util/random.h"
65 #include "sldns/rrdef.h"
66 #include "sldns/wire2str.h"
67 #include "sldns/str2wire.h"
68 #include "sldns/parseutil.h"
69 #include "sldns/sbuffer.h"
72 iter_init(struct module_env* env, int id)
74 struct iter_env* iter_env = (struct iter_env*)calloc(1,
75 sizeof(struct iter_env));
77 log_err("malloc failure");
80 env->modinfo[id] = (void*)iter_env;
81 if(!iter_apply_cfg(iter_env, env->cfg)) {
82 log_err("iterator: could not apply configuration settings.");
89 /** delete caps_whitelist element */
91 caps_free(struct rbnode_type* n, void* ATTR_UNUSED(d))
94 free(((struct name_tree_node*)n)->name);
100 iter_deinit(struct module_env* env, int id)
102 struct iter_env* iter_env;
103 if(!env || !env->modinfo[id])
105 iter_env = (struct iter_env*)env->modinfo[id];
106 free(iter_env->target_fetch_policy);
107 priv_delete(iter_env->priv);
108 donotq_delete(iter_env->donotq);
109 if(iter_env->caps_white) {
110 traverse_postorder(iter_env->caps_white, caps_free, NULL);
111 free(iter_env->caps_white);
114 env->modinfo[id] = NULL;
117 /** new query for iterator */
119 iter_new(struct module_qstate* qstate, int id)
121 struct iter_qstate* iq = (struct iter_qstate*)regional_alloc(
122 qstate->region, sizeof(struct iter_qstate));
123 qstate->minfo[id] = iq;
126 memset(iq, 0, sizeof(*iq));
127 iq->state = INIT_REQUEST_STATE;
128 iq->final_state = FINISHED_STATE;
129 iq->an_prepend_list = NULL;
130 iq->an_prepend_last = NULL;
131 iq->ns_prepend_list = NULL;
132 iq->ns_prepend_last = NULL;
135 iq->num_target_queries = 0;
136 iq->num_current_queries = 0;
137 iq->query_restart_count = 0;
138 iq->referral_count = 0;
140 iq->ratelimit_ok = 0;
141 iq->target_count = NULL;
142 iq->wait_priming_stub = 0;
143 iq->refetch_glue = 0;
144 iq->dnssec_expected = 0;
145 iq->dnssec_lame_query = 0;
146 iq->chase_flags = qstate->query_flags;
147 /* Start with the (current) qname. */
148 iq->qchase = qstate->qinfo;
149 outbound_list_init(&iq->outlist);
150 iq->minimise_count = 0;
151 iq->minimise_timeout_count = 0;
152 if (qstate->env->cfg->qname_minimisation)
153 iq->minimisation_state = INIT_MINIMISE_STATE;
155 iq->minimisation_state = DONOT_MINIMISE_STATE;
157 memset(&iq->qinfo_out, 0, sizeof(struct query_info));
162 * Transition to the next state. This can be used to advance a currently
163 * processing event. It cannot be used to reactivate a forEvent.
165 * @param iq: iterator query state
166 * @param nextstate The state to transition to.
167 * @return true. This is so this can be called as the return value for the
168 * actual process*State() methods. (Transitioning to the next state
169 * implies further processing).
172 next_state(struct iter_qstate* iq, enum iter_state nextstate)
174 /* If transitioning to a "response" state, make sure that there is a
176 if(iter_state_is_responsestate(nextstate)) {
177 if(iq->response == NULL) {
178 log_err("transitioning to response state sans "
182 iq->state = nextstate;
187 * Transition an event to its final state. Final states always either return
188 * a result up the module chain, or reactivate a dependent event. Which
189 * final state to transition to is set in the module state for the event when
190 * it was created, and depends on the original purpose of the event.
192 * The response is stored in the qstate->buf buffer.
194 * @param iq: iterator query state
195 * @return false. This is so this method can be used as the return value for
196 * the processState methods. (Transitioning to the final state
199 final_state(struct iter_qstate* iq)
201 return next_state(iq, iq->final_state);
205 * Callback routine to handle errors in parent query states
206 * @param qstate: query state that failed.
207 * @param id: module id.
208 * @param super: super state.
211 error_supers(struct module_qstate* qstate, int id, struct module_qstate* super)
213 struct iter_qstate* super_iq = (struct iter_qstate*)super->minfo[id];
215 if(qstate->qinfo.qtype == LDNS_RR_TYPE_A ||
216 qstate->qinfo.qtype == LDNS_RR_TYPE_AAAA) {
217 /* mark address as failed. */
218 struct delegpt_ns* dpns = NULL;
219 super_iq->num_target_queries--;
221 dpns = delegpt_find_ns(super_iq->dp,
222 qstate->qinfo.qname, qstate->qinfo.qname_len);
225 verbose(VERB_ALGO, "subq error, but not interested");
226 log_query_info(VERB_ALGO, "superq", &super->qinfo);
228 delegpt_log(VERB_ALGO, super_iq->dp);
232 /* see if the failure did get (parent-lame) info */
233 if(!cache_fill_missing(super->env, super_iq->qchase.qclass,
234 super->region, super_iq->dp))
235 log_err("out of memory adding missing");
237 dpns->resolved = 1; /* mark as failed */
239 if(qstate->qinfo.qtype == LDNS_RR_TYPE_NS) {
240 /* prime failed to get delegation */
243 /* evaluate targets again */
244 super_iq->state = QUERYTARGETS_STATE;
245 /* super becomes runnable, and will process this change */
249 * Return an error to the client
250 * @param qstate: our query state
251 * @param id: module id
252 * @param rcode: error code (DNS errcode).
253 * @return: 0 for use by caller, to make notation easy, like:
254 * return error_response(..).
257 error_response(struct module_qstate* qstate, int id, int rcode)
259 verbose(VERB_QUERY, "return error response %s",
260 sldns_lookup_by_id(sldns_rcodes, rcode)?
261 sldns_lookup_by_id(sldns_rcodes, rcode)->name:"??");
262 qstate->return_rcode = rcode;
263 qstate->return_msg = NULL;
264 qstate->ext_state[id] = module_finished;
269 * Return an error to the client and cache the error code in the
270 * message cache (so per qname, qtype, qclass).
271 * @param qstate: our query state
272 * @param id: module id
273 * @param rcode: error code (DNS errcode).
274 * @return: 0 for use by caller, to make notation easy, like:
275 * return error_response(..).
278 error_response_cache(struct module_qstate* qstate, int id, int rcode)
280 if(!qstate->no_cache_store) {
282 struct reply_info err;
283 if(qstate->prefetch_leeway > NORR_TTL) {
284 verbose(VERB_ALGO, "error response for prefetch in cache");
285 /* attempt to adjust the cache entry prefetch */
286 if(dns_cache_prefetch_adjust(qstate->env, &qstate->qinfo,
287 NORR_TTL, qstate->query_flags))
288 return error_response(qstate, id, rcode);
289 /* if that fails (not in cache), fall through to store err */
291 memset(&err, 0, sizeof(err));
292 err.flags = (uint16_t)(BIT_QR | BIT_RA);
293 FLAGS_SET_RCODE(err.flags, rcode);
296 err.prefetch_ttl = PREFETCH_TTL_CALC(err.ttl);
297 /* do not waste time trying to validate this servfail */
298 err.security = sec_status_indeterminate;
299 verbose(VERB_ALGO, "store error response in message cache");
300 iter_dns_store(qstate->env, &qstate->qinfo, &err, 0, 0, 0, NULL,
301 qstate->query_flags);
303 return error_response(qstate, id, rcode);
306 /** check if prepend item is duplicate item */
308 prepend_is_duplicate(struct ub_packed_rrset_key** sets, size_t to,
309 struct ub_packed_rrset_key* dup)
312 for(i=0; i<to; i++) {
313 if(sets[i]->rk.type == dup->rk.type &&
314 sets[i]->rk.rrset_class == dup->rk.rrset_class &&
315 sets[i]->rk.dname_len == dup->rk.dname_len &&
316 query_dname_compare(sets[i]->rk.dname, dup->rk.dname)
323 /** prepend the prepend list in the answer and authority section of dns_msg */
325 iter_prepend(struct iter_qstate* iq, struct dns_msg* msg,
326 struct regional* region)
328 struct iter_prep_list* p;
329 struct ub_packed_rrset_key** sets;
330 size_t num_an = 0, num_ns = 0;;
331 for(p = iq->an_prepend_list; p; p = p->next)
333 for(p = iq->ns_prepend_list; p; p = p->next)
335 if(num_an + num_ns == 0)
337 verbose(VERB_ALGO, "prepending %d rrsets", (int)num_an + (int)num_ns);
338 if(num_an > RR_COUNT_MAX || num_ns > RR_COUNT_MAX ||
339 msg->rep->rrset_count > RR_COUNT_MAX) return 0; /* overflow */
340 sets = regional_alloc(region, (num_an+num_ns+msg->rep->rrset_count) *
341 sizeof(struct ub_packed_rrset_key*));
346 for(p = iq->an_prepend_list; p; p = p->next) {
347 sets[num_an++] = p->rrset;
349 memcpy(sets+num_an, msg->rep->rrsets, msg->rep->an_numrrsets *
350 sizeof(struct ub_packed_rrset_key*));
353 for(p = iq->ns_prepend_list; p; p = p->next) {
354 if(prepend_is_duplicate(sets+msg->rep->an_numrrsets+num_an,
355 num_ns, p->rrset) || prepend_is_duplicate(
356 msg->rep->rrsets+msg->rep->an_numrrsets,
357 msg->rep->ns_numrrsets, p->rrset))
359 sets[msg->rep->an_numrrsets + num_an + num_ns++] = p->rrset;
361 memcpy(sets + num_an + msg->rep->an_numrrsets + num_ns,
362 msg->rep->rrsets + msg->rep->an_numrrsets,
363 (msg->rep->ns_numrrsets + msg->rep->ar_numrrsets) *
364 sizeof(struct ub_packed_rrset_key*));
366 /* NXDOMAIN rcode can stay if we prepended DNAME/CNAMEs, because
367 * this is what recursors should give. */
368 msg->rep->rrset_count += num_an + num_ns;
369 msg->rep->an_numrrsets += num_an;
370 msg->rep->ns_numrrsets += num_ns;
371 msg->rep->rrsets = sets;
376 * Find rrset in ANSWER prepend list.
377 * to avoid duplicate DNAMEs when a DNAME is traversed twice.
378 * @param iq: iterator query state.
379 * @param rrset: rrset to add.
380 * @return false if not found
383 iter_find_rrset_in_prepend_answer(struct iter_qstate* iq,
384 struct ub_packed_rrset_key* rrset)
386 struct iter_prep_list* p = iq->an_prepend_list;
388 if(ub_rrset_compare(p->rrset, rrset) == 0 &&
389 rrsetdata_equal((struct packed_rrset_data*)p->rrset
390 ->entry.data, (struct packed_rrset_data*)rrset
399 * Add rrset to ANSWER prepend list
400 * @param qstate: query state.
401 * @param iq: iterator query state.
402 * @param rrset: rrset to add.
403 * @return false on failure (malloc).
406 iter_add_prepend_answer(struct module_qstate* qstate, struct iter_qstate* iq,
407 struct ub_packed_rrset_key* rrset)
409 struct iter_prep_list* p = (struct iter_prep_list*)regional_alloc(
410 qstate->region, sizeof(struct iter_prep_list));
416 if(iq->an_prepend_last)
417 iq->an_prepend_last->next = p;
418 else iq->an_prepend_list = p;
419 iq->an_prepend_last = p;
424 * Add rrset to AUTHORITY prepend list
425 * @param qstate: query state.
426 * @param iq: iterator query state.
427 * @param rrset: rrset to add.
428 * @return false on failure (malloc).
431 iter_add_prepend_auth(struct module_qstate* qstate, struct iter_qstate* iq,
432 struct ub_packed_rrset_key* rrset)
434 struct iter_prep_list* p = (struct iter_prep_list*)regional_alloc(
435 qstate->region, sizeof(struct iter_prep_list));
441 if(iq->ns_prepend_last)
442 iq->ns_prepend_last->next = p;
443 else iq->ns_prepend_list = p;
444 iq->ns_prepend_last = p;
449 * Given a CNAME response (defined as a response containing a CNAME or DNAME
450 * that does not answer the request), process the response, modifying the
451 * state as necessary. This follows the CNAME/DNAME chain and returns the
454 * sets the new query name, after following the CNAME/DNAME chain.
455 * @param qstate: query state.
456 * @param iq: iterator query state.
457 * @param msg: the response.
458 * @param mname: returned target new query name.
459 * @param mname_len: length of mname.
460 * @return false on (malloc) error.
463 handle_cname_response(struct module_qstate* qstate, struct iter_qstate* iq,
464 struct dns_msg* msg, uint8_t** mname, size_t* mname_len)
467 /* Start with the (current) qname. */
468 *mname = iq->qchase.qname;
469 *mname_len = iq->qchase.qname_len;
471 /* Iterate over the ANSWER rrsets in order, looking for CNAMEs and
473 for(i=0; i<msg->rep->an_numrrsets; i++) {
474 struct ub_packed_rrset_key* r = msg->rep->rrsets[i];
475 /* If there is a (relevant) DNAME, add it to the list.
476 * We always expect there to be CNAME that was generated
477 * by this DNAME following, so we don't process the DNAME
479 if(ntohs(r->rk.type) == LDNS_RR_TYPE_DNAME &&
480 dname_strict_subdomain_c(*mname, r->rk.dname) &&
481 !iter_find_rrset_in_prepend_answer(iq, r)) {
482 if(!iter_add_prepend_answer(qstate, iq, r))
487 if(ntohs(r->rk.type) == LDNS_RR_TYPE_CNAME &&
488 query_dname_compare(*mname, r->rk.dname) == 0 &&
489 !iter_find_rrset_in_prepend_answer(iq, r)) {
490 /* Add this relevant CNAME rrset to the prepend list.*/
491 if(!iter_add_prepend_answer(qstate, iq, r))
493 get_cname_target(r, mname, mname_len);
496 /* Other rrsets in the section are ignored. */
498 /* add authority rrsets to authority prepend, for wildcarded CNAMEs */
499 for(i=msg->rep->an_numrrsets; i<msg->rep->an_numrrsets +
500 msg->rep->ns_numrrsets; i++) {
501 struct ub_packed_rrset_key* r = msg->rep->rrsets[i];
502 /* only add NSEC/NSEC3, as they may be needed for validation */
503 if(ntohs(r->rk.type) == LDNS_RR_TYPE_NSEC ||
504 ntohs(r->rk.type) == LDNS_RR_TYPE_NSEC3) {
505 if(!iter_add_prepend_auth(qstate, iq, r))
512 /** see if target name is caps-for-id whitelisted */
514 is_caps_whitelisted(struct iter_env* ie, struct iter_qstate* iq)
516 if(!ie->caps_white) return 0; /* no whitelist, or no capsforid */
517 return name_tree_lookup(ie->caps_white, iq->qchase.qname,
518 iq->qchase.qname_len, dname_count_labels(iq->qchase.qname),
519 iq->qchase.qclass) != NULL;
522 /** create target count structure for this query */
524 target_count_create(struct iter_qstate* iq)
526 if(!iq->target_count) {
527 iq->target_count = (int*)calloc(2, sizeof(int));
528 /* if calloc fails we simply do not track this number */
530 iq->target_count[0] = 1;
535 target_count_increase(struct iter_qstate* iq, int num)
537 target_count_create(iq);
539 iq->target_count[1] += num;
543 * Generate a subrequest.
544 * Generate a local request event. Local events are tied to this module, and
545 * have a corresponding (first tier) event that is waiting for this event to
546 * resolve to continue.
548 * @param qname The query name for this request.
549 * @param qnamelen length of qname
550 * @param qtype The query type for this request.
551 * @param qclass The query class for this request.
552 * @param qstate The event that is generating this event.
553 * @param id: module id.
554 * @param iq: The iterator state that is generating this event.
555 * @param initial_state The initial response state (normally this
556 * is QUERY_RESP_STATE, unless it is known that the request won't
557 * need iterative processing
558 * @param finalstate The final state for the response to this request.
559 * @param subq_ret: if newly allocated, the subquerystate, or NULL if it does
560 * not need initialisation.
561 * @param v: if true, validation is done on the subquery.
562 * @return false on error (malloc).
565 generate_sub_request(uint8_t* qname, size_t qnamelen, uint16_t qtype,
566 uint16_t qclass, struct module_qstate* qstate, int id,
567 struct iter_qstate* iq, enum iter_state initial_state,
568 enum iter_state finalstate, struct module_qstate** subq_ret, int v)
570 struct module_qstate* subq = NULL;
571 struct iter_qstate* subiq = NULL;
572 uint16_t qflags = 0; /* OPCODE QUERY, no flags */
573 struct query_info qinf;
574 int prime = (finalstate == PRIME_RESP_STATE)?1:0;
577 qinf.qname_len = qnamelen;
579 qinf.qclass = qclass;
580 qinf.local_alias = NULL;
582 /* RD should be set only when sending the query back through the INIT
584 if(initial_state == INIT_REQUEST_STATE)
586 /* We set the CD flag so we can send this through the "head" of
587 * the resolution chain, which might have a validator. We are
588 * uninterested in validating things not on the direct resolution
595 /* attach subquery, lookup existing or make a new one */
596 fptr_ok(fptr_whitelist_modenv_attach_sub(qstate->env->attach_sub));
597 if(!(*qstate->env->attach_sub)(qstate, &qinf, qflags, prime, valrec,
603 /* initialise the new subquery */
605 subq->ext_state[id] = module_state_initial;
606 subq->minfo[id] = regional_alloc(subq->region,
607 sizeof(struct iter_qstate));
608 if(!subq->minfo[id]) {
609 log_err("init subq: out of memory");
610 fptr_ok(fptr_whitelist_modenv_kill_sub(
611 qstate->env->kill_sub));
612 (*qstate->env->kill_sub)(subq);
615 subiq = (struct iter_qstate*)subq->minfo[id];
616 memset(subiq, 0, sizeof(*subiq));
617 subiq->num_target_queries = 0;
618 target_count_create(iq);
619 subiq->target_count = iq->target_count;
621 iq->target_count[0] ++; /* extra reference */
622 subiq->num_current_queries = 0;
623 subiq->depth = iq->depth+1;
624 outbound_list_init(&subiq->outlist);
625 subiq->state = initial_state;
626 subiq->final_state = finalstate;
627 subiq->qchase = subq->qinfo;
628 subiq->chase_flags = subq->query_flags;
629 subiq->refetch_glue = 0;
630 if(qstate->env->cfg->qname_minimisation)
631 subiq->minimisation_state = INIT_MINIMISE_STATE;
633 subiq->minimisation_state = DONOT_MINIMISE_STATE;
634 memset(&subiq->qinfo_out, 0, sizeof(struct query_info));
640 * Generate and send a root priming request.
641 * @param qstate: the qtstate that triggered the need to prime.
642 * @param iq: iterator query state.
643 * @param id: module id.
644 * @param qclass: the class to prime.
645 * @return 0 on failure
648 prime_root(struct module_qstate* qstate, struct iter_qstate* iq, int id,
652 struct module_qstate* subq;
653 verbose(VERB_DETAIL, "priming . %s NS",
654 sldns_lookup_by_id(sldns_rr_classes, (int)qclass)?
655 sldns_lookup_by_id(sldns_rr_classes, (int)qclass)->name:"??");
656 dp = hints_lookup_root(qstate->env->hints, qclass);
658 verbose(VERB_ALGO, "Cannot prime due to lack of hints");
661 /* Priming requests start at the QUERYTARGETS state, skipping
662 * the normal INIT state logic (which would cause an infloop). */
663 if(!generate_sub_request((uint8_t*)"\000", 1, LDNS_RR_TYPE_NS,
664 qclass, qstate, id, iq, QUERYTARGETS_STATE, PRIME_RESP_STATE,
666 verbose(VERB_ALGO, "could not prime root");
670 struct iter_qstate* subiq =
671 (struct iter_qstate*)subq->minfo[id];
672 /* Set the initial delegation point to the hint.
673 * copy dp, it is now part of the root prime query.
674 * dp was part of in the fixed hints structure. */
675 subiq->dp = delegpt_copy(dp, subq->region);
677 log_err("out of memory priming root, copydp");
678 fptr_ok(fptr_whitelist_modenv_kill_sub(
679 qstate->env->kill_sub));
680 (*qstate->env->kill_sub)(subq);
683 /* there should not be any target queries. */
684 subiq->num_target_queries = 0;
685 subiq->dnssec_expected = iter_indicates_dnssec(
686 qstate->env, subiq->dp, NULL, subq->qinfo.qclass);
689 /* this module stops, our submodule starts, and does the query. */
690 qstate->ext_state[id] = module_wait_subquery;
695 * Generate and process a stub priming request. This method tests for the
696 * need to prime a stub zone, so it is safe to call for every request.
698 * @param qstate: the qtstate that triggered the need to prime.
699 * @param iq: iterator query state.
700 * @param id: module id.
701 * @param qname: request name.
702 * @param qclass: request class.
703 * @return true if a priming subrequest was made, false if not. The will only
704 * issue a priming request if it detects an unprimed stub.
705 * Uses value of 2 to signal during stub-prime in root-prime situation
706 * that a noprime-stub is available and resolution can continue.
709 prime_stub(struct module_qstate* qstate, struct iter_qstate* iq, int id,
710 uint8_t* qname, uint16_t qclass)
712 /* Lookup the stub hint. This will return null if the stub doesn't
713 * need to be re-primed. */
714 struct iter_hints_stub* stub;
715 struct delegpt* stub_dp;
716 struct module_qstate* subq;
719 stub = hints_lookup_stub(qstate->env->hints, qname, qclass, iq->dp);
720 /* The stub (if there is one) does not need priming. */
725 /* is it a noprime stub (always use) */
728 if(iq->dp == NULL) r = 2;
729 /* copy the dp out of the fixed hints structure, so that
730 * it can be changed when servicing this query */
731 iq->dp = delegpt_copy(stub_dp, qstate->region);
733 log_err("out of memory priming stub");
734 (void)error_response(qstate, id, LDNS_RCODE_SERVFAIL);
735 return 1; /* return 1 to make module stop, with error */
737 log_nametypeclass(VERB_DETAIL, "use stub", stub_dp->name,
738 LDNS_RR_TYPE_NS, qclass);
742 /* Otherwise, we need to (re)prime the stub. */
743 log_nametypeclass(VERB_DETAIL, "priming stub", stub_dp->name,
744 LDNS_RR_TYPE_NS, qclass);
746 /* Stub priming events start at the QUERYTARGETS state to avoid the
747 * redundant INIT state processing. */
748 if(!generate_sub_request(stub_dp->name, stub_dp->namelen,
749 LDNS_RR_TYPE_NS, qclass, qstate, id, iq,
750 QUERYTARGETS_STATE, PRIME_RESP_STATE, &subq, 0)) {
751 verbose(VERB_ALGO, "could not prime stub");
752 (void)error_response(qstate, id, LDNS_RCODE_SERVFAIL);
753 return 1; /* return 1 to make module stop, with error */
756 struct iter_qstate* subiq =
757 (struct iter_qstate*)subq->minfo[id];
759 /* Set the initial delegation point to the hint. */
760 /* make copy to avoid use of stub dp by different qs/threads */
761 subiq->dp = delegpt_copy(stub_dp, subq->region);
763 log_err("out of memory priming stub, copydp");
764 fptr_ok(fptr_whitelist_modenv_kill_sub(
765 qstate->env->kill_sub));
766 (*qstate->env->kill_sub)(subq);
767 (void)error_response(qstate, id, LDNS_RCODE_SERVFAIL);
768 return 1; /* return 1 to make module stop, with error */
770 /* there should not be any target queries -- although there
771 * wouldn't be anyway, since stub hints never have
772 * missing targets. */
773 subiq->num_target_queries = 0;
774 subiq->wait_priming_stub = 1;
775 subiq->dnssec_expected = iter_indicates_dnssec(
776 qstate->env, subiq->dp, NULL, subq->qinfo.qclass);
779 /* this module stops, our submodule starts, and does the query. */
780 qstate->ext_state[id] = module_wait_subquery;
785 * Generate A and AAAA checks for glue that is in-zone for the referral
786 * we just got to obtain authoritative information on the adresses.
788 * @param qstate: the qtstate that triggered the need to prime.
789 * @param iq: iterator query state.
790 * @param id: module id.
793 generate_a_aaaa_check(struct module_qstate* qstate, struct iter_qstate* iq,
796 struct iter_env* ie = (struct iter_env*)qstate->env->modinfo[id];
797 struct module_qstate* subq;
799 struct reply_info* rep = iq->response->rep;
800 struct ub_packed_rrset_key* s;
803 if(iq->depth == ie->max_dependency_depth)
805 /* walk through additional, and check if in-zone,
806 * only relevant A, AAAA are left after scrub anyway */
807 for(i=rep->an_numrrsets+rep->ns_numrrsets; i<rep->rrset_count; i++) {
809 /* check *ALL* addresses that are transmitted in additional*/
810 /* is it an address ? */
811 if( !(ntohs(s->rk.type)==LDNS_RR_TYPE_A ||
812 ntohs(s->rk.type)==LDNS_RR_TYPE_AAAA)) {
815 /* is this query the same as the A/AAAA check for it */
816 if(qstate->qinfo.qtype == ntohs(s->rk.type) &&
817 qstate->qinfo.qclass == ntohs(s->rk.rrset_class) &&
818 query_dname_compare(qstate->qinfo.qname,
820 (qstate->query_flags&BIT_RD) &&
821 !(qstate->query_flags&BIT_CD))
824 /* generate subrequest for it */
825 log_nametypeclass(VERB_ALGO, "schedule addr fetch",
826 s->rk.dname, ntohs(s->rk.type),
827 ntohs(s->rk.rrset_class));
828 if(!generate_sub_request(s->rk.dname, s->rk.dname_len,
829 ntohs(s->rk.type), ntohs(s->rk.rrset_class),
831 INIT_REQUEST_STATE, FINISHED_STATE, &subq, 1)) {
832 verbose(VERB_ALGO, "could not generate addr check");
835 /* ignore subq - not need for more init */
840 * Generate a NS check request to obtain authoritative information
843 * @param qstate: the qtstate that triggered the need to prime.
844 * @param iq: iterator query state.
845 * @param id: module id.
848 generate_ns_check(struct module_qstate* qstate, struct iter_qstate* iq, int id)
850 struct iter_env* ie = (struct iter_env*)qstate->env->modinfo[id];
851 struct module_qstate* subq;
854 if(iq->depth == ie->max_dependency_depth)
856 /* is this query the same as the nscheck? */
857 if(qstate->qinfo.qtype == LDNS_RR_TYPE_NS &&
858 query_dname_compare(iq->dp->name, qstate->qinfo.qname)==0 &&
859 (qstate->query_flags&BIT_RD) && !(qstate->query_flags&BIT_CD)){
860 /* spawn off A, AAAA queries for in-zone glue to check */
861 generate_a_aaaa_check(qstate, iq, id);
865 log_nametypeclass(VERB_ALGO, "schedule ns fetch",
866 iq->dp->name, LDNS_RR_TYPE_NS, iq->qchase.qclass);
867 if(!generate_sub_request(iq->dp->name, iq->dp->namelen,
868 LDNS_RR_TYPE_NS, iq->qchase.qclass, qstate, id, iq,
869 INIT_REQUEST_STATE, FINISHED_STATE, &subq, 1)) {
870 verbose(VERB_ALGO, "could not generate ns check");
874 struct iter_qstate* subiq =
875 (struct iter_qstate*)subq->minfo[id];
877 /* make copy to avoid use of stub dp by different qs/threads */
878 /* refetch glue to start higher up the tree */
879 subiq->refetch_glue = 1;
880 subiq->dp = delegpt_copy(iq->dp, subq->region);
882 log_err("out of memory generating ns check, copydp");
883 fptr_ok(fptr_whitelist_modenv_kill_sub(
884 qstate->env->kill_sub));
885 (*qstate->env->kill_sub)(subq);
892 * Generate a DNSKEY prefetch query to get the DNSKEY for the DS record we
893 * just got in a referral (where we have dnssec_expected, thus have trust
894 * anchors above it). Note that right after calling this routine the
895 * iterator detached subqueries (because of following the referral), and thus
896 * the DNSKEY query becomes detached, its return stored in the cache for
897 * later lookup by the validator. This cache lookup by the validator avoids
898 * the roundtrip incurred by the DNSKEY query. The DNSKEY query is now
899 * performed at about the same time the original query is sent to the domain,
900 * thus the two answers are likely to be returned at about the same time,
901 * saving a roundtrip from the validated lookup.
903 * @param qstate: the qtstate that triggered the need to prime.
904 * @param iq: iterator query state.
905 * @param id: module id.
908 generate_dnskey_prefetch(struct module_qstate* qstate,
909 struct iter_qstate* iq, int id)
911 struct module_qstate* subq;
914 /* is this query the same as the prefetch? */
915 if(qstate->qinfo.qtype == LDNS_RR_TYPE_DNSKEY &&
916 query_dname_compare(iq->dp->name, qstate->qinfo.qname)==0 &&
917 (qstate->query_flags&BIT_RD) && !(qstate->query_flags&BIT_CD)){
921 /* if the DNSKEY is in the cache this lookup will stop quickly */
922 log_nametypeclass(VERB_ALGO, "schedule dnskey prefetch",
923 iq->dp->name, LDNS_RR_TYPE_DNSKEY, iq->qchase.qclass);
924 if(!generate_sub_request(iq->dp->name, iq->dp->namelen,
925 LDNS_RR_TYPE_DNSKEY, iq->qchase.qclass, qstate, id, iq,
926 INIT_REQUEST_STATE, FINISHED_STATE, &subq, 0)) {
927 /* we'll be slower, but it'll work */
928 verbose(VERB_ALGO, "could not generate dnskey prefetch");
932 struct iter_qstate* subiq =
933 (struct iter_qstate*)subq->minfo[id];
934 /* this qstate has the right delegation for the dnskey lookup*/
935 /* make copy to avoid use of stub dp by different qs/threads */
936 subiq->dp = delegpt_copy(iq->dp, subq->region);
937 /* if !subiq->dp, it'll start from the cache, no problem */
942 * See if the query needs forwarding.
944 * @param qstate: query state.
945 * @param iq: iterator query state.
946 * @return true if the request is forwarded, false if not.
947 * If returns true but, iq->dp is NULL then a malloc failure occurred.
950 forward_request(struct module_qstate* qstate, struct iter_qstate* iq)
953 uint8_t* delname = iq->qchase.qname;
954 size_t delnamelen = iq->qchase.qname_len;
955 if(iq->refetch_glue) {
956 delname = iq->dp->name;
957 delnamelen = iq->dp->namelen;
959 /* strip one label off of DS query to lookup higher for it */
960 if( (iq->qchase.qtype == LDNS_RR_TYPE_DS || iq->refetch_glue)
961 && !dname_is_root(iq->qchase.qname))
962 dname_remove_label(&delname, &delnamelen);
963 dp = forwards_lookup(qstate->env->fwds, delname, iq->qchase.qclass);
966 /* send recursion desired to forward addr */
967 iq->chase_flags |= BIT_RD;
968 iq->dp = delegpt_copy(dp, qstate->region);
969 /* iq->dp checked by caller */
970 verbose(VERB_ALGO, "forwarding request");
975 * Process the initial part of the request handling. This state roughly
976 * corresponds to resolver algorithms steps 1 (find answer in cache) and 2
977 * (find the best servers to ask).
979 * Note that all requests start here, and query restarts revisit this state.
981 * This state either generates: 1) a response, from cache or error, 2) a
982 * priming event, or 3) forwards the request to the next state (init2,
985 * @param qstate: query state.
986 * @param iq: iterator query state.
987 * @param ie: iterator shared global environment.
988 * @param id: module id.
989 * @return true if the event needs more request processing immediately,
993 processInitRequest(struct module_qstate* qstate, struct iter_qstate* iq,
994 struct iter_env* ie, int id)
998 struct dns_msg* msg = NULL;
1000 log_query_info(VERB_DETAIL, "resolving", &qstate->qinfo);
1003 /* We enforce a maximum number of query restarts. This is primarily a
1004 * cheap way to prevent CNAME loops. */
1005 if(iq->query_restart_count > MAX_RESTART_COUNT) {
1006 verbose(VERB_QUERY, "request has exceeded the maximum number"
1007 " of query restarts with %d", iq->query_restart_count);
1008 return error_response(qstate, id, LDNS_RCODE_SERVFAIL);
1011 /* We enforce a maximum recursion/dependency depth -- in general,
1012 * this is unnecessary for dependency loops (although it will
1013 * catch those), but it provides a sensible limit to the amount
1014 * of work required to answer a given query. */
1015 verbose(VERB_ALGO, "request has dependency depth of %d", iq->depth);
1016 if(iq->depth > ie->max_dependency_depth) {
1017 verbose(VERB_QUERY, "request has exceeded the maximum "
1018 "dependency depth with depth of %d", iq->depth);
1019 return error_response(qstate, id, LDNS_RCODE_SERVFAIL);
1022 /* If the request is qclass=ANY, setup to generate each class */
1023 if(qstate->qinfo.qclass == LDNS_RR_CLASS_ANY) {
1024 iq->qchase.qclass = 0;
1025 return next_state(iq, COLLECT_CLASS_STATE);
1028 /* Resolver Algorithm Step 1 -- Look for the answer in local data. */
1030 /* This either results in a query restart (CNAME cache response), a
1031 * terminating response (ANSWER), or a cache miss (null). */
1033 if(qstate->blacklist) {
1034 /* if cache, or anything else, was blacklisted then
1035 * getting older results from cache is a bad idea, no cache */
1036 verbose(VERB_ALGO, "cache blacklisted, going to the network");
1038 } else if(!qstate->no_cache_lookup) {
1039 msg = dns_cache_lookup(qstate->env, iq->qchase.qname,
1040 iq->qchase.qname_len, iq->qchase.qtype,
1041 iq->qchase.qclass, qstate->query_flags,
1042 qstate->region, qstate->env->scratch);
1043 if(!msg && qstate->env->neg_cache) {
1044 /* lookup in negative cache; may result in
1045 * NOERROR/NODATA or NXDOMAIN answers that need validation */
1046 msg = val_neg_getmsg(qstate->env->neg_cache, &iq->qchase,
1047 qstate->region, qstate->env->rrset_cache,
1048 qstate->env->scratch_buffer,
1049 *qstate->env->now, 1/*add SOA*/, NULL);
1051 /* item taken from cache does not match our query name, thus
1052 * security needs to be re-examined later */
1053 if(msg && query_dname_compare(qstate->qinfo.qname,
1054 iq->qchase.qname) != 0)
1055 msg->rep->security = sec_status_unchecked;
1058 /* handle positive cache response */
1059 enum response_type type = response_type_from_cache(msg,
1061 if(verbosity >= VERB_ALGO) {
1062 log_dns_msg("msg from cache lookup", &msg->qinfo,
1064 verbose(VERB_ALGO, "msg ttl is %d, prefetch ttl %d",
1066 (int)msg->rep->prefetch_ttl);
1069 if(type == RESPONSE_TYPE_CNAME) {
1072 verbose(VERB_ALGO, "returning CNAME response from "
1074 if(!handle_cname_response(qstate, iq, msg,
1076 return error_response(qstate, id,
1077 LDNS_RCODE_SERVFAIL);
1078 iq->qchase.qname = sname;
1079 iq->qchase.qname_len = slen;
1080 /* This *is* a query restart, even if it is a cheap
1083 iq->refetch_glue = 0;
1084 iq->query_restart_count++;
1086 sock_list_insert(&qstate->reply_origin, NULL, 0, qstate->region);
1087 if(qstate->env->cfg->qname_minimisation)
1088 iq->minimisation_state = INIT_MINIMISE_STATE;
1089 return next_state(iq, INIT_REQUEST_STATE);
1092 /* if from cache, NULL, else insert 'cache IP' len=0 */
1093 if(qstate->reply_origin)
1094 sock_list_insert(&qstate->reply_origin, NULL, 0, qstate->region);
1095 /* it is an answer, response, to final state */
1096 verbose(VERB_ALGO, "returning answer from cache.");
1098 return final_state(iq);
1101 /* attempt to forward the request */
1102 if(forward_request(qstate, iq))
1105 log_err("alloc failure for forward dp");
1106 return error_response(qstate, id, LDNS_RCODE_SERVFAIL);
1108 iq->refetch_glue = 0;
1109 iq->minimisation_state = DONOT_MINIMISE_STATE;
1110 /* the request has been forwarded.
1111 * forwarded requests need to be immediately sent to the
1112 * next state, QUERYTARGETS. */
1113 return next_state(iq, QUERYTARGETS_STATE);
1116 /* Resolver Algorithm Step 2 -- find the "best" servers. */
1118 /* first, adjust for DS queries. To avoid the grandparent problem,
1119 * we just look for the closest set of server to the parent of qname.
1120 * When re-fetching glue we also need to ask the parent.
1122 if(iq->refetch_glue) {
1124 log_err("internal or malloc fail: no dp for refetch");
1125 return error_response(qstate, id, LDNS_RCODE_SERVFAIL);
1127 delname = iq->dp->name;
1128 delnamelen = iq->dp->namelen;
1130 delname = iq->qchase.qname;
1131 delnamelen = iq->qchase.qname_len;
1133 if(iq->qchase.qtype == LDNS_RR_TYPE_DS || iq->refetch_glue ||
1134 (iq->qchase.qtype == LDNS_RR_TYPE_NS && qstate->prefetch_leeway)) {
1135 /* remove first label from delname, root goes to hints,
1136 * but only to fetch glue, not for qtype=DS. */
1137 /* also when prefetching an NS record, fetch it again from
1138 * its parent, just as if it expired, so that you do not
1139 * get stuck on an older nameserver that gives old NSrecords */
1140 if(dname_is_root(delname) && (iq->refetch_glue ||
1141 (iq->qchase.qtype == LDNS_RR_TYPE_NS &&
1142 qstate->prefetch_leeway)))
1143 delname = NULL; /* go to root priming */
1144 else dname_remove_label(&delname, &delnamelen);
1146 /* delname is the name to lookup a delegation for. If NULL rootprime */
1149 /* Lookup the delegation in the cache. If null, then the
1150 * cache needs to be primed for the qclass. */
1152 iq->dp = dns_cache_find_delegation(qstate->env, delname,
1153 delnamelen, iq->qchase.qtype, iq->qchase.qclass,
1154 qstate->region, &iq->deleg_msg,
1155 *qstate->env->now+qstate->prefetch_leeway);
1158 /* If the cache has returned nothing, then we have a
1159 * root priming situation. */
1160 if(iq->dp == NULL) {
1161 /* if there is a stub, then no root prime needed */
1162 int r = prime_stub(qstate, iq, id, delname,
1165 break; /* got noprime-stub-zone, continue */
1167 return 0; /* stub prime request made */
1168 if(forwards_lookup_root(qstate->env->fwds,
1169 iq->qchase.qclass)) {
1170 /* forward zone root, no root prime needed */
1171 /* fill in some dp - safety belt */
1172 iq->dp = hints_lookup_root(qstate->env->hints,
1175 log_err("internal error: no hints dp");
1176 return error_response(qstate, id,
1177 LDNS_RCODE_SERVFAIL);
1179 iq->dp = delegpt_copy(iq->dp, qstate->region);
1181 log_err("out of memory in safety belt");
1182 return error_response(qstate, id,
1183 LDNS_RCODE_SERVFAIL);
1185 return next_state(iq, INIT_REQUEST_2_STATE);
1187 /* Note that the result of this will set a new
1188 * DelegationPoint based on the result of priming. */
1189 if(!prime_root(qstate, iq, id, iq->qchase.qclass))
1190 return error_response(qstate, id,
1191 LDNS_RCODE_REFUSED);
1193 /* priming creates and sends a subordinate query, with
1194 * this query as the parent. So further processing for
1195 * this event will stop until reactivated by the
1196 * results of priming. */
1199 if(!iq->ratelimit_ok && qstate->prefetch_leeway)
1200 iq->ratelimit_ok = 1; /* allow prefetches, this keeps
1201 otherwise valid data in the cache */
1202 if(!iq->ratelimit_ok && infra_ratelimit_exceeded(
1203 qstate->env->infra_cache, iq->dp->name,
1204 iq->dp->namelen, *qstate->env->now)) {
1205 /* and increment the rate, so that the rate for time
1206 * now will also exceed the rate, keeping cache fresh */
1207 (void)infra_ratelimit_inc(qstate->env->infra_cache,
1208 iq->dp->name, iq->dp->namelen,
1210 /* see if we are passed through with slip factor */
1211 if(qstate->env->cfg->ratelimit_factor != 0 &&
1212 ub_random_max(qstate->env->rnd,
1213 qstate->env->cfg->ratelimit_factor) == 1) {
1214 iq->ratelimit_ok = 1;
1215 log_nametypeclass(VERB_ALGO, "ratelimit allowed through for "
1216 "delegation point", iq->dp->name,
1217 LDNS_RR_TYPE_NS, LDNS_RR_CLASS_IN);
1219 log_nametypeclass(VERB_ALGO, "ratelimit exceeded with "
1220 "delegation point", iq->dp->name,
1221 LDNS_RR_TYPE_NS, LDNS_RR_CLASS_IN);
1222 return error_response(qstate, id, LDNS_RCODE_SERVFAIL);
1226 /* see if this dp not useless.
1228 * o all NS items are required glue.
1229 * or the query is for NS item that is required glue.
1230 * o no addresses are provided.
1232 * Instead, go up one level, and try to get even further
1233 * If the root was useless, use safety belt information.
1234 * Only check cache returns, because replies for servers
1235 * could be useless but lead to loops (bumping into the
1236 * same server reply) if useless-checked.
1238 if(iter_dp_is_useless(&qstate->qinfo, qstate->query_flags,
1240 if(dname_is_root(iq->dp->name)) {
1241 /* use safety belt */
1242 verbose(VERB_QUERY, "Cache has root NS but "
1243 "no addresses. Fallback to the safety belt.");
1244 iq->dp = hints_lookup_root(qstate->env->hints,
1246 /* note deleg_msg is from previous lookup,
1247 * but RD is on, so it is not used */
1249 log_err("internal error: no hints dp");
1250 return error_response(qstate, id,
1251 LDNS_RCODE_REFUSED);
1253 iq->dp = delegpt_copy(iq->dp, qstate->region);
1255 log_err("out of memory in safety belt");
1256 return error_response(qstate, id,
1257 LDNS_RCODE_SERVFAIL);
1262 "cache delegation was useless:");
1263 delegpt_log(VERB_ALGO, iq->dp);
1265 delname = iq->dp->name;
1266 delnamelen = iq->dp->namelen;
1267 dname_remove_label(&delname, &delnamelen);
1272 verbose(VERB_ALGO, "cache delegation returns delegpt");
1273 delegpt_log(VERB_ALGO, iq->dp);
1275 /* Otherwise, set the current delegation point and move on to the
1277 return next_state(iq, INIT_REQUEST_2_STATE);
1281 * Process the second part of the initial request handling. This state
1282 * basically exists so that queries that generate root priming events have
1283 * the same init processing as ones that do not. Request events that reach
1284 * this state must have a valid currentDelegationPoint set.
1286 * This part is primarly handling stub zone priming. Events that reach this
1287 * state must have a current delegation point.
1289 * @param qstate: query state.
1290 * @param iq: iterator query state.
1291 * @param id: module id.
1292 * @return true if the event needs more request processing immediately,
1296 processInitRequest2(struct module_qstate* qstate, struct iter_qstate* iq,
1301 log_query_info(VERB_QUERY, "resolving (init part 2): ",
1304 if(iq->refetch_glue) {
1306 log_err("internal or malloc fail: no dp for refetch");
1307 return error_response(qstate, id, LDNS_RCODE_SERVFAIL);
1309 delname = iq->dp->name;
1310 delnamelen = iq->dp->namelen;
1312 delname = iq->qchase.qname;
1313 delnamelen = iq->qchase.qname_len;
1315 if(iq->qchase.qtype == LDNS_RR_TYPE_DS || iq->refetch_glue) {
1316 if(!dname_is_root(delname))
1317 dname_remove_label(&delname, &delnamelen);
1318 iq->refetch_glue = 0; /* if CNAME causes restart, no refetch */
1320 /* Check to see if we need to prime a stub zone. */
1321 if(prime_stub(qstate, iq, id, delname, iq->qchase.qclass)) {
1322 /* A priming sub request was made */
1326 /* most events just get forwarded to the next state. */
1327 return next_state(iq, INIT_REQUEST_3_STATE);
1331 * Process the third part of the initial request handling. This state exists
1332 * as a separate state so that queries that generate stub priming events
1333 * will get the tail end of the init process but not repeat the stub priming
1336 * @param qstate: query state.
1337 * @param iq: iterator query state.
1338 * @param id: module id.
1339 * @return true, advancing the event to the QUERYTARGETS_STATE.
1342 processInitRequest3(struct module_qstate* qstate, struct iter_qstate* iq,
1345 log_query_info(VERB_QUERY, "resolving (init part 3): ",
1347 /* if the cache reply dp equals a validation anchor or msg has DS,
1348 * then DNSSEC RRSIGs are expected in the reply */
1349 iq->dnssec_expected = iter_indicates_dnssec(qstate->env, iq->dp,
1350 iq->deleg_msg, iq->qchase.qclass);
1352 /* If the RD flag wasn't set, then we just finish with the
1353 * cached referral as the response. */
1354 if(!(qstate->query_flags & BIT_RD) && iq->deleg_msg) {
1355 iq->response = iq->deleg_msg;
1356 if(verbosity >= VERB_ALGO && iq->response)
1357 log_dns_msg("no RD requested, using delegation msg",
1358 &iq->response->qinfo, iq->response->rep);
1359 if(qstate->reply_origin)
1360 sock_list_insert(&qstate->reply_origin, NULL, 0, qstate->region);
1361 return final_state(iq);
1363 /* After this point, unset the RD flag -- this query is going to
1364 * be sent to an auth. server. */
1365 iq->chase_flags &= ~BIT_RD;
1367 /* if dnssec expected, fetch key for the trust-anchor or cached-DS */
1368 if(iq->dnssec_expected && qstate->env->cfg->prefetch_key &&
1369 !(qstate->query_flags&BIT_CD)) {
1370 generate_dnskey_prefetch(qstate, iq, id);
1371 fptr_ok(fptr_whitelist_modenv_detach_subs(
1372 qstate->env->detach_subs));
1373 (*qstate->env->detach_subs)(qstate);
1376 /* Jump to the next state. */
1377 return next_state(iq, QUERYTARGETS_STATE);
1381 * Given a basic query, generate a parent-side "target" query.
1382 * These are subordinate queries for missing delegation point target addresses,
1383 * for which only the parent of the delegation provides correct IP addresses.
1385 * @param qstate: query state.
1386 * @param iq: iterator query state.
1387 * @param id: module id.
1388 * @param name: target qname.
1389 * @param namelen: target qname length.
1390 * @param qtype: target qtype (either A or AAAA).
1391 * @param qclass: target qclass.
1392 * @return true on success, false on failure.
1395 generate_parentside_target_query(struct module_qstate* qstate,
1396 struct iter_qstate* iq, int id, uint8_t* name, size_t namelen,
1397 uint16_t qtype, uint16_t qclass)
1399 struct module_qstate* subq;
1400 if(!generate_sub_request(name, namelen, qtype, qclass, qstate,
1401 id, iq, INIT_REQUEST_STATE, FINISHED_STATE, &subq, 0))
1404 struct iter_qstate* subiq =
1405 (struct iter_qstate*)subq->minfo[id];
1406 /* blacklist the cache - we want to fetch parent stuff */
1407 sock_list_insert(&subq->blacklist, NULL, 0, subq->region);
1408 subiq->query_for_pside_glue = 1;
1409 if(dname_subdomain_c(name, iq->dp->name)) {
1410 subiq->dp = delegpt_copy(iq->dp, subq->region);
1411 subiq->dnssec_expected = iter_indicates_dnssec(
1412 qstate->env, subiq->dp, NULL,
1413 subq->qinfo.qclass);
1414 subiq->refetch_glue = 1;
1416 subiq->dp = dns_cache_find_delegation(qstate->env,
1417 name, namelen, qtype, qclass, subq->region,
1419 *qstate->env->now+subq->prefetch_leeway);
1420 /* if no dp, then it's from root, refetch unneeded */
1422 subiq->dnssec_expected = iter_indicates_dnssec(
1423 qstate->env, subiq->dp, NULL,
1424 subq->qinfo.qclass);
1425 subiq->refetch_glue = 1;
1429 log_nametypeclass(VERB_QUERY, "new pside target", name, qtype, qclass);
1434 * Given a basic query, generate a "target" query. These are subordinate
1435 * queries for missing delegation point target addresses.
1437 * @param qstate: query state.
1438 * @param iq: iterator query state.
1439 * @param id: module id.
1440 * @param name: target qname.
1441 * @param namelen: target qname length.
1442 * @param qtype: target qtype (either A or AAAA).
1443 * @param qclass: target qclass.
1444 * @return true on success, false on failure.
1447 generate_target_query(struct module_qstate* qstate, struct iter_qstate* iq,
1448 int id, uint8_t* name, size_t namelen, uint16_t qtype, uint16_t qclass)
1450 struct module_qstate* subq;
1451 if(!generate_sub_request(name, namelen, qtype, qclass, qstate,
1452 id, iq, INIT_REQUEST_STATE, FINISHED_STATE, &subq, 0))
1454 log_nametypeclass(VERB_QUERY, "new target", name, qtype, qclass);
1459 * Given an event at a certain state, generate zero or more target queries
1460 * for it's current delegation point.
1462 * @param qstate: query state.
1463 * @param iq: iterator query state.
1464 * @param ie: iterator shared global environment.
1465 * @param id: module id.
1466 * @param maxtargets: The maximum number of targets to query for.
1467 * if it is negative, there is no maximum number of targets.
1468 * @param num: returns the number of queries generated and processed,
1469 * which may be zero if there were no missing targets.
1470 * @return false on error.
1473 query_for_targets(struct module_qstate* qstate, struct iter_qstate* iq,
1474 struct iter_env* ie, int id, int maxtargets, int* num)
1476 int query_count = 0;
1477 struct delegpt_ns* ns;
1481 if(iq->depth == ie->max_dependency_depth)
1483 if(iq->depth > 0 && iq->target_count &&
1484 iq->target_count[1] > MAX_TARGET_COUNT) {
1485 char s[LDNS_MAX_DOMAINLEN+1];
1486 dname_str(qstate->qinfo.qname, s);
1487 verbose(VERB_QUERY, "request %s has exceeded the maximum "
1488 "number of glue fetches %d", s, iq->target_count[1]);
1492 iter_mark_cycle_targets(qstate, iq->dp);
1493 missing = (int)delegpt_count_missing_targets(iq->dp);
1494 log_assert(maxtargets != 0); /* that would not be useful */
1496 /* Generate target requests. Basically, any missing targets
1497 * are queried for here, regardless if it is necessary to do
1498 * so to continue processing. */
1499 if(maxtargets < 0 || maxtargets > missing)
1501 else toget = maxtargets;
1506 /* select 'toget' items from the total of 'missing' items */
1507 log_assert(toget <= missing);
1509 /* loop over missing targets */
1510 for(ns = iq->dp->nslist; ns; ns = ns->next) {
1514 /* randomly select this item with probability toget/missing */
1515 if(!iter_ns_probability(qstate->env->rnd, toget, missing)) {
1516 /* do not select this one, next; select toget number
1517 * of items from a list one less in size */
1522 if(ie->supports_ipv6 && !ns->got6) {
1523 /* Send the AAAA request. */
1524 if(!generate_target_query(qstate, iq, id,
1525 ns->name, ns->namelen,
1526 LDNS_RR_TYPE_AAAA, iq->qchase.qclass)) {
1529 qstate->ext_state[id] = module_wait_subquery;
1534 /* Send the A request. */
1535 if(ie->supports_ipv4 && !ns->got4) {
1536 if(!generate_target_query(qstate, iq, id,
1537 ns->name, ns->namelen,
1538 LDNS_RR_TYPE_A, iq->qchase.qclass)) {
1541 qstate->ext_state[id] = module_wait_subquery;
1547 /* mark this target as in progress. */
1556 qstate->ext_state[id] = module_wait_subquery;
1561 /** see if last resort is possible - does config allow queries to parent */
1563 can_have_last_resort(struct module_env* env, struct delegpt* dp,
1564 struct iter_qstate* iq)
1566 struct delegpt* fwddp;
1567 struct iter_hints_stub* stub;
1568 /* do not process a last resort (the parent side) if a stub
1569 * or forward is configured, because we do not want to go 'above'
1570 * the configured servers */
1571 if(!dname_is_root(dp->name) && (stub = (struct iter_hints_stub*)
1572 name_tree_find(&env->hints->tree, dp->name, dp->namelen,
1573 dp->namelabs, iq->qchase.qclass)) &&
1574 /* has_parent side is turned off for stub_first, where we
1575 * are allowed to go to the parent */
1576 stub->dp->has_parent_side_NS) {
1577 verbose(VERB_QUERY, "configured stub servers failed -- returning SERVFAIL");
1580 if((fwddp = forwards_find(env->fwds, dp->name, iq->qchase.qclass)) &&
1581 /* has_parent_side is turned off for forward_first, where
1582 * we are allowed to go to the parent */
1583 fwddp->has_parent_side_NS) {
1584 verbose(VERB_QUERY, "configured forward servers failed -- returning SERVFAIL");
1591 * Called by processQueryTargets when it would like extra targets to query
1592 * but it seems to be out of options. At last resort some less appealing
1593 * options are explored. If there are no more options, the result is SERVFAIL
1595 * @param qstate: query state.
1596 * @param iq: iterator query state.
1597 * @param ie: iterator shared global environment.
1598 * @param id: module id.
1599 * @return true if the event requires more request processing immediately,
1603 processLastResort(struct module_qstate* qstate, struct iter_qstate* iq,
1604 struct iter_env* ie, int id)
1606 struct delegpt_ns* ns;
1607 int query_count = 0;
1608 verbose(VERB_ALGO, "No more query targets, attempting last resort");
1611 if(!can_have_last_resort(qstate->env, iq->dp, iq)) {
1612 /* fail -- no more targets, no more hope of targets, no hope
1614 return error_response_cache(qstate, id, LDNS_RCODE_SERVFAIL);
1616 if(!iq->dp->has_parent_side_NS && dname_is_root(iq->dp->name)) {
1617 struct delegpt* p = hints_lookup_root(qstate->env->hints,
1620 struct delegpt_ns* ns;
1621 struct delegpt_addr* a;
1622 iq->chase_flags &= ~BIT_RD; /* go to authorities */
1623 for(ns = p->nslist; ns; ns=ns->next) {
1624 (void)delegpt_add_ns(iq->dp, qstate->region,
1625 ns->name, ns->lame);
1627 for(a = p->target_list; a; a=a->next_target) {
1628 (void)delegpt_add_addr(iq->dp, qstate->region,
1629 &a->addr, a->addrlen, a->bogus,
1633 iq->dp->has_parent_side_NS = 1;
1634 } else if(!iq->dp->has_parent_side_NS) {
1635 if(!iter_lookup_parent_NS_from_cache(qstate->env, iq->dp,
1636 qstate->region, &qstate->qinfo)
1637 || !iq->dp->has_parent_side_NS) {
1638 /* if: malloc failure in lookup go up to try */
1639 /* if: no parent NS in cache - go up one level */
1640 verbose(VERB_ALGO, "try to grab parent NS");
1641 iq->store_parent_NS = iq->dp;
1642 iq->chase_flags &= ~BIT_RD; /* go to authorities */
1643 iq->deleg_msg = NULL;
1644 iq->refetch_glue = 1;
1645 iq->query_restart_count++;
1647 if(qstate->env->cfg->qname_minimisation)
1648 iq->minimisation_state = INIT_MINIMISE_STATE;
1649 return next_state(iq, INIT_REQUEST_STATE);
1652 /* see if that makes new names available */
1653 if(!cache_fill_missing(qstate->env, iq->qchase.qclass,
1654 qstate->region, iq->dp))
1655 log_err("out of memory in cache_fill_missing");
1656 if(iq->dp->usable_list) {
1657 verbose(VERB_ALGO, "try parent-side-name, w. glue from cache");
1658 return next_state(iq, QUERYTARGETS_STATE);
1660 /* try to fill out parent glue from cache */
1661 if(iter_lookup_parent_glue_from_cache(qstate->env, iq->dp,
1662 qstate->region, &qstate->qinfo)) {
1663 /* got parent stuff from cache, see if we can continue */
1664 verbose(VERB_ALGO, "try parent-side glue from cache");
1665 return next_state(iq, QUERYTARGETS_STATE);
1667 /* query for an extra name added by the parent-NS record */
1668 if(delegpt_count_missing_targets(iq->dp) > 0) {
1670 verbose(VERB_ALGO, "try parent-side target name");
1671 if(!query_for_targets(qstate, iq, ie, id, 1, &qs)) {
1672 return error_response(qstate, id, LDNS_RCODE_SERVFAIL);
1674 iq->num_target_queries += qs;
1675 target_count_increase(iq, qs);
1677 qstate->ext_state[id] = module_wait_subquery;
1678 return 0; /* and wait for them */
1681 if(iq->depth == ie->max_dependency_depth) {
1682 verbose(VERB_QUERY, "maxdepth and need more nameservers, fail");
1683 return error_response_cache(qstate, id, LDNS_RCODE_SERVFAIL);
1685 if(iq->depth > 0 && iq->target_count &&
1686 iq->target_count[1] > MAX_TARGET_COUNT) {
1687 char s[LDNS_MAX_DOMAINLEN+1];
1688 dname_str(qstate->qinfo.qname, s);
1689 verbose(VERB_QUERY, "request %s has exceeded the maximum "
1690 "number of glue fetches %d", s, iq->target_count[1]);
1691 return error_response_cache(qstate, id, LDNS_RCODE_SERVFAIL);
1693 /* mark cycle targets for parent-side lookups */
1694 iter_mark_pside_cycle_targets(qstate, iq->dp);
1695 /* see if we can issue queries to get nameserver addresses */
1696 /* this lookup is not randomized, but sequential. */
1697 for(ns = iq->dp->nslist; ns; ns = ns->next) {
1698 /* query for parent-side A and AAAA for nameservers */
1699 if(ie->supports_ipv6 && !ns->done_pside6) {
1700 /* Send the AAAA request. */
1701 if(!generate_parentside_target_query(qstate, iq, id,
1702 ns->name, ns->namelen,
1703 LDNS_RR_TYPE_AAAA, iq->qchase.qclass))
1704 return error_response(qstate, id,
1705 LDNS_RCODE_SERVFAIL);
1706 ns->done_pside6 = 1;
1709 if(ie->supports_ipv4 && !ns->done_pside4) {
1710 /* Send the A request. */
1711 if(!generate_parentside_target_query(qstate, iq, id,
1712 ns->name, ns->namelen,
1713 LDNS_RR_TYPE_A, iq->qchase.qclass))
1714 return error_response(qstate, id,
1715 LDNS_RCODE_SERVFAIL);
1716 ns->done_pside4 = 1;
1719 if(query_count != 0) { /* suspend to await results */
1720 verbose(VERB_ALGO, "try parent-side glue lookup");
1721 iq->num_target_queries += query_count;
1722 target_count_increase(iq, query_count);
1723 qstate->ext_state[id] = module_wait_subquery;
1728 /* if this was a parent-side glue query itself, then store that
1729 * failure in cache. */
1730 if(!qstate->no_cache_store && iq->query_for_pside_glue
1732 iter_store_parentside_neg(qstate->env, &qstate->qinfo,
1733 iq->deleg_msg?iq->deleg_msg->rep:
1734 (iq->response?iq->response->rep:NULL));
1736 verbose(VERB_QUERY, "out of query targets -- returning SERVFAIL");
1737 /* fail -- no more targets, no more hope of targets, no hope
1739 return error_response_cache(qstate, id, LDNS_RCODE_SERVFAIL);
1743 * Try to find the NS record set that will resolve a qtype DS query. Due
1744 * to grandparent/grandchild reasons we did not get a proper lookup right
1745 * away. We need to create type NS queries until we get the right parent
1746 * for this lookup. We remove labels from the query to find the right point.
1747 * If we end up at the old dp name, then there is no solution.
1749 * @param qstate: query state.
1750 * @param iq: iterator query state.
1751 * @param id: module id.
1752 * @return true if the event requires more immediate processing, false if
1753 * not. This is generally only true when forwarding the request to
1754 * the final state (i.e., on answer).
1757 processDSNSFind(struct module_qstate* qstate, struct iter_qstate* iq, int id)
1759 struct module_qstate* subq = NULL;
1760 verbose(VERB_ALGO, "processDSNSFind");
1762 if(!iq->dsns_point) {
1764 iq->dsns_point = iq->qchase.qname;
1765 iq->dsns_point_len = iq->qchase.qname_len;
1767 /* robustcheck for internal error: we are not underneath the dp */
1768 if(!dname_subdomain_c(iq->dsns_point, iq->dp->name)) {
1769 return error_response_cache(qstate, id, LDNS_RCODE_SERVFAIL);
1772 /* go up one (more) step, until we hit the dp, if so, end */
1773 dname_remove_label(&iq->dsns_point, &iq->dsns_point_len);
1774 if(query_dname_compare(iq->dsns_point, iq->dp->name) == 0) {
1775 /* there was no inbetween nameserver, use the old delegation
1776 * point again. And this time, because dsns_point is nonNULL
1777 * we are going to accept the (bad) result */
1778 iq->state = QUERYTARGETS_STATE;
1781 iq->state = DSNS_FIND_STATE;
1783 /* spawn NS lookup (validation not needed, this is for DS lookup) */
1784 log_nametypeclass(VERB_ALGO, "fetch nameservers",
1785 iq->dsns_point, LDNS_RR_TYPE_NS, iq->qchase.qclass);
1786 if(!generate_sub_request(iq->dsns_point, iq->dsns_point_len,
1787 LDNS_RR_TYPE_NS, iq->qchase.qclass, qstate, id, iq,
1788 INIT_REQUEST_STATE, FINISHED_STATE, &subq, 0)) {
1789 return error_response_cache(qstate, id, LDNS_RCODE_SERVFAIL);
1796 * This is the request event state where the request will be sent to one of
1797 * its current query targets. This state also handles issuing target lookup
1798 * queries for missing target IP addresses. Queries typically iterate on
1799 * this state, both when they are just trying different targets for a given
1800 * delegation point, and when they change delegation points. This state
1801 * roughly corresponds to RFC 1034 algorithm steps 3 and 4.
1803 * @param qstate: query state.
1804 * @param iq: iterator query state.
1805 * @param ie: iterator shared global environment.
1806 * @param id: module id.
1807 * @return true if the event requires more request processing immediately,
1808 * false if not. This state only returns true when it is generating
1809 * a SERVFAIL response because the query has hit a dead end.
1812 processQueryTargets(struct module_qstate* qstate, struct iter_qstate* iq,
1813 struct iter_env* ie, int id)
1816 struct delegpt_addr* target;
1817 struct outbound_entry* outq;
1819 /* NOTE: a request will encounter this state for each target it
1820 * needs to send a query to. That is, at least one per referral,
1821 * more if some targets timeout or return throwaway answers. */
1823 log_query_info(VERB_QUERY, "processQueryTargets:", &qstate->qinfo);
1824 verbose(VERB_ALGO, "processQueryTargets: targetqueries %d, "
1825 "currentqueries %d sentcount %d", iq->num_target_queries,
1826 iq->num_current_queries, iq->sent_count);
1828 /* Make sure that we haven't run away */
1829 /* FIXME: is this check even necessary? */
1830 if(iq->referral_count > MAX_REFERRAL_COUNT) {
1831 verbose(VERB_QUERY, "request has exceeded the maximum "
1832 "number of referrrals with %d", iq->referral_count);
1833 return error_response(qstate, id, LDNS_RCODE_SERVFAIL);
1835 if(iq->sent_count > MAX_SENT_COUNT) {
1836 verbose(VERB_QUERY, "request has exceeded the maximum "
1837 "number of sends with %d", iq->sent_count);
1838 return error_response(qstate, id, LDNS_RCODE_SERVFAIL);
1841 /* Make sure we have a delegation point, otherwise priming failed
1842 * or another failure occurred */
1844 verbose(VERB_QUERY, "Failed to get a delegation, giving up");
1845 return error_response(qstate, id, LDNS_RCODE_SERVFAIL);
1847 if(!ie->supports_ipv6)
1848 delegpt_no_ipv6(iq->dp);
1849 if(!ie->supports_ipv4)
1850 delegpt_no_ipv4(iq->dp);
1851 delegpt_log(VERB_ALGO, iq->dp);
1853 if(iq->num_current_queries>0) {
1854 /* already busy answering a query, this restart is because
1855 * more delegpt addrs became available, wait for existing
1857 verbose(VERB_ALGO, "woke up, but wait for outstanding query");
1858 qstate->ext_state[id] = module_wait_reply;
1863 /* < not <=, because although the array is large enough for <=, the
1864 * generated query will immediately be discarded due to depth and
1865 * that servfail is cached, which is not good as opportunism goes. */
1866 if(iq->depth < ie->max_dependency_depth
1867 && iq->sent_count < TARGET_FETCH_STOP) {
1868 tf_policy = ie->target_fetch_policy[iq->depth];
1871 /* if in 0x20 fallback get as many targets as possible */
1872 if(iq->caps_fallback) {
1874 size_t naddr, nres, navail;
1875 if(!query_for_targets(qstate, iq, ie, id, -1, &extra)) {
1876 return error_response(qstate, id, LDNS_RCODE_SERVFAIL);
1878 iq->num_target_queries += extra;
1879 target_count_increase(iq, extra);
1880 if(iq->num_target_queries > 0) {
1881 /* wait to get all targets, we want to try em */
1882 verbose(VERB_ALGO, "wait for all targets for fallback");
1883 qstate->ext_state[id] = module_wait_reply;
1886 /* did we do enough fallback queries already? */
1887 delegpt_count_addr(iq->dp, &naddr, &nres, &navail);
1888 /* the current caps_server is the number of fallbacks sent.
1889 * the original query is one that matched too, so we have
1890 * caps_server+1 number of matching queries now */
1891 if(iq->caps_server+1 >= naddr*3 ||
1892 iq->caps_server*2+2 >= MAX_SENT_COUNT) {
1893 /* *2 on sentcount check because ipv6 may fail */
1894 /* we're done, process the response */
1895 verbose(VERB_ALGO, "0x20 fallback had %d responses "
1896 "match for %d wanted, done.",
1897 (int)iq->caps_server+1, (int)naddr*3);
1898 iq->response = iq->caps_response;
1899 iq->caps_fallback = 0;
1900 iter_dec_attempts(iq->dp, 3); /* space for fallback */
1901 iq->num_current_queries++; /* RespState decrements it*/
1902 iq->referral_count++; /* make sure we don't loop */
1904 iq->state = QUERY_RESP_STATE;
1907 verbose(VERB_ALGO, "0x20 fallback number %d",
1908 (int)iq->caps_server);
1910 /* if there is a policy to fetch missing targets
1911 * opportunistically, do it. we rely on the fact that once a
1912 * query (or queries) for a missing name have been issued,
1913 * they will not show up again. */
1914 } else if(tf_policy != 0) {
1916 verbose(VERB_ALGO, "attempt to get extra %d targets",
1918 (void)query_for_targets(qstate, iq, ie, id, tf_policy, &extra);
1919 /* errors ignored, these targets are not strictly necessary for
1920 * this result, we do not have to reply with SERVFAIL */
1921 iq->num_target_queries += extra;
1922 target_count_increase(iq, extra);
1925 /* Add the current set of unused targets to our queue. */
1926 delegpt_add_unused_targets(iq->dp);
1928 /* Select the next usable target, filtering out unsuitable targets. */
1929 target = iter_server_selection(ie, qstate->env, iq->dp,
1930 iq->dp->name, iq->dp->namelen, iq->qchase.qtype,
1931 &iq->dnssec_lame_query, &iq->chase_to_rd,
1932 iq->num_target_queries, qstate->blacklist);
1934 /* If no usable target was selected... */
1936 /* Here we distinguish between three states: generate a new
1937 * target query, just wait, or quit (with a SERVFAIL).
1938 * We have the following information: number of active
1939 * target queries, number of active current queries,
1940 * the presence of missing targets at this delegation
1941 * point, and the given query target policy. */
1943 /* Check for the wait condition. If this is true, then
1944 * an action must be taken. */
1945 if(iq->num_target_queries==0 && iq->num_current_queries==0) {
1946 /* If there is nothing to wait for, then we need
1947 * to distinguish between generating (a) new target
1948 * query, or failing. */
1949 if(delegpt_count_missing_targets(iq->dp) > 0) {
1951 verbose(VERB_ALGO, "querying for next "
1953 if(!query_for_targets(qstate, iq, ie, id,
1955 return error_response(qstate, id,
1956 LDNS_RCODE_SERVFAIL);
1959 delegpt_count_missing_targets(iq->dp) == 0){
1960 /* it looked like there were missing
1961 * targets, but they did not turn up.
1962 * Try the bad choices again (if any),
1963 * when we get back here missing==0,
1964 * so this is not a loop. */
1967 iq->num_target_queries += qs;
1968 target_count_increase(iq, qs);
1970 /* Since a target query might have been made, we
1971 * need to check again. */
1972 if(iq->num_target_queries == 0) {
1973 /* if in capsforid fallback, instead of last
1974 * resort, we agree with the current reply
1975 * we have (if any) (our count of addrs bad)*/
1976 if(iq->caps_fallback && iq->caps_reply) {
1977 /* we're done, process the response */
1978 verbose(VERB_ALGO, "0x20 fallback had %d responses, "
1979 "but no more servers except "
1980 "last resort, done.",
1981 (int)iq->caps_server+1);
1982 iq->response = iq->caps_response;
1983 iq->caps_fallback = 0;
1984 iter_dec_attempts(iq->dp, 3); /* space for fallback */
1985 iq->num_current_queries++; /* RespState decrements it*/
1986 iq->referral_count++; /* make sure we don't loop */
1988 iq->state = QUERY_RESP_STATE;
1991 return processLastResort(qstate, iq, ie, id);
1995 /* otherwise, we have no current targets, so submerge
1996 * until one of the target or direct queries return. */
1997 if(iq->num_target_queries>0 && iq->num_current_queries>0) {
1998 verbose(VERB_ALGO, "no current targets -- waiting "
1999 "for %d targets to resolve or %d outstanding"
2000 " queries to respond", iq->num_target_queries,
2001 iq->num_current_queries);
2002 qstate->ext_state[id] = module_wait_reply;
2003 } else if(iq->num_target_queries>0) {
2004 verbose(VERB_ALGO, "no current targets -- waiting "
2005 "for %d targets to resolve.",
2006 iq->num_target_queries);
2007 qstate->ext_state[id] = module_wait_subquery;
2009 verbose(VERB_ALGO, "no current targets -- waiting "
2010 "for %d outstanding queries to respond.",
2011 iq->num_current_queries);
2012 qstate->ext_state[id] = module_wait_reply;
2017 /* if not forwarding, check ratelimits per delegationpoint name */
2018 if(!(iq->chase_flags & BIT_RD) && !iq->ratelimit_ok) {
2019 if(!infra_ratelimit_inc(qstate->env->infra_cache, iq->dp->name,
2020 iq->dp->namelen, *qstate->env->now)) {
2021 verbose(VERB_ALGO, "query exceeded ratelimits");
2022 return error_response(qstate, id, LDNS_RCODE_SERVFAIL);
2026 if(iq->minimisation_state == INIT_MINIMISE_STATE) {
2027 /* (Re)set qinfo_out to (new) delegation point, except when
2028 * qinfo_out is already a subdomain of dp. This happens when
2029 * increasing by more than one label at once (QNAMEs with more
2030 * than MAX_MINIMISE_COUNT labels). */
2031 if(!(iq->qinfo_out.qname_len
2032 && dname_subdomain_c(iq->qchase.qname,
2033 iq->qinfo_out.qname)
2034 && dname_subdomain_c(iq->qinfo_out.qname,
2036 iq->qinfo_out.qname = iq->dp->name;
2037 iq->qinfo_out.qname_len = iq->dp->namelen;
2038 iq->qinfo_out.qtype = LDNS_RR_TYPE_A;
2039 iq->qinfo_out.qclass = iq->qchase.qclass;
2040 iq->qinfo_out.local_alias = NULL;
2041 iq->minimise_count = 0;
2044 iq->minimisation_state = MINIMISE_STATE;
2046 if(iq->minimisation_state == MINIMISE_STATE) {
2047 int qchaselabs = dname_count_labels(iq->qchase.qname);
2048 int labdiff = qchaselabs -
2049 dname_count_labels(iq->qinfo_out.qname);
2051 iq->qinfo_out.qname = iq->qchase.qname;
2052 iq->qinfo_out.qname_len = iq->qchase.qname_len;
2053 iq->minimise_count++;
2054 iq->minimise_timeout_count = 0;
2056 iter_dec_attempts(iq->dp, 1);
2058 /* Limit number of iterations for QNAMEs with more
2059 * than MAX_MINIMISE_COUNT labels. Send first MINIMISE_ONE_LAB
2060 * labels of QNAME always individually.
2062 if(qchaselabs > MAX_MINIMISE_COUNT && labdiff > 1 &&
2063 iq->minimise_count > MINIMISE_ONE_LAB) {
2064 if(iq->minimise_count < MAX_MINIMISE_COUNT) {
2065 int multilabs = qchaselabs - 1 -
2067 int extralabs = multilabs /
2068 MINIMISE_MULTIPLE_LABS;
2070 if (MAX_MINIMISE_COUNT - iq->minimise_count >=
2071 multilabs % MINIMISE_MULTIPLE_LABS)
2072 /* Default behaviour is to add 1 label
2073 * every iteration. Therefore, decrement
2074 * the extralabs by 1 */
2076 if (extralabs < labdiff)
2077 labdiff -= extralabs;
2081 /* Last minimised iteration, send all labels with
2088 verbose(VERB_QUERY, "removing %d labels", labdiff-1);
2089 dname_remove_labels(&iq->qinfo_out.qname,
2090 &iq->qinfo_out.qname_len,
2093 if(labdiff < 1 || (labdiff < 2
2094 && (iq->qchase.qtype == LDNS_RR_TYPE_DS
2095 || iq->qchase.qtype == LDNS_RR_TYPE_A)))
2096 /* Stop minimising this query, resolve "as usual" */
2097 iq->minimisation_state = DONOT_MINIMISE_STATE;
2098 else if(!qstate->no_cache_lookup) {
2099 struct dns_msg* msg = dns_cache_lookup(qstate->env,
2100 iq->qinfo_out.qname, iq->qinfo_out.qname_len,
2101 iq->qinfo_out.qtype, iq->qinfo_out.qclass,
2102 qstate->query_flags, qstate->region,
2103 qstate->env->scratch);
2104 if(msg && msg->rep->an_numrrsets == 0
2105 && FLAGS_GET_RCODE(msg->rep->flags) ==
2107 /* no need to send query if it is already
2108 * cached as NOERROR/NODATA */
2112 if(iq->minimisation_state == SKIP_MINIMISE_STATE) {
2113 iq->minimise_timeout_count++;
2114 if(iq->minimise_timeout_count < MAX_MINIMISE_TIMEOUT_COUNT)
2115 /* Do not increment qname, continue incrementing next
2117 iq->minimisation_state = MINIMISE_STATE;
2118 else if(!qstate->env->cfg->qname_minimisation_strict)
2119 /* Too many time-outs detected for this QNAME and QTYPE.
2120 * We give up, disable QNAME minimisation. */
2121 iq->minimisation_state = DONOT_MINIMISE_STATE;
2123 if(iq->minimisation_state == DONOT_MINIMISE_STATE)
2124 iq->qinfo_out = iq->qchase;
2126 /* We have a valid target. */
2127 if(verbosity >= VERB_QUERY) {
2128 log_query_info(VERB_QUERY, "sending query:", &iq->qinfo_out);
2129 log_name_addr(VERB_QUERY, "sending to target:", iq->dp->name,
2130 &target->addr, target->addrlen);
2131 verbose(VERB_ALGO, "dnssec status: %s%s",
2132 iq->dnssec_expected?"expected": "not expected",
2133 iq->dnssec_lame_query?" but lame_query anyway": "");
2135 fptr_ok(fptr_whitelist_modenv_send_query(qstate->env->send_query));
2136 outq = (*qstate->env->send_query)(&iq->qinfo_out,
2137 iq->chase_flags | (iq->chase_to_rd?BIT_RD:0),
2138 /* unset CD if to forwarder(RD set) and not dnssec retry
2139 * (blacklist nonempty) and no trust-anchors are configured
2140 * above the qname or on the first attempt when dnssec is on */
2141 EDNS_DO| ((iq->chase_to_rd||(iq->chase_flags&BIT_RD)!=0)&&
2142 !qstate->blacklist&&(!iter_indicates_dnssec_fwd(qstate->env,
2143 &iq->qinfo_out)||target->attempts==1)?0:BIT_CD),
2144 iq->dnssec_expected, iq->caps_fallback || is_caps_whitelisted(
2145 ie, iq), &target->addr, target->addrlen,
2146 iq->dp->name, iq->dp->namelen,
2147 (iq->dp->ssl_upstream || qstate->env->cfg->ssl_upstream), qstate);
2149 log_addr(VERB_DETAIL, "error sending query to auth server",
2150 &target->addr, target->addrlen);
2151 if(!(iq->chase_flags & BIT_RD) && !iq->ratelimit_ok)
2152 infra_ratelimit_dec(qstate->env->infra_cache, iq->dp->name,
2153 iq->dp->namelen, *qstate->env->now);
2154 return next_state(iq, QUERYTARGETS_STATE);
2156 outbound_list_insert(&iq->outlist, outq);
2157 iq->num_current_queries++;
2159 qstate->ext_state[id] = module_wait_reply;
2164 /** find NS rrset in given list */
2165 static struct ub_packed_rrset_key*
2166 find_NS(struct reply_info* rep, size_t from, size_t to)
2169 for(i=from; i<to; i++) {
2170 if(ntohs(rep->rrsets[i]->rk.type) == LDNS_RR_TYPE_NS)
2171 return rep->rrsets[i];
2178 * Process the query response. All queries end up at this state first. This
2179 * process generally consists of analyzing the response and routing the
2180 * event to the next state (either bouncing it back to a request state, or
2181 * terminating the processing for this event).
2183 * @param qstate: query state.
2184 * @param iq: iterator query state.
2185 * @param id: module id.
2186 * @return true if the event requires more immediate processing, false if
2187 * not. This is generally only true when forwarding the request to
2188 * the final state (i.e., on answer).
2191 processQueryResponse(struct module_qstate* qstate, struct iter_qstate* iq,
2195 enum response_type type;
2196 iq->num_current_queries--;
2198 if(!inplace_cb_query_response_call(qstate->env, qstate, iq->response))
2199 log_err("unable to call query_response callback");
2201 if(iq->response == NULL) {
2202 /* Don't increment qname when QNAME minimisation is enabled */
2203 if(qstate->env->cfg->qname_minimisation)
2204 iq->minimisation_state = SKIP_MINIMISE_STATE;
2205 iq->chase_to_rd = 0;
2206 iq->dnssec_lame_query = 0;
2207 verbose(VERB_ALGO, "query response was timeout");
2208 return next_state(iq, QUERYTARGETS_STATE);
2210 type = response_type_from_server(
2211 (int)((iq->chase_flags&BIT_RD) || iq->chase_to_rd),
2212 iq->response, &iq->qchase, iq->dp);
2213 iq->chase_to_rd = 0;
2214 if(type == RESPONSE_TYPE_REFERRAL && (iq->chase_flags&BIT_RD)) {
2215 /* When forwarding (RD bit is set), we handle referrals
2216 * differently. No queries should be sent elsewhere */
2217 type = RESPONSE_TYPE_ANSWER;
2219 if(!qstate->env->cfg->disable_dnssec_lame_check && iq->dnssec_expected
2220 && !iq->dnssec_lame_query &&
2221 !(iq->chase_flags&BIT_RD)
2222 && iq->sent_count < DNSSEC_LAME_DETECT_COUNT
2223 && type != RESPONSE_TYPE_LAME
2224 && type != RESPONSE_TYPE_REC_LAME
2225 && type != RESPONSE_TYPE_THROWAWAY
2226 && type != RESPONSE_TYPE_UNTYPED) {
2227 /* a possible answer, see if it is missing DNSSEC */
2228 /* but not when forwarding, so we dont mark fwder lame */
2229 if(!iter_msg_has_dnssec(iq->response)) {
2230 /* Mark this address as dnsseclame in this dp,
2231 * because that will make serverselection disprefer
2232 * it, but also, once it is the only final option,
2233 * use dnssec-lame-bypass if it needs to query there.*/
2235 struct delegpt_addr* a = delegpt_find_addr(
2236 iq->dp, &qstate->reply->addr,
2237 qstate->reply->addrlen);
2238 if(a) a->dnsseclame = 1;
2240 /* test the answer is from the zone we expected,
2241 * otherwise, (due to parent,child on same server), we
2242 * might mark the server,zone lame inappropriately */
2243 if(!iter_msg_from_zone(iq->response, iq->dp, type,
2245 qstate->reply = NULL;
2246 type = RESPONSE_TYPE_LAME;
2249 } else iq->dnssec_lame_query = 0;
2250 /* see if referral brings us close to the target */
2251 if(type == RESPONSE_TYPE_REFERRAL) {
2252 struct ub_packed_rrset_key* ns = find_NS(
2253 iq->response->rep, iq->response->rep->an_numrrsets,
2254 iq->response->rep->an_numrrsets
2255 + iq->response->rep->ns_numrrsets);
2256 if(!ns) ns = find_NS(iq->response->rep, 0,
2257 iq->response->rep->an_numrrsets);
2258 if(!ns || !dname_strict_subdomain_c(ns->rk.dname, iq->dp->name)
2259 || !dname_subdomain_c(iq->qchase.qname, ns->rk.dname)){
2260 verbose(VERB_ALGO, "bad referral, throwaway");
2261 type = RESPONSE_TYPE_THROWAWAY;
2263 iter_scrub_ds(iq->response, ns, iq->dp->name);
2264 } else iter_scrub_ds(iq->response, NULL, NULL);
2265 if(type == RESPONSE_TYPE_THROWAWAY &&
2266 FLAGS_GET_RCODE(iq->response->rep->flags) == LDNS_RCODE_YXDOMAIN) {
2267 /* YXDOMAIN is a permanent error, no need to retry */
2268 type = RESPONSE_TYPE_ANSWER;
2270 if(type == RESPONSE_TYPE_CNAME && iq->response->rep->an_numrrsets >= 1
2271 && ntohs(iq->response->rep->rrsets[0]->rk.type) == LDNS_RR_TYPE_DNAME) {
2272 uint8_t* sname = NULL;
2273 size_t snamelen = 0;
2274 get_cname_target(iq->response->rep->rrsets[0], &sname,
2276 if(snamelen && dname_subdomain_c(sname, iq->response->rep->rrsets[0]->rk.dname)) {
2277 /* DNAME to a subdomain loop; do not recurse */
2278 type = RESPONSE_TYPE_ANSWER;
2282 /* handle each of the type cases */
2283 if(type == RESPONSE_TYPE_ANSWER) {
2284 /* ANSWER type responses terminate the query algorithm,
2285 * so they sent on their */
2286 if(verbosity >= VERB_DETAIL) {
2287 verbose(VERB_DETAIL, "query response was %s",
2288 FLAGS_GET_RCODE(iq->response->rep->flags)
2289 ==LDNS_RCODE_NXDOMAIN?"NXDOMAIN ANSWER":
2290 (iq->response->rep->an_numrrsets?"ANSWER":
2293 /* if qtype is DS, check we have the right level of answer,
2294 * like grandchild answer but we need the middle, reject it */
2295 if(iq->qchase.qtype == LDNS_RR_TYPE_DS && !iq->dsns_point
2296 && !(iq->chase_flags&BIT_RD)
2297 && iter_ds_toolow(iq->response, iq->dp)
2298 && iter_dp_cangodown(&iq->qchase, iq->dp)) {
2299 /* close down outstanding requests to be discarded */
2300 outbound_list_clear(&iq->outlist);
2301 iq->num_current_queries = 0;
2302 fptr_ok(fptr_whitelist_modenv_detach_subs(
2303 qstate->env->detach_subs));
2304 (*qstate->env->detach_subs)(qstate);
2305 iq->num_target_queries = 0;
2306 return processDSNSFind(qstate, iq, id);
2308 if(!qstate->no_cache_store)
2309 iter_dns_store(qstate->env, &iq->response->qinfo,
2310 iq->response->rep, 0, qstate->prefetch_leeway,
2311 iq->dp&&iq->dp->has_parent_side_NS,
2312 qstate->region, qstate->query_flags);
2313 /* close down outstanding requests to be discarded */
2314 outbound_list_clear(&iq->outlist);
2315 iq->num_current_queries = 0;
2316 fptr_ok(fptr_whitelist_modenv_detach_subs(
2317 qstate->env->detach_subs));
2318 (*qstate->env->detach_subs)(qstate);
2319 iq->num_target_queries = 0;
2321 sock_list_insert(&qstate->reply_origin,
2322 &qstate->reply->addr, qstate->reply->addrlen,
2324 if(iq->minimisation_state != DONOT_MINIMISE_STATE) {
2325 if(FLAGS_GET_RCODE(iq->response->rep->flags) !=
2326 LDNS_RCODE_NOERROR) {
2327 if(qstate->env->cfg->qname_minimisation_strict)
2328 return final_state(iq);
2329 /* Best effort qname-minimisation.
2330 * Stop minimising and send full query when
2331 * RCODE is not NOERROR. */
2332 iq->minimisation_state = DONOT_MINIMISE_STATE;
2334 if(FLAGS_GET_RCODE(iq->response->rep->flags) ==
2335 LDNS_RCODE_NXDOMAIN) {
2336 /* Stop resolving when NXDOMAIN is DNSSEC
2337 * signed. Based on assumption that namservers
2338 * serving signed zones do not return NXDOMAIN
2339 * for empty-non-terminals. */
2340 if(iq->dnssec_expected)
2341 return final_state(iq);
2342 /* Make subrequest to validate intermediate
2343 * NXDOMAIN if harden-below-nxdomain is
2345 if(qstate->env->cfg->harden_below_nxdomain) {
2346 struct module_qstate* subq = NULL;
2347 log_query_info(VERB_QUERY,
2348 "schedule NXDOMAIN validation:",
2349 &iq->response->qinfo);
2350 if(!generate_sub_request(
2351 iq->response->qinfo.qname,
2352 iq->response->qinfo.qname_len,
2353 iq->response->qinfo.qtype,
2354 iq->response->qinfo.qclass,
2357 FINISHED_STATE, &subq, 1))
2359 "could not validate NXDOMAIN "
2363 return next_state(iq, QUERYTARGETS_STATE);
2365 return final_state(iq);
2366 } else if(type == RESPONSE_TYPE_REFERRAL) {
2367 /* REFERRAL type responses get a reset of the
2368 * delegation point, and back to the QUERYTARGETS_STATE. */
2369 verbose(VERB_DETAIL, "query response was REFERRAL");
2371 if(!(iq->chase_flags & BIT_RD) && !iq->ratelimit_ok) {
2372 /* we have a referral, no ratelimit, we can send
2373 * our queries to the given name */
2374 infra_ratelimit_dec(qstate->env->infra_cache,
2375 iq->dp->name, iq->dp->namelen,
2379 /* if hardened, only store referral if we asked for it */
2380 if(!qstate->no_cache_store &&
2381 (!qstate->env->cfg->harden_referral_path ||
2382 ( qstate->qinfo.qtype == LDNS_RR_TYPE_NS
2383 && (qstate->query_flags&BIT_RD)
2384 && !(qstate->query_flags&BIT_CD)
2385 /* we know that all other NS rrsets are scrubbed
2386 * away, thus on referral only one is left.
2387 * see if that equals the query name... */
2388 && ( /* auth section, but sometimes in answer section*/
2389 reply_find_rrset_section_ns(iq->response->rep,
2390 iq->qchase.qname, iq->qchase.qname_len,
2391 LDNS_RR_TYPE_NS, iq->qchase.qclass)
2392 || reply_find_rrset_section_an(iq->response->rep,
2393 iq->qchase.qname, iq->qchase.qname_len,
2394 LDNS_RR_TYPE_NS, iq->qchase.qclass)
2397 /* Store the referral under the current query */
2398 /* no prefetch-leeway, since its not the answer */
2399 iter_dns_store(qstate->env, &iq->response->qinfo,
2400 iq->response->rep, 1, 0, 0, NULL, 0);
2401 if(iq->store_parent_NS)
2402 iter_store_parentside_NS(qstate->env,
2404 if(qstate->env->neg_cache)
2405 val_neg_addreferral(qstate->env->neg_cache,
2406 iq->response->rep, iq->dp->name);
2408 /* store parent-side-in-zone-glue, if directly queried for */
2409 if(!qstate->no_cache_store && iq->query_for_pside_glue
2410 && !iq->pside_glue) {
2411 iq->pside_glue = reply_find_rrset(iq->response->rep,
2412 iq->qchase.qname, iq->qchase.qname_len,
2413 iq->qchase.qtype, iq->qchase.qclass);
2414 if(iq->pside_glue) {
2415 log_rrset_key(VERB_ALGO, "found parent-side "
2416 "glue", iq->pside_glue);
2417 iter_store_parentside_rrset(qstate->env,
2422 /* Reset the event state, setting the current delegation
2423 * point to the referral. */
2424 iq->deleg_msg = iq->response;
2425 iq->dp = delegpt_from_message(iq->response, qstate->region);
2426 if (qstate->env->cfg->qname_minimisation)
2427 iq->minimisation_state = INIT_MINIMISE_STATE;
2429 return error_response(qstate, id, LDNS_RCODE_SERVFAIL);
2430 if(!cache_fill_missing(qstate->env, iq->qchase.qclass,
2431 qstate->region, iq->dp))
2432 return error_response(qstate, id, LDNS_RCODE_SERVFAIL);
2433 if(iq->store_parent_NS && query_dname_compare(iq->dp->name,
2434 iq->store_parent_NS->name) == 0)
2435 iter_merge_retry_counts(iq->dp, iq->store_parent_NS);
2436 delegpt_log(VERB_ALGO, iq->dp);
2437 /* Count this as a referral. */
2438 iq->referral_count++;
2440 /* see if the next dp is a trust anchor, or a DS was sent
2441 * along, indicating dnssec is expected for next zone */
2442 iq->dnssec_expected = iter_indicates_dnssec(qstate->env,
2443 iq->dp, iq->response, iq->qchase.qclass);
2444 /* if dnssec, validating then also fetch the key for the DS */
2445 if(iq->dnssec_expected && qstate->env->cfg->prefetch_key &&
2446 !(qstate->query_flags&BIT_CD))
2447 generate_dnskey_prefetch(qstate, iq, id);
2449 /* spawn off NS and addr to auth servers for the NS we just
2450 * got in the referral. This gets authoritative answer
2451 * (answer section trust level) rrset.
2452 * right after, we detach the subs, answer goes to cache. */
2453 if(qstate->env->cfg->harden_referral_path)
2454 generate_ns_check(qstate, iq, id);
2456 /* stop current outstanding queries.
2457 * FIXME: should the outstanding queries be waited for and
2458 * handled? Say by a subquery that inherits the outbound_entry.
2460 outbound_list_clear(&iq->outlist);
2461 iq->num_current_queries = 0;
2462 fptr_ok(fptr_whitelist_modenv_detach_subs(
2463 qstate->env->detach_subs));
2464 (*qstate->env->detach_subs)(qstate);
2465 iq->num_target_queries = 0;
2466 verbose(VERB_ALGO, "cleared outbound list for next round");
2467 return next_state(iq, QUERYTARGETS_STATE);
2468 } else if(type == RESPONSE_TYPE_CNAME) {
2469 uint8_t* sname = NULL;
2470 size_t snamelen = 0;
2471 /* CNAME type responses get a query restart (i.e., get a
2472 * reset of the query state and go back to INIT_REQUEST_STATE).
2474 verbose(VERB_DETAIL, "query response was CNAME");
2475 if(verbosity >= VERB_ALGO)
2476 log_dns_msg("cname msg", &iq->response->qinfo,
2478 /* if qtype is DS, check we have the right level of answer,
2479 * like grandchild answer but we need the middle, reject it */
2480 if(iq->qchase.qtype == LDNS_RR_TYPE_DS && !iq->dsns_point
2481 && !(iq->chase_flags&BIT_RD)
2482 && iter_ds_toolow(iq->response, iq->dp)
2483 && iter_dp_cangodown(&iq->qchase, iq->dp)) {
2484 outbound_list_clear(&iq->outlist);
2485 iq->num_current_queries = 0;
2486 fptr_ok(fptr_whitelist_modenv_detach_subs(
2487 qstate->env->detach_subs));
2488 (*qstate->env->detach_subs)(qstate);
2489 iq->num_target_queries = 0;
2490 return processDSNSFind(qstate, iq, id);
2492 /* Process the CNAME response. */
2493 if(!handle_cname_response(qstate, iq, iq->response,
2495 return error_response(qstate, id, LDNS_RCODE_SERVFAIL);
2496 /* cache the CNAME response under the current query */
2497 /* NOTE : set referral=1, so that rrsets get stored but not
2498 * the partial query answer (CNAME only). */
2499 /* prefetchleeway applied because this updates answer parts */
2500 if(!qstate->no_cache_store)
2501 iter_dns_store(qstate->env, &iq->response->qinfo,
2502 iq->response->rep, 1, qstate->prefetch_leeway,
2503 iq->dp&&iq->dp->has_parent_side_NS, NULL,
2504 qstate->query_flags);
2505 /* set the current request's qname to the new value. */
2506 iq->qchase.qname = sname;
2507 iq->qchase.qname_len = snamelen;
2508 if (qstate->env->cfg->qname_minimisation)
2509 iq->minimisation_state = INIT_MINIMISE_STATE;
2510 /* Clear the query state, since this is a query restart. */
2511 iq->deleg_msg = NULL;
2513 iq->dsns_point = NULL;
2514 /* Note the query restart. */
2515 iq->query_restart_count++;
2518 /* stop current outstanding queries.
2519 * FIXME: should the outstanding queries be waited for and
2520 * handled? Say by a subquery that inherits the outbound_entry.
2522 outbound_list_clear(&iq->outlist);
2523 iq->num_current_queries = 0;
2524 fptr_ok(fptr_whitelist_modenv_detach_subs(
2525 qstate->env->detach_subs));
2526 (*qstate->env->detach_subs)(qstate);
2527 iq->num_target_queries = 0;
2529 sock_list_insert(&qstate->reply_origin,
2530 &qstate->reply->addr, qstate->reply->addrlen,
2532 verbose(VERB_ALGO, "cleared outbound list for query restart");
2533 /* go to INIT_REQUEST_STATE for new qname. */
2534 return next_state(iq, INIT_REQUEST_STATE);
2535 } else if(type == RESPONSE_TYPE_LAME) {
2536 /* Cache the LAMEness. */
2537 verbose(VERB_DETAIL, "query response was %sLAME",
2538 dnsseclame?"DNSSEC ":"");
2539 if(!dname_subdomain_c(iq->qchase.qname, iq->dp->name)) {
2540 log_err("mark lame: mismatch in qname and dpname");
2541 /* throwaway this reply below */
2542 } else if(qstate->reply) {
2543 /* need addr for lameness cache, but we may have
2544 * gotten this from cache, so test to be sure */
2545 if(!infra_set_lame(qstate->env->infra_cache,
2546 &qstate->reply->addr, qstate->reply->addrlen,
2547 iq->dp->name, iq->dp->namelen,
2548 *qstate->env->now, dnsseclame, 0,
2550 log_err("mark host lame: out of memory");
2552 } else if(type == RESPONSE_TYPE_REC_LAME) {
2553 /* Cache the LAMEness. */
2554 verbose(VERB_DETAIL, "query response REC_LAME: "
2555 "recursive but not authoritative server");
2556 if(!dname_subdomain_c(iq->qchase.qname, iq->dp->name)) {
2557 log_err("mark rec_lame: mismatch in qname and dpname");
2558 /* throwaway this reply below */
2559 } else if(qstate->reply) {
2560 /* need addr for lameness cache, but we may have
2561 * gotten this from cache, so test to be sure */
2562 verbose(VERB_DETAIL, "mark as REC_LAME");
2563 if(!infra_set_lame(qstate->env->infra_cache,
2564 &qstate->reply->addr, qstate->reply->addrlen,
2565 iq->dp->name, iq->dp->namelen,
2566 *qstate->env->now, 0, 1, iq->qchase.qtype))
2567 log_err("mark host lame: out of memory");
2569 } else if(type == RESPONSE_TYPE_THROWAWAY) {
2570 /* LAME and THROWAWAY responses are handled the same way.
2571 * In this case, the event is just sent directly back to
2572 * the QUERYTARGETS_STATE without resetting anything,
2573 * because, clearly, the next target must be tried. */
2574 verbose(VERB_DETAIL, "query response was THROWAWAY");
2576 log_warn("A query response came back with an unknown type: %d",
2580 /* LAME, THROWAWAY and "unknown" all end up here.
2581 * Recycle to the QUERYTARGETS state to hopefully try a
2582 * different target. */
2583 if (qstate->env->cfg->qname_minimisation &&
2584 !qstate->env->cfg->qname_minimisation_strict)
2585 iq->minimisation_state = DONOT_MINIMISE_STATE;
2586 return next_state(iq, QUERYTARGETS_STATE);
2590 * Return priming query results to interested super querystates.
2592 * Sets the delegation point and delegation message (not nonRD queries).
2593 * This is a callback from walk_supers.
2595 * @param qstate: priming query state that finished.
2596 * @param id: module id.
2597 * @param forq: the qstate for which priming has been done.
2600 prime_supers(struct module_qstate* qstate, int id, struct module_qstate* forq)
2602 struct iter_qstate* foriq = (struct iter_qstate*)forq->minfo[id];
2603 struct delegpt* dp = NULL;
2605 log_assert(qstate->is_priming || foriq->wait_priming_stub);
2606 log_assert(qstate->return_rcode == LDNS_RCODE_NOERROR);
2607 /* Convert our response to a delegation point */
2608 dp = delegpt_from_message(qstate->return_msg, forq->region);
2610 /* if there is no convertable delegation point, then
2611 * the ANSWER type was (presumably) a negative answer. */
2612 verbose(VERB_ALGO, "prime response was not a positive "
2615 foriq->state = QUERYTARGETS_STATE;
2619 log_query_info(VERB_DETAIL, "priming successful for", &qstate->qinfo);
2620 delegpt_log(VERB_ALGO, dp);
2622 foriq->deleg_msg = dns_copy_msg(qstate->return_msg, forq->region);
2623 if(!foriq->deleg_msg) {
2624 log_err("copy prime response: out of memory");
2626 foriq->state = QUERYTARGETS_STATE;
2630 /* root priming responses go to init stage 2, priming stub
2631 * responses to to stage 3. */
2632 if(foriq->wait_priming_stub) {
2633 foriq->state = INIT_REQUEST_3_STATE;
2634 foriq->wait_priming_stub = 0;
2635 } else foriq->state = INIT_REQUEST_2_STATE;
2636 /* because we are finished, the parent will be reactivated */
2640 * This handles the response to a priming query. This is used to handle both
2641 * root and stub priming responses. This is basically the equivalent of the
2642 * QUERY_RESP_STATE, but will not handle CNAME responses and will treat
2643 * REFERRALs as ANSWERS. It will also update and reactivate the originating
2646 * @param qstate: query state.
2647 * @param id: module id.
2648 * @return true if the event needs more immediate processing, false if not.
2649 * This state always returns false.
2652 processPrimeResponse(struct module_qstate* qstate, int id)
2654 struct iter_qstate* iq = (struct iter_qstate*)qstate->minfo[id];
2655 enum response_type type;
2656 iq->response->rep->flags &= ~(BIT_RD|BIT_RA); /* ignore rec-lame */
2657 type = response_type_from_server(
2658 (int)((iq->chase_flags&BIT_RD) || iq->chase_to_rd),
2659 iq->response, &iq->qchase, iq->dp);
2660 if(type == RESPONSE_TYPE_ANSWER) {
2661 qstate->return_rcode = LDNS_RCODE_NOERROR;
2662 qstate->return_msg = iq->response;
2664 qstate->return_rcode = LDNS_RCODE_SERVFAIL;
2665 qstate->return_msg = NULL;
2668 /* validate the root or stub after priming (if enabled).
2669 * This is the same query as the prime query, but with validation.
2670 * Now that we are primed, the additional queries that validation
2671 * may need can be resolved, such as DLV. */
2672 if(qstate->env->cfg->harden_referral_path) {
2673 struct module_qstate* subq = NULL;
2674 log_nametypeclass(VERB_ALGO, "schedule prime validation",
2675 qstate->qinfo.qname, qstate->qinfo.qtype,
2676 qstate->qinfo.qclass);
2677 if(!generate_sub_request(qstate->qinfo.qname,
2678 qstate->qinfo.qname_len, qstate->qinfo.qtype,
2679 qstate->qinfo.qclass, qstate, id, iq,
2680 INIT_REQUEST_STATE, FINISHED_STATE, &subq, 1)) {
2681 verbose(VERB_ALGO, "could not generate prime check");
2683 generate_a_aaaa_check(qstate, iq, id);
2686 /* This event is finished. */
2687 qstate->ext_state[id] = module_finished;
2692 * Do final processing on responses to target queries. Events reach this
2693 * state after the iterative resolution algorithm terminates. This state is
2694 * responsible for reactiving the original event, and housekeeping related
2695 * to received target responses (caching, updating the current delegation
2697 * Callback from walk_supers for every super state that is interested in
2698 * the results from this query.
2700 * @param qstate: query state.
2701 * @param id: module id.
2702 * @param forq: super query state.
2705 processTargetResponse(struct module_qstate* qstate, int id,
2706 struct module_qstate* forq)
2708 struct iter_qstate* iq = (struct iter_qstate*)qstate->minfo[id];
2709 struct iter_qstate* foriq = (struct iter_qstate*)forq->minfo[id];
2710 struct ub_packed_rrset_key* rrset;
2711 struct delegpt_ns* dpns;
2712 log_assert(qstate->return_rcode == LDNS_RCODE_NOERROR);
2714 foriq->state = QUERYTARGETS_STATE;
2715 log_query_info(VERB_ALGO, "processTargetResponse", &qstate->qinfo);
2716 log_query_info(VERB_ALGO, "processTargetResponse super", &forq->qinfo);
2718 /* Tell the originating event that this target query has finished
2719 * (regardless if it succeeded or not). */
2720 foriq->num_target_queries--;
2722 /* check to see if parent event is still interested (in orig name). */
2724 verbose(VERB_ALGO, "subq: parent not interested, was reset");
2725 return; /* not interested anymore */
2727 dpns = delegpt_find_ns(foriq->dp, qstate->qinfo.qname,
2728 qstate->qinfo.qname_len);
2730 /* If not interested, just stop processing this event */
2731 verbose(VERB_ALGO, "subq: parent not interested anymore");
2732 /* could be because parent was jostled out of the cache,
2733 and a new identical query arrived, that does not want it*/
2737 /* if iq->query_for_pside_glue then add the pside_glue (marked lame) */
2738 if(iq->pside_glue) {
2739 /* if the pside_glue is NULL, then it could not be found,
2740 * the done_pside is already set when created and a cache
2741 * entry created in processFinished so nothing to do here */
2742 log_rrset_key(VERB_ALGO, "add parentside glue to dp",
2744 if(!delegpt_add_rrset(foriq->dp, forq->region,
2746 log_err("out of memory adding pside glue");
2749 /* This response is relevant to the current query, so we
2750 * add (attempt to add, anyway) this target(s) and reactivate
2751 * the original event.
2752 * NOTE: we could only look for the AnswerRRset if the
2753 * response type was ANSWER. */
2754 rrset = reply_find_answer_rrset(&iq->qchase, qstate->return_msg->rep);
2756 /* if CNAMEs have been followed - add new NS to delegpt. */
2757 /* BTW. RFC 1918 says NS should not have got CNAMEs. Robust. */
2758 if(!delegpt_find_ns(foriq->dp, rrset->rk.dname,
2759 rrset->rk.dname_len)) {
2760 /* if dpns->lame then set newcname ns lame too */
2761 if(!delegpt_add_ns(foriq->dp, forq->region,
2762 rrset->rk.dname, dpns->lame))
2763 log_err("out of memory adding cnamed-ns");
2765 /* if dpns->lame then set the address(es) lame too */
2766 if(!delegpt_add_rrset(foriq->dp, forq->region, rrset,
2768 log_err("out of memory adding targets");
2769 verbose(VERB_ALGO, "added target response");
2770 delegpt_log(VERB_ALGO, foriq->dp);
2772 verbose(VERB_ALGO, "iterator TargetResponse failed");
2773 dpns->resolved = 1; /* fail the target */
2778 * Process response for DS NS Find queries, that attempt to find the delegation
2779 * point where we ask the DS query from.
2781 * @param qstate: query state.
2782 * @param id: module id.
2783 * @param forq: super query state.
2786 processDSNSResponse(struct module_qstate* qstate, int id,
2787 struct module_qstate* forq)
2789 struct iter_qstate* foriq = (struct iter_qstate*)forq->minfo[id];
2791 /* if the finished (iq->response) query has no NS set: continue
2792 * up to look for the right dp; nothing to change, do DPNSstate */
2793 if(qstate->return_rcode != LDNS_RCODE_NOERROR)
2794 return; /* seek further */
2795 /* find the NS RRset (without allowing CNAMEs) */
2796 if(!reply_find_rrset(qstate->return_msg->rep, qstate->qinfo.qname,
2797 qstate->qinfo.qname_len, LDNS_RR_TYPE_NS,
2798 qstate->qinfo.qclass)){
2799 return; /* seek further */
2802 /* else, store as DP and continue at querytargets */
2803 foriq->state = QUERYTARGETS_STATE;
2804 foriq->dp = delegpt_from_message(qstate->return_msg, forq->region);
2806 log_err("out of memory in dsns dp alloc");
2807 return; /* dp==NULL in QUERYTARGETS makes SERVFAIL */
2809 /* success, go query the querytargets in the new dp (and go down) */
2813 * Process response for qclass=ANY queries for a particular class.
2814 * Append to result or error-exit.
2816 * @param qstate: query state.
2817 * @param id: module id.
2818 * @param forq: super query state.
2821 processClassResponse(struct module_qstate* qstate, int id,
2822 struct module_qstate* forq)
2824 struct iter_qstate* foriq = (struct iter_qstate*)forq->minfo[id];
2825 struct dns_msg* from = qstate->return_msg;
2826 log_query_info(VERB_ALGO, "processClassResponse", &qstate->qinfo);
2827 log_query_info(VERB_ALGO, "processClassResponse super", &forq->qinfo);
2828 if(qstate->return_rcode != LDNS_RCODE_NOERROR) {
2829 /* cause servfail for qclass ANY query */
2830 foriq->response = NULL;
2831 foriq->state = FINISHED_STATE;
2835 if(!foriq->response) {
2836 /* allocate the response: copy RCODE, sec_state */
2837 foriq->response = dns_copy_msg(from, forq->region);
2838 if(!foriq->response) {
2839 log_err("malloc failed for qclass ANY response");
2840 foriq->state = FINISHED_STATE;
2843 foriq->response->qinfo.qclass = forq->qinfo.qclass;
2844 /* qclass ANY does not receive the AA flag on replies */
2845 foriq->response->rep->authoritative = 0;
2847 struct dns_msg* to = foriq->response;
2848 /* add _from_ this response _to_ existing collection */
2849 /* if there are records, copy RCODE */
2850 /* lower sec_state if this message is lower */
2851 if(from->rep->rrset_count != 0) {
2852 size_t n = from->rep->rrset_count+to->rep->rrset_count;
2853 struct ub_packed_rrset_key** dest, **d;
2854 /* copy appropriate rcode */
2855 to->rep->flags = from->rep->flags;
2857 if(from->rep->rrset_count > RR_COUNT_MAX ||
2858 to->rep->rrset_count > RR_COUNT_MAX) {
2859 log_err("malloc failed (too many rrsets) in collect ANY");
2860 foriq->state = FINISHED_STATE;
2861 return; /* integer overflow protection */
2863 dest = regional_alloc(forq->region, sizeof(dest[0])*n);
2865 log_err("malloc failed in collect ANY");
2866 foriq->state = FINISHED_STATE;
2871 memcpy(dest, to->rep->rrsets, to->rep->an_numrrsets
2873 dest += to->rep->an_numrrsets;
2874 memcpy(dest, from->rep->rrsets, from->rep->an_numrrsets
2876 dest += from->rep->an_numrrsets;
2878 memcpy(dest, to->rep->rrsets+to->rep->an_numrrsets,
2879 to->rep->ns_numrrsets * sizeof(dest[0]));
2880 dest += to->rep->ns_numrrsets;
2881 memcpy(dest, from->rep->rrsets+from->rep->an_numrrsets,
2882 from->rep->ns_numrrsets * sizeof(dest[0]));
2883 dest += from->rep->ns_numrrsets;
2885 memcpy(dest, to->rep->rrsets+to->rep->an_numrrsets+
2886 to->rep->ns_numrrsets,
2887 to->rep->ar_numrrsets * sizeof(dest[0]));
2888 dest += to->rep->ar_numrrsets;
2889 memcpy(dest, from->rep->rrsets+from->rep->an_numrrsets+
2890 from->rep->ns_numrrsets,
2891 from->rep->ar_numrrsets * sizeof(dest[0]));
2893 to->rep->rrsets = d;
2894 to->rep->an_numrrsets += from->rep->an_numrrsets;
2895 to->rep->ns_numrrsets += from->rep->ns_numrrsets;
2896 to->rep->ar_numrrsets += from->rep->ar_numrrsets;
2897 to->rep->rrset_count = n;
2899 if(from->rep->security < to->rep->security) /* lowest sec */
2900 to->rep->security = from->rep->security;
2901 if(from->rep->qdcount != 0) /* insert qd if appropriate */
2902 to->rep->qdcount = from->rep->qdcount;
2903 if(from->rep->ttl < to->rep->ttl) /* use smallest TTL */
2904 to->rep->ttl = from->rep->ttl;
2905 if(from->rep->prefetch_ttl < to->rep->prefetch_ttl)
2906 to->rep->prefetch_ttl = from->rep->prefetch_ttl;
2909 foriq->num_current_queries --;
2910 if(foriq->num_current_queries == 0)
2911 foriq->state = FINISHED_STATE;
2915 * Collect class ANY responses and make them into one response. This
2916 * state is started and it creates queries for all classes (that have
2917 * root hints). The answers are then collected.
2919 * @param qstate: query state.
2920 * @param id: module id.
2921 * @return true if the event needs more immediate processing, false if not.
2924 processCollectClass(struct module_qstate* qstate, int id)
2926 struct iter_qstate* iq = (struct iter_qstate*)qstate->minfo[id];
2927 struct module_qstate* subq;
2928 /* If qchase.qclass == 0 then send out queries for all classes.
2929 * Otherwise, do nothing (wait for all answers to arrive and the
2930 * processClassResponse to put them together, and that moves us
2931 * towards the Finished state when done. */
2932 if(iq->qchase.qclass == 0) {
2934 iq->qchase.qclass = LDNS_RR_CLASS_ANY;
2935 while(iter_get_next_root(qstate->env->hints,
2936 qstate->env->fwds, &c)) {
2937 /* generate query for this class */
2938 log_nametypeclass(VERB_ALGO, "spawn collect query",
2939 qstate->qinfo.qname, qstate->qinfo.qtype, c);
2940 if(!generate_sub_request(qstate->qinfo.qname,
2941 qstate->qinfo.qname_len, qstate->qinfo.qtype,
2942 c, qstate, id, iq, INIT_REQUEST_STATE,
2943 FINISHED_STATE, &subq,
2944 (int)!(qstate->query_flags&BIT_CD))) {
2945 return error_response(qstate, id,
2946 LDNS_RCODE_SERVFAIL);
2948 /* ignore subq, no special init required */
2949 iq->num_current_queries ++;
2954 /* if no roots are configured at all, return */
2955 if(iq->num_current_queries == 0) {
2956 verbose(VERB_ALGO, "No root hints or fwds, giving up "
2958 return error_response(qstate, id, LDNS_RCODE_REFUSED);
2960 /* return false, wait for queries to return */
2962 /* if woke up here because of an answer, wait for more answers */
2967 * This handles the final state for first-tier responses (i.e., responses to
2968 * externally generated queries).
2970 * @param qstate: query state.
2971 * @param iq: iterator query state.
2972 * @param id: module id.
2973 * @return true if the event needs more processing, false if not. Since this
2974 * is the final state for an event, it always returns false.
2977 processFinished(struct module_qstate* qstate, struct iter_qstate* iq,
2980 log_query_info(VERB_QUERY, "finishing processing for",
2983 /* store negative cache element for parent side glue. */
2984 if(!qstate->no_cache_store && iq->query_for_pside_glue
2986 iter_store_parentside_neg(qstate->env, &qstate->qinfo,
2987 iq->deleg_msg?iq->deleg_msg->rep:
2988 (iq->response?iq->response->rep:NULL));
2990 verbose(VERB_ALGO, "No response is set, servfail");
2991 return error_response(qstate, id, LDNS_RCODE_SERVFAIL);
2994 /* Make sure that the RA flag is set (since the presence of
2995 * this module means that recursion is available) */
2996 iq->response->rep->flags |= BIT_RA;
2998 /* Clear the AA flag */
2999 /* FIXME: does this action go here or in some other module? */
3000 iq->response->rep->flags &= ~BIT_AA;
3002 /* make sure QR flag is on */
3003 iq->response->rep->flags |= BIT_QR;
3005 /* we have finished processing this query */
3006 qstate->ext_state[id] = module_finished;
3008 /* TODO: we are using a private TTL, trim the response. */
3009 /* if (mPrivateTTL > 0){IterUtils.setPrivateTTL(resp, mPrivateTTL); } */
3011 /* prepend any items we have accumulated */
3012 if(iq->an_prepend_list || iq->ns_prepend_list) {
3013 if(!iter_prepend(iq, iq->response, qstate->region)) {
3014 log_err("prepend rrsets: out of memory");
3015 return error_response(qstate, id, LDNS_RCODE_SERVFAIL);
3017 /* reset the query name back */
3018 iq->response->qinfo = qstate->qinfo;
3019 /* the security state depends on the combination */
3020 iq->response->rep->security = sec_status_unchecked;
3021 /* store message with the finished prepended items,
3022 * but only if we did recursion. The nonrecursion referral
3023 * from cache does not need to be stored in the msg cache. */
3024 if(!qstate->no_cache_store && qstate->query_flags&BIT_RD) {
3025 iter_dns_store(qstate->env, &qstate->qinfo,
3026 iq->response->rep, 0, qstate->prefetch_leeway,
3027 iq->dp&&iq->dp->has_parent_side_NS,
3028 qstate->region, qstate->query_flags);
3031 qstate->return_rcode = LDNS_RCODE_NOERROR;
3032 qstate->return_msg = iq->response;
3037 * Return priming query results to interestes super querystates.
3039 * Sets the delegation point and delegation message (not nonRD queries).
3040 * This is a callback from walk_supers.
3042 * @param qstate: query state that finished.
3043 * @param id: module id.
3044 * @param super: the qstate to inform.
3047 iter_inform_super(struct module_qstate* qstate, int id,
3048 struct module_qstate* super)
3050 if(!qstate->is_priming && super->qinfo.qclass == LDNS_RR_CLASS_ANY)
3051 processClassResponse(qstate, id, super);
3052 else if(super->qinfo.qtype == LDNS_RR_TYPE_DS && ((struct iter_qstate*)
3053 super->minfo[id])->state == DSNS_FIND_STATE)
3054 processDSNSResponse(qstate, id, super);
3055 else if(qstate->return_rcode != LDNS_RCODE_NOERROR)
3056 error_supers(qstate, id, super);
3057 else if(qstate->is_priming)
3058 prime_supers(qstate, id, super);
3059 else processTargetResponse(qstate, id, super);
3063 * Handle iterator state.
3064 * Handle events. This is the real processing loop for events, responsible
3065 * for moving events through the various states. If a processing method
3066 * returns true, then it will be advanced to the next state. If false, then
3067 * processing will stop.
3069 * @param qstate: query state.
3070 * @param ie: iterator shared global environment.
3071 * @param iq: iterator query state.
3072 * @param id: module id.
3075 iter_handle(struct module_qstate* qstate, struct iter_qstate* iq,
3076 struct iter_env* ie, int id)
3080 verbose(VERB_ALGO, "iter_handle processing q with state %s",
3081 iter_state_to_string(iq->state));
3083 case INIT_REQUEST_STATE:
3084 cont = processInitRequest(qstate, iq, ie, id);
3086 case INIT_REQUEST_2_STATE:
3087 cont = processInitRequest2(qstate, iq, id);
3089 case INIT_REQUEST_3_STATE:
3090 cont = processInitRequest3(qstate, iq, id);
3092 case QUERYTARGETS_STATE:
3093 cont = processQueryTargets(qstate, iq, ie, id);
3095 case QUERY_RESP_STATE:
3096 cont = processQueryResponse(qstate, iq, id);
3098 case PRIME_RESP_STATE:
3099 cont = processPrimeResponse(qstate, id);
3101 case COLLECT_CLASS_STATE:
3102 cont = processCollectClass(qstate, id);
3104 case DSNS_FIND_STATE:
3105 cont = processDSNSFind(qstate, iq, id);
3107 case FINISHED_STATE:
3108 cont = processFinished(qstate, iq, id);
3111 log_warn("iterator: invalid state: %d",
3120 * This is the primary entry point for processing request events. Note that
3121 * this method should only be used by external modules.
3122 * @param qstate: query state.
3123 * @param ie: iterator shared global environment.
3124 * @param iq: iterator query state.
3125 * @param id: module id.
3128 process_request(struct module_qstate* qstate, struct iter_qstate* iq,
3129 struct iter_env* ie, int id)
3131 /* external requests start in the INIT state, and finish using the
3132 * FINISHED state. */
3133 iq->state = INIT_REQUEST_STATE;
3134 iq->final_state = FINISHED_STATE;
3135 verbose(VERB_ALGO, "process_request: new external request event");
3136 iter_handle(qstate, iq, ie, id);
3139 /** process authoritative server reply */
3141 process_response(struct module_qstate* qstate, struct iter_qstate* iq,
3142 struct iter_env* ie, int id, struct outbound_entry* outbound,
3143 enum module_ev event)
3145 struct msg_parse* prs;
3146 struct edns_data edns;
3149 verbose(VERB_ALGO, "process_response: new external response event");
3150 iq->response = NULL;
3151 iq->state = QUERY_RESP_STATE;
3152 if(event == module_event_noreply || event == module_event_error) {
3153 if(event == module_event_noreply && iq->sent_count >= 3 &&
3154 qstate->env->cfg->use_caps_bits_for_id &&
3155 !iq->caps_fallback) {
3156 /* start fallback */
3157 iq->caps_fallback = 1;
3158 iq->caps_server = 0;
3159 iq->caps_reply = NULL;
3160 iq->caps_response = NULL;
3161 iq->state = QUERYTARGETS_STATE;
3162 iq->num_current_queries--;
3163 /* need fresh attempts for the 0x20 fallback, if
3164 * that was the cause for the failure */
3165 iter_dec_attempts(iq->dp, 3);
3166 verbose(VERB_DETAIL, "Capsforid: timeouts, starting fallback");
3171 if( (event != module_event_reply && event != module_event_capsfail)
3172 || !qstate->reply) {
3173 log_err("Bad event combined with response");
3174 outbound_list_remove(&iq->outlist, outbound);
3175 (void)error_response(qstate, id, LDNS_RCODE_SERVFAIL);
3180 prs = (struct msg_parse*)regional_alloc(qstate->env->scratch,
3181 sizeof(struct msg_parse));
3183 log_err("out of memory on incoming message");
3184 /* like packet got dropped */
3187 memset(prs, 0, sizeof(*prs));
3188 memset(&edns, 0, sizeof(edns));
3189 pkt = qstate->reply->c->buffer;
3190 sldns_buffer_set_position(pkt, 0);
3191 if(parse_packet(pkt, prs, qstate->env->scratch) != LDNS_RCODE_NOERROR) {
3192 verbose(VERB_ALGO, "parse error on reply packet");
3195 /* edns is not examined, but removed from message to help cache */
3196 if(parse_extract_edns(prs, &edns, qstate->env->scratch) !=
3200 /* Copy the edns options we may got from the back end */
3202 qstate->edns_opts_back_in = edns_opt_copy_region(edns.opt_list,
3204 if(!qstate->edns_opts_back_in) {
3205 log_err("out of memory on incoming message");
3206 /* like packet got dropped */
3209 if(!inplace_cb_edns_back_parsed_call(qstate->env, qstate)) {
3210 log_err("unable to call edns_back_parsed callback");
3215 /* remove CD-bit, we asked for in case we handle validation ourself */
3216 prs->flags &= ~BIT_CD;
3218 /* normalize and sanitize: easy to delete items from linked lists */
3219 if(!scrub_message(pkt, prs, &iq->qinfo_out, iq->dp->name,
3220 qstate->env->scratch, qstate->env, ie)) {
3221 /* if 0x20 enabled, start fallback, but we have no message */
3222 if(event == module_event_capsfail && !iq->caps_fallback) {
3223 iq->caps_fallback = 1;
3224 iq->caps_server = 0;
3225 iq->caps_reply = NULL;
3226 iq->caps_response = NULL;
3227 iq->state = QUERYTARGETS_STATE;
3228 iq->num_current_queries--;
3229 verbose(VERB_DETAIL, "Capsforid: scrub failed, starting fallback with no response");
3234 /* allocate response dns_msg in region */
3235 iq->response = dns_alloc_msg(pkt, prs, qstate->region);
3238 log_query_info(VERB_DETAIL, "response for", &qstate->qinfo);
3239 log_name_addr(VERB_DETAIL, "reply from", iq->dp->name,
3240 &qstate->reply->addr, qstate->reply->addrlen);
3241 if(verbosity >= VERB_ALGO)
3242 log_dns_msg("incoming scrubbed packet:", &iq->response->qinfo,
3245 if(event == module_event_capsfail || iq->caps_fallback) {
3246 /* for fallback we care about main answer, not additionals */
3247 /* removing that makes comparison more likely to succeed */
3248 caps_strip_reply(iq->response->rep);
3249 if(!iq->caps_fallback) {
3250 /* start fallback */
3251 iq->caps_fallback = 1;
3252 iq->caps_server = 0;
3253 iq->caps_reply = iq->response->rep;
3254 iq->caps_response = iq->response;
3255 iq->state = QUERYTARGETS_STATE;
3256 iq->num_current_queries--;
3257 verbose(VERB_DETAIL, "Capsforid: starting fallback");
3260 /* check if reply is the same, otherwise, fail */
3261 if(!iq->caps_reply) {
3262 iq->caps_reply = iq->response->rep;
3263 iq->caps_response = iq->response;
3264 iq->caps_server = -1; /*become zero at ++,
3265 so that we start the full set of trials */
3266 } else if(caps_failed_rcode(iq->caps_reply) &&
3267 !caps_failed_rcode(iq->response->rep)) {
3268 /* prefer to upgrade to non-SERVFAIL */
3269 iq->caps_reply = iq->response->rep;
3270 iq->caps_response = iq->response;
3271 } else if(!caps_failed_rcode(iq->caps_reply) &&
3272 caps_failed_rcode(iq->response->rep)) {
3273 /* if we have non-SERVFAIL as answer then
3274 * we can ignore SERVFAILs for the equality
3276 /* no instructions here, skip other else */
3277 } else if(caps_failed_rcode(iq->caps_reply) &&
3278 caps_failed_rcode(iq->response->rep)) {
3279 /* failure is same as other failure in fallbk*/
3280 /* no instructions here, skip other else */
3281 } else if(!reply_equal(iq->response->rep, iq->caps_reply,
3282 qstate->env->scratch)) {
3283 verbose(VERB_DETAIL, "Capsforid fallback: "
3284 "getting different replies, failed");
3285 outbound_list_remove(&iq->outlist, outbound);
3286 (void)error_response(qstate, id,
3287 LDNS_RCODE_SERVFAIL);
3290 /* continue the fallback procedure at next server */
3292 iq->state = QUERYTARGETS_STATE;
3293 iq->num_current_queries--;
3294 verbose(VERB_DETAIL, "Capsforid: reply is equal. "
3295 "go to next fallback");
3299 iq->caps_fallback = 0; /* if we were in fallback, 0x20 is OK now */
3302 outbound_list_remove(&iq->outlist, outbound);
3303 iter_handle(qstate, iq, ie, id);
3307 iter_operate(struct module_qstate* qstate, enum module_ev event, int id,
3308 struct outbound_entry* outbound)
3310 struct iter_env* ie = (struct iter_env*)qstate->env->modinfo[id];
3311 struct iter_qstate* iq = (struct iter_qstate*)qstate->minfo[id];
3312 verbose(VERB_QUERY, "iterator[module %d] operate: extstate:%s event:%s",
3313 id, strextstate(qstate->ext_state[id]), strmodulevent(event));
3314 if(iq) log_query_info(VERB_QUERY, "iterator operate: query",
3316 if(iq && qstate->qinfo.qname != iq->qchase.qname)
3317 log_query_info(VERB_QUERY, "iterator operate: chased to",
3320 /* perform iterator state machine */
3321 if((event == module_event_new || event == module_event_pass) &&
3323 if(!iter_new(qstate, id)) {
3324 (void)error_response(qstate, id, LDNS_RCODE_SERVFAIL);
3327 iq = (struct iter_qstate*)qstate->minfo[id];
3328 process_request(qstate, iq, ie, id);
3331 if(iq && event == module_event_pass) {
3332 iter_handle(qstate, iq, ie, id);
3335 if(iq && outbound) {
3336 process_response(qstate, iq, ie, id, outbound, event);
3339 if(event == module_event_error) {
3340 verbose(VERB_ALGO, "got called with event error, giving up");
3341 (void)error_response(qstate, id, LDNS_RCODE_SERVFAIL);
3345 log_err("bad event for iterator");
3346 (void)error_response(qstate, id, LDNS_RCODE_SERVFAIL);
3350 iter_clear(struct module_qstate* qstate, int id)
3352 struct iter_qstate* iq;
3355 iq = (struct iter_qstate*)qstate->minfo[id];
3357 outbound_list_clear(&iq->outlist);
3358 if(iq->target_count && --iq->target_count[0] == 0)
3359 free(iq->target_count);
3360 iq->num_current_queries = 0;
3362 qstate->minfo[id] = NULL;
3366 iter_get_mem(struct module_env* env, int id)
3368 struct iter_env* ie = (struct iter_env*)env->modinfo[id];
3371 return sizeof(*ie) + sizeof(int)*((size_t)ie->max_dependency_depth+1)
3372 + donotq_get_mem(ie->donotq) + priv_get_mem(ie->priv);
3376 * The iterator function block
3378 static struct module_func_block iter_block = {
3380 &iter_init, &iter_deinit, &iter_operate, &iter_inform_super,
3381 &iter_clear, &iter_get_mem
3384 struct module_func_block*
3385 iter_get_funcblock(void)
3391 iter_state_to_string(enum iter_state state)
3395 case INIT_REQUEST_STATE :
3396 return "INIT REQUEST STATE";
3397 case INIT_REQUEST_2_STATE :
3398 return "INIT REQUEST STATE (stage 2)";
3399 case INIT_REQUEST_3_STATE:
3400 return "INIT REQUEST STATE (stage 3)";
3401 case QUERYTARGETS_STATE :
3402 return "QUERY TARGETS STATE";
3403 case PRIME_RESP_STATE :
3404 return "PRIME RESPONSE STATE";
3405 case COLLECT_CLASS_STATE :
3406 return "COLLECT CLASS STATE";
3407 case DSNS_FIND_STATE :
3408 return "DSNS FIND STATE";
3409 case QUERY_RESP_STATE :
3410 return "QUERY RESPONSE STATE";
3411 case FINISHED_STATE :
3412 return "FINISHED RESPONSE STATE";
3414 return "UNKNOWN ITER STATE";
3419 iter_state_is_responsestate(enum iter_state s)
3422 case INIT_REQUEST_STATE :
3423 case INIT_REQUEST_2_STATE :
3424 case INIT_REQUEST_3_STATE :
3425 case QUERYTARGETS_STATE :
3426 case COLLECT_CLASS_STATE :