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"
58269257Sdes#include "ldns/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
135238106Sdes	if((a->s.query_flags&BIT_RD) && !(b->s.query_flags&BIT_RD))
136238106Sdes		return -1;
137238106Sdes	if(!(a->s.query_flags&BIT_RD) && (b->s.query_flags&BIT_RD))
138238106Sdes		return 1;
139238106Sdes
140238106Sdes	if((a->s.query_flags&BIT_CD) && !(b->s.query_flags&BIT_CD))
141238106Sdes		return -1;
142238106Sdes	if(!(a->s.query_flags&BIT_CD) && (b->s.query_flags&BIT_CD))
143238106Sdes		return 1;
144238106Sdes
145238106Sdes	return query_info_compare(&a->s.qinfo, &b->s.qinfo);
146238106Sdes}
147238106Sdes
148238106Sdesint
149238106Sdesmesh_state_ref_compare(const void* ap, const void* bp)
150238106Sdes{
151238106Sdes	struct mesh_state_ref* a = (struct mesh_state_ref*)ap;
152238106Sdes	struct mesh_state_ref* b = (struct mesh_state_ref*)bp;
153238106Sdes	return mesh_state_compare(a->s, b->s);
154238106Sdes}
155238106Sdes
156238106Sdesstruct mesh_area*
157238106Sdesmesh_create(struct module_stack* stack, struct module_env* env)
158238106Sdes{
159238106Sdes	struct mesh_area* mesh = calloc(1, sizeof(struct mesh_area));
160238106Sdes	if(!mesh) {
161238106Sdes		log_err("mesh area alloc: out of memory");
162238106Sdes		return NULL;
163238106Sdes	}
164238106Sdes	mesh->histogram = timehist_setup();
165269257Sdes	mesh->qbuf_bak = sldns_buffer_new(env->cfg->msg_buffer_size);
166238106Sdes	if(!mesh->histogram || !mesh->qbuf_bak) {
167238106Sdes		free(mesh);
168238106Sdes		log_err("mesh area alloc: out of memory");
169238106Sdes		return NULL;
170238106Sdes	}
171238106Sdes	mesh->mods = *stack;
172238106Sdes	mesh->env = env;
173238106Sdes	rbtree_init(&mesh->run, &mesh_state_compare);
174238106Sdes	rbtree_init(&mesh->all, &mesh_state_compare);
175238106Sdes	mesh->num_reply_addrs = 0;
176238106Sdes	mesh->num_reply_states = 0;
177238106Sdes	mesh->num_detached_states = 0;
178238106Sdes	mesh->num_forever_states = 0;
179238106Sdes	mesh->stats_jostled = 0;
180238106Sdes	mesh->stats_dropped = 0;
181238106Sdes	mesh->max_reply_states = env->cfg->num_queries_per_thread;
182238106Sdes	mesh->max_forever_states = (mesh->max_reply_states+1)/2;
183238106Sdes#ifndef S_SPLINT_S
184238106Sdes	mesh->jostle_max.tv_sec = (time_t)(env->cfg->jostle_time / 1000);
185238106Sdes	mesh->jostle_max.tv_usec = (time_t)((env->cfg->jostle_time % 1000)
186238106Sdes		*1000);
187238106Sdes#endif
188238106Sdes	return mesh;
189238106Sdes}
190238106Sdes
191238106Sdes/** help mesh delete delete mesh states */
192238106Sdesstatic void
193238106Sdesmesh_delete_helper(rbnode_t* n)
194238106Sdes{
195238106Sdes	struct mesh_state* mstate = (struct mesh_state*)n->key;
196238106Sdes	/* perform a full delete, not only 'cleanup' routine,
197238106Sdes	 * because other callbacks expect a clean state in the mesh.
198238106Sdes	 * For 're-entrant' calls */
199238106Sdes	mesh_state_delete(&mstate->s);
200238106Sdes	/* but because these delete the items from the tree, postorder
201238106Sdes	 * traversal and rbtree rebalancing do not work together */
202238106Sdes}
203238106Sdes
204238106Sdesvoid
205238106Sdesmesh_delete(struct mesh_area* mesh)
206238106Sdes{
207238106Sdes	if(!mesh)
208238106Sdes		return;
209238106Sdes	/* free all query states */
210238106Sdes	while(mesh->all.count)
211238106Sdes		mesh_delete_helper(mesh->all.root);
212238106Sdes	timehist_delete(mesh->histogram);
213269257Sdes	sldns_buffer_free(mesh->qbuf_bak);
214238106Sdes	free(mesh);
215238106Sdes}
216238106Sdes
217238106Sdesvoid
218238106Sdesmesh_delete_all(struct mesh_area* mesh)
219238106Sdes{
220238106Sdes	/* free all query states */
221238106Sdes	while(mesh->all.count)
222238106Sdes		mesh_delete_helper(mesh->all.root);
223238106Sdes	mesh->stats_dropped += mesh->num_reply_addrs;
224238106Sdes	/* clear mesh area references */
225238106Sdes	rbtree_init(&mesh->run, &mesh_state_compare);
226238106Sdes	rbtree_init(&mesh->all, &mesh_state_compare);
227238106Sdes	mesh->num_reply_addrs = 0;
228238106Sdes	mesh->num_reply_states = 0;
229238106Sdes	mesh->num_detached_states = 0;
230238106Sdes	mesh->num_forever_states = 0;
231238106Sdes	mesh->forever_first = NULL;
232238106Sdes	mesh->forever_last = NULL;
233238106Sdes	mesh->jostle_first = NULL;
234238106Sdes	mesh->jostle_last = NULL;
235238106Sdes}
236238106Sdes
237269257Sdesint mesh_make_new_space(struct mesh_area* mesh, sldns_buffer* qbuf)
238238106Sdes{
239238106Sdes	struct mesh_state* m = mesh->jostle_first;
240238106Sdes	/* free space is available */
241238106Sdes	if(mesh->num_reply_states < mesh->max_reply_states)
242238106Sdes		return 1;
243238106Sdes	/* try to kick out a jostle-list item */
244238106Sdes	if(m && m->reply_list && m->list_select == mesh_jostle_list) {
245238106Sdes		/* how old is it? */
246238106Sdes		struct timeval age;
247238106Sdes		timeval_subtract(&age, mesh->env->now_tv,
248238106Sdes			&m->reply_list->start_time);
249238106Sdes		if(timeval_smaller(&mesh->jostle_max, &age)) {
250238106Sdes			/* its a goner */
251238106Sdes			log_nametypeclass(VERB_ALGO, "query jostled out to "
252238106Sdes				"make space for a new one",
253238106Sdes				m->s.qinfo.qname, m->s.qinfo.qtype,
254238106Sdes				m->s.qinfo.qclass);
255238106Sdes			/* backup the query */
256269257Sdes			if(qbuf) sldns_buffer_copy(mesh->qbuf_bak, qbuf);
257238106Sdes			/* notify supers */
258238106Sdes			if(m->super_set.count > 0) {
259238106Sdes				verbose(VERB_ALGO, "notify supers of failure");
260238106Sdes				m->s.return_msg = NULL;
261238106Sdes				m->s.return_rcode = LDNS_RCODE_SERVFAIL;
262238106Sdes				mesh_walk_supers(mesh, m);
263238106Sdes			}
264238106Sdes			mesh->stats_jostled ++;
265238106Sdes			mesh_state_delete(&m->s);
266238106Sdes			/* restore the query - note that the qinfo ptr to
267238106Sdes			 * the querybuffer is then correct again. */
268269257Sdes			if(qbuf) sldns_buffer_copy(qbuf, mesh->qbuf_bak);
269238106Sdes			return 1;
270238106Sdes		}
271238106Sdes	}
272238106Sdes	/* no space for new item */
273238106Sdes	return 0;
274238106Sdes}
275238106Sdes
276238106Sdesvoid mesh_new_client(struct mesh_area* mesh, struct query_info* qinfo,
277238106Sdes        uint16_t qflags, struct edns_data* edns, struct comm_reply* rep,
278238106Sdes        uint16_t qid)
279238106Sdes{
280238106Sdes	/* do not use CD flag from user for mesh state, we want the CD-query
281238106Sdes	 * to receive validation anyway, to protect out cache contents and
282238106Sdes	 * avoid bad-data in this cache that a downstream validator cannot
283238106Sdes	 * remove from this cache */
284238106Sdes	struct mesh_state* s = mesh_area_find(mesh, qinfo, qflags&BIT_RD, 0);
285238106Sdes	int was_detached = 0;
286238106Sdes	int was_noreply = 0;
287238106Sdes	int added = 0;
288238106Sdes	/* does this create a new reply state? */
289238106Sdes	if(!s || s->list_select == mesh_no_list) {
290238106Sdes		if(!mesh_make_new_space(mesh, rep->c->buffer)) {
291238106Sdes			verbose(VERB_ALGO, "Too many queries. dropping "
292238106Sdes				"incoming query.");
293238106Sdes			comm_point_drop_reply(rep);
294238106Sdes			mesh->stats_dropped ++;
295238106Sdes			return;
296238106Sdes		}
297238106Sdes		/* for this new reply state, the reply address is free,
298238106Sdes		 * so the limit of reply addresses does not stop reply states*/
299238106Sdes	} else {
300238106Sdes		/* protect our memory usage from storing reply addresses */
301238106Sdes		if(mesh->num_reply_addrs > mesh->max_reply_states*16) {
302238106Sdes			verbose(VERB_ALGO, "Too many requests queued. "
303238106Sdes				"dropping incoming query.");
304238106Sdes			mesh->stats_dropped++;
305238106Sdes			comm_point_drop_reply(rep);
306238106Sdes			return;
307238106Sdes		}
308238106Sdes	}
309238106Sdes	/* see if it already exists, if not, create one */
310238106Sdes	if(!s) {
311238106Sdes#ifdef UNBOUND_DEBUG
312238106Sdes		struct rbnode_t* n;
313238106Sdes#endif
314238106Sdes		s = mesh_state_create(mesh->env, qinfo, qflags&BIT_RD, 0);
315238106Sdes		if(!s) {
316238106Sdes			log_err("mesh_state_create: out of memory; SERVFAIL");
317238106Sdes			error_encode(rep->c->buffer, LDNS_RCODE_SERVFAIL,
318238106Sdes				qinfo, qid, qflags, edns);
319238106Sdes			comm_point_send_reply(rep);
320238106Sdes			return;
321238106Sdes		}
322238106Sdes#ifdef UNBOUND_DEBUG
323238106Sdes		n =
324269257Sdes#else
325269257Sdes		(void)
326238106Sdes#endif
327238106Sdes		rbtree_insert(&mesh->all, &s->node);
328238106Sdes		log_assert(n != NULL);
329238106Sdes		/* set detached (it is now) */
330238106Sdes		mesh->num_detached_states++;
331238106Sdes		added = 1;
332238106Sdes	}
333238106Sdes	if(!s->reply_list && !s->cb_list && s->super_set.count == 0)
334238106Sdes		was_detached = 1;
335238106Sdes	if(!s->reply_list && !s->cb_list)
336238106Sdes		was_noreply = 1;
337238106Sdes	/* add reply to s */
338238106Sdes	if(!mesh_state_add_reply(s, edns, rep, qid, qflags, qinfo->qname)) {
339238106Sdes			log_err("mesh_new_client: out of memory; SERVFAIL");
340238106Sdes			error_encode(rep->c->buffer, LDNS_RCODE_SERVFAIL,
341238106Sdes				qinfo, qid, qflags, edns);
342238106Sdes			comm_point_send_reply(rep);
343238106Sdes			if(added)
344238106Sdes				mesh_state_delete(&s->s);
345238106Sdes			return;
346238106Sdes	}
347238106Sdes	/* update statistics */
348238106Sdes	if(was_detached) {
349238106Sdes		log_assert(mesh->num_detached_states > 0);
350238106Sdes		mesh->num_detached_states--;
351238106Sdes	}
352238106Sdes	if(was_noreply) {
353238106Sdes		mesh->num_reply_states ++;
354238106Sdes	}
355238106Sdes	mesh->num_reply_addrs++;
356238106Sdes	if(s->list_select == mesh_no_list) {
357238106Sdes		/* move to either the forever or the jostle_list */
358238106Sdes		if(mesh->num_forever_states < mesh->max_forever_states) {
359238106Sdes			mesh->num_forever_states ++;
360238106Sdes			mesh_list_insert(s, &mesh->forever_first,
361238106Sdes				&mesh->forever_last);
362238106Sdes			s->list_select = mesh_forever_list;
363238106Sdes		} else {
364238106Sdes			mesh_list_insert(s, &mesh->jostle_first,
365238106Sdes				&mesh->jostle_last);
366238106Sdes			s->list_select = mesh_jostle_list;
367238106Sdes		}
368238106Sdes	}
369238106Sdes	if(added)
370238106Sdes		mesh_run(mesh, s, module_event_new, NULL);
371238106Sdes}
372238106Sdes
373238106Sdesint
374238106Sdesmesh_new_callback(struct mesh_area* mesh, struct query_info* qinfo,
375269257Sdes	uint16_t qflags, struct edns_data* edns, sldns_buffer* buf,
376238106Sdes	uint16_t qid, mesh_cb_func_t cb, void* cb_arg)
377238106Sdes{
378238106Sdes	struct mesh_state* s = mesh_area_find(mesh, qinfo, qflags&BIT_RD, 0);
379238106Sdes	int was_detached = 0;
380238106Sdes	int was_noreply = 0;
381238106Sdes	int added = 0;
382238106Sdes	/* there are no limits on the number of callbacks */
383238106Sdes
384238106Sdes	/* see if it already exists, if not, create one */
385238106Sdes	if(!s) {
386238106Sdes#ifdef UNBOUND_DEBUG
387238106Sdes		struct rbnode_t* n;
388238106Sdes#endif
389238106Sdes		s = mesh_state_create(mesh->env, qinfo, qflags&BIT_RD, 0);
390238106Sdes		if(!s) {
391238106Sdes			return 0;
392238106Sdes		}
393238106Sdes#ifdef UNBOUND_DEBUG
394238106Sdes		n =
395269257Sdes#else
396269257Sdes		(void)
397238106Sdes#endif
398238106Sdes		rbtree_insert(&mesh->all, &s->node);
399238106Sdes		log_assert(n != NULL);
400238106Sdes		/* set detached (it is now) */
401238106Sdes		mesh->num_detached_states++;
402238106Sdes		added = 1;
403238106Sdes	}
404238106Sdes	if(!s->reply_list && !s->cb_list && s->super_set.count == 0)
405238106Sdes		was_detached = 1;
406238106Sdes	if(!s->reply_list && !s->cb_list)
407238106Sdes		was_noreply = 1;
408238106Sdes	/* add reply to s */
409238106Sdes	if(!mesh_state_add_cb(s, edns, buf, cb, cb_arg, qid, qflags)) {
410238106Sdes			if(added)
411238106Sdes				mesh_state_delete(&s->s);
412238106Sdes			return 0;
413238106Sdes	}
414238106Sdes	/* update statistics */
415238106Sdes	if(was_detached) {
416238106Sdes		log_assert(mesh->num_detached_states > 0);
417238106Sdes		mesh->num_detached_states--;
418238106Sdes	}
419238106Sdes	if(was_noreply) {
420238106Sdes		mesh->num_reply_states ++;
421238106Sdes	}
422238106Sdes	mesh->num_reply_addrs++;
423238106Sdes	if(added)
424238106Sdes		mesh_run(mesh, s, module_event_new, NULL);
425238106Sdes	return 1;
426238106Sdes}
427238106Sdes
428238106Sdesvoid mesh_new_prefetch(struct mesh_area* mesh, struct query_info* qinfo,
429269257Sdes        uint16_t qflags, time_t leeway)
430238106Sdes{
431238106Sdes	struct mesh_state* s = mesh_area_find(mesh, qinfo, qflags&BIT_RD, 0);
432238106Sdes#ifdef UNBOUND_DEBUG
433238106Sdes	struct rbnode_t* n;
434238106Sdes#endif
435238106Sdes	/* already exists, and for a different purpose perhaps.
436238106Sdes	 * if mesh_no_list, keep it that way. */
437238106Sdes	if(s) {
438238106Sdes		/* make it ignore the cache from now on */
439238106Sdes		if(!s->s.blacklist)
440238106Sdes			sock_list_insert(&s->s.blacklist, NULL, 0, s->s.region);
441238106Sdes		if(s->s.prefetch_leeway < leeway)
442238106Sdes			s->s.prefetch_leeway = leeway;
443238106Sdes		return;
444238106Sdes	}
445238106Sdes	if(!mesh_make_new_space(mesh, NULL)) {
446238106Sdes		verbose(VERB_ALGO, "Too many queries. dropped prefetch.");
447238106Sdes		mesh->stats_dropped ++;
448238106Sdes		return;
449238106Sdes	}
450238106Sdes	s = mesh_state_create(mesh->env, qinfo, qflags&BIT_RD, 0);
451238106Sdes	if(!s) {
452238106Sdes		log_err("prefetch mesh_state_create: out of memory");
453238106Sdes		return;
454238106Sdes	}
455238106Sdes#ifdef UNBOUND_DEBUG
456238106Sdes	n =
457269257Sdes#else
458269257Sdes	(void)
459238106Sdes#endif
460238106Sdes	rbtree_insert(&mesh->all, &s->node);
461238106Sdes	log_assert(n != NULL);
462238106Sdes	/* set detached (it is now) */
463238106Sdes	mesh->num_detached_states++;
464238106Sdes	/* make it ignore the cache */
465238106Sdes	sock_list_insert(&s->s.blacklist, NULL, 0, s->s.region);
466238106Sdes	s->s.prefetch_leeway = leeway;
467238106Sdes
468238106Sdes	if(s->list_select == mesh_no_list) {
469238106Sdes		/* move to either the forever or the jostle_list */
470238106Sdes		if(mesh->num_forever_states < mesh->max_forever_states) {
471238106Sdes			mesh->num_forever_states ++;
472238106Sdes			mesh_list_insert(s, &mesh->forever_first,
473238106Sdes				&mesh->forever_last);
474238106Sdes			s->list_select = mesh_forever_list;
475238106Sdes		} else {
476238106Sdes			mesh_list_insert(s, &mesh->jostle_first,
477238106Sdes				&mesh->jostle_last);
478238106Sdes			s->list_select = mesh_jostle_list;
479238106Sdes		}
480238106Sdes	}
481238106Sdes	mesh_run(mesh, s, module_event_new, NULL);
482238106Sdes}
483238106Sdes
484238106Sdesvoid mesh_report_reply(struct mesh_area* mesh, struct outbound_entry* e,
485238106Sdes        struct comm_reply* reply, int what)
486238106Sdes{
487238106Sdes	enum module_ev event = module_event_reply;
488238106Sdes	e->qstate->reply = reply;
489238106Sdes	if(what != NETEVENT_NOERROR) {
490238106Sdes		event = module_event_noreply;
491238106Sdes		if(what == NETEVENT_CAPSFAIL)
492238106Sdes			event = module_event_capsfail;
493238106Sdes	}
494238106Sdes	mesh_run(mesh, e->qstate->mesh_info, event, e);
495238106Sdes}
496238106Sdes
497238106Sdesstruct mesh_state*
498238106Sdesmesh_state_create(struct module_env* env, struct query_info* qinfo,
499238106Sdes	uint16_t qflags, int prime)
500238106Sdes{
501238106Sdes	struct regional* region = alloc_reg_obtain(env->alloc);
502238106Sdes	struct mesh_state* mstate;
503238106Sdes	int i;
504238106Sdes	if(!region)
505238106Sdes		return NULL;
506238106Sdes	mstate = (struct mesh_state*)regional_alloc(region,
507238106Sdes		sizeof(struct mesh_state));
508238106Sdes	if(!mstate) {
509238106Sdes		alloc_reg_release(env->alloc, region);
510238106Sdes		return NULL;
511238106Sdes	}
512238106Sdes	memset(mstate, 0, sizeof(*mstate));
513238106Sdes	mstate->node = *RBTREE_NULL;
514238106Sdes	mstate->run_node = *RBTREE_NULL;
515238106Sdes	mstate->node.key = mstate;
516238106Sdes	mstate->run_node.key = mstate;
517238106Sdes	mstate->reply_list = NULL;
518238106Sdes	mstate->list_select = mesh_no_list;
519238106Sdes	mstate->replies_sent = 0;
520238106Sdes	rbtree_init(&mstate->super_set, &mesh_state_ref_compare);
521238106Sdes	rbtree_init(&mstate->sub_set, &mesh_state_ref_compare);
522238106Sdes	mstate->num_activated = 0;
523238106Sdes	/* init module qstate */
524238106Sdes	mstate->s.qinfo.qtype = qinfo->qtype;
525238106Sdes	mstate->s.qinfo.qclass = qinfo->qclass;
526238106Sdes	mstate->s.qinfo.qname_len = qinfo->qname_len;
527238106Sdes	mstate->s.qinfo.qname = regional_alloc_init(region, qinfo->qname,
528238106Sdes		qinfo->qname_len);
529238106Sdes	if(!mstate->s.qinfo.qname) {
530238106Sdes		alloc_reg_release(env->alloc, region);
531238106Sdes		return NULL;
532238106Sdes	}
533238106Sdes	/* remove all weird bits from qflags */
534238106Sdes	mstate->s.query_flags = (qflags & (BIT_RD|BIT_CD));
535238106Sdes	mstate->s.is_priming = prime;
536238106Sdes	mstate->s.reply = NULL;
537238106Sdes	mstate->s.region = region;
538238106Sdes	mstate->s.curmod = 0;
539238106Sdes	mstate->s.return_msg = 0;
540238106Sdes	mstate->s.return_rcode = LDNS_RCODE_NOERROR;
541238106Sdes	mstate->s.env = env;
542238106Sdes	mstate->s.mesh_info = mstate;
543238106Sdes	mstate->s.prefetch_leeway = 0;
544238106Sdes	/* init modules */
545238106Sdes	for(i=0; i<env->mesh->mods.num; i++) {
546238106Sdes		mstate->s.minfo[i] = NULL;
547238106Sdes		mstate->s.ext_state[i] = module_state_initial;
548238106Sdes	}
549238106Sdes	return mstate;
550238106Sdes}
551238106Sdes
552238106Sdesvoid
553238106Sdesmesh_state_cleanup(struct mesh_state* mstate)
554238106Sdes{
555238106Sdes	struct mesh_area* mesh;
556238106Sdes	int i;
557238106Sdes	if(!mstate)
558238106Sdes		return;
559238106Sdes	mesh = mstate->s.env->mesh;
560238106Sdes	/* drop unsent replies */
561238106Sdes	if(!mstate->replies_sent) {
562238106Sdes		struct mesh_reply* rep;
563238106Sdes		struct mesh_cb* cb;
564238106Sdes		for(rep=mstate->reply_list; rep; rep=rep->next) {
565238106Sdes			comm_point_drop_reply(&rep->query_reply);
566238106Sdes			mesh->num_reply_addrs--;
567238106Sdes		}
568238106Sdes		for(cb=mstate->cb_list; cb; cb=cb->next) {
569238106Sdes			fptr_ok(fptr_whitelist_mesh_cb(cb->cb));
570238106Sdes			(*cb->cb)(cb->cb_arg, LDNS_RCODE_SERVFAIL, NULL,
571238106Sdes				sec_status_unchecked, NULL);
572238106Sdes			mesh->num_reply_addrs--;
573238106Sdes		}
574238106Sdes	}
575238106Sdes
576238106Sdes	/* de-init modules */
577238106Sdes	for(i=0; i<mesh->mods.num; i++) {
578238106Sdes		fptr_ok(fptr_whitelist_mod_clear(mesh->mods.mod[i]->clear));
579238106Sdes		(*mesh->mods.mod[i]->clear)(&mstate->s, i);
580238106Sdes		mstate->s.minfo[i] = NULL;
581238106Sdes		mstate->s.ext_state[i] = module_finished;
582238106Sdes	}
583238106Sdes	alloc_reg_release(mstate->s.env->alloc, mstate->s.region);
584238106Sdes}
585238106Sdes
586238106Sdesvoid
587238106Sdesmesh_state_delete(struct module_qstate* qstate)
588238106Sdes{
589238106Sdes	struct mesh_area* mesh;
590238106Sdes	struct mesh_state_ref* super, ref;
591238106Sdes	struct mesh_state* mstate;
592238106Sdes	if(!qstate)
593238106Sdes		return;
594238106Sdes	mstate = qstate->mesh_info;
595238106Sdes	mesh = mstate->s.env->mesh;
596238106Sdes	mesh_detach_subs(&mstate->s);
597238106Sdes	if(mstate->list_select == mesh_forever_list) {
598238106Sdes		mesh->num_forever_states --;
599238106Sdes		mesh_list_remove(mstate, &mesh->forever_first,
600238106Sdes			&mesh->forever_last);
601238106Sdes	} else if(mstate->list_select == mesh_jostle_list) {
602238106Sdes		mesh_list_remove(mstate, &mesh->jostle_first,
603238106Sdes			&mesh->jostle_last);
604238106Sdes	}
605238106Sdes	if(!mstate->reply_list && !mstate->cb_list
606238106Sdes		&& mstate->super_set.count == 0) {
607238106Sdes		log_assert(mesh->num_detached_states > 0);
608238106Sdes		mesh->num_detached_states--;
609238106Sdes	}
610238106Sdes	if(mstate->reply_list || mstate->cb_list) {
611238106Sdes		log_assert(mesh->num_reply_states > 0);
612238106Sdes		mesh->num_reply_states--;
613238106Sdes	}
614238106Sdes	ref.node.key = &ref;
615238106Sdes	ref.s = mstate;
616238106Sdes	RBTREE_FOR(super, struct mesh_state_ref*, &mstate->super_set) {
617238106Sdes		(void)rbtree_delete(&super->s->sub_set, &ref);
618238106Sdes	}
619238106Sdes	(void)rbtree_delete(&mesh->run, mstate);
620238106Sdes	(void)rbtree_delete(&mesh->all, mstate);
621238106Sdes	mesh_state_cleanup(mstate);
622238106Sdes}
623238106Sdes
624238106Sdes/** helper recursive rbtree find routine */
625238106Sdesstatic int
626238106Sdesfind_in_subsub(struct mesh_state* m, struct mesh_state* tofind, size_t *c)
627238106Sdes{
628238106Sdes	struct mesh_state_ref* r;
629238106Sdes	if((*c)++ > MESH_MAX_SUBSUB)
630238106Sdes		return 1;
631238106Sdes	RBTREE_FOR(r, struct mesh_state_ref*, &m->sub_set) {
632238106Sdes		if(r->s == tofind || find_in_subsub(r->s, tofind, c))
633238106Sdes			return 1;
634238106Sdes	}
635238106Sdes	return 0;
636238106Sdes}
637238106Sdes
638238106Sdes/** find cycle for already looked up mesh_state */
639238106Sdesstatic int
640238106Sdesmesh_detect_cycle_found(struct module_qstate* qstate, struct mesh_state* dep_m)
641238106Sdes{
642238106Sdes	struct mesh_state* cyc_m = qstate->mesh_info;
643238106Sdes	size_t counter = 0;
644238106Sdes	if(!dep_m)
645238106Sdes		return 0;
646238106Sdes	if(dep_m == cyc_m || find_in_subsub(dep_m, cyc_m, &counter)) {
647238106Sdes		if(counter > MESH_MAX_SUBSUB)
648238106Sdes			return 2;
649238106Sdes		return 1;
650238106Sdes	}
651238106Sdes	return 0;
652238106Sdes}
653238106Sdes
654238106Sdesvoid mesh_detach_subs(struct module_qstate* qstate)
655238106Sdes{
656238106Sdes	struct mesh_area* mesh = qstate->env->mesh;
657238106Sdes	struct mesh_state_ref* ref, lookup;
658238106Sdes#ifdef UNBOUND_DEBUG
659238106Sdes	struct rbnode_t* n;
660238106Sdes#endif
661238106Sdes	lookup.node.key = &lookup;
662238106Sdes	lookup.s = qstate->mesh_info;
663238106Sdes	RBTREE_FOR(ref, struct mesh_state_ref*, &qstate->mesh_info->sub_set) {
664238106Sdes#ifdef UNBOUND_DEBUG
665238106Sdes		n =
666269257Sdes#else
667269257Sdes		(void)
668238106Sdes#endif
669238106Sdes		rbtree_delete(&ref->s->super_set, &lookup);
670238106Sdes		log_assert(n != NULL); /* must have been present */
671238106Sdes		if(!ref->s->reply_list && !ref->s->cb_list
672238106Sdes			&& ref->s->super_set.count == 0) {
673238106Sdes			mesh->num_detached_states++;
674238106Sdes			log_assert(mesh->num_detached_states +
675238106Sdes				mesh->num_reply_states <= mesh->all.count);
676238106Sdes		}
677238106Sdes	}
678238106Sdes	rbtree_init(&qstate->mesh_info->sub_set, &mesh_state_ref_compare);
679238106Sdes}
680238106Sdes
681238106Sdesint mesh_attach_sub(struct module_qstate* qstate, struct query_info* qinfo,
682238106Sdes        uint16_t qflags, int prime, struct module_qstate** newq)
683238106Sdes{
684238106Sdes	/* find it, if not, create it */
685238106Sdes	struct mesh_area* mesh = qstate->env->mesh;
686238106Sdes	struct mesh_state* sub = mesh_area_find(mesh, qinfo, qflags, prime);
687249141Sdes	int was_detached;
688238106Sdes	if(mesh_detect_cycle_found(qstate, sub)) {
689238106Sdes		verbose(VERB_ALGO, "attach failed, cycle detected");
690238106Sdes		return 0;
691238106Sdes	}
692238106Sdes	if(!sub) {
693238106Sdes#ifdef UNBOUND_DEBUG
694238106Sdes		struct rbnode_t* n;
695238106Sdes#endif
696238106Sdes		/* create a new one */
697238106Sdes		sub = mesh_state_create(qstate->env, qinfo, qflags, prime);
698238106Sdes		if(!sub) {
699238106Sdes			log_err("mesh_attach_sub: out of memory");
700238106Sdes			return 0;
701238106Sdes		}
702238106Sdes#ifdef UNBOUND_DEBUG
703238106Sdes		n =
704269257Sdes#else
705269257Sdes		(void)
706238106Sdes#endif
707238106Sdes		rbtree_insert(&mesh->all, &sub->node);
708238106Sdes		log_assert(n != NULL);
709238106Sdes		/* set detached (it is now) */
710238106Sdes		mesh->num_detached_states++;
711238106Sdes		/* set new query state to run */
712238106Sdes#ifdef UNBOUND_DEBUG
713238106Sdes		n =
714269257Sdes#else
715269257Sdes		(void)
716238106Sdes#endif
717238106Sdes		rbtree_insert(&mesh->run, &sub->run_node);
718238106Sdes		log_assert(n != NULL);
719238106Sdes		*newq = &sub->s;
720238106Sdes	} else
721238106Sdes		*newq = NULL;
722249141Sdes	was_detached = (sub->super_set.count == 0);
723238106Sdes	if(!mesh_state_attachment(qstate->mesh_info, sub))
724238106Sdes		return 0;
725249141Sdes	/* if it was a duplicate  attachment, the count was not zero before */
726249141Sdes	if(!sub->reply_list && !sub->cb_list && was_detached &&
727249141Sdes		sub->super_set.count == 1) {
728238106Sdes		/* it used to be detached, before this one got added */
729238106Sdes		log_assert(mesh->num_detached_states > 0);
730238106Sdes		mesh->num_detached_states--;
731238106Sdes	}
732238106Sdes	/* *newq will be run when inited after the current module stops */
733238106Sdes	return 1;
734238106Sdes}
735238106Sdes
736238106Sdesint mesh_state_attachment(struct mesh_state* super, struct mesh_state* sub)
737238106Sdes{
738238106Sdes#ifdef UNBOUND_DEBUG
739238106Sdes	struct rbnode_t* n;
740238106Sdes#endif
741238106Sdes	struct mesh_state_ref* subref; /* points to sub, inserted in super */
742238106Sdes	struct mesh_state_ref* superref; /* points to super, inserted in sub */
743238106Sdes	if( !(subref = regional_alloc(super->s.region,
744238106Sdes		sizeof(struct mesh_state_ref))) ||
745238106Sdes		!(superref = regional_alloc(sub->s.region,
746238106Sdes		sizeof(struct mesh_state_ref))) ) {
747238106Sdes		log_err("mesh_state_attachment: out of memory");
748238106Sdes		return 0;
749238106Sdes	}
750238106Sdes	superref->node.key = superref;
751238106Sdes	superref->s = super;
752238106Sdes	subref->node.key = subref;
753238106Sdes	subref->s = sub;
754249141Sdes	if(!rbtree_insert(&sub->super_set, &superref->node)) {
755249141Sdes		/* this should not happen, iterator and validator do not
756249141Sdes		 * attach subqueries that are identical. */
757249141Sdes		/* already attached, we are done, nothing todo.
758249141Sdes		 * since superref and subref already allocated in region,
759249141Sdes		 * we cannot free them */
760249141Sdes		return 1;
761249141Sdes	}
762238106Sdes#ifdef UNBOUND_DEBUG
763238106Sdes	n =
764269257Sdes#else
765269257Sdes	(void)
766238106Sdes#endif
767238106Sdes	rbtree_insert(&super->sub_set, &subref->node);
768249141Sdes	log_assert(n != NULL); /* we checked above if statement, the reverse
769249141Sdes	  administration should not fail now, unless they are out of sync */
770238106Sdes	return 1;
771238106Sdes}
772238106Sdes
773238106Sdes/**
774238106Sdes * callback results to mesh cb entry
775238106Sdes * @param m: mesh state to send it for.
776238106Sdes * @param rcode: if not 0, error code.
777238106Sdes * @param rep: reply to send (or NULL if rcode is set).
778238106Sdes * @param r: callback entry
779238106Sdes */
780238106Sdesstatic void
781238106Sdesmesh_do_callback(struct mesh_state* m, int rcode, struct reply_info* rep,
782238106Sdes	struct mesh_cb* r)
783238106Sdes{
784238106Sdes	int secure;
785238106Sdes	char* reason = NULL;
786238106Sdes	/* bogus messages are not made into servfail, sec_status passed
787238106Sdes	 * to the callback function */
788238106Sdes	if(rep && rep->security == sec_status_secure)
789238106Sdes		secure = 1;
790238106Sdes	else	secure = 0;
791238106Sdes	if(!rep && rcode == LDNS_RCODE_NOERROR)
792238106Sdes		rcode = LDNS_RCODE_SERVFAIL;
793238106Sdes	if(!rcode && rep->security == sec_status_bogus) {
794238106Sdes		if(!(reason = errinf_to_str(&m->s)))
795238106Sdes			rcode = LDNS_RCODE_SERVFAIL;
796238106Sdes	}
797238106Sdes	/* send the reply */
798238106Sdes	if(rcode) {
799238106Sdes		fptr_ok(fptr_whitelist_mesh_cb(r->cb));
800238106Sdes		(*r->cb)(r->cb_arg, rcode, r->buf, sec_status_unchecked, NULL);
801238106Sdes	} else {
802238106Sdes		size_t udp_size = r->edns.udp_size;
803269257Sdes		sldns_buffer_clear(r->buf);
804238106Sdes		r->edns.edns_version = EDNS_ADVERTISED_VERSION;
805238106Sdes		r->edns.udp_size = EDNS_ADVERTISED_SIZE;
806238106Sdes		r->edns.ext_rcode = 0;
807238106Sdes		r->edns.bits &= EDNS_DO;
808238106Sdes		if(!reply_info_answer_encode(&m->s.qinfo, rep, r->qid,
809238106Sdes			r->qflags, r->buf, 0, 1,
810238106Sdes			m->s.env->scratch, udp_size, &r->edns,
811238106Sdes			(int)(r->edns.bits & EDNS_DO), secure))
812238106Sdes		{
813238106Sdes			fptr_ok(fptr_whitelist_mesh_cb(r->cb));
814238106Sdes			(*r->cb)(r->cb_arg, LDNS_RCODE_SERVFAIL, r->buf,
815238106Sdes				sec_status_unchecked, NULL);
816238106Sdes		} else {
817238106Sdes			fptr_ok(fptr_whitelist_mesh_cb(r->cb));
818238106Sdes			(*r->cb)(r->cb_arg, LDNS_RCODE_NOERROR, r->buf,
819238106Sdes				rep->security, reason);
820238106Sdes		}
821238106Sdes	}
822238106Sdes	free(reason);
823238106Sdes	m->s.env->mesh->num_reply_addrs--;
824238106Sdes}
825238106Sdes
826238106Sdes/**
827238106Sdes * Send reply to mesh reply entry
828238106Sdes * @param m: mesh state to send it for.
829238106Sdes * @param rcode: if not 0, error code.
830238106Sdes * @param rep: reply to send (or NULL if rcode is set).
831238106Sdes * @param r: reply entry
832238106Sdes * @param prev: previous reply, already has its answer encoded in buffer.
833238106Sdes */
834238106Sdesstatic void
835238106Sdesmesh_send_reply(struct mesh_state* m, int rcode, struct reply_info* rep,
836238106Sdes	struct mesh_reply* r, struct mesh_reply* prev)
837238106Sdes{
838238106Sdes	struct timeval end_time;
839238106Sdes	struct timeval duration;
840238106Sdes	int secure;
841238106Sdes	/* examine security status */
842238106Sdes	if(m->s.env->need_to_validate && (!(r->qflags&BIT_CD) ||
843238106Sdes		m->s.env->cfg->ignore_cd) && rep &&
844238106Sdes		rep->security <= sec_status_bogus) {
845238106Sdes		rcode = LDNS_RCODE_SERVFAIL;
846238106Sdes		if(m->s.env->cfg->stat_extended)
847238106Sdes			m->s.env->mesh->ans_bogus++;
848238106Sdes	}
849238106Sdes	if(rep && rep->security == sec_status_secure)
850238106Sdes		secure = 1;
851238106Sdes	else	secure = 0;
852238106Sdes	if(!rep && rcode == LDNS_RCODE_NOERROR)
853238106Sdes		rcode = LDNS_RCODE_SERVFAIL;
854238106Sdes	/* send the reply */
855238106Sdes	if(prev && prev->qflags == r->qflags &&
856238106Sdes		prev->edns.edns_present == r->edns.edns_present &&
857238106Sdes		prev->edns.bits == r->edns.bits &&
858238106Sdes		prev->edns.udp_size == r->edns.udp_size) {
859238106Sdes		/* if the previous reply is identical to this one, fix ID */
860238106Sdes		if(prev->query_reply.c->buffer != r->query_reply.c->buffer)
861269257Sdes			sldns_buffer_copy(r->query_reply.c->buffer,
862238106Sdes				prev->query_reply.c->buffer);
863269257Sdes		sldns_buffer_write_at(r->query_reply.c->buffer, 0,
864238106Sdes			&r->qid, sizeof(uint16_t));
865269257Sdes		sldns_buffer_write_at(r->query_reply.c->buffer, 12,
866238106Sdes			r->qname, m->s.qinfo.qname_len);
867238106Sdes		comm_point_send_reply(&r->query_reply);
868238106Sdes	} else if(rcode) {
869238106Sdes		m->s.qinfo.qname = r->qname;
870238106Sdes		error_encode(r->query_reply.c->buffer, rcode, &m->s.qinfo,
871238106Sdes			r->qid, r->qflags, &r->edns);
872238106Sdes		comm_point_send_reply(&r->query_reply);
873238106Sdes	} else {
874238106Sdes		size_t udp_size = r->edns.udp_size;
875238106Sdes		r->edns.edns_version = EDNS_ADVERTISED_VERSION;
876238106Sdes		r->edns.udp_size = EDNS_ADVERTISED_SIZE;
877238106Sdes		r->edns.ext_rcode = 0;
878238106Sdes		r->edns.bits &= EDNS_DO;
879238106Sdes		m->s.qinfo.qname = r->qname;
880238106Sdes		if(!reply_info_answer_encode(&m->s.qinfo, rep, r->qid,
881238106Sdes			r->qflags, r->query_reply.c->buffer, 0, 1,
882238106Sdes			m->s.env->scratch, udp_size, &r->edns,
883238106Sdes			(int)(r->edns.bits & EDNS_DO), secure))
884238106Sdes		{
885238106Sdes			error_encode(r->query_reply.c->buffer,
886238106Sdes				LDNS_RCODE_SERVFAIL, &m->s.qinfo, r->qid,
887238106Sdes				r->qflags, &r->edns);
888238106Sdes		}
889238106Sdes		comm_point_send_reply(&r->query_reply);
890238106Sdes	}
891238106Sdes	/* account */
892238106Sdes	m->s.env->mesh->num_reply_addrs--;
893238106Sdes	end_time = *m->s.env->now_tv;
894238106Sdes	timeval_subtract(&duration, &end_time, &r->start_time);
895269257Sdes	verbose(VERB_ALGO, "query took " ARG_LL "d.%6.6d sec",
896269257Sdes		(long long)duration.tv_sec, (int)duration.tv_usec);
897238106Sdes	m->s.env->mesh->replies_sent++;
898238106Sdes	timeval_add(&m->s.env->mesh->replies_sum_wait, &duration);
899238106Sdes	timehist_insert(m->s.env->mesh->histogram, &duration);
900238106Sdes	if(m->s.env->cfg->stat_extended) {
901269257Sdes		uint16_t rc = FLAGS_GET_RCODE(sldns_buffer_read_u16_at(r->
902238106Sdes			query_reply.c->buffer, 2));
903238106Sdes		if(secure) m->s.env->mesh->ans_secure++;
904238106Sdes		m->s.env->mesh->ans_rcode[ rc ] ++;
905269257Sdes		if(rc == 0 && LDNS_ANCOUNT(sldns_buffer_begin(r->
906238106Sdes			query_reply.c->buffer)) == 0)
907238106Sdes			m->s.env->mesh->ans_nodata++;
908238106Sdes	}
909238106Sdes}
910238106Sdes
911238106Sdesvoid mesh_query_done(struct mesh_state* mstate)
912238106Sdes{
913238106Sdes	struct mesh_reply* r;
914238106Sdes	struct mesh_reply* prev = NULL;
915238106Sdes	struct mesh_cb* c;
916238106Sdes	struct reply_info* rep = (mstate->s.return_msg?
917238106Sdes		mstate->s.return_msg->rep:NULL);
918238106Sdes	for(r = mstate->reply_list; r; r = r->next) {
919238106Sdes		mesh_send_reply(mstate, mstate->s.return_rcode, rep, r, prev);
920238106Sdes		prev = r;
921238106Sdes	}
922238106Sdes	mstate->replies_sent = 1;
923238106Sdes	for(c = mstate->cb_list; c; c = c->next) {
924238106Sdes		mesh_do_callback(mstate, mstate->s.return_rcode, rep, c);
925238106Sdes	}
926238106Sdes}
927238106Sdes
928238106Sdesvoid mesh_walk_supers(struct mesh_area* mesh, struct mesh_state* mstate)
929238106Sdes{
930238106Sdes	struct mesh_state_ref* ref;
931238106Sdes	RBTREE_FOR(ref, struct mesh_state_ref*, &mstate->super_set)
932238106Sdes	{
933238106Sdes		/* make super runnable */
934238106Sdes		(void)rbtree_insert(&mesh->run, &ref->s->run_node);
935238106Sdes		/* callback the function to inform super of result */
936238106Sdes		fptr_ok(fptr_whitelist_mod_inform_super(
937238106Sdes			mesh->mods.mod[ref->s->s.curmod]->inform_super));
938238106Sdes		(*mesh->mods.mod[ref->s->s.curmod]->inform_super)(&mstate->s,
939238106Sdes			ref->s->s.curmod, &ref->s->s);
940238106Sdes	}
941238106Sdes}
942238106Sdes
943238106Sdesstruct mesh_state* mesh_area_find(struct mesh_area* mesh,
944238106Sdes	struct query_info* qinfo, uint16_t qflags, int prime)
945238106Sdes{
946238106Sdes	struct mesh_state key;
947238106Sdes	struct mesh_state* result;
948238106Sdes
949238106Sdes	key.node.key = &key;
950238106Sdes	key.s.is_priming = prime;
951238106Sdes	key.s.qinfo = *qinfo;
952238106Sdes	key.s.query_flags = qflags;
953238106Sdes
954238106Sdes	result = (struct mesh_state*)rbtree_search(&mesh->all, &key);
955238106Sdes	return result;
956238106Sdes}
957238106Sdes
958238106Sdesint mesh_state_add_cb(struct mesh_state* s, struct edns_data* edns,
959269257Sdes        sldns_buffer* buf, mesh_cb_func_t cb, void* cb_arg,
960238106Sdes	uint16_t qid, uint16_t qflags)
961238106Sdes{
962238106Sdes	struct mesh_cb* r = regional_alloc(s->s.region,
963238106Sdes		sizeof(struct mesh_cb));
964238106Sdes	if(!r)
965238106Sdes		return 0;
966238106Sdes	r->buf = buf;
967238106Sdes	log_assert(fptr_whitelist_mesh_cb(cb)); /* early failure ifmissing*/
968238106Sdes	r->cb = cb;
969238106Sdes	r->cb_arg = cb_arg;
970238106Sdes	r->edns = *edns;
971238106Sdes	r->qid = qid;
972238106Sdes	r->qflags = qflags;
973238106Sdes	r->next = s->cb_list;
974238106Sdes	s->cb_list = r;
975238106Sdes	return 1;
976238106Sdes
977238106Sdes}
978238106Sdes
979238106Sdesint mesh_state_add_reply(struct mesh_state* s, struct edns_data* edns,
980238106Sdes        struct comm_reply* rep, uint16_t qid, uint16_t qflags, uint8_t* qname)
981238106Sdes{
982238106Sdes	struct mesh_reply* r = regional_alloc(s->s.region,
983238106Sdes		sizeof(struct mesh_reply));
984238106Sdes	if(!r)
985238106Sdes		return 0;
986238106Sdes	r->query_reply = *rep;
987238106Sdes	r->edns = *edns;
988238106Sdes	r->qid = qid;
989238106Sdes	r->qflags = qflags;
990238106Sdes	r->start_time = *s->s.env->now_tv;
991238106Sdes	r->next = s->reply_list;
992238106Sdes	r->qname = regional_alloc_init(s->s.region, qname,
993238106Sdes		s->s.qinfo.qname_len);
994238106Sdes	if(!r->qname)
995238106Sdes		return 0;
996238106Sdes	s->reply_list = r;
997238106Sdes	return 1;
998238106Sdes
999238106Sdes}
1000238106Sdes
1001238106Sdes/**
1002238106Sdes * Continue processing the mesh state at another module.
1003238106Sdes * Handles module to modules tranfer of control.
1004238106Sdes * Handles module finished.
1005238106Sdes * @param mesh: the mesh area.
1006238106Sdes * @param mstate: currently active mesh state.
1007238106Sdes * 	Deleted if finished, calls _done and _supers to
1008238106Sdes * 	send replies to clients and inform other mesh states.
1009238106Sdes * 	This in turn may create additional runnable mesh states.
1010238106Sdes * @param s: state at which the current module exited.
1011238106Sdes * @param ev: the event sent to the module.
1012238106Sdes * 	returned is the event to send to the next module.
1013238106Sdes * @return true if continue processing at the new module.
1014238106Sdes * 	false if not continued processing is needed.
1015238106Sdes */
1016238106Sdesstatic int
1017238106Sdesmesh_continue(struct mesh_area* mesh, struct mesh_state* mstate,
1018238106Sdes	enum module_ext_state s, enum module_ev* ev)
1019238106Sdes{
1020238106Sdes	mstate->num_activated++;
1021238106Sdes	if(mstate->num_activated > MESH_MAX_ACTIVATION) {
1022238106Sdes		/* module is looping. Stop it. */
1023238106Sdes		log_err("internal error: looping module stopped");
1024238106Sdes		log_query_info(VERB_QUERY, "pass error for qstate",
1025238106Sdes			&mstate->s.qinfo);
1026238106Sdes		s = module_error;
1027238106Sdes	}
1028238106Sdes	if(s == module_wait_module || s == module_restart_next) {
1029238106Sdes		/* start next module */
1030238106Sdes		mstate->s.curmod++;
1031238106Sdes		if(mesh->mods.num == mstate->s.curmod) {
1032238106Sdes			log_err("Cannot pass to next module; at last module");
1033238106Sdes			log_query_info(VERB_QUERY, "pass error for qstate",
1034238106Sdes				&mstate->s.qinfo);
1035238106Sdes			mstate->s.curmod--;
1036238106Sdes			return mesh_continue(mesh, mstate, module_error, ev);
1037238106Sdes		}
1038238106Sdes		if(s == module_restart_next) {
1039238106Sdes			fptr_ok(fptr_whitelist_mod_clear(
1040238106Sdes				mesh->mods.mod[mstate->s.curmod]->clear));
1041238106Sdes			(*mesh->mods.mod[mstate->s.curmod]->clear)
1042238106Sdes				(&mstate->s, mstate->s.curmod);
1043238106Sdes			mstate->s.minfo[mstate->s.curmod] = NULL;
1044238106Sdes		}
1045238106Sdes		*ev = module_event_pass;
1046238106Sdes		return 1;
1047238106Sdes	}
1048238106Sdes	if(s == module_error && mstate->s.return_rcode == LDNS_RCODE_NOERROR) {
1049238106Sdes		/* error is bad, handle pass back up below */
1050238106Sdes		mstate->s.return_rcode = LDNS_RCODE_SERVFAIL;
1051238106Sdes	}
1052238106Sdes	if(s == module_error || s == module_finished) {
1053238106Sdes		if(mstate->s.curmod == 0) {
1054238106Sdes			mesh_query_done(mstate);
1055238106Sdes			mesh_walk_supers(mesh, mstate);
1056238106Sdes			mesh_state_delete(&mstate->s);
1057238106Sdes			return 0;
1058238106Sdes		}
1059238106Sdes		/* pass along the locus of control */
1060238106Sdes		mstate->s.curmod --;
1061238106Sdes		*ev = module_event_moddone;
1062238106Sdes		return 1;
1063238106Sdes	}
1064238106Sdes	return 0;
1065238106Sdes}
1066238106Sdes
1067238106Sdesvoid mesh_run(struct mesh_area* mesh, struct mesh_state* mstate,
1068238106Sdes	enum module_ev ev, struct outbound_entry* e)
1069238106Sdes{
1070238106Sdes	enum module_ext_state s;
1071238106Sdes	verbose(VERB_ALGO, "mesh_run: start");
1072238106Sdes	while(mstate) {
1073238106Sdes		/* run the module */
1074238106Sdes		fptr_ok(fptr_whitelist_mod_operate(
1075238106Sdes			mesh->mods.mod[mstate->s.curmod]->operate));
1076238106Sdes		(*mesh->mods.mod[mstate->s.curmod]->operate)
1077238106Sdes			(&mstate->s, ev, mstate->s.curmod, e);
1078238106Sdes
1079238106Sdes		/* examine results */
1080238106Sdes		mstate->s.reply = NULL;
1081238106Sdes		regional_free_all(mstate->s.env->scratch);
1082238106Sdes		s = mstate->s.ext_state[mstate->s.curmod];
1083238106Sdes		verbose(VERB_ALGO, "mesh_run: %s module exit state is %s",
1084238106Sdes			mesh->mods.mod[mstate->s.curmod]->name, strextstate(s));
1085238106Sdes		e = NULL;
1086238106Sdes		if(mesh_continue(mesh, mstate, s, &ev))
1087238106Sdes			continue;
1088238106Sdes
1089238106Sdes		/* run more modules */
1090238106Sdes		ev = module_event_pass;
1091238106Sdes		if(mesh->run.count > 0) {
1092238106Sdes			/* pop random element off the runnable tree */
1093238106Sdes			mstate = (struct mesh_state*)mesh->run.root->key;
1094238106Sdes			(void)rbtree_delete(&mesh->run, mstate);
1095238106Sdes		} else mstate = NULL;
1096238106Sdes	}
1097238106Sdes	if(verbosity >= VERB_ALGO) {
1098238106Sdes		mesh_stats(mesh, "mesh_run: end");
1099238106Sdes		mesh_log_list(mesh);
1100238106Sdes	}
1101238106Sdes}
1102238106Sdes
1103238106Sdesvoid
1104238106Sdesmesh_log_list(struct mesh_area* mesh)
1105238106Sdes{
1106238106Sdes	char buf[30];
1107238106Sdes	struct mesh_state* m;
1108238106Sdes	int num = 0;
1109238106Sdes	RBTREE_FOR(m, struct mesh_state*, &mesh->all) {
1110238106Sdes		snprintf(buf, sizeof(buf), "%d%s%s%s%s%s mod%d %s%s",
1111238106Sdes			num++, (m->s.is_priming)?"p":"",  /* prime */
1112238106Sdes			(m->s.query_flags&BIT_RD)?"RD":"",
1113238106Sdes			(m->s.query_flags&BIT_CD)?"CD":"",
1114238106Sdes			(m->super_set.count==0)?"d":"", /* detached */
1115238106Sdes			(m->sub_set.count!=0)?"c":"",  /* children */
1116238106Sdes			m->s.curmod, (m->reply_list)?"rep":"", /*hasreply*/
1117238106Sdes			(m->cb_list)?"cb":"" /* callbacks */
1118238106Sdes			);
1119238106Sdes		log_query_info(VERB_ALGO, buf, &m->s.qinfo);
1120238106Sdes	}
1121238106Sdes}
1122238106Sdes
1123238106Sdesvoid
1124238106Sdesmesh_stats(struct mesh_area* mesh, const char* str)
1125238106Sdes{
1126238106Sdes	verbose(VERB_DETAIL, "%s %u recursion states (%u with reply, "
1127238106Sdes		"%u detached), %u waiting replies, %u recursion replies "
1128238106Sdes		"sent, %d replies dropped, %d states jostled out",
1129238106Sdes		str, (unsigned)mesh->all.count,
1130238106Sdes		(unsigned)mesh->num_reply_states,
1131238106Sdes		(unsigned)mesh->num_detached_states,
1132238106Sdes		(unsigned)mesh->num_reply_addrs,
1133238106Sdes		(unsigned)mesh->replies_sent,
1134238106Sdes		(unsigned)mesh->stats_dropped,
1135238106Sdes		(unsigned)mesh->stats_jostled);
1136238106Sdes	if(mesh->replies_sent > 0) {
1137238106Sdes		struct timeval avg;
1138238106Sdes		timeval_divide(&avg, &mesh->replies_sum_wait,
1139238106Sdes			mesh->replies_sent);
1140238106Sdes		log_info("average recursion processing time "
1141269257Sdes			ARG_LL "d.%6.6d sec",
1142269257Sdes			(long long)avg.tv_sec, (int)avg.tv_usec);
1143238106Sdes		log_info("histogram of recursion processing times");
1144238106Sdes		timehist_log(mesh->histogram, "recursions");
1145238106Sdes	}
1146238106Sdes}
1147238106Sdes
1148238106Sdesvoid
1149238106Sdesmesh_stats_clear(struct mesh_area* mesh)
1150238106Sdes{
1151238106Sdes	if(!mesh)
1152238106Sdes		return;
1153238106Sdes	mesh->replies_sent = 0;
1154238106Sdes	mesh->replies_sum_wait.tv_sec = 0;
1155238106Sdes	mesh->replies_sum_wait.tv_usec = 0;
1156238106Sdes	mesh->stats_jostled = 0;
1157238106Sdes	mesh->stats_dropped = 0;
1158238106Sdes	timehist_clear(mesh->histogram);
1159238106Sdes	mesh->ans_secure = 0;
1160238106Sdes	mesh->ans_bogus = 0;
1161238106Sdes	memset(&mesh->ans_rcode[0], 0, sizeof(size_t)*16);
1162238106Sdes	mesh->ans_nodata = 0;
1163238106Sdes}
1164238106Sdes
1165238106Sdessize_t
1166238106Sdesmesh_get_mem(struct mesh_area* mesh)
1167238106Sdes{
1168238106Sdes	struct mesh_state* m;
1169238106Sdes	size_t s = sizeof(*mesh) + sizeof(struct timehist) +
1170238106Sdes		sizeof(struct th_buck)*mesh->histogram->num +
1171269257Sdes		sizeof(sldns_buffer) + sldns_buffer_capacity(mesh->qbuf_bak);
1172238106Sdes	RBTREE_FOR(m, struct mesh_state*, &mesh->all) {
1173238106Sdes		/* all, including m itself allocated in qstate region */
1174238106Sdes		s += regional_get_mem(m->s.region);
1175238106Sdes	}
1176238106Sdes	return s;
1177238106Sdes}
1178238106Sdes
1179238106Sdesint
1180238106Sdesmesh_detect_cycle(struct module_qstate* qstate, struct query_info* qinfo,
1181238106Sdes	uint16_t flags, int prime)
1182238106Sdes{
1183238106Sdes	struct mesh_area* mesh = qstate->env->mesh;
1184238106Sdes	struct mesh_state* dep_m = mesh_area_find(mesh, qinfo, flags, prime);
1185238106Sdes	return mesh_detect_cycle_found(qstate, dep_m);
1186238106Sdes}
1187238106Sdes
1188238106Sdesvoid mesh_list_insert(struct mesh_state* m, struct mesh_state** fp,
1189238106Sdes        struct mesh_state** lp)
1190238106Sdes{
1191238106Sdes	/* insert as last element */
1192238106Sdes	m->prev = *lp;
1193238106Sdes	m->next = NULL;
1194238106Sdes	if(*lp)
1195238106Sdes		(*lp)->next = m;
1196238106Sdes	else	*fp = m;
1197238106Sdes	*lp = m;
1198238106Sdes}
1199238106Sdes
1200238106Sdesvoid mesh_list_remove(struct mesh_state* m, struct mesh_state** fp,
1201238106Sdes        struct mesh_state** lp)
1202238106Sdes{
1203238106Sdes	if(m->next)
1204238106Sdes		m->next->prev = m->prev;
1205238106Sdes	else	*lp = m->prev;
1206238106Sdes	if(m->prev)
1207238106Sdes		m->prev->next = m->next;
1208238106Sdes	else	*fp = m->next;
1209238106Sdes}
1210