xref: /freebsd/contrib/unbound/services/mesh.c (revision 9e4c35f867aca020df8d01fb7371bf5ae1cc8a2d)
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 "services/cache/rrset.h"
50 #include "util/log.h"
51 #include "util/net_help.h"
52 #include "util/module.h"
53 #include "util/regional.h"
54 #include "util/data/msgencode.h"
55 #include "util/timehist.h"
56 #include "util/fptr_wlist.h"
57 #include "util/alloc.h"
58 #include "util/config_file.h"
59 #include "util/edns.h"
60 #include "sldns/sbuffer.h"
61 #include "sldns/wire2str.h"
62 #include "services/localzone.h"
63 #include "util/data/dname.h"
64 #include "respip/respip.h"
65 #include "services/listen_dnsport.h"
66 
67 /** subtract timers and the values do not overflow or become negative */
68 static void
69 timeval_subtract(struct timeval* d, const struct timeval* end, const struct timeval* start)
70 {
71 #ifndef S_SPLINT_S
72 	time_t end_usec = end->tv_usec;
73 	d->tv_sec = end->tv_sec - start->tv_sec;
74 	if(end_usec < start->tv_usec) {
75 		end_usec += 1000000;
76 		d->tv_sec--;
77 	}
78 	d->tv_usec = end_usec - start->tv_usec;
79 #endif
80 }
81 
82 /** add timers and the values do not overflow or become negative */
83 static void
84 timeval_add(struct timeval* d, const struct timeval* add)
85 {
86 #ifndef S_SPLINT_S
87 	d->tv_sec += add->tv_sec;
88 	d->tv_usec += add->tv_usec;
89 	if(d->tv_usec >= 1000000 ) {
90 		d->tv_usec -= 1000000;
91 		d->tv_sec++;
92 	}
93 #endif
94 }
95 
96 /** divide sum of timers to get average */
97 static void
98 timeval_divide(struct timeval* avg, const struct timeval* sum, size_t d)
99 {
100 #ifndef S_SPLINT_S
101 	size_t leftover;
102 	if(d == 0) {
103 		avg->tv_sec = 0;
104 		avg->tv_usec = 0;
105 		return;
106 	}
107 	avg->tv_sec = sum->tv_sec / d;
108 	avg->tv_usec = sum->tv_usec / d;
109 	/* handle fraction from seconds divide */
110 	leftover = sum->tv_sec - avg->tv_sec*d;
111 	avg->tv_usec += (leftover*1000000)/d;
112 #endif
113 }
114 
115 /** histogram compare of time values */
116 static int
117 timeval_smaller(const struct timeval* x, const struct timeval* y)
118 {
119 #ifndef S_SPLINT_S
120 	if(x->tv_sec < y->tv_sec)
121 		return 1;
122 	else if(x->tv_sec == y->tv_sec) {
123 		if(x->tv_usec <= y->tv_usec)
124 			return 1;
125 		else	return 0;
126 	}
127 	else	return 0;
128 #endif
129 }
130 
131 /**
132  * Compare two response-ip client info entries for the purpose of mesh state
133  * compare.  It returns 0 if ci_a and ci_b are considered equal; otherwise
134  * 1 or -1 (they mean 'ci_a is larger/smaller than ci_b', respectively, but
135  * in practice it should be only used to mean they are different).
136  * We cannot share the mesh state for two queries if different response-ip
137  * actions can apply in the end, even if those queries are otherwise identical.
138  * For this purpose we compare tag lists and tag action lists; they should be
139  * identical to share the same state.
140  * For tag data, we don't look into the data content, as it can be
141  * expensive; unless tag data are not defined for both or they point to the
142  * exact same data in memory (i.e., they come from the same ACL entry), we
143  * consider these data different.
144  * Likewise, if the client info is associated with views, we don't look into
145  * the views.  They are considered different unless they are exactly the same
146  * even if the views only differ in the names.
147  */
148 static int
149 client_info_compare(const struct respip_client_info* ci_a,
150 	const struct respip_client_info* ci_b)
151 {
152 	int cmp;
153 
154 	if(!ci_a && !ci_b)
155 		return 0;
156 	if(ci_a && !ci_b)
157 		return -1;
158 	if(!ci_a && ci_b)
159 		return 1;
160 	if(ci_a->taglen != ci_b->taglen)
161 		return (ci_a->taglen < ci_b->taglen) ? -1 : 1;
162 	if(ci_a->taglist && !ci_b->taglist)
163 		return -1;
164 	if(!ci_a->taglist && ci_b->taglist)
165 		return 1;
166 	if(ci_a->taglist && ci_b->taglist) {
167 		cmp = memcmp(ci_a->taglist, ci_b->taglist, ci_a->taglen);
168 		if(cmp != 0)
169 			return cmp;
170 	}
171 	if(ci_a->tag_actions_size != ci_b->tag_actions_size)
172 		return (ci_a->tag_actions_size < ci_b->tag_actions_size) ?
173 			-1 : 1;
174 	if(ci_a->tag_actions && !ci_b->tag_actions)
175 		return -1;
176 	if(!ci_a->tag_actions && ci_b->tag_actions)
177 		return 1;
178 	if(ci_a->tag_actions && ci_b->tag_actions) {
179 		cmp = memcmp(ci_a->tag_actions, ci_b->tag_actions,
180 			ci_a->tag_actions_size);
181 		if(cmp != 0)
182 			return cmp;
183 	}
184 	if(ci_a->tag_datas != ci_b->tag_datas)
185 		return ci_a->tag_datas < ci_b->tag_datas ? -1 : 1;
186 	if(ci_a->view != ci_b->view)
187 		return ci_a->view < ci_b->view ? -1 : 1;
188 	/* For the unbound daemon these should be non-NULL and identical,
189 	 * but we check that just in case. */
190 	if(ci_a->respip_set != ci_b->respip_set)
191 		return ci_a->respip_set < ci_b->respip_set ? -1 : 1;
192 	return 0;
193 }
194 
195 int
196 mesh_state_compare(const void* ap, const void* bp)
197 {
198 	struct mesh_state* a = (struct mesh_state*)ap;
199 	struct mesh_state* b = (struct mesh_state*)bp;
200 	int cmp;
201 
202 	if(a->unique < b->unique)
203 		return -1;
204 	if(a->unique > b->unique)
205 		return 1;
206 
207 	if(a->s.is_priming && !b->s.is_priming)
208 		return -1;
209 	if(!a->s.is_priming && b->s.is_priming)
210 		return 1;
211 
212 	if(a->s.is_valrec && !b->s.is_valrec)
213 		return -1;
214 	if(!a->s.is_valrec && b->s.is_valrec)
215 		return 1;
216 
217 	if((a->s.query_flags&BIT_RD) && !(b->s.query_flags&BIT_RD))
218 		return -1;
219 	if(!(a->s.query_flags&BIT_RD) && (b->s.query_flags&BIT_RD))
220 		return 1;
221 
222 	if((a->s.query_flags&BIT_CD) && !(b->s.query_flags&BIT_CD))
223 		return -1;
224 	if(!(a->s.query_flags&BIT_CD) && (b->s.query_flags&BIT_CD))
225 		return 1;
226 
227 	cmp = query_info_compare(&a->s.qinfo, &b->s.qinfo);
228 	if(cmp != 0)
229 		return cmp;
230 	return client_info_compare(a->s.client_info, b->s.client_info);
231 }
232 
233 int
234 mesh_state_ref_compare(const void* ap, const void* bp)
235 {
236 	struct mesh_state_ref* a = (struct mesh_state_ref*)ap;
237 	struct mesh_state_ref* b = (struct mesh_state_ref*)bp;
238 	return mesh_state_compare(a->s, b->s);
239 }
240 
241 struct mesh_area*
242 mesh_create(struct module_stack* stack, struct module_env* env)
243 {
244 	struct mesh_area* mesh = calloc(1, sizeof(struct mesh_area));
245 	if(!mesh) {
246 		log_err("mesh area alloc: out of memory");
247 		return NULL;
248 	}
249 	mesh->histogram = timehist_setup();
250 	mesh->qbuf_bak = sldns_buffer_new(env->cfg->msg_buffer_size);
251 	if(!mesh->histogram || !mesh->qbuf_bak) {
252 		free(mesh);
253 		log_err("mesh area alloc: out of memory");
254 		return NULL;
255 	}
256 	mesh->mods = *stack;
257 	mesh->env = env;
258 	rbtree_init(&mesh->run, &mesh_state_compare);
259 	rbtree_init(&mesh->all, &mesh_state_compare);
260 	mesh->num_reply_addrs = 0;
261 	mesh->num_reply_states = 0;
262 	mesh->num_detached_states = 0;
263 	mesh->num_forever_states = 0;
264 	mesh->stats_jostled = 0;
265 	mesh->stats_dropped = 0;
266 	mesh->ans_expired = 0;
267 	mesh->max_reply_states = env->cfg->num_queries_per_thread;
268 	mesh->max_forever_states = (mesh->max_reply_states+1)/2;
269 #ifndef S_SPLINT_S
270 	mesh->jostle_max.tv_sec = (time_t)(env->cfg->jostle_time / 1000);
271 	mesh->jostle_max.tv_usec = (time_t)((env->cfg->jostle_time % 1000)
272 		*1000);
273 #endif
274 	return mesh;
275 }
276 
277 /** help mesh delete delete mesh states */
278 static void
279 mesh_delete_helper(rbnode_type* n)
280 {
281 	struct mesh_state* mstate = (struct mesh_state*)n->key;
282 	/* perform a full delete, not only 'cleanup' routine,
283 	 * because other callbacks expect a clean state in the mesh.
284 	 * For 're-entrant' calls */
285 	mesh_state_delete(&mstate->s);
286 	/* but because these delete the items from the tree, postorder
287 	 * traversal and rbtree rebalancing do not work together */
288 }
289 
290 void
291 mesh_delete(struct mesh_area* mesh)
292 {
293 	if(!mesh)
294 		return;
295 	/* free all query states */
296 	while(mesh->all.count)
297 		mesh_delete_helper(mesh->all.root);
298 	timehist_delete(mesh->histogram);
299 	sldns_buffer_free(mesh->qbuf_bak);
300 	free(mesh);
301 }
302 
303 void
304 mesh_delete_all(struct mesh_area* mesh)
305 {
306 	/* free all query states */
307 	while(mesh->all.count)
308 		mesh_delete_helper(mesh->all.root);
309 	mesh->stats_dropped += mesh->num_reply_addrs;
310 	/* clear mesh area references */
311 	rbtree_init(&mesh->run, &mesh_state_compare);
312 	rbtree_init(&mesh->all, &mesh_state_compare);
313 	mesh->num_reply_addrs = 0;
314 	mesh->num_reply_states = 0;
315 	mesh->num_detached_states = 0;
316 	mesh->num_forever_states = 0;
317 	mesh->forever_first = NULL;
318 	mesh->forever_last = NULL;
319 	mesh->jostle_first = NULL;
320 	mesh->jostle_last = NULL;
321 }
322 
323 int mesh_make_new_space(struct mesh_area* mesh, sldns_buffer* qbuf)
324 {
325 	struct mesh_state* m = mesh->jostle_first;
326 	/* free space is available */
327 	if(mesh->num_reply_states < mesh->max_reply_states)
328 		return 1;
329 	/* try to kick out a jostle-list item */
330 	if(m && m->reply_list && m->list_select == mesh_jostle_list) {
331 		/* how old is it? */
332 		struct timeval age;
333 		timeval_subtract(&age, mesh->env->now_tv,
334 			&m->reply_list->start_time);
335 		if(timeval_smaller(&mesh->jostle_max, &age)) {
336 			/* its a goner */
337 			log_nametypeclass(VERB_ALGO, "query jostled out to "
338 				"make space for a new one",
339 				m->s.qinfo.qname, m->s.qinfo.qtype,
340 				m->s.qinfo.qclass);
341 			/* backup the query */
342 			if(qbuf) sldns_buffer_copy(mesh->qbuf_bak, qbuf);
343 			/* notify supers */
344 			if(m->super_set.count > 0) {
345 				verbose(VERB_ALGO, "notify supers of failure");
346 				m->s.return_msg = NULL;
347 				m->s.return_rcode = LDNS_RCODE_SERVFAIL;
348 				mesh_walk_supers(mesh, m);
349 			}
350 			mesh->stats_jostled ++;
351 			mesh_state_delete(&m->s);
352 			/* restore the query - note that the qinfo ptr to
353 			 * the querybuffer is then correct again. */
354 			if(qbuf) sldns_buffer_copy(qbuf, mesh->qbuf_bak);
355 			return 1;
356 		}
357 	}
358 	/* no space for new item */
359 	return 0;
360 }
361 
362 struct dns_msg*
363 mesh_serve_expired_lookup(struct module_qstate* qstate,
364 	struct query_info* lookup_qinfo)
365 {
366 	hashvalue_type h;
367 	struct lruhash_entry* e;
368 	struct dns_msg* msg;
369 	struct reply_info* data;
370 	struct msgreply_entry* key;
371 	time_t timenow = *qstate->env->now;
372 	int must_validate = (!(qstate->query_flags&BIT_CD)
373 		|| qstate->env->cfg->ignore_cd) && qstate->env->need_to_validate;
374 	/* Lookup cache */
375 	h = query_info_hash(lookup_qinfo, qstate->query_flags);
376 	e = slabhash_lookup(qstate->env->msg_cache, h, lookup_qinfo, 0);
377 	if(!e) return NULL;
378 
379 	key = (struct msgreply_entry*)e->key;
380 	data = (struct reply_info*)e->data;
381 	msg = tomsg(qstate->env, &key->key, data, qstate->region, timenow,
382 		qstate->env->cfg->serve_expired, qstate->env->scratch);
383 	if(!msg)
384 		goto bail_out;
385 
386 	/* Check CNAME chain (if any)
387 	 * This is part of tomsg above; no need to check now. */
388 
389 	/* Check security status of the cached answer.
390 	 * tomsg above has a subset of these checks, so we are leaving
391 	 * these as is.
392 	 * In case of bogus or revalidation we don't care to reply here. */
393 	if(must_validate && (msg->rep->security == sec_status_bogus ||
394 		msg->rep->security == sec_status_secure_sentinel_fail)) {
395 		verbose(VERB_ALGO, "Serve expired: bogus answer found in cache");
396 		goto bail_out;
397 	} else if(msg->rep->security == sec_status_unchecked && must_validate) {
398 		verbose(VERB_ALGO, "Serve expired: unchecked entry needs "
399 			"validation");
400 		goto bail_out; /* need to validate cache entry first */
401 	} else if(msg->rep->security == sec_status_secure &&
402 		!reply_all_rrsets_secure(msg->rep) && must_validate) {
403 			verbose(VERB_ALGO, "Serve expired: secure entry"
404 				" changed status");
405 			goto bail_out; /* rrset changed, re-verify */
406 	}
407 
408 	lock_rw_unlock(&e->lock);
409 	return msg;
410 
411 bail_out:
412 	lock_rw_unlock(&e->lock);
413 	return NULL;
414 }
415 
416 
417 /** Init the serve expired data structure */
418 static int
419 mesh_serve_expired_init(struct mesh_state* mstate, int timeout)
420 {
421 	struct timeval t;
422 
423 	/* Create serve_expired_data if not there yet */
424 	if(!mstate->s.serve_expired_data) {
425 		mstate->s.serve_expired_data = (struct serve_expired_data*)
426 			regional_alloc_zero(
427 				mstate->s.region, sizeof(struct serve_expired_data));
428 		if(!mstate->s.serve_expired_data)
429 			return 0;
430 	}
431 
432 	/* Don't overwrite the function if already set */
433 	mstate->s.serve_expired_data->get_cached_answer =
434 		mstate->s.serve_expired_data->get_cached_answer?
435 		mstate->s.serve_expired_data->get_cached_answer:
436 		mesh_serve_expired_lookup;
437 
438 	/* In case this timer already popped, start it again */
439 	if(!mstate->s.serve_expired_data->timer) {
440 		mstate->s.serve_expired_data->timer = comm_timer_create(
441 			mstate->s.env->worker_base, mesh_serve_expired_callback, mstate);
442 		if(!mstate->s.serve_expired_data->timer)
443 			return 0;
444 #ifndef S_SPLINT_S
445 		t.tv_sec = timeout/1000;
446 		t.tv_usec = (timeout%1000)*1000;
447 #endif
448 		comm_timer_set(mstate->s.serve_expired_data->timer, &t);
449 	}
450 	return 1;
451 }
452 
453 void mesh_new_client(struct mesh_area* mesh, struct query_info* qinfo,
454 	struct respip_client_info* cinfo, uint16_t qflags,
455 	struct edns_data* edns, struct comm_reply* rep, uint16_t qid)
456 {
457 	struct mesh_state* s = NULL;
458 	int unique = unique_mesh_state(edns->opt_list, mesh->env);
459 	int was_detached = 0;
460 	int was_noreply = 0;
461 	int added = 0;
462 	int timeout = mesh->env->cfg->serve_expired?
463 		mesh->env->cfg->serve_expired_client_timeout:0;
464 	struct sldns_buffer* r_buffer = rep->c->buffer;
465 	if(rep->c->tcp_req_info) {
466 		r_buffer = rep->c->tcp_req_info->spool_buffer;
467 	}
468 	if(!unique)
469 		s = mesh_area_find(mesh, cinfo, qinfo, qflags&(BIT_RD|BIT_CD), 0, 0);
470 	/* does this create a new reply state? */
471 	if(!s || s->list_select == mesh_no_list) {
472 		if(!mesh_make_new_space(mesh, rep->c->buffer)) {
473 			verbose(VERB_ALGO, "Too many queries. dropping "
474 				"incoming query.");
475 			comm_point_drop_reply(rep);
476 			mesh->stats_dropped++;
477 			return;
478 		}
479 		/* for this new reply state, the reply address is free,
480 		 * so the limit of reply addresses does not stop reply states*/
481 	} else {
482 		/* protect our memory usage from storing reply addresses */
483 		if(mesh->num_reply_addrs > mesh->max_reply_states*16) {
484 			verbose(VERB_ALGO, "Too many requests queued. "
485 				"dropping incoming query.");
486 			comm_point_drop_reply(rep);
487 			mesh->stats_dropped++;
488 			return;
489 		}
490 	}
491 	/* see if it already exists, if not, create one */
492 	if(!s) {
493 #ifdef UNBOUND_DEBUG
494 		struct rbnode_type* n;
495 #endif
496 		s = mesh_state_create(mesh->env, qinfo, cinfo,
497 			qflags&(BIT_RD|BIT_CD), 0, 0);
498 		if(!s) {
499 			log_err("mesh_state_create: out of memory; SERVFAIL");
500 			if(!inplace_cb_reply_servfail_call(mesh->env, qinfo, NULL, NULL,
501 				LDNS_RCODE_SERVFAIL, edns, rep, mesh->env->scratch))
502 					edns->opt_list = NULL;
503 			error_encode(r_buffer, LDNS_RCODE_SERVFAIL,
504 				qinfo, qid, qflags, edns);
505 			comm_point_send_reply(rep);
506 			return;
507 		}
508 		if(unique)
509 			mesh_state_make_unique(s);
510 		/* copy the edns options we got from the front */
511 		if(edns->opt_list) {
512 			s->s.edns_opts_front_in = edns_opt_copy_region(edns->opt_list,
513 				s->s.region);
514 			if(!s->s.edns_opts_front_in) {
515 				log_err("mesh_state_create: out of memory; SERVFAIL");
516 				if(!inplace_cb_reply_servfail_call(mesh->env, qinfo, NULL,
517 					NULL, LDNS_RCODE_SERVFAIL, edns, rep, mesh->env->scratch))
518 						edns->opt_list = NULL;
519 				error_encode(r_buffer, LDNS_RCODE_SERVFAIL,
520 					qinfo, qid, qflags, edns);
521 				comm_point_send_reply(rep);
522 				return;
523 			}
524 		}
525 
526 #ifdef UNBOUND_DEBUG
527 		n =
528 #else
529 		(void)
530 #endif
531 		rbtree_insert(&mesh->all, &s->node);
532 		log_assert(n != NULL);
533 		/* set detached (it is now) */
534 		mesh->num_detached_states++;
535 		added = 1;
536 	}
537 	if(!s->reply_list && !s->cb_list) {
538 		was_noreply = 1;
539 		if(s->super_set.count == 0) {
540 			was_detached = 1;
541 		}
542 	}
543 	/* add reply to s */
544 	if(!mesh_state_add_reply(s, edns, rep, qid, qflags, qinfo)) {
545 		log_err("mesh_new_client: out of memory; SERVFAIL");
546 		goto servfail_mem;
547 	}
548 	if(rep->c->tcp_req_info) {
549 		if(!tcp_req_info_add_meshstate(rep->c->tcp_req_info, mesh, s)) {
550 			log_err("mesh_new_client: out of memory add tcpreqinfo");
551 			goto servfail_mem;
552 		}
553 	}
554 	/* add serve expired timer if required and not already there */
555 	if(timeout && !mesh_serve_expired_init(s, timeout)) {
556 		log_err("mesh_new_client: out of memory initializing serve expired");
557 		goto servfail_mem;
558 	}
559 	/* update statistics */
560 	if(was_detached) {
561 		log_assert(mesh->num_detached_states > 0);
562 		mesh->num_detached_states--;
563 	}
564 	if(was_noreply) {
565 		mesh->num_reply_states ++;
566 	}
567 	mesh->num_reply_addrs++;
568 	if(s->list_select == mesh_no_list) {
569 		/* move to either the forever or the jostle_list */
570 		if(mesh->num_forever_states < mesh->max_forever_states) {
571 			mesh->num_forever_states ++;
572 			mesh_list_insert(s, &mesh->forever_first,
573 				&mesh->forever_last);
574 			s->list_select = mesh_forever_list;
575 		} else {
576 			mesh_list_insert(s, &mesh->jostle_first,
577 				&mesh->jostle_last);
578 			s->list_select = mesh_jostle_list;
579 		}
580 	}
581 	if(added)
582 		mesh_run(mesh, s, module_event_new, NULL);
583 	return;
584 
585 servfail_mem:
586 	if(!inplace_cb_reply_servfail_call(mesh->env, qinfo, &s->s,
587 		NULL, LDNS_RCODE_SERVFAIL, edns, rep, mesh->env->scratch))
588 			edns->opt_list = NULL;
589 	error_encode(r_buffer, LDNS_RCODE_SERVFAIL,
590 		qinfo, qid, qflags, edns);
591 	comm_point_send_reply(rep);
592 	if(added)
593 		mesh_state_delete(&s->s);
594 	return;
595 }
596 
597 int
598 mesh_new_callback(struct mesh_area* mesh, struct query_info* qinfo,
599 	uint16_t qflags, struct edns_data* edns, sldns_buffer* buf,
600 	uint16_t qid, mesh_cb_func_type cb, void* cb_arg)
601 {
602 	struct mesh_state* s = NULL;
603 	int unique = unique_mesh_state(edns->opt_list, mesh->env);
604 	int timeout = mesh->env->cfg->serve_expired?
605 		mesh->env->cfg->serve_expired_client_timeout:0;
606 	int was_detached = 0;
607 	int was_noreply = 0;
608 	int added = 0;
609 	if(!unique)
610 		s = mesh_area_find(mesh, NULL, qinfo, qflags&(BIT_RD|BIT_CD), 0, 0);
611 
612 	/* there are no limits on the number of callbacks */
613 
614 	/* see if it already exists, if not, create one */
615 	if(!s) {
616 #ifdef UNBOUND_DEBUG
617 		struct rbnode_type* n;
618 #endif
619 		s = mesh_state_create(mesh->env, qinfo, NULL,
620 			qflags&(BIT_RD|BIT_CD), 0, 0);
621 		if(!s) {
622 			return 0;
623 		}
624 		if(unique)
625 			mesh_state_make_unique(s);
626 		if(edns->opt_list) {
627 			s->s.edns_opts_front_in = edns_opt_copy_region(edns->opt_list,
628 				s->s.region);
629 			if(!s->s.edns_opts_front_in) {
630 				return 0;
631 			}
632 		}
633 #ifdef UNBOUND_DEBUG
634 		n =
635 #else
636 		(void)
637 #endif
638 		rbtree_insert(&mesh->all, &s->node);
639 		log_assert(n != NULL);
640 		/* set detached (it is now) */
641 		mesh->num_detached_states++;
642 		added = 1;
643 	}
644 	if(!s->reply_list && !s->cb_list) {
645 		was_noreply = 1;
646 		if(s->super_set.count == 0) {
647 			was_detached = 1;
648 		}
649 	}
650 	/* add reply to s */
651 	if(!mesh_state_add_cb(s, edns, buf, cb, cb_arg, qid, qflags)) {
652 		if(added)
653 			mesh_state_delete(&s->s);
654 		return 0;
655 	}
656 	/* add serve expired timer if not already there */
657 	if(timeout && !mesh_serve_expired_init(s, timeout)) {
658 		return 0;
659 	}
660 	/* update statistics */
661 	if(was_detached) {
662 		log_assert(mesh->num_detached_states > 0);
663 		mesh->num_detached_states--;
664 	}
665 	if(was_noreply) {
666 		mesh->num_reply_states ++;
667 	}
668 	mesh->num_reply_addrs++;
669 	if(added)
670 		mesh_run(mesh, s, module_event_new, NULL);
671 	return 1;
672 }
673 
674 /* Internal backend routine of mesh_new_prefetch().  It takes one additional
675  * parameter, 'run', which controls whether to run the prefetch state
676  * immediately.  When this function is called internally 'run' could be
677  * 0 (false), in which case the new state is only made runnable so it
678  * will not be run recursively on top of the current state. */
679 static void mesh_schedule_prefetch(struct mesh_area* mesh,
680 	struct query_info* qinfo, uint16_t qflags, time_t leeway, int run)
681 {
682 	struct mesh_state* s = mesh_area_find(mesh, NULL, qinfo,
683 		qflags&(BIT_RD|BIT_CD), 0, 0);
684 #ifdef UNBOUND_DEBUG
685 	struct rbnode_type* n;
686 #endif
687 	/* already exists, and for a different purpose perhaps.
688 	 * if mesh_no_list, keep it that way. */
689 	if(s) {
690 		/* make it ignore the cache from now on */
691 		if(!s->s.blacklist)
692 			sock_list_insert(&s->s.blacklist, NULL, 0, s->s.region);
693 		if(s->s.prefetch_leeway < leeway)
694 			s->s.prefetch_leeway = leeway;
695 		return;
696 	}
697 	if(!mesh_make_new_space(mesh, NULL)) {
698 		verbose(VERB_ALGO, "Too many queries. dropped prefetch.");
699 		mesh->stats_dropped ++;
700 		return;
701 	}
702 
703 	s = mesh_state_create(mesh->env, qinfo, NULL,
704 		qflags&(BIT_RD|BIT_CD), 0, 0);
705 	if(!s) {
706 		log_err("prefetch mesh_state_create: out of memory");
707 		return;
708 	}
709 #ifdef UNBOUND_DEBUG
710 	n =
711 #else
712 	(void)
713 #endif
714 	rbtree_insert(&mesh->all, &s->node);
715 	log_assert(n != NULL);
716 	/* set detached (it is now) */
717 	mesh->num_detached_states++;
718 	/* make it ignore the cache */
719 	sock_list_insert(&s->s.blacklist, NULL, 0, s->s.region);
720 	s->s.prefetch_leeway = leeway;
721 
722 	if(s->list_select == mesh_no_list) {
723 		/* move to either the forever or the jostle_list */
724 		if(mesh->num_forever_states < mesh->max_forever_states) {
725 			mesh->num_forever_states ++;
726 			mesh_list_insert(s, &mesh->forever_first,
727 				&mesh->forever_last);
728 			s->list_select = mesh_forever_list;
729 		} else {
730 			mesh_list_insert(s, &mesh->jostle_first,
731 				&mesh->jostle_last);
732 			s->list_select = mesh_jostle_list;
733 		}
734 	}
735 
736 	if(!run) {
737 #ifdef UNBOUND_DEBUG
738 		n =
739 #else
740 		(void)
741 #endif
742 		rbtree_insert(&mesh->run, &s->run_node);
743 		log_assert(n != NULL);
744 		return;
745 	}
746 
747 	mesh_run(mesh, s, module_event_new, NULL);
748 }
749 
750 void mesh_new_prefetch(struct mesh_area* mesh, struct query_info* qinfo,
751         uint16_t qflags, time_t leeway)
752 {
753 	mesh_schedule_prefetch(mesh, qinfo, qflags, leeway, 1);
754 }
755 
756 void mesh_report_reply(struct mesh_area* mesh, struct outbound_entry* e,
757         struct comm_reply* reply, int what)
758 {
759 	enum module_ev event = module_event_reply;
760 	e->qstate->reply = reply;
761 	if(what != NETEVENT_NOERROR) {
762 		event = module_event_noreply;
763 		if(what == NETEVENT_CAPSFAIL)
764 			event = module_event_capsfail;
765 	}
766 	mesh_run(mesh, e->qstate->mesh_info, event, e);
767 }
768 
769 struct mesh_state*
770 mesh_state_create(struct module_env* env, struct query_info* qinfo,
771 	struct respip_client_info* cinfo, uint16_t qflags, int prime,
772 	int valrec)
773 {
774 	struct regional* region = alloc_reg_obtain(env->alloc);
775 	struct mesh_state* mstate;
776 	int i;
777 	if(!region)
778 		return NULL;
779 	mstate = (struct mesh_state*)regional_alloc(region,
780 		sizeof(struct mesh_state));
781 	if(!mstate) {
782 		alloc_reg_release(env->alloc, region);
783 		return NULL;
784 	}
785 	memset(mstate, 0, sizeof(*mstate));
786 	mstate->node = *RBTREE_NULL;
787 	mstate->run_node = *RBTREE_NULL;
788 	mstate->node.key = mstate;
789 	mstate->run_node.key = mstate;
790 	mstate->reply_list = NULL;
791 	mstate->list_select = mesh_no_list;
792 	mstate->replies_sent = 0;
793 	rbtree_init(&mstate->super_set, &mesh_state_ref_compare);
794 	rbtree_init(&mstate->sub_set, &mesh_state_ref_compare);
795 	mstate->num_activated = 0;
796 	mstate->unique = NULL;
797 	/* init module qstate */
798 	mstate->s.qinfo.qtype = qinfo->qtype;
799 	mstate->s.qinfo.qclass = qinfo->qclass;
800 	mstate->s.qinfo.local_alias = NULL;
801 	mstate->s.qinfo.qname_len = qinfo->qname_len;
802 	mstate->s.qinfo.qname = regional_alloc_init(region, qinfo->qname,
803 		qinfo->qname_len);
804 	if(!mstate->s.qinfo.qname) {
805 		alloc_reg_release(env->alloc, region);
806 		return NULL;
807 	}
808 	if(cinfo) {
809 		mstate->s.client_info = regional_alloc_init(region, cinfo,
810 			sizeof(*cinfo));
811 		if(!mstate->s.client_info) {
812 			alloc_reg_release(env->alloc, region);
813 			return NULL;
814 		}
815 	}
816 	/* remove all weird bits from qflags */
817 	mstate->s.query_flags = (qflags & (BIT_RD|BIT_CD));
818 	mstate->s.is_priming = prime;
819 	mstate->s.is_valrec = valrec;
820 	mstate->s.reply = NULL;
821 	mstate->s.region = region;
822 	mstate->s.curmod = 0;
823 	mstate->s.return_msg = 0;
824 	mstate->s.return_rcode = LDNS_RCODE_NOERROR;
825 	mstate->s.env = env;
826 	mstate->s.mesh_info = mstate;
827 	mstate->s.prefetch_leeway = 0;
828 	mstate->s.serve_expired_data = NULL;
829 	mstate->s.no_cache_lookup = 0;
830 	mstate->s.no_cache_store = 0;
831 	mstate->s.need_refetch = 0;
832 	mstate->s.was_ratelimited = 0;
833 
834 	/* init modules */
835 	for(i=0; i<env->mesh->mods.num; i++) {
836 		mstate->s.minfo[i] = NULL;
837 		mstate->s.ext_state[i] = module_state_initial;
838 	}
839 	/* init edns option lists */
840 	mstate->s.edns_opts_front_in = NULL;
841 	mstate->s.edns_opts_back_out = NULL;
842 	mstate->s.edns_opts_back_in = NULL;
843 	mstate->s.edns_opts_front_out = NULL;
844 
845 	return mstate;
846 }
847 
848 int
849 mesh_state_is_unique(struct mesh_state* mstate)
850 {
851 	return mstate->unique != NULL;
852 }
853 
854 void
855 mesh_state_make_unique(struct mesh_state* mstate)
856 {
857 	mstate->unique = mstate;
858 }
859 
860 void
861 mesh_state_cleanup(struct mesh_state* mstate)
862 {
863 	struct mesh_area* mesh;
864 	int i;
865 	if(!mstate)
866 		return;
867 	mesh = mstate->s.env->mesh;
868 	/* Stop and delete the serve expired timer */
869 	if(mstate->s.serve_expired_data && mstate->s.serve_expired_data->timer) {
870 		comm_timer_delete(mstate->s.serve_expired_data->timer);
871 		mstate->s.serve_expired_data->timer = NULL;
872 	}
873 	/* drop unsent replies */
874 	if(!mstate->replies_sent) {
875 		struct mesh_reply* rep = mstate->reply_list;
876 		struct mesh_cb* cb;
877 		/* in tcp_req_info, the mstates linked are removed, but
878 		 * the reply_list is now NULL, so the remove-from-empty-list
879 		 * takes no time and also it does not do the mesh accounting */
880 		mstate->reply_list = NULL;
881 		for(; rep; rep=rep->next) {
882 			comm_point_drop_reply(&rep->query_reply);
883 			log_assert(mesh->num_reply_addrs > 0);
884 			mesh->num_reply_addrs--;
885 		}
886 		while((cb = mstate->cb_list)!=NULL) {
887 			mstate->cb_list = cb->next;
888 			fptr_ok(fptr_whitelist_mesh_cb(cb->cb));
889 			(*cb->cb)(cb->cb_arg, LDNS_RCODE_SERVFAIL, NULL,
890 				sec_status_unchecked, NULL, 0);
891 			log_assert(mesh->num_reply_addrs > 0);
892 			mesh->num_reply_addrs--;
893 		}
894 	}
895 
896 	/* de-init modules */
897 	for(i=0; i<mesh->mods.num; i++) {
898 		fptr_ok(fptr_whitelist_mod_clear(mesh->mods.mod[i]->clear));
899 		(*mesh->mods.mod[i]->clear)(&mstate->s, i);
900 		mstate->s.minfo[i] = NULL;
901 		mstate->s.ext_state[i] = module_finished;
902 	}
903 	alloc_reg_release(mstate->s.env->alloc, mstate->s.region);
904 }
905 
906 void
907 mesh_state_delete(struct module_qstate* qstate)
908 {
909 	struct mesh_area* mesh;
910 	struct mesh_state_ref* super, ref;
911 	struct mesh_state* mstate;
912 	if(!qstate)
913 		return;
914 	mstate = qstate->mesh_info;
915 	mesh = mstate->s.env->mesh;
916 	mesh_detach_subs(&mstate->s);
917 	if(mstate->list_select == mesh_forever_list) {
918 		mesh->num_forever_states --;
919 		mesh_list_remove(mstate, &mesh->forever_first,
920 			&mesh->forever_last);
921 	} else if(mstate->list_select == mesh_jostle_list) {
922 		mesh_list_remove(mstate, &mesh->jostle_first,
923 			&mesh->jostle_last);
924 	}
925 	if(!mstate->reply_list && !mstate->cb_list
926 		&& mstate->super_set.count == 0) {
927 		log_assert(mesh->num_detached_states > 0);
928 		mesh->num_detached_states--;
929 	}
930 	if(mstate->reply_list || mstate->cb_list) {
931 		log_assert(mesh->num_reply_states > 0);
932 		mesh->num_reply_states--;
933 	}
934 	ref.node.key = &ref;
935 	ref.s = mstate;
936 	RBTREE_FOR(super, struct mesh_state_ref*, &mstate->super_set) {
937 		(void)rbtree_delete(&super->s->sub_set, &ref);
938 	}
939 	(void)rbtree_delete(&mesh->run, mstate);
940 	(void)rbtree_delete(&mesh->all, mstate);
941 	mesh_state_cleanup(mstate);
942 }
943 
944 /** helper recursive rbtree find routine */
945 static int
946 find_in_subsub(struct mesh_state* m, struct mesh_state* tofind, size_t *c)
947 {
948 	struct mesh_state_ref* r;
949 	if((*c)++ > MESH_MAX_SUBSUB)
950 		return 1;
951 	RBTREE_FOR(r, struct mesh_state_ref*, &m->sub_set) {
952 		if(r->s == tofind || find_in_subsub(r->s, tofind, c))
953 			return 1;
954 	}
955 	return 0;
956 }
957 
958 /** find cycle for already looked up mesh_state */
959 static int
960 mesh_detect_cycle_found(struct module_qstate* qstate, struct mesh_state* dep_m)
961 {
962 	struct mesh_state* cyc_m = qstate->mesh_info;
963 	size_t counter = 0;
964 	if(!dep_m)
965 		return 0;
966 	if(dep_m == cyc_m || find_in_subsub(dep_m, cyc_m, &counter)) {
967 		if(counter > MESH_MAX_SUBSUB)
968 			return 2;
969 		return 1;
970 	}
971 	return 0;
972 }
973 
974 void mesh_detach_subs(struct module_qstate* qstate)
975 {
976 	struct mesh_area* mesh = qstate->env->mesh;
977 	struct mesh_state_ref* ref, lookup;
978 #ifdef UNBOUND_DEBUG
979 	struct rbnode_type* n;
980 #endif
981 	lookup.node.key = &lookup;
982 	lookup.s = qstate->mesh_info;
983 	RBTREE_FOR(ref, struct mesh_state_ref*, &qstate->mesh_info->sub_set) {
984 #ifdef UNBOUND_DEBUG
985 		n =
986 #else
987 		(void)
988 #endif
989 		rbtree_delete(&ref->s->super_set, &lookup);
990 		log_assert(n != NULL); /* must have been present */
991 		if(!ref->s->reply_list && !ref->s->cb_list
992 			&& ref->s->super_set.count == 0) {
993 			mesh->num_detached_states++;
994 			log_assert(mesh->num_detached_states +
995 				mesh->num_reply_states <= mesh->all.count);
996 		}
997 	}
998 	rbtree_init(&qstate->mesh_info->sub_set, &mesh_state_ref_compare);
999 }
1000 
1001 int mesh_add_sub(struct module_qstate* qstate, struct query_info* qinfo,
1002         uint16_t qflags, int prime, int valrec, struct module_qstate** newq,
1003 	struct mesh_state** sub)
1004 {
1005 	/* find it, if not, create it */
1006 	struct mesh_area* mesh = qstate->env->mesh;
1007 	*sub = mesh_area_find(mesh, NULL, qinfo, qflags,
1008 		prime, valrec);
1009 	if(mesh_detect_cycle_found(qstate, *sub)) {
1010 		verbose(VERB_ALGO, "attach failed, cycle detected");
1011 		return 0;
1012 	}
1013 	if(!*sub) {
1014 #ifdef UNBOUND_DEBUG
1015 		struct rbnode_type* n;
1016 #endif
1017 		/* create a new one */
1018 		*sub = mesh_state_create(qstate->env, qinfo, NULL, qflags, prime,
1019 			valrec);
1020 		if(!*sub) {
1021 			log_err("mesh_attach_sub: out of memory");
1022 			return 0;
1023 		}
1024 #ifdef UNBOUND_DEBUG
1025 		n =
1026 #else
1027 		(void)
1028 #endif
1029 		rbtree_insert(&mesh->all, &(*sub)->node);
1030 		log_assert(n != NULL);
1031 		/* set detached (it is now) */
1032 		mesh->num_detached_states++;
1033 		/* set new query state to run */
1034 #ifdef UNBOUND_DEBUG
1035 		n =
1036 #else
1037 		(void)
1038 #endif
1039 		rbtree_insert(&mesh->run, &(*sub)->run_node);
1040 		log_assert(n != NULL);
1041 		*newq = &(*sub)->s;
1042 	} else
1043 		*newq = NULL;
1044 	return 1;
1045 }
1046 
1047 int mesh_attach_sub(struct module_qstate* qstate, struct query_info* qinfo,
1048         uint16_t qflags, int prime, int valrec, struct module_qstate** newq)
1049 {
1050 	struct mesh_area* mesh = qstate->env->mesh;
1051 	struct mesh_state* sub = NULL;
1052 	int was_detached;
1053 	if(!mesh_add_sub(qstate, qinfo, qflags, prime, valrec, newq, &sub))
1054 		return 0;
1055 	was_detached = (sub->super_set.count == 0);
1056 	if(!mesh_state_attachment(qstate->mesh_info, sub))
1057 		return 0;
1058 	/* if it was a duplicate  attachment, the count was not zero before */
1059 	if(!sub->reply_list && !sub->cb_list && was_detached &&
1060 		sub->super_set.count == 1) {
1061 		/* it used to be detached, before this one got added */
1062 		log_assert(mesh->num_detached_states > 0);
1063 		mesh->num_detached_states--;
1064 	}
1065 	/* *newq will be run when inited after the current module stops */
1066 	return 1;
1067 }
1068 
1069 int mesh_state_attachment(struct mesh_state* super, struct mesh_state* sub)
1070 {
1071 #ifdef UNBOUND_DEBUG
1072 	struct rbnode_type* n;
1073 #endif
1074 	struct mesh_state_ref* subref; /* points to sub, inserted in super */
1075 	struct mesh_state_ref* superref; /* points to super, inserted in sub */
1076 	if( !(subref = regional_alloc(super->s.region,
1077 		sizeof(struct mesh_state_ref))) ||
1078 		!(superref = regional_alloc(sub->s.region,
1079 		sizeof(struct mesh_state_ref))) ) {
1080 		log_err("mesh_state_attachment: out of memory");
1081 		return 0;
1082 	}
1083 	superref->node.key = superref;
1084 	superref->s = super;
1085 	subref->node.key = subref;
1086 	subref->s = sub;
1087 	if(!rbtree_insert(&sub->super_set, &superref->node)) {
1088 		/* this should not happen, iterator and validator do not
1089 		 * attach subqueries that are identical. */
1090 		/* already attached, we are done, nothing todo.
1091 		 * since superref and subref already allocated in region,
1092 		 * we cannot free them */
1093 		return 1;
1094 	}
1095 #ifdef UNBOUND_DEBUG
1096 	n =
1097 #else
1098 	(void)
1099 #endif
1100 	rbtree_insert(&super->sub_set, &subref->node);
1101 	log_assert(n != NULL); /* we checked above if statement, the reverse
1102 	  administration should not fail now, unless they are out of sync */
1103 	return 1;
1104 }
1105 
1106 /**
1107  * callback results to mesh cb entry
1108  * @param m: mesh state to send it for.
1109  * @param rcode: if not 0, error code.
1110  * @param rep: reply to send (or NULL if rcode is set).
1111  * @param r: callback entry
1112  */
1113 static void
1114 mesh_do_callback(struct mesh_state* m, int rcode, struct reply_info* rep,
1115 	struct mesh_cb* r)
1116 {
1117 	int secure;
1118 	char* reason = NULL;
1119 	int was_ratelimited = m->s.was_ratelimited;
1120 	/* bogus messages are not made into servfail, sec_status passed
1121 	 * to the callback function */
1122 	if(rep && rep->security == sec_status_secure)
1123 		secure = 1;
1124 	else	secure = 0;
1125 	if(!rep && rcode == LDNS_RCODE_NOERROR)
1126 		rcode = LDNS_RCODE_SERVFAIL;
1127 	if(!rcode && (rep->security == sec_status_bogus ||
1128 		rep->security == sec_status_secure_sentinel_fail)) {
1129 		if(!(reason = errinf_to_str_bogus(&m->s)))
1130 			rcode = LDNS_RCODE_SERVFAIL;
1131 	}
1132 	/* send the reply */
1133 	if(rcode) {
1134 		if(rcode == LDNS_RCODE_SERVFAIL) {
1135 			if(!inplace_cb_reply_servfail_call(m->s.env, &m->s.qinfo, &m->s,
1136 				rep, rcode, &r->edns, NULL, m->s.region))
1137 					r->edns.opt_list = NULL;
1138 		} else {
1139 			if(!inplace_cb_reply_call(m->s.env, &m->s.qinfo, &m->s, rep, rcode,
1140 				&r->edns, NULL, m->s.region))
1141 					r->edns.opt_list = NULL;
1142 		}
1143 		fptr_ok(fptr_whitelist_mesh_cb(r->cb));
1144 		(*r->cb)(r->cb_arg, rcode, r->buf, sec_status_unchecked, NULL,
1145 			was_ratelimited);
1146 	} else {
1147 		size_t udp_size = r->edns.udp_size;
1148 		sldns_buffer_clear(r->buf);
1149 		r->edns.edns_version = EDNS_ADVERTISED_VERSION;
1150 		r->edns.udp_size = EDNS_ADVERTISED_SIZE;
1151 		r->edns.ext_rcode = 0;
1152 		r->edns.bits &= EDNS_DO;
1153 
1154 		if(!inplace_cb_reply_call(m->s.env, &m->s.qinfo, &m->s, rep,
1155 			LDNS_RCODE_NOERROR, &r->edns, NULL, m->s.region) ||
1156 			!reply_info_answer_encode(&m->s.qinfo, rep, r->qid,
1157 			r->qflags, r->buf, 0, 1,
1158 			m->s.env->scratch, udp_size, &r->edns,
1159 			(int)(r->edns.bits & EDNS_DO), secure))
1160 		{
1161 			fptr_ok(fptr_whitelist_mesh_cb(r->cb));
1162 			(*r->cb)(r->cb_arg, LDNS_RCODE_SERVFAIL, r->buf,
1163 				sec_status_unchecked, NULL, 0);
1164 		} else {
1165 			fptr_ok(fptr_whitelist_mesh_cb(r->cb));
1166 			(*r->cb)(r->cb_arg, LDNS_RCODE_NOERROR, r->buf,
1167 				rep->security, reason, was_ratelimited);
1168 		}
1169 	}
1170 	free(reason);
1171 	log_assert(m->s.env->mesh->num_reply_addrs > 0);
1172 	m->s.env->mesh->num_reply_addrs--;
1173 }
1174 
1175 /**
1176  * Send reply to mesh reply entry
1177  * @param m: mesh state to send it for.
1178  * @param rcode: if not 0, error code.
1179  * @param rep: reply to send (or NULL if rcode is set).
1180  * @param r: reply entry
1181  * @param r_buffer: buffer to use for reply entry.
1182  * @param prev: previous reply, already has its answer encoded in buffer.
1183  * @param prev_buffer: buffer for previous reply.
1184  */
1185 static void
1186 mesh_send_reply(struct mesh_state* m, int rcode, struct reply_info* rep,
1187 	struct mesh_reply* r, struct sldns_buffer* r_buffer,
1188 	struct mesh_reply* prev, struct sldns_buffer* prev_buffer)
1189 {
1190 	struct timeval end_time;
1191 	struct timeval duration;
1192 	int secure;
1193 	/* Copy the client's EDNS for later restore, to make sure the edns
1194 	 * compare is with the correct edns options. */
1195 	struct edns_data edns_bak = r->edns;
1196 	/* examine security status */
1197 	if(m->s.env->need_to_validate && (!(r->qflags&BIT_CD) ||
1198 		m->s.env->cfg->ignore_cd) && rep &&
1199 		(rep->security <= sec_status_bogus ||
1200 		rep->security == sec_status_secure_sentinel_fail)) {
1201 		rcode = LDNS_RCODE_SERVFAIL;
1202 		if(m->s.env->cfg->stat_extended)
1203 			m->s.env->mesh->ans_bogus++;
1204 	}
1205 	if(rep && rep->security == sec_status_secure)
1206 		secure = 1;
1207 	else	secure = 0;
1208 	if(!rep && rcode == LDNS_RCODE_NOERROR)
1209 		rcode = LDNS_RCODE_SERVFAIL;
1210 	/* send the reply */
1211 	/* We don't reuse the encoded answer if either the previous or current
1212 	 * response has a local alias.  We could compare the alias records
1213 	 * and still reuse the previous answer if they are the same, but that
1214 	 * would be complicated and error prone for the relatively minor case.
1215 	 * So we err on the side of safety. */
1216 	if(prev && prev_buffer && prev->qflags == r->qflags &&
1217 		!prev->local_alias && !r->local_alias &&
1218 		prev->edns.edns_present == r->edns.edns_present &&
1219 		prev->edns.bits == r->edns.bits &&
1220 		prev->edns.udp_size == r->edns.udp_size &&
1221 		edns_opt_list_compare(prev->edns.opt_list, r->edns.opt_list)
1222 		== 0) {
1223 		/* if the previous reply is identical to this one, fix ID */
1224 		if(prev_buffer != r_buffer)
1225 			sldns_buffer_copy(r_buffer, prev_buffer);
1226 		sldns_buffer_write_at(r_buffer, 0, &r->qid, sizeof(uint16_t));
1227 		sldns_buffer_write_at(r_buffer, 12, r->qname,
1228 			m->s.qinfo.qname_len);
1229 		comm_point_send_reply(&r->query_reply);
1230 	} else if(rcode) {
1231 		m->s.qinfo.qname = r->qname;
1232 		m->s.qinfo.local_alias = r->local_alias;
1233 		if(rcode == LDNS_RCODE_SERVFAIL) {
1234 			if(!inplace_cb_reply_servfail_call(m->s.env, &m->s.qinfo, &m->s,
1235 				rep, rcode, &r->edns, NULL, m->s.region))
1236 					r->edns.opt_list = NULL;
1237 		} else {
1238 			if(!inplace_cb_reply_call(m->s.env, &m->s.qinfo, &m->s, rep, rcode,
1239 				&r->edns, NULL, m->s.region))
1240 					r->edns.opt_list = NULL;
1241 		}
1242 		error_encode(r_buffer, rcode, &m->s.qinfo, r->qid,
1243 			r->qflags, &r->edns);
1244 		comm_point_send_reply(&r->query_reply);
1245 	} else {
1246 		size_t udp_size = r->edns.udp_size;
1247 		r->edns.edns_version = EDNS_ADVERTISED_VERSION;
1248 		r->edns.udp_size = EDNS_ADVERTISED_SIZE;
1249 		r->edns.ext_rcode = 0;
1250 		r->edns.bits &= EDNS_DO;
1251 		m->s.qinfo.qname = r->qname;
1252 		m->s.qinfo.local_alias = r->local_alias;
1253 		if(!inplace_cb_reply_call(m->s.env, &m->s.qinfo, &m->s, rep,
1254 			LDNS_RCODE_NOERROR, &r->edns, NULL, m->s.region) ||
1255 			!apply_edns_options(&r->edns, &edns_bak,
1256 				m->s.env->cfg, r->query_reply.c,
1257 				m->s.region) ||
1258 			!reply_info_answer_encode(&m->s.qinfo, rep, r->qid,
1259 			r->qflags, r_buffer, 0, 1, m->s.env->scratch,
1260 			udp_size, &r->edns, (int)(r->edns.bits & EDNS_DO),
1261 			secure))
1262 		{
1263 			if(!inplace_cb_reply_servfail_call(m->s.env, &m->s.qinfo, &m->s,
1264 			rep, LDNS_RCODE_SERVFAIL, &r->edns, NULL, m->s.region))
1265 				r->edns.opt_list = NULL;
1266 			error_encode(r_buffer, LDNS_RCODE_SERVFAIL,
1267 				&m->s.qinfo, r->qid, r->qflags, &r->edns);
1268 		}
1269 		r->edns = edns_bak;
1270 		comm_point_send_reply(&r->query_reply);
1271 	}
1272 	/* account */
1273 	log_assert(m->s.env->mesh->num_reply_addrs > 0);
1274 	m->s.env->mesh->num_reply_addrs--;
1275 	end_time = *m->s.env->now_tv;
1276 	timeval_subtract(&duration, &end_time, &r->start_time);
1277 	verbose(VERB_ALGO, "query took " ARG_LL "d.%6.6d sec",
1278 		(long long)duration.tv_sec, (int)duration.tv_usec);
1279 	m->s.env->mesh->replies_sent++;
1280 	timeval_add(&m->s.env->mesh->replies_sum_wait, &duration);
1281 	timehist_insert(m->s.env->mesh->histogram, &duration);
1282 	if(m->s.env->cfg->stat_extended) {
1283 		uint16_t rc = FLAGS_GET_RCODE(sldns_buffer_read_u16_at(
1284 			r_buffer, 2));
1285 		if(secure) m->s.env->mesh->ans_secure++;
1286 		m->s.env->mesh->ans_rcode[ rc ] ++;
1287 		if(rc == 0 && LDNS_ANCOUNT(sldns_buffer_begin(r_buffer)) == 0)
1288 			m->s.env->mesh->ans_nodata++;
1289 	}
1290 	/* Log reply sent */
1291 	if(m->s.env->cfg->log_replies) {
1292 		log_reply_info(NO_VERBOSE, &m->s.qinfo, &r->query_reply.addr,
1293 			r->query_reply.addrlen, duration, 0, r_buffer);
1294 	}
1295 }
1296 
1297 void mesh_query_done(struct mesh_state* mstate)
1298 {
1299 	struct mesh_reply* r;
1300 	struct mesh_reply* prev = NULL;
1301 	struct sldns_buffer* prev_buffer = NULL;
1302 	struct mesh_cb* c;
1303 	struct reply_info* rep = (mstate->s.return_msg?
1304 		mstate->s.return_msg->rep:NULL);
1305 	/* No need for the serve expired timer anymore; we are going to reply. */
1306 	if(mstate->s.serve_expired_data) {
1307 		comm_timer_delete(mstate->s.serve_expired_data->timer);
1308 		mstate->s.serve_expired_data->timer = NULL;
1309 	}
1310 	if(mstate->s.return_rcode == LDNS_RCODE_SERVFAIL ||
1311 		(rep && FLAGS_GET_RCODE(rep->flags) == LDNS_RCODE_SERVFAIL)) {
1312 		/* we are SERVFAILing; check for expired asnwer here */
1313 		mesh_serve_expired_callback(mstate);
1314 		if((mstate->reply_list || mstate->cb_list)
1315 		&& mstate->s.env->cfg->log_servfail
1316 		&& !mstate->s.env->cfg->val_log_squelch) {
1317 			char* err = errinf_to_str_servfail(&mstate->s);
1318 			if(err)
1319 				log_err("%s", err);
1320 			free(err);
1321 		}
1322 	}
1323 	for(r = mstate->reply_list; r; r = r->next) {
1324 		/* if a response-ip address block has been stored the
1325 		 *  information should be logged for each client. */
1326 		if(mstate->s.respip_action_info &&
1327 			mstate->s.respip_action_info->addrinfo) {
1328 			respip_inform_print(mstate->s.respip_action_info,
1329 				r->qname, mstate->s.qinfo.qtype,
1330 				mstate->s.qinfo.qclass, r->local_alias,
1331 				&r->query_reply);
1332 			if(mstate->s.env->cfg->stat_extended &&
1333 				mstate->s.respip_action_info->rpz_used) {
1334 				if(mstate->s.respip_action_info->rpz_disabled)
1335 					mstate->s.env->mesh->rpz_action[RPZ_DISABLED_ACTION]++;
1336 				if(mstate->s.respip_action_info->rpz_cname_override)
1337 					mstate->s.env->mesh->rpz_action[RPZ_CNAME_OVERRIDE_ACTION]++;
1338 				else
1339 					mstate->s.env->mesh->rpz_action[respip_action_to_rpz_action(
1340 						mstate->s.respip_action_info->action)]++;
1341 			}
1342 		}
1343 
1344 		/* if this query is determined to be dropped during the
1345 		 * mesh processing, this is the point to take that action. */
1346 		if(mstate->s.is_drop) {
1347 			/* briefly set the reply_list to NULL, so that the
1348 			 * tcp req info cleanup routine that calls the mesh
1349 			 * to deregister the meshstate for it is not done
1350 			 * because the list is NULL and also accounting is not
1351 			 * done there, but instead we do that here. */
1352 			struct mesh_reply* reply_list = mstate->reply_list;
1353 			mstate->reply_list = NULL;
1354 			comm_point_drop_reply(&r->query_reply);
1355 			mstate->reply_list = reply_list;
1356 		} else {
1357 			struct sldns_buffer* r_buffer = r->query_reply.c->buffer;
1358 			struct mesh_reply* rlist = mstate->reply_list;
1359 			if(r->query_reply.c->tcp_req_info) {
1360 				r_buffer = r->query_reply.c->tcp_req_info->spool_buffer;
1361 				prev_buffer = NULL;
1362 			}
1363 			/* briefly set the replylist to null in case the
1364 			 * meshsendreply calls tcpreqinfo sendreply that
1365 			 * comm_point_drops because of size, and then the
1366 			 * null stops the mesh state remove and thus
1367 			 * reply_list modification and accounting */
1368 			mstate->reply_list = NULL;
1369 			mesh_send_reply(mstate, mstate->s.return_rcode, rep,
1370 				r, r_buffer, prev, prev_buffer);
1371 			mstate->reply_list = rlist;
1372 			if(r->query_reply.c->tcp_req_info) {
1373 				tcp_req_info_remove_mesh_state(r->query_reply.c->tcp_req_info, mstate);
1374 				r_buffer = NULL;
1375 			}
1376 			prev = r;
1377 			prev_buffer = r_buffer;
1378 		}
1379 	}
1380 	if(mstate->reply_list) {
1381 		mstate->reply_list = NULL;
1382 		if(!mstate->reply_list && !mstate->cb_list) {
1383 			/* was a reply state, not anymore */
1384 			log_assert(mstate->s.env->mesh->num_reply_states > 0);
1385 			mstate->s.env->mesh->num_reply_states--;
1386 		}
1387 		if(!mstate->reply_list && !mstate->cb_list &&
1388 			mstate->super_set.count == 0)
1389 			mstate->s.env->mesh->num_detached_states++;
1390 	}
1391 	mstate->replies_sent = 1;
1392 	while((c = mstate->cb_list) != NULL) {
1393 		/* take this cb off the list; so that the list can be
1394 		 * changed, eg. by adds from the callback routine */
1395 		if(!mstate->reply_list && mstate->cb_list && !c->next) {
1396 			/* was a reply state, not anymore */
1397 			log_assert(mstate->s.env->mesh->num_reply_states > 0);
1398 			mstate->s.env->mesh->num_reply_states--;
1399 		}
1400 		mstate->cb_list = c->next;
1401 		if(!mstate->reply_list && !mstate->cb_list &&
1402 			mstate->super_set.count == 0)
1403 			mstate->s.env->mesh->num_detached_states++;
1404 		mesh_do_callback(mstate, mstate->s.return_rcode, rep, c);
1405 	}
1406 }
1407 
1408 void mesh_walk_supers(struct mesh_area* mesh, struct mesh_state* mstate)
1409 {
1410 	struct mesh_state_ref* ref;
1411 	RBTREE_FOR(ref, struct mesh_state_ref*, &mstate->super_set)
1412 	{
1413 		/* make super runnable */
1414 		(void)rbtree_insert(&mesh->run, &ref->s->run_node);
1415 		/* callback the function to inform super of result */
1416 		fptr_ok(fptr_whitelist_mod_inform_super(
1417 			mesh->mods.mod[ref->s->s.curmod]->inform_super));
1418 		(*mesh->mods.mod[ref->s->s.curmod]->inform_super)(&mstate->s,
1419 			ref->s->s.curmod, &ref->s->s);
1420 		/* copy state that is always relevant to super */
1421 		copy_state_to_super(&mstate->s, ref->s->s.curmod, &ref->s->s);
1422 	}
1423 }
1424 
1425 struct mesh_state* mesh_area_find(struct mesh_area* mesh,
1426 	struct respip_client_info* cinfo, struct query_info* qinfo,
1427 	uint16_t qflags, int prime, int valrec)
1428 {
1429 	struct mesh_state key;
1430 	struct mesh_state* result;
1431 
1432 	key.node.key = &key;
1433 	key.s.is_priming = prime;
1434 	key.s.is_valrec = valrec;
1435 	key.s.qinfo = *qinfo;
1436 	key.s.query_flags = qflags;
1437 	/* We are searching for a similar mesh state when we DO want to
1438 	 * aggregate the state. Thus unique is set to NULL. (default when we
1439 	 * desire aggregation).*/
1440 	key.unique = NULL;
1441 	key.s.client_info = cinfo;
1442 
1443 	result = (struct mesh_state*)rbtree_search(&mesh->all, &key);
1444 	return result;
1445 }
1446 
1447 int mesh_state_add_cb(struct mesh_state* s, struct edns_data* edns,
1448         sldns_buffer* buf, mesh_cb_func_type cb, void* cb_arg,
1449 	uint16_t qid, uint16_t qflags)
1450 {
1451 	struct mesh_cb* r = regional_alloc(s->s.region,
1452 		sizeof(struct mesh_cb));
1453 	if(!r)
1454 		return 0;
1455 	r->buf = buf;
1456 	log_assert(fptr_whitelist_mesh_cb(cb)); /* early failure ifmissing*/
1457 	r->cb = cb;
1458 	r->cb_arg = cb_arg;
1459 	r->edns = *edns;
1460 	if(edns->opt_list) {
1461 		r->edns.opt_list = edns_opt_copy_region(edns->opt_list,
1462 			s->s.region);
1463 		if(!r->edns.opt_list)
1464 			return 0;
1465 	}
1466 	r->qid = qid;
1467 	r->qflags = qflags;
1468 	r->next = s->cb_list;
1469 	s->cb_list = r;
1470 	return 1;
1471 
1472 }
1473 
1474 int mesh_state_add_reply(struct mesh_state* s, struct edns_data* edns,
1475         struct comm_reply* rep, uint16_t qid, uint16_t qflags,
1476         const struct query_info* qinfo)
1477 {
1478 	struct mesh_reply* r = regional_alloc(s->s.region,
1479 		sizeof(struct mesh_reply));
1480 	if(!r)
1481 		return 0;
1482 	r->query_reply = *rep;
1483 	r->edns = *edns;
1484 	if(edns->opt_list) {
1485 		r->edns.opt_list = edns_opt_copy_region(edns->opt_list,
1486 			s->s.region);
1487 		if(!r->edns.opt_list)
1488 			return 0;
1489 	}
1490 	r->qid = qid;
1491 	r->qflags = qflags;
1492 	r->start_time = *s->s.env->now_tv;
1493 	r->next = s->reply_list;
1494 	r->qname = regional_alloc_init(s->s.region, qinfo->qname,
1495 		s->s.qinfo.qname_len);
1496 	if(!r->qname)
1497 		return 0;
1498 
1499 	/* Data related to local alias stored in 'qinfo' (if any) is ephemeral
1500 	 * and can be different for different original queries (even if the
1501 	 * replaced query name is the same).  So we need to make a deep copy
1502 	 * and store the copy for each reply info. */
1503 	if(qinfo->local_alias) {
1504 		struct packed_rrset_data* d;
1505 		struct packed_rrset_data* dsrc;
1506 		r->local_alias = regional_alloc_zero(s->s.region,
1507 			sizeof(*qinfo->local_alias));
1508 		if(!r->local_alias)
1509 			return 0;
1510 		r->local_alias->rrset = regional_alloc_init(s->s.region,
1511 			qinfo->local_alias->rrset,
1512 			sizeof(*qinfo->local_alias->rrset));
1513 		if(!r->local_alias->rrset)
1514 			return 0;
1515 		dsrc = qinfo->local_alias->rrset->entry.data;
1516 
1517 		/* In the current implementation, a local alias must be
1518 		 * a single CNAME RR (see worker_handle_request()). */
1519 		log_assert(!qinfo->local_alias->next && dsrc->count == 1 &&
1520 			qinfo->local_alias->rrset->rk.type ==
1521 			htons(LDNS_RR_TYPE_CNAME));
1522 		/* we should make a local copy for the owner name of
1523 		 * the RRset */
1524 		r->local_alias->rrset->rk.dname_len =
1525 			qinfo->local_alias->rrset->rk.dname_len;
1526 		r->local_alias->rrset->rk.dname = regional_alloc_init(
1527 			s->s.region, qinfo->local_alias->rrset->rk.dname,
1528 			qinfo->local_alias->rrset->rk.dname_len);
1529 		if(!r->local_alias->rrset->rk.dname)
1530 			return 0;
1531 
1532 		/* the rrset is not packed, like in the cache, but it is
1533 		 * individualy allocated with an allocator from localzone. */
1534 		d = regional_alloc_zero(s->s.region, sizeof(*d));
1535 		if(!d)
1536 			return 0;
1537 		r->local_alias->rrset->entry.data = d;
1538 		if(!rrset_insert_rr(s->s.region, d, dsrc->rr_data[0],
1539 			dsrc->rr_len[0], dsrc->rr_ttl[0], "CNAME local alias"))
1540 			return 0;
1541 	} else
1542 		r->local_alias = NULL;
1543 
1544 	s->reply_list = r;
1545 	return 1;
1546 }
1547 
1548 /* Extract the query info and flags from 'mstate' into '*qinfop' and '*qflags'.
1549  * Since this is only used for internal refetch of otherwise-expired answer,
1550  * we simply ignore the rare failure mode when memory allocation fails. */
1551 static void
1552 mesh_copy_qinfo(struct mesh_state* mstate, struct query_info** qinfop,
1553 	uint16_t* qflags)
1554 {
1555 	struct regional* region = mstate->s.env->scratch;
1556 	struct query_info* qinfo;
1557 
1558 	qinfo = regional_alloc_init(region, &mstate->s.qinfo, sizeof(*qinfo));
1559 	if(!qinfo)
1560 		return;
1561 	qinfo->qname = regional_alloc_init(region, qinfo->qname,
1562 		qinfo->qname_len);
1563 	if(!qinfo->qname)
1564 		return;
1565 	*qinfop = qinfo;
1566 	*qflags = mstate->s.query_flags;
1567 }
1568 
1569 /**
1570  * Continue processing the mesh state at another module.
1571  * Handles module to modules transfer of control.
1572  * Handles module finished.
1573  * @param mesh: the mesh area.
1574  * @param mstate: currently active mesh state.
1575  * 	Deleted if finished, calls _done and _supers to
1576  * 	send replies to clients and inform other mesh states.
1577  * 	This in turn may create additional runnable mesh states.
1578  * @param s: state at which the current module exited.
1579  * @param ev: the event sent to the module.
1580  * 	returned is the event to send to the next module.
1581  * @return true if continue processing at the new module.
1582  * 	false if not continued processing is needed.
1583  */
1584 static int
1585 mesh_continue(struct mesh_area* mesh, struct mesh_state* mstate,
1586 	enum module_ext_state s, enum module_ev* ev)
1587 {
1588 	mstate->num_activated++;
1589 	if(mstate->num_activated > MESH_MAX_ACTIVATION) {
1590 		/* module is looping. Stop it. */
1591 		log_err("internal error: looping module (%s) stopped",
1592 			mesh->mods.mod[mstate->s.curmod]->name);
1593 		log_query_info(NO_VERBOSE, "pass error for qstate",
1594 			&mstate->s.qinfo);
1595 		s = module_error;
1596 	}
1597 	if(s == module_wait_module || s == module_restart_next) {
1598 		/* start next module */
1599 		mstate->s.curmod++;
1600 		if(mesh->mods.num == mstate->s.curmod) {
1601 			log_err("Cannot pass to next module; at last module");
1602 			log_query_info(VERB_QUERY, "pass error for qstate",
1603 				&mstate->s.qinfo);
1604 			mstate->s.curmod--;
1605 			return mesh_continue(mesh, mstate, module_error, ev);
1606 		}
1607 		if(s == module_restart_next) {
1608 			int curmod = mstate->s.curmod;
1609 			for(; mstate->s.curmod < mesh->mods.num;
1610 				mstate->s.curmod++) {
1611 				fptr_ok(fptr_whitelist_mod_clear(
1612 					mesh->mods.mod[mstate->s.curmod]->clear));
1613 				(*mesh->mods.mod[mstate->s.curmod]->clear)
1614 					(&mstate->s, mstate->s.curmod);
1615 				mstate->s.minfo[mstate->s.curmod] = NULL;
1616 			}
1617 			mstate->s.curmod = curmod;
1618 		}
1619 		*ev = module_event_pass;
1620 		return 1;
1621 	}
1622 	if(s == module_wait_subquery && mstate->sub_set.count == 0) {
1623 		log_err("module cannot wait for subquery, subquery list empty");
1624 		log_query_info(VERB_QUERY, "pass error for qstate",
1625 			&mstate->s.qinfo);
1626 		s = module_error;
1627 	}
1628 	if(s == module_error && mstate->s.return_rcode == LDNS_RCODE_NOERROR) {
1629 		/* error is bad, handle pass back up below */
1630 		mstate->s.return_rcode = LDNS_RCODE_SERVFAIL;
1631 	}
1632 	if(s == module_error) {
1633 		mesh_query_done(mstate);
1634 		mesh_walk_supers(mesh, mstate);
1635 		mesh_state_delete(&mstate->s);
1636 		return 0;
1637 	}
1638 	if(s == module_finished) {
1639 		if(mstate->s.curmod == 0) {
1640 			struct query_info* qinfo = NULL;
1641 			uint16_t qflags;
1642 
1643 			mesh_query_done(mstate);
1644 			mesh_walk_supers(mesh, mstate);
1645 
1646 			/* If the answer to the query needs to be refetched
1647 			 * from an external DNS server, we'll need to schedule
1648 			 * a prefetch after removing the current state, so
1649 			 * we need to make a copy of the query info here. */
1650 			if(mstate->s.need_refetch)
1651 				mesh_copy_qinfo(mstate, &qinfo, &qflags);
1652 
1653 			mesh_state_delete(&mstate->s);
1654 			if(qinfo) {
1655 				mesh_schedule_prefetch(mesh, qinfo, qflags,
1656 					0, 1);
1657 			}
1658 			return 0;
1659 		}
1660 		/* pass along the locus of control */
1661 		mstate->s.curmod --;
1662 		*ev = module_event_moddone;
1663 		return 1;
1664 	}
1665 	return 0;
1666 }
1667 
1668 void mesh_run(struct mesh_area* mesh, struct mesh_state* mstate,
1669 	enum module_ev ev, struct outbound_entry* e)
1670 {
1671 	enum module_ext_state s;
1672 	verbose(VERB_ALGO, "mesh_run: start");
1673 	while(mstate) {
1674 		/* run the module */
1675 		fptr_ok(fptr_whitelist_mod_operate(
1676 			mesh->mods.mod[mstate->s.curmod]->operate));
1677 		(*mesh->mods.mod[mstate->s.curmod]->operate)
1678 			(&mstate->s, ev, mstate->s.curmod, e);
1679 
1680 		/* examine results */
1681 		mstate->s.reply = NULL;
1682 		regional_free_all(mstate->s.env->scratch);
1683 		s = mstate->s.ext_state[mstate->s.curmod];
1684 		verbose(VERB_ALGO, "mesh_run: %s module exit state is %s",
1685 			mesh->mods.mod[mstate->s.curmod]->name, strextstate(s));
1686 		e = NULL;
1687 		if(mesh_continue(mesh, mstate, s, &ev))
1688 			continue;
1689 
1690 		/* run more modules */
1691 		ev = module_event_pass;
1692 		if(mesh->run.count > 0) {
1693 			/* pop random element off the runnable tree */
1694 			mstate = (struct mesh_state*)mesh->run.root->key;
1695 			(void)rbtree_delete(&mesh->run, mstate);
1696 		} else mstate = NULL;
1697 	}
1698 	if(verbosity >= VERB_ALGO) {
1699 		mesh_stats(mesh, "mesh_run: end");
1700 		mesh_log_list(mesh);
1701 	}
1702 }
1703 
1704 void
1705 mesh_log_list(struct mesh_area* mesh)
1706 {
1707 	char buf[30];
1708 	struct mesh_state* m;
1709 	int num = 0;
1710 	RBTREE_FOR(m, struct mesh_state*, &mesh->all) {
1711 		snprintf(buf, sizeof(buf), "%d%s%s%s%s%s%s mod%d %s%s",
1712 			num++, (m->s.is_priming)?"p":"",  /* prime */
1713 			(m->s.is_valrec)?"v":"",  /* prime */
1714 			(m->s.query_flags&BIT_RD)?"RD":"",
1715 			(m->s.query_flags&BIT_CD)?"CD":"",
1716 			(m->super_set.count==0)?"d":"", /* detached */
1717 			(m->sub_set.count!=0)?"c":"",  /* children */
1718 			m->s.curmod, (m->reply_list)?"rep":"", /*hasreply*/
1719 			(m->cb_list)?"cb":"" /* callbacks */
1720 			);
1721 		log_query_info(VERB_ALGO, buf, &m->s.qinfo);
1722 	}
1723 }
1724 
1725 void
1726 mesh_stats(struct mesh_area* mesh, const char* str)
1727 {
1728 	verbose(VERB_DETAIL, "%s %u recursion states (%u with reply, "
1729 		"%u detached), %u waiting replies, %u recursion replies "
1730 		"sent, %d replies dropped, %d states jostled out",
1731 		str, (unsigned)mesh->all.count,
1732 		(unsigned)mesh->num_reply_states,
1733 		(unsigned)mesh->num_detached_states,
1734 		(unsigned)mesh->num_reply_addrs,
1735 		(unsigned)mesh->replies_sent,
1736 		(unsigned)mesh->stats_dropped,
1737 		(unsigned)mesh->stats_jostled);
1738 	if(mesh->replies_sent > 0) {
1739 		struct timeval avg;
1740 		timeval_divide(&avg, &mesh->replies_sum_wait,
1741 			mesh->replies_sent);
1742 		log_info("average recursion processing time "
1743 			ARG_LL "d.%6.6d sec",
1744 			(long long)avg.tv_sec, (int)avg.tv_usec);
1745 		log_info("histogram of recursion processing times");
1746 		timehist_log(mesh->histogram, "recursions");
1747 	}
1748 }
1749 
1750 void
1751 mesh_stats_clear(struct mesh_area* mesh)
1752 {
1753 	if(!mesh)
1754 		return;
1755 	mesh->replies_sent = 0;
1756 	mesh->replies_sum_wait.tv_sec = 0;
1757 	mesh->replies_sum_wait.tv_usec = 0;
1758 	mesh->stats_jostled = 0;
1759 	mesh->stats_dropped = 0;
1760 	timehist_clear(mesh->histogram);
1761 	mesh->ans_secure = 0;
1762 	mesh->ans_bogus = 0;
1763 	mesh->ans_expired = 0;
1764 	memset(&mesh->ans_rcode[0], 0, sizeof(size_t)*UB_STATS_RCODE_NUM);
1765 	memset(&mesh->rpz_action[0], 0, sizeof(size_t)*UB_STATS_RPZ_ACTION_NUM);
1766 	mesh->ans_nodata = 0;
1767 }
1768 
1769 size_t
1770 mesh_get_mem(struct mesh_area* mesh)
1771 {
1772 	struct mesh_state* m;
1773 	size_t s = sizeof(*mesh) + sizeof(struct timehist) +
1774 		sizeof(struct th_buck)*mesh->histogram->num +
1775 		sizeof(sldns_buffer) + sldns_buffer_capacity(mesh->qbuf_bak);
1776 	RBTREE_FOR(m, struct mesh_state*, &mesh->all) {
1777 		/* all, including m itself allocated in qstate region */
1778 		s += regional_get_mem(m->s.region);
1779 	}
1780 	return s;
1781 }
1782 
1783 int
1784 mesh_detect_cycle(struct module_qstate* qstate, struct query_info* qinfo,
1785 	uint16_t flags, int prime, int valrec)
1786 {
1787 	struct mesh_area* mesh = qstate->env->mesh;
1788 	struct mesh_state* dep_m = NULL;
1789 	if(!mesh_state_is_unique(qstate->mesh_info))
1790 		dep_m = mesh_area_find(mesh, NULL, qinfo, flags, prime, valrec);
1791 	return mesh_detect_cycle_found(qstate, dep_m);
1792 }
1793 
1794 void mesh_list_insert(struct mesh_state* m, struct mesh_state** fp,
1795         struct mesh_state** lp)
1796 {
1797 	/* insert as last element */
1798 	m->prev = *lp;
1799 	m->next = NULL;
1800 	if(*lp)
1801 		(*lp)->next = m;
1802 	else	*fp = m;
1803 	*lp = m;
1804 }
1805 
1806 void mesh_list_remove(struct mesh_state* m, struct mesh_state** fp,
1807         struct mesh_state** lp)
1808 {
1809 	if(m->next)
1810 		m->next->prev = m->prev;
1811 	else	*lp = m->prev;
1812 	if(m->prev)
1813 		m->prev->next = m->next;
1814 	else	*fp = m->next;
1815 }
1816 
1817 void mesh_state_remove_reply(struct mesh_area* mesh, struct mesh_state* m,
1818 	struct comm_point* cp)
1819 {
1820 	struct mesh_reply* n, *prev = NULL;
1821 	n = m->reply_list;
1822 	/* when in mesh_cleanup, it sets the reply_list to NULL, so that
1823 	 * there is no accounting twice */
1824 	if(!n) return; /* nothing to remove, also no accounting needed */
1825 	while(n) {
1826 		if(n->query_reply.c == cp) {
1827 			/* unlink it */
1828 			if(prev) prev->next = n->next;
1829 			else m->reply_list = n->next;
1830 			/* delete it, but allocated in m region */
1831 			log_assert(mesh->num_reply_addrs > 0);
1832 			mesh->num_reply_addrs--;
1833 
1834 			/* prev = prev; */
1835 			n = n->next;
1836 			continue;
1837 		}
1838 		prev = n;
1839 		n = n->next;
1840 	}
1841 	/* it was not detached (because it had a reply list), could be now */
1842 	if(!m->reply_list && !m->cb_list
1843 		&& m->super_set.count == 0) {
1844 		mesh->num_detached_states++;
1845 	}
1846 	/* if not replies any more in mstate, it is no longer a reply_state */
1847 	if(!m->reply_list && !m->cb_list) {
1848 		log_assert(mesh->num_reply_states > 0);
1849 		mesh->num_reply_states--;
1850 	}
1851 }
1852 
1853 
1854 static int
1855 apply_respip_action(struct module_qstate* qstate,
1856 	const struct query_info* qinfo, struct respip_client_info* cinfo,
1857 	struct respip_action_info* actinfo, struct reply_info* rep,
1858 	struct ub_packed_rrset_key** alias_rrset,
1859 	struct reply_info** encode_repp, struct auth_zones* az)
1860 {
1861 	if(qinfo->qtype != LDNS_RR_TYPE_A &&
1862 		qinfo->qtype != LDNS_RR_TYPE_AAAA &&
1863 		qinfo->qtype != LDNS_RR_TYPE_ANY)
1864 		return 1;
1865 
1866 	if(!respip_rewrite_reply(qinfo, cinfo, rep, encode_repp, actinfo,
1867 		alias_rrset, 0, qstate->region, az))
1868 		return 0;
1869 
1870 	/* xxx_deny actions mean dropping the reply, unless the original reply
1871 	 * was redirected to response-ip data. */
1872 	if((actinfo->action == respip_deny ||
1873 		actinfo->action == respip_inform_deny) &&
1874 		*encode_repp == rep)
1875 		*encode_repp = NULL;
1876 
1877 	return 1;
1878 }
1879 
1880 void
1881 mesh_serve_expired_callback(void* arg)
1882 {
1883 	struct mesh_state* mstate = (struct mesh_state*) arg;
1884 	struct module_qstate* qstate = &mstate->s;
1885 	struct mesh_reply* r, *rlist;
1886 	struct mesh_area* mesh = qstate->env->mesh;
1887 	struct dns_msg* msg;
1888 	struct mesh_cb* c;
1889 	struct mesh_reply* prev = NULL;
1890 	struct sldns_buffer* prev_buffer = NULL;
1891 	struct sldns_buffer* r_buffer = NULL;
1892 	struct reply_info* partial_rep = NULL;
1893 	struct ub_packed_rrset_key* alias_rrset = NULL;
1894 	struct reply_info* encode_rep = NULL;
1895 	struct respip_action_info actinfo;
1896 	struct query_info* lookup_qinfo = &qstate->qinfo;
1897 	struct query_info qinfo_tmp;
1898 	int must_validate = (!(qstate->query_flags&BIT_CD)
1899 		|| qstate->env->cfg->ignore_cd) && qstate->env->need_to_validate;
1900 	if(!qstate->serve_expired_data) return;
1901 	verbose(VERB_ALGO, "Serve expired: Trying to reply with expired data");
1902 	comm_timer_delete(qstate->serve_expired_data->timer);
1903 	qstate->serve_expired_data->timer = NULL;
1904 	if(qstate->blacklist || qstate->no_cache_lookup || qstate->is_drop) {
1905 		verbose(VERB_ALGO,
1906 			"Serve expired: Not allowed to look into cache for stale");
1907 		return;
1908 	}
1909 	/* The following while is used instead of the `goto lookup_cache`
1910 	 * like in the worker. */
1911 	while(1) {
1912 		fptr_ok(fptr_whitelist_serve_expired_lookup(
1913 			qstate->serve_expired_data->get_cached_answer));
1914 		msg = qstate->serve_expired_data->get_cached_answer(qstate,
1915 			lookup_qinfo);
1916 		if(!msg)
1917 			return;
1918 		/* Reset these in case we pass a second time from here. */
1919 		encode_rep = msg->rep;
1920 		memset(&actinfo, 0, sizeof(actinfo));
1921 		actinfo.action = respip_none;
1922 		alias_rrset = NULL;
1923 		if((mesh->use_response_ip || mesh->use_rpz) &&
1924 			!partial_rep && !apply_respip_action(qstate, &qstate->qinfo,
1925 			qstate->client_info, &actinfo, msg->rep, &alias_rrset, &encode_rep,
1926 			qstate->env->auth_zones)) {
1927 			return;
1928 		} else if(partial_rep &&
1929 			!respip_merge_cname(partial_rep, &qstate->qinfo, msg->rep,
1930 			qstate->client_info, must_validate, &encode_rep, qstate->region,
1931 			qstate->env->auth_zones)) {
1932 			return;
1933 		}
1934 		if(!encode_rep || alias_rrset) {
1935 			if(!encode_rep) {
1936 				/* Needs drop */
1937 				return;
1938 			} else {
1939 				/* A partial CNAME chain is found. */
1940 				partial_rep = encode_rep;
1941 			}
1942 		}
1943 		/* We've found a partial reply ending with an
1944 		* alias.  Replace the lookup qinfo for the
1945 		* alias target and lookup the cache again to
1946 		* (possibly) complete the reply.  As we're
1947 		* passing the "base" reply, there will be no
1948 		* more alias chasing. */
1949 		if(partial_rep) {
1950 			memset(&qinfo_tmp, 0, sizeof(qinfo_tmp));
1951 			get_cname_target(alias_rrset, &qinfo_tmp.qname,
1952 				&qinfo_tmp.qname_len);
1953 			if(!qinfo_tmp.qname) {
1954 				log_err("Serve expired: unexpected: invalid answer alias");
1955 				return;
1956 			}
1957 			qinfo_tmp.qtype = qstate->qinfo.qtype;
1958 			qinfo_tmp.qclass = qstate->qinfo.qclass;
1959 			lookup_qinfo = &qinfo_tmp;
1960 			continue;
1961 		}
1962 		break;
1963 	}
1964 
1965 	if(verbosity >= VERB_ALGO)
1966 		log_dns_msg("Serve expired lookup", &qstate->qinfo, msg->rep);
1967 
1968 	for(r = mstate->reply_list; r; r = r->next) {
1969 		/* If address info is returned, it means the action should be an
1970 		* 'inform' variant and the information should be logged. */
1971 		if(actinfo.addrinfo) {
1972 			respip_inform_print(&actinfo, r->qname,
1973 				qstate->qinfo.qtype, qstate->qinfo.qclass,
1974 				r->local_alias, &r->query_reply);
1975 
1976 			if(qstate->env->cfg->stat_extended && actinfo.rpz_used) {
1977 				if(actinfo.rpz_disabled)
1978 					qstate->env->mesh->rpz_action[RPZ_DISABLED_ACTION]++;
1979 				if(actinfo.rpz_cname_override)
1980 					qstate->env->mesh->rpz_action[RPZ_CNAME_OVERRIDE_ACTION]++;
1981 				else
1982 					qstate->env->mesh->rpz_action[
1983 						respip_action_to_rpz_action(actinfo.action)]++;
1984 			}
1985 		}
1986 
1987 		r_buffer = r->query_reply.c->buffer;
1988 		if(r->query_reply.c->tcp_req_info)
1989 			r_buffer = r->query_reply.c->tcp_req_info->spool_buffer;
1990 		/* briefly set the replylist to null in case the meshsendreply
1991 		 * calls tcpreqinfo sendreply that comm_point_drops because
1992 		 * of size, and then the null stops the mesh state remove and
1993 		 * thus reply_list modification and accounting */
1994 		rlist = mstate->reply_list;
1995 		mstate->reply_list = NULL;
1996 		mesh_send_reply(mstate, LDNS_RCODE_NOERROR, msg->rep,
1997 			r, r_buffer, prev, prev_buffer);
1998 		mstate->reply_list = rlist;
1999 		if(r->query_reply.c->tcp_req_info)
2000 			tcp_req_info_remove_mesh_state(r->query_reply.c->tcp_req_info, mstate);
2001 		prev = r;
2002 		prev_buffer = r_buffer;
2003 
2004 		/* Account for each reply sent. */
2005 		mesh->ans_expired++;
2006 
2007 	}
2008 	if(mstate->reply_list) {
2009 		mstate->reply_list = NULL;
2010 		if(!mstate->reply_list && !mstate->cb_list) {
2011 			log_assert(mesh->num_reply_states > 0);
2012 			mesh->num_reply_states--;
2013 			if(mstate->super_set.count == 0) {
2014 				mesh->num_detached_states++;
2015 			}
2016 		}
2017 	}
2018 	while((c = mstate->cb_list) != NULL) {
2019 		/* take this cb off the list; so that the list can be
2020 		 * changed, eg. by adds from the callback routine */
2021 		if(!mstate->reply_list && mstate->cb_list && !c->next) {
2022 			/* was a reply state, not anymore */
2023 			log_assert(qstate->env->mesh->num_reply_states > 0);
2024 			qstate->env->mesh->num_reply_states--;
2025 		}
2026 		mstate->cb_list = c->next;
2027 		if(!mstate->reply_list && !mstate->cb_list &&
2028 			mstate->super_set.count == 0)
2029 			qstate->env->mesh->num_detached_states++;
2030 		mesh_do_callback(mstate, LDNS_RCODE_NOERROR, msg->rep, c);
2031 	}
2032 }
2033