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 #ifdef HAVE_TARGETCONDITIONALS_H
92 #include <TargetConditionals.h>
95 #if defined(TARGET_OS_TV) || defined(TARGET_OS_WATCH)
99 /** print build options. */
101 print_build_options(void)
104 const char *evnm="event", *evsys="", *evmethod="";
107 struct ub_event_base* base;
108 printf("Version %s\n\n", PACKAGE_VERSION);
109 printf("Configure line: %s\n", CONFCMDLINE);
110 base = ub_default_event_base(0,&t,&now);
111 ub_get_event_sys(base, &evnm, &evsys, &evmethod);
112 printf("Linked libs: %s %s (it uses %s), %s\n",
113 evnm, evsys, evmethod,
115 # ifdef SSLEAY_VERSION
116 SSLeay_version(SSLEAY_VERSION)
118 OpenSSL_version(OPENSSL_VERSION)
120 #elif defined(HAVE_NSS)
122 #elif defined(HAVE_NETTLE)
126 printf("Linked modules:");
127 for(m = module_list_avail(); *m; m++)
131 printf("DNSCrypt feature available\n");
133 #ifdef USE_TCP_FASTOPEN
134 printf("TCP Fastopen feature available\n");
136 ub_event_base_free(base);
137 printf("\nBSD licensed, see LICENSE in source package for details.\n");
138 printf("Report bugs to %s\n", PACKAGE_BUGREPORT);
145 printf("usage: unbound [options]\n");
146 printf(" start unbound daemon DNS resolver.\n");
147 printf("-h this help.\n");
148 printf("-c file config file to read instead of %s\n", CONFIGFILE);
149 printf(" file format is described in unbound.conf(5).\n");
150 printf("-d do not fork into the background.\n");
151 printf("-p do not create a pidfile.\n");
152 printf("-v verbose (more times to increase verbosity).\n");
153 printf("-V show version number and build options.\n");
155 printf("-w opt windows option: \n");
156 printf(" install, remove - manage the services entry\n");
157 printf(" service - used to start from services control panel\n");
159 printf("\nVersion %s\n", PACKAGE_VERSION);
160 printf("BSD licensed, see LICENSE in source package for details.\n");
161 printf("Report bugs to %s\n", PACKAGE_BUGREPORT);
164 #ifndef unbound_testbound
165 int replay_var_compare(const void* ATTR_UNUSED(a), const void* ATTR_UNUSED(b))
172 /** check file descriptor count */
174 checkrlimits(struct config_file* cfg)
177 #ifdef HAVE_GETRLIMIT
178 /* list has number of ports to listen to, ifs number addresses */
179 int list = ((cfg->do_udp?1:0) + (cfg->do_tcp?1 +
180 (int)cfg->incoming_num_tcp:0));
181 size_t listen_ifs = (size_t)(cfg->num_ifs==0?
182 ((cfg->do_ip4 && !cfg->if_automatic?1:0) +
183 (cfg->do_ip6?1:0)):cfg->num_ifs);
184 size_t listen_num = list*listen_ifs;
185 size_t outudpnum = (size_t)cfg->outgoing_num_ports;
186 size_t outtcpnum = cfg->outgoing_num_tcp;
187 size_t misc = 4; /* logfile, pidfile, stdout... */
188 size_t perthread_noudp = listen_num + outtcpnum +
189 2/*cmdpipe*/ + 2/*libevent*/ + misc;
190 size_t perthread = perthread_noudp + outudpnum;
192 #if !defined(HAVE_PTHREAD) && !defined(HAVE_SOLARIS_THREADS)
193 int numthread = 1; /* it forks */
195 int numthread = (cfg->num_threads?cfg->num_threads:1);
197 size_t total = numthread * perthread + misc;
202 strncmp(ub_event_get_version(), "mini-event", 10) == 0) {
203 log_warn("too many file descriptors requested. The builtin"
204 "mini-event cannot handle more than 1024. Config "
205 "for less fds or compile with libevent");
206 if(numthread*perthread_noudp+15 > 1024)
207 fatal_exit("too much tcp. not enough fds.");
208 cfg->outgoing_num_ports = (int)((1024
209 - numthread*perthread_noudp
210 - 10 /* safety margin */) /numthread);
211 log_warn("continuing with less udp ports: %u",
212 cfg->outgoing_num_ports);
216 strncmp(ub_event_get_version(), "winsock-event", 13) == 0) {
217 log_err("too many file descriptors requested. The winsock"
218 " event handler cannot handle more than 64 per "
219 " thread. Config for less fds");
220 if(perthread_noudp+2 > 64)
221 fatal_exit("too much tcp. not enough fds.");
222 cfg->outgoing_num_ports = (int)((64
224 - 2/* safety margin */));
225 log_warn("continuing with less udp ports: %u",
226 cfg->outgoing_num_ports);
227 total = numthread*(perthread_noudp+
228 (size_t)cfg->outgoing_num_ports)+misc;
230 if(getrlimit(RLIMIT_NOFILE, &rlim) < 0) {
231 log_warn("getrlimit: %s", strerror(errno));
234 if(rlim.rlim_cur == (rlim_t)RLIM_INFINITY)
236 if((size_t)rlim.rlim_cur < total) {
237 avail = (size_t)rlim.rlim_cur;
238 rlim.rlim_cur = (rlim_t)(total + 10);
239 rlim.rlim_max = (rlim_t)(total + 10);
240 #ifdef HAVE_SETRLIMIT
241 if(setrlimit(RLIMIT_NOFILE, &rlim) < 0) {
242 log_warn("setrlimit: %s", strerror(errno));
244 log_warn("cannot increase max open fds from %u to %u",
245 (unsigned)avail, (unsigned)total+10);
246 /* check that calculation below does not underflow,
247 * with 15 as margin */
248 if(numthread*perthread_noudp+15 > avail)
249 fatal_exit("too much tcp. not enough fds.");
250 cfg->outgoing_num_ports = (int)((avail
251 - numthread*perthread_noudp
252 - 10 /* safety margin */) /numthread);
253 log_warn("continuing with less udp ports: %u",
254 cfg->outgoing_num_ports);
255 log_warn("increase ulimit or decrease threads, "
256 "ports in config to remove this warning");
258 #ifdef HAVE_SETRLIMIT
261 verbose(VERB_ALGO, "increased limit(open files) from %u to %u",
262 (unsigned)avail, (unsigned)total+10);
266 #endif /* HAVE_GETRLIMIT */
267 #endif /* S_SPLINT_S */
270 /** set verbosity, check rlimits, cache settings */
272 apply_settings(struct daemon* daemon, struct config_file* cfg,
273 int cmdline_verbose, int debug_mode)
275 /* apply if they have changed */
276 verbosity = cmdline_verbose + cfg->verbosity;
277 if (debug_mode > 1) {
282 daemon_apply_cfg(daemon, cfg);
285 if (cfg->use_systemd && cfg->do_daemonize) {
286 log_warn("use-systemd and do-daemonize should not be enabled at the same time");
289 log_ident_set_or_default(cfg->log_identity);
293 /** Read existing pid from pidfile.
294 * @param file: file name of pid file.
295 * @return: the pid from the file or -1 if none.
298 readpid (const char* file)
306 if ((fd = open(file, O_RDONLY)) == -1) {
308 log_err("Could not read pidfile %s: %s",
309 file, strerror(errno));
313 if (((l = read(fd, pidbuf, sizeof(pidbuf)))) == -1) {
315 log_err("Could not read pidfile %s: %s",
316 file, strerror(errno));
323 /* Empty pidfile means no pidfile... */
328 pidbuf[sizeof(pidbuf)-1] = 0;
329 pid = (pid_t)strtol(pidbuf, &t, 10);
331 if (*t && *t != '\n') {
337 /** write pid to file.
338 * @param pidfile: file name of pid file.
339 * @param pid: pid to write to file.
342 writepid (const char* pidfile, pid_t pid)
346 if ((f = fopen(pidfile, "w")) == NULL ) {
347 log_err("cannot open pidfile %s: %s",
348 pidfile, strerror(errno));
351 if(fprintf(f, "%lu\n", (unsigned long)pid) < 0) {
352 log_err("cannot write to pidfile %s: %s",
353 pidfile, strerror(errno));
359 * check old pid file.
360 * @param pidfile: the file name of the pid file.
361 * @param inchroot: if pidfile is inchroot and we can thus expect to
362 * be able to delete it.
365 checkoldpid(char* pidfile, int inchroot)
368 if((old = readpid(pidfile)) != -1) {
369 /* see if it is still alive */
370 if(kill(old, 0) == 0 || errno == EPERM)
371 log_warn("unbound is already running as pid %u.",
374 log_warn("did not exit gracefully last time (%u)",
378 #endif /* HAVE_KILL */
380 /** detach from command line */
384 #if defined(HAVE_DAEMON) && !defined(DEPRECATED_DAEMON)
385 /* use POSIX daemon(3) function */
386 if(daemon(1, 0) != 0)
387 fatal_exit("daemon failed: %s", strerror(errno));
388 #else /* no HAVE_DAEMON */
396 fatal_exit("fork failed: %s", strerror(errno));
398 /* exit interactive session */
404 fatal_exit("setsid() failed: %s", strerror(errno));
406 if ((fd = open("/dev/null", O_RDWR, 0)) != -1) {
407 (void)dup2(fd, STDIN_FILENO);
408 (void)dup2(fd, STDOUT_FILENO);
409 (void)dup2(fd, STDERR_FILENO);
413 #endif /* HAVE_FORK */
414 #endif /* HAVE_DAEMON */
417 /** daemonize, drop user privileges and chroot if needed */
419 perform_setup(struct daemon* daemon, struct config_file* cfg, int debug_mode,
420 const char** cfgfile, int need_pidfile)
426 struct passwd *pwd = NULL;
428 if(cfg->username && cfg->username[0]) {
429 if((pwd = getpwnam(cfg->username)) == NULL)
430 fatal_exit("user '%s' does not exist.", cfg->username);
431 /* endpwent below, in case we need pwd for setusercontext */
435 w_config_adjust_directory(cfg);
438 /* read ssl keys while superuser and outside chroot */
440 if(!(daemon->rc = daemon_remote_create(cfg)))
441 fatal_exit("could not set up remote-control");
442 if(cfg->ssl_service_key && cfg->ssl_service_key[0]) {
443 if(!(daemon->listen_sslctx = listen_sslctx_create(
444 cfg->ssl_service_key, cfg->ssl_service_pem, NULL)))
445 fatal_exit("could not set up listen SSL_CTX");
446 if(cfg->tls_ciphers && cfg->tls_ciphers[0]) {
447 if (!SSL_CTX_set_cipher_list(daemon->listen_sslctx, cfg->tls_ciphers)) {
448 fatal_exit("failed to set tls-cipher %s", cfg->tls_ciphers);
451 #ifdef HAVE_SSL_CTX_SET_CIPHERSUITES
452 if(cfg->tls_ciphersuites && cfg->tls_ciphersuites[0]) {
453 if (!SSL_CTX_set_ciphersuites(daemon->listen_sslctx, cfg->tls_ciphersuites)) {
454 fatal_exit("failed to set tls-ciphersuites %s", cfg->tls_ciphersuites);
458 if(cfg->tls_session_ticket_keys.first &&
459 cfg->tls_session_ticket_keys.first->str[0] != 0) {
460 if(!listen_sslctx_setup_ticket_keys(daemon->listen_sslctx, cfg->tls_session_ticket_keys.first)) {
461 fatal_exit("could not set session ticket SSL_CTX");
465 if(!(daemon->connect_sslctx = connect_sslctx_create(NULL, NULL,
466 cfg->tls_cert_bundle, cfg->tls_win_cert)))
467 fatal_exit("could not set up connect SSL_CTX");
470 /* init syslog (as root) if needed, before daemonize, otherwise
471 * a fork error could not be printed since daemonize closed stderr.*/
472 if(cfg->use_syslog) {
473 log_init(cfg->logfile, cfg->use_syslog, cfg->chrootdir);
475 /* if using a logfile, we cannot open it because the logfile would
476 * be created with the wrong permissions, we cannot chown it because
477 * we cannot chown system logfiles, so we do not open at all.
478 * So, using a logfile, the user does not see errors unless -d is
479 * given to unbound on the commandline. */
482 /* true if pidfile is inside chrootdir, or nochroot */
483 pidinchroot = need_pidfile && (!(cfg->chrootdir && cfg->chrootdir[0]) ||
484 (cfg->chrootdir && cfg->chrootdir[0] &&
485 strncmp(cfg->pidfile, cfg->chrootdir,
486 strlen(cfg->chrootdir))==0));
488 /* check old pid file before forking */
489 if(cfg->pidfile && cfg->pidfile[0] && need_pidfile) {
490 /* calculate position of pidfile */
491 if(cfg->pidfile[0] == '/')
492 daemon->pidfile = strdup(cfg->pidfile);
493 else daemon->pidfile = fname_after_chroot(cfg->pidfile,
496 fatal_exit("pidfile alloc: out of memory");
497 checkoldpid(daemon->pidfile, pidinchroot);
501 /* daemonize because pid is needed by the writepid func */
502 if(!debug_mode && cfg->do_daemonize) {
506 /* write new pidfile (while still root, so can be outside chroot) */
508 if(cfg->pidfile && cfg->pidfile[0] && need_pidfile) {
509 writepid(daemon->pidfile, getpid());
510 if(cfg->username && cfg->username[0] && cfg_uid != (uid_t)-1 &&
513 if(chown(daemon->pidfile, cfg_uid, cfg_gid) == -1) {
514 verbose(VERB_QUERY, "cannot chown %u.%u %s: %s",
515 (unsigned)cfg_uid, (unsigned)cfg_gid,
516 daemon->pidfile, strerror(errno));
518 # endif /* HAVE_CHOWN */
524 #endif /* HAVE_KILL */
526 /* Set user context */
528 if(cfg->username && cfg->username[0] && cfg_uid != (uid_t)-1) {
529 #ifdef HAVE_SETUSERCONTEXT
530 /* setusercontext does initgroups, setuid, setgid, and
531 * also resource limits from login config, but we
532 * still call setresuid, setresgid to be sure to set all uid*/
533 if(setusercontext(NULL, pwd, cfg_uid, (unsigned)
534 LOGIN_SETALL & ~LOGIN_SETUSER & ~LOGIN_SETGROUP) != 0)
535 log_warn("unable to setusercontext %s: %s",
536 cfg->username, strerror(errno));
539 #endif /* HAVE_SETUSERCONTEXT */
541 #endif /* HAVE_GETPWNAM */
543 /* box into the chroot */
545 if(cfg->chrootdir && cfg->chrootdir[0]) {
546 if(chdir(cfg->chrootdir)) {
547 fatal_exit("unable to chdir to chroot %s: %s",
548 cfg->chrootdir, strerror(errno));
550 verbose(VERB_QUERY, "chdir to %s", cfg->chrootdir);
551 if(chroot(cfg->chrootdir))
552 fatal_exit("unable to chroot to %s: %s",
553 cfg->chrootdir, strerror(errno));
555 fatal_exit("unable to chdir to / in chroot %s: %s",
556 cfg->chrootdir, strerror(errno));
557 verbose(VERB_QUERY, "chroot to %s", cfg->chrootdir);
558 if(strncmp(*cfgfile, cfg->chrootdir,
559 strlen(cfg->chrootdir)) == 0)
560 (*cfgfile) += strlen(cfg->chrootdir);
562 /* adjust stored pidfile for chroot */
563 if(daemon->pidfile && daemon->pidfile[0] &&
564 strncmp(daemon->pidfile, cfg->chrootdir,
565 strlen(cfg->chrootdir))==0) {
566 char* old = daemon->pidfile;
567 daemon->pidfile = strdup(old+strlen(cfg->chrootdir));
570 log_err("out of memory in pidfile adjust");
572 daemon->chroot = strdup(cfg->chrootdir);
574 log_err("out of memory in daemon chroot dir storage");
579 /* change to working directory inside chroot */
580 if(cfg->directory && cfg->directory[0]) {
581 char* dir = cfg->directory;
582 if(cfg->chrootdir && cfg->chrootdir[0] &&
583 strncmp(dir, cfg->chrootdir,
584 strlen(cfg->chrootdir)) == 0)
585 dir += strlen(cfg->chrootdir);
588 fatal_exit("Could not chdir to %s: %s",
589 dir, strerror(errno));
591 verbose(VERB_QUERY, "chdir to %s", dir);
595 /* drop permissions after chroot, getpwnam, pidfile, syslog done*/
597 if(cfg->username && cfg->username[0] && cfg_uid != (uid_t)-1) {
598 # ifdef HAVE_INITGROUPS
599 if(initgroups(cfg->username, cfg_gid) != 0)
600 log_warn("unable to initgroups %s: %s",
601 cfg->username, strerror(errno));
602 # endif /* HAVE_INITGROUPS */
603 # ifdef HAVE_ENDPWENT
607 #ifdef HAVE_SETRESGID
608 if(setresgid(cfg_gid,cfg_gid,cfg_gid) != 0)
609 #elif defined(HAVE_SETREGID) && !defined(DARWIN_BROKEN_SETREUID)
610 if(setregid(cfg_gid,cfg_gid) != 0)
611 #else /* use setgid */
612 if(setgid(cfg_gid) != 0)
613 #endif /* HAVE_SETRESGID */
614 fatal_exit("unable to set group id of %s: %s",
615 cfg->username, strerror(errno));
616 #ifdef HAVE_SETRESUID
617 if(setresuid(cfg_uid,cfg_uid,cfg_uid) != 0)
618 #elif defined(HAVE_SETREUID) && !defined(DARWIN_BROKEN_SETREUID)
619 if(setreuid(cfg_uid,cfg_uid) != 0)
620 #else /* use setuid */
621 if(setuid(cfg_uid) != 0)
622 #endif /* HAVE_SETRESUID */
623 fatal_exit("unable to set user id of %s: %s",
624 cfg->username, strerror(errno));
625 verbose(VERB_QUERY, "drop user privileges, run as %s",
628 #endif /* HAVE_GETPWNAM */
629 /* file logging inited after chroot,chdir,setuid is done so that
630 * it would succeed on SIGHUP as well */
632 log_init(cfg->logfile, cfg->use_syslog, cfg->chrootdir);
637 * @param cfgfile: the config file name.
638 * @param cmdline_verbose: verbosity resulting from commandline -v.
639 * These increase verbosity as specified in the config file.
640 * @param debug_mode: if set, do not daemonize.
641 * @param need_pidfile: if false, no pidfile is checked or created.
644 run_daemon(const char* cfgfile, int cmdline_verbose, int debug_mode, int need_pidfile)
646 struct config_file* cfg = NULL;
647 struct daemon* daemon = NULL;
650 if(!(daemon = daemon_init()))
651 fatal_exit("alloc failure");
652 while(!daemon->need_to_exit) {
654 verbose(VERB_OPS, "Restart of %s.", PACKAGE_STRING);
655 else verbose(VERB_OPS, "Start of %s.", PACKAGE_STRING);
658 if(!(cfg = config_create()))
659 fatal_exit("Could not alloc config defaults");
660 if(!config_read(cfg, cfgfile, daemon->chroot)) {
662 fatal_exit("Could not read config file: %s."
663 " Maybe try unbound -dd, it stays on "
664 "the commandline to see more errors, "
665 "or unbound-checkconf", cfgfile);
666 log_warn("Continuing with default config settings");
668 apply_settings(daemon, cfg, cmdline_verbose, debug_mode);
670 config_lookup_uid(cfg);
673 if(!daemon_open_shared_ports(daemon))
674 fatal_exit("could not open ports");
676 perform_setup(daemon, cfg, debug_mode, &cfgfile, need_pidfile);
679 /* reopen log after HUP to facilitate log rotation */
681 log_init(cfg->logfile, 0, cfg->chrootdir);
686 /* clean up for restart */
687 verbose(VERB_ALGO, "cleanup.");
688 daemon_cleanup(daemon);
691 verbose(VERB_ALGO, "Exit cleanup.");
692 /* this unlink may not work if the pidfile is located outside
693 * of the chroot/workdir or we no longer have permissions */
694 if(daemon->pidfile) {
696 /* truncate pidfile */
697 fd = open(daemon->pidfile, O_WRONLY | O_TRUNC, 0644);
701 unlink(daemon->pidfile);
703 daemon_delete(daemon);
706 /** getopt global, in case header files fail to declare it. */
708 /** getopt global, in case header files fail to declare it. */
712 * main program. Set options given commandline arguments.
713 * @param argc: number of commandline arguments.
714 * @param argv: array of commandline arguments.
715 * @return: exit status of the program.
718 main(int argc, char* argv[])
721 const char* cfgfile = CONFIGFILE;
722 const char* winopt = NULL;
723 const char* log_ident_default;
724 int cmdline_verbose = 0;
726 int need_pidfile = 1;
732 log_init(NULL, 0, NULL);
733 log_ident_default = strrchr(argv[0],'/')?strrchr(argv[0],'/')+1:argv[0];
734 log_ident_set_default(log_ident_default);
735 log_ident_set(log_ident_default);
736 /* parse the options */
737 while( (c=getopt(argc, argv, "c:dhpvw:V")) != -1) {
759 print_build_options();
769 /* argv += optind; not using further arguments */
773 wsvc_command_option(winopt, cfgfile, cmdline_verbose,
776 fatal_exit("option not supported");
785 run_daemon(cfgfile, cmdline_verbose, debug_mode, need_pidfile);
786 log_init(NULL, 0, NULL); /* close logfile */
787 #ifndef unbound_testbound
789 lock_basic_destroy((lock_basic_type*)log_get_lock());