2 * daemon/unbound.c - main program for unbound DNS resolver daemon.
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.
40 * Main program to start the DNS resolver daemon.
49 #include "daemon/daemon.h"
50 #include "daemon/remote.h"
51 #include "util/config_file.h"
52 #include "util/storage/slabhash.h"
53 #include "services/listen_dnsport.h"
54 #include "services/cache/rrset.h"
55 #include "services/cache/infra.h"
56 #include "util/fptr_wlist.h"
57 #include "util/data/msgreply.h"
58 #include "util/module.h"
59 #include "util/net_help.h"
60 #include "util/ub_event.h"
63 #include <openssl/crypto.h>
70 #include <openssl/ssl.h>
73 /* splint chokes on this system header file */
74 #ifdef HAVE_SYS_RESOURCE_H
75 #include <sys/resource.h>
77 #endif /* S_SPLINT_S */
78 #ifdef HAVE_LOGIN_CAP_H
79 #include <login_cap.h>
83 # include "winrc/win_svc.h"
91 /** print build options. */
93 print_build_options(void)
96 const char *evnm="event", *evsys="", *evmethod="";
99 struct ub_event_base* base;
100 printf("Version %s\n\n", PACKAGE_VERSION);
101 printf("Configure line: %s\n", CONFCMDLINE);
102 base = ub_default_event_base(0,&t,&now);
103 ub_get_event_sys(base, &evnm, &evsys, &evmethod);
104 printf("Linked libs: %s %s (it uses %s), %s\n",
105 evnm, evsys, evmethod,
107 # ifdef SSLEAY_VERSION
108 SSLeay_version(SSLEAY_VERSION)
110 OpenSSL_version(OPENSSL_VERSION)
112 #elif defined(HAVE_NSS)
114 #elif defined(HAVE_NETTLE)
118 printf("Linked modules:");
119 for(m = module_list_avail(); *m; m++)
123 printf("DNSCrypt feature available\n");
125 #ifdef USE_TCP_FASTOPEN
126 printf("TCP Fastopen feature available\n");
128 ub_event_base_free(base);
129 printf("\nBSD licensed, see LICENSE in source package for details.\n");
130 printf("Report bugs to %s\n", PACKAGE_BUGREPORT);
137 printf("usage: unbound [options]\n");
138 printf(" start unbound daemon DNS resolver.\n");
139 printf("-h this help.\n");
140 printf("-c file config file to read instead of %s\n", CONFIGFILE);
141 printf(" file format is described in unbound.conf(5).\n");
142 printf("-d do not fork into the background.\n");
143 printf("-p do not create a pidfile.\n");
144 printf("-v verbose (more times to increase verbosity).\n");
145 printf("-V show version number and build options.\n");
147 printf("-w opt windows option: \n");
148 printf(" install, remove - manage the services entry\n");
149 printf(" service - used to start from services control panel\n");
151 printf("\nVersion %s\n", PACKAGE_VERSION);
152 printf("BSD licensed, see LICENSE in source package for details.\n");
153 printf("Report bugs to %s\n", PACKAGE_BUGREPORT);
156 #ifndef unbound_testbound
157 int replay_var_compare(const void* ATTR_UNUSED(a), const void* ATTR_UNUSED(b))
164 /** check file descriptor count */
166 checkrlimits(struct config_file* cfg)
169 #ifdef HAVE_GETRLIMIT
170 /* list has number of ports to listen to, ifs number addresses */
171 int list = ((cfg->do_udp?1:0) + (cfg->do_tcp?1 +
172 (int)cfg->incoming_num_tcp:0));
173 size_t listen_ifs = (size_t)(cfg->num_ifs==0?
174 ((cfg->do_ip4 && !cfg->if_automatic?1:0) +
175 (cfg->do_ip6?1:0)):cfg->num_ifs);
176 size_t listen_num = list*listen_ifs;
177 size_t outudpnum = (size_t)cfg->outgoing_num_ports;
178 size_t outtcpnum = cfg->outgoing_num_tcp;
179 size_t misc = 4; /* logfile, pidfile, stdout... */
180 size_t perthread_noudp = listen_num + outtcpnum +
181 2/*cmdpipe*/ + 2/*libevent*/ + misc;
182 size_t perthread = perthread_noudp + outudpnum;
184 #if !defined(HAVE_PTHREAD) && !defined(HAVE_SOLARIS_THREADS)
185 int numthread = 1; /* it forks */
187 int numthread = (cfg->num_threads?cfg->num_threads:1);
189 size_t total = numthread * perthread + misc;
194 strncmp(ub_event_get_version(), "mini-event", 10) == 0) {
195 log_warn("too many file descriptors requested. The builtin"
196 "mini-event cannot handle more than 1024. Config "
197 "for less fds or compile with libevent");
198 if(numthread*perthread_noudp+15 > 1024)
199 fatal_exit("too much tcp. not enough fds.");
200 cfg->outgoing_num_ports = (int)((1024
201 - numthread*perthread_noudp
202 - 10 /* safety margin */) /numthread);
203 log_warn("continuing with less udp ports: %u",
204 cfg->outgoing_num_ports);
208 strncmp(ub_event_get_version(), "winsock-event", 13) == 0) {
209 log_err("too many file descriptors requested. The winsock"
210 " event handler cannot handle more than 64 per "
211 " thread. Config for less fds");
212 if(perthread_noudp+2 > 64)
213 fatal_exit("too much tcp. not enough fds.");
214 cfg->outgoing_num_ports = (int)((64
216 - 2/* safety margin */));
217 log_warn("continuing with less udp ports: %u",
218 cfg->outgoing_num_ports);
219 total = numthread*(perthread_noudp+
220 (size_t)cfg->outgoing_num_ports)+misc;
222 if(getrlimit(RLIMIT_NOFILE, &rlim) < 0) {
223 log_warn("getrlimit: %s", strerror(errno));
226 if(rlim.rlim_cur == (rlim_t)RLIM_INFINITY)
228 if((size_t)rlim.rlim_cur < total) {
229 avail = (size_t)rlim.rlim_cur;
230 rlim.rlim_cur = (rlim_t)(total + 10);
231 rlim.rlim_max = (rlim_t)(total + 10);
232 #ifdef HAVE_SETRLIMIT
233 if(setrlimit(RLIMIT_NOFILE, &rlim) < 0) {
234 log_warn("setrlimit: %s", strerror(errno));
236 log_warn("cannot increase max open fds from %u to %u",
237 (unsigned)avail, (unsigned)total+10);
238 /* check that calculation below does not underflow,
239 * with 15 as margin */
240 if(numthread*perthread_noudp+15 > avail)
241 fatal_exit("too much tcp. not enough fds.");
242 cfg->outgoing_num_ports = (int)((avail
243 - numthread*perthread_noudp
244 - 10 /* safety margin */) /numthread);
245 log_warn("continuing with less udp ports: %u",
246 cfg->outgoing_num_ports);
247 log_warn("increase ulimit or decrease threads, "
248 "ports in config to remove this warning");
250 #ifdef HAVE_SETRLIMIT
253 verbose(VERB_ALGO, "increased limit(open files) from %u to %u",
254 (unsigned)avail, (unsigned)total+10);
258 #endif /* HAVE_GETRLIMIT */
259 #endif /* S_SPLINT_S */
262 /** set verbosity, check rlimits, cache settings */
264 apply_settings(struct daemon* daemon, struct config_file* cfg,
265 int cmdline_verbose, int debug_mode)
267 /* apply if they have changed */
268 verbosity = cmdline_verbose + cfg->verbosity;
269 if (debug_mode > 1) {
274 daemon_apply_cfg(daemon, cfg);
277 if (cfg->use_systemd && cfg->do_daemonize) {
278 log_warn("use-systemd and do-daemonize should not be enabled at the same time");
281 log_ident_set_or_default(cfg->log_identity);
285 /** Read existing pid from pidfile.
286 * @param file: file name of pid file.
287 * @return: the pid from the file or -1 if none.
290 readpid (const char* file)
298 if ((fd = open(file, O_RDONLY)) == -1) {
300 log_err("Could not read pidfile %s: %s",
301 file, strerror(errno));
305 if (((l = read(fd, pidbuf, sizeof(pidbuf)))) == -1) {
307 log_err("Could not read pidfile %s: %s",
308 file, strerror(errno));
315 /* Empty pidfile means no pidfile... */
320 pidbuf[sizeof(pidbuf)-1] = 0;
321 pid = (pid_t)strtol(pidbuf, &t, 10);
323 if (*t && *t != '\n') {
329 /** write pid to file.
330 * @param pidfile: file name of pid file.
331 * @param pid: pid to write to file.
334 writepid (const char* pidfile, pid_t pid)
338 if ((f = fopen(pidfile, "w")) == NULL ) {
339 log_err("cannot open pidfile %s: %s",
340 pidfile, strerror(errno));
343 if(fprintf(f, "%lu\n", (unsigned long)pid) < 0) {
344 log_err("cannot write to pidfile %s: %s",
345 pidfile, strerror(errno));
351 * check old pid file.
352 * @param pidfile: the file name of the pid file.
353 * @param inchroot: if pidfile is inchroot and we can thus expect to
354 * be able to delete it.
357 checkoldpid(char* pidfile, int inchroot)
360 if((old = readpid(pidfile)) != -1) {
361 /* see if it is still alive */
362 if(kill(old, 0) == 0 || errno == EPERM)
363 log_warn("unbound is already running as pid %u.",
366 log_warn("did not exit gracefully last time (%u)",
370 #endif /* HAVE_KILL */
372 /** detach from command line */
376 #if defined(HAVE_DAEMON) && !defined(DEPRECATED_DAEMON)
377 /* use POSIX daemon(3) function */
378 if(daemon(1, 0) != 0)
379 fatal_exit("daemon failed: %s", strerror(errno));
380 #else /* no HAVE_DAEMON */
388 fatal_exit("fork failed: %s", strerror(errno));
390 /* exit interactive session */
396 fatal_exit("setsid() failed: %s", strerror(errno));
398 if ((fd = open("/dev/null", O_RDWR, 0)) != -1) {
399 (void)dup2(fd, STDIN_FILENO);
400 (void)dup2(fd, STDOUT_FILENO);
401 (void)dup2(fd, STDERR_FILENO);
405 #endif /* HAVE_FORK */
406 #endif /* HAVE_DAEMON */
409 /** daemonize, drop user privileges and chroot if needed */
411 perform_setup(struct daemon* daemon, struct config_file* cfg, int debug_mode,
412 const char** cfgfile, int need_pidfile)
418 struct passwd *pwd = NULL;
420 if(cfg->username && cfg->username[0]) {
421 if((pwd = getpwnam(cfg->username)) == NULL)
422 fatal_exit("user '%s' does not exist.", cfg->username);
423 /* endpwent below, in case we need pwd for setusercontext */
427 w_config_adjust_directory(cfg);
430 /* read ssl keys while superuser and outside chroot */
432 if(!(daemon->rc = daemon_remote_create(cfg)))
433 fatal_exit("could not set up remote-control");
434 if(cfg->ssl_service_key && cfg->ssl_service_key[0]) {
435 if(!(daemon->listen_sslctx = listen_sslctx_create(
436 cfg->ssl_service_key, cfg->ssl_service_pem, NULL)))
437 fatal_exit("could not set up listen SSL_CTX");
438 if(cfg->tls_ciphers && cfg->tls_ciphers[0]) {
439 if (!SSL_CTX_set_cipher_list(daemon->listen_sslctx, cfg->tls_ciphers)) {
440 fatal_exit("failed to set tls-cipher %s", cfg->tls_ciphers);
443 #ifdef HAVE_SSL_CTX_SET_CIPHERSUITES
444 if(cfg->tls_ciphersuites && cfg->tls_ciphersuites[0]) {
445 if (!SSL_CTX_set_ciphersuites(daemon->listen_sslctx, cfg->tls_ciphersuites)) {
446 fatal_exit("failed to set tls-ciphersuites %s", cfg->tls_ciphersuites);
450 if(cfg->tls_session_ticket_keys.first &&
451 cfg->tls_session_ticket_keys.first->str[0] != 0) {
452 if(!listen_sslctx_setup_ticket_keys(daemon->listen_sslctx, cfg->tls_session_ticket_keys.first)) {
453 fatal_exit("could not set session ticket SSL_CTX");
457 if(!(daemon->connect_sslctx = connect_sslctx_create(NULL, NULL,
458 cfg->tls_cert_bundle, cfg->tls_win_cert)))
459 fatal_exit("could not set up connect SSL_CTX");
462 /* init syslog (as root) if needed, before daemonize, otherwise
463 * a fork error could not be printed since daemonize closed stderr.*/
464 if(cfg->use_syslog) {
465 log_init(cfg->logfile, cfg->use_syslog, cfg->chrootdir);
467 /* if using a logfile, we cannot open it because the logfile would
468 * be created with the wrong permissions, we cannot chown it because
469 * we cannot chown system logfiles, so we do not open at all.
470 * So, using a logfile, the user does not see errors unless -d is
471 * given to unbound on the commandline. */
474 /* true if pidfile is inside chrootdir, or nochroot */
475 pidinchroot = need_pidfile && (!(cfg->chrootdir && cfg->chrootdir[0]) ||
476 (cfg->chrootdir && cfg->chrootdir[0] &&
477 strncmp(cfg->pidfile, cfg->chrootdir,
478 strlen(cfg->chrootdir))==0));
480 /* check old pid file before forking */
481 if(cfg->pidfile && cfg->pidfile[0] && need_pidfile) {
482 /* calculate position of pidfile */
483 if(cfg->pidfile[0] == '/')
484 daemon->pidfile = strdup(cfg->pidfile);
485 else daemon->pidfile = fname_after_chroot(cfg->pidfile,
488 fatal_exit("pidfile alloc: out of memory");
489 checkoldpid(daemon->pidfile, pidinchroot);
493 /* daemonize because pid is needed by the writepid func */
494 if(!debug_mode && cfg->do_daemonize) {
498 /* write new pidfile (while still root, so can be outside chroot) */
500 if(cfg->pidfile && cfg->pidfile[0] && need_pidfile) {
501 writepid(daemon->pidfile, getpid());
502 if(cfg->username && cfg->username[0] && cfg_uid != (uid_t)-1 &&
505 if(chown(daemon->pidfile, cfg_uid, cfg_gid) == -1) {
506 verbose(VERB_QUERY, "cannot chown %u.%u %s: %s",
507 (unsigned)cfg_uid, (unsigned)cfg_gid,
508 daemon->pidfile, strerror(errno));
510 # endif /* HAVE_CHOWN */
516 #endif /* HAVE_KILL */
518 /* Set user context */
520 if(cfg->username && cfg->username[0] && cfg_uid != (uid_t)-1) {
521 #ifdef HAVE_SETUSERCONTEXT
522 /* setusercontext does initgroups, setuid, setgid, and
523 * also resource limits from login config, but we
524 * still call setresuid, setresgid to be sure to set all uid*/
525 if(setusercontext(NULL, pwd, cfg_uid, (unsigned)
526 LOGIN_SETALL & ~LOGIN_SETUSER & ~LOGIN_SETGROUP) != 0)
527 log_warn("unable to setusercontext %s: %s",
528 cfg->username, strerror(errno));
529 #endif /* HAVE_SETUSERCONTEXT */
531 #endif /* HAVE_GETPWNAM */
533 /* box into the chroot */
535 if(cfg->chrootdir && cfg->chrootdir[0]) {
536 if(chdir(cfg->chrootdir)) {
537 fatal_exit("unable to chdir to chroot %s: %s",
538 cfg->chrootdir, strerror(errno));
540 verbose(VERB_QUERY, "chdir to %s", cfg->chrootdir);
541 if(chroot(cfg->chrootdir))
542 fatal_exit("unable to chroot to %s: %s",
543 cfg->chrootdir, strerror(errno));
545 fatal_exit("unable to chdir to / in chroot %s: %s",
546 cfg->chrootdir, strerror(errno));
547 verbose(VERB_QUERY, "chroot to %s", cfg->chrootdir);
548 if(strncmp(*cfgfile, cfg->chrootdir,
549 strlen(cfg->chrootdir)) == 0)
550 (*cfgfile) += strlen(cfg->chrootdir);
552 /* adjust stored pidfile for chroot */
553 if(daemon->pidfile && daemon->pidfile[0] &&
554 strncmp(daemon->pidfile, cfg->chrootdir,
555 strlen(cfg->chrootdir))==0) {
556 char* old = daemon->pidfile;
557 daemon->pidfile = strdup(old+strlen(cfg->chrootdir));
560 log_err("out of memory in pidfile adjust");
562 daemon->chroot = strdup(cfg->chrootdir);
564 log_err("out of memory in daemon chroot dir storage");
569 /* change to working directory inside chroot */
570 if(cfg->directory && cfg->directory[0]) {
571 char* dir = cfg->directory;
572 if(cfg->chrootdir && cfg->chrootdir[0] &&
573 strncmp(dir, cfg->chrootdir,
574 strlen(cfg->chrootdir)) == 0)
575 dir += strlen(cfg->chrootdir);
578 fatal_exit("Could not chdir to %s: %s",
579 dir, strerror(errno));
581 verbose(VERB_QUERY, "chdir to %s", dir);
585 /* drop permissions after chroot, getpwnam, pidfile, syslog done*/
587 if(cfg->username && cfg->username[0] && cfg_uid != (uid_t)-1) {
588 # ifdef HAVE_INITGROUPS
589 if(initgroups(cfg->username, cfg_gid) != 0)
590 log_warn("unable to initgroups %s: %s",
591 cfg->username, strerror(errno));
592 # endif /* HAVE_INITGROUPS */
593 # ifdef HAVE_ENDPWENT
597 #ifdef HAVE_SETRESGID
598 if(setresgid(cfg_gid,cfg_gid,cfg_gid) != 0)
599 #elif defined(HAVE_SETREGID) && !defined(DARWIN_BROKEN_SETREUID)
600 if(setregid(cfg_gid,cfg_gid) != 0)
601 #else /* use setgid */
602 if(setgid(cfg_gid) != 0)
603 #endif /* HAVE_SETRESGID */
604 fatal_exit("unable to set group id of %s: %s",
605 cfg->username, strerror(errno));
606 #ifdef HAVE_SETRESUID
607 if(setresuid(cfg_uid,cfg_uid,cfg_uid) != 0)
608 #elif defined(HAVE_SETREUID) && !defined(DARWIN_BROKEN_SETREUID)
609 if(setreuid(cfg_uid,cfg_uid) != 0)
610 #else /* use setuid */
611 if(setuid(cfg_uid) != 0)
612 #endif /* HAVE_SETRESUID */
613 fatal_exit("unable to set user id of %s: %s",
614 cfg->username, strerror(errno));
615 verbose(VERB_QUERY, "drop user privileges, run as %s",
618 #endif /* HAVE_GETPWNAM */
619 /* file logging inited after chroot,chdir,setuid is done so that
620 * it would succeed on SIGHUP as well */
622 log_init(cfg->logfile, cfg->use_syslog, cfg->chrootdir);
627 * @param cfgfile: the config file name.
628 * @param cmdline_verbose: verbosity resulting from commandline -v.
629 * These increase verbosity as specified in the config file.
630 * @param debug_mode: if set, do not daemonize.
631 * @param need_pidfile: if false, no pidfile is checked or created.
634 run_daemon(const char* cfgfile, int cmdline_verbose, int debug_mode, int need_pidfile)
636 struct config_file* cfg = NULL;
637 struct daemon* daemon = NULL;
640 if(!(daemon = daemon_init()))
641 fatal_exit("alloc failure");
642 while(!daemon->need_to_exit) {
644 verbose(VERB_OPS, "Restart of %s.", PACKAGE_STRING);
645 else verbose(VERB_OPS, "Start of %s.", PACKAGE_STRING);
648 if(!(cfg = config_create()))
649 fatal_exit("Could not alloc config defaults");
650 if(!config_read(cfg, cfgfile, daemon->chroot)) {
652 fatal_exit("Could not read config file: %s."
653 " Maybe try unbound -dd, it stays on "
654 "the commandline to see more errors, "
655 "or unbound-checkconf", cfgfile);
656 log_warn("Continuing with default config settings");
658 apply_settings(daemon, cfg, cmdline_verbose, debug_mode);
660 config_lookup_uid(cfg);
663 if(!daemon_open_shared_ports(daemon))
664 fatal_exit("could not open ports");
666 perform_setup(daemon, cfg, debug_mode, &cfgfile, need_pidfile);
669 /* reopen log after HUP to facilitate log rotation */
671 log_init(cfg->logfile, 0, cfg->chrootdir);
676 /* clean up for restart */
677 verbose(VERB_ALGO, "cleanup.");
678 daemon_cleanup(daemon);
681 verbose(VERB_ALGO, "Exit cleanup.");
682 /* this unlink may not work if the pidfile is located outside
683 * of the chroot/workdir or we no longer have permissions */
684 if(daemon->pidfile) {
686 /* truncate pidfile */
687 fd = open(daemon->pidfile, O_WRONLY | O_TRUNC, 0644);
691 unlink(daemon->pidfile);
693 daemon_delete(daemon);
696 /** getopt global, in case header files fail to declare it. */
698 /** getopt global, in case header files fail to declare it. */
702 * main program. Set options given commandline arguments.
703 * @param argc: number of commandline arguments.
704 * @param argv: array of commandline arguments.
705 * @return: exit status of the program.
708 main(int argc, char* argv[])
711 const char* cfgfile = CONFIGFILE;
712 const char* winopt = NULL;
713 const char* log_ident_default;
714 int cmdline_verbose = 0;
716 int need_pidfile = 1;
722 log_init(NULL, 0, NULL);
723 log_ident_default = strrchr(argv[0],'/')?strrchr(argv[0],'/')+1:argv[0];
724 log_ident_set_default(log_ident_default);
725 log_ident_set(log_ident_default);
726 /* parse the options */
727 while( (c=getopt(argc, argv, "c:dhpvw:V")) != -1) {
749 print_build_options();
759 /* argv += optind; not using further arguments */
763 wsvc_command_option(winopt, cfgfile, cmdline_verbose,
766 fatal_exit("option not supported");
775 run_daemon(cfgfile, cmdline_verbose, debug_mode, need_pidfile);
776 log_init(NULL, 0, NULL); /* close logfile */
777 #ifndef unbound_testbound
779 lock_basic_destroy((lock_basic_type*)log_get_lock());