xref: /freebsd/contrib/unbound/daemon/worker.c (revision 24e365220007c415f495cf8dcb228ece6002b8b7)
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 			"subnetcache")==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 			"subnetcache")==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 	uint16_t udpsize = edns->udp_size;
453 	int secure = 0;
454 	time_t timenow = *worker->env.now;
455 	int must_validate = (!(flags&BIT_CD) || worker->env.cfg->ignore_cd)
456 		&& worker->env.need_to_validate;
457 	struct dns_msg *msg = NULL;
458 	struct delegpt *dp;
459 
460 	dp = dns_cache_find_delegation(&worker->env, qinfo->qname,
461 		qinfo->qname_len, qinfo->qtype, qinfo->qclass,
462 		worker->scratchpad, &msg, timenow);
463 	if(!dp) { /* no delegation, need to reprime */
464 		return 0;
465 	}
466 	/* In case we have a local alias, copy it into the delegation message.
467 	 * Shallow copy should be fine, as we'll be done with msg in this
468 	 * function. */
469 	msg->qinfo.local_alias = qinfo->local_alias;
470 	if(must_validate) {
471 		switch(check_delegation_secure(msg->rep)) {
472 		case sec_status_unchecked:
473 			/* some rrsets have not been verified yet, go and
474 			 * let validator do that */
475 			return 0;
476 		case sec_status_bogus:
477 		case sec_status_secure_sentinel_fail:
478 			/* some rrsets are bogus, reply servfail */
479 			edns->edns_version = EDNS_ADVERTISED_VERSION;
480 			edns->udp_size = EDNS_ADVERTISED_SIZE;
481 			edns->ext_rcode = 0;
482 			edns->bits &= EDNS_DO;
483 			if(!inplace_cb_reply_servfail_call(&worker->env, qinfo, NULL,
484 				msg->rep, LDNS_RCODE_SERVFAIL, edns, repinfo, worker->scratchpad,
485 				worker->env.now_tv))
486 					return 0;
487 			error_encode(repinfo->c->buffer, LDNS_RCODE_SERVFAIL,
488 				&msg->qinfo, id, flags, edns);
489 			if(worker->stats.extended) {
490 				worker->stats.ans_bogus++;
491 				worker->stats.ans_rcode[LDNS_RCODE_SERVFAIL]++;
492 			}
493 			return 1;
494 		case sec_status_secure:
495 			/* all rrsets are secure */
496 			/* remove non-secure rrsets from the add. section*/
497 			if(worker->env.cfg->val_clean_additional)
498 				deleg_remove_nonsecure_additional(msg->rep);
499 			secure = 1;
500 			break;
501 		case sec_status_indeterminate:
502 		case sec_status_insecure:
503 		default:
504 			/* not secure */
505 			secure = 0;
506 			break;
507 		}
508 	}
509 	/* return this delegation from the cache */
510 	edns->edns_version = EDNS_ADVERTISED_VERSION;
511 	edns->udp_size = EDNS_ADVERTISED_SIZE;
512 	edns->ext_rcode = 0;
513 	edns->bits &= EDNS_DO;
514 	if(!inplace_cb_reply_cache_call(&worker->env, qinfo, NULL, msg->rep,
515 		(int)(flags&LDNS_RCODE_MASK), edns, repinfo, worker->scratchpad,
516 		worker->env.now_tv))
517 			return 0;
518 	msg->rep->flags |= BIT_QR|BIT_RA;
519 	if(!reply_info_answer_encode(&msg->qinfo, msg->rep, id, flags,
520 		repinfo->c->buffer, 0, 1, worker->scratchpad,
521 		udpsize, edns, (int)(edns->bits & EDNS_DO), secure)) {
522 		if(!inplace_cb_reply_servfail_call(&worker->env, qinfo, NULL, NULL,
523 			LDNS_RCODE_SERVFAIL, edns, repinfo, worker->scratchpad,
524 			worker->env.now_tv))
525 				edns->opt_list_inplace_cb_out = NULL;
526 		error_encode(repinfo->c->buffer, LDNS_RCODE_SERVFAIL,
527 			&msg->qinfo, id, flags, edns);
528 	}
529 	if(worker->stats.extended) {
530 		if(secure) worker->stats.ans_secure++;
531 		server_stats_insrcode(&worker->stats, repinfo->c->buffer);
532 	}
533 	return 1;
534 }
535 
536 /** Apply, if applicable, a response IP action to a cached answer.
537  * If the answer is rewritten as a result of an action, '*encode_repp' will
538  * point to the reply info containing the modified answer.  '*encode_repp' will
539  * be intact otherwise.
540  * It returns 1 on success, 0 otherwise. */
541 static int
542 apply_respip_action(struct worker* worker, const struct query_info* qinfo,
543 	struct respip_client_info* cinfo, struct reply_info* rep,
544 	struct comm_reply* repinfo, struct ub_packed_rrset_key** alias_rrset,
545 	struct reply_info** encode_repp, struct auth_zones* az)
546 {
547 	struct respip_action_info actinfo = {0, 0, 0, 0, NULL, 0, NULL};
548 	actinfo.action = respip_none;
549 
550 	if(qinfo->qtype != LDNS_RR_TYPE_A &&
551 		qinfo->qtype != LDNS_RR_TYPE_AAAA &&
552 		qinfo->qtype != LDNS_RR_TYPE_ANY)
553 		return 1;
554 
555 	if(!respip_rewrite_reply(qinfo, cinfo, rep, encode_repp, &actinfo,
556 		alias_rrset, 0, worker->scratchpad, az))
557 		return 0;
558 
559 	/* xxx_deny actions mean dropping the reply, unless the original reply
560 	 * was redirected to response-ip data. */
561 	if((actinfo.action == respip_deny ||
562 		actinfo.action == respip_inform_deny) &&
563 		*encode_repp == rep)
564 		*encode_repp = NULL;
565 
566 	/* If address info is returned, it means the action should be an
567 	 * 'inform' variant and the information should be logged. */
568 	if(actinfo.addrinfo) {
569 		respip_inform_print(&actinfo, qinfo->qname,
570 			qinfo->qtype, qinfo->qclass, qinfo->local_alias,
571 			repinfo);
572 
573 		if(worker->stats.extended && actinfo.rpz_used) {
574 			if(actinfo.rpz_disabled)
575 				worker->stats.rpz_action[RPZ_DISABLED_ACTION]++;
576 			if(actinfo.rpz_cname_override)
577 				worker->stats.rpz_action[RPZ_CNAME_OVERRIDE_ACTION]++;
578 			else
579 				worker->stats.rpz_action[
580 					respip_action_to_rpz_action(actinfo.action)]++;
581 		}
582 	}
583 
584 	return 1;
585 }
586 
587 /** answer query from the cache.
588  * Normally, the answer message will be built in repinfo->c->buffer; if the
589  * answer is supposed to be suppressed or the answer is supposed to be an
590  * incomplete CNAME chain, the buffer is explicitly cleared to signal the
591  * caller as such.  In the latter case *partial_rep will point to the incomplete
592  * reply, and this function is (possibly) supposed to be called again with that
593  * *partial_rep value to complete the chain.  In addition, if the query should
594  * be completely dropped, '*need_drop' will be set to 1. */
595 static int
596 answer_from_cache(struct worker* worker, struct query_info* qinfo,
597 	struct respip_client_info* cinfo, int* need_drop, int* is_expired_answer,
598 	int* is_secure_answer, struct ub_packed_rrset_key** alias_rrset,
599 	struct reply_info** partial_repp,
600 	struct reply_info* rep, uint16_t id, uint16_t flags,
601 	struct comm_reply* repinfo, struct edns_data* edns)
602 {
603 	time_t timenow = *worker->env.now;
604 	uint16_t udpsize = edns->udp_size;
605 	struct reply_info* encode_rep = rep;
606 	struct reply_info* partial_rep = *partial_repp;
607 	int must_validate = (!(flags&BIT_CD) || worker->env.cfg->ignore_cd)
608 		&& worker->env.need_to_validate;
609 	*partial_repp = NULL;  /* avoid accidental further pass */
610 
611 	/* Check TTL */
612 	if(rep->ttl < timenow) {
613 		/* Check if we need to serve expired now */
614 		if(worker->env.cfg->serve_expired &&
615 			!worker->env.cfg->serve_expired_client_timeout) {
616 				if(worker->env.cfg->serve_expired_ttl &&
617 					rep->serve_expired_ttl < timenow)
618 					return 0;
619 				if(!rrset_array_lock(rep->ref, rep->rrset_count, 0))
620 					return 0;
621 				*is_expired_answer = 1;
622 		} else {
623 			/* the rrsets may have been updated in the meantime.
624 			 * we will refetch the message format from the
625 			 * authoritative server
626 			 */
627 			return 0;
628 		}
629 	} else {
630 		if(!rrset_array_lock(rep->ref, rep->rrset_count, timenow))
631 			return 0;
632 	}
633 	/* locked and ids and ttls are OK. */
634 
635 	/* check CNAME chain (if any) */
636 	if(rep->an_numrrsets > 0 && (rep->rrsets[0]->rk.type ==
637 		htons(LDNS_RR_TYPE_CNAME) || rep->rrsets[0]->rk.type ==
638 		htons(LDNS_RR_TYPE_DNAME))) {
639 		if(!reply_check_cname_chain(qinfo, rep)) {
640 			/* cname chain invalid, redo iterator steps */
641 			verbose(VERB_ALGO, "Cache reply: cname chain broken");
642 			goto bail_out;
643 		}
644 	}
645 	/* check security status of the cached answer */
646 	if(must_validate && (rep->security == sec_status_bogus ||
647 		rep->security == sec_status_secure_sentinel_fail)) {
648 		/* BAD cached */
649 		edns->edns_version = EDNS_ADVERTISED_VERSION;
650 		edns->udp_size = EDNS_ADVERTISED_SIZE;
651 		edns->ext_rcode = 0;
652 		edns->bits &= EDNS_DO;
653 		if(!inplace_cb_reply_servfail_call(&worker->env, qinfo, NULL, rep,
654 			LDNS_RCODE_SERVFAIL, edns, repinfo, worker->scratchpad,
655 			worker->env.now_tv))
656 			goto bail_out;
657 		error_encode(repinfo->c->buffer, LDNS_RCODE_SERVFAIL,
658 			qinfo, id, flags, edns);
659 		rrset_array_unlock_touch(worker->env.rrset_cache,
660 			worker->scratchpad, rep->ref, rep->rrset_count);
661 		if(worker->stats.extended) {
662 			worker->stats.ans_bogus ++;
663 			worker->stats.ans_rcode[LDNS_RCODE_SERVFAIL] ++;
664 		}
665 		return 1;
666 	} else if(rep->security == sec_status_unchecked && must_validate) {
667 		verbose(VERB_ALGO, "Cache reply: unchecked entry needs "
668 			"validation");
669 		goto bail_out; /* need to validate cache entry first */
670 	} else if(rep->security == sec_status_secure) {
671 		if(reply_all_rrsets_secure(rep)) {
672 			*is_secure_answer = 1;
673 		} else {
674 			if(must_validate) {
675 				verbose(VERB_ALGO, "Cache reply: secure entry"
676 					" changed status");
677 				goto bail_out; /* rrset changed, re-verify */
678 			}
679 			*is_secure_answer = 0;
680 		}
681 	} else *is_secure_answer = 0;
682 
683 	edns->edns_version = EDNS_ADVERTISED_VERSION;
684 	edns->udp_size = EDNS_ADVERTISED_SIZE;
685 	edns->ext_rcode = 0;
686 	edns->bits &= EDNS_DO;
687 	if(!inplace_cb_reply_cache_call(&worker->env, qinfo, NULL, rep,
688 		(int)(flags&LDNS_RCODE_MASK), edns, repinfo, worker->scratchpad,
689 		worker->env.now_tv))
690 		goto bail_out;
691 	*alias_rrset = NULL; /* avoid confusion if caller set it to non-NULL */
692 	if((worker->daemon->use_response_ip || worker->daemon->use_rpz) &&
693 		!partial_rep && !apply_respip_action(worker, qinfo, cinfo, rep,
694 		repinfo, alias_rrset,
695 		&encode_rep, worker->env.auth_zones)) {
696 		goto bail_out;
697 	} else if(partial_rep &&
698 		!respip_merge_cname(partial_rep, qinfo, rep, cinfo,
699 		must_validate, &encode_rep, worker->scratchpad,
700 		worker->env.auth_zones)) {
701 		goto bail_out;
702 	}
703 	if(encode_rep != rep) {
704 		/* if rewritten, it can't be considered "secure" */
705 		*is_secure_answer = 0;
706 	}
707 	if(!encode_rep || *alias_rrset) {
708 		if(!encode_rep)
709 			*need_drop = 1;
710 		else {
711 			/* If a partial CNAME chain is found, we first need to
712 			 * make a copy of the reply in the scratchpad so we
713 			 * can release the locks and lookup the cache again. */
714 			*partial_repp = reply_info_copy(encode_rep, NULL,
715 				worker->scratchpad);
716 			if(!*partial_repp)
717 				goto bail_out;
718 		}
719 	} else if(!reply_info_answer_encode(qinfo, encode_rep, id, flags,
720 		repinfo->c->buffer, timenow, 1, worker->scratchpad,
721 		udpsize, edns, (int)(edns->bits & EDNS_DO), *is_secure_answer)) {
722 		if(!inplace_cb_reply_servfail_call(&worker->env, qinfo, NULL, NULL,
723 			LDNS_RCODE_SERVFAIL, edns, repinfo, worker->scratchpad,
724 			worker->env.now_tv))
725 				edns->opt_list_inplace_cb_out = NULL;
726 		error_encode(repinfo->c->buffer, LDNS_RCODE_SERVFAIL,
727 			qinfo, id, flags, edns);
728 	}
729 	/* cannot send the reply right now, because blocking network syscall
730 	 * is bad while holding locks. */
731 	rrset_array_unlock_touch(worker->env.rrset_cache, worker->scratchpad,
732 		rep->ref, rep->rrset_count);
733 	/* go and return this buffer to the client */
734 	return 1;
735 
736 bail_out:
737 	rrset_array_unlock_touch(worker->env.rrset_cache,
738 		worker->scratchpad, rep->ref, rep->rrset_count);
739 	return 0;
740 }
741 
742 /** Reply to client and perform prefetch to keep cache up to date. */
743 static void
744 reply_and_prefetch(struct worker* worker, struct query_info* qinfo,
745 	uint16_t flags, struct comm_reply* repinfo, time_t leeway, int noreply)
746 {
747 	/* first send answer to client to keep its latency
748 	 * as small as a cachereply */
749 	if(!noreply) {
750 		if(repinfo->c->tcp_req_info) {
751 			sldns_buffer_copy(
752 				repinfo->c->tcp_req_info->spool_buffer,
753 				repinfo->c->buffer);
754 		}
755 		comm_point_send_reply(repinfo);
756 	}
757 	server_stats_prefetch(&worker->stats, worker);
758 
759 	/* create the prefetch in the mesh as a normal lookup without
760 	 * client addrs waiting, which has the cache blacklisted (to bypass
761 	 * the cache and go to the network for the data). */
762 	/* this (potentially) runs the mesh for the new query */
763 	mesh_new_prefetch(worker->env.mesh, qinfo, flags, leeway +
764 		PREFETCH_EXPIRY_ADD);
765 }
766 
767 /**
768  * Fill CH class answer into buffer. Keeps query.
769  * @param pkt: buffer
770  * @param str: string to put into text record (<255).
771  * 	array of strings, every string becomes a text record.
772  * @param num: number of strings in array.
773  * @param edns: edns reply information.
774  * @param worker: worker with scratch region.
775  * @param repinfo: reply information for a communication point.
776  */
777 static void
778 chaos_replystr(sldns_buffer* pkt, char** str, int num, struct edns_data* edns,
779 	struct worker* worker, struct comm_reply* repinfo)
780 {
781 	int i;
782 	unsigned int rd = LDNS_RD_WIRE(sldns_buffer_begin(pkt));
783 	unsigned int cd = LDNS_CD_WIRE(sldns_buffer_begin(pkt));
784 	size_t udpsize = edns->udp_size;
785 	edns->edns_version = EDNS_ADVERTISED_VERSION;
786 	edns->udp_size = EDNS_ADVERTISED_SIZE;
787 	edns->bits &= EDNS_DO;
788 	if(!inplace_cb_reply_local_call(&worker->env, NULL, NULL, NULL,
789 		LDNS_RCODE_NOERROR, edns, repinfo, worker->scratchpad,
790 		worker->env.now_tv))
791 			edns->opt_list_inplace_cb_out = NULL;
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 		if(sldns_buffer_position(pkt)+2+2+2+4+2+1+len+
808 			calc_edns_field_size(edns) > udpsize) {
809 			sldns_buffer_write_u16_at(pkt, 6, i); /* ANCOUNT */
810 			LDNS_TC_SET(sldns_buffer_begin(pkt));
811 			break;
812 		}
813 		sldns_buffer_write_u16(pkt, 0xc00c); /* compr ptr to query */
814 		sldns_buffer_write_u16(pkt, LDNS_RR_TYPE_TXT);
815 		sldns_buffer_write_u16(pkt, LDNS_RR_CLASS_CH);
816 		sldns_buffer_write_u32(pkt, 0); /* TTL */
817 		sldns_buffer_write_u16(pkt, sizeof(uint8_t) + len);
818 		sldns_buffer_write_u8(pkt, len);
819 		sldns_buffer_write(pkt, str[i], len);
820 	}
821 	sldns_buffer_flip(pkt);
822 	if(sldns_buffer_capacity(pkt) >=
823 		sldns_buffer_limit(pkt)+calc_edns_field_size(edns))
824 		attach_edns_record(pkt, edns);
825 }
826 
827 /** Reply with one string */
828 static void
829 chaos_replyonestr(sldns_buffer* pkt, const char* str, struct edns_data* edns,
830 	struct worker* worker, struct comm_reply* repinfo)
831 {
832 	chaos_replystr(pkt, (char**)&str, 1, edns, worker, repinfo);
833 }
834 
835 /**
836  * Create CH class trustanchor answer.
837  * @param pkt: buffer
838  * @param edns: edns reply information.
839  * @param w: worker with scratch region.
840  * @param repinfo: reply information for a communication point.
841  */
842 static void
843 chaos_trustanchor(sldns_buffer* pkt, struct edns_data* edns, struct worker* w,
844 	struct comm_reply* repinfo)
845 {
846 #define TA_RESPONSE_MAX_TXT 16 /* max number of TXT records */
847 #define TA_RESPONSE_MAX_TAGS 32 /* max number of tags printed per zone */
848 	char* str_array[TA_RESPONSE_MAX_TXT];
849 	uint16_t tags[TA_RESPONSE_MAX_TAGS];
850 	int num = 0;
851 	struct trust_anchor* ta;
852 
853 	if(!w->env.need_to_validate) {
854 		/* no validator module, reply no trustanchors */
855 		chaos_replystr(pkt, NULL, 0, edns, w, repinfo);
856 		return;
857 	}
858 
859 	/* fill the string with contents */
860 	lock_basic_lock(&w->env.anchors->lock);
861 	RBTREE_FOR(ta, struct trust_anchor*, w->env.anchors->tree) {
862 		char* str;
863 		size_t i, numtag, str_len = 255;
864 		if(num == TA_RESPONSE_MAX_TXT) continue;
865 		str = (char*)regional_alloc(w->scratchpad, str_len);
866 		if(!str) continue;
867 		lock_basic_lock(&ta->lock);
868 		numtag = anchor_list_keytags(ta, tags, TA_RESPONSE_MAX_TAGS);
869 		if(numtag == 0) {
870 			/* empty, insecure point */
871 			lock_basic_unlock(&ta->lock);
872 			continue;
873 		}
874 		str_array[num] = str;
875 		num++;
876 
877 		/* spool name of anchor */
878 		(void)sldns_wire2str_dname_buf(ta->name, ta->namelen, str, str_len);
879 		str_len -= strlen(str); str += strlen(str);
880 		/* spool tags */
881 		for(i=0; i<numtag; i++) {
882 			snprintf(str, str_len, " %u", (unsigned)tags[i]);
883 			str_len -= strlen(str); str += strlen(str);
884 		}
885 		lock_basic_unlock(&ta->lock);
886 	}
887 	lock_basic_unlock(&w->env.anchors->lock);
888 
889 	chaos_replystr(pkt, str_array, num, edns, w, repinfo);
890 	regional_free_all(w->scratchpad);
891 }
892 
893 /**
894  * Answer CH class queries.
895  * @param w: worker
896  * @param qinfo: query info. Pointer into packet buffer.
897  * @param edns: edns info from query.
898  * @param repinfo: reply information for a communication point.
899  * @param pkt: packet buffer.
900  * @return: true if a reply is to be sent.
901  */
902 static int
903 answer_chaos(struct worker* w, struct query_info* qinfo,
904 	struct edns_data* edns, struct comm_reply* repinfo, sldns_buffer* pkt)
905 {
906 	struct config_file* cfg = w->env.cfg;
907 	if(qinfo->qtype != LDNS_RR_TYPE_ANY && qinfo->qtype != LDNS_RR_TYPE_TXT)
908 		return 0;
909 	if(query_dname_compare(qinfo->qname,
910 		(uint8_t*)"\002id\006server") == 0 ||
911 		query_dname_compare(qinfo->qname,
912 		(uint8_t*)"\010hostname\004bind") == 0)
913 	{
914 		if(cfg->hide_identity)
915 			return 0;
916 		if(cfg->identity==NULL || cfg->identity[0]==0) {
917 			char buf[MAXHOSTNAMELEN+1];
918 			if (gethostname(buf, MAXHOSTNAMELEN) == 0) {
919 				buf[MAXHOSTNAMELEN] = 0;
920 				chaos_replyonestr(pkt, buf, edns, w, repinfo);
921 			} else 	{
922 				log_err("gethostname: %s", strerror(errno));
923 				chaos_replyonestr(pkt, "no hostname", edns, w, repinfo);
924 			}
925 		}
926 		else 	chaos_replyonestr(pkt, cfg->identity, edns, w, repinfo);
927 		return 1;
928 	}
929 	if(query_dname_compare(qinfo->qname,
930 		(uint8_t*)"\007version\006server") == 0 ||
931 		query_dname_compare(qinfo->qname,
932 		(uint8_t*)"\007version\004bind") == 0)
933 	{
934 		if(cfg->hide_version)
935 			return 0;
936 		if(cfg->version==NULL || cfg->version[0]==0)
937 			chaos_replyonestr(pkt, PACKAGE_STRING, edns, w, repinfo);
938 		else 	chaos_replyonestr(pkt, cfg->version, edns, w, repinfo);
939 		return 1;
940 	}
941 	if(query_dname_compare(qinfo->qname,
942 		(uint8_t*)"\013trustanchor\007unbound") == 0)
943 	{
944 		if(cfg->hide_trustanchor)
945 			return 0;
946 		chaos_trustanchor(pkt, edns, w, repinfo);
947 		return 1;
948 	}
949 
950 	return 0;
951 }
952 
953 /**
954  * Answer notify queries.  These are notifies for authoritative zones,
955  * the reply is an ack that the notify has been received.  We need to check
956  * access permission here.
957  * @param w: worker
958  * @param qinfo: query info. Pointer into packet buffer.
959  * @param edns: edns info from query.
960  * @param repinfo: reply info with source address.
961  * @param pkt: packet buffer.
962  */
963 static void
964 answer_notify(struct worker* w, struct query_info* qinfo,
965 	struct edns_data* edns, sldns_buffer* pkt, struct comm_reply* repinfo)
966 {
967 	int refused = 0;
968 	int rcode = LDNS_RCODE_NOERROR;
969 	uint32_t serial = 0;
970 	int has_serial;
971 	if(!w->env.auth_zones) return;
972 	has_serial = auth_zone_parse_notify_serial(pkt, &serial);
973 	if(auth_zones_notify(w->env.auth_zones, &w->env, qinfo->qname,
974 		qinfo->qname_len, qinfo->qclass, &repinfo->addr,
975 		repinfo->addrlen, has_serial, serial, &refused)) {
976 		rcode = LDNS_RCODE_NOERROR;
977 	} else {
978 		if(refused)
979 			rcode = LDNS_RCODE_REFUSED;
980 		else	rcode = LDNS_RCODE_SERVFAIL;
981 	}
982 
983 	if(verbosity >= VERB_DETAIL) {
984 		char buf[380];
985 		char zname[255+1];
986 		char sr[25];
987 		dname_str(qinfo->qname, zname);
988 		sr[0]=0;
989 		if(has_serial)
990 			snprintf(sr, sizeof(sr), "serial %u ",
991 				(unsigned)serial);
992 		if(rcode == LDNS_RCODE_REFUSED)
993 			snprintf(buf, sizeof(buf),
994 				"refused NOTIFY %sfor %s from", sr, zname);
995 		else if(rcode == LDNS_RCODE_SERVFAIL)
996 			snprintf(buf, sizeof(buf),
997 				"servfail for NOTIFY %sfor %s from", sr, zname);
998 		else	snprintf(buf, sizeof(buf),
999 				"received NOTIFY %sfor %s from", sr, zname);
1000 		log_addr(VERB_DETAIL, buf, &repinfo->addr, repinfo->addrlen);
1001 	}
1002 	edns->edns_version = EDNS_ADVERTISED_VERSION;
1003 	edns->udp_size = EDNS_ADVERTISED_SIZE;
1004 	edns->ext_rcode = 0;
1005 	edns->bits &= EDNS_DO;
1006 	error_encode(pkt, rcode, qinfo,
1007 		*(uint16_t*)(void *)sldns_buffer_begin(pkt),
1008 		sldns_buffer_read_u16_at(pkt, 2), edns);
1009 	LDNS_OPCODE_SET(sldns_buffer_begin(pkt), LDNS_PACKET_NOTIFY);
1010 }
1011 
1012 static int
1013 deny_refuse(struct comm_point* c, enum acl_access acl,
1014 	enum acl_access deny, enum acl_access refuse,
1015 	struct worker* worker, struct comm_reply* repinfo)
1016 {
1017 	if(acl == deny) {
1018 		comm_point_drop_reply(repinfo);
1019 		if(worker->stats.extended)
1020 			worker->stats.unwanted_queries++;
1021 		return 0;
1022 	} else if(acl == refuse) {
1023 		log_addr(VERB_ALGO, "refused query from",
1024 			&repinfo->addr, repinfo->addrlen);
1025 		log_buf(VERB_ALGO, "refuse", c->buffer);
1026 		if(worker->stats.extended)
1027 			worker->stats.unwanted_queries++;
1028 		if(worker_check_request(c->buffer, worker) == -1) {
1029 			comm_point_drop_reply(repinfo);
1030 			return 0; /* discard this */
1031 		}
1032 		sldns_buffer_set_limit(c->buffer, LDNS_HEADER_SIZE);
1033 		sldns_buffer_write_at(c->buffer, 4,
1034 			(uint8_t*)"\0\0\0\0\0\0\0\0", 8);
1035 		LDNS_QR_SET(sldns_buffer_begin(c->buffer));
1036 		LDNS_RCODE_SET(sldns_buffer_begin(c->buffer),
1037 			LDNS_RCODE_REFUSED);
1038 		sldns_buffer_set_position(c->buffer, LDNS_HEADER_SIZE);
1039 		sldns_buffer_flip(c->buffer);
1040 		return 1;
1041 	}
1042 
1043 	return -1;
1044 }
1045 
1046 static int
1047 deny_refuse_all(struct comm_point* c, enum acl_access acl,
1048 	struct worker* worker, struct comm_reply* repinfo)
1049 {
1050 	return deny_refuse(c, acl, acl_deny, acl_refuse, worker, repinfo);
1051 }
1052 
1053 static int
1054 deny_refuse_non_local(struct comm_point* c, enum acl_access acl,
1055 	struct worker* worker, struct comm_reply* repinfo)
1056 {
1057 	return deny_refuse(c, acl, acl_deny_non_local, acl_refuse_non_local, worker, repinfo);
1058 }
1059 
1060 int
1061 worker_handle_request(struct comm_point* c, void* arg, int error,
1062 	struct comm_reply* repinfo)
1063 {
1064 	struct worker* worker = (struct worker*)arg;
1065 	int ret;
1066 	hashvalue_type h;
1067 	struct lruhash_entry* e;
1068 	struct query_info qinfo;
1069 	struct edns_data edns;
1070 	enum acl_access acl;
1071 	struct acl_addr* acladdr;
1072 	int rc = 0;
1073 	int need_drop = 0;
1074 	int is_expired_answer = 0;
1075 	int is_secure_answer = 0;
1076 	/* We might have to chase a CNAME chain internally, in which case
1077 	 * we'll have up to two replies and combine them to build a complete
1078 	 * answer.  These variables control this case. */
1079 	struct ub_packed_rrset_key* alias_rrset = NULL;
1080 	struct reply_info* partial_rep = NULL;
1081 	struct query_info* lookup_qinfo = &qinfo;
1082 	struct query_info qinfo_tmp; /* placeholder for lookup_qinfo */
1083 	struct respip_client_info* cinfo = NULL, cinfo_tmp;
1084 	memset(&qinfo, 0, sizeof(qinfo));
1085 
1086 	if((error != NETEVENT_NOERROR && error != NETEVENT_DONE)|| !repinfo) {
1087 		/* some bad tcp query DNS formats give these error calls */
1088 		verbose(VERB_ALGO, "handle request called with err=%d", error);
1089 		return 0;
1090 	}
1091 #ifdef USE_DNSCRYPT
1092 	repinfo->max_udp_size = worker->daemon->cfg->max_udp_size;
1093 	if(!dnsc_handle_curved_request(worker->daemon->dnscenv, repinfo)) {
1094 		worker->stats.num_query_dnscrypt_crypted_malformed++;
1095 		return 0;
1096 	}
1097 	if(c->dnscrypt && !repinfo->is_dnscrypted) {
1098 		char buf[LDNS_MAX_DOMAINLEN+1];
1099 		/* Check if this is unencrypted and asking for certs */
1100 		if(worker_check_request(c->buffer, worker) != 0) {
1101 			verbose(VERB_ALGO,
1102 				"dnscrypt: worker check request: bad query.");
1103 			log_addr(VERB_CLIENT,"from",&repinfo->addr,
1104 				repinfo->addrlen);
1105 			comm_point_drop_reply(repinfo);
1106 			return 0;
1107 		}
1108 		if(!query_info_parse(&qinfo, c->buffer)) {
1109 			verbose(VERB_ALGO,
1110 				"dnscrypt: worker parse request: formerror.");
1111 			log_addr(VERB_CLIENT, "from", &repinfo->addr,
1112 				repinfo->addrlen);
1113 			comm_point_drop_reply(repinfo);
1114 			return 0;
1115 		}
1116 		dname_str(qinfo.qname, buf);
1117 		if(!(qinfo.qtype == LDNS_RR_TYPE_TXT &&
1118 			strcasecmp(buf,
1119 			worker->daemon->dnscenv->provider_name) == 0)) {
1120 			verbose(VERB_ALGO,
1121 				"dnscrypt: not TXT \"%s\". Received: %s \"%s\"",
1122 				worker->daemon->dnscenv->provider_name,
1123 				sldns_rr_descript(qinfo.qtype)->_name,
1124 				buf);
1125 			comm_point_drop_reply(repinfo);
1126 			worker->stats.num_query_dnscrypt_cleartext++;
1127 			return 0;
1128 		}
1129 		worker->stats.num_query_dnscrypt_cert++;
1130 		sldns_buffer_rewind(c->buffer);
1131 	} else if(c->dnscrypt && repinfo->is_dnscrypted) {
1132 		worker->stats.num_query_dnscrypt_crypted++;
1133 	}
1134 #endif
1135 #ifdef USE_DNSTAP
1136 	/*
1137 	 * sending src (client)/dst (local service) addresses over DNSTAP from incoming request handler
1138 	 */
1139 	if(worker->dtenv.log_client_query_messages) {
1140 		log_addr(VERB_ALGO, "request from client", &repinfo->addr, repinfo->addrlen);
1141 		log_addr(VERB_ALGO, "to local addr", (void*)repinfo->c->socket->addr->ai_addr, repinfo->c->socket->addr->ai_addrlen);
1142 		dt_msg_send_client_query(&worker->dtenv, &repinfo->addr, (void*)repinfo->c->socket->addr->ai_addr, c->type, c->buffer);
1143 	}
1144 #endif
1145 	acladdr = acl_addr_lookup(worker->daemon->acl, &repinfo->addr,
1146 		repinfo->addrlen);
1147 	acl = acl_get_control(acladdr);
1148 	if((ret=deny_refuse_all(c, acl, worker, repinfo)) != -1)
1149 	{
1150 		if(ret == 1)
1151 			goto send_reply;
1152 		return ret;
1153 	}
1154 	if((ret=worker_check_request(c->buffer, worker)) != 0) {
1155 		verbose(VERB_ALGO, "worker check request: bad query.");
1156 		log_addr(VERB_CLIENT,"from",&repinfo->addr, repinfo->addrlen);
1157 		if(ret != -1) {
1158 			LDNS_QR_SET(sldns_buffer_begin(c->buffer));
1159 			LDNS_RCODE_SET(sldns_buffer_begin(c->buffer), ret);
1160 			return 1;
1161 		}
1162 		comm_point_drop_reply(repinfo);
1163 		return 0;
1164 	}
1165 
1166 	worker->stats.num_queries++;
1167 
1168 	/* check if this query should be dropped based on source ip rate limiting */
1169 	if(!infra_ip_ratelimit_inc(worker->env.infra_cache, repinfo,
1170 			*worker->env.now, c->buffer)) {
1171 		/* See if we are passed through with slip factor */
1172 		if(worker->env.cfg->ip_ratelimit_factor != 0 &&
1173 			ub_random_max(worker->env.rnd,
1174 						  worker->env.cfg->ip_ratelimit_factor) == 0) {
1175 
1176 			char addrbuf[128];
1177 			addr_to_str(&repinfo->addr, repinfo->addrlen,
1178 						addrbuf, sizeof(addrbuf));
1179 		  verbose(VERB_QUERY, "ip_ratelimit allowed through for ip address %s because of slip in ip_ratelimit_factor",
1180 				  addrbuf);
1181 		} else {
1182 			worker->stats.num_queries_ip_ratelimited++;
1183 			comm_point_drop_reply(repinfo);
1184 			return 0;
1185 		}
1186 	}
1187 
1188 	/* see if query is in the cache */
1189 	if(!query_info_parse(&qinfo, c->buffer)) {
1190 		verbose(VERB_ALGO, "worker parse request: formerror.");
1191 		log_addr(VERB_CLIENT,"from",&repinfo->addr, repinfo->addrlen);
1192 		memset(&qinfo, 0, sizeof(qinfo)); /* zero qinfo.qname */
1193 		if(worker_err_ratelimit(worker, LDNS_RCODE_FORMERR) == -1) {
1194 			comm_point_drop_reply(repinfo);
1195 			return 0;
1196 		}
1197 		sldns_buffer_rewind(c->buffer);
1198 		LDNS_QR_SET(sldns_buffer_begin(c->buffer));
1199 		LDNS_RCODE_SET(sldns_buffer_begin(c->buffer),
1200 			LDNS_RCODE_FORMERR);
1201 		goto send_reply;
1202 	}
1203 	if(worker->env.cfg->log_queries) {
1204 		char ip[128];
1205 		addr_to_str(&repinfo->addr, repinfo->addrlen, ip, sizeof(ip));
1206 		log_query_in(ip, qinfo.qname, qinfo.qtype, qinfo.qclass);
1207 	}
1208 	if(qinfo.qtype == LDNS_RR_TYPE_AXFR ||
1209 		qinfo.qtype == LDNS_RR_TYPE_IXFR) {
1210 		verbose(VERB_ALGO, "worker request: refused zone transfer.");
1211 		log_addr(VERB_CLIENT,"from",&repinfo->addr, repinfo->addrlen);
1212 		sldns_buffer_rewind(c->buffer);
1213 		LDNS_QR_SET(sldns_buffer_begin(c->buffer));
1214 		LDNS_RCODE_SET(sldns_buffer_begin(c->buffer),
1215 			LDNS_RCODE_REFUSED);
1216 		if(worker->stats.extended) {
1217 			worker->stats.qtype[qinfo.qtype]++;
1218 		}
1219 		goto send_reply;
1220 	}
1221 	if(qinfo.qtype == LDNS_RR_TYPE_OPT ||
1222 		qinfo.qtype == LDNS_RR_TYPE_TSIG ||
1223 		qinfo.qtype == LDNS_RR_TYPE_TKEY ||
1224 		qinfo.qtype == LDNS_RR_TYPE_MAILA ||
1225 		qinfo.qtype == LDNS_RR_TYPE_MAILB ||
1226 		(qinfo.qtype >= 128 && qinfo.qtype <= 248)) {
1227 		verbose(VERB_ALGO, "worker request: formerror for meta-type.");
1228 		log_addr(VERB_CLIENT,"from",&repinfo->addr, repinfo->addrlen);
1229 		if(worker_err_ratelimit(worker, LDNS_RCODE_FORMERR) == -1) {
1230 			comm_point_drop_reply(repinfo);
1231 			return 0;
1232 		}
1233 		sldns_buffer_rewind(c->buffer);
1234 		LDNS_QR_SET(sldns_buffer_begin(c->buffer));
1235 		LDNS_RCODE_SET(sldns_buffer_begin(c->buffer),
1236 			LDNS_RCODE_FORMERR);
1237 		if(worker->stats.extended) {
1238 			worker->stats.qtype[qinfo.qtype]++;
1239 		}
1240 		goto send_reply;
1241 	}
1242 	if((ret=parse_edns_from_query_pkt(c->buffer, &edns, worker->env.cfg, c,
1243 					worker->scratchpad)) != 0) {
1244 		struct edns_data reply_edns;
1245 		verbose(VERB_ALGO, "worker parse edns: formerror.");
1246 		log_addr(VERB_CLIENT,"from",&repinfo->addr, repinfo->addrlen);
1247 		memset(&reply_edns, 0, sizeof(reply_edns));
1248 		reply_edns.edns_present = 1;
1249 		reply_edns.udp_size = EDNS_ADVERTISED_SIZE;
1250 		LDNS_RCODE_SET(sldns_buffer_begin(c->buffer), ret);
1251 		error_encode(c->buffer, ret, &qinfo,
1252 			*(uint16_t*)(void *)sldns_buffer_begin(c->buffer),
1253 			sldns_buffer_read_u16_at(c->buffer, 2), &reply_edns);
1254 		regional_free_all(worker->scratchpad);
1255 		goto send_reply;
1256 	}
1257 	if(edns.edns_present) {
1258 		if(edns.edns_version != 0) {
1259 			edns.ext_rcode = (uint8_t)(EDNS_RCODE_BADVERS>>4);
1260 			edns.edns_version = EDNS_ADVERTISED_VERSION;
1261 			edns.udp_size = EDNS_ADVERTISED_SIZE;
1262 			edns.bits &= EDNS_DO;
1263 			edns.opt_list_in = NULL;
1264 			edns.opt_list_out = NULL;
1265 			edns.opt_list_inplace_cb_out = 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 	}
1286 	if(edns.udp_size > worker->daemon->cfg->max_udp_size &&
1287 		c->type == comm_udp) {
1288 		verbose(VERB_QUERY,
1289 			"worker request: max UDP reply size modified"
1290 			" (%d to max-udp-size)", (int)edns.udp_size);
1291 		log_addr(VERB_CLIENT,"from",&repinfo->addr, repinfo->addrlen);
1292 		edns.udp_size = worker->daemon->cfg->max_udp_size;
1293 	}
1294 	if(edns.udp_size < LDNS_HEADER_SIZE) {
1295 		verbose(VERB_ALGO, "worker request: edns is too small.");
1296 		log_addr(VERB_CLIENT, "from", &repinfo->addr, repinfo->addrlen);
1297 		LDNS_QR_SET(sldns_buffer_begin(c->buffer));
1298 		LDNS_TC_SET(sldns_buffer_begin(c->buffer));
1299 		LDNS_RCODE_SET(sldns_buffer_begin(c->buffer),
1300 			LDNS_RCODE_SERVFAIL);
1301 		sldns_buffer_set_position(c->buffer, LDNS_HEADER_SIZE);
1302 		sldns_buffer_write_at(c->buffer, 4,
1303 			(uint8_t*)"\0\0\0\0\0\0\0\0", 8);
1304 		sldns_buffer_flip(c->buffer);
1305 		regional_free_all(worker->scratchpad);
1306 		goto send_reply;
1307 	}
1308 	if(worker->stats.extended)
1309 		server_stats_insquery(&worker->stats, c, qinfo.qtype,
1310 			qinfo.qclass, &edns, repinfo);
1311 	if(c->type != comm_udp)
1312 		edns.udp_size = 65535; /* max size for TCP replies */
1313 	if(qinfo.qclass == LDNS_RR_CLASS_CH && answer_chaos(worker, &qinfo,
1314 		&edns, repinfo, c->buffer)) {
1315 		regional_free_all(worker->scratchpad);
1316 		goto send_reply;
1317 	}
1318 	if(LDNS_OPCODE_WIRE(sldns_buffer_begin(c->buffer)) ==
1319 		LDNS_PACKET_NOTIFY) {
1320 		answer_notify(worker, &qinfo, &edns, c->buffer, repinfo);
1321 		regional_free_all(worker->scratchpad);
1322 		goto send_reply;
1323 	}
1324 	if(local_zones_answer(worker->daemon->local_zones, &worker->env, &qinfo,
1325 		&edns, c->buffer, worker->scratchpad, repinfo, acladdr->taglist,
1326 		acladdr->taglen, acladdr->tag_actions,
1327 		acladdr->tag_actions_size, acladdr->tag_datas,
1328 		acladdr->tag_datas_size, worker->daemon->cfg->tagname,
1329 		worker->daemon->cfg->num_tags, acladdr->view)) {
1330 		regional_free_all(worker->scratchpad);
1331 		if(sldns_buffer_limit(c->buffer) == 0) {
1332 			comm_point_drop_reply(repinfo);
1333 			return 0;
1334 		}
1335 		goto send_reply;
1336 	}
1337 	if(worker->env.auth_zones &&
1338 		rpz_callback_from_worker_request(worker->env.auth_zones,
1339 		&worker->env, &qinfo, &edns, c->buffer, worker->scratchpad,
1340 		repinfo, acladdr->taglist, acladdr->taglen, &worker->stats)) {
1341 		regional_free_all(worker->scratchpad);
1342 		if(sldns_buffer_limit(c->buffer) == 0) {
1343 			comm_point_drop_reply(repinfo);
1344 			return 0;
1345 		}
1346 		goto send_reply;
1347 	}
1348 	if(worker->env.auth_zones &&
1349 		auth_zones_answer(worker->env.auth_zones, &worker->env,
1350 		&qinfo, &edns, repinfo, c->buffer, worker->scratchpad)) {
1351 		regional_free_all(worker->scratchpad);
1352 		if(sldns_buffer_limit(c->buffer) == 0) {
1353 			comm_point_drop_reply(repinfo);
1354 			return 0;
1355 		}
1356 		/* set RA for everyone that can have recursion (based on
1357 		 * access control list) */
1358 		if(LDNS_RD_WIRE(sldns_buffer_begin(c->buffer)) &&
1359 		   acl != acl_deny_non_local && acl != acl_refuse_non_local)
1360 			LDNS_RA_SET(sldns_buffer_begin(c->buffer));
1361 		goto send_reply;
1362 	}
1363 
1364 	/* We've looked in our local zones. If the answer isn't there, we
1365 	 * might need to bail out based on ACLs now. */
1366 	if((ret=deny_refuse_non_local(c, acl, worker, repinfo)) != -1)
1367 	{
1368 		regional_free_all(worker->scratchpad);
1369 		if(ret == 1)
1370 			goto send_reply;
1371 		return ret;
1372 	}
1373 
1374 	/* If this request does not have the recursion bit set, verify
1375 	 * ACLs allow the recursion bit to be treated as set. */
1376 	if(!(LDNS_RD_WIRE(sldns_buffer_begin(c->buffer))) &&
1377 		acl == acl_allow_setrd ) {
1378 		LDNS_RD_SET(sldns_buffer_begin(c->buffer));
1379 	}
1380 
1381 	/* If this request does not have the recursion bit set, verify
1382 	 * ACLs allow the snooping. */
1383 	if(!(LDNS_RD_WIRE(sldns_buffer_begin(c->buffer))) &&
1384 		acl != acl_allow_snoop ) {
1385 		error_encode(c->buffer, LDNS_RCODE_REFUSED, &qinfo,
1386 			*(uint16_t*)(void *)sldns_buffer_begin(c->buffer),
1387 			sldns_buffer_read_u16_at(c->buffer, 2), NULL);
1388 		regional_free_all(worker->scratchpad);
1389 		log_addr(VERB_ALGO, "refused nonrec (cache snoop) query from",
1390 			&repinfo->addr, repinfo->addrlen);
1391 		goto send_reply;
1392 	}
1393 
1394 	/* If we've found a local alias, replace the qname with the alias
1395 	 * target before resolving it. */
1396 	if(qinfo.local_alias) {
1397 		struct ub_packed_rrset_key* rrset = qinfo.local_alias->rrset;
1398 		struct packed_rrset_data* d = rrset->entry.data;
1399 
1400 		/* Sanity check: our current implementation only supports
1401 		 * a single CNAME RRset as a local alias. */
1402 		if(qinfo.local_alias->next ||
1403 			rrset->rk.type != htons(LDNS_RR_TYPE_CNAME) ||
1404 			d->count != 1) {
1405 			log_err("assumption failure: unexpected local alias");
1406 			regional_free_all(worker->scratchpad);
1407 			return 0; /* drop it */
1408 		}
1409 		qinfo.qname = d->rr_data[0] + 2;
1410 		qinfo.qname_len = d->rr_len[0] - 2;
1411 	}
1412 
1413 	/* If we may apply IP-based actions to the answer, build the client
1414 	 * information.  As this can be expensive, skip it if there is
1415 	 * absolutely no possibility of it. */
1416 	if((worker->daemon->use_response_ip || worker->daemon->use_rpz) &&
1417 		(qinfo.qtype == LDNS_RR_TYPE_A ||
1418 		qinfo.qtype == LDNS_RR_TYPE_AAAA ||
1419 		qinfo.qtype == LDNS_RR_TYPE_ANY)) {
1420 		cinfo_tmp.taglist = acladdr->taglist;
1421 		cinfo_tmp.taglen = acladdr->taglen;
1422 		cinfo_tmp.tag_actions = acladdr->tag_actions;
1423 		cinfo_tmp.tag_actions_size = acladdr->tag_actions_size;
1424 		cinfo_tmp.tag_datas = acladdr->tag_datas;
1425 		cinfo_tmp.tag_datas_size = acladdr->tag_datas_size;
1426 		cinfo_tmp.view = acladdr->view;
1427 		cinfo_tmp.respip_set = worker->daemon->respip_set;
1428 		cinfo = &cinfo_tmp;
1429 	}
1430 
1431 lookup_cache:
1432 	/* Lookup the cache.  In case we chase an intermediate CNAME chain
1433 	 * this is a two-pass operation, and lookup_qinfo is different for
1434 	 * each pass.  We should still pass the original qinfo to
1435 	 * answer_from_cache(), however, since it's used to build the reply. */
1436 	if(!edns_bypass_cache_stage(edns.opt_list_in, &worker->env)) {
1437 		is_expired_answer = 0;
1438 		is_secure_answer = 0;
1439 		h = query_info_hash(lookup_qinfo, sldns_buffer_read_u16_at(c->buffer, 2));
1440 		if((e=slabhash_lookup(worker->env.msg_cache, h, lookup_qinfo, 0))) {
1441 			/* answer from cache - we have acquired a readlock on it */
1442 			if(answer_from_cache(worker, &qinfo,
1443 				cinfo, &need_drop, &is_expired_answer, &is_secure_answer,
1444 				&alias_rrset, &partial_rep, (struct reply_info*)e->data,
1445 				*(uint16_t*)(void *)sldns_buffer_begin(c->buffer),
1446 				sldns_buffer_read_u16_at(c->buffer, 2), repinfo,
1447 				&edns)) {
1448 				/* prefetch it if the prefetch TTL expired.
1449 				 * Note that if there is more than one pass
1450 				 * its qname must be that used for cache
1451 				 * lookup. */
1452 				if((worker->env.cfg->prefetch && *worker->env.now >=
1453 							((struct reply_info*)e->data)->prefetch_ttl) ||
1454 						(worker->env.cfg->serve_expired &&
1455 						*worker->env.now >= ((struct reply_info*)e->data)->ttl)) {
1456 
1457 					time_t leeway = ((struct reply_info*)e->
1458 						data)->ttl - *worker->env.now;
1459 					if(((struct reply_info*)e->data)->ttl
1460 						< *worker->env.now)
1461 						leeway = 0;
1462 					lock_rw_unlock(&e->lock);
1463 					reply_and_prefetch(worker, lookup_qinfo,
1464 						sldns_buffer_read_u16_at(c->buffer, 2),
1465 						repinfo, leeway,
1466 						(partial_rep || need_drop));
1467 					if(!partial_rep) {
1468 						rc = 0;
1469 						regional_free_all(worker->scratchpad);
1470 						goto send_reply_rc;
1471 					}
1472 				} else if(!partial_rep) {
1473 					lock_rw_unlock(&e->lock);
1474 					regional_free_all(worker->scratchpad);
1475 					goto send_reply;
1476 				} else {
1477 					/* Note that we've already released the
1478 					 * lock if we're here after prefetch. */
1479 					lock_rw_unlock(&e->lock);
1480 				}
1481 				/* We've found a partial reply ending with an
1482 				 * alias.  Replace the lookup qinfo for the
1483 				 * alias target and lookup the cache again to
1484 				 * (possibly) complete the reply.  As we're
1485 				 * passing the "base" reply, there will be no
1486 				 * more alias chasing. */
1487 				memset(&qinfo_tmp, 0, sizeof(qinfo_tmp));
1488 				get_cname_target(alias_rrset, &qinfo_tmp.qname,
1489 					&qinfo_tmp.qname_len);
1490 				if(!qinfo_tmp.qname) {
1491 					log_err("unexpected: invalid answer alias");
1492 					regional_free_all(worker->scratchpad);
1493 					return 0; /* drop query */
1494 				}
1495 				qinfo_tmp.qtype = qinfo.qtype;
1496 				qinfo_tmp.qclass = qinfo.qclass;
1497 				lookup_qinfo = &qinfo_tmp;
1498 				goto lookup_cache;
1499 			}
1500 			verbose(VERB_ALGO, "answer from the cache failed");
1501 			lock_rw_unlock(&e->lock);
1502 		}
1503 		if(!LDNS_RD_WIRE(sldns_buffer_begin(c->buffer))) {
1504 			if(answer_norec_from_cache(worker, &qinfo,
1505 				*(uint16_t*)(void *)sldns_buffer_begin(c->buffer),
1506 				sldns_buffer_read_u16_at(c->buffer, 2), repinfo,
1507 				&edns)) {
1508 				regional_free_all(worker->scratchpad);
1509 				goto send_reply;
1510 			}
1511 			verbose(VERB_ALGO, "answer norec from cache -- "
1512 				"need to validate or not primed");
1513 		}
1514 	}
1515 	sldns_buffer_rewind(c->buffer);
1516 	server_stats_querymiss(&worker->stats, worker);
1517 
1518 	if(verbosity >= VERB_CLIENT) {
1519 		if(c->type == comm_udp)
1520 			log_addr(VERB_CLIENT, "udp request from",
1521 				&repinfo->addr, repinfo->addrlen);
1522 		else	log_addr(VERB_CLIENT, "tcp request from",
1523 				&repinfo->addr, repinfo->addrlen);
1524 	}
1525 
1526 	/* grab a work request structure for this new request */
1527 	mesh_new_client(worker->env.mesh, &qinfo, cinfo,
1528 		sldns_buffer_read_u16_at(c->buffer, 2),
1529 		&edns, repinfo, *(uint16_t*)(void *)sldns_buffer_begin(c->buffer));
1530 	regional_free_all(worker->scratchpad);
1531 	worker_mem_report(worker, NULL);
1532 	return 0;
1533 
1534 send_reply:
1535 	rc = 1;
1536 send_reply_rc:
1537 	if(need_drop) {
1538 		comm_point_drop_reply(repinfo);
1539 		return 0;
1540 	}
1541 	if(is_expired_answer) {
1542 		worker->stats.ans_expired++;
1543 	}
1544 	server_stats_insrcode(&worker->stats, c->buffer);
1545 	if(worker->stats.extended) {
1546 		if(is_secure_answer) worker->stats.ans_secure++;
1547 	}
1548 #ifdef USE_DNSTAP
1549 	/*
1550 	 * sending src (client)/dst (local service) addresses over DNSTAP from send_reply code label (when we serviced local zone for ex.)
1551 	 */
1552 	if(worker->dtenv.log_client_response_messages) {
1553 		log_addr(VERB_ALGO, "from local addr", (void*)repinfo->c->socket->addr->ai_addr, repinfo->c->socket->addr->ai_addrlen);
1554                 log_addr(VERB_ALGO, "response to client", &repinfo->addr, repinfo->addrlen);
1555 		dt_msg_send_client_response(&worker->dtenv, &repinfo->addr, (void*)repinfo->c->socket->addr->ai_addr, c->type, c->buffer);
1556 	}
1557 #endif
1558 	if(worker->env.cfg->log_replies)
1559 	{
1560 		struct timeval tv;
1561 		memset(&tv, 0, sizeof(tv));
1562 		if(qinfo.local_alias && qinfo.local_alias->rrset &&
1563 			qinfo.local_alias->rrset->rk.dname) {
1564 			/* log original qname, before the local alias was
1565 			 * used to resolve that CNAME to something else */
1566 			qinfo.qname = qinfo.local_alias->rrset->rk.dname;
1567 			log_reply_info(NO_VERBOSE, &qinfo, &repinfo->addr, repinfo->addrlen,
1568 				tv, 1, c->buffer);
1569 		} else {
1570 			log_reply_info(NO_VERBOSE, &qinfo, &repinfo->addr, repinfo->addrlen,
1571 				tv, 1, c->buffer);
1572 		}
1573 	}
1574 #ifdef USE_DNSCRYPT
1575 	if(!dnsc_handle_uncurved_request(repinfo)) {
1576 		return 0;
1577 	}
1578 #endif
1579 	return rc;
1580 }
1581 
1582 void
1583 worker_sighandler(int sig, void* arg)
1584 {
1585 	/* note that log, print, syscalls here give race conditions.
1586 	 * And cause hangups if the log-lock is held by the application. */
1587 	struct worker* worker = (struct worker*)arg;
1588 	switch(sig) {
1589 #ifdef SIGHUP
1590 		case SIGHUP:
1591 			comm_base_exit(worker->base);
1592 			break;
1593 #endif
1594 		case SIGINT:
1595 			worker->need_to_exit = 1;
1596 			comm_base_exit(worker->base);
1597 			break;
1598 #ifdef SIGQUIT
1599 		case SIGQUIT:
1600 			worker->need_to_exit = 1;
1601 			comm_base_exit(worker->base);
1602 			break;
1603 #endif
1604 		case SIGTERM:
1605 			worker->need_to_exit = 1;
1606 			comm_base_exit(worker->base);
1607 			break;
1608 		default:
1609 			/* unknown signal, ignored */
1610 			break;
1611 	}
1612 }
1613 
1614 /** restart statistics timer for worker, if enabled */
1615 static void
1616 worker_restart_timer(struct worker* worker)
1617 {
1618 	if(worker->env.cfg->stat_interval > 0) {
1619 		struct timeval tv;
1620 #ifndef S_SPLINT_S
1621 		tv.tv_sec = worker->env.cfg->stat_interval;
1622 		tv.tv_usec = 0;
1623 #endif
1624 		comm_timer_set(worker->stat_timer, &tv);
1625 	}
1626 }
1627 
1628 void worker_stat_timer_cb(void* arg)
1629 {
1630 	struct worker* worker = (struct worker*)arg;
1631 	server_stats_log(&worker->stats, worker, worker->thread_num);
1632 	mesh_stats(worker->env.mesh, "mesh has");
1633 	worker_mem_report(worker, NULL);
1634 	/* SHM is enabled, process data to SHM */
1635 	if (worker->daemon->cfg->shm_enable) {
1636 		shm_main_run(worker);
1637 	}
1638 	if(!worker->daemon->cfg->stat_cumulative) {
1639 		worker_stats_clear(worker);
1640 	}
1641 	/* start next timer */
1642 	worker_restart_timer(worker);
1643 }
1644 
1645 void worker_probe_timer_cb(void* arg)
1646 {
1647 	struct worker* worker = (struct worker*)arg;
1648 	struct timeval tv;
1649 #ifndef S_SPLINT_S
1650 	tv.tv_sec = (time_t)autr_probe_timer(&worker->env);
1651 	tv.tv_usec = 0;
1652 #endif
1653 	if(tv.tv_sec != 0)
1654 		comm_timer_set(worker->env.probe_timer, &tv);
1655 }
1656 
1657 struct worker*
1658 worker_create(struct daemon* daemon, int id, int* ports, int n)
1659 {
1660 	unsigned int seed;
1661 	struct worker* worker = (struct worker*)calloc(1,
1662 		sizeof(struct worker));
1663 	if(!worker)
1664 		return NULL;
1665 	worker->numports = n;
1666 	worker->ports = (int*)memdup(ports, sizeof(int)*n);
1667 	if(!worker->ports) {
1668 		free(worker);
1669 		return NULL;
1670 	}
1671 	worker->daemon = daemon;
1672 	worker->thread_num = id;
1673 	if(!(worker->cmd = tube_create())) {
1674 		free(worker->ports);
1675 		free(worker);
1676 		return NULL;
1677 	}
1678 	/* create random state here to avoid locking trouble in RAND_bytes */
1679 	if(!(worker->rndstate = ub_initstate(daemon->rand))) {
1680 		log_err("could not init random numbers.");
1681 		tube_delete(worker->cmd);
1682 		free(worker->ports);
1683 		free(worker);
1684 		return NULL;
1685 	}
1686 	explicit_bzero(&seed, sizeof(seed));
1687 	return worker;
1688 }
1689 
1690 int
1691 worker_init(struct worker* worker, struct config_file *cfg,
1692 	struct listen_port* ports, int do_sigs)
1693 {
1694 #ifdef USE_DNSTAP
1695 	struct dt_env* dtenv = &worker->dtenv;
1696 #else
1697 	void* dtenv = NULL;
1698 #endif
1699 	worker->need_to_exit = 0;
1700 	worker->base = comm_base_create(do_sigs);
1701 	if(!worker->base) {
1702 		log_err("could not create event handling base");
1703 		worker_delete(worker);
1704 		return 0;
1705 	}
1706 	comm_base_set_slow_accept_handlers(worker->base, &worker_stop_accept,
1707 		&worker_start_accept, worker);
1708 	if(do_sigs) {
1709 #ifdef SIGHUP
1710 		ub_thread_sig_unblock(SIGHUP);
1711 #endif
1712 		ub_thread_sig_unblock(SIGINT);
1713 #ifdef SIGQUIT
1714 		ub_thread_sig_unblock(SIGQUIT);
1715 #endif
1716 		ub_thread_sig_unblock(SIGTERM);
1717 #ifndef LIBEVENT_SIGNAL_PROBLEM
1718 		worker->comsig = comm_signal_create(worker->base,
1719 			worker_sighandler, worker);
1720 		if(!worker->comsig
1721 #ifdef SIGHUP
1722 			|| !comm_signal_bind(worker->comsig, SIGHUP)
1723 #endif
1724 #ifdef SIGQUIT
1725 			|| !comm_signal_bind(worker->comsig, SIGQUIT)
1726 #endif
1727 			|| !comm_signal_bind(worker->comsig, SIGTERM)
1728 			|| !comm_signal_bind(worker->comsig, SIGINT)) {
1729 			log_err("could not create signal handlers");
1730 			worker_delete(worker);
1731 			return 0;
1732 		}
1733 #endif /* LIBEVENT_SIGNAL_PROBLEM */
1734 		if(!daemon_remote_open_accept(worker->daemon->rc,
1735 			worker->daemon->rc_ports, worker)) {
1736 			worker_delete(worker);
1737 			return 0;
1738 		}
1739 #ifdef UB_ON_WINDOWS
1740 		wsvc_setup_worker(worker);
1741 #endif /* UB_ON_WINDOWS */
1742 	} else { /* !do_sigs */
1743 		worker->comsig = NULL;
1744 	}
1745 #ifdef USE_DNSTAP
1746 	if(cfg->dnstap) {
1747 		log_assert(worker->daemon->dtenv != NULL);
1748 		memcpy(&worker->dtenv, worker->daemon->dtenv, sizeof(struct dt_env));
1749 		if(!dt_init(&worker->dtenv, worker->base))
1750 			fatal_exit("dt_init failed");
1751 	}
1752 #endif
1753 	worker->front = listen_create(worker->base, ports,
1754 		cfg->msg_buffer_size, (int)cfg->incoming_num_tcp,
1755 		cfg->do_tcp_keepalive
1756 			? cfg->tcp_keepalive_timeout
1757 			: cfg->tcp_idle_timeout,
1758 		cfg->harden_large_queries, cfg->http_max_streams,
1759 		cfg->http_endpoint, cfg->http_notls_downstream,
1760 		worker->daemon->tcl, worker->daemon->listen_sslctx,
1761 		dtenv, worker_handle_request, worker);
1762 	if(!worker->front) {
1763 		log_err("could not create listening sockets");
1764 		worker_delete(worker);
1765 		return 0;
1766 	}
1767 	worker->back = outside_network_create(worker->base,
1768 		cfg->msg_buffer_size, (size_t)cfg->outgoing_num_ports,
1769 		cfg->out_ifs, cfg->num_out_ifs, cfg->do_ip4, cfg->do_ip6,
1770 		cfg->do_tcp?cfg->outgoing_num_tcp:0, cfg->ip_dscp,
1771 		worker->daemon->env->infra_cache, worker->rndstate,
1772 		cfg->use_caps_bits_for_id, worker->ports, worker->numports,
1773 		cfg->unwanted_threshold, cfg->outgoing_tcp_mss,
1774 		&worker_alloc_cleanup, worker,
1775 		cfg->do_udp || cfg->udp_upstream_without_downstream,
1776 		worker->daemon->connect_sslctx, cfg->delay_close,
1777 		cfg->tls_use_sni, dtenv, cfg->udp_connect,
1778 		cfg->max_reuse_tcp_queries, cfg->tcp_reuse_timeout,
1779 		cfg->tcp_auth_query_timeout);
1780 	if(!worker->back) {
1781 		log_err("could not create outgoing sockets");
1782 		worker_delete(worker);
1783 		return 0;
1784 	}
1785 	iterator_set_ip46_support(&worker->daemon->mods, worker->daemon->env,
1786 		worker->back);
1787 	/* start listening to commands */
1788 	if(!tube_setup_bg_listen(worker->cmd, worker->base,
1789 		&worker_handle_control_cmd, worker)) {
1790 		log_err("could not create control compt.");
1791 		worker_delete(worker);
1792 		return 0;
1793 	}
1794 	worker->stat_timer = comm_timer_create(worker->base,
1795 		worker_stat_timer_cb, worker);
1796 	if(!worker->stat_timer) {
1797 		log_err("could not create statistics timer");
1798 	}
1799 
1800 	/* we use the msg_buffer_size as a good estimate for what the
1801 	 * user wants for memory usage sizes */
1802 	worker->scratchpad = regional_create_custom(cfg->msg_buffer_size);
1803 	if(!worker->scratchpad) {
1804 		log_err("malloc failure");
1805 		worker_delete(worker);
1806 		return 0;
1807 	}
1808 
1809 	server_stats_init(&worker->stats, cfg);
1810 	alloc_init(&worker->alloc, &worker->daemon->superalloc,
1811 		worker->thread_num);
1812 	alloc_set_id_cleanup(&worker->alloc, &worker_alloc_cleanup, worker);
1813 	worker->env = *worker->daemon->env;
1814 	comm_base_timept(worker->base, &worker->env.now, &worker->env.now_tv);
1815 	worker->env.worker = worker;
1816 	worker->env.worker_base = worker->base;
1817 	worker->env.send_query = &worker_send_query;
1818 	worker->env.alloc = &worker->alloc;
1819 	worker->env.outnet = worker->back;
1820 	worker->env.rnd = worker->rndstate;
1821 	/* If case prefetch is triggered, the corresponding mesh will clear
1822 	 * the scratchpad for the module env in the middle of request handling.
1823 	 * It would be prone to a use-after-free kind of bug, so we avoid
1824 	 * sharing it with worker's own scratchpad at the cost of having
1825 	 * one more pad per worker. */
1826 	worker->env.scratch = regional_create_custom(cfg->msg_buffer_size);
1827 	if(!worker->env.scratch) {
1828 		log_err("malloc failure");
1829 		worker_delete(worker);
1830 		return 0;
1831 	}
1832 	worker->env.mesh = mesh_create(&worker->daemon->mods, &worker->env);
1833 	if(!worker->env.mesh) {
1834 		log_err("malloc failure");
1835 		worker_delete(worker);
1836 		return 0;
1837 	}
1838 	/* Pass on daemon variables that we would need in the mesh area */
1839 	worker->env.mesh->use_response_ip = worker->daemon->use_response_ip;
1840 	worker->env.mesh->use_rpz = worker->daemon->use_rpz;
1841 
1842 	worker->env.detach_subs = &mesh_detach_subs;
1843 	worker->env.attach_sub = &mesh_attach_sub;
1844 	worker->env.add_sub = &mesh_add_sub;
1845 	worker->env.kill_sub = &mesh_state_delete;
1846 	worker->env.detect_cycle = &mesh_detect_cycle;
1847 	worker->env.scratch_buffer = sldns_buffer_new(cfg->msg_buffer_size);
1848 	if(!worker->env.scratch_buffer) {
1849 		log_err("malloc failure");
1850 		worker_delete(worker);
1851 		return 0;
1852 	}
1853 	if(!(worker->env.fwds = forwards_create()) ||
1854 		!forwards_apply_cfg(worker->env.fwds, cfg)) {
1855 		log_err("Could not set forward zones");
1856 		worker_delete(worker);
1857 		return 0;
1858 	}
1859 	if(!(worker->env.hints = hints_create()) ||
1860 		!hints_apply_cfg(worker->env.hints, cfg)) {
1861 		log_err("Could not set root or stub hints");
1862 		worker_delete(worker);
1863 		return 0;
1864 	}
1865 	/* one probe timer per process -- if we have 5011 anchors */
1866 	if(autr_get_num_anchors(worker->env.anchors) > 0
1867 #ifndef THREADS_DISABLED
1868 		&& worker->thread_num == 0
1869 #endif
1870 		) {
1871 		struct timeval tv;
1872 		tv.tv_sec = 0;
1873 		tv.tv_usec = 0;
1874 		worker->env.probe_timer = comm_timer_create(worker->base,
1875 			worker_probe_timer_cb, worker);
1876 		if(!worker->env.probe_timer) {
1877 			log_err("could not create 5011-probe timer");
1878 		} else {
1879 			/* let timer fire, then it can reset itself */
1880 			comm_timer_set(worker->env.probe_timer, &tv);
1881 		}
1882 	}
1883 	/* zone transfer tasks, setup once per process, if any */
1884 	if(worker->env.auth_zones
1885 #ifndef THREADS_DISABLED
1886 		&& worker->thread_num == 0
1887 #endif
1888 		) {
1889 		auth_xfer_pickup_initial(worker->env.auth_zones, &worker->env);
1890 		auth_zones_pickup_zonemd_verify(worker->env.auth_zones,
1891 			&worker->env);
1892 	}
1893 #ifdef USE_DNSTAP
1894 	if(worker->daemon->cfg->dnstap
1895 #ifndef THREADS_DISABLED
1896 		&& worker->thread_num == 0
1897 #endif
1898 		) {
1899 		if(!dt_io_thread_start(dtenv->dtio, comm_base_internal(
1900 			worker->base), worker->daemon->num)) {
1901 			log_err("could not start dnstap io thread");
1902 			worker_delete(worker);
1903 			return 0;
1904 		}
1905 	}
1906 #endif /* USE_DNSTAP */
1907 	worker_mem_report(worker, NULL);
1908 	/* if statistics enabled start timer */
1909 	if(worker->env.cfg->stat_interval > 0) {
1910 		verbose(VERB_ALGO, "set statistics interval %d secs",
1911 			worker->env.cfg->stat_interval);
1912 		worker_restart_timer(worker);
1913 	}
1914 	return 1;
1915 }
1916 
1917 void
1918 worker_work(struct worker* worker)
1919 {
1920 	comm_base_dispatch(worker->base);
1921 }
1922 
1923 void
1924 worker_delete(struct worker* worker)
1925 {
1926 	if(!worker)
1927 		return;
1928 	if(worker->env.mesh && verbosity >= VERB_OPS) {
1929 		server_stats_log(&worker->stats, worker, worker->thread_num);
1930 		mesh_stats(worker->env.mesh, "mesh has");
1931 		worker_mem_report(worker, NULL);
1932 	}
1933 	outside_network_quit_prepare(worker->back);
1934 	mesh_delete(worker->env.mesh);
1935 	sldns_buffer_free(worker->env.scratch_buffer);
1936 	forwards_delete(worker->env.fwds);
1937 	hints_delete(worker->env.hints);
1938 	listen_delete(worker->front);
1939 	outside_network_delete(worker->back);
1940 	comm_signal_delete(worker->comsig);
1941 	tube_delete(worker->cmd);
1942 	comm_timer_delete(worker->stat_timer);
1943 	comm_timer_delete(worker->env.probe_timer);
1944 	free(worker->ports);
1945 	if(worker->thread_num == 0) {
1946 #ifdef UB_ON_WINDOWS
1947 		wsvc_desetup_worker(worker);
1948 #endif /* UB_ON_WINDOWS */
1949 	}
1950 #ifdef USE_DNSTAP
1951 	if(worker->daemon->cfg->dnstap
1952 #ifndef THREADS_DISABLED
1953 		&& worker->thread_num == 0
1954 #endif
1955 		) {
1956 		dt_io_thread_stop(worker->dtenv.dtio);
1957 	}
1958 	dt_deinit(&worker->dtenv);
1959 #endif /* USE_DNSTAP */
1960 	comm_base_delete(worker->base);
1961 	ub_randfree(worker->rndstate);
1962 	alloc_clear(&worker->alloc);
1963 	regional_destroy(worker->env.scratch);
1964 	regional_destroy(worker->scratchpad);
1965 	free(worker);
1966 }
1967 
1968 struct outbound_entry*
1969 worker_send_query(struct query_info* qinfo, uint16_t flags, int dnssec,
1970 	int want_dnssec, int nocaps, struct sockaddr_storage* addr,
1971 	socklen_t addrlen, uint8_t* zone, size_t zonelen, int tcp_upstream,
1972 	int ssl_upstream, char* tls_auth_name, struct module_qstate* q)
1973 {
1974 	struct worker* worker = q->env->worker;
1975 	struct outbound_entry* e = (struct outbound_entry*)regional_alloc(
1976 		q->region, sizeof(*e));
1977 	if(!e)
1978 		return NULL;
1979 	e->qstate = q;
1980 	e->qsent = outnet_serviced_query(worker->back, qinfo, flags, dnssec,
1981 		want_dnssec, nocaps, tcp_upstream,
1982 		ssl_upstream, tls_auth_name, addr, addrlen, zone, zonelen, q,
1983 		worker_handle_service_reply, e, worker->back->udp_buff, q->env);
1984 	if(!e->qsent) {
1985 		return NULL;
1986 	}
1987 	return e;
1988 }
1989 
1990 void
1991 worker_alloc_cleanup(void* arg)
1992 {
1993 	struct worker* worker = (struct worker*)arg;
1994 	slabhash_clear(&worker->env.rrset_cache->table);
1995 	slabhash_clear(worker->env.msg_cache);
1996 }
1997 
1998 void worker_stats_clear(struct worker* worker)
1999 {
2000 	server_stats_init(&worker->stats, worker->env.cfg);
2001 	mesh_stats_clear(worker->env.mesh);
2002 	worker->back->unwanted_replies = 0;
2003 	worker->back->num_tcp_outgoing = 0;
2004 }
2005 
2006 void worker_start_accept(void* arg)
2007 {
2008 	struct worker* worker = (struct worker*)arg;
2009 	listen_start_accept(worker->front);
2010 	if(worker->thread_num == 0)
2011 		daemon_remote_start_accept(worker->daemon->rc);
2012 }
2013 
2014 void worker_stop_accept(void* arg)
2015 {
2016 	struct worker* worker = (struct worker*)arg;
2017 	listen_stop_accept(worker->front);
2018 	if(worker->thread_num == 0)
2019 		daemon_remote_stop_accept(worker->daemon->rc);
2020 }
2021 
2022 /* --- fake callbacks for fptr_wlist to work --- */
2023 struct outbound_entry* libworker_send_query(
2024 	struct query_info* ATTR_UNUSED(qinfo),
2025 	uint16_t ATTR_UNUSED(flags), int ATTR_UNUSED(dnssec),
2026 	int ATTR_UNUSED(want_dnssec), int ATTR_UNUSED(nocaps),
2027 	struct sockaddr_storage* ATTR_UNUSED(addr), socklen_t ATTR_UNUSED(addrlen),
2028 	uint8_t* ATTR_UNUSED(zone), size_t ATTR_UNUSED(zonelen), int ATTR_UNUSED(tcp_upstream),
2029 	int ATTR_UNUSED(ssl_upstream), char* ATTR_UNUSED(tls_auth_name),
2030 	struct module_qstate* ATTR_UNUSED(q))
2031 {
2032 	log_assert(0);
2033 	return 0;
2034 }
2035 
2036 int libworker_handle_service_reply(struct comm_point* ATTR_UNUSED(c),
2037 	void* ATTR_UNUSED(arg), int ATTR_UNUSED(error),
2038         struct comm_reply* ATTR_UNUSED(reply_info))
2039 {
2040 	log_assert(0);
2041 	return 0;
2042 }
2043 
2044 void libworker_handle_control_cmd(struct tube* ATTR_UNUSED(tube),
2045         uint8_t* ATTR_UNUSED(buffer), size_t ATTR_UNUSED(len),
2046         int ATTR_UNUSED(error), void* ATTR_UNUSED(arg))
2047 {
2048 	log_assert(0);
2049 }
2050 
2051 void libworker_fg_done_cb(void* ATTR_UNUSED(arg), int ATTR_UNUSED(rcode),
2052 	sldns_buffer* ATTR_UNUSED(buf), enum sec_status ATTR_UNUSED(s),
2053 	char* ATTR_UNUSED(why_bogus), int ATTR_UNUSED(was_ratelimited))
2054 {
2055 	log_assert(0);
2056 }
2057 
2058 void libworker_bg_done_cb(void* ATTR_UNUSED(arg), int ATTR_UNUSED(rcode),
2059 	sldns_buffer* ATTR_UNUSED(buf), enum sec_status ATTR_UNUSED(s),
2060 	char* ATTR_UNUSED(why_bogus), int ATTR_UNUSED(was_ratelimited))
2061 {
2062 	log_assert(0);
2063 }
2064 
2065 void libworker_event_done_cb(void* ATTR_UNUSED(arg), int ATTR_UNUSED(rcode),
2066 	sldns_buffer* ATTR_UNUSED(buf), enum sec_status ATTR_UNUSED(s),
2067 	char* ATTR_UNUSED(why_bogus), int ATTR_UNUSED(was_ratelimited))
2068 {
2069 	log_assert(0);
2070 }
2071 
2072 int context_query_cmp(const void* ATTR_UNUSED(a), const void* ATTR_UNUSED(b))
2073 {
2074 	log_assert(0);
2075 	return 0;
2076 }
2077 
2078 int order_lock_cmp(const void* ATTR_UNUSED(e1), const void* ATTR_UNUSED(e2))
2079 {
2080 	log_assert(0);
2081 	return 0;
2082 }
2083 
2084 int codeline_cmp(const void* ATTR_UNUSED(a), const void* ATTR_UNUSED(b))
2085 {
2086 	log_assert(0);
2087 	return 0;
2088 }
2089 
2090 #ifdef USE_DNSTAP
2091 void dtio_tap_callback(int ATTR_UNUSED(fd), short ATTR_UNUSED(ev),
2092 	void* ATTR_UNUSED(arg))
2093 {
2094 	log_assert(0);
2095 }
2096 #endif
2097 
2098 #ifdef USE_DNSTAP
2099 void dtio_mainfdcallback(int ATTR_UNUSED(fd), short ATTR_UNUSED(ev),
2100 	void* ATTR_UNUSED(arg))
2101 {
2102 	log_assert(0);
2103 }
2104 #endif
2105