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/data/msgreply.h"
57 #include "util/module.h"
58 #include "util/net_help.h"
61 #include <openssl/crypto.h>
69 #ifdef HAVE_SYS_RESOURCE_H
70 #include <sys/resource.h>
72 #ifdef HAVE_LOGIN_CAP_H
73 #include <login_cap.h>
78 # include "util/winsock_event.h"
80 # include "util/mini_event.h"
87 # include "winrc/win_svc.h"
95 /** global debug value to keep track of heap memory allocation */
96 void* unbound_start_brk = 0;
98 #if !defined(HAVE_EVENT_BASE_GET_METHOD) && (defined(HAVE_EV_LOOP) || defined(HAVE_EV_DEFAULT_LOOP))
99 static const char* ev_backend2str(int b)
102 case EVBACKEND_SELECT: return "select";
103 case EVBACKEND_POLL: return "poll";
104 case EVBACKEND_EPOLL: return "epoll";
105 case EVBACKEND_KQUEUE: return "kqueue";
106 case EVBACKEND_DEVPOLL: return "devpoll";
107 case EVBACKEND_PORT: return "evport";
113 /** get the event system in use */
114 static void get_event_sys(const char** n, const char** s, const char** m)
119 *m = "WSAWaitForMultipleEvents";
120 #elif defined(USE_MINI_EVENT)
125 struct event_base* b;
126 *s = event_get_version();
127 # ifdef HAVE_EVENT_BASE_GET_METHOD
129 b = event_base_new();
130 *m = event_base_get_method(b);
131 # elif defined(HAVE_EV_LOOP) || defined(HAVE_EV_DEFAULT_LOOP)
133 b = (struct event_base*)ev_default_loop(EVFLAG_AUTO);
134 *m = ev_backend2str(ev_backend((struct ev_loop*)b));
137 *m = "not obtainable";
140 # ifdef HAVE_EVENT_BASE_FREE
150 const char *evnm="event", *evsys="", *evmethod="";
151 printf("usage: unbound [options]\n");
152 printf(" start unbound daemon DNS resolver.\n");
153 printf("-h this help\n");
154 printf("-c file config file to read instead of %s\n", CONFIGFILE);
155 printf(" file format is described in unbound.conf(5).\n");
156 printf("-d do not fork into the background.\n");
157 printf("-v verbose (more times to increase verbosity)\n");
159 printf("-w opt windows option: \n");
160 printf(" install, remove - manage the services entry\n");
161 printf(" service - used to start from services control panel\n");
163 printf("Version %s\n", PACKAGE_VERSION);
164 get_event_sys(&evnm, &evsys, &evmethod);
165 printf("linked libs: %s %s (it uses %s), ldns %s, %s\n",
166 evnm, evsys, evmethod, ldns_version(),
168 SSLeay_version(SSLEAY_VERSION)
169 #elif defined(HAVE_NSS)
173 printf("linked modules:");
174 for(m = module_list_avail(); *m; m++)
177 printf("configured for %s on %s with options:%s\n",
178 CONFIGURE_TARGET, CONFIGURE_DATE, CONFIGURE_BUILD_WITH);
179 printf("BSD licensed, see LICENSE in source package for details.\n");
180 printf("Report bugs to %s\n", PACKAGE_BUGREPORT);
183 #ifndef unbound_testbound
184 int replay_var_compare(const void* ATTR_UNUSED(a), const void* ATTR_UNUSED(b))
191 /** check file descriptor count */
193 checkrlimits(struct config_file* cfg)
195 #ifdef HAVE_GETRLIMIT
196 /* list has number of ports to listen to, ifs number addresses */
197 int list = ((cfg->do_udp?1:0) + (cfg->do_tcp?1 +
198 (int)cfg->incoming_num_tcp:0));
199 size_t listen_ifs = (size_t)(cfg->num_ifs==0?
200 ((cfg->do_ip4 && !cfg->if_automatic?1:0) +
201 (cfg->do_ip6?1:0)):cfg->num_ifs);
202 size_t listen_num = list*listen_ifs;
203 size_t outudpnum = (size_t)cfg->outgoing_num_ports;
204 size_t outtcpnum = cfg->outgoing_num_tcp;
205 size_t misc = 4; /* logfile, pidfile, stdout... */
206 size_t perthread_noudp = listen_num + outtcpnum +
207 2/*cmdpipe*/ + 2/*libevent*/ + misc;
208 size_t perthread = perthread_noudp + outudpnum;
210 #if !defined(HAVE_PTHREAD) && !defined(HAVE_SOLARIS_THREADS)
211 int numthread = 1; /* it forks */
213 int numthread = (cfg->num_threads?cfg->num_threads:1);
215 size_t total = numthread * perthread + misc;
220 strncmp(event_get_version(), "mini-event", 10) == 0) {
221 log_warn("too many file descriptors requested. The builtin"
222 "mini-event cannot handle more than 1024. Config "
223 "for less fds or compile with libevent");
224 if(numthread*perthread_noudp+15 > 1024)
225 fatal_exit("too much tcp. not enough fds.");
226 cfg->outgoing_num_ports = (int)((1024
227 - numthread*perthread_noudp
228 - 10 /* safety margin */) /numthread);
229 log_warn("continuing with less udp ports: %u",
230 cfg->outgoing_num_ports);
234 strncmp(event_get_version(), "winsock-event", 13) == 0) {
235 log_err("too many file descriptors requested. The winsock"
236 " event handler cannot handle more than 64 per "
237 " thread. Config for less fds");
238 if(perthread_noudp+2 > 64)
239 fatal_exit("too much tcp. not enough fds.");
240 cfg->outgoing_num_ports = (int)((64
242 - 2/* safety margin */));
243 log_warn("continuing with less udp ports: %u",
244 cfg->outgoing_num_ports);
245 total = numthread*(perthread_noudp+
246 (size_t)cfg->outgoing_num_ports)+misc;
248 if(getrlimit(RLIMIT_NOFILE, &rlim) < 0) {
249 log_warn("getrlimit: %s", strerror(errno));
252 if(rlim.rlim_cur == (rlim_t)RLIM_INFINITY)
254 if((size_t)rlim.rlim_cur < total) {
255 avail = (size_t)rlim.rlim_cur;
256 rlim.rlim_cur = (rlim_t)(total + 10);
257 rlim.rlim_max = (rlim_t)(total + 10);
258 #ifdef HAVE_SETRLIMIT
259 if(setrlimit(RLIMIT_NOFILE, &rlim) < 0) {
260 log_warn("setrlimit: %s", strerror(errno));
264 log_warn("cannot increase max open fds from %u to %u",
265 (unsigned)avail, (unsigned)total+10);
266 /* check that calculation below does not underflow,
267 * with 15 as margin */
268 if(numthread*perthread_noudp+15 > avail)
269 fatal_exit("too much tcp. not enough fds.");
270 cfg->outgoing_num_ports = (int)((avail
271 - numthread*perthread_noudp
272 - 10 /* safety margin */) /numthread);
273 log_warn("continuing with less udp ports: %u",
274 cfg->outgoing_num_ports);
275 log_warn("increase ulimit or decrease threads, "
276 "ports in config to remove this warning");
279 log_warn("increased limit(open files) from %u to %u",
280 (unsigned)avail, (unsigned)total+10);
284 #endif /* HAVE_GETRLIMIT */
287 /** set verbosity, check rlimits, cache settings */
289 apply_settings(struct daemon* daemon, struct config_file* cfg,
292 /* apply if they have changed */
293 verbosity = cmdline_verbose + cfg->verbosity;
294 daemon_apply_cfg(daemon, cfg);
299 /** Read existing pid from pidfile.
300 * @param file: file name of pid file.
301 * @return: the pid from the file or -1 if none.
304 readpid (const char* file)
312 if ((fd = open(file, O_RDONLY)) == -1) {
314 log_err("Could not read pidfile %s: %s",
315 file, strerror(errno));
319 if (((l = read(fd, pidbuf, sizeof(pidbuf)))) == -1) {
321 log_err("Could not read pidfile %s: %s",
322 file, strerror(errno));
329 /* Empty pidfile means no pidfile... */
334 pidbuf[sizeof(pidbuf)-1] = 0;
335 pid = (pid_t)strtol(pidbuf, &t, 10);
337 if (*t && *t != '\n') {
343 /** write pid to file.
344 * @param pidfile: file name of pid file.
345 * @param pid: pid to write to file.
348 writepid (const char* pidfile, pid_t pid)
352 if ((f = fopen(pidfile, "w")) == NULL ) {
353 log_err("cannot open pidfile %s: %s",
354 pidfile, strerror(errno));
357 if(fprintf(f, "%lu\n", (unsigned long)pid) < 0) {
358 log_err("cannot write to pidfile %s: %s",
359 pidfile, strerror(errno));
365 * check old pid file.
366 * @param pidfile: the file name of the pid file.
367 * @param inchroot: if pidfile is inchroot and we can thus expect to
368 * be able to delete it.
371 checkoldpid(char* pidfile, int inchroot)
374 if((old = readpid(pidfile)) != -1) {
375 /* see if it is still alive */
376 if(kill(old, 0) == 0 || errno == EPERM)
377 log_warn("unbound is already running as pid %u.",
380 log_warn("did not exit gracefully last time (%u)",
384 #endif /* HAVE_KILL */
386 /** detach from command line */
390 #if defined(HAVE_DAEMON) && !defined(DEPRECATED_DAEMON)
391 /* use POSIX daemon(3) function */
392 if(daemon(1, 0) != 0)
393 fatal_exit("daemon failed: %s", strerror(errno));
394 #else /* no HAVE_DAEMON */
402 fatal_exit("fork failed: %s", strerror(errno));
404 /* exit interactive session */
410 fatal_exit("setsid() failed: %s", strerror(errno));
412 if ((fd = open("/dev/null", O_RDWR, 0)) != -1) {
413 (void)dup2(fd, STDIN_FILENO);
414 (void)dup2(fd, STDOUT_FILENO);
415 (void)dup2(fd, STDERR_FILENO);
419 #endif /* HAVE_FORK */
420 #endif /* HAVE_DAEMON */
423 /** daemonize, drop user priviliges and chroot if needed */
425 perform_setup(struct daemon* daemon, struct config_file* cfg, int debug_mode,
426 const char** cfgfile)
429 struct passwd *pwd = NULL;
432 /* initialize, but not to 0 (root) */
433 memset(&uid, 112, sizeof(uid));
434 memset(&gid, 112, sizeof(gid));
437 if(cfg->username && cfg->username[0]) {
438 if((pwd = getpwnam(cfg->username)) == NULL)
439 fatal_exit("user '%s' does not exist.", cfg->username);
442 /* endpwent below, in case we need pwd for setusercontext */
446 /* init syslog (as root) if needed, before daemonize, otherwise
447 * a fork error could not be printed since daemonize closed stderr.*/
448 if(cfg->use_syslog) {
449 log_init(cfg->logfile, cfg->use_syslog, cfg->chrootdir);
451 /* if using a logfile, we cannot open it because the logfile would
452 * be created with the wrong permissions, we cannot chown it because
453 * we cannot chown system logfiles, so we do not open at all.
454 * So, using a logfile, the user does not see errors unless -d is
455 * given to unbound on the commandline. */
457 /* read ssl keys while superuser and outside chroot */
459 if(!(daemon->rc = daemon_remote_create(cfg)))
460 fatal_exit("could not set up remote-control");
461 if(cfg->ssl_service_key && cfg->ssl_service_key[0]) {
462 if(!(daemon->listen_sslctx = listen_sslctx_create(
463 cfg->ssl_service_key, cfg->ssl_service_pem, NULL)))
464 fatal_exit("could not set up listen SSL_CTX");
466 if(!(daemon->connect_sslctx = connect_sslctx_create(NULL, NULL, NULL)))
467 fatal_exit("could not set up connect SSL_CTX");
471 /* check old pid file before forking */
472 if(cfg->pidfile && cfg->pidfile[0]) {
473 /* calculate position of pidfile */
474 if(cfg->pidfile[0] == '/')
475 daemon->pidfile = strdup(cfg->pidfile);
476 else daemon->pidfile = fname_after_chroot(cfg->pidfile,
479 fatal_exit("pidfile alloc: out of memory");
480 checkoldpid(daemon->pidfile,
481 /* true if pidfile is inside chrootdir, or nochroot */
482 !(cfg->chrootdir && cfg->chrootdir[0]) ||
483 (cfg->chrootdir && cfg->chrootdir[0] &&
484 strncmp(daemon->pidfile, cfg->chrootdir,
485 strlen(cfg->chrootdir))==0));
489 /* daemonize because pid is needed by the writepid func */
490 if(!debug_mode && cfg->do_daemonize) {
494 /* write new pidfile (while still root, so can be outside chroot) */
496 if(cfg->pidfile && cfg->pidfile[0]) {
497 writepid(daemon->pidfile, getpid());
498 if(!(cfg->chrootdir && cfg->chrootdir[0]) ||
499 (cfg->chrootdir && cfg->chrootdir[0] &&
500 strncmp(daemon->pidfile, cfg->chrootdir,
501 strlen(cfg->chrootdir))==0)) {
502 /* delete of pidfile could potentially work,
503 * chown to get permissions */
504 if(cfg->username && cfg->username[0]) {
505 if(chown(daemon->pidfile, uid, gid) == -1) {
506 log_err("cannot chown %u.%u %s: %s",
507 (unsigned)uid, (unsigned)gid,
508 daemon->pidfile, strerror(errno));
517 /* Set user context */
519 if(cfg->username && cfg->username[0]) {
520 #ifdef HAVE_SETUSERCONTEXT
521 /* setusercontext does initgroups, setuid, setgid, and
522 * also resource limits from login config, but we
523 * still call setresuid, setresgid to be sure to set all uid*/
524 if(setusercontext(NULL, pwd, uid,
525 LOGIN_SETALL & ~LOGIN_SETUSER & ~LOGIN_SETGROUP) != 0)
526 log_warn("unable to setusercontext %s: %s",
527 cfg->username, strerror(errno));
528 #endif /* HAVE_SETUSERCONTEXT */
530 #endif /* HAVE_GETPWNAM */
532 /* box into the chroot */
534 if(cfg->chrootdir && cfg->chrootdir[0]) {
535 if(chdir(cfg->chrootdir)) {
536 fatal_exit("unable to chdir to chroot %s: %s",
537 cfg->chrootdir, strerror(errno));
539 verbose(VERB_QUERY, "chdir to %s", cfg->chrootdir);
540 if(chroot(cfg->chrootdir))
541 fatal_exit("unable to chroot to %s: %s",
542 cfg->chrootdir, strerror(errno));
544 fatal_exit("unable to chdir to / in chroot %s: %s",
545 cfg->chrootdir, strerror(errno));
546 verbose(VERB_QUERY, "chroot to %s", cfg->chrootdir);
547 if(strncmp(*cfgfile, cfg->chrootdir,
548 strlen(cfg->chrootdir)) == 0)
549 (*cfgfile) += strlen(cfg->chrootdir);
551 /* adjust stored pidfile for chroot */
552 if(daemon->pidfile && daemon->pidfile[0] &&
553 strncmp(daemon->pidfile, cfg->chrootdir,
554 strlen(cfg->chrootdir))==0) {
555 char* old = daemon->pidfile;
556 daemon->pidfile = strdup(old+strlen(cfg->chrootdir));
559 log_err("out of memory in pidfile adjust");
561 daemon->chroot = strdup(cfg->chrootdir);
563 log_err("out of memory in daemon chroot dir storage");
568 /* change to working directory inside chroot */
569 if(cfg->directory && cfg->directory[0]) {
570 char* dir = cfg->directory;
571 if(cfg->chrootdir && cfg->chrootdir[0] &&
572 strncmp(dir, cfg->chrootdir,
573 strlen(cfg->chrootdir)) == 0)
574 dir += strlen(cfg->chrootdir);
577 fatal_exit("Could not chdir to %s: %s",
578 dir, strerror(errno));
580 verbose(VERB_QUERY, "chdir to %s", dir);
584 /* drop permissions after chroot, getpwnam, pidfile, syslog done*/
586 if(cfg->username && cfg->username[0]) {
587 # ifdef HAVE_INITGROUPS
588 if(initgroups(cfg->username, gid) != 0)
589 log_warn("unable to initgroups %s: %s",
590 cfg->username, strerror(errno));
591 # endif /* HAVE_INITGROUPS */
594 #ifdef HAVE_SETRESGID
595 if(setresgid(gid,gid,gid) != 0)
596 #elif defined(HAVE_SETREGID) && !defined(DARWIN_BROKEN_SETREUID)
597 if(setregid(gid,gid) != 0)
598 #else /* use setgid */
600 #endif /* HAVE_SETRESGID */
601 fatal_exit("unable to set group id of %s: %s",
602 cfg->username, strerror(errno));
603 #ifdef HAVE_SETRESUID
604 if(setresuid(uid,uid,uid) != 0)
605 #elif defined(HAVE_SETREUID) && !defined(DARWIN_BROKEN_SETREUID)
606 if(setreuid(uid,uid) != 0)
607 #else /* use setuid */
609 #endif /* HAVE_SETRESUID */
610 fatal_exit("unable to set user id of %s: %s",
611 cfg->username, strerror(errno));
612 verbose(VERB_QUERY, "drop user privileges, run as %s",
615 #endif /* HAVE_GETPWNAM */
616 /* file logging inited after chroot,chdir,setuid is done so that
617 * it would succeed on SIGHUP as well */
619 log_init(cfg->logfile, cfg->use_syslog, cfg->chrootdir);
624 * @param cfgfile: the config file name.
625 * @param cmdline_verbose: verbosity resulting from commandline -v.
626 * These increase verbosity as specified in the config file.
627 * @param debug_mode: if set, do not daemonize.
630 run_daemon(const char* cfgfile, int cmdline_verbose, int debug_mode)
632 struct config_file* cfg = NULL;
633 struct daemon* daemon = NULL;
636 if(!(daemon = daemon_init()))
637 fatal_exit("alloc failure");
638 while(!daemon->need_to_exit) {
640 verbose(VERB_OPS, "Restart of %s.", PACKAGE_STRING);
641 else verbose(VERB_OPS, "Start of %s.", PACKAGE_STRING);
644 if(!(cfg = config_create()))
645 fatal_exit("Could not alloc config defaults");
646 if(!config_read(cfg, cfgfile, daemon->chroot)) {
648 fatal_exit("Could not read config file: %s",
650 log_warn("Continuing with default config settings");
652 apply_settings(daemon, cfg, cmdline_verbose);
655 if(!daemon_open_shared_ports(daemon))
656 fatal_exit("could not open ports");
658 perform_setup(daemon, cfg, debug_mode, &cfgfile);
661 /* reopen log after HUP to facilitate log rotation */
663 log_init(cfg->logfile, 0, cfg->chrootdir);
668 /* clean up for restart */
669 verbose(VERB_ALGO, "cleanup.");
670 daemon_cleanup(daemon);
673 verbose(VERB_ALGO, "Exit cleanup.");
674 /* this unlink may not work if the pidfile is located outside
675 * of the chroot/workdir or we no longer have permissions */
676 if(daemon->pidfile) {
678 /* truncate pidfile */
679 fd = open(daemon->pidfile, O_WRONLY | O_TRUNC, 0644);
683 unlink(daemon->pidfile);
685 daemon_delete(daemon);
688 /** getopt global, in case header files fail to declare it. */
690 /** getopt global, in case header files fail to declare it. */
694 * main program. Set options given commandline arguments.
695 * @param argc: number of commandline arguments.
696 * @param argv: array of commandline arguments.
697 * @return: exit status of the program.
700 main(int argc, char* argv[])
703 const char* cfgfile = CONFIGFILE;
704 const char* winopt = NULL;
705 int cmdline_verbose = 0;
712 /* take debug snapshot of heap */
713 unbound_start_brk = sbrk(0);
716 log_init(NULL, 0, NULL);
717 /* parse the options */
718 while( (c=getopt(argc, argv, "c:dhvw:")) != -1) {
748 wsvc_command_option(winopt, cfgfile, cmdline_verbose,
751 fatal_exit("option not supported");
760 run_daemon(cfgfile, cmdline_verbose, debug_mode);
761 log_init(NULL, 0, NULL); /* close logfile */