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