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