xref: /freebsd/contrib/unbound/daemon/worker.c (revision 595e514d0df2bac5b813d35f83e32875dbf16a83)
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 LIMITED
25  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
26  * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE
27  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
28  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
29  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
30  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
31  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
32  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
33  * 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 <ldns/wire2host.h>
44 #include "util/log.h"
45 #include "util/net_help.h"
46 #include "util/random.h"
47 #include "daemon/worker.h"
48 #include "daemon/daemon.h"
49 #include "daemon/remote.h"
50 #include "daemon/acl_list.h"
51 #include "util/netevent.h"
52 #include "util/config_file.h"
53 #include "util/module.h"
54 #include "util/regional.h"
55 #include "util/storage/slabhash.h"
56 #include "services/listen_dnsport.h"
57 #include "services/outside_network.h"
58 #include "services/outbound_list.h"
59 #include "services/cache/rrset.h"
60 #include "services/cache/infra.h"
61 #include "services/cache/dns.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 
74 #ifdef HAVE_SYS_TYPES_H
75 #  include <sys/types.h>
76 #endif
77 #ifdef HAVE_NETDB_H
78 #include <netdb.h>
79 #endif
80 #include <signal.h>
81 #ifdef UB_ON_WINDOWS
82 #include "winrc/win_svc.h"
83 #endif
84 
85 /** Size of an UDP datagram */
86 #define NORMAL_UDP_SIZE	512 /* bytes */
87 
88 /**
89  * seconds to add to prefetch leeway.  This is a TTL that expires old rrsets
90  * earlier than they should in order to put the new update into the cache.
91  * This additional value is to make sure that if not all TTLs are equal in
92  * the message to be updated(and replaced), that rrsets with up to this much
93  * extra TTL are also replaced.  This means that the resulting new message
94  * will have (most likely) this TTL at least, avoiding very small 'split
95  * second' TTLs due to operators choosing relative primes for TTLs (or so).
96  * Also has to be at least one to break ties (and overwrite cached entry).
97  */
98 #define PREFETCH_EXPIRY_ADD 60
99 
100 #ifdef UNBOUND_ALLOC_STATS
101 /** measure memory leakage */
102 static void
103 debug_memleak(size_t accounted, size_t heap,
104 	size_t total_alloc, size_t total_free)
105 {
106 	static int init = 0;
107 	static size_t base_heap, base_accounted, base_alloc, base_free;
108 	size_t base_af, cur_af, grow_af, grow_acc;
109 	if(!init) {
110 		init = 1;
111 		base_heap = heap;
112 		base_accounted = accounted;
113 		base_alloc = total_alloc;
114 		base_free = total_free;
115 	}
116 	base_af = base_alloc - base_free;
117 	cur_af = total_alloc - total_free;
118 	grow_af = cur_af - base_af;
119 	grow_acc = accounted - base_accounted;
120 	log_info("Leakage: %d leaked. growth: %u use, %u acc, %u heap",
121 		(int)(grow_af - grow_acc), (unsigned)grow_af,
122 		(unsigned)grow_acc, (unsigned)(heap - base_heap));
123 }
124 
125 /** give debug heap size indication */
126 static void
127 debug_total_mem(size_t calctotal)
128 {
129 #ifdef HAVE_SBRK
130 	extern void* unbound_start_brk;
131 	extern size_t unbound_mem_alloc, unbound_mem_freed;
132 	void* cur = sbrk(0);
133 	int total = cur-unbound_start_brk;
134 	log_info("Total heap memory estimate: %u  total-alloc: %u  "
135 		"total-free: %u", (unsigned)total,
136 		(unsigned)unbound_mem_alloc, (unsigned)unbound_mem_freed);
137 	debug_memleak(calctotal, (size_t)total,
138 		unbound_mem_alloc, unbound_mem_freed);
139 #else
140 	(void)calctotal;
141 #endif /* HAVE_SBRK */
142 }
143 #endif /* UNBOUND_ALLOC_STATS */
144 
145 /** Report on memory usage by this thread and global */
146 static void
147 worker_mem_report(struct worker* ATTR_UNUSED(worker),
148 	struct serviced_query* ATTR_UNUSED(cur_serv))
149 {
150 #ifdef UNBOUND_ALLOC_STATS
151 	/* debug func in validator module */
152 	size_t total, front, back, mesh, msg, rrset, infra, ac, superac;
153 	size_t me, iter, val, anch;
154 	int i;
155 	if(verbosity < VERB_ALGO)
156 		return;
157 	front = listen_get_mem(worker->front);
158 	back = outnet_get_mem(worker->back);
159 	msg = slabhash_get_mem(worker->env.msg_cache);
160 	rrset = slabhash_get_mem(&worker->env.rrset_cache->table);
161 	infra = infra_get_mem(worker->env.infra_cache);
162 	mesh = mesh_get_mem(worker->env.mesh);
163 	ac = alloc_get_mem(&worker->alloc);
164 	superac = alloc_get_mem(&worker->daemon->superalloc);
165 	anch = anchors_get_mem(worker->env.anchors);
166 	iter = 0;
167 	val = 0;
168 	for(i=0; i<worker->env.mesh->mods.num; i++) {
169 		fptr_ok(fptr_whitelist_mod_get_mem(worker->env.mesh->
170 			mods.mod[i]->get_mem));
171 		if(strcmp(worker->env.mesh->mods.mod[i]->name, "validator")==0)
172 			val += (*worker->env.mesh->mods.mod[i]->get_mem)
173 				(&worker->env, i);
174 		else	iter += (*worker->env.mesh->mods.mod[i]->get_mem)
175 				(&worker->env, i);
176 	}
177 	me = sizeof(*worker) + sizeof(*worker->base) + sizeof(*worker->comsig)
178 		+ comm_point_get_mem(worker->cmd_com)
179 		+ sizeof(worker->rndstate)
180 		+ regional_get_mem(worker->scratchpad)
181 		+ sizeof(*worker->env.scratch_buffer)
182 		+ ldns_buffer_capacity(worker->env.scratch_buffer)
183 		+ forwards_get_mem(worker->env.fwds)
184 		+ hints_get_mem(worker->env.hints);
185 	if(worker->thread_num == 0)
186 		me += acl_list_get_mem(worker->daemon->acl);
187 	if(cur_serv) {
188 		me += serviced_get_mem(cur_serv);
189 	}
190 	total = front+back+mesh+msg+rrset+infra+iter+val+ac+superac+me;
191 	log_info("Memory conditions: %u front=%u back=%u mesh=%u msg=%u "
192 		"rrset=%u infra=%u iter=%u val=%u anchors=%u "
193 		"alloccache=%u globalalloccache=%u me=%u",
194 		(unsigned)total, (unsigned)front, (unsigned)back,
195 		(unsigned)mesh, (unsigned)msg, (unsigned)rrset,
196 		(unsigned)infra, (unsigned)iter, (unsigned)val, (unsigned)anch,
197 		(unsigned)ac, (unsigned)superac, (unsigned)me);
198 	debug_total_mem(total);
199 #else /* no UNBOUND_ALLOC_STATS */
200 	size_t val = 0;
201 	int i;
202 	if(verbosity < VERB_QUERY)
203 		return;
204 	for(i=0; i<worker->env.mesh->mods.num; i++) {
205 		fptr_ok(fptr_whitelist_mod_get_mem(worker->env.mesh->
206 			mods.mod[i]->get_mem));
207 		if(strcmp(worker->env.mesh->mods.mod[i]->name, "validator")==0)
208 			val += (*worker->env.mesh->mods.mod[i]->get_mem)
209 				(&worker->env, i);
210 	}
211 	verbose(VERB_QUERY, "cache memory msg=%u rrset=%u infra=%u val=%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);
216 #endif /* UNBOUND_ALLOC_STATS */
217 }
218 
219 void
220 worker_send_cmd(struct worker* worker, enum worker_commands cmd)
221 {
222 	uint32_t c = (uint32_t)htonl(cmd);
223 	if(!tube_write_msg(worker->cmd, (uint8_t*)&c, sizeof(c), 0)) {
224 		log_err("worker send cmd %d failed", (int)cmd);
225 	}
226 }
227 
228 int
229 worker_handle_reply(struct comm_point* c, void* arg, int error,
230 	struct comm_reply* reply_info)
231 {
232 	struct module_qstate* q = (struct module_qstate*)arg;
233 	struct worker* worker = q->env->worker;
234 	struct outbound_entry e;
235 	e.qstate = q;
236 	e.qsent = NULL;
237 
238 	if(error != 0) {
239 		mesh_report_reply(worker->env.mesh, &e, reply_info, error);
240 		worker_mem_report(worker, NULL);
241 		return 0;
242 	}
243 	/* sanity check. */
244 	if(!LDNS_QR_WIRE(ldns_buffer_begin(c->buffer))
245 		|| LDNS_OPCODE_WIRE(ldns_buffer_begin(c->buffer)) !=
246 			LDNS_PACKET_QUERY
247 		|| LDNS_QDCOUNT(ldns_buffer_begin(c->buffer)) > 1) {
248 		/* error becomes timeout for the module as if this reply
249 		 * never arrived. */
250 		mesh_report_reply(worker->env.mesh, &e, reply_info,
251 			NETEVENT_TIMEOUT);
252 		worker_mem_report(worker, NULL);
253 		return 0;
254 	}
255 	mesh_report_reply(worker->env.mesh, &e, reply_info, NETEVENT_NOERROR);
256 	worker_mem_report(worker, NULL);
257 	return 0;
258 }
259 
260 int
261 worker_handle_service_reply(struct comm_point* c, void* arg, int error,
262 	struct comm_reply* reply_info)
263 {
264 	struct outbound_entry* e = (struct outbound_entry*)arg;
265 	struct worker* worker = e->qstate->env->worker;
266 	struct serviced_query *sq = e->qsent;
267 
268 	verbose(VERB_ALGO, "worker svcd callback for qstate %p", e->qstate);
269 	if(error != 0) {
270 		mesh_report_reply(worker->env.mesh, e, reply_info, error);
271 		worker_mem_report(worker, sq);
272 		return 0;
273 	}
274 	/* sanity check. */
275 	if(!LDNS_QR_WIRE(ldns_buffer_begin(c->buffer))
276 		|| LDNS_OPCODE_WIRE(ldns_buffer_begin(c->buffer)) !=
277 			LDNS_PACKET_QUERY
278 		|| LDNS_QDCOUNT(ldns_buffer_begin(c->buffer)) > 1) {
279 		/* error becomes timeout for the module as if this reply
280 		 * never arrived. */
281 		verbose(VERB_ALGO, "worker: bad reply handled as timeout");
282 		mesh_report_reply(worker->env.mesh, e, reply_info,
283 			NETEVENT_TIMEOUT);
284 		worker_mem_report(worker, sq);
285 		return 0;
286 	}
287 	mesh_report_reply(worker->env.mesh, e, reply_info, NETEVENT_NOERROR);
288 	worker_mem_report(worker, sq);
289 	return 0;
290 }
291 
292 /** check request sanity.
293  * @param pkt: the wire packet to examine for sanity.
294  * @param worker: parameters for checking.
295  * @return error code, 0 OK, or -1 discard.
296 */
297 static int
298 worker_check_request(ldns_buffer* pkt, struct worker* worker)
299 {
300 	if(ldns_buffer_limit(pkt) < LDNS_HEADER_SIZE) {
301 		verbose(VERB_QUERY, "request too short, discarded");
302 		return -1;
303 	}
304 	if(ldns_buffer_limit(pkt) > NORMAL_UDP_SIZE &&
305 		worker->daemon->cfg->harden_large_queries) {
306 		verbose(VERB_QUERY, "request too large, discarded");
307 		return -1;
308 	}
309 	if(LDNS_QR_WIRE(ldns_buffer_begin(pkt))) {
310 		verbose(VERB_QUERY, "request has QR bit on, discarded");
311 		return -1;
312 	}
313 	if(LDNS_TC_WIRE(ldns_buffer_begin(pkt))) {
314 		LDNS_TC_CLR(ldns_buffer_begin(pkt));
315 		verbose(VERB_QUERY, "request bad, has TC bit on");
316 		return LDNS_RCODE_FORMERR;
317 	}
318 	if(LDNS_OPCODE_WIRE(ldns_buffer_begin(pkt)) != LDNS_PACKET_QUERY) {
319 		verbose(VERB_QUERY, "request unknown opcode %d",
320 			LDNS_OPCODE_WIRE(ldns_buffer_begin(pkt)));
321 		return LDNS_RCODE_NOTIMPL;
322 	}
323 	if(LDNS_QDCOUNT(ldns_buffer_begin(pkt)) != 1) {
324 		verbose(VERB_QUERY, "request wrong nr qd=%d",
325 			LDNS_QDCOUNT(ldns_buffer_begin(pkt)));
326 		return LDNS_RCODE_FORMERR;
327 	}
328 	if(LDNS_ANCOUNT(ldns_buffer_begin(pkt)) != 0) {
329 		verbose(VERB_QUERY, "request wrong nr an=%d",
330 			LDNS_ANCOUNT(ldns_buffer_begin(pkt)));
331 		return LDNS_RCODE_FORMERR;
332 	}
333 	if(LDNS_NSCOUNT(ldns_buffer_begin(pkt)) != 0) {
334 		verbose(VERB_QUERY, "request wrong nr ns=%d",
335 			LDNS_NSCOUNT(ldns_buffer_begin(pkt)));
336 		return LDNS_RCODE_FORMERR;
337 	}
338 	if(LDNS_ARCOUNT(ldns_buffer_begin(pkt)) > 1) {
339 		verbose(VERB_QUERY, "request wrong nr ar=%d",
340 			LDNS_ARCOUNT(ldns_buffer_begin(pkt)));
341 		return LDNS_RCODE_FORMERR;
342 	}
343 	return 0;
344 }
345 
346 void
347 worker_handle_control_cmd(struct tube* ATTR_UNUSED(tube), uint8_t* msg,
348 	size_t len, int error, void* arg)
349 {
350 	struct worker* worker = (struct worker*)arg;
351 	enum worker_commands cmd;
352 	if(error != NETEVENT_NOERROR) {
353 		free(msg);
354 		if(error == NETEVENT_CLOSED)
355 			comm_base_exit(worker->base);
356 		else	log_info("control event: %d", error);
357 		return;
358 	}
359 	if(len != sizeof(uint32_t)) {
360 		fatal_exit("bad control msg length %d", (int)len);
361 	}
362 	cmd = ldns_read_uint32(msg);
363 	free(msg);
364 	switch(cmd) {
365 	case worker_cmd_quit:
366 		verbose(VERB_ALGO, "got control cmd quit");
367 		comm_base_exit(worker->base);
368 		break;
369 	case worker_cmd_stats:
370 		verbose(VERB_ALGO, "got control cmd stats");
371 		server_stats_reply(worker, 1);
372 		break;
373 	case worker_cmd_stats_noreset:
374 		verbose(VERB_ALGO, "got control cmd stats_noreset");
375 		server_stats_reply(worker, 0);
376 		break;
377 	case worker_cmd_remote:
378 		verbose(VERB_ALGO, "got control cmd remote");
379 		daemon_remote_exec(worker);
380 		break;
381 	default:
382 		log_err("bad command %d", (int)cmd);
383 		break;
384 	}
385 }
386 
387 /** check if a delegation is secure */
388 static enum sec_status
389 check_delegation_secure(struct reply_info *rep)
390 {
391 	/* return smallest security status */
392 	size_t i;
393 	enum sec_status sec = sec_status_secure;
394 	enum sec_status s;
395 	size_t num = rep->an_numrrsets + rep->ns_numrrsets;
396 	/* check if answer and authority are OK */
397 	for(i=0; i<num; i++) {
398 		s = ((struct packed_rrset_data*)rep->rrsets[i]->entry.data)
399 			->security;
400 		if(s < sec)
401 			sec = s;
402 	}
403 	/* in additional, only unchecked triggers revalidation */
404 	for(i=num; i<rep->rrset_count; i++) {
405 		s = ((struct packed_rrset_data*)rep->rrsets[i]->entry.data)
406 			->security;
407 		if(s == sec_status_unchecked)
408 			return s;
409 	}
410 	return sec;
411 }
412 
413 /** remove nonsecure from a delegation referral additional section */
414 static void
415 deleg_remove_nonsecure_additional(struct reply_info* rep)
416 {
417 	/* we can simply edit it, since we are working in the scratch region */
418 	size_t i;
419 	enum sec_status s;
420 
421 	for(i = rep->an_numrrsets+rep->ns_numrrsets; i<rep->rrset_count; i++) {
422 		s = ((struct packed_rrset_data*)rep->rrsets[i]->entry.data)
423 			->security;
424 		if(s != sec_status_secure) {
425 			memmove(rep->rrsets+i, rep->rrsets+i+1,
426 				sizeof(struct ub_packed_rrset_key*)*
427 				(rep->rrset_count - i - 1));
428 			rep->ar_numrrsets--;
429 			rep->rrset_count--;
430 			i--;
431 		}
432 	}
433 }
434 
435 /** answer nonrecursive query from the cache */
436 static int
437 answer_norec_from_cache(struct worker* worker, struct query_info* qinfo,
438 	uint16_t id, uint16_t flags, struct comm_reply* repinfo,
439 	struct edns_data* edns)
440 {
441 	/* for a nonrecursive query return either:
442 	 * 	o an error (servfail; we try to avoid this)
443 	 * 	o a delegation (closest we have; this routine tries that)
444 	 * 	o the answer (checked by answer_from_cache)
445 	 *
446 	 * So, grab a delegation from the rrset cache.
447 	 * Then check if it needs validation, if so, this routine fails,
448 	 * so that iterator can prime and validator can verify rrsets.
449 	 */
450 	uint16_t udpsize = edns->udp_size;
451 	int secure = 0;
452 	uint32_t timenow = *worker->env.now;
453 	int must_validate = (!(flags&BIT_CD) || worker->env.cfg->ignore_cd)
454 		&& worker->env.need_to_validate;
455 	struct dns_msg *msg = NULL;
456 	struct delegpt *dp;
457 
458 	dp = dns_cache_find_delegation(&worker->env, qinfo->qname,
459 		qinfo->qname_len, qinfo->qtype, qinfo->qclass,
460 		worker->scratchpad, &msg, timenow);
461 	if(!dp) { /* no delegation, need to reprime */
462 		regional_free_all(worker->scratchpad);
463 		return 0;
464 	}
465 	if(must_validate) {
466 		switch(check_delegation_secure(msg->rep)) {
467 		case sec_status_unchecked:
468 			/* some rrsets have not been verified yet, go and
469 			 * let validator do that */
470 			regional_free_all(worker->scratchpad);
471 			return 0;
472 		case sec_status_bogus:
473 			/* some rrsets are bogus, reply servfail */
474 			edns->edns_version = EDNS_ADVERTISED_VERSION;
475 			edns->udp_size = EDNS_ADVERTISED_SIZE;
476 			edns->ext_rcode = 0;
477 			edns->bits &= EDNS_DO;
478 			error_encode(repinfo->c->buffer, LDNS_RCODE_SERVFAIL,
479 				&msg->qinfo, id, flags, edns);
480 			regional_free_all(worker->scratchpad);
481 			if(worker->stats.extended) {
482 				worker->stats.ans_bogus++;
483 				worker->stats.ans_rcode[LDNS_RCODE_SERVFAIL]++;
484 			}
485 			return 1;
486 		case sec_status_secure:
487 			/* all rrsets are secure */
488 			/* remove non-secure rrsets from the add. section*/
489 			if(worker->env.cfg->val_clean_additional)
490 				deleg_remove_nonsecure_additional(msg->rep);
491 			secure = 1;
492 			break;
493 		case sec_status_indeterminate:
494 		case sec_status_insecure:
495 		default:
496 			/* not secure */
497 			secure = 0;
498 			break;
499 		}
500 	}
501 	/* return this delegation from the cache */
502 	edns->edns_version = EDNS_ADVERTISED_VERSION;
503 	edns->udp_size = EDNS_ADVERTISED_SIZE;
504 	edns->ext_rcode = 0;
505 	edns->bits &= EDNS_DO;
506 	msg->rep->flags |= BIT_QR|BIT_RA;
507 	if(!reply_info_answer_encode(&msg->qinfo, msg->rep, id, flags,
508 		repinfo->c->buffer, 0, 1, worker->scratchpad,
509 		udpsize, edns, (int)(edns->bits & EDNS_DO), secure)) {
510 		error_encode(repinfo->c->buffer, LDNS_RCODE_SERVFAIL,
511 			&msg->qinfo, id, flags, edns);
512 	}
513 	regional_free_all(worker->scratchpad);
514 	if(worker->stats.extended) {
515 		if(secure) worker->stats.ans_secure++;
516 		server_stats_insrcode(&worker->stats, repinfo->c->buffer);
517 	}
518 	return 1;
519 }
520 
521 /** answer query from the cache */
522 static int
523 answer_from_cache(struct worker* worker, struct query_info* qinfo,
524 	struct reply_info* rep, uint16_t id, uint16_t flags,
525 	struct comm_reply* repinfo, struct edns_data* edns)
526 {
527 	uint32_t timenow = *worker->env.now;
528 	uint16_t udpsize = edns->udp_size;
529 	int secure;
530 	int must_validate = (!(flags&BIT_CD) || worker->env.cfg->ignore_cd)
531 		&& worker->env.need_to_validate;
532 	/* see if it is possible */
533 	if(rep->ttl < timenow) {
534 		/* the rrsets may have been updated in the meantime.
535 		 * we will refetch the message format from the
536 		 * authoritative server
537 		 */
538 		return 0;
539 	}
540 	if(!rrset_array_lock(rep->ref, rep->rrset_count, timenow))
541 		return 0;
542 	/* locked and ids and ttls are OK. */
543 	/* check CNAME chain (if any) */
544 	if(rep->an_numrrsets > 0 && (rep->rrsets[0]->rk.type ==
545 		htons(LDNS_RR_TYPE_CNAME) || rep->rrsets[0]->rk.type ==
546 		htons(LDNS_RR_TYPE_DNAME))) {
547 		if(!reply_check_cname_chain(rep)) {
548 			/* cname chain invalid, redo iterator steps */
549 			verbose(VERB_ALGO, "Cache reply: cname chain broken");
550 		bail_out:
551 			rrset_array_unlock_touch(worker->env.rrset_cache,
552 				worker->scratchpad, rep->ref, rep->rrset_count);
553 			regional_free_all(worker->scratchpad);
554 			return 0;
555 		}
556 	}
557 	/* check security status of the cached answer */
558 	if( rep->security == sec_status_bogus && must_validate) {
559 		/* BAD cached */
560 		edns->edns_version = EDNS_ADVERTISED_VERSION;
561 		edns->udp_size = EDNS_ADVERTISED_SIZE;
562 		edns->ext_rcode = 0;
563 		edns->bits &= EDNS_DO;
564 		error_encode(repinfo->c->buffer, LDNS_RCODE_SERVFAIL,
565 			qinfo, id, flags, edns);
566 		rrset_array_unlock_touch(worker->env.rrset_cache,
567 			worker->scratchpad, rep->ref, rep->rrset_count);
568 		regional_free_all(worker->scratchpad);
569 		if(worker->stats.extended) {
570 			worker->stats.ans_bogus ++;
571 			worker->stats.ans_rcode[LDNS_RCODE_SERVFAIL] ++;
572 		}
573 		return 1;
574 	} else if( rep->security == sec_status_unchecked && must_validate) {
575 		verbose(VERB_ALGO, "Cache reply: unchecked entry needs "
576 			"validation");
577 		goto bail_out; /* need to validate cache entry first */
578 	} else if(rep->security == sec_status_secure) {
579 		if(reply_all_rrsets_secure(rep))
580 			secure = 1;
581 		else	{
582 			if(must_validate) {
583 				verbose(VERB_ALGO, "Cache reply: secure entry"
584 					" changed status");
585 				goto bail_out; /* rrset changed, re-verify */
586 			}
587 			secure = 0;
588 		}
589 	} else	secure = 0;
590 
591 	edns->edns_version = EDNS_ADVERTISED_VERSION;
592 	edns->udp_size = EDNS_ADVERTISED_SIZE;
593 	edns->ext_rcode = 0;
594 	edns->bits &= EDNS_DO;
595 	if(!reply_info_answer_encode(qinfo, rep, id, flags,
596 		repinfo->c->buffer, timenow, 1, worker->scratchpad,
597 		udpsize, edns, (int)(edns->bits & EDNS_DO), secure)) {
598 		error_encode(repinfo->c->buffer, LDNS_RCODE_SERVFAIL,
599 			qinfo, id, flags, edns);
600 	}
601 	/* cannot send the reply right now, because blocking network syscall
602 	 * is bad while holding locks. */
603 	rrset_array_unlock_touch(worker->env.rrset_cache, worker->scratchpad,
604 		rep->ref, rep->rrset_count);
605 	regional_free_all(worker->scratchpad);
606 	if(worker->stats.extended) {
607 		if(secure) worker->stats.ans_secure++;
608 		server_stats_insrcode(&worker->stats, repinfo->c->buffer);
609 	}
610 	/* go and return this buffer to the client */
611 	return 1;
612 }
613 
614 /** Reply to client and perform prefetch to keep cache up to date */
615 static void
616 reply_and_prefetch(struct worker* worker, struct query_info* qinfo,
617 	uint16_t flags, struct comm_reply* repinfo, uint32_t leeway)
618 {
619 	/* first send answer to client to keep its latency
620 	 * as small as a cachereply */
621 	comm_point_send_reply(repinfo);
622 	server_stats_prefetch(&worker->stats, worker);
623 
624 	/* create the prefetch in the mesh as a normal lookup without
625 	 * client addrs waiting, which has the cache blacklisted (to bypass
626 	 * the cache and go to the network for the data). */
627 	/* this (potentially) runs the mesh for the new query */
628 	mesh_new_prefetch(worker->env.mesh, qinfo, flags, leeway +
629 		PREFETCH_EXPIRY_ADD);
630 }
631 
632 /**
633  * Fill CH class answer into buffer. Keeps query.
634  * @param pkt: buffer
635  * @param str: string to put into text record (<255).
636  * @param edns: edns reply information.
637  */
638 static void
639 chaos_replystr(ldns_buffer* pkt, const char* str, struct edns_data* edns)
640 {
641 	size_t len = strlen(str);
642 	unsigned int rd = LDNS_RD_WIRE(ldns_buffer_begin(pkt));
643 	unsigned int cd = LDNS_CD_WIRE(ldns_buffer_begin(pkt));
644 	if(len>255) len=255; /* cap size of TXT record */
645 	ldns_buffer_clear(pkt);
646 	ldns_buffer_skip(pkt, (ssize_t)sizeof(uint16_t)); /* skip id */
647 	ldns_buffer_write_u16(pkt, (uint16_t)(BIT_QR|BIT_RA));
648 	if(rd) LDNS_RD_SET(ldns_buffer_begin(pkt));
649 	if(cd) LDNS_CD_SET(ldns_buffer_begin(pkt));
650 	ldns_buffer_write_u16(pkt, 1); /* qdcount */
651 	ldns_buffer_write_u16(pkt, 1); /* ancount */
652 	ldns_buffer_write_u16(pkt, 0); /* nscount */
653 	ldns_buffer_write_u16(pkt, 0); /* arcount */
654 	(void)query_dname_len(pkt); /* skip qname */
655 	ldns_buffer_skip(pkt, (ssize_t)sizeof(uint16_t)); /* skip qtype */
656 	ldns_buffer_skip(pkt, (ssize_t)sizeof(uint16_t)); /* skip qclass */
657 	ldns_buffer_write_u16(pkt, 0xc00c); /* compr ptr to query */
658 	ldns_buffer_write_u16(pkt, LDNS_RR_TYPE_TXT);
659 	ldns_buffer_write_u16(pkt, LDNS_RR_CLASS_CH);
660 	ldns_buffer_write_u32(pkt, 0); /* TTL */
661 	ldns_buffer_write_u16(pkt, sizeof(uint8_t) + len);
662 	ldns_buffer_write_u8(pkt, len);
663 	ldns_buffer_write(pkt, str, len);
664 	ldns_buffer_flip(pkt);
665 	edns->edns_version = EDNS_ADVERTISED_VERSION;
666 	edns->udp_size = EDNS_ADVERTISED_SIZE;
667 	edns->bits &= EDNS_DO;
668 	attach_edns_record(pkt, edns);
669 }
670 
671 /**
672  * Answer CH class queries.
673  * @param w: worker
674  * @param qinfo: query info. Pointer into packet buffer.
675  * @param edns: edns info from query.
676  * @param pkt: packet buffer.
677  * @return: true if a reply is to be sent.
678  */
679 static int
680 answer_chaos(struct worker* w, struct query_info* qinfo,
681 	struct edns_data* edns, ldns_buffer* pkt)
682 {
683 	struct config_file* cfg = w->env.cfg;
684 	if(qinfo->qtype != LDNS_RR_TYPE_ANY && qinfo->qtype != LDNS_RR_TYPE_TXT)
685 		return 0;
686 	if(query_dname_compare(qinfo->qname,
687 		(uint8_t*)"\002id\006server") == 0 ||
688 		query_dname_compare(qinfo->qname,
689 		(uint8_t*)"\010hostname\004bind") == 0)
690 	{
691 		if(cfg->hide_identity)
692 			return 0;
693 		if(cfg->identity==NULL || cfg->identity[0]==0) {
694 			char buf[MAXHOSTNAMELEN+1];
695 			if (gethostname(buf, MAXHOSTNAMELEN) == 0) {
696 				buf[MAXHOSTNAMELEN] = 0;
697 				chaos_replystr(pkt, buf, edns);
698 			} else 	{
699 				log_err("gethostname: %s", strerror(errno));
700 				chaos_replystr(pkt, "no hostname", edns);
701 			}
702 		}
703 		else 	chaos_replystr(pkt, cfg->identity, edns);
704 		return 1;
705 	}
706 	if(query_dname_compare(qinfo->qname,
707 		(uint8_t*)"\007version\006server") == 0 ||
708 		query_dname_compare(qinfo->qname,
709 		(uint8_t*)"\007version\004bind") == 0)
710 	{
711 		if(cfg->hide_version)
712 			return 0;
713 		if(cfg->version==NULL || cfg->version[0]==0)
714 			chaos_replystr(pkt, PACKAGE_STRING, edns);
715 		else 	chaos_replystr(pkt, cfg->version, edns);
716 		return 1;
717 	}
718 	return 0;
719 }
720 
721 int
722 worker_handle_request(struct comm_point* c, void* arg, int error,
723 	struct comm_reply* repinfo)
724 {
725 	struct worker* worker = (struct worker*)arg;
726 	int ret;
727 	hashvalue_t h;
728 	struct lruhash_entry* e;
729 	struct query_info qinfo;
730 	struct edns_data edns;
731 	enum acl_access acl;
732 
733 	if(error != NETEVENT_NOERROR) {
734 		/* some bad tcp query DNS formats give these error calls */
735 		verbose(VERB_ALGO, "handle request called with err=%d", error);
736 		return 0;
737 	}
738 	acl = acl_list_lookup(worker->daemon->acl, &repinfo->addr,
739 		repinfo->addrlen);
740 	if(acl == acl_deny) {
741 		comm_point_drop_reply(repinfo);
742 		if(worker->stats.extended)
743 			worker->stats.unwanted_queries++;
744 		return 0;
745 	} else if(acl == acl_refuse) {
746 		log_addr(VERB_ALGO, "refused query from",
747 			&repinfo->addr, repinfo->addrlen);
748 		log_buf(VERB_ALGO, "refuse", c->buffer);
749 		if(worker->stats.extended)
750 			worker->stats.unwanted_queries++;
751 		if(worker_check_request(c->buffer, worker) == -1) {
752 			comm_point_drop_reply(repinfo);
753 			return 0; /* discard this */
754 		}
755 		ldns_buffer_set_limit(c->buffer, LDNS_HEADER_SIZE);
756 		ldns_buffer_write_at(c->buffer, 4,
757 			(uint8_t*)"\0\0\0\0\0\0\0\0", 8);
758 		LDNS_QR_SET(ldns_buffer_begin(c->buffer));
759 		LDNS_RCODE_SET(ldns_buffer_begin(c->buffer),
760 			LDNS_RCODE_REFUSED);
761 		return 1;
762 	}
763 	if((ret=worker_check_request(c->buffer, worker)) != 0) {
764 		verbose(VERB_ALGO, "worker check request: bad query.");
765 		log_addr(VERB_CLIENT,"from",&repinfo->addr, repinfo->addrlen);
766 		if(ret != -1) {
767 			LDNS_QR_SET(ldns_buffer_begin(c->buffer));
768 			LDNS_RCODE_SET(ldns_buffer_begin(c->buffer), ret);
769 			return 1;
770 		}
771 		comm_point_drop_reply(repinfo);
772 		return 0;
773 	}
774 	worker->stats.num_queries++;
775 	/* see if query is in the cache */
776 	if(!query_info_parse(&qinfo, c->buffer)) {
777 		verbose(VERB_ALGO, "worker parse request: formerror.");
778 		log_addr(VERB_CLIENT,"from",&repinfo->addr, repinfo->addrlen);
779 		ldns_buffer_rewind(c->buffer);
780 		LDNS_QR_SET(ldns_buffer_begin(c->buffer));
781 		LDNS_RCODE_SET(ldns_buffer_begin(c->buffer),
782 			LDNS_RCODE_FORMERR);
783 		server_stats_insrcode(&worker->stats, c->buffer);
784 		return 1;
785 	}
786 	if(worker->env.cfg->log_queries) {
787 		char ip[128];
788 		addr_to_str(&repinfo->addr, repinfo->addrlen, ip, sizeof(ip));
789 		log_nametypeclass(0, ip, qinfo.qname, qinfo.qtype, qinfo.qclass);
790 	}
791 	if(qinfo.qtype == LDNS_RR_TYPE_AXFR ||
792 		qinfo.qtype == LDNS_RR_TYPE_IXFR) {
793 		verbose(VERB_ALGO, "worker request: refused zone transfer.");
794 		log_addr(VERB_CLIENT,"from",&repinfo->addr, repinfo->addrlen);
795 		ldns_buffer_rewind(c->buffer);
796 		LDNS_QR_SET(ldns_buffer_begin(c->buffer));
797 		LDNS_RCODE_SET(ldns_buffer_begin(c->buffer),
798 			LDNS_RCODE_REFUSED);
799 		if(worker->stats.extended) {
800 			worker->stats.qtype[qinfo.qtype]++;
801 			server_stats_insrcode(&worker->stats, c->buffer);
802 		}
803 		return 1;
804 	}
805 	if((ret=parse_edns_from_pkt(c->buffer, &edns)) != 0) {
806 		verbose(VERB_ALGO, "worker parse edns: formerror.");
807 		log_addr(VERB_CLIENT,"from",&repinfo->addr, repinfo->addrlen);
808 		ldns_buffer_rewind(c->buffer);
809 		LDNS_QR_SET(ldns_buffer_begin(c->buffer));
810 		LDNS_RCODE_SET(ldns_buffer_begin(c->buffer), ret);
811 		server_stats_insrcode(&worker->stats, c->buffer);
812 		return 1;
813 	}
814 	if(edns.edns_present && edns.edns_version != 0) {
815 		edns.ext_rcode = (uint8_t)(EDNS_RCODE_BADVERS>>4);
816 		edns.edns_version = EDNS_ADVERTISED_VERSION;
817 		edns.udp_size = EDNS_ADVERTISED_SIZE;
818 		edns.bits &= EDNS_DO;
819 		verbose(VERB_ALGO, "query with bad edns version.");
820 		log_addr(VERB_CLIENT,"from",&repinfo->addr, repinfo->addrlen);
821 		error_encode(c->buffer, EDNS_RCODE_BADVERS&0xf, &qinfo,
822 			*(uint16_t*)ldns_buffer_begin(c->buffer),
823 			ldns_buffer_read_u16_at(c->buffer, 2), NULL);
824 		attach_edns_record(c->buffer, &edns);
825 		return 1;
826 	}
827 	if(edns.edns_present && edns.udp_size < NORMAL_UDP_SIZE &&
828 		worker->daemon->cfg->harden_short_bufsize) {
829 		verbose(VERB_QUERY, "worker request: EDNS bufsize %d ignored",
830 			(int)edns.udp_size);
831 		log_addr(VERB_CLIENT,"from",&repinfo->addr, repinfo->addrlen);
832 		edns.udp_size = NORMAL_UDP_SIZE;
833 	}
834 	if(edns.edns_present && edns.udp_size < LDNS_HEADER_SIZE) {
835 		verbose(VERB_ALGO, "worker request: edns is too small.");
836 		log_addr(VERB_CLIENT, "from", &repinfo->addr, repinfo->addrlen);
837 		LDNS_QR_SET(ldns_buffer_begin(c->buffer));
838 		LDNS_TC_SET(ldns_buffer_begin(c->buffer));
839 		LDNS_RCODE_SET(ldns_buffer_begin(c->buffer),
840 			LDNS_RCODE_SERVFAIL);
841 		ldns_buffer_set_position(c->buffer, LDNS_HEADER_SIZE);
842 		ldns_buffer_write_at(c->buffer, 4,
843 			(uint8_t*)"\0\0\0\0\0\0\0\0", 8);
844 		ldns_buffer_flip(c->buffer);
845 		return 1;
846 	}
847 	if(worker->stats.extended)
848 		server_stats_insquery(&worker->stats, c, qinfo.qtype,
849 			qinfo.qclass, &edns, repinfo);
850 	if(c->type != comm_udp)
851 		edns.udp_size = 65535; /* max size for TCP replies */
852 	if(qinfo.qclass == LDNS_RR_CLASS_CH && answer_chaos(worker, &qinfo,
853 		&edns, c->buffer)) {
854 		server_stats_insrcode(&worker->stats, c->buffer);
855 		return 1;
856 	}
857 	if(local_zones_answer(worker->daemon->local_zones, &qinfo, &edns,
858 		c->buffer, worker->scratchpad)) {
859 		regional_free_all(worker->scratchpad);
860 		if(ldns_buffer_limit(c->buffer) == 0) {
861 			comm_point_drop_reply(repinfo);
862 			return 0;
863 		}
864 		server_stats_insrcode(&worker->stats, c->buffer);
865 		return 1;
866 	}
867 	if(!(LDNS_RD_WIRE(ldns_buffer_begin(c->buffer))) &&
868 		acl != acl_allow_snoop ) {
869 		ldns_buffer_set_limit(c->buffer, LDNS_HEADER_SIZE);
870 		ldns_buffer_write_at(c->buffer, 4,
871 			(uint8_t*)"\0\0\0\0\0\0\0\0", 8);
872 		LDNS_QR_SET(ldns_buffer_begin(c->buffer));
873 		LDNS_RCODE_SET(ldns_buffer_begin(c->buffer),
874 			LDNS_RCODE_REFUSED);
875 		ldns_buffer_flip(c->buffer);
876 		server_stats_insrcode(&worker->stats, c->buffer);
877 		log_addr(VERB_ALGO, "refused nonrec (cache snoop) query from",
878 			&repinfo->addr, repinfo->addrlen);
879 		return 1;
880 	}
881 	h = query_info_hash(&qinfo);
882 	if((e=slabhash_lookup(worker->env.msg_cache, h, &qinfo, 0))) {
883 		/* answer from cache - we have acquired a readlock on it */
884 		if(answer_from_cache(worker, &qinfo,
885 			(struct reply_info*)e->data,
886 			*(uint16_t*)ldns_buffer_begin(c->buffer),
887 			ldns_buffer_read_u16_at(c->buffer, 2), repinfo,
888 			&edns)) {
889 			/* prefetch it if the prefetch TTL expired */
890 			if(worker->env.cfg->prefetch && *worker->env.now >=
891 				((struct reply_info*)e->data)->prefetch_ttl) {
892 				uint32_t leeway = ((struct reply_info*)e->
893 					data)->ttl - *worker->env.now;
894 				lock_rw_unlock(&e->lock);
895 				reply_and_prefetch(worker, &qinfo,
896 					ldns_buffer_read_u16_at(c->buffer, 2),
897 					repinfo, leeway);
898 				return 0;
899 			}
900 			lock_rw_unlock(&e->lock);
901 			return 1;
902 		}
903 		verbose(VERB_ALGO, "answer from the cache failed");
904 		lock_rw_unlock(&e->lock);
905 	}
906 	if(!LDNS_RD_WIRE(ldns_buffer_begin(c->buffer))) {
907 		if(answer_norec_from_cache(worker, &qinfo,
908 			*(uint16_t*)ldns_buffer_begin(c->buffer),
909 			ldns_buffer_read_u16_at(c->buffer, 2), repinfo,
910 			&edns)) {
911 			return 1;
912 		}
913 		verbose(VERB_ALGO, "answer norec from cache -- "
914 			"need to validate or not primed");
915 	}
916 	ldns_buffer_rewind(c->buffer);
917 	server_stats_querymiss(&worker->stats, worker);
918 
919 	if(verbosity >= VERB_CLIENT) {
920 		if(c->type == comm_udp)
921 			log_addr(VERB_CLIENT, "udp request from",
922 				&repinfo->addr, repinfo->addrlen);
923 		else	log_addr(VERB_CLIENT, "tcp request from",
924 				&repinfo->addr, repinfo->addrlen);
925 	}
926 
927 	/* grab a work request structure for this new request */
928 	mesh_new_client(worker->env.mesh, &qinfo,
929 		ldns_buffer_read_u16_at(c->buffer, 2),
930 		&edns, repinfo, *(uint16_t*)ldns_buffer_begin(c->buffer));
931 	worker_mem_report(worker, NULL);
932 	return 0;
933 }
934 
935 void
936 worker_sighandler(int sig, void* arg)
937 {
938 	/* note that log, print, syscalls here give race conditions. */
939 	/* we still print DETAIL logs, because this is extensive per message
940 	 * logging anyway, and the operator may then have an interest
941 	 * in the cause for unbound to exit */
942 	struct worker* worker = (struct worker*)arg;
943 	switch(sig) {
944 #ifdef SIGHUP
945 		case SIGHUP:
946 			verbose(VERB_QUERY, "caught signal SIGHUP");
947 			comm_base_exit(worker->base);
948 			break;
949 #endif
950 		case SIGINT:
951 			verbose(VERB_QUERY, "caught signal SIGINT");
952 			worker->need_to_exit = 1;
953 			comm_base_exit(worker->base);
954 			break;
955 #ifdef SIGQUIT
956 		case SIGQUIT:
957 			verbose(VERB_QUERY, "caught signal SIGQUIT");
958 			worker->need_to_exit = 1;
959 			comm_base_exit(worker->base);
960 			break;
961 #endif
962 		case SIGTERM:
963 			verbose(VERB_QUERY, "caught signal SIGTERM");
964 			worker->need_to_exit = 1;
965 			comm_base_exit(worker->base);
966 			break;
967 		default:
968 			log_err("unknown signal: %d, ignored", sig);
969 			break;
970 	}
971 }
972 
973 /** restart statistics timer for worker, if enabled */
974 static void
975 worker_restart_timer(struct worker* worker)
976 {
977 	if(worker->env.cfg->stat_interval > 0) {
978 		struct timeval tv;
979 #ifndef S_SPLINT_S
980 		tv.tv_sec = worker->env.cfg->stat_interval;
981 		tv.tv_usec = 0;
982 #endif
983 		comm_timer_set(worker->stat_timer, &tv);
984 	}
985 }
986 
987 void worker_stat_timer_cb(void* arg)
988 {
989 	struct worker* worker = (struct worker*)arg;
990 	server_stats_log(&worker->stats, worker, worker->thread_num);
991 	mesh_stats(worker->env.mesh, "mesh has");
992 	worker_mem_report(worker, NULL);
993 	if(!worker->daemon->cfg->stat_cumulative) {
994 		worker_stats_clear(worker);
995 	}
996 	/* start next timer */
997 	worker_restart_timer(worker);
998 }
999 
1000 void worker_probe_timer_cb(void* arg)
1001 {
1002 	struct worker* worker = (struct worker*)arg;
1003 	struct timeval tv;
1004 #ifndef S_SPLINT_S
1005 	tv.tv_sec = (time_t)autr_probe_timer(&worker->env);
1006 	tv.tv_usec = 0;
1007 #endif
1008 	if(tv.tv_sec != 0)
1009 		comm_timer_set(worker->env.probe_timer, &tv);
1010 }
1011 
1012 struct worker*
1013 worker_create(struct daemon* daemon, int id, int* ports, int n)
1014 {
1015 	unsigned int seed;
1016 	struct worker* worker = (struct worker*)calloc(1,
1017 		sizeof(struct worker));
1018 	if(!worker)
1019 		return NULL;
1020 	worker->numports = n;
1021 	worker->ports = (int*)memdup(ports, sizeof(int)*n);
1022 	if(!worker->ports) {
1023 		free(worker);
1024 		return NULL;
1025 	}
1026 	worker->daemon = daemon;
1027 	worker->thread_num = id;
1028 	if(!(worker->cmd = tube_create())) {
1029 		free(worker->ports);
1030 		free(worker);
1031 		return NULL;
1032 	}
1033 	/* create random state here to avoid locking trouble in RAND_bytes */
1034 	seed = (unsigned int)time(NULL) ^ (unsigned int)getpid() ^
1035 		(((unsigned int)worker->thread_num)<<17);
1036 		/* shift thread_num so it does not match out pid bits */
1037 	if(!(worker->rndstate = ub_initstate(seed, daemon->rand))) {
1038 		seed = 0;
1039 		log_err("could not init random numbers.");
1040 		tube_delete(worker->cmd);
1041 		free(worker->ports);
1042 		free(worker);
1043 		return NULL;
1044 	}
1045 	seed = 0;
1046 	return worker;
1047 }
1048 
1049 int
1050 worker_init(struct worker* worker, struct config_file *cfg,
1051 	struct listen_port* ports, int do_sigs)
1052 {
1053 	worker->need_to_exit = 0;
1054 	worker->base = comm_base_create(do_sigs);
1055 	if(!worker->base) {
1056 		log_err("could not create event handling base");
1057 		worker_delete(worker);
1058 		return 0;
1059 	}
1060 	comm_base_set_slow_accept_handlers(worker->base, &worker_stop_accept,
1061 		&worker_start_accept, worker);
1062 	if(do_sigs) {
1063 #ifdef SIGHUP
1064 		ub_thread_sig_unblock(SIGHUP);
1065 #endif
1066 		ub_thread_sig_unblock(SIGINT);
1067 #ifdef SIGQUIT
1068 		ub_thread_sig_unblock(SIGQUIT);
1069 #endif
1070 		ub_thread_sig_unblock(SIGTERM);
1071 #ifndef LIBEVENT_SIGNAL_PROBLEM
1072 		worker->comsig = comm_signal_create(worker->base,
1073 			worker_sighandler, worker);
1074 		if(!worker->comsig
1075 #ifdef SIGHUP
1076 			|| !comm_signal_bind(worker->comsig, SIGHUP)
1077 #endif
1078 #ifdef SIGQUIT
1079 			|| !comm_signal_bind(worker->comsig, SIGQUIT)
1080 #endif
1081 			|| !comm_signal_bind(worker->comsig, SIGTERM)
1082 			|| !comm_signal_bind(worker->comsig, SIGINT)) {
1083 			log_err("could not create signal handlers");
1084 			worker_delete(worker);
1085 			return 0;
1086 		}
1087 #endif /* LIBEVENT_SIGNAL_PROBLEM */
1088 		if(!daemon_remote_open_accept(worker->daemon->rc,
1089 			worker->daemon->rc_ports, worker)) {
1090 			worker_delete(worker);
1091 			return 0;
1092 		}
1093 #ifdef UB_ON_WINDOWS
1094 		wsvc_setup_worker(worker);
1095 #endif /* UB_ON_WINDOWS */
1096 	} else { /* !do_sigs */
1097 		worker->comsig = NULL;
1098 	}
1099 	worker->front = listen_create(worker->base, ports,
1100 		cfg->msg_buffer_size, (int)cfg->incoming_num_tcp,
1101 		worker->daemon->listen_sslctx, worker_handle_request, worker);
1102 	if(!worker->front) {
1103 		log_err("could not create listening sockets");
1104 		worker_delete(worker);
1105 		return 0;
1106 	}
1107 	worker->back = outside_network_create(worker->base,
1108 		cfg->msg_buffer_size, (size_t)cfg->outgoing_num_ports,
1109 		cfg->out_ifs, cfg->num_out_ifs, cfg->do_ip4, cfg->do_ip6,
1110 		cfg->do_tcp?cfg->outgoing_num_tcp:0,
1111 		worker->daemon->env->infra_cache, worker->rndstate,
1112 		cfg->use_caps_bits_for_id, worker->ports, worker->numports,
1113 		cfg->unwanted_threshold, &worker_alloc_cleanup, worker,
1114 		cfg->do_udp, worker->daemon->connect_sslctx);
1115 	if(!worker->back) {
1116 		log_err("could not create outgoing sockets");
1117 		worker_delete(worker);
1118 		return 0;
1119 	}
1120 	/* start listening to commands */
1121 	if(!tube_setup_bg_listen(worker->cmd, worker->base,
1122 		&worker_handle_control_cmd, worker)) {
1123 		log_err("could not create control compt.");
1124 		worker_delete(worker);
1125 		return 0;
1126 	}
1127 	worker->stat_timer = comm_timer_create(worker->base,
1128 		worker_stat_timer_cb, worker);
1129 	if(!worker->stat_timer) {
1130 		log_err("could not create statistics timer");
1131 	}
1132 
1133 	/* we use the msg_buffer_size as a good estimate for what the
1134 	 * user wants for memory usage sizes */
1135 	worker->scratchpad = regional_create_custom(cfg->msg_buffer_size);
1136 	if(!worker->scratchpad) {
1137 		log_err("malloc failure");
1138 		worker_delete(worker);
1139 		return 0;
1140 	}
1141 
1142 	server_stats_init(&worker->stats, cfg);
1143 	alloc_init(&worker->alloc, &worker->daemon->superalloc,
1144 		worker->thread_num);
1145 	alloc_set_id_cleanup(&worker->alloc, &worker_alloc_cleanup, worker);
1146 	worker->env = *worker->daemon->env;
1147 	comm_base_timept(worker->base, &worker->env.now, &worker->env.now_tv);
1148 	if(worker->thread_num == 0)
1149 		log_set_time(worker->env.now);
1150 	worker->env.worker = worker;
1151 	worker->env.send_query = &worker_send_query;
1152 	worker->env.alloc = &worker->alloc;
1153 	worker->env.rnd = worker->rndstate;
1154 	worker->env.scratch = worker->scratchpad;
1155 	worker->env.mesh = mesh_create(&worker->daemon->mods, &worker->env);
1156 	worker->env.detach_subs = &mesh_detach_subs;
1157 	worker->env.attach_sub = &mesh_attach_sub;
1158 	worker->env.kill_sub = &mesh_state_delete;
1159 	worker->env.detect_cycle = &mesh_detect_cycle;
1160 	worker->env.scratch_buffer = ldns_buffer_new(cfg->msg_buffer_size);
1161 	if(!(worker->env.fwds = forwards_create()) ||
1162 		!forwards_apply_cfg(worker->env.fwds, cfg)) {
1163 		log_err("Could not set forward zones");
1164 		worker_delete(worker);
1165 		return 0;
1166 	}
1167 	if(!(worker->env.hints = hints_create()) ||
1168 		!hints_apply_cfg(worker->env.hints, cfg)) {
1169 		log_err("Could not set root or stub hints");
1170 		worker_delete(worker);
1171 		return 0;
1172 	}
1173 	/* one probe timer per process -- if we have 5011 anchors */
1174 	if(autr_get_num_anchors(worker->env.anchors) > 0
1175 #ifndef THREADS_DISABLED
1176 		&& worker->thread_num == 0
1177 #endif
1178 		) {
1179 		struct timeval tv;
1180 		tv.tv_sec = 0;
1181 		tv.tv_usec = 0;
1182 		worker->env.probe_timer = comm_timer_create(worker->base,
1183 			worker_probe_timer_cb, worker);
1184 		if(!worker->env.probe_timer) {
1185 			log_err("could not create 5011-probe timer");
1186 		} else {
1187 			/* let timer fire, then it can reset itself */
1188 			comm_timer_set(worker->env.probe_timer, &tv);
1189 		}
1190 	}
1191 	if(!worker->env.mesh || !worker->env.scratch_buffer) {
1192 		worker_delete(worker);
1193 		return 0;
1194 	}
1195 	worker_mem_report(worker, NULL);
1196 	/* if statistics enabled start timer */
1197 	if(worker->env.cfg->stat_interval > 0) {
1198 		verbose(VERB_ALGO, "set statistics interval %d secs",
1199 			worker->env.cfg->stat_interval);
1200 		worker_restart_timer(worker);
1201 	}
1202 	return 1;
1203 }
1204 
1205 void
1206 worker_work(struct worker* worker)
1207 {
1208 	comm_base_dispatch(worker->base);
1209 }
1210 
1211 void
1212 worker_delete(struct worker* worker)
1213 {
1214 	if(!worker)
1215 		return;
1216 	if(worker->env.mesh && verbosity >= VERB_OPS) {
1217 		server_stats_log(&worker->stats, worker, worker->thread_num);
1218 		mesh_stats(worker->env.mesh, "mesh has");
1219 		worker_mem_report(worker, NULL);
1220 	}
1221 	outside_network_quit_prepare(worker->back);
1222 	mesh_delete(worker->env.mesh);
1223 	ldns_buffer_free(worker->env.scratch_buffer);
1224 	forwards_delete(worker->env.fwds);
1225 	hints_delete(worker->env.hints);
1226 	listen_delete(worker->front);
1227 	outside_network_delete(worker->back);
1228 	comm_signal_delete(worker->comsig);
1229 	tube_delete(worker->cmd);
1230 	comm_timer_delete(worker->stat_timer);
1231 	comm_timer_delete(worker->env.probe_timer);
1232 	free(worker->ports);
1233 	if(worker->thread_num == 0) {
1234 		log_set_time(NULL);
1235 #ifdef UB_ON_WINDOWS
1236 		wsvc_desetup_worker(worker);
1237 #endif /* UB_ON_WINDOWS */
1238 	}
1239 	comm_base_delete(worker->base);
1240 	ub_randfree(worker->rndstate);
1241 	alloc_clear(&worker->alloc);
1242 	regional_destroy(worker->scratchpad);
1243 	free(worker);
1244 }
1245 
1246 struct outbound_entry*
1247 worker_send_query(uint8_t* qname, size_t qnamelen, uint16_t qtype,
1248 	uint16_t qclass, uint16_t flags, int dnssec, int want_dnssec,
1249 	struct sockaddr_storage* addr, socklen_t addrlen, uint8_t* zone,
1250 	size_t zonelen, struct module_qstate* q)
1251 {
1252 	struct worker* worker = q->env->worker;
1253 	struct outbound_entry* e = (struct outbound_entry*)regional_alloc(
1254 		q->region, sizeof(*e));
1255 	if(!e)
1256 		return NULL;
1257 	e->qstate = q;
1258 	e->qsent = outnet_serviced_query(worker->back, qname,
1259 		qnamelen, qtype, qclass, flags, dnssec, want_dnssec,
1260 		q->env->cfg->tcp_upstream, q->env->cfg->ssl_upstream, addr,
1261 		addrlen, zone, zonelen, worker_handle_service_reply, e,
1262 		worker->back->udp_buff);
1263 	if(!e->qsent) {
1264 		return NULL;
1265 	}
1266 	return e;
1267 }
1268 
1269 void
1270 worker_alloc_cleanup(void* arg)
1271 {
1272 	struct worker* worker = (struct worker*)arg;
1273 	slabhash_clear(&worker->env.rrset_cache->table);
1274 	slabhash_clear(worker->env.msg_cache);
1275 }
1276 
1277 void worker_stats_clear(struct worker* worker)
1278 {
1279 	server_stats_init(&worker->stats, worker->env.cfg);
1280 	mesh_stats_clear(worker->env.mesh);
1281 	worker->back->unwanted_replies = 0;
1282 }
1283 
1284 void worker_start_accept(void* arg)
1285 {
1286 	struct worker* worker = (struct worker*)arg;
1287 	listen_start_accept(worker->front);
1288 	if(worker->thread_num == 0)
1289 		daemon_remote_start_accept(worker->daemon->rc);
1290 }
1291 
1292 void worker_stop_accept(void* arg)
1293 {
1294 	struct worker* worker = (struct worker*)arg;
1295 	listen_stop_accept(worker->front);
1296 	if(worker->thread_num == 0)
1297 		daemon_remote_stop_accept(worker->daemon->rc);
1298 }
1299 
1300 /* --- fake callbacks for fptr_wlist to work --- */
1301 struct outbound_entry* libworker_send_query(uint8_t* ATTR_UNUSED(qname),
1302 	size_t ATTR_UNUSED(qnamelen), uint16_t ATTR_UNUSED(qtype),
1303 	uint16_t ATTR_UNUSED(qclass), uint16_t ATTR_UNUSED(flags),
1304 	int ATTR_UNUSED(dnssec), int ATTR_UNUSED(want_dnssec),
1305 	struct sockaddr_storage* ATTR_UNUSED(addr),
1306 	socklen_t ATTR_UNUSED(addrlen), struct module_qstate* ATTR_UNUSED(q))
1307 {
1308 	log_assert(0);
1309 	return 0;
1310 }
1311 
1312 int libworker_handle_reply(struct comm_point* ATTR_UNUSED(c),
1313 	void* ATTR_UNUSED(arg), int ATTR_UNUSED(error),
1314         struct comm_reply* ATTR_UNUSED(reply_info))
1315 {
1316 	log_assert(0);
1317 	return 0;
1318 }
1319 
1320 int libworker_handle_service_reply(struct comm_point* ATTR_UNUSED(c),
1321 	void* ATTR_UNUSED(arg), int ATTR_UNUSED(error),
1322         struct comm_reply* ATTR_UNUSED(reply_info))
1323 {
1324 	log_assert(0);
1325 	return 0;
1326 }
1327 
1328 void libworker_handle_control_cmd(struct tube* ATTR_UNUSED(tube),
1329         uint8_t* ATTR_UNUSED(buffer), size_t ATTR_UNUSED(len),
1330         int ATTR_UNUSED(error), void* ATTR_UNUSED(arg))
1331 {
1332 	log_assert(0);
1333 }
1334 
1335 void libworker_fg_done_cb(void* ATTR_UNUSED(arg), int ATTR_UNUSED(rcode),
1336         ldns_buffer* ATTR_UNUSED(buf), enum sec_status ATTR_UNUSED(s),
1337 	char* ATTR_UNUSED(why_bogus))
1338 {
1339 	log_assert(0);
1340 }
1341 
1342 void libworker_bg_done_cb(void* ATTR_UNUSED(arg), int ATTR_UNUSED(rcode),
1343         ldns_buffer* ATTR_UNUSED(buf), enum sec_status ATTR_UNUSED(s),
1344 	char* ATTR_UNUSED(why_bogus))
1345 {
1346 	log_assert(0);
1347 }
1348 
1349 int context_query_cmp(const void* ATTR_UNUSED(a), const void* ATTR_UNUSED(b))
1350 {
1351 	log_assert(0);
1352 	return 0;
1353 }
1354 
1355 int order_lock_cmp(const void* ATTR_UNUSED(e1), const void* ATTR_UNUSED(e2))
1356 {
1357         log_assert(0);
1358         return 0;
1359 }
1360 
1361 int codeline_cmp(const void* ATTR_UNUSED(a), const void* ATTR_UNUSED(b))
1362 {
1363         log_assert(0);
1364         return 0;
1365 }
1366 
1367