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)
185 printf("linked modules:");
186 for(m = module_list_avail(); *m; m++)
189 printf("BSD licensed, see LICENSE in source package for details.\n");
190 printf("Report bugs to %s\n", PACKAGE_BUGREPORT);
193 #ifndef unbound_testbound
194 int replay_var_compare(const void* ATTR_UNUSED(a), const void* ATTR_UNUSED(b))
201 /** check file descriptor count */
203 checkrlimits(struct config_file* cfg)
206 #ifdef HAVE_GETRLIMIT
207 /* list has number of ports to listen to, ifs number addresses */
208 int list = ((cfg->do_udp?1:0) + (cfg->do_tcp?1 +
209 (int)cfg->incoming_num_tcp:0));
210 size_t listen_ifs = (size_t)(cfg->num_ifs==0?
211 ((cfg->do_ip4 && !cfg->if_automatic?1:0) +
212 (cfg->do_ip6?1:0)):cfg->num_ifs);
213 size_t listen_num = list*listen_ifs;
214 size_t outudpnum = (size_t)cfg->outgoing_num_ports;
215 size_t outtcpnum = cfg->outgoing_num_tcp;
216 size_t misc = 4; /* logfile, pidfile, stdout... */
217 size_t perthread_noudp = listen_num + outtcpnum +
218 2/*cmdpipe*/ + 2/*libevent*/ + misc;
219 size_t perthread = perthread_noudp + outudpnum;
221 #if !defined(HAVE_PTHREAD) && !defined(HAVE_SOLARIS_THREADS)
222 int numthread = 1; /* it forks */
224 int numthread = (cfg->num_threads?cfg->num_threads:1);
226 size_t total = numthread * perthread + misc;
231 strncmp(event_get_version(), "mini-event", 10) == 0) {
232 log_warn("too many file descriptors requested. The builtin"
233 "mini-event cannot handle more than 1024. Config "
234 "for less fds or compile with libevent");
235 if(numthread*perthread_noudp+15 > 1024)
236 fatal_exit("too much tcp. not enough fds.");
237 cfg->outgoing_num_ports = (int)((1024
238 - numthread*perthread_noudp
239 - 10 /* safety margin */) /numthread);
240 log_warn("continuing with less udp ports: %u",
241 cfg->outgoing_num_ports);
245 strncmp(event_get_version(), "winsock-event", 13) == 0) {
246 log_err("too many file descriptors requested. The winsock"
247 " event handler cannot handle more than 64 per "
248 " thread. Config for less fds");
249 if(perthread_noudp+2 > 64)
250 fatal_exit("too much tcp. not enough fds.");
251 cfg->outgoing_num_ports = (int)((64
253 - 2/* safety margin */));
254 log_warn("continuing with less udp ports: %u",
255 cfg->outgoing_num_ports);
256 total = numthread*(perthread_noudp+
257 (size_t)cfg->outgoing_num_ports)+misc;
259 if(getrlimit(RLIMIT_NOFILE, &rlim) < 0) {
260 log_warn("getrlimit: %s", strerror(errno));
263 if(rlim.rlim_cur == (rlim_t)RLIM_INFINITY)
265 if((size_t)rlim.rlim_cur < total) {
266 avail = (size_t)rlim.rlim_cur;
267 rlim.rlim_cur = (rlim_t)(total + 10);
268 rlim.rlim_max = (rlim_t)(total + 10);
269 #ifdef HAVE_SETRLIMIT
270 if(setrlimit(RLIMIT_NOFILE, &rlim) < 0) {
271 log_warn("setrlimit: %s", strerror(errno));
273 log_warn("cannot increase max open fds from %u to %u",
274 (unsigned)avail, (unsigned)total+10);
275 /* check that calculation below does not underflow,
276 * with 15 as margin */
277 if(numthread*perthread_noudp+15 > avail)
278 fatal_exit("too much tcp. not enough fds.");
279 cfg->outgoing_num_ports = (int)((avail
280 - numthread*perthread_noudp
281 - 10 /* safety margin */) /numthread);
282 log_warn("continuing with less udp ports: %u",
283 cfg->outgoing_num_ports);
284 log_warn("increase ulimit or decrease threads, "
285 "ports in config to remove this warning");
287 #ifdef HAVE_SETRLIMIT
290 verbose(VERB_ALGO, "increased limit(open files) from %u to %u",
291 (unsigned)avail, (unsigned)total+10);
295 #endif /* HAVE_GETRLIMIT */
296 #endif /* S_SPLINT_S */
299 /** set verbosity, check rlimits, cache settings */
301 apply_settings(struct daemon* daemon, struct config_file* cfg,
302 int cmdline_verbose, int debug_mode)
304 /* apply if they have changed */
305 verbosity = cmdline_verbose + cfg->verbosity;
306 if (debug_mode > 1) {
310 daemon_apply_cfg(daemon, cfg);
315 /** Read existing pid from pidfile.
316 * @param file: file name of pid file.
317 * @return: the pid from the file or -1 if none.
320 readpid (const char* file)
328 if ((fd = open(file, O_RDONLY)) == -1) {
330 log_err("Could not read pidfile %s: %s",
331 file, strerror(errno));
335 if (((l = read(fd, pidbuf, sizeof(pidbuf)))) == -1) {
337 log_err("Could not read pidfile %s: %s",
338 file, strerror(errno));
345 /* Empty pidfile means no pidfile... */
350 pidbuf[sizeof(pidbuf)-1] = 0;
351 pid = (pid_t)strtol(pidbuf, &t, 10);
353 if (*t && *t != '\n') {
359 /** write pid to file.
360 * @param pidfile: file name of pid file.
361 * @param pid: pid to write to file.
364 writepid (const char* pidfile, pid_t pid)
368 if ((f = fopen(pidfile, "w")) == NULL ) {
369 log_err("cannot open pidfile %s: %s",
370 pidfile, strerror(errno));
373 if(fprintf(f, "%lu\n", (unsigned long)pid) < 0) {
374 log_err("cannot write to pidfile %s: %s",
375 pidfile, strerror(errno));
381 * check old pid file.
382 * @param pidfile: the file name of the pid file.
383 * @param inchroot: if pidfile is inchroot and we can thus expect to
384 * be able to delete it.
387 checkoldpid(char* pidfile, int inchroot)
390 if((old = readpid(pidfile)) != -1) {
391 /* see if it is still alive */
392 if(kill(old, 0) == 0 || errno == EPERM)
393 log_warn("unbound is already running as pid %u.",
396 log_warn("did not exit gracefully last time (%u)",
400 #endif /* HAVE_KILL */
402 /** detach from command line */
406 #if defined(HAVE_DAEMON) && !defined(DEPRECATED_DAEMON)
407 /* use POSIX daemon(3) function */
408 if(daemon(1, 0) != 0)
409 fatal_exit("daemon failed: %s", strerror(errno));
410 #else /* no HAVE_DAEMON */
418 fatal_exit("fork failed: %s", strerror(errno));
420 /* exit interactive session */
426 fatal_exit("setsid() failed: %s", strerror(errno));
428 if ((fd = open("/dev/null", O_RDWR, 0)) != -1) {
429 (void)dup2(fd, STDIN_FILENO);
430 (void)dup2(fd, STDOUT_FILENO);
431 (void)dup2(fd, STDERR_FILENO);
435 #endif /* HAVE_FORK */
436 #endif /* HAVE_DAEMON */
439 /** daemonize, drop user priviliges and chroot if needed */
441 perform_setup(struct daemon* daemon, struct config_file* cfg, int debug_mode,
442 const char** cfgfile)
445 struct passwd *pwd = NULL;
447 if(cfg->username && cfg->username[0]) {
448 if((pwd = getpwnam(cfg->username)) == NULL)
449 fatal_exit("user '%s' does not exist.", cfg->username);
450 /* endpwent below, in case we need pwd for setusercontext */
454 /* init syslog (as root) if needed, before daemonize, otherwise
455 * a fork error could not be printed since daemonize closed stderr.*/
456 if(cfg->use_syslog) {
457 log_init(cfg->logfile, cfg->use_syslog, cfg->chrootdir);
459 /* if using a logfile, we cannot open it because the logfile would
460 * be created with the wrong permissions, we cannot chown it because
461 * we cannot chown system logfiles, so we do not open at all.
462 * So, using a logfile, the user does not see errors unless -d is
463 * given to unbound on the commandline. */
465 /* read ssl keys while superuser and outside chroot */
467 if(!(daemon->rc = daemon_remote_create(cfg)))
468 fatal_exit("could not set up remote-control");
469 if(cfg->ssl_service_key && cfg->ssl_service_key[0]) {
470 if(!(daemon->listen_sslctx = listen_sslctx_create(
471 cfg->ssl_service_key, cfg->ssl_service_pem, NULL)))
472 fatal_exit("could not set up listen SSL_CTX");
474 if(!(daemon->connect_sslctx = connect_sslctx_create(NULL, NULL, NULL)))
475 fatal_exit("could not set up connect SSL_CTX");
479 /* check old pid file before forking */
480 if(cfg->pidfile && cfg->pidfile[0]) {
481 /* calculate position of pidfile */
482 if(cfg->pidfile[0] == '/')
483 daemon->pidfile = strdup(cfg->pidfile);
484 else daemon->pidfile = fname_after_chroot(cfg->pidfile,
487 fatal_exit("pidfile alloc: out of memory");
488 checkoldpid(daemon->pidfile,
489 /* true if pidfile is inside chrootdir, or nochroot */
490 !(cfg->chrootdir && cfg->chrootdir[0]) ||
491 (cfg->chrootdir && cfg->chrootdir[0] &&
492 strncmp(daemon->pidfile, cfg->chrootdir,
493 strlen(cfg->chrootdir))==0));
497 /* daemonize because pid is needed by the writepid func */
498 if(!debug_mode && cfg->do_daemonize) {
502 /* write new pidfile (while still root, so can be outside chroot) */
504 if(cfg->pidfile && cfg->pidfile[0]) {
505 writepid(daemon->pidfile, getpid());
506 if(cfg->username && cfg->username[0] && cfg_uid != (uid_t)-1) {
508 if(chown(daemon->pidfile, cfg_uid, cfg_gid) == -1) {
509 log_err("cannot chown %u.%u %s: %s",
510 (unsigned)cfg_uid, (unsigned)cfg_gid,
511 daemon->pidfile, strerror(errno));
513 # endif /* HAVE_CHOWN */
518 #endif /* HAVE_KILL */
520 /* Set user context */
522 if(cfg->username && cfg->username[0] && cfg_uid != (uid_t)-1) {
523 #ifdef HAVE_SETUSERCONTEXT
524 /* setusercontext does initgroups, setuid, setgid, and
525 * also resource limits from login config, but we
526 * still call setresuid, setresgid to be sure to set all uid*/
527 if(setusercontext(NULL, pwd, cfg_uid, (unsigned)
528 LOGIN_SETALL & ~LOGIN_SETUSER & ~LOGIN_SETGROUP) != 0)
529 log_warn("unable to setusercontext %s: %s",
530 cfg->username, strerror(errno));
531 #endif /* HAVE_SETUSERCONTEXT */
533 #endif /* HAVE_GETPWNAM */
535 /* box into the chroot */
537 if(cfg->chrootdir && cfg->chrootdir[0]) {
538 if(chdir(cfg->chrootdir)) {
539 fatal_exit("unable to chdir to chroot %s: %s",
540 cfg->chrootdir, strerror(errno));
542 verbose(VERB_QUERY, "chdir to %s", cfg->chrootdir);
543 if(chroot(cfg->chrootdir))
544 fatal_exit("unable to chroot to %s: %s",
545 cfg->chrootdir, strerror(errno));
547 fatal_exit("unable to chdir to / in chroot %s: %s",
548 cfg->chrootdir, strerror(errno));
549 verbose(VERB_QUERY, "chroot to %s", cfg->chrootdir);
550 if(strncmp(*cfgfile, cfg->chrootdir,
551 strlen(cfg->chrootdir)) == 0)
552 (*cfgfile) += strlen(cfg->chrootdir);
554 /* adjust stored pidfile for chroot */
555 if(daemon->pidfile && daemon->pidfile[0] &&
556 strncmp(daemon->pidfile, cfg->chrootdir,
557 strlen(cfg->chrootdir))==0) {
558 char* old = daemon->pidfile;
559 daemon->pidfile = strdup(old+strlen(cfg->chrootdir));
562 log_err("out of memory in pidfile adjust");
564 daemon->chroot = strdup(cfg->chrootdir);
566 log_err("out of memory in daemon chroot dir storage");
571 /* change to working directory inside chroot */
572 if(cfg->directory && cfg->directory[0]) {
573 char* dir = cfg->directory;
574 if(cfg->chrootdir && cfg->chrootdir[0] &&
575 strncmp(dir, cfg->chrootdir,
576 strlen(cfg->chrootdir)) == 0)
577 dir += strlen(cfg->chrootdir);
580 fatal_exit("Could not chdir to %s: %s",
581 dir, strerror(errno));
583 verbose(VERB_QUERY, "chdir to %s", dir);
587 /* drop permissions after chroot, getpwnam, pidfile, syslog done*/
589 if(cfg->username && cfg->username[0] && cfg_uid != (uid_t)-1) {
590 # ifdef HAVE_INITGROUPS
591 if(initgroups(cfg->username, cfg_gid) != 0)
592 log_warn("unable to initgroups %s: %s",
593 cfg->username, strerror(errno));
594 # endif /* HAVE_INITGROUPS */
597 #ifdef HAVE_SETRESGID
598 if(setresgid(cfg_gid,cfg_gid,cfg_gid) != 0)
599 #elif defined(HAVE_SETREGID) && !defined(DARWIN_BROKEN_SETREUID)
600 if(setregid(cfg_gid,cfg_gid) != 0)
601 #else /* use setgid */
602 if(setgid(cfg_gid) != 0)
603 #endif /* HAVE_SETRESGID */
604 fatal_exit("unable to set group id of %s: %s",
605 cfg->username, strerror(errno));
606 #ifdef HAVE_SETRESUID
607 if(setresuid(cfg_uid,cfg_uid,cfg_uid) != 0)
608 #elif defined(HAVE_SETREUID) && !defined(DARWIN_BROKEN_SETREUID)
609 if(setreuid(cfg_uid,cfg_uid) != 0)
610 #else /* use setuid */
611 if(setuid(cfg_uid) != 0)
612 #endif /* HAVE_SETRESUID */
613 fatal_exit("unable to set user id of %s: %s",
614 cfg->username, strerror(errno));
615 verbose(VERB_QUERY, "drop user privileges, run as %s",
618 #endif /* HAVE_GETPWNAM */
619 /* file logging inited after chroot,chdir,setuid is done so that
620 * it would succeed on SIGHUP as well */
622 log_init(cfg->logfile, cfg->use_syslog, cfg->chrootdir);
627 * @param cfgfile: the config file name.
628 * @param cmdline_verbose: verbosity resulting from commandline -v.
629 * These increase verbosity as specified in the config file.
630 * @param debug_mode: if set, do not daemonize.
633 run_daemon(const char* cfgfile, int cmdline_verbose, int debug_mode)
635 struct config_file* cfg = NULL;
636 struct daemon* daemon = NULL;
639 if(!(daemon = daemon_init()))
640 fatal_exit("alloc failure");
641 while(!daemon->need_to_exit) {
643 verbose(VERB_OPS, "Restart of %s.", PACKAGE_STRING);
644 else verbose(VERB_OPS, "Start of %s.", PACKAGE_STRING);
647 if(!(cfg = config_create()))
648 fatal_exit("Could not alloc config defaults");
649 if(!config_read(cfg, cfgfile, daemon->chroot)) {
651 fatal_exit("Could not read config file: %s",
653 log_warn("Continuing with default config settings");
655 apply_settings(daemon, cfg, cmdline_verbose, debug_mode);
657 config_lookup_uid(cfg);
660 if(!daemon_open_shared_ports(daemon))
661 fatal_exit("could not open ports");
663 perform_setup(daemon, cfg, debug_mode, &cfgfile);
666 /* reopen log after HUP to facilitate log rotation */
668 log_init(cfg->logfile, 0, cfg->chrootdir);
673 /* clean up for restart */
674 verbose(VERB_ALGO, "cleanup.");
675 daemon_cleanup(daemon);
678 verbose(VERB_ALGO, "Exit cleanup.");
679 /* this unlink may not work if the pidfile is located outside
680 * of the chroot/workdir or we no longer have permissions */
681 if(daemon->pidfile) {
683 /* truncate pidfile */
684 fd = open(daemon->pidfile, O_WRONLY | O_TRUNC, 0644);
688 unlink(daemon->pidfile);
690 daemon_delete(daemon);
693 /** getopt global, in case header files fail to declare it. */
695 /** getopt global, in case header files fail to declare it. */
699 * main program. Set options given commandline arguments.
700 * @param argc: number of commandline arguments.
701 * @param argv: array of commandline arguments.
702 * @return: exit status of the program.
705 main(int argc, char* argv[])
708 const char* cfgfile = CONFIGFILE;
709 const char* winopt = NULL;
710 int cmdline_verbose = 0;
717 /* take debug snapshot of heap */
718 unbound_start_brk = sbrk(0);
721 log_init(NULL, 0, NULL);
722 log_ident_set(strrchr(argv[0],'/')?strrchr(argv[0],'/')+1:argv[0]);
723 /* parse the options */
724 while( (c=getopt(argc, argv, "c:dhvw:")) != -1) {
754 wsvc_command_option(winopt, cfgfile, cmdline_verbose,
757 fatal_exit("option not supported");
766 run_daemon(cfgfile, cmdline_verbose, debug_mode);
767 log_init(NULL, 0, NULL); /* close logfile */