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