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"
62 #include <openssl/crypto.h>
71 /* splint chokes on this system header file */
72 #ifdef HAVE_SYS_RESOURCE_H
73 #include <sys/resource.h>
75 #endif /* S_SPLINT_S */
76 #ifdef HAVE_LOGIN_CAP_H
77 #include <login_cap.h>
82 # include "util/winsock_event.h"
84 # include "util/mini_event.h"
90 # include "event2/event.h"
91 # include "event2/event_struct.h"
92 # include "event2/event_compat.h"
97 # include "winrc/win_svc.h"
106 /** global debug value to keep track of heap memory allocation */
107 void* unbound_start_brk = 0;
110 #if !defined(HAVE_EVENT_BASE_GET_METHOD) && (defined(HAVE_EV_LOOP) || defined(HAVE_EV_DEFAULT_LOOP))
111 static const char* ev_backend2str(int b)
114 case EVBACKEND_SELECT: return "select";
115 case EVBACKEND_POLL: return "poll";
116 case EVBACKEND_EPOLL: return "epoll";
117 case EVBACKEND_KQUEUE: return "kqueue";
118 case EVBACKEND_DEVPOLL: return "devpoll";
119 case EVBACKEND_PORT: return "evport";
125 /** get the event system in use */
126 static void get_event_sys(const char** n, const char** s, const char** m)
131 *m = "WSAWaitForMultipleEvents";
132 #elif defined(USE_MINI_EVENT)
137 struct event_base* b;
138 *s = event_get_version();
139 # ifdef HAVE_EVENT_BASE_GET_METHOD
141 b = event_base_new();
142 *m = event_base_get_method(b);
143 # elif defined(HAVE_EV_LOOP) || defined(HAVE_EV_DEFAULT_LOOP)
145 b = (struct event_base*)ev_default_loop(EVFLAG_AUTO);
146 *m = ev_backend2str(ev_backend((struct ev_loop*)b));
149 *m = "not obtainable";
152 # ifdef HAVE_EVENT_BASE_FREE
162 const char *evnm="event", *evsys="", *evmethod="";
163 printf("usage: unbound [options]\n");
164 printf(" start unbound daemon DNS resolver.\n");
165 printf("-h this help\n");
166 printf("-c file config file to read instead of %s\n", CONFIGFILE);
167 printf(" file format is described in unbound.conf(5).\n");
168 printf("-d do not fork into the background.\n");
169 printf("-v verbose (more times to increase verbosity)\n");
171 printf("-w opt windows option: \n");
172 printf(" install, remove - manage the services entry\n");
173 printf(" service - used to start from services control panel\n");
175 printf("Version %s\n", PACKAGE_VERSION);
176 get_event_sys(&evnm, &evsys, &evmethod);
177 printf("linked libs: %s %s (it uses %s), %s\n",
178 evnm, evsys, evmethod,
180 SSLeay_version(SSLEAY_VERSION)
181 #elif defined(HAVE_NSS)
183 #elif defined(HAVE_NETTLE)
187 printf("linked modules:");
188 for(m = module_list_avail(); *m; m++)
191 printf("BSD licensed, see LICENSE in source package for details.\n");
192 printf("Report bugs to %s\n", PACKAGE_BUGREPORT);
195 #ifndef unbound_testbound
196 int replay_var_compare(const void* ATTR_UNUSED(a), const void* ATTR_UNUSED(b))
203 /** check file descriptor count */
205 checkrlimits(struct config_file* cfg)
208 #ifdef HAVE_GETRLIMIT
209 /* list has number of ports to listen to, ifs number addresses */
210 int list = ((cfg->do_udp?1:0) + (cfg->do_tcp?1 +
211 (int)cfg->incoming_num_tcp:0));
212 size_t listen_ifs = (size_t)(cfg->num_ifs==0?
213 ((cfg->do_ip4 && !cfg->if_automatic?1:0) +
214 (cfg->do_ip6?1:0)):cfg->num_ifs);
215 size_t listen_num = list*listen_ifs;
216 size_t outudpnum = (size_t)cfg->outgoing_num_ports;
217 size_t outtcpnum = cfg->outgoing_num_tcp;
218 size_t misc = 4; /* logfile, pidfile, stdout... */
219 size_t perthread_noudp = listen_num + outtcpnum +
220 2/*cmdpipe*/ + 2/*libevent*/ + misc;
221 size_t perthread = perthread_noudp + outudpnum;
223 #if !defined(HAVE_PTHREAD) && !defined(HAVE_SOLARIS_THREADS)
224 int numthread = 1; /* it forks */
226 int numthread = (cfg->num_threads?cfg->num_threads:1);
228 size_t total = numthread * perthread + misc;
233 strncmp(event_get_version(), "mini-event", 10) == 0) {
234 log_warn("too many file descriptors requested. The builtin"
235 "mini-event cannot handle more than 1024. Config "
236 "for less fds or compile with libevent");
237 if(numthread*perthread_noudp+15 > 1024)
238 fatal_exit("too much tcp. not enough fds.");
239 cfg->outgoing_num_ports = (int)((1024
240 - numthread*perthread_noudp
241 - 10 /* safety margin */) /numthread);
242 log_warn("continuing with less udp ports: %u",
243 cfg->outgoing_num_ports);
247 strncmp(event_get_version(), "winsock-event", 13) == 0) {
248 log_err("too many file descriptors requested. The winsock"
249 " event handler cannot handle more than 64 per "
250 " thread. Config for less fds");
251 if(perthread_noudp+2 > 64)
252 fatal_exit("too much tcp. not enough fds.");
253 cfg->outgoing_num_ports = (int)((64
255 - 2/* safety margin */));
256 log_warn("continuing with less udp ports: %u",
257 cfg->outgoing_num_ports);
258 total = numthread*(perthread_noudp+
259 (size_t)cfg->outgoing_num_ports)+misc;
261 if(getrlimit(RLIMIT_NOFILE, &rlim) < 0) {
262 log_warn("getrlimit: %s", strerror(errno));
265 if(rlim.rlim_cur == (rlim_t)RLIM_INFINITY)
267 if((size_t)rlim.rlim_cur < total) {
268 avail = (size_t)rlim.rlim_cur;
269 rlim.rlim_cur = (rlim_t)(total + 10);
270 rlim.rlim_max = (rlim_t)(total + 10);
271 #ifdef HAVE_SETRLIMIT
272 if(setrlimit(RLIMIT_NOFILE, &rlim) < 0) {
273 log_warn("setrlimit: %s", strerror(errno));
275 log_warn("cannot increase max open fds from %u to %u",
276 (unsigned)avail, (unsigned)total+10);
277 /* check that calculation below does not underflow,
278 * with 15 as margin */
279 if(numthread*perthread_noudp+15 > avail)
280 fatal_exit("too much tcp. not enough fds.");
281 cfg->outgoing_num_ports = (int)((avail
282 - numthread*perthread_noudp
283 - 10 /* safety margin */) /numthread);
284 log_warn("continuing with less udp ports: %u",
285 cfg->outgoing_num_ports);
286 log_warn("increase ulimit or decrease threads, "
287 "ports in config to remove this warning");
289 #ifdef HAVE_SETRLIMIT
292 verbose(VERB_ALGO, "increased limit(open files) from %u to %u",
293 (unsigned)avail, (unsigned)total+10);
297 #endif /* HAVE_GETRLIMIT */
298 #endif /* S_SPLINT_S */
301 /** set verbosity, check rlimits, cache settings */
303 apply_settings(struct daemon* daemon, struct config_file* cfg,
304 int cmdline_verbose, int debug_mode)
306 /* apply if they have changed */
307 verbosity = cmdline_verbose + cfg->verbosity;
308 if (debug_mode > 1) {
312 daemon_apply_cfg(daemon, cfg);
317 /** Read existing pid from pidfile.
318 * @param file: file name of pid file.
319 * @return: the pid from the file or -1 if none.
322 readpid (const char* file)
330 if ((fd = open(file, O_RDONLY)) == -1) {
332 log_err("Could not read pidfile %s: %s",
333 file, strerror(errno));
337 if (((l = read(fd, pidbuf, sizeof(pidbuf)))) == -1) {
339 log_err("Could not read pidfile %s: %s",
340 file, strerror(errno));
347 /* Empty pidfile means no pidfile... */
352 pidbuf[sizeof(pidbuf)-1] = 0;
353 pid = (pid_t)strtol(pidbuf, &t, 10);
355 if (*t && *t != '\n') {
361 /** write pid to file.
362 * @param pidfile: file name of pid file.
363 * @param pid: pid to write to file.
366 writepid (const char* pidfile, pid_t pid)
370 if ((f = fopen(pidfile, "w")) == NULL ) {
371 log_err("cannot open pidfile %s: %s",
372 pidfile, strerror(errno));
375 if(fprintf(f, "%lu\n", (unsigned long)pid) < 0) {
376 log_err("cannot write to pidfile %s: %s",
377 pidfile, strerror(errno));
383 * check old pid file.
384 * @param pidfile: the file name of the pid file.
385 * @param inchroot: if pidfile is inchroot and we can thus expect to
386 * be able to delete it.
389 checkoldpid(char* pidfile, int inchroot)
392 if((old = readpid(pidfile)) != -1) {
393 /* see if it is still alive */
394 if(kill(old, 0) == 0 || errno == EPERM)
395 log_warn("unbound is already running as pid %u.",
398 log_warn("did not exit gracefully last time (%u)",
402 #endif /* HAVE_KILL */
404 /** detach from command line */
408 #if defined(HAVE_DAEMON) && !defined(DEPRECATED_DAEMON)
409 /* use POSIX daemon(3) function */
410 if(daemon(1, 0) != 0)
411 fatal_exit("daemon failed: %s", strerror(errno));
412 #else /* no HAVE_DAEMON */
420 fatal_exit("fork failed: %s", strerror(errno));
422 /* exit interactive session */
428 fatal_exit("setsid() failed: %s", strerror(errno));
430 if ((fd = open("/dev/null", O_RDWR, 0)) != -1) {
431 (void)dup2(fd, STDIN_FILENO);
432 (void)dup2(fd, STDOUT_FILENO);
433 (void)dup2(fd, STDERR_FILENO);
437 #endif /* HAVE_FORK */
438 #endif /* HAVE_DAEMON */
441 /** daemonize, drop user priviliges and chroot if needed */
443 perform_setup(struct daemon* daemon, struct config_file* cfg, int debug_mode,
444 const char** cfgfile)
450 struct passwd *pwd = NULL;
452 if(cfg->username && cfg->username[0]) {
453 if((pwd = getpwnam(cfg->username)) == NULL)
454 fatal_exit("user '%s' does not exist.", cfg->username);
455 /* endpwent below, in case we need pwd for setusercontext */
459 w_config_adjust_directory(cfg);
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. */
473 /* read ssl keys while superuser and outside chroot */
475 if(!(daemon->rc = daemon_remote_create(cfg)))
476 fatal_exit("could not set up remote-control");
477 if(cfg->ssl_service_key && cfg->ssl_service_key[0]) {
478 if(!(daemon->listen_sslctx = listen_sslctx_create(
479 cfg->ssl_service_key, cfg->ssl_service_pem, NULL)))
480 fatal_exit("could not set up listen SSL_CTX");
482 if(!(daemon->connect_sslctx = connect_sslctx_create(NULL, NULL, NULL)))
483 fatal_exit("could not set up connect SSL_CTX");
487 /* true if pidfile is inside chrootdir, or nochroot */
488 pidinchroot = !(cfg->chrootdir && cfg->chrootdir[0]) ||
489 (cfg->chrootdir && cfg->chrootdir[0] &&
490 strncmp(cfg->pidfile, cfg->chrootdir,
491 strlen(cfg->chrootdir))==0);
493 /* check old pid file before forking */
494 if(cfg->pidfile && cfg->pidfile[0]) {
495 /* calculate position of pidfile */
496 if(cfg->pidfile[0] == '/')
497 daemon->pidfile = strdup(cfg->pidfile);
498 else daemon->pidfile = fname_after_chroot(cfg->pidfile,
501 fatal_exit("pidfile alloc: out of memory");
502 checkoldpid(daemon->pidfile, pidinchroot);
506 /* daemonize because pid is needed by the writepid func */
507 if(!debug_mode && cfg->do_daemonize) {
511 /* write new pidfile (while still root, so can be outside chroot) */
513 if(cfg->pidfile && cfg->pidfile[0]) {
514 writepid(daemon->pidfile, getpid());
515 if(cfg->username && cfg->username[0] && cfg_uid != (uid_t)-1 &&
518 if(chown(daemon->pidfile, cfg_uid, cfg_gid) == -1) {
519 verbose(VERB_QUERY, "cannot chown %u.%u %s: %s",
520 (unsigned)cfg_uid, (unsigned)cfg_gid,
521 daemon->pidfile, strerror(errno));
523 # endif /* HAVE_CHOWN */
528 #endif /* HAVE_KILL */
530 /* Set user context */
532 if(cfg->username && cfg->username[0] && cfg_uid != (uid_t)-1) {
533 #ifdef HAVE_SETUSERCONTEXT
534 /* setusercontext does initgroups, setuid, setgid, and
535 * also resource limits from login config, but we
536 * still call setresuid, setresgid to be sure to set all uid*/
537 if(setusercontext(NULL, pwd, cfg_uid, (unsigned)
538 LOGIN_SETALL & ~LOGIN_SETUSER & ~LOGIN_SETGROUP) != 0)
539 log_warn("unable to setusercontext %s: %s",
540 cfg->username, strerror(errno));
541 #endif /* HAVE_SETUSERCONTEXT */
543 #endif /* HAVE_GETPWNAM */
545 /* box into the chroot */
547 if(cfg->chrootdir && cfg->chrootdir[0]) {
548 if(chdir(cfg->chrootdir)) {
549 fatal_exit("unable to chdir to chroot %s: %s",
550 cfg->chrootdir, strerror(errno));
552 verbose(VERB_QUERY, "chdir to %s", cfg->chrootdir);
553 if(chroot(cfg->chrootdir))
554 fatal_exit("unable to chroot to %s: %s",
555 cfg->chrootdir, strerror(errno));
557 fatal_exit("unable to chdir to / in chroot %s: %s",
558 cfg->chrootdir, strerror(errno));
559 verbose(VERB_QUERY, "chroot to %s", cfg->chrootdir);
560 if(strncmp(*cfgfile, cfg->chrootdir,
561 strlen(cfg->chrootdir)) == 0)
562 (*cfgfile) += strlen(cfg->chrootdir);
564 /* adjust stored pidfile for chroot */
565 if(daemon->pidfile && daemon->pidfile[0] &&
566 strncmp(daemon->pidfile, cfg->chrootdir,
567 strlen(cfg->chrootdir))==0) {
568 char* old = daemon->pidfile;
569 daemon->pidfile = strdup(old+strlen(cfg->chrootdir));
572 log_err("out of memory in pidfile adjust");
574 daemon->chroot = strdup(cfg->chrootdir);
576 log_err("out of memory in daemon chroot dir storage");
581 /* change to working directory inside chroot */
582 if(cfg->directory && cfg->directory[0]) {
583 char* dir = cfg->directory;
584 if(cfg->chrootdir && cfg->chrootdir[0] &&
585 strncmp(dir, cfg->chrootdir,
586 strlen(cfg->chrootdir)) == 0)
587 dir += strlen(cfg->chrootdir);
590 fatal_exit("Could not chdir to %s: %s",
591 dir, strerror(errno));
593 verbose(VERB_QUERY, "chdir to %s", dir);
597 /* drop permissions after chroot, getpwnam, pidfile, syslog done*/
599 if(cfg->username && cfg->username[0] && cfg_uid != (uid_t)-1) {
600 # ifdef HAVE_INITGROUPS
601 if(initgroups(cfg->username, cfg_gid) != 0)
602 log_warn("unable to initgroups %s: %s",
603 cfg->username, strerror(errno));
604 # endif /* HAVE_INITGROUPS */
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.
643 run_daemon(const char* cfgfile, int cmdline_verbose, int debug_mode)
645 struct config_file* cfg = NULL;
646 struct daemon* daemon = NULL;
649 if(!(daemon = daemon_init()))
650 fatal_exit("alloc failure");
651 while(!daemon->need_to_exit) {
653 verbose(VERB_OPS, "Restart of %s.", PACKAGE_STRING);
654 else verbose(VERB_OPS, "Start of %s.", PACKAGE_STRING);
657 if(!(cfg = config_create()))
658 fatal_exit("Could not alloc config defaults");
659 if(!config_read(cfg, cfgfile, daemon->chroot)) {
661 fatal_exit("Could not read config file: %s",
663 log_warn("Continuing with default config settings");
665 apply_settings(daemon, cfg, cmdline_verbose, debug_mode);
667 config_lookup_uid(cfg);
670 if(!daemon_open_shared_ports(daemon))
671 fatal_exit("could not open ports");
673 perform_setup(daemon, cfg, debug_mode, &cfgfile);
676 /* reopen log after HUP to facilitate log rotation */
678 log_init(cfg->logfile, 0, cfg->chrootdir);
683 /* clean up for restart */
684 verbose(VERB_ALGO, "cleanup.");
685 daemon_cleanup(daemon);
688 verbose(VERB_ALGO, "Exit cleanup.");
689 /* this unlink may not work if the pidfile is located outside
690 * of the chroot/workdir or we no longer have permissions */
691 if(daemon->pidfile) {
693 /* truncate pidfile */
694 fd = open(daemon->pidfile, O_WRONLY | O_TRUNC, 0644);
698 unlink(daemon->pidfile);
700 daemon_delete(daemon);
703 /** getopt global, in case header files fail to declare it. */
705 /** getopt global, in case header files fail to declare it. */
709 * main program. Set options given commandline arguments.
710 * @param argc: number of commandline arguments.
711 * @param argv: array of commandline arguments.
712 * @return: exit status of the program.
715 main(int argc, char* argv[])
718 const char* cfgfile = CONFIGFILE;
719 const char* winopt = NULL;
720 int cmdline_verbose = 0;
727 /* take debug snapshot of heap */
728 unbound_start_brk = sbrk(0);
731 log_init(NULL, 0, NULL);
732 log_ident_set(strrchr(argv[0],'/')?strrchr(argv[0],'/')+1:argv[0]);
733 /* parse the options */
734 while( (c=getopt(argc, argv, "c:dhvw:")) != -1) {
764 wsvc_command_option(winopt, cfgfile, cmdline_verbose,
767 fatal_exit("option not supported");
776 run_daemon(cfgfile, cmdline_verbose, debug_mode);
777 log_init(NULL, 0, NULL); /* close logfile */