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"
50 #include "util/net_help.h"
51 #include "util/module.h"
52 #include "util/regional.h"
53 #include "util/data/msgencode.h"
54 #include "util/timehist.h"
55 #include "util/fptr_wlist.h"
56 #include "util/alloc.h"
57 #include "util/config_file.h"
58 #include "sldns/sbuffer.h"
59 #include "sldns/wire2str.h"
60 #include "services/localzone.h"
61 #include "util/data/dname.h"
63 /** subtract timers and the values do not overflow or become negative */
65 timeval_subtract(struct timeval* d, const struct timeval* end, const struct timeval* start)
68 time_t end_usec = end->tv_usec;
69 d->tv_sec = end->tv_sec - start->tv_sec;
70 if(end_usec < start->tv_usec) {
74 d->tv_usec = end_usec - start->tv_usec;
78 /** add timers and the values do not overflow or become negative */
80 timeval_add(struct timeval* d, const struct timeval* add)
83 d->tv_sec += add->tv_sec;
84 d->tv_usec += add->tv_usec;
85 if(d->tv_usec > 1000000 ) {
86 d->tv_usec -= 1000000;
92 /** divide sum of timers to get average */
94 timeval_divide(struct timeval* avg, const struct timeval* sum, size_t d)
103 avg->tv_sec = sum->tv_sec / d;
104 avg->tv_usec = sum->tv_usec / d;
105 /* handle fraction from seconds divide */
106 leftover = sum->tv_sec - avg->tv_sec*d;
107 avg->tv_usec += (leftover*1000000)/d;
111 /** histogram compare of time values */
113 timeval_smaller(const struct timeval* x, const struct timeval* y)
116 if(x->tv_sec < y->tv_sec)
118 else if(x->tv_sec == y->tv_sec) {
119 if(x->tv_usec <= y->tv_usec)
128 mesh_state_compare(const void* ap, const void* bp)
130 struct mesh_state* a = (struct mesh_state*)ap;
131 struct mesh_state* b = (struct mesh_state*)bp;
133 if(a->unique < b->unique)
135 if(a->unique > b->unique)
138 if(a->s.is_priming && !b->s.is_priming)
140 if(!a->s.is_priming && b->s.is_priming)
143 if(a->s.is_valrec && !b->s.is_valrec)
145 if(!a->s.is_valrec && b->s.is_valrec)
148 if((a->s.query_flags&BIT_RD) && !(b->s.query_flags&BIT_RD))
150 if(!(a->s.query_flags&BIT_RD) && (b->s.query_flags&BIT_RD))
153 if((a->s.query_flags&BIT_CD) && !(b->s.query_flags&BIT_CD))
155 if(!(a->s.query_flags&BIT_CD) && (b->s.query_flags&BIT_CD))
158 return query_info_compare(&a->s.qinfo, &b->s.qinfo);
162 mesh_state_ref_compare(const void* ap, const void* bp)
164 struct mesh_state_ref* a = (struct mesh_state_ref*)ap;
165 struct mesh_state_ref* b = (struct mesh_state_ref*)bp;
166 return mesh_state_compare(a->s, b->s);
170 mesh_create(struct module_stack* stack, struct module_env* env)
172 struct mesh_area* mesh = calloc(1, sizeof(struct mesh_area));
174 log_err("mesh area alloc: out of memory");
177 mesh->histogram = timehist_setup();
178 mesh->qbuf_bak = sldns_buffer_new(env->cfg->msg_buffer_size);
179 if(!mesh->histogram || !mesh->qbuf_bak) {
181 log_err("mesh area alloc: out of memory");
186 rbtree_init(&mesh->run, &mesh_state_compare);
187 rbtree_init(&mesh->all, &mesh_state_compare);
188 mesh->num_reply_addrs = 0;
189 mesh->num_reply_states = 0;
190 mesh->num_detached_states = 0;
191 mesh->num_forever_states = 0;
192 mesh->stats_jostled = 0;
193 mesh->stats_dropped = 0;
194 mesh->max_reply_states = env->cfg->num_queries_per_thread;
195 mesh->max_forever_states = (mesh->max_reply_states+1)/2;
197 mesh->jostle_max.tv_sec = (time_t)(env->cfg->jostle_time / 1000);
198 mesh->jostle_max.tv_usec = (time_t)((env->cfg->jostle_time % 1000)
204 /** help mesh delete delete mesh states */
206 mesh_delete_helper(rbnode_t* n)
208 struct mesh_state* mstate = (struct mesh_state*)n->key;
209 /* perform a full delete, not only 'cleanup' routine,
210 * because other callbacks expect a clean state in the mesh.
211 * For 're-entrant' calls */
212 mesh_state_delete(&mstate->s);
213 /* but because these delete the items from the tree, postorder
214 * traversal and rbtree rebalancing do not work together */
218 mesh_delete(struct mesh_area* mesh)
222 /* free all query states */
223 while(mesh->all.count)
224 mesh_delete_helper(mesh->all.root);
225 timehist_delete(mesh->histogram);
226 sldns_buffer_free(mesh->qbuf_bak);
231 mesh_delete_all(struct mesh_area* mesh)
233 /* free all query states */
234 while(mesh->all.count)
235 mesh_delete_helper(mesh->all.root);
236 mesh->stats_dropped += mesh->num_reply_addrs;
237 /* clear mesh area references */
238 rbtree_init(&mesh->run, &mesh_state_compare);
239 rbtree_init(&mesh->all, &mesh_state_compare);
240 mesh->num_reply_addrs = 0;
241 mesh->num_reply_states = 0;
242 mesh->num_detached_states = 0;
243 mesh->num_forever_states = 0;
244 mesh->forever_first = NULL;
245 mesh->forever_last = NULL;
246 mesh->jostle_first = NULL;
247 mesh->jostle_last = NULL;
250 int mesh_make_new_space(struct mesh_area* mesh, sldns_buffer* qbuf)
252 struct mesh_state* m = mesh->jostle_first;
253 /* free space is available */
254 if(mesh->num_reply_states < mesh->max_reply_states)
256 /* try to kick out a jostle-list item */
257 if(m && m->reply_list && m->list_select == mesh_jostle_list) {
260 timeval_subtract(&age, mesh->env->now_tv,
261 &m->reply_list->start_time);
262 if(timeval_smaller(&mesh->jostle_max, &age)) {
264 log_nametypeclass(VERB_ALGO, "query jostled out to "
265 "make space for a new one",
266 m->s.qinfo.qname, m->s.qinfo.qtype,
268 /* backup the query */
269 if(qbuf) sldns_buffer_copy(mesh->qbuf_bak, qbuf);
271 if(m->super_set.count > 0) {
272 verbose(VERB_ALGO, "notify supers of failure");
273 m->s.return_msg = NULL;
274 m->s.return_rcode = LDNS_RCODE_SERVFAIL;
275 mesh_walk_supers(mesh, m);
277 mesh->stats_jostled ++;
278 mesh_state_delete(&m->s);
279 /* restore the query - note that the qinfo ptr to
280 * the querybuffer is then correct again. */
281 if(qbuf) sldns_buffer_copy(qbuf, mesh->qbuf_bak);
285 /* no space for new item */
289 void mesh_new_client(struct mesh_area* mesh, struct query_info* qinfo,
290 uint16_t qflags, struct edns_data* edns, struct comm_reply* rep,
293 struct mesh_state* s = NULL;
294 int unique = edns_unique_mesh_state(edns->opt_list, mesh->env);
295 int was_detached = 0;
299 s = mesh_area_find(mesh, qinfo, qflags&(BIT_RD|BIT_CD), 0, 0);
300 /* does this create a new reply state? */
301 if(!s || s->list_select == mesh_no_list) {
302 if(!mesh_make_new_space(mesh, rep->c->buffer)) {
303 verbose(VERB_ALGO, "Too many queries. dropping "
305 comm_point_drop_reply(rep);
306 mesh->stats_dropped ++;
309 /* for this new reply state, the reply address is free,
310 * so the limit of reply addresses does not stop reply states*/
312 /* protect our memory usage from storing reply addresses */
313 if(mesh->num_reply_addrs > mesh->max_reply_states*16) {
314 verbose(VERB_ALGO, "Too many requests queued. "
315 "dropping incoming query.");
316 mesh->stats_dropped++;
317 comm_point_drop_reply(rep);
321 /* see if it already exists, if not, create one */
326 s = mesh_state_create(mesh->env, qinfo, qflags&(BIT_RD|BIT_CD), 0, 0);
328 log_err("mesh_state_create: out of memory; SERVFAIL");
329 if(!inplace_cb_reply_servfail_call(mesh->env, qinfo, NULL, NULL,
330 LDNS_RCODE_SERVFAIL, edns, mesh->env->scratch))
331 edns->opt_list = NULL;
332 error_encode(rep->c->buffer, LDNS_RCODE_SERVFAIL,
333 qinfo, qid, qflags, edns);
334 comm_point_send_reply(rep);
338 mesh_state_make_unique(s);
339 /* copy the edns options we got from the front */
341 s->s.edns_opts_front_in = edns_opt_copy_region(edns->opt_list,
343 if(!s->s.edns_opts_front_in) {
344 log_err("mesh_state_create: out of memory; SERVFAIL");
345 if(!inplace_cb_reply_servfail_call(mesh->env, qinfo, NULL,
346 NULL, LDNS_RCODE_SERVFAIL, edns, mesh->env->scratch))
347 edns->opt_list = NULL;
348 error_encode(rep->c->buffer, LDNS_RCODE_SERVFAIL,
349 qinfo, qid, qflags, edns);
350 comm_point_send_reply(rep);
360 rbtree_insert(&mesh->all, &s->node);
361 log_assert(n != NULL);
362 /* set detached (it is now) */
363 mesh->num_detached_states++;
366 if(!s->reply_list && !s->cb_list && s->super_set.count == 0)
368 if(!s->reply_list && !s->cb_list)
371 if(!mesh_state_add_reply(s, edns, rep, qid, qflags, qinfo)) {
372 log_err("mesh_new_client: out of memory; SERVFAIL");
373 if(!inplace_cb_reply_servfail_call(mesh->env, qinfo, &s->s,
374 NULL, LDNS_RCODE_SERVFAIL, edns, mesh->env->scratch))
375 edns->opt_list = NULL;
376 error_encode(rep->c->buffer, LDNS_RCODE_SERVFAIL,
377 qinfo, qid, qflags, edns);
378 comm_point_send_reply(rep);
380 mesh_state_delete(&s->s);
383 /* update statistics */
385 log_assert(mesh->num_detached_states > 0);
386 mesh->num_detached_states--;
389 mesh->num_reply_states ++;
391 mesh->num_reply_addrs++;
392 if(s->list_select == mesh_no_list) {
393 /* move to either the forever or the jostle_list */
394 if(mesh->num_forever_states < mesh->max_forever_states) {
395 mesh->num_forever_states ++;
396 mesh_list_insert(s, &mesh->forever_first,
397 &mesh->forever_last);
398 s->list_select = mesh_forever_list;
400 mesh_list_insert(s, &mesh->jostle_first,
402 s->list_select = mesh_jostle_list;
406 mesh_run(mesh, s, module_event_new, NULL);
410 mesh_new_callback(struct mesh_area* mesh, struct query_info* qinfo,
411 uint16_t qflags, struct edns_data* edns, sldns_buffer* buf,
412 uint16_t qid, mesh_cb_func_t cb, void* cb_arg)
414 struct mesh_state* s = NULL;
415 int unique = edns_unique_mesh_state(edns->opt_list, mesh->env);
416 int was_detached = 0;
420 s = mesh_area_find(mesh, qinfo, qflags&(BIT_RD|BIT_CD), 0, 0);
421 /* there are no limits on the number of callbacks */
423 /* see if it already exists, if not, create one */
428 s = mesh_state_create(mesh->env, qinfo, qflags&(BIT_RD|BIT_CD), 0, 0);
433 mesh_state_make_unique(s);
435 s->s.edns_opts_front_in = edns_opt_copy_region(edns->opt_list,
437 if(!s->s.edns_opts_front_in) {
446 rbtree_insert(&mesh->all, &s->node);
447 log_assert(n != NULL);
448 /* set detached (it is now) */
449 mesh->num_detached_states++;
452 if(!s->reply_list && !s->cb_list && s->super_set.count == 0)
454 if(!s->reply_list && !s->cb_list)
457 if(!mesh_state_add_cb(s, edns, buf, cb, cb_arg, qid, qflags)) {
459 mesh_state_delete(&s->s);
462 /* update statistics */
464 log_assert(mesh->num_detached_states > 0);
465 mesh->num_detached_states--;
468 mesh->num_reply_states ++;
470 mesh->num_reply_addrs++;
472 mesh_run(mesh, s, module_event_new, NULL);
476 void mesh_new_prefetch(struct mesh_area* mesh, struct query_info* qinfo,
477 uint16_t qflags, time_t leeway)
479 struct mesh_state* s = mesh_area_find(mesh, qinfo, qflags&(BIT_RD|BIT_CD),
484 /* already exists, and for a different purpose perhaps.
485 * if mesh_no_list, keep it that way. */
487 /* make it ignore the cache from now on */
489 sock_list_insert(&s->s.blacklist, NULL, 0, s->s.region);
490 if(s->s.prefetch_leeway < leeway)
491 s->s.prefetch_leeway = leeway;
494 if(!mesh_make_new_space(mesh, NULL)) {
495 verbose(VERB_ALGO, "Too many queries. dropped prefetch.");
496 mesh->stats_dropped ++;
500 s = mesh_state_create(mesh->env, qinfo, qflags&(BIT_RD|BIT_CD), 0, 0);
502 log_err("prefetch mesh_state_create: out of memory");
510 rbtree_insert(&mesh->all, &s->node);
511 log_assert(n != NULL);
512 /* set detached (it is now) */
513 mesh->num_detached_states++;
514 /* make it ignore the cache */
515 sock_list_insert(&s->s.blacklist, NULL, 0, s->s.region);
516 s->s.prefetch_leeway = leeway;
518 if(s->list_select == mesh_no_list) {
519 /* move to either the forever or the jostle_list */
520 if(mesh->num_forever_states < mesh->max_forever_states) {
521 mesh->num_forever_states ++;
522 mesh_list_insert(s, &mesh->forever_first,
523 &mesh->forever_last);
524 s->list_select = mesh_forever_list;
526 mesh_list_insert(s, &mesh->jostle_first,
528 s->list_select = mesh_jostle_list;
531 mesh_run(mesh, s, module_event_new, NULL);
534 void mesh_report_reply(struct mesh_area* mesh, struct outbound_entry* e,
535 struct comm_reply* reply, int what)
537 enum module_ev event = module_event_reply;
538 e->qstate->reply = reply;
539 if(what != NETEVENT_NOERROR) {
540 event = module_event_noreply;
541 if(what == NETEVENT_CAPSFAIL)
542 event = module_event_capsfail;
544 mesh_run(mesh, e->qstate->mesh_info, event, e);
548 mesh_state_create(struct module_env* env, struct query_info* qinfo,
549 uint16_t qflags, int prime, int valrec)
551 struct regional* region = alloc_reg_obtain(env->alloc);
552 struct mesh_state* mstate;
556 mstate = (struct mesh_state*)regional_alloc(region,
557 sizeof(struct mesh_state));
559 alloc_reg_release(env->alloc, region);
562 memset(mstate, 0, sizeof(*mstate));
563 mstate->node = *RBTREE_NULL;
564 mstate->run_node = *RBTREE_NULL;
565 mstate->node.key = mstate;
566 mstate->run_node.key = mstate;
567 mstate->reply_list = NULL;
568 mstate->list_select = mesh_no_list;
569 mstate->replies_sent = 0;
570 rbtree_init(&mstate->super_set, &mesh_state_ref_compare);
571 rbtree_init(&mstate->sub_set, &mesh_state_ref_compare);
572 mstate->num_activated = 0;
573 mstate->unique = NULL;
574 /* init module qstate */
575 mstate->s.qinfo.qtype = qinfo->qtype;
576 mstate->s.qinfo.qclass = qinfo->qclass;
577 mstate->s.qinfo.local_alias = NULL;
578 mstate->s.qinfo.qname_len = qinfo->qname_len;
579 mstate->s.qinfo.qname = regional_alloc_init(region, qinfo->qname,
581 if(!mstate->s.qinfo.qname) {
582 alloc_reg_release(env->alloc, region);
585 /* remove all weird bits from qflags */
586 mstate->s.query_flags = (qflags & (BIT_RD|BIT_CD));
587 mstate->s.is_priming = prime;
588 mstate->s.is_valrec = valrec;
589 mstate->s.reply = NULL;
590 mstate->s.region = region;
591 mstate->s.curmod = 0;
592 mstate->s.return_msg = 0;
593 mstate->s.return_rcode = LDNS_RCODE_NOERROR;
595 mstate->s.mesh_info = mstate;
596 mstate->s.prefetch_leeway = 0;
597 mstate->s.no_cache_lookup = 0;
598 mstate->s.no_cache_store = 0;
600 for(i=0; i<env->mesh->mods.num; i++) {
601 mstate->s.minfo[i] = NULL;
602 mstate->s.ext_state[i] = module_state_initial;
604 /* init edns option lists */
605 mstate->s.edns_opts_front_in = NULL;
606 mstate->s.edns_opts_back_out = NULL;
607 mstate->s.edns_opts_back_in = NULL;
608 mstate->s.edns_opts_front_out = NULL;
614 mesh_state_is_unique(struct mesh_state* mstate)
616 return mstate->unique != NULL;
620 mesh_state_make_unique(struct mesh_state* mstate)
622 mstate->unique = mstate;
626 mesh_state_cleanup(struct mesh_state* mstate)
628 struct mesh_area* mesh;
632 mesh = mstate->s.env->mesh;
633 /* drop unsent replies */
634 if(!mstate->replies_sent) {
635 struct mesh_reply* rep;
637 for(rep=mstate->reply_list; rep; rep=rep->next) {
638 comm_point_drop_reply(&rep->query_reply);
639 mesh->num_reply_addrs--;
641 for(cb=mstate->cb_list; cb; cb=cb->next) {
642 fptr_ok(fptr_whitelist_mesh_cb(cb->cb));
643 (*cb->cb)(cb->cb_arg, LDNS_RCODE_SERVFAIL, NULL,
644 sec_status_unchecked, NULL);
645 mesh->num_reply_addrs--;
649 /* de-init modules */
650 for(i=0; i<mesh->mods.num; i++) {
651 fptr_ok(fptr_whitelist_mod_clear(mesh->mods.mod[i]->clear));
652 (*mesh->mods.mod[i]->clear)(&mstate->s, i);
653 mstate->s.minfo[i] = NULL;
654 mstate->s.ext_state[i] = module_finished;
656 alloc_reg_release(mstate->s.env->alloc, mstate->s.region);
660 mesh_state_delete(struct module_qstate* qstate)
662 struct mesh_area* mesh;
663 struct mesh_state_ref* super, ref;
664 struct mesh_state* mstate;
667 mstate = qstate->mesh_info;
668 mesh = mstate->s.env->mesh;
669 mesh_detach_subs(&mstate->s);
670 if(mstate->list_select == mesh_forever_list) {
671 mesh->num_forever_states --;
672 mesh_list_remove(mstate, &mesh->forever_first,
673 &mesh->forever_last);
674 } else if(mstate->list_select == mesh_jostle_list) {
675 mesh_list_remove(mstate, &mesh->jostle_first,
678 if(!mstate->reply_list && !mstate->cb_list
679 && mstate->super_set.count == 0) {
680 log_assert(mesh->num_detached_states > 0);
681 mesh->num_detached_states--;
683 if(mstate->reply_list || mstate->cb_list) {
684 log_assert(mesh->num_reply_states > 0);
685 mesh->num_reply_states--;
689 RBTREE_FOR(super, struct mesh_state_ref*, &mstate->super_set) {
690 (void)rbtree_delete(&super->s->sub_set, &ref);
692 (void)rbtree_delete(&mesh->run, mstate);
693 (void)rbtree_delete(&mesh->all, mstate);
694 mesh_state_cleanup(mstate);
697 /** helper recursive rbtree find routine */
699 find_in_subsub(struct mesh_state* m, struct mesh_state* tofind, size_t *c)
701 struct mesh_state_ref* r;
702 if((*c)++ > MESH_MAX_SUBSUB)
704 RBTREE_FOR(r, struct mesh_state_ref*, &m->sub_set) {
705 if(r->s == tofind || find_in_subsub(r->s, tofind, c))
711 /** find cycle for already looked up mesh_state */
713 mesh_detect_cycle_found(struct module_qstate* qstate, struct mesh_state* dep_m)
715 struct mesh_state* cyc_m = qstate->mesh_info;
719 if(dep_m == cyc_m || find_in_subsub(dep_m, cyc_m, &counter)) {
720 if(counter > MESH_MAX_SUBSUB)
727 void mesh_detach_subs(struct module_qstate* qstate)
729 struct mesh_area* mesh = qstate->env->mesh;
730 struct mesh_state_ref* ref, lookup;
734 lookup.node.key = &lookup;
735 lookup.s = qstate->mesh_info;
736 RBTREE_FOR(ref, struct mesh_state_ref*, &qstate->mesh_info->sub_set) {
742 rbtree_delete(&ref->s->super_set, &lookup);
743 log_assert(n != NULL); /* must have been present */
744 if(!ref->s->reply_list && !ref->s->cb_list
745 && ref->s->super_set.count == 0) {
746 mesh->num_detached_states++;
747 log_assert(mesh->num_detached_states +
748 mesh->num_reply_states <= mesh->all.count);
751 rbtree_init(&qstate->mesh_info->sub_set, &mesh_state_ref_compare);
754 int mesh_attach_sub(struct module_qstate* qstate, struct query_info* qinfo,
755 uint16_t qflags, int prime, int valrec, struct module_qstate** newq)
757 /* find it, if not, create it */
758 struct mesh_area* mesh = qstate->env->mesh;
759 struct mesh_state* sub = mesh_area_find(mesh, qinfo, qflags, prime, valrec);
761 if(mesh_detect_cycle_found(qstate, sub)) {
762 verbose(VERB_ALGO, "attach failed, cycle detected");
769 /* create a new one */
770 sub = mesh_state_create(qstate->env, qinfo, qflags, prime, valrec);
772 log_err("mesh_attach_sub: out of memory");
780 rbtree_insert(&mesh->all, &sub->node);
781 log_assert(n != NULL);
782 /* set detached (it is now) */
783 mesh->num_detached_states++;
784 /* set new query state to run */
790 rbtree_insert(&mesh->run, &sub->run_node);
791 log_assert(n != NULL);
795 was_detached = (sub->super_set.count == 0);
796 if(!mesh_state_attachment(qstate->mesh_info, sub))
798 /* if it was a duplicate attachment, the count was not zero before */
799 if(!sub->reply_list && !sub->cb_list && was_detached &&
800 sub->super_set.count == 1) {
801 /* it used to be detached, before this one got added */
802 log_assert(mesh->num_detached_states > 0);
803 mesh->num_detached_states--;
805 /* *newq will be run when inited after the current module stops */
809 int mesh_state_attachment(struct mesh_state* super, struct mesh_state* sub)
814 struct mesh_state_ref* subref; /* points to sub, inserted in super */
815 struct mesh_state_ref* superref; /* points to super, inserted in sub */
816 if( !(subref = regional_alloc(super->s.region,
817 sizeof(struct mesh_state_ref))) ||
818 !(superref = regional_alloc(sub->s.region,
819 sizeof(struct mesh_state_ref))) ) {
820 log_err("mesh_state_attachment: out of memory");
823 superref->node.key = superref;
825 subref->node.key = subref;
827 if(!rbtree_insert(&sub->super_set, &superref->node)) {
828 /* this should not happen, iterator and validator do not
829 * attach subqueries that are identical. */
830 /* already attached, we are done, nothing todo.
831 * since superref and subref already allocated in region,
832 * we cannot free them */
840 rbtree_insert(&super->sub_set, &subref->node);
841 log_assert(n != NULL); /* we checked above if statement, the reverse
842 administration should not fail now, unless they are out of sync */
847 * callback results to mesh cb entry
848 * @param m: mesh state to send it for.
849 * @param rcode: if not 0, error code.
850 * @param rep: reply to send (or NULL if rcode is set).
851 * @param r: callback entry
854 mesh_do_callback(struct mesh_state* m, int rcode, struct reply_info* rep,
859 /* bogus messages are not made into servfail, sec_status passed
860 * to the callback function */
861 if(rep && rep->security == sec_status_secure)
864 if(!rep && rcode == LDNS_RCODE_NOERROR)
865 rcode = LDNS_RCODE_SERVFAIL;
866 if(!rcode && rep->security == sec_status_bogus) {
867 if(!(reason = errinf_to_str(&m->s)))
868 rcode = LDNS_RCODE_SERVFAIL;
872 if(rcode == LDNS_RCODE_SERVFAIL) {
873 if(!inplace_cb_reply_servfail_call(m->s.env, &m->s.qinfo, &m->s,
874 rep, rcode, &r->edns, m->s.region))
875 r->edns.opt_list = NULL;
877 if(!inplace_cb_reply_call(m->s.env, &m->s.qinfo, &m->s, rep, rcode,
878 &r->edns, m->s.region))
879 r->edns.opt_list = NULL;
881 fptr_ok(fptr_whitelist_mesh_cb(r->cb));
882 (*r->cb)(r->cb_arg, rcode, r->buf, sec_status_unchecked, NULL);
884 size_t udp_size = r->edns.udp_size;
885 sldns_buffer_clear(r->buf);
886 r->edns.edns_version = EDNS_ADVERTISED_VERSION;
887 r->edns.udp_size = EDNS_ADVERTISED_SIZE;
888 r->edns.ext_rcode = 0;
889 r->edns.bits &= EDNS_DO;
891 if(!inplace_cb_reply_call(m->s.env, &m->s.qinfo, &m->s, rep,
892 LDNS_RCODE_NOERROR, &r->edns, m->s.region) ||
893 !reply_info_answer_encode(&m->s.qinfo, rep, r->qid,
894 r->qflags, r->buf, 0, 1,
895 m->s.env->scratch, udp_size, &r->edns,
896 (int)(r->edns.bits & EDNS_DO), secure))
898 fptr_ok(fptr_whitelist_mesh_cb(r->cb));
899 (*r->cb)(r->cb_arg, LDNS_RCODE_SERVFAIL, r->buf,
900 sec_status_unchecked, NULL);
902 fptr_ok(fptr_whitelist_mesh_cb(r->cb));
903 (*r->cb)(r->cb_arg, LDNS_RCODE_NOERROR, r->buf,
904 rep->security, reason);
908 m->s.env->mesh->num_reply_addrs--;
912 * Send reply to mesh reply entry
913 * @param m: mesh state to send it for.
914 * @param rcode: if not 0, error code.
915 * @param rep: reply to send (or NULL if rcode is set).
916 * @param r: reply entry
917 * @param prev: previous reply, already has its answer encoded in buffer.
920 mesh_send_reply(struct mesh_state* m, int rcode, struct reply_info* rep,
921 struct mesh_reply* r, struct mesh_reply* prev)
923 struct timeval end_time;
924 struct timeval duration;
926 /* Copy the client's EDNS for later restore, to make sure the edns
927 * compare is with the correct edns options. */
928 struct edns_data edns_bak = r->edns;
929 /* examine security status */
930 if(m->s.env->need_to_validate && (!(r->qflags&BIT_CD) ||
931 m->s.env->cfg->ignore_cd) && rep &&
932 rep->security <= sec_status_bogus) {
933 rcode = LDNS_RCODE_SERVFAIL;
934 if(m->s.env->cfg->stat_extended)
935 m->s.env->mesh->ans_bogus++;
937 if(rep && rep->security == sec_status_secure)
940 if(!rep && rcode == LDNS_RCODE_NOERROR)
941 rcode = LDNS_RCODE_SERVFAIL;
943 /* We don't reuse the encoded answer if either the previous or current
944 * response has a local alias. We could compare the alias records
945 * and still reuse the previous answer if they are the same, but that
946 * would be complicated and error prone for the relatively minor case.
947 * So we err on the side of safety. */
948 if(prev && prev->qflags == r->qflags &&
949 !prev->local_alias && !r->local_alias &&
950 prev->edns.edns_present == r->edns.edns_present &&
951 prev->edns.bits == r->edns.bits &&
952 prev->edns.udp_size == r->edns.udp_size &&
953 edns_opt_list_compare(prev->edns.opt_list, r->edns.opt_list)
955 /* if the previous reply is identical to this one, fix ID */
956 if(prev->query_reply.c->buffer != r->query_reply.c->buffer)
957 sldns_buffer_copy(r->query_reply.c->buffer,
958 prev->query_reply.c->buffer);
959 sldns_buffer_write_at(r->query_reply.c->buffer, 0,
960 &r->qid, sizeof(uint16_t));
961 sldns_buffer_write_at(r->query_reply.c->buffer, 12,
962 r->qname, m->s.qinfo.qname_len);
963 comm_point_send_reply(&r->query_reply);
965 m->s.qinfo.qname = r->qname;
966 m->s.qinfo.local_alias = r->local_alias;
967 if(rcode == LDNS_RCODE_SERVFAIL) {
968 if(!inplace_cb_reply_servfail_call(m->s.env, &m->s.qinfo, &m->s,
969 rep, rcode, &r->edns, m->s.region))
970 r->edns.opt_list = NULL;
972 if(!inplace_cb_reply_call(m->s.env, &m->s.qinfo, &m->s, rep, rcode,
973 &r->edns, m->s.region))
974 r->edns.opt_list = NULL;
976 error_encode(r->query_reply.c->buffer, rcode, &m->s.qinfo,
977 r->qid, r->qflags, &r->edns);
978 comm_point_send_reply(&r->query_reply);
980 size_t udp_size = r->edns.udp_size;
981 r->edns.edns_version = EDNS_ADVERTISED_VERSION;
982 r->edns.udp_size = EDNS_ADVERTISED_SIZE;
983 r->edns.ext_rcode = 0;
984 r->edns.bits &= EDNS_DO;
985 m->s.qinfo.qname = r->qname;
986 m->s.qinfo.local_alias = r->local_alias;
987 if(!inplace_cb_reply_call(m->s.env, &m->s.qinfo, &m->s, rep,
988 LDNS_RCODE_NOERROR, &r->edns, m->s.region) ||
989 !reply_info_answer_encode(&m->s.qinfo, rep, r->qid,
990 r->qflags, r->query_reply.c->buffer, 0, 1,
991 m->s.env->scratch, udp_size, &r->edns,
992 (int)(r->edns.bits & EDNS_DO), secure))
994 if(!inplace_cb_reply_servfail_call(m->s.env, &m->s.qinfo, &m->s,
995 rep, LDNS_RCODE_SERVFAIL, &r->edns, m->s.region))
996 r->edns.opt_list = NULL;
997 error_encode(r->query_reply.c->buffer,
998 LDNS_RCODE_SERVFAIL, &m->s.qinfo, r->qid,
999 r->qflags, &r->edns);
1002 comm_point_send_reply(&r->query_reply);
1005 m->s.env->mesh->num_reply_addrs--;
1006 end_time = *m->s.env->now_tv;
1007 timeval_subtract(&duration, &end_time, &r->start_time);
1008 verbose(VERB_ALGO, "query took " ARG_LL "d.%6.6d sec",
1009 (long long)duration.tv_sec, (int)duration.tv_usec);
1010 m->s.env->mesh->replies_sent++;
1011 timeval_add(&m->s.env->mesh->replies_sum_wait, &duration);
1012 timehist_insert(m->s.env->mesh->histogram, &duration);
1013 if(m->s.env->cfg->stat_extended) {
1014 uint16_t rc = FLAGS_GET_RCODE(sldns_buffer_read_u16_at(r->
1015 query_reply.c->buffer, 2));
1016 if(secure) m->s.env->mesh->ans_secure++;
1017 m->s.env->mesh->ans_rcode[ rc ] ++;
1018 if(rc == 0 && LDNS_ANCOUNT(sldns_buffer_begin(r->
1019 query_reply.c->buffer)) == 0)
1020 m->s.env->mesh->ans_nodata++;
1024 void mesh_query_done(struct mesh_state* mstate)
1026 struct mesh_reply* r;
1027 struct mesh_reply* prev = NULL;
1029 struct reply_info* rep = (mstate->s.return_msg?
1030 mstate->s.return_msg->rep:NULL);
1031 for(r = mstate->reply_list; r; r = r->next) {
1032 mesh_send_reply(mstate, mstate->s.return_rcode, rep, r, prev);
1035 mstate->replies_sent = 1;
1036 for(c = mstate->cb_list; c; c = c->next) {
1037 mesh_do_callback(mstate, mstate->s.return_rcode, rep, c);
1041 void mesh_walk_supers(struct mesh_area* mesh, struct mesh_state* mstate)
1043 struct mesh_state_ref* ref;
1044 RBTREE_FOR(ref, struct mesh_state_ref*, &mstate->super_set)
1046 /* make super runnable */
1047 (void)rbtree_insert(&mesh->run, &ref->s->run_node);
1048 /* callback the function to inform super of result */
1049 fptr_ok(fptr_whitelist_mod_inform_super(
1050 mesh->mods.mod[ref->s->s.curmod]->inform_super));
1051 (*mesh->mods.mod[ref->s->s.curmod]->inform_super)(&mstate->s,
1052 ref->s->s.curmod, &ref->s->s);
1056 struct mesh_state* mesh_area_find(struct mesh_area* mesh,
1057 struct query_info* qinfo, uint16_t qflags, int prime, int valrec)
1059 struct mesh_state key;
1060 struct mesh_state* result;
1062 key.node.key = &key;
1063 key.s.is_priming = prime;
1064 key.s.is_valrec = valrec;
1065 key.s.qinfo = *qinfo;
1066 key.s.query_flags = qflags;
1067 /* We are searching for a similar mesh state when we DO want to
1068 * aggregate the state. Thus unique is set to NULL. (default when we
1069 * desire aggregation).*/
1072 result = (struct mesh_state*)rbtree_search(&mesh->all, &key);
1076 int mesh_state_add_cb(struct mesh_state* s, struct edns_data* edns,
1077 sldns_buffer* buf, mesh_cb_func_t cb, void* cb_arg,
1078 uint16_t qid, uint16_t qflags)
1080 struct mesh_cb* r = regional_alloc(s->s.region,
1081 sizeof(struct mesh_cb));
1085 log_assert(fptr_whitelist_mesh_cb(cb)); /* early failure ifmissing*/
1089 if(edns->opt_list) {
1090 r->edns.opt_list = edns_opt_copy_region(edns->opt_list,
1092 if(!r->edns.opt_list)
1097 r->next = s->cb_list;
1103 int mesh_state_add_reply(struct mesh_state* s, struct edns_data* edns,
1104 struct comm_reply* rep, uint16_t qid, uint16_t qflags,
1105 const struct query_info* qinfo)
1107 struct mesh_reply* r = regional_alloc(s->s.region,
1108 sizeof(struct mesh_reply));
1111 r->query_reply = *rep;
1113 if(edns->opt_list) {
1114 r->edns.opt_list = edns_opt_copy_region(edns->opt_list,
1116 if(!r->edns.opt_list)
1121 r->start_time = *s->s.env->now_tv;
1122 r->next = s->reply_list;
1123 r->qname = regional_alloc_init(s->s.region, qinfo->qname,
1124 s->s.qinfo.qname_len);
1128 /* Data related to local alias stored in 'qinfo' (if any) is ephemeral
1129 * and can be different for different original queries (even if the
1130 * replaced query name is the same). So we need to make a deep copy
1131 * and store the copy for each reply info. */
1132 if(qinfo->local_alias) {
1133 struct packed_rrset_data* d;
1134 struct packed_rrset_data* dsrc;
1135 r->local_alias = regional_alloc_zero(s->s.region,
1136 sizeof(*qinfo->local_alias));
1139 r->local_alias->rrset = regional_alloc_init(s->s.region,
1140 qinfo->local_alias->rrset,
1141 sizeof(*qinfo->local_alias->rrset));
1142 if(!r->local_alias->rrset)
1144 dsrc = qinfo->local_alias->rrset->entry.data;
1146 /* In the current implementation, a local alias must be
1147 * a single CNAME RR (see worker_handle_request()). */
1148 log_assert(!qinfo->local_alias->next && dsrc->count == 1 &&
1149 qinfo->local_alias->rrset->rk.type ==
1150 htons(LDNS_RR_TYPE_CNAME));
1151 /* Technically, we should make a local copy for the owner
1152 * name of the RRset, but in the case of the first (and
1153 * currently only) local alias RRset, the owner name should
1154 * point to the qname of the corresponding query, which should
1155 * be valid throughout the lifetime of this mesh_reply. So
1156 * we can skip copying. */
1157 log_assert(qinfo->local_alias->rrset->rk.dname ==
1158 sldns_buffer_at(rep->c->buffer, LDNS_HEADER_SIZE));
1160 d = regional_alloc_init(s->s.region, dsrc,
1161 sizeof(struct packed_rrset_data)
1162 + sizeof(size_t) + sizeof(uint8_t*) + sizeof(time_t));
1165 r->local_alias->rrset->entry.data = d;
1166 d->rr_len = (size_t*)((uint8_t*)d +
1167 sizeof(struct packed_rrset_data));
1168 d->rr_data = (uint8_t**)&(d->rr_len[1]);
1169 d->rr_ttl = (time_t*)&(d->rr_data[1]);
1170 d->rr_len[0] = dsrc->rr_len[0];
1171 d->rr_ttl[0] = dsrc->rr_ttl[0];
1172 d->rr_data[0] = regional_alloc_init(s->s.region,
1173 dsrc->rr_data[0], d->rr_len[0]);
1177 r->local_alias = NULL;
1184 * Continue processing the mesh state at another module.
1185 * Handles module to modules tranfer of control.
1186 * Handles module finished.
1187 * @param mesh: the mesh area.
1188 * @param mstate: currently active mesh state.
1189 * Deleted if finished, calls _done and _supers to
1190 * send replies to clients and inform other mesh states.
1191 * This in turn may create additional runnable mesh states.
1192 * @param s: state at which the current module exited.
1193 * @param ev: the event sent to the module.
1194 * returned is the event to send to the next module.
1195 * @return true if continue processing at the new module.
1196 * false if not continued processing is needed.
1199 mesh_continue(struct mesh_area* mesh, struct mesh_state* mstate,
1200 enum module_ext_state s, enum module_ev* ev)
1202 mstate->num_activated++;
1203 if(mstate->num_activated > MESH_MAX_ACTIVATION) {
1204 /* module is looping. Stop it. */
1205 log_err("internal error: looping module stopped");
1206 log_query_info(VERB_QUERY, "pass error for qstate",
1210 if(s == module_wait_module || s == module_restart_next) {
1211 /* start next module */
1213 if(mesh->mods.num == mstate->s.curmod) {
1214 log_err("Cannot pass to next module; at last module");
1215 log_query_info(VERB_QUERY, "pass error for qstate",
1218 return mesh_continue(mesh, mstate, module_error, ev);
1220 if(s == module_restart_next) {
1221 fptr_ok(fptr_whitelist_mod_clear(
1222 mesh->mods.mod[mstate->s.curmod]->clear));
1223 (*mesh->mods.mod[mstate->s.curmod]->clear)
1224 (&mstate->s, mstate->s.curmod);
1225 mstate->s.minfo[mstate->s.curmod] = NULL;
1227 *ev = module_event_pass;
1230 if(s == module_wait_subquery && mstate->sub_set.count == 0) {
1231 log_err("module cannot wait for subquery, subquery list empty");
1232 log_query_info(VERB_QUERY, "pass error for qstate",
1236 if(s == module_error && mstate->s.return_rcode == LDNS_RCODE_NOERROR) {
1237 /* error is bad, handle pass back up below */
1238 mstate->s.return_rcode = LDNS_RCODE_SERVFAIL;
1240 if(s == module_error || s == module_finished) {
1241 if(mstate->s.curmod == 0) {
1242 mesh_query_done(mstate);
1243 mesh_walk_supers(mesh, mstate);
1244 mesh_state_delete(&mstate->s);
1247 /* pass along the locus of control */
1248 mstate->s.curmod --;
1249 *ev = module_event_moddone;
1255 void mesh_run(struct mesh_area* mesh, struct mesh_state* mstate,
1256 enum module_ev ev, struct outbound_entry* e)
1258 enum module_ext_state s;
1259 verbose(VERB_ALGO, "mesh_run: start");
1261 /* run the module */
1262 fptr_ok(fptr_whitelist_mod_operate(
1263 mesh->mods.mod[mstate->s.curmod]->operate));
1264 (*mesh->mods.mod[mstate->s.curmod]->operate)
1265 (&mstate->s, ev, mstate->s.curmod, e);
1267 /* examine results */
1268 mstate->s.reply = NULL;
1269 regional_free_all(mstate->s.env->scratch);
1270 s = mstate->s.ext_state[mstate->s.curmod];
1271 verbose(VERB_ALGO, "mesh_run: %s module exit state is %s",
1272 mesh->mods.mod[mstate->s.curmod]->name, strextstate(s));
1274 if(mesh_continue(mesh, mstate, s, &ev))
1277 /* run more modules */
1278 ev = module_event_pass;
1279 if(mesh->run.count > 0) {
1280 /* pop random element off the runnable tree */
1281 mstate = (struct mesh_state*)mesh->run.root->key;
1282 (void)rbtree_delete(&mesh->run, mstate);
1283 } else mstate = NULL;
1285 if(verbosity >= VERB_ALGO) {
1286 mesh_stats(mesh, "mesh_run: end");
1287 mesh_log_list(mesh);
1292 mesh_log_list(struct mesh_area* mesh)
1295 struct mesh_state* m;
1297 RBTREE_FOR(m, struct mesh_state*, &mesh->all) {
1298 snprintf(buf, sizeof(buf), "%d%s%s%s%s%s%s mod%d %s%s",
1299 num++, (m->s.is_priming)?"p":"", /* prime */
1300 (m->s.is_valrec)?"v":"", /* prime */
1301 (m->s.query_flags&BIT_RD)?"RD":"",
1302 (m->s.query_flags&BIT_CD)?"CD":"",
1303 (m->super_set.count==0)?"d":"", /* detached */
1304 (m->sub_set.count!=0)?"c":"", /* children */
1305 m->s.curmod, (m->reply_list)?"rep":"", /*hasreply*/
1306 (m->cb_list)?"cb":"" /* callbacks */
1308 log_query_info(VERB_ALGO, buf, &m->s.qinfo);
1313 mesh_stats(struct mesh_area* mesh, const char* str)
1315 verbose(VERB_DETAIL, "%s %u recursion states (%u with reply, "
1316 "%u detached), %u waiting replies, %u recursion replies "
1317 "sent, %d replies dropped, %d states jostled out",
1318 str, (unsigned)mesh->all.count,
1319 (unsigned)mesh->num_reply_states,
1320 (unsigned)mesh->num_detached_states,
1321 (unsigned)mesh->num_reply_addrs,
1322 (unsigned)mesh->replies_sent,
1323 (unsigned)mesh->stats_dropped,
1324 (unsigned)mesh->stats_jostled);
1325 if(mesh->replies_sent > 0) {
1327 timeval_divide(&avg, &mesh->replies_sum_wait,
1328 mesh->replies_sent);
1329 log_info("average recursion processing time "
1330 ARG_LL "d.%6.6d sec",
1331 (long long)avg.tv_sec, (int)avg.tv_usec);
1332 log_info("histogram of recursion processing times");
1333 timehist_log(mesh->histogram, "recursions");
1338 mesh_stats_clear(struct mesh_area* mesh)
1342 mesh->replies_sent = 0;
1343 mesh->replies_sum_wait.tv_sec = 0;
1344 mesh->replies_sum_wait.tv_usec = 0;
1345 mesh->stats_jostled = 0;
1346 mesh->stats_dropped = 0;
1347 timehist_clear(mesh->histogram);
1348 mesh->ans_secure = 0;
1349 mesh->ans_bogus = 0;
1350 memset(&mesh->ans_rcode[0], 0, sizeof(size_t)*16);
1351 mesh->ans_nodata = 0;
1355 mesh_get_mem(struct mesh_area* mesh)
1357 struct mesh_state* m;
1358 size_t s = sizeof(*mesh) + sizeof(struct timehist) +
1359 sizeof(struct th_buck)*mesh->histogram->num +
1360 sizeof(sldns_buffer) + sldns_buffer_capacity(mesh->qbuf_bak);
1361 RBTREE_FOR(m, struct mesh_state*, &mesh->all) {
1362 /* all, including m itself allocated in qstate region */
1363 s += regional_get_mem(m->s.region);
1369 mesh_detect_cycle(struct module_qstate* qstate, struct query_info* qinfo,
1370 uint16_t flags, int prime, int valrec)
1372 struct mesh_area* mesh = qstate->env->mesh;
1373 struct mesh_state* dep_m = NULL;
1374 if(!mesh_state_is_unique(qstate->mesh_info))
1375 dep_m = mesh_area_find(mesh, qinfo, flags, prime, valrec);
1376 return mesh_detect_cycle_found(qstate, dep_m);
1379 void mesh_list_insert(struct mesh_state* m, struct mesh_state** fp,
1380 struct mesh_state** lp)
1382 /* insert as last element */
1391 void mesh_list_remove(struct mesh_state* m, struct mesh_state** fp,
1392 struct mesh_state** lp)
1395 m->next->prev = m->prev;
1398 m->prev->next = m->next;