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"
62 #include <openssl/crypto.h>
71 /* splint chokes on this system header file */
72 #ifdef HAVE_SYS_RESOURCE_H
73 #include <sys/resource.h>
75 #endif /* S_SPLINT_S */
76 #ifdef HAVE_LOGIN_CAP_H
77 #include <login_cap.h>
82 # include "util/winsock_event.h"
84 # include "util/mini_event.h"
91 # include "winrc/win_svc.h"
100 /** global debug value to keep track of heap memory allocation */
101 void* unbound_start_brk = 0;
104 #if !defined(HAVE_EVENT_BASE_GET_METHOD) && (defined(HAVE_EV_LOOP) || defined(HAVE_EV_DEFAULT_LOOP))
105 static const char* ev_backend2str(int b)
108 case EVBACKEND_SELECT: return "select";
109 case EVBACKEND_POLL: return "poll";
110 case EVBACKEND_EPOLL: return "epoll";
111 case EVBACKEND_KQUEUE: return "kqueue";
112 case EVBACKEND_DEVPOLL: return "devpoll";
113 case EVBACKEND_PORT: return "evport";
119 /** get the event system in use */
120 static void get_event_sys(const char** n, const char** s, const char** m)
125 *m = "WSAWaitForMultipleEvents";
126 #elif defined(USE_MINI_EVENT)
131 struct event_base* b;
132 *s = event_get_version();
133 # ifdef HAVE_EVENT_BASE_GET_METHOD
135 b = event_base_new();
136 *m = event_base_get_method(b);
137 # elif defined(HAVE_EV_LOOP) || defined(HAVE_EV_DEFAULT_LOOP)
139 b = (struct event_base*)ev_default_loop(EVFLAG_AUTO);
140 *m = ev_backend2str(ev_backend((struct ev_loop*)b));
143 *m = "not obtainable";
146 # ifdef HAVE_EVENT_BASE_FREE
156 const char *evnm="event", *evsys="", *evmethod="";
157 printf("usage: unbound [options]\n");
158 printf(" start unbound daemon DNS resolver.\n");
159 printf("-h this help\n");
160 printf("-c file config file to read instead of %s\n", CONFIGFILE);
161 printf(" file format is described in unbound.conf(5).\n");
162 printf("-d do not fork into the background.\n");
163 printf("-v verbose (more times to increase verbosity)\n");
165 printf("-w opt windows option: \n");
166 printf(" install, remove - manage the services entry\n");
167 printf(" service - used to start from services control panel\n");
169 printf("Version %s\n", PACKAGE_VERSION);
170 get_event_sys(&evnm, &evsys, &evmethod);
171 printf("linked libs: %s %s (it uses %s), %s\n",
172 evnm, evsys, evmethod,
174 SSLeay_version(SSLEAY_VERSION)
175 #elif defined(HAVE_NSS)
179 printf("linked modules:");
180 for(m = module_list_avail(); *m; m++)
183 printf("BSD licensed, see LICENSE in source package for details.\n");
184 printf("Report bugs to %s\n", PACKAGE_BUGREPORT);
187 #ifndef unbound_testbound
188 int replay_var_compare(const void* ATTR_UNUSED(a), const void* ATTR_UNUSED(b))
195 /** check file descriptor count */
197 checkrlimits(struct config_file* cfg)
200 #ifdef HAVE_GETRLIMIT
201 /* list has number of ports to listen to, ifs number addresses */
202 int list = ((cfg->do_udp?1:0) + (cfg->do_tcp?1 +
203 (int)cfg->incoming_num_tcp:0));
204 size_t listen_ifs = (size_t)(cfg->num_ifs==0?
205 ((cfg->do_ip4 && !cfg->if_automatic?1:0) +
206 (cfg->do_ip6?1:0)):cfg->num_ifs);
207 size_t listen_num = list*listen_ifs;
208 size_t outudpnum = (size_t)cfg->outgoing_num_ports;
209 size_t outtcpnum = cfg->outgoing_num_tcp;
210 size_t misc = 4; /* logfile, pidfile, stdout... */
211 size_t perthread_noudp = listen_num + outtcpnum +
212 2/*cmdpipe*/ + 2/*libevent*/ + misc;
213 size_t perthread = perthread_noudp + outudpnum;
215 #if !defined(HAVE_PTHREAD) && !defined(HAVE_SOLARIS_THREADS)
216 int numthread = 1; /* it forks */
218 int numthread = (cfg->num_threads?cfg->num_threads:1);
220 size_t total = numthread * perthread + misc;
225 strncmp(event_get_version(), "mini-event", 10) == 0) {
226 log_warn("too many file descriptors requested. The builtin"
227 "mini-event cannot handle more than 1024. Config "
228 "for less fds or compile with libevent");
229 if(numthread*perthread_noudp+15 > 1024)
230 fatal_exit("too much tcp. not enough fds.");
231 cfg->outgoing_num_ports = (int)((1024
232 - numthread*perthread_noudp
233 - 10 /* safety margin */) /numthread);
234 log_warn("continuing with less udp ports: %u",
235 cfg->outgoing_num_ports);
239 strncmp(event_get_version(), "winsock-event", 13) == 0) {
240 log_err("too many file descriptors requested. The winsock"
241 " event handler cannot handle more than 64 per "
242 " thread. Config for less fds");
243 if(perthread_noudp+2 > 64)
244 fatal_exit("too much tcp. not enough fds.");
245 cfg->outgoing_num_ports = (int)((64
247 - 2/* safety margin */));
248 log_warn("continuing with less udp ports: %u",
249 cfg->outgoing_num_ports);
250 total = numthread*(perthread_noudp+
251 (size_t)cfg->outgoing_num_ports)+misc;
253 if(getrlimit(RLIMIT_NOFILE, &rlim) < 0) {
254 log_warn("getrlimit: %s", strerror(errno));
257 if(rlim.rlim_cur == (rlim_t)RLIM_INFINITY)
259 if((size_t)rlim.rlim_cur < total) {
260 avail = (size_t)rlim.rlim_cur;
261 rlim.rlim_cur = (rlim_t)(total + 10);
262 rlim.rlim_max = (rlim_t)(total + 10);
263 #ifdef HAVE_SETRLIMIT
264 if(setrlimit(RLIMIT_NOFILE, &rlim) < 0) {
265 log_warn("setrlimit: %s", strerror(errno));
269 log_warn("cannot increase max open fds from %u to %u",
270 (unsigned)avail, (unsigned)total+10);
271 /* check that calculation below does not underflow,
272 * with 15 as margin */
273 if(numthread*perthread_noudp+15 > avail)
274 fatal_exit("too much tcp. not enough fds.");
275 cfg->outgoing_num_ports = (int)((avail
276 - numthread*perthread_noudp
277 - 10 /* safety margin */) /numthread);
278 log_warn("continuing with less udp ports: %u",
279 cfg->outgoing_num_ports);
280 log_warn("increase ulimit or decrease threads, "
281 "ports in config to remove this warning");
284 log_warn("increased limit(open files) from %u to %u",
285 (unsigned)avail, (unsigned)total+10);
289 #endif /* HAVE_GETRLIMIT */
290 #endif /* S_SPLINT_S */
293 /** set verbosity, check rlimits, cache settings */
295 apply_settings(struct daemon* daemon, struct config_file* cfg,
298 /* apply if they have changed */
299 verbosity = cmdline_verbose + cfg->verbosity;
300 daemon_apply_cfg(daemon, cfg);
305 /** Read existing pid from pidfile.
306 * @param file: file name of pid file.
307 * @return: the pid from the file or -1 if none.
310 readpid (const char* file)
318 if ((fd = open(file, O_RDONLY)) == -1) {
320 log_err("Could not read pidfile %s: %s",
321 file, strerror(errno));
325 if (((l = read(fd, pidbuf, sizeof(pidbuf)))) == -1) {
327 log_err("Could not read pidfile %s: %s",
328 file, strerror(errno));
335 /* Empty pidfile means no pidfile... */
340 pidbuf[sizeof(pidbuf)-1] = 0;
341 pid = (pid_t)strtol(pidbuf, &t, 10);
343 if (*t && *t != '\n') {
349 /** write pid to file.
350 * @param pidfile: file name of pid file.
351 * @param pid: pid to write to file.
354 writepid (const char* pidfile, pid_t pid)
358 if ((f = fopen(pidfile, "w")) == NULL ) {
359 log_err("cannot open pidfile %s: %s",
360 pidfile, strerror(errno));
363 if(fprintf(f, "%lu\n", (unsigned long)pid) < 0) {
364 log_err("cannot write to pidfile %s: %s",
365 pidfile, strerror(errno));
371 * check old pid file.
372 * @param pidfile: the file name of the pid file.
373 * @param inchroot: if pidfile is inchroot and we can thus expect to
374 * be able to delete it.
377 checkoldpid(char* pidfile, int inchroot)
380 if((old = readpid(pidfile)) != -1) {
381 /* see if it is still alive */
382 if(kill(old, 0) == 0 || errno == EPERM)
383 log_warn("unbound is already running as pid %u.",
386 log_warn("did not exit gracefully last time (%u)",
390 #endif /* HAVE_KILL */
392 /** detach from command line */
396 #if defined(HAVE_DAEMON) && !defined(DEPRECATED_DAEMON)
397 /* use POSIX daemon(3) function */
398 if(daemon(1, 0) != 0)
399 fatal_exit("daemon failed: %s", strerror(errno));
400 #else /* no HAVE_DAEMON */
408 fatal_exit("fork failed: %s", strerror(errno));
410 /* exit interactive session */
416 fatal_exit("setsid() failed: %s", strerror(errno));
418 if ((fd = open("/dev/null", O_RDWR, 0)) != -1) {
419 (void)dup2(fd, STDIN_FILENO);
420 (void)dup2(fd, STDOUT_FILENO);
421 (void)dup2(fd, STDERR_FILENO);
425 #endif /* HAVE_FORK */
426 #endif /* HAVE_DAEMON */
429 /** daemonize, drop user priviliges and chroot if needed */
431 perform_setup(struct daemon* daemon, struct config_file* cfg, int debug_mode,
432 const char** cfgfile)
435 struct passwd *pwd = NULL;
438 /* initialize, but not to 0 (root) */
439 memset(&uid, 112, sizeof(uid));
440 memset(&gid, 112, sizeof(gid));
443 if(cfg->username && cfg->username[0]) {
444 if((pwd = getpwnam(cfg->username)) == NULL)
445 fatal_exit("user '%s' does not exist.", cfg->username);
448 /* endpwent below, in case we need pwd for setusercontext */
452 /* init syslog (as root) if needed, before daemonize, otherwise
453 * a fork error could not be printed since daemonize closed stderr.*/
454 if(cfg->use_syslog) {
455 log_init(cfg->logfile, cfg->use_syslog, cfg->chrootdir);
457 /* if using a logfile, we cannot open it because the logfile would
458 * be created with the wrong permissions, we cannot chown it because
459 * we cannot chown system logfiles, so we do not open at all.
460 * So, using a logfile, the user does not see errors unless -d is
461 * given to unbound on the commandline. */
463 /* read ssl keys while superuser and outside chroot */
465 if(!(daemon->rc = daemon_remote_create(cfg)))
466 fatal_exit("could not set up remote-control");
467 if(cfg->ssl_service_key && cfg->ssl_service_key[0]) {
468 if(!(daemon->listen_sslctx = listen_sslctx_create(
469 cfg->ssl_service_key, cfg->ssl_service_pem, NULL)))
470 fatal_exit("could not set up listen SSL_CTX");
472 if(!(daemon->connect_sslctx = connect_sslctx_create(NULL, NULL, NULL)))
473 fatal_exit("could not set up connect SSL_CTX");
477 /* check old pid file before forking */
478 if(cfg->pidfile && cfg->pidfile[0]) {
479 /* calculate position of pidfile */
480 if(cfg->pidfile[0] == '/')
481 daemon->pidfile = strdup(cfg->pidfile);
482 else daemon->pidfile = fname_after_chroot(cfg->pidfile,
485 fatal_exit("pidfile alloc: out of memory");
486 checkoldpid(daemon->pidfile,
487 /* true if pidfile is inside chrootdir, or nochroot */
488 !(cfg->chrootdir && cfg->chrootdir[0]) ||
489 (cfg->chrootdir && cfg->chrootdir[0] &&
490 strncmp(daemon->pidfile, cfg->chrootdir,
491 strlen(cfg->chrootdir))==0));
495 /* daemonize because pid is needed by the writepid func */
496 if(!debug_mode && cfg->do_daemonize) {
500 /* write new pidfile (while still root, so can be outside chroot) */
502 if(cfg->pidfile && cfg->pidfile[0]) {
503 writepid(daemon->pidfile, getpid());
504 if(!(cfg->chrootdir && cfg->chrootdir[0]) ||
505 (cfg->chrootdir && cfg->chrootdir[0] &&
506 strncmp(daemon->pidfile, cfg->chrootdir,
507 strlen(cfg->chrootdir))==0)) {
508 /* delete of pidfile could potentially work,
509 * chown to get permissions */
510 if(cfg->username && cfg->username[0]) {
511 if(chown(daemon->pidfile, uid, gid) == -1) {
512 log_err("cannot chown %u.%u %s: %s",
513 (unsigned)uid, (unsigned)gid,
514 daemon->pidfile, strerror(errno));
523 /* Set user context */
525 if(cfg->username && cfg->username[0]) {
526 #ifdef HAVE_SETUSERCONTEXT
527 /* setusercontext does initgroups, setuid, setgid, and
528 * also resource limits from login config, but we
529 * still call setresuid, setresgid to be sure to set all uid*/
530 if(setusercontext(NULL, pwd, uid, (unsigned)
531 LOGIN_SETALL & ~LOGIN_SETUSER & ~LOGIN_SETGROUP) != 0)
532 log_warn("unable to setusercontext %s: %s",
533 cfg->username, strerror(errno));
534 #endif /* HAVE_SETUSERCONTEXT */
536 #endif /* HAVE_GETPWNAM */
538 /* box into the chroot */
540 if(cfg->chrootdir && cfg->chrootdir[0]) {
541 if(chdir(cfg->chrootdir)) {
542 fatal_exit("unable to chdir to chroot %s: %s",
543 cfg->chrootdir, strerror(errno));
545 verbose(VERB_QUERY, "chdir to %s", cfg->chrootdir);
546 if(chroot(cfg->chrootdir))
547 fatal_exit("unable to chroot to %s: %s",
548 cfg->chrootdir, strerror(errno));
550 fatal_exit("unable to chdir to / in chroot %s: %s",
551 cfg->chrootdir, strerror(errno));
552 verbose(VERB_QUERY, "chroot to %s", cfg->chrootdir);
553 if(strncmp(*cfgfile, cfg->chrootdir,
554 strlen(cfg->chrootdir)) == 0)
555 (*cfgfile) += strlen(cfg->chrootdir);
557 /* adjust stored pidfile for chroot */
558 if(daemon->pidfile && daemon->pidfile[0] &&
559 strncmp(daemon->pidfile, cfg->chrootdir,
560 strlen(cfg->chrootdir))==0) {
561 char* old = daemon->pidfile;
562 daemon->pidfile = strdup(old+strlen(cfg->chrootdir));
565 log_err("out of memory in pidfile adjust");
567 daemon->chroot = strdup(cfg->chrootdir);
569 log_err("out of memory in daemon chroot dir storage");
574 /* change to working directory inside chroot */
575 if(cfg->directory && cfg->directory[0]) {
576 char* dir = cfg->directory;
577 if(cfg->chrootdir && cfg->chrootdir[0] &&
578 strncmp(dir, cfg->chrootdir,
579 strlen(cfg->chrootdir)) == 0)
580 dir += strlen(cfg->chrootdir);
583 fatal_exit("Could not chdir to %s: %s",
584 dir, strerror(errno));
586 verbose(VERB_QUERY, "chdir to %s", dir);
590 /* drop permissions after chroot, getpwnam, pidfile, syslog done*/
592 if(cfg->username && cfg->username[0]) {
593 # ifdef HAVE_INITGROUPS
594 if(initgroups(cfg->username, gid) != 0)
595 log_warn("unable to initgroups %s: %s",
596 cfg->username, strerror(errno));
597 # endif /* HAVE_INITGROUPS */
600 #ifdef HAVE_SETRESGID
601 if(setresgid(gid,gid,gid) != 0)
602 #elif defined(HAVE_SETREGID) && !defined(DARWIN_BROKEN_SETREUID)
603 if(setregid(gid,gid) != 0)
604 #else /* use setgid */
606 #endif /* HAVE_SETRESGID */
607 fatal_exit("unable to set group id of %s: %s",
608 cfg->username, strerror(errno));
609 #ifdef HAVE_SETRESUID
610 if(setresuid(uid,uid,uid) != 0)
611 #elif defined(HAVE_SETREUID) && !defined(DARWIN_BROKEN_SETREUID)
612 if(setreuid(uid,uid) != 0)
613 #else /* use setuid */
615 #endif /* HAVE_SETRESUID */
616 fatal_exit("unable to set user id of %s: %s",
617 cfg->username, strerror(errno));
618 verbose(VERB_QUERY, "drop user privileges, run as %s",
621 #endif /* HAVE_GETPWNAM */
622 /* file logging inited after chroot,chdir,setuid is done so that
623 * it would succeed on SIGHUP as well */
625 log_init(cfg->logfile, cfg->use_syslog, cfg->chrootdir);
630 * @param cfgfile: the config file name.
631 * @param cmdline_verbose: verbosity resulting from commandline -v.
632 * These increase verbosity as specified in the config file.
633 * @param debug_mode: if set, do not daemonize.
636 run_daemon(const char* cfgfile, int cmdline_verbose, int debug_mode)
638 struct config_file* cfg = NULL;
639 struct daemon* daemon = NULL;
642 if(!(daemon = daemon_init()))
643 fatal_exit("alloc failure");
644 while(!daemon->need_to_exit) {
646 verbose(VERB_OPS, "Restart of %s.", PACKAGE_STRING);
647 else verbose(VERB_OPS, "Start of %s.", PACKAGE_STRING);
650 if(!(cfg = config_create()))
651 fatal_exit("Could not alloc config defaults");
652 if(!config_read(cfg, cfgfile, daemon->chroot)) {
654 fatal_exit("Could not read config file: %s",
656 log_warn("Continuing with default config settings");
658 apply_settings(daemon, cfg, cmdline_verbose);
661 if(!daemon_open_shared_ports(daemon))
662 fatal_exit("could not open ports");
664 perform_setup(daemon, cfg, debug_mode, &cfgfile);
667 /* reopen log after HUP to facilitate log rotation */
669 log_init(cfg->logfile, 0, cfg->chrootdir);
674 /* clean up for restart */
675 verbose(VERB_ALGO, "cleanup.");
676 daemon_cleanup(daemon);
679 verbose(VERB_ALGO, "Exit cleanup.");
680 /* this unlink may not work if the pidfile is located outside
681 * of the chroot/workdir or we no longer have permissions */
682 if(daemon->pidfile) {
684 /* truncate pidfile */
685 fd = open(daemon->pidfile, O_WRONLY | O_TRUNC, 0644);
689 unlink(daemon->pidfile);
691 daemon_delete(daemon);
694 /** getopt global, in case header files fail to declare it. */
696 /** getopt global, in case header files fail to declare it. */
700 * main program. Set options given commandline arguments.
701 * @param argc: number of commandline arguments.
702 * @param argv: array of commandline arguments.
703 * @return: exit status of the program.
706 main(int argc, char* argv[])
709 const char* cfgfile = CONFIGFILE;
710 const char* winopt = NULL;
711 int cmdline_verbose = 0;
718 /* take debug snapshot of heap */
719 unbound_start_brk = sbrk(0);
722 log_init(NULL, 0, NULL);
723 log_ident_set(strrchr(argv[0],'/')?strrchr(argv[0],'/')+1:argv[0]);
724 /* parse the options */
725 while( (c=getopt(argc, argv, "c:dhvw:")) != -1) {
755 wsvc_command_option(winopt, cfgfile, cmdline_verbose,
758 fatal_exit("option not supported");
767 run_daemon(cfgfile, cmdline_verbose, debug_mode);
768 log_init(NULL, 0, NULL); /* close logfile */