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