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>
70 #include <openssl/ssl.h>
73 /* splint chokes on this system header file */
74 #ifdef HAVE_SYS_RESOURCE_H
75 #include <sys/resource.h>
77 #endif /* S_SPLINT_S */
78 #ifdef HAVE_LOGIN_CAP_H
79 #include <login_cap.h>
83 # include "winrc/win_svc.h"
92 static void usage(void)
95 const char *evnm="event", *evsys="", *evmethod="";
98 struct ub_event_base* base;
99 printf("usage: local-unbound [options]\n");
100 printf(" start unbound daemon DNS resolver.\n");
101 printf("-h this help\n");
102 printf("-c file config file to read instead of %s\n", CONFIGFILE);
103 printf(" file format is described in unbound.conf(5).\n");
104 printf("-d do not fork into the background.\n");
105 printf("-p do not create a pidfile.\n");
106 printf("-v verbose (more times to increase verbosity)\n");
108 printf("-w opt windows option: \n");
109 printf(" install, remove - manage the services entry\n");
110 printf(" service - used to start from services control panel\n");
112 printf("Version %s\n", PACKAGE_VERSION);
113 base = ub_default_event_base(0,&t,&now);
114 ub_get_event_sys(base, &evnm, &evsys, &evmethod);
115 printf("linked libs: %s %s (it uses %s), %s\n",
116 evnm, evsys, evmethod,
118 # ifdef SSLEAY_VERSION
119 SSLeay_version(SSLEAY_VERSION)
121 OpenSSL_version(OPENSSL_VERSION)
123 #elif defined(HAVE_NSS)
125 #elif defined(HAVE_NETTLE)
129 printf("linked modules:");
130 for(m = module_list_avail(); *m; m++)
134 printf("DNSCrypt feature available\n");
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 default logfile identity based on value from argv[0] at startup **/
249 log_ident_set_fromdefault(struct config_file* cfg,
250 const char *log_default_identity)
252 if(cfg->log_identity == NULL || cfg->log_identity[0] == 0)
253 log_ident_set(log_default_identity);
255 log_ident_set(cfg->log_identity);
258 /** set verbosity, check rlimits, cache settings */
260 apply_settings(struct daemon* daemon, struct config_file* cfg,
261 int cmdline_verbose, int debug_mode, const char* log_default_identity)
263 /* apply if they have changed */
264 verbosity = cmdline_verbose + cfg->verbosity;
265 if (debug_mode > 1) {
270 daemon_apply_cfg(daemon, cfg);
273 if (cfg->use_systemd && cfg->do_daemonize) {
274 log_warn("use-systemd and do-daemonize should not be enabled at the same time");
277 log_ident_set_fromdefault(cfg, log_default_identity);
281 /** Read existing pid from pidfile.
282 * @param file: file name of pid file.
283 * @return: the pid from the file or -1 if none.
286 readpid (const char* file)
294 if ((fd = open(file, O_RDONLY)) == -1) {
296 log_err("Could not read pidfile %s: %s",
297 file, strerror(errno));
301 if (((l = read(fd, pidbuf, sizeof(pidbuf)))) == -1) {
303 log_err("Could not read pidfile %s: %s",
304 file, strerror(errno));
311 /* Empty pidfile means no pidfile... */
316 pidbuf[sizeof(pidbuf)-1] = 0;
317 pid = (pid_t)strtol(pidbuf, &t, 10);
319 if (*t && *t != '\n') {
325 /** write pid to file.
326 * @param pidfile: file name of pid file.
327 * @param pid: pid to write to file.
330 writepid (const char* pidfile, pid_t pid)
334 if ((f = fopen(pidfile, "w")) == NULL ) {
335 log_err("cannot open pidfile %s: %s",
336 pidfile, strerror(errno));
339 if(fprintf(f, "%lu\n", (unsigned long)pid) < 0) {
340 log_err("cannot write to pidfile %s: %s",
341 pidfile, strerror(errno));
347 * check old pid file.
348 * @param pidfile: the file name of the pid file.
349 * @param inchroot: if pidfile is inchroot and we can thus expect to
350 * be able to delete it.
353 checkoldpid(char* pidfile, int inchroot)
356 if((old = readpid(pidfile)) != -1) {
357 /* see if it is still alive */
358 if(kill(old, 0) == 0 || errno == EPERM)
359 log_warn("unbound is already running as pid %u.",
362 log_warn("did not exit gracefully last time (%u)",
366 #endif /* HAVE_KILL */
368 /** detach from command line */
372 #if defined(HAVE_DAEMON) && !defined(DEPRECATED_DAEMON)
373 /* use POSIX daemon(3) function */
374 if(daemon(1, 0) != 0)
375 fatal_exit("daemon failed: %s", strerror(errno));
376 #else /* no HAVE_DAEMON */
384 fatal_exit("fork failed: %s", strerror(errno));
386 /* exit interactive session */
392 fatal_exit("setsid() failed: %s", strerror(errno));
394 if ((fd = open("/dev/null", O_RDWR, 0)) != -1) {
395 (void)dup2(fd, STDIN_FILENO);
396 (void)dup2(fd, STDOUT_FILENO);
397 (void)dup2(fd, STDERR_FILENO);
401 #endif /* HAVE_FORK */
402 #endif /* HAVE_DAEMON */
405 /** daemonize, drop user privileges and chroot if needed */
407 perform_setup(struct daemon* daemon, struct config_file* cfg, int debug_mode,
408 const char** cfgfile, int need_pidfile)
414 struct passwd *pwd = NULL;
416 if(cfg->username && cfg->username[0]) {
417 if((pwd = getpwnam(cfg->username)) == NULL)
418 fatal_exit("user '%s' does not exist.", cfg->username);
419 /* endpwent below, in case we need pwd for setusercontext */
423 w_config_adjust_directory(cfg);
426 /* read ssl keys while superuser and outside chroot */
428 if(!(daemon->rc = daemon_remote_create(cfg)))
429 fatal_exit("could not set up remote-control");
430 if(cfg->ssl_service_key && cfg->ssl_service_key[0]) {
431 if(!(daemon->listen_sslctx = listen_sslctx_create(
432 cfg->ssl_service_key, cfg->ssl_service_pem, NULL)))
433 fatal_exit("could not set up listen SSL_CTX");
434 if(cfg->tls_ciphers && cfg->tls_ciphers[0]) {
435 if (!SSL_CTX_set_cipher_list(daemon->listen_sslctx, cfg->tls_ciphers)) {
436 fatal_exit("failed to set tls-cipher %s", cfg->tls_ciphers);
439 #ifdef HAVE_SSL_CTX_SET_CIPHERSUITES
440 if(cfg->tls_ciphersuites && cfg->tls_ciphersuites[0]) {
441 if (!SSL_CTX_set_ciphersuites(daemon->listen_sslctx, cfg->tls_ciphersuites)) {
442 fatal_exit("failed to set tls-ciphersuites %s", cfg->tls_ciphersuites);
446 if(cfg->tls_session_ticket_keys.first &&
447 cfg->tls_session_ticket_keys.first->str[0] != 0) {
448 if(!listen_sslctx_setup_ticket_keys(daemon->listen_sslctx, cfg->tls_session_ticket_keys.first)) {
449 fatal_exit("could not set session ticket SSL_CTX");
453 if(!(daemon->connect_sslctx = connect_sslctx_create(NULL, NULL,
454 cfg->tls_cert_bundle, cfg->tls_win_cert)))
455 fatal_exit("could not set up connect SSL_CTX");
458 /* init syslog (as root) if needed, before daemonize, otherwise
459 * a fork error could not be printed since daemonize closed stderr.*/
460 if(cfg->use_syslog) {
461 log_init(cfg->logfile, cfg->use_syslog, cfg->chrootdir);
463 /* if using a logfile, we cannot open it because the logfile would
464 * be created with the wrong permissions, we cannot chown it because
465 * we cannot chown system logfiles, so we do not open at all.
466 * So, using a logfile, the user does not see errors unless -d is
467 * given to unbound on the commandline. */
470 /* true if pidfile is inside chrootdir, or nochroot */
471 pidinchroot = need_pidfile && (!(cfg->chrootdir && cfg->chrootdir[0]) ||
472 (cfg->chrootdir && cfg->chrootdir[0] &&
473 strncmp(cfg->pidfile, cfg->chrootdir,
474 strlen(cfg->chrootdir))==0));
476 /* check old pid file before forking */
477 if(cfg->pidfile && cfg->pidfile[0] && need_pidfile) {
478 /* calculate position of pidfile */
479 if(cfg->pidfile[0] == '/')
480 daemon->pidfile = strdup(cfg->pidfile);
481 else daemon->pidfile = fname_after_chroot(cfg->pidfile,
484 fatal_exit("pidfile alloc: out of memory");
485 checkoldpid(daemon->pidfile, pidinchroot);
489 /* daemonize because pid is needed by the writepid func */
490 if(!debug_mode && cfg->do_daemonize) {
494 /* write new pidfile (while still root, so can be outside chroot) */
496 if(cfg->pidfile && cfg->pidfile[0] && need_pidfile) {
497 writepid(daemon->pidfile, getpid());
498 if(cfg->username && cfg->username[0] && cfg_uid != (uid_t)-1 &&
501 if(chown(daemon->pidfile, cfg_uid, cfg_gid) == -1) {
502 verbose(VERB_QUERY, "cannot chown %u.%u %s: %s",
503 (unsigned)cfg_uid, (unsigned)cfg_gid,
504 daemon->pidfile, strerror(errno));
506 # endif /* HAVE_CHOWN */
512 #endif /* HAVE_KILL */
514 /* Set user context */
516 if(cfg->username && cfg->username[0] && cfg_uid != (uid_t)-1) {
517 #ifdef HAVE_SETUSERCONTEXT
518 /* setusercontext does initgroups, setuid, setgid, and
519 * also resource limits from login config, but we
520 * still call setresuid, setresgid to be sure to set all uid*/
521 if(setusercontext(NULL, pwd, cfg_uid, (unsigned)
522 LOGIN_SETALL & ~LOGIN_SETUSER & ~LOGIN_SETGROUP) != 0)
523 log_warn("unable to setusercontext %s: %s",
524 cfg->username, strerror(errno));
525 #endif /* HAVE_SETUSERCONTEXT */
527 #endif /* HAVE_GETPWNAM */
529 /* box into the chroot */
531 if(cfg->chrootdir && cfg->chrootdir[0]) {
532 if(chdir(cfg->chrootdir)) {
533 fatal_exit("unable to chdir to chroot %s: %s",
534 cfg->chrootdir, strerror(errno));
536 verbose(VERB_QUERY, "chdir to %s", cfg->chrootdir);
537 if(chroot(cfg->chrootdir))
538 fatal_exit("unable to chroot to %s: %s",
539 cfg->chrootdir, strerror(errno));
541 fatal_exit("unable to chdir to / in chroot %s: %s",
542 cfg->chrootdir, strerror(errno));
543 verbose(VERB_QUERY, "chroot to %s", cfg->chrootdir);
544 if(strncmp(*cfgfile, cfg->chrootdir,
545 strlen(cfg->chrootdir)) == 0)
546 (*cfgfile) += strlen(cfg->chrootdir);
548 /* adjust stored pidfile for chroot */
549 if(daemon->pidfile && daemon->pidfile[0] &&
550 strncmp(daemon->pidfile, cfg->chrootdir,
551 strlen(cfg->chrootdir))==0) {
552 char* old = daemon->pidfile;
553 daemon->pidfile = strdup(old+strlen(cfg->chrootdir));
556 log_err("out of memory in pidfile adjust");
558 daemon->chroot = strdup(cfg->chrootdir);
560 log_err("out of memory in daemon chroot dir storage");
565 /* change to working directory inside chroot */
566 if(cfg->directory && cfg->directory[0]) {
567 char* dir = cfg->directory;
568 if(cfg->chrootdir && cfg->chrootdir[0] &&
569 strncmp(dir, cfg->chrootdir,
570 strlen(cfg->chrootdir)) == 0)
571 dir += strlen(cfg->chrootdir);
574 fatal_exit("Could not chdir to %s: %s",
575 dir, strerror(errno));
577 verbose(VERB_QUERY, "chdir to %s", dir);
581 /* drop permissions after chroot, getpwnam, pidfile, syslog done*/
583 if(cfg->username && cfg->username[0] && cfg_uid != (uid_t)-1) {
584 # ifdef HAVE_INITGROUPS
585 if(initgroups(cfg->username, cfg_gid) != 0)
586 log_warn("unable to initgroups %s: %s",
587 cfg->username, strerror(errno));
588 # endif /* HAVE_INITGROUPS */
589 # ifdef HAVE_ENDPWENT
593 #ifdef HAVE_SETRESGID
594 if(setresgid(cfg_gid,cfg_gid,cfg_gid) != 0)
595 #elif defined(HAVE_SETREGID) && !defined(DARWIN_BROKEN_SETREUID)
596 if(setregid(cfg_gid,cfg_gid) != 0)
597 #else /* use setgid */
598 if(setgid(cfg_gid) != 0)
599 #endif /* HAVE_SETRESGID */
600 fatal_exit("unable to set group id of %s: %s",
601 cfg->username, strerror(errno));
602 #ifdef HAVE_SETRESUID
603 if(setresuid(cfg_uid,cfg_uid,cfg_uid) != 0)
604 #elif defined(HAVE_SETREUID) && !defined(DARWIN_BROKEN_SETREUID)
605 if(setreuid(cfg_uid,cfg_uid) != 0)
606 #else /* use setuid */
607 if(setuid(cfg_uid) != 0)
608 #endif /* HAVE_SETRESUID */
609 fatal_exit("unable to set user id of %s: %s",
610 cfg->username, strerror(errno));
611 verbose(VERB_QUERY, "drop user privileges, run as %s",
614 #endif /* HAVE_GETPWNAM */
615 /* file logging inited after chroot,chdir,setuid is done so that
616 * it would succeed on SIGHUP as well */
618 log_init(cfg->logfile, cfg->use_syslog, cfg->chrootdir);
623 * @param cfgfile: the config file name.
624 * @param cmdline_verbose: verbosity resulting from commandline -v.
625 * These increase verbosity as specified in the config file.
626 * @param debug_mode: if set, do not daemonize.
627 * @param log_default_identity: Default identity to report in logs
628 * @param need_pidfile: if false, no pidfile is checked or created.
631 run_daemon(const char* cfgfile, int cmdline_verbose, int debug_mode, const char* log_default_identity, int need_pidfile)
633 struct config_file* cfg = NULL;
634 struct daemon* daemon = NULL;
637 if(!(daemon = daemon_init()))
638 fatal_exit("alloc failure");
639 while(!daemon->need_to_exit) {
641 verbose(VERB_OPS, "Restart of %s.", PACKAGE_STRING);
642 else verbose(VERB_OPS, "Start of %s.", PACKAGE_STRING);
645 if(!(cfg = config_create()))
646 fatal_exit("Could not alloc config defaults");
647 if(!config_read(cfg, cfgfile, daemon->chroot)) {
649 fatal_exit("Could not read config file: %s."
650 " Maybe try unbound -dd, it stays on "
651 "the commandline to see more errors, "
652 "or unbound-checkconf", cfgfile);
653 log_warn("Continuing with default config settings");
655 apply_settings(daemon, cfg, cmdline_verbose, debug_mode, log_default_identity);
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, need_pidfile);
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 const char* log_ident_default;
711 int cmdline_verbose = 0;
713 int need_pidfile = 1;
719 log_init(NULL, 0, NULL);
720 log_ident_default = strrchr(argv[0],'/')?strrchr(argv[0],'/')+1:argv[0];
721 log_ident_set(log_ident_default);
722 /* parse the options */
723 while( (c=getopt(argc, argv, "c:dhpvw:")) != -1) {
752 /* argv += optind; not using further arguments */
756 wsvc_command_option(winopt, cfgfile, cmdline_verbose,
759 fatal_exit("option not supported");
768 run_daemon(cfgfile, cmdline_verbose, debug_mode, log_ident_default, need_pidfile);
769 log_init(NULL, 0, NULL); /* close logfile */
770 #ifndef unbound_testbound
772 lock_quick_destroy((lock_quick_type*)log_get_lock());