xref: /freebsd/contrib/unbound/services/mesh.c (revision cddbc3b40812213ff00041f79174cac0be360a2a)
1 /*
2  * services/mesh.c - deal with mesh of query states and handle events for that.
3  *
4  * Copyright (c) 2007, NLnet Labs. All rights reserved.
5  *
6  * This software is open source.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  *
12  * Redistributions of source code must retain the above copyright notice,
13  * this list of conditions and the following disclaimer.
14  *
15  * Redistributions in binary form must reproduce the above copyright notice,
16  * this list of conditions and the following disclaimer in the documentation
17  * and/or other materials provided with the distribution.
18  *
19  * Neither the name of the NLNET LABS nor the names of its contributors may
20  * be used to endorse or promote products derived from this software without
21  * specific prior written permission.
22  *
23  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
24  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
25  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
26  * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
27  * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
28  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
29  * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
30  * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
31  * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
32  * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
33  * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
34  */
35 
36 /**
37  * \file
38  *
39  * This file contains functions to assist in dealing with a mesh of
40  * query states. This mesh is supposed to be thread-specific.
41  * It consists of query states (per qname, qtype, qclass) and connections
42  * between query states and the super and subquery states, and replies to
43  * send back to clients.
44  */
45 #include "config.h"
46 #include "services/mesh.h"
47 #include "services/outbound_list.h"
48 #include "services/cache/dns.h"
49 #include "util/log.h"
50 #include "util/net_help.h"
51 #include "util/module.h"
52 #include "util/regional.h"
53 #include "util/data/msgencode.h"
54 #include "util/timehist.h"
55 #include "util/fptr_wlist.h"
56 #include "util/alloc.h"
57 #include "util/config_file.h"
58 #include "util/edns.h"
59 #include "sldns/sbuffer.h"
60 #include "sldns/wire2str.h"
61 #include "services/localzone.h"
62 #include "util/data/dname.h"
63 #include "respip/respip.h"
64 
65 /** subtract timers and the values do not overflow or become negative */
66 static void
67 timeval_subtract(struct timeval* d, const struct timeval* end, const struct timeval* start)
68 {
69 #ifndef S_SPLINT_S
70 	time_t end_usec = end->tv_usec;
71 	d->tv_sec = end->tv_sec - start->tv_sec;
72 	if(end_usec < start->tv_usec) {
73 		end_usec += 1000000;
74 		d->tv_sec--;
75 	}
76 	d->tv_usec = end_usec - start->tv_usec;
77 #endif
78 }
79 
80 /** add timers and the values do not overflow or become negative */
81 static void
82 timeval_add(struct timeval* d, const struct timeval* add)
83 {
84 #ifndef S_SPLINT_S
85 	d->tv_sec += add->tv_sec;
86 	d->tv_usec += add->tv_usec;
87 	if(d->tv_usec > 1000000 ) {
88 		d->tv_usec -= 1000000;
89 		d->tv_sec++;
90 	}
91 #endif
92 }
93 
94 /** divide sum of timers to get average */
95 static void
96 timeval_divide(struct timeval* avg, const struct timeval* sum, size_t d)
97 {
98 #ifndef S_SPLINT_S
99 	size_t leftover;
100 	if(d == 0) {
101 		avg->tv_sec = 0;
102 		avg->tv_usec = 0;
103 		return;
104 	}
105 	avg->tv_sec = sum->tv_sec / d;
106 	avg->tv_usec = sum->tv_usec / d;
107 	/* handle fraction from seconds divide */
108 	leftover = sum->tv_sec - avg->tv_sec*d;
109 	avg->tv_usec += (leftover*1000000)/d;
110 #endif
111 }
112 
113 /** histogram compare of time values */
114 static int
115 timeval_smaller(const struct timeval* x, const struct timeval* y)
116 {
117 #ifndef S_SPLINT_S
118 	if(x->tv_sec < y->tv_sec)
119 		return 1;
120 	else if(x->tv_sec == y->tv_sec) {
121 		if(x->tv_usec <= y->tv_usec)
122 			return 1;
123 		else	return 0;
124 	}
125 	else	return 0;
126 #endif
127 }
128 
129 /*
130  * Compare two response-ip client info entries for the purpose of mesh state
131  * compare.  It returns 0 if ci_a and ci_b are considered equal; otherwise
132  * 1 or -1 (they mean 'ci_a is larger/smaller than ci_b', respectively, but
133  * in practice it should be only used to mean they are different).
134  * We cannot share the mesh state for two queries if different response-ip
135  * actions can apply in the end, even if those queries are otherwise identical.
136  * For this purpose we compare tag lists and tag action lists; they should be
137  * identical to share the same state.
138  * For tag data, we don't look into the data content, as it can be
139  * expensive; unless tag data are not defined for both or they point to the
140  * exact same data in memory (i.e., they come from the same ACL entry), we
141  * consider these data different.
142  * Likewise, if the client info is associated with views, we don't look into
143  * the views.  They are considered different unless they are exactly the same
144  * even if the views only differ in the names.
145  */
146 static int
147 client_info_compare(const struct respip_client_info* ci_a,
148 	const struct respip_client_info* ci_b)
149 {
150 	int cmp;
151 
152 	if(!ci_a && !ci_b)
153 		return 0;
154 	if(ci_a && !ci_b)
155 		return -1;
156 	if(!ci_a && ci_b)
157 		return 1;
158 	if(ci_a->taglen != ci_b->taglen)
159 		return (ci_a->taglen < ci_b->taglen) ? -1 : 1;
160 	cmp = memcmp(ci_a->taglist, ci_b->taglist, ci_a->taglen);
161 	if(cmp != 0)
162 		return cmp;
163 	if(ci_a->tag_actions_size != ci_b->tag_actions_size)
164 		return (ci_a->tag_actions_size < ci_b->tag_actions_size) ?
165 			-1 : 1;
166 	cmp = memcmp(ci_a->tag_actions, ci_b->tag_actions,
167 		ci_a->tag_actions_size);
168 	if(cmp != 0)
169 		return cmp;
170 	if(ci_a->tag_datas != ci_b->tag_datas)
171 		return ci_a->tag_datas < ci_b->tag_datas ? -1 : 1;
172 	if(ci_a->view != ci_b->view)
173 		return ci_a->view < ci_b->view ? -1 : 1;
174 	/* For the unbound daemon these should be non-NULL and identical,
175 	 * but we check that just in case. */
176 	if(ci_a->respip_set != ci_b->respip_set)
177 		return ci_a->respip_set < ci_b->respip_set ? -1 : 1;
178 	return 0;
179 }
180 
181 int
182 mesh_state_compare(const void* ap, const void* bp)
183 {
184 	struct mesh_state* a = (struct mesh_state*)ap;
185 	struct mesh_state* b = (struct mesh_state*)bp;
186 	int cmp;
187 
188 	if(a->unique < b->unique)
189 		return -1;
190 	if(a->unique > b->unique)
191 		return 1;
192 
193 	if(a->s.is_priming && !b->s.is_priming)
194 		return -1;
195 	if(!a->s.is_priming && b->s.is_priming)
196 		return 1;
197 
198 	if(a->s.is_valrec && !b->s.is_valrec)
199 		return -1;
200 	if(!a->s.is_valrec && b->s.is_valrec)
201 		return 1;
202 
203 	if((a->s.query_flags&BIT_RD) && !(b->s.query_flags&BIT_RD))
204 		return -1;
205 	if(!(a->s.query_flags&BIT_RD) && (b->s.query_flags&BIT_RD))
206 		return 1;
207 
208 	if((a->s.query_flags&BIT_CD) && !(b->s.query_flags&BIT_CD))
209 		return -1;
210 	if(!(a->s.query_flags&BIT_CD) && (b->s.query_flags&BIT_CD))
211 		return 1;
212 
213 	cmp = query_info_compare(&a->s.qinfo, &b->s.qinfo);
214 	if(cmp != 0)
215 		return cmp;
216 	return client_info_compare(a->s.client_info, b->s.client_info);
217 }
218 
219 int
220 mesh_state_ref_compare(const void* ap, const void* bp)
221 {
222 	struct mesh_state_ref* a = (struct mesh_state_ref*)ap;
223 	struct mesh_state_ref* b = (struct mesh_state_ref*)bp;
224 	return mesh_state_compare(a->s, b->s);
225 }
226 
227 struct mesh_area*
228 mesh_create(struct module_stack* stack, struct module_env* env)
229 {
230 	struct mesh_area* mesh = calloc(1, sizeof(struct mesh_area));
231 	if(!mesh) {
232 		log_err("mesh area alloc: out of memory");
233 		return NULL;
234 	}
235 	mesh->histogram = timehist_setup();
236 	mesh->qbuf_bak = sldns_buffer_new(env->cfg->msg_buffer_size);
237 	if(!mesh->histogram || !mesh->qbuf_bak) {
238 		free(mesh);
239 		log_err("mesh area alloc: out of memory");
240 		return NULL;
241 	}
242 	mesh->mods = *stack;
243 	mesh->env = env;
244 	rbtree_init(&mesh->run, &mesh_state_compare);
245 	rbtree_init(&mesh->all, &mesh_state_compare);
246 	mesh->num_reply_addrs = 0;
247 	mesh->num_reply_states = 0;
248 	mesh->num_detached_states = 0;
249 	mesh->num_forever_states = 0;
250 	mesh->stats_jostled = 0;
251 	mesh->stats_dropped = 0;
252 	mesh->max_reply_states = env->cfg->num_queries_per_thread;
253 	mesh->max_forever_states = (mesh->max_reply_states+1)/2;
254 #ifndef S_SPLINT_S
255 	mesh->jostle_max.tv_sec = (time_t)(env->cfg->jostle_time / 1000);
256 	mesh->jostle_max.tv_usec = (time_t)((env->cfg->jostle_time % 1000)
257 		*1000);
258 #endif
259 	return mesh;
260 }
261 
262 /** help mesh delete delete mesh states */
263 static void
264 mesh_delete_helper(rbnode_type* n)
265 {
266 	struct mesh_state* mstate = (struct mesh_state*)n->key;
267 	/* perform a full delete, not only 'cleanup' routine,
268 	 * because other callbacks expect a clean state in the mesh.
269 	 * For 're-entrant' calls */
270 	mesh_state_delete(&mstate->s);
271 	/* but because these delete the items from the tree, postorder
272 	 * traversal and rbtree rebalancing do not work together */
273 }
274 
275 void
276 mesh_delete(struct mesh_area* mesh)
277 {
278 	if(!mesh)
279 		return;
280 	/* free all query states */
281 	while(mesh->all.count)
282 		mesh_delete_helper(mesh->all.root);
283 	timehist_delete(mesh->histogram);
284 	sldns_buffer_free(mesh->qbuf_bak);
285 	free(mesh);
286 }
287 
288 void
289 mesh_delete_all(struct mesh_area* mesh)
290 {
291 	/* free all query states */
292 	while(mesh->all.count)
293 		mesh_delete_helper(mesh->all.root);
294 	mesh->stats_dropped += mesh->num_reply_addrs;
295 	/* clear mesh area references */
296 	rbtree_init(&mesh->run, &mesh_state_compare);
297 	rbtree_init(&mesh->all, &mesh_state_compare);
298 	mesh->num_reply_addrs = 0;
299 	mesh->num_reply_states = 0;
300 	mesh->num_detached_states = 0;
301 	mesh->num_forever_states = 0;
302 	mesh->forever_first = NULL;
303 	mesh->forever_last = NULL;
304 	mesh->jostle_first = NULL;
305 	mesh->jostle_last = NULL;
306 }
307 
308 int mesh_make_new_space(struct mesh_area* mesh, sldns_buffer* qbuf)
309 {
310 	struct mesh_state* m = mesh->jostle_first;
311 	/* free space is available */
312 	if(mesh->num_reply_states < mesh->max_reply_states)
313 		return 1;
314 	/* try to kick out a jostle-list item */
315 	if(m && m->reply_list && m->list_select == mesh_jostle_list) {
316 		/* how old is it? */
317 		struct timeval age;
318 		timeval_subtract(&age, mesh->env->now_tv,
319 			&m->reply_list->start_time);
320 		if(timeval_smaller(&mesh->jostle_max, &age)) {
321 			/* its a goner */
322 			log_nametypeclass(VERB_ALGO, "query jostled out to "
323 				"make space for a new one",
324 				m->s.qinfo.qname, m->s.qinfo.qtype,
325 				m->s.qinfo.qclass);
326 			/* backup the query */
327 			if(qbuf) sldns_buffer_copy(mesh->qbuf_bak, qbuf);
328 			/* notify supers */
329 			if(m->super_set.count > 0) {
330 				verbose(VERB_ALGO, "notify supers of failure");
331 				m->s.return_msg = NULL;
332 				m->s.return_rcode = LDNS_RCODE_SERVFAIL;
333 				mesh_walk_supers(mesh, m);
334 			}
335 			mesh->stats_jostled ++;
336 			mesh_state_delete(&m->s);
337 			/* restore the query - note that the qinfo ptr to
338 			 * the querybuffer is then correct again. */
339 			if(qbuf) sldns_buffer_copy(qbuf, mesh->qbuf_bak);
340 			return 1;
341 		}
342 	}
343 	/* no space for new item */
344 	return 0;
345 }
346 
347 void mesh_new_client(struct mesh_area* mesh, struct query_info* qinfo,
348 	struct respip_client_info* cinfo, uint16_t qflags,
349 	struct edns_data* edns, struct comm_reply* rep, uint16_t qid)
350 {
351 	struct mesh_state* s = NULL;
352 	int unique = unique_mesh_state(edns->opt_list, mesh->env);
353 	int was_detached = 0;
354 	int was_noreply = 0;
355 	int added = 0;
356 	if(!unique)
357 		s = mesh_area_find(mesh, cinfo, qinfo, qflags&(BIT_RD|BIT_CD), 0, 0);
358 	/* does this create a new reply state? */
359 	if(!s || s->list_select == mesh_no_list) {
360 		if(!mesh_make_new_space(mesh, rep->c->buffer)) {
361 			verbose(VERB_ALGO, "Too many queries. dropping "
362 				"incoming query.");
363 			comm_point_drop_reply(rep);
364 			mesh->stats_dropped ++;
365 			return;
366 		}
367 		/* for this new reply state, the reply address is free,
368 		 * so the limit of reply addresses does not stop reply states*/
369 	} else {
370 		/* protect our memory usage from storing reply addresses */
371 		if(mesh->num_reply_addrs > mesh->max_reply_states*16) {
372 			verbose(VERB_ALGO, "Too many requests queued. "
373 				"dropping incoming query.");
374 			mesh->stats_dropped++;
375 			comm_point_drop_reply(rep);
376 			return;
377 		}
378 	}
379 	/* see if it already exists, if not, create one */
380 	if(!s) {
381 #ifdef UNBOUND_DEBUG
382 		struct rbnode_type* n;
383 #endif
384 		s = mesh_state_create(mesh->env, qinfo, cinfo,
385 			qflags&(BIT_RD|BIT_CD), 0, 0);
386 		if(!s) {
387 			log_err("mesh_state_create: out of memory; SERVFAIL");
388 			if(!inplace_cb_reply_servfail_call(mesh->env, qinfo, NULL, NULL,
389 				LDNS_RCODE_SERVFAIL, edns, rep, mesh->env->scratch))
390 					edns->opt_list = NULL;
391 			error_encode(rep->c->buffer, LDNS_RCODE_SERVFAIL,
392 				qinfo, qid, qflags, edns);
393 			comm_point_send_reply(rep);
394 			return;
395 		}
396 		if(unique)
397 			mesh_state_make_unique(s);
398 		/* copy the edns options we got from the front */
399 		if(edns->opt_list) {
400 			s->s.edns_opts_front_in = edns_opt_copy_region(edns->opt_list,
401 				s->s.region);
402 			if(!s->s.edns_opts_front_in) {
403 				log_err("mesh_state_create: out of memory; SERVFAIL");
404 				if(!inplace_cb_reply_servfail_call(mesh->env, qinfo, NULL,
405 					NULL, LDNS_RCODE_SERVFAIL, edns, rep, mesh->env->scratch))
406 						edns->opt_list = NULL;
407 				error_encode(rep->c->buffer, LDNS_RCODE_SERVFAIL,
408 					qinfo, qid, qflags, edns);
409 				comm_point_send_reply(rep);
410 				return;
411 			}
412 		}
413 
414 #ifdef UNBOUND_DEBUG
415 		n =
416 #else
417 		(void)
418 #endif
419 		rbtree_insert(&mesh->all, &s->node);
420 		log_assert(n != NULL);
421 		/* set detached (it is now) */
422 		mesh->num_detached_states++;
423 		added = 1;
424 	}
425 	if(!s->reply_list && !s->cb_list && s->super_set.count == 0)
426 		was_detached = 1;
427 	if(!s->reply_list && !s->cb_list)
428 		was_noreply = 1;
429 	/* add reply to s */
430 	if(!mesh_state_add_reply(s, edns, rep, qid, qflags, qinfo)) {
431 			log_err("mesh_new_client: out of memory; SERVFAIL");
432 			if(!inplace_cb_reply_servfail_call(mesh->env, qinfo, &s->s,
433 				NULL, LDNS_RCODE_SERVFAIL, edns, rep, mesh->env->scratch))
434 					edns->opt_list = NULL;
435 			error_encode(rep->c->buffer, LDNS_RCODE_SERVFAIL,
436 				qinfo, qid, qflags, edns);
437 			comm_point_send_reply(rep);
438 			if(added)
439 				mesh_state_delete(&s->s);
440 			return;
441 	}
442 	/* update statistics */
443 	if(was_detached) {
444 		log_assert(mesh->num_detached_states > 0);
445 		mesh->num_detached_states--;
446 	}
447 	if(was_noreply) {
448 		mesh->num_reply_states ++;
449 	}
450 	mesh->num_reply_addrs++;
451 	if(s->list_select == mesh_no_list) {
452 		/* move to either the forever or the jostle_list */
453 		if(mesh->num_forever_states < mesh->max_forever_states) {
454 			mesh->num_forever_states ++;
455 			mesh_list_insert(s, &mesh->forever_first,
456 				&mesh->forever_last);
457 			s->list_select = mesh_forever_list;
458 		} else {
459 			mesh_list_insert(s, &mesh->jostle_first,
460 				&mesh->jostle_last);
461 			s->list_select = mesh_jostle_list;
462 		}
463 	}
464 	if(added)
465 		mesh_run(mesh, s, module_event_new, NULL);
466 }
467 
468 int
469 mesh_new_callback(struct mesh_area* mesh, struct query_info* qinfo,
470 	uint16_t qflags, struct edns_data* edns, sldns_buffer* buf,
471 	uint16_t qid, mesh_cb_func_type cb, void* cb_arg)
472 {
473 	struct mesh_state* s = NULL;
474 	int unique = unique_mesh_state(edns->opt_list, mesh->env);
475 	int was_detached = 0;
476 	int was_noreply = 0;
477 	int added = 0;
478 	if(!unique)
479 		s = mesh_area_find(mesh, NULL, qinfo, qflags&(BIT_RD|BIT_CD), 0, 0);
480 
481 	/* there are no limits on the number of callbacks */
482 
483 	/* see if it already exists, if not, create one */
484 	if(!s) {
485 #ifdef UNBOUND_DEBUG
486 		struct rbnode_type* n;
487 #endif
488 		s = mesh_state_create(mesh->env, qinfo, NULL,
489 			qflags&(BIT_RD|BIT_CD), 0, 0);
490 		if(!s) {
491 			return 0;
492 		}
493 		if(unique)
494 			mesh_state_make_unique(s);
495 		if(edns->opt_list) {
496 			s->s.edns_opts_front_in = edns_opt_copy_region(edns->opt_list,
497 				s->s.region);
498 			if(!s->s.edns_opts_front_in) {
499 				return 0;
500 			}
501 		}
502 #ifdef UNBOUND_DEBUG
503 		n =
504 #else
505 		(void)
506 #endif
507 		rbtree_insert(&mesh->all, &s->node);
508 		log_assert(n != NULL);
509 		/* set detached (it is now) */
510 		mesh->num_detached_states++;
511 		added = 1;
512 	}
513 	if(!s->reply_list && !s->cb_list && s->super_set.count == 0)
514 		was_detached = 1;
515 	if(!s->reply_list && !s->cb_list)
516 		was_noreply = 1;
517 	/* add reply to s */
518 	if(!mesh_state_add_cb(s, edns, buf, cb, cb_arg, qid, qflags)) {
519 			if(added)
520 				mesh_state_delete(&s->s);
521 			return 0;
522 	}
523 	/* update statistics */
524 	if(was_detached) {
525 		log_assert(mesh->num_detached_states > 0);
526 		mesh->num_detached_states--;
527 	}
528 	if(was_noreply) {
529 		mesh->num_reply_states ++;
530 	}
531 	mesh->num_reply_addrs++;
532 	if(added)
533 		mesh_run(mesh, s, module_event_new, NULL);
534 	return 1;
535 }
536 
537 static void mesh_schedule_prefetch(struct mesh_area* mesh,
538 	struct query_info* qinfo, uint16_t qflags, time_t leeway, int run);
539 
540 void mesh_new_prefetch(struct mesh_area* mesh, struct query_info* qinfo,
541         uint16_t qflags, time_t leeway)
542 {
543 	mesh_schedule_prefetch(mesh, qinfo, qflags, leeway, 1);
544 }
545 
546 /* Internal backend routine of mesh_new_prefetch().  It takes one additional
547  * parameter, 'run', which controls whether to run the prefetch state
548  * immediately.  When this function is called internally 'run' could be
549  * 0 (false), in which case the new state is only made runnable so it
550  * will not be run recursively on top of the current state. */
551 static void mesh_schedule_prefetch(struct mesh_area* mesh,
552 	struct query_info* qinfo, uint16_t qflags, time_t leeway, int run)
553 {
554 	struct mesh_state* s = mesh_area_find(mesh, NULL, qinfo,
555 		qflags&(BIT_RD|BIT_CD), 0, 0);
556 #ifdef UNBOUND_DEBUG
557 	struct rbnode_type* n;
558 #endif
559 	/* already exists, and for a different purpose perhaps.
560 	 * if mesh_no_list, keep it that way. */
561 	if(s) {
562 		/* make it ignore the cache from now on */
563 		if(!s->s.blacklist)
564 			sock_list_insert(&s->s.blacklist, NULL, 0, s->s.region);
565 		if(s->s.prefetch_leeway < leeway)
566 			s->s.prefetch_leeway = leeway;
567 		return;
568 	}
569 	if(!mesh_make_new_space(mesh, NULL)) {
570 		verbose(VERB_ALGO, "Too many queries. dropped prefetch.");
571 		mesh->stats_dropped ++;
572 		return;
573 	}
574 
575 	s = mesh_state_create(mesh->env, qinfo, NULL,
576 		qflags&(BIT_RD|BIT_CD), 0, 0);
577 	if(!s) {
578 		log_err("prefetch mesh_state_create: out of memory");
579 		return;
580 	}
581 #ifdef UNBOUND_DEBUG
582 	n =
583 #else
584 	(void)
585 #endif
586 	rbtree_insert(&mesh->all, &s->node);
587 	log_assert(n != NULL);
588 	/* set detached (it is now) */
589 	mesh->num_detached_states++;
590 	/* make it ignore the cache */
591 	sock_list_insert(&s->s.blacklist, NULL, 0, s->s.region);
592 	s->s.prefetch_leeway = leeway;
593 
594 	if(s->list_select == mesh_no_list) {
595 		/* move to either the forever or the jostle_list */
596 		if(mesh->num_forever_states < mesh->max_forever_states) {
597 			mesh->num_forever_states ++;
598 			mesh_list_insert(s, &mesh->forever_first,
599 				&mesh->forever_last);
600 			s->list_select = mesh_forever_list;
601 		} else {
602 			mesh_list_insert(s, &mesh->jostle_first,
603 				&mesh->jostle_last);
604 			s->list_select = mesh_jostle_list;
605 		}
606 	}
607 
608 	if(!run) {
609 #ifdef UNBOUND_DEBUG
610 		n =
611 #else
612 		(void)
613 #endif
614 		rbtree_insert(&mesh->run, &s->run_node);
615 		log_assert(n != NULL);
616 		return;
617 	}
618 
619 	mesh_run(mesh, s, module_event_new, NULL);
620 }
621 
622 void mesh_report_reply(struct mesh_area* mesh, struct outbound_entry* e,
623         struct comm_reply* reply, int what)
624 {
625 	enum module_ev event = module_event_reply;
626 	e->qstate->reply = reply;
627 	if(what != NETEVENT_NOERROR) {
628 		event = module_event_noreply;
629 		if(what == NETEVENT_CAPSFAIL)
630 			event = module_event_capsfail;
631 	}
632 	mesh_run(mesh, e->qstate->mesh_info, event, e);
633 }
634 
635 struct mesh_state*
636 mesh_state_create(struct module_env* env, struct query_info* qinfo,
637 	struct respip_client_info* cinfo, uint16_t qflags, int prime,
638 	int valrec)
639 {
640 	struct regional* region = alloc_reg_obtain(env->alloc);
641 	struct mesh_state* mstate;
642 	int i;
643 	if(!region)
644 		return NULL;
645 	mstate = (struct mesh_state*)regional_alloc(region,
646 		sizeof(struct mesh_state));
647 	if(!mstate) {
648 		alloc_reg_release(env->alloc, region);
649 		return NULL;
650 	}
651 	memset(mstate, 0, sizeof(*mstate));
652 	mstate->node = *RBTREE_NULL;
653 	mstate->run_node = *RBTREE_NULL;
654 	mstate->node.key = mstate;
655 	mstate->run_node.key = mstate;
656 	mstate->reply_list = NULL;
657 	mstate->list_select = mesh_no_list;
658 	mstate->replies_sent = 0;
659 	rbtree_init(&mstate->super_set, &mesh_state_ref_compare);
660 	rbtree_init(&mstate->sub_set, &mesh_state_ref_compare);
661 	mstate->num_activated = 0;
662 	mstate->unique = NULL;
663 	/* init module qstate */
664 	mstate->s.qinfo.qtype = qinfo->qtype;
665 	mstate->s.qinfo.qclass = qinfo->qclass;
666 	mstate->s.qinfo.local_alias = NULL;
667 	mstate->s.qinfo.qname_len = qinfo->qname_len;
668 	mstate->s.qinfo.qname = regional_alloc_init(region, qinfo->qname,
669 		qinfo->qname_len);
670 	if(!mstate->s.qinfo.qname) {
671 		alloc_reg_release(env->alloc, region);
672 		return NULL;
673 	}
674 	if(cinfo) {
675 		mstate->s.client_info = regional_alloc_init(region, cinfo,
676 			sizeof(*cinfo));
677 		if(!mstate->s.client_info) {
678 			alloc_reg_release(env->alloc, region);
679 			return NULL;
680 		}
681 	}
682 	/* remove all weird bits from qflags */
683 	mstate->s.query_flags = (qflags & (BIT_RD|BIT_CD));
684 	mstate->s.is_priming = prime;
685 	mstate->s.is_valrec = valrec;
686 	mstate->s.reply = NULL;
687 	mstate->s.region = region;
688 	mstate->s.curmod = 0;
689 	mstate->s.return_msg = 0;
690 	mstate->s.return_rcode = LDNS_RCODE_NOERROR;
691 	mstate->s.env = env;
692 	mstate->s.mesh_info = mstate;
693 	mstate->s.prefetch_leeway = 0;
694 	mstate->s.no_cache_lookup = 0;
695 	mstate->s.no_cache_store = 0;
696 	mstate->s.need_refetch = 0;
697 	mstate->s.was_ratelimited = 0;
698 
699 	/* init modules */
700 	for(i=0; i<env->mesh->mods.num; i++) {
701 		mstate->s.minfo[i] = NULL;
702 		mstate->s.ext_state[i] = module_state_initial;
703 	}
704 	/* init edns option lists */
705 	mstate->s.edns_opts_front_in = NULL;
706 	mstate->s.edns_opts_back_out = NULL;
707 	mstate->s.edns_opts_back_in = NULL;
708 	mstate->s.edns_opts_front_out = NULL;
709 
710 	return mstate;
711 }
712 
713 int
714 mesh_state_is_unique(struct mesh_state* mstate)
715 {
716 	return mstate->unique != NULL;
717 }
718 
719 void
720 mesh_state_make_unique(struct mesh_state* mstate)
721 {
722 	mstate->unique = mstate;
723 }
724 
725 void
726 mesh_state_cleanup(struct mesh_state* mstate)
727 {
728 	struct mesh_area* mesh;
729 	int i;
730 	if(!mstate)
731 		return;
732 	mesh = mstate->s.env->mesh;
733 	/* drop unsent replies */
734 	if(!mstate->replies_sent) {
735 		struct mesh_reply* rep;
736 		struct mesh_cb* cb;
737 		for(rep=mstate->reply_list; rep; rep=rep->next) {
738 			comm_point_drop_reply(&rep->query_reply);
739 			mesh->num_reply_addrs--;
740 		}
741 		while((cb = mstate->cb_list)!=NULL) {
742 			mstate->cb_list = cb->next;
743 			fptr_ok(fptr_whitelist_mesh_cb(cb->cb));
744 			(*cb->cb)(cb->cb_arg, LDNS_RCODE_SERVFAIL, NULL,
745 				sec_status_unchecked, NULL, 0);
746 			mesh->num_reply_addrs--;
747 		}
748 	}
749 
750 	/* de-init modules */
751 	for(i=0; i<mesh->mods.num; i++) {
752 		fptr_ok(fptr_whitelist_mod_clear(mesh->mods.mod[i]->clear));
753 		(*mesh->mods.mod[i]->clear)(&mstate->s, i);
754 		mstate->s.minfo[i] = NULL;
755 		mstate->s.ext_state[i] = module_finished;
756 	}
757 	alloc_reg_release(mstate->s.env->alloc, mstate->s.region);
758 }
759 
760 void
761 mesh_state_delete(struct module_qstate* qstate)
762 {
763 	struct mesh_area* mesh;
764 	struct mesh_state_ref* super, ref;
765 	struct mesh_state* mstate;
766 	if(!qstate)
767 		return;
768 	mstate = qstate->mesh_info;
769 	mesh = mstate->s.env->mesh;
770 	mesh_detach_subs(&mstate->s);
771 	if(mstate->list_select == mesh_forever_list) {
772 		mesh->num_forever_states --;
773 		mesh_list_remove(mstate, &mesh->forever_first,
774 			&mesh->forever_last);
775 	} else if(mstate->list_select == mesh_jostle_list) {
776 		mesh_list_remove(mstate, &mesh->jostle_first,
777 			&mesh->jostle_last);
778 	}
779 	if(!mstate->reply_list && !mstate->cb_list
780 		&& mstate->super_set.count == 0) {
781 		log_assert(mesh->num_detached_states > 0);
782 		mesh->num_detached_states--;
783 	}
784 	if(mstate->reply_list || mstate->cb_list) {
785 		log_assert(mesh->num_reply_states > 0);
786 		mesh->num_reply_states--;
787 	}
788 	ref.node.key = &ref;
789 	ref.s = mstate;
790 	RBTREE_FOR(super, struct mesh_state_ref*, &mstate->super_set) {
791 		(void)rbtree_delete(&super->s->sub_set, &ref);
792 	}
793 	(void)rbtree_delete(&mesh->run, mstate);
794 	(void)rbtree_delete(&mesh->all, mstate);
795 	mesh_state_cleanup(mstate);
796 }
797 
798 /** helper recursive rbtree find routine */
799 static int
800 find_in_subsub(struct mesh_state* m, struct mesh_state* tofind, size_t *c)
801 {
802 	struct mesh_state_ref* r;
803 	if((*c)++ > MESH_MAX_SUBSUB)
804 		return 1;
805 	RBTREE_FOR(r, struct mesh_state_ref*, &m->sub_set) {
806 		if(r->s == tofind || find_in_subsub(r->s, tofind, c))
807 			return 1;
808 	}
809 	return 0;
810 }
811 
812 /** find cycle for already looked up mesh_state */
813 static int
814 mesh_detect_cycle_found(struct module_qstate* qstate, struct mesh_state* dep_m)
815 {
816 	struct mesh_state* cyc_m = qstate->mesh_info;
817 	size_t counter = 0;
818 	if(!dep_m)
819 		return 0;
820 	if(dep_m == cyc_m || find_in_subsub(dep_m, cyc_m, &counter)) {
821 		if(counter > MESH_MAX_SUBSUB)
822 			return 2;
823 		return 1;
824 	}
825 	return 0;
826 }
827 
828 void mesh_detach_subs(struct module_qstate* qstate)
829 {
830 	struct mesh_area* mesh = qstate->env->mesh;
831 	struct mesh_state_ref* ref, lookup;
832 #ifdef UNBOUND_DEBUG
833 	struct rbnode_type* n;
834 #endif
835 	lookup.node.key = &lookup;
836 	lookup.s = qstate->mesh_info;
837 	RBTREE_FOR(ref, struct mesh_state_ref*, &qstate->mesh_info->sub_set) {
838 #ifdef UNBOUND_DEBUG
839 		n =
840 #else
841 		(void)
842 #endif
843 		rbtree_delete(&ref->s->super_set, &lookup);
844 		log_assert(n != NULL); /* must have been present */
845 		if(!ref->s->reply_list && !ref->s->cb_list
846 			&& ref->s->super_set.count == 0) {
847 			mesh->num_detached_states++;
848 			log_assert(mesh->num_detached_states +
849 				mesh->num_reply_states <= mesh->all.count);
850 		}
851 	}
852 	rbtree_init(&qstate->mesh_info->sub_set, &mesh_state_ref_compare);
853 }
854 
855 int mesh_add_sub(struct module_qstate* qstate, struct query_info* qinfo,
856         uint16_t qflags, int prime, int valrec, struct module_qstate** newq,
857 	struct mesh_state** sub)
858 {
859 	/* find it, if not, create it */
860 	struct mesh_area* mesh = qstate->env->mesh;
861 	*sub = mesh_area_find(mesh, NULL, qinfo, qflags,
862 		prime, valrec);
863 	if(mesh_detect_cycle_found(qstate, *sub)) {
864 		verbose(VERB_ALGO, "attach failed, cycle detected");
865 		return 0;
866 	}
867 	if(!*sub) {
868 #ifdef UNBOUND_DEBUG
869 		struct rbnode_type* n;
870 #endif
871 		/* create a new one */
872 		*sub = mesh_state_create(qstate->env, qinfo, NULL, qflags, prime,
873 			valrec);
874 		if(!*sub) {
875 			log_err("mesh_attach_sub: out of memory");
876 			return 0;
877 		}
878 #ifdef UNBOUND_DEBUG
879 		n =
880 #else
881 		(void)
882 #endif
883 		rbtree_insert(&mesh->all, &(*sub)->node);
884 		log_assert(n != NULL);
885 		/* set detached (it is now) */
886 		mesh->num_detached_states++;
887 		/* set new query state to run */
888 #ifdef UNBOUND_DEBUG
889 		n =
890 #else
891 		(void)
892 #endif
893 		rbtree_insert(&mesh->run, &(*sub)->run_node);
894 		log_assert(n != NULL);
895 		*newq = &(*sub)->s;
896 	} else
897 		*newq = NULL;
898 	return 1;
899 }
900 
901 int mesh_attach_sub(struct module_qstate* qstate, struct query_info* qinfo,
902         uint16_t qflags, int prime, int valrec, struct module_qstate** newq)
903 {
904 	struct mesh_area* mesh = qstate->env->mesh;
905 	struct mesh_state* sub = NULL;
906 	int was_detached;
907 	if(!mesh_add_sub(qstate, qinfo, qflags, prime, valrec, newq, &sub))
908 		return 0;
909 	was_detached = (sub->super_set.count == 0);
910 	if(!mesh_state_attachment(qstate->mesh_info, sub))
911 		return 0;
912 	/* if it was a duplicate  attachment, the count was not zero before */
913 	if(!sub->reply_list && !sub->cb_list && was_detached &&
914 		sub->super_set.count == 1) {
915 		/* it used to be detached, before this one got added */
916 		log_assert(mesh->num_detached_states > 0);
917 		mesh->num_detached_states--;
918 	}
919 	/* *newq will be run when inited after the current module stops */
920 	return 1;
921 }
922 
923 int mesh_state_attachment(struct mesh_state* super, struct mesh_state* sub)
924 {
925 #ifdef UNBOUND_DEBUG
926 	struct rbnode_type* n;
927 #endif
928 	struct mesh_state_ref* subref; /* points to sub, inserted in super */
929 	struct mesh_state_ref* superref; /* points to super, inserted in sub */
930 	if( !(subref = regional_alloc(super->s.region,
931 		sizeof(struct mesh_state_ref))) ||
932 		!(superref = regional_alloc(sub->s.region,
933 		sizeof(struct mesh_state_ref))) ) {
934 		log_err("mesh_state_attachment: out of memory");
935 		return 0;
936 	}
937 	superref->node.key = superref;
938 	superref->s = super;
939 	subref->node.key = subref;
940 	subref->s = sub;
941 	if(!rbtree_insert(&sub->super_set, &superref->node)) {
942 		/* this should not happen, iterator and validator do not
943 		 * attach subqueries that are identical. */
944 		/* already attached, we are done, nothing todo.
945 		 * since superref and subref already allocated in region,
946 		 * we cannot free them */
947 		return 1;
948 	}
949 #ifdef UNBOUND_DEBUG
950 	n =
951 #else
952 	(void)
953 #endif
954 	rbtree_insert(&super->sub_set, &subref->node);
955 	log_assert(n != NULL); /* we checked above if statement, the reverse
956 	  administration should not fail now, unless they are out of sync */
957 	return 1;
958 }
959 
960 /**
961  * callback results to mesh cb entry
962  * @param m: mesh state to send it for.
963  * @param rcode: if not 0, error code.
964  * @param rep: reply to send (or NULL if rcode is set).
965  * @param r: callback entry
966  */
967 static void
968 mesh_do_callback(struct mesh_state* m, int rcode, struct reply_info* rep,
969 	struct mesh_cb* r)
970 {
971 	int secure;
972 	char* reason = NULL;
973 	int was_ratelimited = m->s.was_ratelimited;
974 	/* bogus messages are not made into servfail, sec_status passed
975 	 * to the callback function */
976 	if(rep && rep->security == sec_status_secure)
977 		secure = 1;
978 	else	secure = 0;
979 	if(!rep && rcode == LDNS_RCODE_NOERROR)
980 		rcode = LDNS_RCODE_SERVFAIL;
981 	if(!rcode && (rep->security == sec_status_bogus ||
982 		rep->security == sec_status_secure_sentinel_fail)) {
983 		if(!(reason = errinf_to_str_bogus(&m->s)))
984 			rcode = LDNS_RCODE_SERVFAIL;
985 	}
986 	/* send the reply */
987 	if(rcode) {
988 		if(rcode == LDNS_RCODE_SERVFAIL) {
989 			if(!inplace_cb_reply_servfail_call(m->s.env, &m->s.qinfo, &m->s,
990 				rep, rcode, &r->edns, NULL, m->s.region))
991 					r->edns.opt_list = NULL;
992 		} else {
993 			if(!inplace_cb_reply_call(m->s.env, &m->s.qinfo, &m->s, rep, rcode,
994 				&r->edns, NULL, m->s.region))
995 					r->edns.opt_list = NULL;
996 		}
997 		fptr_ok(fptr_whitelist_mesh_cb(r->cb));
998 		(*r->cb)(r->cb_arg, rcode, r->buf, sec_status_unchecked, NULL,
999 			was_ratelimited);
1000 	} else {
1001 		size_t udp_size = r->edns.udp_size;
1002 		sldns_buffer_clear(r->buf);
1003 		r->edns.edns_version = EDNS_ADVERTISED_VERSION;
1004 		r->edns.udp_size = EDNS_ADVERTISED_SIZE;
1005 		r->edns.ext_rcode = 0;
1006 		r->edns.bits &= EDNS_DO;
1007 
1008 		if(!inplace_cb_reply_call(m->s.env, &m->s.qinfo, &m->s, rep,
1009 			LDNS_RCODE_NOERROR, &r->edns, NULL, m->s.region) ||
1010 			!reply_info_answer_encode(&m->s.qinfo, rep, r->qid,
1011 			r->qflags, r->buf, 0, 1,
1012 			m->s.env->scratch, udp_size, &r->edns,
1013 			(int)(r->edns.bits & EDNS_DO), secure))
1014 		{
1015 			fptr_ok(fptr_whitelist_mesh_cb(r->cb));
1016 			(*r->cb)(r->cb_arg, LDNS_RCODE_SERVFAIL, r->buf,
1017 				sec_status_unchecked, NULL, 0);
1018 		} else {
1019 			fptr_ok(fptr_whitelist_mesh_cb(r->cb));
1020 			(*r->cb)(r->cb_arg, LDNS_RCODE_NOERROR, r->buf,
1021 				rep->security, reason, was_ratelimited);
1022 		}
1023 	}
1024 	free(reason);
1025 	m->s.env->mesh->num_reply_addrs--;
1026 }
1027 
1028 /**
1029  * Send reply to mesh reply entry
1030  * @param m: mesh state to send it for.
1031  * @param rcode: if not 0, error code.
1032  * @param rep: reply to send (or NULL if rcode is set).
1033  * @param r: reply entry
1034  * @param prev: previous reply, already has its answer encoded in buffer.
1035  */
1036 static void
1037 mesh_send_reply(struct mesh_state* m, int rcode, struct reply_info* rep,
1038 	struct mesh_reply* r, struct mesh_reply* prev)
1039 {
1040 	struct timeval end_time;
1041 	struct timeval duration;
1042 	int secure;
1043 	/* Copy the client's EDNS for later restore, to make sure the edns
1044 	 * compare is with the correct edns options. */
1045 	struct edns_data edns_bak = r->edns;
1046 	/* examine security status */
1047 	if(m->s.env->need_to_validate && (!(r->qflags&BIT_CD) ||
1048 		m->s.env->cfg->ignore_cd) && rep &&
1049 		(rep->security <= sec_status_bogus ||
1050 		rep->security == sec_status_secure_sentinel_fail)) {
1051 		rcode = LDNS_RCODE_SERVFAIL;
1052 		if(m->s.env->cfg->stat_extended)
1053 			m->s.env->mesh->ans_bogus++;
1054 	}
1055 	if(rep && rep->security == sec_status_secure)
1056 		secure = 1;
1057 	else	secure = 0;
1058 	if(!rep && rcode == LDNS_RCODE_NOERROR)
1059 		rcode = LDNS_RCODE_SERVFAIL;
1060 	/* send the reply */
1061 	/* We don't reuse the encoded answer if either the previous or current
1062 	 * response has a local alias.  We could compare the alias records
1063 	 * and still reuse the previous answer if they are the same, but that
1064 	 * would be complicated and error prone for the relatively minor case.
1065 	 * So we err on the side of safety. */
1066 	if(prev && prev->qflags == r->qflags &&
1067 		!prev->local_alias && !r->local_alias &&
1068 		prev->edns.edns_present == r->edns.edns_present &&
1069 		prev->edns.bits == r->edns.bits &&
1070 		prev->edns.udp_size == r->edns.udp_size &&
1071 		edns_opt_list_compare(prev->edns.opt_list, r->edns.opt_list)
1072 		== 0) {
1073 		/* if the previous reply is identical to this one, fix ID */
1074 		if(prev->query_reply.c->buffer != r->query_reply.c->buffer)
1075 			sldns_buffer_copy(r->query_reply.c->buffer,
1076 				prev->query_reply.c->buffer);
1077 		sldns_buffer_write_at(r->query_reply.c->buffer, 0,
1078 			&r->qid, sizeof(uint16_t));
1079 		sldns_buffer_write_at(r->query_reply.c->buffer, 12,
1080 			r->qname, m->s.qinfo.qname_len);
1081 		comm_point_send_reply(&r->query_reply);
1082 	} else if(rcode) {
1083 		m->s.qinfo.qname = r->qname;
1084 		m->s.qinfo.local_alias = r->local_alias;
1085 		if(rcode == LDNS_RCODE_SERVFAIL) {
1086 			if(!inplace_cb_reply_servfail_call(m->s.env, &m->s.qinfo, &m->s,
1087 				rep, rcode, &r->edns, NULL, m->s.region))
1088 					r->edns.opt_list = NULL;
1089 		} else {
1090 			if(!inplace_cb_reply_call(m->s.env, &m->s.qinfo, &m->s, rep, rcode,
1091 				&r->edns, NULL, m->s.region))
1092 					r->edns.opt_list = NULL;
1093 		}
1094 		error_encode(r->query_reply.c->buffer, rcode, &m->s.qinfo,
1095 			r->qid, r->qflags, &r->edns);
1096 		comm_point_send_reply(&r->query_reply);
1097 	} else {
1098 		size_t udp_size = r->edns.udp_size;
1099 		r->edns.edns_version = EDNS_ADVERTISED_VERSION;
1100 		r->edns.udp_size = EDNS_ADVERTISED_SIZE;
1101 		r->edns.ext_rcode = 0;
1102 		r->edns.bits &= EDNS_DO;
1103 		m->s.qinfo.qname = r->qname;
1104 		m->s.qinfo.local_alias = r->local_alias;
1105 		if(!inplace_cb_reply_call(m->s.env, &m->s.qinfo, &m->s, rep,
1106 			LDNS_RCODE_NOERROR, &r->edns, NULL, m->s.region) ||
1107 			!apply_edns_options(&r->edns, &edns_bak,
1108 				m->s.env->cfg, r->query_reply.c,
1109 				m->s.region) ||
1110 			!reply_info_answer_encode(&m->s.qinfo, rep, r->qid,
1111 			r->qflags, r->query_reply.c->buffer, 0, 1,
1112 			m->s.env->scratch, udp_size, &r->edns,
1113 			(int)(r->edns.bits & EDNS_DO), secure))
1114 		{
1115 			if(!inplace_cb_reply_servfail_call(m->s.env, &m->s.qinfo, &m->s,
1116 			rep, LDNS_RCODE_SERVFAIL, &r->edns, NULL, m->s.region))
1117 				r->edns.opt_list = NULL;
1118 			error_encode(r->query_reply.c->buffer,
1119 				LDNS_RCODE_SERVFAIL, &m->s.qinfo, r->qid,
1120 				r->qflags, &r->edns);
1121 		}
1122 		r->edns = edns_bak;
1123 		comm_point_send_reply(&r->query_reply);
1124 	}
1125 	/* account */
1126 	m->s.env->mesh->num_reply_addrs--;
1127 	end_time = *m->s.env->now_tv;
1128 	timeval_subtract(&duration, &end_time, &r->start_time);
1129 	verbose(VERB_ALGO, "query took " ARG_LL "d.%6.6d sec",
1130 		(long long)duration.tv_sec, (int)duration.tv_usec);
1131 	m->s.env->mesh->replies_sent++;
1132 	timeval_add(&m->s.env->mesh->replies_sum_wait, &duration);
1133 	timehist_insert(m->s.env->mesh->histogram, &duration);
1134 	if(m->s.env->cfg->stat_extended) {
1135 		uint16_t rc = FLAGS_GET_RCODE(sldns_buffer_read_u16_at(r->
1136 			query_reply.c->buffer, 2));
1137 		if(secure) m->s.env->mesh->ans_secure++;
1138 		m->s.env->mesh->ans_rcode[ rc ] ++;
1139 		if(rc == 0 && LDNS_ANCOUNT(sldns_buffer_begin(r->
1140 			query_reply.c->buffer)) == 0)
1141 			m->s.env->mesh->ans_nodata++;
1142 	}
1143 	/* Log reply sent */
1144 	if(m->s.env->cfg->log_replies) {
1145 		log_reply_info(0, &m->s.qinfo, &r->query_reply.addr,
1146 			r->query_reply.addrlen, duration, 0,
1147 			r->query_reply.c->buffer);
1148 	}
1149 }
1150 
1151 void mesh_query_done(struct mesh_state* mstate)
1152 {
1153 	struct mesh_reply* r;
1154 	struct mesh_reply* prev = NULL;
1155 	struct mesh_cb* c;
1156 	struct reply_info* rep = (mstate->s.return_msg?
1157 		mstate->s.return_msg->rep:NULL);
1158 	if((mstate->s.return_rcode == LDNS_RCODE_SERVFAIL ||
1159 		(rep && FLAGS_GET_RCODE(rep->flags) == LDNS_RCODE_SERVFAIL))
1160 		&& mstate->s.env->cfg->log_servfail
1161 		&& !mstate->s.env->cfg->val_log_squelch) {
1162 		char* err = errinf_to_str_servfail(&mstate->s);
1163 		if(err)
1164 			log_err("%s", err);
1165 		free(err);
1166 	}
1167 	for(r = mstate->reply_list; r; r = r->next) {
1168 		/* if a response-ip address block has been stored the
1169 		 *  information should be logged for each client. */
1170 		if(mstate->s.respip_action_info &&
1171 			mstate->s.respip_action_info->addrinfo) {
1172 			respip_inform_print(mstate->s.respip_action_info->addrinfo,
1173 				r->qname, mstate->s.qinfo.qtype,
1174 				mstate->s.qinfo.qclass, r->local_alias,
1175 				&r->query_reply);
1176 		}
1177 
1178 		/* if this query is determined to be dropped during the
1179 		 * mesh processing, this is the point to take that action. */
1180 		if(mstate->s.is_drop)
1181 			comm_point_drop_reply(&r->query_reply);
1182 		else {
1183 			mesh_send_reply(mstate, mstate->s.return_rcode, rep,
1184 				r, prev);
1185 			prev = r;
1186 		}
1187 	}
1188 	mstate->replies_sent = 1;
1189 	while((c = mstate->cb_list) != NULL) {
1190 		/* take this cb off the list; so that the list can be
1191 		 * changed, eg. by adds from the callback routine */
1192 		if(!mstate->reply_list && mstate->cb_list && !c->next) {
1193 			/* was a reply state, not anymore */
1194 			mstate->s.env->mesh->num_reply_states--;
1195 		}
1196 		mstate->cb_list = c->next;
1197 		if(!mstate->reply_list && !mstate->cb_list &&
1198 			mstate->super_set.count == 0)
1199 			mstate->s.env->mesh->num_detached_states++;
1200 		mesh_do_callback(mstate, mstate->s.return_rcode, rep, c);
1201 	}
1202 }
1203 
1204 void mesh_walk_supers(struct mesh_area* mesh, struct mesh_state* mstate)
1205 {
1206 	struct mesh_state_ref* ref;
1207 	RBTREE_FOR(ref, struct mesh_state_ref*, &mstate->super_set)
1208 	{
1209 		/* make super runnable */
1210 		(void)rbtree_insert(&mesh->run, &ref->s->run_node);
1211 		/* callback the function to inform super of result */
1212 		fptr_ok(fptr_whitelist_mod_inform_super(
1213 			mesh->mods.mod[ref->s->s.curmod]->inform_super));
1214 		(*mesh->mods.mod[ref->s->s.curmod]->inform_super)(&mstate->s,
1215 			ref->s->s.curmod, &ref->s->s);
1216 		/* copy state that is always relevant to super */
1217 		copy_state_to_super(&mstate->s, ref->s->s.curmod, &ref->s->s);
1218 	}
1219 }
1220 
1221 struct mesh_state* mesh_area_find(struct mesh_area* mesh,
1222 	struct respip_client_info* cinfo, struct query_info* qinfo,
1223 	uint16_t qflags, int prime, int valrec)
1224 {
1225 	struct mesh_state key;
1226 	struct mesh_state* result;
1227 
1228 	key.node.key = &key;
1229 	key.s.is_priming = prime;
1230 	key.s.is_valrec = valrec;
1231 	key.s.qinfo = *qinfo;
1232 	key.s.query_flags = qflags;
1233 	/* We are searching for a similar mesh state when we DO want to
1234 	 * aggregate the state. Thus unique is set to NULL. (default when we
1235 	 * desire aggregation).*/
1236 	key.unique = NULL;
1237 	key.s.client_info = cinfo;
1238 
1239 	result = (struct mesh_state*)rbtree_search(&mesh->all, &key);
1240 	return result;
1241 }
1242 
1243 int mesh_state_add_cb(struct mesh_state* s, struct edns_data* edns,
1244         sldns_buffer* buf, mesh_cb_func_type cb, void* cb_arg,
1245 	uint16_t qid, uint16_t qflags)
1246 {
1247 	struct mesh_cb* r = regional_alloc(s->s.region,
1248 		sizeof(struct mesh_cb));
1249 	if(!r)
1250 		return 0;
1251 	r->buf = buf;
1252 	log_assert(fptr_whitelist_mesh_cb(cb)); /* early failure ifmissing*/
1253 	r->cb = cb;
1254 	r->cb_arg = cb_arg;
1255 	r->edns = *edns;
1256 	if(edns->opt_list) {
1257 		r->edns.opt_list = edns_opt_copy_region(edns->opt_list,
1258 			s->s.region);
1259 		if(!r->edns.opt_list)
1260 			return 0;
1261 	}
1262 	r->qid = qid;
1263 	r->qflags = qflags;
1264 	r->next = s->cb_list;
1265 	s->cb_list = r;
1266 	return 1;
1267 
1268 }
1269 
1270 int mesh_state_add_reply(struct mesh_state* s, struct edns_data* edns,
1271         struct comm_reply* rep, uint16_t qid, uint16_t qflags,
1272         const struct query_info* qinfo)
1273 {
1274 	struct mesh_reply* r = regional_alloc(s->s.region,
1275 		sizeof(struct mesh_reply));
1276 	if(!r)
1277 		return 0;
1278 	r->query_reply = *rep;
1279 	r->edns = *edns;
1280 	if(edns->opt_list) {
1281 		r->edns.opt_list = edns_opt_copy_region(edns->opt_list,
1282 			s->s.region);
1283 		if(!r->edns.opt_list)
1284 			return 0;
1285 	}
1286 	r->qid = qid;
1287 	r->qflags = qflags;
1288 	r->start_time = *s->s.env->now_tv;
1289 	r->next = s->reply_list;
1290 	r->qname = regional_alloc_init(s->s.region, qinfo->qname,
1291 		s->s.qinfo.qname_len);
1292 	if(!r->qname)
1293 		return 0;
1294 
1295 	/* Data related to local alias stored in 'qinfo' (if any) is ephemeral
1296 	 * and can be different for different original queries (even if the
1297 	 * replaced query name is the same).  So we need to make a deep copy
1298 	 * and store the copy for each reply info. */
1299 	if(qinfo->local_alias) {
1300 		struct packed_rrset_data* d;
1301 		struct packed_rrset_data* dsrc;
1302 		r->local_alias = regional_alloc_zero(s->s.region,
1303 			sizeof(*qinfo->local_alias));
1304 		if(!r->local_alias)
1305 			return 0;
1306 		r->local_alias->rrset = regional_alloc_init(s->s.region,
1307 			qinfo->local_alias->rrset,
1308 			sizeof(*qinfo->local_alias->rrset));
1309 		if(!r->local_alias->rrset)
1310 			return 0;
1311 		dsrc = qinfo->local_alias->rrset->entry.data;
1312 
1313 		/* In the current implementation, a local alias must be
1314 		 * a single CNAME RR (see worker_handle_request()). */
1315 		log_assert(!qinfo->local_alias->next && dsrc->count == 1 &&
1316 			qinfo->local_alias->rrset->rk.type ==
1317 			htons(LDNS_RR_TYPE_CNAME));
1318 		/* Technically, we should make a local copy for the owner
1319 		 * name of the RRset, but in the case of the first (and
1320 		 * currently only) local alias RRset, the owner name should
1321 		 * point to the qname of the corresponding query, which should
1322 		 * be valid throughout the lifetime of this mesh_reply.  So
1323 		 * we can skip copying. */
1324 		log_assert(qinfo->local_alias->rrset->rk.dname ==
1325 			sldns_buffer_at(rep->c->buffer, LDNS_HEADER_SIZE));
1326 
1327 		d = regional_alloc_init(s->s.region, dsrc,
1328 			sizeof(struct packed_rrset_data)
1329 			+ sizeof(size_t) + sizeof(uint8_t*) + sizeof(time_t));
1330 		if(!d)
1331 			return 0;
1332 		r->local_alias->rrset->entry.data = d;
1333 		d->rr_len = (size_t*)((uint8_t*)d +
1334 			sizeof(struct packed_rrset_data));
1335 		d->rr_data = (uint8_t**)&(d->rr_len[1]);
1336 		d->rr_ttl = (time_t*)&(d->rr_data[1]);
1337 		d->rr_len[0] = dsrc->rr_len[0];
1338 		d->rr_ttl[0] = dsrc->rr_ttl[0];
1339 		d->rr_data[0] = regional_alloc_init(s->s.region,
1340 			dsrc->rr_data[0], d->rr_len[0]);
1341 		if(!d->rr_data[0])
1342 			return 0;
1343 	} else
1344 		r->local_alias = NULL;
1345 
1346 	s->reply_list = r;
1347 	return 1;
1348 }
1349 
1350 /* Extract the query info and flags from 'mstate' into '*qinfop' and '*qflags'.
1351  * Since this is only used for internal refetch of otherwise-expired answer,
1352  * we simply ignore the rare failure mode when memory allocation fails. */
1353 static void
1354 mesh_copy_qinfo(struct mesh_state* mstate, struct query_info** qinfop,
1355 	uint16_t* qflags)
1356 {
1357 	struct regional* region = mstate->s.env->scratch;
1358 	struct query_info* qinfo;
1359 
1360 	qinfo = regional_alloc_init(region, &mstate->s.qinfo, sizeof(*qinfo));
1361 	if(!qinfo)
1362 		return;
1363 	qinfo->qname = regional_alloc_init(region, qinfo->qname,
1364 		qinfo->qname_len);
1365 	if(!qinfo->qname)
1366 		return;
1367 	*qinfop = qinfo;
1368 	*qflags = mstate->s.query_flags;
1369 }
1370 
1371 /**
1372  * Continue processing the mesh state at another module.
1373  * Handles module to modules transfer of control.
1374  * Handles module finished.
1375  * @param mesh: the mesh area.
1376  * @param mstate: currently active mesh state.
1377  * 	Deleted if finished, calls _done and _supers to
1378  * 	send replies to clients and inform other mesh states.
1379  * 	This in turn may create additional runnable mesh states.
1380  * @param s: state at which the current module exited.
1381  * @param ev: the event sent to the module.
1382  * 	returned is the event to send to the next module.
1383  * @return true if continue processing at the new module.
1384  * 	false if not continued processing is needed.
1385  */
1386 static int
1387 mesh_continue(struct mesh_area* mesh, struct mesh_state* mstate,
1388 	enum module_ext_state s, enum module_ev* ev)
1389 {
1390 	mstate->num_activated++;
1391 	if(mstate->num_activated > MESH_MAX_ACTIVATION) {
1392 		/* module is looping. Stop it. */
1393 		log_err("internal error: looping module (%s) stopped",
1394 			mesh->mods.mod[mstate->s.curmod]->name);
1395 		log_query_info(VERB_QUERY, "pass error for qstate",
1396 			&mstate->s.qinfo);
1397 		s = module_error;
1398 	}
1399 	if(s == module_wait_module || s == module_restart_next) {
1400 		/* start next module */
1401 		mstate->s.curmod++;
1402 		if(mesh->mods.num == mstate->s.curmod) {
1403 			log_err("Cannot pass to next module; at last module");
1404 			log_query_info(VERB_QUERY, "pass error for qstate",
1405 				&mstate->s.qinfo);
1406 			mstate->s.curmod--;
1407 			return mesh_continue(mesh, mstate, module_error, ev);
1408 		}
1409 		if(s == module_restart_next) {
1410 			int curmod = mstate->s.curmod;
1411 			for(; mstate->s.curmod < mesh->mods.num;
1412 				mstate->s.curmod++) {
1413 				fptr_ok(fptr_whitelist_mod_clear(
1414 					mesh->mods.mod[mstate->s.curmod]->clear));
1415 				(*mesh->mods.mod[mstate->s.curmod]->clear)
1416 					(&mstate->s, mstate->s.curmod);
1417 				mstate->s.minfo[mstate->s.curmod] = NULL;
1418 			}
1419 			mstate->s.curmod = curmod;
1420 		}
1421 		*ev = module_event_pass;
1422 		return 1;
1423 	}
1424 	if(s == module_wait_subquery && mstate->sub_set.count == 0) {
1425 		log_err("module cannot wait for subquery, subquery list empty");
1426 		log_query_info(VERB_QUERY, "pass error for qstate",
1427 			&mstate->s.qinfo);
1428 		s = module_error;
1429 	}
1430 	if(s == module_error && mstate->s.return_rcode == LDNS_RCODE_NOERROR) {
1431 		/* error is bad, handle pass back up below */
1432 		mstate->s.return_rcode = LDNS_RCODE_SERVFAIL;
1433 	}
1434 	if(s == module_error) {
1435 		mesh_query_done(mstate);
1436 		mesh_walk_supers(mesh, mstate);
1437 		mesh_state_delete(&mstate->s);
1438 		return 0;
1439 	}
1440 	if(s == module_finished) {
1441 		if(mstate->s.curmod == 0) {
1442 			struct query_info* qinfo = NULL;
1443 			uint16_t qflags;
1444 
1445 			mesh_query_done(mstate);
1446 			mesh_walk_supers(mesh, mstate);
1447 
1448 			/* If the answer to the query needs to be refetched
1449 			 * from an external DNS server, we'll need to schedule
1450 			 * a prefetch after removing the current state, so
1451 			 * we need to make a copy of the query info here. */
1452 			if(mstate->s.need_refetch)
1453 				mesh_copy_qinfo(mstate, &qinfo, &qflags);
1454 
1455 			mesh_state_delete(&mstate->s);
1456 			if(qinfo) {
1457 				mesh_schedule_prefetch(mesh, qinfo, qflags,
1458 					0, 1);
1459 			}
1460 			return 0;
1461 		}
1462 		/* pass along the locus of control */
1463 		mstate->s.curmod --;
1464 		*ev = module_event_moddone;
1465 		return 1;
1466 	}
1467 	return 0;
1468 }
1469 
1470 void mesh_run(struct mesh_area* mesh, struct mesh_state* mstate,
1471 	enum module_ev ev, struct outbound_entry* e)
1472 {
1473 	enum module_ext_state s;
1474 	verbose(VERB_ALGO, "mesh_run: start");
1475 	while(mstate) {
1476 		/* run the module */
1477 		fptr_ok(fptr_whitelist_mod_operate(
1478 			mesh->mods.mod[mstate->s.curmod]->operate));
1479 		(*mesh->mods.mod[mstate->s.curmod]->operate)
1480 			(&mstate->s, ev, mstate->s.curmod, e);
1481 
1482 		/* examine results */
1483 		mstate->s.reply = NULL;
1484 		regional_free_all(mstate->s.env->scratch);
1485 		s = mstate->s.ext_state[mstate->s.curmod];
1486 		verbose(VERB_ALGO, "mesh_run: %s module exit state is %s",
1487 			mesh->mods.mod[mstate->s.curmod]->name, strextstate(s));
1488 		e = NULL;
1489 		if(mesh_continue(mesh, mstate, s, &ev))
1490 			continue;
1491 
1492 		/* run more modules */
1493 		ev = module_event_pass;
1494 		if(mesh->run.count > 0) {
1495 			/* pop random element off the runnable tree */
1496 			mstate = (struct mesh_state*)mesh->run.root->key;
1497 			(void)rbtree_delete(&mesh->run, mstate);
1498 		} else mstate = NULL;
1499 	}
1500 	if(verbosity >= VERB_ALGO) {
1501 		mesh_stats(mesh, "mesh_run: end");
1502 		mesh_log_list(mesh);
1503 	}
1504 }
1505 
1506 void
1507 mesh_log_list(struct mesh_area* mesh)
1508 {
1509 	char buf[30];
1510 	struct mesh_state* m;
1511 	int num = 0;
1512 	RBTREE_FOR(m, struct mesh_state*, &mesh->all) {
1513 		snprintf(buf, sizeof(buf), "%d%s%s%s%s%s%s mod%d %s%s",
1514 			num++, (m->s.is_priming)?"p":"",  /* prime */
1515 			(m->s.is_valrec)?"v":"",  /* prime */
1516 			(m->s.query_flags&BIT_RD)?"RD":"",
1517 			(m->s.query_flags&BIT_CD)?"CD":"",
1518 			(m->super_set.count==0)?"d":"", /* detached */
1519 			(m->sub_set.count!=0)?"c":"",  /* children */
1520 			m->s.curmod, (m->reply_list)?"rep":"", /*hasreply*/
1521 			(m->cb_list)?"cb":"" /* callbacks */
1522 			);
1523 		log_query_info(VERB_ALGO, buf, &m->s.qinfo);
1524 	}
1525 }
1526 
1527 void
1528 mesh_stats(struct mesh_area* mesh, const char* str)
1529 {
1530 	verbose(VERB_DETAIL, "%s %u recursion states (%u with reply, "
1531 		"%u detached), %u waiting replies, %u recursion replies "
1532 		"sent, %d replies dropped, %d states jostled out",
1533 		str, (unsigned)mesh->all.count,
1534 		(unsigned)mesh->num_reply_states,
1535 		(unsigned)mesh->num_detached_states,
1536 		(unsigned)mesh->num_reply_addrs,
1537 		(unsigned)mesh->replies_sent,
1538 		(unsigned)mesh->stats_dropped,
1539 		(unsigned)mesh->stats_jostled);
1540 	if(mesh->replies_sent > 0) {
1541 		struct timeval avg;
1542 		timeval_divide(&avg, &mesh->replies_sum_wait,
1543 			mesh->replies_sent);
1544 		log_info("average recursion processing time "
1545 			ARG_LL "d.%6.6d sec",
1546 			(long long)avg.tv_sec, (int)avg.tv_usec);
1547 		log_info("histogram of recursion processing times");
1548 		timehist_log(mesh->histogram, "recursions");
1549 	}
1550 }
1551 
1552 void
1553 mesh_stats_clear(struct mesh_area* mesh)
1554 {
1555 	if(!mesh)
1556 		return;
1557 	mesh->replies_sent = 0;
1558 	mesh->replies_sum_wait.tv_sec = 0;
1559 	mesh->replies_sum_wait.tv_usec = 0;
1560 	mesh->stats_jostled = 0;
1561 	mesh->stats_dropped = 0;
1562 	timehist_clear(mesh->histogram);
1563 	mesh->ans_secure = 0;
1564 	mesh->ans_bogus = 0;
1565 	memset(&mesh->ans_rcode[0], 0, sizeof(size_t)*16);
1566 	mesh->ans_nodata = 0;
1567 }
1568 
1569 size_t
1570 mesh_get_mem(struct mesh_area* mesh)
1571 {
1572 	struct mesh_state* m;
1573 	size_t s = sizeof(*mesh) + sizeof(struct timehist) +
1574 		sizeof(struct th_buck)*mesh->histogram->num +
1575 		sizeof(sldns_buffer) + sldns_buffer_capacity(mesh->qbuf_bak);
1576 	RBTREE_FOR(m, struct mesh_state*, &mesh->all) {
1577 		/* all, including m itself allocated in qstate region */
1578 		s += regional_get_mem(m->s.region);
1579 	}
1580 	return s;
1581 }
1582 
1583 int
1584 mesh_detect_cycle(struct module_qstate* qstate, struct query_info* qinfo,
1585 	uint16_t flags, int prime, int valrec)
1586 {
1587 	struct mesh_area* mesh = qstate->env->mesh;
1588 	struct mesh_state* dep_m = NULL;
1589 	if(!mesh_state_is_unique(qstate->mesh_info))
1590 		dep_m = mesh_area_find(mesh, NULL, qinfo, flags, prime, valrec);
1591 	return mesh_detect_cycle_found(qstate, dep_m);
1592 }
1593 
1594 void mesh_list_insert(struct mesh_state* m, struct mesh_state** fp,
1595         struct mesh_state** lp)
1596 {
1597 	/* insert as last element */
1598 	m->prev = *lp;
1599 	m->next = NULL;
1600 	if(*lp)
1601 		(*lp)->next = m;
1602 	else	*fp = m;
1603 	*lp = m;
1604 }
1605 
1606 void mesh_list_remove(struct mesh_state* m, struct mesh_state** fp,
1607         struct mesh_state** lp)
1608 {
1609 	if(m->next)
1610 		m->next->prev = m->prev;
1611 	else	*lp = m->prev;
1612 	if(m->prev)
1613 		m->prev->next = m->next;
1614 	else	*fp = m->next;
1615 }
1616