2 * iterator/iterator.c - iterative resolver DNS query response module
4 * Copyright (c) 2007, NLnet Labs. All rights reserved.
6 * This software is open source.
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions
12 * Redistributions of source code must retain the above copyright notice,
13 * this list of conditions and the following disclaimer.
15 * Redistributions in binary form must reproduce the above copyright notice,
16 * this list of conditions and the following disclaimer in the documentation
17 * and/or other materials provided with the distribution.
19 * Neither the name of the NLNET LABS nor the names of its contributors may
20 * be used to endorse or promote products derived from this software without
21 * specific prior written permission.
23 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
24 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
25 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
26 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
27 * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
28 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
29 * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
30 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
31 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
32 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
33 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
39 * This file contains a module that performs recusive iterative DNS query
44 #include "iterator/iterator.h"
45 #include "iterator/iter_utils.h"
46 #include "iterator/iter_hints.h"
47 #include "iterator/iter_fwd.h"
48 #include "iterator/iter_donotq.h"
49 #include "iterator/iter_delegpt.h"
50 #include "iterator/iter_resptype.h"
51 #include "iterator/iter_scrub.h"
52 #include "iterator/iter_priv.h"
53 #include "validator/val_neg.h"
54 #include "services/cache/dns.h"
55 #include "services/cache/infra.h"
56 #include "util/module.h"
57 #include "util/netevent.h"
58 #include "util/net_help.h"
59 #include "util/regional.h"
60 #include "util/data/dname.h"
61 #include "util/data/msgencode.h"
62 #include "util/fptr_wlist.h"
63 #include "util/config_file.h"
64 #include "ldns/rrdef.h"
65 #include "ldns/wire2str.h"
66 #include "ldns/parseutil.h"
67 #include "ldns/sbuffer.h"
70 iter_init(struct module_env* env, int id)
72 struct iter_env* iter_env = (struct iter_env*)calloc(1,
73 sizeof(struct iter_env));
75 log_err("malloc failure");
78 env->modinfo[id] = (void*)iter_env;
79 if(!iter_apply_cfg(iter_env, env->cfg)) {
80 log_err("iterator: could not apply configuration settings.");
87 iter_deinit(struct module_env* env, int id)
89 struct iter_env* iter_env;
90 if(!env || !env->modinfo[id])
92 iter_env = (struct iter_env*)env->modinfo[id];
93 free(iter_env->target_fetch_policy);
94 priv_delete(iter_env->priv);
95 donotq_delete(iter_env->donotq);
97 env->modinfo[id] = NULL;
100 /** new query for iterator */
102 iter_new(struct module_qstate* qstate, int id)
104 struct iter_qstate* iq = (struct iter_qstate*)regional_alloc(
105 qstate->region, sizeof(struct iter_qstate));
106 qstate->minfo[id] = iq;
109 memset(iq, 0, sizeof(*iq));
110 iq->state = INIT_REQUEST_STATE;
111 iq->final_state = FINISHED_STATE;
112 iq->an_prepend_list = NULL;
113 iq->an_prepend_last = NULL;
114 iq->ns_prepend_list = NULL;
115 iq->ns_prepend_last = NULL;
118 iq->num_target_queries = 0;
119 iq->num_current_queries = 0;
120 iq->query_restart_count = 0;
121 iq->referral_count = 0;
123 iq->wait_priming_stub = 0;
124 iq->refetch_glue = 0;
125 iq->dnssec_expected = 0;
126 iq->dnssec_lame_query = 0;
127 iq->chase_flags = qstate->query_flags;
128 /* Start with the (current) qname. */
129 iq->qchase = qstate->qinfo;
130 outbound_list_init(&iq->outlist);
135 * Transition to the next state. This can be used to advance a currently
136 * processing event. It cannot be used to reactivate a forEvent.
138 * @param iq: iterator query state
139 * @param nextstate The state to transition to.
140 * @return true. This is so this can be called as the return value for the
141 * actual process*State() methods. (Transitioning to the next state
142 * implies further processing).
145 next_state(struct iter_qstate* iq, enum iter_state nextstate)
147 /* If transitioning to a "response" state, make sure that there is a
149 if(iter_state_is_responsestate(nextstate)) {
150 if(iq->response == NULL) {
151 log_err("transitioning to response state sans "
155 iq->state = nextstate;
160 * Transition an event to its final state. Final states always either return
161 * a result up the module chain, or reactivate a dependent event. Which
162 * final state to transtion to is set in the module state for the event when
163 * it was created, and depends on the original purpose of the event.
165 * The response is stored in the qstate->buf buffer.
167 * @param iq: iterator query state
168 * @return false. This is so this method can be used as the return value for
169 * the processState methods. (Transitioning to the final state
172 final_state(struct iter_qstate* iq)
174 return next_state(iq, iq->final_state);
178 * Callback routine to handle errors in parent query states
179 * @param qstate: query state that failed.
180 * @param id: module id.
181 * @param super: super state.
184 error_supers(struct module_qstate* qstate, int id, struct module_qstate* super)
186 struct iter_qstate* super_iq = (struct iter_qstate*)super->minfo[id];
188 if(qstate->qinfo.qtype == LDNS_RR_TYPE_A ||
189 qstate->qinfo.qtype == LDNS_RR_TYPE_AAAA) {
190 /* mark address as failed. */
191 struct delegpt_ns* dpns = NULL;
193 dpns = delegpt_find_ns(super_iq->dp,
194 qstate->qinfo.qname, qstate->qinfo.qname_len);
197 verbose(VERB_ALGO, "subq error, but not interested");
198 log_query_info(VERB_ALGO, "superq", &super->qinfo);
200 delegpt_log(VERB_ALGO, super_iq->dp);
204 /* see if the failure did get (parent-lame) info */
205 if(!cache_fill_missing(super->env,
206 super_iq->qchase.qclass, super->region,
208 log_err("out of memory adding missing");
210 dpns->resolved = 1; /* mark as failed */
211 super_iq->num_target_queries--;
213 if(qstate->qinfo.qtype == LDNS_RR_TYPE_NS) {
214 /* prime failed to get delegation */
217 /* evaluate targets again */
218 super_iq->state = QUERYTARGETS_STATE;
219 /* super becomes runnable, and will process this change */
223 * Return an error to the client
224 * @param qstate: our query state
225 * @param id: module id
226 * @param rcode: error code (DNS errcode).
227 * @return: 0 for use by caller, to make notation easy, like:
228 * return error_response(..).
231 error_response(struct module_qstate* qstate, int id, int rcode)
233 verbose(VERB_QUERY, "return error response %s",
234 sldns_lookup_by_id(sldns_rcodes, rcode)?
235 sldns_lookup_by_id(sldns_rcodes, rcode)->name:"??");
236 qstate->return_rcode = rcode;
237 qstate->return_msg = NULL;
238 qstate->ext_state[id] = module_finished;
243 * Return an error to the client and cache the error code in the
244 * message cache (so per qname, qtype, qclass).
245 * @param qstate: our query state
246 * @param id: module id
247 * @param rcode: error code (DNS errcode).
248 * @return: 0 for use by caller, to make notation easy, like:
249 * return error_response(..).
252 error_response_cache(struct module_qstate* qstate, int id, int rcode)
255 struct reply_info err;
256 memset(&err, 0, sizeof(err));
257 err.flags = (uint16_t)(BIT_QR | BIT_RA);
258 FLAGS_SET_RCODE(err.flags, rcode);
261 err.prefetch_ttl = PREFETCH_TTL_CALC(err.ttl);
262 /* do not waste time trying to validate this servfail */
263 err.security = sec_status_indeterminate;
264 verbose(VERB_ALGO, "store error response in message cache");
265 iter_dns_store(qstate->env, &qstate->qinfo, &err, 0, 0, 0, NULL);
266 return error_response(qstate, id, rcode);
269 /** check if prepend item is duplicate item */
271 prepend_is_duplicate(struct ub_packed_rrset_key** sets, size_t to,
272 struct ub_packed_rrset_key* dup)
275 for(i=0; i<to; i++) {
276 if(sets[i]->rk.type == dup->rk.type &&
277 sets[i]->rk.rrset_class == dup->rk.rrset_class &&
278 sets[i]->rk.dname_len == dup->rk.dname_len &&
279 query_dname_compare(sets[i]->rk.dname, dup->rk.dname)
286 /** prepend the prepend list in the answer and authority section of dns_msg */
288 iter_prepend(struct iter_qstate* iq, struct dns_msg* msg,
289 struct regional* region)
291 struct iter_prep_list* p;
292 struct ub_packed_rrset_key** sets;
293 size_t num_an = 0, num_ns = 0;;
294 for(p = iq->an_prepend_list; p; p = p->next)
296 for(p = iq->ns_prepend_list; p; p = p->next)
298 if(num_an + num_ns == 0)
300 verbose(VERB_ALGO, "prepending %d rrsets", (int)num_an + (int)num_ns);
301 sets = regional_alloc(region, (num_an+num_ns+msg->rep->rrset_count) *
302 sizeof(struct ub_packed_rrset_key*));
307 for(p = iq->an_prepend_list; p; p = p->next) {
308 sets[num_an++] = p->rrset;
310 memcpy(sets+num_an, msg->rep->rrsets, msg->rep->an_numrrsets *
311 sizeof(struct ub_packed_rrset_key*));
314 for(p = iq->ns_prepend_list; p; p = p->next) {
315 if(prepend_is_duplicate(sets+msg->rep->an_numrrsets+num_an,
316 num_ns, p->rrset) || prepend_is_duplicate(
317 msg->rep->rrsets+msg->rep->an_numrrsets,
318 msg->rep->ns_numrrsets, p->rrset))
320 sets[msg->rep->an_numrrsets + num_an + num_ns++] = p->rrset;
322 memcpy(sets + num_an + msg->rep->an_numrrsets + num_ns,
323 msg->rep->rrsets + msg->rep->an_numrrsets,
324 (msg->rep->ns_numrrsets + msg->rep->ar_numrrsets) *
325 sizeof(struct ub_packed_rrset_key*));
327 /* NXDOMAIN rcode can stay if we prepended DNAME/CNAMEs, because
328 * this is what recursors should give. */
329 msg->rep->rrset_count += num_an + num_ns;
330 msg->rep->an_numrrsets += num_an;
331 msg->rep->ns_numrrsets += num_ns;
332 msg->rep->rrsets = sets;
337 * Add rrset to ANSWER prepend list
338 * @param qstate: query state.
339 * @param iq: iterator query state.
340 * @param rrset: rrset to add.
341 * @return false on failure (malloc).
344 iter_add_prepend_answer(struct module_qstate* qstate, struct iter_qstate* iq,
345 struct ub_packed_rrset_key* rrset)
347 struct iter_prep_list* p = (struct iter_prep_list*)regional_alloc(
348 qstate->region, sizeof(struct iter_prep_list));
354 if(iq->an_prepend_last)
355 iq->an_prepend_last->next = p;
356 else iq->an_prepend_list = p;
357 iq->an_prepend_last = p;
362 * Add rrset to AUTHORITY prepend list
363 * @param qstate: query state.
364 * @param iq: iterator query state.
365 * @param rrset: rrset to add.
366 * @return false on failure (malloc).
369 iter_add_prepend_auth(struct module_qstate* qstate, struct iter_qstate* iq,
370 struct ub_packed_rrset_key* rrset)
372 struct iter_prep_list* p = (struct iter_prep_list*)regional_alloc(
373 qstate->region, sizeof(struct iter_prep_list));
379 if(iq->ns_prepend_last)
380 iq->ns_prepend_last->next = p;
381 else iq->ns_prepend_list = p;
382 iq->ns_prepend_last = p;
387 * Given a CNAME response (defined as a response containing a CNAME or DNAME
388 * that does not answer the request), process the response, modifying the
389 * state as necessary. This follows the CNAME/DNAME chain and returns the
392 * sets the new query name, after following the CNAME/DNAME chain.
393 * @param qstate: query state.
394 * @param iq: iterator query state.
395 * @param msg: the response.
396 * @param mname: returned target new query name.
397 * @param mname_len: length of mname.
398 * @return false on (malloc) error.
401 handle_cname_response(struct module_qstate* qstate, struct iter_qstate* iq,
402 struct dns_msg* msg, uint8_t** mname, size_t* mname_len)
405 /* Start with the (current) qname. */
406 *mname = iq->qchase.qname;
407 *mname_len = iq->qchase.qname_len;
409 /* Iterate over the ANSWER rrsets in order, looking for CNAMEs and
411 for(i=0; i<msg->rep->an_numrrsets; i++) {
412 struct ub_packed_rrset_key* r = msg->rep->rrsets[i];
413 /* If there is a (relevant) DNAME, add it to the list.
414 * We always expect there to be CNAME that was generated
415 * by this DNAME following, so we don't process the DNAME
417 if(ntohs(r->rk.type) == LDNS_RR_TYPE_DNAME &&
418 dname_strict_subdomain_c(*mname, r->rk.dname)) {
419 if(!iter_add_prepend_answer(qstate, iq, r))
424 if(ntohs(r->rk.type) == LDNS_RR_TYPE_CNAME &&
425 query_dname_compare(*mname, r->rk.dname) == 0) {
426 /* Add this relevant CNAME rrset to the prepend list.*/
427 if(!iter_add_prepend_answer(qstate, iq, r))
429 get_cname_target(r, mname, mname_len);
432 /* Other rrsets in the section are ignored. */
434 /* add authority rrsets to authority prepend, for wildcarded CNAMEs */
435 for(i=msg->rep->an_numrrsets; i<msg->rep->an_numrrsets +
436 msg->rep->ns_numrrsets; i++) {
437 struct ub_packed_rrset_key* r = msg->rep->rrsets[i];
438 /* only add NSEC/NSEC3, as they may be needed for validation */
439 if(ntohs(r->rk.type) == LDNS_RR_TYPE_NSEC ||
440 ntohs(r->rk.type) == LDNS_RR_TYPE_NSEC3) {
441 if(!iter_add_prepend_auth(qstate, iq, r))
449 * Generate a subrequest.
450 * Generate a local request event. Local events are tied to this module, and
451 * have a correponding (first tier) event that is waiting for this event to
452 * resolve to continue.
454 * @param qname The query name for this request.
455 * @param qnamelen length of qname
456 * @param qtype The query type for this request.
457 * @param qclass The query class for this request.
458 * @param qstate The event that is generating this event.
459 * @param id: module id.
460 * @param iq: The iterator state that is generating this event.
461 * @param initial_state The initial response state (normally this
462 * is QUERY_RESP_STATE, unless it is known that the request won't
463 * need iterative processing
464 * @param finalstate The final state for the response to this request.
465 * @param subq_ret: if newly allocated, the subquerystate, or NULL if it does
466 * not need initialisation.
467 * @param v: if true, validation is done on the subquery.
468 * @return false on error (malloc).
471 generate_sub_request(uint8_t* qname, size_t qnamelen, uint16_t qtype,
472 uint16_t qclass, struct module_qstate* qstate, int id,
473 struct iter_qstate* iq, enum iter_state initial_state,
474 enum iter_state finalstate, struct module_qstate** subq_ret, int v)
476 struct module_qstate* subq = NULL;
477 struct iter_qstate* subiq = NULL;
478 uint16_t qflags = 0; /* OPCODE QUERY, no flags */
479 struct query_info qinf;
480 int prime = (finalstate == PRIME_RESP_STATE)?1:0;
482 qinf.qname_len = qnamelen;
484 qinf.qclass = qclass;
486 /* RD should be set only when sending the query back through the INIT
488 if(initial_state == INIT_REQUEST_STATE)
490 /* We set the CD flag so we can send this through the "head" of
491 * the resolution chain, which might have a validator. We are
492 * uninterested in validating things not on the direct resolution
497 /* attach subquery, lookup existing or make a new one */
498 fptr_ok(fptr_whitelist_modenv_attach_sub(qstate->env->attach_sub));
499 if(!(*qstate->env->attach_sub)(qstate, &qinf, qflags, prime, &subq)) {
504 /* initialise the new subquery */
506 subq->ext_state[id] = module_state_initial;
507 subq->minfo[id] = regional_alloc(subq->region,
508 sizeof(struct iter_qstate));
509 if(!subq->minfo[id]) {
510 log_err("init subq: out of memory");
511 fptr_ok(fptr_whitelist_modenv_kill_sub(
512 qstate->env->kill_sub));
513 (*qstate->env->kill_sub)(subq);
516 subiq = (struct iter_qstate*)subq->minfo[id];
517 memset(subiq, 0, sizeof(*subiq));
518 subiq->num_target_queries = 0;
519 subiq->num_current_queries = 0;
520 subiq->depth = iq->depth+1;
521 outbound_list_init(&subiq->outlist);
522 subiq->state = initial_state;
523 subiq->final_state = finalstate;
524 subiq->qchase = subq->qinfo;
525 subiq->chase_flags = subq->query_flags;
526 subiq->refetch_glue = 0;
532 * Generate and send a root priming request.
533 * @param qstate: the qtstate that triggered the need to prime.
534 * @param iq: iterator query state.
535 * @param id: module id.
536 * @param qclass: the class to prime.
537 * @return 0 on failure
540 prime_root(struct module_qstate* qstate, struct iter_qstate* iq, int id,
544 struct module_qstate* subq;
545 verbose(VERB_DETAIL, "priming . %s NS",
546 sldns_lookup_by_id(sldns_rr_classes, (int)qclass)?
547 sldns_lookup_by_id(sldns_rr_classes, (int)qclass)->name:"??");
548 dp = hints_lookup_root(qstate->env->hints, qclass);
550 verbose(VERB_ALGO, "Cannot prime due to lack of hints");
553 /* Priming requests start at the QUERYTARGETS state, skipping
554 * the normal INIT state logic (which would cause an infloop). */
555 if(!generate_sub_request((uint8_t*)"\000", 1, LDNS_RR_TYPE_NS,
556 qclass, qstate, id, iq, QUERYTARGETS_STATE, PRIME_RESP_STATE,
558 verbose(VERB_ALGO, "could not prime root");
562 struct iter_qstate* subiq =
563 (struct iter_qstate*)subq->minfo[id];
564 /* Set the initial delegation point to the hint.
565 * copy dp, it is now part of the root prime query.
566 * dp was part of in the fixed hints structure. */
567 subiq->dp = delegpt_copy(dp, subq->region);
569 log_err("out of memory priming root, copydp");
570 fptr_ok(fptr_whitelist_modenv_kill_sub(
571 qstate->env->kill_sub));
572 (*qstate->env->kill_sub)(subq);
575 /* there should not be any target queries. */
576 subiq->num_target_queries = 0;
577 subiq->dnssec_expected = iter_indicates_dnssec(
578 qstate->env, subiq->dp, NULL, subq->qinfo.qclass);
581 /* this module stops, our submodule starts, and does the query. */
582 qstate->ext_state[id] = module_wait_subquery;
587 * Generate and process a stub priming request. This method tests for the
588 * need to prime a stub zone, so it is safe to call for every request.
590 * @param qstate: the qtstate that triggered the need to prime.
591 * @param iq: iterator query state.
592 * @param id: module id.
593 * @param qname: request name.
594 * @param qclass: request class.
595 * @return true if a priming subrequest was made, false if not. The will only
596 * issue a priming request if it detects an unprimed stub.
597 * Uses value of 2 to signal during stub-prime in root-prime situation
598 * that a noprime-stub is available and resolution can continue.
601 prime_stub(struct module_qstate* qstate, struct iter_qstate* iq, int id,
602 uint8_t* qname, uint16_t qclass)
604 /* Lookup the stub hint. This will return null if the stub doesn't
605 * need to be re-primed. */
606 struct iter_hints_stub* stub;
607 struct delegpt* stub_dp;
608 struct module_qstate* subq;
611 stub = hints_lookup_stub(qstate->env->hints, qname, qclass, iq->dp);
612 /* The stub (if there is one) does not need priming. */
617 /* is it a noprime stub (always use) */
620 if(iq->dp == NULL) r = 2;
621 /* copy the dp out of the fixed hints structure, so that
622 * it can be changed when servicing this query */
623 iq->dp = delegpt_copy(stub_dp, qstate->region);
625 log_err("out of memory priming stub");
626 (void)error_response(qstate, id, LDNS_RCODE_SERVFAIL);
627 return 1; /* return 1 to make module stop, with error */
629 log_nametypeclass(VERB_DETAIL, "use stub", stub_dp->name,
630 LDNS_RR_TYPE_NS, qclass);
634 /* Otherwise, we need to (re)prime the stub. */
635 log_nametypeclass(VERB_DETAIL, "priming stub", stub_dp->name,
636 LDNS_RR_TYPE_NS, qclass);
638 /* Stub priming events start at the QUERYTARGETS state to avoid the
639 * redundant INIT state processing. */
640 if(!generate_sub_request(stub_dp->name, stub_dp->namelen,
641 LDNS_RR_TYPE_NS, qclass, qstate, id, iq,
642 QUERYTARGETS_STATE, PRIME_RESP_STATE, &subq, 0)) {
643 verbose(VERB_ALGO, "could not prime stub");
644 (void)error_response(qstate, id, LDNS_RCODE_SERVFAIL);
645 return 1; /* return 1 to make module stop, with error */
648 struct iter_qstate* subiq =
649 (struct iter_qstate*)subq->minfo[id];
651 /* Set the initial delegation point to the hint. */
652 /* make copy to avoid use of stub dp by different qs/threads */
653 subiq->dp = delegpt_copy(stub_dp, subq->region);
655 log_err("out of memory priming stub, copydp");
656 fptr_ok(fptr_whitelist_modenv_kill_sub(
657 qstate->env->kill_sub));
658 (*qstate->env->kill_sub)(subq);
659 (void)error_response(qstate, id, LDNS_RCODE_SERVFAIL);
660 return 1; /* return 1 to make module stop, with error */
662 /* there should not be any target queries -- although there
663 * wouldn't be anyway, since stub hints never have
664 * missing targets. */
665 subiq->num_target_queries = 0;
666 subiq->wait_priming_stub = 1;
667 subiq->dnssec_expected = iter_indicates_dnssec(
668 qstate->env, subiq->dp, NULL, subq->qinfo.qclass);
671 /* this module stops, our submodule starts, and does the query. */
672 qstate->ext_state[id] = module_wait_subquery;
677 * Generate A and AAAA checks for glue that is in-zone for the referral
678 * we just got to obtain authoritative information on the adresses.
680 * @param qstate: the qtstate that triggered the need to prime.
681 * @param iq: iterator query state.
682 * @param id: module id.
685 generate_a_aaaa_check(struct module_qstate* qstate, struct iter_qstate* iq,
688 struct iter_env* ie = (struct iter_env*)qstate->env->modinfo[id];
689 struct module_qstate* subq;
691 struct reply_info* rep = iq->response->rep;
692 struct ub_packed_rrset_key* s;
695 if(iq->depth == ie->max_dependency_depth)
697 /* walk through additional, and check if in-zone,
698 * only relevant A, AAAA are left after scrub anyway */
699 for(i=rep->an_numrrsets+rep->ns_numrrsets; i<rep->rrset_count; i++) {
701 /* check *ALL* addresses that are transmitted in additional*/
702 /* is it an address ? */
703 if( !(ntohs(s->rk.type)==LDNS_RR_TYPE_A ||
704 ntohs(s->rk.type)==LDNS_RR_TYPE_AAAA)) {
707 /* is this query the same as the A/AAAA check for it */
708 if(qstate->qinfo.qtype == ntohs(s->rk.type) &&
709 qstate->qinfo.qclass == ntohs(s->rk.rrset_class) &&
710 query_dname_compare(qstate->qinfo.qname,
712 (qstate->query_flags&BIT_RD) &&
713 !(qstate->query_flags&BIT_CD))
716 /* generate subrequest for it */
717 log_nametypeclass(VERB_ALGO, "schedule addr fetch",
718 s->rk.dname, ntohs(s->rk.type),
719 ntohs(s->rk.rrset_class));
720 if(!generate_sub_request(s->rk.dname, s->rk.dname_len,
721 ntohs(s->rk.type), ntohs(s->rk.rrset_class),
723 INIT_REQUEST_STATE, FINISHED_STATE, &subq, 1)) {
724 verbose(VERB_ALGO, "could not generate addr check");
727 /* ignore subq - not need for more init */
732 * Generate a NS check request to obtain authoritative information
735 * @param qstate: the qtstate that triggered the need to prime.
736 * @param iq: iterator query state.
737 * @param id: module id.
740 generate_ns_check(struct module_qstate* qstate, struct iter_qstate* iq, int id)
742 struct iter_env* ie = (struct iter_env*)qstate->env->modinfo[id];
743 struct module_qstate* subq;
746 if(iq->depth == ie->max_dependency_depth)
748 /* is this query the same as the nscheck? */
749 if(qstate->qinfo.qtype == LDNS_RR_TYPE_NS &&
750 query_dname_compare(iq->dp->name, qstate->qinfo.qname)==0 &&
751 (qstate->query_flags&BIT_RD) && !(qstate->query_flags&BIT_CD)){
752 /* spawn off A, AAAA queries for in-zone glue to check */
753 generate_a_aaaa_check(qstate, iq, id);
757 log_nametypeclass(VERB_ALGO, "schedule ns fetch",
758 iq->dp->name, LDNS_RR_TYPE_NS, iq->qchase.qclass);
759 if(!generate_sub_request(iq->dp->name, iq->dp->namelen,
760 LDNS_RR_TYPE_NS, iq->qchase.qclass, qstate, id, iq,
761 INIT_REQUEST_STATE, FINISHED_STATE, &subq, 1)) {
762 verbose(VERB_ALGO, "could not generate ns check");
766 struct iter_qstate* subiq =
767 (struct iter_qstate*)subq->minfo[id];
769 /* make copy to avoid use of stub dp by different qs/threads */
770 /* refetch glue to start higher up the tree */
771 subiq->refetch_glue = 1;
772 subiq->dp = delegpt_copy(iq->dp, subq->region);
774 log_err("out of memory generating ns check, copydp");
775 fptr_ok(fptr_whitelist_modenv_kill_sub(
776 qstate->env->kill_sub));
777 (*qstate->env->kill_sub)(subq);
784 * Generate a DNSKEY prefetch query to get the DNSKEY for the DS record we
785 * just got in a referral (where we have dnssec_expected, thus have trust
786 * anchors above it). Note that right after calling this routine the
787 * iterator detached subqueries (because of following the referral), and thus
788 * the DNSKEY query becomes detached, its return stored in the cache for
789 * later lookup by the validator. This cache lookup by the validator avoids
790 * the roundtrip incurred by the DNSKEY query. The DNSKEY query is now
791 * performed at about the same time the original query is sent to the domain,
792 * thus the two answers are likely to be returned at about the same time,
793 * saving a roundtrip from the validated lookup.
795 * @param qstate: the qtstate that triggered the need to prime.
796 * @param iq: iterator query state.
797 * @param id: module id.
800 generate_dnskey_prefetch(struct module_qstate* qstate,
801 struct iter_qstate* iq, int id)
803 struct module_qstate* subq;
806 /* is this query the same as the prefetch? */
807 if(qstate->qinfo.qtype == LDNS_RR_TYPE_DNSKEY &&
808 query_dname_compare(iq->dp->name, qstate->qinfo.qname)==0 &&
809 (qstate->query_flags&BIT_RD) && !(qstate->query_flags&BIT_CD)){
813 /* if the DNSKEY is in the cache this lookup will stop quickly */
814 log_nametypeclass(VERB_ALGO, "schedule dnskey prefetch",
815 iq->dp->name, LDNS_RR_TYPE_DNSKEY, iq->qchase.qclass);
816 if(!generate_sub_request(iq->dp->name, iq->dp->namelen,
817 LDNS_RR_TYPE_DNSKEY, iq->qchase.qclass, qstate, id, iq,
818 INIT_REQUEST_STATE, FINISHED_STATE, &subq, 0)) {
819 /* we'll be slower, but it'll work */
820 verbose(VERB_ALGO, "could not generate dnskey prefetch");
824 struct iter_qstate* subiq =
825 (struct iter_qstate*)subq->minfo[id];
826 /* this qstate has the right delegation for the dnskey lookup*/
827 /* make copy to avoid use of stub dp by different qs/threads */
828 subiq->dp = delegpt_copy(iq->dp, subq->region);
829 /* if !subiq->dp, it'll start from the cache, no problem */
834 * See if the query needs forwarding.
836 * @param qstate: query state.
837 * @param iq: iterator query state.
838 * @return true if the request is forwarded, false if not.
839 * If returns true but, iq->dp is NULL then a malloc failure occurred.
842 forward_request(struct module_qstate* qstate, struct iter_qstate* iq)
845 uint8_t* delname = iq->qchase.qname;
846 size_t delnamelen = iq->qchase.qname_len;
847 if(iq->refetch_glue) {
848 delname = iq->dp->name;
849 delnamelen = iq->dp->namelen;
851 /* strip one label off of DS query to lookup higher for it */
852 if( (iq->qchase.qtype == LDNS_RR_TYPE_DS || iq->refetch_glue)
853 && !dname_is_root(iq->qchase.qname))
854 dname_remove_label(&delname, &delnamelen);
855 dp = forwards_lookup(qstate->env->fwds, delname, iq->qchase.qclass);
858 /* send recursion desired to forward addr */
859 iq->chase_flags |= BIT_RD;
860 iq->dp = delegpt_copy(dp, qstate->region);
861 /* iq->dp checked by caller */
862 verbose(VERB_ALGO, "forwarding request");
867 * Process the initial part of the request handling. This state roughly
868 * corresponds to resolver algorithms steps 1 (find answer in cache) and 2
869 * (find the best servers to ask).
871 * Note that all requests start here, and query restarts revisit this state.
873 * This state either generates: 1) a response, from cache or error, 2) a
874 * priming event, or 3) forwards the request to the next state (init2,
877 * @param qstate: query state.
878 * @param iq: iterator query state.
879 * @param ie: iterator shared global environment.
880 * @param id: module id.
881 * @return true if the event needs more request processing immediately,
885 processInitRequest(struct module_qstate* qstate, struct iter_qstate* iq,
886 struct iter_env* ie, int id)
892 log_query_info(VERB_DETAIL, "resolving", &qstate->qinfo);
895 /* We enforce a maximum number of query restarts. This is primarily a
896 * cheap way to prevent CNAME loops. */
897 if(iq->query_restart_count > MAX_RESTART_COUNT) {
898 verbose(VERB_QUERY, "request has exceeded the maximum number"
899 " of query restarts with %d", iq->query_restart_count);
900 return error_response(qstate, id, LDNS_RCODE_SERVFAIL);
903 /* We enforce a maximum recursion/dependency depth -- in general,
904 * this is unnecessary for dependency loops (although it will
905 * catch those), but it provides a sensible limit to the amount
906 * of work required to answer a given query. */
907 verbose(VERB_ALGO, "request has dependency depth of %d", iq->depth);
908 if(iq->depth > ie->max_dependency_depth) {
909 verbose(VERB_QUERY, "request has exceeded the maximum "
910 "dependency depth with depth of %d", iq->depth);
911 return error_response(qstate, id, LDNS_RCODE_SERVFAIL);
914 /* If the request is qclass=ANY, setup to generate each class */
915 if(qstate->qinfo.qclass == LDNS_RR_CLASS_ANY) {
916 iq->qchase.qclass = 0;
917 return next_state(iq, COLLECT_CLASS_STATE);
920 /* Resolver Algorithm Step 1 -- Look for the answer in local data. */
922 /* This either results in a query restart (CNAME cache response), a
923 * terminating response (ANSWER), or a cache miss (null). */
925 if(qstate->blacklist) {
926 /* if cache, or anything else, was blacklisted then
927 * getting older results from cache is a bad idea, no cache */
928 verbose(VERB_ALGO, "cache blacklisted, going to the network");
931 msg = dns_cache_lookup(qstate->env, iq->qchase.qname,
932 iq->qchase.qname_len, iq->qchase.qtype,
933 iq->qchase.qclass, qstate->region, qstate->env->scratch);
934 if(!msg && qstate->env->neg_cache) {
935 /* lookup in negative cache; may result in
936 * NOERROR/NODATA or NXDOMAIN answers that need validation */
937 msg = val_neg_getmsg(qstate->env->neg_cache, &iq->qchase,
938 qstate->region, qstate->env->rrset_cache,
939 qstate->env->scratch_buffer,
940 *qstate->env->now, 1/*add SOA*/, NULL);
942 /* item taken from cache does not match our query name, thus
943 * security needs to be re-examined later */
944 if(msg && query_dname_compare(qstate->qinfo.qname,
945 iq->qchase.qname) != 0)
946 msg->rep->security = sec_status_unchecked;
949 /* handle positive cache response */
950 enum response_type type = response_type_from_cache(msg,
952 if(verbosity >= VERB_ALGO) {
953 log_dns_msg("msg from cache lookup", &msg->qinfo,
955 verbose(VERB_ALGO, "msg ttl is %d, prefetch ttl %d",
957 (int)msg->rep->prefetch_ttl);
960 if(type == RESPONSE_TYPE_CNAME) {
963 verbose(VERB_ALGO, "returning CNAME response from "
965 if(!handle_cname_response(qstate, iq, msg,
967 return error_response(qstate, id,
968 LDNS_RCODE_SERVFAIL);
969 iq->qchase.qname = sname;
970 iq->qchase.qname_len = slen;
971 /* This *is* a query restart, even if it is a cheap
974 iq->refetch_glue = 0;
975 iq->query_restart_count++;
977 sock_list_insert(&qstate->reply_origin, NULL, 0, qstate->region);
978 return next_state(iq, INIT_REQUEST_STATE);
981 /* if from cache, NULL, else insert 'cache IP' len=0 */
982 if(qstate->reply_origin)
983 sock_list_insert(&qstate->reply_origin, NULL, 0, qstate->region);
984 /* it is an answer, response, to final state */
985 verbose(VERB_ALGO, "returning answer from cache.");
987 return final_state(iq);
990 /* attempt to forward the request */
991 if(forward_request(qstate, iq))
994 log_err("alloc failure for forward dp");
995 return error_response(qstate, id, LDNS_RCODE_SERVFAIL);
997 iq->refetch_glue = 0;
998 /* the request has been forwarded.
999 * forwarded requests need to be immediately sent to the
1000 * next state, QUERYTARGETS. */
1001 return next_state(iq, QUERYTARGETS_STATE);
1004 /* Resolver Algorithm Step 2 -- find the "best" servers. */
1006 /* first, adjust for DS queries. To avoid the grandparent problem,
1007 * we just look for the closest set of server to the parent of qname.
1008 * When re-fetching glue we also need to ask the parent.
1010 if(iq->refetch_glue) {
1012 log_err("internal or malloc fail: no dp for refetch");
1013 return error_response(qstate, id, LDNS_RCODE_SERVFAIL);
1015 delname = iq->dp->name;
1016 delnamelen = iq->dp->namelen;
1018 delname = iq->qchase.qname;
1019 delnamelen = iq->qchase.qname_len;
1021 if(iq->qchase.qtype == LDNS_RR_TYPE_DS || iq->refetch_glue ||
1022 (iq->qchase.qtype == LDNS_RR_TYPE_NS && qstate->prefetch_leeway)) {
1023 /* remove first label from delname, root goes to hints,
1024 * but only to fetch glue, not for qtype=DS. */
1025 /* also when prefetching an NS record, fetch it again from
1026 * its parent, just as if it expired, so that you do not
1027 * get stuck on an older nameserver that gives old NSrecords */
1028 if(dname_is_root(delname) && (iq->refetch_glue ||
1029 (iq->qchase.qtype == LDNS_RR_TYPE_NS &&
1030 qstate->prefetch_leeway)))
1031 delname = NULL; /* go to root priming */
1032 else dname_remove_label(&delname, &delnamelen);
1034 /* delname is the name to lookup a delegation for. If NULL rootprime */
1037 /* Lookup the delegation in the cache. If null, then the
1038 * cache needs to be primed for the qclass. */
1040 iq->dp = dns_cache_find_delegation(qstate->env, delname,
1041 delnamelen, iq->qchase.qtype, iq->qchase.qclass,
1042 qstate->region, &iq->deleg_msg,
1043 *qstate->env->now+qstate->prefetch_leeway);
1046 /* If the cache has returned nothing, then we have a
1047 * root priming situation. */
1048 if(iq->dp == NULL) {
1049 /* if there is a stub, then no root prime needed */
1050 int r = prime_stub(qstate, iq, id, delname,
1053 break; /* got noprime-stub-zone, continue */
1055 return 0; /* stub prime request made */
1056 if(forwards_lookup_root(qstate->env->fwds,
1057 iq->qchase.qclass)) {
1058 /* forward zone root, no root prime needed */
1059 /* fill in some dp - safety belt */
1060 iq->dp = hints_lookup_root(qstate->env->hints,
1063 log_err("internal error: no hints dp");
1064 return error_response(qstate, id,
1065 LDNS_RCODE_SERVFAIL);
1067 iq->dp = delegpt_copy(iq->dp, qstate->region);
1069 log_err("out of memory in safety belt");
1070 return error_response(qstate, id,
1071 LDNS_RCODE_SERVFAIL);
1073 return next_state(iq, INIT_REQUEST_2_STATE);
1075 /* Note that the result of this will set a new
1076 * DelegationPoint based on the result of priming. */
1077 if(!prime_root(qstate, iq, id, iq->qchase.qclass))
1078 return error_response(qstate, id,
1079 LDNS_RCODE_REFUSED);
1081 /* priming creates and sends a subordinate query, with
1082 * this query as the parent. So further processing for
1083 * this event will stop until reactivated by the
1084 * results of priming. */
1088 /* see if this dp not useless.
1090 * o all NS items are required glue.
1091 * or the query is for NS item that is required glue.
1092 * o no addresses are provided.
1094 * Instead, go up one level, and try to get even further
1095 * If the root was useless, use safety belt information.
1096 * Only check cache returns, because replies for servers
1097 * could be useless but lead to loops (bumping into the
1098 * same server reply) if useless-checked.
1100 if(iter_dp_is_useless(&qstate->qinfo, qstate->query_flags,
1102 if(dname_is_root(iq->dp->name)) {
1103 /* use safety belt */
1104 verbose(VERB_QUERY, "Cache has root NS but "
1105 "no addresses. Fallback to the safety belt.");
1106 iq->dp = hints_lookup_root(qstate->env->hints,
1108 /* note deleg_msg is from previous lookup,
1109 * but RD is on, so it is not used */
1111 log_err("internal error: no hints dp");
1112 return error_response(qstate, id,
1113 LDNS_RCODE_REFUSED);
1115 iq->dp = delegpt_copy(iq->dp, qstate->region);
1117 log_err("out of memory in safety belt");
1118 return error_response(qstate, id,
1119 LDNS_RCODE_SERVFAIL);
1124 "cache delegation was useless:");
1125 delegpt_log(VERB_ALGO, iq->dp);
1127 delname = iq->dp->name;
1128 delnamelen = iq->dp->namelen;
1129 dname_remove_label(&delname, &delnamelen);
1134 verbose(VERB_ALGO, "cache delegation returns delegpt");
1135 delegpt_log(VERB_ALGO, iq->dp);
1137 /* Otherwise, set the current delegation point and move on to the
1139 return next_state(iq, INIT_REQUEST_2_STATE);
1143 * Process the second part of the initial request handling. This state
1144 * basically exists so that queries that generate root priming events have
1145 * the same init processing as ones that do not. Request events that reach
1146 * this state must have a valid currentDelegationPoint set.
1148 * This part is primarly handling stub zone priming. Events that reach this
1149 * state must have a current delegation point.
1151 * @param qstate: query state.
1152 * @param iq: iterator query state.
1153 * @param id: module id.
1154 * @return true if the event needs more request processing immediately,
1158 processInitRequest2(struct module_qstate* qstate, struct iter_qstate* iq,
1163 log_query_info(VERB_QUERY, "resolving (init part 2): ",
1166 if(iq->refetch_glue) {
1168 log_err("internal or malloc fail: no dp for refetch");
1169 return error_response(qstate, id, LDNS_RCODE_SERVFAIL);
1171 delname = iq->dp->name;
1172 delnamelen = iq->dp->namelen;
1174 delname = iq->qchase.qname;
1175 delnamelen = iq->qchase.qname_len;
1177 if(iq->qchase.qtype == LDNS_RR_TYPE_DS || iq->refetch_glue) {
1178 if(!dname_is_root(delname))
1179 dname_remove_label(&delname, &delnamelen);
1180 iq->refetch_glue = 0; /* if CNAME causes restart, no refetch */
1182 /* Check to see if we need to prime a stub zone. */
1183 if(prime_stub(qstate, iq, id, delname, iq->qchase.qclass)) {
1184 /* A priming sub request was made */
1188 /* most events just get forwarded to the next state. */
1189 return next_state(iq, INIT_REQUEST_3_STATE);
1193 * Process the third part of the initial request handling. This state exists
1194 * as a separate state so that queries that generate stub priming events
1195 * will get the tail end of the init process but not repeat the stub priming
1198 * @param qstate: query state.
1199 * @param iq: iterator query state.
1200 * @param id: module id.
1201 * @return true, advancing the event to the QUERYTARGETS_STATE.
1204 processInitRequest3(struct module_qstate* qstate, struct iter_qstate* iq,
1207 log_query_info(VERB_QUERY, "resolving (init part 3): ",
1209 /* if the cache reply dp equals a validation anchor or msg has DS,
1210 * then DNSSEC RRSIGs are expected in the reply */
1211 iq->dnssec_expected = iter_indicates_dnssec(qstate->env, iq->dp,
1212 iq->deleg_msg, iq->qchase.qclass);
1214 /* If the RD flag wasn't set, then we just finish with the
1215 * cached referral as the response. */
1216 if(!(qstate->query_flags & BIT_RD)) {
1217 iq->response = iq->deleg_msg;
1218 if(verbosity >= VERB_ALGO && iq->response)
1219 log_dns_msg("no RD requested, using delegation msg",
1220 &iq->response->qinfo, iq->response->rep);
1221 if(qstate->reply_origin)
1222 sock_list_insert(&qstate->reply_origin, NULL, 0, qstate->region);
1223 return final_state(iq);
1225 /* After this point, unset the RD flag -- this query is going to
1226 * be sent to an auth. server. */
1227 iq->chase_flags &= ~BIT_RD;
1229 /* if dnssec expected, fetch key for the trust-anchor or cached-DS */
1230 if(iq->dnssec_expected && qstate->env->cfg->prefetch_key &&
1231 !(qstate->query_flags&BIT_CD)) {
1232 generate_dnskey_prefetch(qstate, iq, id);
1233 fptr_ok(fptr_whitelist_modenv_detach_subs(
1234 qstate->env->detach_subs));
1235 (*qstate->env->detach_subs)(qstate);
1238 /* Jump to the next state. */
1239 return next_state(iq, QUERYTARGETS_STATE);
1243 * Given a basic query, generate a parent-side "target" query.
1244 * These are subordinate queries for missing delegation point target addresses,
1245 * for which only the parent of the delegation provides correct IP addresses.
1247 * @param qstate: query state.
1248 * @param iq: iterator query state.
1249 * @param id: module id.
1250 * @param name: target qname.
1251 * @param namelen: target qname length.
1252 * @param qtype: target qtype (either A or AAAA).
1253 * @param qclass: target qclass.
1254 * @return true on success, false on failure.
1257 generate_parentside_target_query(struct module_qstate* qstate,
1258 struct iter_qstate* iq, int id, uint8_t* name, size_t namelen,
1259 uint16_t qtype, uint16_t qclass)
1261 struct module_qstate* subq;
1262 if(!generate_sub_request(name, namelen, qtype, qclass, qstate,
1263 id, iq, INIT_REQUEST_STATE, FINISHED_STATE, &subq, 0))
1266 struct iter_qstate* subiq =
1267 (struct iter_qstate*)subq->minfo[id];
1268 /* blacklist the cache - we want to fetch parent stuff */
1269 sock_list_insert(&subq->blacklist, NULL, 0, subq->region);
1270 subiq->query_for_pside_glue = 1;
1271 if(dname_subdomain_c(name, iq->dp->name)) {
1272 subiq->dp = delegpt_copy(iq->dp, subq->region);
1273 subiq->dnssec_expected = iter_indicates_dnssec(
1274 qstate->env, subiq->dp, NULL,
1275 subq->qinfo.qclass);
1276 subiq->refetch_glue = 1;
1278 subiq->dp = dns_cache_find_delegation(qstate->env,
1279 name, namelen, qtype, qclass, subq->region,
1281 *qstate->env->now+subq->prefetch_leeway);
1282 /* if no dp, then it's from root, refetch unneeded */
1284 subiq->dnssec_expected = iter_indicates_dnssec(
1285 qstate->env, subiq->dp, NULL,
1286 subq->qinfo.qclass);
1287 subiq->refetch_glue = 1;
1291 log_nametypeclass(VERB_QUERY, "new pside target", name, qtype, qclass);
1296 * Given a basic query, generate a "target" query. These are subordinate
1297 * queries for missing delegation point target addresses.
1299 * @param qstate: query state.
1300 * @param iq: iterator query state.
1301 * @param id: module id.
1302 * @param name: target qname.
1303 * @param namelen: target qname length.
1304 * @param qtype: target qtype (either A or AAAA).
1305 * @param qclass: target qclass.
1306 * @return true on success, false on failure.
1309 generate_target_query(struct module_qstate* qstate, struct iter_qstate* iq,
1310 int id, uint8_t* name, size_t namelen, uint16_t qtype, uint16_t qclass)
1312 struct module_qstate* subq;
1313 if(!generate_sub_request(name, namelen, qtype, qclass, qstate,
1314 id, iq, INIT_REQUEST_STATE, FINISHED_STATE, &subq, 0))
1316 log_nametypeclass(VERB_QUERY, "new target", name, qtype, qclass);
1321 * Given an event at a certain state, generate zero or more target queries
1322 * for it's current delegation point.
1324 * @param qstate: query state.
1325 * @param iq: iterator query state.
1326 * @param ie: iterator shared global environment.
1327 * @param id: module id.
1328 * @param maxtargets: The maximum number of targets to query for.
1329 * if it is negative, there is no maximum number of targets.
1330 * @param num: returns the number of queries generated and processed,
1331 * which may be zero if there were no missing targets.
1332 * @return false on error.
1335 query_for_targets(struct module_qstate* qstate, struct iter_qstate* iq,
1336 struct iter_env* ie, int id, int maxtargets, int* num)
1338 int query_count = 0;
1339 struct delegpt_ns* ns;
1343 if(iq->depth == ie->max_dependency_depth)
1346 iter_mark_cycle_targets(qstate, iq->dp);
1347 missing = (int)delegpt_count_missing_targets(iq->dp);
1348 log_assert(maxtargets != 0); /* that would not be useful */
1350 /* Generate target requests. Basically, any missing targets
1351 * are queried for here, regardless if it is necessary to do
1352 * so to continue processing. */
1353 if(maxtargets < 0 || maxtargets > missing)
1355 else toget = maxtargets;
1360 /* select 'toget' items from the total of 'missing' items */
1361 log_assert(toget <= missing);
1363 /* loop over missing targets */
1364 for(ns = iq->dp->nslist; ns; ns = ns->next) {
1368 /* randomly select this item with probability toget/missing */
1369 if(!iter_ns_probability(qstate->env->rnd, toget, missing)) {
1370 /* do not select this one, next; select toget number
1371 * of items from a list one less in size */
1376 if(ie->supports_ipv6 && !ns->got6) {
1377 /* Send the AAAA request. */
1378 if(!generate_target_query(qstate, iq, id,
1379 ns->name, ns->namelen,
1380 LDNS_RR_TYPE_AAAA, iq->qchase.qclass)) {
1383 qstate->ext_state[id] = module_wait_subquery;
1388 /* Send the A request. */
1389 if(ie->supports_ipv4 && !ns->got4) {
1390 if(!generate_target_query(qstate, iq, id,
1391 ns->name, ns->namelen,
1392 LDNS_RR_TYPE_A, iq->qchase.qclass)) {
1395 qstate->ext_state[id] = module_wait_subquery;
1401 /* mark this target as in progress. */
1410 qstate->ext_state[id] = module_wait_subquery;
1415 /** see if last resort is possible - does config allow queries to parent */
1417 can_have_last_resort(struct module_env* env, struct delegpt* dp,
1418 struct iter_qstate* iq)
1420 struct delegpt* fwddp;
1421 struct iter_hints_stub* stub;
1422 /* do not process a last resort (the parent side) if a stub
1423 * or forward is configured, because we do not want to go 'above'
1424 * the configured servers */
1425 if(!dname_is_root(dp->name) && (stub = (struct iter_hints_stub*)
1426 name_tree_find(&env->hints->tree, dp->name, dp->namelen,
1427 dp->namelabs, iq->qchase.qclass)) &&
1428 /* has_parent side is turned off for stub_first, where we
1429 * are allowed to go to the parent */
1430 stub->dp->has_parent_side_NS) {
1431 verbose(VERB_QUERY, "configured stub servers failed -- returning SERVFAIL");
1434 if((fwddp = forwards_find(env->fwds, dp->name, iq->qchase.qclass)) &&
1435 /* has_parent_side is turned off for forward_first, where
1436 * we are allowed to go to the parent */
1437 fwddp->has_parent_side_NS) {
1438 verbose(VERB_QUERY, "configured forward servers failed -- returning SERVFAIL");
1445 * Called by processQueryTargets when it would like extra targets to query
1446 * but it seems to be out of options. At last resort some less appealing
1447 * options are explored. If there are no more options, the result is SERVFAIL
1449 * @param qstate: query state.
1450 * @param iq: iterator query state.
1451 * @param ie: iterator shared global environment.
1452 * @param id: module id.
1453 * @return true if the event requires more request processing immediately,
1457 processLastResort(struct module_qstate* qstate, struct iter_qstate* iq,
1458 struct iter_env* ie, int id)
1460 struct delegpt_ns* ns;
1461 int query_count = 0;
1462 verbose(VERB_ALGO, "No more query targets, attempting last resort");
1465 if(!can_have_last_resort(qstate->env, iq->dp, iq)) {
1466 /* fail -- no more targets, no more hope of targets, no hope
1468 return error_response_cache(qstate, id, LDNS_RCODE_SERVFAIL);
1470 if(!iq->dp->has_parent_side_NS && dname_is_root(iq->dp->name)) {
1471 struct delegpt* p = hints_lookup_root(qstate->env->hints,
1474 struct delegpt_ns* ns;
1475 struct delegpt_addr* a;
1476 iq->chase_flags &= ~BIT_RD; /* go to authorities */
1477 for(ns = p->nslist; ns; ns=ns->next) {
1478 (void)delegpt_add_ns(iq->dp, qstate->region,
1479 ns->name, ns->lame);
1481 for(a = p->target_list; a; a=a->next_target) {
1482 (void)delegpt_add_addr(iq->dp, qstate->region,
1483 &a->addr, a->addrlen, a->bogus,
1487 iq->dp->has_parent_side_NS = 1;
1488 } else if(!iq->dp->has_parent_side_NS) {
1489 if(!iter_lookup_parent_NS_from_cache(qstate->env, iq->dp,
1490 qstate->region, &qstate->qinfo)
1491 || !iq->dp->has_parent_side_NS) {
1492 /* if: malloc failure in lookup go up to try */
1493 /* if: no parent NS in cache - go up one level */
1494 verbose(VERB_ALGO, "try to grab parent NS");
1495 iq->store_parent_NS = iq->dp;
1496 iq->chase_flags &= ~BIT_RD; /* go to authorities */
1497 iq->deleg_msg = NULL;
1498 iq->refetch_glue = 1;
1499 iq->query_restart_count++;
1501 return next_state(iq, INIT_REQUEST_STATE);
1504 /* see if that makes new names available */
1505 if(!cache_fill_missing(qstate->env, iq->qchase.qclass,
1506 qstate->region, iq->dp))
1507 log_err("out of memory in cache_fill_missing");
1508 if(iq->dp->usable_list) {
1509 verbose(VERB_ALGO, "try parent-side-name, w. glue from cache");
1510 return next_state(iq, QUERYTARGETS_STATE);
1512 /* try to fill out parent glue from cache */
1513 if(iter_lookup_parent_glue_from_cache(qstate->env, iq->dp,
1514 qstate->region, &qstate->qinfo)) {
1515 /* got parent stuff from cache, see if we can continue */
1516 verbose(VERB_ALGO, "try parent-side glue from cache");
1517 return next_state(iq, QUERYTARGETS_STATE);
1519 /* query for an extra name added by the parent-NS record */
1520 if(delegpt_count_missing_targets(iq->dp) > 0) {
1522 verbose(VERB_ALGO, "try parent-side target name");
1523 if(!query_for_targets(qstate, iq, ie, id, 1, &qs)) {
1524 return error_response(qstate, id, LDNS_RCODE_SERVFAIL);
1526 iq->num_target_queries += qs;
1528 qstate->ext_state[id] = module_wait_subquery;
1529 return 0; /* and wait for them */
1532 if(iq->depth == ie->max_dependency_depth) {
1533 verbose(VERB_QUERY, "maxdepth and need more nameservers, fail");
1534 return error_response_cache(qstate, id, LDNS_RCODE_SERVFAIL);
1536 /* mark cycle targets for parent-side lookups */
1537 iter_mark_pside_cycle_targets(qstate, iq->dp);
1538 /* see if we can issue queries to get nameserver addresses */
1539 /* this lookup is not randomized, but sequential. */
1540 for(ns = iq->dp->nslist; ns; ns = ns->next) {
1541 /* query for parent-side A and AAAA for nameservers */
1542 if(ie->supports_ipv6 && !ns->done_pside6) {
1543 /* Send the AAAA request. */
1544 if(!generate_parentside_target_query(qstate, iq, id,
1545 ns->name, ns->namelen,
1546 LDNS_RR_TYPE_AAAA, iq->qchase.qclass))
1547 return error_response(qstate, id,
1548 LDNS_RCODE_SERVFAIL);
1549 ns->done_pside6 = 1;
1552 if(ie->supports_ipv4 && !ns->done_pside4) {
1553 /* Send the A request. */
1554 if(!generate_parentside_target_query(qstate, iq, id,
1555 ns->name, ns->namelen,
1556 LDNS_RR_TYPE_A, iq->qchase.qclass))
1557 return error_response(qstate, id,
1558 LDNS_RCODE_SERVFAIL);
1559 ns->done_pside4 = 1;
1562 if(query_count != 0) { /* suspend to await results */
1563 verbose(VERB_ALGO, "try parent-side glue lookup");
1564 iq->num_target_queries += query_count;
1565 qstate->ext_state[id] = module_wait_subquery;
1570 /* if this was a parent-side glue query itself, then store that
1571 * failure in cache. */
1572 if(iq->query_for_pside_glue && !iq->pside_glue)
1573 iter_store_parentside_neg(qstate->env, &qstate->qinfo,
1574 iq->deleg_msg?iq->deleg_msg->rep:
1575 (iq->response?iq->response->rep:NULL));
1577 verbose(VERB_QUERY, "out of query targets -- returning SERVFAIL");
1578 /* fail -- no more targets, no more hope of targets, no hope
1580 return error_response_cache(qstate, id, LDNS_RCODE_SERVFAIL);
1584 * Try to find the NS record set that will resolve a qtype DS query. Due
1585 * to grandparent/grandchild reasons we did not get a proper lookup right
1586 * away. We need to create type NS queries until we get the right parent
1587 * for this lookup. We remove labels from the query to find the right point.
1588 * If we end up at the old dp name, then there is no solution.
1590 * @param qstate: query state.
1591 * @param iq: iterator query state.
1592 * @param id: module id.
1593 * @return true if the event requires more immediate processing, false if
1594 * not. This is generally only true when forwarding the request to
1595 * the final state (i.e., on answer).
1598 processDSNSFind(struct module_qstate* qstate, struct iter_qstate* iq, int id)
1600 struct module_qstate* subq = NULL;
1601 verbose(VERB_ALGO, "processDSNSFind");
1603 if(!iq->dsns_point) {
1605 iq->dsns_point = iq->qchase.qname;
1606 iq->dsns_point_len = iq->qchase.qname_len;
1608 /* robustcheck for internal error: we are not underneath the dp */
1609 if(!dname_subdomain_c(iq->dsns_point, iq->dp->name)) {
1610 return error_response_cache(qstate, id, LDNS_RCODE_SERVFAIL);
1613 /* go up one (more) step, until we hit the dp, if so, end */
1614 dname_remove_label(&iq->dsns_point, &iq->dsns_point_len);
1615 if(query_dname_compare(iq->dsns_point, iq->dp->name) == 0) {
1616 /* there was no inbetween nameserver, use the old delegation
1617 * point again. And this time, because dsns_point is nonNULL
1618 * we are going to accept the (bad) result */
1619 iq->state = QUERYTARGETS_STATE;
1622 iq->state = DSNS_FIND_STATE;
1624 /* spawn NS lookup (validation not needed, this is for DS lookup) */
1625 log_nametypeclass(VERB_ALGO, "fetch nameservers",
1626 iq->dsns_point, LDNS_RR_TYPE_NS, iq->qchase.qclass);
1627 if(!generate_sub_request(iq->dsns_point, iq->dsns_point_len,
1628 LDNS_RR_TYPE_NS, iq->qchase.qclass, qstate, id, iq,
1629 INIT_REQUEST_STATE, FINISHED_STATE, &subq, 0)) {
1630 return error_response_cache(qstate, id, LDNS_RCODE_SERVFAIL);
1637 * This is the request event state where the request will be sent to one of
1638 * its current query targets. This state also handles issuing target lookup
1639 * queries for missing target IP addresses. Queries typically iterate on
1640 * this state, both when they are just trying different targets for a given
1641 * delegation point, and when they change delegation points. This state
1642 * roughly corresponds to RFC 1034 algorithm steps 3 and 4.
1644 * @param qstate: query state.
1645 * @param iq: iterator query state.
1646 * @param ie: iterator shared global environment.
1647 * @param id: module id.
1648 * @return true if the event requires more request processing immediately,
1649 * false if not. This state only returns true when it is generating
1650 * a SERVFAIL response because the query has hit a dead end.
1653 processQueryTargets(struct module_qstate* qstate, struct iter_qstate* iq,
1654 struct iter_env* ie, int id)
1657 struct delegpt_addr* target;
1658 struct outbound_entry* outq;
1660 /* NOTE: a request will encounter this state for each target it
1661 * needs to send a query to. That is, at least one per referral,
1662 * more if some targets timeout or return throwaway answers. */
1664 log_query_info(VERB_QUERY, "processQueryTargets:", &qstate->qinfo);
1665 verbose(VERB_ALGO, "processQueryTargets: targetqueries %d, "
1666 "currentqueries %d sentcount %d", iq->num_target_queries,
1667 iq->num_current_queries, iq->sent_count);
1669 /* Make sure that we haven't run away */
1670 /* FIXME: is this check even necessary? */
1671 if(iq->referral_count > MAX_REFERRAL_COUNT) {
1672 verbose(VERB_QUERY, "request has exceeded the maximum "
1673 "number of referrrals with %d", iq->referral_count);
1674 return error_response(qstate, id, LDNS_RCODE_SERVFAIL);
1676 if(iq->sent_count > MAX_SENT_COUNT) {
1677 verbose(VERB_QUERY, "request has exceeded the maximum "
1678 "number of sends with %d", iq->sent_count);
1679 return error_response(qstate, id, LDNS_RCODE_SERVFAIL);
1682 /* Make sure we have a delegation point, otherwise priming failed
1683 * or another failure occurred */
1685 verbose(VERB_QUERY, "Failed to get a delegation, giving up");
1686 return error_response(qstate, id, LDNS_RCODE_SERVFAIL);
1688 if(!ie->supports_ipv6)
1689 delegpt_no_ipv6(iq->dp);
1690 if(!ie->supports_ipv4)
1691 delegpt_no_ipv4(iq->dp);
1692 delegpt_log(VERB_ALGO, iq->dp);
1694 if(iq->num_current_queries>0) {
1695 /* already busy answering a query, this restart is because
1696 * more delegpt addrs became available, wait for existing
1698 verbose(VERB_ALGO, "woke up, but wait for outstanding query");
1699 qstate->ext_state[id] = module_wait_reply;
1704 /* < not <=, because although the array is large enough for <=, the
1705 * generated query will immediately be discarded due to depth and
1706 * that servfail is cached, which is not good as opportunism goes. */
1707 if(iq->depth < ie->max_dependency_depth
1708 && iq->sent_count < TARGET_FETCH_STOP) {
1709 tf_policy = ie->target_fetch_policy[iq->depth];
1712 /* if in 0x20 fallback get as many targets as possible */
1713 if(iq->caps_fallback) {
1715 size_t naddr, nres, navail;
1716 if(!query_for_targets(qstate, iq, ie, id, -1, &extra)) {
1717 return error_response(qstate, id, LDNS_RCODE_SERVFAIL);
1719 iq->num_target_queries += extra;
1720 if(iq->num_target_queries > 0) {
1721 /* wait to get all targets, we want to try em */
1722 verbose(VERB_ALGO, "wait for all targets for fallback");
1723 qstate->ext_state[id] = module_wait_reply;
1726 /* did we do enough fallback queries already? */
1727 delegpt_count_addr(iq->dp, &naddr, &nres, &navail);
1728 /* the current caps_server is the number of fallbacks sent.
1729 * the original query is one that matched too, so we have
1730 * caps_server+1 number of matching queries now */
1731 if(iq->caps_server+1 >= naddr*3 ||
1732 iq->caps_server+1 >= MAX_SENT_COUNT) {
1733 /* we're done, process the response */
1734 verbose(VERB_ALGO, "0x20 fallback had %d responses "
1735 "match for %d wanted, done.",
1736 (int)iq->caps_server+1, (int)naddr*3);
1737 iq->caps_fallback = 0;
1738 iter_dec_attempts(iq->dp, 3); /* space for fallback */
1739 iq->num_current_queries++; /* RespState decrements it*/
1740 iq->referral_count++; /* make sure we don't loop */
1742 iq->state = QUERY_RESP_STATE;
1745 verbose(VERB_ALGO, "0x20 fallback number %d",
1746 (int)iq->caps_server);
1748 /* if there is a policy to fetch missing targets
1749 * opportunistically, do it. we rely on the fact that once a
1750 * query (or queries) for a missing name have been issued,
1751 * they will not show up again. */
1752 } else if(tf_policy != 0) {
1754 verbose(VERB_ALGO, "attempt to get extra %d targets",
1756 (void)query_for_targets(qstate, iq, ie, id, tf_policy, &extra);
1757 /* errors ignored, these targets are not strictly necessary for
1758 * this result, we do not have to reply with SERVFAIL */
1759 iq->num_target_queries += extra;
1762 /* Add the current set of unused targets to our queue. */
1763 delegpt_add_unused_targets(iq->dp);
1765 /* Select the next usable target, filtering out unsuitable targets. */
1766 target = iter_server_selection(ie, qstate->env, iq->dp,
1767 iq->dp->name, iq->dp->namelen, iq->qchase.qtype,
1768 &iq->dnssec_lame_query, &iq->chase_to_rd,
1769 iq->num_target_queries, qstate->blacklist);
1771 /* If no usable target was selected... */
1773 /* Here we distinguish between three states: generate a new
1774 * target query, just wait, or quit (with a SERVFAIL).
1775 * We have the following information: number of active
1776 * target queries, number of active current queries,
1777 * the presence of missing targets at this delegation
1778 * point, and the given query target policy. */
1780 /* Check for the wait condition. If this is true, then
1781 * an action must be taken. */
1782 if(iq->num_target_queries==0 && iq->num_current_queries==0) {
1783 /* If there is nothing to wait for, then we need
1784 * to distinguish between generating (a) new target
1785 * query, or failing. */
1786 if(delegpt_count_missing_targets(iq->dp) > 0) {
1788 verbose(VERB_ALGO, "querying for next "
1790 if(!query_for_targets(qstate, iq, ie, id,
1792 return error_response(qstate, id,
1793 LDNS_RCODE_SERVFAIL);
1796 delegpt_count_missing_targets(iq->dp) == 0){
1797 /* it looked like there were missing
1798 * targets, but they did not turn up.
1799 * Try the bad choices again (if any),
1800 * when we get back here missing==0,
1801 * so this is not a loop. */
1804 iq->num_target_queries += qs;
1806 /* Since a target query might have been made, we
1807 * need to check again. */
1808 if(iq->num_target_queries == 0) {
1809 return processLastResort(qstate, iq, ie, id);
1813 /* otherwise, we have no current targets, so submerge
1814 * until one of the target or direct queries return. */
1815 if(iq->num_target_queries>0 && iq->num_current_queries>0) {
1816 verbose(VERB_ALGO, "no current targets -- waiting "
1817 "for %d targets to resolve or %d outstanding"
1818 " queries to respond", iq->num_target_queries,
1819 iq->num_current_queries);
1820 qstate->ext_state[id] = module_wait_reply;
1821 } else if(iq->num_target_queries>0) {
1822 verbose(VERB_ALGO, "no current targets -- waiting "
1823 "for %d targets to resolve.",
1824 iq->num_target_queries);
1825 qstate->ext_state[id] = module_wait_subquery;
1827 verbose(VERB_ALGO, "no current targets -- waiting "
1828 "for %d outstanding queries to respond.",
1829 iq->num_current_queries);
1830 qstate->ext_state[id] = module_wait_reply;
1835 /* We have a valid target. */
1836 if(verbosity >= VERB_QUERY) {
1837 log_query_info(VERB_QUERY, "sending query:", &iq->qchase);
1838 log_name_addr(VERB_QUERY, "sending to target:", iq->dp->name,
1839 &target->addr, target->addrlen);
1840 verbose(VERB_ALGO, "dnssec status: %s%s",
1841 iq->dnssec_expected?"expected": "not expected",
1842 iq->dnssec_lame_query?" but lame_query anyway": "");
1844 fptr_ok(fptr_whitelist_modenv_send_query(qstate->env->send_query));
1845 outq = (*qstate->env->send_query)(
1846 iq->qchase.qname, iq->qchase.qname_len,
1847 iq->qchase.qtype, iq->qchase.qclass,
1848 iq->chase_flags | (iq->chase_to_rd?BIT_RD:0), EDNS_DO|BIT_CD,
1849 iq->dnssec_expected, &target->addr, target->addrlen,
1850 iq->dp->name, iq->dp->namelen, qstate);
1852 log_addr(VERB_DETAIL, "error sending query to auth server",
1853 &target->addr, target->addrlen);
1854 return next_state(iq, QUERYTARGETS_STATE);
1856 outbound_list_insert(&iq->outlist, outq);
1857 iq->num_current_queries++;
1859 qstate->ext_state[id] = module_wait_reply;
1864 /** find NS rrset in given list */
1865 static struct ub_packed_rrset_key*
1866 find_NS(struct reply_info* rep, size_t from, size_t to)
1869 for(i=from; i<to; i++) {
1870 if(ntohs(rep->rrsets[i]->rk.type) == LDNS_RR_TYPE_NS)
1871 return rep->rrsets[i];
1878 * Process the query response. All queries end up at this state first. This
1879 * process generally consists of analyzing the response and routing the
1880 * event to the next state (either bouncing it back to a request state, or
1881 * terminating the processing for this event).
1883 * @param qstate: query state.
1884 * @param iq: iterator query state.
1885 * @param id: module id.
1886 * @return true if the event requires more immediate processing, false if
1887 * not. This is generally only true when forwarding the request to
1888 * the final state (i.e., on answer).
1891 processQueryResponse(struct module_qstate* qstate, struct iter_qstate* iq,
1895 enum response_type type;
1896 iq->num_current_queries--;
1897 if(iq->response == NULL) {
1898 iq->chase_to_rd = 0;
1899 iq->dnssec_lame_query = 0;
1900 verbose(VERB_ALGO, "query response was timeout");
1901 return next_state(iq, QUERYTARGETS_STATE);
1903 type = response_type_from_server(
1904 (int)((iq->chase_flags&BIT_RD) || iq->chase_to_rd),
1905 iq->response, &iq->qchase, iq->dp);
1906 iq->chase_to_rd = 0;
1907 if(type == RESPONSE_TYPE_REFERRAL && (iq->chase_flags&BIT_RD)) {
1908 /* When forwarding (RD bit is set), we handle referrals
1909 * differently. No queries should be sent elsewhere */
1910 type = RESPONSE_TYPE_ANSWER;
1912 if(iq->dnssec_expected && !iq->dnssec_lame_query &&
1913 !(iq->chase_flags&BIT_RD)
1914 && type != RESPONSE_TYPE_LAME
1915 && type != RESPONSE_TYPE_REC_LAME
1916 && type != RESPONSE_TYPE_THROWAWAY
1917 && type != RESPONSE_TYPE_UNTYPED) {
1918 /* a possible answer, see if it is missing DNSSEC */
1919 /* but not when forwarding, so we dont mark fwder lame */
1920 if(!iter_msg_has_dnssec(iq->response)) {
1921 /* Mark this address as dnsseclame in this dp,
1922 * because that will make serverselection disprefer
1923 * it, but also, once it is the only final option,
1924 * use dnssec-lame-bypass if it needs to query there.*/
1926 struct delegpt_addr* a = delegpt_find_addr(
1927 iq->dp, &qstate->reply->addr,
1928 qstate->reply->addrlen);
1929 if(a) a->dnsseclame = 1;
1931 /* test the answer is from the zone we expected,
1932 * otherwise, (due to parent,child on same server), we
1933 * might mark the server,zone lame inappropriately */
1934 if(!iter_msg_from_zone(iq->response, iq->dp, type,
1936 qstate->reply = NULL;
1937 type = RESPONSE_TYPE_LAME;
1940 } else iq->dnssec_lame_query = 0;
1941 /* see if referral brings us close to the target */
1942 if(type == RESPONSE_TYPE_REFERRAL) {
1943 struct ub_packed_rrset_key* ns = find_NS(
1944 iq->response->rep, iq->response->rep->an_numrrsets,
1945 iq->response->rep->an_numrrsets
1946 + iq->response->rep->ns_numrrsets);
1947 if(!ns) ns = find_NS(iq->response->rep, 0,
1948 iq->response->rep->an_numrrsets);
1949 if(!ns || !dname_strict_subdomain_c(ns->rk.dname, iq->dp->name)
1950 || !dname_subdomain_c(iq->qchase.qname, ns->rk.dname)){
1951 verbose(VERB_ALGO, "bad referral, throwaway");
1952 type = RESPONSE_TYPE_THROWAWAY;
1954 iter_scrub_ds(iq->response, ns, iq->dp->name);
1955 } else iter_scrub_ds(iq->response, NULL, NULL);
1957 /* handle each of the type cases */
1958 if(type == RESPONSE_TYPE_ANSWER) {
1959 /* ANSWER type responses terminate the query algorithm,
1960 * so they sent on their */
1961 if(verbosity >= VERB_DETAIL) {
1962 verbose(VERB_DETAIL, "query response was %s",
1963 FLAGS_GET_RCODE(iq->response->rep->flags)
1964 ==LDNS_RCODE_NXDOMAIN?"NXDOMAIN ANSWER":
1965 (iq->response->rep->an_numrrsets?"ANSWER":
1968 /* if qtype is DS, check we have the right level of answer,
1969 * like grandchild answer but we need the middle, reject it */
1970 if(iq->qchase.qtype == LDNS_RR_TYPE_DS && !iq->dsns_point
1971 && !(iq->chase_flags&BIT_RD)
1972 && iter_ds_toolow(iq->response, iq->dp)
1973 && iter_dp_cangodown(&iq->qchase, iq->dp)) {
1974 /* close down outstanding requests to be discarded */
1975 outbound_list_clear(&iq->outlist);
1976 iq->num_current_queries = 0;
1977 fptr_ok(fptr_whitelist_modenv_detach_subs(
1978 qstate->env->detach_subs));
1979 (*qstate->env->detach_subs)(qstate);
1980 iq->num_target_queries = 0;
1981 return processDSNSFind(qstate, iq, id);
1983 iter_dns_store(qstate->env, &iq->response->qinfo,
1984 iq->response->rep, 0, qstate->prefetch_leeway,
1985 iq->dp&&iq->dp->has_parent_side_NS,
1987 /* close down outstanding requests to be discarded */
1988 outbound_list_clear(&iq->outlist);
1989 iq->num_current_queries = 0;
1990 fptr_ok(fptr_whitelist_modenv_detach_subs(
1991 qstate->env->detach_subs));
1992 (*qstate->env->detach_subs)(qstate);
1993 iq->num_target_queries = 0;
1995 sock_list_insert(&qstate->reply_origin,
1996 &qstate->reply->addr, qstate->reply->addrlen,
1998 return final_state(iq);
1999 } else if(type == RESPONSE_TYPE_REFERRAL) {
2000 /* REFERRAL type responses get a reset of the
2001 * delegation point, and back to the QUERYTARGETS_STATE. */
2002 verbose(VERB_DETAIL, "query response was REFERRAL");
2004 /* if hardened, only store referral if we asked for it */
2005 if(!qstate->env->cfg->harden_referral_path ||
2006 ( qstate->qinfo.qtype == LDNS_RR_TYPE_NS
2007 && (qstate->query_flags&BIT_RD)
2008 && !(qstate->query_flags&BIT_CD)
2009 /* we know that all other NS rrsets are scrubbed
2010 * away, thus on referral only one is left.
2011 * see if that equals the query name... */
2012 && ( /* auth section, but sometimes in answer section*/
2013 reply_find_rrset_section_ns(iq->response->rep,
2014 iq->qchase.qname, iq->qchase.qname_len,
2015 LDNS_RR_TYPE_NS, iq->qchase.qclass)
2016 || reply_find_rrset_section_an(iq->response->rep,
2017 iq->qchase.qname, iq->qchase.qname_len,
2018 LDNS_RR_TYPE_NS, iq->qchase.qclass)
2021 /* Store the referral under the current query */
2022 /* no prefetch-leeway, since its not the answer */
2023 iter_dns_store(qstate->env, &iq->response->qinfo,
2024 iq->response->rep, 1, 0, 0, NULL);
2025 if(iq->store_parent_NS)
2026 iter_store_parentside_NS(qstate->env,
2028 if(qstate->env->neg_cache)
2029 val_neg_addreferral(qstate->env->neg_cache,
2030 iq->response->rep, iq->dp->name);
2032 /* store parent-side-in-zone-glue, if directly queried for */
2033 if(iq->query_for_pside_glue && !iq->pside_glue) {
2034 iq->pside_glue = reply_find_rrset(iq->response->rep,
2035 iq->qchase.qname, iq->qchase.qname_len,
2036 iq->qchase.qtype, iq->qchase.qclass);
2037 if(iq->pside_glue) {
2038 log_rrset_key(VERB_ALGO, "found parent-side "
2039 "glue", iq->pside_glue);
2040 iter_store_parentside_rrset(qstate->env,
2045 /* Reset the event state, setting the current delegation
2046 * point to the referral. */
2047 iq->deleg_msg = iq->response;
2048 iq->dp = delegpt_from_message(iq->response, qstate->region);
2050 return error_response(qstate, id, LDNS_RCODE_SERVFAIL);
2051 if(!cache_fill_missing(qstate->env, iq->qchase.qclass,
2052 qstate->region, iq->dp))
2053 return error_response(qstate, id, LDNS_RCODE_SERVFAIL);
2054 if(iq->store_parent_NS && query_dname_compare(iq->dp->name,
2055 iq->store_parent_NS->name) == 0)
2056 iter_merge_retry_counts(iq->dp, iq->store_parent_NS);
2057 delegpt_log(VERB_ALGO, iq->dp);
2058 /* Count this as a referral. */
2059 iq->referral_count++;
2061 /* see if the next dp is a trust anchor, or a DS was sent
2062 * along, indicating dnssec is expected for next zone */
2063 iq->dnssec_expected = iter_indicates_dnssec(qstate->env,
2064 iq->dp, iq->response, iq->qchase.qclass);
2065 /* if dnssec, validating then also fetch the key for the DS */
2066 if(iq->dnssec_expected && qstate->env->cfg->prefetch_key &&
2067 !(qstate->query_flags&BIT_CD))
2068 generate_dnskey_prefetch(qstate, iq, id);
2070 /* spawn off NS and addr to auth servers for the NS we just
2071 * got in the referral. This gets authoritative answer
2072 * (answer section trust level) rrset.
2073 * right after, we detach the subs, answer goes to cache. */
2074 if(qstate->env->cfg->harden_referral_path)
2075 generate_ns_check(qstate, iq, id);
2077 /* stop current outstanding queries.
2078 * FIXME: should the outstanding queries be waited for and
2079 * handled? Say by a subquery that inherits the outbound_entry.
2081 outbound_list_clear(&iq->outlist);
2082 iq->num_current_queries = 0;
2083 fptr_ok(fptr_whitelist_modenv_detach_subs(
2084 qstate->env->detach_subs));
2085 (*qstate->env->detach_subs)(qstate);
2086 iq->num_target_queries = 0;
2087 verbose(VERB_ALGO, "cleared outbound list for next round");
2088 return next_state(iq, QUERYTARGETS_STATE);
2089 } else if(type == RESPONSE_TYPE_CNAME) {
2090 uint8_t* sname = NULL;
2091 size_t snamelen = 0;
2092 /* CNAME type responses get a query restart (i.e., get a
2093 * reset of the query state and go back to INIT_REQUEST_STATE).
2095 verbose(VERB_DETAIL, "query response was CNAME");
2096 if(verbosity >= VERB_ALGO)
2097 log_dns_msg("cname msg", &iq->response->qinfo,
2099 /* if qtype is DS, check we have the right level of answer,
2100 * like grandchild answer but we need the middle, reject it */
2101 if(iq->qchase.qtype == LDNS_RR_TYPE_DS && !iq->dsns_point
2102 && !(iq->chase_flags&BIT_RD)
2103 && iter_ds_toolow(iq->response, iq->dp)
2104 && iter_dp_cangodown(&iq->qchase, iq->dp)) {
2105 outbound_list_clear(&iq->outlist);
2106 iq->num_current_queries = 0;
2107 fptr_ok(fptr_whitelist_modenv_detach_subs(
2108 qstate->env->detach_subs));
2109 (*qstate->env->detach_subs)(qstate);
2110 iq->num_target_queries = 0;
2111 return processDSNSFind(qstate, iq, id);
2113 /* Process the CNAME response. */
2114 if(!handle_cname_response(qstate, iq, iq->response,
2116 return error_response(qstate, id, LDNS_RCODE_SERVFAIL);
2117 /* cache the CNAME response under the current query */
2118 /* NOTE : set referral=1, so that rrsets get stored but not
2119 * the partial query answer (CNAME only). */
2120 /* prefetchleeway applied because this updates answer parts */
2121 iter_dns_store(qstate->env, &iq->response->qinfo,
2122 iq->response->rep, 1, qstate->prefetch_leeway,
2123 iq->dp&&iq->dp->has_parent_side_NS, NULL);
2124 /* set the current request's qname to the new value. */
2125 iq->qchase.qname = sname;
2126 iq->qchase.qname_len = snamelen;
2127 /* Clear the query state, since this is a query restart. */
2128 iq->deleg_msg = NULL;
2130 iq->dsns_point = NULL;
2131 /* Note the query restart. */
2132 iq->query_restart_count++;
2135 /* stop current outstanding queries.
2136 * FIXME: should the outstanding queries be waited for and
2137 * handled? Say by a subquery that inherits the outbound_entry.
2139 outbound_list_clear(&iq->outlist);
2140 iq->num_current_queries = 0;
2141 fptr_ok(fptr_whitelist_modenv_detach_subs(
2142 qstate->env->detach_subs));
2143 (*qstate->env->detach_subs)(qstate);
2144 iq->num_target_queries = 0;
2146 sock_list_insert(&qstate->reply_origin,
2147 &qstate->reply->addr, qstate->reply->addrlen,
2149 verbose(VERB_ALGO, "cleared outbound list for query restart");
2150 /* go to INIT_REQUEST_STATE for new qname. */
2151 return next_state(iq, INIT_REQUEST_STATE);
2152 } else if(type == RESPONSE_TYPE_LAME) {
2153 /* Cache the LAMEness. */
2154 verbose(VERB_DETAIL, "query response was %sLAME",
2155 dnsseclame?"DNSSEC ":"");
2156 if(!dname_subdomain_c(iq->qchase.qname, iq->dp->name)) {
2157 log_err("mark lame: mismatch in qname and dpname");
2158 /* throwaway this reply below */
2159 } else if(qstate->reply) {
2160 /* need addr for lameness cache, but we may have
2161 * gotten this from cache, so test to be sure */
2162 if(!infra_set_lame(qstate->env->infra_cache,
2163 &qstate->reply->addr, qstate->reply->addrlen,
2164 iq->dp->name, iq->dp->namelen,
2165 *qstate->env->now, dnsseclame, 0,
2167 log_err("mark host lame: out of memory");
2169 } else if(type == RESPONSE_TYPE_REC_LAME) {
2170 /* Cache the LAMEness. */
2171 verbose(VERB_DETAIL, "query response REC_LAME: "
2172 "recursive but not authoritative server");
2173 if(!dname_subdomain_c(iq->qchase.qname, iq->dp->name)) {
2174 log_err("mark rec_lame: mismatch in qname and dpname");
2175 /* throwaway this reply below */
2176 } else if(qstate->reply) {
2177 /* need addr for lameness cache, but we may have
2178 * gotten this from cache, so test to be sure */
2179 verbose(VERB_DETAIL, "mark as REC_LAME");
2180 if(!infra_set_lame(qstate->env->infra_cache,
2181 &qstate->reply->addr, qstate->reply->addrlen,
2182 iq->dp->name, iq->dp->namelen,
2183 *qstate->env->now, 0, 1, iq->qchase.qtype))
2184 log_err("mark host lame: out of memory");
2186 } else if(type == RESPONSE_TYPE_THROWAWAY) {
2187 /* LAME and THROWAWAY responses are handled the same way.
2188 * In this case, the event is just sent directly back to
2189 * the QUERYTARGETS_STATE without resetting anything,
2190 * because, clearly, the next target must be tried. */
2191 verbose(VERB_DETAIL, "query response was THROWAWAY");
2193 log_warn("A query response came back with an unknown type: %d",
2197 /* LAME, THROWAWAY and "unknown" all end up here.
2198 * Recycle to the QUERYTARGETS state to hopefully try a
2199 * different target. */
2200 return next_state(iq, QUERYTARGETS_STATE);
2204 * Return priming query results to interestes super querystates.
2206 * Sets the delegation point and delegation message (not nonRD queries).
2207 * This is a callback from walk_supers.
2209 * @param qstate: priming query state that finished.
2210 * @param id: module id.
2211 * @param forq: the qstate for which priming has been done.
2214 prime_supers(struct module_qstate* qstate, int id, struct module_qstate* forq)
2216 struct iter_qstate* foriq = (struct iter_qstate*)forq->minfo[id];
2217 struct delegpt* dp = NULL;
2219 log_assert(qstate->is_priming || foriq->wait_priming_stub);
2220 log_assert(qstate->return_rcode == LDNS_RCODE_NOERROR);
2221 /* Convert our response to a delegation point */
2222 dp = delegpt_from_message(qstate->return_msg, forq->region);
2224 /* if there is no convertable delegation point, then
2225 * the ANSWER type was (presumably) a negative answer. */
2226 verbose(VERB_ALGO, "prime response was not a positive "
2229 foriq->state = QUERYTARGETS_STATE;
2233 log_query_info(VERB_DETAIL, "priming successful for", &qstate->qinfo);
2234 delegpt_log(VERB_ALGO, dp);
2236 foriq->deleg_msg = dns_copy_msg(qstate->return_msg, forq->region);
2237 if(!foriq->deleg_msg) {
2238 log_err("copy prime response: out of memory");
2240 foriq->state = QUERYTARGETS_STATE;
2244 /* root priming responses go to init stage 2, priming stub
2245 * responses to to stage 3. */
2246 if(foriq->wait_priming_stub) {
2247 foriq->state = INIT_REQUEST_3_STATE;
2248 foriq->wait_priming_stub = 0;
2249 } else foriq->state = INIT_REQUEST_2_STATE;
2250 /* because we are finished, the parent will be reactivated */
2254 * This handles the response to a priming query. This is used to handle both
2255 * root and stub priming responses. This is basically the equivalent of the
2256 * QUERY_RESP_STATE, but will not handle CNAME responses and will treat
2257 * REFERRALs as ANSWERS. It will also update and reactivate the originating
2260 * @param qstate: query state.
2261 * @param id: module id.
2262 * @return true if the event needs more immediate processing, false if not.
2263 * This state always returns false.
2266 processPrimeResponse(struct module_qstate* qstate, int id)
2268 struct iter_qstate* iq = (struct iter_qstate*)qstate->minfo[id];
2269 enum response_type type;
2270 iq->response->rep->flags &= ~(BIT_RD|BIT_RA); /* ignore rec-lame */
2271 type = response_type_from_server(
2272 (int)((iq->chase_flags&BIT_RD) || iq->chase_to_rd),
2273 iq->response, &iq->qchase, iq->dp);
2274 if(type == RESPONSE_TYPE_ANSWER) {
2275 qstate->return_rcode = LDNS_RCODE_NOERROR;
2276 qstate->return_msg = iq->response;
2278 qstate->return_rcode = LDNS_RCODE_SERVFAIL;
2279 qstate->return_msg = NULL;
2282 /* validate the root or stub after priming (if enabled).
2283 * This is the same query as the prime query, but with validation.
2284 * Now that we are primed, the additional queries that validation
2285 * may need can be resolved, such as DLV. */
2286 if(qstate->env->cfg->harden_referral_path) {
2287 struct module_qstate* subq = NULL;
2288 log_nametypeclass(VERB_ALGO, "schedule prime validation",
2289 qstate->qinfo.qname, qstate->qinfo.qtype,
2290 qstate->qinfo.qclass);
2291 if(!generate_sub_request(qstate->qinfo.qname,
2292 qstate->qinfo.qname_len, qstate->qinfo.qtype,
2293 qstate->qinfo.qclass, qstate, id, iq,
2294 INIT_REQUEST_STATE, FINISHED_STATE, &subq, 1)) {
2295 verbose(VERB_ALGO, "could not generate prime check");
2297 generate_a_aaaa_check(qstate, iq, id);
2300 /* This event is finished. */
2301 qstate->ext_state[id] = module_finished;
2306 * Do final processing on responses to target queries. Events reach this
2307 * state after the iterative resolution algorithm terminates. This state is
2308 * responsible for reactiving the original event, and housekeeping related
2309 * to received target responses (caching, updating the current delegation
2311 * Callback from walk_supers for every super state that is interested in
2312 * the results from this query.
2314 * @param qstate: query state.
2315 * @param id: module id.
2316 * @param forq: super query state.
2319 processTargetResponse(struct module_qstate* qstate, int id,
2320 struct module_qstate* forq)
2322 struct iter_qstate* iq = (struct iter_qstate*)qstate->minfo[id];
2323 struct iter_qstate* foriq = (struct iter_qstate*)forq->minfo[id];
2324 struct ub_packed_rrset_key* rrset;
2325 struct delegpt_ns* dpns;
2326 log_assert(qstate->return_rcode == LDNS_RCODE_NOERROR);
2328 foriq->state = QUERYTARGETS_STATE;
2329 log_query_info(VERB_ALGO, "processTargetResponse", &qstate->qinfo);
2330 log_query_info(VERB_ALGO, "processTargetResponse super", &forq->qinfo);
2332 /* check to see if parent event is still interested (in orig name). */
2334 verbose(VERB_ALGO, "subq: parent not interested, was reset");
2335 return; /* not interested anymore */
2337 dpns = delegpt_find_ns(foriq->dp, qstate->qinfo.qname,
2338 qstate->qinfo.qname_len);
2340 /* If not interested, just stop processing this event */
2341 verbose(VERB_ALGO, "subq: parent not interested anymore");
2342 /* could be because parent was jostled out of the cache,
2343 and a new identical query arrived, that does not want it*/
2347 /* Tell the originating event that this target query has finished
2348 * (regardless if it succeeded or not). */
2349 foriq->num_target_queries--;
2351 /* if iq->query_for_pside_glue then add the pside_glue (marked lame) */
2352 if(iq->pside_glue) {
2353 /* if the pside_glue is NULL, then it could not be found,
2354 * the done_pside is already set when created and a cache
2355 * entry created in processFinished so nothing to do here */
2356 log_rrset_key(VERB_ALGO, "add parentside glue to dp",
2358 if(!delegpt_add_rrset(foriq->dp, forq->region,
2360 log_err("out of memory adding pside glue");
2363 /* This response is relevant to the current query, so we
2364 * add (attempt to add, anyway) this target(s) and reactivate
2365 * the original event.
2366 * NOTE: we could only look for the AnswerRRset if the
2367 * response type was ANSWER. */
2368 rrset = reply_find_answer_rrset(&iq->qchase, qstate->return_msg->rep);
2370 /* if CNAMEs have been followed - add new NS to delegpt. */
2371 /* BTW. RFC 1918 says NS should not have got CNAMEs. Robust. */
2372 if(!delegpt_find_ns(foriq->dp, rrset->rk.dname,
2373 rrset->rk.dname_len)) {
2374 /* if dpns->lame then set newcname ns lame too */
2375 if(!delegpt_add_ns(foriq->dp, forq->region,
2376 rrset->rk.dname, dpns->lame))
2377 log_err("out of memory adding cnamed-ns");
2379 /* if dpns->lame then set the address(es) lame too */
2380 if(!delegpt_add_rrset(foriq->dp, forq->region, rrset,
2382 log_err("out of memory adding targets");
2383 verbose(VERB_ALGO, "added target response");
2384 delegpt_log(VERB_ALGO, foriq->dp);
2386 verbose(VERB_ALGO, "iterator TargetResponse failed");
2387 dpns->resolved = 1; /* fail the target */
2392 * Process response for DS NS Find queries, that attempt to find the delegation
2393 * point where we ask the DS query from.
2395 * @param qstate: query state.
2396 * @param id: module id.
2397 * @param forq: super query state.
2400 processDSNSResponse(struct module_qstate* qstate, int id,
2401 struct module_qstate* forq)
2403 struct iter_qstate* foriq = (struct iter_qstate*)forq->minfo[id];
2405 /* if the finished (iq->response) query has no NS set: continue
2406 * up to look for the right dp; nothing to change, do DPNSstate */
2407 if(qstate->return_rcode != LDNS_RCODE_NOERROR)
2408 return; /* seek further */
2409 /* find the NS RRset (without allowing CNAMEs) */
2410 if(!reply_find_rrset(qstate->return_msg->rep, qstate->qinfo.qname,
2411 qstate->qinfo.qname_len, LDNS_RR_TYPE_NS,
2412 qstate->qinfo.qclass)){
2413 return; /* seek further */
2416 /* else, store as DP and continue at querytargets */
2417 foriq->state = QUERYTARGETS_STATE;
2418 foriq->dp = delegpt_from_message(qstate->return_msg, forq->region);
2420 log_err("out of memory in dsns dp alloc");
2421 return; /* dp==NULL in QUERYTARGETS makes SERVFAIL */
2423 /* success, go query the querytargets in the new dp (and go down) */
2427 * Process response for qclass=ANY queries for a particular class.
2428 * Append to result or error-exit.
2430 * @param qstate: query state.
2431 * @param id: module id.
2432 * @param forq: super query state.
2435 processClassResponse(struct module_qstate* qstate, int id,
2436 struct module_qstate* forq)
2438 struct iter_qstate* foriq = (struct iter_qstate*)forq->minfo[id];
2439 struct dns_msg* from = qstate->return_msg;
2440 log_query_info(VERB_ALGO, "processClassResponse", &qstate->qinfo);
2441 log_query_info(VERB_ALGO, "processClassResponse super", &forq->qinfo);
2442 if(qstate->return_rcode != LDNS_RCODE_NOERROR) {
2443 /* cause servfail for qclass ANY query */
2444 foriq->response = NULL;
2445 foriq->state = FINISHED_STATE;
2449 if(!foriq->response) {
2450 /* allocate the response: copy RCODE, sec_state */
2451 foriq->response = dns_copy_msg(from, forq->region);
2452 if(!foriq->response) {
2453 log_err("malloc failed for qclass ANY response");
2454 foriq->state = FINISHED_STATE;
2457 foriq->response->qinfo.qclass = forq->qinfo.qclass;
2458 /* qclass ANY does not receive the AA flag on replies */
2459 foriq->response->rep->authoritative = 0;
2461 struct dns_msg* to = foriq->response;
2462 /* add _from_ this response _to_ existing collection */
2463 /* if there are records, copy RCODE */
2464 /* lower sec_state if this message is lower */
2465 if(from->rep->rrset_count != 0) {
2466 size_t n = from->rep->rrset_count+to->rep->rrset_count;
2467 struct ub_packed_rrset_key** dest, **d;
2468 /* copy appropriate rcode */
2469 to->rep->flags = from->rep->flags;
2471 dest = regional_alloc(forq->region, sizeof(dest[0])*n);
2473 log_err("malloc failed in collect ANY");
2474 foriq->state = FINISHED_STATE;
2479 memcpy(dest, to->rep->rrsets, to->rep->an_numrrsets
2481 dest += to->rep->an_numrrsets;
2482 memcpy(dest, from->rep->rrsets, from->rep->an_numrrsets
2484 dest += from->rep->an_numrrsets;
2486 memcpy(dest, to->rep->rrsets+to->rep->an_numrrsets,
2487 to->rep->ns_numrrsets * sizeof(dest[0]));
2488 dest += to->rep->ns_numrrsets;
2489 memcpy(dest, from->rep->rrsets+from->rep->an_numrrsets,
2490 from->rep->ns_numrrsets * sizeof(dest[0]));
2491 dest += from->rep->ns_numrrsets;
2493 memcpy(dest, to->rep->rrsets+to->rep->an_numrrsets+
2494 to->rep->ns_numrrsets,
2495 to->rep->ar_numrrsets * sizeof(dest[0]));
2496 dest += to->rep->ar_numrrsets;
2497 memcpy(dest, from->rep->rrsets+from->rep->an_numrrsets+
2498 from->rep->ns_numrrsets,
2499 from->rep->ar_numrrsets * sizeof(dest[0]));
2501 to->rep->rrsets = d;
2502 to->rep->an_numrrsets += from->rep->an_numrrsets;
2503 to->rep->ns_numrrsets += from->rep->ns_numrrsets;
2504 to->rep->ar_numrrsets += from->rep->ar_numrrsets;
2505 to->rep->rrset_count = n;
2507 if(from->rep->security < to->rep->security) /* lowest sec */
2508 to->rep->security = from->rep->security;
2509 if(from->rep->qdcount != 0) /* insert qd if appropriate */
2510 to->rep->qdcount = from->rep->qdcount;
2511 if(from->rep->ttl < to->rep->ttl) /* use smallest TTL */
2512 to->rep->ttl = from->rep->ttl;
2513 if(from->rep->prefetch_ttl < to->rep->prefetch_ttl)
2514 to->rep->prefetch_ttl = from->rep->prefetch_ttl;
2517 foriq->num_current_queries --;
2518 if(foriq->num_current_queries == 0)
2519 foriq->state = FINISHED_STATE;
2523 * Collect class ANY responses and make them into one response. This
2524 * state is started and it creates queries for all classes (that have
2525 * root hints). The answers are then collected.
2527 * @param qstate: query state.
2528 * @param id: module id.
2529 * @return true if the event needs more immediate processing, false if not.
2532 processCollectClass(struct module_qstate* qstate, int id)
2534 struct iter_qstate* iq = (struct iter_qstate*)qstate->minfo[id];
2535 struct module_qstate* subq;
2536 /* If qchase.qclass == 0 then send out queries for all classes.
2537 * Otherwise, do nothing (wait for all answers to arrive and the
2538 * processClassResponse to put them together, and that moves us
2539 * towards the Finished state when done. */
2540 if(iq->qchase.qclass == 0) {
2542 iq->qchase.qclass = LDNS_RR_CLASS_ANY;
2543 while(iter_get_next_root(qstate->env->hints,
2544 qstate->env->fwds, &c)) {
2545 /* generate query for this class */
2546 log_nametypeclass(VERB_ALGO, "spawn collect query",
2547 qstate->qinfo.qname, qstate->qinfo.qtype, c);
2548 if(!generate_sub_request(qstate->qinfo.qname,
2549 qstate->qinfo.qname_len, qstate->qinfo.qtype,
2550 c, qstate, id, iq, INIT_REQUEST_STATE,
2551 FINISHED_STATE, &subq,
2552 (int)!(qstate->query_flags&BIT_CD))) {
2553 return error_response(qstate, id,
2554 LDNS_RCODE_SERVFAIL);
2556 /* ignore subq, no special init required */
2557 iq->num_current_queries ++;
2562 /* if no roots are configured at all, return */
2563 if(iq->num_current_queries == 0) {
2564 verbose(VERB_ALGO, "No root hints or fwds, giving up "
2566 return error_response(qstate, id, LDNS_RCODE_REFUSED);
2568 /* return false, wait for queries to return */
2570 /* if woke up here because of an answer, wait for more answers */
2575 * This handles the final state for first-tier responses (i.e., responses to
2576 * externally generated queries).
2578 * @param qstate: query state.
2579 * @param iq: iterator query state.
2580 * @param id: module id.
2581 * @return true if the event needs more processing, false if not. Since this
2582 * is the final state for an event, it always returns false.
2585 processFinished(struct module_qstate* qstate, struct iter_qstate* iq,
2588 log_query_info(VERB_QUERY, "finishing processing for",
2591 /* store negative cache element for parent side glue. */
2592 if(iq->query_for_pside_glue && !iq->pside_glue)
2593 iter_store_parentside_neg(qstate->env, &qstate->qinfo,
2594 iq->deleg_msg?iq->deleg_msg->rep:
2595 (iq->response?iq->response->rep:NULL));
2597 verbose(VERB_ALGO, "No response is set, servfail");
2598 return error_response(qstate, id, LDNS_RCODE_SERVFAIL);
2601 /* Make sure that the RA flag is set (since the presence of
2602 * this module means that recursion is available) */
2603 iq->response->rep->flags |= BIT_RA;
2605 /* Clear the AA flag */
2606 /* FIXME: does this action go here or in some other module? */
2607 iq->response->rep->flags &= ~BIT_AA;
2609 /* make sure QR flag is on */
2610 iq->response->rep->flags |= BIT_QR;
2612 /* we have finished processing this query */
2613 qstate->ext_state[id] = module_finished;
2615 /* TODO: we are using a private TTL, trim the response. */
2616 /* if (mPrivateTTL > 0){IterUtils.setPrivateTTL(resp, mPrivateTTL); } */
2618 /* prepend any items we have accumulated */
2619 if(iq->an_prepend_list || iq->ns_prepend_list) {
2620 if(!iter_prepend(iq, iq->response, qstate->region)) {
2621 log_err("prepend rrsets: out of memory");
2622 return error_response(qstate, id, LDNS_RCODE_SERVFAIL);
2624 /* reset the query name back */
2625 iq->response->qinfo = qstate->qinfo;
2626 /* the security state depends on the combination */
2627 iq->response->rep->security = sec_status_unchecked;
2628 /* store message with the finished prepended items,
2629 * but only if we did recursion. The nonrecursion referral
2630 * from cache does not need to be stored in the msg cache. */
2631 if(qstate->query_flags&BIT_RD) {
2632 iter_dns_store(qstate->env, &qstate->qinfo,
2633 iq->response->rep, 0, qstate->prefetch_leeway,
2634 iq->dp&&iq->dp->has_parent_side_NS,
2638 qstate->return_rcode = LDNS_RCODE_NOERROR;
2639 qstate->return_msg = iq->response;
2644 * Return priming query results to interestes super querystates.
2646 * Sets the delegation point and delegation message (not nonRD queries).
2647 * This is a callback from walk_supers.
2649 * @param qstate: query state that finished.
2650 * @param id: module id.
2651 * @param super: the qstate to inform.
2654 iter_inform_super(struct module_qstate* qstate, int id,
2655 struct module_qstate* super)
2657 if(!qstate->is_priming && super->qinfo.qclass == LDNS_RR_CLASS_ANY)
2658 processClassResponse(qstate, id, super);
2659 else if(super->qinfo.qtype == LDNS_RR_TYPE_DS && ((struct iter_qstate*)
2660 super->minfo[id])->state == DSNS_FIND_STATE)
2661 processDSNSResponse(qstate, id, super);
2662 else if(qstate->return_rcode != LDNS_RCODE_NOERROR)
2663 error_supers(qstate, id, super);
2664 else if(qstate->is_priming)
2665 prime_supers(qstate, id, super);
2666 else processTargetResponse(qstate, id, super);
2670 * Handle iterator state.
2671 * Handle events. This is the real processing loop for events, responsible
2672 * for moving events through the various states. If a processing method
2673 * returns true, then it will be advanced to the next state. If false, then
2674 * processing will stop.
2676 * @param qstate: query state.
2677 * @param ie: iterator shared global environment.
2678 * @param iq: iterator query state.
2679 * @param id: module id.
2682 iter_handle(struct module_qstate* qstate, struct iter_qstate* iq,
2683 struct iter_env* ie, int id)
2687 verbose(VERB_ALGO, "iter_handle processing q with state %s",
2688 iter_state_to_string(iq->state));
2690 case INIT_REQUEST_STATE:
2691 cont = processInitRequest(qstate, iq, ie, id);
2693 case INIT_REQUEST_2_STATE:
2694 cont = processInitRequest2(qstate, iq, id);
2696 case INIT_REQUEST_3_STATE:
2697 cont = processInitRequest3(qstate, iq, id);
2699 case QUERYTARGETS_STATE:
2700 cont = processQueryTargets(qstate, iq, ie, id);
2702 case QUERY_RESP_STATE:
2703 cont = processQueryResponse(qstate, iq, id);
2705 case PRIME_RESP_STATE:
2706 cont = processPrimeResponse(qstate, id);
2708 case COLLECT_CLASS_STATE:
2709 cont = processCollectClass(qstate, id);
2711 case DSNS_FIND_STATE:
2712 cont = processDSNSFind(qstate, iq, id);
2714 case FINISHED_STATE:
2715 cont = processFinished(qstate, iq, id);
2718 log_warn("iterator: invalid state: %d",
2727 * This is the primary entry point for processing request events. Note that
2728 * this method should only be used by external modules.
2729 * @param qstate: query state.
2730 * @param ie: iterator shared global environment.
2731 * @param iq: iterator query state.
2732 * @param id: module id.
2735 process_request(struct module_qstate* qstate, struct iter_qstate* iq,
2736 struct iter_env* ie, int id)
2738 /* external requests start in the INIT state, and finish using the
2739 * FINISHED state. */
2740 iq->state = INIT_REQUEST_STATE;
2741 iq->final_state = FINISHED_STATE;
2742 verbose(VERB_ALGO, "process_request: new external request event");
2743 iter_handle(qstate, iq, ie, id);
2746 /** process authoritative server reply */
2748 process_response(struct module_qstate* qstate, struct iter_qstate* iq,
2749 struct iter_env* ie, int id, struct outbound_entry* outbound,
2750 enum module_ev event)
2752 struct msg_parse* prs;
2753 struct edns_data edns;
2756 verbose(VERB_ALGO, "process_response: new external response event");
2757 iq->response = NULL;
2758 iq->state = QUERY_RESP_STATE;
2759 if(event == module_event_noreply || event == module_event_error) {
2762 if( (event != module_event_reply && event != module_event_capsfail)
2763 || !qstate->reply) {
2764 log_err("Bad event combined with response");
2765 outbound_list_remove(&iq->outlist, outbound);
2766 (void)error_response(qstate, id, LDNS_RCODE_SERVFAIL);
2771 prs = (struct msg_parse*)regional_alloc(qstate->env->scratch,
2772 sizeof(struct msg_parse));
2774 log_err("out of memory on incoming message");
2775 /* like packet got dropped */
2778 memset(prs, 0, sizeof(*prs));
2779 memset(&edns, 0, sizeof(edns));
2780 pkt = qstate->reply->c->buffer;
2781 sldns_buffer_set_position(pkt, 0);
2782 if(parse_packet(pkt, prs, qstate->env->scratch) != LDNS_RCODE_NOERROR) {
2783 verbose(VERB_ALGO, "parse error on reply packet");
2786 /* edns is not examined, but removed from message to help cache */
2787 if(parse_extract_edns(prs, &edns) != LDNS_RCODE_NOERROR)
2789 /* remove CD-bit, we asked for in case we handle validation ourself */
2790 prs->flags &= ~BIT_CD;
2792 /* normalize and sanitize: easy to delete items from linked lists */
2793 if(!scrub_message(pkt, prs, &iq->qchase, iq->dp->name,
2794 qstate->env->scratch, qstate->env, ie))
2797 /* allocate response dns_msg in region */
2798 iq->response = dns_alloc_msg(pkt, prs, qstate->region);
2801 log_query_info(VERB_DETAIL, "response for", &qstate->qinfo);
2802 log_name_addr(VERB_DETAIL, "reply from", iq->dp->name,
2803 &qstate->reply->addr, qstate->reply->addrlen);
2804 if(verbosity >= VERB_ALGO)
2805 log_dns_msg("incoming scrubbed packet:", &iq->response->qinfo,
2808 if(event == module_event_capsfail) {
2809 if(!iq->caps_fallback) {
2810 /* start fallback */
2811 iq->caps_fallback = 1;
2812 iq->caps_server = 0;
2813 iq->caps_reply = iq->response->rep;
2814 iq->state = QUERYTARGETS_STATE;
2815 iq->num_current_queries--;
2816 verbose(VERB_DETAIL, "Capsforid: starting fallback");
2819 /* check if reply is the same, otherwise, fail */
2820 if(!reply_equal(iq->response->rep, iq->caps_reply,
2821 qstate->env->scratch)) {
2822 verbose(VERB_DETAIL, "Capsforid fallback: "
2823 "getting different replies, failed");
2824 outbound_list_remove(&iq->outlist, outbound);
2825 (void)error_response(qstate, id,
2826 LDNS_RCODE_SERVFAIL);
2829 /* continue the fallback procedure at next server */
2831 iq->state = QUERYTARGETS_STATE;
2832 iq->num_current_queries--;
2833 verbose(VERB_DETAIL, "Capsforid: reply is equal. "
2834 "go to next fallback");
2838 iq->caps_fallback = 0; /* if we were in fallback, 0x20 is OK now */
2841 outbound_list_remove(&iq->outlist, outbound);
2842 iter_handle(qstate, iq, ie, id);
2846 iter_operate(struct module_qstate* qstate, enum module_ev event, int id,
2847 struct outbound_entry* outbound)
2849 struct iter_env* ie = (struct iter_env*)qstate->env->modinfo[id];
2850 struct iter_qstate* iq = (struct iter_qstate*)qstate->minfo[id];
2851 verbose(VERB_QUERY, "iterator[module %d] operate: extstate:%s event:%s",
2852 id, strextstate(qstate->ext_state[id]), strmodulevent(event));
2853 if(iq) log_query_info(VERB_QUERY, "iterator operate: query",
2855 if(iq && qstate->qinfo.qname != iq->qchase.qname)
2856 log_query_info(VERB_QUERY, "iterator operate: chased to",
2859 /* perform iterator state machine */
2860 if((event == module_event_new || event == module_event_pass) &&
2862 if(!iter_new(qstate, id)) {
2863 (void)error_response(qstate, id, LDNS_RCODE_SERVFAIL);
2866 iq = (struct iter_qstate*)qstate->minfo[id];
2867 process_request(qstate, iq, ie, id);
2870 if(iq && event == module_event_pass) {
2871 iter_handle(qstate, iq, ie, id);
2874 if(iq && outbound) {
2875 process_response(qstate, iq, ie, id, outbound, event);
2878 if(event == module_event_error) {
2879 verbose(VERB_ALGO, "got called with event error, giving up");
2880 (void)error_response(qstate, id, LDNS_RCODE_SERVFAIL);
2884 log_err("bad event for iterator");
2885 (void)error_response(qstate, id, LDNS_RCODE_SERVFAIL);
2889 iter_clear(struct module_qstate* qstate, int id)
2891 struct iter_qstate* iq;
2894 iq = (struct iter_qstate*)qstate->minfo[id];
2896 outbound_list_clear(&iq->outlist);
2897 iq->num_current_queries = 0;
2899 qstate->minfo[id] = NULL;
2903 iter_get_mem(struct module_env* env, int id)
2905 struct iter_env* ie = (struct iter_env*)env->modinfo[id];
2908 return sizeof(*ie) + sizeof(int)*((size_t)ie->max_dependency_depth+1)
2909 + donotq_get_mem(ie->donotq) + priv_get_mem(ie->priv);
2913 * The iterator function block
2915 static struct module_func_block iter_block = {
2917 &iter_init, &iter_deinit, &iter_operate, &iter_inform_super,
2918 &iter_clear, &iter_get_mem
2921 struct module_func_block*
2922 iter_get_funcblock(void)
2928 iter_state_to_string(enum iter_state state)
2932 case INIT_REQUEST_STATE :
2933 return "INIT REQUEST STATE";
2934 case INIT_REQUEST_2_STATE :
2935 return "INIT REQUEST STATE (stage 2)";
2936 case INIT_REQUEST_3_STATE:
2937 return "INIT REQUEST STATE (stage 3)";
2938 case QUERYTARGETS_STATE :
2939 return "QUERY TARGETS STATE";
2940 case PRIME_RESP_STATE :
2941 return "PRIME RESPONSE STATE";
2942 case COLLECT_CLASS_STATE :
2943 return "COLLECT CLASS STATE";
2944 case DSNS_FIND_STATE :
2945 return "DSNS FIND STATE";
2946 case QUERY_RESP_STATE :
2947 return "QUERY RESPONSE STATE";
2948 case FINISHED_STATE :
2949 return "FINISHED RESPONSE STATE";
2951 return "UNKNOWN ITER STATE";
2956 iter_state_is_responsestate(enum iter_state s)
2959 case INIT_REQUEST_STATE :
2960 case INIT_REQUEST_2_STATE :
2961 case INIT_REQUEST_3_STATE :
2962 case QUERYTARGETS_STATE :
2963 case COLLECT_CLASS_STATE :