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)
447 struct passwd *pwd = NULL;
449 if(cfg->username && cfg->username[0]) {
450 if((pwd = getpwnam(cfg->username)) == NULL)
451 fatal_exit("user '%s' does not exist.", cfg->username);
452 /* endpwent below, in case we need pwd for setusercontext */
456 w_config_adjust_directory(cfg);
459 /* init syslog (as root) if needed, before daemonize, otherwise
460 * a fork error could not be printed since daemonize closed stderr.*/
461 if(cfg->use_syslog) {
462 log_init(cfg->logfile, cfg->use_syslog, cfg->chrootdir);
464 /* if using a logfile, we cannot open it because the logfile would
465 * be created with the wrong permissions, we cannot chown it because
466 * we cannot chown system logfiles, so we do not open at all.
467 * So, using a logfile, the user does not see errors unless -d is
468 * given to unbound on the commandline. */
470 /* read ssl keys while superuser and outside chroot */
472 if(!(daemon->rc = daemon_remote_create(cfg)))
473 fatal_exit("could not set up remote-control");
474 if(cfg->ssl_service_key && cfg->ssl_service_key[0]) {
475 if(!(daemon->listen_sslctx = listen_sslctx_create(
476 cfg->ssl_service_key, cfg->ssl_service_pem, NULL)))
477 fatal_exit("could not set up listen SSL_CTX");
479 if(!(daemon->connect_sslctx = connect_sslctx_create(NULL, NULL, NULL)))
480 fatal_exit("could not set up connect SSL_CTX");
484 /* check old pid file before forking */
485 if(cfg->pidfile && cfg->pidfile[0]) {
486 /* calculate position of pidfile */
487 if(cfg->pidfile[0] == '/')
488 daemon->pidfile = strdup(cfg->pidfile);
489 else daemon->pidfile = fname_after_chroot(cfg->pidfile,
492 fatal_exit("pidfile alloc: out of memory");
493 checkoldpid(daemon->pidfile,
494 /* true if pidfile is inside chrootdir, or nochroot */
495 !(cfg->chrootdir && cfg->chrootdir[0]) ||
496 (cfg->chrootdir && cfg->chrootdir[0] &&
497 strncmp(daemon->pidfile, cfg->chrootdir,
498 strlen(cfg->chrootdir))==0));
502 /* daemonize because pid is needed by the writepid func */
503 if(!debug_mode && cfg->do_daemonize) {
507 /* write new pidfile (while still root, so can be outside chroot) */
509 if(cfg->pidfile && cfg->pidfile[0]) {
510 writepid(daemon->pidfile, getpid());
511 if(cfg->username && cfg->username[0] && cfg_uid != (uid_t)-1) {
513 if(chown(daemon->pidfile, cfg_uid, cfg_gid) == -1) {
514 log_err("cannot chown %u.%u %s: %s",
515 (unsigned)cfg_uid, (unsigned)cfg_gid,
516 daemon->pidfile, strerror(errno));
518 # endif /* HAVE_CHOWN */
523 #endif /* HAVE_KILL */
525 /* Set user context */
527 if(cfg->username && cfg->username[0] && cfg_uid != (uid_t)-1) {
528 #ifdef HAVE_SETUSERCONTEXT
529 /* setusercontext does initgroups, setuid, setgid, and
530 * also resource limits from login config, but we
531 * still call setresuid, setresgid to be sure to set all uid*/
532 if(setusercontext(NULL, pwd, cfg_uid, (unsigned)
533 LOGIN_SETALL & ~LOGIN_SETUSER & ~LOGIN_SETGROUP) != 0)
534 log_warn("unable to setusercontext %s: %s",
535 cfg->username, strerror(errno));
536 #endif /* HAVE_SETUSERCONTEXT */
538 #endif /* HAVE_GETPWNAM */
540 /* box into the chroot */
542 if(cfg->chrootdir && cfg->chrootdir[0]) {
543 if(chdir(cfg->chrootdir)) {
544 fatal_exit("unable to chdir to chroot %s: %s",
545 cfg->chrootdir, strerror(errno));
547 verbose(VERB_QUERY, "chdir to %s", cfg->chrootdir);
548 if(chroot(cfg->chrootdir))
549 fatal_exit("unable to chroot to %s: %s",
550 cfg->chrootdir, strerror(errno));
552 fatal_exit("unable to chdir to / in chroot %s: %s",
553 cfg->chrootdir, strerror(errno));
554 verbose(VERB_QUERY, "chroot to %s", cfg->chrootdir);
555 if(strncmp(*cfgfile, cfg->chrootdir,
556 strlen(cfg->chrootdir)) == 0)
557 (*cfgfile) += strlen(cfg->chrootdir);
559 /* adjust stored pidfile for chroot */
560 if(daemon->pidfile && daemon->pidfile[0] &&
561 strncmp(daemon->pidfile, cfg->chrootdir,
562 strlen(cfg->chrootdir))==0) {
563 char* old = daemon->pidfile;
564 daemon->pidfile = strdup(old+strlen(cfg->chrootdir));
567 log_err("out of memory in pidfile adjust");
569 daemon->chroot = strdup(cfg->chrootdir);
571 log_err("out of memory in daemon chroot dir storage");
576 /* change to working directory inside chroot */
577 if(cfg->directory && cfg->directory[0]) {
578 char* dir = cfg->directory;
579 if(cfg->chrootdir && cfg->chrootdir[0] &&
580 strncmp(dir, cfg->chrootdir,
581 strlen(cfg->chrootdir)) == 0)
582 dir += strlen(cfg->chrootdir);
585 fatal_exit("Could not chdir to %s: %s",
586 dir, strerror(errno));
588 verbose(VERB_QUERY, "chdir to %s", dir);
592 /* drop permissions after chroot, getpwnam, pidfile, syslog done*/
594 if(cfg->username && cfg->username[0] && cfg_uid != (uid_t)-1) {
595 # ifdef HAVE_INITGROUPS
596 if(initgroups(cfg->username, cfg_gid) != 0)
597 log_warn("unable to initgroups %s: %s",
598 cfg->username, strerror(errno));
599 # endif /* HAVE_INITGROUPS */
602 #ifdef HAVE_SETRESGID
603 if(setresgid(cfg_gid,cfg_gid,cfg_gid) != 0)
604 #elif defined(HAVE_SETREGID) && !defined(DARWIN_BROKEN_SETREUID)
605 if(setregid(cfg_gid,cfg_gid) != 0)
606 #else /* use setgid */
607 if(setgid(cfg_gid) != 0)
608 #endif /* HAVE_SETRESGID */
609 fatal_exit("unable to set group id of %s: %s",
610 cfg->username, strerror(errno));
611 #ifdef HAVE_SETRESUID
612 if(setresuid(cfg_uid,cfg_uid,cfg_uid) != 0)
613 #elif defined(HAVE_SETREUID) && !defined(DARWIN_BROKEN_SETREUID)
614 if(setreuid(cfg_uid,cfg_uid) != 0)
615 #else /* use setuid */
616 if(setuid(cfg_uid) != 0)
617 #endif /* HAVE_SETRESUID */
618 fatal_exit("unable to set user id of %s: %s",
619 cfg->username, strerror(errno));
620 verbose(VERB_QUERY, "drop user privileges, run as %s",
623 #endif /* HAVE_GETPWNAM */
624 /* file logging inited after chroot,chdir,setuid is done so that
625 * it would succeed on SIGHUP as well */
627 log_init(cfg->logfile, cfg->use_syslog, cfg->chrootdir);
632 * @param cfgfile: the config file name.
633 * @param cmdline_verbose: verbosity resulting from commandline -v.
634 * These increase verbosity as specified in the config file.
635 * @param debug_mode: if set, do not daemonize.
638 run_daemon(const char* cfgfile, int cmdline_verbose, int debug_mode)
640 struct config_file* cfg = NULL;
641 struct daemon* daemon = NULL;
644 if(!(daemon = daemon_init()))
645 fatal_exit("alloc failure");
646 while(!daemon->need_to_exit) {
648 verbose(VERB_OPS, "Restart of %s.", PACKAGE_STRING);
649 else verbose(VERB_OPS, "Start of %s.", PACKAGE_STRING);
652 if(!(cfg = config_create()))
653 fatal_exit("Could not alloc config defaults");
654 if(!config_read(cfg, cfgfile, daemon->chroot)) {
656 fatal_exit("Could not read config file: %s",
658 log_warn("Continuing with default config settings");
660 apply_settings(daemon, cfg, cmdline_verbose, debug_mode);
662 config_lookup_uid(cfg);
665 if(!daemon_open_shared_ports(daemon))
666 fatal_exit("could not open ports");
668 perform_setup(daemon, cfg, debug_mode, &cfgfile);
671 /* reopen log after HUP to facilitate log rotation */
673 log_init(cfg->logfile, 0, cfg->chrootdir);
678 /* clean up for restart */
679 verbose(VERB_ALGO, "cleanup.");
680 daemon_cleanup(daemon);
683 verbose(VERB_ALGO, "Exit cleanup.");
684 /* this unlink may not work if the pidfile is located outside
685 * of the chroot/workdir or we no longer have permissions */
686 if(daemon->pidfile) {
688 /* truncate pidfile */
689 fd = open(daemon->pidfile, O_WRONLY | O_TRUNC, 0644);
693 unlink(daemon->pidfile);
695 daemon_delete(daemon);
698 /** getopt global, in case header files fail to declare it. */
700 /** getopt global, in case header files fail to declare it. */
704 * main program. Set options given commandline arguments.
705 * @param argc: number of commandline arguments.
706 * @param argv: array of commandline arguments.
707 * @return: exit status of the program.
710 main(int argc, char* argv[])
713 const char* cfgfile = CONFIGFILE;
714 const char* winopt = NULL;
715 int cmdline_verbose = 0;
722 /* take debug snapshot of heap */
723 unbound_start_brk = sbrk(0);
726 log_init(NULL, 0, NULL);
727 log_ident_set(strrchr(argv[0],'/')?strrchr(argv[0],'/')+1:argv[0]);
728 /* parse the options */
729 while( (c=getopt(argc, argv, "c:dhvw:")) != -1) {
759 wsvc_command_option(winopt, cfgfile, cmdline_verbose,
762 fatal_exit("option not supported");
771 run_daemon(cfgfile, cmdline_verbose, debug_mode);
772 log_init(NULL, 0, NULL); /* close logfile */