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 static void usage(void)
94 const char *evnm="event", *evsys="", *evmethod="";
97 struct ub_event_base* base;
98 printf("usage: unbound [options]\n");
99 printf(" start unbound daemon DNS resolver.\n");
100 printf("-h this help\n");
101 printf("-c file config file to read instead of %s\n", CONFIGFILE);
102 printf(" file format is described in unbound.conf(5).\n");
103 printf("-d do not fork into the background.\n");
104 printf("-v verbose (more times to increase verbosity)\n");
106 printf("-w opt windows option: \n");
107 printf(" install, remove - manage the services entry\n");
108 printf(" service - used to start from services control panel\n");
110 printf("Version %s\n", PACKAGE_VERSION);
111 base = ub_default_event_base(0,&t,&now);
112 ub_get_event_sys(base, &evnm, &evsys, &evmethod);
113 printf("linked libs: %s %s (it uses %s), %s\n",
114 evnm, evsys, evmethod,
116 # ifdef SSLEAY_VERSION
117 SSLeay_version(SSLEAY_VERSION)
119 OpenSSL_version(OPENSSL_VERSION)
121 #elif defined(HAVE_NSS)
123 #elif defined(HAVE_NETTLE)
127 printf("linked modules:");
128 for(m = module_list_avail(); *m; m++)
131 printf("BSD licensed, see LICENSE in source package for details.\n");
132 printf("Report bugs to %s\n", PACKAGE_BUGREPORT);
133 ub_event_base_free(base);
136 #ifndef unbound_testbound
137 int replay_var_compare(const void* ATTR_UNUSED(a), const void* ATTR_UNUSED(b))
144 /** check file descriptor count */
146 checkrlimits(struct config_file* cfg)
149 #ifdef HAVE_GETRLIMIT
150 /* list has number of ports to listen to, ifs number addresses */
151 int list = ((cfg->do_udp?1:0) + (cfg->do_tcp?1 +
152 (int)cfg->incoming_num_tcp:0));
153 size_t listen_ifs = (size_t)(cfg->num_ifs==0?
154 ((cfg->do_ip4 && !cfg->if_automatic?1:0) +
155 (cfg->do_ip6?1:0)):cfg->num_ifs);
156 size_t listen_num = list*listen_ifs;
157 size_t outudpnum = (size_t)cfg->outgoing_num_ports;
158 size_t outtcpnum = cfg->outgoing_num_tcp;
159 size_t misc = 4; /* logfile, pidfile, stdout... */
160 size_t perthread_noudp = listen_num + outtcpnum +
161 2/*cmdpipe*/ + 2/*libevent*/ + misc;
162 size_t perthread = perthread_noudp + outudpnum;
164 #if !defined(HAVE_PTHREAD) && !defined(HAVE_SOLARIS_THREADS)
165 int numthread = 1; /* it forks */
167 int numthread = (cfg->num_threads?cfg->num_threads:1);
169 size_t total = numthread * perthread + misc;
174 strncmp(ub_event_get_version(), "mini-event", 10) == 0) {
175 log_warn("too many file descriptors requested. The builtin"
176 "mini-event cannot handle more than 1024. Config "
177 "for less fds or compile with libevent");
178 if(numthread*perthread_noudp+15 > 1024)
179 fatal_exit("too much tcp. not enough fds.");
180 cfg->outgoing_num_ports = (int)((1024
181 - numthread*perthread_noudp
182 - 10 /* safety margin */) /numthread);
183 log_warn("continuing with less udp ports: %u",
184 cfg->outgoing_num_ports);
188 strncmp(ub_event_get_version(), "winsock-event", 13) == 0) {
189 log_err("too many file descriptors requested. The winsock"
190 " event handler cannot handle more than 64 per "
191 " thread. Config for less fds");
192 if(perthread_noudp+2 > 64)
193 fatal_exit("too much tcp. not enough fds.");
194 cfg->outgoing_num_ports = (int)((64
196 - 2/* safety margin */));
197 log_warn("continuing with less udp ports: %u",
198 cfg->outgoing_num_ports);
199 total = numthread*(perthread_noudp+
200 (size_t)cfg->outgoing_num_ports)+misc;
202 if(getrlimit(RLIMIT_NOFILE, &rlim) < 0) {
203 log_warn("getrlimit: %s", strerror(errno));
206 if(rlim.rlim_cur == (rlim_t)RLIM_INFINITY)
208 if((size_t)rlim.rlim_cur < total) {
209 avail = (size_t)rlim.rlim_cur;
210 rlim.rlim_cur = (rlim_t)(total + 10);
211 rlim.rlim_max = (rlim_t)(total + 10);
212 #ifdef HAVE_SETRLIMIT
213 if(setrlimit(RLIMIT_NOFILE, &rlim) < 0) {
214 log_warn("setrlimit: %s", strerror(errno));
216 log_warn("cannot increase max open fds from %u to %u",
217 (unsigned)avail, (unsigned)total+10);
218 /* check that calculation below does not underflow,
219 * with 15 as margin */
220 if(numthread*perthread_noudp+15 > avail)
221 fatal_exit("too much tcp. not enough fds.");
222 cfg->outgoing_num_ports = (int)((avail
223 - numthread*perthread_noudp
224 - 10 /* safety margin */) /numthread);
225 log_warn("continuing with less udp ports: %u",
226 cfg->outgoing_num_ports);
227 log_warn("increase ulimit or decrease threads, "
228 "ports in config to remove this warning");
230 #ifdef HAVE_SETRLIMIT
233 verbose(VERB_ALGO, "increased limit(open files) from %u to %u",
234 (unsigned)avail, (unsigned)total+10);
238 #endif /* HAVE_GETRLIMIT */
239 #endif /* S_SPLINT_S */
242 /** set default logfile identity based on value from argv[0] at startup **/
244 log_ident_set_fromdefault(struct config_file* cfg,
245 const char *log_default_identity)
247 if(cfg->log_identity == NULL || cfg->log_identity[0] == 0)
248 log_ident_set(log_default_identity);
250 log_ident_set(cfg->log_identity);
253 /** set verbosity, check rlimits, cache settings */
255 apply_settings(struct daemon* daemon, struct config_file* cfg,
256 int cmdline_verbose, int debug_mode, const char* log_default_identity)
258 /* apply if they have changed */
259 verbosity = cmdline_verbose + cfg->verbosity;
260 if (debug_mode > 1) {
265 daemon_apply_cfg(daemon, cfg);
267 log_ident_set_fromdefault(cfg, log_default_identity);
271 /** Read existing pid from pidfile.
272 * @param file: file name of pid file.
273 * @return: the pid from the file or -1 if none.
276 readpid (const char* file)
284 if ((fd = open(file, O_RDONLY)) == -1) {
286 log_err("Could not read pidfile %s: %s",
287 file, strerror(errno));
291 if (((l = read(fd, pidbuf, sizeof(pidbuf)))) == -1) {
293 log_err("Could not read pidfile %s: %s",
294 file, strerror(errno));
301 /* Empty pidfile means no pidfile... */
306 pidbuf[sizeof(pidbuf)-1] = 0;
307 pid = (pid_t)strtol(pidbuf, &t, 10);
309 if (*t && *t != '\n') {
315 /** write pid to file.
316 * @param pidfile: file name of pid file.
317 * @param pid: pid to write to file.
320 writepid (const char* pidfile, pid_t pid)
324 if ((f = fopen(pidfile, "w")) == NULL ) {
325 log_err("cannot open pidfile %s: %s",
326 pidfile, strerror(errno));
329 if(fprintf(f, "%lu\n", (unsigned long)pid) < 0) {
330 log_err("cannot write to pidfile %s: %s",
331 pidfile, strerror(errno));
337 * check old pid file.
338 * @param pidfile: the file name of the pid file.
339 * @param inchroot: if pidfile is inchroot and we can thus expect to
340 * be able to delete it.
343 checkoldpid(char* pidfile, int inchroot)
346 if((old = readpid(pidfile)) != -1) {
347 /* see if it is still alive */
348 if(kill(old, 0) == 0 || errno == EPERM)
349 log_warn("unbound is already running as pid %u.",
352 log_warn("did not exit gracefully last time (%u)",
356 #endif /* HAVE_KILL */
358 /** detach from command line */
362 #if defined(HAVE_DAEMON) && !defined(DEPRECATED_DAEMON)
363 /* use POSIX daemon(3) function */
364 if(daemon(1, 0) != 0)
365 fatal_exit("daemon failed: %s", strerror(errno));
366 #else /* no HAVE_DAEMON */
374 fatal_exit("fork failed: %s", strerror(errno));
376 /* exit interactive session */
382 fatal_exit("setsid() failed: %s", strerror(errno));
384 if ((fd = open("/dev/null", O_RDWR, 0)) != -1) {
385 (void)dup2(fd, STDIN_FILENO);
386 (void)dup2(fd, STDOUT_FILENO);
387 (void)dup2(fd, STDERR_FILENO);
391 #endif /* HAVE_FORK */
392 #endif /* HAVE_DAEMON */
395 /** daemonize, drop user priviliges and chroot if needed */
397 perform_setup(struct daemon* daemon, struct config_file* cfg, int debug_mode,
398 const char** cfgfile)
404 struct passwd *pwd = NULL;
406 if(cfg->username && cfg->username[0]) {
407 if((pwd = getpwnam(cfg->username)) == NULL)
408 fatal_exit("user '%s' does not exist.", cfg->username);
409 /* endpwent below, in case we need pwd for setusercontext */
413 w_config_adjust_directory(cfg);
416 /* init syslog (as root) if needed, before daemonize, otherwise
417 * a fork error could not be printed since daemonize closed stderr.*/
418 if(cfg->use_syslog) {
419 log_init(cfg->logfile, cfg->use_syslog, cfg->chrootdir);
421 /* if using a logfile, we cannot open it because the logfile would
422 * be created with the wrong permissions, we cannot chown it because
423 * we cannot chown system logfiles, so we do not open at all.
424 * So, using a logfile, the user does not see errors unless -d is
425 * given to unbound on the commandline. */
427 /* read ssl keys while superuser and outside chroot */
429 if(!(daemon->rc = daemon_remote_create(cfg)))
430 fatal_exit("could not set up remote-control");
431 if(cfg->ssl_service_key && cfg->ssl_service_key[0]) {
432 if(!(daemon->listen_sslctx = listen_sslctx_create(
433 cfg->ssl_service_key, cfg->ssl_service_pem, NULL)))
434 fatal_exit("could not set up listen SSL_CTX");
436 if(!(daemon->connect_sslctx = connect_sslctx_create(NULL, NULL, NULL)))
437 fatal_exit("could not set up connect SSL_CTX");
441 /* true if pidfile is inside chrootdir, or nochroot */
442 pidinchroot = !(cfg->chrootdir && cfg->chrootdir[0]) ||
443 (cfg->chrootdir && cfg->chrootdir[0] &&
444 strncmp(cfg->pidfile, cfg->chrootdir,
445 strlen(cfg->chrootdir))==0);
447 /* check old pid file before forking */
448 if(cfg->pidfile && cfg->pidfile[0]) {
449 /* calculate position of pidfile */
450 if(cfg->pidfile[0] == '/')
451 daemon->pidfile = strdup(cfg->pidfile);
452 else daemon->pidfile = fname_after_chroot(cfg->pidfile,
455 fatal_exit("pidfile alloc: out of memory");
456 checkoldpid(daemon->pidfile, pidinchroot);
460 /* daemonize because pid is needed by the writepid func */
461 if(!debug_mode && cfg->do_daemonize) {
465 /* write new pidfile (while still root, so can be outside chroot) */
467 if(cfg->pidfile && cfg->pidfile[0]) {
468 writepid(daemon->pidfile, getpid());
469 if(cfg->username && cfg->username[0] && cfg_uid != (uid_t)-1 &&
472 if(chown(daemon->pidfile, cfg_uid, cfg_gid) == -1) {
473 verbose(VERB_QUERY, "cannot chown %u.%u %s: %s",
474 (unsigned)cfg_uid, (unsigned)cfg_gid,
475 daemon->pidfile, strerror(errno));
477 # endif /* HAVE_CHOWN */
482 #endif /* HAVE_KILL */
484 /* Set user context */
486 if(cfg->username && cfg->username[0] && cfg_uid != (uid_t)-1) {
487 #ifdef HAVE_SETUSERCONTEXT
488 /* setusercontext does initgroups, setuid, setgid, and
489 * also resource limits from login config, but we
490 * still call setresuid, setresgid to be sure to set all uid*/
491 if(setusercontext(NULL, pwd, cfg_uid, (unsigned)
492 LOGIN_SETALL & ~LOGIN_SETUSER & ~LOGIN_SETGROUP) != 0)
493 log_warn("unable to setusercontext %s: %s",
494 cfg->username, strerror(errno));
495 #endif /* HAVE_SETUSERCONTEXT */
497 #endif /* HAVE_GETPWNAM */
499 /* box into the chroot */
501 if(cfg->chrootdir && cfg->chrootdir[0]) {
502 if(chdir(cfg->chrootdir)) {
503 fatal_exit("unable to chdir to chroot %s: %s",
504 cfg->chrootdir, strerror(errno));
506 verbose(VERB_QUERY, "chdir to %s", cfg->chrootdir);
507 if(chroot(cfg->chrootdir))
508 fatal_exit("unable to chroot to %s: %s",
509 cfg->chrootdir, strerror(errno));
511 fatal_exit("unable to chdir to / in chroot %s: %s",
512 cfg->chrootdir, strerror(errno));
513 verbose(VERB_QUERY, "chroot to %s", cfg->chrootdir);
514 if(strncmp(*cfgfile, cfg->chrootdir,
515 strlen(cfg->chrootdir)) == 0)
516 (*cfgfile) += strlen(cfg->chrootdir);
518 /* adjust stored pidfile for chroot */
519 if(daemon->pidfile && daemon->pidfile[0] &&
520 strncmp(daemon->pidfile, cfg->chrootdir,
521 strlen(cfg->chrootdir))==0) {
522 char* old = daemon->pidfile;
523 daemon->pidfile = strdup(old+strlen(cfg->chrootdir));
526 log_err("out of memory in pidfile adjust");
528 daemon->chroot = strdup(cfg->chrootdir);
530 log_err("out of memory in daemon chroot dir storage");
535 /* change to working directory inside chroot */
536 if(cfg->directory && cfg->directory[0]) {
537 char* dir = cfg->directory;
538 if(cfg->chrootdir && cfg->chrootdir[0] &&
539 strncmp(dir, cfg->chrootdir,
540 strlen(cfg->chrootdir)) == 0)
541 dir += strlen(cfg->chrootdir);
544 fatal_exit("Could not chdir to %s: %s",
545 dir, strerror(errno));
547 verbose(VERB_QUERY, "chdir to %s", dir);
551 /* drop permissions after chroot, getpwnam, pidfile, syslog done*/
553 if(cfg->username && cfg->username[0] && cfg_uid != (uid_t)-1) {
554 # ifdef HAVE_INITGROUPS
555 if(initgroups(cfg->username, cfg_gid) != 0)
556 log_warn("unable to initgroups %s: %s",
557 cfg->username, strerror(errno));
558 # endif /* HAVE_INITGROUPS */
559 # ifdef HAVE_ENDPWENT
563 #ifdef HAVE_SETRESGID
564 if(setresgid(cfg_gid,cfg_gid,cfg_gid) != 0)
565 #elif defined(HAVE_SETREGID) && !defined(DARWIN_BROKEN_SETREUID)
566 if(setregid(cfg_gid,cfg_gid) != 0)
567 #else /* use setgid */
568 if(setgid(cfg_gid) != 0)
569 #endif /* HAVE_SETRESGID */
570 fatal_exit("unable to set group id of %s: %s",
571 cfg->username, strerror(errno));
572 #ifdef HAVE_SETRESUID
573 if(setresuid(cfg_uid,cfg_uid,cfg_uid) != 0)
574 #elif defined(HAVE_SETREUID) && !defined(DARWIN_BROKEN_SETREUID)
575 if(setreuid(cfg_uid,cfg_uid) != 0)
576 #else /* use setuid */
577 if(setuid(cfg_uid) != 0)
578 #endif /* HAVE_SETRESUID */
579 fatal_exit("unable to set user id of %s: %s",
580 cfg->username, strerror(errno));
581 verbose(VERB_QUERY, "drop user privileges, run as %s",
584 #endif /* HAVE_GETPWNAM */
585 /* file logging inited after chroot,chdir,setuid is done so that
586 * it would succeed on SIGHUP as well */
588 log_init(cfg->logfile, cfg->use_syslog, cfg->chrootdir);
593 * @param cfgfile: the config file name.
594 * @param cmdline_verbose: verbosity resulting from commandline -v.
595 * These increase verbosity as specified in the config file.
596 * @param debug_mode: if set, do not daemonize.
597 * @param log_default_identity: Default identity to report in logs
600 run_daemon(const char* cfgfile, int cmdline_verbose, int debug_mode, const char* log_default_identity)
602 struct config_file* cfg = NULL;
603 struct daemon* daemon = NULL;
606 if(!(daemon = daemon_init()))
607 fatal_exit("alloc failure");
608 while(!daemon->need_to_exit) {
610 verbose(VERB_OPS, "Restart of %s.", PACKAGE_STRING);
611 else verbose(VERB_OPS, "Start of %s.", PACKAGE_STRING);
614 if(!(cfg = config_create()))
615 fatal_exit("Could not alloc config defaults");
616 if(!config_read(cfg, cfgfile, daemon->chroot)) {
618 fatal_exit("Could not read config file: %s",
620 log_warn("Continuing with default config settings");
622 apply_settings(daemon, cfg, cmdline_verbose, debug_mode, log_default_identity);
624 config_lookup_uid(cfg);
627 if(!daemon_open_shared_ports(daemon))
628 fatal_exit("could not open ports");
630 perform_setup(daemon, cfg, debug_mode, &cfgfile);
633 /* reopen log after HUP to facilitate log rotation */
635 log_init(cfg->logfile, 0, cfg->chrootdir);
640 /* clean up for restart */
641 verbose(VERB_ALGO, "cleanup.");
642 daemon_cleanup(daemon);
645 verbose(VERB_ALGO, "Exit cleanup.");
646 /* this unlink may not work if the pidfile is located outside
647 * of the chroot/workdir or we no longer have permissions */
648 if(daemon->pidfile) {
650 /* truncate pidfile */
651 fd = open(daemon->pidfile, O_WRONLY | O_TRUNC, 0644);
655 unlink(daemon->pidfile);
657 daemon_delete(daemon);
660 /** getopt global, in case header files fail to declare it. */
662 /** getopt global, in case header files fail to declare it. */
666 * main program. Set options given commandline arguments.
667 * @param argc: number of commandline arguments.
668 * @param argv: array of commandline arguments.
669 * @return: exit status of the program.
672 main(int argc, char* argv[])
675 const char* cfgfile = CONFIGFILE;
676 const char* winopt = NULL;
677 const char* log_ident_default;
678 int cmdline_verbose = 0;
684 log_init(NULL, 0, NULL);
685 log_ident_default = strrchr(argv[0],'/')?strrchr(argv[0],'/')+1:argv[0];
686 log_ident_set(log_ident_default);
687 /* parse the options */
688 while( (c=getopt(argc, argv, "c:dhvw:")) != -1) {
718 wsvc_command_option(winopt, cfgfile, cmdline_verbose,
721 fatal_exit("option not supported");
730 run_daemon(cfgfile, cmdline_verbose, debug_mode, log_ident_default);
731 log_init(NULL, 0, NULL); /* close logfile */