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