xref: /freebsd/contrib/unbound/daemon/worker.c (revision 2faf504d1ab821fe2b9df9d2afb49bb35e1334f4)
1 /*
2  * daemon/worker.c - worker that handles a pending list of requests.
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 implements the worker that handles callbacks on events, for
40  * pending requests.
41  */
42 #include "config.h"
43 #include "util/log.h"
44 #include "util/net_help.h"
45 #include "util/random.h"
46 #include "daemon/worker.h"
47 #include "daemon/daemon.h"
48 #include "daemon/remote.h"
49 #include "daemon/acl_list.h"
50 #include "util/netevent.h"
51 #include "util/config_file.h"
52 #include "util/module.h"
53 #include "util/regional.h"
54 #include "util/storage/slabhash.h"
55 #include "services/listen_dnsport.h"
56 #include "services/outside_network.h"
57 #include "services/outbound_list.h"
58 #include "services/cache/rrset.h"
59 #include "services/cache/infra.h"
60 #include "services/cache/dns.h"
61 #include "services/authzone.h"
62 #include "services/mesh.h"
63 #include "services/localzone.h"
64 #include "services/rpz.h"
65 #include "util/data/msgparse.h"
66 #include "util/data/msgencode.h"
67 #include "util/data/dname.h"
68 #include "util/fptr_wlist.h"
69 #include "util/tube.h"
70 #include "util/edns.h"
71 #include "iterator/iter_fwd.h"
72 #include "iterator/iter_hints.h"
73 #include "iterator/iter_utils.h"
74 #include "validator/autotrust.h"
75 #include "validator/val_anchor.h"
76 #include "respip/respip.h"
77 #include "libunbound/context.h"
78 #include "libunbound/libworker.h"
79 #include "sldns/sbuffer.h"
80 #include "sldns/wire2str.h"
81 #include "util/shm_side/shm_main.h"
82 #include "dnscrypt/dnscrypt.h"
83 #include "dnstap/dtstream.h"
84 
85 #ifdef HAVE_SYS_TYPES_H
86 #  include <sys/types.h>
87 #endif
88 #ifdef HAVE_NETDB_H
89 #include <netdb.h>
90 #endif
91 #include <signal.h>
92 #ifdef UB_ON_WINDOWS
93 #include "winrc/win_svc.h"
94 #endif
95 
96 /** Size of an UDP datagram */
97 #define NORMAL_UDP_SIZE	512 /* bytes */
98 /** ratelimit for error responses */
99 #define ERROR_RATELIMIT 100 /* qps */
100 
101 /**
102  * seconds to add to prefetch leeway.  This is a TTL that expires old rrsets
103  * earlier than they should in order to put the new update into the cache.
104  * This additional value is to make sure that if not all TTLs are equal in
105  * the message to be updated(and replaced), that rrsets with up to this much
106  * extra TTL are also replaced.  This means that the resulting new message
107  * will have (most likely) this TTL at least, avoiding very small 'split
108  * second' TTLs due to operators choosing relative primes for TTLs (or so).
109  * Also has to be at least one to break ties (and overwrite cached entry).
110  */
111 #define PREFETCH_EXPIRY_ADD 60
112 
113 /** Report on memory usage by this thread and global */
114 static void
115 worker_mem_report(struct worker* ATTR_UNUSED(worker),
116 	struct serviced_query* ATTR_UNUSED(cur_serv))
117 {
118 #ifdef UNBOUND_ALLOC_STATS
119 	/* measure memory leakage */
120 	extern size_t unbound_mem_alloc, unbound_mem_freed;
121 	/* debug func in validator module */
122 	size_t total, front, back, mesh, msg, rrset, infra, ac, superac;
123 	size_t me, iter, val, anch;
124 	int i;
125 #ifdef CLIENT_SUBNET
126 	size_t subnet = 0;
127 #endif /* CLIENT_SUBNET */
128 	if(verbosity < VERB_ALGO)
129 		return;
130 	front = listen_get_mem(worker->front);
131 	back = outnet_get_mem(worker->back);
132 	msg = slabhash_get_mem(worker->env.msg_cache);
133 	rrset = slabhash_get_mem(&worker->env.rrset_cache->table);
134 	infra = infra_get_mem(worker->env.infra_cache);
135 	mesh = mesh_get_mem(worker->env.mesh);
136 	ac = alloc_get_mem(&worker->alloc);
137 	superac = alloc_get_mem(&worker->daemon->superalloc);
138 	anch = anchors_get_mem(worker->env.anchors);
139 	iter = 0;
140 	val = 0;
141 	for(i=0; i<worker->env.mesh->mods.num; i++) {
142 		fptr_ok(fptr_whitelist_mod_get_mem(worker->env.mesh->
143 			mods.mod[i]->get_mem));
144 		if(strcmp(worker->env.mesh->mods.mod[i]->name, "validator")==0)
145 			val += (*worker->env.mesh->mods.mod[i]->get_mem)
146 				(&worker->env, i);
147 #ifdef CLIENT_SUBNET
148 		else if(strcmp(worker->env.mesh->mods.mod[i]->name,
149 			"subnet")==0)
150 			subnet += (*worker->env.mesh->mods.mod[i]->get_mem)
151 				(&worker->env, i);
152 #endif /* CLIENT_SUBNET */
153 		else	iter += (*worker->env.mesh->mods.mod[i]->get_mem)
154 				(&worker->env, i);
155 	}
156 	me = sizeof(*worker) + sizeof(*worker->base) + sizeof(*worker->comsig)
157 		+ comm_point_get_mem(worker->cmd_com)
158 		+ sizeof(worker->rndstate)
159 		+ regional_get_mem(worker->scratchpad)
160 		+ sizeof(*worker->env.scratch_buffer)
161 		+ sldns_buffer_capacity(worker->env.scratch_buffer)
162 		+ forwards_get_mem(worker->env.fwds)
163 		+ hints_get_mem(worker->env.hints);
164 	if(worker->thread_num == 0)
165 		me += acl_list_get_mem(worker->daemon->acl);
166 	if(cur_serv) {
167 		me += serviced_get_mem(cur_serv);
168 	}
169 	total = front+back+mesh+msg+rrset+infra+iter+val+ac+superac+me;
170 #ifdef CLIENT_SUBNET
171 	total += subnet;
172 	log_info("Memory conditions: %u front=%u back=%u mesh=%u msg=%u "
173 		"rrset=%u infra=%u iter=%u val=%u subnet=%u anchors=%u "
174 		"alloccache=%u globalalloccache=%u me=%u",
175 		(unsigned)total, (unsigned)front, (unsigned)back,
176 		(unsigned)mesh, (unsigned)msg, (unsigned)rrset, (unsigned)infra,
177 		(unsigned)iter, (unsigned)val,
178 		(unsigned)subnet, (unsigned)anch, (unsigned)ac,
179 		(unsigned)superac, (unsigned)me);
180 #else /* no CLIENT_SUBNET */
181 	log_info("Memory conditions: %u front=%u back=%u mesh=%u msg=%u "
182 		"rrset=%u infra=%u iter=%u val=%u anchors=%u "
183 		"alloccache=%u globalalloccache=%u me=%u",
184 		(unsigned)total, (unsigned)front, (unsigned)back,
185 		(unsigned)mesh, (unsigned)msg, (unsigned)rrset,
186 		(unsigned)infra, (unsigned)iter, (unsigned)val, (unsigned)anch,
187 		(unsigned)ac, (unsigned)superac, (unsigned)me);
188 #endif /* CLIENT_SUBNET */
189 	log_info("Total heap memory estimate: %u  total-alloc: %u  "
190 		"total-free: %u", (unsigned)total,
191 		(unsigned)unbound_mem_alloc, (unsigned)unbound_mem_freed);
192 #else /* no UNBOUND_ALLOC_STATS */
193 	size_t val = 0;
194 #ifdef CLIENT_SUBNET
195 	size_t subnet = 0;
196 #endif /* CLIENT_SUBNET */
197 	int i;
198 	if(verbosity < VERB_QUERY)
199 		return;
200 	for(i=0; i<worker->env.mesh->mods.num; i++) {
201 		fptr_ok(fptr_whitelist_mod_get_mem(worker->env.mesh->
202 			mods.mod[i]->get_mem));
203 		if(strcmp(worker->env.mesh->mods.mod[i]->name, "validator")==0)
204 			val += (*worker->env.mesh->mods.mod[i]->get_mem)
205 				(&worker->env, i);
206 #ifdef CLIENT_SUBNET
207 		else if(strcmp(worker->env.mesh->mods.mod[i]->name,
208 			"subnet")==0)
209 			subnet += (*worker->env.mesh->mods.mod[i]->get_mem)
210 				(&worker->env, i);
211 #endif /* CLIENT_SUBNET */
212 	}
213 #ifdef CLIENT_SUBNET
214 	verbose(VERB_QUERY, "cache memory msg=%u rrset=%u infra=%u val=%u "
215 		"subnet=%u",
216 		(unsigned)slabhash_get_mem(worker->env.msg_cache),
217 		(unsigned)slabhash_get_mem(&worker->env.rrset_cache->table),
218 		(unsigned)infra_get_mem(worker->env.infra_cache),
219 		(unsigned)val, (unsigned)subnet);
220 #else /* no CLIENT_SUBNET */
221 	verbose(VERB_QUERY, "cache memory msg=%u rrset=%u infra=%u val=%u",
222 		(unsigned)slabhash_get_mem(worker->env.msg_cache),
223 		(unsigned)slabhash_get_mem(&worker->env.rrset_cache->table),
224 		(unsigned)infra_get_mem(worker->env.infra_cache),
225 		(unsigned)val);
226 #endif /* CLIENT_SUBNET */
227 #endif /* UNBOUND_ALLOC_STATS */
228 }
229 
230 void
231 worker_send_cmd(struct worker* worker, enum worker_commands cmd)
232 {
233 	uint32_t c = (uint32_t)htonl(cmd);
234 	if(!tube_write_msg(worker->cmd, (uint8_t*)&c, sizeof(c), 0)) {
235 		log_err("worker send cmd %d failed", (int)cmd);
236 	}
237 }
238 
239 int
240 worker_handle_service_reply(struct comm_point* c, void* arg, int error,
241 	struct comm_reply* reply_info)
242 {
243 	struct outbound_entry* e = (struct outbound_entry*)arg;
244 	struct worker* worker = e->qstate->env->worker;
245 	struct serviced_query *sq = e->qsent;
246 
247 	verbose(VERB_ALGO, "worker svcd callback for qstate %p", e->qstate);
248 	if(error != 0) {
249 		mesh_report_reply(worker->env.mesh, e, reply_info, error);
250 		worker_mem_report(worker, sq);
251 		return 0;
252 	}
253 	/* sanity check. */
254 	if(!LDNS_QR_WIRE(sldns_buffer_begin(c->buffer))
255 		|| LDNS_OPCODE_WIRE(sldns_buffer_begin(c->buffer)) !=
256 			LDNS_PACKET_QUERY
257 		|| LDNS_QDCOUNT(sldns_buffer_begin(c->buffer)) > 1) {
258 		/* error becomes timeout for the module as if this reply
259 		 * never arrived. */
260 		verbose(VERB_ALGO, "worker: bad reply handled as timeout");
261 		mesh_report_reply(worker->env.mesh, e, reply_info,
262 			NETEVENT_TIMEOUT);
263 		worker_mem_report(worker, sq);
264 		return 0;
265 	}
266 	mesh_report_reply(worker->env.mesh, e, reply_info, NETEVENT_NOERROR);
267 	worker_mem_report(worker, sq);
268 	return 0;
269 }
270 
271 /** ratelimit error replies
272  * @param worker: the worker struct with ratelimit counter
273  * @param err: error code that would be wanted.
274  * @return value of err if okay, or -1 if it should be discarded instead.
275  */
276 static int
277 worker_err_ratelimit(struct worker* worker, int err)
278 {
279 	if(worker->err_limit_time == *worker->env.now) {
280 		/* see if limit is exceeded for this second */
281 		if(worker->err_limit_count++ > ERROR_RATELIMIT)
282 			return -1;
283 	} else {
284 		/* new second, new limits */
285 		worker->err_limit_time = *worker->env.now;
286 		worker->err_limit_count = 1;
287 	}
288 	return err;
289 }
290 
291 /** check request sanity.
292  * @param pkt: the wire packet to examine for sanity.
293  * @param worker: parameters for checking.
294  * @return error code, 0 OK, or -1 discard.
295 */
296 static int
297 worker_check_request(sldns_buffer* pkt, struct worker* worker)
298 {
299 	if(sldns_buffer_limit(pkt) < LDNS_HEADER_SIZE) {
300 		verbose(VERB_QUERY, "request too short, discarded");
301 		return -1;
302 	}
303 	if(sldns_buffer_limit(pkt) > NORMAL_UDP_SIZE &&
304 		worker->daemon->cfg->harden_large_queries) {
305 		verbose(VERB_QUERY, "request too large, discarded");
306 		return -1;
307 	}
308 	if(LDNS_QR_WIRE(sldns_buffer_begin(pkt))) {
309 		verbose(VERB_QUERY, "request has QR bit on, discarded");
310 		return -1;
311 	}
312 	if(LDNS_TC_WIRE(sldns_buffer_begin(pkt))) {
313 		LDNS_TC_CLR(sldns_buffer_begin(pkt));
314 		verbose(VERB_QUERY, "request bad, has TC bit on");
315 		return worker_err_ratelimit(worker, LDNS_RCODE_FORMERR);
316 	}
317 	if(LDNS_OPCODE_WIRE(sldns_buffer_begin(pkt)) != LDNS_PACKET_QUERY &&
318 		LDNS_OPCODE_WIRE(sldns_buffer_begin(pkt)) != LDNS_PACKET_NOTIFY) {
319 		verbose(VERB_QUERY, "request unknown opcode %d",
320 			LDNS_OPCODE_WIRE(sldns_buffer_begin(pkt)));
321 		return worker_err_ratelimit(worker, LDNS_RCODE_NOTIMPL);
322 	}
323 	if(LDNS_QDCOUNT(sldns_buffer_begin(pkt)) != 1) {
324 		verbose(VERB_QUERY, "request wrong nr qd=%d",
325 			LDNS_QDCOUNT(sldns_buffer_begin(pkt)));
326 		return worker_err_ratelimit(worker, LDNS_RCODE_FORMERR);
327 	}
328 	if(LDNS_ANCOUNT(sldns_buffer_begin(pkt)) != 0 &&
329 		(LDNS_ANCOUNT(sldns_buffer_begin(pkt)) != 1 ||
330 		LDNS_OPCODE_WIRE(sldns_buffer_begin(pkt)) != LDNS_PACKET_NOTIFY)) {
331 		verbose(VERB_QUERY, "request wrong nr an=%d",
332 			LDNS_ANCOUNT(sldns_buffer_begin(pkt)));
333 		return worker_err_ratelimit(worker, LDNS_RCODE_FORMERR);
334 	}
335 	if(LDNS_NSCOUNT(sldns_buffer_begin(pkt)) != 0) {
336 		verbose(VERB_QUERY, "request wrong nr ns=%d",
337 			LDNS_NSCOUNT(sldns_buffer_begin(pkt)));
338 		return worker_err_ratelimit(worker, LDNS_RCODE_FORMERR);
339 	}
340 	if(LDNS_ARCOUNT(sldns_buffer_begin(pkt)) > 1) {
341 		verbose(VERB_QUERY, "request wrong nr ar=%d",
342 			LDNS_ARCOUNT(sldns_buffer_begin(pkt)));
343 		return worker_err_ratelimit(worker, LDNS_RCODE_FORMERR);
344 	}
345 	return 0;
346 }
347 
348 void
349 worker_handle_control_cmd(struct tube* ATTR_UNUSED(tube), uint8_t* msg,
350 	size_t len, int error, void* arg)
351 {
352 	struct worker* worker = (struct worker*)arg;
353 	enum worker_commands cmd;
354 	if(error != NETEVENT_NOERROR) {
355 		free(msg);
356 		if(error == NETEVENT_CLOSED)
357 			comm_base_exit(worker->base);
358 		else	log_info("control event: %d", error);
359 		return;
360 	}
361 	if(len != sizeof(uint32_t)) {
362 		fatal_exit("bad control msg length %d", (int)len);
363 	}
364 	cmd = sldns_read_uint32(msg);
365 	free(msg);
366 	switch(cmd) {
367 	case worker_cmd_quit:
368 		verbose(VERB_ALGO, "got control cmd quit");
369 		comm_base_exit(worker->base);
370 		break;
371 	case worker_cmd_stats:
372 		verbose(VERB_ALGO, "got control cmd stats");
373 		server_stats_reply(worker, 1);
374 		break;
375 	case worker_cmd_stats_noreset:
376 		verbose(VERB_ALGO, "got control cmd stats_noreset");
377 		server_stats_reply(worker, 0);
378 		break;
379 	case worker_cmd_remote:
380 		verbose(VERB_ALGO, "got control cmd remote");
381 		daemon_remote_exec(worker);
382 		break;
383 	default:
384 		log_err("bad command %d", (int)cmd);
385 		break;
386 	}
387 }
388 
389 /** check if a delegation is secure */
390 static enum sec_status
391 check_delegation_secure(struct reply_info *rep)
392 {
393 	/* return smallest security status */
394 	size_t i;
395 	enum sec_status sec = sec_status_secure;
396 	enum sec_status s;
397 	size_t num = rep->an_numrrsets + rep->ns_numrrsets;
398 	/* check if answer and authority are OK */
399 	for(i=0; i<num; i++) {
400 		s = ((struct packed_rrset_data*)rep->rrsets[i]->entry.data)
401 			->security;
402 		if(s < sec)
403 			sec = s;
404 	}
405 	/* in additional, only unchecked triggers revalidation */
406 	for(i=num; i<rep->rrset_count; i++) {
407 		s = ((struct packed_rrset_data*)rep->rrsets[i]->entry.data)
408 			->security;
409 		if(s == sec_status_unchecked)
410 			return s;
411 	}
412 	return sec;
413 }
414 
415 /** remove nonsecure from a delegation referral additional section */
416 static void
417 deleg_remove_nonsecure_additional(struct reply_info* rep)
418 {
419 	/* we can simply edit it, since we are working in the scratch region */
420 	size_t i;
421 	enum sec_status s;
422 
423 	for(i = rep->an_numrrsets+rep->ns_numrrsets; i<rep->rrset_count; i++) {
424 		s = ((struct packed_rrset_data*)rep->rrsets[i]->entry.data)
425 			->security;
426 		if(s != sec_status_secure) {
427 			memmove(rep->rrsets+i, rep->rrsets+i+1,
428 				sizeof(struct ub_packed_rrset_key*)*
429 				(rep->rrset_count - i - 1));
430 			rep->ar_numrrsets--;
431 			rep->rrset_count--;
432 			i--;
433 		}
434 	}
435 }
436 
437 /** answer nonrecursive query from the cache */
438 static int
439 answer_norec_from_cache(struct worker* worker, struct query_info* qinfo,
440 	uint16_t id, uint16_t flags, struct comm_reply* repinfo,
441 	struct edns_data* edns)
442 {
443 	/* for a nonrecursive query return either:
444 	 * 	o an error (servfail; we try to avoid this)
445 	 * 	o a delegation (closest we have; this routine tries that)
446 	 * 	o the answer (checked by answer_from_cache)
447 	 *
448 	 * So, grab a delegation from the rrset cache.
449 	 * Then check if it needs validation, if so, this routine fails,
450 	 * so that iterator can prime and validator can verify rrsets.
451 	 */
452 	struct edns_data edns_bak;
453 	uint16_t udpsize = edns->udp_size;
454 	int secure = 0;
455 	time_t timenow = *worker->env.now;
456 	int must_validate = (!(flags&BIT_CD) || worker->env.cfg->ignore_cd)
457 		&& worker->env.need_to_validate;
458 	struct dns_msg *msg = NULL;
459 	struct delegpt *dp;
460 
461 	dp = dns_cache_find_delegation(&worker->env, qinfo->qname,
462 		qinfo->qname_len, qinfo->qtype, qinfo->qclass,
463 		worker->scratchpad, &msg, timenow);
464 	if(!dp) { /* no delegation, need to reprime */
465 		return 0;
466 	}
467 	/* In case we have a local alias, copy it into the delegation message.
468 	 * Shallow copy should be fine, as we'll be done with msg in this
469 	 * function. */
470 	msg->qinfo.local_alias = qinfo->local_alias;
471 	if(must_validate) {
472 		switch(check_delegation_secure(msg->rep)) {
473 		case sec_status_unchecked:
474 			/* some rrsets have not been verified yet, go and
475 			 * let validator do that */
476 			return 0;
477 		case sec_status_bogus:
478 		case sec_status_secure_sentinel_fail:
479 			/* some rrsets are bogus, reply servfail */
480 			edns->edns_version = EDNS_ADVERTISED_VERSION;
481 			edns->udp_size = EDNS_ADVERTISED_SIZE;
482 			edns->ext_rcode = 0;
483 			edns->bits &= EDNS_DO;
484 			if(!inplace_cb_reply_servfail_call(&worker->env, qinfo, NULL,
485 				msg->rep, LDNS_RCODE_SERVFAIL, edns, repinfo, worker->scratchpad,
486 				worker->env.now_tv))
487 					return 0;
488 			error_encode(repinfo->c->buffer, LDNS_RCODE_SERVFAIL,
489 				&msg->qinfo, id, flags, edns);
490 			if(worker->stats.extended) {
491 				worker->stats.ans_bogus++;
492 				worker->stats.ans_rcode[LDNS_RCODE_SERVFAIL]++;
493 			}
494 			return 1;
495 		case sec_status_secure:
496 			/* all rrsets are secure */
497 			/* remove non-secure rrsets from the add. section*/
498 			if(worker->env.cfg->val_clean_additional)
499 				deleg_remove_nonsecure_additional(msg->rep);
500 			secure = 1;
501 			break;
502 		case sec_status_indeterminate:
503 		case sec_status_insecure:
504 		default:
505 			/* not secure */
506 			secure = 0;
507 			break;
508 		}
509 	}
510 	/* return this delegation from the cache */
511 	edns_bak = *edns;
512 	edns->edns_version = EDNS_ADVERTISED_VERSION;
513 	edns->udp_size = EDNS_ADVERTISED_SIZE;
514 	edns->ext_rcode = 0;
515 	edns->bits &= EDNS_DO;
516 	if(!inplace_cb_reply_cache_call(&worker->env, qinfo, NULL, msg->rep,
517 		(int)(flags&LDNS_RCODE_MASK), edns, repinfo, worker->scratchpad,
518 		worker->env.now_tv))
519 			return 0;
520 	msg->rep->flags |= BIT_QR|BIT_RA;
521 	if(!apply_edns_options(edns, &edns_bak, worker->env.cfg,
522 		repinfo->c, worker->scratchpad) ||
523 		!reply_info_answer_encode(&msg->qinfo, msg->rep, id, flags,
524 		repinfo->c->buffer, 0, 1, worker->scratchpad,
525 		udpsize, edns, (int)(edns->bits & EDNS_DO), secure)) {
526 		if(!inplace_cb_reply_servfail_call(&worker->env, qinfo, NULL, NULL,
527 			LDNS_RCODE_SERVFAIL, edns, repinfo, worker->scratchpad,
528 			worker->env.now_tv))
529 				edns->opt_list = NULL;
530 		error_encode(repinfo->c->buffer, LDNS_RCODE_SERVFAIL,
531 			&msg->qinfo, id, flags, edns);
532 	}
533 	if(worker->stats.extended) {
534 		if(secure) worker->stats.ans_secure++;
535 		server_stats_insrcode(&worker->stats, repinfo->c->buffer);
536 	}
537 	return 1;
538 }
539 
540 /** Apply, if applicable, a response IP action to a cached answer.
541  * If the answer is rewritten as a result of an action, '*encode_repp' will
542  * point to the reply info containing the modified answer.  '*encode_repp' will
543  * be intact otherwise.
544  * It returns 1 on success, 0 otherwise. */
545 static int
546 apply_respip_action(struct worker* worker, const struct query_info* qinfo,
547 	struct respip_client_info* cinfo, struct reply_info* rep,
548 	struct comm_reply* repinfo, struct ub_packed_rrset_key** alias_rrset,
549 	struct reply_info** encode_repp, struct auth_zones* az)
550 {
551 	struct respip_action_info actinfo = {0, 0, 0, 0, NULL, 0, NULL};
552 	actinfo.action = respip_none;
553 
554 	if(qinfo->qtype != LDNS_RR_TYPE_A &&
555 		qinfo->qtype != LDNS_RR_TYPE_AAAA &&
556 		qinfo->qtype != LDNS_RR_TYPE_ANY)
557 		return 1;
558 
559 	if(!respip_rewrite_reply(qinfo, cinfo, rep, encode_repp, &actinfo,
560 		alias_rrset, 0, worker->scratchpad, az))
561 		return 0;
562 
563 	/* xxx_deny actions mean dropping the reply, unless the original reply
564 	 * was redirected to response-ip data. */
565 	if((actinfo.action == respip_deny ||
566 		actinfo.action == respip_inform_deny) &&
567 		*encode_repp == rep)
568 		*encode_repp = NULL;
569 
570 	/* If address info is returned, it means the action should be an
571 	 * 'inform' variant and the information should be logged. */
572 	if(actinfo.addrinfo) {
573 		respip_inform_print(&actinfo, qinfo->qname,
574 			qinfo->qtype, qinfo->qclass, qinfo->local_alias,
575 			repinfo);
576 
577 		if(worker->stats.extended && actinfo.rpz_used) {
578 			if(actinfo.rpz_disabled)
579 				worker->stats.rpz_action[RPZ_DISABLED_ACTION]++;
580 			if(actinfo.rpz_cname_override)
581 				worker->stats.rpz_action[RPZ_CNAME_OVERRIDE_ACTION]++;
582 			else
583 				worker->stats.rpz_action[
584 					respip_action_to_rpz_action(actinfo.action)]++;
585 		}
586 	}
587 
588 	return 1;
589 }
590 
591 /** answer query from the cache.
592  * Normally, the answer message will be built in repinfo->c->buffer; if the
593  * answer is supposed to be suppressed or the answer is supposed to be an
594  * incomplete CNAME chain, the buffer is explicitly cleared to signal the
595  * caller as such.  In the latter case *partial_rep will point to the incomplete
596  * reply, and this function is (possibly) supposed to be called again with that
597  * *partial_rep value to complete the chain.  In addition, if the query should
598  * be completely dropped, '*need_drop' will be set to 1. */
599 static int
600 answer_from_cache(struct worker* worker, struct query_info* qinfo,
601 	struct respip_client_info* cinfo, int* need_drop, int* is_expired_answer,
602 	int* is_secure_answer, struct ub_packed_rrset_key** alias_rrset,
603 	struct reply_info** partial_repp,
604 	struct reply_info* rep, uint16_t id, uint16_t flags,
605 	struct comm_reply* repinfo, struct edns_data* edns)
606 {
607 	struct edns_data edns_bak;
608 	time_t timenow = *worker->env.now;
609 	uint16_t udpsize = edns->udp_size;
610 	struct reply_info* encode_rep = rep;
611 	struct reply_info* partial_rep = *partial_repp;
612 	int must_validate = (!(flags&BIT_CD) || worker->env.cfg->ignore_cd)
613 		&& worker->env.need_to_validate;
614 	*partial_repp = NULL;  /* avoid accidental further pass */
615 
616 	/* Check TTL */
617 	if(rep->ttl < timenow) {
618 		/* Check if we need to serve expired now */
619 		if(worker->env.cfg->serve_expired &&
620 			!worker->env.cfg->serve_expired_client_timeout) {
621 				if(worker->env.cfg->serve_expired_ttl &&
622 					rep->serve_expired_ttl < timenow)
623 					return 0;
624 				if(!rrset_array_lock(rep->ref, rep->rrset_count, 0))
625 					return 0;
626 				*is_expired_answer = 1;
627 		} else {
628 			/* the rrsets may have been updated in the meantime.
629 			 * we will refetch the message format from the
630 			 * authoritative server
631 			 */
632 			return 0;
633 		}
634 	} else {
635 		if(!rrset_array_lock(rep->ref, rep->rrset_count, timenow))
636 			return 0;
637 	}
638 	/* locked and ids and ttls are OK. */
639 
640 	/* check CNAME chain (if any) */
641 	if(rep->an_numrrsets > 0 && (rep->rrsets[0]->rk.type ==
642 		htons(LDNS_RR_TYPE_CNAME) || rep->rrsets[0]->rk.type ==
643 		htons(LDNS_RR_TYPE_DNAME))) {
644 		if(!reply_check_cname_chain(qinfo, rep)) {
645 			/* cname chain invalid, redo iterator steps */
646 			verbose(VERB_ALGO, "Cache reply: cname chain broken");
647 			goto bail_out;
648 		}
649 	}
650 	/* check security status of the cached answer */
651 	if(must_validate && (rep->security == sec_status_bogus ||
652 		rep->security == sec_status_secure_sentinel_fail)) {
653 		/* BAD cached */
654 		edns->edns_version = EDNS_ADVERTISED_VERSION;
655 		edns->udp_size = EDNS_ADVERTISED_SIZE;
656 		edns->ext_rcode = 0;
657 		edns->bits &= EDNS_DO;
658 		if(!inplace_cb_reply_servfail_call(&worker->env, qinfo, NULL, rep,
659 			LDNS_RCODE_SERVFAIL, edns, repinfo, worker->scratchpad,
660 			worker->env.now_tv))
661 			goto bail_out;
662 		error_encode(repinfo->c->buffer, LDNS_RCODE_SERVFAIL,
663 			qinfo, id, flags, edns);
664 		rrset_array_unlock_touch(worker->env.rrset_cache,
665 			worker->scratchpad, rep->ref, rep->rrset_count);
666 		if(worker->stats.extended) {
667 			worker->stats.ans_bogus ++;
668 			worker->stats.ans_rcode[LDNS_RCODE_SERVFAIL] ++;
669 		}
670 		return 1;
671 	} else if(rep->security == sec_status_unchecked && must_validate) {
672 		verbose(VERB_ALGO, "Cache reply: unchecked entry needs "
673 			"validation");
674 		goto bail_out; /* need to validate cache entry first */
675 	} else if(rep->security == sec_status_secure) {
676 		if(reply_all_rrsets_secure(rep)) {
677 			*is_secure_answer = 1;
678 		} else {
679 			if(must_validate) {
680 				verbose(VERB_ALGO, "Cache reply: secure entry"
681 					" changed status");
682 				goto bail_out; /* rrset changed, re-verify */
683 			}
684 			*is_secure_answer = 0;
685 		}
686 	} else *is_secure_answer = 0;
687 
688 	edns_bak = *edns;
689 	edns->edns_version = EDNS_ADVERTISED_VERSION;
690 	edns->udp_size = EDNS_ADVERTISED_SIZE;
691 	edns->ext_rcode = 0;
692 	edns->bits &= EDNS_DO;
693 	if(!inplace_cb_reply_cache_call(&worker->env, qinfo, NULL, rep,
694 		(int)(flags&LDNS_RCODE_MASK), edns, repinfo, worker->scratchpad,
695 		worker->env.now_tv))
696 		goto bail_out;
697 	*alias_rrset = NULL; /* avoid confusion if caller set it to non-NULL */
698 	if((worker->daemon->use_response_ip || worker->daemon->use_rpz) &&
699 		!partial_rep && !apply_respip_action(worker, qinfo, cinfo, rep,
700 		repinfo, alias_rrset,
701 		&encode_rep, worker->env.auth_zones)) {
702 		goto bail_out;
703 	} else if(partial_rep &&
704 		!respip_merge_cname(partial_rep, qinfo, rep, cinfo,
705 		must_validate, &encode_rep, worker->scratchpad,
706 		worker->env.auth_zones)) {
707 		goto bail_out;
708 	}
709 	if(encode_rep != rep) {
710 		/* if rewritten, it can't be considered "secure" */
711 		*is_secure_answer = 0;
712 	}
713 	if(!encode_rep || *alias_rrset) {
714 		if(!encode_rep)
715 			*need_drop = 1;
716 		else {
717 			/* If a partial CNAME chain is found, we first need to
718 			 * make a copy of the reply in the scratchpad so we
719 			 * can release the locks and lookup the cache again. */
720 			*partial_repp = reply_info_copy(encode_rep, NULL,
721 				worker->scratchpad);
722 			if(!*partial_repp)
723 				goto bail_out;
724 		}
725 	} else if(!apply_edns_options(edns, &edns_bak, worker->env.cfg,
726 		repinfo->c, worker->scratchpad) ||
727 		!reply_info_answer_encode(qinfo, encode_rep, id, flags,
728 		repinfo->c->buffer, timenow, 1, worker->scratchpad,
729 		udpsize, edns, (int)(edns->bits & EDNS_DO), *is_secure_answer)) {
730 		if(!inplace_cb_reply_servfail_call(&worker->env, qinfo, NULL, NULL,
731 			LDNS_RCODE_SERVFAIL, edns, repinfo, worker->scratchpad,
732 			worker->env.now_tv))
733 				edns->opt_list = NULL;
734 		error_encode(repinfo->c->buffer, LDNS_RCODE_SERVFAIL,
735 			qinfo, id, flags, edns);
736 	}
737 	/* cannot send the reply right now, because blocking network syscall
738 	 * is bad while holding locks. */
739 	rrset_array_unlock_touch(worker->env.rrset_cache, worker->scratchpad,
740 		rep->ref, rep->rrset_count);
741 	/* go and return this buffer to the client */
742 	return 1;
743 
744 bail_out:
745 	rrset_array_unlock_touch(worker->env.rrset_cache,
746 		worker->scratchpad, rep->ref, rep->rrset_count);
747 	return 0;
748 }
749 
750 /** Reply to client and perform prefetch to keep cache up to date. */
751 static void
752 reply_and_prefetch(struct worker* worker, struct query_info* qinfo,
753 	uint16_t flags, struct comm_reply* repinfo, time_t leeway, int noreply)
754 {
755 	/* first send answer to client to keep its latency
756 	 * as small as a cachereply */
757 	if(!noreply) {
758 		if(repinfo->c->tcp_req_info) {
759 			sldns_buffer_copy(
760 				repinfo->c->tcp_req_info->spool_buffer,
761 				repinfo->c->buffer);
762 		}
763 		comm_point_send_reply(repinfo);
764 	}
765 	server_stats_prefetch(&worker->stats, worker);
766 
767 	/* create the prefetch in the mesh as a normal lookup without
768 	 * client addrs waiting, which has the cache blacklisted (to bypass
769 	 * the cache and go to the network for the data). */
770 	/* this (potentially) runs the mesh for the new query */
771 	mesh_new_prefetch(worker->env.mesh, qinfo, flags, leeway +
772 		PREFETCH_EXPIRY_ADD);
773 }
774 
775 /**
776  * Fill CH class answer into buffer. Keeps query.
777  * @param pkt: buffer
778  * @param str: string to put into text record (<255).
779  * 	array of strings, every string becomes a text record.
780  * @param num: number of strings in array.
781  * @param edns: edns reply information.
782  * @param worker: worker with scratch region.
783  * @param repinfo: reply information for a communication point.
784  */
785 static void
786 chaos_replystr(sldns_buffer* pkt, char** str, int num, struct edns_data* edns,
787 	struct worker* worker, struct comm_reply* repinfo)
788 {
789 	int i;
790 	unsigned int rd = LDNS_RD_WIRE(sldns_buffer_begin(pkt));
791 	unsigned int cd = LDNS_CD_WIRE(sldns_buffer_begin(pkt));
792 	sldns_buffer_clear(pkt);
793 	sldns_buffer_skip(pkt, (ssize_t)sizeof(uint16_t)); /* skip id */
794 	sldns_buffer_write_u16(pkt, (uint16_t)(BIT_QR|BIT_RA));
795 	if(rd) LDNS_RD_SET(sldns_buffer_begin(pkt));
796 	if(cd) LDNS_CD_SET(sldns_buffer_begin(pkt));
797 	sldns_buffer_write_u16(pkt, 1); /* qdcount */
798 	sldns_buffer_write_u16(pkt, (uint16_t)num); /* ancount */
799 	sldns_buffer_write_u16(pkt, 0); /* nscount */
800 	sldns_buffer_write_u16(pkt, 0); /* arcount */
801 	(void)query_dname_len(pkt); /* skip qname */
802 	sldns_buffer_skip(pkt, (ssize_t)sizeof(uint16_t)); /* skip qtype */
803 	sldns_buffer_skip(pkt, (ssize_t)sizeof(uint16_t)); /* skip qclass */
804 	for(i=0; i<num; i++) {
805 		size_t len = strlen(str[i]);
806 		if(len>255) len=255; /* cap size of TXT record */
807 		sldns_buffer_write_u16(pkt, 0xc00c); /* compr ptr to query */
808 		sldns_buffer_write_u16(pkt, LDNS_RR_TYPE_TXT);
809 		sldns_buffer_write_u16(pkt, LDNS_RR_CLASS_CH);
810 		sldns_buffer_write_u32(pkt, 0); /* TTL */
811 		sldns_buffer_write_u16(pkt, sizeof(uint8_t) + len);
812 		sldns_buffer_write_u8(pkt, len);
813 		sldns_buffer_write(pkt, str[i], len);
814 	}
815 	sldns_buffer_flip(pkt);
816 	edns->edns_version = EDNS_ADVERTISED_VERSION;
817 	edns->udp_size = EDNS_ADVERTISED_SIZE;
818 	edns->bits &= EDNS_DO;
819 	if(!inplace_cb_reply_local_call(&worker->env, NULL, NULL, NULL,
820 		LDNS_RCODE_NOERROR, edns, repinfo, worker->scratchpad,
821 		worker->env.now_tv))
822 			edns->opt_list = NULL;
823 	if(sldns_buffer_capacity(pkt) >=
824 		sldns_buffer_limit(pkt)+calc_edns_field_size(edns))
825 		attach_edns_record(pkt, edns);
826 }
827 
828 /** Reply with one string */
829 static void
830 chaos_replyonestr(sldns_buffer* pkt, const char* str, struct edns_data* edns,
831 	struct worker* worker, struct comm_reply* repinfo)
832 {
833 	chaos_replystr(pkt, (char**)&str, 1, edns, worker, repinfo);
834 }
835 
836 /**
837  * Create CH class trustanchor answer.
838  * @param pkt: buffer
839  * @param edns: edns reply information.
840  * @param w: worker with scratch region.
841  * @param repinfo: reply information for a communication point.
842  */
843 static void
844 chaos_trustanchor(sldns_buffer* pkt, struct edns_data* edns, struct worker* w,
845 	struct comm_reply* repinfo)
846 {
847 #define TA_RESPONSE_MAX_TXT 16 /* max number of TXT records */
848 #define TA_RESPONSE_MAX_TAGS 32 /* max number of tags printed per zone */
849 	char* str_array[TA_RESPONSE_MAX_TXT];
850 	uint16_t tags[TA_RESPONSE_MAX_TAGS];
851 	int num = 0;
852 	struct trust_anchor* ta;
853 
854 	if(!w->env.need_to_validate) {
855 		/* no validator module, reply no trustanchors */
856 		chaos_replystr(pkt, NULL, 0, edns, w, repinfo);
857 		return;
858 	}
859 
860 	/* fill the string with contents */
861 	lock_basic_lock(&w->env.anchors->lock);
862 	RBTREE_FOR(ta, struct trust_anchor*, w->env.anchors->tree) {
863 		char* str;
864 		size_t i, numtag, str_len = 255;
865 		if(num == TA_RESPONSE_MAX_TXT) continue;
866 		str = (char*)regional_alloc(w->scratchpad, str_len);
867 		if(!str) continue;
868 		lock_basic_lock(&ta->lock);
869 		numtag = anchor_list_keytags(ta, tags, TA_RESPONSE_MAX_TAGS);
870 		if(numtag == 0) {
871 			/* empty, insecure point */
872 			lock_basic_unlock(&ta->lock);
873 			continue;
874 		}
875 		str_array[num] = str;
876 		num++;
877 
878 		/* spool name of anchor */
879 		(void)sldns_wire2str_dname_buf(ta->name, ta->namelen, str, str_len);
880 		str_len -= strlen(str); str += strlen(str);
881 		/* spool tags */
882 		for(i=0; i<numtag; i++) {
883 			snprintf(str, str_len, " %u", (unsigned)tags[i]);
884 			str_len -= strlen(str); str += strlen(str);
885 		}
886 		lock_basic_unlock(&ta->lock);
887 	}
888 	lock_basic_unlock(&w->env.anchors->lock);
889 
890 	chaos_replystr(pkt, str_array, num, edns, w, repinfo);
891 	regional_free_all(w->scratchpad);
892 }
893 
894 /**
895  * Answer CH class queries.
896  * @param w: worker
897  * @param qinfo: query info. Pointer into packet buffer.
898  * @param edns: edns info from query.
899  * @param repinfo: reply information for a communication point.
900  * @param pkt: packet buffer.
901  * @return: true if a reply is to be sent.
902  */
903 static int
904 answer_chaos(struct worker* w, struct query_info* qinfo,
905 	struct edns_data* edns, struct comm_reply* repinfo, sldns_buffer* pkt)
906 {
907 	struct config_file* cfg = w->env.cfg;
908 	if(qinfo->qtype != LDNS_RR_TYPE_ANY && qinfo->qtype != LDNS_RR_TYPE_TXT)
909 		return 0;
910 	if(query_dname_compare(qinfo->qname,
911 		(uint8_t*)"\002id\006server") == 0 ||
912 		query_dname_compare(qinfo->qname,
913 		(uint8_t*)"\010hostname\004bind") == 0)
914 	{
915 		if(cfg->hide_identity)
916 			return 0;
917 		if(cfg->identity==NULL || cfg->identity[0]==0) {
918 			char buf[MAXHOSTNAMELEN+1];
919 			if (gethostname(buf, MAXHOSTNAMELEN) == 0) {
920 				buf[MAXHOSTNAMELEN] = 0;
921 				chaos_replyonestr(pkt, buf, edns, w, repinfo);
922 			} else 	{
923 				log_err("gethostname: %s", strerror(errno));
924 				chaos_replyonestr(pkt, "no hostname", edns, w, repinfo);
925 			}
926 		}
927 		else 	chaos_replyonestr(pkt, cfg->identity, edns, w, repinfo);
928 		return 1;
929 	}
930 	if(query_dname_compare(qinfo->qname,
931 		(uint8_t*)"\007version\006server") == 0 ||
932 		query_dname_compare(qinfo->qname,
933 		(uint8_t*)"\007version\004bind") == 0)
934 	{
935 		if(cfg->hide_version)
936 			return 0;
937 		if(cfg->version==NULL || cfg->version[0]==0)
938 			chaos_replyonestr(pkt, PACKAGE_STRING, edns, w, repinfo);
939 		else 	chaos_replyonestr(pkt, cfg->version, edns, w, repinfo);
940 		return 1;
941 	}
942 	if(query_dname_compare(qinfo->qname,
943 		(uint8_t*)"\013trustanchor\007unbound") == 0)
944 	{
945 		if(cfg->hide_trustanchor)
946 			return 0;
947 		chaos_trustanchor(pkt, edns, w, repinfo);
948 		return 1;
949 	}
950 
951 	return 0;
952 }
953 
954 /**
955  * Answer notify queries.  These are notifies for authoritative zones,
956  * the reply is an ack that the notify has been received.  We need to check
957  * access permission here.
958  * @param w: worker
959  * @param qinfo: query info. Pointer into packet buffer.
960  * @param edns: edns info from query.
961  * @param repinfo: reply info with source address.
962  * @param pkt: packet buffer.
963  */
964 static void
965 answer_notify(struct worker* w, struct query_info* qinfo,
966 	struct edns_data* edns, sldns_buffer* pkt, struct comm_reply* repinfo)
967 {
968 	int refused = 0;
969 	int rcode = LDNS_RCODE_NOERROR;
970 	uint32_t serial = 0;
971 	int has_serial;
972 	if(!w->env.auth_zones) return;
973 	has_serial = auth_zone_parse_notify_serial(pkt, &serial);
974 	if(auth_zones_notify(w->env.auth_zones, &w->env, qinfo->qname,
975 		qinfo->qname_len, qinfo->qclass, &repinfo->addr,
976 		repinfo->addrlen, has_serial, serial, &refused)) {
977 		rcode = LDNS_RCODE_NOERROR;
978 	} else {
979 		if(refused)
980 			rcode = LDNS_RCODE_REFUSED;
981 		else	rcode = LDNS_RCODE_SERVFAIL;
982 	}
983 
984 	if(verbosity >= VERB_DETAIL) {
985 		char buf[380];
986 		char zname[255+1];
987 		char sr[25];
988 		dname_str(qinfo->qname, zname);
989 		sr[0]=0;
990 		if(has_serial)
991 			snprintf(sr, sizeof(sr), "serial %u ",
992 				(unsigned)serial);
993 		if(rcode == LDNS_RCODE_REFUSED)
994 			snprintf(buf, sizeof(buf),
995 				"refused NOTIFY %sfor %s from", sr, zname);
996 		else if(rcode == LDNS_RCODE_SERVFAIL)
997 			snprintf(buf, sizeof(buf),
998 				"servfail for NOTIFY %sfor %s from", sr, zname);
999 		else	snprintf(buf, sizeof(buf),
1000 				"received NOTIFY %sfor %s from", sr, zname);
1001 		log_addr(VERB_DETAIL, buf, &repinfo->addr, repinfo->addrlen);
1002 	}
1003 	edns->edns_version = EDNS_ADVERTISED_VERSION;
1004 	edns->udp_size = EDNS_ADVERTISED_SIZE;
1005 	edns->ext_rcode = 0;
1006 	edns->bits &= EDNS_DO;
1007 	edns->opt_list = NULL;
1008 	error_encode(pkt, rcode, qinfo,
1009 		*(uint16_t*)(void *)sldns_buffer_begin(pkt),
1010 		sldns_buffer_read_u16_at(pkt, 2), edns);
1011 	LDNS_OPCODE_SET(sldns_buffer_begin(pkt), LDNS_PACKET_NOTIFY);
1012 }
1013 
1014 static int
1015 deny_refuse(struct comm_point* c, enum acl_access acl,
1016 	enum acl_access deny, enum acl_access refuse,
1017 	struct worker* worker, struct comm_reply* repinfo)
1018 {
1019 	if(acl == deny) {
1020 		comm_point_drop_reply(repinfo);
1021 		if(worker->stats.extended)
1022 			worker->stats.unwanted_queries++;
1023 		return 0;
1024 	} else if(acl == refuse) {
1025 		log_addr(VERB_ALGO, "refused query from",
1026 			&repinfo->addr, repinfo->addrlen);
1027 		log_buf(VERB_ALGO, "refuse", c->buffer);
1028 		if(worker->stats.extended)
1029 			worker->stats.unwanted_queries++;
1030 		if(worker_check_request(c->buffer, worker) == -1) {
1031 			comm_point_drop_reply(repinfo);
1032 			return 0; /* discard this */
1033 		}
1034 		sldns_buffer_set_limit(c->buffer, LDNS_HEADER_SIZE);
1035 		sldns_buffer_write_at(c->buffer, 4,
1036 			(uint8_t*)"\0\0\0\0\0\0\0\0", 8);
1037 		LDNS_QR_SET(sldns_buffer_begin(c->buffer));
1038 		LDNS_RCODE_SET(sldns_buffer_begin(c->buffer),
1039 			LDNS_RCODE_REFUSED);
1040 		sldns_buffer_set_position(c->buffer, LDNS_HEADER_SIZE);
1041 		sldns_buffer_flip(c->buffer);
1042 		return 1;
1043 	}
1044 
1045 	return -1;
1046 }
1047 
1048 static int
1049 deny_refuse_all(struct comm_point* c, enum acl_access acl,
1050 	struct worker* worker, struct comm_reply* repinfo)
1051 {
1052 	return deny_refuse(c, acl, acl_deny, acl_refuse, worker, repinfo);
1053 }
1054 
1055 static int
1056 deny_refuse_non_local(struct comm_point* c, enum acl_access acl,
1057 	struct worker* worker, struct comm_reply* repinfo)
1058 {
1059 	return deny_refuse(c, acl, acl_deny_non_local, acl_refuse_non_local, worker, repinfo);
1060 }
1061 
1062 int
1063 worker_handle_request(struct comm_point* c, void* arg, int error,
1064 	struct comm_reply* repinfo)
1065 {
1066 	struct worker* worker = (struct worker*)arg;
1067 	int ret;
1068 	hashvalue_type h;
1069 	struct lruhash_entry* e;
1070 	struct query_info qinfo;
1071 	struct edns_data edns;
1072 	enum acl_access acl;
1073 	struct acl_addr* acladdr;
1074 	int rc = 0;
1075 	int need_drop = 0;
1076 	int is_expired_answer = 0;
1077 	int is_secure_answer = 0;
1078 	/* We might have to chase a CNAME chain internally, in which case
1079 	 * we'll have up to two replies and combine them to build a complete
1080 	 * answer.  These variables control this case. */
1081 	struct ub_packed_rrset_key* alias_rrset = NULL;
1082 	struct reply_info* partial_rep = NULL;
1083 	struct query_info* lookup_qinfo = &qinfo;
1084 	struct query_info qinfo_tmp; /* placeholder for lookup_qinfo */
1085 	struct respip_client_info* cinfo = NULL, cinfo_tmp;
1086 	memset(&qinfo, 0, sizeof(qinfo));
1087 
1088 	if((error != NETEVENT_NOERROR && error != NETEVENT_DONE)|| !repinfo) {
1089 		/* some bad tcp query DNS formats give these error calls */
1090 		verbose(VERB_ALGO, "handle request called with err=%d", error);
1091 		return 0;
1092 	}
1093 #ifdef USE_DNSCRYPT
1094 	repinfo->max_udp_size = worker->daemon->cfg->max_udp_size;
1095 	if(!dnsc_handle_curved_request(worker->daemon->dnscenv, repinfo)) {
1096 		worker->stats.num_query_dnscrypt_crypted_malformed++;
1097 		return 0;
1098 	}
1099 	if(c->dnscrypt && !repinfo->is_dnscrypted) {
1100 		char buf[LDNS_MAX_DOMAINLEN+1];
1101 		/* Check if this is unencrypted and asking for certs */
1102 		if(worker_check_request(c->buffer, worker) != 0) {
1103 			verbose(VERB_ALGO,
1104 				"dnscrypt: worker check request: bad query.");
1105 			log_addr(VERB_CLIENT,"from",&repinfo->addr,
1106 				repinfo->addrlen);
1107 			comm_point_drop_reply(repinfo);
1108 			return 0;
1109 		}
1110 		if(!query_info_parse(&qinfo, c->buffer)) {
1111 			verbose(VERB_ALGO,
1112 				"dnscrypt: worker parse request: formerror.");
1113 			log_addr(VERB_CLIENT, "from", &repinfo->addr,
1114 				repinfo->addrlen);
1115 			comm_point_drop_reply(repinfo);
1116 			return 0;
1117 		}
1118 		dname_str(qinfo.qname, buf);
1119 		if(!(qinfo.qtype == LDNS_RR_TYPE_TXT &&
1120 			strcasecmp(buf,
1121 			worker->daemon->dnscenv->provider_name) == 0)) {
1122 			verbose(VERB_ALGO,
1123 				"dnscrypt: not TXT \"%s\". Received: %s \"%s\"",
1124 				worker->daemon->dnscenv->provider_name,
1125 				sldns_rr_descript(qinfo.qtype)->_name,
1126 				buf);
1127 			comm_point_drop_reply(repinfo);
1128 			worker->stats.num_query_dnscrypt_cleartext++;
1129 			return 0;
1130 		}
1131 		worker->stats.num_query_dnscrypt_cert++;
1132 		sldns_buffer_rewind(c->buffer);
1133 	} else if(c->dnscrypt && repinfo->is_dnscrypted) {
1134 		worker->stats.num_query_dnscrypt_crypted++;
1135 	}
1136 #endif
1137 #ifdef USE_DNSTAP
1138 	/*
1139 	 * sending src (client)/dst (local service) addresses over DNSTAP from incoming request handler
1140 	 */
1141 	if(worker->dtenv.log_client_query_messages) {
1142 		log_addr(VERB_ALGO, "request from client", &repinfo->addr, repinfo->addrlen);
1143 		log_addr(VERB_ALGO, "to local addr", (void*)repinfo->c->socket->addr->ai_addr, repinfo->c->socket->addr->ai_addrlen);
1144 		dt_msg_send_client_query(&worker->dtenv, &repinfo->addr, (void*)repinfo->c->socket->addr->ai_addr, c->type, c->buffer);
1145 	}
1146 #endif
1147 	acladdr = acl_addr_lookup(worker->daemon->acl, &repinfo->addr,
1148 		repinfo->addrlen);
1149 	acl = acl_get_control(acladdr);
1150 	if((ret=deny_refuse_all(c, acl, worker, repinfo)) != -1)
1151 	{
1152 		if(ret == 1)
1153 			goto send_reply;
1154 		return ret;
1155 	}
1156 	if((ret=worker_check_request(c->buffer, worker)) != 0) {
1157 		verbose(VERB_ALGO, "worker check request: bad query.");
1158 		log_addr(VERB_CLIENT,"from",&repinfo->addr, repinfo->addrlen);
1159 		if(ret != -1) {
1160 			LDNS_QR_SET(sldns_buffer_begin(c->buffer));
1161 			LDNS_RCODE_SET(sldns_buffer_begin(c->buffer), ret);
1162 			return 1;
1163 		}
1164 		comm_point_drop_reply(repinfo);
1165 		return 0;
1166 	}
1167 
1168 	worker->stats.num_queries++;
1169 
1170 	/* check if this query should be dropped based on source ip rate limiting */
1171 	if(!infra_ip_ratelimit_inc(worker->env.infra_cache, repinfo,
1172 			*worker->env.now, c->buffer)) {
1173 		/* See if we are passed through with slip factor */
1174 		if(worker->env.cfg->ip_ratelimit_factor != 0 &&
1175 			ub_random_max(worker->env.rnd,
1176 						  worker->env.cfg->ip_ratelimit_factor) == 0) {
1177 
1178 			char addrbuf[128];
1179 			addr_to_str(&repinfo->addr, repinfo->addrlen,
1180 						addrbuf, sizeof(addrbuf));
1181 		  verbose(VERB_QUERY, "ip_ratelimit allowed through for ip address %s because of slip in ip_ratelimit_factor",
1182 				  addrbuf);
1183 		} else {
1184 			worker->stats.num_queries_ip_ratelimited++;
1185 			comm_point_drop_reply(repinfo);
1186 			return 0;
1187 		}
1188 	}
1189 
1190 	/* see if query is in the cache */
1191 	if(!query_info_parse(&qinfo, c->buffer)) {
1192 		verbose(VERB_ALGO, "worker parse request: formerror.");
1193 		log_addr(VERB_CLIENT,"from",&repinfo->addr, repinfo->addrlen);
1194 		memset(&qinfo, 0, sizeof(qinfo)); /* zero qinfo.qname */
1195 		if(worker_err_ratelimit(worker, LDNS_RCODE_FORMERR) == -1) {
1196 			comm_point_drop_reply(repinfo);
1197 			return 0;
1198 		}
1199 		sldns_buffer_rewind(c->buffer);
1200 		LDNS_QR_SET(sldns_buffer_begin(c->buffer));
1201 		LDNS_RCODE_SET(sldns_buffer_begin(c->buffer),
1202 			LDNS_RCODE_FORMERR);
1203 		goto send_reply;
1204 	}
1205 	if(worker->env.cfg->log_queries) {
1206 		char ip[128];
1207 		addr_to_str(&repinfo->addr, repinfo->addrlen, ip, sizeof(ip));
1208 		log_query_in(ip, qinfo.qname, qinfo.qtype, qinfo.qclass);
1209 	}
1210 	if(qinfo.qtype == LDNS_RR_TYPE_AXFR ||
1211 		qinfo.qtype == LDNS_RR_TYPE_IXFR) {
1212 		verbose(VERB_ALGO, "worker request: refused zone transfer.");
1213 		log_addr(VERB_CLIENT,"from",&repinfo->addr, repinfo->addrlen);
1214 		sldns_buffer_rewind(c->buffer);
1215 		LDNS_QR_SET(sldns_buffer_begin(c->buffer));
1216 		LDNS_RCODE_SET(sldns_buffer_begin(c->buffer),
1217 			LDNS_RCODE_REFUSED);
1218 		if(worker->stats.extended) {
1219 			worker->stats.qtype[qinfo.qtype]++;
1220 		}
1221 		goto send_reply;
1222 	}
1223 	if(qinfo.qtype == LDNS_RR_TYPE_OPT ||
1224 		qinfo.qtype == LDNS_RR_TYPE_TSIG ||
1225 		qinfo.qtype == LDNS_RR_TYPE_TKEY ||
1226 		qinfo.qtype == LDNS_RR_TYPE_MAILA ||
1227 		qinfo.qtype == LDNS_RR_TYPE_MAILB ||
1228 		(qinfo.qtype >= 128 && qinfo.qtype <= 248)) {
1229 		verbose(VERB_ALGO, "worker request: formerror for meta-type.");
1230 		log_addr(VERB_CLIENT,"from",&repinfo->addr, repinfo->addrlen);
1231 		if(worker_err_ratelimit(worker, LDNS_RCODE_FORMERR) == -1) {
1232 			comm_point_drop_reply(repinfo);
1233 			return 0;
1234 		}
1235 		sldns_buffer_rewind(c->buffer);
1236 		LDNS_QR_SET(sldns_buffer_begin(c->buffer));
1237 		LDNS_RCODE_SET(sldns_buffer_begin(c->buffer),
1238 			LDNS_RCODE_FORMERR);
1239 		if(worker->stats.extended) {
1240 			worker->stats.qtype[qinfo.qtype]++;
1241 		}
1242 		goto send_reply;
1243 	}
1244 	if((ret=parse_edns_from_pkt(c->buffer, &edns, worker->scratchpad)) != 0) {
1245 		struct edns_data reply_edns;
1246 		verbose(VERB_ALGO, "worker parse edns: formerror.");
1247 		log_addr(VERB_CLIENT,"from",&repinfo->addr, repinfo->addrlen);
1248 		memset(&reply_edns, 0, sizeof(reply_edns));
1249 		reply_edns.edns_present = 1;
1250 		reply_edns.udp_size = EDNS_ADVERTISED_SIZE;
1251 		LDNS_RCODE_SET(sldns_buffer_begin(c->buffer), ret);
1252 		error_encode(c->buffer, ret, &qinfo,
1253 			*(uint16_t*)(void *)sldns_buffer_begin(c->buffer),
1254 			sldns_buffer_read_u16_at(c->buffer, 2), &reply_edns);
1255 		regional_free_all(worker->scratchpad);
1256 		goto send_reply;
1257 	}
1258 	if(edns.edns_present) {
1259 		struct edns_option* edns_opt;
1260 		if(edns.edns_version != 0) {
1261 			edns.ext_rcode = (uint8_t)(EDNS_RCODE_BADVERS>>4);
1262 			edns.edns_version = EDNS_ADVERTISED_VERSION;
1263 			edns.udp_size = EDNS_ADVERTISED_SIZE;
1264 			edns.bits &= EDNS_DO;
1265 			edns.opt_list = NULL;
1266 			edns.padding_block_size = 0;
1267 			verbose(VERB_ALGO, "query with bad edns version.");
1268 			log_addr(VERB_CLIENT,"from",&repinfo->addr, repinfo->addrlen);
1269 			error_encode(c->buffer, EDNS_RCODE_BADVERS&0xf, &qinfo,
1270 				*(uint16_t*)(void *)sldns_buffer_begin(c->buffer),
1271 				sldns_buffer_read_u16_at(c->buffer, 2), NULL);
1272 			if(sldns_buffer_capacity(c->buffer) >=
1273 			   sldns_buffer_limit(c->buffer)+calc_edns_field_size(&edns))
1274 				attach_edns_record(c->buffer, &edns);
1275 			regional_free_all(worker->scratchpad);
1276 			goto send_reply;
1277 		}
1278 		if(edns.udp_size < NORMAL_UDP_SIZE &&
1279 		   worker->daemon->cfg->harden_short_bufsize) {
1280 			verbose(VERB_QUERY, "worker request: EDNS bufsize %d ignored",
1281 				(int)edns.udp_size);
1282 			log_addr(VERB_CLIENT,"from",&repinfo->addr, repinfo->addrlen);
1283 			edns.udp_size = NORMAL_UDP_SIZE;
1284 		}
1285 		if(c->type != comm_udp) {
1286 			edns_opt = edns_opt_list_find(edns.opt_list, LDNS_EDNS_KEEPALIVE);
1287 			if(edns_opt && edns_opt->opt_len > 0) {
1288 				edns.ext_rcode = 0;
1289 				edns.edns_version = EDNS_ADVERTISED_VERSION;
1290 				edns.udp_size = EDNS_ADVERTISED_SIZE;
1291 				edns.bits &= EDNS_DO;
1292 				edns.opt_list = NULL;
1293 				verbose(VERB_ALGO, "query with bad edns keepalive.");
1294 				log_addr(VERB_CLIENT,"from",&repinfo->addr, repinfo->addrlen);
1295 				error_encode(c->buffer, LDNS_RCODE_FORMERR, &qinfo,
1296 					*(uint16_t*)(void *)sldns_buffer_begin(c->buffer),
1297 					sldns_buffer_read_u16_at(c->buffer, 2), NULL);
1298 				if(sldns_buffer_capacity(c->buffer) >=
1299 				   sldns_buffer_limit(c->buffer)+calc_edns_field_size(&edns))
1300 					attach_edns_record(c->buffer, &edns);
1301 				regional_free_all(worker->scratchpad);
1302 				goto send_reply;
1303 			}
1304 		}
1305 	}
1306 	if(edns.udp_size > worker->daemon->cfg->max_udp_size &&
1307 		c->type == comm_udp) {
1308 		verbose(VERB_QUERY,
1309 			"worker request: max UDP reply size modified"
1310 			" (%d to max-udp-size)", (int)edns.udp_size);
1311 		log_addr(VERB_CLIENT,"from",&repinfo->addr, repinfo->addrlen);
1312 		edns.udp_size = worker->daemon->cfg->max_udp_size;
1313 	}
1314 	if(edns.udp_size < LDNS_HEADER_SIZE) {
1315 		verbose(VERB_ALGO, "worker request: edns is too small.");
1316 		log_addr(VERB_CLIENT, "from", &repinfo->addr, repinfo->addrlen);
1317 		LDNS_QR_SET(sldns_buffer_begin(c->buffer));
1318 		LDNS_TC_SET(sldns_buffer_begin(c->buffer));
1319 		LDNS_RCODE_SET(sldns_buffer_begin(c->buffer),
1320 			LDNS_RCODE_SERVFAIL);
1321 		sldns_buffer_set_position(c->buffer, LDNS_HEADER_SIZE);
1322 		sldns_buffer_write_at(c->buffer, 4,
1323 			(uint8_t*)"\0\0\0\0\0\0\0\0", 8);
1324 		sldns_buffer_flip(c->buffer);
1325 		regional_free_all(worker->scratchpad);
1326 		goto send_reply;
1327 	}
1328 	if(worker->stats.extended)
1329 		server_stats_insquery(&worker->stats, c, qinfo.qtype,
1330 			qinfo.qclass, &edns, repinfo);
1331 	if(c->type != comm_udp)
1332 		edns.udp_size = 65535; /* max size for TCP replies */
1333 	if(qinfo.qclass == LDNS_RR_CLASS_CH && answer_chaos(worker, &qinfo,
1334 		&edns, repinfo, c->buffer)) {
1335 		regional_free_all(worker->scratchpad);
1336 		goto send_reply;
1337 	}
1338 	if(LDNS_OPCODE_WIRE(sldns_buffer_begin(c->buffer)) ==
1339 		LDNS_PACKET_NOTIFY) {
1340 		answer_notify(worker, &qinfo, &edns, c->buffer, repinfo);
1341 		regional_free_all(worker->scratchpad);
1342 		goto send_reply;
1343 	}
1344 	if(local_zones_answer(worker->daemon->local_zones, &worker->env, &qinfo,
1345 		&edns, c->buffer, worker->scratchpad, repinfo, acladdr->taglist,
1346 		acladdr->taglen, acladdr->tag_actions,
1347 		acladdr->tag_actions_size, acladdr->tag_datas,
1348 		acladdr->tag_datas_size, worker->daemon->cfg->tagname,
1349 		worker->daemon->cfg->num_tags, acladdr->view)) {
1350 		regional_free_all(worker->scratchpad);
1351 		if(sldns_buffer_limit(c->buffer) == 0) {
1352 			comm_point_drop_reply(repinfo);
1353 			return 0;
1354 		}
1355 		goto send_reply;
1356 	}
1357 	if(worker->env.auth_zones &&
1358 		rpz_apply_qname_trigger(worker->env.auth_zones,
1359 		&worker->env, &qinfo, &edns, c->buffer, worker->scratchpad,
1360 		repinfo, acladdr->taglist, acladdr->taglen, &worker->stats)) {
1361 		regional_free_all(worker->scratchpad);
1362 		if(sldns_buffer_limit(c->buffer) == 0) {
1363 			comm_point_drop_reply(repinfo);
1364 			return 0;
1365 		}
1366 		goto send_reply;
1367 	}
1368 	if(worker->env.auth_zones &&
1369 		auth_zones_answer(worker->env.auth_zones, &worker->env,
1370 		&qinfo, &edns, repinfo, c->buffer, worker->scratchpad)) {
1371 		regional_free_all(worker->scratchpad);
1372 		if(sldns_buffer_limit(c->buffer) == 0) {
1373 			comm_point_drop_reply(repinfo);
1374 			return 0;
1375 		}
1376 		/* set RA for everyone that can have recursion (based on
1377 		 * access control list) */
1378 		if(LDNS_RD_WIRE(sldns_buffer_begin(c->buffer)) &&
1379 		   acl != acl_deny_non_local && acl != acl_refuse_non_local)
1380 			LDNS_RA_SET(sldns_buffer_begin(c->buffer));
1381 		goto send_reply;
1382 	}
1383 
1384 	/* We've looked in our local zones. If the answer isn't there, we
1385 	 * might need to bail out based on ACLs now. */
1386 	if((ret=deny_refuse_non_local(c, acl, worker, repinfo)) != -1)
1387 	{
1388 		regional_free_all(worker->scratchpad);
1389 		if(ret == 1)
1390 			goto send_reply;
1391 		return ret;
1392 	}
1393 
1394 	/* If this request does not have the recursion bit set, verify
1395 	 * ACLs allow the recursion bit to be treated as set. */
1396 	if(!(LDNS_RD_WIRE(sldns_buffer_begin(c->buffer))) &&
1397 		acl == acl_allow_setrd ) {
1398 		LDNS_RD_SET(sldns_buffer_begin(c->buffer));
1399 	}
1400 
1401 	/* If this request does not have the recursion bit set, verify
1402 	 * ACLs allow the snooping. */
1403 	if(!(LDNS_RD_WIRE(sldns_buffer_begin(c->buffer))) &&
1404 		acl != acl_allow_snoop ) {
1405 		error_encode(c->buffer, LDNS_RCODE_REFUSED, &qinfo,
1406 			*(uint16_t*)(void *)sldns_buffer_begin(c->buffer),
1407 			sldns_buffer_read_u16_at(c->buffer, 2), NULL);
1408 		regional_free_all(worker->scratchpad);
1409 		log_addr(VERB_ALGO, "refused nonrec (cache snoop) query from",
1410 			&repinfo->addr, repinfo->addrlen);
1411 		goto send_reply;
1412 	}
1413 
1414 	/* If we've found a local alias, replace the qname with the alias
1415 	 * target before resolving it. */
1416 	if(qinfo.local_alias) {
1417 		struct ub_packed_rrset_key* rrset = qinfo.local_alias->rrset;
1418 		struct packed_rrset_data* d = rrset->entry.data;
1419 
1420 		/* Sanity check: our current implementation only supports
1421 		 * a single CNAME RRset as a local alias. */
1422 		if(qinfo.local_alias->next ||
1423 			rrset->rk.type != htons(LDNS_RR_TYPE_CNAME) ||
1424 			d->count != 1) {
1425 			log_err("assumption failure: unexpected local alias");
1426 			regional_free_all(worker->scratchpad);
1427 			return 0; /* drop it */
1428 		}
1429 		qinfo.qname = d->rr_data[0] + 2;
1430 		qinfo.qname_len = d->rr_len[0] - 2;
1431 	}
1432 
1433 	/* If we may apply IP-based actions to the answer, build the client
1434 	 * information.  As this can be expensive, skip it if there is
1435 	 * absolutely no possibility of it. */
1436 	if((worker->daemon->use_response_ip || worker->daemon->use_rpz) &&
1437 		(qinfo.qtype == LDNS_RR_TYPE_A ||
1438 		qinfo.qtype == LDNS_RR_TYPE_AAAA ||
1439 		qinfo.qtype == LDNS_RR_TYPE_ANY)) {
1440 		cinfo_tmp.taglist = acladdr->taglist;
1441 		cinfo_tmp.taglen = acladdr->taglen;
1442 		cinfo_tmp.tag_actions = acladdr->tag_actions;
1443 		cinfo_tmp.tag_actions_size = acladdr->tag_actions_size;
1444 		cinfo_tmp.tag_datas = acladdr->tag_datas;
1445 		cinfo_tmp.tag_datas_size = acladdr->tag_datas_size;
1446 		cinfo_tmp.view = acladdr->view;
1447 		cinfo_tmp.respip_set = worker->daemon->respip_set;
1448 		cinfo = &cinfo_tmp;
1449 	}
1450 
1451 lookup_cache:
1452 	/* Lookup the cache.  In case we chase an intermediate CNAME chain
1453 	 * this is a two-pass operation, and lookup_qinfo is different for
1454 	 * each pass.  We should still pass the original qinfo to
1455 	 * answer_from_cache(), however, since it's used to build the reply. */
1456 	if(!edns_bypass_cache_stage(edns.opt_list, &worker->env)) {
1457 		is_expired_answer = 0;
1458 		is_secure_answer = 0;
1459 		h = query_info_hash(lookup_qinfo, sldns_buffer_read_u16_at(c->buffer, 2));
1460 		if((e=slabhash_lookup(worker->env.msg_cache, h, lookup_qinfo, 0))) {
1461 			/* answer from cache - we have acquired a readlock on it */
1462 			if(answer_from_cache(worker, &qinfo,
1463 				cinfo, &need_drop, &is_expired_answer, &is_secure_answer,
1464 				&alias_rrset, &partial_rep, (struct reply_info*)e->data,
1465 				*(uint16_t*)(void *)sldns_buffer_begin(c->buffer),
1466 				sldns_buffer_read_u16_at(c->buffer, 2), repinfo,
1467 				&edns)) {
1468 				/* prefetch it if the prefetch TTL expired.
1469 				 * Note that if there is more than one pass
1470 				 * its qname must be that used for cache
1471 				 * lookup. */
1472 				if((worker->env.cfg->prefetch && *worker->env.now >=
1473 							((struct reply_info*)e->data)->prefetch_ttl) ||
1474 						(worker->env.cfg->serve_expired &&
1475 						*worker->env.now >= ((struct reply_info*)e->data)->ttl)) {
1476 
1477 					time_t leeway = ((struct reply_info*)e->
1478 						data)->ttl - *worker->env.now;
1479 					if(((struct reply_info*)e->data)->ttl
1480 						< *worker->env.now)
1481 						leeway = 0;
1482 					lock_rw_unlock(&e->lock);
1483 					reply_and_prefetch(worker, lookup_qinfo,
1484 						sldns_buffer_read_u16_at(c->buffer, 2),
1485 						repinfo, leeway,
1486 						(partial_rep || need_drop));
1487 					if(!partial_rep) {
1488 						rc = 0;
1489 						regional_free_all(worker->scratchpad);
1490 						goto send_reply_rc;
1491 					}
1492 				} else if(!partial_rep) {
1493 					lock_rw_unlock(&e->lock);
1494 					regional_free_all(worker->scratchpad);
1495 					goto send_reply;
1496 				} else {
1497 					/* Note that we've already released the
1498 					 * lock if we're here after prefetch. */
1499 					lock_rw_unlock(&e->lock);
1500 				}
1501 				/* We've found a partial reply ending with an
1502 				 * alias.  Replace the lookup qinfo for the
1503 				 * alias target and lookup the cache again to
1504 				 * (possibly) complete the reply.  As we're
1505 				 * passing the "base" reply, there will be no
1506 				 * more alias chasing. */
1507 				memset(&qinfo_tmp, 0, sizeof(qinfo_tmp));
1508 				get_cname_target(alias_rrset, &qinfo_tmp.qname,
1509 					&qinfo_tmp.qname_len);
1510 				if(!qinfo_tmp.qname) {
1511 					log_err("unexpected: invalid answer alias");
1512 					regional_free_all(worker->scratchpad);
1513 					return 0; /* drop query */
1514 				}
1515 				qinfo_tmp.qtype = qinfo.qtype;
1516 				qinfo_tmp.qclass = qinfo.qclass;
1517 				lookup_qinfo = &qinfo_tmp;
1518 				goto lookup_cache;
1519 			}
1520 			verbose(VERB_ALGO, "answer from the cache failed");
1521 			lock_rw_unlock(&e->lock);
1522 		}
1523 		if(!LDNS_RD_WIRE(sldns_buffer_begin(c->buffer))) {
1524 			if(answer_norec_from_cache(worker, &qinfo,
1525 				*(uint16_t*)(void *)sldns_buffer_begin(c->buffer),
1526 				sldns_buffer_read_u16_at(c->buffer, 2), repinfo,
1527 				&edns)) {
1528 				regional_free_all(worker->scratchpad);
1529 				goto send_reply;
1530 			}
1531 			verbose(VERB_ALGO, "answer norec from cache -- "
1532 				"need to validate or not primed");
1533 		}
1534 	}
1535 	sldns_buffer_rewind(c->buffer);
1536 	server_stats_querymiss(&worker->stats, worker);
1537 
1538 	if(verbosity >= VERB_CLIENT) {
1539 		if(c->type == comm_udp)
1540 			log_addr(VERB_CLIENT, "udp request from",
1541 				&repinfo->addr, repinfo->addrlen);
1542 		else	log_addr(VERB_CLIENT, "tcp request from",
1543 				&repinfo->addr, repinfo->addrlen);
1544 	}
1545 
1546 	/* grab a work request structure for this new request */
1547 	mesh_new_client(worker->env.mesh, &qinfo, cinfo,
1548 		sldns_buffer_read_u16_at(c->buffer, 2),
1549 		&edns, repinfo, *(uint16_t*)(void *)sldns_buffer_begin(c->buffer));
1550 	regional_free_all(worker->scratchpad);
1551 	worker_mem_report(worker, NULL);
1552 	return 0;
1553 
1554 send_reply:
1555 	rc = 1;
1556 send_reply_rc:
1557 	if(need_drop) {
1558 		comm_point_drop_reply(repinfo);
1559 		return 0;
1560 	}
1561 	if(is_expired_answer) {
1562 		worker->stats.ans_expired++;
1563 	}
1564 	server_stats_insrcode(&worker->stats, c->buffer);
1565 	if(worker->stats.extended) {
1566 		if(is_secure_answer) worker->stats.ans_secure++;
1567 	}
1568 #ifdef USE_DNSTAP
1569 	/*
1570 	 * sending src (client)/dst (local service) addresses over DNSTAP from send_reply code label (when we serviced local zone for ex.)
1571 	 */
1572 	if(worker->dtenv.log_client_response_messages) {
1573 		log_addr(VERB_ALGO, "from local addr", (void*)repinfo->c->socket->addr->ai_addr, repinfo->c->socket->addr->ai_addrlen);
1574                 log_addr(VERB_ALGO, "response to client", &repinfo->addr, repinfo->addrlen);
1575 		dt_msg_send_client_response(&worker->dtenv, &repinfo->addr, (void*)repinfo->c->socket->addr->ai_addr, c->type, c->buffer);
1576 	}
1577 #endif
1578 	if(worker->env.cfg->log_replies)
1579 	{
1580 		struct timeval tv;
1581 		memset(&tv, 0, sizeof(tv));
1582 		if(qinfo.local_alias && qinfo.local_alias->rrset &&
1583 			qinfo.local_alias->rrset->rk.dname) {
1584 			/* log original qname, before the local alias was
1585 			 * used to resolve that CNAME to something else */
1586 			qinfo.qname = qinfo.local_alias->rrset->rk.dname;
1587 			log_reply_info(NO_VERBOSE, &qinfo, &repinfo->addr, repinfo->addrlen,
1588 				tv, 1, c->buffer);
1589 		} else {
1590 			log_reply_info(NO_VERBOSE, &qinfo, &repinfo->addr, repinfo->addrlen,
1591 				tv, 1, c->buffer);
1592 		}
1593 	}
1594 #ifdef USE_DNSCRYPT
1595 	if(!dnsc_handle_uncurved_request(repinfo)) {
1596 		return 0;
1597 	}
1598 #endif
1599 	return rc;
1600 }
1601 
1602 void
1603 worker_sighandler(int sig, void* arg)
1604 {
1605 	/* note that log, print, syscalls here give race conditions.
1606 	 * And cause hangups if the log-lock is held by the application. */
1607 	struct worker* worker = (struct worker*)arg;
1608 	switch(sig) {
1609 #ifdef SIGHUP
1610 		case SIGHUP:
1611 			comm_base_exit(worker->base);
1612 			break;
1613 #endif
1614 		case SIGINT:
1615 			worker->need_to_exit = 1;
1616 			comm_base_exit(worker->base);
1617 			break;
1618 #ifdef SIGQUIT
1619 		case SIGQUIT:
1620 			worker->need_to_exit = 1;
1621 			comm_base_exit(worker->base);
1622 			break;
1623 #endif
1624 		case SIGTERM:
1625 			worker->need_to_exit = 1;
1626 			comm_base_exit(worker->base);
1627 			break;
1628 		default:
1629 			/* unknown signal, ignored */
1630 			break;
1631 	}
1632 }
1633 
1634 /** restart statistics timer for worker, if enabled */
1635 static void
1636 worker_restart_timer(struct worker* worker)
1637 {
1638 	if(worker->env.cfg->stat_interval > 0) {
1639 		struct timeval tv;
1640 #ifndef S_SPLINT_S
1641 		tv.tv_sec = worker->env.cfg->stat_interval;
1642 		tv.tv_usec = 0;
1643 #endif
1644 		comm_timer_set(worker->stat_timer, &tv);
1645 	}
1646 }
1647 
1648 void worker_stat_timer_cb(void* arg)
1649 {
1650 	struct worker* worker = (struct worker*)arg;
1651 	server_stats_log(&worker->stats, worker, worker->thread_num);
1652 	mesh_stats(worker->env.mesh, "mesh has");
1653 	worker_mem_report(worker, NULL);
1654 	/* SHM is enabled, process data to SHM */
1655 	if (worker->daemon->cfg->shm_enable) {
1656 		shm_main_run(worker);
1657 	}
1658 	if(!worker->daemon->cfg->stat_cumulative) {
1659 		worker_stats_clear(worker);
1660 	}
1661 	/* start next timer */
1662 	worker_restart_timer(worker);
1663 }
1664 
1665 void worker_probe_timer_cb(void* arg)
1666 {
1667 	struct worker* worker = (struct worker*)arg;
1668 	struct timeval tv;
1669 #ifndef S_SPLINT_S
1670 	tv.tv_sec = (time_t)autr_probe_timer(&worker->env);
1671 	tv.tv_usec = 0;
1672 #endif
1673 	if(tv.tv_sec != 0)
1674 		comm_timer_set(worker->env.probe_timer, &tv);
1675 }
1676 
1677 struct worker*
1678 worker_create(struct daemon* daemon, int id, int* ports, int n)
1679 {
1680 	unsigned int seed;
1681 	struct worker* worker = (struct worker*)calloc(1,
1682 		sizeof(struct worker));
1683 	if(!worker)
1684 		return NULL;
1685 	worker->numports = n;
1686 	worker->ports = (int*)memdup(ports, sizeof(int)*n);
1687 	if(!worker->ports) {
1688 		free(worker);
1689 		return NULL;
1690 	}
1691 	worker->daemon = daemon;
1692 	worker->thread_num = id;
1693 	if(!(worker->cmd = tube_create())) {
1694 		free(worker->ports);
1695 		free(worker);
1696 		return NULL;
1697 	}
1698 	/* create random state here to avoid locking trouble in RAND_bytes */
1699 	if(!(worker->rndstate = ub_initstate(daemon->rand))) {
1700 		log_err("could not init random numbers.");
1701 		tube_delete(worker->cmd);
1702 		free(worker->ports);
1703 		free(worker);
1704 		return NULL;
1705 	}
1706 	explicit_bzero(&seed, sizeof(seed));
1707 	return worker;
1708 }
1709 
1710 int
1711 worker_init(struct worker* worker, struct config_file *cfg,
1712 	struct listen_port* ports, int do_sigs)
1713 {
1714 #ifdef USE_DNSTAP
1715 	struct dt_env* dtenv = &worker->dtenv;
1716 #else
1717 	void* dtenv = NULL;
1718 #endif
1719 	worker->need_to_exit = 0;
1720 	worker->base = comm_base_create(do_sigs);
1721 	if(!worker->base) {
1722 		log_err("could not create event handling base");
1723 		worker_delete(worker);
1724 		return 0;
1725 	}
1726 	comm_base_set_slow_accept_handlers(worker->base, &worker_stop_accept,
1727 		&worker_start_accept, worker);
1728 	if(do_sigs) {
1729 #ifdef SIGHUP
1730 		ub_thread_sig_unblock(SIGHUP);
1731 #endif
1732 		ub_thread_sig_unblock(SIGINT);
1733 #ifdef SIGQUIT
1734 		ub_thread_sig_unblock(SIGQUIT);
1735 #endif
1736 		ub_thread_sig_unblock(SIGTERM);
1737 #ifndef LIBEVENT_SIGNAL_PROBLEM
1738 		worker->comsig = comm_signal_create(worker->base,
1739 			worker_sighandler, worker);
1740 		if(!worker->comsig
1741 #ifdef SIGHUP
1742 			|| !comm_signal_bind(worker->comsig, SIGHUP)
1743 #endif
1744 #ifdef SIGQUIT
1745 			|| !comm_signal_bind(worker->comsig, SIGQUIT)
1746 #endif
1747 			|| !comm_signal_bind(worker->comsig, SIGTERM)
1748 			|| !comm_signal_bind(worker->comsig, SIGINT)) {
1749 			log_err("could not create signal handlers");
1750 			worker_delete(worker);
1751 			return 0;
1752 		}
1753 #endif /* LIBEVENT_SIGNAL_PROBLEM */
1754 		if(!daemon_remote_open_accept(worker->daemon->rc,
1755 			worker->daemon->rc_ports, worker)) {
1756 			worker_delete(worker);
1757 			return 0;
1758 		}
1759 #ifdef UB_ON_WINDOWS
1760 		wsvc_setup_worker(worker);
1761 #endif /* UB_ON_WINDOWS */
1762 	} else { /* !do_sigs */
1763 		worker->comsig = NULL;
1764 	}
1765 #ifdef USE_DNSTAP
1766 	if(cfg->dnstap) {
1767 		log_assert(worker->daemon->dtenv != NULL);
1768 		memcpy(&worker->dtenv, worker->daemon->dtenv, sizeof(struct dt_env));
1769 		if(!dt_init(&worker->dtenv, worker->base))
1770 			fatal_exit("dt_init failed");
1771 	}
1772 #endif
1773 	worker->front = listen_create(worker->base, ports,
1774 		cfg->msg_buffer_size, (int)cfg->incoming_num_tcp,
1775 		cfg->do_tcp_keepalive
1776 			? cfg->tcp_keepalive_timeout
1777 			: cfg->tcp_idle_timeout,
1778 		cfg->harden_large_queries, cfg->http_max_streams,
1779 		cfg->http_endpoint, cfg->http_notls_downstream,
1780 		worker->daemon->tcl, worker->daemon->listen_sslctx,
1781 		dtenv, worker_handle_request, worker);
1782 	if(!worker->front) {
1783 		log_err("could not create listening sockets");
1784 		worker_delete(worker);
1785 		return 0;
1786 	}
1787 	worker->back = outside_network_create(worker->base,
1788 		cfg->msg_buffer_size, (size_t)cfg->outgoing_num_ports,
1789 		cfg->out_ifs, cfg->num_out_ifs, cfg->do_ip4, cfg->do_ip6,
1790 		cfg->do_tcp?cfg->outgoing_num_tcp:0, cfg->ip_dscp,
1791 		worker->daemon->env->infra_cache, worker->rndstate,
1792 		cfg->use_caps_bits_for_id, worker->ports, worker->numports,
1793 		cfg->unwanted_threshold, cfg->outgoing_tcp_mss,
1794 		&worker_alloc_cleanup, worker,
1795 		cfg->do_udp || cfg->udp_upstream_without_downstream,
1796 		worker->daemon->connect_sslctx, cfg->delay_close,
1797 		cfg->tls_use_sni, dtenv, cfg->udp_connect,
1798 		cfg->max_reuse_tcp_queries, cfg->tcp_reuse_timeout,
1799 		cfg->tcp_auth_query_timeout);
1800 	if(!worker->back) {
1801 		log_err("could not create outgoing sockets");
1802 		worker_delete(worker);
1803 		return 0;
1804 	}
1805 	iterator_set_ip46_support(&worker->daemon->mods, worker->daemon->env,
1806 		worker->back);
1807 	/* start listening to commands */
1808 	if(!tube_setup_bg_listen(worker->cmd, worker->base,
1809 		&worker_handle_control_cmd, worker)) {
1810 		log_err("could not create control compt.");
1811 		worker_delete(worker);
1812 		return 0;
1813 	}
1814 	worker->stat_timer = comm_timer_create(worker->base,
1815 		worker_stat_timer_cb, worker);
1816 	if(!worker->stat_timer) {
1817 		log_err("could not create statistics timer");
1818 	}
1819 
1820 	/* we use the msg_buffer_size as a good estimate for what the
1821 	 * user wants for memory usage sizes */
1822 	worker->scratchpad = regional_create_custom(cfg->msg_buffer_size);
1823 	if(!worker->scratchpad) {
1824 		log_err("malloc failure");
1825 		worker_delete(worker);
1826 		return 0;
1827 	}
1828 
1829 	server_stats_init(&worker->stats, cfg);
1830 	alloc_init(&worker->alloc, &worker->daemon->superalloc,
1831 		worker->thread_num);
1832 	alloc_set_id_cleanup(&worker->alloc, &worker_alloc_cleanup, worker);
1833 	worker->env = *worker->daemon->env;
1834 	comm_base_timept(worker->base, &worker->env.now, &worker->env.now_tv);
1835 	worker->env.worker = worker;
1836 	worker->env.worker_base = worker->base;
1837 	worker->env.send_query = &worker_send_query;
1838 	worker->env.alloc = &worker->alloc;
1839 	worker->env.outnet = worker->back;
1840 	worker->env.rnd = worker->rndstate;
1841 	/* If case prefetch is triggered, the corresponding mesh will clear
1842 	 * the scratchpad for the module env in the middle of request handling.
1843 	 * It would be prone to a use-after-free kind of bug, so we avoid
1844 	 * sharing it with worker's own scratchpad at the cost of having
1845 	 * one more pad per worker. */
1846 	worker->env.scratch = regional_create_custom(cfg->msg_buffer_size);
1847 	if(!worker->env.scratch) {
1848 		log_err("malloc failure");
1849 		worker_delete(worker);
1850 		return 0;
1851 	}
1852 	worker->env.mesh = mesh_create(&worker->daemon->mods, &worker->env);
1853 	if(!worker->env.mesh) {
1854 		log_err("malloc failure");
1855 		worker_delete(worker);
1856 		return 0;
1857 	}
1858 	/* Pass on daemon variables that we would need in the mesh area */
1859 	worker->env.mesh->use_response_ip = worker->daemon->use_response_ip;
1860 	worker->env.mesh->use_rpz = worker->daemon->use_rpz;
1861 
1862 	worker->env.detach_subs = &mesh_detach_subs;
1863 	worker->env.attach_sub = &mesh_attach_sub;
1864 	worker->env.add_sub = &mesh_add_sub;
1865 	worker->env.kill_sub = &mesh_state_delete;
1866 	worker->env.detect_cycle = &mesh_detect_cycle;
1867 	worker->env.scratch_buffer = sldns_buffer_new(cfg->msg_buffer_size);
1868 	if(!worker->env.scratch_buffer) {
1869 		log_err("malloc failure");
1870 		worker_delete(worker);
1871 		return 0;
1872 	}
1873 	if(!(worker->env.fwds = forwards_create()) ||
1874 		!forwards_apply_cfg(worker->env.fwds, cfg)) {
1875 		log_err("Could not set forward zones");
1876 		worker_delete(worker);
1877 		return 0;
1878 	}
1879 	if(!(worker->env.hints = hints_create()) ||
1880 		!hints_apply_cfg(worker->env.hints, cfg)) {
1881 		log_err("Could not set root or stub hints");
1882 		worker_delete(worker);
1883 		return 0;
1884 	}
1885 	/* one probe timer per process -- if we have 5011 anchors */
1886 	if(autr_get_num_anchors(worker->env.anchors) > 0
1887 #ifndef THREADS_DISABLED
1888 		&& worker->thread_num == 0
1889 #endif
1890 		) {
1891 		struct timeval tv;
1892 		tv.tv_sec = 0;
1893 		tv.tv_usec = 0;
1894 		worker->env.probe_timer = comm_timer_create(worker->base,
1895 			worker_probe_timer_cb, worker);
1896 		if(!worker->env.probe_timer) {
1897 			log_err("could not create 5011-probe timer");
1898 		} else {
1899 			/* let timer fire, then it can reset itself */
1900 			comm_timer_set(worker->env.probe_timer, &tv);
1901 		}
1902 	}
1903 	/* zone transfer tasks, setup once per process, if any */
1904 	if(worker->env.auth_zones
1905 #ifndef THREADS_DISABLED
1906 		&& worker->thread_num == 0
1907 #endif
1908 		) {
1909 		auth_xfer_pickup_initial(worker->env.auth_zones, &worker->env);
1910 		auth_zones_pickup_zonemd_verify(worker->env.auth_zones,
1911 			&worker->env);
1912 	}
1913 #ifdef USE_DNSTAP
1914 	if(worker->daemon->cfg->dnstap
1915 #ifndef THREADS_DISABLED
1916 		&& worker->thread_num == 0
1917 #endif
1918 		) {
1919 		if(!dt_io_thread_start(dtenv->dtio, comm_base_internal(
1920 			worker->base), worker->daemon->num)) {
1921 			log_err("could not start dnstap io thread");
1922 			worker_delete(worker);
1923 			return 0;
1924 		}
1925 	}
1926 #endif /* USE_DNSTAP */
1927 	worker_mem_report(worker, NULL);
1928 	/* if statistics enabled start timer */
1929 	if(worker->env.cfg->stat_interval > 0) {
1930 		verbose(VERB_ALGO, "set statistics interval %d secs",
1931 			worker->env.cfg->stat_interval);
1932 		worker_restart_timer(worker);
1933 	}
1934 	return 1;
1935 }
1936 
1937 void
1938 worker_work(struct worker* worker)
1939 {
1940 	comm_base_dispatch(worker->base);
1941 }
1942 
1943 void
1944 worker_delete(struct worker* worker)
1945 {
1946 	if(!worker)
1947 		return;
1948 	if(worker->env.mesh && verbosity >= VERB_OPS) {
1949 		server_stats_log(&worker->stats, worker, worker->thread_num);
1950 		mesh_stats(worker->env.mesh, "mesh has");
1951 		worker_mem_report(worker, NULL);
1952 	}
1953 	outside_network_quit_prepare(worker->back);
1954 	mesh_delete(worker->env.mesh);
1955 	sldns_buffer_free(worker->env.scratch_buffer);
1956 	forwards_delete(worker->env.fwds);
1957 	hints_delete(worker->env.hints);
1958 	listen_delete(worker->front);
1959 	outside_network_delete(worker->back);
1960 	comm_signal_delete(worker->comsig);
1961 	tube_delete(worker->cmd);
1962 	comm_timer_delete(worker->stat_timer);
1963 	comm_timer_delete(worker->env.probe_timer);
1964 	free(worker->ports);
1965 	if(worker->thread_num == 0) {
1966 #ifdef UB_ON_WINDOWS
1967 		wsvc_desetup_worker(worker);
1968 #endif /* UB_ON_WINDOWS */
1969 	}
1970 #ifdef USE_DNSTAP
1971 	if(worker->daemon->cfg->dnstap
1972 #ifndef THREADS_DISABLED
1973 		&& worker->thread_num == 0
1974 #endif
1975 		) {
1976 		dt_io_thread_stop(worker->dtenv.dtio);
1977 	}
1978 	dt_deinit(&worker->dtenv);
1979 #endif /* USE_DNSTAP */
1980 	comm_base_delete(worker->base);
1981 	ub_randfree(worker->rndstate);
1982 	alloc_clear(&worker->alloc);
1983 	regional_destroy(worker->env.scratch);
1984 	regional_destroy(worker->scratchpad);
1985 	free(worker);
1986 }
1987 
1988 struct outbound_entry*
1989 worker_send_query(struct query_info* qinfo, uint16_t flags, int dnssec,
1990 	int want_dnssec, int nocaps, struct sockaddr_storage* addr,
1991 	socklen_t addrlen, uint8_t* zone, size_t zonelen, int ssl_upstream,
1992 	char* tls_auth_name, struct module_qstate* q)
1993 {
1994 	struct worker* worker = q->env->worker;
1995 	struct outbound_entry* e = (struct outbound_entry*)regional_alloc(
1996 		q->region, sizeof(*e));
1997 	if(!e)
1998 		return NULL;
1999 	e->qstate = q;
2000 	e->qsent = outnet_serviced_query(worker->back, qinfo, flags, dnssec,
2001 		want_dnssec, nocaps, q->env->cfg->tcp_upstream,
2002 		ssl_upstream, tls_auth_name, addr, addrlen, zone, zonelen, q,
2003 		worker_handle_service_reply, e, worker->back->udp_buff, q->env);
2004 	if(!e->qsent) {
2005 		return NULL;
2006 	}
2007 	return e;
2008 }
2009 
2010 void
2011 worker_alloc_cleanup(void* arg)
2012 {
2013 	struct worker* worker = (struct worker*)arg;
2014 	slabhash_clear(&worker->env.rrset_cache->table);
2015 	slabhash_clear(worker->env.msg_cache);
2016 }
2017 
2018 void worker_stats_clear(struct worker* worker)
2019 {
2020 	server_stats_init(&worker->stats, worker->env.cfg);
2021 	mesh_stats_clear(worker->env.mesh);
2022 	worker->back->unwanted_replies = 0;
2023 	worker->back->num_tcp_outgoing = 0;
2024 }
2025 
2026 void worker_start_accept(void* arg)
2027 {
2028 	struct worker* worker = (struct worker*)arg;
2029 	listen_start_accept(worker->front);
2030 	if(worker->thread_num == 0)
2031 		daemon_remote_start_accept(worker->daemon->rc);
2032 }
2033 
2034 void worker_stop_accept(void* arg)
2035 {
2036 	struct worker* worker = (struct worker*)arg;
2037 	listen_stop_accept(worker->front);
2038 	if(worker->thread_num == 0)
2039 		daemon_remote_stop_accept(worker->daemon->rc);
2040 }
2041 
2042 /* --- fake callbacks for fptr_wlist to work --- */
2043 struct outbound_entry* libworker_send_query(
2044 	struct query_info* ATTR_UNUSED(qinfo),
2045 	uint16_t ATTR_UNUSED(flags), int ATTR_UNUSED(dnssec),
2046 	int ATTR_UNUSED(want_dnssec), int ATTR_UNUSED(nocaps),
2047 	struct sockaddr_storage* ATTR_UNUSED(addr), socklen_t ATTR_UNUSED(addrlen),
2048 	uint8_t* ATTR_UNUSED(zone), size_t ATTR_UNUSED(zonelen),
2049 	int ATTR_UNUSED(ssl_upstream), char* ATTR_UNUSED(tls_auth_name),
2050 	struct module_qstate* ATTR_UNUSED(q))
2051 {
2052 	log_assert(0);
2053 	return 0;
2054 }
2055 
2056 int libworker_handle_service_reply(struct comm_point* ATTR_UNUSED(c),
2057 	void* ATTR_UNUSED(arg), int ATTR_UNUSED(error),
2058         struct comm_reply* ATTR_UNUSED(reply_info))
2059 {
2060 	log_assert(0);
2061 	return 0;
2062 }
2063 
2064 void libworker_handle_control_cmd(struct tube* ATTR_UNUSED(tube),
2065         uint8_t* ATTR_UNUSED(buffer), size_t ATTR_UNUSED(len),
2066         int ATTR_UNUSED(error), void* ATTR_UNUSED(arg))
2067 {
2068 	log_assert(0);
2069 }
2070 
2071 void libworker_fg_done_cb(void* ATTR_UNUSED(arg), int ATTR_UNUSED(rcode),
2072 	sldns_buffer* ATTR_UNUSED(buf), enum sec_status ATTR_UNUSED(s),
2073 	char* ATTR_UNUSED(why_bogus), int ATTR_UNUSED(was_ratelimited))
2074 {
2075 	log_assert(0);
2076 }
2077 
2078 void libworker_bg_done_cb(void* ATTR_UNUSED(arg), int ATTR_UNUSED(rcode),
2079 	sldns_buffer* ATTR_UNUSED(buf), enum sec_status ATTR_UNUSED(s),
2080 	char* ATTR_UNUSED(why_bogus), int ATTR_UNUSED(was_ratelimited))
2081 {
2082 	log_assert(0);
2083 }
2084 
2085 void libworker_event_done_cb(void* ATTR_UNUSED(arg), int ATTR_UNUSED(rcode),
2086 	sldns_buffer* ATTR_UNUSED(buf), enum sec_status ATTR_UNUSED(s),
2087 	char* ATTR_UNUSED(why_bogus), int ATTR_UNUSED(was_ratelimited))
2088 {
2089 	log_assert(0);
2090 }
2091 
2092 int context_query_cmp(const void* ATTR_UNUSED(a), const void* ATTR_UNUSED(b))
2093 {
2094 	log_assert(0);
2095 	return 0;
2096 }
2097 
2098 int order_lock_cmp(const void* ATTR_UNUSED(e1), const void* ATTR_UNUSED(e2))
2099 {
2100 	log_assert(0);
2101 	return 0;
2102 }
2103 
2104 int codeline_cmp(const void* ATTR_UNUSED(a), const void* ATTR_UNUSED(b))
2105 {
2106 	log_assert(0);
2107 	return 0;
2108 }
2109 
2110 #ifdef USE_DNSTAP
2111 void dtio_tap_callback(int ATTR_UNUSED(fd), short ATTR_UNUSED(ev),
2112 	void* ATTR_UNUSED(arg))
2113 {
2114 	log_assert(0);
2115 }
2116 #endif
2117 
2118 #ifdef USE_DNSTAP
2119 void dtio_mainfdcallback(int ATTR_UNUSED(fd), short ATTR_UNUSED(ev),
2120 	void* ATTR_UNUSED(arg))
2121 {
2122 	log_assert(0);
2123 }
2124 #endif
2125