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 recursive 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/rrset.h" 56 #include "services/cache/infra.h" 57 #include "services/authzone.h" 58 #include "util/module.h" 59 #include "util/netevent.h" 60 #include "util/net_help.h" 61 #include "util/regional.h" 62 #include "util/data/dname.h" 63 #include "util/data/msgencode.h" 64 #include "util/fptr_wlist.h" 65 #include "util/config_file.h" 66 #include "util/random.h" 67 #include "sldns/rrdef.h" 68 #include "sldns/wire2str.h" 69 #include "sldns/str2wire.h" 70 #include "sldns/parseutil.h" 71 #include "sldns/sbuffer.h" 72 73 /* number of packets */ 74 int MAX_GLOBAL_QUOTA = 200; 75 /* in msec */ 76 int UNKNOWN_SERVER_NICENESS = 376; 77 /* in msec */ 78 int USEFUL_SERVER_TOP_TIMEOUT = 120000; 79 /* Equals USEFUL_SERVER_TOP_TIMEOUT*4 */ 80 int BLACKLIST_PENALTY = (120000*4); 81 /** Timeout when only a single probe query per IP is allowed. */ 82 int PROBE_MAXRTO = PROBE_MAXRTO_DEFAULT; /* in msec */ 83 84 static void target_count_increase_nx(struct iter_qstate* iq, int num); 85 86 int 87 iter_init(struct module_env* env, int id) 88 { 89 struct iter_env* iter_env = (struct iter_env*)calloc(1, 90 sizeof(struct iter_env)); 91 if(!iter_env) { 92 log_err("malloc failure"); 93 return 0; 94 } 95 env->modinfo[id] = (void*)iter_env; 96 97 lock_basic_init(&iter_env->queries_ratelimit_lock); 98 lock_protect(&iter_env->queries_ratelimit_lock, 99 &iter_env->num_queries_ratelimited, 100 sizeof(iter_env->num_queries_ratelimited)); 101 102 if(!iter_apply_cfg(iter_env, env->cfg)) { 103 log_err("iterator: could not apply configuration settings."); 104 return 0; 105 } 106 107 return 1; 108 } 109 110 void 111 iter_deinit(struct module_env* env, int id) 112 { 113 struct iter_env* iter_env; 114 if(!env || !env->modinfo[id]) 115 return; 116 iter_env = (struct iter_env*)env->modinfo[id]; 117 lock_basic_destroy(&iter_env->queries_ratelimit_lock); 118 free(iter_env->target_fetch_policy); 119 priv_delete(iter_env->priv); 120 donotq_delete(iter_env->donotq); 121 caps_white_delete(iter_env->caps_white); 122 free(iter_env); 123 env->modinfo[id] = NULL; 124 } 125 126 /** new query for iterator */ 127 static int 128 iter_new(struct module_qstate* qstate, int id) 129 { 130 struct iter_qstate* iq = (struct iter_qstate*)regional_alloc( 131 qstate->region, sizeof(struct iter_qstate)); 132 qstate->minfo[id] = iq; 133 if(!iq) 134 return 0; 135 memset(iq, 0, sizeof(*iq)); 136 iq->state = INIT_REQUEST_STATE; 137 iq->final_state = FINISHED_STATE; 138 iq->an_prepend_list = NULL; 139 iq->an_prepend_last = NULL; 140 iq->ns_prepend_list = NULL; 141 iq->ns_prepend_last = NULL; 142 iq->dp = NULL; 143 iq->depth = 0; 144 iq->num_target_queries = 0; 145 iq->num_current_queries = 0; 146 iq->query_restart_count = 0; 147 iq->referral_count = 0; 148 iq->sent_count = 0; 149 iq->ratelimit_ok = 0; 150 iq->target_count = NULL; 151 iq->dp_target_count = 0; 152 iq->wait_priming_stub = 0; 153 iq->refetch_glue = 0; 154 iq->dnssec_expected = 0; 155 iq->dnssec_lame_query = 0; 156 iq->chase_flags = qstate->query_flags; 157 /* Start with the (current) qname. */ 158 iq->qchase = qstate->qinfo; 159 outbound_list_init(&iq->outlist); 160 iq->minimise_count = 0; 161 iq->timeout_count = 0; 162 if (qstate->env->cfg->qname_minimisation) 163 iq->minimisation_state = INIT_MINIMISE_STATE; 164 else 165 iq->minimisation_state = DONOT_MINIMISE_STATE; 166 167 memset(&iq->qinfo_out, 0, sizeof(struct query_info)); 168 return 1; 169 } 170 171 /** 172 * Transition to the next state. This can be used to advance a currently 173 * processing event. It cannot be used to reactivate a forEvent. 174 * 175 * @param iq: iterator query state 176 * @param nextstate The state to transition to. 177 * @return true. This is so this can be called as the return value for the 178 * actual process*State() methods. (Transitioning to the next state 179 * implies further processing). 180 */ 181 static int 182 next_state(struct iter_qstate* iq, enum iter_state nextstate) 183 { 184 /* If transitioning to a "response" state, make sure that there is a 185 * response */ 186 if(iter_state_is_responsestate(nextstate)) { 187 if(iq->response == NULL) { 188 log_err("transitioning to response state sans " 189 "response."); 190 } 191 } 192 iq->state = nextstate; 193 return 1; 194 } 195 196 /** 197 * Transition an event to its final state. Final states always either return 198 * a result up the module chain, or reactivate a dependent event. Which 199 * final state to transition to is set in the module state for the event when 200 * it was created, and depends on the original purpose of the event. 201 * 202 * The response is stored in the qstate->buf buffer. 203 * 204 * @param iq: iterator query state 205 * @return false. This is so this method can be used as the return value for 206 * the processState methods. (Transitioning to the final state 207 */ 208 static int 209 final_state(struct iter_qstate* iq) 210 { 211 return next_state(iq, iq->final_state); 212 } 213 214 /** 215 * Callback routine to handle errors in parent query states 216 * @param qstate: query state that failed. 217 * @param id: module id. 218 * @param super: super state. 219 */ 220 static void 221 error_supers(struct module_qstate* qstate, int id, struct module_qstate* super) 222 { 223 struct iter_env* ie = (struct iter_env*)qstate->env->modinfo[id]; 224 struct iter_qstate* super_iq = (struct iter_qstate*)super->minfo[id]; 225 226 if(qstate->qinfo.qtype == LDNS_RR_TYPE_A || 227 qstate->qinfo.qtype == LDNS_RR_TYPE_AAAA) { 228 /* mark address as failed. */ 229 struct delegpt_ns* dpns = NULL; 230 super_iq->num_target_queries--; 231 if(super_iq->dp) 232 dpns = delegpt_find_ns(super_iq->dp, 233 qstate->qinfo.qname, qstate->qinfo.qname_len); 234 if(!dpns) { 235 /* not interested */ 236 /* this can happen, for eg. qname minimisation asked 237 * for an NXDOMAIN to be validated, and used qtype 238 * A for that, and the error of that, the name, is 239 * not listed in super_iq->dp */ 240 verbose(VERB_ALGO, "subq error, but not interested"); 241 log_query_info(VERB_ALGO, "superq", &super->qinfo); 242 return; 243 } else { 244 /* see if the failure did get (parent-lame) info */ 245 if(!cache_fill_missing(super->env, super_iq->qchase.qclass, 246 super->region, super_iq->dp, 0)) 247 log_err("out of memory adding missing"); 248 } 249 delegpt_mark_neg(dpns, qstate->qinfo.qtype); 250 if((dpns->got4 == 2 || (!ie->supports_ipv4 && !ie->nat64.use_nat64)) && 251 (dpns->got6 == 2 || !ie->supports_ipv6)) { 252 dpns->resolved = 1; /* mark as failed */ 253 target_count_increase_nx(super_iq, 1); 254 } 255 } 256 if(qstate->qinfo.qtype == LDNS_RR_TYPE_NS) { 257 /* prime failed to get delegation */ 258 super_iq->dp = NULL; 259 } 260 /* evaluate targets again */ 261 super_iq->state = QUERYTARGETS_STATE; 262 /* super becomes runnable, and will process this change */ 263 } 264 265 /** 266 * Return an error to the client 267 * @param qstate: our query state 268 * @param id: module id 269 * @param rcode: error code (DNS errcode). 270 * @return: 0 for use by caller, to make notation easy, like: 271 * return error_response(..). 272 */ 273 static int 274 error_response(struct module_qstate* qstate, int id, int rcode) 275 { 276 verbose(VERB_QUERY, "return error response %s", 277 sldns_lookup_by_id(sldns_rcodes, rcode)? 278 sldns_lookup_by_id(sldns_rcodes, rcode)->name:"??"); 279 qstate->return_rcode = rcode; 280 qstate->return_msg = NULL; 281 qstate->ext_state[id] = module_finished; 282 return 0; 283 } 284 285 /** 286 * Return an error to the client and cache the error code in the 287 * message cache (so per qname, qtype, qclass). 288 * @param qstate: our query state 289 * @param id: module id 290 * @param rcode: error code (DNS errcode). 291 * @return: 0 for use by caller, to make notation easy, like: 292 * return error_response(..). 293 */ 294 static int 295 error_response_cache(struct module_qstate* qstate, int id, int rcode) 296 { 297 struct reply_info err; 298 struct msgreply_entry* msg; 299 if(qstate->no_cache_store) { 300 return error_response(qstate, id, rcode); 301 } 302 if(qstate->prefetch_leeway > NORR_TTL) { 303 verbose(VERB_ALGO, "error response for prefetch in cache"); 304 /* attempt to adjust the cache entry prefetch */ 305 if(dns_cache_prefetch_adjust(qstate->env, &qstate->qinfo, 306 NORR_TTL, qstate->query_flags)) 307 return error_response(qstate, id, rcode); 308 /* if that fails (not in cache), fall through to store err */ 309 } 310 if((msg=msg_cache_lookup(qstate->env, 311 qstate->qinfo.qname, qstate->qinfo.qname_len, 312 qstate->qinfo.qtype, qstate->qinfo.qclass, 313 qstate->query_flags, 0, 314 qstate->env->cfg->serve_expired)) != NULL) { 315 struct reply_info* rep = (struct reply_info*)msg->entry.data; 316 if(qstate->env->cfg->serve_expired && rep) { 317 if(qstate->env->cfg->serve_expired_ttl_reset && 318 *qstate->env->now + qstate->env->cfg->serve_expired_ttl 319 > rep->serve_expired_ttl) { 320 verbose(VERB_ALGO, "reset serve-expired-ttl for " 321 "response in cache"); 322 rep->serve_expired_ttl = *qstate->env->now + 323 qstate->env->cfg->serve_expired_ttl; 324 } 325 verbose(VERB_ALGO, "set serve-expired-norec-ttl for " 326 "response in cache"); 327 rep->serve_expired_norec_ttl = NORR_TTL + 328 *qstate->env->now; 329 } 330 if(rep && (FLAGS_GET_RCODE(rep->flags) == 331 LDNS_RCODE_NOERROR || 332 FLAGS_GET_RCODE(rep->flags) == 333 LDNS_RCODE_NXDOMAIN || 334 FLAGS_GET_RCODE(rep->flags) == 335 LDNS_RCODE_YXDOMAIN) && 336 (qstate->env->cfg->serve_expired || 337 *qstate->env->now <= rep->ttl)) { 338 /* we have a good entry, don't overwrite */ 339 lock_rw_unlock(&msg->entry.lock); 340 return error_response(qstate, id, rcode); 341 } 342 lock_rw_unlock(&msg->entry.lock); 343 /* nothing interesting is cached (already error response or 344 * expired good record when we don't serve expired), so this 345 * servfail cache entry is useful (stops waste of time on this 346 * servfail NORR_TTL) */ 347 } 348 /* store in cache */ 349 memset(&err, 0, sizeof(err)); 350 err.flags = (uint16_t)(BIT_QR | BIT_RA); 351 FLAGS_SET_RCODE(err.flags, rcode); 352 err.qdcount = 1; 353 err.ttl = NORR_TTL; 354 err.prefetch_ttl = PREFETCH_TTL_CALC(err.ttl); 355 err.serve_expired_ttl = NORR_TTL; 356 /* do not waste time trying to validate this servfail */ 357 err.security = sec_status_indeterminate; 358 verbose(VERB_ALGO, "store error response in message cache"); 359 iter_dns_store(qstate->env, &qstate->qinfo, &err, 0, 0, 0, NULL, 360 qstate->query_flags, qstate->qstarttime, qstate->is_valrec); 361 return error_response(qstate, id, rcode); 362 } 363 364 /** check if prepend item is duplicate item */ 365 static int 366 prepend_is_duplicate(struct ub_packed_rrset_key** sets, size_t to, 367 struct ub_packed_rrset_key* dup) 368 { 369 size_t i; 370 for(i=0; i<to; i++) { 371 if(sets[i]->rk.type == dup->rk.type && 372 sets[i]->rk.rrset_class == dup->rk.rrset_class && 373 sets[i]->rk.dname_len == dup->rk.dname_len && 374 query_dname_compare(sets[i]->rk.dname, dup->rk.dname) 375 == 0) 376 return 1; 377 } 378 return 0; 379 } 380 381 /** prepend the prepend list in the answer and authority section of dns_msg */ 382 static int 383 iter_prepend(struct iter_qstate* iq, struct dns_msg* msg, 384 struct regional* region) 385 { 386 struct iter_prep_list* p; 387 struct ub_packed_rrset_key** sets; 388 size_t num_an = 0, num_ns = 0;; 389 for(p = iq->an_prepend_list; p; p = p->next) 390 num_an++; 391 for(p = iq->ns_prepend_list; p; p = p->next) 392 num_ns++; 393 if(num_an + num_ns == 0) 394 return 1; 395 verbose(VERB_ALGO, "prepending %d rrsets", (int)num_an + (int)num_ns); 396 if(num_an > RR_COUNT_MAX || num_ns > RR_COUNT_MAX || 397 msg->rep->rrset_count > RR_COUNT_MAX) return 0; /* overflow */ 398 sets = regional_alloc(region, (num_an+num_ns+msg->rep->rrset_count) * 399 sizeof(struct ub_packed_rrset_key*)); 400 if(!sets) 401 return 0; 402 /* ANSWER section */ 403 num_an = 0; 404 for(p = iq->an_prepend_list; p; p = p->next) { 405 sets[num_an++] = p->rrset; 406 if(ub_packed_rrset_ttl(p->rrset) < msg->rep->ttl) { 407 msg->rep->ttl = ub_packed_rrset_ttl(p->rrset); 408 msg->rep->prefetch_ttl = PREFETCH_TTL_CALC(msg->rep->ttl); 409 msg->rep->serve_expired_ttl = msg->rep->ttl + SERVE_EXPIRED_TTL; 410 } 411 } 412 memcpy(sets+num_an, msg->rep->rrsets, msg->rep->an_numrrsets * 413 sizeof(struct ub_packed_rrset_key*)); 414 /* AUTH section */ 415 num_ns = 0; 416 for(p = iq->ns_prepend_list; p; p = p->next) { 417 if(prepend_is_duplicate(sets+msg->rep->an_numrrsets+num_an, 418 num_ns, p->rrset) || prepend_is_duplicate( 419 msg->rep->rrsets+msg->rep->an_numrrsets, 420 msg->rep->ns_numrrsets, p->rrset)) 421 continue; 422 sets[msg->rep->an_numrrsets + num_an + num_ns++] = p->rrset; 423 if(ub_packed_rrset_ttl(p->rrset) < msg->rep->ttl) { 424 msg->rep->ttl = ub_packed_rrset_ttl(p->rrset); 425 msg->rep->prefetch_ttl = PREFETCH_TTL_CALC(msg->rep->ttl); 426 msg->rep->serve_expired_ttl = msg->rep->ttl + SERVE_EXPIRED_TTL; 427 } 428 } 429 memcpy(sets + num_an + msg->rep->an_numrrsets + num_ns, 430 msg->rep->rrsets + msg->rep->an_numrrsets, 431 (msg->rep->ns_numrrsets + msg->rep->ar_numrrsets) * 432 sizeof(struct ub_packed_rrset_key*)); 433 434 /* NXDOMAIN rcode can stay if we prepended DNAME/CNAMEs, because 435 * this is what recursors should give. */ 436 msg->rep->rrset_count += num_an + num_ns; 437 msg->rep->an_numrrsets += num_an; 438 msg->rep->ns_numrrsets += num_ns; 439 msg->rep->rrsets = sets; 440 return 1; 441 } 442 443 /** 444 * Find rrset in ANSWER prepend list. 445 * to avoid duplicate DNAMEs when a DNAME is traversed twice. 446 * @param iq: iterator query state. 447 * @param rrset: rrset to add. 448 * @return false if not found 449 */ 450 static int 451 iter_find_rrset_in_prepend_answer(struct iter_qstate* iq, 452 struct ub_packed_rrset_key* rrset) 453 { 454 struct iter_prep_list* p = iq->an_prepend_list; 455 while(p) { 456 if(ub_rrset_compare(p->rrset, rrset) == 0 && 457 rrsetdata_equal((struct packed_rrset_data*)p->rrset 458 ->entry.data, (struct packed_rrset_data*)rrset 459 ->entry.data)) 460 return 1; 461 p = p->next; 462 } 463 return 0; 464 } 465 466 /** 467 * Add rrset to ANSWER prepend list 468 * @param qstate: query state. 469 * @param iq: iterator query state. 470 * @param rrset: rrset to add. 471 * @return false on failure (malloc). 472 */ 473 static int 474 iter_add_prepend_answer(struct module_qstate* qstate, struct iter_qstate* iq, 475 struct ub_packed_rrset_key* rrset) 476 { 477 struct iter_prep_list* p = (struct iter_prep_list*)regional_alloc( 478 qstate->region, sizeof(struct iter_prep_list)); 479 if(!p) 480 return 0; 481 p->rrset = rrset; 482 p->next = NULL; 483 /* add at end */ 484 if(iq->an_prepend_last) 485 iq->an_prepend_last->next = p; 486 else iq->an_prepend_list = p; 487 iq->an_prepend_last = p; 488 return 1; 489 } 490 491 /** 492 * Add rrset to AUTHORITY prepend list 493 * @param qstate: query state. 494 * @param iq: iterator query state. 495 * @param rrset: rrset to add. 496 * @return false on failure (malloc). 497 */ 498 static int 499 iter_add_prepend_auth(struct module_qstate* qstate, struct iter_qstate* iq, 500 struct ub_packed_rrset_key* rrset) 501 { 502 struct iter_prep_list* p = (struct iter_prep_list*)regional_alloc( 503 qstate->region, sizeof(struct iter_prep_list)); 504 if(!p) 505 return 0; 506 p->rrset = rrset; 507 p->next = NULL; 508 /* add at end */ 509 if(iq->ns_prepend_last) 510 iq->ns_prepend_last->next = p; 511 else iq->ns_prepend_list = p; 512 iq->ns_prepend_last = p; 513 return 1; 514 } 515 516 /** 517 * Given a CNAME response (defined as a response containing a CNAME or DNAME 518 * that does not answer the request), process the response, modifying the 519 * state as necessary. This follows the CNAME/DNAME chain and returns the 520 * final query name. 521 * 522 * sets the new query name, after following the CNAME/DNAME chain. 523 * @param qstate: query state. 524 * @param iq: iterator query state. 525 * @param msg: the response. 526 * @param mname: returned target new query name. 527 * @param mname_len: length of mname. 528 * @return false on (malloc) error. 529 */ 530 static int 531 handle_cname_response(struct module_qstate* qstate, struct iter_qstate* iq, 532 struct dns_msg* msg, uint8_t** mname, size_t* mname_len) 533 { 534 size_t i; 535 /* Start with the (current) qname. */ 536 *mname = iq->qchase.qname; 537 *mname_len = iq->qchase.qname_len; 538 539 /* Iterate over the ANSWER rrsets in order, looking for CNAMEs and 540 * DNAMES. */ 541 for(i=0; i<msg->rep->an_numrrsets; i++) { 542 struct ub_packed_rrset_key* r = msg->rep->rrsets[i]; 543 /* If there is a (relevant) DNAME, add it to the list. 544 * We always expect there to be CNAME that was generated 545 * by this DNAME following, so we don't process the DNAME 546 * directly. */ 547 if(ntohs(r->rk.type) == LDNS_RR_TYPE_DNAME && 548 dname_strict_subdomain_c(*mname, r->rk.dname) && 549 !iter_find_rrset_in_prepend_answer(iq, r)) { 550 if(!iter_add_prepend_answer(qstate, iq, r)) 551 return 0; 552 continue; 553 } 554 555 if(ntohs(r->rk.type) == LDNS_RR_TYPE_CNAME && 556 query_dname_compare(*mname, r->rk.dname) == 0 && 557 !iter_find_rrset_in_prepend_answer(iq, r)) { 558 /* Add this relevant CNAME rrset to the prepend list.*/ 559 if(!iter_add_prepend_answer(qstate, iq, r)) 560 return 0; 561 get_cname_target(r, mname, mname_len); 562 } 563 564 /* Other rrsets in the section are ignored. */ 565 } 566 /* add authority rrsets to authority prepend, for wildcarded CNAMEs */ 567 for(i=msg->rep->an_numrrsets; i<msg->rep->an_numrrsets + 568 msg->rep->ns_numrrsets; i++) { 569 struct ub_packed_rrset_key* r = msg->rep->rrsets[i]; 570 /* only add NSEC/NSEC3, as they may be needed for validation */ 571 if(ntohs(r->rk.type) == LDNS_RR_TYPE_NSEC || 572 ntohs(r->rk.type) == LDNS_RR_TYPE_NSEC3) { 573 if(!iter_add_prepend_auth(qstate, iq, r)) 574 return 0; 575 } 576 } 577 return 1; 578 } 579 580 /** fill fail address for later recovery */ 581 static void 582 fill_fail_addr(struct iter_qstate* iq, struct sockaddr_storage* addr, 583 socklen_t addrlen) 584 { 585 if(addrlen == 0) { 586 iq->fail_addr_type = 0; 587 return; 588 } 589 if(((struct sockaddr_in*)addr)->sin_family == AF_INET) { 590 iq->fail_addr_type = 4; 591 memcpy(&iq->fail_addr.in, 592 &((struct sockaddr_in*)addr)->sin_addr, 593 sizeof(iq->fail_addr.in)); 594 } 595 #ifdef AF_INET6 596 else if(((struct sockaddr_in*)addr)->sin_family == AF_INET6) { 597 iq->fail_addr_type = 6; 598 memcpy(&iq->fail_addr.in6, 599 &((struct sockaddr_in6*)addr)->sin6_addr, 600 sizeof(iq->fail_addr.in6)); 601 } 602 #endif 603 else { 604 iq->fail_addr_type = 0; 605 } 606 } 607 608 /** print fail addr to string */ 609 static void 610 print_fail_addr(struct iter_qstate* iq, char* buf, size_t len) 611 { 612 if(iq->fail_addr_type == 4) { 613 if(inet_ntop(AF_INET, &iq->fail_addr.in, buf, 614 (socklen_t)len) == 0) 615 (void)strlcpy(buf, "(inet_ntop error)", len); 616 } 617 #ifdef AF_INET6 618 else if(iq->fail_addr_type == 6) { 619 if(inet_ntop(AF_INET6, &iq->fail_addr.in6, buf, 620 (socklen_t)len) == 0) 621 (void)strlcpy(buf, "(inet_ntop error)", len); 622 } 623 #endif 624 else 625 (void)strlcpy(buf, "", len); 626 } 627 628 /** add response specific error information for log servfail */ 629 static void 630 errinf_reply(struct module_qstate* qstate, struct iter_qstate* iq) 631 { 632 if(qstate->env->cfg->val_log_level < 2 && !qstate->env->cfg->log_servfail) 633 return; 634 if((qstate->reply && qstate->reply->remote_addrlen != 0) || 635 (iq->fail_addr_type != 0)) { 636 char from[256], frm[512]; 637 if(qstate->reply && qstate->reply->remote_addrlen != 0) 638 addr_to_str(&qstate->reply->remote_addr, 639 qstate->reply->remote_addrlen, from, 640 sizeof(from)); 641 else 642 print_fail_addr(iq, from, sizeof(from)); 643 snprintf(frm, sizeof(frm), "from %s", from); 644 errinf(qstate, frm); 645 } 646 if(iq->scrub_failures || iq->parse_failures) { 647 if(iq->scrub_failures) 648 errinf(qstate, "upstream response failed scrub"); 649 if(iq->parse_failures) 650 errinf(qstate, "could not parse upstream response"); 651 } else if(iq->response == NULL && iq->timeout_count != 0) { 652 errinf(qstate, "upstream server timeout"); 653 } else if(iq->response == NULL) { 654 errinf(qstate, "no server to query"); 655 if(iq->dp) { 656 if(iq->dp->target_list == NULL) 657 errinf(qstate, "no addresses for nameservers"); 658 else errinf(qstate, "nameserver addresses not usable"); 659 if(iq->dp->nslist == NULL) 660 errinf(qstate, "have no nameserver names"); 661 if(iq->dp->bogus) 662 errinf(qstate, "NS record was dnssec bogus"); 663 } 664 } 665 if(iq->response && iq->response->rep) { 666 if(FLAGS_GET_RCODE(iq->response->rep->flags) != 0) { 667 char rcode[256], rc[32]; 668 (void)sldns_wire2str_rcode_buf( 669 FLAGS_GET_RCODE(iq->response->rep->flags), 670 rc, sizeof(rc)); 671 snprintf(rcode, sizeof(rcode), "got %s", rc); 672 errinf(qstate, rcode); 673 } else { 674 /* rcode NOERROR */ 675 if(iq->response->rep->an_numrrsets == 0) { 676 errinf(qstate, "nodata answer"); 677 } 678 } 679 } 680 } 681 682 /** see if last resort is possible - does config allow queries to parent */ 683 static int 684 can_have_last_resort(struct module_env* env, uint8_t* nm, size_t ATTR_UNUSED(nmlen), 685 uint16_t qclass, int* have_dp, struct delegpt** retdp, 686 struct regional* region) 687 { 688 struct delegpt* dp = NULL; 689 int nolock = 0; 690 /* do not process a last resort (the parent side) if a stub 691 * or forward is configured, because we do not want to go 'above' 692 * the configured servers */ 693 if(!dname_is_root(nm) && 694 (dp = hints_find(env->hints, nm, qclass, nolock)) && 695 /* has_parent side is turned off for stub_first, where we 696 * are allowed to go to the parent */ 697 dp->has_parent_side_NS) { 698 if(retdp) *retdp = delegpt_copy(dp, region); 699 lock_rw_unlock(&env->hints->lock); 700 if(have_dp) *have_dp = 1; 701 return 0; 702 } 703 if(dp) { 704 lock_rw_unlock(&env->hints->lock); 705 dp = NULL; 706 } 707 if((dp = forwards_find(env->fwds, nm, qclass, nolock)) && 708 /* has_parent_side is turned off for forward_first, where 709 * we are allowed to go to the parent */ 710 dp->has_parent_side_NS) { 711 if(retdp) *retdp = delegpt_copy(dp, region); 712 lock_rw_unlock(&env->fwds->lock); 713 if(have_dp) *have_dp = 1; 714 return 0; 715 } 716 /* lock_() calls are macros that could be nothing, surround in {} */ 717 if(dp) { lock_rw_unlock(&env->fwds->lock); } 718 return 1; 719 } 720 721 /** see if target name is caps-for-id whitelisted */ 722 static int 723 is_caps_whitelisted(struct iter_env* ie, struct iter_qstate* iq) 724 { 725 if(!ie->caps_white) return 0; /* no whitelist, or no capsforid */ 726 return name_tree_lookup(ie->caps_white, iq->qchase.qname, 727 iq->qchase.qname_len, dname_count_labels(iq->qchase.qname), 728 iq->qchase.qclass) != NULL; 729 } 730 731 /** 732 * Create target count structure for this query. This is always explicitly 733 * created for the parent query. 734 */ 735 static void 736 target_count_create(struct iter_qstate* iq) 737 { 738 if(!iq->target_count) { 739 iq->target_count = (int*)calloc(TARGET_COUNT_MAX, sizeof(int)); 740 /* if calloc fails we simply do not track this number */ 741 if(iq->target_count) { 742 iq->target_count[TARGET_COUNT_REF] = 1; 743 iq->nxns_dp = (uint8_t**)calloc(1, sizeof(uint8_t*)); 744 } 745 } 746 } 747 748 static void 749 target_count_increase(struct iter_qstate* iq, int num) 750 { 751 target_count_create(iq); 752 if(iq->target_count) 753 iq->target_count[TARGET_COUNT_QUERIES] += num; 754 iq->dp_target_count++; 755 } 756 757 static void 758 target_count_increase_nx(struct iter_qstate* iq, int num) 759 { 760 target_count_create(iq); 761 if(iq->target_count) 762 iq->target_count[TARGET_COUNT_NX] += num; 763 } 764 765 static void 766 target_count_increase_global_quota(struct iter_qstate* iq, int num) 767 { 768 target_count_create(iq); 769 if(iq->target_count) 770 iq->target_count[TARGET_COUNT_GLOBAL_QUOTA] += num; 771 } 772 773 /** 774 * Generate a subrequest. 775 * Generate a local request event. Local events are tied to this module, and 776 * have a corresponding (first tier) event that is waiting for this event to 777 * resolve to continue. 778 * 779 * @param qname The query name for this request. 780 * @param qnamelen length of qname 781 * @param qtype The query type for this request. 782 * @param qclass The query class for this request. 783 * @param qstate The event that is generating this event. 784 * @param id: module id. 785 * @param iq: The iterator state that is generating this event. 786 * @param initial_state The initial response state (normally this 787 * is QUERY_RESP_STATE, unless it is known that the request won't 788 * need iterative processing 789 * @param finalstate The final state for the response to this request. 790 * @param subq_ret: if newly allocated, the subquerystate, or NULL if it does 791 * not need initialisation. 792 * @param v: if true, validation is done on the subquery. 793 * @param detached: true if this qstate should not attach to the subquery 794 * @return false on error (malloc). 795 */ 796 static int 797 generate_sub_request(uint8_t* qname, size_t qnamelen, uint16_t qtype, 798 uint16_t qclass, struct module_qstate* qstate, int id, 799 struct iter_qstate* iq, enum iter_state initial_state, 800 enum iter_state finalstate, struct module_qstate** subq_ret, int v, 801 int detached) 802 { 803 struct module_qstate* subq = NULL; 804 struct iter_qstate* subiq = NULL; 805 uint16_t qflags = 0; /* OPCODE QUERY, no flags */ 806 struct query_info qinf; 807 int prime = (finalstate == PRIME_RESP_STATE)?1:0; 808 int valrec = 0; 809 qinf.qname = qname; 810 qinf.qname_len = qnamelen; 811 qinf.qtype = qtype; 812 qinf.qclass = qclass; 813 qinf.local_alias = NULL; 814 815 /* RD should be set only when sending the query back through the INIT 816 * state. */ 817 if(initial_state == INIT_REQUEST_STATE) 818 qflags |= BIT_RD; 819 /* We set the CD flag so we can send this through the "head" of 820 * the resolution chain, which might have a validator. We are 821 * uninterested in validating things not on the direct resolution 822 * path. */ 823 if(!v) { 824 qflags |= BIT_CD; 825 valrec = 1; 826 } 827 828 if(detached) { 829 struct mesh_state* sub = NULL; 830 fptr_ok(fptr_whitelist_modenv_add_sub( 831 qstate->env->add_sub)); 832 if(!(*qstate->env->add_sub)(qstate, &qinf, 833 qflags, prime, valrec, &subq, &sub)){ 834 return 0; 835 } 836 } 837 else { 838 /* attach subquery, lookup existing or make a new one */ 839 fptr_ok(fptr_whitelist_modenv_attach_sub( 840 qstate->env->attach_sub)); 841 if(!(*qstate->env->attach_sub)(qstate, &qinf, qflags, prime, 842 valrec, &subq)) { 843 return 0; 844 } 845 } 846 *subq_ret = subq; 847 if(subq) { 848 /* initialise the new subquery */ 849 subq->curmod = id; 850 subq->ext_state[id] = module_state_initial; 851 subq->minfo[id] = regional_alloc(subq->region, 852 sizeof(struct iter_qstate)); 853 if(!subq->minfo[id]) { 854 log_err("init subq: out of memory"); 855 fptr_ok(fptr_whitelist_modenv_kill_sub( 856 qstate->env->kill_sub)); 857 (*qstate->env->kill_sub)(subq); 858 return 0; 859 } 860 subiq = (struct iter_qstate*)subq->minfo[id]; 861 memset(subiq, 0, sizeof(*subiq)); 862 subiq->num_target_queries = 0; 863 target_count_create(iq); 864 subiq->target_count = iq->target_count; 865 if(iq->target_count) { 866 iq->target_count[TARGET_COUNT_REF] ++; /* extra reference */ 867 subiq->nxns_dp = iq->nxns_dp; 868 } 869 subiq->dp_target_count = 0; 870 subiq->num_current_queries = 0; 871 subiq->depth = iq->depth+1; 872 outbound_list_init(&subiq->outlist); 873 subiq->state = initial_state; 874 subiq->final_state = finalstate; 875 subiq->qchase = subq->qinfo; 876 subiq->chase_flags = subq->query_flags; 877 subiq->refetch_glue = 0; 878 if(qstate->env->cfg->qname_minimisation) 879 subiq->minimisation_state = INIT_MINIMISE_STATE; 880 else 881 subiq->minimisation_state = DONOT_MINIMISE_STATE; 882 memset(&subiq->qinfo_out, 0, sizeof(struct query_info)); 883 } 884 return 1; 885 } 886 887 /** 888 * Generate and send a root priming request. 889 * @param qstate: the qtstate that triggered the need to prime. 890 * @param iq: iterator query state. 891 * @param id: module id. 892 * @param qclass: the class to prime. 893 * @return 0 on failure 894 */ 895 static int 896 prime_root(struct module_qstate* qstate, struct iter_qstate* iq, int id, 897 uint16_t qclass) 898 { 899 struct delegpt* dp; 900 struct module_qstate* subq; 901 int nolock = 0; 902 verbose(VERB_DETAIL, "priming . %s NS", 903 sldns_lookup_by_id(sldns_rr_classes, (int)qclass)? 904 sldns_lookup_by_id(sldns_rr_classes, (int)qclass)->name:"??"); 905 dp = hints_find_root(qstate->env->hints, qclass, nolock); 906 if(!dp) { 907 verbose(VERB_ALGO, "Cannot prime due to lack of hints"); 908 return 0; 909 } 910 /* Priming requests start at the QUERYTARGETS state, skipping 911 * the normal INIT state logic (which would cause an infloop). */ 912 if(!generate_sub_request((uint8_t*)"\000", 1, LDNS_RR_TYPE_NS, 913 qclass, qstate, id, iq, QUERYTARGETS_STATE, PRIME_RESP_STATE, 914 &subq, 0, 0)) { 915 lock_rw_unlock(&qstate->env->hints->lock); 916 verbose(VERB_ALGO, "could not prime root"); 917 return 0; 918 } 919 if(subq) { 920 struct iter_qstate* subiq = 921 (struct iter_qstate*)subq->minfo[id]; 922 /* Set the initial delegation point to the hint. 923 * copy dp, it is now part of the root prime query. 924 * dp was part of in the fixed hints structure. */ 925 subiq->dp = delegpt_copy(dp, subq->region); 926 lock_rw_unlock(&qstate->env->hints->lock); 927 if(!subiq->dp) { 928 log_err("out of memory priming root, copydp"); 929 fptr_ok(fptr_whitelist_modenv_kill_sub( 930 qstate->env->kill_sub)); 931 (*qstate->env->kill_sub)(subq); 932 return 0; 933 } 934 /* there should not be any target queries. */ 935 subiq->num_target_queries = 0; 936 subiq->dnssec_expected = iter_indicates_dnssec( 937 qstate->env, subiq->dp, NULL, subq->qinfo.qclass); 938 } else { 939 lock_rw_unlock(&qstate->env->hints->lock); 940 } 941 942 /* this module stops, our submodule starts, and does the query. */ 943 qstate->ext_state[id] = module_wait_subquery; 944 return 1; 945 } 946 947 /** 948 * Generate and process a stub priming request. This method tests for the 949 * need to prime a stub zone, so it is safe to call for every request. 950 * 951 * @param qstate: the qtstate that triggered the need to prime. 952 * @param iq: iterator query state. 953 * @param id: module id. 954 * @param qname: request name. 955 * @param qclass: request class. 956 * @return true if a priming subrequest was made, false if not. The will only 957 * issue a priming request if it detects an unprimed stub. 958 * Uses value of 2 to signal during stub-prime in root-prime situation 959 * that a noprime-stub is available and resolution can continue. 960 */ 961 static int 962 prime_stub(struct module_qstate* qstate, struct iter_qstate* iq, int id, 963 uint8_t* qname, uint16_t qclass) 964 { 965 /* Lookup the stub hint. This will return null if the stub doesn't 966 * need to be re-primed. */ 967 struct iter_hints_stub* stub; 968 struct delegpt* stub_dp; 969 struct module_qstate* subq; 970 int nolock = 0; 971 972 if(!qname) return 0; 973 stub = hints_lookup_stub(qstate->env->hints, qname, qclass, iq->dp, 974 nolock); 975 /* The stub (if there is one) does not need priming. */ 976 if(!stub) return 0; 977 stub_dp = stub->dp; 978 /* if we have an auth_zone dp, and stub is equal, don't prime stub 979 * yet, unless we want to fallback and avoid the auth_zone */ 980 if(!iq->auth_zone_avoid && iq->dp && iq->dp->auth_dp && 981 query_dname_compare(iq->dp->name, stub_dp->name) == 0) { 982 lock_rw_unlock(&qstate->env->hints->lock); 983 return 0; 984 } 985 986 /* is it a noprime stub (always use) */ 987 if(stub->noprime) { 988 int r = 0; 989 if(iq->dp == NULL) r = 2; 990 /* copy the dp out of the fixed hints structure, so that 991 * it can be changed when servicing this query */ 992 iq->dp = delegpt_copy(stub_dp, qstate->region); 993 lock_rw_unlock(&qstate->env->hints->lock); 994 if(!iq->dp) { 995 log_err("out of memory priming stub"); 996 errinf(qstate, "malloc failure, priming stub"); 997 (void)error_response(qstate, id, LDNS_RCODE_SERVFAIL); 998 return 1; /* return 1 to make module stop, with error */ 999 } 1000 log_nametypeclass(VERB_DETAIL, "use stub", iq->dp->name, 1001 LDNS_RR_TYPE_NS, qclass); 1002 return r; 1003 } 1004 1005 /* Otherwise, we need to (re)prime the stub. */ 1006 log_nametypeclass(VERB_DETAIL, "priming stub", stub_dp->name, 1007 LDNS_RR_TYPE_NS, qclass); 1008 1009 /* Stub priming events start at the QUERYTARGETS state to avoid the 1010 * redundant INIT state processing. */ 1011 if(!generate_sub_request(stub_dp->name, stub_dp->namelen, 1012 LDNS_RR_TYPE_NS, qclass, qstate, id, iq, 1013 QUERYTARGETS_STATE, PRIME_RESP_STATE, &subq, 0, 0)) { 1014 lock_rw_unlock(&qstate->env->hints->lock); 1015 verbose(VERB_ALGO, "could not prime stub"); 1016 errinf(qstate, "could not generate lookup for stub prime"); 1017 (void)error_response(qstate, id, LDNS_RCODE_SERVFAIL); 1018 return 1; /* return 1 to make module stop, with error */ 1019 } 1020 if(subq) { 1021 struct iter_qstate* subiq = 1022 (struct iter_qstate*)subq->minfo[id]; 1023 1024 /* Set the initial delegation point to the hint. */ 1025 /* make copy to avoid use of stub dp by different qs/threads */ 1026 subiq->dp = delegpt_copy(stub_dp, subq->region); 1027 lock_rw_unlock(&qstate->env->hints->lock); 1028 if(!subiq->dp) { 1029 log_err("out of memory priming stub, copydp"); 1030 fptr_ok(fptr_whitelist_modenv_kill_sub( 1031 qstate->env->kill_sub)); 1032 (*qstate->env->kill_sub)(subq); 1033 errinf(qstate, "malloc failure, in stub prime"); 1034 (void)error_response(qstate, id, LDNS_RCODE_SERVFAIL); 1035 return 1; /* return 1 to make module stop, with error */ 1036 } 1037 /* there should not be any target queries -- although there 1038 * wouldn't be anyway, since stub hints never have 1039 * missing targets. */ 1040 subiq->num_target_queries = 0; 1041 subiq->wait_priming_stub = 1; 1042 subiq->dnssec_expected = iter_indicates_dnssec( 1043 qstate->env, subiq->dp, NULL, subq->qinfo.qclass); 1044 } else { 1045 lock_rw_unlock(&qstate->env->hints->lock); 1046 } 1047 1048 /* this module stops, our submodule starts, and does the query. */ 1049 qstate->ext_state[id] = module_wait_subquery; 1050 return 1; 1051 } 1052 1053 /** 1054 * Generate a delegation point for an auth zone (unless cached dp is better) 1055 * false on alloc failure. 1056 */ 1057 static int 1058 auth_zone_delegpt(struct module_qstate* qstate, struct iter_qstate* iq, 1059 uint8_t* delname, size_t delnamelen) 1060 { 1061 struct auth_zone* z; 1062 if(iq->auth_zone_avoid) 1063 return 1; 1064 if(!delname) { 1065 delname = iq->qchase.qname; 1066 delnamelen = iq->qchase.qname_len; 1067 } 1068 lock_rw_rdlock(&qstate->env->auth_zones->lock); 1069 z = auth_zones_find_zone(qstate->env->auth_zones, delname, delnamelen, 1070 qstate->qinfo.qclass); 1071 if(!z) { 1072 lock_rw_unlock(&qstate->env->auth_zones->lock); 1073 return 1; 1074 } 1075 lock_rw_rdlock(&z->lock); 1076 lock_rw_unlock(&qstate->env->auth_zones->lock); 1077 if(z->for_upstream) { 1078 if(iq->dp && query_dname_compare(z->name, iq->dp->name) == 0 1079 && iq->dp->auth_dp && qstate->blacklist && 1080 z->fallback_enabled) { 1081 /* cache is blacklisted and fallback, and we 1082 * already have an auth_zone dp */ 1083 if(verbosity>=VERB_ALGO) { 1084 char buf[LDNS_MAX_DOMAINLEN]; 1085 dname_str(z->name, buf); 1086 verbose(VERB_ALGO, "auth_zone %s " 1087 "fallback because cache blacklisted", 1088 buf); 1089 } 1090 lock_rw_unlock(&z->lock); 1091 iq->dp = NULL; 1092 return 1; 1093 } 1094 if(iq->dp==NULL || dname_subdomain_c(z->name, iq->dp->name)) { 1095 struct delegpt* dp; 1096 if(qstate->blacklist && z->fallback_enabled) { 1097 /* cache is blacklisted because of a DNSSEC 1098 * validation failure, and the zone allows 1099 * fallback to the internet, query there. */ 1100 if(verbosity>=VERB_ALGO) { 1101 char buf[LDNS_MAX_DOMAINLEN]; 1102 dname_str(z->name, buf); 1103 verbose(VERB_ALGO, "auth_zone %s " 1104 "fallback because cache blacklisted", 1105 buf); 1106 } 1107 lock_rw_unlock(&z->lock); 1108 return 1; 1109 } 1110 dp = (struct delegpt*)regional_alloc_zero( 1111 qstate->region, sizeof(*dp)); 1112 if(!dp) { 1113 log_err("alloc failure"); 1114 if(z->fallback_enabled) { 1115 lock_rw_unlock(&z->lock); 1116 return 1; /* just fallback */ 1117 } 1118 lock_rw_unlock(&z->lock); 1119 errinf(qstate, "malloc failure"); 1120 return 0; 1121 } 1122 dp->name = regional_alloc_init(qstate->region, 1123 z->name, z->namelen); 1124 if(!dp->name) { 1125 log_err("alloc failure"); 1126 if(z->fallback_enabled) { 1127 lock_rw_unlock(&z->lock); 1128 return 1; /* just fallback */ 1129 } 1130 lock_rw_unlock(&z->lock); 1131 errinf(qstate, "malloc failure"); 1132 return 0; 1133 } 1134 dp->namelen = z->namelen; 1135 dp->namelabs = z->namelabs; 1136 dp->auth_dp = 1; 1137 iq->dp = dp; 1138 } 1139 } 1140 1141 lock_rw_unlock(&z->lock); 1142 return 1; 1143 } 1144 1145 /** 1146 * Generate A and AAAA checks for glue that is in-zone for the referral 1147 * we just got to obtain authoritative information on the addresses. 1148 * 1149 * @param qstate: the qtstate that triggered the need to prime. 1150 * @param iq: iterator query state. 1151 * @param id: module id. 1152 */ 1153 static void 1154 generate_a_aaaa_check(struct module_qstate* qstate, struct iter_qstate* iq, 1155 int id) 1156 { 1157 struct iter_env* ie = (struct iter_env*)qstate->env->modinfo[id]; 1158 struct module_qstate* subq; 1159 size_t i; 1160 struct reply_info* rep = iq->response->rep; 1161 struct ub_packed_rrset_key* s; 1162 log_assert(iq->dp); 1163 1164 if(iq->depth == ie->max_dependency_depth) 1165 return; 1166 /* walk through additional, and check if in-zone, 1167 * only relevant A, AAAA are left after scrub anyway */ 1168 for(i=rep->an_numrrsets+rep->ns_numrrsets; i<rep->rrset_count; i++) { 1169 s = rep->rrsets[i]; 1170 /* check *ALL* addresses that are transmitted in additional*/ 1171 /* is it an address ? */ 1172 if( !(ntohs(s->rk.type)==LDNS_RR_TYPE_A || 1173 ntohs(s->rk.type)==LDNS_RR_TYPE_AAAA)) { 1174 continue; 1175 } 1176 /* is this query the same as the A/AAAA check for it */ 1177 if(qstate->qinfo.qtype == ntohs(s->rk.type) && 1178 qstate->qinfo.qclass == ntohs(s->rk.rrset_class) && 1179 query_dname_compare(qstate->qinfo.qname, 1180 s->rk.dname)==0 && 1181 (qstate->query_flags&BIT_RD) && 1182 !(qstate->query_flags&BIT_CD)) 1183 continue; 1184 1185 /* generate subrequest for it */ 1186 log_nametypeclass(VERB_ALGO, "schedule addr fetch", 1187 s->rk.dname, ntohs(s->rk.type), 1188 ntohs(s->rk.rrset_class)); 1189 if(!generate_sub_request(s->rk.dname, s->rk.dname_len, 1190 ntohs(s->rk.type), ntohs(s->rk.rrset_class), 1191 qstate, id, iq, 1192 INIT_REQUEST_STATE, FINISHED_STATE, &subq, 1, 0)) { 1193 verbose(VERB_ALGO, "could not generate addr check"); 1194 return; 1195 } 1196 /* ignore subq - not need for more init */ 1197 } 1198 } 1199 1200 /** 1201 * Generate a NS check request to obtain authoritative information 1202 * on an NS rrset. 1203 * 1204 * @param qstate: the qstate that triggered the need to prime. 1205 * @param iq: iterator query state. 1206 * @param id: module id. 1207 */ 1208 static void 1209 generate_ns_check(struct module_qstate* qstate, struct iter_qstate* iq, int id) 1210 { 1211 struct iter_env* ie = (struct iter_env*)qstate->env->modinfo[id]; 1212 struct module_qstate* subq; 1213 log_assert(iq->dp); 1214 1215 if(iq->depth == ie->max_dependency_depth) 1216 return; 1217 if(!can_have_last_resort(qstate->env, iq->dp->name, iq->dp->namelen, 1218 iq->qchase.qclass, NULL, NULL, NULL)) 1219 return; 1220 /* is this query the same as the nscheck? */ 1221 if(qstate->qinfo.qtype == LDNS_RR_TYPE_NS && 1222 query_dname_compare(iq->dp->name, qstate->qinfo.qname)==0 && 1223 (qstate->query_flags&BIT_RD) && !(qstate->query_flags&BIT_CD)){ 1224 /* spawn off A, AAAA queries for in-zone glue to check */ 1225 generate_a_aaaa_check(qstate, iq, id); 1226 return; 1227 } 1228 /* no need to get the NS record for DS, it is above the zonecut */ 1229 if(qstate->qinfo.qtype == LDNS_RR_TYPE_DS) 1230 return; 1231 1232 log_nametypeclass(VERB_ALGO, "schedule ns fetch", 1233 iq->dp->name, LDNS_RR_TYPE_NS, iq->qchase.qclass); 1234 if(!generate_sub_request(iq->dp->name, iq->dp->namelen, 1235 LDNS_RR_TYPE_NS, iq->qchase.qclass, qstate, id, iq, 1236 INIT_REQUEST_STATE, FINISHED_STATE, &subq, 1, 0)) { 1237 verbose(VERB_ALGO, "could not generate ns check"); 1238 return; 1239 } 1240 if(subq) { 1241 struct iter_qstate* subiq = 1242 (struct iter_qstate*)subq->minfo[id]; 1243 1244 /* make copy to avoid use of stub dp by different qs/threads */ 1245 /* refetch glue to start higher up the tree */ 1246 subiq->refetch_glue = 1; 1247 subiq->dp = delegpt_copy(iq->dp, subq->region); 1248 if(!subiq->dp) { 1249 log_err("out of memory generating ns check, copydp"); 1250 fptr_ok(fptr_whitelist_modenv_kill_sub( 1251 qstate->env->kill_sub)); 1252 (*qstate->env->kill_sub)(subq); 1253 return; 1254 } 1255 } 1256 } 1257 1258 /** 1259 * Generate a DNSKEY prefetch query to get the DNSKEY for the DS record we 1260 * just got in a referral (where we have dnssec_expected, thus have trust 1261 * anchors above it). Note that right after calling this routine the 1262 * iterator detached subqueries (because of following the referral), and thus 1263 * the DNSKEY query becomes detached, its return stored in the cache for 1264 * later lookup by the validator. This cache lookup by the validator avoids 1265 * the roundtrip incurred by the DNSKEY query. The DNSKEY query is now 1266 * performed at about the same time the original query is sent to the domain, 1267 * thus the two answers are likely to be returned at about the same time, 1268 * saving a roundtrip from the validated lookup. 1269 * 1270 * @param qstate: the qtstate that triggered the need to prime. 1271 * @param iq: iterator query state. 1272 * @param id: module id. 1273 */ 1274 static void 1275 generate_dnskey_prefetch(struct module_qstate* qstate, 1276 struct iter_qstate* iq, int id) 1277 { 1278 struct module_qstate* subq; 1279 log_assert(iq->dp); 1280 1281 /* is this query the same as the prefetch? */ 1282 if(qstate->qinfo.qtype == LDNS_RR_TYPE_DNSKEY && 1283 query_dname_compare(iq->dp->name, qstate->qinfo.qname)==0 && 1284 (qstate->query_flags&BIT_RD) && !(qstate->query_flags&BIT_CD)){ 1285 return; 1286 } 1287 /* we do not generate this prefetch when the query list is full, 1288 * the query is fetched, if needed, when the validator wants it. 1289 * At that time the validator waits for it, after spawning it. 1290 * This means there is one state that uses cpu and a socket, the 1291 * spawned while this one waits, and not several at the same time, 1292 * if we had created the lookup here. And this helps to keep 1293 * the total load down, but the query still succeeds to resolve. */ 1294 if(mesh_jostle_exceeded(qstate->env->mesh)) 1295 return; 1296 1297 /* if the DNSKEY is in the cache this lookup will stop quickly */ 1298 log_nametypeclass(VERB_ALGO, "schedule dnskey prefetch", 1299 iq->dp->name, LDNS_RR_TYPE_DNSKEY, iq->qchase.qclass); 1300 if(!generate_sub_request(iq->dp->name, iq->dp->namelen, 1301 LDNS_RR_TYPE_DNSKEY, iq->qchase.qclass, qstate, id, iq, 1302 INIT_REQUEST_STATE, FINISHED_STATE, &subq, 0, 0)) { 1303 /* we'll be slower, but it'll work */ 1304 verbose(VERB_ALGO, "could not generate dnskey prefetch"); 1305 return; 1306 } 1307 if(subq) { 1308 struct iter_qstate* subiq = 1309 (struct iter_qstate*)subq->minfo[id]; 1310 /* this qstate has the right delegation for the dnskey lookup*/ 1311 /* make copy to avoid use of stub dp by different qs/threads */ 1312 subiq->dp = delegpt_copy(iq->dp, subq->region); 1313 /* if !subiq->dp, it'll start from the cache, no problem */ 1314 } 1315 } 1316 1317 /** 1318 * See if the query needs forwarding. 1319 * 1320 * @param qstate: query state. 1321 * @param iq: iterator query state. 1322 * @return true if the request is forwarded, false if not. 1323 * If returns true but, iq->dp is NULL then a malloc failure occurred. 1324 */ 1325 static int 1326 forward_request(struct module_qstate* qstate, struct iter_qstate* iq) 1327 { 1328 struct delegpt* dp; 1329 uint8_t* delname = iq->qchase.qname; 1330 size_t delnamelen = iq->qchase.qname_len; 1331 int nolock = 0; 1332 if(iq->refetch_glue && iq->dp) { 1333 delname = iq->dp->name; 1334 delnamelen = iq->dp->namelen; 1335 } 1336 /* strip one label off of DS query to lookup higher for it */ 1337 if( (iq->qchase.qtype == LDNS_RR_TYPE_DS || iq->refetch_glue) 1338 && !dname_is_root(iq->qchase.qname)) 1339 dname_remove_label(&delname, &delnamelen); 1340 dp = forwards_lookup(qstate->env->fwds, delname, iq->qchase.qclass, 1341 nolock); 1342 if(!dp) return 0; 1343 /* send recursion desired to forward addr */ 1344 iq->chase_flags |= BIT_RD; 1345 iq->dp = delegpt_copy(dp, qstate->region); 1346 lock_rw_unlock(&qstate->env->fwds->lock); 1347 /* iq->dp checked by caller */ 1348 verbose(VERB_ALGO, "forwarding request"); 1349 return 1; 1350 } 1351 1352 /** 1353 * Process the initial part of the request handling. This state roughly 1354 * corresponds to resolver algorithms steps 1 (find answer in cache) and 2 1355 * (find the best servers to ask). 1356 * 1357 * Note that all requests start here, and query restarts revisit this state. 1358 * 1359 * This state either generates: 1) a response, from cache or error, 2) a 1360 * priming event, or 3) forwards the request to the next state (init2, 1361 * generally). 1362 * 1363 * @param qstate: query state. 1364 * @param iq: iterator query state. 1365 * @param ie: iterator shared global environment. 1366 * @param id: module id. 1367 * @return true if the event needs more request processing immediately, 1368 * false if not. 1369 */ 1370 static int 1371 processInitRequest(struct module_qstate* qstate, struct iter_qstate* iq, 1372 struct iter_env* ie, int id) 1373 { 1374 uint8_t dpname_storage[LDNS_MAX_DOMAINLEN+1]; 1375 uint8_t* delname, *dpname=NULL; 1376 size_t delnamelen, dpnamelen=0; 1377 struct dns_msg* msg = NULL; 1378 1379 log_query_info(VERB_DETAIL, "resolving", &qstate->qinfo); 1380 /* check effort */ 1381 1382 /* We enforce a maximum number of query restarts. This is primarily a 1383 * cheap way to prevent CNAME loops. */ 1384 if(iq->query_restart_count > ie->max_query_restarts) { 1385 verbose(VERB_QUERY, "request has exceeded the maximum number" 1386 " of query restarts with %d", iq->query_restart_count); 1387 errinf(qstate, "request has exceeded the maximum number " 1388 "restarts (eg. indirections)"); 1389 if(iq->qchase.qname) 1390 errinf_dname(qstate, "stop at", iq->qchase.qname); 1391 return error_response_cache(qstate, id, LDNS_RCODE_SERVFAIL); 1392 } 1393 1394 /* We enforce a maximum recursion/dependency depth -- in general, 1395 * this is unnecessary for dependency loops (although it will 1396 * catch those), but it provides a sensible limit to the amount 1397 * of work required to answer a given query. */ 1398 verbose(VERB_ALGO, "request has dependency depth of %d", iq->depth); 1399 if(iq->depth > ie->max_dependency_depth) { 1400 verbose(VERB_QUERY, "request has exceeded the maximum " 1401 "dependency depth with depth of %d", iq->depth); 1402 errinf(qstate, "request has exceeded the maximum dependency " 1403 "depth (eg. nameserver lookup recursion)"); 1404 return error_response(qstate, id, LDNS_RCODE_SERVFAIL); 1405 } 1406 1407 /* If the request is qclass=ANY, setup to generate each class */ 1408 if(qstate->qinfo.qclass == LDNS_RR_CLASS_ANY) { 1409 iq->qchase.qclass = 0; 1410 return next_state(iq, COLLECT_CLASS_STATE); 1411 } 1412 1413 /* 1414 * If we are restricted by a forward-zone or a stub-zone, we 1415 * can't re-fetch glue for this delegation point. 1416 * we won’t try to re-fetch glue if the iq->dp is null. 1417 */ 1418 if (iq->refetch_glue && 1419 iq->dp && 1420 !can_have_last_resort(qstate->env, iq->dp->name, 1421 iq->dp->namelen, iq->qchase.qclass, NULL, NULL, NULL)) { 1422 iq->refetch_glue = 0; 1423 } 1424 1425 /* Resolver Algorithm Step 1 -- Look for the answer in local data. */ 1426 1427 /* This either results in a query restart (CNAME cache response), a 1428 * terminating response (ANSWER), or a cache miss (null). */ 1429 1430 /* Check RPZ for override */ 1431 if(qstate->env->auth_zones) { 1432 /* apply rpz qname triggers, like after cname */ 1433 struct dns_msg* forged_response = 1434 rpz_callback_from_iterator_cname(qstate, iq); 1435 if(forged_response) { 1436 uint8_t* sname = 0; 1437 size_t slen = 0; 1438 int count = 0; 1439 while(forged_response && reply_find_rrset_section_an( 1440 forged_response->rep, iq->qchase.qname, 1441 iq->qchase.qname_len, LDNS_RR_TYPE_CNAME, 1442 iq->qchase.qclass) && 1443 iq->qchase.qtype != LDNS_RR_TYPE_CNAME && 1444 count++ < ie->max_query_restarts) { 1445 /* another cname to follow */ 1446 if(!handle_cname_response(qstate, iq, forged_response, 1447 &sname, &slen)) { 1448 errinf(qstate, "malloc failure, CNAME info"); 1449 return error_response(qstate, id, LDNS_RCODE_SERVFAIL); 1450 } 1451 iq->qchase.qname = sname; 1452 iq->qchase.qname_len = slen; 1453 forged_response = 1454 rpz_callback_from_iterator_cname(qstate, iq); 1455 } 1456 if(forged_response != NULL) { 1457 qstate->ext_state[id] = module_finished; 1458 qstate->return_rcode = LDNS_RCODE_NOERROR; 1459 qstate->return_msg = forged_response; 1460 iq->response = forged_response; 1461 next_state(iq, FINISHED_STATE); 1462 if(!iter_prepend(iq, qstate->return_msg, qstate->region)) { 1463 log_err("rpz: after cached cname, prepend rrsets: out of memory"); 1464 return error_response(qstate, id, LDNS_RCODE_SERVFAIL); 1465 } 1466 qstate->return_msg->qinfo = qstate->qinfo; 1467 return 0; 1468 } 1469 /* Follow the CNAME response */ 1470 iq->dp = NULL; 1471 iq->refetch_glue = 0; 1472 iq->query_restart_count++; 1473 iq->sent_count = 0; 1474 iq->dp_target_count = 0; 1475 sock_list_insert(&qstate->reply_origin, NULL, 0, qstate->region); 1476 if(qstate->env->cfg->qname_minimisation) 1477 iq->minimisation_state = INIT_MINIMISE_STATE; 1478 return next_state(iq, INIT_REQUEST_STATE); 1479 } 1480 } 1481 1482 if (iter_stub_fwd_no_cache(qstate, &iq->qchase, &dpname, &dpnamelen, 1483 dpname_storage, sizeof(dpname_storage))) { 1484 /* Asked to not query cache. */ 1485 verbose(VERB_ALGO, "no-cache set, going to the network"); 1486 qstate->no_cache_lookup = 1; 1487 qstate->no_cache_store = 1; 1488 msg = NULL; 1489 } else if(qstate->blacklist) { 1490 /* if cache, or anything else, was blacklisted then 1491 * getting older results from cache is a bad idea, no cache */ 1492 verbose(VERB_ALGO, "cache blacklisted, going to the network"); 1493 msg = NULL; 1494 } else if(!qstate->no_cache_lookup) { 1495 msg = dns_cache_lookup(qstate->env, iq->qchase.qname, 1496 iq->qchase.qname_len, iq->qchase.qtype, 1497 iq->qchase.qclass, qstate->query_flags, 1498 qstate->region, qstate->env->scratch, 0, dpname, 1499 dpnamelen); 1500 if(!msg && qstate->env->neg_cache && 1501 iter_qname_indicates_dnssec(qstate->env, &iq->qchase)) { 1502 /* lookup in negative cache; may result in 1503 * NOERROR/NODATA or NXDOMAIN answers that need validation */ 1504 msg = val_neg_getmsg(qstate->env->neg_cache, &iq->qchase, 1505 qstate->region, qstate->env->rrset_cache, 1506 qstate->env->scratch_buffer, 1507 *qstate->env->now, 1/*add SOA*/, NULL, 1508 qstate->env->cfg); 1509 } 1510 /* item taken from cache does not match our query name, thus 1511 * security needs to be re-examined later */ 1512 if(msg && query_dname_compare(qstate->qinfo.qname, 1513 iq->qchase.qname) != 0) 1514 msg->rep->security = sec_status_unchecked; 1515 } 1516 if(msg) { 1517 /* handle positive cache response */ 1518 enum response_type type = response_type_from_cache(msg, 1519 &iq->qchase); 1520 if(verbosity >= VERB_ALGO) { 1521 log_dns_msg("msg from cache lookup", &msg->qinfo, 1522 msg->rep); 1523 verbose(VERB_ALGO, "msg ttl is %d, prefetch ttl %d", 1524 (int)msg->rep->ttl, 1525 (int)msg->rep->prefetch_ttl); 1526 } 1527 1528 if(type == RESPONSE_TYPE_CNAME) { 1529 uint8_t* sname = 0; 1530 size_t slen = 0; 1531 verbose(VERB_ALGO, "returning CNAME response from " 1532 "cache"); 1533 if(!handle_cname_response(qstate, iq, msg, 1534 &sname, &slen)) { 1535 errinf(qstate, "failed to prepend CNAME " 1536 "components, malloc failure"); 1537 return error_response(qstate, id, 1538 LDNS_RCODE_SERVFAIL); 1539 } 1540 iq->qchase.qname = sname; 1541 iq->qchase.qname_len = slen; 1542 /* This *is* a query restart, even if it is a cheap 1543 * one. */ 1544 iq->dp = NULL; 1545 iq->refetch_glue = 0; 1546 iq->query_restart_count++; 1547 iq->sent_count = 0; 1548 iq->dp_target_count = 0; 1549 sock_list_insert(&qstate->reply_origin, NULL, 0, qstate->region); 1550 if(qstate->env->cfg->qname_minimisation) 1551 iq->minimisation_state = INIT_MINIMISE_STATE; 1552 return next_state(iq, INIT_REQUEST_STATE); 1553 } 1554 /* if from cache, NULL, else insert 'cache IP' len=0 */ 1555 if(qstate->reply_origin) 1556 sock_list_insert(&qstate->reply_origin, NULL, 0, qstate->region); 1557 if(FLAGS_GET_RCODE(msg->rep->flags) == LDNS_RCODE_SERVFAIL) 1558 errinf(qstate, "SERVFAIL in cache"); 1559 /* it is an answer, response, to final state */ 1560 verbose(VERB_ALGO, "returning answer from cache."); 1561 iq->response = msg; 1562 return final_state(iq); 1563 } 1564 1565 /* attempt to forward the request */ 1566 if(forward_request(qstate, iq)) 1567 { 1568 if(!iq->dp) { 1569 log_err("alloc failure for forward dp"); 1570 errinf(qstate, "malloc failure for forward zone"); 1571 return error_response(qstate, id, LDNS_RCODE_SERVFAIL); 1572 } 1573 if(!cache_fill_missing(qstate->env, iq->qchase.qclass, 1574 qstate->region, iq->dp, 0)) { 1575 errinf(qstate, "malloc failure, copy extra info into delegation point"); 1576 return error_response(qstate, id, LDNS_RCODE_SERVFAIL); 1577 } 1578 if((qstate->query_flags&BIT_RD)==0) { 1579 /* If the server accepts RD=0 queries and forwards 1580 * with RD=1, then if the server is listed as an NS 1581 * entry, it starts query loops. Stop that loop by 1582 * disallowing the query. The RD=0 was previously used 1583 * to check the cache with allow_snoop. For stubs, 1584 * the iterator pass would have primed the stub and 1585 * then cached information can be used for further 1586 * queries. */ 1587 verbose(VERB_ALGO, "cannot forward RD=0 query, to stop query loops"); 1588 errinf(qstate, "cannot forward RD=0 query"); 1589 return error_response(qstate, id, LDNS_RCODE_SERVFAIL); 1590 } 1591 iq->refetch_glue = 0; 1592 iq->minimisation_state = DONOT_MINIMISE_STATE; 1593 /* the request has been forwarded. 1594 * forwarded requests need to be immediately sent to the 1595 * next state, QUERYTARGETS. */ 1596 return next_state(iq, QUERYTARGETS_STATE); 1597 } 1598 1599 /* Resolver Algorithm Step 2 -- find the "best" servers. */ 1600 1601 /* first, adjust for DS queries. To avoid the grandparent problem, 1602 * we just look for the closest set of server to the parent of qname. 1603 * When re-fetching glue we also need to ask the parent. 1604 */ 1605 if(iq->refetch_glue) { 1606 if(!iq->dp) { 1607 log_err("internal or malloc fail: no dp for refetch"); 1608 errinf(qstate, "malloc failure, for delegation info"); 1609 return error_response(qstate, id, LDNS_RCODE_SERVFAIL); 1610 } 1611 delname = iq->dp->name; 1612 delnamelen = iq->dp->namelen; 1613 } else { 1614 delname = iq->qchase.qname; 1615 delnamelen = iq->qchase.qname_len; 1616 } 1617 if(iq->qchase.qtype == LDNS_RR_TYPE_DS || iq->refetch_glue || 1618 (iq->qchase.qtype == LDNS_RR_TYPE_NS && qstate->prefetch_leeway 1619 && can_have_last_resort(qstate->env, delname, delnamelen, iq->qchase.qclass, NULL, NULL, NULL))) { 1620 /* remove first label from delname, root goes to hints, 1621 * but only to fetch glue, not for qtype=DS. */ 1622 /* also when prefetching an NS record, fetch it again from 1623 * its parent, just as if it expired, so that you do not 1624 * get stuck on an older nameserver that gives old NSrecords */ 1625 if(dname_is_root(delname) && (iq->refetch_glue || 1626 (iq->qchase.qtype == LDNS_RR_TYPE_NS && 1627 qstate->prefetch_leeway))) 1628 delname = NULL; /* go to root priming */ 1629 else dname_remove_label(&delname, &delnamelen); 1630 } 1631 /* delname is the name to lookup a delegation for. If NULL rootprime */ 1632 while(1) { 1633 1634 /* Lookup the delegation in the cache. If null, then the 1635 * cache needs to be primed for the qclass. */ 1636 if(delname) 1637 iq->dp = dns_cache_find_delegation(qstate->env, delname, 1638 delnamelen, iq->qchase.qtype, iq->qchase.qclass, 1639 qstate->region, &iq->deleg_msg, 1640 *qstate->env->now+qstate->prefetch_leeway, 1, 1641 dpname, dpnamelen); 1642 else iq->dp = NULL; 1643 1644 /* If the cache has returned nothing, then we have a 1645 * root priming situation. */ 1646 if(iq->dp == NULL) { 1647 int r; 1648 int nolock = 0; 1649 /* if under auth zone, no prime needed */ 1650 if(!auth_zone_delegpt(qstate, iq, delname, delnamelen)) 1651 return error_response(qstate, id, 1652 LDNS_RCODE_SERVFAIL); 1653 if(iq->dp) /* use auth zone dp */ 1654 return next_state(iq, INIT_REQUEST_2_STATE); 1655 /* if there is a stub, then no root prime needed */ 1656 r = prime_stub(qstate, iq, id, delname, 1657 iq->qchase.qclass); 1658 if(r == 2) 1659 break; /* got noprime-stub-zone, continue */ 1660 else if(r) 1661 return 0; /* stub prime request made */ 1662 if(forwards_lookup_root(qstate->env->fwds, 1663 iq->qchase.qclass, nolock)) { 1664 lock_rw_unlock(&qstate->env->fwds->lock); 1665 /* forward zone root, no root prime needed */ 1666 /* fill in some dp - safety belt */ 1667 iq->dp = hints_find_root(qstate->env->hints, 1668 iq->qchase.qclass, nolock); 1669 if(!iq->dp) { 1670 log_err("internal error: no hints dp"); 1671 errinf(qstate, "no hints for this class"); 1672 return error_response_cache(qstate, id, 1673 LDNS_RCODE_SERVFAIL); 1674 } 1675 iq->dp = delegpt_copy(iq->dp, qstate->region); 1676 lock_rw_unlock(&qstate->env->hints->lock); 1677 if(!iq->dp) { 1678 log_err("out of memory in safety belt"); 1679 errinf(qstate, "malloc failure, in safety belt"); 1680 return error_response(qstate, id, 1681 LDNS_RCODE_SERVFAIL); 1682 } 1683 return next_state(iq, INIT_REQUEST_2_STATE); 1684 } 1685 /* Note that the result of this will set a new 1686 * DelegationPoint based on the result of priming. */ 1687 if(!prime_root(qstate, iq, id, iq->qchase.qclass)) 1688 return error_response(qstate, id, 1689 LDNS_RCODE_REFUSED); 1690 1691 /* priming creates and sends a subordinate query, with 1692 * this query as the parent. So further processing for 1693 * this event will stop until reactivated by the 1694 * results of priming. */ 1695 return 0; 1696 } 1697 if(!iq->ratelimit_ok && qstate->prefetch_leeway) 1698 iq->ratelimit_ok = 1; /* allow prefetches, this keeps 1699 otherwise valid data in the cache */ 1700 1701 /* see if this dp not useless. 1702 * It is useless if: 1703 * o all NS items are required glue. 1704 * or the query is for NS item that is required glue. 1705 * o no addresses are provided. 1706 * o RD qflag is on. 1707 * Instead, go up one level, and try to get even further 1708 * If the root was useless, use safety belt information. 1709 * Only check cache returns, because replies for servers 1710 * could be useless but lead to loops (bumping into the 1711 * same server reply) if useless-checked. 1712 */ 1713 if(iter_dp_is_useless(&qstate->qinfo, qstate->query_flags, 1714 iq->dp, ie->supports_ipv4, ie->supports_ipv6, 1715 ie->nat64.use_nat64)) { 1716 int have_dp = 0; 1717 if(!can_have_last_resort(qstate->env, iq->dp->name, iq->dp->namelen, iq->qchase.qclass, &have_dp, &iq->dp, qstate->region)) { 1718 if(have_dp) { 1719 verbose(VERB_QUERY, "cache has stub " 1720 "or fwd but no addresses, " 1721 "fallback to config"); 1722 if(have_dp && !iq->dp) { 1723 log_err("out of memory in " 1724 "stub/fwd fallback"); 1725 errinf(qstate, "malloc failure, for fallback to config"); 1726 return error_response(qstate, 1727 id, LDNS_RCODE_SERVFAIL); 1728 } 1729 break; 1730 } 1731 verbose(VERB_ALGO, "useless dp " 1732 "but cannot go up, servfail"); 1733 delegpt_log(VERB_ALGO, iq->dp); 1734 errinf(qstate, "no useful nameservers, " 1735 "and cannot go up"); 1736 errinf_dname(qstate, "for zone", iq->dp->name); 1737 return error_response(qstate, id, 1738 LDNS_RCODE_SERVFAIL); 1739 } 1740 if(dname_is_root(iq->dp->name)) { 1741 /* use safety belt */ 1742 int nolock = 0; 1743 verbose(VERB_QUERY, "Cache has root NS but " 1744 "no addresses. Fallback to the safety belt."); 1745 iq->dp = hints_find_root(qstate->env->hints, 1746 iq->qchase.qclass, nolock); 1747 /* note deleg_msg is from previous lookup, 1748 * but RD is on, so it is not used */ 1749 if(!iq->dp) { 1750 log_err("internal error: no hints dp"); 1751 return error_response(qstate, id, 1752 LDNS_RCODE_REFUSED); 1753 } 1754 iq->dp = delegpt_copy(iq->dp, qstate->region); 1755 lock_rw_unlock(&qstate->env->hints->lock); 1756 if(!iq->dp) { 1757 log_err("out of memory in safety belt"); 1758 errinf(qstate, "malloc failure, in safety belt, for root"); 1759 return error_response(qstate, id, 1760 LDNS_RCODE_SERVFAIL); 1761 } 1762 break; 1763 } else { 1764 verbose(VERB_ALGO, 1765 "cache delegation was useless:"); 1766 delegpt_log(VERB_ALGO, iq->dp); 1767 /* go up */ 1768 delname = iq->dp->name; 1769 delnamelen = iq->dp->namelen; 1770 dname_remove_label(&delname, &delnamelen); 1771 } 1772 } else break; 1773 } 1774 1775 verbose(VERB_ALGO, "cache delegation returns delegpt"); 1776 delegpt_log(VERB_ALGO, iq->dp); 1777 1778 /* Otherwise, set the current delegation point and move on to the 1779 * next state. */ 1780 return next_state(iq, INIT_REQUEST_2_STATE); 1781 } 1782 1783 /** 1784 * Process the second part of the initial request handling. This state 1785 * basically exists so that queries that generate root priming events have 1786 * the same init processing as ones that do not. Request events that reach 1787 * this state must have a valid currentDelegationPoint set. 1788 * 1789 * This part is primarily handling stub zone priming. Events that reach this 1790 * state must have a current delegation point. 1791 * 1792 * @param qstate: query state. 1793 * @param iq: iterator query state. 1794 * @param id: module id. 1795 * @return true if the event needs more request processing immediately, 1796 * false if not. 1797 */ 1798 static int 1799 processInitRequest2(struct module_qstate* qstate, struct iter_qstate* iq, 1800 int id) 1801 { 1802 uint8_t* delname; 1803 size_t delnamelen; 1804 log_query_info(VERB_QUERY, "resolving (init part 2): ", 1805 &qstate->qinfo); 1806 1807 delname = iq->qchase.qname; 1808 delnamelen = iq->qchase.qname_len; 1809 if(iq->refetch_glue) { 1810 struct iter_hints_stub* stub; 1811 int nolock = 0; 1812 if(!iq->dp) { 1813 log_err("internal or malloc fail: no dp for refetch"); 1814 errinf(qstate, "malloc failure, no delegation info"); 1815 return error_response(qstate, id, LDNS_RCODE_SERVFAIL); 1816 } 1817 /* Do not send queries above stub, do not set delname to dp if 1818 * this is above stub without stub-first. */ 1819 stub = hints_lookup_stub( 1820 qstate->env->hints, iq->qchase.qname, iq->qchase.qclass, 1821 iq->dp, nolock); 1822 if(!stub || !stub->dp->has_parent_side_NS || 1823 dname_subdomain_c(iq->dp->name, stub->dp->name)) { 1824 delname = iq->dp->name; 1825 delnamelen = iq->dp->namelen; 1826 } 1827 /* lock_() calls are macros that could be nothing, surround in {} */ 1828 if(stub) { lock_rw_unlock(&qstate->env->hints->lock); } 1829 } 1830 if(iq->qchase.qtype == LDNS_RR_TYPE_DS || iq->refetch_glue) { 1831 if(!dname_is_root(delname)) 1832 dname_remove_label(&delname, &delnamelen); 1833 iq->refetch_glue = 0; /* if CNAME causes restart, no refetch */ 1834 } 1835 1836 /* see if we have an auth zone to answer from, improves dp from cache 1837 * (if any dp from cache) with auth zone dp, if that is lower */ 1838 if(!auth_zone_delegpt(qstate, iq, delname, delnamelen)) 1839 return error_response(qstate, id, LDNS_RCODE_SERVFAIL); 1840 1841 /* Check to see if we need to prime a stub zone. */ 1842 if(prime_stub(qstate, iq, id, delname, iq->qchase.qclass)) { 1843 /* A priming sub request was made */ 1844 return 0; 1845 } 1846 1847 /* most events just get forwarded to the next state. */ 1848 return next_state(iq, INIT_REQUEST_3_STATE); 1849 } 1850 1851 /** 1852 * Process the third part of the initial request handling. This state exists 1853 * as a separate state so that queries that generate stub priming events 1854 * will get the tail end of the init process but not repeat the stub priming 1855 * check. 1856 * 1857 * @param qstate: query state. 1858 * @param iq: iterator query state. 1859 * @param id: module id. 1860 * @return true, advancing the event to the QUERYTARGETS_STATE. 1861 */ 1862 static int 1863 processInitRequest3(struct module_qstate* qstate, struct iter_qstate* iq, 1864 int id) 1865 { 1866 log_query_info(VERB_QUERY, "resolving (init part 3): ", 1867 &qstate->qinfo); 1868 /* if the cache reply dp equals a validation anchor or msg has DS, 1869 * then DNSSEC RRSIGs are expected in the reply */ 1870 iq->dnssec_expected = iter_indicates_dnssec(qstate->env, iq->dp, 1871 iq->deleg_msg, iq->qchase.qclass); 1872 1873 /* If the RD flag wasn't set, then we just finish with the 1874 * cached referral as the response. */ 1875 if(!(qstate->query_flags & BIT_RD) && iq->deleg_msg) { 1876 iq->response = iq->deleg_msg; 1877 if(verbosity >= VERB_ALGO && iq->response) 1878 log_dns_msg("no RD requested, using delegation msg", 1879 &iq->response->qinfo, iq->response->rep); 1880 if(qstate->reply_origin) 1881 sock_list_insert(&qstate->reply_origin, NULL, 0, qstate->region); 1882 return final_state(iq); 1883 } 1884 /* After this point, unset the RD flag -- this query is going to 1885 * be sent to an auth. server. */ 1886 iq->chase_flags &= ~BIT_RD; 1887 1888 /* if dnssec expected, fetch key for the trust-anchor or cached-DS */ 1889 if(iq->dnssec_expected && qstate->env->cfg->prefetch_key && 1890 !(qstate->query_flags&BIT_CD)) { 1891 generate_dnskey_prefetch(qstate, iq, id); 1892 fptr_ok(fptr_whitelist_modenv_detach_subs( 1893 qstate->env->detach_subs)); 1894 (*qstate->env->detach_subs)(qstate); 1895 } 1896 1897 /* Jump to the next state. */ 1898 return next_state(iq, QUERYTARGETS_STATE); 1899 } 1900 1901 /** 1902 * Given a basic query, generate a parent-side "target" query. 1903 * These are subordinate queries for missing delegation point target addresses, 1904 * for which only the parent of the delegation provides correct IP addresses. 1905 * 1906 * @param qstate: query state. 1907 * @param iq: iterator query state. 1908 * @param id: module id. 1909 * @param name: target qname. 1910 * @param namelen: target qname length. 1911 * @param qtype: target qtype (either A or AAAA). 1912 * @param qclass: target qclass. 1913 * @return true on success, false on failure. 1914 */ 1915 static int 1916 generate_parentside_target_query(struct module_qstate* qstate, 1917 struct iter_qstate* iq, int id, uint8_t* name, size_t namelen, 1918 uint16_t qtype, uint16_t qclass) 1919 { 1920 struct module_qstate* subq; 1921 if(!generate_sub_request(name, namelen, qtype, qclass, qstate, 1922 id, iq, INIT_REQUEST_STATE, FINISHED_STATE, &subq, 0, 0)) 1923 return 0; 1924 if(subq) { 1925 struct iter_qstate* subiq = 1926 (struct iter_qstate*)subq->minfo[id]; 1927 /* blacklist the cache - we want to fetch parent stuff */ 1928 sock_list_insert(&subq->blacklist, NULL, 0, subq->region); 1929 subiq->query_for_pside_glue = 1; 1930 if(dname_subdomain_c(name, iq->dp->name)) { 1931 subiq->dp = delegpt_copy(iq->dp, subq->region); 1932 subiq->dnssec_expected = iter_indicates_dnssec( 1933 qstate->env, subiq->dp, NULL, 1934 subq->qinfo.qclass); 1935 subiq->refetch_glue = 1; 1936 } else { 1937 subiq->dp = dns_cache_find_delegation(qstate->env, 1938 name, namelen, qtype, qclass, subq->region, 1939 &subiq->deleg_msg, 1940 *qstate->env->now+subq->prefetch_leeway, 1941 1, NULL, 0); 1942 /* if no dp, then it's from root, refetch unneeded */ 1943 if(subiq->dp) { 1944 subiq->dnssec_expected = iter_indicates_dnssec( 1945 qstate->env, subiq->dp, NULL, 1946 subq->qinfo.qclass); 1947 subiq->refetch_glue = 1; 1948 } 1949 } 1950 } 1951 log_nametypeclass(VERB_QUERY, "new pside target", name, qtype, qclass); 1952 return 1; 1953 } 1954 1955 /** 1956 * Given a basic query, generate a "target" query. These are subordinate 1957 * queries for missing delegation point target addresses. 1958 * 1959 * @param qstate: query state. 1960 * @param iq: iterator query state. 1961 * @param id: module id. 1962 * @param name: target qname. 1963 * @param namelen: target qname length. 1964 * @param qtype: target qtype (either A or AAAA). 1965 * @param qclass: target qclass. 1966 * @return true on success, false on failure. 1967 */ 1968 static int 1969 generate_target_query(struct module_qstate* qstate, struct iter_qstate* iq, 1970 int id, uint8_t* name, size_t namelen, uint16_t qtype, uint16_t qclass) 1971 { 1972 struct module_qstate* subq; 1973 if(!generate_sub_request(name, namelen, qtype, qclass, qstate, 1974 id, iq, INIT_REQUEST_STATE, FINISHED_STATE, &subq, 0, 0)) 1975 return 0; 1976 log_nametypeclass(VERB_QUERY, "new target", name, qtype, qclass); 1977 return 1; 1978 } 1979 1980 /** 1981 * Given an event at a certain state, generate zero or more target queries 1982 * for it's current delegation point. 1983 * 1984 * @param qstate: query state. 1985 * @param iq: iterator query state. 1986 * @param ie: iterator shared global environment. 1987 * @param id: module id. 1988 * @param maxtargets: The maximum number of targets to query for. 1989 * if it is negative, there is no maximum number of targets. 1990 * @param num: returns the number of queries generated and processed, 1991 * which may be zero if there were no missing targets. 1992 * @return 0 on success, nonzero on error. 1 means temporary failure and 1993 * 2 means the failure can be cached. 1994 */ 1995 static int 1996 query_for_targets(struct module_qstate* qstate, struct iter_qstate* iq, 1997 struct iter_env* ie, int id, int maxtargets, int* num) 1998 { 1999 int query_count = 0; 2000 struct delegpt_ns* ns; 2001 int missing; 2002 int toget = 0; 2003 2004 iter_mark_cycle_targets(qstate, iq->dp); 2005 missing = (int)delegpt_count_missing_targets(iq->dp, NULL); 2006 log_assert(maxtargets != 0); /* that would not be useful */ 2007 2008 /* Generate target requests. Basically, any missing targets 2009 * are queried for here, regardless if it is necessary to do 2010 * so to continue processing. */ 2011 if(maxtargets < 0 || maxtargets > missing) 2012 toget = missing; 2013 else toget = maxtargets; 2014 if(toget == 0) { 2015 *num = 0; 2016 return 0; 2017 } 2018 2019 /* now that we are sure that a target query is going to be made, 2020 * check the limits. */ 2021 if(iq->depth == ie->max_dependency_depth) 2022 return 1; 2023 if(iq->depth > 0 && iq->target_count && 2024 iq->target_count[TARGET_COUNT_QUERIES] > MAX_TARGET_COUNT) { 2025 char s[LDNS_MAX_DOMAINLEN]; 2026 dname_str(qstate->qinfo.qname, s); 2027 verbose(VERB_QUERY, "request %s has exceeded the maximum " 2028 "number of glue fetches %d", s, 2029 iq->target_count[TARGET_COUNT_QUERIES]); 2030 return 2; 2031 } 2032 if(iq->dp_target_count > MAX_DP_TARGET_COUNT) { 2033 char s[LDNS_MAX_DOMAINLEN]; 2034 dname_str(qstate->qinfo.qname, s); 2035 verbose(VERB_QUERY, "request %s has exceeded the maximum " 2036 "number of glue fetches %d to a single delegation point", 2037 s, iq->dp_target_count); 2038 return 2; 2039 } 2040 2041 /* select 'toget' items from the total of 'missing' items */ 2042 log_assert(toget <= missing); 2043 2044 /* loop over missing targets */ 2045 for(ns = iq->dp->nslist; ns; ns = ns->next) { 2046 if(ns->resolved) 2047 continue; 2048 2049 /* randomly select this item with probability toget/missing */ 2050 if(!iter_ns_probability(qstate->env->rnd, toget, missing)) { 2051 /* do not select this one, next; select toget number 2052 * of items from a list one less in size */ 2053 missing --; 2054 continue; 2055 } 2056 2057 if(ie->supports_ipv6 && 2058 ((ns->lame && !ns->done_pside6) || 2059 (!ns->lame && !ns->got6))) { 2060 /* Send the AAAA request. */ 2061 if(!generate_target_query(qstate, iq, id, 2062 ns->name, ns->namelen, 2063 LDNS_RR_TYPE_AAAA, iq->qchase.qclass)) { 2064 *num = query_count; 2065 if(query_count > 0) 2066 qstate->ext_state[id] = module_wait_subquery; 2067 return 1; 2068 } 2069 query_count++; 2070 /* If the mesh query list is full, exit the loop here. 2071 * This makes the routine spawn one query at a time, 2072 * and this means there is no query state load 2073 * increase, because the spawned state uses cpu and a 2074 * socket while this state waits for that spawned 2075 * state. Next time we can look up further targets */ 2076 if(mesh_jostle_exceeded(qstate->env->mesh)) { 2077 /* If no ip4 query is possible, that makes 2078 * this ns resolved. */ 2079 if(!((ie->supports_ipv4 || ie->nat64.use_nat64) && 2080 ((ns->lame && !ns->done_pside4) || 2081 (!ns->lame && !ns->got4)))) { 2082 ns->resolved = 1; 2083 } 2084 break; 2085 } 2086 } 2087 /* Send the A request. */ 2088 if((ie->supports_ipv4 || ie->nat64.use_nat64) && 2089 ((ns->lame && !ns->done_pside4) || 2090 (!ns->lame && !ns->got4))) { 2091 if(!generate_target_query(qstate, iq, id, 2092 ns->name, ns->namelen, 2093 LDNS_RR_TYPE_A, iq->qchase.qclass)) { 2094 *num = query_count; 2095 if(query_count > 0) 2096 qstate->ext_state[id] = module_wait_subquery; 2097 return 1; 2098 } 2099 query_count++; 2100 /* If the mesh query list is full, exit the loop. */ 2101 if(mesh_jostle_exceeded(qstate->env->mesh)) { 2102 /* With the ip6 query already checked for, 2103 * this makes the ns resolved. It is no longer 2104 * a missing target. */ 2105 ns->resolved = 1; 2106 break; 2107 } 2108 } 2109 2110 /* mark this target as in progress. */ 2111 ns->resolved = 1; 2112 missing--; 2113 toget--; 2114 if(toget == 0) 2115 break; 2116 } 2117 *num = query_count; 2118 if(query_count > 0) 2119 qstate->ext_state[id] = module_wait_subquery; 2120 2121 return 0; 2122 } 2123 2124 /** 2125 * Called by processQueryTargets when it would like extra targets to query 2126 * but it seems to be out of options. At last resort some less appealing 2127 * options are explored. If there are no more options, the result is SERVFAIL 2128 * 2129 * @param qstate: query state. 2130 * @param iq: iterator query state. 2131 * @param ie: iterator shared global environment. 2132 * @param id: module id. 2133 * @return true if the event requires more request processing immediately, 2134 * false if not. 2135 */ 2136 static int 2137 processLastResort(struct module_qstate* qstate, struct iter_qstate* iq, 2138 struct iter_env* ie, int id) 2139 { 2140 struct delegpt_ns* ns; 2141 int query_count = 0; 2142 verbose(VERB_ALGO, "No more query targets, attempting last resort"); 2143 log_assert(iq->dp); 2144 2145 if(!can_have_last_resort(qstate->env, iq->dp->name, iq->dp->namelen, 2146 iq->qchase.qclass, NULL, NULL, NULL)) { 2147 /* fail -- no more targets, no more hope of targets, no hope 2148 * of a response. */ 2149 errinf(qstate, "all the configured stub or forward servers failed,"); 2150 errinf_dname(qstate, "at zone", iq->dp->name); 2151 errinf_reply(qstate, iq); 2152 verbose(VERB_QUERY, "configured stub or forward servers failed -- returning SERVFAIL"); 2153 return error_response_cache(qstate, id, LDNS_RCODE_SERVFAIL); 2154 } 2155 iq->dp->fallback_to_parent_side_NS = 1; 2156 if(qstate->env->cfg->harden_unverified_glue) { 2157 if(!cache_fill_missing(qstate->env, iq->qchase.qclass, 2158 qstate->region, iq->dp, PACKED_RRSET_UNVERIFIED_GLUE)) 2159 log_err("out of memory in cache_fill_missing"); 2160 if(iq->dp->usable_list) { 2161 verbose(VERB_ALGO, "try unverified glue from cache"); 2162 return next_state(iq, QUERYTARGETS_STATE); 2163 } 2164 } 2165 if(!iq->dp->has_parent_side_NS && dname_is_root(iq->dp->name)) { 2166 struct delegpt* dp; 2167 int nolock = 0; 2168 dp = hints_find_root(qstate->env->hints, 2169 iq->qchase.qclass, nolock); 2170 if(dp) { 2171 struct delegpt_addr* a; 2172 iq->chase_flags &= ~BIT_RD; /* go to authorities */ 2173 for(ns = dp->nslist; ns; ns=ns->next) { 2174 (void)delegpt_add_ns(iq->dp, qstate->region, 2175 ns->name, ns->lame, ns->tls_auth_name, 2176 ns->port); 2177 } 2178 for(a = dp->target_list; a; a=a->next_target) { 2179 (void)delegpt_add_addr(iq->dp, qstate->region, 2180 &a->addr, a->addrlen, a->bogus, 2181 a->lame, a->tls_auth_name, -1, NULL); 2182 } 2183 lock_rw_unlock(&qstate->env->hints->lock); 2184 /* copy over some configuration since we update the 2185 * delegation point in place */ 2186 iq->dp->tcp_upstream = dp->tcp_upstream; 2187 iq->dp->ssl_upstream = dp->ssl_upstream; 2188 } 2189 iq->dp->has_parent_side_NS = 1; 2190 } else if(!iq->dp->has_parent_side_NS) { 2191 if(!iter_lookup_parent_NS_from_cache(qstate->env, iq->dp, 2192 qstate->region, &qstate->qinfo) 2193 || !iq->dp->has_parent_side_NS) { 2194 /* if: malloc failure in lookup go up to try */ 2195 /* if: no parent NS in cache - go up one level */ 2196 verbose(VERB_ALGO, "try to grab parent NS"); 2197 iq->store_parent_NS = iq->dp; 2198 iq->chase_flags &= ~BIT_RD; /* go to authorities */ 2199 iq->deleg_msg = NULL; 2200 iq->refetch_glue = 1; 2201 iq->query_restart_count++; 2202 iq->sent_count = 0; 2203 iq->dp_target_count = 0; 2204 if(qstate->env->cfg->qname_minimisation) 2205 iq->minimisation_state = INIT_MINIMISE_STATE; 2206 return next_state(iq, INIT_REQUEST_STATE); 2207 } 2208 } 2209 /* see if that makes new names available */ 2210 if(!cache_fill_missing(qstate->env, iq->qchase.qclass, 2211 qstate->region, iq->dp, 0)) 2212 log_err("out of memory in cache_fill_missing"); 2213 if(iq->dp->usable_list) { 2214 verbose(VERB_ALGO, "try parent-side-name, w. glue from cache"); 2215 return next_state(iq, QUERYTARGETS_STATE); 2216 } 2217 /* try to fill out parent glue from cache */ 2218 if(iter_lookup_parent_glue_from_cache(qstate->env, iq->dp, 2219 qstate->region, &qstate->qinfo)) { 2220 /* got parent stuff from cache, see if we can continue */ 2221 verbose(VERB_ALGO, "try parent-side glue from cache"); 2222 return next_state(iq, QUERYTARGETS_STATE); 2223 } 2224 /* query for an extra name added by the parent-NS record */ 2225 if(delegpt_count_missing_targets(iq->dp, NULL) > 0) { 2226 int qs = 0, ret; 2227 verbose(VERB_ALGO, "try parent-side target name"); 2228 if((ret=query_for_targets(qstate, iq, ie, id, 1, &qs))!=0) { 2229 errinf(qstate, "could not fetch nameserver"); 2230 errinf_dname(qstate, "at zone", iq->dp->name); 2231 if(ret == 1) 2232 return error_response(qstate, id, LDNS_RCODE_SERVFAIL); 2233 return error_response_cache(qstate, id, LDNS_RCODE_SERVFAIL); 2234 } 2235 iq->num_target_queries += qs; 2236 target_count_increase(iq, qs); 2237 if(qs != 0) { 2238 qstate->ext_state[id] = module_wait_subquery; 2239 return 0; /* and wait for them */ 2240 } 2241 } 2242 if(iq->depth == ie->max_dependency_depth) { 2243 verbose(VERB_QUERY, "maxdepth and need more nameservers, fail"); 2244 errinf(qstate, "cannot fetch more nameservers because at max dependency depth"); 2245 return error_response_cache(qstate, id, LDNS_RCODE_SERVFAIL); 2246 } 2247 if(iq->depth > 0 && iq->target_count && 2248 iq->target_count[TARGET_COUNT_QUERIES] > MAX_TARGET_COUNT) { 2249 char s[LDNS_MAX_DOMAINLEN]; 2250 dname_str(qstate->qinfo.qname, s); 2251 verbose(VERB_QUERY, "request %s has exceeded the maximum " 2252 "number of glue fetches %d", s, 2253 iq->target_count[TARGET_COUNT_QUERIES]); 2254 errinf(qstate, "exceeded the maximum number of glue fetches"); 2255 return error_response_cache(qstate, id, LDNS_RCODE_SERVFAIL); 2256 } 2257 /* mark cycle targets for parent-side lookups */ 2258 iter_mark_pside_cycle_targets(qstate, iq->dp); 2259 /* see if we can issue queries to get nameserver addresses */ 2260 /* this lookup is not randomized, but sequential. */ 2261 for(ns = iq->dp->nslist; ns; ns = ns->next) { 2262 /* if this nameserver is at a delegation point, but that 2263 * delegation point is a stub and we cannot go higher, skip*/ 2264 if( ((ie->supports_ipv6 && !ns->done_pside6) || 2265 ((ie->supports_ipv4 || ie->nat64.use_nat64) && !ns->done_pside4)) && 2266 !can_have_last_resort(qstate->env, ns->name, ns->namelen, 2267 iq->qchase.qclass, NULL, NULL, NULL)) { 2268 log_nametypeclass(VERB_ALGO, "cannot pside lookup ns " 2269 "because it is also a stub/forward,", 2270 ns->name, LDNS_RR_TYPE_NS, iq->qchase.qclass); 2271 if(ie->supports_ipv6) ns->done_pside6 = 1; 2272 if(ie->supports_ipv4 || ie->nat64.use_nat64) ns->done_pside4 = 1; 2273 continue; 2274 } 2275 /* query for parent-side A and AAAA for nameservers */ 2276 if(ie->supports_ipv6 && !ns->done_pside6) { 2277 /* Send the AAAA request. */ 2278 if(!generate_parentside_target_query(qstate, iq, id, 2279 ns->name, ns->namelen, 2280 LDNS_RR_TYPE_AAAA, iq->qchase.qclass)) { 2281 errinf_dname(qstate, "could not generate nameserver AAAA lookup for", ns->name); 2282 return error_response(qstate, id, 2283 LDNS_RCODE_SERVFAIL); 2284 } 2285 ns->done_pside6 = 1; 2286 query_count++; 2287 if(mesh_jostle_exceeded(qstate->env->mesh)) { 2288 /* Wait for the lookup; do not spawn multiple 2289 * lookups at a time. */ 2290 verbose(VERB_ALGO, "try parent-side glue lookup"); 2291 iq->num_target_queries += query_count; 2292 target_count_increase(iq, query_count); 2293 qstate->ext_state[id] = module_wait_subquery; 2294 return 0; 2295 } 2296 } 2297 if((ie->supports_ipv4 || ie->nat64.use_nat64) && !ns->done_pside4) { 2298 /* Send the A request. */ 2299 if(!generate_parentside_target_query(qstate, iq, id, 2300 ns->name, ns->namelen, 2301 LDNS_RR_TYPE_A, iq->qchase.qclass)) { 2302 errinf_dname(qstate, "could not generate nameserver A lookup for", ns->name); 2303 return error_response(qstate, id, 2304 LDNS_RCODE_SERVFAIL); 2305 } 2306 ns->done_pside4 = 1; 2307 query_count++; 2308 } 2309 if(query_count != 0) { /* suspend to await results */ 2310 verbose(VERB_ALGO, "try parent-side glue lookup"); 2311 iq->num_target_queries += query_count; 2312 target_count_increase(iq, query_count); 2313 qstate->ext_state[id] = module_wait_subquery; 2314 return 0; 2315 } 2316 } 2317 2318 /* if this was a parent-side glue query itself, then store that 2319 * failure in cache. */ 2320 if(!qstate->no_cache_store && iq->query_for_pside_glue 2321 && !iq->pside_glue) 2322 iter_store_parentside_neg(qstate->env, &qstate->qinfo, 2323 iq->deleg_msg?iq->deleg_msg->rep: 2324 (iq->response?iq->response->rep:NULL)); 2325 2326 errinf(qstate, "all servers for this domain failed,"); 2327 errinf_dname(qstate, "at zone", iq->dp->name); 2328 errinf_reply(qstate, iq); 2329 verbose(VERB_QUERY, "out of query targets -- returning SERVFAIL"); 2330 /* fail -- no more targets, no more hope of targets, no hope 2331 * of a response. */ 2332 return error_response_cache(qstate, id, LDNS_RCODE_SERVFAIL); 2333 } 2334 2335 /** 2336 * Try to find the NS record set that will resolve a qtype DS query. Due 2337 * to grandparent/grandchild reasons we did not get a proper lookup right 2338 * away. We need to create type NS queries until we get the right parent 2339 * for this lookup. We remove labels from the query to find the right point. 2340 * If we end up at the old dp name, then there is no solution. 2341 * 2342 * @param qstate: query state. 2343 * @param iq: iterator query state. 2344 * @param id: module id. 2345 * @return true if the event requires more immediate processing, false if 2346 * not. This is generally only true when forwarding the request to 2347 * the final state (i.e., on answer). 2348 */ 2349 static int 2350 processDSNSFind(struct module_qstate* qstate, struct iter_qstate* iq, int id) 2351 { 2352 struct module_qstate* subq = NULL; 2353 verbose(VERB_ALGO, "processDSNSFind"); 2354 2355 if(!iq->dsns_point) { 2356 /* initialize */ 2357 iq->dsns_point = iq->qchase.qname; 2358 iq->dsns_point_len = iq->qchase.qname_len; 2359 } 2360 /* robustcheck for internal error: we are not underneath the dp */ 2361 if(!dname_subdomain_c(iq->dsns_point, iq->dp->name)) { 2362 errinf_dname(qstate, "for DS query parent-child nameserver search the query is not under the zone", iq->dp->name); 2363 return error_response_cache(qstate, id, LDNS_RCODE_SERVFAIL); 2364 } 2365 2366 /* go up one (more) step, until we hit the dp, if so, end */ 2367 dname_remove_label(&iq->dsns_point, &iq->dsns_point_len); 2368 if(query_dname_compare(iq->dsns_point, iq->dp->name) == 0) { 2369 /* there was no inbetween nameserver, use the old delegation 2370 * point again. And this time, because dsns_point is nonNULL 2371 * we are going to accept the (bad) result */ 2372 iq->state = QUERYTARGETS_STATE; 2373 return 1; 2374 } 2375 iq->state = DSNS_FIND_STATE; 2376 2377 /* spawn NS lookup (validation not needed, this is for DS lookup) */ 2378 log_nametypeclass(VERB_ALGO, "fetch nameservers", 2379 iq->dsns_point, LDNS_RR_TYPE_NS, iq->qchase.qclass); 2380 if(!generate_sub_request(iq->dsns_point, iq->dsns_point_len, 2381 LDNS_RR_TYPE_NS, iq->qchase.qclass, qstate, id, iq, 2382 INIT_REQUEST_STATE, FINISHED_STATE, &subq, 0, 0)) { 2383 errinf_dname(qstate, "for DS query parent-child nameserver search, could not generate NS lookup for", iq->dsns_point); 2384 return error_response_cache(qstate, id, LDNS_RCODE_SERVFAIL); 2385 } 2386 2387 return 0; 2388 } 2389 2390 /** 2391 * Check if we wait responses for sent queries and update the iterator's 2392 * external state. 2393 */ 2394 static void 2395 check_waiting_queries(struct iter_qstate* iq, struct module_qstate* qstate, 2396 int id) 2397 { 2398 if(iq->num_target_queries>0 && iq->num_current_queries>0) { 2399 verbose(VERB_ALGO, "waiting for %d targets to " 2400 "resolve or %d outstanding queries to " 2401 "respond", iq->num_target_queries, 2402 iq->num_current_queries); 2403 qstate->ext_state[id] = module_wait_reply; 2404 } else if(iq->num_target_queries>0) { 2405 verbose(VERB_ALGO, "waiting for %d targets to " 2406 "resolve", iq->num_target_queries); 2407 qstate->ext_state[id] = module_wait_subquery; 2408 } else { 2409 verbose(VERB_ALGO, "waiting for %d " 2410 "outstanding queries to respond", 2411 iq->num_current_queries); 2412 qstate->ext_state[id] = module_wait_reply; 2413 } 2414 } 2415 2416 /** 2417 * This is the request event state where the request will be sent to one of 2418 * its current query targets. This state also handles issuing target lookup 2419 * queries for missing target IP addresses. Queries typically iterate on 2420 * this state, both when they are just trying different targets for a given 2421 * delegation point, and when they change delegation points. This state 2422 * roughly corresponds to RFC 1034 algorithm steps 3 and 4. 2423 * 2424 * @param qstate: query state. 2425 * @param iq: iterator query state. 2426 * @param ie: iterator shared global environment. 2427 * @param id: module id. 2428 * @return true if the event requires more request processing immediately, 2429 * false if not. This state only returns true when it is generating 2430 * a SERVFAIL response because the query has hit a dead end. 2431 */ 2432 static int 2433 processQueryTargets(struct module_qstate* qstate, struct iter_qstate* iq, 2434 struct iter_env* ie, int id) 2435 { 2436 int tf_policy; 2437 struct delegpt_addr* target; 2438 struct outbound_entry* outq; 2439 struct sockaddr_storage real_addr; 2440 socklen_t real_addrlen; 2441 int auth_fallback = 0; 2442 uint8_t* qout_orig = NULL; 2443 size_t qout_orig_len = 0; 2444 int sq_check_ratelimit = 1; 2445 int sq_was_ratelimited = 0; 2446 int can_do_promisc = 0; 2447 2448 /* NOTE: a request will encounter this state for each target it 2449 * needs to send a query to. That is, at least one per referral, 2450 * more if some targets timeout or return throwaway answers. */ 2451 2452 log_query_info(VERB_QUERY, "processQueryTargets:", &qstate->qinfo); 2453 verbose(VERB_ALGO, "processQueryTargets: targetqueries %d, " 2454 "currentqueries %d sentcount %d", iq->num_target_queries, 2455 iq->num_current_queries, iq->sent_count); 2456 2457 /* Make sure that we haven't run away */ 2458 if(iq->referral_count > MAX_REFERRAL_COUNT) { 2459 verbose(VERB_QUERY, "request has exceeded the maximum " 2460 "number of referrrals with %d", iq->referral_count); 2461 errinf(qstate, "exceeded the maximum of referrals"); 2462 return error_response_cache(qstate, id, LDNS_RCODE_SERVFAIL); 2463 } 2464 if(iq->sent_count > ie->max_sent_count) { 2465 verbose(VERB_QUERY, "request has exceeded the maximum " 2466 "number of sends with %d", iq->sent_count); 2467 errinf(qstate, "exceeded the maximum number of sends"); 2468 return error_response_cache(qstate, id, LDNS_RCODE_SERVFAIL); 2469 } 2470 2471 /* Check if we reached MAX_TARGET_NX limit without a fallback activation. */ 2472 if(iq->target_count && !*iq->nxns_dp && 2473 iq->target_count[TARGET_COUNT_NX] > MAX_TARGET_NX) { 2474 struct delegpt_ns* ns; 2475 /* If we can wait for resolution, do so. */ 2476 if(iq->num_target_queries>0 || iq->num_current_queries>0) { 2477 check_waiting_queries(iq, qstate, id); 2478 return 0; 2479 } 2480 verbose(VERB_ALGO, "request has exceeded the maximum " 2481 "number of nxdomain nameserver lookups (%d) with %d", 2482 MAX_TARGET_NX, iq->target_count[TARGET_COUNT_NX]); 2483 /* Check for dp because we require one below */ 2484 if(!iq->dp) { 2485 verbose(VERB_QUERY, "Failed to get a delegation, " 2486 "giving up"); 2487 errinf(qstate, "failed to get a delegation (eg. prime " 2488 "failure)"); 2489 return error_response(qstate, id, LDNS_RCODE_SERVFAIL); 2490 } 2491 /* We reached the limit but we already have parent side 2492 * information; stop resolution */ 2493 if(iq->dp->has_parent_side_NS) { 2494 verbose(VERB_ALGO, "parent-side information is " 2495 "already present for the delegation point, no " 2496 "fallback possible"); 2497 errinf(qstate, "exceeded the maximum nameserver nxdomains"); 2498 return error_response_cache(qstate, id, LDNS_RCODE_SERVFAIL); 2499 } 2500 verbose(VERB_ALGO, "initiating parent-side fallback for " 2501 "nxdomain nameserver lookups"); 2502 /* Mark all the current NSes as resolved to allow for parent 2503 * fallback */ 2504 for(ns=iq->dp->nslist; ns; ns=ns->next) { 2505 ns->resolved = 1; 2506 } 2507 /* Note the delegation point that triggered the NXNS fallback; 2508 * no reason for shared queries to keep trying there. 2509 * This also marks the fallback activation. */ 2510 *iq->nxns_dp = malloc(iq->dp->namelen); 2511 if(!*iq->nxns_dp) { 2512 verbose(VERB_ALGO, "out of memory while initiating " 2513 "fallback"); 2514 errinf(qstate, "exceeded the maximum nameserver " 2515 "nxdomains (malloc)"); 2516 return error_response(qstate, id, LDNS_RCODE_SERVFAIL); 2517 } 2518 memcpy(*iq->nxns_dp, iq->dp->name, iq->dp->namelen); 2519 } else if(iq->target_count && *iq->nxns_dp) { 2520 /* Handle the NXNS fallback case. */ 2521 /* If we can wait for resolution, do so. */ 2522 if(iq->num_target_queries>0 || iq->num_current_queries>0) { 2523 check_waiting_queries(iq, qstate, id); 2524 return 0; 2525 } 2526 /* Check for dp because we require one below */ 2527 if(!iq->dp) { 2528 verbose(VERB_QUERY, "Failed to get a delegation, " 2529 "giving up"); 2530 errinf(qstate, "failed to get a delegation (eg. prime " 2531 "failure)"); 2532 return error_response(qstate, id, LDNS_RCODE_SERVFAIL); 2533 } 2534 2535 if(iq->target_count[TARGET_COUNT_NX] > MAX_TARGET_NX_FALLBACK) { 2536 verbose(VERB_ALGO, "request has exceeded the maximum " 2537 "number of fallback nxdomain nameserver " 2538 "lookups (%d) with %d", MAX_TARGET_NX_FALLBACK, 2539 iq->target_count[TARGET_COUNT_NX]); 2540 errinf(qstate, "exceeded the maximum nameserver nxdomains"); 2541 return error_response_cache(qstate, id, LDNS_RCODE_SERVFAIL); 2542 } 2543 2544 if(!iq->dp->has_parent_side_NS) { 2545 struct delegpt_ns* ns; 2546 if(!dname_canonical_compare(*iq->nxns_dp, iq->dp->name)) { 2547 verbose(VERB_ALGO, "this delegation point " 2548 "initiated the fallback, marking the " 2549 "nslist as resolved"); 2550 for(ns=iq->dp->nslist; ns; ns=ns->next) { 2551 ns->resolved = 1; 2552 } 2553 } 2554 } 2555 } 2556 2557 /* Make sure we have a delegation point, otherwise priming failed 2558 * or another failure occurred */ 2559 if(!iq->dp) { 2560 verbose(VERB_QUERY, "Failed to get a delegation, giving up"); 2561 errinf(qstate, "failed to get a delegation (eg. prime failure)"); 2562 return error_response(qstate, id, LDNS_RCODE_SERVFAIL); 2563 } 2564 if(!ie->supports_ipv6) 2565 delegpt_no_ipv6(iq->dp); 2566 if(!ie->supports_ipv4 && !ie->nat64.use_nat64) 2567 delegpt_no_ipv4(iq->dp); 2568 delegpt_log(VERB_ALGO, iq->dp); 2569 2570 if(iq->num_current_queries>0) { 2571 /* already busy answering a query, this restart is because 2572 * more delegpt addrs became available, wait for existing 2573 * query. */ 2574 verbose(VERB_ALGO, "woke up, but wait for outstanding query"); 2575 qstate->ext_state[id] = module_wait_reply; 2576 return 0; 2577 } 2578 2579 if(iq->minimisation_state == INIT_MINIMISE_STATE 2580 && !(iq->chase_flags & BIT_RD)) { 2581 /* (Re)set qinfo_out to (new) delegation point, except when 2582 * qinfo_out is already a subdomain of dp. This happens when 2583 * increasing by more than one label at once (QNAMEs with more 2584 * than MAX_MINIMISE_COUNT labels). */ 2585 if(!(iq->qinfo_out.qname_len 2586 && dname_subdomain_c(iq->qchase.qname, 2587 iq->qinfo_out.qname) 2588 && dname_subdomain_c(iq->qinfo_out.qname, 2589 iq->dp->name))) { 2590 iq->qinfo_out.qname = iq->dp->name; 2591 iq->qinfo_out.qname_len = iq->dp->namelen; 2592 iq->qinfo_out.qtype = LDNS_RR_TYPE_A; 2593 iq->qinfo_out.qclass = iq->qchase.qclass; 2594 iq->qinfo_out.local_alias = NULL; 2595 iq->minimise_count = 0; 2596 } 2597 2598 iq->minimisation_state = MINIMISE_STATE; 2599 } 2600 if(iq->minimisation_state == MINIMISE_STATE) { 2601 int qchaselabs = dname_count_labels(iq->qchase.qname); 2602 int labdiff = qchaselabs - 2603 dname_count_labels(iq->qinfo_out.qname); 2604 2605 qout_orig = iq->qinfo_out.qname; 2606 qout_orig_len = iq->qinfo_out.qname_len; 2607 iq->qinfo_out.qname = iq->qchase.qname; 2608 iq->qinfo_out.qname_len = iq->qchase.qname_len; 2609 iq->minimise_count++; 2610 iq->timeout_count = 0; 2611 2612 iter_dec_attempts(iq->dp, 1, ie->outbound_msg_retry); 2613 2614 /* Limit number of iterations for QNAMEs with more 2615 * than MAX_MINIMISE_COUNT labels. Send first MINIMISE_ONE_LAB 2616 * labels of QNAME always individually. 2617 */ 2618 if(qchaselabs > MAX_MINIMISE_COUNT && labdiff > 1 && 2619 iq->minimise_count > MINIMISE_ONE_LAB) { 2620 if(iq->minimise_count < MAX_MINIMISE_COUNT) { 2621 int multilabs = qchaselabs - 1 - 2622 MINIMISE_ONE_LAB; 2623 int extralabs = multilabs / 2624 MINIMISE_MULTIPLE_LABS; 2625 2626 if (MAX_MINIMISE_COUNT - iq->minimise_count >= 2627 multilabs % MINIMISE_MULTIPLE_LABS) 2628 /* Default behaviour is to add 1 label 2629 * every iteration. Therefore, decrement 2630 * the extralabs by 1 */ 2631 extralabs--; 2632 if (extralabs < labdiff) 2633 labdiff -= extralabs; 2634 else 2635 labdiff = 1; 2636 } 2637 /* Last minimised iteration, send all labels with 2638 * QTYPE=NS */ 2639 else 2640 labdiff = 1; 2641 } 2642 2643 if(labdiff > 1) { 2644 verbose(VERB_QUERY, "removing %d labels", labdiff-1); 2645 dname_remove_labels(&iq->qinfo_out.qname, 2646 &iq->qinfo_out.qname_len, 2647 labdiff-1); 2648 } 2649 if(labdiff < 1 || (labdiff < 2 2650 && (iq->qchase.qtype == LDNS_RR_TYPE_DS 2651 || iq->qchase.qtype == LDNS_RR_TYPE_A))) 2652 /* Stop minimising this query, resolve "as usual" */ 2653 iq->minimisation_state = DONOT_MINIMISE_STATE; 2654 else if(!qstate->no_cache_lookup) { 2655 struct dns_msg* msg = dns_cache_lookup(qstate->env, 2656 iq->qinfo_out.qname, iq->qinfo_out.qname_len, 2657 iq->qinfo_out.qtype, iq->qinfo_out.qclass, 2658 qstate->query_flags, qstate->region, 2659 qstate->env->scratch, 0, iq->dp->name, 2660 iq->dp->namelen); 2661 if(msg && FLAGS_GET_RCODE(msg->rep->flags) == 2662 LDNS_RCODE_NOERROR) 2663 /* no need to send query if it is already 2664 * cached as NOERROR */ 2665 return 1; 2666 if(msg && FLAGS_GET_RCODE(msg->rep->flags) == 2667 LDNS_RCODE_NXDOMAIN && 2668 qstate->env->need_to_validate && 2669 qstate->env->cfg->harden_below_nxdomain) { 2670 if(msg->rep->security == sec_status_secure) { 2671 iq->response = msg; 2672 return final_state(iq); 2673 } 2674 if(msg->rep->security == sec_status_unchecked) { 2675 struct module_qstate* subq = NULL; 2676 if(!generate_sub_request( 2677 iq->qinfo_out.qname, 2678 iq->qinfo_out.qname_len, 2679 iq->qinfo_out.qtype, 2680 iq->qinfo_out.qclass, 2681 qstate, id, iq, 2682 INIT_REQUEST_STATE, 2683 FINISHED_STATE, &subq, 1, 1)) 2684 verbose(VERB_ALGO, 2685 "could not validate NXDOMAIN " 2686 "response"); 2687 } 2688 } 2689 if(msg && FLAGS_GET_RCODE(msg->rep->flags) == 2690 LDNS_RCODE_NXDOMAIN) { 2691 /* return and add a label in the next 2692 * minimisation iteration. 2693 */ 2694 return 1; 2695 } 2696 } 2697 } 2698 if(iq->minimisation_state == SKIP_MINIMISE_STATE) { 2699 if(iq->timeout_count < MAX_MINIMISE_TIMEOUT_COUNT) 2700 /* Do not increment qname, continue incrementing next 2701 * iteration */ 2702 iq->minimisation_state = MINIMISE_STATE; 2703 else if(!qstate->env->cfg->qname_minimisation_strict) 2704 /* Too many time-outs detected for this QNAME and QTYPE. 2705 * We give up, disable QNAME minimisation. */ 2706 iq->minimisation_state = DONOT_MINIMISE_STATE; 2707 } 2708 if(iq->minimisation_state == DONOT_MINIMISE_STATE) 2709 iq->qinfo_out = iq->qchase; 2710 2711 /* now find an answer to this query */ 2712 /* see if authority zones have an answer */ 2713 /* now we know the dp, we can check the auth zone for locally hosted 2714 * contents */ 2715 if(!iq->auth_zone_avoid && qstate->blacklist) { 2716 if(auth_zones_can_fallback(qstate->env->auth_zones, 2717 iq->dp->name, iq->dp->namelen, iq->qinfo_out.qclass)) { 2718 /* if cache is blacklisted and this zone allows us 2719 * to fallback to the internet, then do so, and 2720 * fetch results from the internet servers */ 2721 iq->auth_zone_avoid = 1; 2722 } 2723 } 2724 if(iq->auth_zone_avoid) { 2725 iq->auth_zone_avoid = 0; 2726 auth_fallback = 1; 2727 } else if(auth_zones_lookup(qstate->env->auth_zones, &iq->qinfo_out, 2728 qstate->region, &iq->response, &auth_fallback, iq->dp->name, 2729 iq->dp->namelen)) { 2730 /* use this as a response to be processed by the iterator */ 2731 if(verbosity >= VERB_ALGO) { 2732 log_dns_msg("msg from auth zone", 2733 &iq->response->qinfo, iq->response->rep); 2734 } 2735 if((iq->chase_flags&BIT_RD) && !(iq->response->rep->flags&BIT_AA)) { 2736 verbose(VERB_ALGO, "forwarder, ignoring referral from auth zone"); 2737 } else { 2738 qstate->env->mesh->num_query_authzone_up++; 2739 iq->num_current_queries++; 2740 iq->chase_to_rd = 0; 2741 iq->dnssec_lame_query = 0; 2742 iq->auth_zone_response = 1; 2743 return next_state(iq, QUERY_RESP_STATE); 2744 } 2745 } 2746 iq->auth_zone_response = 0; 2747 if(auth_fallback == 0) { 2748 /* like we got servfail from the auth zone lookup, and 2749 * no internet fallback */ 2750 verbose(VERB_ALGO, "auth zone lookup failed, no fallback," 2751 " servfail"); 2752 errinf(qstate, "auth zone lookup failed, fallback is off"); 2753 return error_response_cache(qstate, id, LDNS_RCODE_SERVFAIL); 2754 } 2755 if(iq->dp->auth_dp) { 2756 /* we wanted to fallback, but had no delegpt, only the 2757 * auth zone generated delegpt, create an actual one */ 2758 iq->auth_zone_avoid = 1; 2759 return next_state(iq, INIT_REQUEST_STATE); 2760 } 2761 /* but mostly, fallback==1 (like, when no such auth zone exists) 2762 * and we continue with lookups */ 2763 2764 tf_policy = 0; 2765 /* < not <=, because although the array is large enough for <=, the 2766 * generated query will immediately be discarded due to depth and 2767 * that servfail is cached, which is not good as opportunism goes. */ 2768 if(iq->depth < ie->max_dependency_depth 2769 && iq->num_target_queries == 0 2770 && (!iq->target_count || iq->target_count[TARGET_COUNT_NX]==0) 2771 && iq->sent_count < TARGET_FETCH_STOP) { 2772 can_do_promisc = 1; 2773 } 2774 /* if the mesh query list is full, then do not waste cpu and sockets to 2775 * fetch promiscuous targets. They can be looked up when needed. */ 2776 if(!iq->dp->fallback_to_parent_side_NS && can_do_promisc 2777 && !mesh_jostle_exceeded(qstate->env->mesh)) { 2778 tf_policy = ie->target_fetch_policy[iq->depth]; 2779 } 2780 2781 /* if in 0x20 fallback get as many targets as possible */ 2782 if(iq->caps_fallback) { 2783 int extra = 0, ret; 2784 size_t naddr, nres, navail; 2785 if((ret=query_for_targets(qstate, iq, ie, id, -1, &extra))!=0) { 2786 errinf(qstate, "could not fetch nameservers for 0x20 fallback"); 2787 if(ret == 1) 2788 return error_response(qstate, id, LDNS_RCODE_SERVFAIL); 2789 return error_response_cache(qstate, id, LDNS_RCODE_SERVFAIL); 2790 } 2791 iq->num_target_queries += extra; 2792 target_count_increase(iq, extra); 2793 if(iq->num_target_queries > 0) { 2794 /* wait to get all targets, we want to try em */ 2795 verbose(VERB_ALGO, "wait for all targets for fallback"); 2796 qstate->ext_state[id] = module_wait_reply; 2797 /* undo qname minimise step because we'll get back here 2798 * to do it again */ 2799 if(qout_orig && iq->minimise_count > 0) { 2800 iq->minimise_count--; 2801 iq->qinfo_out.qname = qout_orig; 2802 iq->qinfo_out.qname_len = qout_orig_len; 2803 } 2804 return 0; 2805 } 2806 /* did we do enough fallback queries already? */ 2807 delegpt_count_addr(iq->dp, &naddr, &nres, &navail); 2808 /* the current caps_server is the number of fallbacks sent. 2809 * the original query is one that matched too, so we have 2810 * caps_server+1 number of matching queries now */ 2811 if(iq->caps_server+1 >= naddr*3 || 2812 iq->caps_server*2+2 >= (size_t)ie->max_sent_count) { 2813 /* *2 on sentcount check because ipv6 may fail */ 2814 /* we're done, process the response */ 2815 verbose(VERB_ALGO, "0x20 fallback had %d responses " 2816 "match for %d wanted, done.", 2817 (int)iq->caps_server+1, (int)naddr*3); 2818 iq->response = iq->caps_response; 2819 iq->caps_fallback = 0; 2820 iter_dec_attempts(iq->dp, 3, ie->outbound_msg_retry); /* space for fallback */ 2821 iq->num_current_queries++; /* RespState decrements it*/ 2822 iq->referral_count++; /* make sure we don't loop */ 2823 iq->sent_count = 0; 2824 iq->dp_target_count = 0; 2825 iq->state = QUERY_RESP_STATE; 2826 return 1; 2827 } 2828 verbose(VERB_ALGO, "0x20 fallback number %d", 2829 (int)iq->caps_server); 2830 2831 /* if there is a policy to fetch missing targets 2832 * opportunistically, do it. we rely on the fact that once a 2833 * query (or queries) for a missing name have been issued, 2834 * they will not show up again. */ 2835 } else if(tf_policy != 0) { 2836 int extra = 0; 2837 verbose(VERB_ALGO, "attempt to get extra %d targets", 2838 tf_policy); 2839 (void)query_for_targets(qstate, iq, ie, id, tf_policy, &extra); 2840 /* errors ignored, these targets are not strictly necessary for 2841 * this result, we do not have to reply with SERVFAIL */ 2842 iq->num_target_queries += extra; 2843 target_count_increase(iq, extra); 2844 } 2845 2846 /* Add the current set of unused targets to our queue. */ 2847 delegpt_add_unused_targets(iq->dp); 2848 2849 if(qstate->env->auth_zones) { 2850 uint8_t* sname = NULL; 2851 size_t snamelen = 0; 2852 /* apply rpz triggers at query time; nameserver IP and dname */ 2853 struct dns_msg* forged_response_after_cname; 2854 struct dns_msg* forged_response = rpz_callback_from_iterator_module(qstate, iq); 2855 int count = 0; 2856 while(forged_response && reply_find_rrset_section_an( 2857 forged_response->rep, iq->qchase.qname, 2858 iq->qchase.qname_len, LDNS_RR_TYPE_CNAME, 2859 iq->qchase.qclass) && 2860 iq->qchase.qtype != LDNS_RR_TYPE_CNAME && 2861 count++ < ie->max_query_restarts) { 2862 /* another cname to follow */ 2863 if(!handle_cname_response(qstate, iq, forged_response, 2864 &sname, &snamelen)) { 2865 errinf(qstate, "malloc failure, CNAME info"); 2866 return error_response(qstate, id, LDNS_RCODE_SERVFAIL); 2867 } 2868 iq->qchase.qname = sname; 2869 iq->qchase.qname_len = snamelen; 2870 forged_response_after_cname = 2871 rpz_callback_from_iterator_cname(qstate, iq); 2872 if(forged_response_after_cname) { 2873 forged_response = forged_response_after_cname; 2874 } else { 2875 /* Follow the CNAME with a query restart */ 2876 iq->deleg_msg = NULL; 2877 iq->dp = NULL; 2878 iq->dsns_point = NULL; 2879 iq->auth_zone_response = 0; 2880 iq->refetch_glue = 0; 2881 iq->query_restart_count++; 2882 iq->sent_count = 0; 2883 iq->dp_target_count = 0; 2884 if(qstate->env->cfg->qname_minimisation) 2885 iq->minimisation_state = INIT_MINIMISE_STATE; 2886 outbound_list_clear(&iq->outlist); 2887 iq->num_current_queries = 0; 2888 fptr_ok(fptr_whitelist_modenv_detach_subs( 2889 qstate->env->detach_subs)); 2890 (*qstate->env->detach_subs)(qstate); 2891 iq->num_target_queries = 0; 2892 return next_state(iq, INIT_REQUEST_STATE); 2893 } 2894 } 2895 if(forged_response != NULL) { 2896 qstate->ext_state[id] = module_finished; 2897 qstate->return_rcode = LDNS_RCODE_NOERROR; 2898 qstate->return_msg = forged_response; 2899 iq->response = forged_response; 2900 next_state(iq, FINISHED_STATE); 2901 if(!iter_prepend(iq, qstate->return_msg, qstate->region)) { 2902 log_err("rpz: prepend rrsets: out of memory"); 2903 return error_response(qstate, id, LDNS_RCODE_SERVFAIL); 2904 } 2905 return 0; 2906 } 2907 } 2908 2909 /* Select the next usable target, filtering out unsuitable targets. */ 2910 target = iter_server_selection(ie, qstate->env, iq->dp, 2911 iq->dp->name, iq->dp->namelen, iq->qchase.qtype, 2912 &iq->dnssec_lame_query, &iq->chase_to_rd, 2913 iq->num_target_queries, qstate->blacklist, 2914 qstate->prefetch_leeway); 2915 2916 /* If no usable target was selected... */ 2917 if(!target) { 2918 /* Here we distinguish between three states: generate a new 2919 * target query, just wait, or quit (with a SERVFAIL). 2920 * We have the following information: number of active 2921 * target queries, number of active current queries, 2922 * the presence of missing targets at this delegation 2923 * point, and the given query target policy. */ 2924 2925 /* Check for the wait condition. If this is true, then 2926 * an action must be taken. */ 2927 if(iq->num_target_queries==0 && iq->num_current_queries==0) { 2928 /* If there is nothing to wait for, then we need 2929 * to distinguish between generating (a) new target 2930 * query, or failing. */ 2931 if(delegpt_count_missing_targets(iq->dp, NULL) > 0) { 2932 int qs = 0, ret; 2933 verbose(VERB_ALGO, "querying for next " 2934 "missing target"); 2935 if((ret=query_for_targets(qstate, iq, ie, id, 2936 1, &qs))!=0) { 2937 errinf(qstate, "could not fetch nameserver"); 2938 errinf_dname(qstate, "at zone", iq->dp->name); 2939 if(ret == 1) 2940 return error_response(qstate, id, 2941 LDNS_RCODE_SERVFAIL); 2942 return error_response_cache(qstate, id, 2943 LDNS_RCODE_SERVFAIL); 2944 } 2945 if(qs == 0 && 2946 delegpt_count_missing_targets(iq->dp, NULL) == 0){ 2947 /* it looked like there were missing 2948 * targets, but they did not turn up. 2949 * Try the bad choices again (if any), 2950 * when we get back here missing==0, 2951 * so this is not a loop. */ 2952 return 1; 2953 } 2954 if(qs == 0) { 2955 /* There should be targets now, and 2956 * if there are not, it should not 2957 * wait for no targets. Stop it from 2958 * waiting forever, or looping to 2959 * here, as a safeguard. */ 2960 errinf(qstate, "could not generate nameserver lookups"); 2961 errinf_dname(qstate, "at zone", iq->dp->name); 2962 return error_response(qstate, id, 2963 LDNS_RCODE_SERVFAIL); 2964 } 2965 iq->num_target_queries += qs; 2966 target_count_increase(iq, qs); 2967 } 2968 /* Since a target query might have been made, we 2969 * need to check again. */ 2970 if(iq->num_target_queries == 0) { 2971 /* if in capsforid fallback, instead of last 2972 * resort, we agree with the current reply 2973 * we have (if any) (our count of addrs bad)*/ 2974 if(iq->caps_fallback && iq->caps_reply) { 2975 /* we're done, process the response */ 2976 verbose(VERB_ALGO, "0x20 fallback had %d responses, " 2977 "but no more servers except " 2978 "last resort, done.", 2979 (int)iq->caps_server+1); 2980 iq->response = iq->caps_response; 2981 iq->caps_fallback = 0; 2982 iter_dec_attempts(iq->dp, 3, ie->outbound_msg_retry); /* space for fallback */ 2983 iq->num_current_queries++; /* RespState decrements it*/ 2984 iq->referral_count++; /* make sure we don't loop */ 2985 iq->sent_count = 0; 2986 iq->dp_target_count = 0; 2987 iq->state = QUERY_RESP_STATE; 2988 return 1; 2989 } 2990 return processLastResort(qstate, iq, ie, id); 2991 } 2992 } 2993 2994 /* otherwise, we have no current targets, so submerge 2995 * until one of the target or direct queries return. */ 2996 verbose(VERB_ALGO, "no current targets"); 2997 check_waiting_queries(iq, qstate, id); 2998 /* undo qname minimise step because we'll get back here 2999 * to do it again */ 3000 if(qout_orig && iq->minimise_count > 0) { 3001 iq->minimise_count--; 3002 iq->qinfo_out.qname = qout_orig; 3003 iq->qinfo_out.qname_len = qout_orig_len; 3004 } 3005 return 0; 3006 } 3007 3008 /* We have a target. We could have created promiscuous target 3009 * queries but we are currently under pressure (mesh_jostle_exceeded). 3010 * If we are configured to allow promiscuous target queries and haven't 3011 * gone out to the network for a target query for this delegation, then 3012 * it is possible to slip in a promiscuous one with a 1/10 chance. */ 3013 if(can_do_promisc && tf_policy == 0 && iq->depth == 0 3014 && iq->depth < ie->max_dependency_depth 3015 && ie->target_fetch_policy[iq->depth] != 0 3016 && iq->dp_target_count == 0 3017 && !ub_random_max(qstate->env->rnd, 10)) { 3018 int extra = 0; 3019 verbose(VERB_ALGO, "available target exists in cache but " 3020 "attempt to get extra 1 target"); 3021 (void)query_for_targets(qstate, iq, ie, id, 1, &extra); 3022 /* errors ignored, these targets are not strictly necessary for 3023 * this result, we do not have to reply with SERVFAIL */ 3024 if(extra > 0) { 3025 iq->num_target_queries += extra; 3026 target_count_increase(iq, extra); 3027 check_waiting_queries(iq, qstate, id); 3028 /* undo qname minimise step because we'll get back here 3029 * to do it again */ 3030 if(qout_orig && iq->minimise_count > 0) { 3031 iq->minimise_count--; 3032 iq->qinfo_out.qname = qout_orig; 3033 iq->qinfo_out.qname_len = qout_orig_len; 3034 } 3035 return 0; 3036 } 3037 } 3038 3039 target_count_increase_global_quota(iq, 1); 3040 if(iq->target_count && iq->target_count[TARGET_COUNT_GLOBAL_QUOTA] 3041 > MAX_GLOBAL_QUOTA) { 3042 char s[LDNS_MAX_DOMAINLEN]; 3043 dname_str(qstate->qinfo.qname, s); 3044 verbose(VERB_QUERY, "request %s has exceeded the maximum " 3045 "global quota on number of upstream queries %d", s, 3046 iq->target_count[TARGET_COUNT_GLOBAL_QUOTA]); 3047 return error_response_cache(qstate, id, LDNS_RCODE_SERVFAIL); 3048 } 3049 3050 /* Do not check ratelimit for forwarding queries or if we already got a 3051 * pass. */ 3052 sq_check_ratelimit = (!(iq->chase_flags & BIT_RD) && !iq->ratelimit_ok); 3053 /* We have a valid target. */ 3054 if(verbosity >= VERB_QUERY) { 3055 log_query_info(VERB_QUERY, "sending query:", &iq->qinfo_out); 3056 log_name_addr(VERB_QUERY, "sending to target:", iq->dp->name, 3057 &target->addr, target->addrlen); 3058 verbose(VERB_ALGO, "dnssec status: %s%s", 3059 iq->dnssec_expected?"expected": "not expected", 3060 iq->dnssec_lame_query?" but lame_query anyway": ""); 3061 } 3062 3063 real_addr = target->addr; 3064 real_addrlen = target->addrlen; 3065 3066 if(ie->nat64.use_nat64 && target->addr.ss_family == AF_INET) { 3067 addr_to_nat64(&target->addr, &ie->nat64.nat64_prefix_addr, 3068 ie->nat64.nat64_prefix_addrlen, ie->nat64.nat64_prefix_net, 3069 &real_addr, &real_addrlen); 3070 log_name_addr(VERB_QUERY, "applied NAT64:", 3071 iq->dp->name, &real_addr, real_addrlen); 3072 } 3073 3074 fptr_ok(fptr_whitelist_modenv_send_query(qstate->env->send_query)); 3075 outq = (*qstate->env->send_query)(&iq->qinfo_out, 3076 iq->chase_flags | (iq->chase_to_rd?BIT_RD:0), 3077 /* unset CD if to forwarder(RD set) and not dnssec retry 3078 * (blacklist nonempty) and no trust-anchors are configured 3079 * above the qname or on the first attempt when dnssec is on */ 3080 (qstate->env->cfg->disable_edns_do?0:EDNS_DO)| 3081 ((iq->chase_to_rd||(iq->chase_flags&BIT_RD)!=0)&& 3082 !qstate->blacklist&&(!iter_qname_indicates_dnssec(qstate->env, 3083 &iq->qinfo_out)||target->attempts==1)?0:BIT_CD), 3084 iq->dnssec_expected, iq->caps_fallback || is_caps_whitelisted( 3085 ie, iq), sq_check_ratelimit, &real_addr, real_addrlen, 3086 iq->dp->name, iq->dp->namelen, 3087 (iq->dp->tcp_upstream || qstate->env->cfg->tcp_upstream), 3088 (iq->dp->ssl_upstream || qstate->env->cfg->ssl_upstream), 3089 target->tls_auth_name, qstate, &sq_was_ratelimited); 3090 if(!outq) { 3091 if(sq_was_ratelimited) { 3092 lock_basic_lock(&ie->queries_ratelimit_lock); 3093 ie->num_queries_ratelimited++; 3094 lock_basic_unlock(&ie->queries_ratelimit_lock); 3095 verbose(VERB_ALGO, "query exceeded ratelimits"); 3096 qstate->was_ratelimited = 1; 3097 errinf_dname(qstate, "exceeded ratelimit for zone", 3098 iq->dp->name); 3099 return error_response_cache(qstate, id, LDNS_RCODE_SERVFAIL); 3100 } 3101 log_addr(VERB_QUERY, "error sending query to auth server", 3102 &real_addr, real_addrlen); 3103 if(qstate->env->cfg->qname_minimisation) 3104 iq->minimisation_state = SKIP_MINIMISE_STATE; 3105 return next_state(iq, QUERYTARGETS_STATE); 3106 } 3107 outbound_list_insert(&iq->outlist, outq); 3108 iq->num_current_queries++; 3109 iq->sent_count++; 3110 qstate->ext_state[id] = module_wait_reply; 3111 3112 return 0; 3113 } 3114 3115 /** find NS rrset in given list */ 3116 static struct ub_packed_rrset_key* 3117 find_NS(struct reply_info* rep, size_t from, size_t to) 3118 { 3119 size_t i; 3120 for(i=from; i<to; i++) { 3121 if(ntohs(rep->rrsets[i]->rk.type) == LDNS_RR_TYPE_NS) 3122 return rep->rrsets[i]; 3123 } 3124 return NULL; 3125 } 3126 3127 3128 /** 3129 * Process the query response. All queries end up at this state first. This 3130 * process generally consists of analyzing the response and routing the 3131 * event to the next state (either bouncing it back to a request state, or 3132 * terminating the processing for this event). 3133 * 3134 * @param qstate: query state. 3135 * @param iq: iterator query state. 3136 * @param ie: iterator shared global environment. 3137 * @param id: module id. 3138 * @return true if the event requires more immediate processing, false if 3139 * not. This is generally only true when forwarding the request to 3140 * the final state (i.e., on answer). 3141 */ 3142 static int 3143 processQueryResponse(struct module_qstate* qstate, struct iter_qstate* iq, 3144 struct iter_env* ie, int id) 3145 { 3146 int dnsseclame = 0, origtypecname = 0, orig_empty_nodata_found; 3147 enum response_type type; 3148 3149 iq->num_current_queries--; 3150 3151 if(!inplace_cb_query_response_call(qstate->env, qstate, iq->response)) 3152 log_err("unable to call query_response callback"); 3153 3154 if(iq->response == NULL) { 3155 /* Don't increment qname when QNAME minimisation is enabled */ 3156 if(qstate->env->cfg->qname_minimisation) { 3157 iq->minimisation_state = SKIP_MINIMISE_STATE; 3158 } 3159 iq->timeout_count++; 3160 iq->chase_to_rd = 0; 3161 iq->dnssec_lame_query = 0; 3162 verbose(VERB_ALGO, "query response was timeout"); 3163 return next_state(iq, QUERYTARGETS_STATE); 3164 } 3165 iq->timeout_count = 0; 3166 orig_empty_nodata_found = iq->empty_nodata_found; 3167 type = response_type_from_server( 3168 (int)((iq->chase_flags&BIT_RD) || iq->chase_to_rd), 3169 iq->response, &iq->qinfo_out, iq->dp, &iq->empty_nodata_found); 3170 iq->chase_to_rd = 0; 3171 /* remove TC flag, if this is erroneously set by TCP upstream */ 3172 iq->response->rep->flags &= ~BIT_TC; 3173 if(orig_empty_nodata_found != iq->empty_nodata_found && 3174 iq->empty_nodata_found < EMPTY_NODATA_RETRY_COUNT) { 3175 /* try to search at another server */ 3176 if(qstate->reply) { 3177 struct delegpt_addr* a = delegpt_find_addr( 3178 iq->dp, &qstate->reply->remote_addr, 3179 qstate->reply->remote_addrlen); 3180 /* make selection disprefer it */ 3181 if(a) a->lame = 1; 3182 } 3183 return next_state(iq, QUERYTARGETS_STATE); 3184 } 3185 if(type == RESPONSE_TYPE_REFERRAL && (iq->chase_flags&BIT_RD) && 3186 !iq->auth_zone_response) { 3187 /* When forwarding (RD bit is set), we handle referrals 3188 * differently. No queries should be sent elsewhere */ 3189 type = RESPONSE_TYPE_ANSWER; 3190 } 3191 if(!qstate->env->cfg->disable_dnssec_lame_check && iq->dnssec_expected 3192 && !iq->dnssec_lame_query && 3193 !(iq->chase_flags&BIT_RD) 3194 && iq->sent_count < DNSSEC_LAME_DETECT_COUNT 3195 && type != RESPONSE_TYPE_LAME 3196 && type != RESPONSE_TYPE_REC_LAME 3197 && type != RESPONSE_TYPE_THROWAWAY 3198 && type != RESPONSE_TYPE_UNTYPED) { 3199 /* a possible answer, see if it is missing DNSSEC */ 3200 /* but not when forwarding, so we dont mark fwder lame */ 3201 if(!iter_msg_has_dnssec(iq->response)) { 3202 /* Mark this address as dnsseclame in this dp, 3203 * because that will make serverselection disprefer 3204 * it, but also, once it is the only final option, 3205 * use dnssec-lame-bypass if it needs to query there.*/ 3206 if(qstate->reply) { 3207 struct delegpt_addr* a = delegpt_find_addr( 3208 iq->dp, &qstate->reply->remote_addr, 3209 qstate->reply->remote_addrlen); 3210 if(a) a->dnsseclame = 1; 3211 } 3212 /* test the answer is from the zone we expected, 3213 * otherwise, (due to parent,child on same server), we 3214 * might mark the server,zone lame inappropriately */ 3215 if(!iter_msg_from_zone(iq->response, iq->dp, type, 3216 iq->qchase.qclass)) 3217 qstate->reply = NULL; 3218 type = RESPONSE_TYPE_LAME; 3219 dnsseclame = 1; 3220 } 3221 } else iq->dnssec_lame_query = 0; 3222 /* see if referral brings us close to the target */ 3223 if(type == RESPONSE_TYPE_REFERRAL) { 3224 struct ub_packed_rrset_key* ns = find_NS( 3225 iq->response->rep, iq->response->rep->an_numrrsets, 3226 iq->response->rep->an_numrrsets 3227 + iq->response->rep->ns_numrrsets); 3228 if(!ns) ns = find_NS(iq->response->rep, 0, 3229 iq->response->rep->an_numrrsets); 3230 if(!ns || !dname_strict_subdomain_c(ns->rk.dname, iq->dp->name) 3231 || !dname_subdomain_c(iq->qchase.qname, ns->rk.dname)){ 3232 verbose(VERB_ALGO, "bad referral, throwaway"); 3233 type = RESPONSE_TYPE_THROWAWAY; 3234 } else 3235 iter_scrub_ds(iq->response, ns, iq->dp->name); 3236 } else iter_scrub_ds(iq->response, NULL, NULL); 3237 if(type == RESPONSE_TYPE_THROWAWAY && 3238 FLAGS_GET_RCODE(iq->response->rep->flags) == LDNS_RCODE_YXDOMAIN) { 3239 /* YXDOMAIN is a permanent error, no need to retry */ 3240 type = RESPONSE_TYPE_ANSWER; 3241 } 3242 if(type == RESPONSE_TYPE_CNAME) 3243 origtypecname = 1; 3244 if(type == RESPONSE_TYPE_CNAME && iq->response->rep->an_numrrsets >= 1 3245 && ntohs(iq->response->rep->rrsets[0]->rk.type) == LDNS_RR_TYPE_DNAME) { 3246 uint8_t* sname = NULL; 3247 size_t snamelen = 0; 3248 get_cname_target(iq->response->rep->rrsets[0], &sname, 3249 &snamelen); 3250 if(snamelen && dname_subdomain_c(sname, iq->response->rep->rrsets[0]->rk.dname)) { 3251 /* DNAME to a subdomain loop; do not recurse */ 3252 type = RESPONSE_TYPE_ANSWER; 3253 } 3254 } 3255 if(type == RESPONSE_TYPE_CNAME && 3256 (iq->qchase.qtype == LDNS_RR_TYPE_CNAME || 3257 iq->qchase.qtype == LDNS_RR_TYPE_ANY) && 3258 iq->minimisation_state == MINIMISE_STATE && 3259 query_dname_compare(iq->qchase.qname, iq->qinfo_out.qname) == 0) { 3260 /* The minimised query for full QTYPE and hidden QTYPE can be 3261 * classified as CNAME response type, even when the original 3262 * QTYPE=CNAME. This should be treated as answer response type. 3263 */ 3264 /* For QTYPE=ANY, it is also considered the response, that 3265 * is what the classifier would say, if it saw qtype ANY, 3266 * and this same response was returned for that. The response 3267 * can already be treated as such an answer, without having 3268 * to send another query with a new qtype. */ 3269 type = RESPONSE_TYPE_ANSWER; 3270 } 3271 3272 /* handle each of the type cases */ 3273 if(type == RESPONSE_TYPE_ANSWER) { 3274 /* ANSWER type responses terminate the query algorithm, 3275 * so they sent on their */ 3276 if(verbosity >= VERB_DETAIL) { 3277 verbose(VERB_DETAIL, "query response was %s", 3278 FLAGS_GET_RCODE(iq->response->rep->flags) 3279 ==LDNS_RCODE_NXDOMAIN?"NXDOMAIN ANSWER": 3280 (iq->response->rep->an_numrrsets?"ANSWER": 3281 "nodata ANSWER")); 3282 } 3283 /* if qtype is DS, check we have the right level of answer, 3284 * like grandchild answer but we need the middle, reject it */ 3285 if(iq->qchase.qtype == LDNS_RR_TYPE_DS && !iq->dsns_point 3286 && !(iq->chase_flags&BIT_RD) 3287 && iter_ds_toolow(iq->response, iq->dp) 3288 && iter_dp_cangodown(&iq->qchase, iq->dp)) { 3289 /* close down outstanding requests to be discarded */ 3290 outbound_list_clear(&iq->outlist); 3291 iq->num_current_queries = 0; 3292 fptr_ok(fptr_whitelist_modenv_detach_subs( 3293 qstate->env->detach_subs)); 3294 (*qstate->env->detach_subs)(qstate); 3295 iq->num_target_queries = 0; 3296 return processDSNSFind(qstate, iq, id); 3297 } 3298 if(iq->qchase.qtype == LDNS_RR_TYPE_DNSKEY && SERVE_EXPIRED 3299 && qstate->is_valrec && 3300 reply_find_answer_rrset(&iq->qchase, iq->response->rep) != NULL) { 3301 /* clean out the authority section, if any, so it 3302 * does not overwrite dnssec valid data in the 3303 * validation recursion lookup. */ 3304 verbose(VERB_ALGO, "make DNSKEY minimal for serve " 3305 "expired"); 3306 iter_make_minimal(iq->response->rep); 3307 } 3308 if(!qstate->no_cache_store) 3309 iter_dns_store(qstate->env, &iq->response->qinfo, 3310 iq->response->rep, 3311 iq->qchase.qtype != iq->response->qinfo.qtype, 3312 qstate->prefetch_leeway, 3313 iq->dp&&iq->dp->has_parent_side_NS, 3314 qstate->region, qstate->query_flags, 3315 qstate->qstarttime, qstate->is_valrec); 3316 /* close down outstanding requests to be discarded */ 3317 outbound_list_clear(&iq->outlist); 3318 iq->num_current_queries = 0; 3319 fptr_ok(fptr_whitelist_modenv_detach_subs( 3320 qstate->env->detach_subs)); 3321 (*qstate->env->detach_subs)(qstate); 3322 iq->num_target_queries = 0; 3323 if(qstate->reply) 3324 sock_list_insert(&qstate->reply_origin, 3325 &qstate->reply->remote_addr, 3326 qstate->reply->remote_addrlen, qstate->region); 3327 if(iq->minimisation_state != DONOT_MINIMISE_STATE 3328 && !(iq->chase_flags & BIT_RD)) { 3329 if(FLAGS_GET_RCODE(iq->response->rep->flags) != 3330 LDNS_RCODE_NOERROR) { 3331 if(qstate->env->cfg->qname_minimisation_strict) { 3332 if(FLAGS_GET_RCODE(iq->response->rep->flags) == 3333 LDNS_RCODE_NXDOMAIN) { 3334 iter_scrub_nxdomain(iq->response); 3335 return final_state(iq); 3336 } 3337 return error_response_cache(qstate, id, 3338 LDNS_RCODE_SERVFAIL); 3339 } 3340 /* Best effort qname-minimisation. 3341 * Stop minimising and send full query when 3342 * RCODE is not NOERROR. */ 3343 iq->minimisation_state = DONOT_MINIMISE_STATE; 3344 } 3345 if(FLAGS_GET_RCODE(iq->response->rep->flags) == 3346 LDNS_RCODE_NXDOMAIN && !origtypecname) { 3347 /* Stop resolving when NXDOMAIN is DNSSEC 3348 * signed. Based on assumption that nameservers 3349 * serving signed zones do not return NXDOMAIN 3350 * for empty-non-terminals. */ 3351 /* If this response is actually a CNAME type, 3352 * the nxdomain rcode may not be for the qname, 3353 * and so it is not the final response. */ 3354 if(iq->dnssec_expected) 3355 return final_state(iq); 3356 /* Make subrequest to validate intermediate 3357 * NXDOMAIN if harden-below-nxdomain is 3358 * enabled. */ 3359 if(qstate->env->cfg->harden_below_nxdomain && 3360 qstate->env->need_to_validate) { 3361 struct module_qstate* subq = NULL; 3362 log_query_info(VERB_QUERY, 3363 "schedule NXDOMAIN validation:", 3364 &iq->response->qinfo); 3365 if(!generate_sub_request( 3366 iq->response->qinfo.qname, 3367 iq->response->qinfo.qname_len, 3368 iq->response->qinfo.qtype, 3369 iq->response->qinfo.qclass, 3370 qstate, id, iq, 3371 INIT_REQUEST_STATE, 3372 FINISHED_STATE, &subq, 1, 1)) 3373 verbose(VERB_ALGO, 3374 "could not validate NXDOMAIN " 3375 "response"); 3376 } 3377 } 3378 return next_state(iq, QUERYTARGETS_STATE); 3379 } 3380 return final_state(iq); 3381 } else if(type == RESPONSE_TYPE_REFERRAL) { 3382 struct delegpt* old_dp = NULL; 3383 /* REFERRAL type responses get a reset of the 3384 * delegation point, and back to the QUERYTARGETS_STATE. */ 3385 verbose(VERB_DETAIL, "query response was REFERRAL"); 3386 3387 /* if hardened, only store referral if we asked for it */ 3388 if(!qstate->no_cache_store && 3389 (!qstate->env->cfg->harden_referral_path || 3390 ( qstate->qinfo.qtype == LDNS_RR_TYPE_NS 3391 && (qstate->query_flags&BIT_RD) 3392 && !(qstate->query_flags&BIT_CD) 3393 /* we know that all other NS rrsets are scrubbed 3394 * away, thus on referral only one is left. 3395 * see if that equals the query name... */ 3396 && ( /* auth section, but sometimes in answer section*/ 3397 reply_find_rrset_section_ns(iq->response->rep, 3398 iq->qchase.qname, iq->qchase.qname_len, 3399 LDNS_RR_TYPE_NS, iq->qchase.qclass) 3400 || reply_find_rrset_section_an(iq->response->rep, 3401 iq->qchase.qname, iq->qchase.qname_len, 3402 LDNS_RR_TYPE_NS, iq->qchase.qclass) 3403 ) 3404 ))) { 3405 /* Store the referral under the current query */ 3406 /* no prefetch-leeway, since its not the answer */ 3407 iter_dns_store(qstate->env, &iq->response->qinfo, 3408 iq->response->rep, 1, 0, 0, NULL, 0, 3409 qstate->qstarttime, qstate->is_valrec); 3410 if(iq->store_parent_NS) 3411 iter_store_parentside_NS(qstate->env, 3412 iq->response->rep); 3413 if(qstate->env->neg_cache) 3414 val_neg_addreferral(qstate->env->neg_cache, 3415 iq->response->rep, iq->dp->name); 3416 } 3417 /* store parent-side-in-zone-glue, if directly queried for */ 3418 if(!qstate->no_cache_store && iq->query_for_pside_glue 3419 && !iq->pside_glue) { 3420 iq->pside_glue = reply_find_rrset(iq->response->rep, 3421 iq->qchase.qname, iq->qchase.qname_len, 3422 iq->qchase.qtype, iq->qchase.qclass); 3423 if(iq->pside_glue) { 3424 log_rrset_key(VERB_ALGO, "found parent-side " 3425 "glue", iq->pside_glue); 3426 iter_store_parentside_rrset(qstate->env, 3427 iq->pside_glue); 3428 } 3429 } 3430 3431 /* Reset the event state, setting the current delegation 3432 * point to the referral. */ 3433 iq->deleg_msg = iq->response; 3434 /* Keep current delegation point for label comparison */ 3435 old_dp = iq->dp; 3436 iq->dp = delegpt_from_message(iq->response, qstate->region); 3437 if (qstate->env->cfg->qname_minimisation) 3438 iq->minimisation_state = INIT_MINIMISE_STATE; 3439 if(!iq->dp) { 3440 errinf(qstate, "malloc failure, for delegation point"); 3441 return error_response(qstate, id, LDNS_RCODE_SERVFAIL); 3442 } 3443 if(old_dp->namelabs + 1 < iq->dp->namelabs) { 3444 /* We got a grandchild delegation (more than one label 3445 * difference) than expected. Check for in-between 3446 * delegations in the cache and remove them. 3447 * They could prove problematic when they expire 3448 * and rrset_expired_above() encounters them during 3449 * delegation cache lookups. */ 3450 uint8_t* qname = iq->dp->name; 3451 size_t qnamelen = iq->dp->namelen; 3452 rrset_cache_remove_above(qstate->env->rrset_cache, 3453 &qname, &qnamelen, LDNS_RR_TYPE_NS, 3454 iq->qchase.qclass, *qstate->env->now, 3455 old_dp->name, old_dp->namelen); 3456 } 3457 if(!cache_fill_missing(qstate->env, iq->qchase.qclass, 3458 qstate->region, iq->dp, 0)) { 3459 errinf(qstate, "malloc failure, copy extra info into delegation point"); 3460 return error_response(qstate, id, LDNS_RCODE_SERVFAIL); 3461 } 3462 if(iq->store_parent_NS && query_dname_compare(iq->dp->name, 3463 iq->store_parent_NS->name) == 0) 3464 iter_merge_retry_counts(iq->dp, iq->store_parent_NS, 3465 ie->outbound_msg_retry); 3466 delegpt_log(VERB_ALGO, iq->dp); 3467 /* Count this as a referral. */ 3468 iq->referral_count++; 3469 iq->sent_count = 0; 3470 iq->dp_target_count = 0; 3471 /* see if the next dp is a trust anchor, or a DS was sent 3472 * along, indicating dnssec is expected for next zone */ 3473 iq->dnssec_expected = iter_indicates_dnssec(qstate->env, 3474 iq->dp, iq->response, iq->qchase.qclass); 3475 /* if dnssec, validating then also fetch the key for the DS */ 3476 if(iq->dnssec_expected && qstate->env->cfg->prefetch_key && 3477 !(qstate->query_flags&BIT_CD)) 3478 generate_dnskey_prefetch(qstate, iq, id); 3479 3480 /* spawn off NS and addr to auth servers for the NS we just 3481 * got in the referral. This gets authoritative answer 3482 * (answer section trust level) rrset. 3483 * right after, we detach the subs, answer goes to cache. */ 3484 if(qstate->env->cfg->harden_referral_path) 3485 generate_ns_check(qstate, iq, id); 3486 3487 /* stop current outstanding queries. 3488 * FIXME: should the outstanding queries be waited for and 3489 * handled? Say by a subquery that inherits the outbound_entry. 3490 */ 3491 outbound_list_clear(&iq->outlist); 3492 iq->num_current_queries = 0; 3493 fptr_ok(fptr_whitelist_modenv_detach_subs( 3494 qstate->env->detach_subs)); 3495 (*qstate->env->detach_subs)(qstate); 3496 iq->num_target_queries = 0; 3497 iq->response = NULL; 3498 iq->fail_addr_type = 0; 3499 verbose(VERB_ALGO, "cleared outbound list for next round"); 3500 return next_state(iq, QUERYTARGETS_STATE); 3501 } else if(type == RESPONSE_TYPE_CNAME) { 3502 uint8_t* sname = NULL; 3503 size_t snamelen = 0; 3504 /* CNAME type responses get a query restart (i.e., get a 3505 * reset of the query state and go back to INIT_REQUEST_STATE). 3506 */ 3507 verbose(VERB_DETAIL, "query response was CNAME"); 3508 if(verbosity >= VERB_ALGO) 3509 log_dns_msg("cname msg", &iq->response->qinfo, 3510 iq->response->rep); 3511 /* if qtype is DS, check we have the right level of answer, 3512 * like grandchild answer but we need the middle, reject it */ 3513 if(iq->qchase.qtype == LDNS_RR_TYPE_DS && !iq->dsns_point 3514 && !(iq->chase_flags&BIT_RD) 3515 && iter_ds_toolow(iq->response, iq->dp) 3516 && iter_dp_cangodown(&iq->qchase, iq->dp)) { 3517 outbound_list_clear(&iq->outlist); 3518 iq->num_current_queries = 0; 3519 fptr_ok(fptr_whitelist_modenv_detach_subs( 3520 qstate->env->detach_subs)); 3521 (*qstate->env->detach_subs)(qstate); 3522 iq->num_target_queries = 0; 3523 return processDSNSFind(qstate, iq, id); 3524 } 3525 if(iq->minimisation_state == MINIMISE_STATE && 3526 query_dname_compare(iq->qchase.qname, 3527 iq->qinfo_out.qname) != 0) { 3528 verbose(VERB_ALGO, "continue query minimisation, " 3529 "downwards, after CNAME response for " 3530 "intermediate label"); 3531 /* continue query minimisation, downwards */ 3532 return next_state(iq, QUERYTARGETS_STATE); 3533 } 3534 /* Process the CNAME response. */ 3535 if(!handle_cname_response(qstate, iq, iq->response, 3536 &sname, &snamelen)) { 3537 errinf(qstate, "malloc failure, CNAME info"); 3538 return error_response(qstate, id, LDNS_RCODE_SERVFAIL); 3539 } 3540 /* cache the CNAME response under the current query */ 3541 /* NOTE : set referral=1, so that rrsets get stored but not 3542 * the partial query answer (CNAME only). */ 3543 /* prefetchleeway applied because this updates answer parts */ 3544 if(!qstate->no_cache_store) 3545 iter_dns_store(qstate->env, &iq->response->qinfo, 3546 iq->response->rep, 1, qstate->prefetch_leeway, 3547 iq->dp&&iq->dp->has_parent_side_NS, NULL, 3548 qstate->query_flags, qstate->qstarttime, 3549 qstate->is_valrec); 3550 /* set the current request's qname to the new value. */ 3551 iq->qchase.qname = sname; 3552 iq->qchase.qname_len = snamelen; 3553 if(qstate->env->auth_zones) { 3554 /* apply rpz qname triggers after cname */ 3555 struct dns_msg* forged_response = 3556 rpz_callback_from_iterator_cname(qstate, iq); 3557 int count = 0; 3558 while(forged_response && reply_find_rrset_section_an( 3559 forged_response->rep, iq->qchase.qname, 3560 iq->qchase.qname_len, LDNS_RR_TYPE_CNAME, 3561 iq->qchase.qclass) && 3562 iq->qchase.qtype != LDNS_RR_TYPE_CNAME && 3563 count++ < ie->max_query_restarts) { 3564 /* another cname to follow */ 3565 if(!handle_cname_response(qstate, iq, forged_response, 3566 &sname, &snamelen)) { 3567 errinf(qstate, "malloc failure, CNAME info"); 3568 return error_response(qstate, id, LDNS_RCODE_SERVFAIL); 3569 } 3570 iq->qchase.qname = sname; 3571 iq->qchase.qname_len = snamelen; 3572 forged_response = 3573 rpz_callback_from_iterator_cname(qstate, iq); 3574 } 3575 if(forged_response != NULL) { 3576 qstate->ext_state[id] = module_finished; 3577 qstate->return_rcode = LDNS_RCODE_NOERROR; 3578 qstate->return_msg = forged_response; 3579 iq->response = forged_response; 3580 next_state(iq, FINISHED_STATE); 3581 if(!iter_prepend(iq, qstate->return_msg, qstate->region)) { 3582 log_err("rpz: after cname, prepend rrsets: out of memory"); 3583 return error_response(qstate, id, LDNS_RCODE_SERVFAIL); 3584 } 3585 qstate->return_msg->qinfo = qstate->qinfo; 3586 return 0; 3587 } 3588 } 3589 /* Clear the query state, since this is a query restart. */ 3590 iq->deleg_msg = NULL; 3591 iq->dp = NULL; 3592 iq->dsns_point = NULL; 3593 iq->auth_zone_response = 0; 3594 iq->sent_count = 0; 3595 iq->dp_target_count = 0; 3596 iq->query_restart_count++; 3597 if(qstate->env->cfg->qname_minimisation) 3598 iq->minimisation_state = INIT_MINIMISE_STATE; 3599 3600 /* stop current outstanding queries. 3601 * FIXME: should the outstanding queries be waited for and 3602 * handled? Say by a subquery that inherits the outbound_entry. 3603 */ 3604 outbound_list_clear(&iq->outlist); 3605 iq->num_current_queries = 0; 3606 fptr_ok(fptr_whitelist_modenv_detach_subs( 3607 qstate->env->detach_subs)); 3608 (*qstate->env->detach_subs)(qstate); 3609 iq->num_target_queries = 0; 3610 if(qstate->reply) 3611 sock_list_insert(&qstate->reply_origin, 3612 &qstate->reply->remote_addr, 3613 qstate->reply->remote_addrlen, qstate->region); 3614 verbose(VERB_ALGO, "cleared outbound list for query restart"); 3615 /* go to INIT_REQUEST_STATE for new qname. */ 3616 return next_state(iq, INIT_REQUEST_STATE); 3617 } else if(type == RESPONSE_TYPE_LAME) { 3618 /* Cache the LAMEness. */ 3619 verbose(VERB_DETAIL, "query response was %sLAME", 3620 dnsseclame?"DNSSEC ":""); 3621 if(!dname_subdomain_c(iq->qchase.qname, iq->dp->name)) { 3622 log_err("mark lame: mismatch in qname and dpname"); 3623 /* throwaway this reply below */ 3624 } else if(qstate->reply) { 3625 /* need addr for lameness cache, but we may have 3626 * gotten this from cache, so test to be sure */ 3627 if(!infra_set_lame(qstate->env->infra_cache, 3628 &qstate->reply->remote_addr, 3629 qstate->reply->remote_addrlen, 3630 iq->dp->name, iq->dp->namelen, 3631 *qstate->env->now, dnsseclame, 0, 3632 iq->qchase.qtype)) 3633 log_err("mark host lame: out of memory"); 3634 } 3635 } else if(type == RESPONSE_TYPE_REC_LAME) { 3636 /* Cache the LAMEness. */ 3637 verbose(VERB_DETAIL, "query response REC_LAME: " 3638 "recursive but not authoritative server"); 3639 if(!dname_subdomain_c(iq->qchase.qname, iq->dp->name)) { 3640 log_err("mark rec_lame: mismatch in qname and dpname"); 3641 /* throwaway this reply below */ 3642 } else if(qstate->reply) { 3643 /* need addr for lameness cache, but we may have 3644 * gotten this from cache, so test to be sure */ 3645 verbose(VERB_DETAIL, "mark as REC_LAME"); 3646 if(!infra_set_lame(qstate->env->infra_cache, 3647 &qstate->reply->remote_addr, 3648 qstate->reply->remote_addrlen, 3649 iq->dp->name, iq->dp->namelen, 3650 *qstate->env->now, 0, 1, iq->qchase.qtype)) 3651 log_err("mark host lame: out of memory"); 3652 } 3653 } else if(type == RESPONSE_TYPE_THROWAWAY) { 3654 /* LAME and THROWAWAY responses are handled the same way. 3655 * In this case, the event is just sent directly back to 3656 * the QUERYTARGETS_STATE without resetting anything, 3657 * because, clearly, the next target must be tried. */ 3658 verbose(VERB_DETAIL, "query response was THROWAWAY"); 3659 } else { 3660 log_warn("A query response came back with an unknown type: %d", 3661 (int)type); 3662 } 3663 3664 /* LAME, THROWAWAY and "unknown" all end up here. 3665 * Recycle to the QUERYTARGETS state to hopefully try a 3666 * different target. */ 3667 if (qstate->env->cfg->qname_minimisation && 3668 !qstate->env->cfg->qname_minimisation_strict) 3669 iq->minimisation_state = DONOT_MINIMISE_STATE; 3670 if(iq->auth_zone_response) { 3671 /* can we fallback? */ 3672 iq->auth_zone_response = 0; 3673 if(!auth_zones_can_fallback(qstate->env->auth_zones, 3674 iq->dp->name, iq->dp->namelen, qstate->qinfo.qclass)) { 3675 verbose(VERB_ALGO, "auth zone response bad, and no" 3676 " fallback possible, servfail"); 3677 errinf_dname(qstate, "response is bad, no fallback, " 3678 "for auth zone", iq->dp->name); 3679 return error_response_cache(qstate, id, LDNS_RCODE_SERVFAIL); 3680 } 3681 verbose(VERB_ALGO, "auth zone response was bad, " 3682 "fallback enabled"); 3683 iq->auth_zone_avoid = 1; 3684 if(iq->dp->auth_dp) { 3685 /* we are using a dp for the auth zone, with no 3686 * nameservers, get one first */ 3687 iq->dp = NULL; 3688 return next_state(iq, INIT_REQUEST_STATE); 3689 } 3690 } 3691 return next_state(iq, QUERYTARGETS_STATE); 3692 } 3693 3694 /** 3695 * Return priming query results to interested super querystates. 3696 * 3697 * Sets the delegation point and delegation message (not nonRD queries). 3698 * This is a callback from walk_supers. 3699 * 3700 * @param qstate: priming query state that finished. 3701 * @param id: module id. 3702 * @param forq: the qstate for which priming has been done. 3703 */ 3704 static void 3705 prime_supers(struct module_qstate* qstate, int id, struct module_qstate* forq) 3706 { 3707 struct iter_qstate* foriq = (struct iter_qstate*)forq->minfo[id]; 3708 struct delegpt* dp = NULL; 3709 3710 log_assert(qstate->is_priming || foriq->wait_priming_stub); 3711 log_assert(qstate->return_rcode == LDNS_RCODE_NOERROR); 3712 /* Convert our response to a delegation point */ 3713 dp = delegpt_from_message(qstate->return_msg, forq->region); 3714 if(!dp) { 3715 /* if there is no convertible delegation point, then 3716 * the ANSWER type was (presumably) a negative answer. */ 3717 verbose(VERB_ALGO, "prime response was not a positive " 3718 "ANSWER; failing"); 3719 foriq->dp = NULL; 3720 foriq->state = QUERYTARGETS_STATE; 3721 return; 3722 } 3723 3724 log_query_info(VERB_DETAIL, "priming successful for", &qstate->qinfo); 3725 delegpt_log(VERB_ALGO, dp); 3726 foriq->dp = dp; 3727 foriq->deleg_msg = dns_copy_msg(qstate->return_msg, forq->region); 3728 if(!foriq->deleg_msg) { 3729 log_err("copy prime response: out of memory"); 3730 foriq->dp = NULL; 3731 foriq->state = QUERYTARGETS_STATE; 3732 return; 3733 } 3734 3735 /* root priming responses go to init stage 2, priming stub 3736 * responses to to stage 3. */ 3737 if(foriq->wait_priming_stub) { 3738 foriq->state = INIT_REQUEST_3_STATE; 3739 foriq->wait_priming_stub = 0; 3740 } else foriq->state = INIT_REQUEST_2_STATE; 3741 /* because we are finished, the parent will be reactivated */ 3742 } 3743 3744 /** 3745 * This handles the response to a priming query. This is used to handle both 3746 * root and stub priming responses. This is basically the equivalent of the 3747 * QUERY_RESP_STATE, but will not handle CNAME responses and will treat 3748 * REFERRALs as ANSWERS. It will also update and reactivate the originating 3749 * event. 3750 * 3751 * @param qstate: query state. 3752 * @param id: module id. 3753 * @return true if the event needs more immediate processing, false if not. 3754 * This state always returns false. 3755 */ 3756 static int 3757 processPrimeResponse(struct module_qstate* qstate, int id) 3758 { 3759 struct iter_qstate* iq = (struct iter_qstate*)qstate->minfo[id]; 3760 enum response_type type; 3761 iq->response->rep->flags &= ~(BIT_RD|BIT_RA); /* ignore rec-lame */ 3762 type = response_type_from_server( 3763 (int)((iq->chase_flags&BIT_RD) || iq->chase_to_rd), 3764 iq->response, &iq->qchase, iq->dp, NULL); 3765 if(type == RESPONSE_TYPE_ANSWER) { 3766 qstate->return_rcode = LDNS_RCODE_NOERROR; 3767 qstate->return_msg = iq->response; 3768 } else { 3769 errinf(qstate, "prime response did not get an answer"); 3770 errinf_dname(qstate, "for", qstate->qinfo.qname); 3771 qstate->return_rcode = LDNS_RCODE_SERVFAIL; 3772 qstate->return_msg = NULL; 3773 } 3774 3775 /* validate the root or stub after priming (if enabled). 3776 * This is the same query as the prime query, but with validation. 3777 * Now that we are primed, the additional queries that validation 3778 * may need can be resolved. */ 3779 if(qstate->env->cfg->harden_referral_path) { 3780 struct module_qstate* subq = NULL; 3781 log_nametypeclass(VERB_ALGO, "schedule prime validation", 3782 qstate->qinfo.qname, qstate->qinfo.qtype, 3783 qstate->qinfo.qclass); 3784 if(!generate_sub_request(qstate->qinfo.qname, 3785 qstate->qinfo.qname_len, qstate->qinfo.qtype, 3786 qstate->qinfo.qclass, qstate, id, iq, 3787 INIT_REQUEST_STATE, FINISHED_STATE, &subq, 1, 0)) { 3788 verbose(VERB_ALGO, "could not generate prime check"); 3789 } 3790 generate_a_aaaa_check(qstate, iq, id); 3791 } 3792 3793 /* This event is finished. */ 3794 qstate->ext_state[id] = module_finished; 3795 return 0; 3796 } 3797 3798 /** 3799 * Do final processing on responses to target queries. Events reach this 3800 * state after the iterative resolution algorithm terminates. This state is 3801 * responsible for reactivating the original event, and housekeeping related 3802 * to received target responses (caching, updating the current delegation 3803 * point, etc). 3804 * Callback from walk_supers for every super state that is interested in 3805 * the results from this query. 3806 * 3807 * @param qstate: query state. 3808 * @param id: module id. 3809 * @param forq: super query state. 3810 */ 3811 static void 3812 processTargetResponse(struct module_qstate* qstate, int id, 3813 struct module_qstate* forq) 3814 { 3815 struct iter_env* ie = (struct iter_env*)qstate->env->modinfo[id]; 3816 struct iter_qstate* iq = (struct iter_qstate*)qstate->minfo[id]; 3817 struct iter_qstate* foriq = (struct iter_qstate*)forq->minfo[id]; 3818 struct ub_packed_rrset_key* rrset; 3819 struct delegpt_ns* dpns; 3820 log_assert(qstate->return_rcode == LDNS_RCODE_NOERROR); 3821 3822 foriq->state = QUERYTARGETS_STATE; 3823 log_query_info(VERB_ALGO, "processTargetResponse", &qstate->qinfo); 3824 log_query_info(VERB_ALGO, "processTargetResponse super", &forq->qinfo); 3825 3826 /* Tell the originating event that this target query has finished 3827 * (regardless if it succeeded or not). */ 3828 foriq->num_target_queries--; 3829 3830 /* check to see if parent event is still interested (in orig name). */ 3831 if(!foriq->dp) { 3832 verbose(VERB_ALGO, "subq: parent not interested, was reset"); 3833 return; /* not interested anymore */ 3834 } 3835 dpns = delegpt_find_ns(foriq->dp, qstate->qinfo.qname, 3836 qstate->qinfo.qname_len); 3837 if(!dpns) { 3838 /* If not interested, just stop processing this event */ 3839 verbose(VERB_ALGO, "subq: parent not interested anymore"); 3840 /* could be because parent was jostled out of the cache, 3841 and a new identical query arrived, that does not want it*/ 3842 return; 3843 } 3844 3845 /* if iq->query_for_pside_glue then add the pside_glue (marked lame) */ 3846 if(iq->pside_glue) { 3847 /* if the pside_glue is NULL, then it could not be found, 3848 * the done_pside is already set when created and a cache 3849 * entry created in processFinished so nothing to do here */ 3850 log_rrset_key(VERB_ALGO, "add parentside glue to dp", 3851 iq->pside_glue); 3852 if(!delegpt_add_rrset(foriq->dp, forq->region, 3853 iq->pside_glue, 1, NULL)) 3854 log_err("out of memory adding pside glue"); 3855 } 3856 3857 /* This response is relevant to the current query, so we 3858 * add (attempt to add, anyway) this target(s) and reactivate 3859 * the original event. 3860 * NOTE: we could only look for the AnswerRRset if the 3861 * response type was ANSWER. */ 3862 rrset = reply_find_answer_rrset(&iq->qchase, qstate->return_msg->rep); 3863 if(rrset) { 3864 int additions = 0; 3865 /* if CNAMEs have been followed - add new NS to delegpt. */ 3866 /* BTW. RFC 1918 says NS should not have got CNAMEs. Robust. */ 3867 if(!delegpt_find_ns(foriq->dp, rrset->rk.dname, 3868 rrset->rk.dname_len)) { 3869 /* if dpns->lame then set newcname ns lame too */ 3870 if(!delegpt_add_ns(foriq->dp, forq->region, 3871 rrset->rk.dname, dpns->lame, dpns->tls_auth_name, 3872 dpns->port)) 3873 log_err("out of memory adding cnamed-ns"); 3874 } 3875 /* if dpns->lame then set the address(es) lame too */ 3876 if(!delegpt_add_rrset(foriq->dp, forq->region, rrset, 3877 dpns->lame, &additions)) 3878 log_err("out of memory adding targets"); 3879 if(!additions) { 3880 /* no new addresses, increase the nxns counter, like 3881 * this could be a list of wildcards with no new 3882 * addresses */ 3883 target_count_increase_nx(foriq, 1); 3884 } 3885 verbose(VERB_ALGO, "added target response"); 3886 delegpt_log(VERB_ALGO, foriq->dp); 3887 } else { 3888 verbose(VERB_ALGO, "iterator TargetResponse failed"); 3889 delegpt_mark_neg(dpns, qstate->qinfo.qtype); 3890 if((dpns->got4 == 2 || (!ie->supports_ipv4 && !ie->nat64.use_nat64)) && 3891 (dpns->got6 == 2 || !ie->supports_ipv6)) { 3892 dpns->resolved = 1; /* fail the target */ 3893 /* do not count cached answers */ 3894 if(qstate->reply_origin && qstate->reply_origin->len != 0) { 3895 target_count_increase_nx(foriq, 1); 3896 } 3897 } 3898 } 3899 } 3900 3901 /** 3902 * Process response for DS NS Find queries, that attempt to find the delegation 3903 * point where we ask the DS query from. 3904 * 3905 * @param qstate: query state. 3906 * @param id: module id. 3907 * @param forq: super query state. 3908 */ 3909 static void 3910 processDSNSResponse(struct module_qstate* qstate, int id, 3911 struct module_qstate* forq) 3912 { 3913 struct iter_qstate* foriq = (struct iter_qstate*)forq->minfo[id]; 3914 3915 /* if the finished (iq->response) query has no NS set: continue 3916 * up to look for the right dp; nothing to change, do DPNSstate */ 3917 if(qstate->return_rcode != LDNS_RCODE_NOERROR) 3918 return; /* seek further */ 3919 /* find the NS RRset (without allowing CNAMEs) */ 3920 if(!reply_find_rrset(qstate->return_msg->rep, qstate->qinfo.qname, 3921 qstate->qinfo.qname_len, LDNS_RR_TYPE_NS, 3922 qstate->qinfo.qclass)){ 3923 return; /* seek further */ 3924 } 3925 3926 /* else, store as DP and continue at querytargets */ 3927 foriq->state = QUERYTARGETS_STATE; 3928 foriq->dp = delegpt_from_message(qstate->return_msg, forq->region); 3929 if(!foriq->dp) { 3930 log_err("out of memory in dsns dp alloc"); 3931 errinf(qstate, "malloc failure, in DS search"); 3932 return; /* dp==NULL in QUERYTARGETS makes SERVFAIL */ 3933 } 3934 /* success, go query the querytargets in the new dp (and go down) */ 3935 } 3936 3937 /** 3938 * Process response for qclass=ANY queries for a particular class. 3939 * Append to result or error-exit. 3940 * 3941 * @param qstate: query state. 3942 * @param id: module id. 3943 * @param forq: super query state. 3944 */ 3945 static void 3946 processClassResponse(struct module_qstate* qstate, int id, 3947 struct module_qstate* forq) 3948 { 3949 struct iter_qstate* foriq = (struct iter_qstate*)forq->minfo[id]; 3950 struct dns_msg* from = qstate->return_msg; 3951 log_query_info(VERB_ALGO, "processClassResponse", &qstate->qinfo); 3952 log_query_info(VERB_ALGO, "processClassResponse super", &forq->qinfo); 3953 if(qstate->return_rcode != LDNS_RCODE_NOERROR) { 3954 /* cause servfail for qclass ANY query */ 3955 foriq->response = NULL; 3956 foriq->state = FINISHED_STATE; 3957 return; 3958 } 3959 /* append result */ 3960 if(!foriq->response) { 3961 /* allocate the response: copy RCODE, sec_state */ 3962 foriq->response = dns_copy_msg(from, forq->region); 3963 if(!foriq->response) { 3964 log_err("malloc failed for qclass ANY response"); 3965 foriq->state = FINISHED_STATE; 3966 return; 3967 } 3968 foriq->response->qinfo.qclass = forq->qinfo.qclass; 3969 /* qclass ANY does not receive the AA flag on replies */ 3970 foriq->response->rep->authoritative = 0; 3971 } else { 3972 struct dns_msg* to = foriq->response; 3973 /* add _from_ this response _to_ existing collection */ 3974 /* if there are records, copy RCODE */ 3975 /* lower sec_state if this message is lower */ 3976 if(from->rep->rrset_count != 0) { 3977 size_t n = from->rep->rrset_count+to->rep->rrset_count; 3978 struct ub_packed_rrset_key** dest, **d; 3979 /* copy appropriate rcode */ 3980 to->rep->flags = from->rep->flags; 3981 /* copy rrsets */ 3982 if(from->rep->rrset_count > RR_COUNT_MAX || 3983 to->rep->rrset_count > RR_COUNT_MAX) { 3984 log_err("malloc failed (too many rrsets) in collect ANY"); 3985 foriq->state = FINISHED_STATE; 3986 return; /* integer overflow protection */ 3987 } 3988 dest = regional_alloc(forq->region, sizeof(dest[0])*n); 3989 if(!dest) { 3990 log_err("malloc failed in collect ANY"); 3991 foriq->state = FINISHED_STATE; 3992 return; 3993 } 3994 d = dest; 3995 /* copy AN */ 3996 memcpy(dest, to->rep->rrsets, to->rep->an_numrrsets 3997 * sizeof(dest[0])); 3998 dest += to->rep->an_numrrsets; 3999 memcpy(dest, from->rep->rrsets, from->rep->an_numrrsets 4000 * sizeof(dest[0])); 4001 dest += from->rep->an_numrrsets; 4002 /* copy NS */ 4003 memcpy(dest, to->rep->rrsets+to->rep->an_numrrsets, 4004 to->rep->ns_numrrsets * sizeof(dest[0])); 4005 dest += to->rep->ns_numrrsets; 4006 memcpy(dest, from->rep->rrsets+from->rep->an_numrrsets, 4007 from->rep->ns_numrrsets * sizeof(dest[0])); 4008 dest += from->rep->ns_numrrsets; 4009 /* copy AR */ 4010 memcpy(dest, to->rep->rrsets+to->rep->an_numrrsets+ 4011 to->rep->ns_numrrsets, 4012 to->rep->ar_numrrsets * sizeof(dest[0])); 4013 dest += to->rep->ar_numrrsets; 4014 memcpy(dest, from->rep->rrsets+from->rep->an_numrrsets+ 4015 from->rep->ns_numrrsets, 4016 from->rep->ar_numrrsets * sizeof(dest[0])); 4017 /* update counts */ 4018 to->rep->rrsets = d; 4019 to->rep->an_numrrsets += from->rep->an_numrrsets; 4020 to->rep->ns_numrrsets += from->rep->ns_numrrsets; 4021 to->rep->ar_numrrsets += from->rep->ar_numrrsets; 4022 to->rep->rrset_count = n; 4023 } 4024 if(from->rep->security < to->rep->security) /* lowest sec */ 4025 to->rep->security = from->rep->security; 4026 if(from->rep->qdcount != 0) /* insert qd if appropriate */ 4027 to->rep->qdcount = from->rep->qdcount; 4028 if(from->rep->ttl < to->rep->ttl) /* use smallest TTL */ 4029 to->rep->ttl = from->rep->ttl; 4030 if(from->rep->prefetch_ttl < to->rep->prefetch_ttl) 4031 to->rep->prefetch_ttl = from->rep->prefetch_ttl; 4032 if(from->rep->serve_expired_ttl < to->rep->serve_expired_ttl) 4033 to->rep->serve_expired_ttl = from->rep->serve_expired_ttl; 4034 if(from->rep->serve_expired_norec_ttl < to->rep->serve_expired_norec_ttl) 4035 to->rep->serve_expired_norec_ttl = from->rep->serve_expired_norec_ttl; 4036 } 4037 /* are we done? */ 4038 foriq->num_current_queries --; 4039 if(foriq->num_current_queries == 0) 4040 foriq->state = FINISHED_STATE; 4041 } 4042 4043 /** 4044 * Collect class ANY responses and make them into one response. This 4045 * state is started and it creates queries for all classes (that have 4046 * root hints). The answers are then collected. 4047 * 4048 * @param qstate: query state. 4049 * @param id: module id. 4050 * @return true if the event needs more immediate processing, false if not. 4051 */ 4052 static int 4053 processCollectClass(struct module_qstate* qstate, int id) 4054 { 4055 struct iter_qstate* iq = (struct iter_qstate*)qstate->minfo[id]; 4056 struct module_qstate* subq; 4057 /* If qchase.qclass == 0 then send out queries for all classes. 4058 * Otherwise, do nothing (wait for all answers to arrive and the 4059 * processClassResponse to put them together, and that moves us 4060 * towards the Finished state when done. */ 4061 if(iq->qchase.qclass == 0) { 4062 uint16_t c = 0; 4063 iq->qchase.qclass = LDNS_RR_CLASS_ANY; 4064 while(iter_get_next_root(qstate->env->hints, 4065 qstate->env->fwds, &c)) { 4066 /* generate query for this class */ 4067 log_nametypeclass(VERB_ALGO, "spawn collect query", 4068 qstate->qinfo.qname, qstate->qinfo.qtype, c); 4069 if(!generate_sub_request(qstate->qinfo.qname, 4070 qstate->qinfo.qname_len, qstate->qinfo.qtype, 4071 c, qstate, id, iq, INIT_REQUEST_STATE, 4072 FINISHED_STATE, &subq, 4073 (int)!(qstate->query_flags&BIT_CD), 0)) { 4074 errinf(qstate, "could not generate class ANY" 4075 " lookup query"); 4076 return error_response(qstate, id, 4077 LDNS_RCODE_SERVFAIL); 4078 } 4079 /* ignore subq, no special init required */ 4080 iq->num_current_queries ++; 4081 if(c == 0xffff) 4082 break; 4083 else c++; 4084 } 4085 /* if no roots are configured at all, return */ 4086 if(iq->num_current_queries == 0) { 4087 verbose(VERB_ALGO, "No root hints or fwds, giving up " 4088 "on qclass ANY"); 4089 return error_response_cache(qstate, id, LDNS_RCODE_REFUSED); 4090 } 4091 /* return false, wait for queries to return */ 4092 } 4093 /* if woke up here because of an answer, wait for more answers */ 4094 return 0; 4095 } 4096 4097 /** 4098 * This handles the final state for first-tier responses (i.e., responses to 4099 * externally generated queries). 4100 * 4101 * @param qstate: query state. 4102 * @param iq: iterator query state. 4103 * @param id: module id. 4104 * @return true if the event needs more processing, false if not. Since this 4105 * is the final state for an event, it always returns false. 4106 */ 4107 static int 4108 processFinished(struct module_qstate* qstate, struct iter_qstate* iq, 4109 int id) 4110 { 4111 log_query_info(VERB_QUERY, "finishing processing for", 4112 &qstate->qinfo); 4113 4114 /* store negative cache element for parent side glue. */ 4115 if(!qstate->no_cache_store && iq->query_for_pside_glue 4116 && !iq->pside_glue) 4117 iter_store_parentside_neg(qstate->env, &qstate->qinfo, 4118 iq->deleg_msg?iq->deleg_msg->rep: 4119 (iq->response?iq->response->rep:NULL)); 4120 if(!iq->response) { 4121 verbose(VERB_ALGO, "No response is set, servfail"); 4122 errinf(qstate, "(no response found at query finish)"); 4123 return error_response(qstate, id, LDNS_RCODE_SERVFAIL); 4124 } 4125 4126 /* Make sure that the RA flag is set (since the presence of 4127 * this module means that recursion is available) */ 4128 iq->response->rep->flags |= BIT_RA; 4129 4130 /* Clear the AA flag */ 4131 /* FIXME: does this action go here or in some other module? */ 4132 iq->response->rep->flags &= ~BIT_AA; 4133 4134 /* make sure QR flag is on */ 4135 iq->response->rep->flags |= BIT_QR; 4136 4137 /* explicitly set the EDE string to NULL */ 4138 iq->response->rep->reason_bogus_str = NULL; 4139 if((qstate->env->cfg->val_log_level >= 2 || 4140 qstate->env->cfg->log_servfail) && qstate->errinf && 4141 !qstate->env->cfg->val_log_squelch) { 4142 char* err_str = errinf_to_str_misc(qstate); 4143 if(err_str) { 4144 verbose(VERB_ALGO, "iterator EDE: %s", err_str); 4145 iq->response->rep->reason_bogus_str = err_str; 4146 } 4147 } 4148 4149 /* we have finished processing this query */ 4150 qstate->ext_state[id] = module_finished; 4151 4152 /* TODO: we are using a private TTL, trim the response. */ 4153 /* if (mPrivateTTL > 0){IterUtils.setPrivateTTL(resp, mPrivateTTL); } */ 4154 4155 /* prepend any items we have accumulated */ 4156 if(iq->an_prepend_list || iq->ns_prepend_list) { 4157 if(!iter_prepend(iq, iq->response, qstate->region)) { 4158 log_err("prepend rrsets: out of memory"); 4159 return error_response(qstate, id, LDNS_RCODE_SERVFAIL); 4160 } 4161 /* reset the query name back */ 4162 iq->response->qinfo = qstate->qinfo; 4163 /* the security state depends on the combination */ 4164 iq->response->rep->security = sec_status_unchecked; 4165 /* store message with the finished prepended items, 4166 * but only if we did recursion. The nonrecursion referral 4167 * from cache does not need to be stored in the msg cache. */ 4168 if(!qstate->no_cache_store && (qstate->query_flags&BIT_RD)) { 4169 iter_dns_store(qstate->env, &qstate->qinfo, 4170 iq->response->rep, 0, qstate->prefetch_leeway, 4171 iq->dp&&iq->dp->has_parent_side_NS, 4172 qstate->region, qstate->query_flags, 4173 qstate->qstarttime, qstate->is_valrec); 4174 } 4175 } 4176 qstate->return_rcode = LDNS_RCODE_NOERROR; 4177 qstate->return_msg = iq->response; 4178 return 0; 4179 } 4180 4181 /* 4182 * Return priming query results to interested super querystates. 4183 * 4184 * Sets the delegation point and delegation message (not nonRD queries). 4185 * This is a callback from walk_supers. 4186 * 4187 * @param qstate: query state that finished. 4188 * @param id: module id. 4189 * @param super: the qstate to inform. 4190 */ 4191 void 4192 iter_inform_super(struct module_qstate* qstate, int id, 4193 struct module_qstate* super) 4194 { 4195 if(!qstate->is_priming && super->qinfo.qclass == LDNS_RR_CLASS_ANY) 4196 processClassResponse(qstate, id, super); 4197 else if(super->qinfo.qtype == LDNS_RR_TYPE_DS && ((struct iter_qstate*) 4198 super->minfo[id])->state == DSNS_FIND_STATE) 4199 processDSNSResponse(qstate, id, super); 4200 else if(qstate->return_rcode != LDNS_RCODE_NOERROR) 4201 error_supers(qstate, id, super); 4202 else if(qstate->is_priming) 4203 prime_supers(qstate, id, super); 4204 else processTargetResponse(qstate, id, super); 4205 } 4206 4207 /** 4208 * Handle iterator state. 4209 * Handle events. This is the real processing loop for events, responsible 4210 * for moving events through the various states. If a processing method 4211 * returns true, then it will be advanced to the next state. If false, then 4212 * processing will stop. 4213 * 4214 * @param qstate: query state. 4215 * @param ie: iterator shared global environment. 4216 * @param iq: iterator query state. 4217 * @param id: module id. 4218 */ 4219 static void 4220 iter_handle(struct module_qstate* qstate, struct iter_qstate* iq, 4221 struct iter_env* ie, int id) 4222 { 4223 int cont = 1; 4224 while(cont) { 4225 verbose(VERB_ALGO, "iter_handle processing q with state %s", 4226 iter_state_to_string(iq->state)); 4227 switch(iq->state) { 4228 case INIT_REQUEST_STATE: 4229 cont = processInitRequest(qstate, iq, ie, id); 4230 break; 4231 case INIT_REQUEST_2_STATE: 4232 cont = processInitRequest2(qstate, iq, id); 4233 break; 4234 case INIT_REQUEST_3_STATE: 4235 cont = processInitRequest3(qstate, iq, id); 4236 break; 4237 case QUERYTARGETS_STATE: 4238 cont = processQueryTargets(qstate, iq, ie, id); 4239 break; 4240 case QUERY_RESP_STATE: 4241 cont = processQueryResponse(qstate, iq, ie, id); 4242 break; 4243 case PRIME_RESP_STATE: 4244 cont = processPrimeResponse(qstate, id); 4245 break; 4246 case COLLECT_CLASS_STATE: 4247 cont = processCollectClass(qstate, id); 4248 break; 4249 case DSNS_FIND_STATE: 4250 cont = processDSNSFind(qstate, iq, id); 4251 break; 4252 case FINISHED_STATE: 4253 cont = processFinished(qstate, iq, id); 4254 break; 4255 default: 4256 log_warn("iterator: invalid state: %d", 4257 iq->state); 4258 cont = 0; 4259 break; 4260 } 4261 } 4262 } 4263 4264 /** 4265 * This is the primary entry point for processing request events. Note that 4266 * this method should only be used by external modules. 4267 * @param qstate: query state. 4268 * @param ie: iterator shared global environment. 4269 * @param iq: iterator query state. 4270 * @param id: module id. 4271 */ 4272 static void 4273 process_request(struct module_qstate* qstate, struct iter_qstate* iq, 4274 struct iter_env* ie, int id) 4275 { 4276 /* external requests start in the INIT state, and finish using the 4277 * FINISHED state. */ 4278 iq->state = INIT_REQUEST_STATE; 4279 iq->final_state = FINISHED_STATE; 4280 verbose(VERB_ALGO, "process_request: new external request event"); 4281 iter_handle(qstate, iq, ie, id); 4282 } 4283 4284 /** process authoritative server reply */ 4285 static void 4286 process_response(struct module_qstate* qstate, struct iter_qstate* iq, 4287 struct iter_env* ie, int id, struct outbound_entry* outbound, 4288 enum module_ev event) 4289 { 4290 struct msg_parse* prs; 4291 struct edns_data edns; 4292 sldns_buffer* pkt; 4293 4294 verbose(VERB_ALGO, "process_response: new external response event"); 4295 iq->response = NULL; 4296 iq->state = QUERY_RESP_STATE; 4297 if(event == module_event_noreply || event == module_event_error) { 4298 if(event == module_event_noreply && iq->timeout_count >= 3 && 4299 qstate->env->cfg->use_caps_bits_for_id && 4300 !iq->caps_fallback && !is_caps_whitelisted(ie, iq)) { 4301 /* start fallback */ 4302 iq->caps_fallback = 1; 4303 iq->caps_server = 0; 4304 iq->caps_reply = NULL; 4305 iq->caps_response = NULL; 4306 iq->caps_minimisation_state = DONOT_MINIMISE_STATE; 4307 iq->state = QUERYTARGETS_STATE; 4308 iq->num_current_queries--; 4309 /* need fresh attempts for the 0x20 fallback, if 4310 * that was the cause for the failure */ 4311 iter_dec_attempts(iq->dp, 3, ie->outbound_msg_retry); 4312 verbose(VERB_DETAIL, "Capsforid: timeouts, starting fallback"); 4313 goto handle_it; 4314 } 4315 goto handle_it; 4316 } 4317 if( (event != module_event_reply && event != module_event_capsfail) 4318 || !qstate->reply) { 4319 log_err("Bad event combined with response"); 4320 outbound_list_remove(&iq->outlist, outbound); 4321 errinf(qstate, "module iterator received wrong internal event with a response message"); 4322 (void)error_response(qstate, id, LDNS_RCODE_SERVFAIL); 4323 return; 4324 } 4325 4326 /* parse message */ 4327 fill_fail_addr(iq, &qstate->reply->remote_addr, 4328 qstate->reply->remote_addrlen); 4329 prs = (struct msg_parse*)regional_alloc(qstate->env->scratch, 4330 sizeof(struct msg_parse)); 4331 if(!prs) { 4332 log_err("out of memory on incoming message"); 4333 /* like packet got dropped */ 4334 goto handle_it; 4335 } 4336 memset(prs, 0, sizeof(*prs)); 4337 memset(&edns, 0, sizeof(edns)); 4338 pkt = qstate->reply->c->buffer; 4339 sldns_buffer_set_position(pkt, 0); 4340 if(parse_packet(pkt, prs, qstate->env->scratch) != LDNS_RCODE_NOERROR) { 4341 verbose(VERB_ALGO, "parse error on reply packet"); 4342 iq->parse_failures++; 4343 goto handle_it; 4344 } 4345 /* edns is not examined, but removed from message to help cache */ 4346 if(parse_extract_edns_from_response_msg(prs, &edns, qstate->env->scratch) != 4347 LDNS_RCODE_NOERROR) { 4348 iq->parse_failures++; 4349 goto handle_it; 4350 } 4351 4352 /* Copy the edns options we may got from the back end */ 4353 qstate->edns_opts_back_in = NULL; 4354 if(edns.opt_list_in) { 4355 qstate->edns_opts_back_in = edns_opt_copy_region(edns.opt_list_in, 4356 qstate->region); 4357 if(!qstate->edns_opts_back_in) { 4358 log_err("out of memory on incoming message"); 4359 /* like packet got dropped */ 4360 goto handle_it; 4361 } 4362 } 4363 if(!inplace_cb_edns_back_parsed_call(qstate->env, qstate)) { 4364 log_err("unable to call edns_back_parsed callback"); 4365 goto handle_it; 4366 } 4367 4368 /* remove CD-bit, we asked for in case we handle validation ourself */ 4369 prs->flags &= ~BIT_CD; 4370 4371 /* normalize and sanitize: easy to delete items from linked lists */ 4372 if(!scrub_message(pkt, prs, &iq->qinfo_out, iq->dp->name, 4373 qstate->env->scratch, qstate->env, qstate, ie)) { 4374 /* if 0x20 enabled, start fallback, but we have no message */ 4375 if(event == module_event_capsfail && !iq->caps_fallback) { 4376 iq->caps_fallback = 1; 4377 iq->caps_server = 0; 4378 iq->caps_reply = NULL; 4379 iq->caps_response = NULL; 4380 iq->caps_minimisation_state = DONOT_MINIMISE_STATE; 4381 iq->state = QUERYTARGETS_STATE; 4382 iq->num_current_queries--; 4383 verbose(VERB_DETAIL, "Capsforid: scrub failed, starting fallback with no response"); 4384 } 4385 iq->scrub_failures++; 4386 goto handle_it; 4387 } 4388 4389 /* allocate response dns_msg in region */ 4390 iq->response = dns_alloc_msg(pkt, prs, qstate->region); 4391 if(!iq->response) 4392 goto handle_it; 4393 log_query_info(VERB_DETAIL, "response for", &qstate->qinfo); 4394 log_name_addr(VERB_DETAIL, "reply from", iq->dp->name, 4395 &qstate->reply->remote_addr, qstate->reply->remote_addrlen); 4396 if(verbosity >= VERB_ALGO) 4397 log_dns_msg("incoming scrubbed packet:", &iq->response->qinfo, 4398 iq->response->rep); 4399 4400 if(qstate->env->cfg->aggressive_nsec) { 4401 limit_nsec_ttl(iq->response); 4402 } 4403 if(event == module_event_capsfail || iq->caps_fallback) { 4404 if(qstate->env->cfg->qname_minimisation && 4405 iq->minimisation_state != DONOT_MINIMISE_STATE) { 4406 /* Skip QNAME minimisation for next query, since that 4407 * one has to match the current query. */ 4408 iq->minimisation_state = SKIP_MINIMISE_STATE; 4409 } 4410 /* for fallback we care about main answer, not additionals */ 4411 /* removing that makes comparison more likely to succeed */ 4412 caps_strip_reply(iq->response->rep); 4413 4414 if(iq->caps_fallback && 4415 iq->caps_minimisation_state != iq->minimisation_state) { 4416 /* QNAME minimisation state has changed, restart caps 4417 * fallback. */ 4418 iq->caps_fallback = 0; 4419 } 4420 4421 if(!iq->caps_fallback) { 4422 /* start fallback */ 4423 iq->caps_fallback = 1; 4424 iq->caps_server = 0; 4425 iq->caps_reply = iq->response->rep; 4426 iq->caps_response = iq->response; 4427 iq->caps_minimisation_state = iq->minimisation_state; 4428 iq->state = QUERYTARGETS_STATE; 4429 iq->num_current_queries--; 4430 verbose(VERB_DETAIL, "Capsforid: starting fallback"); 4431 goto handle_it; 4432 } else { 4433 /* check if reply is the same, otherwise, fail */ 4434 if(!iq->caps_reply) { 4435 iq->caps_reply = iq->response->rep; 4436 iq->caps_response = iq->response; 4437 iq->caps_server = -1; /*become zero at ++, 4438 so that we start the full set of trials */ 4439 } else if(caps_failed_rcode(iq->caps_reply) && 4440 !caps_failed_rcode(iq->response->rep)) { 4441 /* prefer to upgrade to non-SERVFAIL */ 4442 iq->caps_reply = iq->response->rep; 4443 iq->caps_response = iq->response; 4444 } else if(!caps_failed_rcode(iq->caps_reply) && 4445 caps_failed_rcode(iq->response->rep)) { 4446 /* if we have non-SERVFAIL as answer then 4447 * we can ignore SERVFAILs for the equality 4448 * comparison */ 4449 /* no instructions here, skip other else */ 4450 } else if(caps_failed_rcode(iq->caps_reply) && 4451 caps_failed_rcode(iq->response->rep)) { 4452 /* failure is same as other failure in fallbk*/ 4453 /* no instructions here, skip other else */ 4454 } else if(!reply_equal(iq->response->rep, iq->caps_reply, 4455 qstate->env->scratch)) { 4456 verbose(VERB_DETAIL, "Capsforid fallback: " 4457 "getting different replies, failed"); 4458 outbound_list_remove(&iq->outlist, outbound); 4459 errinf(qstate, "0x20 failed, then got different replies in fallback"); 4460 (void)error_response_cache(qstate, id, 4461 LDNS_RCODE_SERVFAIL); 4462 return; 4463 } 4464 /* continue the fallback procedure at next server */ 4465 iq->caps_server++; 4466 iq->state = QUERYTARGETS_STATE; 4467 iq->num_current_queries--; 4468 verbose(VERB_DETAIL, "Capsforid: reply is equal. " 4469 "go to next fallback"); 4470 goto handle_it; 4471 } 4472 } 4473 iq->caps_fallback = 0; /* if we were in fallback, 0x20 is OK now */ 4474 4475 handle_it: 4476 outbound_list_remove(&iq->outlist, outbound); 4477 iter_handle(qstate, iq, ie, id); 4478 } 4479 4480 void 4481 iter_operate(struct module_qstate* qstate, enum module_ev event, int id, 4482 struct outbound_entry* outbound) 4483 { 4484 struct iter_env* ie = (struct iter_env*)qstate->env->modinfo[id]; 4485 struct iter_qstate* iq = (struct iter_qstate*)qstate->minfo[id]; 4486 verbose(VERB_QUERY, "iterator[module %d] operate: extstate:%s event:%s", 4487 id, strextstate(qstate->ext_state[id]), strmodulevent(event)); 4488 if(iq) log_query_info(VERB_QUERY, "iterator operate: query", 4489 &qstate->qinfo); 4490 if(iq && qstate->qinfo.qname != iq->qchase.qname) 4491 log_query_info(VERB_QUERY, "iterator operate: chased to", 4492 &iq->qchase); 4493 4494 /* perform iterator state machine */ 4495 if((event == module_event_new || event == module_event_pass) && 4496 iq == NULL) { 4497 if(!iter_new(qstate, id)) { 4498 errinf(qstate, "malloc failure, new iterator module allocation"); 4499 (void)error_response(qstate, id, LDNS_RCODE_SERVFAIL); 4500 return; 4501 } 4502 iq = (struct iter_qstate*)qstate->minfo[id]; 4503 process_request(qstate, iq, ie, id); 4504 return; 4505 } 4506 if(iq && event == module_event_pass) { 4507 iter_handle(qstate, iq, ie, id); 4508 return; 4509 } 4510 if(iq && outbound) { 4511 process_response(qstate, iq, ie, id, outbound, event); 4512 return; 4513 } 4514 if(event == module_event_error) { 4515 verbose(VERB_ALGO, "got called with event error, giving up"); 4516 errinf(qstate, "iterator module got the error event"); 4517 (void)error_response(qstate, id, LDNS_RCODE_SERVFAIL); 4518 return; 4519 } 4520 4521 log_err("bad event for iterator"); 4522 errinf(qstate, "iterator module received wrong event"); 4523 (void)error_response(qstate, id, LDNS_RCODE_SERVFAIL); 4524 } 4525 4526 void 4527 iter_clear(struct module_qstate* qstate, int id) 4528 { 4529 struct iter_qstate* iq; 4530 if(!qstate) 4531 return; 4532 iq = (struct iter_qstate*)qstate->minfo[id]; 4533 if(iq) { 4534 outbound_list_clear(&iq->outlist); 4535 if(iq->target_count && --iq->target_count[TARGET_COUNT_REF] == 0) { 4536 free(iq->target_count); 4537 if(*iq->nxns_dp) free(*iq->nxns_dp); 4538 free(iq->nxns_dp); 4539 } 4540 iq->num_current_queries = 0; 4541 } 4542 qstate->minfo[id] = NULL; 4543 } 4544 4545 size_t 4546 iter_get_mem(struct module_env* env, int id) 4547 { 4548 struct iter_env* ie = (struct iter_env*)env->modinfo[id]; 4549 if(!ie) 4550 return 0; 4551 return sizeof(*ie) + sizeof(int)*((size_t)ie->max_dependency_depth+1) 4552 + donotq_get_mem(ie->donotq) + priv_get_mem(ie->priv); 4553 } 4554 4555 /** 4556 * The iterator function block 4557 */ 4558 static struct module_func_block iter_block = { 4559 "iterator", 4560 NULL, NULL, &iter_init, &iter_deinit, &iter_operate, 4561 &iter_inform_super, &iter_clear, &iter_get_mem 4562 }; 4563 4564 struct module_func_block* 4565 iter_get_funcblock(void) 4566 { 4567 return &iter_block; 4568 } 4569 4570 const char* 4571 iter_state_to_string(enum iter_state state) 4572 { 4573 switch (state) 4574 { 4575 case INIT_REQUEST_STATE : 4576 return "INIT REQUEST STATE"; 4577 case INIT_REQUEST_2_STATE : 4578 return "INIT REQUEST STATE (stage 2)"; 4579 case INIT_REQUEST_3_STATE: 4580 return "INIT REQUEST STATE (stage 3)"; 4581 case QUERYTARGETS_STATE : 4582 return "QUERY TARGETS STATE"; 4583 case PRIME_RESP_STATE : 4584 return "PRIME RESPONSE STATE"; 4585 case COLLECT_CLASS_STATE : 4586 return "COLLECT CLASS STATE"; 4587 case DSNS_FIND_STATE : 4588 return "DSNS FIND STATE"; 4589 case QUERY_RESP_STATE : 4590 return "QUERY RESPONSE STATE"; 4591 case FINISHED_STATE : 4592 return "FINISHED RESPONSE STATE"; 4593 default : 4594 return "UNKNOWN ITER STATE"; 4595 } 4596 } 4597 4598 int 4599 iter_state_is_responsestate(enum iter_state s) 4600 { 4601 switch(s) { 4602 case INIT_REQUEST_STATE : 4603 case INIT_REQUEST_2_STATE : 4604 case INIT_REQUEST_3_STATE : 4605 case QUERYTARGETS_STATE : 4606 case COLLECT_CLASS_STATE : 4607 return 0; 4608 default: 4609 break; 4610 } 4611 return 1; 4612 } 4613