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