1 /* 2 * services/mesh.c - deal with mesh of query states and handle events for that. 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 functions to assist in dealing with a mesh of 40 * query states. This mesh is supposed to be thread-specific. 41 * It consists of query states (per qname, qtype, qclass) and connections 42 * between query states and the super and subquery states, and replies to 43 * send back to clients. 44 */ 45 #include "config.h" 46 #include "services/mesh.h" 47 #include "services/outbound_list.h" 48 #include "services/cache/dns.h" 49 #include "services/cache/rrset.h" 50 #include "util/log.h" 51 #include "util/net_help.h" 52 #include "util/module.h" 53 #include "util/regional.h" 54 #include "util/data/msgencode.h" 55 #include "util/timehist.h" 56 #include "util/fptr_wlist.h" 57 #include "util/alloc.h" 58 #include "util/config_file.h" 59 #include "util/edns.h" 60 #include "sldns/sbuffer.h" 61 #include "sldns/wire2str.h" 62 #include "services/localzone.h" 63 #include "util/data/dname.h" 64 #include "respip/respip.h" 65 #include "services/listen_dnsport.h" 66 67 /** subtract timers and the values do not overflow or become negative */ 68 static void 69 timeval_subtract(struct timeval* d, const struct timeval* end, const struct timeval* start) 70 { 71 #ifndef S_SPLINT_S 72 time_t end_usec = end->tv_usec; 73 d->tv_sec = end->tv_sec - start->tv_sec; 74 if(end_usec < start->tv_usec) { 75 end_usec += 1000000; 76 d->tv_sec--; 77 } 78 d->tv_usec = end_usec - start->tv_usec; 79 #endif 80 } 81 82 /** add timers and the values do not overflow or become negative */ 83 static void 84 timeval_add(struct timeval* d, const struct timeval* add) 85 { 86 #ifndef S_SPLINT_S 87 d->tv_sec += add->tv_sec; 88 d->tv_usec += add->tv_usec; 89 if(d->tv_usec >= 1000000 ) { 90 d->tv_usec -= 1000000; 91 d->tv_sec++; 92 } 93 #endif 94 } 95 96 /** divide sum of timers to get average */ 97 static void 98 timeval_divide(struct timeval* avg, const struct timeval* sum, size_t d) 99 { 100 #ifndef S_SPLINT_S 101 size_t leftover; 102 if(d <= 0) { 103 avg->tv_sec = 0; 104 avg->tv_usec = 0; 105 return; 106 } 107 avg->tv_sec = sum->tv_sec / d; 108 avg->tv_usec = sum->tv_usec / d; 109 /* handle fraction from seconds divide */ 110 leftover = sum->tv_sec - avg->tv_sec*d; 111 if(leftover <= 0) 112 leftover = 0; 113 avg->tv_usec += (((long long)leftover)*((long long)1000000))/d; 114 if(avg->tv_sec < 0) 115 avg->tv_sec = 0; 116 if(avg->tv_usec < 0) 117 avg->tv_usec = 0; 118 #endif 119 } 120 121 /** histogram compare of time values */ 122 static int 123 timeval_smaller(const struct timeval* x, const struct timeval* y) 124 { 125 #ifndef S_SPLINT_S 126 if(x->tv_sec < y->tv_sec) 127 return 1; 128 else if(x->tv_sec == y->tv_sec) { 129 if(x->tv_usec <= y->tv_usec) 130 return 1; 131 else return 0; 132 } 133 else return 0; 134 #endif 135 } 136 137 /** 138 * Compare two response-ip client info entries for the purpose of mesh state 139 * compare. It returns 0 if ci_a and ci_b are considered equal; otherwise 140 * 1 or -1 (they mean 'ci_a is larger/smaller than ci_b', respectively, but 141 * in practice it should be only used to mean they are different). 142 * We cannot share the mesh state for two queries if different response-ip 143 * actions can apply in the end, even if those queries are otherwise identical. 144 * For this purpose we compare tag lists and tag action lists; they should be 145 * identical to share the same state. 146 * For tag data, we don't look into the data content, as it can be 147 * expensive; unless tag data are not defined for both or they point to the 148 * exact same data in memory (i.e., they come from the same ACL entry), we 149 * consider these data different. 150 * Likewise, if the client info is associated with views, we don't look into 151 * the views. They are considered different unless they are exactly the same 152 * even if the views only differ in the names. 153 */ 154 static int 155 client_info_compare(const struct respip_client_info* ci_a, 156 const struct respip_client_info* ci_b) 157 { 158 int cmp; 159 160 if(!ci_a && !ci_b) 161 return 0; 162 if(ci_a && !ci_b) 163 return -1; 164 if(!ci_a && ci_b) 165 return 1; 166 if(ci_a->taglen != ci_b->taglen) 167 return (ci_a->taglen < ci_b->taglen) ? -1 : 1; 168 if(ci_a->taglist && !ci_b->taglist) 169 return -1; 170 if(!ci_a->taglist && ci_b->taglist) 171 return 1; 172 if(ci_a->taglist && ci_b->taglist) { 173 cmp = memcmp(ci_a->taglist, ci_b->taglist, ci_a->taglen); 174 if(cmp != 0) 175 return cmp; 176 } 177 if(ci_a->tag_actions_size != ci_b->tag_actions_size) 178 return (ci_a->tag_actions_size < ci_b->tag_actions_size) ? 179 -1 : 1; 180 if(ci_a->tag_actions && !ci_b->tag_actions) 181 return -1; 182 if(!ci_a->tag_actions && ci_b->tag_actions) 183 return 1; 184 if(ci_a->tag_actions && ci_b->tag_actions) { 185 cmp = memcmp(ci_a->tag_actions, ci_b->tag_actions, 186 ci_a->tag_actions_size); 187 if(cmp != 0) 188 return cmp; 189 } 190 if(ci_a->tag_datas != ci_b->tag_datas) 191 return ci_a->tag_datas < ci_b->tag_datas ? -1 : 1; 192 if(ci_a->view != ci_b->view) 193 return ci_a->view < ci_b->view ? -1 : 1; 194 /* For the unbound daemon these should be non-NULL and identical, 195 * but we check that just in case. */ 196 if(ci_a->respip_set != ci_b->respip_set) 197 return ci_a->respip_set < ci_b->respip_set ? -1 : 1; 198 return 0; 199 } 200 201 int 202 mesh_state_compare(const void* ap, const void* bp) 203 { 204 struct mesh_state* a = (struct mesh_state*)ap; 205 struct mesh_state* b = (struct mesh_state*)bp; 206 int cmp; 207 208 if(a->unique < b->unique) 209 return -1; 210 if(a->unique > b->unique) 211 return 1; 212 213 if(a->s.is_priming && !b->s.is_priming) 214 return -1; 215 if(!a->s.is_priming && b->s.is_priming) 216 return 1; 217 218 if(a->s.is_valrec && !b->s.is_valrec) 219 return -1; 220 if(!a->s.is_valrec && b->s.is_valrec) 221 return 1; 222 223 if((a->s.query_flags&BIT_RD) && !(b->s.query_flags&BIT_RD)) 224 return -1; 225 if(!(a->s.query_flags&BIT_RD) && (b->s.query_flags&BIT_RD)) 226 return 1; 227 228 if((a->s.query_flags&BIT_CD) && !(b->s.query_flags&BIT_CD)) 229 return -1; 230 if(!(a->s.query_flags&BIT_CD) && (b->s.query_flags&BIT_CD)) 231 return 1; 232 233 cmp = query_info_compare(&a->s.qinfo, &b->s.qinfo); 234 if(cmp != 0) 235 return cmp; 236 return client_info_compare(a->s.client_info, b->s.client_info); 237 } 238 239 int 240 mesh_state_ref_compare(const void* ap, const void* bp) 241 { 242 struct mesh_state_ref* a = (struct mesh_state_ref*)ap; 243 struct mesh_state_ref* b = (struct mesh_state_ref*)bp; 244 return mesh_state_compare(a->s, b->s); 245 } 246 247 struct mesh_area* 248 mesh_create(struct module_stack* stack, struct module_env* env) 249 { 250 struct mesh_area* mesh = calloc(1, sizeof(struct mesh_area)); 251 if(!mesh) { 252 log_err("mesh area alloc: out of memory"); 253 return NULL; 254 } 255 mesh->histogram = timehist_setup(); 256 mesh->qbuf_bak = sldns_buffer_new(env->cfg->msg_buffer_size); 257 if(!mesh->histogram || !mesh->qbuf_bak) { 258 free(mesh); 259 log_err("mesh area alloc: out of memory"); 260 return NULL; 261 } 262 mesh->mods = *stack; 263 mesh->env = env; 264 rbtree_init(&mesh->run, &mesh_state_compare); 265 rbtree_init(&mesh->all, &mesh_state_compare); 266 mesh->num_reply_addrs = 0; 267 mesh->num_reply_states = 0; 268 mesh->num_detached_states = 0; 269 mesh->num_forever_states = 0; 270 mesh->stats_jostled = 0; 271 mesh->stats_dropped = 0; 272 mesh->ans_expired = 0; 273 mesh->max_reply_states = env->cfg->num_queries_per_thread; 274 mesh->max_forever_states = (mesh->max_reply_states+1)/2; 275 #ifndef S_SPLINT_S 276 mesh->jostle_max.tv_sec = (time_t)(env->cfg->jostle_time / 1000); 277 mesh->jostle_max.tv_usec = (time_t)((env->cfg->jostle_time % 1000) 278 *1000); 279 #endif 280 return mesh; 281 } 282 283 /** help mesh delete delete mesh states */ 284 static void 285 mesh_delete_helper(rbnode_type* n) 286 { 287 struct mesh_state* mstate = (struct mesh_state*)n->key; 288 /* perform a full delete, not only 'cleanup' routine, 289 * because other callbacks expect a clean state in the mesh. 290 * For 're-entrant' calls */ 291 mesh_state_delete(&mstate->s); 292 /* but because these delete the items from the tree, postorder 293 * traversal and rbtree rebalancing do not work together */ 294 } 295 296 void 297 mesh_delete(struct mesh_area* mesh) 298 { 299 if(!mesh) 300 return; 301 /* free all query states */ 302 while(mesh->all.count) 303 mesh_delete_helper(mesh->all.root); 304 timehist_delete(mesh->histogram); 305 sldns_buffer_free(mesh->qbuf_bak); 306 free(mesh); 307 } 308 309 void 310 mesh_delete_all(struct mesh_area* mesh) 311 { 312 /* free all query states */ 313 while(mesh->all.count) 314 mesh_delete_helper(mesh->all.root); 315 mesh->stats_dropped += mesh->num_reply_addrs; 316 /* clear mesh area references */ 317 rbtree_init(&mesh->run, &mesh_state_compare); 318 rbtree_init(&mesh->all, &mesh_state_compare); 319 mesh->num_reply_addrs = 0; 320 mesh->num_reply_states = 0; 321 mesh->num_detached_states = 0; 322 mesh->num_forever_states = 0; 323 mesh->forever_first = NULL; 324 mesh->forever_last = NULL; 325 mesh->jostle_first = NULL; 326 mesh->jostle_last = NULL; 327 } 328 329 int mesh_make_new_space(struct mesh_area* mesh, sldns_buffer* qbuf) 330 { 331 struct mesh_state* m = mesh->jostle_first; 332 /* free space is available */ 333 if(mesh->num_reply_states < mesh->max_reply_states) 334 return 1; 335 /* try to kick out a jostle-list item */ 336 if(m && m->reply_list && m->list_select == mesh_jostle_list) { 337 /* how old is it? */ 338 struct timeval age; 339 timeval_subtract(&age, mesh->env->now_tv, 340 &m->reply_list->start_time); 341 if(timeval_smaller(&mesh->jostle_max, &age)) { 342 /* its a goner */ 343 log_nametypeclass(VERB_ALGO, "query jostled out to " 344 "make space for a new one", 345 m->s.qinfo.qname, m->s.qinfo.qtype, 346 m->s.qinfo.qclass); 347 /* backup the query */ 348 if(qbuf) sldns_buffer_copy(mesh->qbuf_bak, qbuf); 349 /* notify supers */ 350 if(m->super_set.count > 0) { 351 verbose(VERB_ALGO, "notify supers of failure"); 352 m->s.return_msg = NULL; 353 m->s.return_rcode = LDNS_RCODE_SERVFAIL; 354 mesh_walk_supers(mesh, m); 355 } 356 mesh->stats_jostled ++; 357 mesh_state_delete(&m->s); 358 /* restore the query - note that the qinfo ptr to 359 * the querybuffer is then correct again. */ 360 if(qbuf) sldns_buffer_copy(qbuf, mesh->qbuf_bak); 361 return 1; 362 } 363 } 364 /* no space for new item */ 365 return 0; 366 } 367 368 struct dns_msg* 369 mesh_serve_expired_lookup(struct module_qstate* qstate, 370 struct query_info* lookup_qinfo) 371 { 372 hashvalue_type h; 373 struct lruhash_entry* e; 374 struct dns_msg* msg; 375 struct reply_info* data; 376 struct msgreply_entry* key; 377 time_t timenow = *qstate->env->now; 378 int must_validate = (!(qstate->query_flags&BIT_CD) 379 || qstate->env->cfg->ignore_cd) && qstate->env->need_to_validate; 380 /* Lookup cache */ 381 h = query_info_hash(lookup_qinfo, qstate->query_flags); 382 e = slabhash_lookup(qstate->env->msg_cache, h, lookup_qinfo, 0); 383 if(!e) return NULL; 384 385 key = (struct msgreply_entry*)e->key; 386 data = (struct reply_info*)e->data; 387 msg = tomsg(qstate->env, &key->key, data, qstate->region, timenow, 388 qstate->env->cfg->serve_expired, qstate->env->scratch); 389 if(!msg) 390 goto bail_out; 391 392 /* Check CNAME chain (if any) 393 * This is part of tomsg above; no need to check now. */ 394 395 /* Check security status of the cached answer. 396 * tomsg above has a subset of these checks, so we are leaving 397 * these as is. 398 * In case of bogus or revalidation we don't care to reply here. */ 399 if(must_validate && (msg->rep->security == sec_status_bogus || 400 msg->rep->security == sec_status_secure_sentinel_fail)) { 401 verbose(VERB_ALGO, "Serve expired: bogus answer found in cache"); 402 goto bail_out; 403 } else if(msg->rep->security == sec_status_unchecked && must_validate) { 404 verbose(VERB_ALGO, "Serve expired: unchecked entry needs " 405 "validation"); 406 goto bail_out; /* need to validate cache entry first */ 407 } else if(msg->rep->security == sec_status_secure && 408 !reply_all_rrsets_secure(msg->rep) && must_validate) { 409 verbose(VERB_ALGO, "Serve expired: secure entry" 410 " changed status"); 411 goto bail_out; /* rrset changed, re-verify */ 412 } 413 414 lock_rw_unlock(&e->lock); 415 return msg; 416 417 bail_out: 418 lock_rw_unlock(&e->lock); 419 return NULL; 420 } 421 422 423 /** Init the serve expired data structure */ 424 static int 425 mesh_serve_expired_init(struct mesh_state* mstate, int timeout) 426 { 427 struct timeval t; 428 429 /* Create serve_expired_data if not there yet */ 430 if(!mstate->s.serve_expired_data) { 431 mstate->s.serve_expired_data = (struct serve_expired_data*) 432 regional_alloc_zero( 433 mstate->s.region, sizeof(struct serve_expired_data)); 434 if(!mstate->s.serve_expired_data) 435 return 0; 436 } 437 438 /* Don't overwrite the function if already set */ 439 mstate->s.serve_expired_data->get_cached_answer = 440 mstate->s.serve_expired_data->get_cached_answer? 441 mstate->s.serve_expired_data->get_cached_answer: 442 &mesh_serve_expired_lookup; 443 444 /* In case this timer already popped, start it again */ 445 if(!mstate->s.serve_expired_data->timer) { 446 mstate->s.serve_expired_data->timer = comm_timer_create( 447 mstate->s.env->worker_base, mesh_serve_expired_callback, mstate); 448 if(!mstate->s.serve_expired_data->timer) 449 return 0; 450 #ifndef S_SPLINT_S 451 t.tv_sec = timeout/1000; 452 t.tv_usec = (timeout%1000)*1000; 453 #endif 454 comm_timer_set(mstate->s.serve_expired_data->timer, &t); 455 } 456 return 1; 457 } 458 459 void mesh_new_client(struct mesh_area* mesh, struct query_info* qinfo, 460 struct respip_client_info* cinfo, uint16_t qflags, 461 struct edns_data* edns, struct comm_reply* rep, uint16_t qid) 462 { 463 struct mesh_state* s = NULL; 464 int unique = unique_mesh_state(edns->opt_list_in, mesh->env); 465 int was_detached = 0; 466 int was_noreply = 0; 467 int added = 0; 468 int timeout = mesh->env->cfg->serve_expired? 469 mesh->env->cfg->serve_expired_client_timeout:0; 470 struct sldns_buffer* r_buffer = rep->c->buffer; 471 if(rep->c->tcp_req_info) { 472 r_buffer = rep->c->tcp_req_info->spool_buffer; 473 } 474 if(!unique) 475 s = mesh_area_find(mesh, cinfo, qinfo, qflags&(BIT_RD|BIT_CD), 0, 0); 476 /* does this create a new reply state? */ 477 if(!s || s->list_select == mesh_no_list) { 478 if(!mesh_make_new_space(mesh, rep->c->buffer)) { 479 verbose(VERB_ALGO, "Too many queries. dropping " 480 "incoming query."); 481 comm_point_drop_reply(rep); 482 mesh->stats_dropped++; 483 return; 484 } 485 /* for this new reply state, the reply address is free, 486 * so the limit of reply addresses does not stop reply states*/ 487 } else { 488 /* protect our memory usage from storing reply addresses */ 489 if(mesh->num_reply_addrs > mesh->max_reply_states*16) { 490 verbose(VERB_ALGO, "Too many requests queued. " 491 "dropping incoming query."); 492 comm_point_drop_reply(rep); 493 mesh->stats_dropped++; 494 return; 495 } 496 } 497 /* see if it already exists, if not, create one */ 498 if(!s) { 499 #ifdef UNBOUND_DEBUG 500 struct rbnode_type* n; 501 #endif 502 s = mesh_state_create(mesh->env, qinfo, cinfo, 503 qflags&(BIT_RD|BIT_CD), 0, 0); 504 if(!s) { 505 log_err("mesh_state_create: out of memory; SERVFAIL"); 506 if(!inplace_cb_reply_servfail_call(mesh->env, qinfo, NULL, NULL, 507 LDNS_RCODE_SERVFAIL, edns, rep, mesh->env->scratch, mesh->env->now_tv)) 508 edns->opt_list_inplace_cb_out = NULL; 509 error_encode(r_buffer, LDNS_RCODE_SERVFAIL, 510 qinfo, qid, qflags, edns); 511 comm_point_send_reply(rep); 512 return; 513 } 514 if(unique) 515 mesh_state_make_unique(s); 516 /* copy the edns options we got from the front */ 517 if(edns->opt_list_in) { 518 s->s.edns_opts_front_in = edns_opt_copy_region(edns->opt_list_in, 519 s->s.region); 520 if(!s->s.edns_opts_front_in) { 521 log_err("mesh_state_create: out of memory; SERVFAIL"); 522 if(!inplace_cb_reply_servfail_call(mesh->env, qinfo, NULL, 523 NULL, LDNS_RCODE_SERVFAIL, edns, rep, mesh->env->scratch, mesh->env->now_tv)) 524 edns->opt_list_inplace_cb_out = NULL; 525 error_encode(r_buffer, LDNS_RCODE_SERVFAIL, 526 qinfo, qid, qflags, edns); 527 comm_point_send_reply(rep); 528 return; 529 } 530 } 531 532 #ifdef UNBOUND_DEBUG 533 n = 534 #else 535 (void) 536 #endif 537 rbtree_insert(&mesh->all, &s->node); 538 log_assert(n != NULL); 539 /* set detached (it is now) */ 540 mesh->num_detached_states++; 541 added = 1; 542 } 543 if(!s->reply_list && !s->cb_list) { 544 was_noreply = 1; 545 if(s->super_set.count == 0) { 546 was_detached = 1; 547 } 548 } 549 /* add reply to s */ 550 if(!mesh_state_add_reply(s, edns, rep, qid, qflags, qinfo)) { 551 log_err("mesh_new_client: out of memory; SERVFAIL"); 552 goto servfail_mem; 553 } 554 if(rep->c->tcp_req_info) { 555 if(!tcp_req_info_add_meshstate(rep->c->tcp_req_info, mesh, s)) { 556 log_err("mesh_new_client: out of memory add tcpreqinfo"); 557 goto servfail_mem; 558 } 559 } 560 if(rep->c->use_h2) { 561 http2_stream_add_meshstate(rep->c->h2_stream, mesh, s); 562 } 563 /* add serve expired timer if required and not already there */ 564 if(timeout && !mesh_serve_expired_init(s, timeout)) { 565 log_err("mesh_new_client: out of memory initializing serve expired"); 566 goto servfail_mem; 567 } 568 /* update statistics */ 569 if(was_detached) { 570 log_assert(mesh->num_detached_states > 0); 571 mesh->num_detached_states--; 572 } 573 if(was_noreply) { 574 mesh->num_reply_states ++; 575 } 576 mesh->num_reply_addrs++; 577 if(s->list_select == mesh_no_list) { 578 /* move to either the forever or the jostle_list */ 579 if(mesh->num_forever_states < mesh->max_forever_states) { 580 mesh->num_forever_states ++; 581 mesh_list_insert(s, &mesh->forever_first, 582 &mesh->forever_last); 583 s->list_select = mesh_forever_list; 584 } else { 585 mesh_list_insert(s, &mesh->jostle_first, 586 &mesh->jostle_last); 587 s->list_select = mesh_jostle_list; 588 } 589 } 590 if(added) 591 mesh_run(mesh, s, module_event_new, NULL); 592 return; 593 594 servfail_mem: 595 if(!inplace_cb_reply_servfail_call(mesh->env, qinfo, &s->s, 596 NULL, LDNS_RCODE_SERVFAIL, edns, rep, mesh->env->scratch, mesh->env->now_tv)) 597 edns->opt_list_inplace_cb_out = NULL; 598 error_encode(r_buffer, LDNS_RCODE_SERVFAIL, 599 qinfo, qid, qflags, edns); 600 comm_point_send_reply(rep); 601 if(added) 602 mesh_state_delete(&s->s); 603 return; 604 } 605 606 int 607 mesh_new_callback(struct mesh_area* mesh, struct query_info* qinfo, 608 uint16_t qflags, struct edns_data* edns, sldns_buffer* buf, 609 uint16_t qid, mesh_cb_func_type cb, void* cb_arg) 610 { 611 struct mesh_state* s = NULL; 612 int unique = unique_mesh_state(edns->opt_list_in, mesh->env); 613 int timeout = mesh->env->cfg->serve_expired? 614 mesh->env->cfg->serve_expired_client_timeout:0; 615 int was_detached = 0; 616 int was_noreply = 0; 617 int added = 0; 618 if(!unique) 619 s = mesh_area_find(mesh, NULL, qinfo, qflags&(BIT_RD|BIT_CD), 0, 0); 620 621 /* there are no limits on the number of callbacks */ 622 623 /* see if it already exists, if not, create one */ 624 if(!s) { 625 #ifdef UNBOUND_DEBUG 626 struct rbnode_type* n; 627 #endif 628 s = mesh_state_create(mesh->env, qinfo, NULL, 629 qflags&(BIT_RD|BIT_CD), 0, 0); 630 if(!s) { 631 return 0; 632 } 633 if(unique) 634 mesh_state_make_unique(s); 635 if(edns->opt_list_in) { 636 s->s.edns_opts_front_in = edns_opt_copy_region(edns->opt_list_in, 637 s->s.region); 638 if(!s->s.edns_opts_front_in) { 639 return 0; 640 } 641 } 642 #ifdef UNBOUND_DEBUG 643 n = 644 #else 645 (void) 646 #endif 647 rbtree_insert(&mesh->all, &s->node); 648 log_assert(n != NULL); 649 /* set detached (it is now) */ 650 mesh->num_detached_states++; 651 added = 1; 652 } 653 if(!s->reply_list && !s->cb_list) { 654 was_noreply = 1; 655 if(s->super_set.count == 0) { 656 was_detached = 1; 657 } 658 } 659 /* add reply to s */ 660 if(!mesh_state_add_cb(s, edns, buf, cb, cb_arg, qid, qflags)) { 661 if(added) 662 mesh_state_delete(&s->s); 663 return 0; 664 } 665 /* add serve expired timer if not already there */ 666 if(timeout && !mesh_serve_expired_init(s, timeout)) { 667 return 0; 668 } 669 /* update statistics */ 670 if(was_detached) { 671 log_assert(mesh->num_detached_states > 0); 672 mesh->num_detached_states--; 673 } 674 if(was_noreply) { 675 mesh->num_reply_states ++; 676 } 677 mesh->num_reply_addrs++; 678 if(added) 679 mesh_run(mesh, s, module_event_new, NULL); 680 return 1; 681 } 682 683 /* Internal backend routine of mesh_new_prefetch(). It takes one additional 684 * parameter, 'run', which controls whether to run the prefetch state 685 * immediately. When this function is called internally 'run' could be 686 * 0 (false), in which case the new state is only made runnable so it 687 * will not be run recursively on top of the current state. */ 688 static void mesh_schedule_prefetch(struct mesh_area* mesh, 689 struct query_info* qinfo, uint16_t qflags, time_t leeway, int run) 690 { 691 struct mesh_state* s = mesh_area_find(mesh, NULL, qinfo, 692 qflags&(BIT_RD|BIT_CD), 0, 0); 693 #ifdef UNBOUND_DEBUG 694 struct rbnode_type* n; 695 #endif 696 /* already exists, and for a different purpose perhaps. 697 * if mesh_no_list, keep it that way. */ 698 if(s) { 699 /* make it ignore the cache from now on */ 700 if(!s->s.blacklist) 701 sock_list_insert(&s->s.blacklist, NULL, 0, s->s.region); 702 if(s->s.prefetch_leeway < leeway) 703 s->s.prefetch_leeway = leeway; 704 return; 705 } 706 if(!mesh_make_new_space(mesh, NULL)) { 707 verbose(VERB_ALGO, "Too many queries. dropped prefetch."); 708 mesh->stats_dropped ++; 709 return; 710 } 711 712 s = mesh_state_create(mesh->env, qinfo, NULL, 713 qflags&(BIT_RD|BIT_CD), 0, 0); 714 if(!s) { 715 log_err("prefetch mesh_state_create: out of memory"); 716 return; 717 } 718 #ifdef UNBOUND_DEBUG 719 n = 720 #else 721 (void) 722 #endif 723 rbtree_insert(&mesh->all, &s->node); 724 log_assert(n != NULL); 725 /* set detached (it is now) */ 726 mesh->num_detached_states++; 727 /* make it ignore the cache */ 728 sock_list_insert(&s->s.blacklist, NULL, 0, s->s.region); 729 s->s.prefetch_leeway = leeway; 730 731 if(s->list_select == mesh_no_list) { 732 /* move to either the forever or the jostle_list */ 733 if(mesh->num_forever_states < mesh->max_forever_states) { 734 mesh->num_forever_states ++; 735 mesh_list_insert(s, &mesh->forever_first, 736 &mesh->forever_last); 737 s->list_select = mesh_forever_list; 738 } else { 739 mesh_list_insert(s, &mesh->jostle_first, 740 &mesh->jostle_last); 741 s->list_select = mesh_jostle_list; 742 } 743 } 744 745 if(!run) { 746 #ifdef UNBOUND_DEBUG 747 n = 748 #else 749 (void) 750 #endif 751 rbtree_insert(&mesh->run, &s->run_node); 752 log_assert(n != NULL); 753 return; 754 } 755 756 mesh_run(mesh, s, module_event_new, NULL); 757 } 758 759 void mesh_new_prefetch(struct mesh_area* mesh, struct query_info* qinfo, 760 uint16_t qflags, time_t leeway) 761 { 762 mesh_schedule_prefetch(mesh, qinfo, qflags, leeway, 1); 763 } 764 765 void mesh_report_reply(struct mesh_area* mesh, struct outbound_entry* e, 766 struct comm_reply* reply, int what) 767 { 768 enum module_ev event = module_event_reply; 769 e->qstate->reply = reply; 770 if(what != NETEVENT_NOERROR) { 771 event = module_event_noreply; 772 if(what == NETEVENT_CAPSFAIL) 773 event = module_event_capsfail; 774 } 775 mesh_run(mesh, e->qstate->mesh_info, event, e); 776 } 777 778 struct mesh_state* 779 mesh_state_create(struct module_env* env, struct query_info* qinfo, 780 struct respip_client_info* cinfo, uint16_t qflags, int prime, 781 int valrec) 782 { 783 struct regional* region = alloc_reg_obtain(env->alloc); 784 struct mesh_state* mstate; 785 int i; 786 if(!region) 787 return NULL; 788 mstate = (struct mesh_state*)regional_alloc(region, 789 sizeof(struct mesh_state)); 790 if(!mstate) { 791 alloc_reg_release(env->alloc, region); 792 return NULL; 793 } 794 memset(mstate, 0, sizeof(*mstate)); 795 mstate->node = *RBTREE_NULL; 796 mstate->run_node = *RBTREE_NULL; 797 mstate->node.key = mstate; 798 mstate->run_node.key = mstate; 799 mstate->reply_list = NULL; 800 mstate->list_select = mesh_no_list; 801 mstate->replies_sent = 0; 802 rbtree_init(&mstate->super_set, &mesh_state_ref_compare); 803 rbtree_init(&mstate->sub_set, &mesh_state_ref_compare); 804 mstate->num_activated = 0; 805 mstate->unique = NULL; 806 /* init module qstate */ 807 mstate->s.qinfo.qtype = qinfo->qtype; 808 mstate->s.qinfo.qclass = qinfo->qclass; 809 mstate->s.qinfo.local_alias = NULL; 810 mstate->s.qinfo.qname_len = qinfo->qname_len; 811 mstate->s.qinfo.qname = regional_alloc_init(region, qinfo->qname, 812 qinfo->qname_len); 813 if(!mstate->s.qinfo.qname) { 814 alloc_reg_release(env->alloc, region); 815 return NULL; 816 } 817 if(cinfo) { 818 mstate->s.client_info = regional_alloc_init(region, cinfo, 819 sizeof(*cinfo)); 820 if(!mstate->s.client_info) { 821 alloc_reg_release(env->alloc, region); 822 return NULL; 823 } 824 } 825 /* remove all weird bits from qflags */ 826 mstate->s.query_flags = (qflags & (BIT_RD|BIT_CD)); 827 mstate->s.is_priming = prime; 828 mstate->s.is_valrec = valrec; 829 mstate->s.reply = NULL; 830 mstate->s.region = region; 831 mstate->s.curmod = 0; 832 mstate->s.return_msg = 0; 833 mstate->s.return_rcode = LDNS_RCODE_NOERROR; 834 mstate->s.env = env; 835 mstate->s.mesh_info = mstate; 836 mstate->s.prefetch_leeway = 0; 837 mstate->s.serve_expired_data = NULL; 838 mstate->s.no_cache_lookup = 0; 839 mstate->s.no_cache_store = 0; 840 mstate->s.need_refetch = 0; 841 mstate->s.was_ratelimited = 0; 842 843 /* init modules */ 844 for(i=0; i<env->mesh->mods.num; i++) { 845 mstate->s.minfo[i] = NULL; 846 mstate->s.ext_state[i] = module_state_initial; 847 } 848 /* init edns option lists */ 849 mstate->s.edns_opts_front_in = NULL; 850 mstate->s.edns_opts_back_out = NULL; 851 mstate->s.edns_opts_back_in = NULL; 852 mstate->s.edns_opts_front_out = NULL; 853 854 return mstate; 855 } 856 857 int 858 mesh_state_is_unique(struct mesh_state* mstate) 859 { 860 return mstate->unique != NULL; 861 } 862 863 void 864 mesh_state_make_unique(struct mesh_state* mstate) 865 { 866 mstate->unique = mstate; 867 } 868 869 void 870 mesh_state_cleanup(struct mesh_state* mstate) 871 { 872 struct mesh_area* mesh; 873 int i; 874 if(!mstate) 875 return; 876 mesh = mstate->s.env->mesh; 877 /* Stop and delete the serve expired timer */ 878 if(mstate->s.serve_expired_data && mstate->s.serve_expired_data->timer) { 879 comm_timer_delete(mstate->s.serve_expired_data->timer); 880 mstate->s.serve_expired_data->timer = NULL; 881 } 882 /* drop unsent replies */ 883 if(!mstate->replies_sent) { 884 struct mesh_reply* rep = mstate->reply_list; 885 struct mesh_cb* cb; 886 /* in tcp_req_info, the mstates linked are removed, but 887 * the reply_list is now NULL, so the remove-from-empty-list 888 * takes no time and also it does not do the mesh accounting */ 889 mstate->reply_list = NULL; 890 for(; rep; rep=rep->next) { 891 comm_point_drop_reply(&rep->query_reply); 892 log_assert(mesh->num_reply_addrs > 0); 893 mesh->num_reply_addrs--; 894 } 895 while((cb = mstate->cb_list)!=NULL) { 896 mstate->cb_list = cb->next; 897 fptr_ok(fptr_whitelist_mesh_cb(cb->cb)); 898 (*cb->cb)(cb->cb_arg, LDNS_RCODE_SERVFAIL, NULL, 899 sec_status_unchecked, NULL, 0); 900 log_assert(mesh->num_reply_addrs > 0); 901 mesh->num_reply_addrs--; 902 } 903 } 904 905 /* de-init modules */ 906 for(i=0; i<mesh->mods.num; i++) { 907 fptr_ok(fptr_whitelist_mod_clear(mesh->mods.mod[i]->clear)); 908 (*mesh->mods.mod[i]->clear)(&mstate->s, i); 909 mstate->s.minfo[i] = NULL; 910 mstate->s.ext_state[i] = module_finished; 911 } 912 alloc_reg_release(mstate->s.env->alloc, mstate->s.region); 913 } 914 915 void 916 mesh_state_delete(struct module_qstate* qstate) 917 { 918 struct mesh_area* mesh; 919 struct mesh_state_ref* super, ref; 920 struct mesh_state* mstate; 921 if(!qstate) 922 return; 923 mstate = qstate->mesh_info; 924 mesh = mstate->s.env->mesh; 925 mesh_detach_subs(&mstate->s); 926 if(mstate->list_select == mesh_forever_list) { 927 mesh->num_forever_states --; 928 mesh_list_remove(mstate, &mesh->forever_first, 929 &mesh->forever_last); 930 } else if(mstate->list_select == mesh_jostle_list) { 931 mesh_list_remove(mstate, &mesh->jostle_first, 932 &mesh->jostle_last); 933 } 934 if(!mstate->reply_list && !mstate->cb_list 935 && mstate->super_set.count == 0) { 936 log_assert(mesh->num_detached_states > 0); 937 mesh->num_detached_states--; 938 } 939 if(mstate->reply_list || mstate->cb_list) { 940 log_assert(mesh->num_reply_states > 0); 941 mesh->num_reply_states--; 942 } 943 ref.node.key = &ref; 944 ref.s = mstate; 945 RBTREE_FOR(super, struct mesh_state_ref*, &mstate->super_set) { 946 (void)rbtree_delete(&super->s->sub_set, &ref); 947 } 948 (void)rbtree_delete(&mesh->run, mstate); 949 (void)rbtree_delete(&mesh->all, mstate); 950 mesh_state_cleanup(mstate); 951 } 952 953 /** helper recursive rbtree find routine */ 954 static int 955 find_in_subsub(struct mesh_state* m, struct mesh_state* tofind, size_t *c) 956 { 957 struct mesh_state_ref* r; 958 if((*c)++ > MESH_MAX_SUBSUB) 959 return 1; 960 RBTREE_FOR(r, struct mesh_state_ref*, &m->sub_set) { 961 if(r->s == tofind || find_in_subsub(r->s, tofind, c)) 962 return 1; 963 } 964 return 0; 965 } 966 967 /** find cycle for already looked up mesh_state */ 968 static int 969 mesh_detect_cycle_found(struct module_qstate* qstate, struct mesh_state* dep_m) 970 { 971 struct mesh_state* cyc_m = qstate->mesh_info; 972 size_t counter = 0; 973 if(!dep_m) 974 return 0; 975 if(dep_m == cyc_m || find_in_subsub(dep_m, cyc_m, &counter)) { 976 if(counter > MESH_MAX_SUBSUB) 977 return 2; 978 return 1; 979 } 980 return 0; 981 } 982 983 void mesh_detach_subs(struct module_qstate* qstate) 984 { 985 struct mesh_area* mesh = qstate->env->mesh; 986 struct mesh_state_ref* ref, lookup; 987 #ifdef UNBOUND_DEBUG 988 struct rbnode_type* n; 989 #endif 990 lookup.node.key = &lookup; 991 lookup.s = qstate->mesh_info; 992 RBTREE_FOR(ref, struct mesh_state_ref*, &qstate->mesh_info->sub_set) { 993 #ifdef UNBOUND_DEBUG 994 n = 995 #else 996 (void) 997 #endif 998 rbtree_delete(&ref->s->super_set, &lookup); 999 log_assert(n != NULL); /* must have been present */ 1000 if(!ref->s->reply_list && !ref->s->cb_list 1001 && ref->s->super_set.count == 0) { 1002 mesh->num_detached_states++; 1003 log_assert(mesh->num_detached_states + 1004 mesh->num_reply_states <= mesh->all.count); 1005 } 1006 } 1007 rbtree_init(&qstate->mesh_info->sub_set, &mesh_state_ref_compare); 1008 } 1009 1010 int mesh_add_sub(struct module_qstate* qstate, struct query_info* qinfo, 1011 uint16_t qflags, int prime, int valrec, struct module_qstate** newq, 1012 struct mesh_state** sub) 1013 { 1014 /* find it, if not, create it */ 1015 struct mesh_area* mesh = qstate->env->mesh; 1016 *sub = mesh_area_find(mesh, NULL, qinfo, qflags, 1017 prime, valrec); 1018 if(mesh_detect_cycle_found(qstate, *sub)) { 1019 verbose(VERB_ALGO, "attach failed, cycle detected"); 1020 return 0; 1021 } 1022 if(!*sub) { 1023 #ifdef UNBOUND_DEBUG 1024 struct rbnode_type* n; 1025 #endif 1026 /* create a new one */ 1027 *sub = mesh_state_create(qstate->env, qinfo, NULL, qflags, prime, 1028 valrec); 1029 if(!*sub) { 1030 log_err("mesh_attach_sub: out of memory"); 1031 return 0; 1032 } 1033 #ifdef UNBOUND_DEBUG 1034 n = 1035 #else 1036 (void) 1037 #endif 1038 rbtree_insert(&mesh->all, &(*sub)->node); 1039 log_assert(n != NULL); 1040 /* set detached (it is now) */ 1041 mesh->num_detached_states++; 1042 /* set new query state to run */ 1043 #ifdef UNBOUND_DEBUG 1044 n = 1045 #else 1046 (void) 1047 #endif 1048 rbtree_insert(&mesh->run, &(*sub)->run_node); 1049 log_assert(n != NULL); 1050 *newq = &(*sub)->s; 1051 } else 1052 *newq = NULL; 1053 return 1; 1054 } 1055 1056 int mesh_attach_sub(struct module_qstate* qstate, struct query_info* qinfo, 1057 uint16_t qflags, int prime, int valrec, struct module_qstate** newq) 1058 { 1059 struct mesh_area* mesh = qstate->env->mesh; 1060 struct mesh_state* sub = NULL; 1061 int was_detached; 1062 if(!mesh_add_sub(qstate, qinfo, qflags, prime, valrec, newq, &sub)) 1063 return 0; 1064 was_detached = (sub->super_set.count == 0); 1065 if(!mesh_state_attachment(qstate->mesh_info, sub)) 1066 return 0; 1067 /* if it was a duplicate attachment, the count was not zero before */ 1068 if(!sub->reply_list && !sub->cb_list && was_detached && 1069 sub->super_set.count == 1) { 1070 /* it used to be detached, before this one got added */ 1071 log_assert(mesh->num_detached_states > 0); 1072 mesh->num_detached_states--; 1073 } 1074 /* *newq will be run when inited after the current module stops */ 1075 return 1; 1076 } 1077 1078 int mesh_state_attachment(struct mesh_state* super, struct mesh_state* sub) 1079 { 1080 #ifdef UNBOUND_DEBUG 1081 struct rbnode_type* n; 1082 #endif 1083 struct mesh_state_ref* subref; /* points to sub, inserted in super */ 1084 struct mesh_state_ref* superref; /* points to super, inserted in sub */ 1085 if( !(subref = regional_alloc(super->s.region, 1086 sizeof(struct mesh_state_ref))) || 1087 !(superref = regional_alloc(sub->s.region, 1088 sizeof(struct mesh_state_ref))) ) { 1089 log_err("mesh_state_attachment: out of memory"); 1090 return 0; 1091 } 1092 superref->node.key = superref; 1093 superref->s = super; 1094 subref->node.key = subref; 1095 subref->s = sub; 1096 if(!rbtree_insert(&sub->super_set, &superref->node)) { 1097 /* this should not happen, iterator and validator do not 1098 * attach subqueries that are identical. */ 1099 /* already attached, we are done, nothing todo. 1100 * since superref and subref already allocated in region, 1101 * we cannot free them */ 1102 return 1; 1103 } 1104 #ifdef UNBOUND_DEBUG 1105 n = 1106 #else 1107 (void) 1108 #endif 1109 rbtree_insert(&super->sub_set, &subref->node); 1110 log_assert(n != NULL); /* we checked above if statement, the reverse 1111 administration should not fail now, unless they are out of sync */ 1112 return 1; 1113 } 1114 1115 /** 1116 * callback results to mesh cb entry 1117 * @param m: mesh state to send it for. 1118 * @param rcode: if not 0, error code. 1119 * @param rep: reply to send (or NULL if rcode is set). 1120 * @param r: callback entry 1121 * @param start_time: the time to pass to callback functions, it is 0 or 1122 * a value from one of the packets if the mesh state had packets. 1123 */ 1124 static void 1125 mesh_do_callback(struct mesh_state* m, int rcode, struct reply_info* rep, 1126 struct mesh_cb* r, struct timeval* start_time) 1127 { 1128 int secure; 1129 char* reason = NULL; 1130 int was_ratelimited = m->s.was_ratelimited; 1131 /* bogus messages are not made into servfail, sec_status passed 1132 * to the callback function */ 1133 if(rep && rep->security == sec_status_secure) 1134 secure = 1; 1135 else secure = 0; 1136 if(!rep && rcode == LDNS_RCODE_NOERROR) 1137 rcode = LDNS_RCODE_SERVFAIL; 1138 if(!rcode && (rep->security == sec_status_bogus || 1139 rep->security == sec_status_secure_sentinel_fail)) { 1140 if(!(reason = errinf_to_str_bogus(&m->s))) 1141 rcode = LDNS_RCODE_SERVFAIL; 1142 } 1143 /* send the reply */ 1144 if(rcode) { 1145 if(rcode == LDNS_RCODE_SERVFAIL) { 1146 if(!inplace_cb_reply_servfail_call(m->s.env, &m->s.qinfo, &m->s, 1147 rep, rcode, &r->edns, NULL, m->s.region, start_time)) 1148 r->edns.opt_list_inplace_cb_out = NULL; 1149 } else { 1150 if(!inplace_cb_reply_call(m->s.env, &m->s.qinfo, &m->s, rep, rcode, 1151 &r->edns, NULL, m->s.region, start_time)) 1152 r->edns.opt_list_inplace_cb_out = NULL; 1153 } 1154 fptr_ok(fptr_whitelist_mesh_cb(r->cb)); 1155 (*r->cb)(r->cb_arg, rcode, r->buf, sec_status_unchecked, NULL, 1156 was_ratelimited); 1157 } else { 1158 size_t udp_size = r->edns.udp_size; 1159 sldns_buffer_clear(r->buf); 1160 r->edns.edns_version = EDNS_ADVERTISED_VERSION; 1161 r->edns.udp_size = EDNS_ADVERTISED_SIZE; 1162 r->edns.ext_rcode = 0; 1163 r->edns.bits &= EDNS_DO; 1164 1165 if(!inplace_cb_reply_call(m->s.env, &m->s.qinfo, &m->s, rep, 1166 LDNS_RCODE_NOERROR, &r->edns, NULL, m->s.region, start_time) || 1167 !reply_info_answer_encode(&m->s.qinfo, rep, r->qid, 1168 r->qflags, r->buf, 0, 1, 1169 m->s.env->scratch, udp_size, &r->edns, 1170 (int)(r->edns.bits & EDNS_DO), secure)) 1171 { 1172 fptr_ok(fptr_whitelist_mesh_cb(r->cb)); 1173 (*r->cb)(r->cb_arg, LDNS_RCODE_SERVFAIL, r->buf, 1174 sec_status_unchecked, NULL, 0); 1175 } else { 1176 fptr_ok(fptr_whitelist_mesh_cb(r->cb)); 1177 (*r->cb)(r->cb_arg, LDNS_RCODE_NOERROR, r->buf, 1178 rep->security, reason, was_ratelimited); 1179 } 1180 } 1181 free(reason); 1182 log_assert(m->s.env->mesh->num_reply_addrs > 0); 1183 m->s.env->mesh->num_reply_addrs--; 1184 } 1185 1186 static inline int 1187 mesh_is_rpz_respip_tcponly_action(struct mesh_state const* m) 1188 { 1189 struct respip_action_info const* respip_info = m->s.respip_action_info; 1190 return respip_info == NULL 1191 ? 0 1192 : (respip_info->rpz_used 1193 && !respip_info->rpz_disabled 1194 && respip_info->action == respip_truncate); 1195 } 1196 1197 static inline int 1198 mesh_is_udp(struct mesh_reply const* r) { 1199 return r->query_reply.c->type == comm_udp; 1200 } 1201 1202 /** 1203 * Send reply to mesh reply entry 1204 * @param m: mesh state to send it for. 1205 * @param rcode: if not 0, error code. 1206 * @param rep: reply to send (or NULL if rcode is set). 1207 * @param r: reply entry 1208 * @param r_buffer: buffer to use for reply entry. 1209 * @param prev: previous reply, already has its answer encoded in buffer. 1210 * @param prev_buffer: buffer for previous reply. 1211 */ 1212 static void 1213 mesh_send_reply(struct mesh_state* m, int rcode, struct reply_info* rep, 1214 struct mesh_reply* r, struct sldns_buffer* r_buffer, 1215 struct mesh_reply* prev, struct sldns_buffer* prev_buffer) 1216 { 1217 struct timeval end_time; 1218 struct timeval duration; 1219 int secure; 1220 /* briefly set the replylist to null in case the 1221 * meshsendreply calls tcpreqinfo sendreply that 1222 * comm_point_drops because of size, and then the 1223 * null stops the mesh state remove and thus 1224 * reply_list modification and accounting */ 1225 struct mesh_reply* rlist = m->reply_list; 1226 1227 /* rpz: apply actions */ 1228 rcode = mesh_is_udp(r) && mesh_is_rpz_respip_tcponly_action(m) 1229 ? (rcode|BIT_TC) : rcode; 1230 1231 /* examine security status */ 1232 if(m->s.env->need_to_validate && (!(r->qflags&BIT_CD) || 1233 m->s.env->cfg->ignore_cd) && rep && 1234 (rep->security <= sec_status_bogus || 1235 rep->security == sec_status_secure_sentinel_fail)) { 1236 rcode = LDNS_RCODE_SERVFAIL; 1237 if(m->s.env->cfg->stat_extended) 1238 m->s.env->mesh->ans_bogus++; 1239 } 1240 if(rep && rep->security == sec_status_secure) 1241 secure = 1; 1242 else secure = 0; 1243 if(!rep && rcode == LDNS_RCODE_NOERROR) 1244 rcode = LDNS_RCODE_SERVFAIL; 1245 if(r->query_reply.c->use_h2) { 1246 r->query_reply.c->h2_stream = r->h2_stream; 1247 /* Mesh reply won't exist for long anymore. Make it impossible 1248 * for HTTP/2 stream to refer to mesh state, in case 1249 * connection gets cleanup before HTTP/2 stream close. */ 1250 r->h2_stream->mesh_state = NULL; 1251 } 1252 /* send the reply */ 1253 /* We don't reuse the encoded answer if: 1254 * - either the previous or current response has a local alias. We could 1255 * compare the alias records and still reuse the previous answer if they 1256 * are the same, but that would be complicated and error prone for the 1257 * relatively minor case. So we err on the side of safety. 1258 * - there are registered callback functions for the given rcode, as these 1259 * need to be called for each reply. */ 1260 if(((rcode != LDNS_RCODE_SERVFAIL && 1261 !m->s.env->inplace_cb_lists[inplace_cb_reply]) || 1262 (rcode == LDNS_RCODE_SERVFAIL && 1263 !m->s.env->inplace_cb_lists[inplace_cb_reply_servfail])) && 1264 prev && prev_buffer && prev->qflags == r->qflags && 1265 !prev->local_alias && !r->local_alias && 1266 prev->edns.edns_present == r->edns.edns_present && 1267 prev->edns.bits == r->edns.bits && 1268 prev->edns.udp_size == r->edns.udp_size && 1269 edns_opt_list_compare(prev->edns.opt_list_out, r->edns.opt_list_out) == 0 && 1270 edns_opt_list_compare(prev->edns.opt_list_inplace_cb_out, r->edns.opt_list_inplace_cb_out) == 0 1271 ) { 1272 /* if the previous reply is identical to this one, fix ID */ 1273 if(prev_buffer != r_buffer) 1274 sldns_buffer_copy(r_buffer, prev_buffer); 1275 sldns_buffer_write_at(r_buffer, 0, &r->qid, sizeof(uint16_t)); 1276 sldns_buffer_write_at(r_buffer, 12, r->qname, 1277 m->s.qinfo.qname_len); 1278 m->reply_list = NULL; 1279 comm_point_send_reply(&r->query_reply); 1280 m->reply_list = rlist; 1281 } else if(rcode) { 1282 m->s.qinfo.qname = r->qname; 1283 m->s.qinfo.local_alias = r->local_alias; 1284 if(rcode == LDNS_RCODE_SERVFAIL) { 1285 if(!inplace_cb_reply_servfail_call(m->s.env, &m->s.qinfo, &m->s, 1286 rep, rcode, &r->edns, &r->query_reply, m->s.region, &r->start_time)) 1287 r->edns.opt_list_inplace_cb_out = NULL; 1288 } else { 1289 if(!inplace_cb_reply_call(m->s.env, &m->s.qinfo, &m->s, rep, rcode, 1290 &r->edns, &r->query_reply, m->s.region, &r->start_time)) 1291 r->edns.opt_list_inplace_cb_out = NULL; 1292 } 1293 error_encode(r_buffer, rcode, &m->s.qinfo, r->qid, 1294 r->qflags, &r->edns); 1295 m->reply_list = NULL; 1296 comm_point_send_reply(&r->query_reply); 1297 m->reply_list = rlist; 1298 } else { 1299 size_t udp_size = r->edns.udp_size; 1300 r->edns.edns_version = EDNS_ADVERTISED_VERSION; 1301 r->edns.udp_size = EDNS_ADVERTISED_SIZE; 1302 r->edns.ext_rcode = 0; 1303 r->edns.bits &= EDNS_DO; 1304 m->s.qinfo.qname = r->qname; 1305 m->s.qinfo.local_alias = r->local_alias; 1306 if(!inplace_cb_reply_call(m->s.env, &m->s.qinfo, &m->s, rep, 1307 LDNS_RCODE_NOERROR, &r->edns, &r->query_reply, m->s.region, &r->start_time) || 1308 !reply_info_answer_encode(&m->s.qinfo, rep, r->qid, 1309 r->qflags, r_buffer, 0, 1, m->s.env->scratch, 1310 udp_size, &r->edns, (int)(r->edns.bits & EDNS_DO), 1311 secure)) 1312 { 1313 if(!inplace_cb_reply_servfail_call(m->s.env, &m->s.qinfo, &m->s, 1314 rep, LDNS_RCODE_SERVFAIL, &r->edns, &r->query_reply, m->s.region, &r->start_time)) 1315 r->edns.opt_list_inplace_cb_out = NULL; 1316 error_encode(r_buffer, LDNS_RCODE_SERVFAIL, 1317 &m->s.qinfo, r->qid, r->qflags, &r->edns); 1318 } 1319 m->reply_list = NULL; 1320 comm_point_send_reply(&r->query_reply); 1321 m->reply_list = rlist; 1322 } 1323 /* account */ 1324 log_assert(m->s.env->mesh->num_reply_addrs > 0); 1325 m->s.env->mesh->num_reply_addrs--; 1326 end_time = *m->s.env->now_tv; 1327 timeval_subtract(&duration, &end_time, &r->start_time); 1328 verbose(VERB_ALGO, "query took " ARG_LL "d.%6.6d sec", 1329 (long long)duration.tv_sec, (int)duration.tv_usec); 1330 m->s.env->mesh->replies_sent++; 1331 timeval_add(&m->s.env->mesh->replies_sum_wait, &duration); 1332 timehist_insert(m->s.env->mesh->histogram, &duration); 1333 if(m->s.env->cfg->stat_extended) { 1334 uint16_t rc = FLAGS_GET_RCODE(sldns_buffer_read_u16_at( 1335 r_buffer, 2)); 1336 if(secure) m->s.env->mesh->ans_secure++; 1337 m->s.env->mesh->ans_rcode[ rc ] ++; 1338 if(rc == 0 && LDNS_ANCOUNT(sldns_buffer_begin(r_buffer)) == 0) 1339 m->s.env->mesh->ans_nodata++; 1340 } 1341 /* Log reply sent */ 1342 if(m->s.env->cfg->log_replies) { 1343 log_reply_info(NO_VERBOSE, &m->s.qinfo, &r->query_reply.addr, 1344 r->query_reply.addrlen, duration, 0, r_buffer); 1345 } 1346 } 1347 1348 void mesh_query_done(struct mesh_state* mstate) 1349 { 1350 struct mesh_reply* r; 1351 struct mesh_reply* prev = NULL; 1352 struct sldns_buffer* prev_buffer = NULL; 1353 struct mesh_cb* c; 1354 struct reply_info* rep = (mstate->s.return_msg? 1355 mstate->s.return_msg->rep:NULL); 1356 struct timeval tv = {0, 0}; 1357 /* No need for the serve expired timer anymore; we are going to reply. */ 1358 if(mstate->s.serve_expired_data) { 1359 comm_timer_delete(mstate->s.serve_expired_data->timer); 1360 mstate->s.serve_expired_data->timer = NULL; 1361 } 1362 if(mstate->s.return_rcode == LDNS_RCODE_SERVFAIL || 1363 (rep && FLAGS_GET_RCODE(rep->flags) == LDNS_RCODE_SERVFAIL)) { 1364 /* we are SERVFAILing; check for expired answer here */ 1365 mesh_serve_expired_callback(mstate); 1366 if((mstate->reply_list || mstate->cb_list) 1367 && mstate->s.env->cfg->log_servfail 1368 && !mstate->s.env->cfg->val_log_squelch) { 1369 char* err = errinf_to_str_servfail(&mstate->s); 1370 if(err) 1371 log_err("%s", err); 1372 free(err); 1373 } 1374 } 1375 for(r = mstate->reply_list; r; r = r->next) { 1376 tv = r->start_time; 1377 1378 /* if a response-ip address block has been stored the 1379 * information should be logged for each client. */ 1380 if(mstate->s.respip_action_info && 1381 mstate->s.respip_action_info->addrinfo) { 1382 respip_inform_print(mstate->s.respip_action_info, 1383 r->qname, mstate->s.qinfo.qtype, 1384 mstate->s.qinfo.qclass, r->local_alias, 1385 &r->query_reply); 1386 if(mstate->s.env->cfg->stat_extended && 1387 mstate->s.respip_action_info->rpz_used) { 1388 if(mstate->s.respip_action_info->rpz_disabled) 1389 mstate->s.env->mesh->rpz_action[RPZ_DISABLED_ACTION]++; 1390 if(mstate->s.respip_action_info->rpz_cname_override) 1391 mstate->s.env->mesh->rpz_action[RPZ_CNAME_OVERRIDE_ACTION]++; 1392 else 1393 mstate->s.env->mesh->rpz_action[respip_action_to_rpz_action( 1394 mstate->s.respip_action_info->action)]++; 1395 } 1396 } 1397 1398 /* if this query is determined to be dropped during the 1399 * mesh processing, this is the point to take that action. */ 1400 if(mstate->s.is_drop) { 1401 /* briefly set the reply_list to NULL, so that the 1402 * tcp req info cleanup routine that calls the mesh 1403 * to deregister the meshstate for it is not done 1404 * because the list is NULL and also accounting is not 1405 * done there, but instead we do that here. */ 1406 struct mesh_reply* reply_list = mstate->reply_list; 1407 mstate->reply_list = NULL; 1408 comm_point_drop_reply(&r->query_reply); 1409 mstate->reply_list = reply_list; 1410 } else { 1411 struct sldns_buffer* r_buffer = r->query_reply.c->buffer; 1412 if(r->query_reply.c->tcp_req_info) { 1413 r_buffer = r->query_reply.c->tcp_req_info->spool_buffer; 1414 prev_buffer = NULL; 1415 } 1416 mesh_send_reply(mstate, mstate->s.return_rcode, rep, 1417 r, r_buffer, prev, prev_buffer); 1418 if(r->query_reply.c->tcp_req_info) { 1419 tcp_req_info_remove_mesh_state(r->query_reply.c->tcp_req_info, mstate); 1420 r_buffer = NULL; 1421 } 1422 prev = r; 1423 prev_buffer = r_buffer; 1424 } 1425 } 1426 if(mstate->reply_list) { 1427 mstate->reply_list = NULL; 1428 if(!mstate->reply_list && !mstate->cb_list) { 1429 /* was a reply state, not anymore */ 1430 log_assert(mstate->s.env->mesh->num_reply_states > 0); 1431 mstate->s.env->mesh->num_reply_states--; 1432 } 1433 if(!mstate->reply_list && !mstate->cb_list && 1434 mstate->super_set.count == 0) 1435 mstate->s.env->mesh->num_detached_states++; 1436 } 1437 mstate->replies_sent = 1; 1438 while((c = mstate->cb_list) != NULL) { 1439 /* take this cb off the list; so that the list can be 1440 * changed, eg. by adds from the callback routine */ 1441 if(!mstate->reply_list && mstate->cb_list && !c->next) { 1442 /* was a reply state, not anymore */ 1443 log_assert(mstate->s.env->mesh->num_reply_states > 0); 1444 mstate->s.env->mesh->num_reply_states--; 1445 } 1446 mstate->cb_list = c->next; 1447 if(!mstate->reply_list && !mstate->cb_list && 1448 mstate->super_set.count == 0) 1449 mstate->s.env->mesh->num_detached_states++; 1450 mesh_do_callback(mstate, mstate->s.return_rcode, rep, c, &tv); 1451 } 1452 } 1453 1454 void mesh_walk_supers(struct mesh_area* mesh, struct mesh_state* mstate) 1455 { 1456 struct mesh_state_ref* ref; 1457 RBTREE_FOR(ref, struct mesh_state_ref*, &mstate->super_set) 1458 { 1459 /* make super runnable */ 1460 (void)rbtree_insert(&mesh->run, &ref->s->run_node); 1461 /* callback the function to inform super of result */ 1462 fptr_ok(fptr_whitelist_mod_inform_super( 1463 mesh->mods.mod[ref->s->s.curmod]->inform_super)); 1464 (*mesh->mods.mod[ref->s->s.curmod]->inform_super)(&mstate->s, 1465 ref->s->s.curmod, &ref->s->s); 1466 /* copy state that is always relevant to super */ 1467 copy_state_to_super(&mstate->s, ref->s->s.curmod, &ref->s->s); 1468 } 1469 } 1470 1471 struct mesh_state* mesh_area_find(struct mesh_area* mesh, 1472 struct respip_client_info* cinfo, struct query_info* qinfo, 1473 uint16_t qflags, int prime, int valrec) 1474 { 1475 struct mesh_state key; 1476 struct mesh_state* result; 1477 1478 key.node.key = &key; 1479 key.s.is_priming = prime; 1480 key.s.is_valrec = valrec; 1481 key.s.qinfo = *qinfo; 1482 key.s.query_flags = qflags; 1483 /* We are searching for a similar mesh state when we DO want to 1484 * aggregate the state. Thus unique is set to NULL. (default when we 1485 * desire aggregation).*/ 1486 key.unique = NULL; 1487 key.s.client_info = cinfo; 1488 1489 result = (struct mesh_state*)rbtree_search(&mesh->all, &key); 1490 return result; 1491 } 1492 1493 int mesh_state_add_cb(struct mesh_state* s, struct edns_data* edns, 1494 sldns_buffer* buf, mesh_cb_func_type cb, void* cb_arg, 1495 uint16_t qid, uint16_t qflags) 1496 { 1497 struct mesh_cb* r = regional_alloc(s->s.region, 1498 sizeof(struct mesh_cb)); 1499 if(!r) 1500 return 0; 1501 r->buf = buf; 1502 log_assert(fptr_whitelist_mesh_cb(cb)); /* early failure ifmissing*/ 1503 r->cb = cb; 1504 r->cb_arg = cb_arg; 1505 r->edns = *edns; 1506 if(edns->opt_list_in && !(r->edns.opt_list_in = 1507 edns_opt_copy_region(edns->opt_list_in, s->s.region))) 1508 return 0; 1509 if(edns->opt_list_out && !(r->edns.opt_list_out = 1510 edns_opt_copy_region(edns->opt_list_out, s->s.region))) 1511 return 0; 1512 if(edns->opt_list_inplace_cb_out && !(r->edns.opt_list_inplace_cb_out = 1513 edns_opt_copy_region(edns->opt_list_inplace_cb_out, s->s.region))) 1514 return 0; 1515 r->qid = qid; 1516 r->qflags = qflags; 1517 r->next = s->cb_list; 1518 s->cb_list = r; 1519 return 1; 1520 1521 } 1522 1523 int mesh_state_add_reply(struct mesh_state* s, struct edns_data* edns, 1524 struct comm_reply* rep, uint16_t qid, uint16_t qflags, 1525 const struct query_info* qinfo) 1526 { 1527 struct mesh_reply* r = regional_alloc(s->s.region, 1528 sizeof(struct mesh_reply)); 1529 if(!r) 1530 return 0; 1531 r->query_reply = *rep; 1532 r->edns = *edns; 1533 if(edns->opt_list_in && !(r->edns.opt_list_in = 1534 edns_opt_copy_region(edns->opt_list_in, s->s.region))) 1535 return 0; 1536 if(edns->opt_list_out && !(r->edns.opt_list_out = 1537 edns_opt_copy_region(edns->opt_list_out, s->s.region))) 1538 return 0; 1539 if(edns->opt_list_inplace_cb_out && !(r->edns.opt_list_inplace_cb_out = 1540 edns_opt_copy_region(edns->opt_list_inplace_cb_out, s->s.region))) 1541 return 0; 1542 r->qid = qid; 1543 r->qflags = qflags; 1544 r->start_time = *s->s.env->now_tv; 1545 r->next = s->reply_list; 1546 r->qname = regional_alloc_init(s->s.region, qinfo->qname, 1547 s->s.qinfo.qname_len); 1548 if(!r->qname) 1549 return 0; 1550 if(rep->c->use_h2) 1551 r->h2_stream = rep->c->h2_stream; 1552 1553 /* Data related to local alias stored in 'qinfo' (if any) is ephemeral 1554 * and can be different for different original queries (even if the 1555 * replaced query name is the same). So we need to make a deep copy 1556 * and store the copy for each reply info. */ 1557 if(qinfo->local_alias) { 1558 struct packed_rrset_data* d; 1559 struct packed_rrset_data* dsrc; 1560 r->local_alias = regional_alloc_zero(s->s.region, 1561 sizeof(*qinfo->local_alias)); 1562 if(!r->local_alias) 1563 return 0; 1564 r->local_alias->rrset = regional_alloc_init(s->s.region, 1565 qinfo->local_alias->rrset, 1566 sizeof(*qinfo->local_alias->rrset)); 1567 if(!r->local_alias->rrset) 1568 return 0; 1569 dsrc = qinfo->local_alias->rrset->entry.data; 1570 1571 /* In the current implementation, a local alias must be 1572 * a single CNAME RR (see worker_handle_request()). */ 1573 log_assert(!qinfo->local_alias->next && dsrc->count == 1 && 1574 qinfo->local_alias->rrset->rk.type == 1575 htons(LDNS_RR_TYPE_CNAME)); 1576 /* we should make a local copy for the owner name of 1577 * the RRset */ 1578 r->local_alias->rrset->rk.dname_len = 1579 qinfo->local_alias->rrset->rk.dname_len; 1580 r->local_alias->rrset->rk.dname = regional_alloc_init( 1581 s->s.region, qinfo->local_alias->rrset->rk.dname, 1582 qinfo->local_alias->rrset->rk.dname_len); 1583 if(!r->local_alias->rrset->rk.dname) 1584 return 0; 1585 1586 /* the rrset is not packed, like in the cache, but it is 1587 * individually allocated with an allocator from localzone. */ 1588 d = regional_alloc_zero(s->s.region, sizeof(*d)); 1589 if(!d) 1590 return 0; 1591 r->local_alias->rrset->entry.data = d; 1592 if(!rrset_insert_rr(s->s.region, d, dsrc->rr_data[0], 1593 dsrc->rr_len[0], dsrc->rr_ttl[0], "CNAME local alias")) 1594 return 0; 1595 } else 1596 r->local_alias = NULL; 1597 1598 s->reply_list = r; 1599 return 1; 1600 } 1601 1602 /* Extract the query info and flags from 'mstate' into '*qinfop' and '*qflags'. 1603 * Since this is only used for internal refetch of otherwise-expired answer, 1604 * we simply ignore the rare failure mode when memory allocation fails. */ 1605 static void 1606 mesh_copy_qinfo(struct mesh_state* mstate, struct query_info** qinfop, 1607 uint16_t* qflags) 1608 { 1609 struct regional* region = mstate->s.env->scratch; 1610 struct query_info* qinfo; 1611 1612 qinfo = regional_alloc_init(region, &mstate->s.qinfo, sizeof(*qinfo)); 1613 if(!qinfo) 1614 return; 1615 qinfo->qname = regional_alloc_init(region, qinfo->qname, 1616 qinfo->qname_len); 1617 if(!qinfo->qname) 1618 return; 1619 *qinfop = qinfo; 1620 *qflags = mstate->s.query_flags; 1621 } 1622 1623 /** 1624 * Continue processing the mesh state at another module. 1625 * Handles module to modules transfer of control. 1626 * Handles module finished. 1627 * @param mesh: the mesh area. 1628 * @param mstate: currently active mesh state. 1629 * Deleted if finished, calls _done and _supers to 1630 * send replies to clients and inform other mesh states. 1631 * This in turn may create additional runnable mesh states. 1632 * @param s: state at which the current module exited. 1633 * @param ev: the event sent to the module. 1634 * returned is the event to send to the next module. 1635 * @return true if continue processing at the new module. 1636 * false if not continued processing is needed. 1637 */ 1638 static int 1639 mesh_continue(struct mesh_area* mesh, struct mesh_state* mstate, 1640 enum module_ext_state s, enum module_ev* ev) 1641 { 1642 mstate->num_activated++; 1643 if(mstate->num_activated > MESH_MAX_ACTIVATION) { 1644 /* module is looping. Stop it. */ 1645 log_err("internal error: looping module (%s) stopped", 1646 mesh->mods.mod[mstate->s.curmod]->name); 1647 log_query_info(NO_VERBOSE, "pass error for qstate", 1648 &mstate->s.qinfo); 1649 s = module_error; 1650 } 1651 if(s == module_wait_module || s == module_restart_next) { 1652 /* start next module */ 1653 mstate->s.curmod++; 1654 if(mesh->mods.num == mstate->s.curmod) { 1655 log_err("Cannot pass to next module; at last module"); 1656 log_query_info(VERB_QUERY, "pass error for qstate", 1657 &mstate->s.qinfo); 1658 mstate->s.curmod--; 1659 return mesh_continue(mesh, mstate, module_error, ev); 1660 } 1661 if(s == module_restart_next) { 1662 int curmod = mstate->s.curmod; 1663 for(; mstate->s.curmod < mesh->mods.num; 1664 mstate->s.curmod++) { 1665 fptr_ok(fptr_whitelist_mod_clear( 1666 mesh->mods.mod[mstate->s.curmod]->clear)); 1667 (*mesh->mods.mod[mstate->s.curmod]->clear) 1668 (&mstate->s, mstate->s.curmod); 1669 mstate->s.minfo[mstate->s.curmod] = NULL; 1670 } 1671 mstate->s.curmod = curmod; 1672 } 1673 *ev = module_event_pass; 1674 return 1; 1675 } 1676 if(s == module_wait_subquery && mstate->sub_set.count == 0) { 1677 log_err("module cannot wait for subquery, subquery list empty"); 1678 log_query_info(VERB_QUERY, "pass error for qstate", 1679 &mstate->s.qinfo); 1680 s = module_error; 1681 } 1682 if(s == module_error && mstate->s.return_rcode == LDNS_RCODE_NOERROR) { 1683 /* error is bad, handle pass back up below */ 1684 mstate->s.return_rcode = LDNS_RCODE_SERVFAIL; 1685 } 1686 if(s == module_error) { 1687 mesh_query_done(mstate); 1688 mesh_walk_supers(mesh, mstate); 1689 mesh_state_delete(&mstate->s); 1690 return 0; 1691 } 1692 if(s == module_finished) { 1693 if(mstate->s.curmod == 0) { 1694 struct query_info* qinfo = NULL; 1695 uint16_t qflags; 1696 1697 mesh_query_done(mstate); 1698 mesh_walk_supers(mesh, mstate); 1699 1700 /* If the answer to the query needs to be refetched 1701 * from an external DNS server, we'll need to schedule 1702 * a prefetch after removing the current state, so 1703 * we need to make a copy of the query info here. */ 1704 if(mstate->s.need_refetch) 1705 mesh_copy_qinfo(mstate, &qinfo, &qflags); 1706 1707 mesh_state_delete(&mstate->s); 1708 if(qinfo) { 1709 mesh_schedule_prefetch(mesh, qinfo, qflags, 1710 0, 1); 1711 } 1712 return 0; 1713 } 1714 /* pass along the locus of control */ 1715 mstate->s.curmod --; 1716 *ev = module_event_moddone; 1717 return 1; 1718 } 1719 return 0; 1720 } 1721 1722 void mesh_run(struct mesh_area* mesh, struct mesh_state* mstate, 1723 enum module_ev ev, struct outbound_entry* e) 1724 { 1725 enum module_ext_state s; 1726 verbose(VERB_ALGO, "mesh_run: start"); 1727 while(mstate) { 1728 /* run the module */ 1729 fptr_ok(fptr_whitelist_mod_operate( 1730 mesh->mods.mod[mstate->s.curmod]->operate)); 1731 (*mesh->mods.mod[mstate->s.curmod]->operate) 1732 (&mstate->s, ev, mstate->s.curmod, e); 1733 1734 /* examine results */ 1735 mstate->s.reply = NULL; 1736 regional_free_all(mstate->s.env->scratch); 1737 s = mstate->s.ext_state[mstate->s.curmod]; 1738 verbose(VERB_ALGO, "mesh_run: %s module exit state is %s", 1739 mesh->mods.mod[mstate->s.curmod]->name, strextstate(s)); 1740 e = NULL; 1741 if(mesh_continue(mesh, mstate, s, &ev)) 1742 continue; 1743 1744 /* run more modules */ 1745 ev = module_event_pass; 1746 if(mesh->run.count > 0) { 1747 /* pop random element off the runnable tree */ 1748 mstate = (struct mesh_state*)mesh->run.root->key; 1749 (void)rbtree_delete(&mesh->run, mstate); 1750 } else mstate = NULL; 1751 } 1752 if(verbosity >= VERB_ALGO) { 1753 mesh_stats(mesh, "mesh_run: end"); 1754 mesh_log_list(mesh); 1755 } 1756 } 1757 1758 void 1759 mesh_log_list(struct mesh_area* mesh) 1760 { 1761 char buf[30]; 1762 struct mesh_state* m; 1763 int num = 0; 1764 RBTREE_FOR(m, struct mesh_state*, &mesh->all) { 1765 snprintf(buf, sizeof(buf), "%d%s%s%s%s%s%s mod%d %s%s", 1766 num++, (m->s.is_priming)?"p":"", /* prime */ 1767 (m->s.is_valrec)?"v":"", /* prime */ 1768 (m->s.query_flags&BIT_RD)?"RD":"", 1769 (m->s.query_flags&BIT_CD)?"CD":"", 1770 (m->super_set.count==0)?"d":"", /* detached */ 1771 (m->sub_set.count!=0)?"c":"", /* children */ 1772 m->s.curmod, (m->reply_list)?"rep":"", /*hasreply*/ 1773 (m->cb_list)?"cb":"" /* callbacks */ 1774 ); 1775 log_query_info(VERB_ALGO, buf, &m->s.qinfo); 1776 } 1777 } 1778 1779 void 1780 mesh_stats(struct mesh_area* mesh, const char* str) 1781 { 1782 verbose(VERB_DETAIL, "%s %u recursion states (%u with reply, " 1783 "%u detached), %u waiting replies, %u recursion replies " 1784 "sent, %d replies dropped, %d states jostled out", 1785 str, (unsigned)mesh->all.count, 1786 (unsigned)mesh->num_reply_states, 1787 (unsigned)mesh->num_detached_states, 1788 (unsigned)mesh->num_reply_addrs, 1789 (unsigned)mesh->replies_sent, 1790 (unsigned)mesh->stats_dropped, 1791 (unsigned)mesh->stats_jostled); 1792 if(mesh->replies_sent > 0) { 1793 struct timeval avg; 1794 timeval_divide(&avg, &mesh->replies_sum_wait, 1795 mesh->replies_sent); 1796 log_info("average recursion processing time " 1797 ARG_LL "d.%6.6d sec", 1798 (long long)avg.tv_sec, (int)avg.tv_usec); 1799 log_info("histogram of recursion processing times"); 1800 timehist_log(mesh->histogram, "recursions"); 1801 } 1802 } 1803 1804 void 1805 mesh_stats_clear(struct mesh_area* mesh) 1806 { 1807 if(!mesh) 1808 return; 1809 mesh->replies_sent = 0; 1810 mesh->replies_sum_wait.tv_sec = 0; 1811 mesh->replies_sum_wait.tv_usec = 0; 1812 mesh->stats_jostled = 0; 1813 mesh->stats_dropped = 0; 1814 timehist_clear(mesh->histogram); 1815 mesh->ans_secure = 0; 1816 mesh->ans_bogus = 0; 1817 mesh->ans_expired = 0; 1818 memset(&mesh->ans_rcode[0], 0, sizeof(size_t)*UB_STATS_RCODE_NUM); 1819 memset(&mesh->rpz_action[0], 0, sizeof(size_t)*UB_STATS_RPZ_ACTION_NUM); 1820 mesh->ans_nodata = 0; 1821 } 1822 1823 size_t 1824 mesh_get_mem(struct mesh_area* mesh) 1825 { 1826 struct mesh_state* m; 1827 size_t s = sizeof(*mesh) + sizeof(struct timehist) + 1828 sizeof(struct th_buck)*mesh->histogram->num + 1829 sizeof(sldns_buffer) + sldns_buffer_capacity(mesh->qbuf_bak); 1830 RBTREE_FOR(m, struct mesh_state*, &mesh->all) { 1831 /* all, including m itself allocated in qstate region */ 1832 s += regional_get_mem(m->s.region); 1833 } 1834 return s; 1835 } 1836 1837 int 1838 mesh_detect_cycle(struct module_qstate* qstate, struct query_info* qinfo, 1839 uint16_t flags, int prime, int valrec) 1840 { 1841 struct mesh_area* mesh = qstate->env->mesh; 1842 struct mesh_state* dep_m = NULL; 1843 dep_m = mesh_area_find(mesh, NULL, qinfo, flags, prime, valrec); 1844 return mesh_detect_cycle_found(qstate, dep_m); 1845 } 1846 1847 void mesh_list_insert(struct mesh_state* m, struct mesh_state** fp, 1848 struct mesh_state** lp) 1849 { 1850 /* insert as last element */ 1851 m->prev = *lp; 1852 m->next = NULL; 1853 if(*lp) 1854 (*lp)->next = m; 1855 else *fp = m; 1856 *lp = m; 1857 } 1858 1859 void mesh_list_remove(struct mesh_state* m, struct mesh_state** fp, 1860 struct mesh_state** lp) 1861 { 1862 if(m->next) 1863 m->next->prev = m->prev; 1864 else *lp = m->prev; 1865 if(m->prev) 1866 m->prev->next = m->next; 1867 else *fp = m->next; 1868 } 1869 1870 void mesh_state_remove_reply(struct mesh_area* mesh, struct mesh_state* m, 1871 struct comm_point* cp) 1872 { 1873 struct mesh_reply* n, *prev = NULL; 1874 n = m->reply_list; 1875 /* when in mesh_cleanup, it sets the reply_list to NULL, so that 1876 * there is no accounting twice */ 1877 if(!n) return; /* nothing to remove, also no accounting needed */ 1878 while(n) { 1879 if(n->query_reply.c == cp) { 1880 /* unlink it */ 1881 if(prev) prev->next = n->next; 1882 else m->reply_list = n->next; 1883 /* delete it, but allocated in m region */ 1884 log_assert(mesh->num_reply_addrs > 0); 1885 mesh->num_reply_addrs--; 1886 1887 /* prev = prev; */ 1888 n = n->next; 1889 continue; 1890 } 1891 prev = n; 1892 n = n->next; 1893 } 1894 /* it was not detached (because it had a reply list), could be now */ 1895 if(!m->reply_list && !m->cb_list 1896 && m->super_set.count == 0) { 1897 mesh->num_detached_states++; 1898 } 1899 /* if not replies any more in mstate, it is no longer a reply_state */ 1900 if(!m->reply_list && !m->cb_list) { 1901 log_assert(mesh->num_reply_states > 0); 1902 mesh->num_reply_states--; 1903 } 1904 } 1905 1906 1907 static int 1908 apply_respip_action(struct module_qstate* qstate, 1909 const struct query_info* qinfo, struct respip_client_info* cinfo, 1910 struct respip_action_info* actinfo, struct reply_info* rep, 1911 struct ub_packed_rrset_key** alias_rrset, 1912 struct reply_info** encode_repp, struct auth_zones* az) 1913 { 1914 if(qinfo->qtype != LDNS_RR_TYPE_A && 1915 qinfo->qtype != LDNS_RR_TYPE_AAAA && 1916 qinfo->qtype != LDNS_RR_TYPE_ANY) 1917 return 1; 1918 1919 if(!respip_rewrite_reply(qinfo, cinfo, rep, encode_repp, actinfo, 1920 alias_rrset, 0, qstate->region, az)) 1921 return 0; 1922 1923 /* xxx_deny actions mean dropping the reply, unless the original reply 1924 * was redirected to response-ip data. */ 1925 if((actinfo->action == respip_deny || 1926 actinfo->action == respip_inform_deny) && 1927 *encode_repp == rep) 1928 *encode_repp = NULL; 1929 1930 return 1; 1931 } 1932 1933 void 1934 mesh_serve_expired_callback(void* arg) 1935 { 1936 struct mesh_state* mstate = (struct mesh_state*) arg; 1937 struct module_qstate* qstate = &mstate->s; 1938 struct mesh_reply* r; 1939 struct mesh_area* mesh = qstate->env->mesh; 1940 struct dns_msg* msg; 1941 struct mesh_cb* c; 1942 struct mesh_reply* prev = NULL; 1943 struct sldns_buffer* prev_buffer = NULL; 1944 struct sldns_buffer* r_buffer = NULL; 1945 struct reply_info* partial_rep = NULL; 1946 struct ub_packed_rrset_key* alias_rrset = NULL; 1947 struct reply_info* encode_rep = NULL; 1948 struct respip_action_info actinfo; 1949 struct query_info* lookup_qinfo = &qstate->qinfo; 1950 struct query_info qinfo_tmp; 1951 struct timeval tv = {0, 0}; 1952 int must_validate = (!(qstate->query_flags&BIT_CD) 1953 || qstate->env->cfg->ignore_cd) && qstate->env->need_to_validate; 1954 if(!qstate->serve_expired_data) return; 1955 verbose(VERB_ALGO, "Serve expired: Trying to reply with expired data"); 1956 comm_timer_delete(qstate->serve_expired_data->timer); 1957 qstate->serve_expired_data->timer = NULL; 1958 /* If is_drop or no_cache_lookup (modules that handle their own cache e.g., 1959 * subnetmod) ignore stale data from the main cache. */ 1960 if(qstate->no_cache_lookup || qstate->is_drop) { 1961 verbose(VERB_ALGO, 1962 "Serve expired: Not allowed to look into cache for stale"); 1963 return; 1964 } 1965 /* The following while is used instead of the `goto lookup_cache` 1966 * like in the worker. */ 1967 while(1) { 1968 fptr_ok(fptr_whitelist_serve_expired_lookup( 1969 qstate->serve_expired_data->get_cached_answer)); 1970 msg = (*qstate->serve_expired_data->get_cached_answer)(qstate, 1971 lookup_qinfo); 1972 if(!msg) 1973 return; 1974 /* Reset these in case we pass a second time from here. */ 1975 encode_rep = msg->rep; 1976 memset(&actinfo, 0, sizeof(actinfo)); 1977 actinfo.action = respip_none; 1978 alias_rrset = NULL; 1979 if((mesh->use_response_ip || mesh->use_rpz) && 1980 !partial_rep && !apply_respip_action(qstate, &qstate->qinfo, 1981 qstate->client_info, &actinfo, msg->rep, &alias_rrset, &encode_rep, 1982 qstate->env->auth_zones)) { 1983 return; 1984 } else if(partial_rep && 1985 !respip_merge_cname(partial_rep, &qstate->qinfo, msg->rep, 1986 qstate->client_info, must_validate, &encode_rep, qstate->region, 1987 qstate->env->auth_zones)) { 1988 return; 1989 } 1990 if(!encode_rep || alias_rrset) { 1991 if(!encode_rep) { 1992 /* Needs drop */ 1993 return; 1994 } else { 1995 /* A partial CNAME chain is found. */ 1996 partial_rep = encode_rep; 1997 } 1998 } 1999 /* We've found a partial reply ending with an 2000 * alias. Replace the lookup qinfo for the 2001 * alias target and lookup the cache again to 2002 * (possibly) complete the reply. As we're 2003 * passing the "base" reply, there will be no 2004 * more alias chasing. */ 2005 if(partial_rep) { 2006 memset(&qinfo_tmp, 0, sizeof(qinfo_tmp)); 2007 get_cname_target(alias_rrset, &qinfo_tmp.qname, 2008 &qinfo_tmp.qname_len); 2009 if(!qinfo_tmp.qname) { 2010 log_err("Serve expired: unexpected: invalid answer alias"); 2011 return; 2012 } 2013 qinfo_tmp.qtype = qstate->qinfo.qtype; 2014 qinfo_tmp.qclass = qstate->qinfo.qclass; 2015 lookup_qinfo = &qinfo_tmp; 2016 continue; 2017 } 2018 break; 2019 } 2020 2021 if(verbosity >= VERB_ALGO) 2022 log_dns_msg("Serve expired lookup", &qstate->qinfo, msg->rep); 2023 2024 for(r = mstate->reply_list; r; r = r->next) { 2025 tv = r->start_time; 2026 2027 /* If address info is returned, it means the action should be an 2028 * 'inform' variant and the information should be logged. */ 2029 if(actinfo.addrinfo) { 2030 respip_inform_print(&actinfo, r->qname, 2031 qstate->qinfo.qtype, qstate->qinfo.qclass, 2032 r->local_alias, &r->query_reply); 2033 2034 if(qstate->env->cfg->stat_extended && actinfo.rpz_used) { 2035 if(actinfo.rpz_disabled) 2036 qstate->env->mesh->rpz_action[RPZ_DISABLED_ACTION]++; 2037 if(actinfo.rpz_cname_override) 2038 qstate->env->mesh->rpz_action[RPZ_CNAME_OVERRIDE_ACTION]++; 2039 else 2040 qstate->env->mesh->rpz_action[ 2041 respip_action_to_rpz_action(actinfo.action)]++; 2042 } 2043 } 2044 2045 r_buffer = r->query_reply.c->buffer; 2046 if(r->query_reply.c->tcp_req_info) 2047 r_buffer = r->query_reply.c->tcp_req_info->spool_buffer; 2048 mesh_send_reply(mstate, LDNS_RCODE_NOERROR, msg->rep, 2049 r, r_buffer, prev, prev_buffer); 2050 if(r->query_reply.c->tcp_req_info) 2051 tcp_req_info_remove_mesh_state(r->query_reply.c->tcp_req_info, mstate); 2052 prev = r; 2053 prev_buffer = r_buffer; 2054 2055 /* Account for each reply sent. */ 2056 mesh->ans_expired++; 2057 2058 } 2059 if(mstate->reply_list) { 2060 mstate->reply_list = NULL; 2061 if(!mstate->reply_list && !mstate->cb_list) { 2062 log_assert(mesh->num_reply_states > 0); 2063 mesh->num_reply_states--; 2064 if(mstate->super_set.count == 0) { 2065 mesh->num_detached_states++; 2066 } 2067 } 2068 } 2069 while((c = mstate->cb_list) != NULL) { 2070 /* take this cb off the list; so that the list can be 2071 * changed, eg. by adds from the callback routine */ 2072 if(!mstate->reply_list && mstate->cb_list && !c->next) { 2073 /* was a reply state, not anymore */ 2074 log_assert(qstate->env->mesh->num_reply_states > 0); 2075 qstate->env->mesh->num_reply_states--; 2076 } 2077 mstate->cb_list = c->next; 2078 if(!mstate->reply_list && !mstate->cb_list && 2079 mstate->super_set.count == 0) 2080 qstate->env->mesh->num_detached_states++; 2081 mesh_do_callback(mstate, LDNS_RCODE_NOERROR, msg->rep, c, &tv); 2082 } 2083 } 2084