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