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