xref: /openbsd-src/usr.sbin/unbound/daemon/daemon.c (revision 4c1e55dc91edd6e69ccc60ce855900fbc12cf34f)
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 LIMITED
25  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
26  * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE
27  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
28  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
29  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
30  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
31  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
32  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
33  * 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 #include <ldns/ldns.h>
59 #include "daemon/daemon.h"
60 #include "daemon/worker.h"
61 #include "daemon/remote.h"
62 #include "daemon/acl_list.h"
63 #include "util/log.h"
64 #include "util/config_file.h"
65 #include "util/data/msgreply.h"
66 #include "util/storage/lookup3.h"
67 #include "util/storage/slabhash.h"
68 #include "services/listen_dnsport.h"
69 #include "services/cache/rrset.h"
70 #include "services/cache/infra.h"
71 #include "services/localzone.h"
72 #include "services/modstack.h"
73 #include "util/module.h"
74 #include "util/random.h"
75 #include "util/tube.h"
76 #include <signal.h>
77 
78 /** How many quit requests happened. */
79 static int sig_record_quit = 0;
80 /** How many reload requests happened. */
81 static int sig_record_reload = 0;
82 
83 #if HAVE_DECL_SSL_COMP_GET_COMPRESSION_METHODS
84 /** cleaner ssl memory freeup */
85 static void* comp_meth = NULL;
86 #endif
87 #ifdef LEX_HAS_YYLEX_DESTROY
88 /** remove buffers for parsing and init */
89 int ub_c_lex_destroy(void);
90 #endif
91 
92 /** used when no other sighandling happens, so we don't die
93   * when multiple signals in quick succession are sent to us.
94   * @param sig: signal number.
95   * @return signal handler return type (void or int).
96   */
97 static RETSIGTYPE record_sigh(int sig)
98 {
99 #ifdef LIBEVENT_SIGNAL_PROBLEM
100 	verbose(VERB_OPS, "quit on signal, no cleanup and statistics, "
101 		"because installed libevent version is not threadsafe");
102 	exit(0);
103 #endif
104 	switch(sig)
105 	{
106 		case SIGTERM:
107 #ifdef SIGQUIT
108 		case SIGQUIT:
109 #endif
110 #ifdef SIGBREAK
111 		case SIGBREAK:
112 #endif
113 		case SIGINT:
114 			sig_record_quit++;
115 			break;
116 #ifdef SIGHUP
117 		case SIGHUP:
118 			sig_record_reload++;
119 			break;
120 #endif
121 #ifdef SIGPIPE
122 		case SIGPIPE:
123 			break;
124 #endif
125 		default:
126 			log_err("ignoring signal %d", sig);
127 	}
128 }
129 
130 /**
131  * Signal handling during the time when netevent is disabled.
132  * Stores signals to replay later.
133  */
134 static void
135 signal_handling_record(void)
136 {
137 	if( signal(SIGTERM, record_sigh) == SIG_ERR ||
138 #ifdef SIGQUIT
139 		signal(SIGQUIT, record_sigh) == SIG_ERR ||
140 #endif
141 #ifdef SIGBREAK
142 		signal(SIGBREAK, record_sigh) == SIG_ERR ||
143 #endif
144 #ifdef SIGHUP
145 		signal(SIGHUP, record_sigh) == SIG_ERR ||
146 #endif
147 #ifdef SIGPIPE
148 		signal(SIGPIPE, SIG_IGN) == SIG_ERR ||
149 #endif
150 		signal(SIGINT, record_sigh) == SIG_ERR
151 		)
152 		log_err("install sighandler: %s", strerror(errno));
153 }
154 
155 /**
156  * Replay old signals.
157  * @param wrk: worker that handles signals.
158  */
159 static void
160 signal_handling_playback(struct worker* wrk)
161 {
162 #ifdef SIGHUP
163 	if(sig_record_reload)
164 		worker_sighandler(SIGHUP, wrk);
165 #endif
166 	if(sig_record_quit)
167 		worker_sighandler(SIGTERM, wrk);
168 	sig_record_quit = 0;
169 	sig_record_reload = 0;
170 }
171 
172 struct daemon*
173 daemon_init(void)
174 {
175 	struct daemon* daemon = (struct daemon*)calloc(1,
176 		sizeof(struct daemon));
177 #ifdef USE_WINSOCK
178 	int r;
179 	WSADATA wsa_data;
180 #endif
181 	if(!daemon)
182 		return NULL;
183 #ifdef USE_WINSOCK
184 	r = WSAStartup(MAKEWORD(2,2), &wsa_data);
185 	if(r != 0) {
186 		fatal_exit("could not init winsock. WSAStartup: %s",
187 			wsa_strerror(r));
188 	}
189 #endif /* USE_WINSOCK */
190 	signal_handling_record();
191 	checklock_start();
192 	ERR_load_crypto_strings();
193 	ERR_load_SSL_strings();
194 #ifdef HAVE_OPENSSL_CONFIG
195 	OPENSSL_config("unbound");
196 #endif
197 #ifdef USE_GOST
198 	(void)ldns_key_EVP_load_gost_id();
199 #endif
200 	OpenSSL_add_all_algorithms();
201 #if HAVE_DECL_SSL_COMP_GET_COMPRESSION_METHODS
202 	/* grab the COMP method ptr because openssl leaks it */
203 	comp_meth = (void*)SSL_COMP_get_compression_methods();
204 #endif
205 	(void)SSL_library_init();
206 #ifdef HAVE_TZSET
207 	/* init timezone info while we are not chrooted yet */
208 	tzset();
209 #endif
210 	/* open /dev/random if needed */
211 	ub_systemseed((unsigned)time(NULL)^(unsigned)getpid()^0xe67);
212 	daemon->need_to_exit = 0;
213 	modstack_init(&daemon->mods);
214 	if(!(daemon->env = (struct module_env*)calloc(1,
215 		sizeof(*daemon->env)))) {
216 		free(daemon);
217 		return NULL;
218 	}
219 	alloc_init(&daemon->superalloc, NULL, 0);
220 	daemon->acl = acl_list_create();
221 	if(!daemon->acl) {
222 		free(daemon->env);
223 		free(daemon);
224 		return NULL;
225 	}
226 	if(gettimeofday(&daemon->time_boot, NULL) < 0)
227 		log_err("gettimeofday: %s", strerror(errno));
228 	daemon->time_last_stat = daemon->time_boot;
229 	return daemon;
230 }
231 
232 int
233 daemon_open_shared_ports(struct daemon* daemon)
234 {
235 	log_assert(daemon);
236 	if(daemon->cfg->port != daemon->listening_port) {
237 		listening_ports_free(daemon->ports);
238 		if(!(daemon->ports=listening_ports_open(daemon->cfg)))
239 			return 0;
240 		daemon->listening_port = daemon->cfg->port;
241 	}
242 	if(!daemon->cfg->remote_control_enable && daemon->rc_port) {
243 		listening_ports_free(daemon->rc_ports);
244 		daemon->rc_ports = NULL;
245 		daemon->rc_port = 0;
246 	}
247 	if(daemon->cfg->remote_control_enable &&
248 		daemon->cfg->control_port != daemon->rc_port) {
249 		listening_ports_free(daemon->rc_ports);
250 		if(!(daemon->rc_ports=daemon_remote_open_ports(daemon->cfg)))
251 			return 0;
252 		daemon->rc_port = daemon->cfg->control_port;
253 	}
254 	return 1;
255 }
256 
257 /**
258  * Setup modules. setup module stack.
259  * @param daemon: the daemon
260  */
261 static void daemon_setup_modules(struct daemon* daemon)
262 {
263 	daemon->env->cfg = daemon->cfg;
264 	daemon->env->alloc = &daemon->superalloc;
265 	daemon->env->worker = NULL;
266 	daemon->env->need_to_validate = 0; /* set by module init below */
267 	if(!modstack_setup(&daemon->mods, daemon->cfg->module_conf,
268 		daemon->env)) {
269 		fatal_exit("failed to setup modules");
270 	}
271 }
272 
273 /**
274  * Obtain allowed port numbers, concatenate the list, and shuffle them
275  * (ready to be handed out to threads).
276  * @param daemon: the daemon. Uses rand and cfg.
277  * @param shufport: the portlist output.
278  * @return number of ports available.
279  */
280 static int daemon_get_shufport(struct daemon* daemon, int* shufport)
281 {
282 	int i, n, k, temp;
283 	int avail = 0;
284 	for(i=0; i<65536; i++) {
285 		if(daemon->cfg->outgoing_avail_ports[i]) {
286 			shufport[avail++] = daemon->cfg->
287 				outgoing_avail_ports[i];
288 		}
289 	}
290 	if(avail == 0)
291 		fatal_exit("no ports are permitted for UDP, add "
292 			"with outgoing-port-permit");
293         /* Knuth shuffle */
294 	n = avail;
295 	while(--n > 0) {
296 		k = ub_random_max(daemon->rand, n+1); /* 0<= k<= n */
297 		temp = shufport[k];
298 		shufport[k] = shufport[n];
299 		shufport[n] = temp;
300 	}
301 	return avail;
302 }
303 
304 /**
305  * Allocate empty worker structures. With backptr and thread-number,
306  * from 0..numthread initialised. Used as user arguments to new threads.
307  * Creates the daemon random generator if it does not exist yet.
308  * The random generator stays existing between reloads with a unique state.
309  * @param daemon: the daemon with (new) config settings.
310  */
311 static void
312 daemon_create_workers(struct daemon* daemon)
313 {
314 	int i, numport;
315 	int* shufport;
316 	log_assert(daemon && daemon->cfg);
317 	if(!daemon->rand) {
318 		unsigned int seed = (unsigned int)time(NULL) ^
319 			(unsigned int)getpid() ^ 0x438;
320 		daemon->rand = ub_initstate(seed, NULL);
321 		if(!daemon->rand)
322 			fatal_exit("could not init random generator");
323 	}
324 	hash_set_raninit((uint32_t)ub_random(daemon->rand));
325 	shufport = (int*)calloc(65536, sizeof(int));
326 	if(!shufport)
327 		fatal_exit("out of memory during daemon init");
328 	numport = daemon_get_shufport(daemon, shufport);
329 	verbose(VERB_ALGO, "total of %d outgoing ports available", numport);
330 
331 	daemon->num = (daemon->cfg->num_threads?daemon->cfg->num_threads:1);
332 	daemon->workers = (struct worker**)calloc((size_t)daemon->num,
333 		sizeof(struct worker*));
334 	for(i=0; i<daemon->num; i++) {
335 		if(!(daemon->workers[i] = worker_create(daemon, i,
336 			shufport+numport*i/daemon->num,
337 			numport*(i+1)/daemon->num - numport*i/daemon->num)))
338 			/* the above is not ports/numthr, due to rounding */
339 			fatal_exit("could not create worker");
340 	}
341 	free(shufport);
342 }
343 
344 #ifdef THREADS_DISABLED
345 /**
346  * Close all pipes except for the numbered thread.
347  * @param daemon: daemon to close pipes in.
348  * @param thr: thread number 0..num-1 of thread to skip.
349  */
350 static void close_other_pipes(struct daemon* daemon, int thr)
351 {
352 	int i;
353 	for(i=0; i<daemon->num; i++)
354 		if(i!=thr) {
355 			if(i==0) {
356 				/* only close read part, need to write stats */
357 				tube_close_read(daemon->workers[i]->cmd);
358 			} else {
359 				/* complete close channel to others */
360 				tube_delete(daemon->workers[i]->cmd);
361 				daemon->workers[i]->cmd = NULL;
362 			}
363 		}
364 }
365 #endif /* THREADS_DISABLED */
366 
367 /**
368  * Function to start one thread.
369  * @param arg: user argument.
370  * @return: void* user return value could be used for thread_join results.
371  */
372 static void*
373 thread_start(void* arg)
374 {
375 	struct worker* worker = (struct worker*)arg;
376 	log_thread_set(&worker->thread_num);
377 	ub_thread_blocksigs();
378 #ifdef THREADS_DISABLED
379 	/* close pipe ends used by main */
380 	tube_close_write(worker->cmd);
381 	close_other_pipes(worker->daemon, worker->thread_num);
382 #endif
383 	if(!worker_init(worker, worker->daemon->cfg, worker->daemon->ports, 0))
384 		fatal_exit("Could not initialize thread");
385 
386 	worker_work(worker);
387 	return NULL;
388 }
389 
390 /**
391  * Fork and init the other threads. Main thread returns for special handling.
392  * @param daemon: the daemon with other threads to fork.
393  */
394 static void
395 daemon_start_others(struct daemon* daemon)
396 {
397 	int i;
398 	log_assert(daemon);
399 	verbose(VERB_ALGO, "start threads");
400 	/* skip i=0, is this thread */
401 	for(i=1; i<daemon->num; i++) {
402 		ub_thread_create(&daemon->workers[i]->thr_id,
403 			thread_start, daemon->workers[i]);
404 #ifdef THREADS_DISABLED
405 		/* close pipe end of child */
406 		tube_close_read(daemon->workers[i]->cmd);
407 #endif /* no threads */
408 	}
409 }
410 
411 /**
412  * Stop the other threads.
413  * @param daemon: the daemon with other threads.
414  */
415 static void
416 daemon_stop_others(struct daemon* daemon)
417 {
418 	int i;
419 	log_assert(daemon);
420 	verbose(VERB_ALGO, "stop threads");
421 	/* skip i=0, is this thread */
422 	/* use i=0 buffer for sending cmds; because we are #0 */
423 	for(i=1; i<daemon->num; i++) {
424 		worker_send_cmd(daemon->workers[i], worker_cmd_quit);
425 	}
426 	/* wait for them to quit */
427 	for(i=1; i<daemon->num; i++) {
428 		/* join it to make sure its dead */
429 		verbose(VERB_ALGO, "join %d", i);
430 		ub_thread_join(daemon->workers[i]->thr_id);
431 		verbose(VERB_ALGO, "join success %d", i);
432 	}
433 }
434 
435 void
436 daemon_fork(struct daemon* daemon)
437 {
438 	log_assert(daemon);
439 	if(!acl_list_apply_cfg(daemon->acl, daemon->cfg))
440 		fatal_exit("Could not setup access control list");
441 	if(!(daemon->local_zones = local_zones_create()))
442 		fatal_exit("Could not create local zones: out of memory");
443 	if(!local_zones_apply_cfg(daemon->local_zones, daemon->cfg))
444 		fatal_exit("Could not set up local zones");
445 
446 	/* setup modules */
447 	daemon_setup_modules(daemon);
448 
449 	/* first create all the worker structures, so we can pass
450 	 * them to the newly created threads.
451 	 */
452 	daemon_create_workers(daemon);
453 
454 #if defined(HAVE_EV_LOOP) || defined(HAVE_EV_DEFAULT_LOOP)
455 	/* in libev the first inited base gets signals */
456 	if(!worker_init(daemon->workers[0], daemon->cfg, daemon->ports, 1))
457 		fatal_exit("Could not initialize main thread");
458 #endif
459 
460 	/* Now create the threads and init the workers.
461 	 * By the way, this is thread #0 (the main thread).
462 	 */
463 	daemon_start_others(daemon);
464 
465 	/* Special handling for the main thread. This is the thread
466 	 * that handles signals and remote control.
467 	 */
468 #if !(defined(HAVE_EV_LOOP) || defined(HAVE_EV_DEFAULT_LOOP))
469 	/* libevent has the last inited base get signals (or any base) */
470 	if(!worker_init(daemon->workers[0], daemon->cfg, daemon->ports, 1))
471 		fatal_exit("Could not initialize main thread");
472 #endif
473 	signal_handling_playback(daemon->workers[0]);
474 
475 	/* Start resolver service on main thread. */
476 	log_info("start of service (%s).", PACKAGE_STRING);
477 	worker_work(daemon->workers[0]);
478 	log_info("service stopped (%s).", PACKAGE_STRING);
479 
480 	/* we exited! a signal happened! Stop other threads */
481 	daemon_stop_others(daemon);
482 
483 	daemon->need_to_exit = daemon->workers[0]->need_to_exit;
484 }
485 
486 void
487 daemon_cleanup(struct daemon* daemon)
488 {
489 	int i;
490 	log_assert(daemon);
491 	/* before stopping main worker, handle signals ourselves, so we
492 	   don't die on multiple reload signals for example. */
493 	signal_handling_record();
494 	log_thread_set(NULL);
495 	/* clean up caches because
496 	 * a) RRset IDs will be recycled after a reload, causing collisions
497 	 * b) validation config can change, thus rrset, msg, keycache clear
498 	 * The infra cache is kept, the timing and edns info is still valid */
499 	slabhash_clear(&daemon->env->rrset_cache->table);
500 	slabhash_clear(daemon->env->msg_cache);
501 	local_zones_delete(daemon->local_zones);
502 	daemon->local_zones = NULL;
503 	/* key cache is cleared by module desetup during next daemon_init() */
504 	daemon_remote_clear(daemon->rc);
505 	for(i=0; i<daemon->num; i++)
506 		worker_delete(daemon->workers[i]);
507 	free(daemon->workers);
508 	daemon->workers = NULL;
509 	daemon->num = 0;
510 	daemon->cfg = NULL;
511 }
512 
513 void
514 daemon_delete(struct daemon* daemon)
515 {
516 	if(!daemon)
517 		return;
518 	modstack_desetup(&daemon->mods, daemon->env);
519 	daemon_remote_delete(daemon->rc);
520 	listening_ports_free(daemon->ports);
521 	listening_ports_free(daemon->rc_ports);
522 	if(daemon->env) {
523 		slabhash_delete(daemon->env->msg_cache);
524 		rrset_cache_delete(daemon->env->rrset_cache);
525 		infra_delete(daemon->env->infra_cache);
526 	}
527 	ub_randfree(daemon->rand);
528 	alloc_clear(&daemon->superalloc);
529 	acl_list_delete(daemon->acl);
530 	free(daemon->chroot);
531 	free(daemon->pidfile);
532 	free(daemon->env);
533 	SSL_CTX_free((SSL_CTX*)daemon->listen_sslctx);
534 	SSL_CTX_free((SSL_CTX*)daemon->connect_sslctx);
535 	free(daemon);
536 #ifdef LEX_HAS_YYLEX_DESTROY
537 	/* lex cleanup */
538 	ub_c_lex_destroy();
539 #endif
540 	/* libcrypto cleanup */
541 #if defined(USE_GOST) && defined(HAVE_LDNS_KEY_EVP_UNLOAD_GOST)
542 	ldns_key_EVP_unload_gost();
543 #endif
544 #if HAVE_DECL_SSL_COMP_GET_COMPRESSION_METHODS && HAVE_DECL_SK_SSL_COMP_POP_FREE
545 #ifndef S_SPLINT_S
546 	sk_SSL_COMP_pop_free(comp_meth, (void(*)())CRYPTO_free);
547 #endif
548 #endif
549 #ifdef HAVE_OPENSSL_CONFIG
550 	EVP_cleanup();
551 	ENGINE_cleanup();
552 	CONF_modules_free();
553 #endif
554 	CRYPTO_cleanup_all_ex_data(); /* safe, no more threads right now */
555 	ERR_remove_state(0);
556 	ERR_free_strings();
557 	RAND_cleanup();
558 	checklock_stop();
559 #ifdef USE_WINSOCK
560 	if(WSACleanup() != 0) {
561 		log_err("Could not WSACleanup: %s",
562 			wsa_strerror(WSAGetLastError()));
563 	}
564 #endif
565 }
566 
567 void daemon_apply_cfg(struct daemon* daemon, struct config_file* cfg)
568 {
569         daemon->cfg = cfg;
570 	config_apply(cfg);
571 	if(!daemon->env->msg_cache ||
572 	   cfg->msg_cache_size != slabhash_get_size(daemon->env->msg_cache) ||
573 	   cfg->msg_cache_slabs != daemon->env->msg_cache->size) {
574 		slabhash_delete(daemon->env->msg_cache);
575 		daemon->env->msg_cache = slabhash_create(cfg->msg_cache_slabs,
576 			HASH_DEFAULT_STARTARRAY, cfg->msg_cache_size,
577 			msgreply_sizefunc, query_info_compare,
578 			query_entry_delete, reply_info_delete, NULL);
579 		if(!daemon->env->msg_cache) {
580 			fatal_exit("malloc failure updating config settings");
581 		}
582 	}
583 	if((daemon->env->rrset_cache = rrset_cache_adjust(
584 		daemon->env->rrset_cache, cfg, &daemon->superalloc)) == 0)
585 		fatal_exit("malloc failure updating config settings");
586 	if((daemon->env->infra_cache = infra_adjust(daemon->env->infra_cache,
587 		cfg))==0)
588 		fatal_exit("malloc failure updating config settings");
589 }
590