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 LIMITED
25 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
26 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE
27 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
28 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
29 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
30 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
31 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
32 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
33 * 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"
62 #include <openssl/crypto.h>
70 #ifdef HAVE_SYS_RESOURCE_H
71 #include <sys/resource.h>
73 #ifdef HAVE_LOGIN_CAP_H
74 #include <login_cap.h>
79 # include "util/winsock_event.h"
81 # include "util/mini_event.h"
88 # include "winrc/win_svc.h"
97 /** global debug value to keep track of heap memory allocation */
98 void* unbound_start_brk = 0;
101 #if !defined(HAVE_EVENT_BASE_GET_METHOD) && (defined(HAVE_EV_LOOP) || defined(HAVE_EV_DEFAULT_LOOP))
102 static const char* ev_backend2str(int b)
105 case EVBACKEND_SELECT: return "select";
106 case EVBACKEND_POLL: return "poll";
107 case EVBACKEND_EPOLL: return "epoll";
108 case EVBACKEND_KQUEUE: return "kqueue";
109 case EVBACKEND_DEVPOLL: return "devpoll";
110 case EVBACKEND_PORT: return "evport";
116 /** get the event system in use */
117 static void get_event_sys(const char** n, const char** s, const char** m)
122 *m = "WSAWaitForMultipleEvents";
123 #elif defined(USE_MINI_EVENT)
128 struct event_base* b;
129 *s = event_get_version();
130 # ifdef HAVE_EVENT_BASE_GET_METHOD
132 b = event_base_new();
133 *m = event_base_get_method(b);
134 # elif defined(HAVE_EV_LOOP) || defined(HAVE_EV_DEFAULT_LOOP)
136 b = (struct event_base*)ev_default_loop(EVFLAG_AUTO);
137 *m = ev_backend2str(ev_backend((struct ev_loop*)b));
140 *m = "not obtainable";
143 # ifdef HAVE_EVENT_BASE_FREE
153 const char *evnm="event", *evsys="", *evmethod="";
154 printf("usage: unbound [options]\n");
155 printf(" start unbound daemon DNS resolver.\n");
156 printf("-h this help\n");
157 printf("-c file config file to read instead of %s\n", CONFIGFILE);
158 printf(" file format is described in unbound.conf(5).\n");
159 printf("-d do not fork into the background.\n");
160 printf("-v verbose (more times to increase verbosity)\n");
162 printf("-w opt windows option: \n");
163 printf(" install, remove - manage the services entry\n");
164 printf(" service - used to start from services control panel\n");
166 printf("Version %s\n", PACKAGE_VERSION);
167 get_event_sys(&evnm, &evsys, &evmethod);
168 printf("linked libs: %s %s (it uses %s), ldns %s, %s\n",
169 evnm, evsys, evmethod, ldns_version(),
171 SSLeay_version(SSLEAY_VERSION)
172 #elif defined(HAVE_NSS)
176 printf("linked modules:");
177 for(m = module_list_avail(); *m; m++)
180 printf("BSD licensed, see LICENSE in source package for details.\n");
181 printf("Report bugs to %s\n", PACKAGE_BUGREPORT);
184 #ifndef unbound_testbound
185 int replay_var_compare(const void* ATTR_UNUSED(a), const void* ATTR_UNUSED(b))
192 /** check file descriptor count */
194 checkrlimits(struct config_file* cfg)
196 #ifdef HAVE_GETRLIMIT
197 /* list has number of ports to listen to, ifs number addresses */
198 int list = ((cfg->do_udp?1:0) + (cfg->do_tcp?1 +
199 (int)cfg->incoming_num_tcp:0));
200 size_t listen_ifs = (size_t)(cfg->num_ifs==0?
201 ((cfg->do_ip4 && !cfg->if_automatic?1:0) +
202 (cfg->do_ip6?1:0)):cfg->num_ifs);
203 size_t listen_num = list*listen_ifs;
204 size_t outudpnum = (size_t)cfg->outgoing_num_ports;
205 size_t outtcpnum = cfg->outgoing_num_tcp;
206 size_t misc = 4; /* logfile, pidfile, stdout... */
207 size_t perthread_noudp = listen_num + outtcpnum +
208 2/*cmdpipe*/ + 2/*libevent*/ + misc;
209 size_t perthread = perthread_noudp + outudpnum;
211 #if !defined(HAVE_PTHREAD) && !defined(HAVE_SOLARIS_THREADS)
212 int numthread = 1; /* it forks */
214 int numthread = (cfg->num_threads?cfg->num_threads:1);
216 size_t total = numthread * perthread + misc;
221 strncmp(event_get_version(), "mini-event", 10) == 0) {
222 log_warn("too many file descriptors requested. The builtin"
223 "mini-event cannot handle more than 1024. Config "
224 "for less fds or compile with libevent");
225 if(numthread*perthread_noudp+15 > 1024)
226 fatal_exit("too much tcp. not enough fds.");
227 cfg->outgoing_num_ports = (int)((1024
228 - numthread*perthread_noudp
229 - 10 /* safety margin */) /numthread);
230 log_warn("continuing with less udp ports: %u",
231 cfg->outgoing_num_ports);
235 strncmp(event_get_version(), "winsock-event", 13) == 0) {
236 log_err("too many file descriptors requested. The winsock"
237 " event handler cannot handle more than 64 per "
238 " thread. Config for less fds");
239 if(perthread_noudp+2 > 64)
240 fatal_exit("too much tcp. not enough fds.");
241 cfg->outgoing_num_ports = (int)((64
243 - 2/* safety margin */));
244 log_warn("continuing with less udp ports: %u",
245 cfg->outgoing_num_ports);
246 total = numthread*(perthread_noudp+
247 (size_t)cfg->outgoing_num_ports)+misc;
249 if(getrlimit(RLIMIT_NOFILE, &rlim) < 0) {
250 log_warn("getrlimit: %s", strerror(errno));
253 if(rlim.rlim_cur == (rlim_t)RLIM_INFINITY)
255 if((size_t)rlim.rlim_cur < total) {
256 avail = (size_t)rlim.rlim_cur;
257 rlim.rlim_cur = (rlim_t)(total + 10);
258 rlim.rlim_max = (rlim_t)(total + 10);
259 #ifdef HAVE_SETRLIMIT
260 if(setrlimit(RLIMIT_NOFILE, &rlim) < 0) {
261 log_warn("setrlimit: %s", strerror(errno));
265 log_warn("cannot increase max open fds from %u to %u",
266 (unsigned)avail, (unsigned)total+10);
267 /* check that calculation below does not underflow,
268 * with 15 as margin */
269 if(numthread*perthread_noudp+15 > avail)
270 fatal_exit("too much tcp. not enough fds.");
271 cfg->outgoing_num_ports = (int)((avail
272 - numthread*perthread_noudp
273 - 10 /* safety margin */) /numthread);
274 log_warn("continuing with less udp ports: %u",
275 cfg->outgoing_num_ports);
276 log_warn("increase ulimit or decrease threads, "
277 "ports in config to remove this warning");
280 log_warn("increased limit(open files) from %u to %u",
281 (unsigned)avail, (unsigned)total+10);
285 #endif /* HAVE_GETRLIMIT */
288 /** set verbosity, check rlimits, cache settings */
290 apply_settings(struct daemon* daemon, struct config_file* cfg,
293 /* apply if they have changed */
294 verbosity = cmdline_verbose + cfg->verbosity;
295 daemon_apply_cfg(daemon, cfg);
300 /** Read existing pid from pidfile.
301 * @param file: file name of pid file.
302 * @return: the pid from the file or -1 if none.
305 readpid (const char* file)
313 if ((fd = open(file, O_RDONLY)) == -1) {
315 log_err("Could not read pidfile %s: %s",
316 file, strerror(errno));
320 if (((l = read(fd, pidbuf, sizeof(pidbuf)))) == -1) {
322 log_err("Could not read pidfile %s: %s",
323 file, strerror(errno));
330 /* Empty pidfile means no pidfile... */
335 pidbuf[sizeof(pidbuf)-1] = 0;
336 pid = (pid_t)strtol(pidbuf, &t, 10);
338 if (*t && *t != '\n') {
344 /** write pid to file.
345 * @param pidfile: file name of pid file.
346 * @param pid: pid to write to file.
349 writepid (const char* pidfile, pid_t pid)
353 if ((f = fopen(pidfile, "w")) == NULL ) {
354 log_err("cannot open pidfile %s: %s",
355 pidfile, strerror(errno));
358 if(fprintf(f, "%lu\n", (unsigned long)pid) < 0) {
359 log_err("cannot write to pidfile %s: %s",
360 pidfile, strerror(errno));
366 * check old pid file.
367 * @param pidfile: the file name of the pid file.
368 * @param inchroot: if pidfile is inchroot and we can thus expect to
369 * be able to delete it.
372 checkoldpid(char* pidfile, int inchroot)
375 if((old = readpid(pidfile)) != -1) {
376 /* see if it is still alive */
377 if(kill(old, 0) == 0 || errno == EPERM)
378 log_warn("unbound is already running as pid %u.",
381 log_warn("did not exit gracefully last time (%u)",
385 #endif /* HAVE_KILL */
387 /** detach from command line */
391 #if defined(HAVE_DAEMON) && !defined(DEPRECATED_DAEMON)
392 /* use POSIX daemon(3) function */
393 if(daemon(1, 0) != 0)
394 fatal_exit("daemon failed: %s", strerror(errno));
395 #else /* no HAVE_DAEMON */
403 fatal_exit("fork failed: %s", strerror(errno));
405 /* exit interactive session */
411 fatal_exit("setsid() failed: %s", strerror(errno));
413 if ((fd = open("/dev/null", O_RDWR, 0)) != -1) {
414 (void)dup2(fd, STDIN_FILENO);
415 (void)dup2(fd, STDOUT_FILENO);
416 (void)dup2(fd, STDERR_FILENO);
420 #endif /* HAVE_FORK */
421 #endif /* HAVE_DAEMON */
424 /** daemonize, drop user priviliges and chroot if needed */
426 perform_setup(struct daemon* daemon, struct config_file* cfg, int debug_mode,
427 const char** cfgfile)
430 struct passwd *pwd = NULL;
433 /* initialize, but not to 0 (root) */
434 memset(&uid, 112, sizeof(uid));
435 memset(&gid, 112, sizeof(gid));
438 if(cfg->username && cfg->username[0]) {
439 if((pwd = getpwnam(cfg->username)) == NULL)
440 fatal_exit("user '%s' does not exist.", cfg->username);
443 /* endpwent below, in case we need pwd for setusercontext */
447 /* init syslog (as root) if needed, before daemonize, otherwise
448 * a fork error could not be printed since daemonize closed stderr.*/
449 if(cfg->use_syslog) {
450 log_init(cfg->logfile, cfg->use_syslog, cfg->chrootdir);
452 /* if using a logfile, we cannot open it because the logfile would
453 * be created with the wrong permissions, we cannot chown it because
454 * we cannot chown system logfiles, so we do not open at all.
455 * So, using a logfile, the user does not see errors unless -d is
456 * given to unbound on the commandline. */
458 /* read ssl keys while superuser and outside chroot */
460 if(!(daemon->rc = daemon_remote_create(cfg)))
461 fatal_exit("could not set up remote-control");
462 if(cfg->ssl_service_key && cfg->ssl_service_key[0]) {
463 if(!(daemon->listen_sslctx = listen_sslctx_create(
464 cfg->ssl_service_key, cfg->ssl_service_pem, NULL)))
465 fatal_exit("could not set up listen SSL_CTX");
467 if(!(daemon->connect_sslctx = connect_sslctx_create(NULL, NULL, NULL)))
468 fatal_exit("could not set up connect SSL_CTX");
472 /* check old pid file before forking */
473 if(cfg->pidfile && cfg->pidfile[0]) {
474 /* calculate position of pidfile */
475 if(cfg->pidfile[0] == '/')
476 daemon->pidfile = strdup(cfg->pidfile);
477 else daemon->pidfile = fname_after_chroot(cfg->pidfile,
480 fatal_exit("pidfile alloc: out of memory");
481 checkoldpid(daemon->pidfile,
482 /* true if pidfile is inside chrootdir, or nochroot */
483 !(cfg->chrootdir && cfg->chrootdir[0]) ||
484 (cfg->chrootdir && cfg->chrootdir[0] &&
485 strncmp(daemon->pidfile, cfg->chrootdir,
486 strlen(cfg->chrootdir))==0));
490 /* daemonize because pid is needed by the writepid func */
491 if(!debug_mode && cfg->do_daemonize) {
495 /* write new pidfile (while still root, so can be outside chroot) */
497 if(cfg->pidfile && cfg->pidfile[0]) {
498 writepid(daemon->pidfile, getpid());
499 if(!(cfg->chrootdir && cfg->chrootdir[0]) ||
500 (cfg->chrootdir && cfg->chrootdir[0] &&
501 strncmp(daemon->pidfile, cfg->chrootdir,
502 strlen(cfg->chrootdir))==0)) {
503 /* delete of pidfile could potentially work,
504 * chown to get permissions */
505 if(cfg->username && cfg->username[0]) {
506 if(chown(daemon->pidfile, uid, gid) == -1) {
507 log_err("cannot chown %u.%u %s: %s",
508 (unsigned)uid, (unsigned)gid,
509 daemon->pidfile, strerror(errno));
518 /* Set user context */
520 if(cfg->username && cfg->username[0]) {
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, uid,
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]) {
588 # ifdef HAVE_INITGROUPS
589 if(initgroups(cfg->username, gid) != 0)
590 log_warn("unable to initgroups %s: %s",
591 cfg->username, strerror(errno));
592 # endif /* HAVE_INITGROUPS */
595 #ifdef HAVE_SETRESGID
596 if(setresgid(gid,gid,gid) != 0)
597 #elif defined(HAVE_SETREGID) && !defined(DARWIN_BROKEN_SETREUID)
598 if(setregid(gid,gid) != 0)
599 #else /* use setgid */
601 #endif /* HAVE_SETRESGID */
602 fatal_exit("unable to set group id of %s: %s",
603 cfg->username, strerror(errno));
604 #ifdef HAVE_SETRESUID
605 if(setresuid(uid,uid,uid) != 0)
606 #elif defined(HAVE_SETREUID) && !defined(DARWIN_BROKEN_SETREUID)
607 if(setreuid(uid,uid) != 0)
608 #else /* use setuid */
610 #endif /* HAVE_SETRESUID */
611 fatal_exit("unable to set user id of %s: %s",
612 cfg->username, strerror(errno));
613 verbose(VERB_QUERY, "drop user privileges, run as %s",
616 #endif /* HAVE_GETPWNAM */
617 /* file logging inited after chroot,chdir,setuid is done so that
618 * it would succeed on SIGHUP as well */
620 log_init(cfg->logfile, cfg->use_syslog, cfg->chrootdir);
625 * @param cfgfile: the config file name.
626 * @param cmdline_verbose: verbosity resulting from commandline -v.
627 * These increase verbosity as specified in the config file.
628 * @param debug_mode: if set, do not daemonize.
631 run_daemon(const char* cfgfile, int cmdline_verbose, int debug_mode)
633 struct config_file* cfg = NULL;
634 struct daemon* daemon = NULL;
637 if(!(daemon = daemon_init()))
638 fatal_exit("alloc failure");
639 while(!daemon->need_to_exit) {
641 verbose(VERB_OPS, "Restart of %s.", PACKAGE_STRING);
642 else verbose(VERB_OPS, "Start of %s.", PACKAGE_STRING);
645 if(!(cfg = config_create()))
646 fatal_exit("Could not alloc config defaults");
647 if(!config_read(cfg, cfgfile, daemon->chroot)) {
649 fatal_exit("Could not read config file: %s",
651 log_warn("Continuing with default config settings");
653 apply_settings(daemon, cfg, cmdline_verbose);
656 if(!daemon_open_shared_ports(daemon))
657 fatal_exit("could not open ports");
659 perform_setup(daemon, cfg, debug_mode, &cfgfile);
662 /* reopen log after HUP to facilitate log rotation */
664 log_init(cfg->logfile, 0, cfg->chrootdir);
669 /* clean up for restart */
670 verbose(VERB_ALGO, "cleanup.");
671 daemon_cleanup(daemon);
674 verbose(VERB_ALGO, "Exit cleanup.");
675 /* this unlink may not work if the pidfile is located outside
676 * of the chroot/workdir or we no longer have permissions */
677 if(daemon->pidfile) {
679 /* truncate pidfile */
680 fd = open(daemon->pidfile, O_WRONLY | O_TRUNC, 0644);
684 unlink(daemon->pidfile);
686 daemon_delete(daemon);
689 /** getopt global, in case header files fail to declare it. */
691 /** getopt global, in case header files fail to declare it. */
695 * main program. Set options given commandline arguments.
696 * @param argc: number of commandline arguments.
697 * @param argv: array of commandline arguments.
698 * @return: exit status of the program.
701 main(int argc, char* argv[])
704 const char* cfgfile = CONFIGFILE;
705 const char* winopt = NULL;
706 int cmdline_verbose = 0;
713 /* take debug snapshot of heap */
714 unbound_start_brk = sbrk(0);
717 log_init(NULL, 0, NULL);
718 /* parse the options */
719 while( (c=getopt(argc, argv, "c:dhvw:")) != -1) {
749 wsvc_command_option(winopt, cfgfile, cmdline_verbose,
752 fatal_exit("option not supported");
761 run_daemon(cfgfile, cmdline_verbose, debug_mode);
762 log_init(NULL, 0, NULL); /* close logfile */