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