1238106Sdes/*
2238106Sdes * daemon/unbound.c - main program for unbound DNS resolver daemon.
3238106Sdes *
4238106Sdes * Copyright (c) 2007, NLnet Labs. All rights reserved.
5238106Sdes *
6238106Sdes * This software is open source.
7238106Sdes *
8238106Sdes * Redistribution and use in source and binary forms, with or without
9238106Sdes * modification, are permitted provided that the following conditions
10238106Sdes * are met:
11238106Sdes *
12238106Sdes * Redistributions of source code must retain the above copyright notice,
13238106Sdes * this list of conditions and the following disclaimer.
14238106Sdes *
15238106Sdes * Redistributions in binary form must reproduce the above copyright notice,
16238106Sdes * this list of conditions and the following disclaimer in the documentation
17238106Sdes * and/or other materials provided with the distribution.
18238106Sdes *
19238106Sdes * Neither the name of the NLNET LABS nor the names of its contributors may
20238106Sdes * be used to endorse or promote products derived from this software without
21238106Sdes * specific prior written permission.
22238106Sdes *
23238106Sdes * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
24266114Sdes * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
25266114Sdes * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
26266114Sdes * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
27266114Sdes * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
28266114Sdes * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
29266114Sdes * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
30266114Sdes * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
31266114Sdes * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
32266114Sdes * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
33266114Sdes * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
34238106Sdes *
35238106Sdes */
36238106Sdes
37238106Sdes/**
38238106Sdes * \file
39238106Sdes *
40238106Sdes * Main program to start the DNS resolver daemon.
41238106Sdes */
42238106Sdes
43238106Sdes#include "config.h"
44238106Sdes#ifdef HAVE_GETOPT_H
45238106Sdes#include <getopt.h>
46238106Sdes#endif
47238106Sdes#include <sys/time.h>
48238106Sdes#include "util/log.h"
49238106Sdes#include "daemon/daemon.h"
50238106Sdes#include "daemon/remote.h"
51238106Sdes#include "util/config_file.h"
52238106Sdes#include "util/storage/slabhash.h"
53238106Sdes#include "services/listen_dnsport.h"
54238106Sdes#include "services/cache/rrset.h"
55238106Sdes#include "services/cache/infra.h"
56255579Sdes#include "util/fptr_wlist.h"
57238106Sdes#include "util/data/msgreply.h"
58238106Sdes#include "util/module.h"
59238106Sdes#include "util/net_help.h"
60307729Sdes#include "util/ub_event.h"
61238106Sdes#include <signal.h>
62238106Sdes#include <fcntl.h>
63238106Sdes#include <openssl/crypto.h>
64238106Sdes#ifdef HAVE_PWD_H
65238106Sdes#include <pwd.h>
66238106Sdes#endif
67238106Sdes#ifdef HAVE_GRP_H
68238106Sdes#include <grp.h>
69238106Sdes#endif
70356345Scy#include <openssl/ssl.h>
71238106Sdes
72266114Sdes#ifndef S_SPLINT_S
73266114Sdes/* splint chokes on this system header file */
74238106Sdes#ifdef HAVE_SYS_RESOURCE_H
75238106Sdes#include <sys/resource.h>
76238106Sdes#endif
77266114Sdes#endif /* S_SPLINT_S */
78238106Sdes#ifdef HAVE_LOGIN_CAP_H
79238106Sdes#include <login_cap.h>
80238106Sdes#endif
81238106Sdes
82238106Sdes#ifdef UB_ON_WINDOWS
83238106Sdes#  include "winrc/win_svc.h"
84238106Sdes#endif
85238106Sdes
86249141Sdes#ifdef HAVE_NSS
87249141Sdes/* nss3 */
88249141Sdes#  include "nss.h"
89249141Sdes#endif
90249141Sdes
91366095Scy#ifdef HAVE_TARGETCONDITIONALS_H
92366095Scy#include <TargetConditionals.h>
93366095Scy#endif
94366095Scy
95368129Scy#if (defined(TARGET_OS_TV) && TARGET_OS_TV) || (defined(TARGET_OS_WATCH) && TARGET_OS_WATCH)
96366095Scy#undef HAVE_FORK
97366095Scy#endif
98366095Scy
99356345Scy/** print build options. */
100356345Scystatic void
101356345Scyprint_build_options(void)
102238106Sdes{
103238106Sdes	const char** m;
104238106Sdes	const char *evnm="event", *evsys="", *evmethod="";
105307729Sdes	time_t t;
106307729Sdes	struct timeval now;
107307729Sdes	struct ub_event_base* base;
108356345Scy	printf("Version %s\n\n", PACKAGE_VERSION);
109356345Scy	printf("Configure line: %s\n", CONFCMDLINE);
110307729Sdes	base = ub_default_event_base(0,&t,&now);
111307729Sdes	ub_get_event_sys(base, &evnm, &evsys, &evmethod);
112356345Scy	printf("Linked libs: %s %s (it uses %s), %s\n",
113266114Sdes		evnm, evsys, evmethod,
114249141Sdes#ifdef HAVE_SSL
115307729Sdes#  ifdef SSLEAY_VERSION
116249141Sdes		SSLeay_version(SSLEAY_VERSION)
117307729Sdes#  else
118307729Sdes		OpenSSL_version(OPENSSL_VERSION)
119307729Sdes#  endif
120249141Sdes#elif defined(HAVE_NSS)
121249141Sdes		NSS_GetVersion()
122292206Sdes#elif defined(HAVE_NETTLE)
123292206Sdes		"nettle"
124249141Sdes#endif
125249141Sdes		);
126356345Scy	printf("Linked modules:");
127238106Sdes	for(m = module_list_avail(); *m; m++)
128238106Sdes		printf(" %s", *m);
129238106Sdes	printf("\n");
130356345Scy#ifdef USE_DNSCRYPT
131356345Scy	printf("DNSCrypt feature available\n");
132356345Scy#endif
133356345Scy#ifdef USE_TCP_FASTOPEN
134356345Scy	printf("TCP Fastopen feature available\n");
135356345Scy#endif
136356345Scy	ub_event_base_free(base);
137356345Scy	printf("\nBSD licensed, see LICENSE in source package for details.\n");
138356345Scy	printf("Report bugs to %s\n", PACKAGE_BUGREPORT);
139356345Scy}
140356345Scy
141356345Scy/** print usage. */
142356345Scystatic void
143356345Scyusage(void)
144356345Scy{
145356345Scy	printf("usage:  unbound [options]\n");
146356345Scy	printf("	start unbound daemon DNS resolver.\n");
147356345Scy	printf("-h	this help.\n");
148356345Scy	printf("-c file	config file to read instead of %s\n", CONFIGFILE);
149356345Scy	printf("	file format is described in unbound.conf(5).\n");
150356345Scy	printf("-d	do not fork into the background.\n");
151356345Scy	printf("-p	do not create a pidfile.\n");
152356345Scy	printf("-v	verbose (more times to increase verbosity).\n");
153356345Scy	printf("-V	show version number and build options.\n");
154356345Scy#ifdef UB_ON_WINDOWS
155356345Scy	printf("-w opt	windows option: \n");
156356345Scy	printf("   	install, remove - manage the services entry\n");
157356345Scy	printf("   	service - used to start from services control panel\n");
158356345Scy#endif
159356345Scy	printf("\nVersion %s\n", PACKAGE_VERSION);
160238106Sdes	printf("BSD licensed, see LICENSE in source package for details.\n");
161238106Sdes	printf("Report bugs to %s\n", PACKAGE_BUGREPORT);
162238106Sdes}
163238106Sdes
164238106Sdes#ifndef unbound_testbound
165238106Sdesint replay_var_compare(const void* ATTR_UNUSED(a), const void* ATTR_UNUSED(b))
166238106Sdes{
167238106Sdes        log_assert(0);
168238106Sdes        return 0;
169238106Sdes}
170238106Sdes#endif
171238106Sdes
172238106Sdes/** check file descriptor count */
173238106Sdesstatic void
174238106Sdescheckrlimits(struct config_file* cfg)
175238106Sdes{
176266114Sdes#ifndef S_SPLINT_S
177238106Sdes#ifdef HAVE_GETRLIMIT
178238106Sdes	/* list has number of ports to listen to, ifs number addresses */
179238106Sdes	int list = ((cfg->do_udp?1:0) + (cfg->do_tcp?1 +
180238106Sdes			(int)cfg->incoming_num_tcp:0));
181238106Sdes	size_t listen_ifs = (size_t)(cfg->num_ifs==0?
182238106Sdes		((cfg->do_ip4 && !cfg->if_automatic?1:0) +
183238106Sdes		 (cfg->do_ip6?1:0)):cfg->num_ifs);
184238106Sdes	size_t listen_num = list*listen_ifs;
185238106Sdes	size_t outudpnum = (size_t)cfg->outgoing_num_ports;
186238106Sdes	size_t outtcpnum = cfg->outgoing_num_tcp;
187238106Sdes	size_t misc = 4; /* logfile, pidfile, stdout... */
188238106Sdes	size_t perthread_noudp = listen_num + outtcpnum +
189238106Sdes		2/*cmdpipe*/ + 2/*libevent*/ + misc;
190238106Sdes	size_t perthread = perthread_noudp + outudpnum;
191238106Sdes
192238106Sdes#if !defined(HAVE_PTHREAD) && !defined(HAVE_SOLARIS_THREADS)
193238106Sdes	int numthread = 1; /* it forks */
194238106Sdes#else
195238106Sdes	int numthread = (cfg->num_threads?cfg->num_threads:1);
196238106Sdes#endif
197238106Sdes	size_t total = numthread * perthread + misc;
198238106Sdes	size_t avail;
199238106Sdes	struct rlimit rlim;
200238106Sdes
201238106Sdes	if(total > 1024 &&
202307729Sdes		strncmp(ub_event_get_version(), "mini-event", 10) == 0) {
203238106Sdes		log_warn("too many file descriptors requested. The builtin"
204238106Sdes			"mini-event cannot handle more than 1024. Config "
205238106Sdes			"for less fds or compile with libevent");
206238106Sdes		if(numthread*perthread_noudp+15 > 1024)
207238106Sdes			fatal_exit("too much tcp. not enough fds.");
208238106Sdes		cfg->outgoing_num_ports = (int)((1024
209238106Sdes			- numthread*perthread_noudp
210238106Sdes			- 10 /* safety margin */) /numthread);
211238106Sdes		log_warn("continuing with less udp ports: %u",
212238106Sdes			cfg->outgoing_num_ports);
213238106Sdes		total = 1024;
214238106Sdes	}
215238106Sdes	if(perthread > 64 &&
216307729Sdes		strncmp(ub_event_get_version(), "winsock-event", 13) == 0) {
217238106Sdes		log_err("too many file descriptors requested. The winsock"
218238106Sdes			" event handler cannot handle more than 64 per "
219238106Sdes			" thread. Config for less fds");
220238106Sdes		if(perthread_noudp+2 > 64)
221238106Sdes			fatal_exit("too much tcp. not enough fds.");
222238106Sdes		cfg->outgoing_num_ports = (int)((64
223238106Sdes			- perthread_noudp
224238106Sdes			- 2/* safety margin */));
225238106Sdes		log_warn("continuing with less udp ports: %u",
226238106Sdes			cfg->outgoing_num_ports);
227238106Sdes		total = numthread*(perthread_noudp+
228238106Sdes			(size_t)cfg->outgoing_num_ports)+misc;
229238106Sdes	}
230238106Sdes	if(getrlimit(RLIMIT_NOFILE, &rlim) < 0) {
231238106Sdes		log_warn("getrlimit: %s", strerror(errno));
232238106Sdes		return;
233238106Sdes	}
234238106Sdes	if(rlim.rlim_cur == (rlim_t)RLIM_INFINITY)
235238106Sdes		return;
236238106Sdes	if((size_t)rlim.rlim_cur < total) {
237238106Sdes		avail = (size_t)rlim.rlim_cur;
238238106Sdes		rlim.rlim_cur = (rlim_t)(total + 10);
239238106Sdes		rlim.rlim_max = (rlim_t)(total + 10);
240238106Sdes#ifdef HAVE_SETRLIMIT
241238106Sdes		if(setrlimit(RLIMIT_NOFILE, &rlim) < 0) {
242238106Sdes			log_warn("setrlimit: %s", strerror(errno));
243238106Sdes#endif
244238106Sdes			log_warn("cannot increase max open fds from %u to %u",
245238106Sdes				(unsigned)avail, (unsigned)total+10);
246238106Sdes			/* check that calculation below does not underflow,
247238106Sdes			 * with 15 as margin */
248238106Sdes			if(numthread*perthread_noudp+15 > avail)
249238106Sdes				fatal_exit("too much tcp. not enough fds.");
250238106Sdes			cfg->outgoing_num_ports = (int)((avail
251238106Sdes				- numthread*perthread_noudp
252238106Sdes				- 10 /* safety margin */) /numthread);
253238106Sdes			log_warn("continuing with less udp ports: %u",
254238106Sdes				cfg->outgoing_num_ports);
255238106Sdes			log_warn("increase ulimit or decrease threads, "
256238106Sdes				"ports in config to remove this warning");
257238106Sdes			return;
258276605Sdes#ifdef HAVE_SETRLIMIT
259238106Sdes		}
260276605Sdes#endif
261276605Sdes		verbose(VERB_ALGO, "increased limit(open files) from %u to %u",
262238106Sdes			(unsigned)avail, (unsigned)total+10);
263238106Sdes	}
264238106Sdes#else
265238106Sdes	(void)cfg;
266238106Sdes#endif /* HAVE_GETRLIMIT */
267266114Sdes#endif /* S_SPLINT_S */
268238106Sdes}
269238106Sdes
270238106Sdes/** set verbosity, check rlimits, cache settings */
271238106Sdesstatic void
272361435Scyapply_settings(struct daemon* daemon, struct config_file* cfg,
273361435Scy	int cmdline_verbose, int debug_mode)
274238106Sdes{
275238106Sdes	/* apply if they have changed */
276238106Sdes	verbosity = cmdline_verbose + cfg->verbosity;
277276605Sdes	if (debug_mode > 1) {
278276605Sdes		cfg->use_syslog = 0;
279356345Scy		free(cfg->logfile);
280276605Sdes		cfg->logfile = NULL;
281276605Sdes	}
282238106Sdes	daemon_apply_cfg(daemon, cfg);
283238106Sdes	checkrlimits(cfg);
284356345Scy
285356345Scy	if (cfg->use_systemd && cfg->do_daemonize) {
286356345Scy		log_warn("use-systemd and do-daemonize should not be enabled at the same time");
287356345Scy	}
288356345Scy
289361435Scy	log_ident_set_or_default(cfg->log_identity);
290238106Sdes}
291238106Sdes
292238106Sdes#ifdef HAVE_KILL
293238106Sdes/** Read existing pid from pidfile.
294238106Sdes * @param file: file name of pid file.
295238106Sdes * @return: the pid from the file or -1 if none.
296238106Sdes */
297238106Sdesstatic pid_t
298238106Sdesreadpid (const char* file)
299238106Sdes{
300238106Sdes	int fd;
301238106Sdes	pid_t pid;
302238106Sdes	char pidbuf[32];
303238106Sdes	char* t;
304238106Sdes	ssize_t l;
305238106Sdes
306238106Sdes	if ((fd = open(file, O_RDONLY)) == -1) {
307238106Sdes		if(errno != ENOENT)
308238106Sdes			log_err("Could not read pidfile %s: %s",
309238106Sdes				file, strerror(errno));
310238106Sdes		return -1;
311238106Sdes	}
312238106Sdes
313238106Sdes	if (((l = read(fd, pidbuf, sizeof(pidbuf)))) == -1) {
314238106Sdes		if(errno != ENOENT)
315238106Sdes			log_err("Could not read pidfile %s: %s",
316238106Sdes				file, strerror(errno));
317238106Sdes		close(fd);
318238106Sdes		return -1;
319238106Sdes	}
320238106Sdes
321238106Sdes	close(fd);
322238106Sdes
323238106Sdes	/* Empty pidfile means no pidfile... */
324238106Sdes	if (l == 0) {
325238106Sdes		return -1;
326238106Sdes	}
327238106Sdes
328238106Sdes	pidbuf[sizeof(pidbuf)-1] = 0;
329238106Sdes	pid = (pid_t)strtol(pidbuf, &t, 10);
330238106Sdes
331238106Sdes	if (*t && *t != '\n') {
332238106Sdes		return -1;
333238106Sdes	}
334238106Sdes	return pid;
335238106Sdes}
336238106Sdes
337238106Sdes/** write pid to file.
338238106Sdes * @param pidfile: file name of pid file.
339238106Sdes * @param pid: pid to write to file.
340368693Scy * @return false on failure
341238106Sdes */
342368693Scystatic int
343238106Sdeswritepid (const char* pidfile, pid_t pid)
344238106Sdes{
345368693Scy	int fd;
346368693Scy	char pidbuf[32];
347368693Scy	size_t count = 0;
348368693Scy	snprintf(pidbuf, sizeof(pidbuf), "%lu\n", (unsigned long)pid);
349238106Sdes
350368693Scy	if((fd = open(pidfile, O_WRONLY | O_CREAT | O_TRUNC
351368693Scy#ifdef O_NOFOLLOW
352368693Scy		| O_NOFOLLOW
353368693Scy#endif
354368693Scy		, 0644)) == -1) {
355238106Sdes		log_err("cannot open pidfile %s: %s",
356238106Sdes			pidfile, strerror(errno));
357368693Scy		return 0;
358238106Sdes	}
359368693Scy	while(count < strlen(pidbuf)) {
360368693Scy		ssize_t r = write(fd, pidbuf+count, strlen(pidbuf)-count);
361368693Scy		if(r == -1) {
362368693Scy			if(errno == EAGAIN || errno == EINTR)
363368693Scy				continue;
364368693Scy			log_err("cannot write to pidfile %s: %s",
365368693Scy				pidfile, strerror(errno));
366368693Scy			close(fd);
367368693Scy			return 0;
368368693Scy		} else if(r == 0) {
369368693Scy			log_err("cannot write any bytes to pidfile %s: "
370368693Scy				"write returns 0 bytes written", pidfile);
371368693Scy			close(fd);
372368693Scy			return 0;
373368693Scy		}
374368693Scy		count += r;
375238106Sdes	}
376368693Scy	close(fd);
377368693Scy	return 1;
378238106Sdes}
379238106Sdes
380238106Sdes/**
381238106Sdes * check old pid file.
382238106Sdes * @param pidfile: the file name of the pid file.
383238106Sdes * @param inchroot: if pidfile is inchroot and we can thus expect to
384238106Sdes *	be able to delete it.
385238106Sdes */
386238106Sdesstatic void
387238106Sdescheckoldpid(char* pidfile, int inchroot)
388238106Sdes{
389238106Sdes	pid_t old;
390238106Sdes	if((old = readpid(pidfile)) != -1) {
391238106Sdes		/* see if it is still alive */
392238106Sdes		if(kill(old, 0) == 0 || errno == EPERM)
393238106Sdes			log_warn("unbound is already running as pid %u.",
394238106Sdes				(unsigned)old);
395238106Sdes		else	if(inchroot)
396238106Sdes			log_warn("did not exit gracefully last time (%u)",
397238106Sdes				(unsigned)old);
398238106Sdes	}
399238106Sdes}
400238106Sdes#endif /* HAVE_KILL */
401238106Sdes
402238106Sdes/** detach from command line */
403238106Sdesstatic void
404238106Sdesdetach(void)
405238106Sdes{
406238106Sdes#if defined(HAVE_DAEMON) && !defined(DEPRECATED_DAEMON)
407238106Sdes	/* use POSIX daemon(3) function */
408238106Sdes	if(daemon(1, 0) != 0)
409238106Sdes		fatal_exit("daemon failed: %s", strerror(errno));
410238106Sdes#else /* no HAVE_DAEMON */
411238106Sdes#ifdef HAVE_FORK
412238106Sdes	int fd;
413238106Sdes	/* Take off... */
414238106Sdes	switch (fork()) {
415238106Sdes		case 0:
416238106Sdes			break;
417238106Sdes		case -1:
418238106Sdes			fatal_exit("fork failed: %s", strerror(errno));
419238106Sdes		default:
420238106Sdes			/* exit interactive session */
421238106Sdes			exit(0);
422238106Sdes	}
423238106Sdes	/* detach */
424238106Sdes#ifdef HAVE_SETSID
425238106Sdes	if(setsid() == -1)
426238106Sdes		fatal_exit("setsid() failed: %s", strerror(errno));
427238106Sdes#endif
428238106Sdes	if ((fd = open("/dev/null", O_RDWR, 0)) != -1) {
429238106Sdes		(void)dup2(fd, STDIN_FILENO);
430238106Sdes		(void)dup2(fd, STDOUT_FILENO);
431238106Sdes		(void)dup2(fd, STDERR_FILENO);
432238106Sdes		if (fd > 2)
433238106Sdes			(void)close(fd);
434238106Sdes	}
435238106Sdes#endif /* HAVE_FORK */
436238106Sdes#endif /* HAVE_DAEMON */
437238106Sdes}
438238106Sdes
439356345Scy/** daemonize, drop user privileges and chroot if needed */
440238106Sdesstatic void
441238106Sdesperform_setup(struct daemon* daemon, struct config_file* cfg, int debug_mode,
442356345Scy	const char** cfgfile, int need_pidfile)
443238106Sdes{
444296415Sdes#ifdef HAVE_KILL
445296415Sdes	int pidinchroot;
446296415Sdes#endif
447238106Sdes#ifdef HAVE_GETPWNAM
448238106Sdes	struct passwd *pwd = NULL;
449238106Sdes
450238106Sdes	if(cfg->username && cfg->username[0]) {
451238106Sdes		if((pwd = getpwnam(cfg->username)) == NULL)
452238106Sdes			fatal_exit("user '%s' does not exist.", cfg->username);
453238106Sdes		/* endpwent below, in case we need pwd for setusercontext */
454238106Sdes	}
455238106Sdes#endif
456292206Sdes#ifdef UB_ON_WINDOWS
457292206Sdes	w_config_adjust_directory(cfg);
458292206Sdes#endif
459238106Sdes
460238106Sdes	/* read ssl keys while superuser and outside chroot */
461249141Sdes#ifdef HAVE_SSL
462238106Sdes	if(!(daemon->rc = daemon_remote_create(cfg)))
463238106Sdes		fatal_exit("could not set up remote-control");
464238106Sdes	if(cfg->ssl_service_key && cfg->ssl_service_key[0]) {
465238106Sdes		if(!(daemon->listen_sslctx = listen_sslctx_create(
466238106Sdes			cfg->ssl_service_key, cfg->ssl_service_pem, NULL)))
467238106Sdes			fatal_exit("could not set up listen SSL_CTX");
468356345Scy		if(cfg->tls_ciphers && cfg->tls_ciphers[0]) {
469356345Scy			if (!SSL_CTX_set_cipher_list(daemon->listen_sslctx, cfg->tls_ciphers)) {
470356345Scy				fatal_exit("failed to set tls-cipher %s", cfg->tls_ciphers);
471356345Scy			}
472356345Scy		}
473356345Scy#ifdef HAVE_SSL_CTX_SET_CIPHERSUITES
474356345Scy		if(cfg->tls_ciphersuites && cfg->tls_ciphersuites[0]) {
475356345Scy			if (!SSL_CTX_set_ciphersuites(daemon->listen_sslctx, cfg->tls_ciphersuites)) {
476356345Scy				fatal_exit("failed to set tls-ciphersuites %s", cfg->tls_ciphersuites);
477356345Scy			}
478356345Scy		}
479356345Scy#endif
480356345Scy		if(cfg->tls_session_ticket_keys.first &&
481356345Scy			cfg->tls_session_ticket_keys.first->str[0] != 0) {
482356345Scy			if(!listen_sslctx_setup_ticket_keys(daemon->listen_sslctx, cfg->tls_session_ticket_keys.first)) {
483356345Scy				fatal_exit("could not set session ticket SSL_CTX");
484356345Scy			}
485356345Scy		}
486238106Sdes	}
487356345Scy	if(!(daemon->connect_sslctx = connect_sslctx_create(NULL, NULL,
488356345Scy		cfg->tls_cert_bundle, cfg->tls_win_cert)))
489238106Sdes		fatal_exit("could not set up connect SSL_CTX");
490249141Sdes#endif
491238106Sdes
492356345Scy	/* init syslog (as root) if needed, before daemonize, otherwise
493356345Scy	 * a fork error could not be printed since daemonize closed stderr.*/
494356345Scy	if(cfg->use_syslog) {
495356345Scy		log_init(cfg->logfile, cfg->use_syslog, cfg->chrootdir);
496356345Scy	}
497356345Scy	/* if using a logfile, we cannot open it because the logfile would
498356345Scy	 * be created with the wrong permissions, we cannot chown it because
499356345Scy	 * we cannot chown system logfiles, so we do not open at all.
500356345Scy	 * So, using a logfile, the user does not see errors unless -d is
501356345Scy	 * given to unbound on the commandline. */
502356345Scy
503238106Sdes#ifdef HAVE_KILL
504296415Sdes	/* true if pidfile is inside chrootdir, or nochroot */
505356345Scy	pidinchroot = need_pidfile && (!(cfg->chrootdir && cfg->chrootdir[0]) ||
506296415Sdes				(cfg->chrootdir && cfg->chrootdir[0] &&
507296415Sdes				strncmp(cfg->pidfile, cfg->chrootdir,
508356345Scy				strlen(cfg->chrootdir))==0));
509296415Sdes
510238106Sdes	/* check old pid file before forking */
511356345Scy	if(cfg->pidfile && cfg->pidfile[0] && need_pidfile) {
512238106Sdes		/* calculate position of pidfile */
513238106Sdes		if(cfg->pidfile[0] == '/')
514238106Sdes			daemon->pidfile = strdup(cfg->pidfile);
515238106Sdes		else	daemon->pidfile = fname_after_chroot(cfg->pidfile,
516238106Sdes				cfg, 1);
517238106Sdes		if(!daemon->pidfile)
518238106Sdes			fatal_exit("pidfile alloc: out of memory");
519296415Sdes		checkoldpid(daemon->pidfile, pidinchroot);
520238106Sdes	}
521238106Sdes#endif
522238106Sdes
523238106Sdes	/* daemonize because pid is needed by the writepid func */
524238106Sdes	if(!debug_mode && cfg->do_daemonize) {
525238106Sdes		detach();
526238106Sdes	}
527238106Sdes
528238106Sdes	/* write new pidfile (while still root, so can be outside chroot) */
529238106Sdes#ifdef HAVE_KILL
530356345Scy	if(cfg->pidfile && cfg->pidfile[0] && need_pidfile) {
531368693Scy		if(writepid(daemon->pidfile, getpid())) {
532368693Scy			if(cfg->username && cfg->username[0] && cfg_uid != (uid_t)-1 &&
533368693Scy				pidinchroot) {
534282089Sdes#  ifdef HAVE_CHOWN
535368693Scy				if(chown(daemon->pidfile, cfg_uid, cfg_gid) == -1) {
536368693Scy					verbose(VERB_QUERY, "cannot chown %u.%u %s: %s",
537368693Scy						(unsigned)cfg_uid, (unsigned)cfg_gid,
538368693Scy						daemon->pidfile, strerror(errno));
539368693Scy				}
540368693Scy#  endif /* HAVE_CHOWN */
541238106Sdes			}
542238106Sdes		}
543238106Sdes	}
544238106Sdes#else
545238106Sdes	(void)daemon;
546356345Scy	(void)need_pidfile;
547282089Sdes#endif /* HAVE_KILL */
548238106Sdes
549238106Sdes	/* Set user context */
550238106Sdes#ifdef HAVE_GETPWNAM
551282089Sdes	if(cfg->username && cfg->username[0] && cfg_uid != (uid_t)-1) {
552238106Sdes#ifdef HAVE_SETUSERCONTEXT
553238106Sdes		/* setusercontext does initgroups, setuid, setgid, and
554238106Sdes		 * also resource limits from login config, but we
555238106Sdes		 * still call setresuid, setresgid to be sure to set all uid*/
556282089Sdes		if(setusercontext(NULL, pwd, cfg_uid, (unsigned)
557238106Sdes			LOGIN_SETALL & ~LOGIN_SETUSER & ~LOGIN_SETGROUP) != 0)
558238106Sdes			log_warn("unable to setusercontext %s: %s",
559238106Sdes				cfg->username, strerror(errno));
560366095Scy#else
561366095Scy		(void)pwd;
562238106Sdes#endif /* HAVE_SETUSERCONTEXT */
563238106Sdes	}
564238106Sdes#endif /* HAVE_GETPWNAM */
565238106Sdes
566238106Sdes	/* box into the chroot */
567238106Sdes#ifdef HAVE_CHROOT
568238106Sdes	if(cfg->chrootdir && cfg->chrootdir[0]) {
569238106Sdes		if(chdir(cfg->chrootdir)) {
570238106Sdes			fatal_exit("unable to chdir to chroot %s: %s",
571238106Sdes				cfg->chrootdir, strerror(errno));
572238106Sdes		}
573238106Sdes		verbose(VERB_QUERY, "chdir to %s", cfg->chrootdir);
574238106Sdes		if(chroot(cfg->chrootdir))
575238106Sdes			fatal_exit("unable to chroot to %s: %s",
576238106Sdes				cfg->chrootdir, strerror(errno));
577249141Sdes		if(chdir("/"))
578249141Sdes			fatal_exit("unable to chdir to / in chroot %s: %s",
579249141Sdes				cfg->chrootdir, strerror(errno));
580238106Sdes		verbose(VERB_QUERY, "chroot to %s", cfg->chrootdir);
581238106Sdes		if(strncmp(*cfgfile, cfg->chrootdir,
582238106Sdes			strlen(cfg->chrootdir)) == 0)
583238106Sdes			(*cfgfile) += strlen(cfg->chrootdir);
584238106Sdes
585238106Sdes		/* adjust stored pidfile for chroot */
586238106Sdes		if(daemon->pidfile && daemon->pidfile[0] &&
587238106Sdes			strncmp(daemon->pidfile, cfg->chrootdir,
588238106Sdes			strlen(cfg->chrootdir))==0) {
589238106Sdes			char* old = daemon->pidfile;
590238106Sdes			daemon->pidfile = strdup(old+strlen(cfg->chrootdir));
591238106Sdes			free(old);
592238106Sdes			if(!daemon->pidfile)
593238106Sdes				log_err("out of memory in pidfile adjust");
594238106Sdes		}
595238106Sdes		daemon->chroot = strdup(cfg->chrootdir);
596238106Sdes		if(!daemon->chroot)
597238106Sdes			log_err("out of memory in daemon chroot dir storage");
598238106Sdes	}
599238106Sdes#else
600238106Sdes	(void)cfgfile;
601238106Sdes#endif
602238106Sdes	/* change to working directory inside chroot */
603238106Sdes	if(cfg->directory && cfg->directory[0]) {
604238106Sdes		char* dir = cfg->directory;
605238106Sdes		if(cfg->chrootdir && cfg->chrootdir[0] &&
606238106Sdes			strncmp(dir, cfg->chrootdir,
607238106Sdes			strlen(cfg->chrootdir)) == 0)
608238106Sdes			dir += strlen(cfg->chrootdir);
609238106Sdes		if(dir[0]) {
610238106Sdes			if(chdir(dir)) {
611238106Sdes				fatal_exit("Could not chdir to %s: %s",
612238106Sdes					dir, strerror(errno));
613238106Sdes			}
614238106Sdes			verbose(VERB_QUERY, "chdir to %s", dir);
615238106Sdes		}
616238106Sdes	}
617238106Sdes
618238106Sdes	/* drop permissions after chroot, getpwnam, pidfile, syslog done*/
619238106Sdes#ifdef HAVE_GETPWNAM
620282089Sdes	if(cfg->username && cfg->username[0] && cfg_uid != (uid_t)-1) {
621238106Sdes#  ifdef HAVE_INITGROUPS
622282089Sdes		if(initgroups(cfg->username, cfg_gid) != 0)
623238106Sdes			log_warn("unable to initgroups %s: %s",
624238106Sdes				cfg->username, strerror(errno));
625238106Sdes#  endif /* HAVE_INITGROUPS */
626307729Sdes#  ifdef HAVE_ENDPWENT
627238106Sdes		endpwent();
628307729Sdes#  endif
629238106Sdes
630238106Sdes#ifdef HAVE_SETRESGID
631282089Sdes		if(setresgid(cfg_gid,cfg_gid,cfg_gid) != 0)
632238106Sdes#elif defined(HAVE_SETREGID) && !defined(DARWIN_BROKEN_SETREUID)
633282089Sdes		if(setregid(cfg_gid,cfg_gid) != 0)
634238106Sdes#else /* use setgid */
635282089Sdes		if(setgid(cfg_gid) != 0)
636238106Sdes#endif /* HAVE_SETRESGID */
637238106Sdes			fatal_exit("unable to set group id of %s: %s",
638238106Sdes				cfg->username, strerror(errno));
639238106Sdes#ifdef HAVE_SETRESUID
640282089Sdes		if(setresuid(cfg_uid,cfg_uid,cfg_uid) != 0)
641238106Sdes#elif defined(HAVE_SETREUID) && !defined(DARWIN_BROKEN_SETREUID)
642282089Sdes		if(setreuid(cfg_uid,cfg_uid) != 0)
643238106Sdes#else /* use setuid */
644282089Sdes		if(setuid(cfg_uid) != 0)
645238106Sdes#endif /* HAVE_SETRESUID */
646238106Sdes			fatal_exit("unable to set user id of %s: %s",
647238106Sdes				cfg->username, strerror(errno));
648238106Sdes		verbose(VERB_QUERY, "drop user privileges, run as %s",
649238106Sdes			cfg->username);
650238106Sdes	}
651238106Sdes#endif /* HAVE_GETPWNAM */
652238106Sdes	/* file logging inited after chroot,chdir,setuid is done so that
653238106Sdes	 * it would succeed on SIGHUP as well */
654238106Sdes	if(!cfg->use_syslog)
655238106Sdes		log_init(cfg->logfile, cfg->use_syslog, cfg->chrootdir);
656238106Sdes}
657238106Sdes
658238106Sdes/**
659238106Sdes * Run the daemon.
660238106Sdes * @param cfgfile: the config file name.
661238106Sdes * @param cmdline_verbose: verbosity resulting from commandline -v.
662238106Sdes *    These increase verbosity as specified in the config file.
663238106Sdes * @param debug_mode: if set, do not daemonize.
664356345Scy * @param need_pidfile: if false, no pidfile is checked or created.
665238106Sdes */
666238106Sdesstatic void
667361435Scyrun_daemon(const char* cfgfile, int cmdline_verbose, int debug_mode, int need_pidfile)
668238106Sdes{
669238106Sdes	struct config_file* cfg = NULL;
670238106Sdes	struct daemon* daemon = NULL;
671238106Sdes	int done_setup = 0;
672238106Sdes
673238106Sdes	if(!(daemon = daemon_init()))
674238106Sdes		fatal_exit("alloc failure");
675238106Sdes	while(!daemon->need_to_exit) {
676238106Sdes		if(done_setup)
677238106Sdes			verbose(VERB_OPS, "Restart of %s.", PACKAGE_STRING);
678238106Sdes		else	verbose(VERB_OPS, "Start of %s.", PACKAGE_STRING);
679238106Sdes
680238106Sdes		/* config stuff */
681238106Sdes		if(!(cfg = config_create()))
682238106Sdes			fatal_exit("Could not alloc config defaults");
683238106Sdes		if(!config_read(cfg, cfgfile, daemon->chroot)) {
684238106Sdes			if(errno != ENOENT)
685356345Scy				fatal_exit("Could not read config file: %s."
686356345Scy					" Maybe try unbound -dd, it stays on "
687356345Scy					"the commandline to see more errors, "
688356345Scy					"or unbound-checkconf", cfgfile);
689238106Sdes			log_warn("Continuing with default config settings");
690238106Sdes		}
691361435Scy		apply_settings(daemon, cfg, cmdline_verbose, debug_mode);
692282089Sdes		if(!done_setup)
693282089Sdes			config_lookup_uid(cfg);
694238106Sdes
695238106Sdes		/* prepare */
696238106Sdes		if(!daemon_open_shared_ports(daemon))
697238106Sdes			fatal_exit("could not open ports");
698238106Sdes		if(!done_setup) {
699356345Scy			perform_setup(daemon, cfg, debug_mode, &cfgfile, need_pidfile);
700238106Sdes			done_setup = 1;
701238106Sdes		} else {
702238106Sdes			/* reopen log after HUP to facilitate log rotation */
703238106Sdes			if(!cfg->use_syslog)
704238106Sdes				log_init(cfg->logfile, 0, cfg->chrootdir);
705238106Sdes		}
706238106Sdes		/* work */
707238106Sdes		daemon_fork(daemon);
708238106Sdes
709238106Sdes		/* clean up for restart */
710238106Sdes		verbose(VERB_ALGO, "cleanup.");
711238106Sdes		daemon_cleanup(daemon);
712238106Sdes		config_delete(cfg);
713238106Sdes	}
714238106Sdes	verbose(VERB_ALGO, "Exit cleanup.");
715238106Sdes	/* this unlink may not work if the pidfile is located outside
716238106Sdes	 * of the chroot/workdir or we no longer have permissions */
717238106Sdes	if(daemon->pidfile) {
718238106Sdes		int fd;
719238106Sdes		/* truncate pidfile */
720238106Sdes		fd = open(daemon->pidfile, O_WRONLY | O_TRUNC, 0644);
721238106Sdes		if(fd != -1)
722238106Sdes			close(fd);
723238106Sdes		/* delete pidfile */
724238106Sdes		unlink(daemon->pidfile);
725238106Sdes	}
726238106Sdes	daemon_delete(daemon);
727238106Sdes}
728238106Sdes
729238106Sdes/** getopt global, in case header files fail to declare it. */
730238106Sdesextern int optind;
731238106Sdes/** getopt global, in case header files fail to declare it. */
732238106Sdesextern char* optarg;
733238106Sdes
734238106Sdes/**
735238106Sdes * main program. Set options given commandline arguments.
736238106Sdes * @param argc: number of commandline arguments.
737238106Sdes * @param argv: array of commandline arguments.
738238106Sdes * @return: exit status of the program.
739238106Sdes */
740238106Sdesint
741238106Sdesmain(int argc, char* argv[])
742238106Sdes{
743238106Sdes	int c;
744238106Sdes	const char* cfgfile = CONFIGFILE;
745238106Sdes	const char* winopt = NULL;
746356345Scy	const char* log_ident_default;
747238106Sdes	int cmdline_verbose = 0;
748238106Sdes	int debug_mode = 0;
749356345Scy	int need_pidfile = 1;
750356345Scy
751238106Sdes#ifdef UB_ON_WINDOWS
752238106Sdes	int cmdline_cfg = 0;
753238106Sdes#endif
754238106Sdes
755238106Sdes	log_init(NULL, 0, NULL);
756356345Scy	log_ident_default = strrchr(argv[0],'/')?strrchr(argv[0],'/')+1:argv[0];
757361435Scy	log_ident_set_default(log_ident_default);
758356345Scy	log_ident_set(log_ident_default);
759238106Sdes	/* parse the options */
760356345Scy	while( (c=getopt(argc, argv, "c:dhpvw:V")) != -1) {
761238106Sdes		switch(c) {
762238106Sdes		case 'c':
763238106Sdes			cfgfile = optarg;
764238106Sdes#ifdef UB_ON_WINDOWS
765238106Sdes			cmdline_cfg = 1;
766238106Sdes#endif
767238106Sdes			break;
768238106Sdes		case 'v':
769296415Sdes			cmdline_verbose++;
770238106Sdes			verbosity++;
771238106Sdes			break;
772356345Scy		case 'p':
773356345Scy			need_pidfile = 0;
774356345Scy			break;
775238106Sdes		case 'd':
776276605Sdes			debug_mode++;
777238106Sdes			break;
778238106Sdes		case 'w':
779238106Sdes			winopt = optarg;
780238106Sdes			break;
781356345Scy		case 'V':
782356345Scy			print_build_options();
783356345Scy			return 0;
784238106Sdes		case '?':
785238106Sdes		case 'h':
786238106Sdes		default:
787238106Sdes			usage();
788238106Sdes			return 1;
789238106Sdes		}
790238106Sdes	}
791238106Sdes	argc -= optind;
792356345Scy	/* argv += optind; not using further arguments */
793238106Sdes
794238106Sdes	if(winopt) {
795238106Sdes#ifdef UB_ON_WINDOWS
796238106Sdes		wsvc_command_option(winopt, cfgfile, cmdline_verbose,
797238106Sdes			cmdline_cfg);
798238106Sdes#else
799238106Sdes		fatal_exit("option not supported");
800238106Sdes#endif
801238106Sdes	}
802238106Sdes
803238106Sdes	if(argc != 0) {
804238106Sdes		usage();
805238106Sdes		return 1;
806238106Sdes	}
807238106Sdes
808361435Scy	run_daemon(cfgfile, cmdline_verbose, debug_mode, need_pidfile);
809238106Sdes	log_init(NULL, 0, NULL); /* close logfile */
810356345Scy#ifndef unbound_testbound
811356345Scy	if(log_get_lock()) {
812356345Scy		lock_basic_destroy((lock_basic_type*)log_get_lock());
813356345Scy	}
814356345Scy#endif
815238106Sdes	return 0;
816238106Sdes}
817