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"
90 /** global debug value to keep track of heap memory allocation */
91 void* unbound_start_brk = 0;
93 #if !defined(HAVE_EVENT_BASE_GET_METHOD) && (defined(HAVE_EV_LOOP) || defined(HAVE_EV_DEFAULT_LOOP))
94 static const char* ev_backend2str(int b)
97 case EVBACKEND_SELECT: return "select";
98 case EVBACKEND_POLL: return "poll";
99 case EVBACKEND_EPOLL: return "epoll";
100 case EVBACKEND_KQUEUE: return "kqueue";
101 case EVBACKEND_DEVPOLL: return "devpoll";
102 case EVBACKEND_PORT: return "evport";
108 /** get the event system in use */
109 static void get_event_sys(const char** n, const char** s, const char** m)
114 *m = "WSAWaitForMultipleEvents";
115 #elif defined(USE_MINI_EVENT)
120 struct event_base* b;
121 *s = event_get_version();
122 # ifdef HAVE_EVENT_BASE_GET_METHOD
124 b = event_base_new();
125 *m = event_base_get_method(b);
126 # elif defined(HAVE_EV_LOOP) || defined(HAVE_EV_DEFAULT_LOOP)
128 b = (struct event_base*)ev_default_loop(EVFLAG_AUTO);
129 *m = ev_backend2str(ev_backend((struct ev_loop*)b));
132 *m = "not obtainable";
135 # ifdef HAVE_EVENT_BASE_FREE
145 const char *evnm="event", *evsys="", *evmethod="";
146 printf("usage: unbound [options]\n");
147 printf(" start unbound daemon DNS resolver.\n");
148 printf("-h this help\n");
149 printf("-c file config file to read instead of %s\n", CONFIGFILE);
150 printf(" file format is described in unbound.conf(5).\n");
151 printf("-d do not fork into the background.\n");
152 printf("-v verbose (more times to increase verbosity)\n");
154 printf("-w opt windows option: \n");
155 printf(" install, remove - manage the services entry\n");
156 printf(" service - used to start from services control panel\n");
158 printf("Version %s\n", PACKAGE_VERSION);
159 get_event_sys(&evnm, &evsys, &evmethod);
160 printf("linked libs: %s %s (it uses %s), ldns %s, %s\n",
161 evnm, evsys, evmethod, ldns_version(),
162 SSLeay_version(SSLEAY_VERSION));
163 printf("linked modules:");
164 for(m = module_list_avail(); *m; m++)
167 printf("configured for %s on %s with options:%s\n",
168 CONFIGURE_TARGET, CONFIGURE_DATE, CONFIGURE_BUILD_WITH);
169 printf("BSD licensed, see LICENSE in source package for details.\n");
170 printf("Report bugs to %s\n", PACKAGE_BUGREPORT);
173 #ifndef unbound_testbound
174 int replay_var_compare(const void* ATTR_UNUSED(a), const void* ATTR_UNUSED(b))
181 /** check file descriptor count */
183 checkrlimits(struct config_file* cfg)
185 #ifdef HAVE_GETRLIMIT
186 /* list has number of ports to listen to, ifs number addresses */
187 int list = ((cfg->do_udp?1:0) + (cfg->do_tcp?1 +
188 (int)cfg->incoming_num_tcp:0));
189 size_t listen_ifs = (size_t)(cfg->num_ifs==0?
190 ((cfg->do_ip4 && !cfg->if_automatic?1:0) +
191 (cfg->do_ip6?1:0)):cfg->num_ifs);
192 size_t listen_num = list*listen_ifs;
193 size_t outudpnum = (size_t)cfg->outgoing_num_ports;
194 size_t outtcpnum = cfg->outgoing_num_tcp;
195 size_t misc = 4; /* logfile, pidfile, stdout... */
196 size_t perthread_noudp = listen_num + outtcpnum +
197 2/*cmdpipe*/ + 2/*libevent*/ + misc;
198 size_t perthread = perthread_noudp + outudpnum;
200 #if !defined(HAVE_PTHREAD) && !defined(HAVE_SOLARIS_THREADS)
201 int numthread = 1; /* it forks */
203 int numthread = (cfg->num_threads?cfg->num_threads:1);
205 size_t total = numthread * perthread + misc;
210 strncmp(event_get_version(), "mini-event", 10) == 0) {
211 log_warn("too many file descriptors requested. The builtin"
212 "mini-event cannot handle more than 1024. Config "
213 "for less fds or compile with libevent");
214 if(numthread*perthread_noudp+15 > 1024)
215 fatal_exit("too much tcp. not enough fds.");
216 cfg->outgoing_num_ports = (int)((1024
217 - numthread*perthread_noudp
218 - 10 /* safety margin */) /numthread);
219 log_warn("continuing with less udp ports: %u",
220 cfg->outgoing_num_ports);
224 strncmp(event_get_version(), "winsock-event", 13) == 0) {
225 log_err("too many file descriptors requested. The winsock"
226 " event handler cannot handle more than 64 per "
227 " thread. Config for less fds");
228 if(perthread_noudp+2 > 64)
229 fatal_exit("too much tcp. not enough fds.");
230 cfg->outgoing_num_ports = (int)((64
232 - 2/* safety margin */));
233 log_warn("continuing with less udp ports: %u",
234 cfg->outgoing_num_ports);
235 total = numthread*(perthread_noudp+
236 (size_t)cfg->outgoing_num_ports)+misc;
238 if(getrlimit(RLIMIT_NOFILE, &rlim) < 0) {
239 log_warn("getrlimit: %s", strerror(errno));
242 if(rlim.rlim_cur == (rlim_t)RLIM_INFINITY)
244 if((size_t)rlim.rlim_cur < total) {
245 avail = (size_t)rlim.rlim_cur;
246 rlim.rlim_cur = (rlim_t)(total + 10);
247 rlim.rlim_max = (rlim_t)(total + 10);
248 #ifdef HAVE_SETRLIMIT
249 if(setrlimit(RLIMIT_NOFILE, &rlim) < 0) {
250 log_warn("setrlimit: %s", strerror(errno));
254 log_warn("cannot increase max open fds from %u to %u",
255 (unsigned)avail, (unsigned)total+10);
256 /* check that calculation below does not underflow,
257 * with 15 as margin */
258 if(numthread*perthread_noudp+15 > avail)
259 fatal_exit("too much tcp. not enough fds.");
260 cfg->outgoing_num_ports = (int)((avail
261 - numthread*perthread_noudp
262 - 10 /* safety margin */) /numthread);
263 log_warn("continuing with less udp ports: %u",
264 cfg->outgoing_num_ports);
265 log_warn("increase ulimit or decrease threads, "
266 "ports in config to remove this warning");
269 log_warn("increased limit(open files) from %u to %u",
270 (unsigned)avail, (unsigned)total+10);
274 #endif /* HAVE_GETRLIMIT */
277 /** set verbosity, check rlimits, cache settings */
279 apply_settings(struct daemon* daemon, struct config_file* cfg,
282 /* apply if they have changed */
283 verbosity = cmdline_verbose + cfg->verbosity;
284 daemon_apply_cfg(daemon, cfg);
289 /** Read existing pid from pidfile.
290 * @param file: file name of pid file.
291 * @return: the pid from the file or -1 if none.
294 readpid (const char* file)
302 if ((fd = open(file, O_RDONLY)) == -1) {
304 log_err("Could not read pidfile %s: %s",
305 file, strerror(errno));
309 if (((l = read(fd, pidbuf, sizeof(pidbuf)))) == -1) {
311 log_err("Could not read pidfile %s: %s",
312 file, strerror(errno));
319 /* Empty pidfile means no pidfile... */
324 pidbuf[sizeof(pidbuf)-1] = 0;
325 pid = (pid_t)strtol(pidbuf, &t, 10);
327 if (*t && *t != '\n') {
333 /** write pid to file.
334 * @param pidfile: file name of pid file.
335 * @param pid: pid to write to file.
338 writepid (const char* pidfile, pid_t pid)
342 if ((f = fopen(pidfile, "w")) == NULL ) {
343 log_err("cannot open pidfile %s: %s",
344 pidfile, strerror(errno));
347 if(fprintf(f, "%lu\n", (unsigned long)pid) < 0) {
348 log_err("cannot write to pidfile %s: %s",
349 pidfile, strerror(errno));
355 * check old pid file.
356 * @param pidfile: the file name of the pid file.
357 * @param inchroot: if pidfile is inchroot and we can thus expect to
358 * be able to delete it.
361 checkoldpid(char* pidfile, int inchroot)
364 if((old = readpid(pidfile)) != -1) {
365 /* see if it is still alive */
366 if(kill(old, 0) == 0 || errno == EPERM)
367 log_warn("unbound is already running as pid %u.",
370 log_warn("did not exit gracefully last time (%u)",
374 #endif /* HAVE_KILL */
376 /** detach from command line */
380 #if defined(HAVE_DAEMON) && !defined(DEPRECATED_DAEMON)
381 /* use POSIX daemon(3) function */
382 if(daemon(1, 0) != 0)
383 fatal_exit("daemon failed: %s", strerror(errno));
384 #else /* no HAVE_DAEMON */
392 fatal_exit("fork failed: %s", strerror(errno));
394 /* exit interactive session */
400 fatal_exit("setsid() failed: %s", strerror(errno));
402 if ((fd = open("/dev/null", O_RDWR, 0)) != -1) {
403 (void)dup2(fd, STDIN_FILENO);
404 (void)dup2(fd, STDOUT_FILENO);
405 (void)dup2(fd, STDERR_FILENO);
409 #endif /* HAVE_FORK */
410 #endif /* HAVE_DAEMON */
413 /** daemonize, drop user priviliges and chroot if needed */
415 perform_setup(struct daemon* daemon, struct config_file* cfg, int debug_mode,
416 const char** cfgfile)
419 struct passwd *pwd = NULL;
422 /* initialize, but not to 0 (root) */
423 memset(&uid, 112, sizeof(uid));
424 memset(&gid, 112, sizeof(gid));
427 if(cfg->username && cfg->username[0]) {
428 if((pwd = getpwnam(cfg->username)) == NULL)
429 fatal_exit("user '%s' does not exist.", cfg->username);
432 /* endpwent below, in case we need pwd for setusercontext */
436 /* init syslog (as root) if needed, before daemonize, otherwise
437 * a fork error could not be printed since daemonize closed stderr.*/
438 if(cfg->use_syslog) {
439 log_init(cfg->logfile, cfg->use_syslog, cfg->chrootdir);
441 /* if using a logfile, we cannot open it because the logfile would
442 * be created with the wrong permissions, we cannot chown it because
443 * we cannot chown system logfiles, so we do not open at all.
444 * So, using a logfile, the user does not see errors unless -d is
445 * given to unbound on the commandline. */
447 /* read ssl keys while superuser and outside chroot */
448 if(!(daemon->rc = daemon_remote_create(cfg)))
449 fatal_exit("could not set up remote-control");
450 if(cfg->ssl_service_key && cfg->ssl_service_key[0]) {
451 if(!(daemon->listen_sslctx = listen_sslctx_create(
452 cfg->ssl_service_key, cfg->ssl_service_pem, NULL)))
453 fatal_exit("could not set up listen SSL_CTX");
455 if(!(daemon->connect_sslctx = connect_sslctx_create(NULL, NULL, NULL)))
456 fatal_exit("could not set up connect SSL_CTX");
459 /* check old pid file before forking */
460 if(cfg->pidfile && cfg->pidfile[0]) {
461 /* calculate position of pidfile */
462 if(cfg->pidfile[0] == '/')
463 daemon->pidfile = strdup(cfg->pidfile);
464 else daemon->pidfile = fname_after_chroot(cfg->pidfile,
467 fatal_exit("pidfile alloc: out of memory");
468 checkoldpid(daemon->pidfile,
469 /* true if pidfile is inside chrootdir, or nochroot */
470 !(cfg->chrootdir && cfg->chrootdir[0]) ||
471 (cfg->chrootdir && cfg->chrootdir[0] &&
472 strncmp(daemon->pidfile, cfg->chrootdir,
473 strlen(cfg->chrootdir))==0));
477 /* daemonize because pid is needed by the writepid func */
478 if(!debug_mode && cfg->do_daemonize) {
482 /* write new pidfile (while still root, so can be outside chroot) */
484 if(cfg->pidfile && cfg->pidfile[0]) {
485 writepid(daemon->pidfile, getpid());
486 if(!(cfg->chrootdir && cfg->chrootdir[0]) ||
487 (cfg->chrootdir && cfg->chrootdir[0] &&
488 strncmp(daemon->pidfile, cfg->chrootdir,
489 strlen(cfg->chrootdir))==0)) {
490 /* delete of pidfile could potentially work,
491 * chown to get permissions */
492 if(cfg->username && cfg->username[0]) {
493 if(chown(daemon->pidfile, uid, gid) == -1) {
494 log_err("cannot chown %u.%u %s: %s",
495 (unsigned)uid, (unsigned)gid,
496 daemon->pidfile, strerror(errno));
505 /* Set user context */
507 if(cfg->username && cfg->username[0]) {
508 #ifdef HAVE_SETUSERCONTEXT
509 /* setusercontext does initgroups, setuid, setgid, and
510 * also resource limits from login config, but we
511 * still call setresuid, setresgid to be sure to set all uid*/
512 if(setusercontext(NULL, pwd, uid,
513 LOGIN_SETALL & ~LOGIN_SETUSER & ~LOGIN_SETGROUP) != 0)
514 log_warn("unable to setusercontext %s: %s",
515 cfg->username, strerror(errno));
516 #endif /* HAVE_SETUSERCONTEXT */
518 #endif /* HAVE_GETPWNAM */
520 /* box into the chroot */
522 if(cfg->chrootdir && cfg->chrootdir[0]) {
523 if(chdir(cfg->chrootdir)) {
524 fatal_exit("unable to chdir to chroot %s: %s",
525 cfg->chrootdir, strerror(errno));
527 verbose(VERB_QUERY, "chdir to %s", cfg->chrootdir);
528 if(chroot(cfg->chrootdir))
529 fatal_exit("unable to chroot to %s: %s",
530 cfg->chrootdir, strerror(errno));
531 verbose(VERB_QUERY, "chroot to %s", cfg->chrootdir);
532 if(strncmp(*cfgfile, cfg->chrootdir,
533 strlen(cfg->chrootdir)) == 0)
534 (*cfgfile) += strlen(cfg->chrootdir);
536 /* adjust stored pidfile for chroot */
537 if(daemon->pidfile && daemon->pidfile[0] &&
538 strncmp(daemon->pidfile, cfg->chrootdir,
539 strlen(cfg->chrootdir))==0) {
540 char* old = daemon->pidfile;
541 daemon->pidfile = strdup(old+strlen(cfg->chrootdir));
544 log_err("out of memory in pidfile adjust");
546 daemon->chroot = strdup(cfg->chrootdir);
548 log_err("out of memory in daemon chroot dir storage");
553 /* change to working directory inside chroot */
554 if(cfg->directory && cfg->directory[0]) {
555 char* dir = cfg->directory;
556 if(cfg->chrootdir && cfg->chrootdir[0] &&
557 strncmp(dir, cfg->chrootdir,
558 strlen(cfg->chrootdir)) == 0)
559 dir += strlen(cfg->chrootdir);
562 fatal_exit("Could not chdir to %s: %s",
563 dir, strerror(errno));
565 verbose(VERB_QUERY, "chdir to %s", dir);
569 /* drop permissions after chroot, getpwnam, pidfile, syslog done*/
571 if(cfg->username && cfg->username[0]) {
572 # ifdef HAVE_INITGROUPS
573 if(initgroups(cfg->username, gid) != 0)
574 log_warn("unable to initgroups %s: %s",
575 cfg->username, strerror(errno));
576 # endif /* HAVE_INITGROUPS */
579 #ifdef HAVE_SETRESGID
580 if(setresgid(gid,gid,gid) != 0)
581 #elif defined(HAVE_SETREGID) && !defined(DARWIN_BROKEN_SETREUID)
582 if(setregid(gid,gid) != 0)
583 #else /* use setgid */
585 #endif /* HAVE_SETRESGID */
586 fatal_exit("unable to set group id of %s: %s",
587 cfg->username, strerror(errno));
588 #ifdef HAVE_SETRESUID
589 if(setresuid(uid,uid,uid) != 0)
590 #elif defined(HAVE_SETREUID) && !defined(DARWIN_BROKEN_SETREUID)
591 if(setreuid(uid,uid) != 0)
592 #else /* use setuid */
594 #endif /* HAVE_SETRESUID */
595 fatal_exit("unable to set user id of %s: %s",
596 cfg->username, strerror(errno));
597 verbose(VERB_QUERY, "drop user privileges, run as %s",
600 #endif /* HAVE_GETPWNAM */
601 /* file logging inited after chroot,chdir,setuid is done so that
602 * it would succeed on SIGHUP as well */
604 log_init(cfg->logfile, cfg->use_syslog, cfg->chrootdir);
609 * @param cfgfile: the config file name.
610 * @param cmdline_verbose: verbosity resulting from commandline -v.
611 * These increase verbosity as specified in the config file.
612 * @param debug_mode: if set, do not daemonize.
615 run_daemon(const char* cfgfile, int cmdline_verbose, int debug_mode)
617 struct config_file* cfg = NULL;
618 struct daemon* daemon = NULL;
621 if(!(daemon = daemon_init()))
622 fatal_exit("alloc failure");
623 while(!daemon->need_to_exit) {
625 verbose(VERB_OPS, "Restart of %s.", PACKAGE_STRING);
626 else verbose(VERB_OPS, "Start of %s.", PACKAGE_STRING);
629 if(!(cfg = config_create()))
630 fatal_exit("Could not alloc config defaults");
631 if(!config_read(cfg, cfgfile, daemon->chroot)) {
633 fatal_exit("Could not read config file: %s",
635 log_warn("Continuing with default config settings");
637 apply_settings(daemon, cfg, cmdline_verbose);
640 if(!daemon_open_shared_ports(daemon))
641 fatal_exit("could not open ports");
643 perform_setup(daemon, cfg, debug_mode, &cfgfile);
646 /* reopen log after HUP to facilitate log rotation */
648 log_init(cfg->logfile, 0, cfg->chrootdir);
653 /* clean up for restart */
654 verbose(VERB_ALGO, "cleanup.");
655 daemon_cleanup(daemon);
658 verbose(VERB_ALGO, "Exit cleanup.");
659 /* this unlink may not work if the pidfile is located outside
660 * of the chroot/workdir or we no longer have permissions */
661 if(daemon->pidfile) {
663 /* truncate pidfile */
664 fd = open(daemon->pidfile, O_WRONLY | O_TRUNC, 0644);
668 unlink(daemon->pidfile);
670 daemon_delete(daemon);
673 /** getopt global, in case header files fail to declare it. */
675 /** getopt global, in case header files fail to declare it. */
679 * main program. Set options given commandline arguments.
680 * @param argc: number of commandline arguments.
681 * @param argv: array of commandline arguments.
682 * @return: exit status of the program.
685 main(int argc, char* argv[])
688 const char* cfgfile = CONFIGFILE;
689 const char* winopt = NULL;
690 int cmdline_verbose = 0;
697 /* take debug snapshot of heap */
698 unbound_start_brk = sbrk(0);
701 log_init(NULL, 0, NULL);
702 /* parse the options */
703 while( (c=getopt(argc, argv, "c:dhvw:")) != -1) {
733 wsvc_command_option(winopt, cfgfile, cmdline_verbose,
736 fatal_exit("option not supported");
745 run_daemon(cfgfile, cmdline_verbose, debug_mode);
746 log_init(NULL, 0, NULL); /* close logfile */