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