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