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