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 LIMITED
25 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
26 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE
27 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
28 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
29 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
30 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
31 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
32 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
33 * POSSIBILITY OF SUCH DAMAGE.
39 * This file contains a module that performs recusive iterative DNS query
44 #include <ldns/ldns.h>
45 #include "iterator/iterator.h"
46 #include "iterator/iter_utils.h"
47 #include "iterator/iter_hints.h"
48 #include "iterator/iter_fwd.h"
49 #include "iterator/iter_donotq.h"
50 #include "iterator/iter_delegpt.h"
51 #include "iterator/iter_resptype.h"
52 #include "iterator/iter_scrub.h"
53 #include "iterator/iter_priv.h"
54 #include "validator/val_neg.h"
55 #include "services/cache/dns.h"
56 #include "services/cache/infra.h"
57 #include "util/module.h"
58 #include "util/netevent.h"
59 #include "util/net_help.h"
60 #include "util/regional.h"
61 #include "util/data/dname.h"
62 #include "util/data/msgencode.h"
63 #include "util/fptr_wlist.h"
64 #include "util/config_file.h"
67 iter_init(struct module_env* env, int id)
69 struct iter_env* iter_env = (struct iter_env*)calloc(1,
70 sizeof(struct iter_env));
72 log_err("malloc failure");
75 env->modinfo[id] = (void*)iter_env;
76 if(!iter_apply_cfg(iter_env, env->cfg)) {
77 log_err("iterator: could not apply configuration settings.");
84 iter_deinit(struct module_env* env, int id)
86 struct iter_env* iter_env;
87 if(!env || !env->modinfo[id])
89 iter_env = (struct iter_env*)env->modinfo[id];
90 free(iter_env->target_fetch_policy);
91 priv_delete(iter_env->priv);
92 donotq_delete(iter_env->donotq);
94 env->modinfo[id] = NULL;
97 /** new query for iterator */
99 iter_new(struct module_qstate* qstate, int id)
101 struct iter_qstate* iq = (struct iter_qstate*)regional_alloc(
102 qstate->region, sizeof(struct iter_qstate));
103 qstate->minfo[id] = iq;
106 memset(iq, 0, sizeof(*iq));
107 iq->state = INIT_REQUEST_STATE;
108 iq->final_state = FINISHED_STATE;
109 iq->an_prepend_list = NULL;
110 iq->an_prepend_last = NULL;
111 iq->ns_prepend_list = NULL;
112 iq->ns_prepend_last = NULL;
115 iq->num_target_queries = 0;
116 iq->num_current_queries = 0;
117 iq->query_restart_count = 0;
118 iq->referral_count = 0;
120 iq->wait_priming_stub = 0;
121 iq->refetch_glue = 0;
122 iq->dnssec_expected = 0;
123 iq->dnssec_lame_query = 0;
124 iq->chase_flags = qstate->query_flags;
125 /* Start with the (current) qname. */
126 iq->qchase = qstate->qinfo;
127 outbound_list_init(&iq->outlist);
132 * Transition to the next state. This can be used to advance a currently
133 * processing event. It cannot be used to reactivate a forEvent.
135 * @param iq: iterator query state
136 * @param nextstate The state to transition to.
137 * @return true. This is so this can be called as the return value for the
138 * actual process*State() methods. (Transitioning to the next state
139 * implies further processing).
142 next_state(struct iter_qstate* iq, enum iter_state nextstate)
144 /* If transitioning to a "response" state, make sure that there is a
146 if(iter_state_is_responsestate(nextstate)) {
147 if(iq->response == NULL) {
148 log_err("transitioning to response state sans "
152 iq->state = nextstate;
157 * Transition an event to its final state. Final states always either return
158 * a result up the module chain, or reactivate a dependent event. Which
159 * final state to transtion to is set in the module state for the event when
160 * it was created, and depends on the original purpose of the event.
162 * The response is stored in the qstate->buf buffer.
164 * @param iq: iterator query state
165 * @return false. This is so this method can be used as the return value for
166 * the processState methods. (Transitioning to the final state
169 final_state(struct iter_qstate* iq)
171 return next_state(iq, iq->final_state);
175 * Callback routine to handle errors in parent query states
176 * @param qstate: query state that failed.
177 * @param id: module id.
178 * @param super: super state.
181 error_supers(struct module_qstate* qstate, int id, struct module_qstate* super)
183 struct iter_qstate* super_iq = (struct iter_qstate*)super->minfo[id];
185 if(qstate->qinfo.qtype == LDNS_RR_TYPE_A ||
186 qstate->qinfo.qtype == LDNS_RR_TYPE_AAAA) {
187 /* mark address as failed. */
188 struct delegpt_ns* dpns = NULL;
190 dpns = delegpt_find_ns(super_iq->dp,
191 qstate->qinfo.qname, qstate->qinfo.qname_len);
194 verbose(VERB_ALGO, "subq error, but not interested");
195 log_query_info(VERB_ALGO, "superq", &super->qinfo);
197 delegpt_log(VERB_ALGO, super_iq->dp);
201 /* see if the failure did get (parent-lame) info */
202 if(!cache_fill_missing(super->env,
203 super_iq->qchase.qclass, super->region,
205 log_err("out of memory adding missing");
207 dpns->resolved = 1; /* mark as failed */
208 super_iq->num_target_queries--;
210 if(qstate->qinfo.qtype == LDNS_RR_TYPE_NS) {
211 /* prime failed to get delegation */
214 /* evaluate targets again */
215 super_iq->state = QUERYTARGETS_STATE;
216 /* super becomes runnable, and will process this change */
220 * Return an error to the client
221 * @param qstate: our query state
222 * @param id: module id
223 * @param rcode: error code (DNS errcode).
224 * @return: 0 for use by caller, to make notation easy, like:
225 * return error_response(..).
228 error_response(struct module_qstate* qstate, int id, int rcode)
230 verbose(VERB_QUERY, "return error response %s",
231 ldns_lookup_by_id(ldns_rcodes, rcode)?
232 ldns_lookup_by_id(ldns_rcodes, rcode)->name:"??");
233 qstate->return_rcode = rcode;
234 qstate->return_msg = NULL;
235 qstate->ext_state[id] = module_finished;
240 * Return an error to the client and cache the error code in the
241 * message cache (so per qname, qtype, qclass).
242 * @param qstate: our query state
243 * @param id: module id
244 * @param rcode: error code (DNS errcode).
245 * @return: 0 for use by caller, to make notation easy, like:
246 * return error_response(..).
249 error_response_cache(struct module_qstate* qstate, int id, int rcode)
252 struct reply_info err;
253 memset(&err, 0, sizeof(err));
254 err.flags = (uint16_t)(BIT_QR | BIT_RA);
255 FLAGS_SET_RCODE(err.flags, rcode);
258 err.prefetch_ttl = PREFETCH_TTL_CALC(err.ttl);
259 /* do not waste time trying to validate this servfail */
260 err.security = sec_status_indeterminate;
261 verbose(VERB_ALGO, "store error response in message cache");
262 iter_dns_store(qstate->env, &qstate->qinfo, &err, 0, 0, 0, NULL);
263 return error_response(qstate, id, rcode);
266 /** check if prepend item is duplicate item */
268 prepend_is_duplicate(struct ub_packed_rrset_key** sets, size_t to,
269 struct ub_packed_rrset_key* dup)
272 for(i=0; i<to; i++) {
273 if(sets[i]->rk.type == dup->rk.type &&
274 sets[i]->rk.rrset_class == dup->rk.rrset_class &&
275 sets[i]->rk.dname_len == dup->rk.dname_len &&
276 query_dname_compare(sets[i]->rk.dname, dup->rk.dname)
283 /** prepend the prepend list in the answer and authority section of dns_msg */
285 iter_prepend(struct iter_qstate* iq, struct dns_msg* msg,
286 struct regional* region)
288 struct iter_prep_list* p;
289 struct ub_packed_rrset_key** sets;
290 size_t num_an = 0, num_ns = 0;;
291 for(p = iq->an_prepend_list; p; p = p->next)
293 for(p = iq->ns_prepend_list; p; p = p->next)
295 if(num_an + num_ns == 0)
297 verbose(VERB_ALGO, "prepending %d rrsets", (int)num_an + (int)num_ns);
298 sets = regional_alloc(region, (num_an+num_ns+msg->rep->rrset_count) *
299 sizeof(struct ub_packed_rrset_key*));
304 for(p = iq->an_prepend_list; p; p = p->next) {
305 sets[num_an++] = p->rrset;
307 memcpy(sets+num_an, msg->rep->rrsets, msg->rep->an_numrrsets *
308 sizeof(struct ub_packed_rrset_key*));
311 for(p = iq->ns_prepend_list; p; p = p->next) {
312 if(prepend_is_duplicate(sets+msg->rep->an_numrrsets+num_an,
313 num_ns, p->rrset) || prepend_is_duplicate(
314 msg->rep->rrsets+msg->rep->an_numrrsets,
315 msg->rep->ns_numrrsets, p->rrset))
317 sets[msg->rep->an_numrrsets + num_an + num_ns++] = p->rrset;
319 memcpy(sets + num_an + msg->rep->an_numrrsets + num_ns,
320 msg->rep->rrsets + msg->rep->an_numrrsets,
321 (msg->rep->ns_numrrsets + msg->rep->ar_numrrsets) *
322 sizeof(struct ub_packed_rrset_key*));
324 /* NXDOMAIN rcode can stay if we prepended DNAME/CNAMEs, because
325 * this is what recursors should give. */
326 msg->rep->rrset_count += num_an + num_ns;
327 msg->rep->an_numrrsets += num_an;
328 msg->rep->ns_numrrsets += num_ns;
329 msg->rep->rrsets = sets;
334 * Add rrset to ANSWER prepend list
335 * @param qstate: query state.
336 * @param iq: iterator query state.
337 * @param rrset: rrset to add.
338 * @return false on failure (malloc).
341 iter_add_prepend_answer(struct module_qstate* qstate, struct iter_qstate* iq,
342 struct ub_packed_rrset_key* rrset)
344 struct iter_prep_list* p = (struct iter_prep_list*)regional_alloc(
345 qstate->region, sizeof(struct iter_prep_list));
351 if(iq->an_prepend_last)
352 iq->an_prepend_last->next = p;
353 else iq->an_prepend_list = p;
354 iq->an_prepend_last = p;
359 * Add rrset to AUTHORITY prepend list
360 * @param qstate: query state.
361 * @param iq: iterator query state.
362 * @param rrset: rrset to add.
363 * @return false on failure (malloc).
366 iter_add_prepend_auth(struct module_qstate* qstate, struct iter_qstate* iq,
367 struct ub_packed_rrset_key* rrset)
369 struct iter_prep_list* p = (struct iter_prep_list*)regional_alloc(
370 qstate->region, sizeof(struct iter_prep_list));
376 if(iq->ns_prepend_last)
377 iq->ns_prepend_last->next = p;
378 else iq->ns_prepend_list = p;
379 iq->ns_prepend_last = p;
384 * Given a CNAME response (defined as a response containing a CNAME or DNAME
385 * that does not answer the request), process the response, modifying the
386 * state as necessary. This follows the CNAME/DNAME chain and returns the
389 * sets the new query name, after following the CNAME/DNAME chain.
390 * @param qstate: query state.
391 * @param iq: iterator query state.
392 * @param msg: the response.
393 * @param mname: returned target new query name.
394 * @param mname_len: length of mname.
395 * @return false on (malloc) error.
398 handle_cname_response(struct module_qstate* qstate, struct iter_qstate* iq,
399 struct dns_msg* msg, uint8_t** mname, size_t* mname_len)
402 /* Start with the (current) qname. */
403 *mname = iq->qchase.qname;
404 *mname_len = iq->qchase.qname_len;
406 /* Iterate over the ANSWER rrsets in order, looking for CNAMEs and
408 for(i=0; i<msg->rep->an_numrrsets; i++) {
409 struct ub_packed_rrset_key* r = msg->rep->rrsets[i];
410 /* If there is a (relevant) DNAME, add it to the list.
411 * We always expect there to be CNAME that was generated
412 * by this DNAME following, so we don't process the DNAME
414 if(ntohs(r->rk.type) == LDNS_RR_TYPE_DNAME &&
415 dname_strict_subdomain_c(*mname, r->rk.dname)) {
416 if(!iter_add_prepend_answer(qstate, iq, r))
421 if(ntohs(r->rk.type) == LDNS_RR_TYPE_CNAME &&
422 query_dname_compare(*mname, r->rk.dname) == 0) {
423 /* Add this relevant CNAME rrset to the prepend list.*/
424 if(!iter_add_prepend_answer(qstate, iq, r))
426 get_cname_target(r, mname, mname_len);
429 /* Other rrsets in the section are ignored. */
431 /* add authority rrsets to authority prepend, for wildcarded CNAMEs */
432 for(i=msg->rep->an_numrrsets; i<msg->rep->an_numrrsets +
433 msg->rep->ns_numrrsets; i++) {
434 struct ub_packed_rrset_key* r = msg->rep->rrsets[i];
435 /* only add NSEC/NSEC3, as they may be needed for validation */
436 if(ntohs(r->rk.type) == LDNS_RR_TYPE_NSEC ||
437 ntohs(r->rk.type) == LDNS_RR_TYPE_NSEC3) {
438 if(!iter_add_prepend_auth(qstate, iq, r))
446 * Generate a subrequest.
447 * Generate a local request event. Local events are tied to this module, and
448 * have a correponding (first tier) event that is waiting for this event to
449 * resolve to continue.
451 * @param qname The query name for this request.
452 * @param qnamelen length of qname
453 * @param qtype The query type for this request.
454 * @param qclass The query class for this request.
455 * @param qstate The event that is generating this event.
456 * @param id: module id.
457 * @param iq: The iterator state that is generating this event.
458 * @param initial_state The initial response state (normally this
459 * is QUERY_RESP_STATE, unless it is known that the request won't
460 * need iterative processing
461 * @param finalstate The final state for the response to this request.
462 * @param subq_ret: if newly allocated, the subquerystate, or NULL if it does
463 * not need initialisation.
464 * @param v: if true, validation is done on the subquery.
465 * @return false on error (malloc).
468 generate_sub_request(uint8_t* qname, size_t qnamelen, uint16_t qtype,
469 uint16_t qclass, struct module_qstate* qstate, int id,
470 struct iter_qstate* iq, enum iter_state initial_state,
471 enum iter_state finalstate, struct module_qstate** subq_ret, int v)
473 struct module_qstate* subq = NULL;
474 struct iter_qstate* subiq = NULL;
475 uint16_t qflags = 0; /* OPCODE QUERY, no flags */
476 struct query_info qinf;
477 int prime = (finalstate == PRIME_RESP_STATE)?1:0;
479 qinf.qname_len = qnamelen;
481 qinf.qclass = qclass;
483 /* RD should be set only when sending the query back through the INIT
485 if(initial_state == INIT_REQUEST_STATE)
487 /* We set the CD flag so we can send this through the "head" of
488 * the resolution chain, which might have a validator. We are
489 * uninterested in validating things not on the direct resolution
494 /* attach subquery, lookup existing or make a new one */
495 fptr_ok(fptr_whitelist_modenv_attach_sub(qstate->env->attach_sub));
496 if(!(*qstate->env->attach_sub)(qstate, &qinf, qflags, prime, &subq)) {
501 /* initialise the new subquery */
503 subq->ext_state[id] = module_state_initial;
504 subq->minfo[id] = regional_alloc(subq->region,
505 sizeof(struct iter_qstate));
506 if(!subq->minfo[id]) {
507 log_err("init subq: out of memory");
508 fptr_ok(fptr_whitelist_modenv_kill_sub(
509 qstate->env->kill_sub));
510 (*qstate->env->kill_sub)(subq);
513 subiq = (struct iter_qstate*)subq->minfo[id];
514 memset(subiq, 0, sizeof(*subiq));
515 subiq->num_target_queries = 0;
516 subiq->num_current_queries = 0;
517 subiq->depth = iq->depth+1;
518 outbound_list_init(&subiq->outlist);
519 subiq->state = initial_state;
520 subiq->final_state = finalstate;
521 subiq->qchase = subq->qinfo;
522 subiq->chase_flags = subq->query_flags;
523 subiq->refetch_glue = 0;
529 * Generate and send a root priming request.
530 * @param qstate: the qtstate that triggered the need to prime.
531 * @param iq: iterator query state.
532 * @param id: module id.
533 * @param qclass: the class to prime.
534 * @return 0 on failure
537 prime_root(struct module_qstate* qstate, struct iter_qstate* iq, int id,
541 struct module_qstate* subq;
542 verbose(VERB_DETAIL, "priming . %s NS",
543 ldns_lookup_by_id(ldns_rr_classes, (int)qclass)?
544 ldns_lookup_by_id(ldns_rr_classes, (int)qclass)->name:"??");
545 dp = hints_lookup_root(qstate->env->hints, qclass);
547 verbose(VERB_ALGO, "Cannot prime due to lack of hints");
550 /* Priming requests start at the QUERYTARGETS state, skipping
551 * the normal INIT state logic (which would cause an infloop). */
552 if(!generate_sub_request((uint8_t*)"\000", 1, LDNS_RR_TYPE_NS,
553 qclass, qstate, id, iq, QUERYTARGETS_STATE, PRIME_RESP_STATE,
555 verbose(VERB_ALGO, "could not prime root");
559 struct iter_qstate* subiq =
560 (struct iter_qstate*)subq->minfo[id];
561 /* Set the initial delegation point to the hint.
562 * copy dp, it is now part of the root prime query.
563 * dp was part of in the fixed hints structure. */
564 subiq->dp = delegpt_copy(dp, subq->region);
566 log_err("out of memory priming root, copydp");
567 fptr_ok(fptr_whitelist_modenv_kill_sub(
568 qstate->env->kill_sub));
569 (*qstate->env->kill_sub)(subq);
572 /* there should not be any target queries. */
573 subiq->num_target_queries = 0;
574 subiq->dnssec_expected = iter_indicates_dnssec(
575 qstate->env, subiq->dp, NULL, subq->qinfo.qclass);
578 /* this module stops, our submodule starts, and does the query. */
579 qstate->ext_state[id] = module_wait_subquery;
584 * Generate and process a stub priming request. This method tests for the
585 * need to prime a stub zone, so it is safe to call for every request.
587 * @param qstate: the qtstate that triggered the need to prime.
588 * @param iq: iterator query state.
589 * @param id: module id.
590 * @param qname: request name.
591 * @param qclass: request class.
592 * @return true if a priming subrequest was made, false if not. The will only
593 * issue a priming request if it detects an unprimed stub.
594 * Uses value of 2 to signal during stub-prime in root-prime situation
595 * that a noprime-stub is available and resolution can continue.
598 prime_stub(struct module_qstate* qstate, struct iter_qstate* iq, int id,
599 uint8_t* qname, uint16_t qclass)
601 /* Lookup the stub hint. This will return null if the stub doesn't
602 * need to be re-primed. */
603 struct iter_hints_stub* stub;
604 struct delegpt* stub_dp;
605 struct module_qstate* subq;
608 stub = hints_lookup_stub(qstate->env->hints, qname, qclass, iq->dp);
609 /* The stub (if there is one) does not need priming. */
614 /* is it a noprime stub (always use) */
617 if(iq->dp == NULL) r = 2;
618 /* copy the dp out of the fixed hints structure, so that
619 * it can be changed when servicing this query */
620 iq->dp = delegpt_copy(stub_dp, qstate->region);
622 log_err("out of memory priming stub");
623 (void)error_response(qstate, id, LDNS_RCODE_SERVFAIL);
624 return 1; /* return 1 to make module stop, with error */
626 log_nametypeclass(VERB_DETAIL, "use stub", stub_dp->name,
627 LDNS_RR_TYPE_NS, qclass);
631 /* Otherwise, we need to (re)prime the stub. */
632 log_nametypeclass(VERB_DETAIL, "priming stub", stub_dp->name,
633 LDNS_RR_TYPE_NS, qclass);
635 /* Stub priming events start at the QUERYTARGETS state to avoid the
636 * redundant INIT state processing. */
637 if(!generate_sub_request(stub_dp->name, stub_dp->namelen,
638 LDNS_RR_TYPE_NS, qclass, qstate, id, iq,
639 QUERYTARGETS_STATE, PRIME_RESP_STATE, &subq, 0)) {
640 verbose(VERB_ALGO, "could not prime stub");
641 (void)error_response(qstate, id, LDNS_RCODE_SERVFAIL);
642 return 1; /* return 1 to make module stop, with error */
645 struct iter_qstate* subiq =
646 (struct iter_qstate*)subq->minfo[id];
648 /* Set the initial delegation point to the hint. */
649 /* make copy to avoid use of stub dp by different qs/threads */
650 subiq->dp = delegpt_copy(stub_dp, subq->region);
652 log_err("out of memory priming stub, copydp");
653 fptr_ok(fptr_whitelist_modenv_kill_sub(
654 qstate->env->kill_sub));
655 (*qstate->env->kill_sub)(subq);
656 (void)error_response(qstate, id, LDNS_RCODE_SERVFAIL);
657 return 1; /* return 1 to make module stop, with error */
659 /* there should not be any target queries -- although there
660 * wouldn't be anyway, since stub hints never have
661 * missing targets. */
662 subiq->num_target_queries = 0;
663 subiq->wait_priming_stub = 1;
664 subiq->dnssec_expected = iter_indicates_dnssec(
665 qstate->env, subiq->dp, NULL, subq->qinfo.qclass);
668 /* this module stops, our submodule starts, and does the query. */
669 qstate->ext_state[id] = module_wait_subquery;
674 * Generate A and AAAA checks for glue that is in-zone for the referral
675 * we just got to obtain authoritative information on the adresses.
677 * @param qstate: the qtstate that triggered the need to prime.
678 * @param iq: iterator query state.
679 * @param id: module id.
682 generate_a_aaaa_check(struct module_qstate* qstate, struct iter_qstate* iq,
685 struct iter_env* ie = (struct iter_env*)qstate->env->modinfo[id];
686 struct module_qstate* subq;
688 struct reply_info* rep = iq->response->rep;
689 struct ub_packed_rrset_key* s;
692 if(iq->depth == ie->max_dependency_depth)
694 /* walk through additional, and check if in-zone,
695 * only relevant A, AAAA are left after scrub anyway */
696 for(i=rep->an_numrrsets+rep->ns_numrrsets; i<rep->rrset_count; i++) {
698 /* check *ALL* addresses that are transmitted in additional*/
699 /* is it an address ? */
700 if( !(ntohs(s->rk.type)==LDNS_RR_TYPE_A ||
701 ntohs(s->rk.type)==LDNS_RR_TYPE_AAAA)) {
704 /* is this query the same as the A/AAAA check for it */
705 if(qstate->qinfo.qtype == ntohs(s->rk.type) &&
706 qstate->qinfo.qclass == ntohs(s->rk.rrset_class) &&
707 query_dname_compare(qstate->qinfo.qname,
709 (qstate->query_flags&BIT_RD) &&
710 !(qstate->query_flags&BIT_CD))
713 /* generate subrequest for it */
714 log_nametypeclass(VERB_ALGO, "schedule addr fetch",
715 s->rk.dname, ntohs(s->rk.type),
716 ntohs(s->rk.rrset_class));
717 if(!generate_sub_request(s->rk.dname, s->rk.dname_len,
718 ntohs(s->rk.type), ntohs(s->rk.rrset_class),
720 INIT_REQUEST_STATE, FINISHED_STATE, &subq, 1)) {
721 verbose(VERB_ALGO, "could not generate addr check");
724 /* ignore subq - not need for more init */
729 * Generate a NS check request to obtain authoritative information
732 * @param qstate: the qtstate that triggered the need to prime.
733 * @param iq: iterator query state.
734 * @param id: module id.
737 generate_ns_check(struct module_qstate* qstate, struct iter_qstate* iq, int id)
739 struct iter_env* ie = (struct iter_env*)qstate->env->modinfo[id];
740 struct module_qstate* subq;
743 if(iq->depth == ie->max_dependency_depth)
745 /* is this query the same as the nscheck? */
746 if(qstate->qinfo.qtype == LDNS_RR_TYPE_NS &&
747 query_dname_compare(iq->dp->name, qstate->qinfo.qname)==0 &&
748 (qstate->query_flags&BIT_RD) && !(qstate->query_flags&BIT_CD)){
749 /* spawn off A, AAAA queries for in-zone glue to check */
750 generate_a_aaaa_check(qstate, iq, id);
754 log_nametypeclass(VERB_ALGO, "schedule ns fetch",
755 iq->dp->name, LDNS_RR_TYPE_NS, iq->qchase.qclass);
756 if(!generate_sub_request(iq->dp->name, iq->dp->namelen,
757 LDNS_RR_TYPE_NS, iq->qchase.qclass, qstate, id, iq,
758 INIT_REQUEST_STATE, FINISHED_STATE, &subq, 1)) {
759 verbose(VERB_ALGO, "could not generate ns check");
763 struct iter_qstate* subiq =
764 (struct iter_qstate*)subq->minfo[id];
766 /* make copy to avoid use of stub dp by different qs/threads */
767 /* refetch glue to start higher up the tree */
768 subiq->refetch_glue = 1;
769 subiq->dp = delegpt_copy(iq->dp, subq->region);
771 log_err("out of memory generating ns check, copydp");
772 fptr_ok(fptr_whitelist_modenv_kill_sub(
773 qstate->env->kill_sub));
774 (*qstate->env->kill_sub)(subq);
781 * Generate a DNSKEY prefetch query to get the DNSKEY for the DS record we
782 * just got in a referral (where we have dnssec_expected, thus have trust
783 * anchors above it). Note that right after calling this routine the
784 * iterator detached subqueries (because of following the referral), and thus
785 * the DNSKEY query becomes detached, its return stored in the cache for
786 * later lookup by the validator. This cache lookup by the validator avoids
787 * the roundtrip incurred by the DNSKEY query. The DNSKEY query is now
788 * performed at about the same time the original query is sent to the domain,
789 * thus the two answers are likely to be returned at about the same time,
790 * saving a roundtrip from the validated lookup.
792 * @param qstate: the qtstate that triggered the need to prime.
793 * @param iq: iterator query state.
794 * @param id: module id.
797 generate_dnskey_prefetch(struct module_qstate* qstate,
798 struct iter_qstate* iq, int id)
800 struct module_qstate* subq;
803 /* is this query the same as the prefetch? */
804 if(qstate->qinfo.qtype == LDNS_RR_TYPE_DNSKEY &&
805 query_dname_compare(iq->dp->name, qstate->qinfo.qname)==0 &&
806 (qstate->query_flags&BIT_RD) && !(qstate->query_flags&BIT_CD)){
810 /* if the DNSKEY is in the cache this lookup will stop quickly */
811 log_nametypeclass(VERB_ALGO, "schedule dnskey prefetch",
812 iq->dp->name, LDNS_RR_TYPE_DNSKEY, iq->qchase.qclass);
813 if(!generate_sub_request(iq->dp->name, iq->dp->namelen,
814 LDNS_RR_TYPE_DNSKEY, iq->qchase.qclass, qstate, id, iq,
815 INIT_REQUEST_STATE, FINISHED_STATE, &subq, 0)) {
816 /* we'll be slower, but it'll work */
817 verbose(VERB_ALGO, "could not generate dnskey prefetch");
821 struct iter_qstate* subiq =
822 (struct iter_qstate*)subq->minfo[id];
823 /* this qstate has the right delegation for the dnskey lookup*/
824 /* make copy to avoid use of stub dp by different qs/threads */
825 subiq->dp = delegpt_copy(iq->dp, subq->region);
826 /* if !subiq->dp, it'll start from the cache, no problem */
831 * See if the query needs forwarding.
833 * @param qstate: query state.
834 * @param iq: iterator query state.
835 * @return true if the request is forwarded, false if not.
836 * If returns true but, iq->dp is NULL then a malloc failure occurred.
839 forward_request(struct module_qstate* qstate, struct iter_qstate* iq)
842 uint8_t* delname = iq->qchase.qname;
843 size_t delnamelen = iq->qchase.qname_len;
844 if(iq->refetch_glue) {
845 delname = iq->dp->name;
846 delnamelen = iq->dp->namelen;
848 /* strip one label off of DS query to lookup higher for it */
849 if( (iq->qchase.qtype == LDNS_RR_TYPE_DS || iq->refetch_glue)
850 && !dname_is_root(iq->qchase.qname))
851 dname_remove_label(&delname, &delnamelen);
852 dp = forwards_lookup(qstate->env->fwds, delname, iq->qchase.qclass);
855 /* send recursion desired to forward addr */
856 iq->chase_flags |= BIT_RD;
857 iq->dp = delegpt_copy(dp, qstate->region);
858 /* iq->dp checked by caller */
859 verbose(VERB_ALGO, "forwarding request");
864 * Process the initial part of the request handling. This state roughly
865 * corresponds to resolver algorithms steps 1 (find answer in cache) and 2
866 * (find the best servers to ask).
868 * Note that all requests start here, and query restarts revisit this state.
870 * This state either generates: 1) a response, from cache or error, 2) a
871 * priming event, or 3) forwards the request to the next state (init2,
874 * @param qstate: query state.
875 * @param iq: iterator query state.
876 * @param ie: iterator shared global environment.
877 * @param id: module id.
878 * @return true if the event needs more request processing immediately,
882 processInitRequest(struct module_qstate* qstate, struct iter_qstate* iq,
883 struct iter_env* ie, int id)
889 log_query_info(VERB_DETAIL, "resolving", &qstate->qinfo);
892 /* We enforce a maximum number of query restarts. This is primarily a
893 * cheap way to prevent CNAME loops. */
894 if(iq->query_restart_count > MAX_RESTART_COUNT) {
895 verbose(VERB_QUERY, "request has exceeded the maximum number"
896 " of query restarts with %d", iq->query_restart_count);
897 return error_response(qstate, id, LDNS_RCODE_SERVFAIL);
900 /* We enforce a maximum recursion/dependency depth -- in general,
901 * this is unnecessary for dependency loops (although it will
902 * catch those), but it provides a sensible limit to the amount
903 * of work required to answer a given query. */
904 verbose(VERB_ALGO, "request has dependency depth of %d", iq->depth);
905 if(iq->depth > ie->max_dependency_depth) {
906 verbose(VERB_QUERY, "request has exceeded the maximum "
907 "dependency depth with depth of %d", iq->depth);
908 return error_response(qstate, id, LDNS_RCODE_SERVFAIL);
911 /* If the request is qclass=ANY, setup to generate each class */
912 if(qstate->qinfo.qclass == LDNS_RR_CLASS_ANY) {
913 iq->qchase.qclass = 0;
914 return next_state(iq, COLLECT_CLASS_STATE);
917 /* Resolver Algorithm Step 1 -- Look for the answer in local data. */
919 /* This either results in a query restart (CNAME cache response), a
920 * terminating response (ANSWER), or a cache miss (null). */
922 if(qstate->blacklist) {
923 /* if cache, or anything else, was blacklisted then
924 * getting older results from cache is a bad idea, no cache */
925 verbose(VERB_ALGO, "cache blacklisted, going to the network");
928 msg = dns_cache_lookup(qstate->env, iq->qchase.qname,
929 iq->qchase.qname_len, iq->qchase.qtype,
930 iq->qchase.qclass, qstate->region, qstate->env->scratch);
931 if(!msg && qstate->env->neg_cache) {
932 /* lookup in negative cache; may result in
933 * NOERROR/NODATA or NXDOMAIN answers that need validation */
934 msg = val_neg_getmsg(qstate->env->neg_cache, &iq->qchase,
935 qstate->region, qstate->env->rrset_cache,
936 qstate->env->scratch_buffer,
937 *qstate->env->now, 1/*add SOA*/, NULL);
939 /* item taken from cache does not match our query name, thus
940 * security needs to be re-examined later */
941 if(msg && query_dname_compare(qstate->qinfo.qname,
942 iq->qchase.qname) != 0)
943 msg->rep->security = sec_status_unchecked;
946 /* handle positive cache response */
947 enum response_type type = response_type_from_cache(msg,
949 if(verbosity >= VERB_ALGO) {
950 log_dns_msg("msg from cache lookup", &msg->qinfo,
952 verbose(VERB_ALGO, "msg ttl is %d, prefetch ttl %d",
954 (int)msg->rep->prefetch_ttl);
957 if(type == RESPONSE_TYPE_CNAME) {
960 verbose(VERB_ALGO, "returning CNAME response from "
962 if(!handle_cname_response(qstate, iq, msg,
964 return error_response(qstate, id,
965 LDNS_RCODE_SERVFAIL);
966 iq->qchase.qname = sname;
967 iq->qchase.qname_len = slen;
968 /* This *is* a query restart, even if it is a cheap
971 iq->refetch_glue = 0;
972 iq->query_restart_count++;
974 sock_list_insert(&qstate->reply_origin, NULL, 0, qstate->region);
975 return next_state(iq, INIT_REQUEST_STATE);
978 /* if from cache, NULL, else insert 'cache IP' len=0 */
979 if(qstate->reply_origin)
980 sock_list_insert(&qstate->reply_origin, NULL, 0, qstate->region);
981 /* it is an answer, response, to final state */
982 verbose(VERB_ALGO, "returning answer from cache.");
984 return final_state(iq);
987 /* attempt to forward the request */
988 if(forward_request(qstate, iq))
991 log_err("alloc failure for forward dp");
992 return error_response(qstate, id, LDNS_RCODE_SERVFAIL);
994 iq->refetch_glue = 0;
995 /* the request has been forwarded.
996 * forwarded requests need to be immediately sent to the
997 * next state, QUERYTARGETS. */
998 return next_state(iq, QUERYTARGETS_STATE);
1001 /* Resolver Algorithm Step 2 -- find the "best" servers. */
1003 /* first, adjust for DS queries. To avoid the grandparent problem,
1004 * we just look for the closest set of server to the parent of qname.
1005 * When re-fetching glue we also need to ask the parent.
1007 if(iq->refetch_glue) {
1009 log_err("internal or malloc fail: no dp for refetch");
1010 return error_response(qstate, id, LDNS_RCODE_SERVFAIL);
1012 delname = iq->dp->name;
1013 delnamelen = iq->dp->namelen;
1015 delname = iq->qchase.qname;
1016 delnamelen = iq->qchase.qname_len;
1018 if(iq->qchase.qtype == LDNS_RR_TYPE_DS || iq->refetch_glue ||
1019 (iq->qchase.qtype == LDNS_RR_TYPE_NS && qstate->prefetch_leeway)) {
1020 /* remove first label from delname, root goes to hints,
1021 * but only to fetch glue, not for qtype=DS. */
1022 /* also when prefetching an NS record, fetch it again from
1023 * its parent, just as if it expired, so that you do not
1024 * get stuck on an older nameserver that gives old NSrecords */
1025 if(dname_is_root(delname) && (iq->refetch_glue ||
1026 (iq->qchase.qtype == LDNS_RR_TYPE_NS &&
1027 qstate->prefetch_leeway)))
1028 delname = NULL; /* go to root priming */
1029 else dname_remove_label(&delname, &delnamelen);
1031 /* delname is the name to lookup a delegation for. If NULL rootprime */
1034 /* Lookup the delegation in the cache. If null, then the
1035 * cache needs to be primed for the qclass. */
1037 iq->dp = dns_cache_find_delegation(qstate->env, delname,
1038 delnamelen, iq->qchase.qtype, iq->qchase.qclass,
1039 qstate->region, &iq->deleg_msg,
1040 *qstate->env->now+qstate->prefetch_leeway);
1043 /* If the cache has returned nothing, then we have a
1044 * root priming situation. */
1045 if(iq->dp == NULL) {
1046 /* if there is a stub, then no root prime needed */
1047 int r = prime_stub(qstate, iq, id, delname,
1050 break; /* got noprime-stub-zone, continue */
1052 return 0; /* stub prime request made */
1053 if(forwards_lookup_root(qstate->env->fwds,
1054 iq->qchase.qclass)) {
1055 /* forward zone root, no root prime needed */
1056 /* fill in some dp - safety belt */
1057 iq->dp = hints_lookup_root(qstate->env->hints,
1060 log_err("internal error: no hints dp");
1061 return error_response(qstate, id,
1062 LDNS_RCODE_SERVFAIL);
1064 iq->dp = delegpt_copy(iq->dp, qstate->region);
1066 log_err("out of memory in safety belt");
1067 return error_response(qstate, id,
1068 LDNS_RCODE_SERVFAIL);
1070 return next_state(iq, INIT_REQUEST_2_STATE);
1072 /* Note that the result of this will set a new
1073 * DelegationPoint based on the result of priming. */
1074 if(!prime_root(qstate, iq, id, iq->qchase.qclass))
1075 return error_response(qstate, id,
1076 LDNS_RCODE_REFUSED);
1078 /* priming creates and sends a subordinate query, with
1079 * this query as the parent. So further processing for
1080 * this event will stop until reactivated by the
1081 * results of priming. */
1085 /* see if this dp not useless.
1087 * o all NS items are required glue.
1088 * or the query is for NS item that is required glue.
1089 * o no addresses are provided.
1091 * Instead, go up one level, and try to get even further
1092 * If the root was useless, use safety belt information.
1093 * Only check cache returns, because replies for servers
1094 * could be useless but lead to loops (bumping into the
1095 * same server reply) if useless-checked.
1097 if(iter_dp_is_useless(&qstate->qinfo, qstate->query_flags,
1099 if(dname_is_root(iq->dp->name)) {
1100 /* use safety belt */
1101 verbose(VERB_QUERY, "Cache has root NS but "
1102 "no addresses. Fallback to the safety belt.");
1103 iq->dp = hints_lookup_root(qstate->env->hints,
1105 /* note deleg_msg is from previous lookup,
1106 * but RD is on, so it is not used */
1108 log_err("internal error: no hints dp");
1109 return error_response(qstate, id,
1110 LDNS_RCODE_REFUSED);
1112 iq->dp = delegpt_copy(iq->dp, qstate->region);
1114 log_err("out of memory in safety belt");
1115 return error_response(qstate, id,
1116 LDNS_RCODE_SERVFAIL);
1121 "cache delegation was useless:");
1122 delegpt_log(VERB_ALGO, iq->dp);
1124 delname = iq->dp->name;
1125 delnamelen = iq->dp->namelen;
1126 dname_remove_label(&delname, &delnamelen);
1131 verbose(VERB_ALGO, "cache delegation returns delegpt");
1132 delegpt_log(VERB_ALGO, iq->dp);
1134 /* Otherwise, set the current delegation point and move on to the
1136 return next_state(iq, INIT_REQUEST_2_STATE);
1140 * Process the second part of the initial request handling. This state
1141 * basically exists so that queries that generate root priming events have
1142 * the same init processing as ones that do not. Request events that reach
1143 * this state must have a valid currentDelegationPoint set.
1145 * This part is primarly handling stub zone priming. Events that reach this
1146 * state must have a current delegation point.
1148 * @param qstate: query state.
1149 * @param iq: iterator query state.
1150 * @param id: module id.
1151 * @return true if the event needs more request processing immediately,
1155 processInitRequest2(struct module_qstate* qstate, struct iter_qstate* iq,
1160 log_query_info(VERB_QUERY, "resolving (init part 2): ",
1163 if(iq->refetch_glue) {
1165 log_err("internal or malloc fail: no dp for refetch");
1166 return error_response(qstate, id, LDNS_RCODE_SERVFAIL);
1168 delname = iq->dp->name;
1169 delnamelen = iq->dp->namelen;
1171 delname = iq->qchase.qname;
1172 delnamelen = iq->qchase.qname_len;
1174 if(iq->qchase.qtype == LDNS_RR_TYPE_DS || iq->refetch_glue) {
1175 if(!dname_is_root(delname))
1176 dname_remove_label(&delname, &delnamelen);
1177 iq->refetch_glue = 0; /* if CNAME causes restart, no refetch */
1179 /* Check to see if we need to prime a stub zone. */
1180 if(prime_stub(qstate, iq, id, delname, iq->qchase.qclass)) {
1181 /* A priming sub request was made */
1185 /* most events just get forwarded to the next state. */
1186 return next_state(iq, INIT_REQUEST_3_STATE);
1190 * Process the third part of the initial request handling. This state exists
1191 * as a separate state so that queries that generate stub priming events
1192 * will get the tail end of the init process but not repeat the stub priming
1195 * @param qstate: query state.
1196 * @param iq: iterator query state.
1197 * @param id: module id.
1198 * @return true, advancing the event to the QUERYTARGETS_STATE.
1201 processInitRequest3(struct module_qstate* qstate, struct iter_qstate* iq,
1204 log_query_info(VERB_QUERY, "resolving (init part 3): ",
1206 /* if the cache reply dp equals a validation anchor or msg has DS,
1207 * then DNSSEC RRSIGs are expected in the reply */
1208 iq->dnssec_expected = iter_indicates_dnssec(qstate->env, iq->dp,
1209 iq->deleg_msg, iq->qchase.qclass);
1211 /* If the RD flag wasn't set, then we just finish with the
1212 * cached referral as the response. */
1213 if(!(qstate->query_flags & BIT_RD)) {
1214 iq->response = iq->deleg_msg;
1215 if(verbosity >= VERB_ALGO)
1216 log_dns_msg("no RD requested, using delegation msg",
1217 &iq->response->qinfo, iq->response->rep);
1218 if(qstate->reply_origin)
1219 sock_list_insert(&qstate->reply_origin, NULL, 0, qstate->region);
1220 return final_state(iq);
1222 /* After this point, unset the RD flag -- this query is going to
1223 * be sent to an auth. server. */
1224 iq->chase_flags &= ~BIT_RD;
1226 /* if dnssec expected, fetch key for the trust-anchor or cached-DS */
1227 if(iq->dnssec_expected && qstate->env->cfg->prefetch_key &&
1228 !(qstate->query_flags&BIT_CD)) {
1229 generate_dnskey_prefetch(qstate, iq, id);
1230 fptr_ok(fptr_whitelist_modenv_detach_subs(
1231 qstate->env->detach_subs));
1232 (*qstate->env->detach_subs)(qstate);
1235 /* Jump to the next state. */
1236 return next_state(iq, QUERYTARGETS_STATE);
1240 * Given a basic query, generate a parent-side "target" query.
1241 * These are subordinate queries for missing delegation point target addresses,
1242 * for which only the parent of the delegation provides correct IP addresses.
1244 * @param qstate: query state.
1245 * @param iq: iterator query state.
1246 * @param id: module id.
1247 * @param name: target qname.
1248 * @param namelen: target qname length.
1249 * @param qtype: target qtype (either A or AAAA).
1250 * @param qclass: target qclass.
1251 * @return true on success, false on failure.
1254 generate_parentside_target_query(struct module_qstate* qstate,
1255 struct iter_qstate* iq, int id, uint8_t* name, size_t namelen,
1256 uint16_t qtype, uint16_t qclass)
1258 struct module_qstate* subq;
1259 if(!generate_sub_request(name, namelen, qtype, qclass, qstate,
1260 id, iq, INIT_REQUEST_STATE, FINISHED_STATE, &subq, 0))
1263 struct iter_qstate* subiq =
1264 (struct iter_qstate*)subq->minfo[id];
1265 /* blacklist the cache - we want to fetch parent stuff */
1266 sock_list_insert(&subq->blacklist, NULL, 0, subq->region);
1267 subiq->query_for_pside_glue = 1;
1268 if(dname_subdomain_c(name, iq->dp->name)) {
1269 subiq->dp = delegpt_copy(iq->dp, subq->region);
1270 subiq->dnssec_expected = iter_indicates_dnssec(
1271 qstate->env, subiq->dp, NULL,
1272 subq->qinfo.qclass);
1273 subiq->refetch_glue = 1;
1275 subiq->dp = dns_cache_find_delegation(qstate->env,
1276 name, namelen, qtype, qclass, subq->region,
1278 *qstate->env->now+subq->prefetch_leeway);
1279 /* if no dp, then it's from root, refetch unneeded */
1281 subiq->dnssec_expected = iter_indicates_dnssec(
1282 qstate->env, subiq->dp, NULL,
1283 subq->qinfo.qclass);
1284 subiq->refetch_glue = 1;
1288 log_nametypeclass(VERB_QUERY, "new pside target", name, qtype, qclass);
1293 * Given a basic query, generate a "target" query. These are subordinate
1294 * queries for missing delegation point target addresses.
1296 * @param qstate: query state.
1297 * @param iq: iterator query state.
1298 * @param id: module id.
1299 * @param name: target qname.
1300 * @param namelen: target qname length.
1301 * @param qtype: target qtype (either A or AAAA).
1302 * @param qclass: target qclass.
1303 * @return true on success, false on failure.
1306 generate_target_query(struct module_qstate* qstate, struct iter_qstate* iq,
1307 int id, uint8_t* name, size_t namelen, uint16_t qtype, uint16_t qclass)
1309 struct module_qstate* subq;
1310 if(!generate_sub_request(name, namelen, qtype, qclass, qstate,
1311 id, iq, INIT_REQUEST_STATE, FINISHED_STATE, &subq, 0))
1313 log_nametypeclass(VERB_QUERY, "new target", name, qtype, qclass);
1318 * Given an event at a certain state, generate zero or more target queries
1319 * for it's current delegation point.
1321 * @param qstate: query state.
1322 * @param iq: iterator query state.
1323 * @param ie: iterator shared global environment.
1324 * @param id: module id.
1325 * @param maxtargets: The maximum number of targets to query for.
1326 * if it is negative, there is no maximum number of targets.
1327 * @param num: returns the number of queries generated and processed,
1328 * which may be zero if there were no missing targets.
1329 * @return false on error.
1332 query_for_targets(struct module_qstate* qstate, struct iter_qstate* iq,
1333 struct iter_env* ie, int id, int maxtargets, int* num)
1335 int query_count = 0;
1336 struct delegpt_ns* ns;
1340 if(iq->depth == ie->max_dependency_depth)
1343 iter_mark_cycle_targets(qstate, iq->dp);
1344 missing = (int)delegpt_count_missing_targets(iq->dp);
1345 log_assert(maxtargets != 0); /* that would not be useful */
1347 /* Generate target requests. Basically, any missing targets
1348 * are queried for here, regardless if it is necessary to do
1349 * so to continue processing. */
1350 if(maxtargets < 0 || maxtargets > missing)
1352 else toget = maxtargets;
1357 /* select 'toget' items from the total of 'missing' items */
1358 log_assert(toget <= missing);
1360 /* loop over missing targets */
1361 for(ns = iq->dp->nslist; ns; ns = ns->next) {
1365 /* randomly select this item with probability toget/missing */
1366 if(!iter_ns_probability(qstate->env->rnd, toget, missing)) {
1367 /* do not select this one, next; select toget number
1368 * of items from a list one less in size */
1373 if(ie->supports_ipv6 && !ns->got6) {
1374 /* Send the AAAA request. */
1375 if(!generate_target_query(qstate, iq, id,
1376 ns->name, ns->namelen,
1377 LDNS_RR_TYPE_AAAA, iq->qchase.qclass)) {
1380 qstate->ext_state[id] = module_wait_subquery;
1385 /* Send the A request. */
1386 if(ie->supports_ipv4 && !ns->got4) {
1387 if(!generate_target_query(qstate, iq, id,
1388 ns->name, ns->namelen,
1389 LDNS_RR_TYPE_A, iq->qchase.qclass)) {
1392 qstate->ext_state[id] = module_wait_subquery;
1398 /* mark this target as in progress. */
1407 qstate->ext_state[id] = module_wait_subquery;
1413 * Called by processQueryTargets when it would like extra targets to query
1414 * but it seems to be out of options. At last resort some less appealing
1415 * options are explored. If there are no more options, the result is SERVFAIL
1417 * @param qstate: query state.
1418 * @param iq: iterator query state.
1419 * @param ie: iterator shared global environment.
1420 * @param id: module id.
1421 * @return true if the event requires more request processing immediately,
1425 processLastResort(struct module_qstate* qstate, struct iter_qstate* iq,
1426 struct iter_env* ie, int id)
1428 struct delegpt_ns* ns;
1429 int query_count = 0;
1430 verbose(VERB_ALGO, "No more query targets, attempting last resort");
1433 if(!iq->dp->has_parent_side_NS && dname_is_root(iq->dp->name)) {
1434 struct delegpt* p = hints_lookup_root(qstate->env->hints,
1437 struct delegpt_ns* ns;
1438 struct delegpt_addr* a;
1439 iq->chase_flags &= ~BIT_RD; /* go to authorities */
1440 for(ns = p->nslist; ns; ns=ns->next) {
1441 (void)delegpt_add_ns(iq->dp, qstate->region,
1442 ns->name, (int)ns->lame);
1444 for(a = p->target_list; a; a=a->next_target) {
1445 (void)delegpt_add_addr(iq->dp, qstate->region,
1446 &a->addr, a->addrlen, a->bogus,
1450 iq->dp->has_parent_side_NS = 1;
1451 } else if(!iq->dp->has_parent_side_NS) {
1452 if(!iter_lookup_parent_NS_from_cache(qstate->env, iq->dp,
1453 qstate->region, &qstate->qinfo)
1454 || !iq->dp->has_parent_side_NS) {
1455 /* if: malloc failure in lookup go up to try */
1456 /* if: no parent NS in cache - go up one level */
1457 verbose(VERB_ALGO, "try to grab parent NS");
1458 iq->store_parent_NS = iq->dp;
1459 iq->chase_flags &= ~BIT_RD; /* go to authorities */
1460 iq->deleg_msg = NULL;
1461 iq->refetch_glue = 1;
1462 iq->query_restart_count++;
1464 return next_state(iq, INIT_REQUEST_STATE);
1467 /* see if that makes new names available */
1468 if(!cache_fill_missing(qstate->env, iq->qchase.qclass,
1469 qstate->region, iq->dp))
1470 log_err("out of memory in cache_fill_missing");
1471 if(iq->dp->usable_list) {
1472 verbose(VERB_ALGO, "try parent-side-name, w. glue from cache");
1473 return next_state(iq, QUERYTARGETS_STATE);
1475 /* try to fill out parent glue from cache */
1476 if(iter_lookup_parent_glue_from_cache(qstate->env, iq->dp,
1477 qstate->region, &qstate->qinfo)) {
1478 /* got parent stuff from cache, see if we can continue */
1479 verbose(VERB_ALGO, "try parent-side glue from cache");
1480 return next_state(iq, QUERYTARGETS_STATE);
1482 /* query for an extra name added by the parent-NS record */
1483 if(delegpt_count_missing_targets(iq->dp) > 0) {
1485 verbose(VERB_ALGO, "try parent-side target name");
1486 if(!query_for_targets(qstate, iq, ie, id, 1, &qs)) {
1487 return error_response(qstate, id, LDNS_RCODE_SERVFAIL);
1489 iq->num_target_queries += qs;
1491 qstate->ext_state[id] = module_wait_subquery;
1492 return 0; /* and wait for them */
1495 if(iq->depth == ie->max_dependency_depth) {
1496 verbose(VERB_QUERY, "maxdepth and need more nameservers, fail");
1497 return error_response_cache(qstate, id, LDNS_RCODE_SERVFAIL);
1499 /* mark cycle targets for parent-side lookups */
1500 iter_mark_pside_cycle_targets(qstate, iq->dp);
1501 /* see if we can issue queries to get nameserver addresses */
1502 /* this lookup is not randomized, but sequential. */
1503 for(ns = iq->dp->nslist; ns; ns = ns->next) {
1504 /* query for parent-side A and AAAA for nameservers */
1505 if(ie->supports_ipv6 && !ns->done_pside6) {
1506 /* Send the AAAA request. */
1507 if(!generate_parentside_target_query(qstate, iq, id,
1508 ns->name, ns->namelen,
1509 LDNS_RR_TYPE_AAAA, iq->qchase.qclass))
1510 return error_response(qstate, id,
1511 LDNS_RCODE_SERVFAIL);
1512 ns->done_pside6 = 1;
1515 if(ie->supports_ipv4 && !ns->done_pside4) {
1516 /* Send the A request. */
1517 if(!generate_parentside_target_query(qstate, iq, id,
1518 ns->name, ns->namelen,
1519 LDNS_RR_TYPE_A, iq->qchase.qclass))
1520 return error_response(qstate, id,
1521 LDNS_RCODE_SERVFAIL);
1522 ns->done_pside4 = 1;
1525 if(query_count != 0) { /* suspend to await results */
1526 verbose(VERB_ALGO, "try parent-side glue lookup");
1527 iq->num_target_queries += query_count;
1528 qstate->ext_state[id] = module_wait_subquery;
1533 /* if this was a parent-side glue query itself, then store that
1534 * failure in cache. */
1535 if(iq->query_for_pside_glue && !iq->pside_glue)
1536 iter_store_parentside_neg(qstate->env, &qstate->qinfo,
1537 iq->deleg_msg?iq->deleg_msg->rep:
1538 (iq->response?iq->response->rep:NULL));
1540 verbose(VERB_QUERY, "out of query targets -- returning SERVFAIL");
1541 /* fail -- no more targets, no more hope of targets, no hope
1543 return error_response_cache(qstate, id, LDNS_RCODE_SERVFAIL);
1547 * Try to find the NS record set that will resolve a qtype DS query. Due
1548 * to grandparent/grandchild reasons we did not get a proper lookup right
1549 * away. We need to create type NS queries until we get the right parent
1550 * for this lookup. We remove labels from the query to find the right point.
1551 * If we end up at the old dp name, then there is no solution.
1553 * @param qstate: query state.
1554 * @param iq: iterator query state.
1555 * @param id: module id.
1556 * @return true if the event requires more immediate processing, false if
1557 * not. This is generally only true when forwarding the request to
1558 * the final state (i.e., on answer).
1561 processDSNSFind(struct module_qstate* qstate, struct iter_qstate* iq, int id)
1563 struct module_qstate* subq = NULL;
1564 verbose(VERB_ALGO, "processDSNSFind");
1566 if(!iq->dsns_point) {
1568 iq->dsns_point = iq->qchase.qname;
1569 iq->dsns_point_len = iq->qchase.qname_len;
1571 /* robustcheck for internal error: we are not underneath the dp */
1572 if(!dname_subdomain_c(iq->dsns_point, iq->dp->name)) {
1573 return error_response_cache(qstate, id, LDNS_RCODE_SERVFAIL);
1576 /* go up one (more) step, until we hit the dp, if so, end */
1577 dname_remove_label(&iq->dsns_point, &iq->dsns_point_len);
1578 if(query_dname_compare(iq->dsns_point, iq->dp->name) == 0) {
1579 /* there was no inbetween nameserver, use the old delegation
1580 * point again. And this time, because dsns_point is nonNULL
1581 * we are going to accept the (bad) result */
1582 iq->state = QUERYTARGETS_STATE;
1585 iq->state = DSNS_FIND_STATE;
1587 /* spawn NS lookup (validation not needed, this is for DS lookup) */
1588 log_nametypeclass(VERB_ALGO, "fetch nameservers",
1589 iq->dsns_point, LDNS_RR_TYPE_NS, iq->qchase.qclass);
1590 if(!generate_sub_request(iq->dsns_point, iq->dsns_point_len,
1591 LDNS_RR_TYPE_NS, iq->qchase.qclass, qstate, id, iq,
1592 INIT_REQUEST_STATE, FINISHED_STATE, &subq, 0)) {
1593 return error_response_cache(qstate, id, LDNS_RCODE_SERVFAIL);
1600 * This is the request event state where the request will be sent to one of
1601 * its current query targets. This state also handles issuing target lookup
1602 * queries for missing target IP addresses. Queries typically iterate on
1603 * this state, both when they are just trying different targets for a given
1604 * delegation point, and when they change delegation points. This state
1605 * roughly corresponds to RFC 1034 algorithm steps 3 and 4.
1607 * @param qstate: query state.
1608 * @param iq: iterator query state.
1609 * @param ie: iterator shared global environment.
1610 * @param id: module id.
1611 * @return true if the event requires more request processing immediately,
1612 * false if not. This state only returns true when it is generating
1613 * a SERVFAIL response because the query has hit a dead end.
1616 processQueryTargets(struct module_qstate* qstate, struct iter_qstate* iq,
1617 struct iter_env* ie, int id)
1620 struct delegpt_addr* target;
1621 struct outbound_entry* outq;
1623 /* NOTE: a request will encounter this state for each target it
1624 * needs to send a query to. That is, at least one per referral,
1625 * more if some targets timeout or return throwaway answers. */
1627 log_query_info(VERB_QUERY, "processQueryTargets:", &qstate->qinfo);
1628 verbose(VERB_ALGO, "processQueryTargets: targetqueries %d, "
1629 "currentqueries %d sentcount %d", iq->num_target_queries,
1630 iq->num_current_queries, iq->sent_count);
1632 /* Make sure that we haven't run away */
1633 /* FIXME: is this check even necessary? */
1634 if(iq->referral_count > MAX_REFERRAL_COUNT) {
1635 verbose(VERB_QUERY, "request has exceeded the maximum "
1636 "number of referrrals with %d", iq->referral_count);
1637 return error_response(qstate, id, LDNS_RCODE_SERVFAIL);
1639 if(iq->sent_count > MAX_SENT_COUNT) {
1640 verbose(VERB_QUERY, "request has exceeded the maximum "
1641 "number of sends with %d", iq->sent_count);
1642 return error_response(qstate, id, LDNS_RCODE_SERVFAIL);
1645 /* Make sure we have a delegation point, otherwise priming failed
1646 * or another failure occurred */
1648 verbose(VERB_QUERY, "Failed to get a delegation, giving up");
1649 return error_response(qstate, id, LDNS_RCODE_SERVFAIL);
1651 if(!ie->supports_ipv6)
1652 delegpt_no_ipv6(iq->dp);
1653 if(!ie->supports_ipv4)
1654 delegpt_no_ipv4(iq->dp);
1655 delegpt_log(VERB_ALGO, iq->dp);
1657 if(iq->num_current_queries>0) {
1658 /* already busy answering a query, this restart is because
1659 * more delegpt addrs became available, wait for existing
1661 verbose(VERB_ALGO, "woke up, but wait for outstanding query");
1662 qstate->ext_state[id] = module_wait_reply;
1667 /* < not <=, because although the array is large enough for <=, the
1668 * generated query will immediately be discarded due to depth and
1669 * that servfail is cached, which is not good as opportunism goes. */
1670 if(iq->depth < ie->max_dependency_depth
1671 && iq->sent_count < TARGET_FETCH_STOP) {
1672 tf_policy = ie->target_fetch_policy[iq->depth];
1675 /* if in 0x20 fallback get as many targets as possible */
1676 if(iq->caps_fallback) {
1678 size_t naddr, nres, navail;
1679 if(!query_for_targets(qstate, iq, ie, id, -1, &extra)) {
1680 return error_response(qstate, id, LDNS_RCODE_SERVFAIL);
1682 iq->num_target_queries += extra;
1683 if(iq->num_target_queries > 0) {
1684 /* wait to get all targets, we want to try em */
1685 verbose(VERB_ALGO, "wait for all targets for fallback");
1686 qstate->ext_state[id] = module_wait_reply;
1689 /* did we do enough fallback queries already? */
1690 delegpt_count_addr(iq->dp, &naddr, &nres, &navail);
1691 /* the current caps_server is the number of fallbacks sent.
1692 * the original query is one that matched too, so we have
1693 * caps_server+1 number of matching queries now */
1694 if(iq->caps_server+1 >= naddr*3 ||
1695 iq->caps_server+1 >= MAX_SENT_COUNT) {
1696 /* we're done, process the response */
1697 verbose(VERB_ALGO, "0x20 fallback had %d responses "
1698 "match for %d wanted, done.",
1699 (int)iq->caps_server+1, (int)naddr*3);
1700 iq->caps_fallback = 0;
1701 iter_dec_attempts(iq->dp, 3); /* space for fallback */
1702 iq->num_current_queries++; /* RespState decrements it*/
1703 iq->referral_count++; /* make sure we don't loop */
1705 iq->state = QUERY_RESP_STATE;
1708 verbose(VERB_ALGO, "0x20 fallback number %d",
1709 (int)iq->caps_server);
1711 /* if there is a policy to fetch missing targets
1712 * opportunistically, do it. we rely on the fact that once a
1713 * query (or queries) for a missing name have been issued,
1714 * they will not show up again. */
1715 } else if(tf_policy != 0) {
1717 verbose(VERB_ALGO, "attempt to get extra %d targets",
1719 (void)query_for_targets(qstate, iq, ie, id, tf_policy, &extra);
1720 /* errors ignored, these targets are not strictly necessary for
1721 * this result, we do not have to reply with SERVFAIL */
1722 iq->num_target_queries += extra;
1725 /* Add the current set of unused targets to our queue. */
1726 delegpt_add_unused_targets(iq->dp);
1728 /* Select the next usable target, filtering out unsuitable targets. */
1729 target = iter_server_selection(ie, qstate->env, iq->dp,
1730 iq->dp->name, iq->dp->namelen, iq->qchase.qtype,
1731 &iq->dnssec_lame_query, &iq->chase_to_rd,
1732 iq->num_target_queries, qstate->blacklist);
1734 /* If no usable target was selected... */
1736 /* Here we distinguish between three states: generate a new
1737 * target query, just wait, or quit (with a SERVFAIL).
1738 * We have the following information: number of active
1739 * target queries, number of active current queries,
1740 * the presence of missing targets at this delegation
1741 * point, and the given query target policy. */
1743 /* Check for the wait condition. If this is true, then
1744 * an action must be taken. */
1745 if(iq->num_target_queries==0 && iq->num_current_queries==0) {
1746 /* If there is nothing to wait for, then we need
1747 * to distinguish between generating (a) new target
1748 * query, or failing. */
1749 if(delegpt_count_missing_targets(iq->dp) > 0) {
1751 verbose(VERB_ALGO, "querying for next "
1753 if(!query_for_targets(qstate, iq, ie, id,
1755 return error_response(qstate, id,
1756 LDNS_RCODE_SERVFAIL);
1759 delegpt_count_missing_targets(iq->dp) == 0){
1760 /* it looked like there were missing
1761 * targets, but they did not turn up.
1762 * Try the bad choices again (if any),
1763 * when we get back here missing==0,
1764 * so this is not a loop. */
1767 iq->num_target_queries += qs;
1769 /* Since a target query might have been made, we
1770 * need to check again. */
1771 if(iq->num_target_queries == 0) {
1772 return processLastResort(qstate, iq, ie, id);
1776 /* otherwise, we have no current targets, so submerge
1777 * until one of the target or direct queries return. */
1778 if(iq->num_target_queries>0 && iq->num_current_queries>0) {
1779 verbose(VERB_ALGO, "no current targets -- waiting "
1780 "for %d targets to resolve or %d outstanding"
1781 " queries to respond", iq->num_target_queries,
1782 iq->num_current_queries);
1783 qstate->ext_state[id] = module_wait_reply;
1784 } else if(iq->num_target_queries>0) {
1785 verbose(VERB_ALGO, "no current targets -- waiting "
1786 "for %d targets to resolve.",
1787 iq->num_target_queries);
1788 qstate->ext_state[id] = module_wait_subquery;
1790 verbose(VERB_ALGO, "no current targets -- waiting "
1791 "for %d outstanding queries to respond.",
1792 iq->num_current_queries);
1793 qstate->ext_state[id] = module_wait_reply;
1798 /* We have a valid target. */
1799 if(verbosity >= VERB_QUERY) {
1800 log_query_info(VERB_QUERY, "sending query:", &iq->qchase);
1801 log_name_addr(VERB_QUERY, "sending to target:", iq->dp->name,
1802 &target->addr, target->addrlen);
1803 verbose(VERB_ALGO, "dnssec status: %s%s",
1804 iq->dnssec_expected?"expected": "not expected",
1805 iq->dnssec_lame_query?" but lame_query anyway": "");
1807 fptr_ok(fptr_whitelist_modenv_send_query(qstate->env->send_query));
1808 outq = (*qstate->env->send_query)(
1809 iq->qchase.qname, iq->qchase.qname_len,
1810 iq->qchase.qtype, iq->qchase.qclass,
1811 iq->chase_flags | (iq->chase_to_rd?BIT_RD:0), EDNS_DO|BIT_CD,
1812 iq->dnssec_expected, &target->addr, target->addrlen,
1813 iq->dp->name, iq->dp->namelen, qstate);
1815 log_addr(VERB_DETAIL, "error sending query to auth server",
1816 &target->addr, target->addrlen);
1817 return next_state(iq, QUERYTARGETS_STATE);
1819 outbound_list_insert(&iq->outlist, outq);
1820 iq->num_current_queries++;
1822 qstate->ext_state[id] = module_wait_reply;
1827 /** find NS rrset in given list */
1828 static struct ub_packed_rrset_key*
1829 find_NS(struct reply_info* rep, size_t from, size_t to)
1832 for(i=from; i<to; i++) {
1833 if(ntohs(rep->rrsets[i]->rk.type) == LDNS_RR_TYPE_NS)
1834 return rep->rrsets[i];
1841 * Process the query response. All queries end up at this state first. This
1842 * process generally consists of analyzing the response and routing the
1843 * event to the next state (either bouncing it back to a request state, or
1844 * terminating the processing for this event).
1846 * @param qstate: query state.
1847 * @param iq: iterator query state.
1848 * @param id: module id.
1849 * @return true if the event requires more immediate processing, false if
1850 * not. This is generally only true when forwarding the request to
1851 * the final state (i.e., on answer).
1854 processQueryResponse(struct module_qstate* qstate, struct iter_qstate* iq,
1858 enum response_type type;
1859 iq->num_current_queries--;
1860 if(iq->response == NULL) {
1861 iq->chase_to_rd = 0;
1862 iq->dnssec_lame_query = 0;
1863 verbose(VERB_ALGO, "query response was timeout");
1864 return next_state(iq, QUERYTARGETS_STATE);
1866 type = response_type_from_server(
1867 (int)((iq->chase_flags&BIT_RD) || iq->chase_to_rd),
1868 iq->response, &iq->qchase, iq->dp);
1869 iq->chase_to_rd = 0;
1870 if(type == RESPONSE_TYPE_REFERRAL && (iq->chase_flags&BIT_RD)) {
1871 /* When forwarding (RD bit is set), we handle referrals
1872 * differently. No queries should be sent elsewhere */
1873 type = RESPONSE_TYPE_ANSWER;
1875 if(iq->dnssec_expected && !iq->dnssec_lame_query &&
1876 !(iq->chase_flags&BIT_RD)
1877 && type != RESPONSE_TYPE_LAME
1878 && type != RESPONSE_TYPE_REC_LAME
1879 && type != RESPONSE_TYPE_THROWAWAY
1880 && type != RESPONSE_TYPE_UNTYPED) {
1881 /* a possible answer, see if it is missing DNSSEC */
1882 /* but not when forwarding, so we dont mark fwder lame */
1883 /* also make sure the answer is from the zone we expected,
1884 * otherwise, (due to parent,child on same server), we
1885 * might mark the server,zone lame inappropriately */
1886 if(!iter_msg_has_dnssec(iq->response) &&
1887 iter_msg_from_zone(iq->response, iq->dp, type,
1888 iq->qchase.qclass)) {
1889 type = RESPONSE_TYPE_LAME;
1892 } else iq->dnssec_lame_query = 0;
1893 /* see if referral brings us close to the target */
1894 if(type == RESPONSE_TYPE_REFERRAL) {
1895 struct ub_packed_rrset_key* ns = find_NS(
1896 iq->response->rep, iq->response->rep->an_numrrsets,
1897 iq->response->rep->an_numrrsets
1898 + iq->response->rep->ns_numrrsets);
1899 if(!ns) ns = find_NS(iq->response->rep, 0,
1900 iq->response->rep->an_numrrsets);
1901 if(!ns || !dname_strict_subdomain_c(ns->rk.dname, iq->dp->name)
1902 || !dname_subdomain_c(iq->qchase.qname, ns->rk.dname)){
1903 verbose(VERB_ALGO, "bad referral, throwaway");
1904 type = RESPONSE_TYPE_THROWAWAY;
1906 iter_scrub_ds(iq->response, ns, iq->dp->name);
1907 } else iter_scrub_ds(iq->response, NULL, NULL);
1909 /* handle each of the type cases */
1910 if(type == RESPONSE_TYPE_ANSWER) {
1911 /* ANSWER type responses terminate the query algorithm,
1912 * so they sent on their */
1913 if(verbosity >= VERB_DETAIL) {
1914 verbose(VERB_DETAIL, "query response was %s",
1915 FLAGS_GET_RCODE(iq->response->rep->flags)
1916 ==LDNS_RCODE_NXDOMAIN?"NXDOMAIN ANSWER":
1917 (iq->response->rep->an_numrrsets?"ANSWER":
1920 /* if qtype is DS, check we have the right level of answer,
1921 * like grandchild answer but we need the middle, reject it */
1922 if(iq->qchase.qtype == LDNS_RR_TYPE_DS && !iq->dsns_point
1923 && !(iq->chase_flags&BIT_RD)
1924 && iter_ds_toolow(iq->response, iq->dp)
1925 && iter_dp_cangodown(&iq->qchase, iq->dp)) {
1926 /* close down outstanding requests to be discarded */
1927 outbound_list_clear(&iq->outlist);
1928 iq->num_current_queries = 0;
1929 fptr_ok(fptr_whitelist_modenv_detach_subs(
1930 qstate->env->detach_subs));
1931 (*qstate->env->detach_subs)(qstate);
1932 iq->num_target_queries = 0;
1933 return processDSNSFind(qstate, iq, id);
1935 iter_dns_store(qstate->env, &iq->response->qinfo,
1936 iq->response->rep, 0, qstate->prefetch_leeway,
1937 iq->dp&&iq->dp->has_parent_side_NS,
1939 /* close down outstanding requests to be discarded */
1940 outbound_list_clear(&iq->outlist);
1941 iq->num_current_queries = 0;
1942 fptr_ok(fptr_whitelist_modenv_detach_subs(
1943 qstate->env->detach_subs));
1944 (*qstate->env->detach_subs)(qstate);
1945 iq->num_target_queries = 0;
1947 sock_list_insert(&qstate->reply_origin,
1948 &qstate->reply->addr, qstate->reply->addrlen,
1950 return final_state(iq);
1951 } else if(type == RESPONSE_TYPE_REFERRAL) {
1952 /* REFERRAL type responses get a reset of the
1953 * delegation point, and back to the QUERYTARGETS_STATE. */
1954 verbose(VERB_DETAIL, "query response was REFERRAL");
1956 /* if hardened, only store referral if we asked for it */
1957 if(!qstate->env->cfg->harden_referral_path ||
1958 ( qstate->qinfo.qtype == LDNS_RR_TYPE_NS
1959 && (qstate->query_flags&BIT_RD)
1960 && !(qstate->query_flags&BIT_CD)
1961 /* we know that all other NS rrsets are scrubbed
1962 * away, thus on referral only one is left.
1963 * see if that equals the query name... */
1964 && ( /* auth section, but sometimes in answer section*/
1965 reply_find_rrset_section_ns(iq->response->rep,
1966 iq->qchase.qname, iq->qchase.qname_len,
1967 LDNS_RR_TYPE_NS, iq->qchase.qclass)
1968 || reply_find_rrset_section_an(iq->response->rep,
1969 iq->qchase.qname, iq->qchase.qname_len,
1970 LDNS_RR_TYPE_NS, iq->qchase.qclass)
1973 /* Store the referral under the current query */
1974 /* no prefetch-leeway, since its not the answer */
1975 iter_dns_store(qstate->env, &iq->response->qinfo,
1976 iq->response->rep, 1, 0, 0, NULL);
1977 if(iq->store_parent_NS)
1978 iter_store_parentside_NS(qstate->env,
1980 if(qstate->env->neg_cache)
1981 val_neg_addreferral(qstate->env->neg_cache,
1982 iq->response->rep, iq->dp->name);
1984 /* store parent-side-in-zone-glue, if directly queried for */
1985 if(iq->query_for_pside_glue && !iq->pside_glue) {
1986 iq->pside_glue = reply_find_rrset(iq->response->rep,
1987 iq->qchase.qname, iq->qchase.qname_len,
1988 iq->qchase.qtype, iq->qchase.qclass);
1989 if(iq->pside_glue) {
1990 log_rrset_key(VERB_ALGO, "found parent-side "
1991 "glue", iq->pside_glue);
1992 iter_store_parentside_rrset(qstate->env,
1997 /* Reset the event state, setting the current delegation
1998 * point to the referral. */
1999 iq->deleg_msg = iq->response;
2000 iq->dp = delegpt_from_message(iq->response, qstate->region);
2002 return error_response(qstate, id, LDNS_RCODE_SERVFAIL);
2003 if(!cache_fill_missing(qstate->env, iq->qchase.qclass,
2004 qstate->region, iq->dp))
2005 return error_response(qstate, id, LDNS_RCODE_SERVFAIL);
2006 if(iq->store_parent_NS && query_dname_compare(iq->dp->name,
2007 iq->store_parent_NS->name) == 0)
2008 iter_merge_retry_counts(iq->dp, iq->store_parent_NS);
2009 delegpt_log(VERB_ALGO, iq->dp);
2010 /* Count this as a referral. */
2011 iq->referral_count++;
2013 /* see if the next dp is a trust anchor, or a DS was sent
2014 * along, indicating dnssec is expected for next zone */
2015 iq->dnssec_expected = iter_indicates_dnssec(qstate->env,
2016 iq->dp, iq->response, iq->qchase.qclass);
2017 /* if dnssec, validating then also fetch the key for the DS */
2018 if(iq->dnssec_expected && qstate->env->cfg->prefetch_key &&
2019 !(qstate->query_flags&BIT_CD))
2020 generate_dnskey_prefetch(qstate, iq, id);
2022 /* spawn off NS and addr to auth servers for the NS we just
2023 * got in the referral. This gets authoritative answer
2024 * (answer section trust level) rrset.
2025 * right after, we detach the subs, answer goes to cache. */
2026 if(qstate->env->cfg->harden_referral_path)
2027 generate_ns_check(qstate, iq, id);
2029 /* stop current outstanding queries.
2030 * FIXME: should the outstanding queries be waited for and
2031 * handled? Say by a subquery that inherits the outbound_entry.
2033 outbound_list_clear(&iq->outlist);
2034 iq->num_current_queries = 0;
2035 fptr_ok(fptr_whitelist_modenv_detach_subs(
2036 qstate->env->detach_subs));
2037 (*qstate->env->detach_subs)(qstate);
2038 iq->num_target_queries = 0;
2039 verbose(VERB_ALGO, "cleared outbound list for next round");
2040 return next_state(iq, QUERYTARGETS_STATE);
2041 } else if(type == RESPONSE_TYPE_CNAME) {
2042 uint8_t* sname = NULL;
2043 size_t snamelen = 0;
2044 /* CNAME type responses get a query restart (i.e., get a
2045 * reset of the query state and go back to INIT_REQUEST_STATE).
2047 verbose(VERB_DETAIL, "query response was CNAME");
2048 if(verbosity >= VERB_ALGO)
2049 log_dns_msg("cname msg", &iq->response->qinfo,
2051 /* if qtype is DS, check we have the right level of answer,
2052 * like grandchild answer but we need the middle, reject it */
2053 if(iq->qchase.qtype == LDNS_RR_TYPE_DS && !iq->dsns_point
2054 && !(iq->chase_flags&BIT_RD)
2055 && iter_ds_toolow(iq->response, iq->dp)
2056 && iter_dp_cangodown(&iq->qchase, iq->dp)) {
2057 outbound_list_clear(&iq->outlist);
2058 iq->num_current_queries = 0;
2059 fptr_ok(fptr_whitelist_modenv_detach_subs(
2060 qstate->env->detach_subs));
2061 (*qstate->env->detach_subs)(qstate);
2062 iq->num_target_queries = 0;
2063 return processDSNSFind(qstate, iq, id);
2065 /* Process the CNAME response. */
2066 if(!handle_cname_response(qstate, iq, iq->response,
2068 return error_response(qstate, id, LDNS_RCODE_SERVFAIL);
2069 /* cache the CNAME response under the current query */
2070 /* NOTE : set referral=1, so that rrsets get stored but not
2071 * the partial query answer (CNAME only). */
2072 /* prefetchleeway applied because this updates answer parts */
2073 iter_dns_store(qstate->env, &iq->response->qinfo,
2074 iq->response->rep, 1, qstate->prefetch_leeway,
2075 iq->dp&&iq->dp->has_parent_side_NS, NULL);
2076 /* set the current request's qname to the new value. */
2077 iq->qchase.qname = sname;
2078 iq->qchase.qname_len = snamelen;
2079 /* Clear the query state, since this is a query restart. */
2080 iq->deleg_msg = NULL;
2082 iq->dsns_point = NULL;
2083 /* Note the query restart. */
2084 iq->query_restart_count++;
2087 /* stop current outstanding queries.
2088 * FIXME: should the outstanding queries be waited for and
2089 * handled? Say by a subquery that inherits the outbound_entry.
2091 outbound_list_clear(&iq->outlist);
2092 iq->num_current_queries = 0;
2093 fptr_ok(fptr_whitelist_modenv_detach_subs(
2094 qstate->env->detach_subs));
2095 (*qstate->env->detach_subs)(qstate);
2096 iq->num_target_queries = 0;
2098 sock_list_insert(&qstate->reply_origin,
2099 &qstate->reply->addr, qstate->reply->addrlen,
2101 verbose(VERB_ALGO, "cleared outbound list for query restart");
2102 /* go to INIT_REQUEST_STATE for new qname. */
2103 return next_state(iq, INIT_REQUEST_STATE);
2104 } else if(type == RESPONSE_TYPE_LAME) {
2105 /* Cache the LAMEness. */
2106 verbose(VERB_DETAIL, "query response was %sLAME",
2107 dnsseclame?"DNSSEC ":"");
2108 if(!dname_subdomain_c(iq->qchase.qname, iq->dp->name)) {
2109 log_err("mark lame: mismatch in qname and dpname");
2110 /* throwaway this reply below */
2111 } else if(qstate->reply) {
2112 /* need addr for lameness cache, but we may have
2113 * gotten this from cache, so test to be sure */
2114 if(!infra_set_lame(qstate->env->infra_cache,
2115 &qstate->reply->addr, qstate->reply->addrlen,
2116 iq->dp->name, iq->dp->namelen,
2117 *qstate->env->now, dnsseclame, 0,
2119 log_err("mark host lame: out of memory");
2120 } else log_err("%slame response from cache",
2121 dnsseclame?"DNSSEC ":"");
2122 } else if(type == RESPONSE_TYPE_REC_LAME) {
2123 /* Cache the LAMEness. */
2124 verbose(VERB_DETAIL, "query response REC_LAME: "
2125 "recursive but not authoritative server");
2126 if(!dname_subdomain_c(iq->qchase.qname, iq->dp->name)) {
2127 log_err("mark rec_lame: mismatch in qname and dpname");
2128 /* throwaway this reply below */
2129 } else if(qstate->reply) {
2130 /* need addr for lameness cache, but we may have
2131 * gotten this from cache, so test to be sure */
2132 verbose(VERB_DETAIL, "mark as REC_LAME");
2133 if(!infra_set_lame(qstate->env->infra_cache,
2134 &qstate->reply->addr, qstate->reply->addrlen,
2135 iq->dp->name, iq->dp->namelen,
2136 *qstate->env->now, 0, 1, iq->qchase.qtype))
2137 log_err("mark host lame: out of memory");
2139 } else if(type == RESPONSE_TYPE_THROWAWAY) {
2140 /* LAME and THROWAWAY responses are handled the same way.
2141 * In this case, the event is just sent directly back to
2142 * the QUERYTARGETS_STATE without resetting anything,
2143 * because, clearly, the next target must be tried. */
2144 verbose(VERB_DETAIL, "query response was THROWAWAY");
2146 log_warn("A query response came back with an unknown type: %d",
2150 /* LAME, THROWAWAY and "unknown" all end up here.
2151 * Recycle to the QUERYTARGETS state to hopefully try a
2152 * different target. */
2153 return next_state(iq, QUERYTARGETS_STATE);
2157 * Return priming query results to interestes super querystates.
2159 * Sets the delegation point and delegation message (not nonRD queries).
2160 * This is a callback from walk_supers.
2162 * @param qstate: priming query state that finished.
2163 * @param id: module id.
2164 * @param forq: the qstate for which priming has been done.
2167 prime_supers(struct module_qstate* qstate, int id, struct module_qstate* forq)
2169 struct iter_qstate* foriq = (struct iter_qstate*)forq->minfo[id];
2170 struct delegpt* dp = NULL;
2172 log_assert(qstate->is_priming || foriq->wait_priming_stub);
2173 log_assert(qstate->return_rcode == LDNS_RCODE_NOERROR);
2174 /* Convert our response to a delegation point */
2175 dp = delegpt_from_message(qstate->return_msg, forq->region);
2177 /* if there is no convertable delegation point, then
2178 * the ANSWER type was (presumably) a negative answer. */
2179 verbose(VERB_ALGO, "prime response was not a positive "
2182 foriq->state = QUERYTARGETS_STATE;
2186 log_query_info(VERB_DETAIL, "priming successful for", &qstate->qinfo);
2187 delegpt_log(VERB_ALGO, dp);
2189 foriq->deleg_msg = dns_copy_msg(qstate->return_msg, forq->region);
2190 if(!foriq->deleg_msg) {
2191 log_err("copy prime response: out of memory");
2193 foriq->state = QUERYTARGETS_STATE;
2197 /* root priming responses go to init stage 2, priming stub
2198 * responses to to stage 3. */
2199 if(foriq->wait_priming_stub) {
2200 foriq->state = INIT_REQUEST_3_STATE;
2201 foriq->wait_priming_stub = 0;
2202 } else foriq->state = INIT_REQUEST_2_STATE;
2203 /* because we are finished, the parent will be reactivated */
2207 * This handles the response to a priming query. This is used to handle both
2208 * root and stub priming responses. This is basically the equivalent of the
2209 * QUERY_RESP_STATE, but will not handle CNAME responses and will treat
2210 * REFERRALs as ANSWERS. It will also update and reactivate the originating
2213 * @param qstate: query state.
2214 * @param id: module id.
2215 * @return true if the event needs more immediate processing, false if not.
2216 * This state always returns false.
2219 processPrimeResponse(struct module_qstate* qstate, int id)
2221 struct iter_qstate* iq = (struct iter_qstate*)qstate->minfo[id];
2222 enum response_type type;
2223 iq->response->rep->flags &= ~(BIT_RD|BIT_RA); /* ignore rec-lame */
2224 type = response_type_from_server(
2225 (int)((iq->chase_flags&BIT_RD) || iq->chase_to_rd),
2226 iq->response, &iq->qchase, iq->dp);
2227 if(type == RESPONSE_TYPE_ANSWER) {
2228 qstate->return_rcode = LDNS_RCODE_NOERROR;
2229 qstate->return_msg = iq->response;
2231 qstate->return_rcode = LDNS_RCODE_SERVFAIL;
2232 qstate->return_msg = NULL;
2235 /* validate the root or stub after priming (if enabled).
2236 * This is the same query as the prime query, but with validation.
2237 * Now that we are primed, the additional queries that validation
2238 * may need can be resolved, such as DLV. */
2239 if(qstate->env->cfg->harden_referral_path) {
2240 struct module_qstate* subq = NULL;
2241 log_nametypeclass(VERB_ALGO, "schedule prime validation",
2242 qstate->qinfo.qname, qstate->qinfo.qtype,
2243 qstate->qinfo.qclass);
2244 if(!generate_sub_request(qstate->qinfo.qname,
2245 qstate->qinfo.qname_len, qstate->qinfo.qtype,
2246 qstate->qinfo.qclass, qstate, id, iq,
2247 INIT_REQUEST_STATE, FINISHED_STATE, &subq, 1)) {
2248 verbose(VERB_ALGO, "could not generate prime check");
2250 generate_a_aaaa_check(qstate, iq, id);
2253 /* This event is finished. */
2254 qstate->ext_state[id] = module_finished;
2259 * Do final processing on responses to target queries. Events reach this
2260 * state after the iterative resolution algorithm terminates. This state is
2261 * responsible for reactiving the original event, and housekeeping related
2262 * to received target responses (caching, updating the current delegation
2264 * Callback from walk_supers for every super state that is interested in
2265 * the results from this query.
2267 * @param qstate: query state.
2268 * @param id: module id.
2269 * @param forq: super query state.
2272 processTargetResponse(struct module_qstate* qstate, int id,
2273 struct module_qstate* forq)
2275 struct iter_qstate* iq = (struct iter_qstate*)qstate->minfo[id];
2276 struct iter_qstate* foriq = (struct iter_qstate*)forq->minfo[id];
2277 struct ub_packed_rrset_key* rrset;
2278 struct delegpt_ns* dpns;
2279 log_assert(qstate->return_rcode == LDNS_RCODE_NOERROR);
2281 foriq->state = QUERYTARGETS_STATE;
2282 log_query_info(VERB_ALGO, "processTargetResponse", &qstate->qinfo);
2283 log_query_info(VERB_ALGO, "processTargetResponse super", &forq->qinfo);
2285 /* check to see if parent event is still interested (in orig name). */
2287 verbose(VERB_ALGO, "subq: parent not interested, was reset");
2288 return; /* not interested anymore */
2290 dpns = delegpt_find_ns(foriq->dp, qstate->qinfo.qname,
2291 qstate->qinfo.qname_len);
2293 /* If not interested, just stop processing this event */
2294 verbose(VERB_ALGO, "subq: parent not interested anymore");
2295 /* could be because parent was jostled out of the cache,
2296 and a new identical query arrived, that does not want it*/
2300 /* Tell the originating event that this target query has finished
2301 * (regardless if it succeeded or not). */
2302 foriq->num_target_queries--;
2304 /* if iq->query_for_pside_glue then add the pside_glue (marked lame) */
2305 if(iq->pside_glue) {
2306 /* if the pside_glue is NULL, then it could not be found,
2307 * the done_pside is already set when created and a cache
2308 * entry created in processFinished so nothing to do here */
2309 log_rrset_key(VERB_ALGO, "add parentside glue to dp",
2311 if(!delegpt_add_rrset(foriq->dp, forq->region,
2313 log_err("out of memory adding pside glue");
2316 /* This response is relevant to the current query, so we
2317 * add (attempt to add, anyway) this target(s) and reactivate
2318 * the original event.
2319 * NOTE: we could only look for the AnswerRRset if the
2320 * response type was ANSWER. */
2321 rrset = reply_find_answer_rrset(&iq->qchase, qstate->return_msg->rep);
2323 /* if CNAMEs have been followed - add new NS to delegpt. */
2324 /* BTW. RFC 1918 says NS should not have got CNAMEs. Robust. */
2325 if(!delegpt_find_ns(foriq->dp, rrset->rk.dname,
2326 rrset->rk.dname_len)) {
2327 /* if dpns->lame then set newcname ns lame too */
2328 if(!delegpt_add_ns(foriq->dp, forq->region,
2329 rrset->rk.dname, (int)dpns->lame))
2330 log_err("out of memory adding cnamed-ns");
2332 /* if dpns->lame then set the address(es) lame too */
2333 if(!delegpt_add_rrset(foriq->dp, forq->region, rrset,
2335 log_err("out of memory adding targets");
2336 verbose(VERB_ALGO, "added target response");
2337 delegpt_log(VERB_ALGO, foriq->dp);
2339 verbose(VERB_ALGO, "iterator TargetResponse failed");
2340 dpns->resolved = 1; /* fail the target */
2345 * Process response for DS NS Find queries, that attempt to find the delegation
2346 * point where we ask the DS query from.
2348 * @param qstate: query state.
2349 * @param id: module id.
2350 * @param forq: super query state.
2353 processDSNSResponse(struct module_qstate* qstate, int id,
2354 struct module_qstate* forq)
2356 struct iter_qstate* foriq = (struct iter_qstate*)forq->minfo[id];
2358 /* if the finished (iq->response) query has no NS set: continue
2359 * up to look for the right dp; nothing to change, do DPNSstate */
2360 if(qstate->return_rcode != LDNS_RCODE_NOERROR)
2361 return; /* seek further */
2362 /* find the NS RRset (without allowing CNAMEs) */
2363 if(!reply_find_rrset(qstate->return_msg->rep, qstate->qinfo.qname,
2364 qstate->qinfo.qname_len, LDNS_RR_TYPE_NS,
2365 qstate->qinfo.qclass)){
2366 return; /* seek further */
2369 /* else, store as DP and continue at querytargets */
2370 foriq->state = QUERYTARGETS_STATE;
2371 foriq->dp = delegpt_from_message(qstate->return_msg, forq->region);
2373 log_err("out of memory in dsns dp alloc");
2374 return; /* dp==NULL in QUERYTARGETS makes SERVFAIL */
2376 /* success, go query the querytargets in the new dp (and go down) */
2380 * Process response for qclass=ANY queries for a particular class.
2381 * Append to result or error-exit.
2383 * @param qstate: query state.
2384 * @param id: module id.
2385 * @param forq: super query state.
2388 processClassResponse(struct module_qstate* qstate, int id,
2389 struct module_qstate* forq)
2391 struct iter_qstate* foriq = (struct iter_qstate*)forq->minfo[id];
2392 struct dns_msg* from = qstate->return_msg;
2393 log_query_info(VERB_ALGO, "processClassResponse", &qstate->qinfo);
2394 log_query_info(VERB_ALGO, "processClassResponse super", &forq->qinfo);
2395 if(qstate->return_rcode != LDNS_RCODE_NOERROR) {
2396 /* cause servfail for qclass ANY query */
2397 foriq->response = NULL;
2398 foriq->state = FINISHED_STATE;
2402 if(!foriq->response) {
2403 /* allocate the response: copy RCODE, sec_state */
2404 foriq->response = dns_copy_msg(from, forq->region);
2405 if(!foriq->response) {
2406 log_err("malloc failed for qclass ANY response");
2407 foriq->state = FINISHED_STATE;
2410 foriq->response->qinfo.qclass = forq->qinfo.qclass;
2411 /* qclass ANY does not receive the AA flag on replies */
2412 foriq->response->rep->authoritative = 0;
2414 struct dns_msg* to = foriq->response;
2415 /* add _from_ this response _to_ existing collection */
2416 /* if there are records, copy RCODE */
2417 /* lower sec_state if this message is lower */
2418 if(from->rep->rrset_count != 0) {
2419 size_t n = from->rep->rrset_count+to->rep->rrset_count;
2420 struct ub_packed_rrset_key** dest, **d;
2421 /* copy appropriate rcode */
2422 to->rep->flags = from->rep->flags;
2424 dest = regional_alloc(forq->region, sizeof(dest[0])*n);
2426 log_err("malloc failed in collect ANY");
2427 foriq->state = FINISHED_STATE;
2432 memcpy(dest, to->rep->rrsets, to->rep->an_numrrsets
2434 dest += to->rep->an_numrrsets;
2435 memcpy(dest, from->rep->rrsets, from->rep->an_numrrsets
2437 dest += from->rep->an_numrrsets;
2439 memcpy(dest, to->rep->rrsets+to->rep->an_numrrsets,
2440 to->rep->ns_numrrsets * sizeof(dest[0]));
2441 dest += to->rep->ns_numrrsets;
2442 memcpy(dest, from->rep->rrsets+from->rep->an_numrrsets,
2443 from->rep->ns_numrrsets * sizeof(dest[0]));
2444 dest += from->rep->ns_numrrsets;
2446 memcpy(dest, to->rep->rrsets+to->rep->an_numrrsets+
2447 to->rep->ns_numrrsets,
2448 to->rep->ar_numrrsets * sizeof(dest[0]));
2449 dest += to->rep->ar_numrrsets;
2450 memcpy(dest, from->rep->rrsets+from->rep->an_numrrsets+
2451 from->rep->ns_numrrsets,
2452 from->rep->ar_numrrsets * sizeof(dest[0]));
2454 to->rep->rrsets = d;
2455 to->rep->an_numrrsets += from->rep->an_numrrsets;
2456 to->rep->ns_numrrsets += from->rep->ns_numrrsets;
2457 to->rep->ar_numrrsets += from->rep->ar_numrrsets;
2458 to->rep->rrset_count = n;
2460 if(from->rep->security < to->rep->security) /* lowest sec */
2461 to->rep->security = from->rep->security;
2462 if(from->rep->qdcount != 0) /* insert qd if appropriate */
2463 to->rep->qdcount = from->rep->qdcount;
2464 if(from->rep->ttl < to->rep->ttl) /* use smallest TTL */
2465 to->rep->ttl = from->rep->ttl;
2466 if(from->rep->prefetch_ttl < to->rep->prefetch_ttl)
2467 to->rep->prefetch_ttl = from->rep->prefetch_ttl;
2470 foriq->num_current_queries --;
2471 if(foriq->num_current_queries == 0)
2472 foriq->state = FINISHED_STATE;
2476 * Collect class ANY responses and make them into one response. This
2477 * state is started and it creates queries for all classes (that have
2478 * root hints). The answers are then collected.
2480 * @param qstate: query state.
2481 * @param id: module id.
2482 * @return true if the event needs more immediate processing, false if not.
2485 processCollectClass(struct module_qstate* qstate, int id)
2487 struct iter_qstate* iq = (struct iter_qstate*)qstate->minfo[id];
2488 struct module_qstate* subq;
2489 /* If qchase.qclass == 0 then send out queries for all classes.
2490 * Otherwise, do nothing (wait for all answers to arrive and the
2491 * processClassResponse to put them together, and that moves us
2492 * towards the Finished state when done. */
2493 if(iq->qchase.qclass == 0) {
2495 iq->qchase.qclass = LDNS_RR_CLASS_ANY;
2496 while(iter_get_next_root(qstate->env->hints,
2497 qstate->env->fwds, &c)) {
2498 /* generate query for this class */
2499 log_nametypeclass(VERB_ALGO, "spawn collect query",
2500 qstate->qinfo.qname, qstate->qinfo.qtype, c);
2501 if(!generate_sub_request(qstate->qinfo.qname,
2502 qstate->qinfo.qname_len, qstate->qinfo.qtype,
2503 c, qstate, id, iq, INIT_REQUEST_STATE,
2504 FINISHED_STATE, &subq,
2505 (int)!(qstate->query_flags&BIT_CD))) {
2506 return error_response(qstate, id,
2507 LDNS_RCODE_SERVFAIL);
2509 /* ignore subq, no special init required */
2510 iq->num_current_queries ++;
2515 /* if no roots are configured at all, return */
2516 if(iq->num_current_queries == 0) {
2517 verbose(VERB_ALGO, "No root hints or fwds, giving up "
2519 return error_response(qstate, id, LDNS_RCODE_REFUSED);
2521 /* return false, wait for queries to return */
2523 /* if woke up here because of an answer, wait for more answers */
2528 * This handles the final state for first-tier responses (i.e., responses to
2529 * externally generated queries).
2531 * @param qstate: query state.
2532 * @param iq: iterator query state.
2533 * @param id: module id.
2534 * @return true if the event needs more processing, false if not. Since this
2535 * is the final state for an event, it always returns false.
2538 processFinished(struct module_qstate* qstate, struct iter_qstate* iq,
2541 log_query_info(VERB_QUERY, "finishing processing for",
2544 /* store negative cache element for parent side glue. */
2545 if(iq->query_for_pside_glue && !iq->pside_glue)
2546 iter_store_parentside_neg(qstate->env, &qstate->qinfo,
2547 iq->deleg_msg?iq->deleg_msg->rep:
2548 (iq->response?iq->response->rep:NULL));
2550 verbose(VERB_ALGO, "No response is set, servfail");
2551 return error_response(qstate, id, LDNS_RCODE_SERVFAIL);
2554 /* Make sure that the RA flag is set (since the presence of
2555 * this module means that recursion is available) */
2556 iq->response->rep->flags |= BIT_RA;
2558 /* Clear the AA flag */
2559 /* FIXME: does this action go here or in some other module? */
2560 iq->response->rep->flags &= ~BIT_AA;
2562 /* make sure QR flag is on */
2563 iq->response->rep->flags |= BIT_QR;
2565 /* we have finished processing this query */
2566 qstate->ext_state[id] = module_finished;
2568 /* TODO: we are using a private TTL, trim the response. */
2569 /* if (mPrivateTTL > 0){IterUtils.setPrivateTTL(resp, mPrivateTTL); } */
2571 /* prepend any items we have accumulated */
2572 if(iq->an_prepend_list || iq->ns_prepend_list) {
2573 if(!iter_prepend(iq, iq->response, qstate->region)) {
2574 log_err("prepend rrsets: out of memory");
2575 return error_response(qstate, id, LDNS_RCODE_SERVFAIL);
2577 /* reset the query name back */
2578 iq->response->qinfo = qstate->qinfo;
2579 /* the security state depends on the combination */
2580 iq->response->rep->security = sec_status_unchecked;
2581 /* store message with the finished prepended items,
2582 * but only if we did recursion. The nonrecursion referral
2583 * from cache does not need to be stored in the msg cache. */
2584 if(qstate->query_flags&BIT_RD) {
2585 iter_dns_store(qstate->env, &qstate->qinfo,
2586 iq->response->rep, 0, qstate->prefetch_leeway,
2587 iq->dp&&iq->dp->has_parent_side_NS,
2591 qstate->return_rcode = LDNS_RCODE_NOERROR;
2592 qstate->return_msg = iq->response;
2597 * Return priming query results to interestes super querystates.
2599 * Sets the delegation point and delegation message (not nonRD queries).
2600 * This is a callback from walk_supers.
2602 * @param qstate: query state that finished.
2603 * @param id: module id.
2604 * @param super: the qstate to inform.
2607 iter_inform_super(struct module_qstate* qstate, int id,
2608 struct module_qstate* super)
2610 if(!qstate->is_priming && super->qinfo.qclass == LDNS_RR_CLASS_ANY)
2611 processClassResponse(qstate, id, super);
2612 else if(super->qinfo.qtype == LDNS_RR_TYPE_DS && ((struct iter_qstate*)
2613 super->minfo[id])->state == DSNS_FIND_STATE)
2614 processDSNSResponse(qstate, id, super);
2615 else if(qstate->return_rcode != LDNS_RCODE_NOERROR)
2616 error_supers(qstate, id, super);
2617 else if(qstate->is_priming)
2618 prime_supers(qstate, id, super);
2619 else processTargetResponse(qstate, id, super);
2623 * Handle iterator state.
2624 * Handle events. This is the real processing loop for events, responsible
2625 * for moving events through the various states. If a processing method
2626 * returns true, then it will be advanced to the next state. If false, then
2627 * processing will stop.
2629 * @param qstate: query state.
2630 * @param ie: iterator shared global environment.
2631 * @param iq: iterator query state.
2632 * @param id: module id.
2635 iter_handle(struct module_qstate* qstate, struct iter_qstate* iq,
2636 struct iter_env* ie, int id)
2640 verbose(VERB_ALGO, "iter_handle processing q with state %s",
2641 iter_state_to_string(iq->state));
2643 case INIT_REQUEST_STATE:
2644 cont = processInitRequest(qstate, iq, ie, id);
2646 case INIT_REQUEST_2_STATE:
2647 cont = processInitRequest2(qstate, iq, id);
2649 case INIT_REQUEST_3_STATE:
2650 cont = processInitRequest3(qstate, iq, id);
2652 case QUERYTARGETS_STATE:
2653 cont = processQueryTargets(qstate, iq, ie, id);
2655 case QUERY_RESP_STATE:
2656 cont = processQueryResponse(qstate, iq, id);
2658 case PRIME_RESP_STATE:
2659 cont = processPrimeResponse(qstate, id);
2661 case COLLECT_CLASS_STATE:
2662 cont = processCollectClass(qstate, id);
2664 case DSNS_FIND_STATE:
2665 cont = processDSNSFind(qstate, iq, id);
2667 case FINISHED_STATE:
2668 cont = processFinished(qstate, iq, id);
2671 log_warn("iterator: invalid state: %d",
2680 * This is the primary entry point for processing request events. Note that
2681 * this method should only be used by external modules.
2682 * @param qstate: query state.
2683 * @param ie: iterator shared global environment.
2684 * @param iq: iterator query state.
2685 * @param id: module id.
2688 process_request(struct module_qstate* qstate, struct iter_qstate* iq,
2689 struct iter_env* ie, int id)
2691 /* external requests start in the INIT state, and finish using the
2692 * FINISHED state. */
2693 iq->state = INIT_REQUEST_STATE;
2694 iq->final_state = FINISHED_STATE;
2695 verbose(VERB_ALGO, "process_request: new external request event");
2696 iter_handle(qstate, iq, ie, id);
2699 /** process authoritative server reply */
2701 process_response(struct module_qstate* qstate, struct iter_qstate* iq,
2702 struct iter_env* ie, int id, struct outbound_entry* outbound,
2703 enum module_ev event)
2705 struct msg_parse* prs;
2706 struct edns_data edns;
2709 verbose(VERB_ALGO, "process_response: new external response event");
2710 iq->response = NULL;
2711 iq->state = QUERY_RESP_STATE;
2712 if(event == module_event_noreply || event == module_event_error) {
2715 if( (event != module_event_reply && event != module_event_capsfail)
2716 || !qstate->reply) {
2717 log_err("Bad event combined with response");
2718 outbound_list_remove(&iq->outlist, outbound);
2719 (void)error_response(qstate, id, LDNS_RCODE_SERVFAIL);
2724 prs = (struct msg_parse*)regional_alloc(qstate->env->scratch,
2725 sizeof(struct msg_parse));
2727 log_err("out of memory on incoming message");
2728 /* like packet got dropped */
2731 memset(prs, 0, sizeof(*prs));
2732 memset(&edns, 0, sizeof(edns));
2733 pkt = qstate->reply->c->buffer;
2734 ldns_buffer_set_position(pkt, 0);
2735 if(parse_packet(pkt, prs, qstate->env->scratch) != LDNS_RCODE_NOERROR) {
2736 verbose(VERB_ALGO, "parse error on reply packet");
2739 /* edns is not examined, but removed from message to help cache */
2740 if(parse_extract_edns(prs, &edns) != LDNS_RCODE_NOERROR)
2742 /* remove CD-bit, we asked for in case we handle validation ourself */
2743 prs->flags &= ~BIT_CD;
2745 /* normalize and sanitize: easy to delete items from linked lists */
2746 if(!scrub_message(pkt, prs, &iq->qchase, iq->dp->name,
2747 qstate->env->scratch, qstate->env, ie))
2750 /* allocate response dns_msg in region */
2751 iq->response = dns_alloc_msg(pkt, prs, qstate->region);
2754 log_query_info(VERB_DETAIL, "response for", &qstate->qinfo);
2755 log_name_addr(VERB_DETAIL, "reply from", iq->dp->name,
2756 &qstate->reply->addr, qstate->reply->addrlen);
2757 if(verbosity >= VERB_ALGO)
2758 log_dns_msg("incoming scrubbed packet:", &iq->response->qinfo,
2761 if(event == module_event_capsfail) {
2762 if(!iq->caps_fallback) {
2763 /* start fallback */
2764 iq->caps_fallback = 1;
2765 iq->caps_server = 0;
2766 iq->caps_reply = iq->response->rep;
2767 iq->state = QUERYTARGETS_STATE;
2768 iq->num_current_queries--;
2769 verbose(VERB_DETAIL, "Capsforid: starting fallback");
2772 /* check if reply is the same, otherwise, fail */
2773 if(!reply_equal(iq->response->rep, iq->caps_reply,
2774 qstate->env->scratch_buffer)) {
2775 verbose(VERB_DETAIL, "Capsforid fallback: "
2776 "getting different replies, failed");
2777 outbound_list_remove(&iq->outlist, outbound);
2778 (void)error_response(qstate, id,
2779 LDNS_RCODE_SERVFAIL);
2782 /* continue the fallback procedure at next server */
2784 iq->state = QUERYTARGETS_STATE;
2785 iq->num_current_queries--;
2786 verbose(VERB_DETAIL, "Capsforid: reply is equal. "
2787 "go to next fallback");
2791 iq->caps_fallback = 0; /* if we were in fallback, 0x20 is OK now */
2794 outbound_list_remove(&iq->outlist, outbound);
2795 iter_handle(qstate, iq, ie, id);
2799 iter_operate(struct module_qstate* qstate, enum module_ev event, int id,
2800 struct outbound_entry* outbound)
2802 struct iter_env* ie = (struct iter_env*)qstate->env->modinfo[id];
2803 struct iter_qstate* iq = (struct iter_qstate*)qstate->minfo[id];
2804 verbose(VERB_QUERY, "iterator[module %d] operate: extstate:%s event:%s",
2805 id, strextstate(qstate->ext_state[id]), strmodulevent(event));
2806 if(iq) log_query_info(VERB_QUERY, "iterator operate: query",
2808 if(iq && qstate->qinfo.qname != iq->qchase.qname)
2809 log_query_info(VERB_QUERY, "iterator operate: chased to",
2812 /* perform iterator state machine */
2813 if((event == module_event_new || event == module_event_pass) &&
2815 if(!iter_new(qstate, id)) {
2816 (void)error_response(qstate, id, LDNS_RCODE_SERVFAIL);
2819 iq = (struct iter_qstate*)qstate->minfo[id];
2820 process_request(qstate, iq, ie, id);
2823 if(iq && event == module_event_pass) {
2824 iter_handle(qstate, iq, ie, id);
2827 if(iq && outbound) {
2828 process_response(qstate, iq, ie, id, outbound, event);
2831 if(event == module_event_error) {
2832 verbose(VERB_ALGO, "got called with event error, giving up");
2833 (void)error_response(qstate, id, LDNS_RCODE_SERVFAIL);
2837 log_err("bad event for iterator");
2838 (void)error_response(qstate, id, LDNS_RCODE_SERVFAIL);
2842 iter_clear(struct module_qstate* qstate, int id)
2844 struct iter_qstate* iq;
2847 iq = (struct iter_qstate*)qstate->minfo[id];
2849 outbound_list_clear(&iq->outlist);
2850 iq->num_current_queries = 0;
2852 qstate->minfo[id] = NULL;
2856 iter_get_mem(struct module_env* env, int id)
2858 struct iter_env* ie = (struct iter_env*)env->modinfo[id];
2861 return sizeof(*ie) + sizeof(int)*((size_t)ie->max_dependency_depth+1)
2862 + donotq_get_mem(ie->donotq) + priv_get_mem(ie->priv);
2866 * The iterator function block
2868 static struct module_func_block iter_block = {
2870 &iter_init, &iter_deinit, &iter_operate, &iter_inform_super,
2871 &iter_clear, &iter_get_mem
2874 struct module_func_block*
2875 iter_get_funcblock(void)
2881 iter_state_to_string(enum iter_state state)
2885 case INIT_REQUEST_STATE :
2886 return "INIT REQUEST STATE";
2887 case INIT_REQUEST_2_STATE :
2888 return "INIT REQUEST STATE (stage 2)";
2889 case INIT_REQUEST_3_STATE:
2890 return "INIT REQUEST STATE (stage 3)";
2891 case QUERYTARGETS_STATE :
2892 return "QUERY TARGETS STATE";
2893 case PRIME_RESP_STATE :
2894 return "PRIME RESPONSE STATE";
2895 case COLLECT_CLASS_STATE :
2896 return "COLLECT CLASS STATE";
2897 case DSNS_FIND_STATE :
2898 return "DSNS FIND STATE";
2899 case QUERY_RESP_STATE :
2900 return "QUERY RESPONSE STATE";
2901 case FINISHED_STATE :
2902 return "FINISHED RESPONSE STATE";
2904 return "UNKNOWN ITER STATE";
2909 iter_state_is_responsestate(enum iter_state s)
2912 case INIT_REQUEST_STATE :
2913 case INIT_REQUEST_2_STATE :
2914 case INIT_REQUEST_3_STATE :
2915 case QUERYTARGETS_STATE :
2916 case COLLECT_CLASS_STATE :