2 * daemon/daemon.c - collection of workers that handles requests.
4 * Copyright (c) 2007, NLnet Labs. All rights reserved.
6 * This software is open source.
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions
12 * Redistributions of source code must retain the above copyright notice,
13 * this list of conditions and the following disclaimer.
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.
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.
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.
39 * The daemon consists of global settings and a number of workers.
43 #ifdef HAVE_OPENSSL_ERR_H
44 #include <openssl/err.h>
47 #ifdef HAVE_OPENSSL_RAND_H
48 #include <openssl/rand.h>
51 #ifdef HAVE_OPENSSL_CONF_H
52 #include <openssl/conf.h>
55 #ifdef HAVE_OPENSSL_ENGINE_H
56 #include <openssl/engine.h>
69 #include "daemon/daemon.h"
70 #include "daemon/worker.h"
71 #include "daemon/remote.h"
72 #include "daemon/acl_list.h"
74 #include "util/config_file.h"
75 #include "util/data/msgreply.h"
76 #include "util/storage/lookup3.h"
77 #include "util/storage/slabhash.h"
78 #include "services/listen_dnsport.h"
79 #include "services/cache/rrset.h"
80 #include "services/cache/infra.h"
81 #include "services/localzone.h"
82 #include "services/modstack.h"
83 #include "util/module.h"
84 #include "util/random.h"
85 #include "util/tube.h"
86 #include "util/net_help.h"
87 #include "sldns/keyraw.h"
90 /** How many quit requests happened. */
91 static int sig_record_quit = 0;
92 /** How many reload requests happened. */
93 static int sig_record_reload = 0;
95 #if HAVE_DECL_SSL_COMP_GET_COMPRESSION_METHODS
96 /** cleaner ssl memory freeup */
97 static void* comp_meth = NULL;
99 #ifdef LEX_HAS_YYLEX_DESTROY
100 /** remove buffers for parsing and init */
101 int ub_c_lex_destroy(void);
104 /** used when no other sighandling happens, so we don't die
105 * when multiple signals in quick succession are sent to us.
106 * @param sig: signal number.
107 * @return signal handler return type (void or int).
109 static RETSIGTYPE record_sigh(int sig)
111 #ifdef LIBEVENT_SIGNAL_PROBLEM
112 /* cannot log, verbose here because locks may be held */
113 /* quit on signal, no cleanup and statistics,
114 because installed libevent version is not threadsafe */
139 /* ignoring signal */
145 * Signal handling during the time when netevent is disabled.
146 * Stores signals to replay later.
149 signal_handling_record(void)
151 if( signal(SIGTERM, record_sigh) == SIG_ERR ||
153 signal(SIGQUIT, record_sigh) == SIG_ERR ||
156 signal(SIGBREAK, record_sigh) == SIG_ERR ||
159 signal(SIGHUP, record_sigh) == SIG_ERR ||
162 signal(SIGPIPE, SIG_IGN) == SIG_ERR ||
164 signal(SIGINT, record_sigh) == SIG_ERR
166 log_err("install sighandler: %s", strerror(errno));
170 * Replay old signals.
171 * @param wrk: worker that handles signals.
174 signal_handling_playback(struct worker* wrk)
177 if(sig_record_reload)
178 worker_sighandler(SIGHUP, wrk);
181 worker_sighandler(SIGTERM, wrk);
183 sig_record_reload = 0;
189 struct daemon* daemon = (struct daemon*)calloc(1,
190 sizeof(struct daemon));
198 r = WSAStartup(MAKEWORD(2,2), &wsa_data);
200 fatal_exit("could not init winsock. WSAStartup: %s",
203 #endif /* USE_WINSOCK */
204 signal_handling_record();
207 ERR_load_crypto_strings();
208 ERR_load_SSL_strings();
210 (void)sldns_key_EVP_load_gost_id();
212 OpenSSL_add_all_algorithms();
213 # if HAVE_DECL_SSL_COMP_GET_COMPRESSION_METHODS
214 /* grab the COMP method ptr because openssl leaks it */
215 comp_meth = (void*)SSL_COMP_get_compression_methods();
217 (void)SSL_library_init();
218 # if defined(HAVE_SSL) && defined(OPENSSL_THREADS) && !defined(THREADS_DISABLED)
219 if(!ub_openssl_lock_init())
220 fatal_exit("could not init openssl locks");
222 #elif defined(HAVE_NSS)
223 if(NSS_NoDB_Init(NULL) != SECSuccess)
224 fatal_exit("could not init NSS");
225 #endif /* HAVE_SSL or HAVE_NSS */
227 /* init timezone info while we are not chrooted yet */
230 /* open /dev/random if needed */
231 ub_systemseed((unsigned)time(NULL)^(unsigned)getpid()^0xe67);
232 daemon->need_to_exit = 0;
233 modstack_init(&daemon->mods);
234 if(!(daemon->env = (struct module_env*)calloc(1,
235 sizeof(*daemon->env)))) {
239 alloc_init(&daemon->superalloc, NULL, 0);
240 daemon->acl = acl_list_create();
246 if(gettimeofday(&daemon->time_boot, NULL) < 0)
247 log_err("gettimeofday: %s", strerror(errno));
248 daemon->time_last_stat = daemon->time_boot;
253 daemon_open_shared_ports(struct daemon* daemon)
256 if(daemon->cfg->port != daemon->listening_port) {
258 struct listen_port* p0;
259 daemon->reuseport = 0;
260 /* free and close old ports */
261 if(daemon->ports != NULL) {
262 for(i=0; i<daemon->num_ports; i++)
263 listening_ports_free(daemon->ports[i]);
265 daemon->ports = NULL;
267 /* see if we want to reuseport */
269 if(daemon->cfg->so_reuseport && daemon->cfg->num_threads > 0)
270 daemon->reuseport = 1;
272 /* try to use reuseport */
273 p0 = listening_ports_open(daemon->cfg, &daemon->reuseport);
275 listening_ports_free(p0);
278 if(daemon->reuseport) {
279 /* reuseport was successful, allocate for it */
280 daemon->num_ports = (size_t)daemon->cfg->num_threads;
282 /* do the normal, singleportslist thing,
283 * reuseport not enabled or did not work */
284 daemon->num_ports = 1;
286 if(!(daemon->ports = (struct listen_port**)calloc(
287 daemon->num_ports, sizeof(*daemon->ports)))) {
288 listening_ports_free(p0);
291 daemon->ports[0] = p0;
292 if(daemon->reuseport) {
293 /* continue to use reuseport */
294 for(i=1; i<daemon->num_ports; i++) {
295 if(!(daemon->ports[i]=
296 listening_ports_open(daemon->cfg,
298 || !daemon->reuseport ) {
299 for(i=0; i<daemon->num_ports; i++)
300 listening_ports_free(daemon->ports[i]);
302 daemon->ports = NULL;
307 daemon->listening_port = daemon->cfg->port;
309 if(!daemon->cfg->remote_control_enable && daemon->rc_port) {
310 listening_ports_free(daemon->rc_ports);
311 daemon->rc_ports = NULL;
314 if(daemon->cfg->remote_control_enable &&
315 daemon->cfg->control_port != daemon->rc_port) {
316 listening_ports_free(daemon->rc_ports);
317 if(!(daemon->rc_ports=daemon_remote_open_ports(daemon->cfg)))
319 daemon->rc_port = daemon->cfg->control_port;
325 * Setup modules. setup module stack.
326 * @param daemon: the daemon
328 static void daemon_setup_modules(struct daemon* daemon)
330 daemon->env->cfg = daemon->cfg;
331 daemon->env->alloc = &daemon->superalloc;
332 daemon->env->worker = NULL;
333 daemon->env->need_to_validate = 0; /* set by module init below */
334 if(!modstack_setup(&daemon->mods, daemon->cfg->module_conf,
336 fatal_exit("failed to setup modules");
341 * Obtain allowed port numbers, concatenate the list, and shuffle them
342 * (ready to be handed out to threads).
343 * @param daemon: the daemon. Uses rand and cfg.
344 * @param shufport: the portlist output.
345 * @return number of ports available.
347 static int daemon_get_shufport(struct daemon* daemon, int* shufport)
351 for(i=0; i<65536; i++) {
352 if(daemon->cfg->outgoing_avail_ports[i]) {
353 shufport[avail++] = daemon->cfg->
354 outgoing_avail_ports[i];
358 fatal_exit("no ports are permitted for UDP, add "
359 "with outgoing-port-permit");
363 k = ub_random_max(daemon->rand, n+1); /* 0<= k<= n */
365 shufport[k] = shufport[n];
372 * Allocate empty worker structures. With backptr and thread-number,
373 * from 0..numthread initialised. Used as user arguments to new threads.
374 * Creates the daemon random generator if it does not exist yet.
375 * The random generator stays existing between reloads with a unique state.
376 * @param daemon: the daemon with (new) config settings.
379 daemon_create_workers(struct daemon* daemon)
383 log_assert(daemon && daemon->cfg);
385 unsigned int seed = (unsigned int)time(NULL) ^
386 (unsigned int)getpid() ^ 0x438;
387 daemon->rand = ub_initstate(seed, NULL);
389 fatal_exit("could not init random generator");
391 hash_set_raninit((uint32_t)ub_random(daemon->rand));
392 shufport = (int*)calloc(65536, sizeof(int));
394 fatal_exit("out of memory during daemon init");
395 numport = daemon_get_shufport(daemon, shufport);
396 verbose(VERB_ALGO, "total of %d outgoing ports available", numport);
398 daemon->num = (daemon->cfg->num_threads?daemon->cfg->num_threads:1);
399 if(daemon->reuseport && (int)daemon->num < (int)daemon->num_ports) {
400 log_warn("cannot reduce num-threads to %d because so-reuseport "
401 "so continuing with %d threads.", (int)daemon->num,
402 (int)daemon->num_ports);
403 daemon->num = (int)daemon->num_ports;
405 daemon->workers = (struct worker**)calloc((size_t)daemon->num,
406 sizeof(struct worker*));
407 if(daemon->cfg->dnstap) {
409 daemon->dtenv = dt_create(daemon->cfg->dnstap_socket_path,
410 (unsigned int)daemon->num);
412 fatal_exit("dt_create failed");
413 dt_apply_cfg(daemon->dtenv, daemon->cfg);
415 fatal_exit("dnstap enabled in config but not built with dnstap support");
418 for(i=0; i<daemon->num; i++) {
419 if(!(daemon->workers[i] = worker_create(daemon, i,
420 shufport+numport*i/daemon->num,
421 numport*(i+1)/daemon->num - numport*i/daemon->num)))
422 /* the above is not ports/numthr, due to rounding */
423 fatal_exit("could not create worker");
428 #ifdef THREADS_DISABLED
430 * Close all pipes except for the numbered thread.
431 * @param daemon: daemon to close pipes in.
432 * @param thr: thread number 0..num-1 of thread to skip.
434 static void close_other_pipes(struct daemon* daemon, int thr)
437 for(i=0; i<daemon->num; i++)
440 /* only close read part, need to write stats */
441 tube_close_read(daemon->workers[i]->cmd);
443 /* complete close channel to others */
444 tube_delete(daemon->workers[i]->cmd);
445 daemon->workers[i]->cmd = NULL;
449 #endif /* THREADS_DISABLED */
452 * Function to start one thread.
453 * @param arg: user argument.
454 * @return: void* user return value could be used for thread_join results.
457 thread_start(void* arg)
459 struct worker* worker = (struct worker*)arg;
461 log_thread_set(&worker->thread_num);
462 ub_thread_blocksigs();
463 #ifdef THREADS_DISABLED
464 /* close pipe ends used by main */
465 tube_close_write(worker->cmd);
466 close_other_pipes(worker->daemon, worker->thread_num);
469 if(worker->daemon->cfg->so_reuseport)
470 port_num = worker->thread_num % worker->daemon->num_ports;
474 if(!worker_init(worker, worker->daemon->cfg,
475 worker->daemon->ports[port_num], 0))
476 fatal_exit("Could not initialize thread");
483 * Fork and init the other threads. Main thread returns for special handling.
484 * @param daemon: the daemon with other threads to fork.
487 daemon_start_others(struct daemon* daemon)
491 verbose(VERB_ALGO, "start threads");
492 /* skip i=0, is this thread */
493 for(i=1; i<daemon->num; i++) {
494 ub_thread_create(&daemon->workers[i]->thr_id,
495 thread_start, daemon->workers[i]);
496 #ifdef THREADS_DISABLED
497 /* close pipe end of child */
498 tube_close_read(daemon->workers[i]->cmd);
499 #endif /* no threads */
504 * Stop the other threads.
505 * @param daemon: the daemon with other threads.
508 daemon_stop_others(struct daemon* daemon)
512 verbose(VERB_ALGO, "stop threads");
513 /* skip i=0, is this thread */
514 /* use i=0 buffer for sending cmds; because we are #0 */
515 for(i=1; i<daemon->num; i++) {
516 worker_send_cmd(daemon->workers[i], worker_cmd_quit);
518 /* wait for them to quit */
519 for(i=1; i<daemon->num; i++) {
520 /* join it to make sure its dead */
521 verbose(VERB_ALGO, "join %d", i);
522 ub_thread_join(daemon->workers[i]->thr_id);
523 verbose(VERB_ALGO, "join success %d", i);
528 daemon_fork(struct daemon* daemon)
531 if(!acl_list_apply_cfg(daemon->acl, daemon->cfg))
532 fatal_exit("Could not setup access control list");
533 if(!(daemon->local_zones = local_zones_create()))
534 fatal_exit("Could not create local zones: out of memory");
535 if(!local_zones_apply_cfg(daemon->local_zones, daemon->cfg))
536 fatal_exit("Could not set up local zones");
539 daemon_setup_modules(daemon);
541 /* first create all the worker structures, so we can pass
542 * them to the newly created threads.
544 daemon_create_workers(daemon);
546 #if defined(HAVE_EV_LOOP) || defined(HAVE_EV_DEFAULT_LOOP)
547 /* in libev the first inited base gets signals */
548 if(!worker_init(daemon->workers[0], daemon->cfg, daemon->ports[0], 1))
549 fatal_exit("Could not initialize main thread");
552 /* Now create the threads and init the workers.
553 * By the way, this is thread #0 (the main thread).
555 daemon_start_others(daemon);
557 /* Special handling for the main thread. This is the thread
558 * that handles signals and remote control.
560 #if !(defined(HAVE_EV_LOOP) || defined(HAVE_EV_DEFAULT_LOOP))
561 /* libevent has the last inited base get signals (or any base) */
562 if(!worker_init(daemon->workers[0], daemon->cfg, daemon->ports[0], 1))
563 fatal_exit("Could not initialize main thread");
565 signal_handling_playback(daemon->workers[0]);
567 /* Start resolver service on main thread. */
568 log_info("start of service (%s).", PACKAGE_STRING);
569 worker_work(daemon->workers[0]);
570 log_info("service stopped (%s).", PACKAGE_STRING);
572 /* we exited! a signal happened! Stop other threads */
573 daemon_stop_others(daemon);
575 daemon->need_to_exit = daemon->workers[0]->need_to_exit;
579 daemon_cleanup(struct daemon* daemon)
583 /* before stopping main worker, handle signals ourselves, so we
584 don't die on multiple reload signals for example. */
585 signal_handling_record();
586 log_thread_set(NULL);
587 /* clean up caches because
588 * a) RRset IDs will be recycled after a reload, causing collisions
589 * b) validation config can change, thus rrset, msg, keycache clear
590 * The infra cache is kept, the timing and edns info is still valid */
591 slabhash_clear(&daemon->env->rrset_cache->table);
592 slabhash_clear(daemon->env->msg_cache);
593 local_zones_delete(daemon->local_zones);
594 daemon->local_zones = NULL;
595 /* key cache is cleared by module desetup during next daemon_init() */
596 daemon_remote_clear(daemon->rc);
597 for(i=0; i<daemon->num; i++)
598 worker_delete(daemon->workers[i]);
599 free(daemon->workers);
600 daemon->workers = NULL;
603 dt_delete(daemon->dtenv);
609 daemon_delete(struct daemon* daemon)
614 modstack_desetup(&daemon->mods, daemon->env);
615 daemon_remote_delete(daemon->rc);
616 for(i = 0; i < daemon->num_ports; i++)
617 listening_ports_free(daemon->ports[i]);
619 listening_ports_free(daemon->rc_ports);
621 slabhash_delete(daemon->env->msg_cache);
622 rrset_cache_delete(daemon->env->rrset_cache);
623 infra_delete(daemon->env->infra_cache);
625 ub_randfree(daemon->rand);
626 alloc_clear(&daemon->superalloc);
627 acl_list_delete(daemon->acl);
628 free(daemon->chroot);
629 free(daemon->pidfile);
632 SSL_CTX_free((SSL_CTX*)daemon->listen_sslctx);
633 SSL_CTX_free((SSL_CTX*)daemon->connect_sslctx);
636 #ifdef LEX_HAS_YYLEX_DESTROY
640 /* libcrypto cleanup */
642 # if defined(USE_GOST) && defined(HAVE_LDNS_KEY_EVP_UNLOAD_GOST)
643 sldns_key_EVP_unload_gost();
645 # if HAVE_DECL_SSL_COMP_GET_COMPRESSION_METHODS && HAVE_DECL_SK_SSL_COMP_POP_FREE
647 # if OPENSSL_VERSION_NUMBER < 0x10100000
648 sk_SSL_COMP_pop_free(comp_meth, (void(*)())CRYPTO_free);
652 # ifdef HAVE_OPENSSL_CONFIG
654 # if OPENSSL_VERSION_NUMBER < 0x10100000
659 CRYPTO_cleanup_all_ex_data(); /* safe, no more threads right now */
661 # if OPENSSL_VERSION_NUMBER < 0x10100000
664 # if defined(HAVE_SSL) && defined(OPENSSL_THREADS) && !defined(THREADS_DISABLED)
665 ub_openssl_lock_delete();
667 #elif defined(HAVE_NSS)
669 #endif /* HAVE_SSL or HAVE_NSS */
672 if(WSACleanup() != 0) {
673 log_err("Could not WSACleanup: %s",
674 wsa_strerror(WSAGetLastError()));
679 void daemon_apply_cfg(struct daemon* daemon, struct config_file* cfg)
683 if(!daemon->env->msg_cache ||
684 cfg->msg_cache_size != slabhash_get_size(daemon->env->msg_cache) ||
685 cfg->msg_cache_slabs != daemon->env->msg_cache->size) {
686 slabhash_delete(daemon->env->msg_cache);
687 daemon->env->msg_cache = slabhash_create(cfg->msg_cache_slabs,
688 HASH_DEFAULT_STARTARRAY, cfg->msg_cache_size,
689 msgreply_sizefunc, query_info_compare,
690 query_entry_delete, reply_info_delete, NULL);
691 if(!daemon->env->msg_cache) {
692 fatal_exit("malloc failure updating config settings");
695 if((daemon->env->rrset_cache = rrset_cache_adjust(
696 daemon->env->rrset_cache, cfg, &daemon->superalloc)) == 0)
697 fatal_exit("malloc failure updating config settings");
698 if((daemon->env->infra_cache = infra_adjust(daemon->env->infra_cache,
700 fatal_exit("malloc failure updating config settings");