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