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