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