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