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