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"
60 #include "util/ub_event.h"
63 #include <openssl/crypto.h>
72 /* splint chokes on this system header file */
73 #ifdef HAVE_SYS_RESOURCE_H
74 #include <sys/resource.h>
76 #endif /* S_SPLINT_S */
77 #ifdef HAVE_LOGIN_CAP_H
78 #include <login_cap.h>
82 # include "winrc/win_svc.h"
91 /** global debug value to keep track of heap memory allocation */
92 void* unbound_start_brk = 0;
96 static void usage(void)
99 const char *evnm="event", *evsys="", *evmethod="";
102 struct ub_event_base* base;
103 printf("usage: unbound [options]\n");
104 printf(" start unbound daemon DNS resolver.\n");
105 printf("-h this help\n");
106 printf("-c file config file to read instead of %s\n", CONFIGFILE);
107 printf(" file format is described in unbound.conf(5).\n");
108 printf("-d do not fork into the background.\n");
109 printf("-v verbose (more times to increase verbosity)\n");
111 printf("-w opt windows option: \n");
112 printf(" install, remove - manage the services entry\n");
113 printf(" service - used to start from services control panel\n");
115 printf("Version %s\n", PACKAGE_VERSION);
116 base = ub_default_event_base(0,&t,&now);
117 ub_get_event_sys(base, &evnm, &evsys, &evmethod);
118 printf("linked libs: %s %s (it uses %s), %s\n",
119 evnm, evsys, evmethod,
121 # ifdef SSLEAY_VERSION
122 SSLeay_version(SSLEAY_VERSION)
124 OpenSSL_version(OPENSSL_VERSION)
126 #elif defined(HAVE_NSS)
128 #elif defined(HAVE_NETTLE)
132 printf("linked modules:");
133 for(m = module_list_avail(); *m; m++)
136 printf("BSD licensed, see LICENSE in source package for details.\n");
137 printf("Report bugs to %s\n", PACKAGE_BUGREPORT);
138 ub_event_base_free(base);
141 #ifndef unbound_testbound
142 int replay_var_compare(const void* ATTR_UNUSED(a), const void* ATTR_UNUSED(b))
149 /** check file descriptor count */
151 checkrlimits(struct config_file* cfg)
154 #ifdef HAVE_GETRLIMIT
155 /* list has number of ports to listen to, ifs number addresses */
156 int list = ((cfg->do_udp?1:0) + (cfg->do_tcp?1 +
157 (int)cfg->incoming_num_tcp:0));
158 size_t listen_ifs = (size_t)(cfg->num_ifs==0?
159 ((cfg->do_ip4 && !cfg->if_automatic?1:0) +
160 (cfg->do_ip6?1:0)):cfg->num_ifs);
161 size_t listen_num = list*listen_ifs;
162 size_t outudpnum = (size_t)cfg->outgoing_num_ports;
163 size_t outtcpnum = cfg->outgoing_num_tcp;
164 size_t misc = 4; /* logfile, pidfile, stdout... */
165 size_t perthread_noudp = listen_num + outtcpnum +
166 2/*cmdpipe*/ + 2/*libevent*/ + misc;
167 size_t perthread = perthread_noudp + outudpnum;
169 #if !defined(HAVE_PTHREAD) && !defined(HAVE_SOLARIS_THREADS)
170 int numthread = 1; /* it forks */
172 int numthread = (cfg->num_threads?cfg->num_threads:1);
174 size_t total = numthread * perthread + misc;
179 strncmp(ub_event_get_version(), "mini-event", 10) == 0) {
180 log_warn("too many file descriptors requested. The builtin"
181 "mini-event cannot handle more than 1024. Config "
182 "for less fds or compile with libevent");
183 if(numthread*perthread_noudp+15 > 1024)
184 fatal_exit("too much tcp. not enough fds.");
185 cfg->outgoing_num_ports = (int)((1024
186 - numthread*perthread_noudp
187 - 10 /* safety margin */) /numthread);
188 log_warn("continuing with less udp ports: %u",
189 cfg->outgoing_num_ports);
193 strncmp(ub_event_get_version(), "winsock-event", 13) == 0) {
194 log_err("too many file descriptors requested. The winsock"
195 " event handler cannot handle more than 64 per "
196 " thread. Config for less fds");
197 if(perthread_noudp+2 > 64)
198 fatal_exit("too much tcp. not enough fds.");
199 cfg->outgoing_num_ports = (int)((64
201 - 2/* safety margin */));
202 log_warn("continuing with less udp ports: %u",
203 cfg->outgoing_num_ports);
204 total = numthread*(perthread_noudp+
205 (size_t)cfg->outgoing_num_ports)+misc;
207 if(getrlimit(RLIMIT_NOFILE, &rlim) < 0) {
208 log_warn("getrlimit: %s", strerror(errno));
211 if(rlim.rlim_cur == (rlim_t)RLIM_INFINITY)
213 if((size_t)rlim.rlim_cur < total) {
214 avail = (size_t)rlim.rlim_cur;
215 rlim.rlim_cur = (rlim_t)(total + 10);
216 rlim.rlim_max = (rlim_t)(total + 10);
217 #ifdef HAVE_SETRLIMIT
218 if(setrlimit(RLIMIT_NOFILE, &rlim) < 0) {
219 log_warn("setrlimit: %s", strerror(errno));
221 log_warn("cannot increase max open fds from %u to %u",
222 (unsigned)avail, (unsigned)total+10);
223 /* check that calculation below does not underflow,
224 * with 15 as margin */
225 if(numthread*perthread_noudp+15 > avail)
226 fatal_exit("too much tcp. not enough fds.");
227 cfg->outgoing_num_ports = (int)((avail
228 - numthread*perthread_noudp
229 - 10 /* safety margin */) /numthread);
230 log_warn("continuing with less udp ports: %u",
231 cfg->outgoing_num_ports);
232 log_warn("increase ulimit or decrease threads, "
233 "ports in config to remove this warning");
235 #ifdef HAVE_SETRLIMIT
238 verbose(VERB_ALGO, "increased limit(open files) from %u to %u",
239 (unsigned)avail, (unsigned)total+10);
243 #endif /* HAVE_GETRLIMIT */
244 #endif /* S_SPLINT_S */
247 /** set verbosity, check rlimits, cache settings */
249 apply_settings(struct daemon* daemon, struct config_file* cfg,
250 int cmdline_verbose, int debug_mode)
252 /* apply if they have changed */
253 verbosity = cmdline_verbose + cfg->verbosity;
254 if (debug_mode > 1) {
258 daemon_apply_cfg(daemon, cfg);
263 /** Read existing pid from pidfile.
264 * @param file: file name of pid file.
265 * @return: the pid from the file or -1 if none.
268 readpid (const char* file)
276 if ((fd = open(file, O_RDONLY)) == -1) {
278 log_err("Could not read pidfile %s: %s",
279 file, strerror(errno));
283 if (((l = read(fd, pidbuf, sizeof(pidbuf)))) == -1) {
285 log_err("Could not read pidfile %s: %s",
286 file, strerror(errno));
293 /* Empty pidfile means no pidfile... */
298 pidbuf[sizeof(pidbuf)-1] = 0;
299 pid = (pid_t)strtol(pidbuf, &t, 10);
301 if (*t && *t != '\n') {
307 /** write pid to file.
308 * @param pidfile: file name of pid file.
309 * @param pid: pid to write to file.
312 writepid (const char* pidfile, pid_t pid)
316 if ((f = fopen(pidfile, "w")) == NULL ) {
317 log_err("cannot open pidfile %s: %s",
318 pidfile, strerror(errno));
321 if(fprintf(f, "%lu\n", (unsigned long)pid) < 0) {
322 log_err("cannot write to pidfile %s: %s",
323 pidfile, strerror(errno));
329 * check old pid file.
330 * @param pidfile: the file name of the pid file.
331 * @param inchroot: if pidfile is inchroot and we can thus expect to
332 * be able to delete it.
335 checkoldpid(char* pidfile, int inchroot)
338 if((old = readpid(pidfile)) != -1) {
339 /* see if it is still alive */
340 if(kill(old, 0) == 0 || errno == EPERM)
341 log_warn("unbound is already running as pid %u.",
344 log_warn("did not exit gracefully last time (%u)",
348 #endif /* HAVE_KILL */
350 /** detach from command line */
354 #if defined(HAVE_DAEMON) && !defined(DEPRECATED_DAEMON)
355 /* use POSIX daemon(3) function */
356 if(daemon(1, 0) != 0)
357 fatal_exit("daemon failed: %s", strerror(errno));
358 #else /* no HAVE_DAEMON */
366 fatal_exit("fork failed: %s", strerror(errno));
368 /* exit interactive session */
374 fatal_exit("setsid() failed: %s", strerror(errno));
376 if ((fd = open("/dev/null", O_RDWR, 0)) != -1) {
377 (void)dup2(fd, STDIN_FILENO);
378 (void)dup2(fd, STDOUT_FILENO);
379 (void)dup2(fd, STDERR_FILENO);
383 #endif /* HAVE_FORK */
384 #endif /* HAVE_DAEMON */
387 /** daemonize, drop user priviliges and chroot if needed */
389 perform_setup(struct daemon* daemon, struct config_file* cfg, int debug_mode,
390 const char** cfgfile)
396 struct passwd *pwd = NULL;
398 if(cfg->username && cfg->username[0]) {
399 if((pwd = getpwnam(cfg->username)) == NULL)
400 fatal_exit("user '%s' does not exist.", cfg->username);
401 /* endpwent below, in case we need pwd for setusercontext */
405 w_config_adjust_directory(cfg);
408 /* init syslog (as root) if needed, before daemonize, otherwise
409 * a fork error could not be printed since daemonize closed stderr.*/
410 if(cfg->use_syslog) {
411 log_init(cfg->logfile, cfg->use_syslog, cfg->chrootdir);
413 /* if using a logfile, we cannot open it because the logfile would
414 * be created with the wrong permissions, we cannot chown it because
415 * we cannot chown system logfiles, so we do not open at all.
416 * So, using a logfile, the user does not see errors unless -d is
417 * given to unbound on the commandline. */
419 /* read ssl keys while superuser and outside chroot */
421 if(!(daemon->rc = daemon_remote_create(cfg)))
422 fatal_exit("could not set up remote-control");
423 if(cfg->ssl_service_key && cfg->ssl_service_key[0]) {
424 if(!(daemon->listen_sslctx = listen_sslctx_create(
425 cfg->ssl_service_key, cfg->ssl_service_pem, NULL)))
426 fatal_exit("could not set up listen SSL_CTX");
428 if(!(daemon->connect_sslctx = connect_sslctx_create(NULL, NULL, NULL)))
429 fatal_exit("could not set up connect SSL_CTX");
433 /* true if pidfile is inside chrootdir, or nochroot */
434 pidinchroot = !(cfg->chrootdir && cfg->chrootdir[0]) ||
435 (cfg->chrootdir && cfg->chrootdir[0] &&
436 strncmp(cfg->pidfile, cfg->chrootdir,
437 strlen(cfg->chrootdir))==0);
439 /* check old pid file before forking */
440 if(cfg->pidfile && cfg->pidfile[0]) {
441 /* calculate position of pidfile */
442 if(cfg->pidfile[0] == '/')
443 daemon->pidfile = strdup(cfg->pidfile);
444 else daemon->pidfile = fname_after_chroot(cfg->pidfile,
447 fatal_exit("pidfile alloc: out of memory");
448 checkoldpid(daemon->pidfile, pidinchroot);
452 /* daemonize because pid is needed by the writepid func */
453 if(!debug_mode && cfg->do_daemonize) {
457 /* write new pidfile (while still root, so can be outside chroot) */
459 if(cfg->pidfile && cfg->pidfile[0]) {
460 writepid(daemon->pidfile, getpid());
461 if(cfg->username && cfg->username[0] && cfg_uid != (uid_t)-1 &&
464 if(chown(daemon->pidfile, cfg_uid, cfg_gid) == -1) {
465 verbose(VERB_QUERY, "cannot chown %u.%u %s: %s",
466 (unsigned)cfg_uid, (unsigned)cfg_gid,
467 daemon->pidfile, strerror(errno));
469 # endif /* HAVE_CHOWN */
474 #endif /* HAVE_KILL */
476 /* Set user context */
478 if(cfg->username && cfg->username[0] && cfg_uid != (uid_t)-1) {
479 #ifdef HAVE_SETUSERCONTEXT
480 /* setusercontext does initgroups, setuid, setgid, and
481 * also resource limits from login config, but we
482 * still call setresuid, setresgid to be sure to set all uid*/
483 if(setusercontext(NULL, pwd, cfg_uid, (unsigned)
484 LOGIN_SETALL & ~LOGIN_SETUSER & ~LOGIN_SETGROUP) != 0)
485 log_warn("unable to setusercontext %s: %s",
486 cfg->username, strerror(errno));
487 #endif /* HAVE_SETUSERCONTEXT */
489 #endif /* HAVE_GETPWNAM */
491 /* box into the chroot */
493 if(cfg->chrootdir && cfg->chrootdir[0]) {
494 if(chdir(cfg->chrootdir)) {
495 fatal_exit("unable to chdir to chroot %s: %s",
496 cfg->chrootdir, strerror(errno));
498 verbose(VERB_QUERY, "chdir to %s", cfg->chrootdir);
499 if(chroot(cfg->chrootdir))
500 fatal_exit("unable to chroot to %s: %s",
501 cfg->chrootdir, strerror(errno));
503 fatal_exit("unable to chdir to / in chroot %s: %s",
504 cfg->chrootdir, strerror(errno));
505 verbose(VERB_QUERY, "chroot to %s", cfg->chrootdir);
506 if(strncmp(*cfgfile, cfg->chrootdir,
507 strlen(cfg->chrootdir)) == 0)
508 (*cfgfile) += strlen(cfg->chrootdir);
510 /* adjust stored pidfile for chroot */
511 if(daemon->pidfile && daemon->pidfile[0] &&
512 strncmp(daemon->pidfile, cfg->chrootdir,
513 strlen(cfg->chrootdir))==0) {
514 char* old = daemon->pidfile;
515 daemon->pidfile = strdup(old+strlen(cfg->chrootdir));
518 log_err("out of memory in pidfile adjust");
520 daemon->chroot = strdup(cfg->chrootdir);
522 log_err("out of memory in daemon chroot dir storage");
527 /* change to working directory inside chroot */
528 if(cfg->directory && cfg->directory[0]) {
529 char* dir = cfg->directory;
530 if(cfg->chrootdir && cfg->chrootdir[0] &&
531 strncmp(dir, cfg->chrootdir,
532 strlen(cfg->chrootdir)) == 0)
533 dir += strlen(cfg->chrootdir);
536 fatal_exit("Could not chdir to %s: %s",
537 dir, strerror(errno));
539 verbose(VERB_QUERY, "chdir to %s", dir);
543 /* drop permissions after chroot, getpwnam, pidfile, syslog done*/
545 if(cfg->username && cfg->username[0] && cfg_uid != (uid_t)-1) {
546 # ifdef HAVE_INITGROUPS
547 if(initgroups(cfg->username, cfg_gid) != 0)
548 log_warn("unable to initgroups %s: %s",
549 cfg->username, strerror(errno));
550 # endif /* HAVE_INITGROUPS */
551 # ifdef HAVE_ENDPWENT
555 #ifdef HAVE_SETRESGID
556 if(setresgid(cfg_gid,cfg_gid,cfg_gid) != 0)
557 #elif defined(HAVE_SETREGID) && !defined(DARWIN_BROKEN_SETREUID)
558 if(setregid(cfg_gid,cfg_gid) != 0)
559 #else /* use setgid */
560 if(setgid(cfg_gid) != 0)
561 #endif /* HAVE_SETRESGID */
562 fatal_exit("unable to set group id of %s: %s",
563 cfg->username, strerror(errno));
564 #ifdef HAVE_SETRESUID
565 if(setresuid(cfg_uid,cfg_uid,cfg_uid) != 0)
566 #elif defined(HAVE_SETREUID) && !defined(DARWIN_BROKEN_SETREUID)
567 if(setreuid(cfg_uid,cfg_uid) != 0)
568 #else /* use setuid */
569 if(setuid(cfg_uid) != 0)
570 #endif /* HAVE_SETRESUID */
571 fatal_exit("unable to set user id of %s: %s",
572 cfg->username, strerror(errno));
573 verbose(VERB_QUERY, "drop user privileges, run as %s",
576 #endif /* HAVE_GETPWNAM */
577 /* file logging inited after chroot,chdir,setuid is done so that
578 * it would succeed on SIGHUP as well */
580 log_init(cfg->logfile, cfg->use_syslog, cfg->chrootdir);
585 * @param cfgfile: the config file name.
586 * @param cmdline_verbose: verbosity resulting from commandline -v.
587 * These increase verbosity as specified in the config file.
588 * @param debug_mode: if set, do not daemonize.
591 run_daemon(const char* cfgfile, int cmdline_verbose, int debug_mode)
593 struct config_file* cfg = NULL;
594 struct daemon* daemon = NULL;
597 if(!(daemon = daemon_init()))
598 fatal_exit("alloc failure");
599 while(!daemon->need_to_exit) {
601 verbose(VERB_OPS, "Restart of %s.", PACKAGE_STRING);
602 else verbose(VERB_OPS, "Start of %s.", PACKAGE_STRING);
605 if(!(cfg = config_create()))
606 fatal_exit("Could not alloc config defaults");
607 if(!config_read(cfg, cfgfile, daemon->chroot)) {
609 fatal_exit("Could not read config file: %s",
611 log_warn("Continuing with default config settings");
613 apply_settings(daemon, cfg, cmdline_verbose, debug_mode);
615 config_lookup_uid(cfg);
618 if(!daemon_open_shared_ports(daemon))
619 fatal_exit("could not open ports");
621 perform_setup(daemon, cfg, debug_mode, &cfgfile);
624 /* reopen log after HUP to facilitate log rotation */
626 log_init(cfg->logfile, 0, cfg->chrootdir);
631 /* clean up for restart */
632 verbose(VERB_ALGO, "cleanup.");
633 daemon_cleanup(daemon);
636 verbose(VERB_ALGO, "Exit cleanup.");
637 /* this unlink may not work if the pidfile is located outside
638 * of the chroot/workdir or we no longer have permissions */
639 if(daemon->pidfile) {
641 /* truncate pidfile */
642 fd = open(daemon->pidfile, O_WRONLY | O_TRUNC, 0644);
646 unlink(daemon->pidfile);
648 daemon_delete(daemon);
651 /** getopt global, in case header files fail to declare it. */
653 /** getopt global, in case header files fail to declare it. */
657 * main program. Set options given commandline arguments.
658 * @param argc: number of commandline arguments.
659 * @param argv: array of commandline arguments.
660 * @return: exit status of the program.
663 main(int argc, char* argv[])
666 const char* cfgfile = CONFIGFILE;
667 const char* winopt = NULL;
668 int cmdline_verbose = 0;
675 /* take debug snapshot of heap */
676 unbound_start_brk = sbrk(0);
679 log_init(NULL, 0, NULL);
680 log_ident_set(strrchr(argv[0],'/')?strrchr(argv[0],'/')+1:argv[0]);
681 /* parse the options */
682 while( (c=getopt(argc, argv, "c:dhvw:")) != -1) {
712 wsvc_command_option(winopt, cfgfile, cmdline_verbose,
715 fatal_exit("option not supported");
724 run_daemon(cfgfile, cmdline_verbose, debug_mode);
725 log_init(NULL, 0, NULL); /* close logfile */