]>
git.saurik.com Git - apple/network_cmds.git/blob - unbound/daemon/unbound.c
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"
90 # include "event2/event.h"
91 # include "event2/event_struct.h"
92 # include "event2/event_compat.h"
97 # include "winrc/win_svc.h"
106 /** global debug value to keep track of heap memory allocation */
107 void* unbound_start_brk
= 0;
110 #if !defined(HAVE_EVENT_BASE_GET_METHOD) && (defined(HAVE_EV_LOOP) || defined(HAVE_EV_DEFAULT_LOOP))
111 static const char* ev_backend2str(int b
)
114 case EVBACKEND_SELECT
: return "select";
115 case EVBACKEND_POLL
: return "poll";
116 case EVBACKEND_EPOLL
: return "epoll";
117 case EVBACKEND_KQUEUE
: return "kqueue";
118 case EVBACKEND_DEVPOLL
: return "devpoll";
119 case EVBACKEND_PORT
: return "evport";
125 /** get the event system in use */
126 static void get_event_sys(const char** n
, const char** s
, const char** m
)
131 *m
= "WSAWaitForMultipleEvents";
132 #elif defined(USE_MINI_EVENT)
137 struct event_base
* b
;
138 *s
= event_get_version();
139 # ifdef HAVE_EVENT_BASE_GET_METHOD
141 b
= event_base_new();
142 *m
= event_base_get_method(b
);
143 # elif defined(HAVE_EV_LOOP) || defined(HAVE_EV_DEFAULT_LOOP)
145 b
= (struct event_base
*)ev_default_loop(EVFLAG_AUTO
);
146 *m
= ev_backend2str(ev_backend((struct ev_loop
*)b
));
149 *m
= "not obtainable";
152 # ifdef HAVE_EVENT_BASE_FREE
162 const char *evnm
="event", *evsys
="", *evmethod
="";
163 printf("usage: unbound [options]\n");
164 printf(" start unbound daemon DNS resolver.\n");
165 printf("-h this help\n");
166 printf("-c file config file to read instead of %s\n", CONFIGFILE
);
167 printf(" file format is described in unbound.conf(5).\n");
168 printf("-d do not fork into the background.\n");
169 printf("-v verbose (more times to increase verbosity)\n");
171 printf("-w opt windows option: \n");
172 printf(" install, remove - manage the services entry\n");
173 printf(" service - used to start from services control panel\n");
175 printf("Version %s\n", PACKAGE_VERSION
);
176 get_event_sys(&evnm
, &evsys
, &evmethod
);
177 printf("linked libs: %s %s (it uses %s), %s\n",
178 evnm
, evsys
, evmethod
,
180 SSLeay_version(SSLEAY_VERSION
)
181 #elif defined(HAVE_NSS)
185 printf("linked modules:");
186 for(m
= module_list_avail(); *m
; m
++)
189 printf("BSD licensed, see LICENSE in source package for details.\n");
190 printf("Report bugs to %s\n", PACKAGE_BUGREPORT
);
193 #ifndef unbound_testbound
194 int replay_var_compare(const void* ATTR_UNUSED(a
), const void* ATTR_UNUSED(b
))
201 /** check file descriptor count */
203 checkrlimits(struct config_file
* cfg
)
206 #ifdef HAVE_GETRLIMIT
207 /* list has number of ports to listen to, ifs number addresses */
208 int list
= ((cfg
->do_udp
?1:0) + (cfg
->do_tcp
?1 +
209 (int)cfg
->incoming_num_tcp
:0));
210 size_t listen_ifs
= (size_t)(cfg
->num_ifs
==0?
211 ((cfg
->do_ip4
&& !cfg
->if_automatic
?1:0) +
212 (cfg
->do_ip6
?1:0)):cfg
->num_ifs
);
213 size_t listen_num
= list
*listen_ifs
;
214 size_t outudpnum
= (size_t)cfg
->outgoing_num_ports
;
215 size_t outtcpnum
= cfg
->outgoing_num_tcp
;
216 size_t misc
= 4; /* logfile, pidfile, stdout... */
217 size_t perthread_noudp
= listen_num
+ outtcpnum
+
218 2/*cmdpipe*/ + 2/*libevent*/ + misc
;
219 size_t perthread
= perthread_noudp
+ outudpnum
;
221 #if !defined(HAVE_PTHREAD) && !defined(HAVE_SOLARIS_THREADS)
222 int numthread
= 1; /* it forks */
224 int numthread
= (cfg
->num_threads
?cfg
->num_threads
:1);
226 size_t total
= numthread
* perthread
+ misc
;
231 strncmp(event_get_version(), "mini-event", 10) == 0) {
232 log_warn("too many file descriptors requested. The builtin"
233 "mini-event cannot handle more than 1024. Config "
234 "for less fds or compile with libevent");
235 if(numthread
*perthread_noudp
+15 > 1024)
236 fatal_exit("too much tcp. not enough fds.");
237 cfg
->outgoing_num_ports
= (int)((1024
238 - numthread
*perthread_noudp
239 - 10 /* safety margin */) /numthread
);
240 log_warn("continuing with less udp ports: %u",
241 cfg
->outgoing_num_ports
);
245 strncmp(event_get_version(), "winsock-event", 13) == 0) {
246 log_err("too many file descriptors requested. The winsock"
247 " event handler cannot handle more than 64 per "
248 " thread. Config for less fds");
249 if(perthread_noudp
+2 > 64)
250 fatal_exit("too much tcp. not enough fds.");
251 cfg
->outgoing_num_ports
= (int)((64
253 - 2/* safety margin */));
254 log_warn("continuing with less udp ports: %u",
255 cfg
->outgoing_num_ports
);
256 total
= numthread
*(perthread_noudp
+
257 (size_t)cfg
->outgoing_num_ports
)+misc
;
259 if(getrlimit(RLIMIT_NOFILE
, &rlim
) < 0) {
260 log_warn("getrlimit: %s", strerror(errno
));
263 if(rlim
.rlim_cur
== (rlim_t
)RLIM_INFINITY
)
265 if((size_t)rlim
.rlim_cur
< total
) {
266 avail
= (size_t)rlim
.rlim_cur
;
267 rlim
.rlim_cur
= (rlim_t
)(total
+ 10);
268 rlim
.rlim_max
= (rlim_t
)(total
+ 10);
269 #ifdef HAVE_SETRLIMIT
270 if(setrlimit(RLIMIT_NOFILE
, &rlim
) < 0) {
271 log_warn("setrlimit: %s", strerror(errno
));
273 log_warn("cannot increase max open fds from %u to %u",
274 (unsigned)avail
, (unsigned)total
+10);
275 /* check that calculation below does not underflow,
276 * with 15 as margin */
277 if(numthread
*perthread_noudp
+15 > avail
)
278 fatal_exit("too much tcp. not enough fds.");
279 cfg
->outgoing_num_ports
= (int)((avail
280 - numthread
*perthread_noudp
281 - 10 /* safety margin */) /numthread
);
282 log_warn("continuing with less udp ports: %u",
283 cfg
->outgoing_num_ports
);
284 log_warn("increase ulimit or decrease threads, "
285 "ports in config to remove this warning");
287 #ifdef HAVE_SETRLIMIT
290 verbose(VERB_ALGO
, "increased limit(open files) from %u to %u",
291 (unsigned)avail
, (unsigned)total
+10);
295 #endif /* HAVE_GETRLIMIT */
296 #endif /* S_SPLINT_S */
299 /** set verbosity, check rlimits, cache settings */
301 apply_settings(struct daemon
* daemon
, struct config_file
* cfg
,
302 int cmdline_verbose
, int debug_mode
)
304 /* apply if they have changed */
305 verbosity
= cmdline_verbose
+ cfg
->verbosity
;
306 if (debug_mode
> 1) {
310 daemon_apply_cfg(daemon
, cfg
);
315 /** Read existing pid from pidfile.
316 * @param file: file name of pid file.
317 * @return: the pid from the file or -1 if none.
320 readpid (const char* file
)
328 if ((fd
= open(file
, O_RDONLY
)) == -1) {
330 log_err("Could not read pidfile %s: %s",
331 file
, strerror(errno
));
335 if (((l
= read(fd
, pidbuf
, sizeof(pidbuf
)))) == -1) {
337 log_err("Could not read pidfile %s: %s",
338 file
, strerror(errno
));
345 /* Empty pidfile means no pidfile... */
350 pidbuf
[sizeof(pidbuf
)-1] = 0;
351 pid
= (pid_t
)strtol(pidbuf
, &t
, 10);
353 if (*t
&& *t
!= '\n') {
359 /** write pid to file.
360 * @param pidfile: file name of pid file.
361 * @param pid: pid to write to file.
364 writepid (const char* pidfile
, pid_t pid
)
368 if ((f
= fopen(pidfile
, "w")) == NULL
) {
369 log_err("cannot open pidfile %s: %s",
370 pidfile
, strerror(errno
));
373 if(fprintf(f
, "%lu\n", (unsigned long)pid
) < 0) {
374 log_err("cannot write to pidfile %s: %s",
375 pidfile
, strerror(errno
));
381 * check old pid file.
382 * @param pidfile: the file name of the pid file.
383 * @param inchroot: if pidfile is inchroot and we can thus expect to
384 * be able to delete it.
387 checkoldpid(char* pidfile
, int inchroot
)
390 if((old
= readpid(pidfile
)) != -1) {
391 /* see if it is still alive */
392 if(kill(old
, 0) == 0 || errno
== EPERM
)
393 log_warn("unbound is already running as pid %u.",
396 log_warn("did not exit gracefully last time (%u)",
400 #endif /* HAVE_KILL */
402 /** detach from command line */
406 #if defined(HAVE_DAEMON) && !defined(DEPRECATED_DAEMON)
407 /* use POSIX daemon(3) function */
408 if(daemon(1, 0) != 0)
409 fatal_exit("daemon failed: %s", strerror(errno
));
410 #else /* no HAVE_DAEMON */
418 fatal_exit("fork failed: %s", strerror(errno
));
420 /* exit interactive session */
426 fatal_exit("setsid() failed: %s", strerror(errno
));
428 if ((fd
= open("/dev/null", O_RDWR
, 0)) != -1) {
429 (void)dup2(fd
, STDIN_FILENO
);
430 (void)dup2(fd
, STDOUT_FILENO
);
431 (void)dup2(fd
, STDERR_FILENO
);
435 #endif /* HAVE_FORK */
436 #endif /* HAVE_DAEMON */
439 /** daemonize, drop user priviliges and chroot if needed */
441 perform_setup(struct daemon
* daemon
, struct config_file
* cfg
, int debug_mode
,
442 const char** cfgfile
)
445 struct passwd
*pwd
= NULL
;
448 /* initialize, but not to 0 (root) */
449 memset(&uid
, 112, sizeof(uid
));
450 memset(&gid
, 112, sizeof(gid
));
453 if(cfg
->username
&& cfg
->username
[0]) {
454 if((pwd
= getpwnam(cfg
->username
)) == NULL
)
455 fatal_exit("user '%s' does not exist.", cfg
->username
);
458 /* endpwent below, in case we need pwd for setusercontext */
462 /* init syslog (as root) if needed, before daemonize, otherwise
463 * a fork error could not be printed since daemonize closed stderr.*/
464 if(cfg
->use_syslog
) {
465 log_init(cfg
->logfile
, cfg
->use_syslog
, cfg
->chrootdir
);
467 /* if using a logfile, we cannot open it because the logfile would
468 * be created with the wrong permissions, we cannot chown it because
469 * we cannot chown system logfiles, so we do not open at all.
470 * So, using a logfile, the user does not see errors unless -d is
471 * given to unbound on the commandline. */
473 /* read ssl keys while superuser and outside chroot */
475 if(!(daemon
->rc
= daemon_remote_create(cfg
)))
476 fatal_exit("could not set up remote-control");
477 if(cfg
->ssl_service_key
&& cfg
->ssl_service_key
[0]) {
478 if(!(daemon
->listen_sslctx
= listen_sslctx_create(
479 cfg
->ssl_service_key
, cfg
->ssl_service_pem
, NULL
)))
480 fatal_exit("could not set up listen SSL_CTX");
482 if(!(daemon
->connect_sslctx
= connect_sslctx_create(NULL
, NULL
, NULL
)))
483 fatal_exit("could not set up connect SSL_CTX");
487 /* check old pid file before forking */
488 if(cfg
->pidfile
&& cfg
->pidfile
[0]) {
489 /* calculate position of pidfile */
490 if(cfg
->pidfile
[0] == '/')
491 daemon
->pidfile
= strdup(cfg
->pidfile
);
492 else daemon
->pidfile
= fname_after_chroot(cfg
->pidfile
,
495 fatal_exit("pidfile alloc: out of memory");
496 checkoldpid(daemon
->pidfile
,
497 /* true if pidfile is inside chrootdir, or nochroot */
498 !(cfg
->chrootdir
&& cfg
->chrootdir
[0]) ||
499 (cfg
->chrootdir
&& cfg
->chrootdir
[0] &&
500 strncmp(daemon
->pidfile
, cfg
->chrootdir
,
501 strlen(cfg
->chrootdir
))==0));
505 /* daemonize because pid is needed by the writepid func */
506 if(!debug_mode
&& cfg
->do_daemonize
) {
510 /* write new pidfile (while still root, so can be outside chroot) */
512 if(cfg
->pidfile
&& cfg
->pidfile
[0]) {
513 writepid(daemon
->pidfile
, getpid());
514 if(!(cfg
->chrootdir
&& cfg
->chrootdir
[0]) ||
515 (cfg
->chrootdir
&& cfg
->chrootdir
[0] &&
516 strncmp(daemon
->pidfile
, cfg
->chrootdir
,
517 strlen(cfg
->chrootdir
))==0)) {
518 /* delete of pidfile could potentially work,
519 * chown to get permissions */
520 if(cfg
->username
&& cfg
->username
[0]) {
521 if(chown(daemon
->pidfile
, uid
, gid
) == -1) {
522 log_err("cannot chown %u.%u %s: %s",
523 (unsigned)uid
, (unsigned)gid
,
524 daemon
->pidfile
, strerror(errno
));
533 /* Set user context */
535 if(cfg
->username
&& cfg
->username
[0]) {
536 #ifdef HAVE_SETUSERCONTEXT
537 /* setusercontext does initgroups, setuid, setgid, and
538 * also resource limits from login config, but we
539 * still call setresuid, setresgid to be sure to set all uid*/
540 if(setusercontext(NULL
, pwd
, uid
, (unsigned)
541 LOGIN_SETALL
& ~LOGIN_SETUSER
& ~LOGIN_SETGROUP
) != 0)
542 log_warn("unable to setusercontext %s: %s",
543 cfg
->username
, strerror(errno
));
544 #endif /* HAVE_SETUSERCONTEXT */
546 #endif /* HAVE_GETPWNAM */
548 /* box into the chroot */
550 if(cfg
->chrootdir
&& cfg
->chrootdir
[0]) {
551 if(chdir(cfg
->chrootdir
)) {
552 fatal_exit("unable to chdir to chroot %s: %s",
553 cfg
->chrootdir
, strerror(errno
));
555 verbose(VERB_QUERY
, "chdir to %s", cfg
->chrootdir
);
556 if(chroot(cfg
->chrootdir
))
557 fatal_exit("unable to chroot to %s: %s",
558 cfg
->chrootdir
, strerror(errno
));
560 fatal_exit("unable to chdir to / in chroot %s: %s",
561 cfg
->chrootdir
, strerror(errno
));
562 verbose(VERB_QUERY
, "chroot to %s", cfg
->chrootdir
);
563 if(strncmp(*cfgfile
, cfg
->chrootdir
,
564 strlen(cfg
->chrootdir
)) == 0)
565 (*cfgfile
) += strlen(cfg
->chrootdir
);
567 /* adjust stored pidfile for chroot */
568 if(daemon
->pidfile
&& daemon
->pidfile
[0] &&
569 strncmp(daemon
->pidfile
, cfg
->chrootdir
,
570 strlen(cfg
->chrootdir
))==0) {
571 char* old
= daemon
->pidfile
;
572 daemon
->pidfile
= strdup(old
+strlen(cfg
->chrootdir
));
575 log_err("out of memory in pidfile adjust");
577 daemon
->chroot
= strdup(cfg
->chrootdir
);
579 log_err("out of memory in daemon chroot dir storage");
584 /* change to working directory inside chroot */
585 if(cfg
->directory
&& cfg
->directory
[0]) {
586 char* dir
= cfg
->directory
;
587 if(cfg
->chrootdir
&& cfg
->chrootdir
[0] &&
588 strncmp(dir
, cfg
->chrootdir
,
589 strlen(cfg
->chrootdir
)) == 0)
590 dir
+= strlen(cfg
->chrootdir
);
593 fatal_exit("Could not chdir to %s: %s",
594 dir
, strerror(errno
));
596 verbose(VERB_QUERY
, "chdir to %s", dir
);
600 /* drop permissions after chroot, getpwnam, pidfile, syslog done*/
602 if(cfg
->username
&& cfg
->username
[0]) {
603 # ifdef HAVE_INITGROUPS
604 if(initgroups(cfg
->username
, gid
) != 0)
605 log_warn("unable to initgroups %s: %s",
606 cfg
->username
, strerror(errno
));
607 # endif /* HAVE_INITGROUPS */
610 #ifdef HAVE_SETRESGID
611 if(setresgid(gid
,gid
,gid
) != 0)
612 #elif defined(HAVE_SETREGID) && !defined(DARWIN_BROKEN_SETREUID)
613 if(setregid(gid
,gid
) != 0)
614 #else /* use setgid */
616 #endif /* HAVE_SETRESGID */
617 fatal_exit("unable to set group id of %s: %s",
618 cfg
->username
, strerror(errno
));
619 #ifdef HAVE_SETRESUID
620 if(setresuid(uid
,uid
,uid
) != 0)
621 #elif defined(HAVE_SETREUID) && !defined(DARWIN_BROKEN_SETREUID)
622 if(setreuid(uid
,uid
) != 0)
623 #else /* use setuid */
625 #endif /* HAVE_SETRESUID */
626 fatal_exit("unable to set user id of %s: %s",
627 cfg
->username
, strerror(errno
));
628 verbose(VERB_QUERY
, "drop user privileges, run as %s",
631 #endif /* HAVE_GETPWNAM */
632 /* file logging inited after chroot,chdir,setuid is done so that
633 * it would succeed on SIGHUP as well */
635 log_init(cfg
->logfile
, cfg
->use_syslog
, cfg
->chrootdir
);
640 * @param cfgfile: the config file name.
641 * @param cmdline_verbose: verbosity resulting from commandline -v.
642 * These increase verbosity as specified in the config file.
643 * @param debug_mode: if set, do not daemonize.
646 run_daemon(const char* cfgfile
, int cmdline_verbose
, int debug_mode
)
648 struct config_file
* cfg
= NULL
;
649 struct daemon
* daemon
= NULL
;
652 if(!(daemon
= daemon_init()))
653 fatal_exit("alloc failure");
654 while(!daemon
->need_to_exit
) {
656 verbose(VERB_OPS
, "Restart of %s.", PACKAGE_STRING
);
657 else verbose(VERB_OPS
, "Start of %s.", PACKAGE_STRING
);
660 if(!(cfg
= config_create()))
661 fatal_exit("Could not alloc config defaults");
662 if(!config_read(cfg
, cfgfile
, daemon
->chroot
)) {
664 fatal_exit("Could not read config file: %s",
666 log_warn("Continuing with default config settings");
668 apply_settings(daemon
, cfg
, cmdline_verbose
, debug_mode
);
671 if(!daemon_open_shared_ports(daemon
))
672 fatal_exit("could not open ports");
674 perform_setup(daemon
, cfg
, debug_mode
, &cfgfile
);
677 /* reopen log after HUP to facilitate log rotation */
679 log_init(cfg
->logfile
, 0, cfg
->chrootdir
);
684 /* clean up for restart */
685 verbose(VERB_ALGO
, "cleanup.");
686 daemon_cleanup(daemon
);
689 verbose(VERB_ALGO
, "Exit cleanup.");
690 /* this unlink may not work if the pidfile is located outside
691 * of the chroot/workdir or we no longer have permissions */
692 if(daemon
->pidfile
) {
694 /* truncate pidfile */
695 fd
= open(daemon
->pidfile
, O_WRONLY
| O_TRUNC
, 0644);
699 unlink(daemon
->pidfile
);
701 daemon_delete(daemon
);
704 /** getopt global, in case header files fail to declare it. */
706 /** getopt global, in case header files fail to declare it. */
710 * main program. Set options given commandline arguments.
711 * @param argc: number of commandline arguments.
712 * @param argv: array of commandline arguments.
713 * @return: exit status of the program.
716 main(int argc
, char* argv
[])
719 const char* cfgfile
= CONFIGFILE
;
720 const char* winopt
= NULL
;
721 int cmdline_verbose
= 0;
728 /* take debug snapshot of heap */
729 unbound_start_brk
= sbrk(0);
732 log_init(NULL
, 0, NULL
);
733 log_ident_set(strrchr(argv
[0],'/')?strrchr(argv
[0],'/')+1:argv
[0]);
734 /* parse the options */
735 while( (c
=getopt(argc
, argv
, "c:dhvw:")) != -1) {
765 wsvc_command_option(winopt
, cfgfile
, cmdline_verbose
,
768 fatal_exit("option not supported");
777 run_daemon(cfgfile
, cmdline_verbose
, debug_mode
);
778 log_init(NULL
, 0, NULL
); /* close logfile */