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: local-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("-p do not create a pidfile.\n");
105 printf("-v verbose (more times to increase verbosity)\n");
107 printf("-w opt windows option: \n");
108 printf(" install, remove - manage the services entry\n");
109 printf(" service - used to start from services control panel\n");
111 printf("Version %s\n", PACKAGE_VERSION);
112 base = ub_default_event_base(0,&t,&now);
113 ub_get_event_sys(base, &evnm, &evsys, &evmethod);
114 printf("linked libs: %s %s (it uses %s), %s\n",
115 evnm, evsys, evmethod,
117 # ifdef SSLEAY_VERSION
118 SSLeay_version(SSLEAY_VERSION)
120 OpenSSL_version(OPENSSL_VERSION)
122 #elif defined(HAVE_NSS)
124 #elif defined(HAVE_NETTLE)
128 printf("linked modules:");
129 for(m = module_list_avail(); *m; m++)
133 printf("DNSCrypt feature available\n");
135 printf("BSD licensed, see LICENSE in source package for details.\n");
136 printf("Report bugs to %s\n", PACKAGE_BUGREPORT);
137 ub_event_base_free(base);
140 #ifndef unbound_testbound
141 int replay_var_compare(const void* ATTR_UNUSED(a), const void* ATTR_UNUSED(b))
148 /** check file descriptor count */
150 checkrlimits(struct config_file* cfg)
153 #ifdef HAVE_GETRLIMIT
154 /* list has number of ports to listen to, ifs number addresses */
155 int list = ((cfg->do_udp?1:0) + (cfg->do_tcp?1 +
156 (int)cfg->incoming_num_tcp:0));
157 size_t listen_ifs = (size_t)(cfg->num_ifs==0?
158 ((cfg->do_ip4 && !cfg->if_automatic?1:0) +
159 (cfg->do_ip6?1:0)):cfg->num_ifs);
160 size_t listen_num = list*listen_ifs;
161 size_t outudpnum = (size_t)cfg->outgoing_num_ports;
162 size_t outtcpnum = cfg->outgoing_num_tcp;
163 size_t misc = 4; /* logfile, pidfile, stdout... */
164 size_t perthread_noudp = listen_num + outtcpnum +
165 2/*cmdpipe*/ + 2/*libevent*/ + misc;
166 size_t perthread = perthread_noudp + outudpnum;
168 #if !defined(HAVE_PTHREAD) && !defined(HAVE_SOLARIS_THREADS)
169 int numthread = 1; /* it forks */
171 int numthread = (cfg->num_threads?cfg->num_threads:1);
173 size_t total = numthread * perthread + misc;
178 strncmp(ub_event_get_version(), "mini-event", 10) == 0) {
179 log_warn("too many file descriptors requested. The builtin"
180 "mini-event cannot handle more than 1024. Config "
181 "for less fds or compile with libevent");
182 if(numthread*perthread_noudp+15 > 1024)
183 fatal_exit("too much tcp. not enough fds.");
184 cfg->outgoing_num_ports = (int)((1024
185 - numthread*perthread_noudp
186 - 10 /* safety margin */) /numthread);
187 log_warn("continuing with less udp ports: %u",
188 cfg->outgoing_num_ports);
192 strncmp(ub_event_get_version(), "winsock-event", 13) == 0) {
193 log_err("too many file descriptors requested. The winsock"
194 " event handler cannot handle more than 64 per "
195 " thread. Config for less fds");
196 if(perthread_noudp+2 > 64)
197 fatal_exit("too much tcp. not enough fds.");
198 cfg->outgoing_num_ports = (int)((64
200 - 2/* safety margin */));
201 log_warn("continuing with less udp ports: %u",
202 cfg->outgoing_num_ports);
203 total = numthread*(perthread_noudp+
204 (size_t)cfg->outgoing_num_ports)+misc;
206 if(getrlimit(RLIMIT_NOFILE, &rlim) < 0) {
207 log_warn("getrlimit: %s", strerror(errno));
210 if(rlim.rlim_cur == (rlim_t)RLIM_INFINITY)
212 if((size_t)rlim.rlim_cur < total) {
213 avail = (size_t)rlim.rlim_cur;
214 rlim.rlim_cur = (rlim_t)(total + 10);
215 rlim.rlim_max = (rlim_t)(total + 10);
216 #ifdef HAVE_SETRLIMIT
217 if(setrlimit(RLIMIT_NOFILE, &rlim) < 0) {
218 log_warn("setrlimit: %s", strerror(errno));
220 log_warn("cannot increase max open fds from %u to %u",
221 (unsigned)avail, (unsigned)total+10);
222 /* check that calculation below does not underflow,
223 * with 15 as margin */
224 if(numthread*perthread_noudp+15 > avail)
225 fatal_exit("too much tcp. not enough fds.");
226 cfg->outgoing_num_ports = (int)((avail
227 - numthread*perthread_noudp
228 - 10 /* safety margin */) /numthread);
229 log_warn("continuing with less udp ports: %u",
230 cfg->outgoing_num_ports);
231 log_warn("increase ulimit or decrease threads, "
232 "ports in config to remove this warning");
234 #ifdef HAVE_SETRLIMIT
237 verbose(VERB_ALGO, "increased limit(open files) from %u to %u",
238 (unsigned)avail, (unsigned)total+10);
242 #endif /* HAVE_GETRLIMIT */
243 #endif /* S_SPLINT_S */
246 /** set default logfile identity based on value from argv[0] at startup **/
248 log_ident_set_fromdefault(struct config_file* cfg,
249 const char *log_default_identity)
251 if(cfg->log_identity == NULL || cfg->log_identity[0] == 0)
252 log_ident_set(log_default_identity);
254 log_ident_set(cfg->log_identity);
257 /** set verbosity, check rlimits, cache settings */
259 apply_settings(struct daemon* daemon, struct config_file* cfg,
260 int cmdline_verbose, int debug_mode, const char* log_default_identity)
262 /* apply if they have changed */
263 verbosity = cmdline_verbose + cfg->verbosity;
264 if (debug_mode > 1) {
269 daemon_apply_cfg(daemon, cfg);
272 if (cfg->use_systemd && cfg->do_daemonize) {
273 log_warn("use-systemd and do-daemonize should not be enabled at the same time");
276 log_ident_set_fromdefault(cfg, log_default_identity);
280 /** Read existing pid from pidfile.
281 * @param file: file name of pid file.
282 * @return: the pid from the file or -1 if none.
285 readpid (const char* file)
293 if ((fd = open(file, O_RDONLY)) == -1) {
295 log_err("Could not read pidfile %s: %s",
296 file, strerror(errno));
300 if (((l = read(fd, pidbuf, sizeof(pidbuf)))) == -1) {
302 log_err("Could not read pidfile %s: %s",
303 file, strerror(errno));
310 /* Empty pidfile means no pidfile... */
315 pidbuf[sizeof(pidbuf)-1] = 0;
316 pid = (pid_t)strtol(pidbuf, &t, 10);
318 if (*t && *t != '\n') {
324 /** write pid to file.
325 * @param pidfile: file name of pid file.
326 * @param pid: pid to write to file.
329 writepid (const char* pidfile, pid_t pid)
333 if ((f = fopen(pidfile, "w")) == NULL ) {
334 log_err("cannot open pidfile %s: %s",
335 pidfile, strerror(errno));
338 if(fprintf(f, "%lu\n", (unsigned long)pid) < 0) {
339 log_err("cannot write to pidfile %s: %s",
340 pidfile, strerror(errno));
346 * check old pid file.
347 * @param pidfile: the file name of the pid file.
348 * @param inchroot: if pidfile is inchroot and we can thus expect to
349 * be able to delete it.
352 checkoldpid(char* pidfile, int inchroot)
355 if((old = readpid(pidfile)) != -1) {
356 /* see if it is still alive */
357 if(kill(old, 0) == 0 || errno == EPERM)
358 log_warn("unbound is already running as pid %u.",
361 log_warn("did not exit gracefully last time (%u)",
365 #endif /* HAVE_KILL */
367 /** detach from command line */
371 #if defined(HAVE_DAEMON) && !defined(DEPRECATED_DAEMON)
372 /* use POSIX daemon(3) function */
373 if(daemon(1, 0) != 0)
374 fatal_exit("daemon failed: %s", strerror(errno));
375 #else /* no HAVE_DAEMON */
383 fatal_exit("fork failed: %s", strerror(errno));
385 /* exit interactive session */
391 fatal_exit("setsid() failed: %s", strerror(errno));
393 if ((fd = open("/dev/null", O_RDWR, 0)) != -1) {
394 (void)dup2(fd, STDIN_FILENO);
395 (void)dup2(fd, STDOUT_FILENO);
396 (void)dup2(fd, STDERR_FILENO);
400 #endif /* HAVE_FORK */
401 #endif /* HAVE_DAEMON */
404 /** daemonize, drop user privileges and chroot if needed */
406 perform_setup(struct daemon* daemon, struct config_file* cfg, int debug_mode,
407 const char** cfgfile, int need_pidfile)
413 struct passwd *pwd = NULL;
415 if(cfg->username && cfg->username[0]) {
416 if((pwd = getpwnam(cfg->username)) == NULL)
417 fatal_exit("user '%s' does not exist.", cfg->username);
418 /* endpwent below, in case we need pwd for setusercontext */
422 w_config_adjust_directory(cfg);
425 /* read ssl keys while superuser and outside chroot */
427 if(!(daemon->rc = daemon_remote_create(cfg)))
428 fatal_exit("could not set up remote-control");
429 if(cfg->ssl_service_key && cfg->ssl_service_key[0]) {
430 if(!(daemon->listen_sslctx = listen_sslctx_create(
431 cfg->ssl_service_key, cfg->ssl_service_pem, NULL)))
432 fatal_exit("could not set up listen SSL_CTX");
434 if(!(daemon->connect_sslctx = connect_sslctx_create(NULL, NULL,
435 cfg->tls_cert_bundle, cfg->tls_win_cert)))
436 fatal_exit("could not set up connect SSL_CTX");
439 /* init syslog (as root) if needed, before daemonize, otherwise
440 * a fork error could not be printed since daemonize closed stderr.*/
441 if(cfg->use_syslog) {
442 log_init(cfg->logfile, cfg->use_syslog, cfg->chrootdir);
444 /* if using a logfile, we cannot open it because the logfile would
445 * be created with the wrong permissions, we cannot chown it because
446 * we cannot chown system logfiles, so we do not open at all.
447 * So, using a logfile, the user does not see errors unless -d is
448 * given to unbound on the commandline. */
451 /* true if pidfile is inside chrootdir, or nochroot */
452 pidinchroot = need_pidfile && (!(cfg->chrootdir && cfg->chrootdir[0]) ||
453 (cfg->chrootdir && cfg->chrootdir[0] &&
454 strncmp(cfg->pidfile, cfg->chrootdir,
455 strlen(cfg->chrootdir))==0));
457 /* check old pid file before forking */
458 if(cfg->pidfile && cfg->pidfile[0] && need_pidfile) {
459 /* calculate position of pidfile */
460 if(cfg->pidfile[0] == '/')
461 daemon->pidfile = strdup(cfg->pidfile);
462 else daemon->pidfile = fname_after_chroot(cfg->pidfile,
465 fatal_exit("pidfile alloc: out of memory");
466 checkoldpid(daemon->pidfile, pidinchroot);
470 /* daemonize because pid is needed by the writepid func */
471 if(!debug_mode && cfg->do_daemonize) {
475 /* write new pidfile (while still root, so can be outside chroot) */
477 if(cfg->pidfile && cfg->pidfile[0] && need_pidfile) {
478 writepid(daemon->pidfile, getpid());
479 if(cfg->username && cfg->username[0] && cfg_uid != (uid_t)-1 &&
482 if(chown(daemon->pidfile, cfg_uid, cfg_gid) == -1) {
483 verbose(VERB_QUERY, "cannot chown %u.%u %s: %s",
484 (unsigned)cfg_uid, (unsigned)cfg_gid,
485 daemon->pidfile, strerror(errno));
487 # endif /* HAVE_CHOWN */
493 #endif /* HAVE_KILL */
495 /* Set user context */
497 if(cfg->username && cfg->username[0] && cfg_uid != (uid_t)-1) {
498 #ifdef HAVE_SETUSERCONTEXT
499 /* setusercontext does initgroups, setuid, setgid, and
500 * also resource limits from login config, but we
501 * still call setresuid, setresgid to be sure to set all uid*/
502 if(setusercontext(NULL, pwd, cfg_uid, (unsigned)
503 LOGIN_SETALL & ~LOGIN_SETUSER & ~LOGIN_SETGROUP) != 0)
504 log_warn("unable to setusercontext %s: %s",
505 cfg->username, strerror(errno));
506 #endif /* HAVE_SETUSERCONTEXT */
508 #endif /* HAVE_GETPWNAM */
510 /* box into the chroot */
512 if(cfg->chrootdir && cfg->chrootdir[0]) {
513 if(chdir(cfg->chrootdir)) {
514 fatal_exit("unable to chdir to chroot %s: %s",
515 cfg->chrootdir, strerror(errno));
517 verbose(VERB_QUERY, "chdir to %s", cfg->chrootdir);
518 if(chroot(cfg->chrootdir))
519 fatal_exit("unable to chroot to %s: %s",
520 cfg->chrootdir, strerror(errno));
522 fatal_exit("unable to chdir to / in chroot %s: %s",
523 cfg->chrootdir, strerror(errno));
524 verbose(VERB_QUERY, "chroot to %s", cfg->chrootdir);
525 if(strncmp(*cfgfile, cfg->chrootdir,
526 strlen(cfg->chrootdir)) == 0)
527 (*cfgfile) += strlen(cfg->chrootdir);
529 /* adjust stored pidfile for chroot */
530 if(daemon->pidfile && daemon->pidfile[0] &&
531 strncmp(daemon->pidfile, cfg->chrootdir,
532 strlen(cfg->chrootdir))==0) {
533 char* old = daemon->pidfile;
534 daemon->pidfile = strdup(old+strlen(cfg->chrootdir));
537 log_err("out of memory in pidfile adjust");
539 daemon->chroot = strdup(cfg->chrootdir);
541 log_err("out of memory in daemon chroot dir storage");
546 /* change to working directory inside chroot */
547 if(cfg->directory && cfg->directory[0]) {
548 char* dir = cfg->directory;
549 if(cfg->chrootdir && cfg->chrootdir[0] &&
550 strncmp(dir, cfg->chrootdir,
551 strlen(cfg->chrootdir)) == 0)
552 dir += strlen(cfg->chrootdir);
555 fatal_exit("Could not chdir to %s: %s",
556 dir, strerror(errno));
558 verbose(VERB_QUERY, "chdir to %s", dir);
562 /* drop permissions after chroot, getpwnam, pidfile, syslog done*/
564 if(cfg->username && cfg->username[0] && cfg_uid != (uid_t)-1) {
565 # ifdef HAVE_INITGROUPS
566 if(initgroups(cfg->username, cfg_gid) != 0)
567 log_warn("unable to initgroups %s: %s",
568 cfg->username, strerror(errno));
569 # endif /* HAVE_INITGROUPS */
570 # ifdef HAVE_ENDPWENT
574 #ifdef HAVE_SETRESGID
575 if(setresgid(cfg_gid,cfg_gid,cfg_gid) != 0)
576 #elif defined(HAVE_SETREGID) && !defined(DARWIN_BROKEN_SETREUID)
577 if(setregid(cfg_gid,cfg_gid) != 0)
578 #else /* use setgid */
579 if(setgid(cfg_gid) != 0)
580 #endif /* HAVE_SETRESGID */
581 fatal_exit("unable to set group id of %s: %s",
582 cfg->username, strerror(errno));
583 #ifdef HAVE_SETRESUID
584 if(setresuid(cfg_uid,cfg_uid,cfg_uid) != 0)
585 #elif defined(HAVE_SETREUID) && !defined(DARWIN_BROKEN_SETREUID)
586 if(setreuid(cfg_uid,cfg_uid) != 0)
587 #else /* use setuid */
588 if(setuid(cfg_uid) != 0)
589 #endif /* HAVE_SETRESUID */
590 fatal_exit("unable to set user id of %s: %s",
591 cfg->username, strerror(errno));
592 verbose(VERB_QUERY, "drop user privileges, run as %s",
595 #endif /* HAVE_GETPWNAM */
596 /* file logging inited after chroot,chdir,setuid is done so that
597 * it would succeed on SIGHUP as well */
599 log_init(cfg->logfile, cfg->use_syslog, cfg->chrootdir);
604 * @param cfgfile: the config file name.
605 * @param cmdline_verbose: verbosity resulting from commandline -v.
606 * These increase verbosity as specified in the config file.
607 * @param debug_mode: if set, do not daemonize.
608 * @param log_default_identity: Default identity to report in logs
609 * @param need_pidfile: if false, no pidfile is checked or created.
612 run_daemon(const char* cfgfile, int cmdline_verbose, int debug_mode, const char* log_default_identity, int need_pidfile)
614 struct config_file* cfg = NULL;
615 struct daemon* daemon = NULL;
618 if(!(daemon = daemon_init()))
619 fatal_exit("alloc failure");
620 while(!daemon->need_to_exit) {
622 verbose(VERB_OPS, "Restart of %s.", PACKAGE_STRING);
623 else verbose(VERB_OPS, "Start of %s.", PACKAGE_STRING);
626 if(!(cfg = config_create()))
627 fatal_exit("Could not alloc config defaults");
628 if(!config_read(cfg, cfgfile, daemon->chroot)) {
630 fatal_exit("Could not read config file: %s."
631 " Maybe try unbound -dd, it stays on "
632 "the commandline to see more errors, "
633 "or unbound-checkconf", cfgfile);
634 log_warn("Continuing with default config settings");
636 apply_settings(daemon, cfg, cmdline_verbose, debug_mode, log_default_identity);
638 config_lookup_uid(cfg);
641 if(!daemon_open_shared_ports(daemon))
642 fatal_exit("could not open ports");
644 perform_setup(daemon, cfg, debug_mode, &cfgfile, need_pidfile);
647 /* reopen log after HUP to facilitate log rotation */
649 log_init(cfg->logfile, 0, cfg->chrootdir);
654 /* clean up for restart */
655 verbose(VERB_ALGO, "cleanup.");
656 daemon_cleanup(daemon);
659 verbose(VERB_ALGO, "Exit cleanup.");
660 /* this unlink may not work if the pidfile is located outside
661 * of the chroot/workdir or we no longer have permissions */
662 if(daemon->pidfile) {
664 /* truncate pidfile */
665 fd = open(daemon->pidfile, O_WRONLY | O_TRUNC, 0644);
669 unlink(daemon->pidfile);
671 daemon_delete(daemon);
674 /** getopt global, in case header files fail to declare it. */
676 /** getopt global, in case header files fail to declare it. */
680 * main program. Set options given commandline arguments.
681 * @param argc: number of commandline arguments.
682 * @param argv: array of commandline arguments.
683 * @return: exit status of the program.
686 main(int argc, char* argv[])
689 const char* cfgfile = CONFIGFILE;
690 const char* winopt = NULL;
691 const char* log_ident_default;
692 int cmdline_verbose = 0;
694 int need_pidfile = 1;
700 log_init(NULL, 0, NULL);
701 log_ident_default = strrchr(argv[0],'/')?strrchr(argv[0],'/')+1:argv[0];
702 log_ident_set(log_ident_default);
703 /* parse the options */
704 while( (c=getopt(argc, argv, "c:dhpvw:")) != -1) {
737 wsvc_command_option(winopt, cfgfile, cmdline_verbose,
740 fatal_exit("option not supported");
749 run_daemon(cfgfile, cmdline_verbose, debug_mode, log_ident_default, need_pidfile);
750 log_init(NULL, 0, NULL); /* close logfile */
751 #ifndef unbound_testbound
753 lock_quick_destroy((lock_quick_type*)log_get_lock());