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++)
132 printf("DNSCrypt feature available\n");
134 printf("BSD licensed, see LICENSE in source package for details.\n");
135 printf("Report bugs to %s\n", PACKAGE_BUGREPORT);
136 ub_event_base_free(base);
139 #ifndef unbound_testbound
140 int replay_var_compare(const void* ATTR_UNUSED(a), const void* ATTR_UNUSED(b))
147 /** check file descriptor count */
149 checkrlimits(struct config_file* cfg)
152 #ifdef HAVE_GETRLIMIT
153 /* list has number of ports to listen to, ifs number addresses */
154 int list = ((cfg->do_udp?1:0) + (cfg->do_tcp?1 +
155 (int)cfg->incoming_num_tcp:0));
156 size_t listen_ifs = (size_t)(cfg->num_ifs==0?
157 ((cfg->do_ip4 && !cfg->if_automatic?1:0) +
158 (cfg->do_ip6?1:0)):cfg->num_ifs);
159 size_t listen_num = list*listen_ifs;
160 size_t outudpnum = (size_t)cfg->outgoing_num_ports;
161 size_t outtcpnum = cfg->outgoing_num_tcp;
162 size_t misc = 4; /* logfile, pidfile, stdout... */
163 size_t perthread_noudp = listen_num + outtcpnum +
164 2/*cmdpipe*/ + 2/*libevent*/ + misc;
165 size_t perthread = perthread_noudp + outudpnum;
167 #if !defined(HAVE_PTHREAD) && !defined(HAVE_SOLARIS_THREADS)
168 int numthread = 1; /* it forks */
170 int numthread = (cfg->num_threads?cfg->num_threads:1);
172 size_t total = numthread * perthread + misc;
177 strncmp(ub_event_get_version(), "mini-event", 10) == 0) {
178 log_warn("too many file descriptors requested. The builtin"
179 "mini-event cannot handle more than 1024. Config "
180 "for less fds or compile with libevent");
181 if(numthread*perthread_noudp+15 > 1024)
182 fatal_exit("too much tcp. not enough fds.");
183 cfg->outgoing_num_ports = (int)((1024
184 - numthread*perthread_noudp
185 - 10 /* safety margin */) /numthread);
186 log_warn("continuing with less udp ports: %u",
187 cfg->outgoing_num_ports);
191 strncmp(ub_event_get_version(), "winsock-event", 13) == 0) {
192 log_err("too many file descriptors requested. The winsock"
193 " event handler cannot handle more than 64 per "
194 " thread. Config for less fds");
195 if(perthread_noudp+2 > 64)
196 fatal_exit("too much tcp. not enough fds.");
197 cfg->outgoing_num_ports = (int)((64
199 - 2/* safety margin */));
200 log_warn("continuing with less udp ports: %u",
201 cfg->outgoing_num_ports);
202 total = numthread*(perthread_noudp+
203 (size_t)cfg->outgoing_num_ports)+misc;
205 if(getrlimit(RLIMIT_NOFILE, &rlim) < 0) {
206 log_warn("getrlimit: %s", strerror(errno));
209 if(rlim.rlim_cur == (rlim_t)RLIM_INFINITY)
211 if((size_t)rlim.rlim_cur < total) {
212 avail = (size_t)rlim.rlim_cur;
213 rlim.rlim_cur = (rlim_t)(total + 10);
214 rlim.rlim_max = (rlim_t)(total + 10);
215 #ifdef HAVE_SETRLIMIT
216 if(setrlimit(RLIMIT_NOFILE, &rlim) < 0) {
217 log_warn("setrlimit: %s", strerror(errno));
219 log_warn("cannot increase max open fds from %u to %u",
220 (unsigned)avail, (unsigned)total+10);
221 /* check that calculation below does not underflow,
222 * with 15 as margin */
223 if(numthread*perthread_noudp+15 > avail)
224 fatal_exit("too much tcp. not enough fds.");
225 cfg->outgoing_num_ports = (int)((avail
226 - numthread*perthread_noudp
227 - 10 /* safety margin */) /numthread);
228 log_warn("continuing with less udp ports: %u",
229 cfg->outgoing_num_ports);
230 log_warn("increase ulimit or decrease threads, "
231 "ports in config to remove this warning");
233 #ifdef HAVE_SETRLIMIT
236 verbose(VERB_ALGO, "increased limit(open files) from %u to %u",
237 (unsigned)avail, (unsigned)total+10);
241 #endif /* HAVE_GETRLIMIT */
242 #endif /* S_SPLINT_S */
245 /** set default logfile identity based on value from argv[0] at startup **/
247 log_ident_set_fromdefault(struct config_file* cfg,
248 const char *log_default_identity)
250 if(cfg->log_identity == NULL || cfg->log_identity[0] == 0)
251 log_ident_set(log_default_identity);
253 log_ident_set(cfg->log_identity);
256 /** set verbosity, check rlimits, cache settings */
258 apply_settings(struct daemon* daemon, struct config_file* cfg,
259 int cmdline_verbose, int debug_mode, const char* log_default_identity)
261 /* apply if they have changed */
262 verbosity = cmdline_verbose + cfg->verbosity;
263 if (debug_mode > 1) {
268 daemon_apply_cfg(daemon, cfg);
271 if (cfg->use_systemd && cfg->do_daemonize) {
272 log_warn("use-systemd and do-daemonize should not be enabled at the same time");
275 log_ident_set_fromdefault(cfg, log_default_identity);
279 /** Read existing pid from pidfile.
280 * @param file: file name of pid file.
281 * @return: the pid from the file or -1 if none.
284 readpid (const char* file)
292 if ((fd = open(file, O_RDONLY)) == -1) {
294 log_err("Could not read pidfile %s: %s",
295 file, strerror(errno));
299 if (((l = read(fd, pidbuf, sizeof(pidbuf)))) == -1) {
301 log_err("Could not read pidfile %s: %s",
302 file, strerror(errno));
309 /* Empty pidfile means no pidfile... */
314 pidbuf[sizeof(pidbuf)-1] = 0;
315 pid = (pid_t)strtol(pidbuf, &t, 10);
317 if (*t && *t != '\n') {
323 /** write pid to file.
324 * @param pidfile: file name of pid file.
325 * @param pid: pid to write to file.
328 writepid (const char* pidfile, pid_t pid)
332 if ((f = fopen(pidfile, "w")) == NULL ) {
333 log_err("cannot open pidfile %s: %s",
334 pidfile, strerror(errno));
337 if(fprintf(f, "%lu\n", (unsigned long)pid) < 0) {
338 log_err("cannot write to pidfile %s: %s",
339 pidfile, strerror(errno));
345 * check old pid file.
346 * @param pidfile: the file name of the pid file.
347 * @param inchroot: if pidfile is inchroot and we can thus expect to
348 * be able to delete it.
351 checkoldpid(char* pidfile, int inchroot)
354 if((old = readpid(pidfile)) != -1) {
355 /* see if it is still alive */
356 if(kill(old, 0) == 0 || errno == EPERM)
357 log_warn("unbound is already running as pid %u.",
360 log_warn("did not exit gracefully last time (%u)",
364 #endif /* HAVE_KILL */
366 /** detach from command line */
370 #if defined(HAVE_DAEMON) && !defined(DEPRECATED_DAEMON)
371 /* use POSIX daemon(3) function */
372 if(daemon(1, 0) != 0)
373 fatal_exit("daemon failed: %s", strerror(errno));
374 #else /* no HAVE_DAEMON */
382 fatal_exit("fork failed: %s", strerror(errno));
384 /* exit interactive session */
390 fatal_exit("setsid() failed: %s", strerror(errno));
392 if ((fd = open("/dev/null", O_RDWR, 0)) != -1) {
393 (void)dup2(fd, STDIN_FILENO);
394 (void)dup2(fd, STDOUT_FILENO);
395 (void)dup2(fd, STDERR_FILENO);
399 #endif /* HAVE_FORK */
400 #endif /* HAVE_DAEMON */
403 /** daemonize, drop user privileges and chroot if needed */
405 perform_setup(struct daemon* daemon, struct config_file* cfg, int debug_mode,
406 const char** cfgfile, int need_pidfile)
412 struct passwd *pwd = NULL;
414 if(cfg->username && cfg->username[0]) {
415 if((pwd = getpwnam(cfg->username)) == NULL)
416 fatal_exit("user '%s' does not exist.", cfg->username);
417 /* endpwent below, in case we need pwd for setusercontext */
421 w_config_adjust_directory(cfg);
424 /* read ssl keys while superuser and outside chroot */
426 if(!(daemon->rc = daemon_remote_create(cfg)))
427 fatal_exit("could not set up remote-control");
428 if(cfg->ssl_service_key && cfg->ssl_service_key[0]) {
429 if(!(daemon->listen_sslctx = listen_sslctx_create(
430 cfg->ssl_service_key, cfg->ssl_service_pem, NULL)))
431 fatal_exit("could not set up listen SSL_CTX");
433 if(!(daemon->connect_sslctx = connect_sslctx_create(NULL, NULL,
434 cfg->tls_cert_bundle)))
435 fatal_exit("could not set up connect SSL_CTX");
438 /* init syslog (as root) if needed, before daemonize, otherwise
439 * a fork error could not be printed since daemonize closed stderr.*/
440 if(cfg->use_syslog) {
441 log_init(cfg->logfile, cfg->use_syslog, cfg->chrootdir);
443 /* if using a logfile, we cannot open it because the logfile would
444 * be created with the wrong permissions, we cannot chown it because
445 * we cannot chown system logfiles, so we do not open at all.
446 * So, using a logfile, the user does not see errors unless -d is
447 * given to unbound on the commandline. */
450 /* true if pidfile is inside chrootdir, or nochroot */
451 pidinchroot = need_pidfile && (!(cfg->chrootdir && cfg->chrootdir[0]) ||
452 (cfg->chrootdir && cfg->chrootdir[0] &&
453 strncmp(cfg->pidfile, cfg->chrootdir,
454 strlen(cfg->chrootdir))==0));
456 /* check old pid file before forking */
457 if(cfg->pidfile && cfg->pidfile[0] && need_pidfile) {
458 /* calculate position of pidfile */
459 if(cfg->pidfile[0] == '/')
460 daemon->pidfile = strdup(cfg->pidfile);
461 else daemon->pidfile = fname_after_chroot(cfg->pidfile,
464 fatal_exit("pidfile alloc: out of memory");
465 checkoldpid(daemon->pidfile, pidinchroot);
469 /* daemonize because pid is needed by the writepid func */
470 if(!debug_mode && cfg->do_daemonize) {
474 /* write new pidfile (while still root, so can be outside chroot) */
476 if(cfg->pidfile && cfg->pidfile[0] && need_pidfile) {
477 writepid(daemon->pidfile, getpid());
478 if(cfg->username && cfg->username[0] && cfg_uid != (uid_t)-1 &&
481 if(chown(daemon->pidfile, cfg_uid, cfg_gid) == -1) {
482 verbose(VERB_QUERY, "cannot chown %u.%u %s: %s",
483 (unsigned)cfg_uid, (unsigned)cfg_gid,
484 daemon->pidfile, strerror(errno));
486 # endif /* HAVE_CHOWN */
492 #endif /* HAVE_KILL */
494 /* Set user context */
496 if(cfg->username && cfg->username[0] && cfg_uid != (uid_t)-1) {
497 #ifdef HAVE_SETUSERCONTEXT
498 /* setusercontext does initgroups, setuid, setgid, and
499 * also resource limits from login config, but we
500 * still call setresuid, setresgid to be sure to set all uid*/
501 if(setusercontext(NULL, pwd, cfg_uid, (unsigned)
502 LOGIN_SETALL & ~LOGIN_SETUSER & ~LOGIN_SETGROUP) != 0)
503 log_warn("unable to setusercontext %s: %s",
504 cfg->username, strerror(errno));
505 #endif /* HAVE_SETUSERCONTEXT */
507 #endif /* HAVE_GETPWNAM */
509 /* box into the chroot */
511 if(cfg->chrootdir && cfg->chrootdir[0]) {
512 if(chdir(cfg->chrootdir)) {
513 fatal_exit("unable to chdir to chroot %s: %s",
514 cfg->chrootdir, strerror(errno));
516 verbose(VERB_QUERY, "chdir to %s", cfg->chrootdir);
517 if(chroot(cfg->chrootdir))
518 fatal_exit("unable to chroot to %s: %s",
519 cfg->chrootdir, strerror(errno));
521 fatal_exit("unable to chdir to / in chroot %s: %s",
522 cfg->chrootdir, strerror(errno));
523 verbose(VERB_QUERY, "chroot to %s", cfg->chrootdir);
524 if(strncmp(*cfgfile, cfg->chrootdir,
525 strlen(cfg->chrootdir)) == 0)
526 (*cfgfile) += strlen(cfg->chrootdir);
528 /* adjust stored pidfile for chroot */
529 if(daemon->pidfile && daemon->pidfile[0] &&
530 strncmp(daemon->pidfile, cfg->chrootdir,
531 strlen(cfg->chrootdir))==0) {
532 char* old = daemon->pidfile;
533 daemon->pidfile = strdup(old+strlen(cfg->chrootdir));
536 log_err("out of memory in pidfile adjust");
538 daemon->chroot = strdup(cfg->chrootdir);
540 log_err("out of memory in daemon chroot dir storage");
545 /* change to working directory inside chroot */
546 if(cfg->directory && cfg->directory[0]) {
547 char* dir = cfg->directory;
548 if(cfg->chrootdir && cfg->chrootdir[0] &&
549 strncmp(dir, cfg->chrootdir,
550 strlen(cfg->chrootdir)) == 0)
551 dir += strlen(cfg->chrootdir);
554 fatal_exit("Could not chdir to %s: %s",
555 dir, strerror(errno));
557 verbose(VERB_QUERY, "chdir to %s", dir);
561 /* drop permissions after chroot, getpwnam, pidfile, syslog done*/
563 if(cfg->username && cfg->username[0] && cfg_uid != (uid_t)-1) {
564 # ifdef HAVE_INITGROUPS
565 if(initgroups(cfg->username, cfg_gid) != 0)
566 log_warn("unable to initgroups %s: %s",
567 cfg->username, strerror(errno));
568 # endif /* HAVE_INITGROUPS */
569 # ifdef HAVE_ENDPWENT
573 #ifdef HAVE_SETRESGID
574 if(setresgid(cfg_gid,cfg_gid,cfg_gid) != 0)
575 #elif defined(HAVE_SETREGID) && !defined(DARWIN_BROKEN_SETREUID)
576 if(setregid(cfg_gid,cfg_gid) != 0)
577 #else /* use setgid */
578 if(setgid(cfg_gid) != 0)
579 #endif /* HAVE_SETRESGID */
580 fatal_exit("unable to set group id of %s: %s",
581 cfg->username, strerror(errno));
582 #ifdef HAVE_SETRESUID
583 if(setresuid(cfg_uid,cfg_uid,cfg_uid) != 0)
584 #elif defined(HAVE_SETREUID) && !defined(DARWIN_BROKEN_SETREUID)
585 if(setreuid(cfg_uid,cfg_uid) != 0)
586 #else /* use setuid */
587 if(setuid(cfg_uid) != 0)
588 #endif /* HAVE_SETRESUID */
589 fatal_exit("unable to set user id of %s: %s",
590 cfg->username, strerror(errno));
591 verbose(VERB_QUERY, "drop user privileges, run as %s",
594 #endif /* HAVE_GETPWNAM */
595 /* file logging inited after chroot,chdir,setuid is done so that
596 * it would succeed on SIGHUP as well */
598 log_init(cfg->logfile, cfg->use_syslog, cfg->chrootdir);
603 * @param cfgfile: the config file name.
604 * @param cmdline_verbose: verbosity resulting from commandline -v.
605 * These increase verbosity as specified in the config file.
606 * @param debug_mode: if set, do not daemonize.
607 * @param log_default_identity: Default identity to report in logs
608 * @param need_pidfile: if false, no pidfile is checked or created.
611 run_daemon(const char* cfgfile, int cmdline_verbose, int debug_mode, const char* log_default_identity, int need_pidfile)
613 struct config_file* cfg = NULL;
614 struct daemon* daemon = NULL;
617 if(!(daemon = daemon_init()))
618 fatal_exit("alloc failure");
619 while(!daemon->need_to_exit) {
621 verbose(VERB_OPS, "Restart of %s.", PACKAGE_STRING);
622 else verbose(VERB_OPS, "Start of %s.", PACKAGE_STRING);
625 if(!(cfg = config_create()))
626 fatal_exit("Could not alloc config defaults");
627 if(!config_read(cfg, cfgfile, daemon->chroot)) {
629 fatal_exit("Could not read config file: %s",
631 log_warn("Continuing with default config settings");
633 apply_settings(daemon, cfg, cmdline_verbose, debug_mode, log_default_identity);
635 config_lookup_uid(cfg);
638 if(!daemon_open_shared_ports(daemon))
639 fatal_exit("could not open ports");
641 perform_setup(daemon, cfg, debug_mode, &cfgfile, need_pidfile);
644 /* reopen log after HUP to facilitate log rotation */
646 log_init(cfg->logfile, 0, cfg->chrootdir);
651 /* clean up for restart */
652 verbose(VERB_ALGO, "cleanup.");
653 daemon_cleanup(daemon);
656 verbose(VERB_ALGO, "Exit cleanup.");
657 /* this unlink may not work if the pidfile is located outside
658 * of the chroot/workdir or we no longer have permissions */
659 if(daemon->pidfile) {
661 /* truncate pidfile */
662 fd = open(daemon->pidfile, O_WRONLY | O_TRUNC, 0644);
666 unlink(daemon->pidfile);
668 daemon_delete(daemon);
671 /** getopt global, in case header files fail to declare it. */
673 /** getopt global, in case header files fail to declare it. */
677 * main program. Set options given commandline arguments.
678 * @param argc: number of commandline arguments.
679 * @param argv: array of commandline arguments.
680 * @return: exit status of the program.
683 main(int argc, char* argv[])
686 const char* cfgfile = CONFIGFILE;
687 const char* winopt = NULL;
688 const char* log_ident_default;
689 int cmdline_verbose = 0;
691 int need_pidfile = 1;
697 log_init(NULL, 0, NULL);
698 log_ident_default = strrchr(argv[0],'/')?strrchr(argv[0],'/')+1:argv[0];
699 log_ident_set(log_ident_default);
700 /* parse the options */
701 while( (c=getopt(argc, argv, "c:dhpvw:")) != -1) {
734 wsvc_command_option(winopt, cfgfile, cmdline_verbose,
737 fatal_exit("option not supported");
746 run_daemon(cfgfile, cmdline_verbose, debug_mode, log_ident_default, need_pidfile);
747 log_init(NULL, 0, NULL); /* close logfile */
748 #ifndef unbound_testbound
750 lock_quick_destroy((lock_quick_type*)log_get_lock());