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