2 * services/mesh.c - deal with mesh of query states and handle events for that.
4 * Copyright (c) 2007, NLnet Labs. All rights reserved.
6 * This software is open source.
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions
12 * Redistributions of source code must retain the above copyright notice,
13 * this list of conditions and the following disclaimer.
15 * Redistributions in binary form must reproduce the above copyright notice,
16 * this list of conditions and the following disclaimer in the documentation
17 * and/or other materials provided with the distribution.
19 * Neither the name of the NLNET LABS nor the names of its contributors may
20 * be used to endorse or promote products derived from this software without
21 * specific prior written permission.
23 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
24 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
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.
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.
46 #include "services/mesh.h"
47 #include "services/outbound_list.h"
48 #include "services/cache/dns.h"
49 #include "services/cache/rrset.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"
67 /** subtract timers and the values do not overflow or become negative */
69 timeval_subtract(struct timeval* d, const struct timeval* end, const struct timeval* start)
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) {
78 d->tv_usec = end_usec - start->tv_usec;
82 /** add timers and the values do not overflow or become negative */
84 timeval_add(struct timeval* d, const struct timeval* add)
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;
96 /** divide sum of timers to get average */
98 timeval_divide(struct timeval* avg, const struct timeval* sum, size_t d)
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;
113 avg->tv_usec += (((long long)leftover)*((long long)1000000))/d;
121 /** histogram compare of time values */
123 timeval_smaller(const struct timeval* x, const struct timeval* y)
126 if(x->tv_sec < y->tv_sec)
128 else if(x->tv_sec == y->tv_sec) {
129 if(x->tv_usec <= y->tv_usec)
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.
155 client_info_compare(const struct respip_client_info* ci_a,
156 const struct respip_client_info* ci_b)
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)
170 if(!ci_a->taglist && ci_b->taglist)
172 if(ci_a->taglist && ci_b->taglist) {
173 cmp = memcmp(ci_a->taglist, ci_b->taglist, ci_a->taglen);
177 if(ci_a->tag_actions_size != ci_b->tag_actions_size)
178 return (ci_a->tag_actions_size < ci_b->tag_actions_size) ?
180 if(ci_a->tag_actions && !ci_b->tag_actions)
182 if(!ci_a->tag_actions && ci_b->tag_actions)
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);
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;
202 mesh_state_compare(const void* ap, const void* bp)
204 struct mesh_state* a = (struct mesh_state*)ap;
205 struct mesh_state* b = (struct mesh_state*)bp;
208 if(a->unique < b->unique)
210 if(a->unique > b->unique)
213 if(a->s.is_priming && !b->s.is_priming)
215 if(!a->s.is_priming && b->s.is_priming)
218 if(a->s.is_valrec && !b->s.is_valrec)
220 if(!a->s.is_valrec && b->s.is_valrec)
223 if((a->s.query_flags&BIT_RD) && !(b->s.query_flags&BIT_RD))
225 if(!(a->s.query_flags&BIT_RD) && (b->s.query_flags&BIT_RD))
228 if((a->s.query_flags&BIT_CD) && !(b->s.query_flags&BIT_CD))
230 if(!(a->s.query_flags&BIT_CD) && (b->s.query_flags&BIT_CD))
233 cmp = query_info_compare(&a->s.qinfo, &b->s.qinfo);
236 return client_info_compare(a->s.client_info, b->s.client_info);
240 mesh_state_ref_compare(const void* ap, const void* bp)
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);
248 mesh_create(struct module_stack* stack, struct module_env* env)
250 struct mesh_area* mesh = calloc(1, sizeof(struct mesh_area));
252 log_err("mesh area alloc: out of memory");
255 mesh->histogram = timehist_setup();
256 mesh->qbuf_bak = sldns_buffer_new(env->cfg->msg_buffer_size);
257 if(!mesh->histogram || !mesh->qbuf_bak) {
259 log_err("mesh area alloc: out of memory");
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;
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)
283 /** help mesh delete delete mesh states */
285 mesh_delete_helper(rbnode_type* n)
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 */
297 mesh_delete(struct mesh_area* mesh)
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);
310 mesh_delete_all(struct mesh_area* mesh)
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;
329 int mesh_make_new_space(struct mesh_area* mesh, sldns_buffer* qbuf)
331 struct mesh_state* m = mesh->jostle_first;
332 /* free space is available */
333 if(mesh->num_reply_states < mesh->max_reply_states)
335 /* try to kick out a jostle-list item */
336 if(m && m->reply_list && m->list_select == mesh_jostle_list) {
339 timeval_subtract(&age, mesh->env->now_tv,
340 &m->reply_list->start_time);
341 if(timeval_smaller(&mesh->jostle_max, &age)) {
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,
347 /* backup the query */
348 if(qbuf) sldns_buffer_copy(mesh->qbuf_bak, qbuf);
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);
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);
364 /* no space for new item */
369 mesh_serve_expired_lookup(struct module_qstate* qstate,
370 struct query_info* lookup_qinfo)
373 struct lruhash_entry* e;
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;
381 h = query_info_hash(lookup_qinfo, qstate->query_flags);
382 e = slabhash_lookup(qstate->env->msg_cache, h, lookup_qinfo, 0);
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);
392 /* Check CNAME chain (if any)
393 * This is part of tomsg above; no need to check now. */
395 /* Check security status of the cached answer.
396 * tomsg above has a subset of these checks, so we are leaving
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");
403 } else if(msg->rep->security == sec_status_unchecked && must_validate) {
404 verbose(VERB_ALGO, "Serve expired: unchecked entry needs "
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"
411 goto bail_out; /* rrset changed, re-verify */
414 lock_rw_unlock(&e->lock);
418 lock_rw_unlock(&e->lock);
423 /** Init the serve expired data structure */
425 mesh_serve_expired_init(struct mesh_state* mstate, int timeout)
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*)
433 mstate->s.region, sizeof(struct serve_expired_data));
434 if(!mstate->s.serve_expired_data)
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;
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)
451 t.tv_sec = timeout/1000;
452 t.tv_usec = (timeout%1000)*1000;
454 comm_timer_set(mstate->s.serve_expired_data->timer, &t);
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)
463 struct mesh_state* s = NULL;
464 int unique = unique_mesh_state(edns->opt_list, mesh->env);
465 int was_detached = 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;
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 "
481 comm_point_drop_reply(rep);
482 mesh->stats_dropped++;
485 /* for this new reply state, the reply address is free,
486 * so the limit of reply addresses does not stop reply states*/
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++;
497 /* see if it already exists, if not, create one */
500 struct rbnode_type* n;
502 s = mesh_state_create(mesh->env, qinfo, cinfo,
503 qflags&(BIT_RD|BIT_CD), 0, 0);
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 = NULL;
509 error_encode(r_buffer, LDNS_RCODE_SERVFAIL,
510 qinfo, qid, qflags, edns);
511 comm_point_send_reply(rep);
515 mesh_state_make_unique(s);
516 /* copy the edns options we got from the front */
518 s->s.edns_opts_front_in = edns_opt_copy_region(edns->opt_list,
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 = NULL;
525 error_encode(r_buffer, LDNS_RCODE_SERVFAIL,
526 qinfo, qid, qflags, edns);
527 comm_point_send_reply(rep);
537 rbtree_insert(&mesh->all, &s->node);
538 log_assert(n != NULL);
539 /* set detached (it is now) */
540 mesh->num_detached_states++;
543 if(!s->reply_list && !s->cb_list) {
545 if(s->super_set.count == 0) {
550 if(!mesh_state_add_reply(s, edns, rep, qid, qflags, qinfo)) {
551 log_err("mesh_new_client: out of memory; SERVFAIL");
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");
561 http2_stream_add_meshstate(rep->c->h2_stream, mesh, s);
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");
568 /* update statistics */
570 log_assert(mesh->num_detached_states > 0);
571 mesh->num_detached_states--;
574 mesh->num_reply_states ++;
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;
585 mesh_list_insert(s, &mesh->jostle_first,
587 s->list_select = mesh_jostle_list;
591 mesh_run(mesh, s, module_event_new, NULL);
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 = NULL;
598 error_encode(r_buffer, LDNS_RCODE_SERVFAIL,
599 qinfo, qid, qflags, edns);
600 comm_point_send_reply(rep);
602 mesh_state_delete(&s->s);
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)
611 struct mesh_state* s = NULL;
612 int unique = unique_mesh_state(edns->opt_list, mesh->env);
613 int timeout = mesh->env->cfg->serve_expired?
614 mesh->env->cfg->serve_expired_client_timeout:0;
615 int was_detached = 0;
619 s = mesh_area_find(mesh, NULL, qinfo, qflags&(BIT_RD|BIT_CD), 0, 0);
621 /* there are no limits on the number of callbacks */
623 /* see if it already exists, if not, create one */
626 struct rbnode_type* n;
628 s = mesh_state_create(mesh->env, qinfo, NULL,
629 qflags&(BIT_RD|BIT_CD), 0, 0);
634 mesh_state_make_unique(s);
636 s->s.edns_opts_front_in = edns_opt_copy_region(edns->opt_list,
638 if(!s->s.edns_opts_front_in) {
647 rbtree_insert(&mesh->all, &s->node);
648 log_assert(n != NULL);
649 /* set detached (it is now) */
650 mesh->num_detached_states++;
653 if(!s->reply_list && !s->cb_list) {
655 if(s->super_set.count == 0) {
660 if(!mesh_state_add_cb(s, edns, buf, cb, cb_arg, qid, qflags)) {
662 mesh_state_delete(&s->s);
665 /* add serve expired timer if not already there */
666 if(timeout && !mesh_serve_expired_init(s, timeout)) {
669 /* update statistics */
671 log_assert(mesh->num_detached_states > 0);
672 mesh->num_detached_states--;
675 mesh->num_reply_states ++;
677 mesh->num_reply_addrs++;
679 mesh_run(mesh, s, module_event_new, NULL);
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)
691 struct mesh_state* s = mesh_area_find(mesh, NULL, qinfo,
692 qflags&(BIT_RD|BIT_CD), 0, 0);
694 struct rbnode_type* n;
696 /* already exists, and for a different purpose perhaps.
697 * if mesh_no_list, keep it that way. */
699 /* make it ignore the cache from now on */
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;
706 if(!mesh_make_new_space(mesh, NULL)) {
707 verbose(VERB_ALGO, "Too many queries. dropped prefetch.");
708 mesh->stats_dropped ++;
712 s = mesh_state_create(mesh->env, qinfo, NULL,
713 qflags&(BIT_RD|BIT_CD), 0, 0);
715 log_err("prefetch mesh_state_create: out of memory");
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;
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;
739 mesh_list_insert(s, &mesh->jostle_first,
741 s->list_select = mesh_jostle_list;
751 rbtree_insert(&mesh->run, &s->run_node);
752 log_assert(n != NULL);
756 mesh_run(mesh, s, module_event_new, NULL);
759 void mesh_new_prefetch(struct mesh_area* mesh, struct query_info* qinfo,
760 uint16_t qflags, time_t leeway)
762 mesh_schedule_prefetch(mesh, qinfo, qflags, leeway, 1);
765 void mesh_report_reply(struct mesh_area* mesh, struct outbound_entry* e,
766 struct comm_reply* reply, int what)
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;
775 mesh_run(mesh, e->qstate->mesh_info, event, e);
779 mesh_state_create(struct module_env* env, struct query_info* qinfo,
780 struct respip_client_info* cinfo, uint16_t qflags, int prime,
783 struct regional* region = alloc_reg_obtain(env->alloc);
784 struct mesh_state* mstate;
788 mstate = (struct mesh_state*)regional_alloc(region,
789 sizeof(struct mesh_state));
791 alloc_reg_release(env->alloc, region);
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,
813 if(!mstate->s.qinfo.qname) {
814 alloc_reg_release(env->alloc, region);
818 mstate->s.client_info = regional_alloc_init(region, cinfo,
820 if(!mstate->s.client_info) {
821 alloc_reg_release(env->alloc, region);
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;
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;
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;
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;
858 mesh_state_is_unique(struct mesh_state* mstate)
860 return mstate->unique != NULL;
864 mesh_state_make_unique(struct mesh_state* mstate)
866 mstate->unique = mstate;
870 mesh_state_cleanup(struct mesh_state* mstate)
872 struct mesh_area* mesh;
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;
882 /* drop unsent replies */
883 if(!mstate->replies_sent) {
884 struct mesh_reply* rep = mstate->reply_list;
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--;
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--;
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;
912 alloc_reg_release(mstate->s.env->alloc, mstate->s.region);
916 mesh_state_delete(struct module_qstate* qstate)
918 struct mesh_area* mesh;
919 struct mesh_state_ref* super, ref;
920 struct mesh_state* mstate;
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,
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--;
939 if(mstate->reply_list || mstate->cb_list) {
940 log_assert(mesh->num_reply_states > 0);
941 mesh->num_reply_states--;
945 RBTREE_FOR(super, struct mesh_state_ref*, &mstate->super_set) {
946 (void)rbtree_delete(&super->s->sub_set, &ref);
948 (void)rbtree_delete(&mesh->run, mstate);
949 (void)rbtree_delete(&mesh->all, mstate);
950 mesh_state_cleanup(mstate);
953 /** helper recursive rbtree find routine */
955 find_in_subsub(struct mesh_state* m, struct mesh_state* tofind, size_t *c)
957 struct mesh_state_ref* r;
958 if((*c)++ > MESH_MAX_SUBSUB)
960 RBTREE_FOR(r, struct mesh_state_ref*, &m->sub_set) {
961 if(r->s == tofind || find_in_subsub(r->s, tofind, c))
967 /** find cycle for already looked up mesh_state */
969 mesh_detect_cycle_found(struct module_qstate* qstate, struct mesh_state* dep_m)
971 struct mesh_state* cyc_m = qstate->mesh_info;
975 if(dep_m == cyc_m || find_in_subsub(dep_m, cyc_m, &counter)) {
976 if(counter > MESH_MAX_SUBSUB)
983 void mesh_detach_subs(struct module_qstate* qstate)
985 struct mesh_area* mesh = qstate->env->mesh;
986 struct mesh_state_ref* ref, lookup;
988 struct rbnode_type* n;
990 lookup.node.key = &lookup;
991 lookup.s = qstate->mesh_info;
992 RBTREE_FOR(ref, struct mesh_state_ref*, &qstate->mesh_info->sub_set) {
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);
1007 rbtree_init(&qstate->mesh_info->sub_set, &mesh_state_ref_compare);
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)
1014 /* find it, if not, create it */
1015 struct mesh_area* mesh = qstate->env->mesh;
1016 *sub = mesh_area_find(mesh, NULL, qinfo, qflags,
1018 if(mesh_detect_cycle_found(qstate, *sub)) {
1019 verbose(VERB_ALGO, "attach failed, cycle detected");
1023 #ifdef UNBOUND_DEBUG
1024 struct rbnode_type* n;
1026 /* create a new one */
1027 *sub = mesh_state_create(qstate->env, qinfo, NULL, qflags, prime,
1030 log_err("mesh_attach_sub: out of memory");
1033 #ifdef UNBOUND_DEBUG
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
1048 rbtree_insert(&mesh->run, &(*sub)->run_node);
1049 log_assert(n != NULL);
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)
1059 struct mesh_area* mesh = qstate->env->mesh;
1060 struct mesh_state* sub = NULL;
1062 if(!mesh_add_sub(qstate, qinfo, qflags, prime, valrec, newq, &sub))
1064 was_detached = (sub->super_set.count == 0);
1065 if(!mesh_state_attachment(qstate->mesh_info, sub))
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--;
1074 /* *newq will be run when inited after the current module stops */
1078 int mesh_state_attachment(struct mesh_state* super, struct mesh_state* sub)
1080 #ifdef UNBOUND_DEBUG
1081 struct rbnode_type* n;
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");
1092 superref->node.key = superref;
1093 superref->s = super;
1094 subref->node.key = subref;
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 */
1104 #ifdef UNBOUND_DEBUG
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 */
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.
1125 mesh_do_callback(struct mesh_state* m, int rcode, struct reply_info* rep,
1126 struct mesh_cb* r, struct timeval* start_time)
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)
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;
1143 /* send the reply */
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 = NULL;
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 = NULL;
1154 fptr_ok(fptr_whitelist_mesh_cb(r->cb));
1155 (*r->cb)(r->cb_arg, rcode, r->buf, sec_status_unchecked, NULL,
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;
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))
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);
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);
1182 log_assert(m->s.env->mesh->num_reply_addrs > 0);
1183 m->s.env->mesh->num_reply_addrs--;
1187 * Send reply to mesh reply entry
1188 * @param m: mesh state to send it for.
1189 * @param rcode: if not 0, error code.
1190 * @param rep: reply to send (or NULL if rcode is set).
1191 * @param r: reply entry
1192 * @param r_buffer: buffer to use for reply entry.
1193 * @param prev: previous reply, already has its answer encoded in buffer.
1194 * @param prev_buffer: buffer for previous reply.
1197 mesh_send_reply(struct mesh_state* m, int rcode, struct reply_info* rep,
1198 struct mesh_reply* r, struct sldns_buffer* r_buffer,
1199 struct mesh_reply* prev, struct sldns_buffer* prev_buffer)
1201 struct timeval end_time;
1202 struct timeval duration;
1204 /* Copy the client's EDNS for later restore, to make sure the edns
1205 * compare is with the correct edns options. */
1206 struct edns_data edns_bak = r->edns;
1207 /* briefly set the replylist to null in case the
1208 * meshsendreply calls tcpreqinfo sendreply that
1209 * comm_point_drops because of size, and then the
1210 * null stops the mesh state remove and thus
1211 * reply_list modification and accounting */
1212 struct mesh_reply* rlist = m->reply_list;
1213 /* examine security status */
1214 if(m->s.env->need_to_validate && (!(r->qflags&BIT_CD) ||
1215 m->s.env->cfg->ignore_cd) && rep &&
1216 (rep->security <= sec_status_bogus ||
1217 rep->security == sec_status_secure_sentinel_fail)) {
1218 rcode = LDNS_RCODE_SERVFAIL;
1219 if(m->s.env->cfg->stat_extended)
1220 m->s.env->mesh->ans_bogus++;
1222 if(rep && rep->security == sec_status_secure)
1225 if(!rep && rcode == LDNS_RCODE_NOERROR)
1226 rcode = LDNS_RCODE_SERVFAIL;
1227 if(r->query_reply.c->use_h2) {
1228 r->query_reply.c->h2_stream = r->h2_stream;
1229 /* Mesh reply won't exist for long anymore. Make it impossible
1230 * for HTTP/2 stream to refer to mesh state, in case
1231 * connection gets cleanup before HTTP/2 stream close. */
1232 r->h2_stream->mesh_state = NULL;
1234 /* send the reply */
1235 /* We don't reuse the encoded answer if:
1236 * - either the previous or current response has a local alias. We could
1237 * compare the alias records and still reuse the previous answer if they
1238 * are the same, but that would be complicated and error prone for the
1239 * relatively minor case. So we err on the side of safety.
1240 * - there are registered callback functions for the given rcode, as these
1241 * need to be called for each reply. */
1242 if(((rcode != LDNS_RCODE_SERVFAIL &&
1243 !m->s.env->inplace_cb_lists[inplace_cb_reply]) ||
1244 (rcode == LDNS_RCODE_SERVFAIL &&
1245 !m->s.env->inplace_cb_lists[inplace_cb_reply_servfail])) &&
1246 prev && prev_buffer && prev->qflags == r->qflags &&
1247 !prev->local_alias && !r->local_alias &&
1248 prev->edns.edns_present == r->edns.edns_present &&
1249 prev->edns.bits == r->edns.bits &&
1250 prev->edns.udp_size == r->edns.udp_size &&
1251 edns_opt_list_compare(prev->edns.opt_list, r->edns.opt_list)
1253 /* if the previous reply is identical to this one, fix ID */
1254 if(prev_buffer != r_buffer)
1255 sldns_buffer_copy(r_buffer, prev_buffer);
1256 sldns_buffer_write_at(r_buffer, 0, &r->qid, sizeof(uint16_t));
1257 sldns_buffer_write_at(r_buffer, 12, r->qname,
1258 m->s.qinfo.qname_len);
1259 m->reply_list = NULL;
1260 comm_point_send_reply(&r->query_reply);
1261 m->reply_list = rlist;
1263 m->s.qinfo.qname = r->qname;
1264 m->s.qinfo.local_alias = r->local_alias;
1265 if(rcode == LDNS_RCODE_SERVFAIL) {
1266 if(!inplace_cb_reply_servfail_call(m->s.env, &m->s.qinfo, &m->s,
1267 rep, rcode, &r->edns, &r->query_reply, m->s.region, &r->start_time))
1268 r->edns.opt_list = NULL;
1270 if(!inplace_cb_reply_call(m->s.env, &m->s.qinfo, &m->s, rep, rcode,
1271 &r->edns, &r->query_reply, m->s.region, &r->start_time))
1272 r->edns.opt_list = NULL;
1274 error_encode(r_buffer, rcode, &m->s.qinfo, r->qid,
1275 r->qflags, &r->edns);
1276 m->reply_list = NULL;
1277 comm_point_send_reply(&r->query_reply);
1278 m->reply_list = rlist;
1280 size_t udp_size = r->edns.udp_size;
1281 r->edns.edns_version = EDNS_ADVERTISED_VERSION;
1282 r->edns.udp_size = EDNS_ADVERTISED_SIZE;
1283 r->edns.ext_rcode = 0;
1284 r->edns.bits &= EDNS_DO;
1285 m->s.qinfo.qname = r->qname;
1286 m->s.qinfo.local_alias = r->local_alias;
1287 if(!inplace_cb_reply_call(m->s.env, &m->s.qinfo, &m->s, rep,
1288 LDNS_RCODE_NOERROR, &r->edns, &r->query_reply, m->s.region, &r->start_time) ||
1289 !apply_edns_options(&r->edns, &edns_bak,
1290 m->s.env->cfg, r->query_reply.c,
1292 !reply_info_answer_encode(&m->s.qinfo, rep, r->qid,
1293 r->qflags, r_buffer, 0, 1, m->s.env->scratch,
1294 udp_size, &r->edns, (int)(r->edns.bits & EDNS_DO),
1297 if(!inplace_cb_reply_servfail_call(m->s.env, &m->s.qinfo, &m->s,
1298 rep, LDNS_RCODE_SERVFAIL, &r->edns, &r->query_reply, m->s.region, &r->start_time))
1299 r->edns.opt_list = NULL;
1300 error_encode(r_buffer, LDNS_RCODE_SERVFAIL,
1301 &m->s.qinfo, r->qid, r->qflags, &r->edns);
1304 m->reply_list = NULL;
1305 comm_point_send_reply(&r->query_reply);
1306 m->reply_list = rlist;
1309 log_assert(m->s.env->mesh->num_reply_addrs > 0);
1310 m->s.env->mesh->num_reply_addrs--;
1311 end_time = *m->s.env->now_tv;
1312 timeval_subtract(&duration, &end_time, &r->start_time);
1313 verbose(VERB_ALGO, "query took " ARG_LL "d.%6.6d sec",
1314 (long long)duration.tv_sec, (int)duration.tv_usec);
1315 m->s.env->mesh->replies_sent++;
1316 timeval_add(&m->s.env->mesh->replies_sum_wait, &duration);
1317 timehist_insert(m->s.env->mesh->histogram, &duration);
1318 if(m->s.env->cfg->stat_extended) {
1319 uint16_t rc = FLAGS_GET_RCODE(sldns_buffer_read_u16_at(
1321 if(secure) m->s.env->mesh->ans_secure++;
1322 m->s.env->mesh->ans_rcode[ rc ] ++;
1323 if(rc == 0 && LDNS_ANCOUNT(sldns_buffer_begin(r_buffer)) == 0)
1324 m->s.env->mesh->ans_nodata++;
1326 /* Log reply sent */
1327 if(m->s.env->cfg->log_replies) {
1328 log_reply_info(NO_VERBOSE, &m->s.qinfo, &r->query_reply.addr,
1329 r->query_reply.addrlen, duration, 0, r_buffer);
1333 void mesh_query_done(struct mesh_state* mstate)
1335 struct mesh_reply* r;
1336 struct mesh_reply* prev = NULL;
1337 struct sldns_buffer* prev_buffer = NULL;
1339 struct reply_info* rep = (mstate->s.return_msg?
1340 mstate->s.return_msg->rep:NULL);
1341 struct timeval tv = {0, 0};
1342 /* No need for the serve expired timer anymore; we are going to reply. */
1343 if(mstate->s.serve_expired_data) {
1344 comm_timer_delete(mstate->s.serve_expired_data->timer);
1345 mstate->s.serve_expired_data->timer = NULL;
1347 if(mstate->s.return_rcode == LDNS_RCODE_SERVFAIL ||
1348 (rep && FLAGS_GET_RCODE(rep->flags) == LDNS_RCODE_SERVFAIL)) {
1349 /* we are SERVFAILing; check for expired asnwer here */
1350 mesh_serve_expired_callback(mstate);
1351 if((mstate->reply_list || mstate->cb_list)
1352 && mstate->s.env->cfg->log_servfail
1353 && !mstate->s.env->cfg->val_log_squelch) {
1354 char* err = errinf_to_str_servfail(&mstate->s);
1360 for(r = mstate->reply_list; r; r = r->next) {
1363 /* if a response-ip address block has been stored the
1364 * information should be logged for each client. */
1365 if(mstate->s.respip_action_info &&
1366 mstate->s.respip_action_info->addrinfo) {
1367 respip_inform_print(mstate->s.respip_action_info,
1368 r->qname, mstate->s.qinfo.qtype,
1369 mstate->s.qinfo.qclass, r->local_alias,
1371 if(mstate->s.env->cfg->stat_extended &&
1372 mstate->s.respip_action_info->rpz_used) {
1373 if(mstate->s.respip_action_info->rpz_disabled)
1374 mstate->s.env->mesh->rpz_action[RPZ_DISABLED_ACTION]++;
1375 if(mstate->s.respip_action_info->rpz_cname_override)
1376 mstate->s.env->mesh->rpz_action[RPZ_CNAME_OVERRIDE_ACTION]++;
1378 mstate->s.env->mesh->rpz_action[respip_action_to_rpz_action(
1379 mstate->s.respip_action_info->action)]++;
1383 /* if this query is determined to be dropped during the
1384 * mesh processing, this is the point to take that action. */
1385 if(mstate->s.is_drop) {
1386 /* briefly set the reply_list to NULL, so that the
1387 * tcp req info cleanup routine that calls the mesh
1388 * to deregister the meshstate for it is not done
1389 * because the list is NULL and also accounting is not
1390 * done there, but instead we do that here. */
1391 struct mesh_reply* reply_list = mstate->reply_list;
1392 mstate->reply_list = NULL;
1393 comm_point_drop_reply(&r->query_reply);
1394 mstate->reply_list = reply_list;
1396 struct sldns_buffer* r_buffer = r->query_reply.c->buffer;
1397 if(r->query_reply.c->tcp_req_info) {
1398 r_buffer = r->query_reply.c->tcp_req_info->spool_buffer;
1401 mesh_send_reply(mstate, mstate->s.return_rcode, rep,
1402 r, r_buffer, prev, prev_buffer);
1403 if(r->query_reply.c->tcp_req_info) {
1404 tcp_req_info_remove_mesh_state(r->query_reply.c->tcp_req_info, mstate);
1408 prev_buffer = r_buffer;
1411 if(mstate->reply_list) {
1412 mstate->reply_list = NULL;
1413 if(!mstate->reply_list && !mstate->cb_list) {
1414 /* was a reply state, not anymore */
1415 log_assert(mstate->s.env->mesh->num_reply_states > 0);
1416 mstate->s.env->mesh->num_reply_states--;
1418 if(!mstate->reply_list && !mstate->cb_list &&
1419 mstate->super_set.count == 0)
1420 mstate->s.env->mesh->num_detached_states++;
1422 mstate->replies_sent = 1;
1423 while((c = mstate->cb_list) != NULL) {
1424 /* take this cb off the list; so that the list can be
1425 * changed, eg. by adds from the callback routine */
1426 if(!mstate->reply_list && mstate->cb_list && !c->next) {
1427 /* was a reply state, not anymore */
1428 log_assert(mstate->s.env->mesh->num_reply_states > 0);
1429 mstate->s.env->mesh->num_reply_states--;
1431 mstate->cb_list = c->next;
1432 if(!mstate->reply_list && !mstate->cb_list &&
1433 mstate->super_set.count == 0)
1434 mstate->s.env->mesh->num_detached_states++;
1435 mesh_do_callback(mstate, mstate->s.return_rcode, rep, c, &tv);
1439 void mesh_walk_supers(struct mesh_area* mesh, struct mesh_state* mstate)
1441 struct mesh_state_ref* ref;
1442 RBTREE_FOR(ref, struct mesh_state_ref*, &mstate->super_set)
1444 /* make super runnable */
1445 (void)rbtree_insert(&mesh->run, &ref->s->run_node);
1446 /* callback the function to inform super of result */
1447 fptr_ok(fptr_whitelist_mod_inform_super(
1448 mesh->mods.mod[ref->s->s.curmod]->inform_super));
1449 (*mesh->mods.mod[ref->s->s.curmod]->inform_super)(&mstate->s,
1450 ref->s->s.curmod, &ref->s->s);
1451 /* copy state that is always relevant to super */
1452 copy_state_to_super(&mstate->s, ref->s->s.curmod, &ref->s->s);
1456 struct mesh_state* mesh_area_find(struct mesh_area* mesh,
1457 struct respip_client_info* cinfo, struct query_info* qinfo,
1458 uint16_t qflags, int prime, int valrec)
1460 struct mesh_state key;
1461 struct mesh_state* result;
1463 key.node.key = &key;
1464 key.s.is_priming = prime;
1465 key.s.is_valrec = valrec;
1466 key.s.qinfo = *qinfo;
1467 key.s.query_flags = qflags;
1468 /* We are searching for a similar mesh state when we DO want to
1469 * aggregate the state. Thus unique is set to NULL. (default when we
1470 * desire aggregation).*/
1472 key.s.client_info = cinfo;
1474 result = (struct mesh_state*)rbtree_search(&mesh->all, &key);
1478 int mesh_state_add_cb(struct mesh_state* s, struct edns_data* edns,
1479 sldns_buffer* buf, mesh_cb_func_type cb, void* cb_arg,
1480 uint16_t qid, uint16_t qflags)
1482 struct mesh_cb* r = regional_alloc(s->s.region,
1483 sizeof(struct mesh_cb));
1487 log_assert(fptr_whitelist_mesh_cb(cb)); /* early failure ifmissing*/
1491 if(edns->opt_list) {
1492 r->edns.opt_list = edns_opt_copy_region(edns->opt_list,
1494 if(!r->edns.opt_list)
1499 r->next = s->cb_list;
1505 int mesh_state_add_reply(struct mesh_state* s, struct edns_data* edns,
1506 struct comm_reply* rep, uint16_t qid, uint16_t qflags,
1507 const struct query_info* qinfo)
1509 struct mesh_reply* r = regional_alloc(s->s.region,
1510 sizeof(struct mesh_reply));
1513 r->query_reply = *rep;
1515 if(edns->opt_list) {
1516 r->edns.opt_list = edns_opt_copy_region(edns->opt_list,
1518 if(!r->edns.opt_list)
1523 r->start_time = *s->s.env->now_tv;
1524 r->next = s->reply_list;
1525 r->qname = regional_alloc_init(s->s.region, qinfo->qname,
1526 s->s.qinfo.qname_len);
1530 r->h2_stream = rep->c->h2_stream;
1532 /* Data related to local alias stored in 'qinfo' (if any) is ephemeral
1533 * and can be different for different original queries (even if the
1534 * replaced query name is the same). So we need to make a deep copy
1535 * and store the copy for each reply info. */
1536 if(qinfo->local_alias) {
1537 struct packed_rrset_data* d;
1538 struct packed_rrset_data* dsrc;
1539 r->local_alias = regional_alloc_zero(s->s.region,
1540 sizeof(*qinfo->local_alias));
1543 r->local_alias->rrset = regional_alloc_init(s->s.region,
1544 qinfo->local_alias->rrset,
1545 sizeof(*qinfo->local_alias->rrset));
1546 if(!r->local_alias->rrset)
1548 dsrc = qinfo->local_alias->rrset->entry.data;
1550 /* In the current implementation, a local alias must be
1551 * a single CNAME RR (see worker_handle_request()). */
1552 log_assert(!qinfo->local_alias->next && dsrc->count == 1 &&
1553 qinfo->local_alias->rrset->rk.type ==
1554 htons(LDNS_RR_TYPE_CNAME));
1555 /* we should make a local copy for the owner name of
1557 r->local_alias->rrset->rk.dname_len =
1558 qinfo->local_alias->rrset->rk.dname_len;
1559 r->local_alias->rrset->rk.dname = regional_alloc_init(
1560 s->s.region, qinfo->local_alias->rrset->rk.dname,
1561 qinfo->local_alias->rrset->rk.dname_len);
1562 if(!r->local_alias->rrset->rk.dname)
1565 /* the rrset is not packed, like in the cache, but it is
1566 * individualy allocated with an allocator from localzone. */
1567 d = regional_alloc_zero(s->s.region, sizeof(*d));
1570 r->local_alias->rrset->entry.data = d;
1571 if(!rrset_insert_rr(s->s.region, d, dsrc->rr_data[0],
1572 dsrc->rr_len[0], dsrc->rr_ttl[0], "CNAME local alias"))
1575 r->local_alias = NULL;
1581 /* Extract the query info and flags from 'mstate' into '*qinfop' and '*qflags'.
1582 * Since this is only used for internal refetch of otherwise-expired answer,
1583 * we simply ignore the rare failure mode when memory allocation fails. */
1585 mesh_copy_qinfo(struct mesh_state* mstate, struct query_info** qinfop,
1588 struct regional* region = mstate->s.env->scratch;
1589 struct query_info* qinfo;
1591 qinfo = regional_alloc_init(region, &mstate->s.qinfo, sizeof(*qinfo));
1594 qinfo->qname = regional_alloc_init(region, qinfo->qname,
1599 *qflags = mstate->s.query_flags;
1603 * Continue processing the mesh state at another module.
1604 * Handles module to modules transfer of control.
1605 * Handles module finished.
1606 * @param mesh: the mesh area.
1607 * @param mstate: currently active mesh state.
1608 * Deleted if finished, calls _done and _supers to
1609 * send replies to clients and inform other mesh states.
1610 * This in turn may create additional runnable mesh states.
1611 * @param s: state at which the current module exited.
1612 * @param ev: the event sent to the module.
1613 * returned is the event to send to the next module.
1614 * @return true if continue processing at the new module.
1615 * false if not continued processing is needed.
1618 mesh_continue(struct mesh_area* mesh, struct mesh_state* mstate,
1619 enum module_ext_state s, enum module_ev* ev)
1621 mstate->num_activated++;
1622 if(mstate->num_activated > MESH_MAX_ACTIVATION) {
1623 /* module is looping. Stop it. */
1624 log_err("internal error: looping module (%s) stopped",
1625 mesh->mods.mod[mstate->s.curmod]->name);
1626 log_query_info(NO_VERBOSE, "pass error for qstate",
1630 if(s == module_wait_module || s == module_restart_next) {
1631 /* start next module */
1633 if(mesh->mods.num == mstate->s.curmod) {
1634 log_err("Cannot pass to next module; at last module");
1635 log_query_info(VERB_QUERY, "pass error for qstate",
1638 return mesh_continue(mesh, mstate, module_error, ev);
1640 if(s == module_restart_next) {
1641 int curmod = mstate->s.curmod;
1642 for(; mstate->s.curmod < mesh->mods.num;
1643 mstate->s.curmod++) {
1644 fptr_ok(fptr_whitelist_mod_clear(
1645 mesh->mods.mod[mstate->s.curmod]->clear));
1646 (*mesh->mods.mod[mstate->s.curmod]->clear)
1647 (&mstate->s, mstate->s.curmod);
1648 mstate->s.minfo[mstate->s.curmod] = NULL;
1650 mstate->s.curmod = curmod;
1652 *ev = module_event_pass;
1655 if(s == module_wait_subquery && mstate->sub_set.count == 0) {
1656 log_err("module cannot wait for subquery, subquery list empty");
1657 log_query_info(VERB_QUERY, "pass error for qstate",
1661 if(s == module_error && mstate->s.return_rcode == LDNS_RCODE_NOERROR) {
1662 /* error is bad, handle pass back up below */
1663 mstate->s.return_rcode = LDNS_RCODE_SERVFAIL;
1665 if(s == module_error) {
1666 mesh_query_done(mstate);
1667 mesh_walk_supers(mesh, mstate);
1668 mesh_state_delete(&mstate->s);
1671 if(s == module_finished) {
1672 if(mstate->s.curmod == 0) {
1673 struct query_info* qinfo = NULL;
1676 mesh_query_done(mstate);
1677 mesh_walk_supers(mesh, mstate);
1679 /* If the answer to the query needs to be refetched
1680 * from an external DNS server, we'll need to schedule
1681 * a prefetch after removing the current state, so
1682 * we need to make a copy of the query info here. */
1683 if(mstate->s.need_refetch)
1684 mesh_copy_qinfo(mstate, &qinfo, &qflags);
1686 mesh_state_delete(&mstate->s);
1688 mesh_schedule_prefetch(mesh, qinfo, qflags,
1693 /* pass along the locus of control */
1694 mstate->s.curmod --;
1695 *ev = module_event_moddone;
1701 void mesh_run(struct mesh_area* mesh, struct mesh_state* mstate,
1702 enum module_ev ev, struct outbound_entry* e)
1704 enum module_ext_state s;
1705 verbose(VERB_ALGO, "mesh_run: start");
1707 /* run the module */
1708 fptr_ok(fptr_whitelist_mod_operate(
1709 mesh->mods.mod[mstate->s.curmod]->operate));
1710 (*mesh->mods.mod[mstate->s.curmod]->operate)
1711 (&mstate->s, ev, mstate->s.curmod, e);
1713 /* examine results */
1714 mstate->s.reply = NULL;
1715 regional_free_all(mstate->s.env->scratch);
1716 s = mstate->s.ext_state[mstate->s.curmod];
1717 verbose(VERB_ALGO, "mesh_run: %s module exit state is %s",
1718 mesh->mods.mod[mstate->s.curmod]->name, strextstate(s));
1720 if(mesh_continue(mesh, mstate, s, &ev))
1723 /* run more modules */
1724 ev = module_event_pass;
1725 if(mesh->run.count > 0) {
1726 /* pop random element off the runnable tree */
1727 mstate = (struct mesh_state*)mesh->run.root->key;
1728 (void)rbtree_delete(&mesh->run, mstate);
1729 } else mstate = NULL;
1731 if(verbosity >= VERB_ALGO) {
1732 mesh_stats(mesh, "mesh_run: end");
1733 mesh_log_list(mesh);
1738 mesh_log_list(struct mesh_area* mesh)
1741 struct mesh_state* m;
1743 RBTREE_FOR(m, struct mesh_state*, &mesh->all) {
1744 snprintf(buf, sizeof(buf), "%d%s%s%s%s%s%s mod%d %s%s",
1745 num++, (m->s.is_priming)?"p":"", /* prime */
1746 (m->s.is_valrec)?"v":"", /* prime */
1747 (m->s.query_flags&BIT_RD)?"RD":"",
1748 (m->s.query_flags&BIT_CD)?"CD":"",
1749 (m->super_set.count==0)?"d":"", /* detached */
1750 (m->sub_set.count!=0)?"c":"", /* children */
1751 m->s.curmod, (m->reply_list)?"rep":"", /*hasreply*/
1752 (m->cb_list)?"cb":"" /* callbacks */
1754 log_query_info(VERB_ALGO, buf, &m->s.qinfo);
1759 mesh_stats(struct mesh_area* mesh, const char* str)
1761 verbose(VERB_DETAIL, "%s %u recursion states (%u with reply, "
1762 "%u detached), %u waiting replies, %u recursion replies "
1763 "sent, %d replies dropped, %d states jostled out",
1764 str, (unsigned)mesh->all.count,
1765 (unsigned)mesh->num_reply_states,
1766 (unsigned)mesh->num_detached_states,
1767 (unsigned)mesh->num_reply_addrs,
1768 (unsigned)mesh->replies_sent,
1769 (unsigned)mesh->stats_dropped,
1770 (unsigned)mesh->stats_jostled);
1771 if(mesh->replies_sent > 0) {
1773 timeval_divide(&avg, &mesh->replies_sum_wait,
1774 mesh->replies_sent);
1775 log_info("average recursion processing time "
1776 ARG_LL "d.%6.6d sec",
1777 (long long)avg.tv_sec, (int)avg.tv_usec);
1778 log_info("histogram of recursion processing times");
1779 timehist_log(mesh->histogram, "recursions");
1784 mesh_stats_clear(struct mesh_area* mesh)
1788 mesh->replies_sent = 0;
1789 mesh->replies_sum_wait.tv_sec = 0;
1790 mesh->replies_sum_wait.tv_usec = 0;
1791 mesh->stats_jostled = 0;
1792 mesh->stats_dropped = 0;
1793 timehist_clear(mesh->histogram);
1794 mesh->ans_secure = 0;
1795 mesh->ans_bogus = 0;
1796 mesh->ans_expired = 0;
1797 memset(&mesh->ans_rcode[0], 0, sizeof(size_t)*UB_STATS_RCODE_NUM);
1798 memset(&mesh->rpz_action[0], 0, sizeof(size_t)*UB_STATS_RPZ_ACTION_NUM);
1799 mesh->ans_nodata = 0;
1803 mesh_get_mem(struct mesh_area* mesh)
1805 struct mesh_state* m;
1806 size_t s = sizeof(*mesh) + sizeof(struct timehist) +
1807 sizeof(struct th_buck)*mesh->histogram->num +
1808 sizeof(sldns_buffer) + sldns_buffer_capacity(mesh->qbuf_bak);
1809 RBTREE_FOR(m, struct mesh_state*, &mesh->all) {
1810 /* all, including m itself allocated in qstate region */
1811 s += regional_get_mem(m->s.region);
1817 mesh_detect_cycle(struct module_qstate* qstate, struct query_info* qinfo,
1818 uint16_t flags, int prime, int valrec)
1820 struct mesh_area* mesh = qstate->env->mesh;
1821 struct mesh_state* dep_m = NULL;
1822 dep_m = mesh_area_find(mesh, NULL, qinfo, flags, prime, valrec);
1823 return mesh_detect_cycle_found(qstate, dep_m);
1826 void mesh_list_insert(struct mesh_state* m, struct mesh_state** fp,
1827 struct mesh_state** lp)
1829 /* insert as last element */
1838 void mesh_list_remove(struct mesh_state* m, struct mesh_state** fp,
1839 struct mesh_state** lp)
1842 m->next->prev = m->prev;
1845 m->prev->next = m->next;
1849 void mesh_state_remove_reply(struct mesh_area* mesh, struct mesh_state* m,
1850 struct comm_point* cp)
1852 struct mesh_reply* n, *prev = NULL;
1854 /* when in mesh_cleanup, it sets the reply_list to NULL, so that
1855 * there is no accounting twice */
1856 if(!n) return; /* nothing to remove, also no accounting needed */
1858 if(n->query_reply.c == cp) {
1860 if(prev) prev->next = n->next;
1861 else m->reply_list = n->next;
1862 /* delete it, but allocated in m region */
1863 log_assert(mesh->num_reply_addrs > 0);
1864 mesh->num_reply_addrs--;
1873 /* it was not detached (because it had a reply list), could be now */
1874 if(!m->reply_list && !m->cb_list
1875 && m->super_set.count == 0) {
1876 mesh->num_detached_states++;
1878 /* if not replies any more in mstate, it is no longer a reply_state */
1879 if(!m->reply_list && !m->cb_list) {
1880 log_assert(mesh->num_reply_states > 0);
1881 mesh->num_reply_states--;
1887 apply_respip_action(struct module_qstate* qstate,
1888 const struct query_info* qinfo, struct respip_client_info* cinfo,
1889 struct respip_action_info* actinfo, struct reply_info* rep,
1890 struct ub_packed_rrset_key** alias_rrset,
1891 struct reply_info** encode_repp, struct auth_zones* az)
1893 if(qinfo->qtype != LDNS_RR_TYPE_A &&
1894 qinfo->qtype != LDNS_RR_TYPE_AAAA &&
1895 qinfo->qtype != LDNS_RR_TYPE_ANY)
1898 if(!respip_rewrite_reply(qinfo, cinfo, rep, encode_repp, actinfo,
1899 alias_rrset, 0, qstate->region, az))
1902 /* xxx_deny actions mean dropping the reply, unless the original reply
1903 * was redirected to response-ip data. */
1904 if((actinfo->action == respip_deny ||
1905 actinfo->action == respip_inform_deny) &&
1906 *encode_repp == rep)
1907 *encode_repp = NULL;
1913 mesh_serve_expired_callback(void* arg)
1915 struct mesh_state* mstate = (struct mesh_state*) arg;
1916 struct module_qstate* qstate = &mstate->s;
1917 struct mesh_reply* r;
1918 struct mesh_area* mesh = qstate->env->mesh;
1919 struct dns_msg* msg;
1921 struct mesh_reply* prev = NULL;
1922 struct sldns_buffer* prev_buffer = NULL;
1923 struct sldns_buffer* r_buffer = NULL;
1924 struct reply_info* partial_rep = NULL;
1925 struct ub_packed_rrset_key* alias_rrset = NULL;
1926 struct reply_info* encode_rep = NULL;
1927 struct respip_action_info actinfo;
1928 struct query_info* lookup_qinfo = &qstate->qinfo;
1929 struct query_info qinfo_tmp;
1930 struct timeval tv = {0, 0};
1931 int must_validate = (!(qstate->query_flags&BIT_CD)
1932 || qstate->env->cfg->ignore_cd) && qstate->env->need_to_validate;
1933 if(!qstate->serve_expired_data) return;
1934 verbose(VERB_ALGO, "Serve expired: Trying to reply with expired data");
1935 comm_timer_delete(qstate->serve_expired_data->timer);
1936 qstate->serve_expired_data->timer = NULL;
1937 /* If is_drop or no_cache_lookup (modules that handle their own cache e.g.,
1938 * subnetmod) ignore stale data from the main cache. */
1939 if(qstate->no_cache_lookup || qstate->is_drop) {
1941 "Serve expired: Not allowed to look into cache for stale");
1944 /* The following while is used instead of the `goto lookup_cache`
1945 * like in the worker. */
1947 fptr_ok(fptr_whitelist_serve_expired_lookup(
1948 qstate->serve_expired_data->get_cached_answer));
1949 msg = (*qstate->serve_expired_data->get_cached_answer)(qstate,
1953 /* Reset these in case we pass a second time from here. */
1954 encode_rep = msg->rep;
1955 memset(&actinfo, 0, sizeof(actinfo));
1956 actinfo.action = respip_none;
1958 if((mesh->use_response_ip || mesh->use_rpz) &&
1959 !partial_rep && !apply_respip_action(qstate, &qstate->qinfo,
1960 qstate->client_info, &actinfo, msg->rep, &alias_rrset, &encode_rep,
1961 qstate->env->auth_zones)) {
1963 } else if(partial_rep &&
1964 !respip_merge_cname(partial_rep, &qstate->qinfo, msg->rep,
1965 qstate->client_info, must_validate, &encode_rep, qstate->region,
1966 qstate->env->auth_zones)) {
1969 if(!encode_rep || alias_rrset) {
1974 /* A partial CNAME chain is found. */
1975 partial_rep = encode_rep;
1978 /* We've found a partial reply ending with an
1979 * alias. Replace the lookup qinfo for the
1980 * alias target and lookup the cache again to
1981 * (possibly) complete the reply. As we're
1982 * passing the "base" reply, there will be no
1983 * more alias chasing. */
1985 memset(&qinfo_tmp, 0, sizeof(qinfo_tmp));
1986 get_cname_target(alias_rrset, &qinfo_tmp.qname,
1987 &qinfo_tmp.qname_len);
1988 if(!qinfo_tmp.qname) {
1989 log_err("Serve expired: unexpected: invalid answer alias");
1992 qinfo_tmp.qtype = qstate->qinfo.qtype;
1993 qinfo_tmp.qclass = qstate->qinfo.qclass;
1994 lookup_qinfo = &qinfo_tmp;
2000 if(verbosity >= VERB_ALGO)
2001 log_dns_msg("Serve expired lookup", &qstate->qinfo, msg->rep);
2003 for(r = mstate->reply_list; r; r = r->next) {
2006 /* If address info is returned, it means the action should be an
2007 * 'inform' variant and the information should be logged. */
2008 if(actinfo.addrinfo) {
2009 respip_inform_print(&actinfo, r->qname,
2010 qstate->qinfo.qtype, qstate->qinfo.qclass,
2011 r->local_alias, &r->query_reply);
2013 if(qstate->env->cfg->stat_extended && actinfo.rpz_used) {
2014 if(actinfo.rpz_disabled)
2015 qstate->env->mesh->rpz_action[RPZ_DISABLED_ACTION]++;
2016 if(actinfo.rpz_cname_override)
2017 qstate->env->mesh->rpz_action[RPZ_CNAME_OVERRIDE_ACTION]++;
2019 qstate->env->mesh->rpz_action[
2020 respip_action_to_rpz_action(actinfo.action)]++;
2024 r_buffer = r->query_reply.c->buffer;
2025 if(r->query_reply.c->tcp_req_info)
2026 r_buffer = r->query_reply.c->tcp_req_info->spool_buffer;
2027 mesh_send_reply(mstate, LDNS_RCODE_NOERROR, msg->rep,
2028 r, r_buffer, prev, prev_buffer);
2029 if(r->query_reply.c->tcp_req_info)
2030 tcp_req_info_remove_mesh_state(r->query_reply.c->tcp_req_info, mstate);
2032 prev_buffer = r_buffer;
2034 /* Account for each reply sent. */
2035 mesh->ans_expired++;
2038 if(mstate->reply_list) {
2039 mstate->reply_list = NULL;
2040 if(!mstate->reply_list && !mstate->cb_list) {
2041 log_assert(mesh->num_reply_states > 0);
2042 mesh->num_reply_states--;
2043 if(mstate->super_set.count == 0) {
2044 mesh->num_detached_states++;
2048 while((c = mstate->cb_list) != NULL) {
2049 /* take this cb off the list; so that the list can be
2050 * changed, eg. by adds from the callback routine */
2051 if(!mstate->reply_list && mstate->cb_list && !c->next) {
2052 /* was a reply state, not anymore */
2053 log_assert(qstate->env->mesh->num_reply_states > 0);
2054 qstate->env->mesh->num_reply_states--;
2056 mstate->cb_list = c->next;
2057 if(!mstate->reply_list && !mstate->cb_list &&
2058 mstate->super_set.count == 0)
2059 qstate->env->mesh->num_detached_states++;
2060 mesh_do_callback(mstate, LDNS_RCODE_NOERROR, msg->rep, c, &tv);