xref: /freebsd/contrib/unbound/daemon/daemon.c (revision 5fa84c6ec176d186ddad25d31f8760e50f48157f)
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   */
record_sigh(int sig)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
signal_handling_record(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
signal_handling_playback(struct worker * wrk)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 #ifdef HAVE_SSL
203 /* setup a listening ssl context, fatal_exit() on any failure */
204 static void
setup_listen_sslctx(void ** ctx,int is_dot,int is_doh,struct config_file * cfg,char * chroot)205 setup_listen_sslctx(void** ctx, int is_dot, int is_doh,
206 	struct config_file* cfg, char* chroot)
207 {
208 	char* key = cfg->ssl_service_key;
209 	char* pem = cfg->ssl_service_pem;
210 	if(chroot && strncmp(key, chroot, strlen(chroot)) == 0)
211 		key += strlen(chroot);
212 	if(chroot && pem && strncmp(pem, chroot, strlen(chroot)) == 0)
213 		pem += strlen(chroot);
214 	if(!(*ctx = listen_sslctx_create(key, pem, NULL,
215 		cfg->tls_ciphers, cfg->tls_ciphersuites,
216 		(cfg->tls_session_ticket_keys.first &&
217 		cfg->tls_session_ticket_keys.first->str[0] != 0),
218 		is_dot, is_doh, cfg->tls_protocols))) {
219 		fatal_exit("could not set up listen SSL_CTX");
220 	}
221 }
222 #endif /* HAVE_SSL */
223 
224 #ifdef HAVE_SSL
daemon_setup_listen_dot_sslctx(struct daemon * daemon,struct config_file * cfg)225 void* daemon_setup_listen_dot_sslctx(struct daemon* daemon,
226 	struct config_file* cfg)
227 {
228 	void* ctx;
229 	(void)setup_listen_sslctx(&ctx, 1, 0, cfg, daemon->chroot);
230 	return ctx;
231 }
232 #endif /* HAVE_SSL */
233 
234 #ifdef HAVE_SSL
235 #ifdef HAVE_NGHTTP2_NGHTTP2_H
daemon_setup_listen_doh_sslctx(struct daemon * daemon,struct config_file * cfg)236 void* daemon_setup_listen_doh_sslctx(struct daemon* daemon,
237 	struct config_file* cfg)
238 {
239 	void* ctx;
240 	(void)setup_listen_sslctx(&ctx, 0, 1, cfg, daemon->chroot);
241 	return ctx;
242 }
243 #endif /* HAVE_NGHTTP2_NGHTTP2_H */
244 #endif /* HAVE_SSL */
245 
246 #ifdef HAVE_SSL
247 #ifdef HAVE_NGTCP2
daemon_setup_listen_quic_sslctx(struct daemon * daemon,struct config_file * cfg)248 void* daemon_setup_listen_quic_sslctx(struct daemon* daemon,
249 	struct config_file* cfg)
250 {
251 	void* ctx;
252 	char* chroot = daemon->chroot;
253 	char* key = cfg->ssl_service_key;
254 	char* pem = cfg->ssl_service_pem;
255 	if(chroot && strncmp(key, chroot, strlen(chroot)) == 0)
256 		key += strlen(chroot);
257 	if(chroot && pem && strncmp(pem, chroot, strlen(chroot)) == 0)
258 		pem += strlen(chroot);
259 
260 	if(!(ctx = quic_sslctx_create(key, pem, NULL))) {
261 		fatal_exit("could not set up quic SSL_CTX");
262 	}
263 	return ctx;
264 }
265 #endif /* HAVE_NGTCP2 */
266 #endif /* HAVE_SSL */
267 
268 #ifdef HAVE_SSL
daemon_setup_connect_dot_sslctx(struct daemon * daemon,struct config_file * cfg)269 void* daemon_setup_connect_dot_sslctx(struct daemon* daemon,
270 	struct config_file* cfg)
271 {
272 	void* ctx;
273 	char* bundle, *chroot = daemon->chroot;
274 	bundle = cfg->tls_cert_bundle;
275 	if(chroot && bundle && strncmp(bundle, chroot, strlen(chroot)) == 0)
276 		bundle += strlen(chroot);
277 
278 	if(!(ctx = connect_sslctx_create(NULL, NULL, bundle,
279 		cfg->tls_win_cert)))
280 		fatal_exit("could not set up connect SSL_CTX");
281 	return ctx;
282 }
283 #endif /* HAVE_SSL */
284 
285 /* setups the needed ssl contexts, fatal_exit() on any failure */
286 void
daemon_setup_sslctxs(struct daemon * daemon,struct config_file * cfg)287 daemon_setup_sslctxs(struct daemon* daemon, struct config_file* cfg)
288 {
289 #ifdef HAVE_SSL
290 	char* chroot = daemon->chroot;
291 	if(cfg->ssl_service_key && cfg->ssl_service_key[0]) {
292 		char* key = cfg->ssl_service_key;
293 		char* pem = cfg->ssl_service_pem;
294 		if(chroot && strncmp(key, chroot, strlen(chroot)) == 0)
295 			key += strlen(chroot);
296 		if(chroot && pem && strncmp(pem, chroot, strlen(chroot)) == 0)
297 			pem += strlen(chroot);
298 
299 		/* setup the session keys; the callback to use them will be
300 		 * attached to each sslctx separately */
301 		if(cfg->tls_session_ticket_keys.first &&
302 			cfg->tls_session_ticket_keys.first->str[0] != 0) {
303 			if(!listen_sslctx_setup_ticket_keys(
304 				cfg->tls_session_ticket_keys.first, chroot)) {
305 				fatal_exit("could not set session ticket SSL_CTX");
306 			}
307 		}
308 		daemon->listen_dot_sslctx = daemon_setup_listen_dot_sslctx(
309 			daemon, cfg);
310 #ifdef HAVE_NGHTTP2_NGHTTP2_H
311 		if(cfg_has_https(cfg)) {
312 			daemon->listen_doh_sslctx =
313 				daemon_setup_listen_doh_sslctx(daemon, cfg);
314 		}
315 #endif
316 #ifdef HAVE_NGTCP2
317 		if(cfg_has_quic(cfg)) {
318 			daemon->listen_quic_sslctx =
319 				daemon_setup_listen_quic_sslctx(daemon, cfg);
320 		}
321 #endif /* HAVE_NGTCP2 */
322 
323 		/* Store the file name and mtime to detect changes later. */
324 		daemon->ssl_service_key = strdup(cfg->ssl_service_key);
325 		if(!daemon->ssl_service_key)
326 			fatal_exit("could not setup ssl ctx: out of memory");
327 		if(cfg->ssl_service_pem) {
328 			daemon->ssl_service_pem = strdup(cfg->ssl_service_pem);
329 			if(!daemon->ssl_service_pem)
330 				fatal_exit("could not setup ssl ctx: out of memory");
331 		} else {
332 			daemon->ssl_service_pem = NULL;
333 		}
334 		if(!file_get_mtime(key,
335 			&daemon->mtime_ssl_service_key,
336 			&daemon->mtime_ns_ssl_service_key, NULL))
337 			log_err("Could not stat(%s): %s",
338 				key, strerror(errno));
339 		if(pem) {
340 			if(!file_get_mtime(pem,
341 				&daemon->mtime_ssl_service_pem,
342 				&daemon->mtime_ns_ssl_service_pem, NULL))
343 				log_err("Could not stat(%s): %s",
344 					pem, strerror(errno));
345 		} else {
346 			daemon->mtime_ssl_service_pem = 0;
347 			daemon->mtime_ns_ssl_service_pem = 0;
348 		}
349 	}
350 	daemon->connect_dot_sslctx = daemon_setup_connect_dot_sslctx(
351 		daemon, cfg);
352 #else /* HAVE_SSL */
353 	(void)daemon;(void)cfg;
354 #endif /* HAVE_SSL */
355 }
356 
357 /** Delete the ssl ctxs */
358 static void
daemon_delete_sslctxs(struct daemon * daemon)359 daemon_delete_sslctxs(struct daemon* daemon)
360 {
361 #ifdef HAVE_SSL
362 	listen_sslctx_delete_ticket_keys();
363 	SSL_CTX_free((SSL_CTX*)daemon->listen_dot_sslctx);
364 	daemon->listen_dot_sslctx = NULL;
365 	SSL_CTX_free((SSL_CTX*)daemon->listen_doh_sslctx);
366 	daemon->listen_doh_sslctx = NULL;
367 	SSL_CTX_free((SSL_CTX*)daemon->connect_dot_sslctx);
368 	daemon->connect_dot_sslctx = NULL;
369 	free(daemon->ssl_service_key);
370 	daemon->ssl_service_key = NULL;
371 	free(daemon->ssl_service_pem);
372 	daemon->ssl_service_pem = NULL;
373 #else
374 	(void)daemon;
375 #endif
376 #ifdef HAVE_NGTCP2
377 	SSL_CTX_free((SSL_CTX*)daemon->listen_quic_sslctx);
378 	daemon->listen_quic_sslctx = NULL;
379 #endif
380 }
381 
382 int
ssl_cert_changed(struct daemon * daemon,struct config_file * cfg)383 ssl_cert_changed(struct daemon* daemon, struct config_file* cfg)
384 {
385 	time_t mtime = 0;
386 	long ns = 0;
387 	char* chroot = daemon->chroot;
388 	char* key = cfg->ssl_service_key;
389 	char* pem = cfg->ssl_service_pem;
390 	log_assert(daemon->ssl_service_key && cfg->ssl_service_key);
391 	if(chroot && strncmp(key, chroot, strlen(chroot)) == 0)
392 		key += strlen(chroot);
393 	if(chroot && pem && strncmp(pem, chroot, strlen(chroot)) == 0)
394 		pem += strlen(chroot);
395 
396 	if(strcmp(daemon->ssl_service_key, cfg->ssl_service_key) != 0)
397 		return 1;
398 	if(daemon->ssl_service_pem && cfg->ssl_service_pem &&
399 	   strcmp(daemon->ssl_service_pem, cfg->ssl_service_pem) != 0)
400 		return 1;
401 	if(!file_get_mtime(key, &mtime, &ns, NULL)) {
402 		log_err("Could not stat(%s): %s",
403 			key, strerror(errno));
404 		/* It has probably changed, but file read is likely going to
405 		 * fail. */
406 		return 0;
407 	}
408 	if(mtime != daemon->mtime_ssl_service_key ||
409 		ns != daemon->mtime_ns_ssl_service_key)
410 		return 1;
411 	if(pem) {
412 		if(!file_get_mtime(pem, &mtime, &ns, NULL)) {
413 			log_err("Could not stat(%s): %s",
414 				pem, strerror(errno));
415 			/* It has probably changed, but file read is likely going to
416 			 * fail. */
417 			return 0;
418 		}
419 		if(mtime != daemon->mtime_ssl_service_pem ||
420 			ns != daemon->mtime_ns_ssl_service_pem)
421 			return 1;
422 	}
423 	return 0;
424 }
425 
426 /** Reload the sslctxs if they have changed */
427 static void
daemon_reload_sslctxs(struct daemon * daemon)428 daemon_reload_sslctxs(struct daemon* daemon)
429 {
430 #ifdef HAVE_SSL
431 	if(daemon->cfg->ssl_service_key && daemon->cfg->ssl_service_key[0]) {
432 		/* See if changed */
433 		if(!daemon->ssl_service_key ||
434 			ssl_cert_changed(daemon,daemon->cfg)) {
435 			verbose(VERB_ALGO, "Reloading certificates");
436 			daemon_delete_sslctxs(daemon);
437 			daemon_setup_sslctxs(daemon, daemon->cfg);
438 		}
439 	} else {
440 		/* See if sslctxs are removed from config. */
441 		if(daemon->ssl_service_key) {
442 			verbose(VERB_ALGO, "Removing certificates");
443 			daemon_delete_sslctxs(daemon);
444 		}
445 	}
446 #else
447 	(void)daemon;
448 #endif
449 }
450 
451 struct daemon*
daemon_init(void)452 daemon_init(void)
453 {
454 	struct daemon* daemon = (struct daemon*)calloc(1,
455 		sizeof(struct daemon));
456 #ifdef USE_WINSOCK
457 	int r;
458 	WSADATA wsa_data;
459 #endif
460 	if(!daemon)
461 		return NULL;
462 #ifdef USE_WINSOCK
463 	r = WSAStartup(MAKEWORD(2,2), &wsa_data);
464 	if(r != 0) {
465 		fatal_exit("could not init winsock. WSAStartup: %s",
466 			wsa_strerror(r));
467 	}
468 #endif /* USE_WINSOCK */
469 	signal_handling_record();
470 #ifdef HAVE_SSL
471 #  ifdef HAVE_ERR_LOAD_CRYPTO_STRINGS
472 	ERR_load_crypto_strings();
473 #  endif
474 #if OPENSSL_VERSION_NUMBER < 0x10100000 || !defined(HAVE_OPENSSL_INIT_SSL)
475 	ERR_load_SSL_strings();
476 #endif
477 #  ifdef USE_GOST
478 	(void)sldns_key_EVP_load_gost_id();
479 #  endif
480 #  if OPENSSL_VERSION_NUMBER < 0x10100000 || !defined(HAVE_OPENSSL_INIT_CRYPTO)
481 #    ifndef S_SPLINT_S
482 	OpenSSL_add_all_algorithms();
483 #    endif
484 #  else
485 	OPENSSL_init_crypto(OPENSSL_INIT_ADD_ALL_CIPHERS
486 		| OPENSSL_INIT_ADD_ALL_DIGESTS
487 		| OPENSSL_INIT_LOAD_CRYPTO_STRINGS
488 #    if defined(OPENSSL_INIT_NO_LOAD_CONFIG) && defined(UB_ON_WINDOWS)
489 		| OPENSSL_INIT_NO_LOAD_CONFIG
490 #    endif
491 		, NULL);
492 #  endif
493 #  if HAVE_DECL_SSL_COMP_GET_COMPRESSION_METHODS
494 	/* grab the COMP method ptr because openssl leaks it */
495 	comp_meth = (void*)SSL_COMP_get_compression_methods();
496 #  endif
497 #  if OPENSSL_VERSION_NUMBER < 0x10100000 || !defined(HAVE_OPENSSL_INIT_SSL)
498 	(void)SSL_library_init();
499 #  else
500 	(void)OPENSSL_init_ssl(OPENSSL_INIT_LOAD_SSL_STRINGS
501 #    if defined(OPENSSL_INIT_NO_LOAD_CONFIG) && defined(UB_ON_WINDOWS)
502 		| OPENSSL_INIT_NO_LOAD_CONFIG
503 #    endif
504 		, NULL);
505 #  endif
506 #  if defined(HAVE_SSL) && defined(OPENSSL_THREADS) && !defined(THREADS_DISABLED)
507 	if(!ub_openssl_lock_init())
508 		fatal_exit("could not init openssl locks");
509 #  endif
510 #elif defined(HAVE_NSS)
511 	if(NSS_NoDB_Init(NULL) != SECSuccess)
512 		fatal_exit("could not init NSS");
513 #endif /* HAVE_SSL or HAVE_NSS */
514 #ifdef HAVE_TZSET
515 	/* init timezone info while we are not chrooted yet */
516 	tzset();
517 #endif
518 	daemon->need_to_exit = 0;
519 	modstack_init(&daemon->mods);
520 	if(!(daemon->env = (struct module_env*)calloc(1,
521 		sizeof(*daemon->env)))) {
522 		free(daemon);
523 		return NULL;
524 	}
525 	daemon->env->modstack = &daemon->mods;
526 	/* init edns_known_options */
527 	if(!edns_known_options_init(daemon->env)) {
528 		free(daemon->env);
529 		free(daemon);
530 		return NULL;
531 	}
532 	alloc_init(&daemon->superalloc, NULL, 0);
533 	daemon->acl = acl_list_create();
534 	if(!daemon->acl) {
535 		edns_known_options_delete(daemon->env);
536 		free(daemon->env);
537 		free(daemon);
538 		return NULL;
539 	}
540 	daemon->acl_interface = acl_list_create();
541 	if(!daemon->acl_interface) {
542 		acl_list_delete(daemon->acl);
543 		edns_known_options_delete(daemon->env);
544 		free(daemon->env);
545 		free(daemon);
546 		return NULL;
547 	}
548 	daemon->tcl = tcl_list_create();
549 	if(!daemon->tcl) {
550 		acl_list_delete(daemon->acl_interface);
551 		acl_list_delete(daemon->acl);
552 		edns_known_options_delete(daemon->env);
553 		free(daemon->env);
554 		free(daemon);
555 		return NULL;
556 	}
557 	listen_setup_locks();
558 	if(gettimeofday(&daemon->time_boot, NULL) < 0)
559 		log_err("gettimeofday: %s", strerror(errno));
560 	daemon->time_last_stat = daemon->time_boot;
561 	if((daemon->env->auth_zones = auth_zones_create()) == 0) {
562 		acl_list_delete(daemon->acl_interface);
563 		acl_list_delete(daemon->acl);
564 		tcl_list_delete(daemon->tcl);
565 		edns_known_options_delete(daemon->env);
566 		free(daemon->env);
567 		free(daemon);
568 		return NULL;
569 	}
570 	if(!(daemon->env->edns_strings = edns_strings_create())) {
571 		auth_zones_delete(daemon->env->auth_zones);
572 		acl_list_delete(daemon->acl_interface);
573 		acl_list_delete(daemon->acl);
574 		tcl_list_delete(daemon->tcl);
575 		edns_known_options_delete(daemon->env);
576 		free(daemon->env);
577 		free(daemon);
578 		return NULL;
579 	}
580 	return daemon;
581 }
582 
setup_acl_for_ports(struct acl_list * list,struct listen_port * port_list)583 int setup_acl_for_ports(struct acl_list* list, struct listen_port* port_list)
584 {
585 	struct acl_addr* acl_node;
586 	for(; port_list; port_list=port_list->next) {
587 		if(!port_list->socket) {
588 			/* This is mainly for testbound where port_list is
589 			 * empty. */
590 			continue;
591 		}
592 		if(!(acl_node = acl_interface_insert(list,
593 			(struct sockaddr_storage*)port_list->socket->addr,
594 			port_list->socket->addrlen,
595 			acl_refuse))) {
596 			return 0;
597 		}
598 		port_list->socket->acl = acl_node;
599 	}
600 	return 1;
601 }
602 
603 int
daemon_open_shared_ports(struct daemon * daemon)604 daemon_open_shared_ports(struct daemon* daemon)
605 {
606 	log_assert(daemon);
607 	if(daemon->cfg->port != daemon->listening_port) {
608 		char** resif = NULL;
609 		int num_resif = 0;
610 		size_t i;
611 		struct listen_port* p0;
612 		daemon->reuseport = 0;
613 		/* free and close old ports */
614 		if(daemon->ports != NULL) {
615 			for(i=0; i<daemon->num_ports; i++)
616 				listening_ports_free(daemon->ports[i]);
617 			free(daemon->ports);
618 			daemon->ports = NULL;
619 		}
620 		/* clean acl_interface */
621 		acl_interface_init(daemon->acl_interface);
622 		if(!resolve_interface_names(daemon->cfg->ifs,
623 			daemon->cfg->num_ifs, NULL, &resif, &num_resif))
624 			return 0;
625 		/* see if we want to reuseport */
626 #ifdef SO_REUSEPORT
627 		if(daemon->cfg->so_reuseport && daemon->cfg->num_threads > 0)
628 			daemon->reuseport = 1;
629 #endif
630 		/* try to use reuseport */
631 		p0 = listening_ports_open(daemon->cfg, resif, num_resif,
632 			&daemon->reuseport);
633 		if(!p0) {
634 			listening_ports_free(p0);
635 			config_del_strarray(resif, num_resif);
636 			return 0;
637 		}
638 		if(daemon->reuseport) {
639 			/* reuseport was successful, allocate for it */
640 			daemon->num_ports = (size_t)daemon->cfg->num_threads;
641 		} else {
642 			/* do the normal, singleportslist thing,
643 			 * reuseport not enabled or did not work */
644 			daemon->num_ports = 1;
645 		}
646 		if(!(daemon->ports = (struct listen_port**)calloc(
647 			daemon->num_ports, sizeof(*daemon->ports)))) {
648 			listening_ports_free(p0);
649 			config_del_strarray(resif, num_resif);
650 			return 0;
651 		}
652 		daemon->ports[0] = p0;
653 		if(!setup_acl_for_ports(daemon->acl_interface,
654 		    daemon->ports[0])) {
655 			listening_ports_free(p0);
656 			config_del_strarray(resif, num_resif);
657 			return 0;
658 		}
659 		if(daemon->reuseport) {
660 			/* continue to use reuseport */
661 			for(i=1; i<daemon->num_ports; i++) {
662 				if(!(daemon->ports[i]=
663 					listening_ports_open(daemon->cfg,
664 						resif, num_resif,
665 						&daemon->reuseport))
666 					|| !daemon->reuseport ) {
667 					for(i=0; i<daemon->num_ports; i++)
668 						listening_ports_free(daemon->ports[i]);
669 					free(daemon->ports);
670 					daemon->ports = NULL;
671 					config_del_strarray(resif, num_resif);
672 					return 0;
673 				}
674 				if(!setup_acl_for_ports(daemon->acl_interface,
675 					daemon->ports[i])) {
676 					for(i=0; i<daemon->num_ports; i++)
677 						listening_ports_free(daemon->ports[i]);
678 					free(daemon->ports);
679 					daemon->ports = NULL;
680 					config_del_strarray(resif, num_resif);
681 					return 0;
682 				}
683 			}
684 		}
685 		config_del_strarray(resif, num_resif);
686 		daemon->listening_port = daemon->cfg->port;
687 	}
688 	if(!daemon->cfg->remote_control_enable && daemon->rc_port) {
689 		listening_ports_free(daemon->rc_ports);
690 		daemon->rc_ports = NULL;
691 		daemon->rc_port = 0;
692 	}
693 	if(daemon->cfg->remote_control_enable &&
694 		daemon->cfg->control_port != daemon->rc_port) {
695 		listening_ports_free(daemon->rc_ports);
696 		if(!(daemon->rc_ports=daemon_remote_open_ports(daemon->cfg)))
697 			return 0;
698 		daemon->rc_port = daemon->cfg->control_port;
699 	}
700 	return 1;
701 }
702 
703 int
daemon_privileged(struct daemon * daemon)704 daemon_privileged(struct daemon* daemon)
705 {
706 	daemon->env->cfg = daemon->cfg;
707 	daemon->env->alloc = &daemon->superalloc;
708 	daemon->env->worker = NULL;
709 	if(!modstack_call_startup(&daemon->mods, daemon->cfg->module_conf,
710 		daemon->env)) {
711 		fatal_exit("failed to startup modules");
712 	}
713 	return 1;
714 }
715 
716 /**
717  * Setup modules. setup module stack.
718  * @param daemon: the daemon
719  */
daemon_setup_modules(struct daemon * daemon)720 static void daemon_setup_modules(struct daemon* daemon)
721 {
722 	daemon->env->cfg = daemon->cfg;
723 	daemon->env->alloc = &daemon->superalloc;
724 	daemon->env->worker = NULL;
725 	if(daemon->mods_inited) {
726 		modstack_call_deinit(&daemon->mods, daemon->env);
727 	}
728 	daemon->env->need_to_validate = 0; /* set by module init below */
729 	if(!modstack_call_init(&daemon->mods, daemon->cfg->module_conf,
730 		daemon->env)) {
731 		fatal_exit("failed to init modules");
732 	}
733 	daemon->mods_inited = 1;
734 	log_edns_known_options(VERB_ALGO, daemon->env);
735 }
736 
737 /**
738  * Obtain allowed port numbers, concatenate the list, and shuffle them
739  * (ready to be handed out to threads).
740  * @param daemon: the daemon. Uses rand and cfg.
741  * @param shufport: the portlist output.
742  * @return number of ports available.
743  */
daemon_get_shufport(struct daemon * daemon,int * shufport)744 static int daemon_get_shufport(struct daemon* daemon, int* shufport)
745 {
746 	int i, n, k, temp;
747 	int avail = 0;
748 	for(i=0; i<65536; i++) {
749 		if(daemon->cfg->outgoing_avail_ports[i]) {
750 			shufport[avail++] = daemon->cfg->
751 				outgoing_avail_ports[i];
752 		}
753 	}
754 	if(avail == 0)
755 		fatal_exit("no ports are permitted for UDP, add "
756 			"with outgoing-port-permit");
757         /* Knuth shuffle */
758 	n = avail;
759 	while(--n > 0) {
760 		k = ub_random_max(daemon->rand, n+1); /* 0<= k<= n */
761 		temp = shufport[k];
762 		shufport[k] = shufport[n];
763 		shufport[n] = temp;
764 	}
765 	return avail;
766 }
767 
768 /**
769  * Clear and delete per-worker alloc caches, and free memory maintained in
770  * superalloc.
771  * The rrset and message caches must be empty at the time of call.
772  * @param daemon: the daemon that maintains the alloc caches to be cleared.
773  */
774 static void
daemon_clear_allocs(struct daemon * daemon)775 daemon_clear_allocs(struct daemon* daemon)
776 {
777 	int i;
778 
779 	/* daemon->num may be different during reloads (after configuration
780 	 * read). Use old_num which has the correct value used to setup the
781 	 * worker_allocs */
782 	for(i=0; i<daemon->old_num; i++) {
783 		alloc_clear(daemon->worker_allocs[i]);
784 		free(daemon->worker_allocs[i]);
785 	}
786 	free(daemon->worker_allocs);
787 	daemon->worker_allocs = NULL;
788 
789 	alloc_clear_special(&daemon->superalloc);
790 }
791 
792 /**
793  * Allocate empty worker structures. With backptr and thread-number,
794  * from 0..numthread initialised. Used as user arguments to new threads.
795  * Creates the daemon random generator if it does not exist yet.
796  * The random generator stays existing between reloads with a unique state.
797  * @param daemon: the daemon with (new) config settings.
798  */
799 static void
daemon_create_workers(struct daemon * daemon)800 daemon_create_workers(struct daemon* daemon)
801 {
802 	int i, numport;
803 	int* shufport;
804 	log_assert(daemon && daemon->cfg);
805 	if(!daemon->rand) {
806 		daemon->rand = ub_initstate(NULL);
807 		if(!daemon->rand)
808 			fatal_exit("could not init random generator");
809 		hash_set_raninit((uint32_t)ub_random(daemon->rand));
810 	}
811 	shufport = (int*)calloc(65536, sizeof(int));
812 	if(!shufport)
813 		fatal_exit("out of memory during daemon init");
814 	numport = daemon_get_shufport(daemon, shufport);
815 	verbose(VERB_ALGO, "total of %d outgoing ports available", numport);
816 
817 #ifdef HAVE_NGTCP2
818 	if (cfg_has_quic(daemon->cfg)) {
819 		daemon->doq_table = doq_table_create(daemon->cfg, daemon->rand);
820 		if(!daemon->doq_table)
821 			fatal_exit("could not create doq_table: out of memory");
822 	}
823 #endif
824 
825 	daemon->num = (daemon->cfg->num_threads?daemon->cfg->num_threads:1);
826 	if(daemon->reuseport && (int)daemon->num < (int)daemon->num_ports) {
827 		log_warn("cannot reduce num-threads to %d because so-reuseport "
828 			"so continuing with %d threads.", (int)daemon->num,
829 			(int)daemon->num_ports);
830 		daemon->num = (int)daemon->num_ports;
831 	}
832 	daemon->workers = (struct worker**)calloc((size_t)daemon->num,
833 		sizeof(struct worker*));
834 	if(!daemon->workers)
835 		fatal_exit("out of memory during daemon init");
836 	if(daemon->cfg->dnstap) {
837 #ifdef USE_DNSTAP
838 		daemon->dtenv = dt_create(daemon->cfg);
839 		if (!daemon->dtenv)
840 			fatal_exit("dt_create failed");
841 #else
842 		fatal_exit("dnstap enabled in config but not built with dnstap support");
843 #endif
844 	}
845 	for(i=0; i<daemon->num; i++) {
846 		if(!(daemon->workers[i] = worker_create(daemon, i,
847 			shufport+numport*i/daemon->num,
848 			numport*(i+1)/daemon->num - numport*i/daemon->num)))
849 			/* the above is not ports/numthr, due to rounding */
850 			fatal_exit("could not create worker");
851 	}
852 	/* create per-worker alloc caches if not reusing existing ones. */
853 	if(!daemon->worker_allocs) {
854 		daemon->worker_allocs = (struct alloc_cache**)calloc(
855 			(size_t)daemon->num, sizeof(struct alloc_cache*));
856 		if(!daemon->worker_allocs)
857 			fatal_exit("could not allocate worker allocs");
858 		for(i=0; i<daemon->num; i++) {
859 			struct alloc_cache* alloc = calloc(1,
860 				sizeof(struct alloc_cache));
861 			if (!alloc)
862 				fatal_exit("could not allocate worker alloc");
863 			alloc_init(alloc, &daemon->superalloc, i);
864 			daemon->worker_allocs[i] = alloc;
865 		}
866 	}
867 	free(shufport);
868 }
869 
870 #ifdef THREADS_DISABLED
871 /**
872  * Close all pipes except for the numbered thread.
873  * @param daemon: daemon to close pipes in.
874  * @param thr: thread number 0..num-1 of thread to skip.
875  */
close_other_pipes(struct daemon * daemon,int thr)876 static void close_other_pipes(struct daemon* daemon, int thr)
877 {
878 	int i;
879 	for(i=0; i<daemon->num; i++)
880 		if(i!=thr) {
881 			if(i==0) {
882 				/* only close read part, need to write stats */
883 				tube_close_read(daemon->workers[i]->cmd);
884 			} else {
885 				/* complete close channel to others */
886 				tube_delete(daemon->workers[i]->cmd);
887 				daemon->workers[i]->cmd = NULL;
888 			}
889 		}
890 }
891 #endif /* THREADS_DISABLED */
892 
893 /**
894  * Function to set the thread local log ID.
895  * Either the internal thread number, or the LWP ID on Linux based on
896  * configuration.
897  */
898 static void
set_log_thread_id(struct worker * worker,struct config_file * cfg)899 set_log_thread_id(struct worker* worker, struct config_file* cfg)
900 {
901 	(void)cfg;
902 	log_assert(worker);
903 #if defined(HAVE_GETTID) && !defined(THREADS_DISABLED)
904 	worker->thread_tid = gettid();
905 	if(cfg->log_thread_id)
906 		log_thread_set(&worker->thread_tid);
907 	else
908 #endif
909 		log_thread_set(&worker->thread_num);
910 }
911 
912 /**
913  * Function to start one thread.
914  * @param arg: user argument.
915  * @return: void* user return value could be used for thread_join results.
916  */
917 static void*
thread_start(void * arg)918 thread_start(void* arg)
919 {
920 	struct worker* worker = (struct worker*)arg;
921 	int port_num = 0;
922 	log_assert(worker->thr_id);
923 	set_log_thread_id(worker, worker->daemon->cfg);
924 	{
925 		char name[16]; /* seems to be the safest size between
926 				  different OSes */
927 		snprintf(name, sizeof(name), "unbound/%u", worker->thread_num);
928 		ub_thread_setname(worker->thr_id, name);
929 	}
930 	ub_thread_blocksigs();
931 #ifdef THREADS_DISABLED
932 	/* close pipe ends used by main */
933 	tube_close_write(worker->cmd);
934 	close_other_pipes(worker->daemon, worker->thread_num);
935 #endif
936 #ifdef SO_REUSEPORT
937 	if(worker->daemon->cfg->so_reuseport)
938 		port_num = worker->thread_num % worker->daemon->num_ports;
939 	else
940 		port_num = 0;
941 #endif
942 	if(!worker_init(worker, worker->daemon->cfg,
943 			worker->daemon->ports[port_num], 0))
944 		fatal_exit("Could not initialize thread");
945 
946 	worker_work(worker);
947 	return NULL;
948 }
949 
950 /**
951  * Fork and init the other threads. Main thread returns for special handling.
952  * @param daemon: the daemon with other threads to fork.
953  */
954 static void
daemon_start_others(struct daemon * daemon)955 daemon_start_others(struct daemon* daemon)
956 {
957 	int i;
958 	log_assert(daemon);
959 	verbose(VERB_ALGO, "start threads");
960 	/* skip i=0, is this thread */
961 	for(i=1; i<daemon->num; i++) {
962 		ub_thread_create(&daemon->workers[i]->thr_id,
963 			thread_start, daemon->workers[i]);
964 #ifdef THREADS_DISABLED
965 		/* close pipe end of child */
966 		tube_close_read(daemon->workers[i]->cmd);
967 #endif /* no threads */
968 	}
969 }
970 
971 /**
972  * Stop the other threads.
973  * @param daemon: the daemon with other threads.
974  */
975 static void
daemon_stop_others(struct daemon * daemon)976 daemon_stop_others(struct daemon* daemon)
977 {
978 	int i;
979 	log_assert(daemon);
980 	verbose(VERB_ALGO, "stop threads");
981 	/* skip i=0, is this thread */
982 	/* use i=0 buffer for sending cmds; because we are #0 */
983 	for(i=1; i<daemon->num; i++) {
984 		worker_send_cmd(daemon->workers[i], worker_cmd_quit);
985 	}
986 	/* wait for them to quit */
987 	for(i=1; i<daemon->num; i++) {
988 		/* join it to make sure its dead */
989 		verbose(VERB_ALGO, "join %d", i);
990 		ub_thread_join(daemon->workers[i]->thr_id);
991 		verbose(VERB_ALGO, "join success %d", i);
992 	}
993 }
994 
995 void
daemon_fork(struct daemon * daemon)996 daemon_fork(struct daemon* daemon)
997 {
998 	int have_view_respip_cfg = 0;
999 #ifdef HAVE_SYSTEMD
1000 	int ret;
1001 #endif
1002 
1003 	log_assert(daemon);
1004 	daemon_reload_sslctxs(daemon);
1005 	if(!(daemon->env->views = views_create()))
1006 		fatal_exit("Could not create views: out of memory");
1007 	/* create individual views and their localzone/data trees */
1008 	if(!views_apply_cfg(daemon->env->views, daemon->cfg))
1009 		fatal_exit("Could not set up views");
1010 
1011 	if(!acl_list_apply_cfg(daemon->acl, daemon->cfg, daemon->env->views))
1012 		fatal_exit("Could not setup access control list");
1013 	if(!acl_interface_apply_cfg(daemon->acl_interface, daemon->cfg,
1014 		daemon->env->views))
1015 		fatal_exit("Could not setup interface control list");
1016 	if(!tcl_list_apply_cfg(daemon->tcl, daemon->cfg))
1017 		fatal_exit("Could not setup TCP connection limits");
1018 	if(daemon->cfg->dnscrypt) {
1019 #ifdef USE_DNSCRYPT
1020 		daemon->dnscenv = dnsc_create();
1021 		if (!daemon->dnscenv)
1022 			fatal_exit("dnsc_create failed");
1023 		dnsc_apply_cfg(daemon->dnscenv, daemon->cfg);
1024 #else
1025 		fatal_exit("dnscrypt enabled in config but unbound was not built with "
1026 				   "dnscrypt support");
1027 #endif
1028 	}
1029 	if(daemon->cfg->cookie_secret_file &&
1030 		daemon->cfg->cookie_secret_file[0]) {
1031 		if(!(daemon->cookie_secrets = cookie_secrets_create()))
1032 			fatal_exit("Could not create cookie_secrets: out of memory");
1033 		if(!cookie_secrets_apply_cfg(daemon->cookie_secrets,
1034 			daemon->cfg->cookie_secret_file))
1035 			fatal_exit("Could not setup cookie_secrets");
1036 	}
1037 	/* create global local_zones */
1038 	if(!(daemon->local_zones = local_zones_create()))
1039 		fatal_exit("Could not create local zones: out of memory");
1040 	if(!local_zones_apply_cfg(daemon->local_zones, daemon->cfg))
1041 		fatal_exit("Could not set up local zones");
1042 	if(!(daemon->env->fwds = forwards_create()) ||
1043 		!forwards_apply_cfg(daemon->env->fwds, daemon->cfg))
1044 		fatal_exit("Could not set forward zones");
1045 	if(!(daemon->env->hints = hints_create()) ||
1046 		!hints_apply_cfg(daemon->env->hints, daemon->cfg))
1047 		fatal_exit("Could not set root or stub hints");
1048 
1049 	/* process raw response-ip configuration data */
1050 	if(!(daemon->env->respip_set = respip_set_create()))
1051 		fatal_exit("Could not create response IP set");
1052 	if(!respip_global_apply_cfg(daemon->env->respip_set, daemon->cfg))
1053 		fatal_exit("Could not set up response IP set");
1054 	if(!respip_views_apply_cfg(daemon->env->views, daemon->cfg,
1055 		&have_view_respip_cfg))
1056 		fatal_exit("Could not set up per-view response IP sets");
1057 	daemon->use_response_ip = !respip_set_is_empty(
1058 		daemon->env->respip_set) || have_view_respip_cfg;
1059 
1060 	/* setup modules */
1061 	daemon_setup_modules(daemon);
1062 
1063 	/* read auth zonefiles */
1064 	if(!auth_zones_apply_cfg(daemon->env->auth_zones, daemon->cfg, 1,
1065 		&daemon->use_rpz, daemon->env, &daemon->mods))
1066 		fatal_exit("auth_zones could not be setup");
1067 
1068 	/* Set-up EDNS strings */
1069 	if(!edns_strings_apply_cfg(daemon->env->edns_strings, daemon->cfg))
1070 		fatal_exit("Could not set up EDNS strings");
1071 
1072 #ifdef USE_CACHEDB
1073 	daemon->env->cachedb_enabled = cachedb_is_enabled(&daemon->mods,
1074 		daemon->env);
1075 #endif
1076 	/* response-ip-xxx options don't work as expected without the respip
1077 	 * module.  To avoid run-time operational surprise we reject such
1078 	 * configuration. */
1079 	if(daemon->use_response_ip &&
1080 		modstack_find(&daemon->mods, "respip") < 0)
1081 		fatal_exit("response-ip options require respip module");
1082 	/* RPZ response ip triggers don't work as expected without the respip
1083 	 * module.  To avoid run-time operational surprise we reject such
1084 	 * configuration. */
1085 	if(daemon->use_rpz &&
1086 		modstack_find(&daemon->mods, "respip") < 0)
1087 		fatal_exit("RPZ requires the respip module");
1088 
1089 	/* first create all the worker structures, so we can pass
1090 	 * them to the newly created threads.
1091 	 */
1092 	daemon_create_workers(daemon);
1093 	/* Set it for the first (main) worker since it does not take part in
1094 	 * the thread_start() procedure.
1095 	 */
1096 	set_log_thread_id(daemon->workers[0], daemon->cfg);
1097 	/* If shm stats need an offset, calculate it */
1098 	if(daemon->cfg->shm_enable && daemon->cfg->stat_interval > 0) {
1099 		daemon->stat_time_specific = 1;
1100 		daemon->stat_time_offset =
1101 			((int)time(NULL))%daemon->cfg->stat_interval;
1102 	}
1103 
1104 #if defined(HAVE_EV_LOOP) || defined(HAVE_EV_DEFAULT_LOOP)
1105 	/* in libev the first inited base gets signals */
1106 	if(!worker_init(daemon->workers[0], daemon->cfg, daemon->ports[0], 1))
1107 		fatal_exit("Could not initialize main thread");
1108 #endif
1109 
1110 	/* Now create the threads and init the workers.
1111 	 * By the way, this is thread #0 (the main thread).
1112 	 */
1113 	daemon_start_others(daemon);
1114 
1115 	/* Special handling for the main thread. This is the thread
1116 	 * that handles signals and remote control.
1117 	 */
1118 #if !(defined(HAVE_EV_LOOP) || defined(HAVE_EV_DEFAULT_LOOP))
1119 	/* libevent has the last inited base get signals (or any base) */
1120 	if(!worker_init(daemon->workers[0], daemon->cfg, daemon->ports[0], 1))
1121 		fatal_exit("Could not initialize main thread");
1122 #endif
1123 	signal_handling_playback(daemon->workers[0]);
1124 
1125 	if (!shm_main_init(daemon))
1126 		log_warn("SHM has failed");
1127 
1128 	/* Start resolver service on main thread. */
1129 #ifdef HAVE_SYSTEMD
1130 	ret = sd_notify(0, "READY=1");
1131 	if(ret <= 0 && getenv("NOTIFY_SOCKET"))
1132 		fatal_exit("sd_notify failed %s: %s. Make sure that unbound has "
1133 				"access/permission to use the socket presented by systemd.",
1134 				getenv("NOTIFY_SOCKET"),
1135 				(ret==0?"no $NOTIFY_SOCKET": strerror(-ret)));
1136 #endif
1137 	log_info("start of service (%s).", PACKAGE_STRING);
1138 	worker_work(daemon->workers[0]);
1139 #ifdef HAVE_SYSTEMD
1140 	if (daemon->workers[0]->need_to_exit)
1141 		sd_notify(0, "STOPPING=1");
1142 	else
1143 		sd_notify(0, "RELOADING=1");
1144 #endif
1145 	log_info("service stopped (%s).", PACKAGE_STRING);
1146 
1147 	/* we exited! a signal happened! Stop other threads */
1148 	daemon_stop_others(daemon);
1149 
1150 	/* Shutdown SHM */
1151 	shm_main_shutdown(daemon);
1152 
1153 	daemon->reuse_cache = daemon->workers[0]->reuse_cache;
1154 	daemon->need_to_exit = daemon->workers[0]->need_to_exit;
1155 }
1156 
1157 void
daemon_cleanup(struct daemon * daemon)1158 daemon_cleanup(struct daemon* daemon)
1159 {
1160 	int i;
1161 	log_assert(daemon);
1162 	/* before stopping main worker, handle signals ourselves, so we
1163 	   don't die on multiple reload signals for example. */
1164 	signal_handling_record();
1165 	log_thread_set(NULL);
1166 	/* clean up caches because
1167 	 * a) RRset IDs will be recycled after a reload, causing collisions
1168 	 * b) validation config can change, thus rrset, msg, keycache clear
1169 	 *
1170 	 * If we are trying to keep the cache as long as possible, we should
1171 	 * defer the cleanup until we know whether the new configuration allows
1172 	 * the reuse.  (If we're exiting, cleanup should be done here). */
1173 	if(!daemon->reuse_cache || daemon->need_to_exit) {
1174 		slabhash_clear(&daemon->env->rrset_cache->table);
1175 		slabhash_clear(daemon->env->msg_cache);
1176 	}
1177 	daemon->old_num = daemon->num; /* save the current num */
1178 	forwards_delete(daemon->env->fwds);
1179 	daemon->env->fwds = NULL;
1180 	hints_delete(daemon->env->hints);
1181 	daemon->env->hints = NULL;
1182 	local_zones_delete(daemon->local_zones);
1183 	daemon->local_zones = NULL;
1184 	respip_set_delete(daemon->env->respip_set);
1185 	daemon->env->respip_set = NULL;
1186 	views_delete(daemon->env->views);
1187 	daemon->env->views = NULL;
1188 	if(daemon->env->auth_zones)
1189 		auth_zones_cleanup(daemon->env->auth_zones);
1190 	/* key cache is cleared by module deinit during next daemon_fork() */
1191 	daemon_remote_clear(daemon->rc);
1192 	if(daemon->fast_reload_thread)
1193 		fast_reload_thread_stop(daemon->fast_reload_thread);
1194 	if(daemon->fast_reload_printq_list)
1195 		fast_reload_printq_list_delete(daemon->fast_reload_printq_list);
1196 	for(i=0; i<daemon->num; i++)
1197 		worker_delete(daemon->workers[i]);
1198 	free(daemon->workers);
1199 	daemon->workers = NULL;
1200 	/* Unless we're trying to keep the cache, worker alloc_caches should be
1201 	 * cleared and freed here. We do this after deleting workers to
1202 	 * guarantee that the alloc caches are valid throughout the lifetime
1203 	 * of workers. */
1204 	if(!daemon->reuse_cache || daemon->need_to_exit)
1205 		daemon_clear_allocs(daemon);
1206 	daemon->num = 0;
1207 #ifdef USE_DNSTAP
1208 	dt_delete(daemon->dtenv);
1209 	daemon->dtenv = NULL;
1210 #endif
1211 #ifdef USE_DNSCRYPT
1212 	dnsc_delete(daemon->dnscenv);
1213 	daemon->dnscenv = NULL;
1214 #endif
1215 #ifdef HAVE_NGTCP2
1216 	if (daemon->doq_table) {
1217 		doq_table_delete(daemon->doq_table);
1218 		daemon->doq_table = NULL;
1219 	}
1220 #endif
1221 	daemon->cfg = NULL;
1222 }
1223 
1224 void
daemon_delete(struct daemon * daemon)1225 daemon_delete(struct daemon* daemon)
1226 {
1227 	size_t i;
1228 	if(!daemon)
1229 		return;
1230 	modstack_call_deinit(&daemon->mods, daemon->env);
1231 	modstack_call_destartup(&daemon->mods, daemon->env);
1232 	modstack_free(&daemon->mods);
1233 	daemon_remote_delete(daemon->rc);
1234 	for(i = 0; i < daemon->num_ports; i++)
1235 		listening_ports_free(daemon->ports[i]);
1236 	free(daemon->ports);
1237 	listening_ports_free(daemon->rc_ports);
1238 	if(daemon->env) {
1239 		slabhash_delete(daemon->env->msg_cache);
1240 		rrset_cache_delete(daemon->env->rrset_cache);
1241 		infra_delete(daemon->env->infra_cache);
1242 		edns_known_options_delete(daemon->env);
1243 		edns_strings_delete(daemon->env->edns_strings);
1244 		auth_zones_delete(daemon->env->auth_zones);
1245 	}
1246 	ub_randfree(daemon->rand);
1247 	alloc_clear(&daemon->superalloc);
1248 	acl_list_delete(daemon->acl);
1249 	acl_list_delete(daemon->acl_interface);
1250 	tcl_list_delete(daemon->tcl);
1251 	cookie_secrets_delete(daemon->cookie_secrets);
1252 	listen_desetup_locks();
1253 	free(daemon->chroot);
1254 	free(daemon->pidfile);
1255 	free(daemon->cfgfile);
1256 	free(daemon->env);
1257 	daemon_delete_sslctxs(daemon);
1258 	free(daemon);
1259 	/* lex cleanup */
1260 	ub_c_lex_destroy();
1261 	/* libcrypto cleanup */
1262 #ifdef HAVE_SSL
1263 #  if defined(USE_GOST)
1264 	sldns_key_EVP_unload_gost();
1265 #  endif
1266 #  if HAVE_DECL_SSL_COMP_GET_COMPRESSION_METHODS && HAVE_DECL_SK_SSL_COMP_POP_FREE
1267 #    ifndef S_SPLINT_S
1268 #      if OPENSSL_VERSION_NUMBER < 0x10100000
1269 	sk_SSL_COMP_pop_free(comp_meth, (void(*)())CRYPTO_free);
1270 #      endif
1271 #    endif
1272 #  endif
1273 #  ifdef HAVE_OPENSSL_CONFIG
1274 	EVP_cleanup();
1275 #  if (OPENSSL_VERSION_NUMBER < 0x10100000) && !defined(OPENSSL_NO_ENGINE) && defined(HAVE_ENGINE_CLEANUP)
1276 	ENGINE_cleanup();
1277 #  endif
1278 	CONF_modules_free();
1279 #  endif
1280 #  ifdef HAVE_CRYPTO_CLEANUP_ALL_EX_DATA
1281 	CRYPTO_cleanup_all_ex_data(); /* safe, no more threads right now */
1282 #  endif
1283 #  ifdef HAVE_ERR_FREE_STRINGS
1284 	ERR_free_strings();
1285 #  endif
1286 #  if OPENSSL_VERSION_NUMBER < 0x10100000
1287 	RAND_cleanup();
1288 #  endif
1289 #  if defined(HAVE_SSL) && defined(OPENSSL_THREADS) && !defined(THREADS_DISABLED)
1290 	ub_openssl_lock_delete();
1291 #  endif
1292 #ifndef HAVE_ARC4RANDOM
1293 	_ARC4_LOCK_DESTROY();
1294 #endif
1295 #elif defined(HAVE_NSS)
1296 	NSS_Shutdown();
1297 #endif /* HAVE_SSL or HAVE_NSS */
1298 	checklock_stop();
1299 #ifdef USE_WINSOCK
1300 	if(WSACleanup() != 0) {
1301 		log_err("Could not WSACleanup: %s",
1302 			wsa_strerror(WSAGetLastError()));
1303 	}
1304 #endif
1305 }
1306 
daemon_apply_cfg(struct daemon * daemon,struct config_file * cfg)1307 void daemon_apply_cfg(struct daemon* daemon, struct config_file* cfg)
1308 {
1309 	int new_num = cfg->num_threads?cfg->num_threads:1;
1310 
1311         daemon->cfg = cfg;
1312 	config_apply(cfg);
1313 
1314 	/* If this is a reload and we deferred the decision on whether to
1315 	 * reuse the alloc, RRset, and message caches, then check to see if
1316 	 * it's safe to keep the caches:
1317 	 * - changing the number of threads is obviously incompatible with
1318 	 *   keeping the per-thread alloc caches. It also means we have to
1319 	 *   clear RRset and message caches. (note that 'new_num' may be
1320 	 *   adjusted in daemon_create_workers, but for our purpose we can
1321 	 *   simply compare it with 'old_num'; if they are equal here,
1322 	 *   'new_num' won't be adjusted to a different value than 'old_num').
1323 	 * - changing RRset cache size effectively clears any remaining cache
1324 	 *   entries. We could keep their keys in alloc caches, but it would
1325 	 *   be more consistent with the sense of the change to clear allocs
1326 	 *   and free memory. To do so we also have to clear message cache.
1327 	 * - only changing message cache size does not necessarily affect
1328 	 *   RRset or alloc cache. But almost all new subsequent queries will
1329 	 *   require recursive resolution anyway, so it doesn't help much to
1330 	 *   just keep RRset and alloc caches. For simplicity we clear/free
1331 	 *   the other two, too. */
1332 	if(daemon->worker_allocs &&
1333 		(new_num != daemon->old_num ||
1334 		 !slabhash_is_size(daemon->env->msg_cache, cfg->msg_cache_size,
1335 			cfg->msg_cache_slabs) ||
1336 		 !slabhash_is_size(&daemon->env->rrset_cache->table,
1337 			cfg->rrset_cache_size, cfg->rrset_cache_slabs)))
1338 	{
1339 		log_warn("cannot reuse caches due to critical config change");
1340 		slabhash_clear(&daemon->env->rrset_cache->table);
1341 		slabhash_clear(daemon->env->msg_cache);
1342 		daemon_clear_allocs(daemon);
1343 	}
1344 
1345 	if(!slabhash_is_size(daemon->env->msg_cache, cfg->msg_cache_size,
1346 	   	cfg->msg_cache_slabs)) {
1347 		slabhash_delete(daemon->env->msg_cache);
1348 		daemon->env->msg_cache = slabhash_create(cfg->msg_cache_slabs,
1349 			HASH_DEFAULT_STARTARRAY, cfg->msg_cache_size,
1350 			msgreply_sizefunc, query_info_compare,
1351 			query_entry_delete, reply_info_delete, NULL);
1352 		if(!daemon->env->msg_cache) {
1353 			fatal_exit("malloc failure updating config settings");
1354 		}
1355 	}
1356 	if((daemon->env->rrset_cache = rrset_cache_adjust(
1357 		daemon->env->rrset_cache, cfg, &daemon->superalloc)) == 0)
1358 		fatal_exit("malloc failure updating config settings");
1359 	if((daemon->env->infra_cache = infra_adjust(daemon->env->infra_cache,
1360 		cfg))==0)
1361 		fatal_exit("malloc failure updating config settings");
1362 }
1363