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