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>
72 /* splint chokes on this system header file */
73 #ifdef HAVE_SYS_RESOURCE_H
74 #include <sys/resource.h>
76 #endif /* S_SPLINT_S */
77 #ifdef HAVE_LOGIN_CAP_H
78 #include <login_cap.h>
82 # include "winrc/win_svc.h"
91 static void usage(void)
94 const char *evnm="event", *evsys="", *evmethod="";
97 struct ub_event_base* base;
98 printf("usage: unbound [options]\n");
99 printf(" start unbound daemon DNS resolver.\n");
100 printf("-h this help\n");
101 printf("-c file config file to read instead of %s\n", CONFIGFILE);
102 printf(" file format is described in unbound.conf(5).\n");
103 printf("-d do not fork into the background.\n");
104 printf("-v verbose (more times to increase verbosity)\n");
106 printf("-w opt windows option: \n");
107 printf(" install, remove - manage the services entry\n");
108 printf(" service - used to start from services control panel\n");
110 printf("Version %s\n", PACKAGE_VERSION);
111 base = ub_default_event_base(0,&t,&now);
112 ub_get_event_sys(base, &evnm, &evsys, &evmethod);
113 printf("linked libs: %s %s (it uses %s), %s\n",
114 evnm, evsys, evmethod,
116 # ifdef SSLEAY_VERSION
117 SSLeay_version(SSLEAY_VERSION)
119 OpenSSL_version(OPENSSL_VERSION)
121 #elif defined(HAVE_NSS)
123 #elif defined(HAVE_NETTLE)
127 printf("linked modules:");
128 for(m = module_list_avail(); *m; m++)
131 printf("BSD licensed, see LICENSE in source package for details.\n");
132 printf("Report bugs to %s\n", PACKAGE_BUGREPORT);
133 ub_event_base_free(base);
136 #ifndef unbound_testbound
137 int replay_var_compare(const void* ATTR_UNUSED(a), const void* ATTR_UNUSED(b))
144 /** check file descriptor count */
146 checkrlimits(struct config_file* cfg)
149 #ifdef HAVE_GETRLIMIT
150 /* list has number of ports to listen to, ifs number addresses */
151 int list = ((cfg->do_udp?1:0) + (cfg->do_tcp?1 +
152 (int)cfg->incoming_num_tcp:0));
153 size_t listen_ifs = (size_t)(cfg->num_ifs==0?
154 ((cfg->do_ip4 && !cfg->if_automatic?1:0) +
155 (cfg->do_ip6?1:0)):cfg->num_ifs);
156 size_t listen_num = list*listen_ifs;
157 size_t outudpnum = (size_t)cfg->outgoing_num_ports;
158 size_t outtcpnum = cfg->outgoing_num_tcp;
159 size_t misc = 4; /* logfile, pidfile, stdout... */
160 size_t perthread_noudp = listen_num + outtcpnum +
161 2/*cmdpipe*/ + 2/*libevent*/ + misc;
162 size_t perthread = perthread_noudp + outudpnum;
164 #if !defined(HAVE_PTHREAD) && !defined(HAVE_SOLARIS_THREADS)
165 int numthread = 1; /* it forks */
167 int numthread = (cfg->num_threads?cfg->num_threads:1);
169 size_t total = numthread * perthread + misc;
174 strncmp(ub_event_get_version(), "mini-event", 10) == 0) {
175 log_warn("too many file descriptors requested. The builtin"
176 "mini-event cannot handle more than 1024. Config "
177 "for less fds or compile with libevent");
178 if(numthread*perthread_noudp+15 > 1024)
179 fatal_exit("too much tcp. not enough fds.");
180 cfg->outgoing_num_ports = (int)((1024
181 - numthread*perthread_noudp
182 - 10 /* safety margin */) /numthread);
183 log_warn("continuing with less udp ports: %u",
184 cfg->outgoing_num_ports);
188 strncmp(ub_event_get_version(), "winsock-event", 13) == 0) {
189 log_err("too many file descriptors requested. The winsock"
190 " event handler cannot handle more than 64 per "
191 " thread. Config for less fds");
192 if(perthread_noudp+2 > 64)
193 fatal_exit("too much tcp. not enough fds.");
194 cfg->outgoing_num_ports = (int)((64
196 - 2/* safety margin */));
197 log_warn("continuing with less udp ports: %u",
198 cfg->outgoing_num_ports);
199 total = numthread*(perthread_noudp+
200 (size_t)cfg->outgoing_num_ports)+misc;
202 if(getrlimit(RLIMIT_NOFILE, &rlim) < 0) {
203 log_warn("getrlimit: %s", strerror(errno));
206 if(rlim.rlim_cur == (rlim_t)RLIM_INFINITY)
208 if((size_t)rlim.rlim_cur < total) {
209 avail = (size_t)rlim.rlim_cur;
210 rlim.rlim_cur = (rlim_t)(total + 10);
211 rlim.rlim_max = (rlim_t)(total + 10);
212 #ifdef HAVE_SETRLIMIT
213 if(setrlimit(RLIMIT_NOFILE, &rlim) < 0) {
214 log_warn("setrlimit: %s", strerror(errno));
216 log_warn("cannot increase max open fds from %u to %u",
217 (unsigned)avail, (unsigned)total+10);
218 /* check that calculation below does not underflow,
219 * with 15 as margin */
220 if(numthread*perthread_noudp+15 > avail)
221 fatal_exit("too much tcp. not enough fds.");
222 cfg->outgoing_num_ports = (int)((avail
223 - numthread*perthread_noudp
224 - 10 /* safety margin */) /numthread);
225 log_warn("continuing with less udp ports: %u",
226 cfg->outgoing_num_ports);
227 log_warn("increase ulimit or decrease threads, "
228 "ports in config to remove this warning");
230 #ifdef HAVE_SETRLIMIT
233 verbose(VERB_ALGO, "increased limit(open files) from %u to %u",
234 (unsigned)avail, (unsigned)total+10);
238 #endif /* HAVE_GETRLIMIT */
239 #endif /* S_SPLINT_S */
242 /** set default logfile identity based on value from argv[0] at startup **/
244 log_ident_set_fromdefault(struct config_file* cfg,
245 const char *log_default_identity)
247 if(cfg->log_identity == NULL || cfg->log_identity[0] == 0)
248 log_ident_set(log_default_identity);
250 log_ident_set(cfg->log_identity);
253 /** set verbosity, check rlimits, cache settings */
255 apply_settings(struct daemon* daemon, struct config_file* cfg,
256 int cmdline_verbose, int debug_mode, const char* log_default_identity)
258 /* apply if they have changed */
259 verbosity = cmdline_verbose + cfg->verbosity;
260 if (debug_mode > 1) {
265 daemon_apply_cfg(daemon, cfg);
268 if (cfg->use_systemd && cfg->do_daemonize) {
269 log_warn("use-systemd and do-daemonize should not be enabled at the same time");
272 log_ident_set_fromdefault(cfg, log_default_identity);
276 /** Read existing pid from pidfile.
277 * @param file: file name of pid file.
278 * @return: the pid from the file or -1 if none.
281 readpid (const char* file)
289 if ((fd = open(file, O_RDONLY)) == -1) {
291 log_err("Could not read pidfile %s: %s",
292 file, strerror(errno));
296 if (((l = read(fd, pidbuf, sizeof(pidbuf)))) == -1) {
298 log_err("Could not read pidfile %s: %s",
299 file, strerror(errno));
306 /* Empty pidfile means no pidfile... */
311 pidbuf[sizeof(pidbuf)-1] = 0;
312 pid = (pid_t)strtol(pidbuf, &t, 10);
314 if (*t && *t != '\n') {
320 /** write pid to file.
321 * @param pidfile: file name of pid file.
322 * @param pid: pid to write to file.
325 writepid (const char* pidfile, pid_t pid)
329 if ((f = fopen(pidfile, "w")) == NULL ) {
330 log_err("cannot open pidfile %s: %s",
331 pidfile, strerror(errno));
334 if(fprintf(f, "%lu\n", (unsigned long)pid) < 0) {
335 log_err("cannot write to pidfile %s: %s",
336 pidfile, strerror(errno));
342 * check old pid file.
343 * @param pidfile: the file name of the pid file.
344 * @param inchroot: if pidfile is inchroot and we can thus expect to
345 * be able to delete it.
348 checkoldpid(char* pidfile, int inchroot)
351 if((old = readpid(pidfile)) != -1) {
352 /* see if it is still alive */
353 if(kill(old, 0) == 0 || errno == EPERM)
354 log_warn("unbound is already running as pid %u.",
357 log_warn("did not exit gracefully last time (%u)",
361 #endif /* HAVE_KILL */
363 /** detach from command line */
367 #if defined(HAVE_DAEMON) && !defined(DEPRECATED_DAEMON)
368 /* use POSIX daemon(3) function */
369 if(daemon(1, 0) != 0)
370 fatal_exit("daemon failed: %s", strerror(errno));
371 #else /* no HAVE_DAEMON */
379 fatal_exit("fork failed: %s", strerror(errno));
381 /* exit interactive session */
387 fatal_exit("setsid() failed: %s", strerror(errno));
389 if ((fd = open("/dev/null", O_RDWR, 0)) != -1) {
390 (void)dup2(fd, STDIN_FILENO);
391 (void)dup2(fd, STDOUT_FILENO);
392 (void)dup2(fd, STDERR_FILENO);
396 #endif /* HAVE_FORK */
397 #endif /* HAVE_DAEMON */
400 /** daemonize, drop user priviliges and chroot if needed */
402 perform_setup(struct daemon* daemon, struct config_file* cfg, int debug_mode,
403 const char** cfgfile)
409 struct passwd *pwd = NULL;
411 if(cfg->username && cfg->username[0]) {
412 if((pwd = getpwnam(cfg->username)) == NULL)
413 fatal_exit("user '%s' does not exist.", cfg->username);
414 /* endpwent below, in case we need pwd for setusercontext */
418 w_config_adjust_directory(cfg);
421 /* init syslog (as root) if needed, before daemonize, otherwise
422 * a fork error could not be printed since daemonize closed stderr.*/
423 if(cfg->use_syslog) {
424 log_init(cfg->logfile, cfg->use_syslog, cfg->chrootdir);
426 /* if using a logfile, we cannot open it because the logfile would
427 * be created with the wrong permissions, we cannot chown it because
428 * we cannot chown system logfiles, so we do not open at all.
429 * So, using a logfile, the user does not see errors unless -d is
430 * given to unbound on the commandline. */
432 /* read ssl keys while superuser and outside chroot */
434 if(!(daemon->rc = daemon_remote_create(cfg)))
435 fatal_exit("could not set up remote-control");
436 if(cfg->ssl_service_key && cfg->ssl_service_key[0]) {
437 if(!(daemon->listen_sslctx = listen_sslctx_create(
438 cfg->ssl_service_key, cfg->ssl_service_pem, NULL)))
439 fatal_exit("could not set up listen SSL_CTX");
441 if(!(daemon->connect_sslctx = connect_sslctx_create(NULL, NULL, NULL)))
442 fatal_exit("could not set up connect SSL_CTX");
446 /* true if pidfile is inside chrootdir, or nochroot */
447 pidinchroot = !(cfg->chrootdir && cfg->chrootdir[0]) ||
448 (cfg->chrootdir && cfg->chrootdir[0] &&
449 strncmp(cfg->pidfile, cfg->chrootdir,
450 strlen(cfg->chrootdir))==0);
452 /* check old pid file before forking */
453 if(cfg->pidfile && cfg->pidfile[0]) {
454 /* calculate position of pidfile */
455 if(cfg->pidfile[0] == '/')
456 daemon->pidfile = strdup(cfg->pidfile);
457 else daemon->pidfile = fname_after_chroot(cfg->pidfile,
460 fatal_exit("pidfile alloc: out of memory");
461 checkoldpid(daemon->pidfile, pidinchroot);
465 /* daemonize because pid is needed by the writepid func */
466 if(!debug_mode && cfg->do_daemonize) {
470 /* write new pidfile (while still root, so can be outside chroot) */
472 if(cfg->pidfile && cfg->pidfile[0]) {
473 writepid(daemon->pidfile, getpid());
474 if(cfg->username && cfg->username[0] && cfg_uid != (uid_t)-1 &&
477 if(chown(daemon->pidfile, cfg_uid, cfg_gid) == -1) {
478 verbose(VERB_QUERY, "cannot chown %u.%u %s: %s",
479 (unsigned)cfg_uid, (unsigned)cfg_gid,
480 daemon->pidfile, strerror(errno));
482 # endif /* HAVE_CHOWN */
487 #endif /* HAVE_KILL */
489 /* Set user context */
491 if(cfg->username && cfg->username[0] && cfg_uid != (uid_t)-1) {
492 #ifdef HAVE_SETUSERCONTEXT
493 /* setusercontext does initgroups, setuid, setgid, and
494 * also resource limits from login config, but we
495 * still call setresuid, setresgid to be sure to set all uid*/
496 if(setusercontext(NULL, pwd, cfg_uid, (unsigned)
497 LOGIN_SETALL & ~LOGIN_SETUSER & ~LOGIN_SETGROUP) != 0)
498 log_warn("unable to setusercontext %s: %s",
499 cfg->username, strerror(errno));
500 #endif /* HAVE_SETUSERCONTEXT */
502 #endif /* HAVE_GETPWNAM */
504 /* box into the chroot */
506 if(cfg->chrootdir && cfg->chrootdir[0]) {
507 if(chdir(cfg->chrootdir)) {
508 fatal_exit("unable to chdir to chroot %s: %s",
509 cfg->chrootdir, strerror(errno));
511 verbose(VERB_QUERY, "chdir to %s", cfg->chrootdir);
512 if(chroot(cfg->chrootdir))
513 fatal_exit("unable to chroot to %s: %s",
514 cfg->chrootdir, strerror(errno));
516 fatal_exit("unable to chdir to / in chroot %s: %s",
517 cfg->chrootdir, strerror(errno));
518 verbose(VERB_QUERY, "chroot to %s", cfg->chrootdir);
519 if(strncmp(*cfgfile, cfg->chrootdir,
520 strlen(cfg->chrootdir)) == 0)
521 (*cfgfile) += strlen(cfg->chrootdir);
523 /* adjust stored pidfile for chroot */
524 if(daemon->pidfile && daemon->pidfile[0] &&
525 strncmp(daemon->pidfile, cfg->chrootdir,
526 strlen(cfg->chrootdir))==0) {
527 char* old = daemon->pidfile;
528 daemon->pidfile = strdup(old+strlen(cfg->chrootdir));
531 log_err("out of memory in pidfile adjust");
533 daemon->chroot = strdup(cfg->chrootdir);
535 log_err("out of memory in daemon chroot dir storage");
540 /* change to working directory inside chroot */
541 if(cfg->directory && cfg->directory[0]) {
542 char* dir = cfg->directory;
543 if(cfg->chrootdir && cfg->chrootdir[0] &&
544 strncmp(dir, cfg->chrootdir,
545 strlen(cfg->chrootdir)) == 0)
546 dir += strlen(cfg->chrootdir);
549 fatal_exit("Could not chdir to %s: %s",
550 dir, strerror(errno));
552 verbose(VERB_QUERY, "chdir to %s", dir);
556 /* drop permissions after chroot, getpwnam, pidfile, syslog done*/
558 if(cfg->username && cfg->username[0] && cfg_uid != (uid_t)-1) {
559 # ifdef HAVE_INITGROUPS
560 if(initgroups(cfg->username, cfg_gid) != 0)
561 log_warn("unable to initgroups %s: %s",
562 cfg->username, strerror(errno));
563 # endif /* HAVE_INITGROUPS */
564 # ifdef HAVE_ENDPWENT
568 #ifdef HAVE_SETRESGID
569 if(setresgid(cfg_gid,cfg_gid,cfg_gid) != 0)
570 #elif defined(HAVE_SETREGID) && !defined(DARWIN_BROKEN_SETREUID)
571 if(setregid(cfg_gid,cfg_gid) != 0)
572 #else /* use setgid */
573 if(setgid(cfg_gid) != 0)
574 #endif /* HAVE_SETRESGID */
575 fatal_exit("unable to set group id of %s: %s",
576 cfg->username, strerror(errno));
577 #ifdef HAVE_SETRESUID
578 if(setresuid(cfg_uid,cfg_uid,cfg_uid) != 0)
579 #elif defined(HAVE_SETREUID) && !defined(DARWIN_BROKEN_SETREUID)
580 if(setreuid(cfg_uid,cfg_uid) != 0)
581 #else /* use setuid */
582 if(setuid(cfg_uid) != 0)
583 #endif /* HAVE_SETRESUID */
584 fatal_exit("unable to set user id of %s: %s",
585 cfg->username, strerror(errno));
586 verbose(VERB_QUERY, "drop user privileges, run as %s",
589 #endif /* HAVE_GETPWNAM */
590 /* file logging inited after chroot,chdir,setuid is done so that
591 * it would succeed on SIGHUP as well */
593 log_init(cfg->logfile, cfg->use_syslog, cfg->chrootdir);
598 * @param cfgfile: the config file name.
599 * @param cmdline_verbose: verbosity resulting from commandline -v.
600 * These increase verbosity as specified in the config file.
601 * @param debug_mode: if set, do not daemonize.
602 * @param log_default_identity: Default identity to report in logs
605 run_daemon(const char* cfgfile, int cmdline_verbose, int debug_mode, const char* log_default_identity)
607 struct config_file* cfg = NULL;
608 struct daemon* daemon = NULL;
611 if(!(daemon = daemon_init()))
612 fatal_exit("alloc failure");
613 while(!daemon->need_to_exit) {
615 verbose(VERB_OPS, "Restart of %s.", PACKAGE_STRING);
616 else verbose(VERB_OPS, "Start of %s.", PACKAGE_STRING);
619 if(!(cfg = config_create()))
620 fatal_exit("Could not alloc config defaults");
621 if(!config_read(cfg, cfgfile, daemon->chroot)) {
623 fatal_exit("Could not read config file: %s",
625 log_warn("Continuing with default config settings");
627 apply_settings(daemon, cfg, cmdline_verbose, debug_mode, log_default_identity);
629 config_lookup_uid(cfg);
632 if(!daemon_open_shared_ports(daemon))
633 fatal_exit("could not open ports");
635 perform_setup(daemon, cfg, debug_mode, &cfgfile);
638 /* reopen log after HUP to facilitate log rotation */
640 log_init(cfg->logfile, 0, cfg->chrootdir);
645 /* clean up for restart */
646 verbose(VERB_ALGO, "cleanup.");
647 daemon_cleanup(daemon);
650 verbose(VERB_ALGO, "Exit cleanup.");
651 /* this unlink may not work if the pidfile is located outside
652 * of the chroot/workdir or we no longer have permissions */
653 if(daemon->pidfile) {
655 /* truncate pidfile */
656 fd = open(daemon->pidfile, O_WRONLY | O_TRUNC, 0644);
660 unlink(daemon->pidfile);
662 daemon_delete(daemon);
665 /** getopt global, in case header files fail to declare it. */
667 /** getopt global, in case header files fail to declare it. */
671 * main program. Set options given commandline arguments.
672 * @param argc: number of commandline arguments.
673 * @param argv: array of commandline arguments.
674 * @return: exit status of the program.
677 main(int argc, char* argv[])
680 const char* cfgfile = CONFIGFILE;
681 const char* winopt = NULL;
682 const char* log_ident_default;
683 int cmdline_verbose = 0;
689 log_init(NULL, 0, NULL);
690 log_ident_default = strrchr(argv[0],'/')?strrchr(argv[0],'/')+1:argv[0];
691 log_ident_set(log_ident_default);
692 /* parse the options */
693 while( (c=getopt(argc, argv, "c:dhvw:")) != -1) {
723 wsvc_command_option(winopt, cfgfile, cmdline_verbose,
726 fatal_exit("option not supported");
735 run_daemon(cfgfile, cmdline_verbose, debug_mode, log_ident_default);
736 log_init(NULL, 0, NULL); /* close logfile */