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