xref: /freebsd/contrib/unbound/daemon/daemon.c (revision a64729f5077d77e13b9497cb33ecb3c82e606ee8)
1 /*
2  * daemon/daemon.c - collection of workers that handles 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  * The daemon consists of global settings and a number of workers.
40  */
41 
42 #include "config.h"
43 #ifdef HAVE_OPENSSL_ERR_H
44 #include <openssl/err.h>
45 #endif
46 
47 #ifdef HAVE_OPENSSL_RAND_H
48 #include <openssl/rand.h>
49 #endif
50 
51 #ifdef HAVE_OPENSSL_CONF_H
52 #include <openssl/conf.h>
53 #endif
54 
55 #ifdef HAVE_OPENSSL_ENGINE_H
56 #include <openssl/engine.h>
57 #endif
58 
59 #ifdef HAVE_TIME_H
60 #include <time.h>
61 #endif
62 #include <sys/time.h>
63 
64 #ifdef HAVE_NSS
65 /* nss3 */
66 #include "nss.h"
67 #endif
68 
69 #include "daemon/daemon.h"
70 #include "daemon/worker.h"
71 #include "daemon/remote.h"
72 #include "daemon/acl_list.h"
73 #include "util/log.h"
74 #include "util/config_file.h"
75 #include "util/data/msgreply.h"
76 #include "util/shm_side/shm_main.h"
77 #include "util/storage/lookup3.h"
78 #include "util/storage/slabhash.h"
79 #include "util/tcp_conn_limit.h"
80 #include "util/edns.h"
81 #include "services/listen_dnsport.h"
82 #include "services/cache/rrset.h"
83 #include "services/cache/infra.h"
84 #include "services/localzone.h"
85 #include "services/view.h"
86 #include "services/modstack.h"
87 #include "services/authzone.h"
88 #include "util/module.h"
89 #include "util/random.h"
90 #include "util/tube.h"
91 #include "util/net_help.h"
92 #include "sldns/keyraw.h"
93 #include "respip/respip.h"
94 #include "iterator/iter_fwd.h"
95 #include "iterator/iter_hints.h"
96 #include <signal.h>
97 
98 #ifdef HAVE_SYSTEMD
99 #include <systemd/sd-daemon.h>
100 #endif
101 #ifdef HAVE_NETDB_H
102 #include <netdb.h>
103 #endif
104 #ifdef USE_CACHEDB
105 #include "cachedb/cachedb.h"
106 #endif
107 
108 /** How many quit requests happened. */
109 static int sig_record_quit = 0;
110 /** How many reload requests happened. */
111 static int sig_record_reload = 0;
112 
113 #if HAVE_DECL_SSL_COMP_GET_COMPRESSION_METHODS
114 /** cleaner ssl memory freeup */
115 static void* comp_meth = NULL;
116 #endif
117 /** remove buffers for parsing and init */
118 int ub_c_lex_destroy(void);
119 
120 /** used when no other sighandling happens, so we don't die
121   * when multiple signals in quick succession are sent to us.
122   * @param sig: signal number.
123   * @return signal handler return type (void or int).
124   */
125 static RETSIGTYPE record_sigh(int sig)
126 {
127 #ifdef LIBEVENT_SIGNAL_PROBLEM
128 	/* cannot log, verbose here because locks may be held */
129 	/* quit on signal, no cleanup and statistics,
130 	   because installed libevent version is not threadsafe */
131 	exit(0);
132 #endif
133 	switch(sig)
134 	{
135 		case SIGTERM:
136 #ifdef SIGQUIT
137 		case SIGQUIT:
138 #endif
139 #ifdef SIGBREAK
140 		case SIGBREAK:
141 #endif
142 		case SIGINT:
143 			sig_record_quit++;
144 			break;
145 #ifdef SIGHUP
146 		case SIGHUP:
147 			sig_record_reload++;
148 			break;
149 #endif
150 #ifdef SIGPIPE
151 		case SIGPIPE:
152 			break;
153 #endif
154 		default:
155 			/* ignoring signal */
156 			break;
157 	}
158 }
159 
160 /**
161  * Signal handling during the time when netevent is disabled.
162  * Stores signals to replay later.
163  */
164 static void
165 signal_handling_record(void)
166 {
167 	if( signal(SIGTERM, record_sigh) == SIG_ERR ||
168 #ifdef SIGQUIT
169 		signal(SIGQUIT, record_sigh) == SIG_ERR ||
170 #endif
171 #ifdef SIGBREAK
172 		signal(SIGBREAK, record_sigh) == SIG_ERR ||
173 #endif
174 #ifdef SIGHUP
175 		signal(SIGHUP, record_sigh) == SIG_ERR ||
176 #endif
177 #ifdef SIGPIPE
178 		signal(SIGPIPE, SIG_IGN) == SIG_ERR ||
179 #endif
180 		signal(SIGINT, record_sigh) == SIG_ERR
181 		)
182 		log_err("install sighandler: %s", strerror(errno));
183 }
184 
185 /**
186  * Replay old signals.
187  * @param wrk: worker that handles signals.
188  */
189 static void
190 signal_handling_playback(struct worker* wrk)
191 {
192 #ifdef SIGHUP
193 	if(sig_record_reload)
194 		worker_sighandler(SIGHUP, wrk);
195 #endif
196 	if(sig_record_quit)
197 		worker_sighandler(SIGTERM, wrk);
198 	sig_record_quit = 0;
199 	sig_record_reload = 0;
200 }
201 
202 struct daemon*
203 daemon_init(void)
204 {
205 	struct daemon* daemon = (struct daemon*)calloc(1,
206 		sizeof(struct daemon));
207 #ifdef USE_WINSOCK
208 	int r;
209 	WSADATA wsa_data;
210 #endif
211 	if(!daemon)
212 		return NULL;
213 #ifdef USE_WINSOCK
214 	r = WSAStartup(MAKEWORD(2,2), &wsa_data);
215 	if(r != 0) {
216 		fatal_exit("could not init winsock. WSAStartup: %s",
217 			wsa_strerror(r));
218 	}
219 #endif /* USE_WINSOCK */
220 	signal_handling_record();
221 #ifdef HAVE_SSL
222 #  ifdef HAVE_ERR_LOAD_CRYPTO_STRINGS
223 	ERR_load_crypto_strings();
224 #  endif
225 #if OPENSSL_VERSION_NUMBER < 0x10100000 || !defined(HAVE_OPENSSL_INIT_SSL)
226 	ERR_load_SSL_strings();
227 #endif
228 #  ifdef USE_GOST
229 	(void)sldns_key_EVP_load_gost_id();
230 #  endif
231 #  if OPENSSL_VERSION_NUMBER < 0x10100000 || !defined(HAVE_OPENSSL_INIT_CRYPTO)
232 #    ifndef S_SPLINT_S
233 	OpenSSL_add_all_algorithms();
234 #    endif
235 #  else
236 	OPENSSL_init_crypto(OPENSSL_INIT_ADD_ALL_CIPHERS
237 		| OPENSSL_INIT_ADD_ALL_DIGESTS
238 		| OPENSSL_INIT_LOAD_CRYPTO_STRINGS, NULL);
239 #  endif
240 #  if HAVE_DECL_SSL_COMP_GET_COMPRESSION_METHODS
241 	/* grab the COMP method ptr because openssl leaks it */
242 	comp_meth = (void*)SSL_COMP_get_compression_methods();
243 #  endif
244 #  if OPENSSL_VERSION_NUMBER < 0x10100000 || !defined(HAVE_OPENSSL_INIT_SSL)
245 	(void)SSL_library_init();
246 #  else
247 	(void)OPENSSL_init_ssl(OPENSSL_INIT_LOAD_SSL_STRINGS, NULL);
248 #  endif
249 #  if defined(HAVE_SSL) && defined(OPENSSL_THREADS) && !defined(THREADS_DISABLED)
250 	if(!ub_openssl_lock_init())
251 		fatal_exit("could not init openssl locks");
252 #  endif
253 #elif defined(HAVE_NSS)
254 	if(NSS_NoDB_Init(NULL) != SECSuccess)
255 		fatal_exit("could not init NSS");
256 #endif /* HAVE_SSL or HAVE_NSS */
257 #ifdef HAVE_TZSET
258 	/* init timezone info while we are not chrooted yet */
259 	tzset();
260 #endif
261 	daemon->need_to_exit = 0;
262 	modstack_init(&daemon->mods);
263 	if(!(daemon->env = (struct module_env*)calloc(1,
264 		sizeof(*daemon->env)))) {
265 		free(daemon);
266 		return NULL;
267 	}
268 	daemon->env->modstack = &daemon->mods;
269 	/* init edns_known_options */
270 	if(!edns_known_options_init(daemon->env)) {
271 		free(daemon->env);
272 		free(daemon);
273 		return NULL;
274 	}
275 	alloc_init(&daemon->superalloc, NULL, 0);
276 	daemon->acl = acl_list_create();
277 	if(!daemon->acl) {
278 		edns_known_options_delete(daemon->env);
279 		free(daemon->env);
280 		free(daemon);
281 		return NULL;
282 	}
283 	daemon->acl_interface = acl_list_create();
284 	if(!daemon->acl_interface) {
285 		acl_list_delete(daemon->acl);
286 		edns_known_options_delete(daemon->env);
287 		free(daemon->env);
288 		free(daemon);
289 		return NULL;
290 	}
291 	daemon->tcl = tcl_list_create();
292 	if(!daemon->tcl) {
293 		acl_list_delete(daemon->acl_interface);
294 		acl_list_delete(daemon->acl);
295 		edns_known_options_delete(daemon->env);
296 		free(daemon->env);
297 		free(daemon);
298 		return NULL;
299 	}
300 	listen_setup_locks();
301 	if(gettimeofday(&daemon->time_boot, NULL) < 0)
302 		log_err("gettimeofday: %s", strerror(errno));
303 	daemon->time_last_stat = daemon->time_boot;
304 	if((daemon->env->auth_zones = auth_zones_create()) == 0) {
305 		acl_list_delete(daemon->acl_interface);
306 		acl_list_delete(daemon->acl);
307 		tcl_list_delete(daemon->tcl);
308 		edns_known_options_delete(daemon->env);
309 		free(daemon->env);
310 		free(daemon);
311 		return NULL;
312 	}
313 	if(!(daemon->env->edns_strings = edns_strings_create())) {
314 		auth_zones_delete(daemon->env->auth_zones);
315 		acl_list_delete(daemon->acl_interface);
316 		acl_list_delete(daemon->acl);
317 		tcl_list_delete(daemon->tcl);
318 		edns_known_options_delete(daemon->env);
319 		free(daemon->env);
320 		free(daemon);
321 		return NULL;
322 	}
323 	return daemon;
324 }
325 
326 static int setup_acl_for_ports(struct acl_list* list,
327 	struct listen_port* port_list)
328 {
329 	struct acl_addr* acl_node;
330 	for(; port_list; port_list=port_list->next) {
331 		if(!port_list->socket) {
332 			/* This is mainly for testbound where port_list is
333 			 * empty. */
334 			continue;
335 		}
336 		if(!(acl_node = acl_interface_insert(list,
337 			(struct sockaddr_storage*)port_list->socket->addr,
338 			port_list->socket->addrlen,
339 			acl_refuse))) {
340 			return 0;
341 		}
342 		port_list->socket->acl = acl_node;
343 	}
344 	return 1;
345 }
346 
347 int
348 daemon_open_shared_ports(struct daemon* daemon)
349 {
350 	log_assert(daemon);
351 	if(daemon->cfg->port != daemon->listening_port) {
352 		char** resif = NULL;
353 		int num_resif = 0;
354 		size_t i;
355 		struct listen_port* p0;
356 		daemon->reuseport = 0;
357 		/* free and close old ports */
358 		if(daemon->ports != NULL) {
359 			for(i=0; i<daemon->num_ports; i++)
360 				listening_ports_free(daemon->ports[i]);
361 			free(daemon->ports);
362 			daemon->ports = NULL;
363 		}
364 		/* clean acl_interface */
365 		acl_interface_init(daemon->acl_interface);
366 		if(!resolve_interface_names(daemon->cfg->ifs,
367 			daemon->cfg->num_ifs, NULL, &resif, &num_resif))
368 			return 0;
369 		/* see if we want to reuseport */
370 #ifdef SO_REUSEPORT
371 		if(daemon->cfg->so_reuseport && daemon->cfg->num_threads > 0)
372 			daemon->reuseport = 1;
373 #endif
374 		/* try to use reuseport */
375 		p0 = listening_ports_open(daemon->cfg, resif, num_resif,
376 			&daemon->reuseport);
377 		if(!p0) {
378 			listening_ports_free(p0);
379 			config_del_strarray(resif, num_resif);
380 			return 0;
381 		}
382 		if(daemon->reuseport) {
383 			/* reuseport was successful, allocate for it */
384 			daemon->num_ports = (size_t)daemon->cfg->num_threads;
385 		} else {
386 			/* do the normal, singleportslist thing,
387 			 * reuseport not enabled or did not work */
388 			daemon->num_ports = 1;
389 		}
390 		if(!(daemon->ports = (struct listen_port**)calloc(
391 			daemon->num_ports, sizeof(*daemon->ports)))) {
392 			listening_ports_free(p0);
393 			config_del_strarray(resif, num_resif);
394 			return 0;
395 		}
396 		daemon->ports[0] = p0;
397 		if(!setup_acl_for_ports(daemon->acl_interface,
398 		    daemon->ports[0])) {
399 			listening_ports_free(p0);
400 			config_del_strarray(resif, num_resif);
401 			return 0;
402 		}
403 		if(daemon->reuseport) {
404 			/* continue to use reuseport */
405 			for(i=1; i<daemon->num_ports; i++) {
406 				if(!(daemon->ports[i]=
407 					listening_ports_open(daemon->cfg,
408 						resif, num_resif,
409 						&daemon->reuseport))
410 					|| !daemon->reuseport ) {
411 					for(i=0; i<daemon->num_ports; i++)
412 						listening_ports_free(daemon->ports[i]);
413 					free(daemon->ports);
414 					daemon->ports = NULL;
415 					config_del_strarray(resif, num_resif);
416 					return 0;
417 				}
418 				if(!setup_acl_for_ports(daemon->acl_interface,
419 					daemon->ports[i])) {
420 					for(i=0; i<daemon->num_ports; i++)
421 						listening_ports_free(daemon->ports[i]);
422 					free(daemon->ports);
423 					daemon->ports = NULL;
424 					config_del_strarray(resif, num_resif);
425 					return 0;
426 				}
427 			}
428 		}
429 		config_del_strarray(resif, num_resif);
430 		daemon->listening_port = daemon->cfg->port;
431 	}
432 	if(!daemon->cfg->remote_control_enable && daemon->rc_port) {
433 		listening_ports_free(daemon->rc_ports);
434 		daemon->rc_ports = NULL;
435 		daemon->rc_port = 0;
436 	}
437 	if(daemon->cfg->remote_control_enable &&
438 		daemon->cfg->control_port != daemon->rc_port) {
439 		listening_ports_free(daemon->rc_ports);
440 		if(!(daemon->rc_ports=daemon_remote_open_ports(daemon->cfg)))
441 			return 0;
442 		daemon->rc_port = daemon->cfg->control_port;
443 	}
444 	return 1;
445 }
446 
447 int
448 daemon_privileged(struct daemon* daemon)
449 {
450 	daemon->env->cfg = daemon->cfg;
451 	daemon->env->alloc = &daemon->superalloc;
452 	daemon->env->worker = NULL;
453 	if(!modstack_call_startup(&daemon->mods, daemon->cfg->module_conf,
454 		daemon->env)) {
455 		fatal_exit("failed to startup modules");
456 	}
457 	return 1;
458 }
459 
460 /**
461  * Setup modules. setup module stack.
462  * @param daemon: the daemon
463  */
464 static void daemon_setup_modules(struct daemon* daemon)
465 {
466 	daemon->env->cfg = daemon->cfg;
467 	daemon->env->alloc = &daemon->superalloc;
468 	daemon->env->worker = NULL;
469 	if(daemon->mods_inited) {
470 		modstack_call_deinit(&daemon->mods, daemon->env);
471 	}
472 	daemon->env->need_to_validate = 0; /* set by module init below */
473 	if(!modstack_call_init(&daemon->mods, daemon->cfg->module_conf,
474 		daemon->env)) {
475 		fatal_exit("failed to init modules");
476 	}
477 	daemon->mods_inited = 1;
478 	log_edns_known_options(VERB_ALGO, daemon->env);
479 }
480 
481 /**
482  * Obtain allowed port numbers, concatenate the list, and shuffle them
483  * (ready to be handed out to threads).
484  * @param daemon: the daemon. Uses rand and cfg.
485  * @param shufport: the portlist output.
486  * @return number of ports available.
487  */
488 static int daemon_get_shufport(struct daemon* daemon, int* shufport)
489 {
490 	int i, n, k, temp;
491 	int avail = 0;
492 	for(i=0; i<65536; i++) {
493 		if(daemon->cfg->outgoing_avail_ports[i]) {
494 			shufport[avail++] = daemon->cfg->
495 				outgoing_avail_ports[i];
496 		}
497 	}
498 	if(avail == 0)
499 		fatal_exit("no ports are permitted for UDP, add "
500 			"with outgoing-port-permit");
501         /* Knuth shuffle */
502 	n = avail;
503 	while(--n > 0) {
504 		k = ub_random_max(daemon->rand, n+1); /* 0<= k<= n */
505 		temp = shufport[k];
506 		shufport[k] = shufport[n];
507 		shufport[n] = temp;
508 	}
509 	return avail;
510 }
511 
512 /**
513  * Clear and delete per-worker alloc caches, and free memory maintained in
514  * superalloc.
515  * The rrset and message caches must be empty at the time of call.
516  * @param daemon: the daemon that maintains the alloc caches to be cleared.
517  */
518 static void
519 daemon_clear_allocs(struct daemon* daemon)
520 {
521 	int i;
522 
523 	/* daemon->num may be different during reloads (after configuration
524 	 * read). Use old_num which has the correct value used to setup the
525 	 * worker_allocs */
526 	for(i=0; i<daemon->old_num; i++) {
527 		alloc_clear(daemon->worker_allocs[i]);
528 		free(daemon->worker_allocs[i]);
529 	}
530 	free(daemon->worker_allocs);
531 	daemon->worker_allocs = NULL;
532 
533 	alloc_clear_special(&daemon->superalloc);
534 }
535 
536 /**
537  * Allocate empty worker structures. With backptr and thread-number,
538  * from 0..numthread initialised. Used as user arguments to new threads.
539  * Creates the daemon random generator if it does not exist yet.
540  * The random generator stays existing between reloads with a unique state.
541  * @param daemon: the daemon with (new) config settings.
542  */
543 static void
544 daemon_create_workers(struct daemon* daemon)
545 {
546 	int i, numport;
547 	int* shufport;
548 	log_assert(daemon && daemon->cfg);
549 	if(!daemon->rand) {
550 		daemon->rand = ub_initstate(NULL);
551 		if(!daemon->rand)
552 			fatal_exit("could not init random generator");
553 		hash_set_raninit((uint32_t)ub_random(daemon->rand));
554 	}
555 	shufport = (int*)calloc(65536, sizeof(int));
556 	if(!shufport)
557 		fatal_exit("out of memory during daemon init");
558 	numport = daemon_get_shufport(daemon, shufport);
559 	verbose(VERB_ALGO, "total of %d outgoing ports available", numport);
560 
561 	daemon->num = (daemon->cfg->num_threads?daemon->cfg->num_threads:1);
562 	if(daemon->reuseport && (int)daemon->num < (int)daemon->num_ports) {
563 		log_warn("cannot reduce num-threads to %d because so-reuseport "
564 			"so continuing with %d threads.", (int)daemon->num,
565 			(int)daemon->num_ports);
566 		daemon->num = (int)daemon->num_ports;
567 	}
568 	daemon->workers = (struct worker**)calloc((size_t)daemon->num,
569 		sizeof(struct worker*));
570 	if(!daemon->workers)
571 		fatal_exit("out of memory during daemon init");
572 	if(daemon->cfg->dnstap) {
573 #ifdef USE_DNSTAP
574 		daemon->dtenv = dt_create(daemon->cfg);
575 		if (!daemon->dtenv)
576 			fatal_exit("dt_create failed");
577 #else
578 		fatal_exit("dnstap enabled in config but not built with dnstap support");
579 #endif
580 	}
581 	for(i=0; i<daemon->num; i++) {
582 		if(!(daemon->workers[i] = worker_create(daemon, i,
583 			shufport+numport*i/daemon->num,
584 			numport*(i+1)/daemon->num - numport*i/daemon->num)))
585 			/* the above is not ports/numthr, due to rounding */
586 			fatal_exit("could not create worker");
587 	}
588 	/* create per-worker alloc caches if not reusing existing ones. */
589 	if(!daemon->worker_allocs) {
590 		daemon->worker_allocs = (struct alloc_cache**)calloc(
591 			(size_t)daemon->num, sizeof(struct alloc_cache*));
592 		if(!daemon->worker_allocs)
593 			fatal_exit("could not allocate worker allocs");
594 		for(i=0; i<daemon->num; i++) {
595 			struct alloc_cache* alloc = calloc(1,
596 				sizeof(struct alloc_cache));
597 			if (!alloc)
598 				fatal_exit("could not allocate worker alloc");
599 			alloc_init(alloc, &daemon->superalloc, i);
600 			daemon->worker_allocs[i] = alloc;
601 		}
602 	}
603 	free(shufport);
604 }
605 
606 #ifdef THREADS_DISABLED
607 /**
608  * Close all pipes except for the numbered thread.
609  * @param daemon: daemon to close pipes in.
610  * @param thr: thread number 0..num-1 of thread to skip.
611  */
612 static void close_other_pipes(struct daemon* daemon, int thr)
613 {
614 	int i;
615 	for(i=0; i<daemon->num; i++)
616 		if(i!=thr) {
617 			if(i==0) {
618 				/* only close read part, need to write stats */
619 				tube_close_read(daemon->workers[i]->cmd);
620 			} else {
621 				/* complete close channel to others */
622 				tube_delete(daemon->workers[i]->cmd);
623 				daemon->workers[i]->cmd = NULL;
624 			}
625 		}
626 }
627 #endif /* THREADS_DISABLED */
628 
629 /**
630  * Function to start one thread.
631  * @param arg: user argument.
632  * @return: void* user return value could be used for thread_join results.
633  */
634 static void*
635 thread_start(void* arg)
636 {
637 	struct worker* worker = (struct worker*)arg;
638 	int port_num = 0;
639 	log_thread_set(&worker->thread_num);
640 	ub_thread_blocksigs();
641 #ifdef THREADS_DISABLED
642 	/* close pipe ends used by main */
643 	tube_close_write(worker->cmd);
644 	close_other_pipes(worker->daemon, worker->thread_num);
645 #endif
646 #ifdef SO_REUSEPORT
647 	if(worker->daemon->cfg->so_reuseport)
648 		port_num = worker->thread_num % worker->daemon->num_ports;
649 	else
650 		port_num = 0;
651 #endif
652 	if(!worker_init(worker, worker->daemon->cfg,
653 			worker->daemon->ports[port_num], 0))
654 		fatal_exit("Could not initialize thread");
655 
656 	worker_work(worker);
657 	return NULL;
658 }
659 
660 /**
661  * Fork and init the other threads. Main thread returns for special handling.
662  * @param daemon: the daemon with other threads to fork.
663  */
664 static void
665 daemon_start_others(struct daemon* daemon)
666 {
667 	int i;
668 	log_assert(daemon);
669 	verbose(VERB_ALGO, "start threads");
670 	/* skip i=0, is this thread */
671 	for(i=1; i<daemon->num; i++) {
672 		ub_thread_create(&daemon->workers[i]->thr_id,
673 			thread_start, daemon->workers[i]);
674 #ifdef THREADS_DISABLED
675 		/* close pipe end of child */
676 		tube_close_read(daemon->workers[i]->cmd);
677 #endif /* no threads */
678 	}
679 }
680 
681 /**
682  * Stop the other threads.
683  * @param daemon: the daemon with other threads.
684  */
685 static void
686 daemon_stop_others(struct daemon* daemon)
687 {
688 	int i;
689 	log_assert(daemon);
690 	verbose(VERB_ALGO, "stop threads");
691 	/* skip i=0, is this thread */
692 	/* use i=0 buffer for sending cmds; because we are #0 */
693 	for(i=1; i<daemon->num; i++) {
694 		worker_send_cmd(daemon->workers[i], worker_cmd_quit);
695 	}
696 	/* wait for them to quit */
697 	for(i=1; i<daemon->num; i++) {
698 		/* join it to make sure its dead */
699 		verbose(VERB_ALGO, "join %d", i);
700 		ub_thread_join(daemon->workers[i]->thr_id);
701 		verbose(VERB_ALGO, "join success %d", i);
702 	}
703 }
704 
705 void
706 daemon_fork(struct daemon* daemon)
707 {
708 	int have_view_respip_cfg = 0;
709 #ifdef HAVE_SYSTEMD
710 	int ret;
711 #endif
712 
713 	log_assert(daemon);
714 	if(!(daemon->views = views_create()))
715 		fatal_exit("Could not create views: out of memory");
716 	/* create individual views and their localzone/data trees */
717 	if(!views_apply_cfg(daemon->views, daemon->cfg))
718 		fatal_exit("Could not set up views");
719 
720 	if(!acl_list_apply_cfg(daemon->acl, daemon->cfg, daemon->views))
721 		fatal_exit("Could not setup access control list");
722 	if(!acl_interface_apply_cfg(daemon->acl_interface, daemon->cfg,
723 		daemon->views))
724 		fatal_exit("Could not setup interface control list");
725 	if(!tcl_list_apply_cfg(daemon->tcl, daemon->cfg))
726 		fatal_exit("Could not setup TCP connection limits");
727 	if(daemon->cfg->dnscrypt) {
728 #ifdef USE_DNSCRYPT
729 		daemon->dnscenv = dnsc_create();
730 		if (!daemon->dnscenv)
731 			fatal_exit("dnsc_create failed");
732 		dnsc_apply_cfg(daemon->dnscenv, daemon->cfg);
733 #else
734 		fatal_exit("dnscrypt enabled in config but unbound was not built with "
735 				   "dnscrypt support");
736 #endif
737 	}
738 	if(daemon->cfg->cookie_secret_file &&
739 		daemon->cfg->cookie_secret_file[0]) {
740 		if(!(daemon->cookie_secrets = cookie_secrets_create()))
741 			fatal_exit("Could not create cookie_secrets: out of memory");
742 		if(!cookie_secrets_apply_cfg(daemon->cookie_secrets,
743 			daemon->cfg->cookie_secret_file))
744 			fatal_exit("Could not setup cookie_secrets");
745 	}
746 	/* create global local_zones */
747 	if(!(daemon->local_zones = local_zones_create()))
748 		fatal_exit("Could not create local zones: out of memory");
749 	if(!local_zones_apply_cfg(daemon->local_zones, daemon->cfg))
750 		fatal_exit("Could not set up local zones");
751 	if(!(daemon->env->fwds = forwards_create()) ||
752 		!forwards_apply_cfg(daemon->env->fwds, daemon->cfg))
753 		fatal_exit("Could not set forward zones");
754 	if(!(daemon->env->hints = hints_create()) ||
755 		!hints_apply_cfg(daemon->env->hints, daemon->cfg))
756 		fatal_exit("Could not set root or stub hints");
757 
758 	/* process raw response-ip configuration data */
759 	if(!(daemon->respip_set = respip_set_create()))
760 		fatal_exit("Could not create response IP set");
761 	if(!respip_global_apply_cfg(daemon->respip_set, daemon->cfg))
762 		fatal_exit("Could not set up response IP set");
763 	if(!respip_views_apply_cfg(daemon->views, daemon->cfg,
764 		&have_view_respip_cfg))
765 		fatal_exit("Could not set up per-view response IP sets");
766 	daemon->use_response_ip = !respip_set_is_empty(daemon->respip_set) ||
767 		have_view_respip_cfg;
768 
769 	/* setup modules */
770 	daemon_setup_modules(daemon);
771 
772 	/* read auth zonefiles */
773 	if(!auth_zones_apply_cfg(daemon->env->auth_zones, daemon->cfg, 1,
774 		&daemon->use_rpz, daemon->env, &daemon->mods))
775 		fatal_exit("auth_zones could not be setup");
776 
777 	/* Set-up EDNS strings */
778 	if(!edns_strings_apply_cfg(daemon->env->edns_strings, daemon->cfg))
779 		fatal_exit("Could not set up EDNS strings");
780 
781 #ifdef USE_CACHEDB
782 	daemon->env->cachedb_enabled = cachedb_is_enabled(&daemon->mods,
783 		daemon->env);
784 #endif
785 	/* response-ip-xxx options don't work as expected without the respip
786 	 * module.  To avoid run-time operational surprise we reject such
787 	 * configuration. */
788 	if(daemon->use_response_ip &&
789 		modstack_find(&daemon->mods, "respip") < 0)
790 		fatal_exit("response-ip options require respip module");
791 	/* RPZ response ip triggers don't work as expected without the respip
792 	 * module.  To avoid run-time operational surprise we reject such
793 	 * configuration. */
794 	if(daemon->use_rpz &&
795 		modstack_find(&daemon->mods, "respip") < 0)
796 		fatal_exit("RPZ requires the respip module");
797 
798 	/* first create all the worker structures, so we can pass
799 	 * them to the newly created threads.
800 	 */
801 	daemon_create_workers(daemon);
802 
803 #if defined(HAVE_EV_LOOP) || defined(HAVE_EV_DEFAULT_LOOP)
804 	/* in libev the first inited base gets signals */
805 	if(!worker_init(daemon->workers[0], daemon->cfg, daemon->ports[0], 1))
806 		fatal_exit("Could not initialize main thread");
807 #endif
808 
809 	/* Now create the threads and init the workers.
810 	 * By the way, this is thread #0 (the main thread).
811 	 */
812 	daemon_start_others(daemon);
813 
814 	/* Special handling for the main thread. This is the thread
815 	 * that handles signals and remote control.
816 	 */
817 #if !(defined(HAVE_EV_LOOP) || defined(HAVE_EV_DEFAULT_LOOP))
818 	/* libevent has the last inited base get signals (or any base) */
819 	if(!worker_init(daemon->workers[0], daemon->cfg, daemon->ports[0], 1))
820 		fatal_exit("Could not initialize main thread");
821 #endif
822 	signal_handling_playback(daemon->workers[0]);
823 
824 	if (!shm_main_init(daemon))
825 		log_warn("SHM has failed");
826 
827 	/* Start resolver service on main thread. */
828 #ifdef HAVE_SYSTEMD
829 	ret = sd_notify(0, "READY=1");
830 	if(ret <= 0 && getenv("NOTIFY_SOCKET"))
831 		fatal_exit("sd_notify failed %s: %s. Make sure that unbound has "
832 				"access/permission to use the socket presented by systemd.",
833 				getenv("NOTIFY_SOCKET"),
834 				(ret==0?"no $NOTIFY_SOCKET": strerror(-ret)));
835 #endif
836 	log_info("start of service (%s).", PACKAGE_STRING);
837 	worker_work(daemon->workers[0]);
838 #ifdef HAVE_SYSTEMD
839 	if (daemon->workers[0]->need_to_exit)
840 		sd_notify(0, "STOPPING=1");
841 	else
842 		sd_notify(0, "RELOADING=1");
843 #endif
844 	log_info("service stopped (%s).", PACKAGE_STRING);
845 
846 	/* we exited! a signal happened! Stop other threads */
847 	daemon_stop_others(daemon);
848 
849 	/* Shutdown SHM */
850 	shm_main_shutdown(daemon);
851 
852 	daemon->reuse_cache = daemon->workers[0]->reuse_cache;
853 	daemon->need_to_exit = daemon->workers[0]->need_to_exit;
854 }
855 
856 void
857 daemon_cleanup(struct daemon* daemon)
858 {
859 	int i;
860 	log_assert(daemon);
861 	/* before stopping main worker, handle signals ourselves, so we
862 	   don't die on multiple reload signals for example. */
863 	signal_handling_record();
864 	log_thread_set(NULL);
865 	/* clean up caches because
866 	 * a) RRset IDs will be recycled after a reload, causing collisions
867 	 * b) validation config can change, thus rrset, msg, keycache clear
868 	 *
869 	 * If we are trying to keep the cache as long as possible, we should
870 	 * defer the cleanup until we know whether the new configuration allows
871 	 * the reuse.  (If we're exiting, cleanup should be done here). */
872 	if(!daemon->reuse_cache || daemon->need_to_exit) {
873 		slabhash_clear(&daemon->env->rrset_cache->table);
874 		slabhash_clear(daemon->env->msg_cache);
875 	}
876 	daemon->old_num = daemon->num; /* save the current num */
877 	forwards_delete(daemon->env->fwds);
878 	daemon->env->fwds = NULL;
879 	hints_delete(daemon->env->hints);
880 	daemon->env->hints = NULL;
881 	local_zones_delete(daemon->local_zones);
882 	daemon->local_zones = NULL;
883 	respip_set_delete(daemon->respip_set);
884 	daemon->respip_set = NULL;
885 	views_delete(daemon->views);
886 	daemon->views = NULL;
887 	if(daemon->env->auth_zones)
888 		auth_zones_cleanup(daemon->env->auth_zones);
889 	/* key cache is cleared by module deinit during next daemon_fork() */
890 	daemon_remote_clear(daemon->rc);
891 	for(i=0; i<daemon->num; i++)
892 		worker_delete(daemon->workers[i]);
893 	free(daemon->workers);
894 	daemon->workers = NULL;
895 	/* Unless we're trying to keep the cache, worker alloc_caches should be
896 	 * cleared and freed here. We do this after deleting workers to
897 	 * guarantee that the alloc caches are valid throughout the lifetime
898 	 * of workers. */
899 	if(!daemon->reuse_cache || daemon->need_to_exit)
900 		daemon_clear_allocs(daemon);
901 	daemon->num = 0;
902 #ifdef USE_DNSTAP
903 	dt_delete(daemon->dtenv);
904 	daemon->dtenv = NULL;
905 #endif
906 #ifdef USE_DNSCRYPT
907 	dnsc_delete(daemon->dnscenv);
908 	daemon->dnscenv = NULL;
909 #endif
910 	daemon->cfg = NULL;
911 }
912 
913 void
914 daemon_delete(struct daemon* daemon)
915 {
916 	size_t i;
917 	if(!daemon)
918 		return;
919 	modstack_call_deinit(&daemon->mods, daemon->env);
920 	modstack_call_destartup(&daemon->mods, daemon->env);
921 	modstack_free(&daemon->mods);
922 	daemon_remote_delete(daemon->rc);
923 	for(i = 0; i < daemon->num_ports; i++)
924 		listening_ports_free(daemon->ports[i]);
925 	free(daemon->ports);
926 	listening_ports_free(daemon->rc_ports);
927 	if(daemon->env) {
928 		slabhash_delete(daemon->env->msg_cache);
929 		rrset_cache_delete(daemon->env->rrset_cache);
930 		infra_delete(daemon->env->infra_cache);
931 		edns_known_options_delete(daemon->env);
932 		edns_strings_delete(daemon->env->edns_strings);
933 		auth_zones_delete(daemon->env->auth_zones);
934 	}
935 	ub_randfree(daemon->rand);
936 	alloc_clear(&daemon->superalloc);
937 	acl_list_delete(daemon->acl);
938 	acl_list_delete(daemon->acl_interface);
939 	tcl_list_delete(daemon->tcl);
940 	cookie_secrets_delete(daemon->cookie_secrets);
941 	listen_desetup_locks();
942 	free(daemon->chroot);
943 	free(daemon->pidfile);
944 	free(daemon->env);
945 #ifdef HAVE_SSL
946 	listen_sslctx_delete_ticket_keys();
947 	SSL_CTX_free((SSL_CTX*)daemon->listen_sslctx);
948 	SSL_CTX_free((SSL_CTX*)daemon->connect_sslctx);
949 #endif
950 	free(daemon);
951 	/* lex cleanup */
952 	ub_c_lex_destroy();
953 	/* libcrypto cleanup */
954 #ifdef HAVE_SSL
955 #  if defined(USE_GOST)
956 	sldns_key_EVP_unload_gost();
957 #  endif
958 #  if HAVE_DECL_SSL_COMP_GET_COMPRESSION_METHODS && HAVE_DECL_SK_SSL_COMP_POP_FREE
959 #    ifndef S_SPLINT_S
960 #      if OPENSSL_VERSION_NUMBER < 0x10100000
961 	sk_SSL_COMP_pop_free(comp_meth, (void(*)())CRYPTO_free);
962 #      endif
963 #    endif
964 #  endif
965 #  ifdef HAVE_OPENSSL_CONFIG
966 	EVP_cleanup();
967 #  if (OPENSSL_VERSION_NUMBER < 0x10100000) && !defined(OPENSSL_NO_ENGINE) && defined(HAVE_ENGINE_CLEANUP)
968 	ENGINE_cleanup();
969 #  endif
970 	CONF_modules_free();
971 #  endif
972 #  ifdef HAVE_CRYPTO_CLEANUP_ALL_EX_DATA
973 	CRYPTO_cleanup_all_ex_data(); /* safe, no more threads right now */
974 #  endif
975 #  ifdef HAVE_ERR_FREE_STRINGS
976 	ERR_free_strings();
977 #  endif
978 #  if OPENSSL_VERSION_NUMBER < 0x10100000
979 	RAND_cleanup();
980 #  endif
981 #  if defined(HAVE_SSL) && defined(OPENSSL_THREADS) && !defined(THREADS_DISABLED)
982 	ub_openssl_lock_delete();
983 #  endif
984 #ifndef HAVE_ARC4RANDOM
985 	_ARC4_LOCK_DESTROY();
986 #endif
987 #elif defined(HAVE_NSS)
988 	NSS_Shutdown();
989 #endif /* HAVE_SSL or HAVE_NSS */
990 	checklock_stop();
991 #ifdef USE_WINSOCK
992 	if(WSACleanup() != 0) {
993 		log_err("Could not WSACleanup: %s",
994 			wsa_strerror(WSAGetLastError()));
995 	}
996 #endif
997 }
998 
999 void daemon_apply_cfg(struct daemon* daemon, struct config_file* cfg)
1000 {
1001 	int new_num = cfg->num_threads?cfg->num_threads:1;
1002 
1003         daemon->cfg = cfg;
1004 	config_apply(cfg);
1005 
1006 	/* If this is a reload and we deferred the decision on whether to
1007 	 * reuse the alloc, RRset, and message caches, then check to see if
1008 	 * it's safe to keep the caches:
1009 	 * - changing the number of threads is obviously incompatible with
1010 	 *   keeping the per-thread alloc caches. It also means we have to
1011 	 *   clear RRset and message caches. (note that 'new_num' may be
1012 	 *   adjusted in daemon_create_workers, but for our purpose we can
1013 	 *   simply compare it with 'old_num'; if they are equal here,
1014 	 *   'new_num' won't be adjusted to a different value than 'old_num').
1015 	 * - changing RRset cache size effectively clears any remaining cache
1016 	 *   entries. We could keep their keys in alloc caches, but it would
1017 	 *   be more consistent with the sense of the change to clear allocs
1018 	 *   and free memory. To do so we also have to clear message cache.
1019 	 * - only changing message cache size does not necessarily affect
1020 	 *   RRset or alloc cache. But almost all new subsequent queries will
1021 	 *   require recursive resolution anyway, so it doesn't help much to
1022 	 *   just keep RRset and alloc caches. For simplicity we clear/free
1023 	 *   the other two, too. */
1024 	if(daemon->worker_allocs &&
1025 		(new_num != daemon->old_num ||
1026 		 !slabhash_is_size(daemon->env->msg_cache, cfg->msg_cache_size,
1027 			cfg->msg_cache_slabs) ||
1028 		 !slabhash_is_size(&daemon->env->rrset_cache->table,
1029 			cfg->rrset_cache_size, cfg->rrset_cache_slabs)))
1030 	{
1031 		log_warn("cannot reuse caches due to critical config change");
1032 		slabhash_clear(&daemon->env->rrset_cache->table);
1033 		slabhash_clear(daemon->env->msg_cache);
1034 		daemon_clear_allocs(daemon);
1035 	}
1036 
1037 	if(!slabhash_is_size(daemon->env->msg_cache, cfg->msg_cache_size,
1038 	   	cfg->msg_cache_slabs)) {
1039 		slabhash_delete(daemon->env->msg_cache);
1040 		daemon->env->msg_cache = slabhash_create(cfg->msg_cache_slabs,
1041 			HASH_DEFAULT_STARTARRAY, cfg->msg_cache_size,
1042 			msgreply_sizefunc, query_info_compare,
1043 			query_entry_delete, reply_info_delete, NULL);
1044 		if(!daemon->env->msg_cache) {
1045 			fatal_exit("malloc failure updating config settings");
1046 		}
1047 	}
1048 	if((daemon->env->rrset_cache = rrset_cache_adjust(
1049 		daemon->env->rrset_cache, cfg, &daemon->superalloc)) == 0)
1050 		fatal_exit("malloc failure updating config settings");
1051 	if((daemon->env->infra_cache = infra_adjust(daemon->env->infra_cache,
1052 		cfg))==0)
1053 		fatal_exit("malloc failure updating config settings");
1054 }
1055