1238106Sdes/*
2238106Sdes * services/mesh.c - deal with mesh of query states and handle events for that.
3238106Sdes *
4238106Sdes * Copyright (c) 2007, NLnet Labs. All rights reserved.
5238106Sdes *
6238106Sdes * This software is open source.
7238106Sdes *
8238106Sdes * Redistribution and use in source and binary forms, with or without
9238106Sdes * modification, are permitted provided that the following conditions
10238106Sdes * are met:
11238106Sdes *
12238106Sdes * Redistributions of source code must retain the above copyright notice,
13238106Sdes * this list of conditions and the following disclaimer.
14238106Sdes *
15238106Sdes * Redistributions in binary form must reproduce the above copyright notice,
16238106Sdes * this list of conditions and the following disclaimer in the documentation
17238106Sdes * and/or other materials provided with the distribution.
18238106Sdes *
19238106Sdes * Neither the name of the NLNET LABS nor the names of its contributors may
20238106Sdes * be used to endorse or promote products derived from this software without
21238106Sdes * specific prior written permission.
22238106Sdes *
23238106Sdes * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
24269257Sdes * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
25269257Sdes * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
26269257Sdes * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
27269257Sdes * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
28269257Sdes * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
29269257Sdes * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
30269257Sdes * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
31269257Sdes * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
32269257Sdes * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
33269257Sdes * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
34238106Sdes */
35238106Sdes
36238106Sdes/**
37238106Sdes * \file
38238106Sdes *
39238106Sdes * This file contains functions to assist in dealing with a mesh of
40238106Sdes * query states. This mesh is supposed to be thread-specific.
41238106Sdes * It consists of query states (per qname, qtype, qclass) and connections
42238106Sdes * between query states and the super and subquery states, and replies to
43238106Sdes * send back to clients.
44238106Sdes */
45238106Sdes#include "config.h"
46238106Sdes#include "services/mesh.h"
47238106Sdes#include "services/outbound_list.h"
48238106Sdes#include "services/cache/dns.h"
49238106Sdes#include "util/log.h"
50238106Sdes#include "util/net_help.h"
51238106Sdes#include "util/module.h"
52238106Sdes#include "util/regional.h"
53238106Sdes#include "util/data/msgencode.h"
54238106Sdes#include "util/timehist.h"
55238106Sdes#include "util/fptr_wlist.h"
56238106Sdes#include "util/alloc.h"
57238106Sdes#include "util/config_file.h"
58291767Sdes#include "sldns/sbuffer.h"
59238106Sdes
60238106Sdes/** subtract timers and the values do not overflow or become negative */
61238106Sdesstatic void
62238106Sdestimeval_subtract(struct timeval* d, const struct timeval* end, const struct timeval* start)
63238106Sdes{
64238106Sdes#ifndef S_SPLINT_S
65238106Sdes	time_t end_usec = end->tv_usec;
66238106Sdes	d->tv_sec = end->tv_sec - start->tv_sec;
67238106Sdes	if(end_usec < start->tv_usec) {
68238106Sdes		end_usec += 1000000;
69238106Sdes		d->tv_sec--;
70238106Sdes	}
71238106Sdes	d->tv_usec = end_usec - start->tv_usec;
72238106Sdes#endif
73238106Sdes}
74238106Sdes
75238106Sdes/** add timers and the values do not overflow or become negative */
76238106Sdesstatic void
77238106Sdestimeval_add(struct timeval* d, const struct timeval* add)
78238106Sdes{
79238106Sdes#ifndef S_SPLINT_S
80238106Sdes	d->tv_sec += add->tv_sec;
81238106Sdes	d->tv_usec += add->tv_usec;
82238106Sdes	if(d->tv_usec > 1000000 ) {
83238106Sdes		d->tv_usec -= 1000000;
84238106Sdes		d->tv_sec++;
85238106Sdes	}
86238106Sdes#endif
87238106Sdes}
88238106Sdes
89238106Sdes/** divide sum of timers to get average */
90238106Sdesstatic void
91238106Sdestimeval_divide(struct timeval* avg, const struct timeval* sum, size_t d)
92238106Sdes{
93238106Sdes#ifndef S_SPLINT_S
94238106Sdes	size_t leftover;
95238106Sdes	if(d == 0) {
96238106Sdes		avg->tv_sec = 0;
97238106Sdes		avg->tv_usec = 0;
98238106Sdes		return;
99238106Sdes	}
100238106Sdes	avg->tv_sec = sum->tv_sec / d;
101238106Sdes	avg->tv_usec = sum->tv_usec / d;
102238106Sdes	/* handle fraction from seconds divide */
103238106Sdes	leftover = sum->tv_sec - avg->tv_sec*d;
104238106Sdes	avg->tv_usec += (leftover*1000000)/d;
105238106Sdes#endif
106238106Sdes}
107238106Sdes
108238106Sdes/** histogram compare of time values */
109238106Sdesstatic int
110238106Sdestimeval_smaller(const struct timeval* x, const struct timeval* y)
111238106Sdes{
112238106Sdes#ifndef S_SPLINT_S
113238106Sdes	if(x->tv_sec < y->tv_sec)
114238106Sdes		return 1;
115238106Sdes	else if(x->tv_sec == y->tv_sec) {
116238106Sdes		if(x->tv_usec <= y->tv_usec)
117238106Sdes			return 1;
118238106Sdes		else	return 0;
119238106Sdes	}
120238106Sdes	else	return 0;
121238106Sdes#endif
122238106Sdes}
123238106Sdes
124238106Sdesint
125238106Sdesmesh_state_compare(const void* ap, const void* bp)
126238106Sdes{
127238106Sdes	struct mesh_state* a = (struct mesh_state*)ap;
128238106Sdes	struct mesh_state* b = (struct mesh_state*)bp;
129238106Sdes
130238106Sdes	if(a->s.is_priming && !b->s.is_priming)
131238106Sdes		return -1;
132238106Sdes	if(!a->s.is_priming && b->s.is_priming)
133238106Sdes		return 1;
134238106Sdes
135285206Sdes	if(a->s.is_valrec && !b->s.is_valrec)
136285206Sdes		return -1;
137285206Sdes	if(!a->s.is_valrec && b->s.is_valrec)
138285206Sdes		return 1;
139285206Sdes
140238106Sdes	if((a->s.query_flags&BIT_RD) && !(b->s.query_flags&BIT_RD))
141238106Sdes		return -1;
142238106Sdes	if(!(a->s.query_flags&BIT_RD) && (b->s.query_flags&BIT_RD))
143238106Sdes		return 1;
144238106Sdes
145238106Sdes	if((a->s.query_flags&BIT_CD) && !(b->s.query_flags&BIT_CD))
146238106Sdes		return -1;
147238106Sdes	if(!(a->s.query_flags&BIT_CD) && (b->s.query_flags&BIT_CD))
148238106Sdes		return 1;
149238106Sdes
150238106Sdes	return query_info_compare(&a->s.qinfo, &b->s.qinfo);
151238106Sdes}
152238106Sdes
153238106Sdesint
154238106Sdesmesh_state_ref_compare(const void* ap, const void* bp)
155238106Sdes{
156238106Sdes	struct mesh_state_ref* a = (struct mesh_state_ref*)ap;
157238106Sdes	struct mesh_state_ref* b = (struct mesh_state_ref*)bp;
158238106Sdes	return mesh_state_compare(a->s, b->s);
159238106Sdes}
160238106Sdes
161238106Sdesstruct mesh_area*
162238106Sdesmesh_create(struct module_stack* stack, struct module_env* env)
163238106Sdes{
164238106Sdes	struct mesh_area* mesh = calloc(1, sizeof(struct mesh_area));
165238106Sdes	if(!mesh) {
166238106Sdes		log_err("mesh area alloc: out of memory");
167238106Sdes		return NULL;
168238106Sdes	}
169238106Sdes	mesh->histogram = timehist_setup();
170269257Sdes	mesh->qbuf_bak = sldns_buffer_new(env->cfg->msg_buffer_size);
171238106Sdes	if(!mesh->histogram || !mesh->qbuf_bak) {
172238106Sdes		free(mesh);
173238106Sdes		log_err("mesh area alloc: out of memory");
174238106Sdes		return NULL;
175238106Sdes	}
176238106Sdes	mesh->mods = *stack;
177238106Sdes	mesh->env = env;
178238106Sdes	rbtree_init(&mesh->run, &mesh_state_compare);
179238106Sdes	rbtree_init(&mesh->all, &mesh_state_compare);
180238106Sdes	mesh->num_reply_addrs = 0;
181238106Sdes	mesh->num_reply_states = 0;
182238106Sdes	mesh->num_detached_states = 0;
183238106Sdes	mesh->num_forever_states = 0;
184238106Sdes	mesh->stats_jostled = 0;
185238106Sdes	mesh->stats_dropped = 0;
186238106Sdes	mesh->max_reply_states = env->cfg->num_queries_per_thread;
187238106Sdes	mesh->max_forever_states = (mesh->max_reply_states+1)/2;
188238106Sdes#ifndef S_SPLINT_S
189238106Sdes	mesh->jostle_max.tv_sec = (time_t)(env->cfg->jostle_time / 1000);
190238106Sdes	mesh->jostle_max.tv_usec = (time_t)((env->cfg->jostle_time % 1000)
191238106Sdes		*1000);
192238106Sdes#endif
193238106Sdes	return mesh;
194238106Sdes}
195238106Sdes
196238106Sdes/** help mesh delete delete mesh states */
197238106Sdesstatic void
198238106Sdesmesh_delete_helper(rbnode_t* n)
199238106Sdes{
200238106Sdes	struct mesh_state* mstate = (struct mesh_state*)n->key;
201238106Sdes	/* perform a full delete, not only 'cleanup' routine,
202238106Sdes	 * because other callbacks expect a clean state in the mesh.
203238106Sdes	 * For 're-entrant' calls */
204238106Sdes	mesh_state_delete(&mstate->s);
205238106Sdes	/* but because these delete the items from the tree, postorder
206238106Sdes	 * traversal and rbtree rebalancing do not work together */
207238106Sdes}
208238106Sdes
209238106Sdesvoid
210238106Sdesmesh_delete(struct mesh_area* mesh)
211238106Sdes{
212238106Sdes	if(!mesh)
213238106Sdes		return;
214238106Sdes	/* free all query states */
215238106Sdes	while(mesh->all.count)
216238106Sdes		mesh_delete_helper(mesh->all.root);
217238106Sdes	timehist_delete(mesh->histogram);
218269257Sdes	sldns_buffer_free(mesh->qbuf_bak);
219238106Sdes	free(mesh);
220238106Sdes}
221238106Sdes
222238106Sdesvoid
223238106Sdesmesh_delete_all(struct mesh_area* mesh)
224238106Sdes{
225238106Sdes	/* free all query states */
226238106Sdes	while(mesh->all.count)
227238106Sdes		mesh_delete_helper(mesh->all.root);
228238106Sdes	mesh->stats_dropped += mesh->num_reply_addrs;
229238106Sdes	/* clear mesh area references */
230238106Sdes	rbtree_init(&mesh->run, &mesh_state_compare);
231238106Sdes	rbtree_init(&mesh->all, &mesh_state_compare);
232238106Sdes	mesh->num_reply_addrs = 0;
233238106Sdes	mesh->num_reply_states = 0;
234238106Sdes	mesh->num_detached_states = 0;
235238106Sdes	mesh->num_forever_states = 0;
236238106Sdes	mesh->forever_first = NULL;
237238106Sdes	mesh->forever_last = NULL;
238238106Sdes	mesh->jostle_first = NULL;
239238106Sdes	mesh->jostle_last = NULL;
240238106Sdes}
241238106Sdes
242269257Sdesint mesh_make_new_space(struct mesh_area* mesh, sldns_buffer* qbuf)
243238106Sdes{
244238106Sdes	struct mesh_state* m = mesh->jostle_first;
245238106Sdes	/* free space is available */
246238106Sdes	if(mesh->num_reply_states < mesh->max_reply_states)
247238106Sdes		return 1;
248238106Sdes	/* try to kick out a jostle-list item */
249238106Sdes	if(m && m->reply_list && m->list_select == mesh_jostle_list) {
250238106Sdes		/* how old is it? */
251238106Sdes		struct timeval age;
252238106Sdes		timeval_subtract(&age, mesh->env->now_tv,
253238106Sdes			&m->reply_list->start_time);
254238106Sdes		if(timeval_smaller(&mesh->jostle_max, &age)) {
255238106Sdes			/* its a goner */
256238106Sdes			log_nametypeclass(VERB_ALGO, "query jostled out to "
257238106Sdes				"make space for a new one",
258238106Sdes				m->s.qinfo.qname, m->s.qinfo.qtype,
259238106Sdes				m->s.qinfo.qclass);
260238106Sdes			/* backup the query */
261269257Sdes			if(qbuf) sldns_buffer_copy(mesh->qbuf_bak, qbuf);
262238106Sdes			/* notify supers */
263238106Sdes			if(m->super_set.count > 0) {
264238106Sdes				verbose(VERB_ALGO, "notify supers of failure");
265238106Sdes				m->s.return_msg = NULL;
266238106Sdes				m->s.return_rcode = LDNS_RCODE_SERVFAIL;
267238106Sdes				mesh_walk_supers(mesh, m);
268238106Sdes			}
269238106Sdes			mesh->stats_jostled ++;
270238106Sdes			mesh_state_delete(&m->s);
271238106Sdes			/* restore the query - note that the qinfo ptr to
272238106Sdes			 * the querybuffer is then correct again. */
273269257Sdes			if(qbuf) sldns_buffer_copy(qbuf, mesh->qbuf_bak);
274238106Sdes			return 1;
275238106Sdes		}
276238106Sdes	}
277238106Sdes	/* no space for new item */
278238106Sdes	return 0;
279238106Sdes}
280238106Sdes
281238106Sdesvoid mesh_new_client(struct mesh_area* mesh, struct query_info* qinfo,
282238106Sdes        uint16_t qflags, struct edns_data* edns, struct comm_reply* rep,
283238106Sdes        uint16_t qid)
284238106Sdes{
285285206Sdes	struct mesh_state* s = mesh_area_find(mesh, qinfo, qflags&(BIT_RD|BIT_CD), 0, 0);
286238106Sdes	int was_detached = 0;
287238106Sdes	int was_noreply = 0;
288238106Sdes	int added = 0;
289238106Sdes	/* does this create a new reply state? */
290238106Sdes	if(!s || s->list_select == mesh_no_list) {
291238106Sdes		if(!mesh_make_new_space(mesh, rep->c->buffer)) {
292238106Sdes			verbose(VERB_ALGO, "Too many queries. dropping "
293238106Sdes				"incoming query.");
294238106Sdes			comm_point_drop_reply(rep);
295238106Sdes			mesh->stats_dropped ++;
296238106Sdes			return;
297238106Sdes		}
298238106Sdes		/* for this new reply state, the reply address is free,
299238106Sdes		 * so the limit of reply addresses does not stop reply states*/
300238106Sdes	} else {
301238106Sdes		/* protect our memory usage from storing reply addresses */
302238106Sdes		if(mesh->num_reply_addrs > mesh->max_reply_states*16) {
303238106Sdes			verbose(VERB_ALGO, "Too many requests queued. "
304238106Sdes				"dropping incoming query.");
305238106Sdes			mesh->stats_dropped++;
306238106Sdes			comm_point_drop_reply(rep);
307238106Sdes			return;
308238106Sdes		}
309238106Sdes	}
310238106Sdes	/* see if it already exists, if not, create one */
311238106Sdes	if(!s) {
312238106Sdes#ifdef UNBOUND_DEBUG
313238106Sdes		struct rbnode_t* n;
314238106Sdes#endif
315285206Sdes		s = mesh_state_create(mesh->env, qinfo, qflags&(BIT_RD|BIT_CD), 0, 0);
316238106Sdes		if(!s) {
317238106Sdes			log_err("mesh_state_create: out of memory; SERVFAIL");
318238106Sdes			error_encode(rep->c->buffer, LDNS_RCODE_SERVFAIL,
319238106Sdes				qinfo, qid, qflags, edns);
320238106Sdes			comm_point_send_reply(rep);
321238106Sdes			return;
322238106Sdes		}
323238106Sdes#ifdef UNBOUND_DEBUG
324238106Sdes		n =
325269257Sdes#else
326269257Sdes		(void)
327238106Sdes#endif
328238106Sdes		rbtree_insert(&mesh->all, &s->node);
329238106Sdes		log_assert(n != NULL);
330238106Sdes		/* set detached (it is now) */
331238106Sdes		mesh->num_detached_states++;
332238106Sdes		added = 1;
333238106Sdes	}
334238106Sdes	if(!s->reply_list && !s->cb_list && s->super_set.count == 0)
335238106Sdes		was_detached = 1;
336238106Sdes	if(!s->reply_list && !s->cb_list)
337238106Sdes		was_noreply = 1;
338238106Sdes	/* add reply to s */
339238106Sdes	if(!mesh_state_add_reply(s, edns, rep, qid, qflags, qinfo->qname)) {
340238106Sdes			log_err("mesh_new_client: out of memory; SERVFAIL");
341238106Sdes			error_encode(rep->c->buffer, LDNS_RCODE_SERVFAIL,
342238106Sdes				qinfo, qid, qflags, edns);
343238106Sdes			comm_point_send_reply(rep);
344238106Sdes			if(added)
345238106Sdes				mesh_state_delete(&s->s);
346238106Sdes			return;
347238106Sdes	}
348238106Sdes	/* update statistics */
349238106Sdes	if(was_detached) {
350238106Sdes		log_assert(mesh->num_detached_states > 0);
351238106Sdes		mesh->num_detached_states--;
352238106Sdes	}
353238106Sdes	if(was_noreply) {
354238106Sdes		mesh->num_reply_states ++;
355238106Sdes	}
356238106Sdes	mesh->num_reply_addrs++;
357238106Sdes	if(s->list_select == mesh_no_list) {
358238106Sdes		/* move to either the forever or the jostle_list */
359238106Sdes		if(mesh->num_forever_states < mesh->max_forever_states) {
360238106Sdes			mesh->num_forever_states ++;
361238106Sdes			mesh_list_insert(s, &mesh->forever_first,
362238106Sdes				&mesh->forever_last);
363238106Sdes			s->list_select = mesh_forever_list;
364238106Sdes		} else {
365238106Sdes			mesh_list_insert(s, &mesh->jostle_first,
366238106Sdes				&mesh->jostle_last);
367238106Sdes			s->list_select = mesh_jostle_list;
368238106Sdes		}
369238106Sdes	}
370238106Sdes	if(added)
371238106Sdes		mesh_run(mesh, s, module_event_new, NULL);
372238106Sdes}
373238106Sdes
374238106Sdesint
375238106Sdesmesh_new_callback(struct mesh_area* mesh, struct query_info* qinfo,
376269257Sdes	uint16_t qflags, struct edns_data* edns, sldns_buffer* buf,
377238106Sdes	uint16_t qid, mesh_cb_func_t cb, void* cb_arg)
378238106Sdes{
379285206Sdes	struct mesh_state* s = mesh_area_find(mesh, qinfo, qflags&(BIT_RD|BIT_CD), 0, 0);
380238106Sdes	int was_detached = 0;
381238106Sdes	int was_noreply = 0;
382238106Sdes	int added = 0;
383238106Sdes	/* there are no limits on the number of callbacks */
384238106Sdes
385238106Sdes	/* see if it already exists, if not, create one */
386238106Sdes	if(!s) {
387238106Sdes#ifdef UNBOUND_DEBUG
388238106Sdes		struct rbnode_t* n;
389238106Sdes#endif
390285206Sdes		s = mesh_state_create(mesh->env, qinfo, qflags&(BIT_RD|BIT_CD), 0, 0);
391238106Sdes		if(!s) {
392238106Sdes			return 0;
393238106Sdes		}
394238106Sdes#ifdef UNBOUND_DEBUG
395238106Sdes		n =
396269257Sdes#else
397269257Sdes		(void)
398238106Sdes#endif
399238106Sdes		rbtree_insert(&mesh->all, &s->node);
400238106Sdes		log_assert(n != NULL);
401238106Sdes		/* set detached (it is now) */
402238106Sdes		mesh->num_detached_states++;
403238106Sdes		added = 1;
404238106Sdes	}
405238106Sdes	if(!s->reply_list && !s->cb_list && s->super_set.count == 0)
406238106Sdes		was_detached = 1;
407238106Sdes	if(!s->reply_list && !s->cb_list)
408238106Sdes		was_noreply = 1;
409238106Sdes	/* add reply to s */
410238106Sdes	if(!mesh_state_add_cb(s, edns, buf, cb, cb_arg, qid, qflags)) {
411238106Sdes			if(added)
412238106Sdes				mesh_state_delete(&s->s);
413238106Sdes			return 0;
414238106Sdes	}
415238106Sdes	/* update statistics */
416238106Sdes	if(was_detached) {
417238106Sdes		log_assert(mesh->num_detached_states > 0);
418238106Sdes		mesh->num_detached_states--;
419238106Sdes	}
420238106Sdes	if(was_noreply) {
421238106Sdes		mesh->num_reply_states ++;
422238106Sdes	}
423238106Sdes	mesh->num_reply_addrs++;
424238106Sdes	if(added)
425238106Sdes		mesh_run(mesh, s, module_event_new, NULL);
426238106Sdes	return 1;
427238106Sdes}
428238106Sdes
429238106Sdesvoid mesh_new_prefetch(struct mesh_area* mesh, struct query_info* qinfo,
430269257Sdes        uint16_t qflags, time_t leeway)
431238106Sdes{
432285206Sdes	struct mesh_state* s = mesh_area_find(mesh, qinfo, qflags&(BIT_RD|BIT_CD), 0, 0);
433238106Sdes#ifdef UNBOUND_DEBUG
434238106Sdes	struct rbnode_t* n;
435238106Sdes#endif
436238106Sdes	/* already exists, and for a different purpose perhaps.
437238106Sdes	 * if mesh_no_list, keep it that way. */
438238106Sdes	if(s) {
439238106Sdes		/* make it ignore the cache from now on */
440238106Sdes		if(!s->s.blacklist)
441238106Sdes			sock_list_insert(&s->s.blacklist, NULL, 0, s->s.region);
442238106Sdes		if(s->s.prefetch_leeway < leeway)
443238106Sdes			s->s.prefetch_leeway = leeway;
444238106Sdes		return;
445238106Sdes	}
446238106Sdes	if(!mesh_make_new_space(mesh, NULL)) {
447238106Sdes		verbose(VERB_ALGO, "Too many queries. dropped prefetch.");
448238106Sdes		mesh->stats_dropped ++;
449238106Sdes		return;
450238106Sdes	}
451285206Sdes	s = mesh_state_create(mesh->env, qinfo, qflags&(BIT_RD|BIT_CD), 0, 0);
452238106Sdes	if(!s) {
453238106Sdes		log_err("prefetch mesh_state_create: out of memory");
454238106Sdes		return;
455238106Sdes	}
456238106Sdes#ifdef UNBOUND_DEBUG
457238106Sdes	n =
458269257Sdes#else
459269257Sdes	(void)
460238106Sdes#endif
461238106Sdes	rbtree_insert(&mesh->all, &s->node);
462238106Sdes	log_assert(n != NULL);
463238106Sdes	/* set detached (it is now) */
464238106Sdes	mesh->num_detached_states++;
465238106Sdes	/* make it ignore the cache */
466238106Sdes	sock_list_insert(&s->s.blacklist, NULL, 0, s->s.region);
467238106Sdes	s->s.prefetch_leeway = leeway;
468238106Sdes
469238106Sdes	if(s->list_select == mesh_no_list) {
470238106Sdes		/* move to either the forever or the jostle_list */
471238106Sdes		if(mesh->num_forever_states < mesh->max_forever_states) {
472238106Sdes			mesh->num_forever_states ++;
473238106Sdes			mesh_list_insert(s, &mesh->forever_first,
474238106Sdes				&mesh->forever_last);
475238106Sdes			s->list_select = mesh_forever_list;
476238106Sdes		} else {
477238106Sdes			mesh_list_insert(s, &mesh->jostle_first,
478238106Sdes				&mesh->jostle_last);
479238106Sdes			s->list_select = mesh_jostle_list;
480238106Sdes		}
481238106Sdes	}
482238106Sdes	mesh_run(mesh, s, module_event_new, NULL);
483238106Sdes}
484238106Sdes
485238106Sdesvoid mesh_report_reply(struct mesh_area* mesh, struct outbound_entry* e,
486238106Sdes        struct comm_reply* reply, int what)
487238106Sdes{
488238106Sdes	enum module_ev event = module_event_reply;
489238106Sdes	e->qstate->reply = reply;
490238106Sdes	if(what != NETEVENT_NOERROR) {
491238106Sdes		event = module_event_noreply;
492238106Sdes		if(what == NETEVENT_CAPSFAIL)
493238106Sdes			event = module_event_capsfail;
494238106Sdes	}
495238106Sdes	mesh_run(mesh, e->qstate->mesh_info, event, e);
496238106Sdes}
497238106Sdes
498238106Sdesstruct mesh_state*
499238106Sdesmesh_state_create(struct module_env* env, struct query_info* qinfo,
500285206Sdes	uint16_t qflags, int prime, int valrec)
501238106Sdes{
502238106Sdes	struct regional* region = alloc_reg_obtain(env->alloc);
503238106Sdes	struct mesh_state* mstate;
504238106Sdes	int i;
505238106Sdes	if(!region)
506238106Sdes		return NULL;
507238106Sdes	mstate = (struct mesh_state*)regional_alloc(region,
508238106Sdes		sizeof(struct mesh_state));
509238106Sdes	if(!mstate) {
510238106Sdes		alloc_reg_release(env->alloc, region);
511238106Sdes		return NULL;
512238106Sdes	}
513238106Sdes	memset(mstate, 0, sizeof(*mstate));
514238106Sdes	mstate->node = *RBTREE_NULL;
515238106Sdes	mstate->run_node = *RBTREE_NULL;
516238106Sdes	mstate->node.key = mstate;
517238106Sdes	mstate->run_node.key = mstate;
518238106Sdes	mstate->reply_list = NULL;
519238106Sdes	mstate->list_select = mesh_no_list;
520238106Sdes	mstate->replies_sent = 0;
521238106Sdes	rbtree_init(&mstate->super_set, &mesh_state_ref_compare);
522238106Sdes	rbtree_init(&mstate->sub_set, &mesh_state_ref_compare);
523238106Sdes	mstate->num_activated = 0;
524238106Sdes	/* init module qstate */
525238106Sdes	mstate->s.qinfo.qtype = qinfo->qtype;
526238106Sdes	mstate->s.qinfo.qclass = qinfo->qclass;
527238106Sdes	mstate->s.qinfo.qname_len = qinfo->qname_len;
528238106Sdes	mstate->s.qinfo.qname = regional_alloc_init(region, qinfo->qname,
529238106Sdes		qinfo->qname_len);
530238106Sdes	if(!mstate->s.qinfo.qname) {
531238106Sdes		alloc_reg_release(env->alloc, region);
532238106Sdes		return NULL;
533238106Sdes	}
534238106Sdes	/* remove all weird bits from qflags */
535238106Sdes	mstate->s.query_flags = (qflags & (BIT_RD|BIT_CD));
536238106Sdes	mstate->s.is_priming = prime;
537285206Sdes	mstate->s.is_valrec = valrec;
538238106Sdes	mstate->s.reply = NULL;
539238106Sdes	mstate->s.region = region;
540238106Sdes	mstate->s.curmod = 0;
541238106Sdes	mstate->s.return_msg = 0;
542238106Sdes	mstate->s.return_rcode = LDNS_RCODE_NOERROR;
543238106Sdes	mstate->s.env = env;
544238106Sdes	mstate->s.mesh_info = mstate;
545238106Sdes	mstate->s.prefetch_leeway = 0;
546238106Sdes	/* init modules */
547238106Sdes	for(i=0; i<env->mesh->mods.num; i++) {
548238106Sdes		mstate->s.minfo[i] = NULL;
549238106Sdes		mstate->s.ext_state[i] = module_state_initial;
550238106Sdes	}
551238106Sdes	return mstate;
552238106Sdes}
553238106Sdes
554238106Sdesvoid
555238106Sdesmesh_state_cleanup(struct mesh_state* mstate)
556238106Sdes{
557238106Sdes	struct mesh_area* mesh;
558238106Sdes	int i;
559238106Sdes	if(!mstate)
560238106Sdes		return;
561238106Sdes	mesh = mstate->s.env->mesh;
562238106Sdes	/* drop unsent replies */
563238106Sdes	if(!mstate->replies_sent) {
564238106Sdes		struct mesh_reply* rep;
565238106Sdes		struct mesh_cb* cb;
566238106Sdes		for(rep=mstate->reply_list; rep; rep=rep->next) {
567238106Sdes			comm_point_drop_reply(&rep->query_reply);
568238106Sdes			mesh->num_reply_addrs--;
569238106Sdes		}
570238106Sdes		for(cb=mstate->cb_list; cb; cb=cb->next) {
571238106Sdes			fptr_ok(fptr_whitelist_mesh_cb(cb->cb));
572238106Sdes			(*cb->cb)(cb->cb_arg, LDNS_RCODE_SERVFAIL, NULL,
573238106Sdes				sec_status_unchecked, NULL);
574238106Sdes			mesh->num_reply_addrs--;
575238106Sdes		}
576238106Sdes	}
577238106Sdes
578238106Sdes	/* de-init modules */
579238106Sdes	for(i=0; i<mesh->mods.num; i++) {
580238106Sdes		fptr_ok(fptr_whitelist_mod_clear(mesh->mods.mod[i]->clear));
581238106Sdes		(*mesh->mods.mod[i]->clear)(&mstate->s, i);
582238106Sdes		mstate->s.minfo[i] = NULL;
583238106Sdes		mstate->s.ext_state[i] = module_finished;
584238106Sdes	}
585238106Sdes	alloc_reg_release(mstate->s.env->alloc, mstate->s.region);
586238106Sdes}
587238106Sdes
588238106Sdesvoid
589238106Sdesmesh_state_delete(struct module_qstate* qstate)
590238106Sdes{
591238106Sdes	struct mesh_area* mesh;
592238106Sdes	struct mesh_state_ref* super, ref;
593238106Sdes	struct mesh_state* mstate;
594238106Sdes	if(!qstate)
595238106Sdes		return;
596238106Sdes	mstate = qstate->mesh_info;
597238106Sdes	mesh = mstate->s.env->mesh;
598238106Sdes	mesh_detach_subs(&mstate->s);
599238106Sdes	if(mstate->list_select == mesh_forever_list) {
600238106Sdes		mesh->num_forever_states --;
601238106Sdes		mesh_list_remove(mstate, &mesh->forever_first,
602238106Sdes			&mesh->forever_last);
603238106Sdes	} else if(mstate->list_select == mesh_jostle_list) {
604238106Sdes		mesh_list_remove(mstate, &mesh->jostle_first,
605238106Sdes			&mesh->jostle_last);
606238106Sdes	}
607238106Sdes	if(!mstate->reply_list && !mstate->cb_list
608238106Sdes		&& mstate->super_set.count == 0) {
609238106Sdes		log_assert(mesh->num_detached_states > 0);
610238106Sdes		mesh->num_detached_states--;
611238106Sdes	}
612238106Sdes	if(mstate->reply_list || mstate->cb_list) {
613238106Sdes		log_assert(mesh->num_reply_states > 0);
614238106Sdes		mesh->num_reply_states--;
615238106Sdes	}
616238106Sdes	ref.node.key = &ref;
617238106Sdes	ref.s = mstate;
618238106Sdes	RBTREE_FOR(super, struct mesh_state_ref*, &mstate->super_set) {
619238106Sdes		(void)rbtree_delete(&super->s->sub_set, &ref);
620238106Sdes	}
621238106Sdes	(void)rbtree_delete(&mesh->run, mstate);
622238106Sdes	(void)rbtree_delete(&mesh->all, mstate);
623238106Sdes	mesh_state_cleanup(mstate);
624238106Sdes}
625238106Sdes
626238106Sdes/** helper recursive rbtree find routine */
627238106Sdesstatic int
628238106Sdesfind_in_subsub(struct mesh_state* m, struct mesh_state* tofind, size_t *c)
629238106Sdes{
630238106Sdes	struct mesh_state_ref* r;
631238106Sdes	if((*c)++ > MESH_MAX_SUBSUB)
632238106Sdes		return 1;
633238106Sdes	RBTREE_FOR(r, struct mesh_state_ref*, &m->sub_set) {
634238106Sdes		if(r->s == tofind || find_in_subsub(r->s, tofind, c))
635238106Sdes			return 1;
636238106Sdes	}
637238106Sdes	return 0;
638238106Sdes}
639238106Sdes
640238106Sdes/** find cycle for already looked up mesh_state */
641238106Sdesstatic int
642238106Sdesmesh_detect_cycle_found(struct module_qstate* qstate, struct mesh_state* dep_m)
643238106Sdes{
644238106Sdes	struct mesh_state* cyc_m = qstate->mesh_info;
645238106Sdes	size_t counter = 0;
646238106Sdes	if(!dep_m)
647238106Sdes		return 0;
648238106Sdes	if(dep_m == cyc_m || find_in_subsub(dep_m, cyc_m, &counter)) {
649238106Sdes		if(counter > MESH_MAX_SUBSUB)
650238106Sdes			return 2;
651238106Sdes		return 1;
652238106Sdes	}
653238106Sdes	return 0;
654238106Sdes}
655238106Sdes
656238106Sdesvoid mesh_detach_subs(struct module_qstate* qstate)
657238106Sdes{
658238106Sdes	struct mesh_area* mesh = qstate->env->mesh;
659238106Sdes	struct mesh_state_ref* ref, lookup;
660238106Sdes#ifdef UNBOUND_DEBUG
661238106Sdes	struct rbnode_t* n;
662238106Sdes#endif
663238106Sdes	lookup.node.key = &lookup;
664238106Sdes	lookup.s = qstate->mesh_info;
665238106Sdes	RBTREE_FOR(ref, struct mesh_state_ref*, &qstate->mesh_info->sub_set) {
666238106Sdes#ifdef UNBOUND_DEBUG
667238106Sdes		n =
668269257Sdes#else
669269257Sdes		(void)
670238106Sdes#endif
671238106Sdes		rbtree_delete(&ref->s->super_set, &lookup);
672238106Sdes		log_assert(n != NULL); /* must have been present */
673238106Sdes		if(!ref->s->reply_list && !ref->s->cb_list
674238106Sdes			&& ref->s->super_set.count == 0) {
675238106Sdes			mesh->num_detached_states++;
676238106Sdes			log_assert(mesh->num_detached_states +
677238106Sdes				mesh->num_reply_states <= mesh->all.count);
678238106Sdes		}
679238106Sdes	}
680238106Sdes	rbtree_init(&qstate->mesh_info->sub_set, &mesh_state_ref_compare);
681238106Sdes}
682238106Sdes
683238106Sdesint mesh_attach_sub(struct module_qstate* qstate, struct query_info* qinfo,
684285206Sdes        uint16_t qflags, int prime, int valrec, struct module_qstate** newq)
685238106Sdes{
686238106Sdes	/* find it, if not, create it */
687238106Sdes	struct mesh_area* mesh = qstate->env->mesh;
688285206Sdes	struct mesh_state* sub = mesh_area_find(mesh, qinfo, qflags, prime,
689285206Sdes		valrec);
690249141Sdes	int was_detached;
691238106Sdes	if(mesh_detect_cycle_found(qstate, sub)) {
692238106Sdes		verbose(VERB_ALGO, "attach failed, cycle detected");
693238106Sdes		return 0;
694238106Sdes	}
695238106Sdes	if(!sub) {
696238106Sdes#ifdef UNBOUND_DEBUG
697238106Sdes		struct rbnode_t* n;
698238106Sdes#endif
699238106Sdes		/* create a new one */
700285206Sdes		sub = mesh_state_create(qstate->env, qinfo, qflags, prime,
701285206Sdes			valrec);
702238106Sdes		if(!sub) {
703238106Sdes			log_err("mesh_attach_sub: out of memory");
704238106Sdes			return 0;
705238106Sdes		}
706238106Sdes#ifdef UNBOUND_DEBUG
707238106Sdes		n =
708269257Sdes#else
709269257Sdes		(void)
710238106Sdes#endif
711238106Sdes		rbtree_insert(&mesh->all, &sub->node);
712238106Sdes		log_assert(n != NULL);
713238106Sdes		/* set detached (it is now) */
714238106Sdes		mesh->num_detached_states++;
715238106Sdes		/* set new query state to run */
716238106Sdes#ifdef UNBOUND_DEBUG
717238106Sdes		n =
718269257Sdes#else
719269257Sdes		(void)
720238106Sdes#endif
721238106Sdes		rbtree_insert(&mesh->run, &sub->run_node);
722238106Sdes		log_assert(n != NULL);
723238106Sdes		*newq = &sub->s;
724238106Sdes	} else
725238106Sdes		*newq = NULL;
726249141Sdes	was_detached = (sub->super_set.count == 0);
727238106Sdes	if(!mesh_state_attachment(qstate->mesh_info, sub))
728238106Sdes		return 0;
729249141Sdes	/* if it was a duplicate  attachment, the count was not zero before */
730249141Sdes	if(!sub->reply_list && !sub->cb_list && was_detached &&
731249141Sdes		sub->super_set.count == 1) {
732238106Sdes		/* it used to be detached, before this one got added */
733238106Sdes		log_assert(mesh->num_detached_states > 0);
734238106Sdes		mesh->num_detached_states--;
735238106Sdes	}
736238106Sdes	/* *newq will be run when inited after the current module stops */
737238106Sdes	return 1;
738238106Sdes}
739238106Sdes
740238106Sdesint mesh_state_attachment(struct mesh_state* super, struct mesh_state* sub)
741238106Sdes{
742238106Sdes#ifdef UNBOUND_DEBUG
743238106Sdes	struct rbnode_t* n;
744238106Sdes#endif
745238106Sdes	struct mesh_state_ref* subref; /* points to sub, inserted in super */
746238106Sdes	struct mesh_state_ref* superref; /* points to super, inserted in sub */
747238106Sdes	if( !(subref = regional_alloc(super->s.region,
748238106Sdes		sizeof(struct mesh_state_ref))) ||
749238106Sdes		!(superref = regional_alloc(sub->s.region,
750238106Sdes		sizeof(struct mesh_state_ref))) ) {
751238106Sdes		log_err("mesh_state_attachment: out of memory");
752238106Sdes		return 0;
753238106Sdes	}
754238106Sdes	superref->node.key = superref;
755238106Sdes	superref->s = super;
756238106Sdes	subref->node.key = subref;
757238106Sdes	subref->s = sub;
758249141Sdes	if(!rbtree_insert(&sub->super_set, &superref->node)) {
759249141Sdes		/* this should not happen, iterator and validator do not
760249141Sdes		 * attach subqueries that are identical. */
761249141Sdes		/* already attached, we are done, nothing todo.
762249141Sdes		 * since superref and subref already allocated in region,
763249141Sdes		 * we cannot free them */
764249141Sdes		return 1;
765249141Sdes	}
766238106Sdes#ifdef UNBOUND_DEBUG
767238106Sdes	n =
768269257Sdes#else
769269257Sdes	(void)
770238106Sdes#endif
771238106Sdes	rbtree_insert(&super->sub_set, &subref->node);
772249141Sdes	log_assert(n != NULL); /* we checked above if statement, the reverse
773249141Sdes	  administration should not fail now, unless they are out of sync */
774238106Sdes	return 1;
775238106Sdes}
776238106Sdes
777238106Sdes/**
778238106Sdes * callback results to mesh cb entry
779238106Sdes * @param m: mesh state to send it for.
780238106Sdes * @param rcode: if not 0, error code.
781238106Sdes * @param rep: reply to send (or NULL if rcode is set).
782238106Sdes * @param r: callback entry
783238106Sdes */
784238106Sdesstatic void
785238106Sdesmesh_do_callback(struct mesh_state* m, int rcode, struct reply_info* rep,
786238106Sdes	struct mesh_cb* r)
787238106Sdes{
788238106Sdes	int secure;
789238106Sdes	char* reason = NULL;
790238106Sdes	/* bogus messages are not made into servfail, sec_status passed
791238106Sdes	 * to the callback function */
792238106Sdes	if(rep && rep->security == sec_status_secure)
793238106Sdes		secure = 1;
794238106Sdes	else	secure = 0;
795238106Sdes	if(!rep && rcode == LDNS_RCODE_NOERROR)
796238106Sdes		rcode = LDNS_RCODE_SERVFAIL;
797238106Sdes	if(!rcode && rep->security == sec_status_bogus) {
798238106Sdes		if(!(reason = errinf_to_str(&m->s)))
799238106Sdes			rcode = LDNS_RCODE_SERVFAIL;
800238106Sdes	}
801238106Sdes	/* send the reply */
802238106Sdes	if(rcode) {
803238106Sdes		fptr_ok(fptr_whitelist_mesh_cb(r->cb));
804238106Sdes		(*r->cb)(r->cb_arg, rcode, r->buf, sec_status_unchecked, NULL);
805238106Sdes	} else {
806238106Sdes		size_t udp_size = r->edns.udp_size;
807269257Sdes		sldns_buffer_clear(r->buf);
808238106Sdes		r->edns.edns_version = EDNS_ADVERTISED_VERSION;
809238106Sdes		r->edns.udp_size = EDNS_ADVERTISED_SIZE;
810238106Sdes		r->edns.ext_rcode = 0;
811238106Sdes		r->edns.bits &= EDNS_DO;
812238106Sdes		if(!reply_info_answer_encode(&m->s.qinfo, rep, r->qid,
813238106Sdes			r->qflags, r->buf, 0, 1,
814238106Sdes			m->s.env->scratch, udp_size, &r->edns,
815238106Sdes			(int)(r->edns.bits & EDNS_DO), secure))
816238106Sdes		{
817238106Sdes			fptr_ok(fptr_whitelist_mesh_cb(r->cb));
818238106Sdes			(*r->cb)(r->cb_arg, LDNS_RCODE_SERVFAIL, r->buf,
819238106Sdes				sec_status_unchecked, NULL);
820238106Sdes		} else {
821238106Sdes			fptr_ok(fptr_whitelist_mesh_cb(r->cb));
822238106Sdes			(*r->cb)(r->cb_arg, LDNS_RCODE_NOERROR, r->buf,
823238106Sdes				rep->security, reason);
824238106Sdes		}
825238106Sdes	}
826238106Sdes	free(reason);
827238106Sdes	m->s.env->mesh->num_reply_addrs--;
828238106Sdes}
829238106Sdes
830238106Sdes/**
831238106Sdes * Send reply to mesh reply entry
832238106Sdes * @param m: mesh state to send it for.
833238106Sdes * @param rcode: if not 0, error code.
834238106Sdes * @param rep: reply to send (or NULL if rcode is set).
835238106Sdes * @param r: reply entry
836238106Sdes * @param prev: previous reply, already has its answer encoded in buffer.
837238106Sdes */
838238106Sdesstatic void
839238106Sdesmesh_send_reply(struct mesh_state* m, int rcode, struct reply_info* rep,
840238106Sdes	struct mesh_reply* r, struct mesh_reply* prev)
841238106Sdes{
842238106Sdes	struct timeval end_time;
843238106Sdes	struct timeval duration;
844238106Sdes	int secure;
845238106Sdes	/* examine security status */
846238106Sdes	if(m->s.env->need_to_validate && (!(r->qflags&BIT_CD) ||
847238106Sdes		m->s.env->cfg->ignore_cd) && rep &&
848238106Sdes		rep->security <= sec_status_bogus) {
849238106Sdes		rcode = LDNS_RCODE_SERVFAIL;
850238106Sdes		if(m->s.env->cfg->stat_extended)
851238106Sdes			m->s.env->mesh->ans_bogus++;
852238106Sdes	}
853238106Sdes	if(rep && rep->security == sec_status_secure)
854238106Sdes		secure = 1;
855238106Sdes	else	secure = 0;
856238106Sdes	if(!rep && rcode == LDNS_RCODE_NOERROR)
857238106Sdes		rcode = LDNS_RCODE_SERVFAIL;
858238106Sdes	/* send the reply */
859238106Sdes	if(prev && prev->qflags == r->qflags &&
860238106Sdes		prev->edns.edns_present == r->edns.edns_present &&
861238106Sdes		prev->edns.bits == r->edns.bits &&
862238106Sdes		prev->edns.udp_size == r->edns.udp_size) {
863238106Sdes		/* if the previous reply is identical to this one, fix ID */
864238106Sdes		if(prev->query_reply.c->buffer != r->query_reply.c->buffer)
865269257Sdes			sldns_buffer_copy(r->query_reply.c->buffer,
866238106Sdes				prev->query_reply.c->buffer);
867269257Sdes		sldns_buffer_write_at(r->query_reply.c->buffer, 0,
868238106Sdes			&r->qid, sizeof(uint16_t));
869269257Sdes		sldns_buffer_write_at(r->query_reply.c->buffer, 12,
870238106Sdes			r->qname, m->s.qinfo.qname_len);
871238106Sdes		comm_point_send_reply(&r->query_reply);
872238106Sdes	} else if(rcode) {
873238106Sdes		m->s.qinfo.qname = r->qname;
874238106Sdes		error_encode(r->query_reply.c->buffer, rcode, &m->s.qinfo,
875238106Sdes			r->qid, r->qflags, &r->edns);
876238106Sdes		comm_point_send_reply(&r->query_reply);
877238106Sdes	} else {
878238106Sdes		size_t udp_size = r->edns.udp_size;
879238106Sdes		r->edns.edns_version = EDNS_ADVERTISED_VERSION;
880238106Sdes		r->edns.udp_size = EDNS_ADVERTISED_SIZE;
881238106Sdes		r->edns.ext_rcode = 0;
882238106Sdes		r->edns.bits &= EDNS_DO;
883238106Sdes		m->s.qinfo.qname = r->qname;
884238106Sdes		if(!reply_info_answer_encode(&m->s.qinfo, rep, r->qid,
885238106Sdes			r->qflags, r->query_reply.c->buffer, 0, 1,
886238106Sdes			m->s.env->scratch, udp_size, &r->edns,
887238106Sdes			(int)(r->edns.bits & EDNS_DO), secure))
888238106Sdes		{
889238106Sdes			error_encode(r->query_reply.c->buffer,
890238106Sdes				LDNS_RCODE_SERVFAIL, &m->s.qinfo, r->qid,
891238106Sdes				r->qflags, &r->edns);
892238106Sdes		}
893238106Sdes		comm_point_send_reply(&r->query_reply);
894238106Sdes	}
895238106Sdes	/* account */
896238106Sdes	m->s.env->mesh->num_reply_addrs--;
897238106Sdes	end_time = *m->s.env->now_tv;
898238106Sdes	timeval_subtract(&duration, &end_time, &r->start_time);
899269257Sdes	verbose(VERB_ALGO, "query took " ARG_LL "d.%6.6d sec",
900269257Sdes		(long long)duration.tv_sec, (int)duration.tv_usec);
901238106Sdes	m->s.env->mesh->replies_sent++;
902238106Sdes	timeval_add(&m->s.env->mesh->replies_sum_wait, &duration);
903238106Sdes	timehist_insert(m->s.env->mesh->histogram, &duration);
904238106Sdes	if(m->s.env->cfg->stat_extended) {
905269257Sdes		uint16_t rc = FLAGS_GET_RCODE(sldns_buffer_read_u16_at(r->
906238106Sdes			query_reply.c->buffer, 2));
907238106Sdes		if(secure) m->s.env->mesh->ans_secure++;
908238106Sdes		m->s.env->mesh->ans_rcode[ rc ] ++;
909269257Sdes		if(rc == 0 && LDNS_ANCOUNT(sldns_buffer_begin(r->
910238106Sdes			query_reply.c->buffer)) == 0)
911238106Sdes			m->s.env->mesh->ans_nodata++;
912238106Sdes	}
913238106Sdes}
914238106Sdes
915238106Sdesvoid mesh_query_done(struct mesh_state* mstate)
916238106Sdes{
917238106Sdes	struct mesh_reply* r;
918238106Sdes	struct mesh_reply* prev = NULL;
919238106Sdes	struct mesh_cb* c;
920238106Sdes	struct reply_info* rep = (mstate->s.return_msg?
921238106Sdes		mstate->s.return_msg->rep:NULL);
922238106Sdes	for(r = mstate->reply_list; r; r = r->next) {
923238106Sdes		mesh_send_reply(mstate, mstate->s.return_rcode, rep, r, prev);
924238106Sdes		prev = r;
925238106Sdes	}
926238106Sdes	mstate->replies_sent = 1;
927238106Sdes	for(c = mstate->cb_list; c; c = c->next) {
928238106Sdes		mesh_do_callback(mstate, mstate->s.return_rcode, rep, c);
929238106Sdes	}
930238106Sdes}
931238106Sdes
932238106Sdesvoid mesh_walk_supers(struct mesh_area* mesh, struct mesh_state* mstate)
933238106Sdes{
934238106Sdes	struct mesh_state_ref* ref;
935238106Sdes	RBTREE_FOR(ref, struct mesh_state_ref*, &mstate->super_set)
936238106Sdes	{
937238106Sdes		/* make super runnable */
938238106Sdes		(void)rbtree_insert(&mesh->run, &ref->s->run_node);
939238106Sdes		/* callback the function to inform super of result */
940238106Sdes		fptr_ok(fptr_whitelist_mod_inform_super(
941238106Sdes			mesh->mods.mod[ref->s->s.curmod]->inform_super));
942238106Sdes		(*mesh->mods.mod[ref->s->s.curmod]->inform_super)(&mstate->s,
943238106Sdes			ref->s->s.curmod, &ref->s->s);
944238106Sdes	}
945238106Sdes}
946238106Sdes
947238106Sdesstruct mesh_state* mesh_area_find(struct mesh_area* mesh,
948285206Sdes	struct query_info* qinfo, uint16_t qflags, int prime, int valrec)
949238106Sdes{
950238106Sdes	struct mesh_state key;
951238106Sdes	struct mesh_state* result;
952238106Sdes
953238106Sdes	key.node.key = &key;
954238106Sdes	key.s.is_priming = prime;
955285206Sdes	key.s.is_valrec = valrec;
956238106Sdes	key.s.qinfo = *qinfo;
957238106Sdes	key.s.query_flags = qflags;
958238106Sdes
959238106Sdes	result = (struct mesh_state*)rbtree_search(&mesh->all, &key);
960238106Sdes	return result;
961238106Sdes}
962238106Sdes
963238106Sdesint mesh_state_add_cb(struct mesh_state* s, struct edns_data* edns,
964269257Sdes        sldns_buffer* buf, mesh_cb_func_t cb, void* cb_arg,
965238106Sdes	uint16_t qid, uint16_t qflags)
966238106Sdes{
967238106Sdes	struct mesh_cb* r = regional_alloc(s->s.region,
968238106Sdes		sizeof(struct mesh_cb));
969238106Sdes	if(!r)
970238106Sdes		return 0;
971238106Sdes	r->buf = buf;
972238106Sdes	log_assert(fptr_whitelist_mesh_cb(cb)); /* early failure ifmissing*/
973238106Sdes	r->cb = cb;
974238106Sdes	r->cb_arg = cb_arg;
975238106Sdes	r->edns = *edns;
976238106Sdes	r->qid = qid;
977238106Sdes	r->qflags = qflags;
978238106Sdes	r->next = s->cb_list;
979238106Sdes	s->cb_list = r;
980238106Sdes	return 1;
981238106Sdes
982238106Sdes}
983238106Sdes
984238106Sdesint mesh_state_add_reply(struct mesh_state* s, struct edns_data* edns,
985238106Sdes        struct comm_reply* rep, uint16_t qid, uint16_t qflags, uint8_t* qname)
986238106Sdes{
987238106Sdes	struct mesh_reply* r = regional_alloc(s->s.region,
988238106Sdes		sizeof(struct mesh_reply));
989238106Sdes	if(!r)
990238106Sdes		return 0;
991238106Sdes	r->query_reply = *rep;
992238106Sdes	r->edns = *edns;
993238106Sdes	r->qid = qid;
994238106Sdes	r->qflags = qflags;
995238106Sdes	r->start_time = *s->s.env->now_tv;
996238106Sdes	r->next = s->reply_list;
997238106Sdes	r->qname = regional_alloc_init(s->s.region, qname,
998238106Sdes		s->s.qinfo.qname_len);
999238106Sdes	if(!r->qname)
1000238106Sdes		return 0;
1001238106Sdes	s->reply_list = r;
1002238106Sdes	return 1;
1003238106Sdes
1004238106Sdes}
1005238106Sdes
1006238106Sdes/**
1007238106Sdes * Continue processing the mesh state at another module.
1008238106Sdes * Handles module to modules tranfer of control.
1009238106Sdes * Handles module finished.
1010238106Sdes * @param mesh: the mesh area.
1011238106Sdes * @param mstate: currently active mesh state.
1012238106Sdes * 	Deleted if finished, calls _done and _supers to
1013238106Sdes * 	send replies to clients and inform other mesh states.
1014238106Sdes * 	This in turn may create additional runnable mesh states.
1015238106Sdes * @param s: state at which the current module exited.
1016238106Sdes * @param ev: the event sent to the module.
1017238106Sdes * 	returned is the event to send to the next module.
1018238106Sdes * @return true if continue processing at the new module.
1019238106Sdes * 	false if not continued processing is needed.
1020238106Sdes */
1021238106Sdesstatic int
1022238106Sdesmesh_continue(struct mesh_area* mesh, struct mesh_state* mstate,
1023238106Sdes	enum module_ext_state s, enum module_ev* ev)
1024238106Sdes{
1025238106Sdes	mstate->num_activated++;
1026238106Sdes	if(mstate->num_activated > MESH_MAX_ACTIVATION) {
1027238106Sdes		/* module is looping. Stop it. */
1028238106Sdes		log_err("internal error: looping module stopped");
1029238106Sdes		log_query_info(VERB_QUERY, "pass error for qstate",
1030238106Sdes			&mstate->s.qinfo);
1031238106Sdes		s = module_error;
1032238106Sdes	}
1033238106Sdes	if(s == module_wait_module || s == module_restart_next) {
1034238106Sdes		/* start next module */
1035238106Sdes		mstate->s.curmod++;
1036238106Sdes		if(mesh->mods.num == mstate->s.curmod) {
1037238106Sdes			log_err("Cannot pass to next module; at last module");
1038238106Sdes			log_query_info(VERB_QUERY, "pass error for qstate",
1039238106Sdes				&mstate->s.qinfo);
1040238106Sdes			mstate->s.curmod--;
1041238106Sdes			return mesh_continue(mesh, mstate, module_error, ev);
1042238106Sdes		}
1043238106Sdes		if(s == module_restart_next) {
1044238106Sdes			fptr_ok(fptr_whitelist_mod_clear(
1045238106Sdes				mesh->mods.mod[mstate->s.curmod]->clear));
1046238106Sdes			(*mesh->mods.mod[mstate->s.curmod]->clear)
1047238106Sdes				(&mstate->s, mstate->s.curmod);
1048238106Sdes			mstate->s.minfo[mstate->s.curmod] = NULL;
1049238106Sdes		}
1050238106Sdes		*ev = module_event_pass;
1051238106Sdes		return 1;
1052238106Sdes	}
1053238106Sdes	if(s == module_error && mstate->s.return_rcode == LDNS_RCODE_NOERROR) {
1054238106Sdes		/* error is bad, handle pass back up below */
1055238106Sdes		mstate->s.return_rcode = LDNS_RCODE_SERVFAIL;
1056238106Sdes	}
1057238106Sdes	if(s == module_error || s == module_finished) {
1058238106Sdes		if(mstate->s.curmod == 0) {
1059238106Sdes			mesh_query_done(mstate);
1060238106Sdes			mesh_walk_supers(mesh, mstate);
1061238106Sdes			mesh_state_delete(&mstate->s);
1062238106Sdes			return 0;
1063238106Sdes		}
1064238106Sdes		/* pass along the locus of control */
1065238106Sdes		mstate->s.curmod --;
1066238106Sdes		*ev = module_event_moddone;
1067238106Sdes		return 1;
1068238106Sdes	}
1069238106Sdes	return 0;
1070238106Sdes}
1071238106Sdes
1072238106Sdesvoid mesh_run(struct mesh_area* mesh, struct mesh_state* mstate,
1073238106Sdes	enum module_ev ev, struct outbound_entry* e)
1074238106Sdes{
1075238106Sdes	enum module_ext_state s;
1076238106Sdes	verbose(VERB_ALGO, "mesh_run: start");
1077238106Sdes	while(mstate) {
1078238106Sdes		/* run the module */
1079238106Sdes		fptr_ok(fptr_whitelist_mod_operate(
1080238106Sdes			mesh->mods.mod[mstate->s.curmod]->operate));
1081238106Sdes		(*mesh->mods.mod[mstate->s.curmod]->operate)
1082238106Sdes			(&mstate->s, ev, mstate->s.curmod, e);
1083238106Sdes
1084238106Sdes		/* examine results */
1085238106Sdes		mstate->s.reply = NULL;
1086238106Sdes		regional_free_all(mstate->s.env->scratch);
1087238106Sdes		s = mstate->s.ext_state[mstate->s.curmod];
1088238106Sdes		verbose(VERB_ALGO, "mesh_run: %s module exit state is %s",
1089238106Sdes			mesh->mods.mod[mstate->s.curmod]->name, strextstate(s));
1090238106Sdes		e = NULL;
1091238106Sdes		if(mesh_continue(mesh, mstate, s, &ev))
1092238106Sdes			continue;
1093238106Sdes
1094238106Sdes		/* run more modules */
1095238106Sdes		ev = module_event_pass;
1096238106Sdes		if(mesh->run.count > 0) {
1097238106Sdes			/* pop random element off the runnable tree */
1098238106Sdes			mstate = (struct mesh_state*)mesh->run.root->key;
1099238106Sdes			(void)rbtree_delete(&mesh->run, mstate);
1100238106Sdes		} else mstate = NULL;
1101238106Sdes	}
1102238106Sdes	if(verbosity >= VERB_ALGO) {
1103238106Sdes		mesh_stats(mesh, "mesh_run: end");
1104238106Sdes		mesh_log_list(mesh);
1105238106Sdes	}
1106238106Sdes}
1107238106Sdes
1108238106Sdesvoid
1109238106Sdesmesh_log_list(struct mesh_area* mesh)
1110238106Sdes{
1111238106Sdes	char buf[30];
1112238106Sdes	struct mesh_state* m;
1113238106Sdes	int num = 0;
1114238106Sdes	RBTREE_FOR(m, struct mesh_state*, &mesh->all) {
1115285206Sdes		snprintf(buf, sizeof(buf), "%d%s%s%s%s%s%s mod%d %s%s",
1116238106Sdes			num++, (m->s.is_priming)?"p":"",  /* prime */
1117285206Sdes			(m->s.is_valrec)?"v":"",  /* prime */
1118238106Sdes			(m->s.query_flags&BIT_RD)?"RD":"",
1119238106Sdes			(m->s.query_flags&BIT_CD)?"CD":"",
1120238106Sdes			(m->super_set.count==0)?"d":"", /* detached */
1121238106Sdes			(m->sub_set.count!=0)?"c":"",  /* children */
1122238106Sdes			m->s.curmod, (m->reply_list)?"rep":"", /*hasreply*/
1123238106Sdes			(m->cb_list)?"cb":"" /* callbacks */
1124238106Sdes			);
1125238106Sdes		log_query_info(VERB_ALGO, buf, &m->s.qinfo);
1126238106Sdes	}
1127238106Sdes}
1128238106Sdes
1129238106Sdesvoid
1130238106Sdesmesh_stats(struct mesh_area* mesh, const char* str)
1131238106Sdes{
1132238106Sdes	verbose(VERB_DETAIL, "%s %u recursion states (%u with reply, "
1133238106Sdes		"%u detached), %u waiting replies, %u recursion replies "
1134238106Sdes		"sent, %d replies dropped, %d states jostled out",
1135238106Sdes		str, (unsigned)mesh->all.count,
1136238106Sdes		(unsigned)mesh->num_reply_states,
1137238106Sdes		(unsigned)mesh->num_detached_states,
1138238106Sdes		(unsigned)mesh->num_reply_addrs,
1139238106Sdes		(unsigned)mesh->replies_sent,
1140238106Sdes		(unsigned)mesh->stats_dropped,
1141238106Sdes		(unsigned)mesh->stats_jostled);
1142238106Sdes	if(mesh->replies_sent > 0) {
1143238106Sdes		struct timeval avg;
1144238106Sdes		timeval_divide(&avg, &mesh->replies_sum_wait,
1145238106Sdes			mesh->replies_sent);
1146238106Sdes		log_info("average recursion processing time "
1147269257Sdes			ARG_LL "d.%6.6d sec",
1148269257Sdes			(long long)avg.tv_sec, (int)avg.tv_usec);
1149238106Sdes		log_info("histogram of recursion processing times");
1150238106Sdes		timehist_log(mesh->histogram, "recursions");
1151238106Sdes	}
1152238106Sdes}
1153238106Sdes
1154238106Sdesvoid
1155238106Sdesmesh_stats_clear(struct mesh_area* mesh)
1156238106Sdes{
1157238106Sdes	if(!mesh)
1158238106Sdes		return;
1159238106Sdes	mesh->replies_sent = 0;
1160238106Sdes	mesh->replies_sum_wait.tv_sec = 0;
1161238106Sdes	mesh->replies_sum_wait.tv_usec = 0;
1162238106Sdes	mesh->stats_jostled = 0;
1163238106Sdes	mesh->stats_dropped = 0;
1164238106Sdes	timehist_clear(mesh->histogram);
1165238106Sdes	mesh->ans_secure = 0;
1166238106Sdes	mesh->ans_bogus = 0;
1167238106Sdes	memset(&mesh->ans_rcode[0], 0, sizeof(size_t)*16);
1168238106Sdes	mesh->ans_nodata = 0;
1169238106Sdes}
1170238106Sdes
1171238106Sdessize_t
1172238106Sdesmesh_get_mem(struct mesh_area* mesh)
1173238106Sdes{
1174238106Sdes	struct mesh_state* m;
1175238106Sdes	size_t s = sizeof(*mesh) + sizeof(struct timehist) +
1176238106Sdes		sizeof(struct th_buck)*mesh->histogram->num +
1177269257Sdes		sizeof(sldns_buffer) + sldns_buffer_capacity(mesh->qbuf_bak);
1178238106Sdes	RBTREE_FOR(m, struct mesh_state*, &mesh->all) {
1179238106Sdes		/* all, including m itself allocated in qstate region */
1180238106Sdes		s += regional_get_mem(m->s.region);
1181238106Sdes	}
1182238106Sdes	return s;
1183238106Sdes}
1184238106Sdes
1185238106Sdesint
1186238106Sdesmesh_detect_cycle(struct module_qstate* qstate, struct query_info* qinfo,
1187285206Sdes	uint16_t flags, int prime, int valrec)
1188238106Sdes{
1189238106Sdes	struct mesh_area* mesh = qstate->env->mesh;
1190285206Sdes	struct mesh_state* dep_m = mesh_area_find(mesh, qinfo, flags, prime,
1191285206Sdes		valrec);
1192238106Sdes	return mesh_detect_cycle_found(qstate, dep_m);
1193238106Sdes}
1194238106Sdes
1195238106Sdesvoid mesh_list_insert(struct mesh_state* m, struct mesh_state** fp,
1196238106Sdes        struct mesh_state** lp)
1197238106Sdes{
1198238106Sdes	/* insert as last element */
1199238106Sdes	m->prev = *lp;
1200238106Sdes	m->next = NULL;
1201238106Sdes	if(*lp)
1202238106Sdes		(*lp)->next = m;
1203238106Sdes	else	*fp = m;
1204238106Sdes	*lp = m;
1205238106Sdes}
1206238106Sdes
1207238106Sdesvoid mesh_list_remove(struct mesh_state* m, struct mesh_state** fp,
1208238106Sdes        struct mesh_state** lp)
1209238106Sdes{
1210238106Sdes	if(m->next)
1211238106Sdes		m->next->prev = m->prev;
1212238106Sdes	else	*lp = m->prev;
1213238106Sdes	if(m->prev)
1214238106Sdes		m->prev->next = m->next;
1215238106Sdes	else	*fp = m->next;
1216238106Sdes}
1217