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
24269257Sdes * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
25269257Sdes * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
26269257Sdes * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
27269257Sdes * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
28269257Sdes * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
29269257Sdes * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
30269257Sdes * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
31269257Sdes * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
32269257Sdes * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
33269257Sdes * 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"
60238106Sdes#include <signal.h>
61238106Sdes#include <fcntl.h>
62238106Sdes#include <openssl/crypto.h>
63238106Sdes#ifdef HAVE_PWD_H
64238106Sdes#include <pwd.h>
65238106Sdes#endif
66238106Sdes#ifdef HAVE_GRP_H
67238106Sdes#include <grp.h>
68238106Sdes#endif
69238106Sdes
70269257Sdes#ifndef S_SPLINT_S
71269257Sdes/* splint chokes on this system header file */
72238106Sdes#ifdef HAVE_SYS_RESOURCE_H
73238106Sdes#include <sys/resource.h>
74238106Sdes#endif
75269257Sdes#endif /* S_SPLINT_S */
76238106Sdes#ifdef HAVE_LOGIN_CAP_H
77238106Sdes#include <login_cap.h>
78238106Sdes#endif
79238106Sdes
80238106Sdes#ifdef USE_MINI_EVENT
81238106Sdes#  ifdef USE_WINSOCK
82238106Sdes#    include "util/winsock_event.h"
83238106Sdes#  else
84238106Sdes#    include "util/mini_event.h"
85238106Sdes#  endif
86238106Sdes#else
87285206Sdes#  ifdef HAVE_EVENT_H
88285206Sdes#    include <event.h>
89285206Sdes#  else
90285206Sdes#    include "event2/event.h"
91285206Sdes#    include "event2/event_struct.h"
92285206Sdes#    include "event2/event_compat.h"
93285206Sdes#  endif
94238106Sdes#endif
95238106Sdes
96238106Sdes#ifdef UB_ON_WINDOWS
97238106Sdes#  include "winrc/win_svc.h"
98238106Sdes#endif
99238106Sdes
100249141Sdes#ifdef HAVE_NSS
101249141Sdes/* nss3 */
102249141Sdes#  include "nss.h"
103249141Sdes#endif
104249141Sdes
105255579Sdes#ifdef HAVE_SBRK
106238106Sdes/** global debug value to keep track of heap memory allocation */
107238106Sdesvoid* unbound_start_brk = 0;
108255579Sdes#endif
109238106Sdes
110238106Sdes#if !defined(HAVE_EVENT_BASE_GET_METHOD) && (defined(HAVE_EV_LOOP) || defined(HAVE_EV_DEFAULT_LOOP))
111238106Sdesstatic const char* ev_backend2str(int b)
112238106Sdes{
113238106Sdes	switch(b) {
114238106Sdes	case EVBACKEND_SELECT:	return "select";
115238106Sdes	case EVBACKEND_POLL:	return "poll";
116238106Sdes	case EVBACKEND_EPOLL:	return "epoll";
117238106Sdes	case EVBACKEND_KQUEUE:	return "kqueue";
118238106Sdes	case EVBACKEND_DEVPOLL: return "devpoll";
119238106Sdes	case EVBACKEND_PORT:	return "evport";
120238106Sdes	}
121238106Sdes	return "unknown";
122238106Sdes}
123238106Sdes#endif
124238106Sdes
125238106Sdes/** get the event system in use */
126238106Sdesstatic void get_event_sys(const char** n, const char** s, const char** m)
127238106Sdes{
128238106Sdes#ifdef USE_WINSOCK
129238106Sdes	*n = "event";
130238106Sdes	*s = "winsock";
131238106Sdes	*m = "WSAWaitForMultipleEvents";
132238106Sdes#elif defined(USE_MINI_EVENT)
133238106Sdes	*n = "mini-event";
134238106Sdes	*s = "internal";
135238106Sdes	*m = "select";
136238106Sdes#else
137238106Sdes	struct event_base* b;
138238106Sdes	*s = event_get_version();
139238106Sdes#  ifdef HAVE_EVENT_BASE_GET_METHOD
140238106Sdes	*n = "libevent";
141238106Sdes	b = event_base_new();
142238106Sdes	*m = event_base_get_method(b);
143238106Sdes#  elif defined(HAVE_EV_LOOP) || defined(HAVE_EV_DEFAULT_LOOP)
144238106Sdes	*n = "libev";
145238106Sdes	b = (struct event_base*)ev_default_loop(EVFLAG_AUTO);
146238106Sdes	*m = ev_backend2str(ev_backend((struct ev_loop*)b));
147238106Sdes#  else
148238106Sdes	*n = "unknown";
149238106Sdes	*m = "not obtainable";
150238106Sdes	b = NULL;
151238106Sdes#  endif
152238106Sdes#  ifdef HAVE_EVENT_BASE_FREE
153238106Sdes	event_base_free(b);
154238106Sdes#  endif
155238106Sdes#endif
156238106Sdes}
157238106Sdes
158238106Sdes/** print usage. */
159238106Sdesstatic void usage()
160238106Sdes{
161238106Sdes	const char** m;
162238106Sdes	const char *evnm="event", *evsys="", *evmethod="";
163238106Sdes	printf("usage:  unbound [options]\n");
164238106Sdes	printf("	start unbound daemon DNS resolver.\n");
165238106Sdes	printf("-h	this help\n");
166238106Sdes	printf("-c file	config file to read instead of %s\n", CONFIGFILE);
167238106Sdes	printf("	file format is described in unbound.conf(5).\n");
168238106Sdes	printf("-d	do not fork into the background.\n");
169238106Sdes	printf("-v	verbose (more times to increase verbosity)\n");
170238106Sdes#ifdef UB_ON_WINDOWS
171238106Sdes	printf("-w opt	windows option: \n");
172238106Sdes	printf("   	install, remove - manage the services entry\n");
173238106Sdes	printf("   	service - used to start from services control panel\n");
174238106Sdes#endif
175238106Sdes	printf("Version %s\n", PACKAGE_VERSION);
176238106Sdes	get_event_sys(&evnm, &evsys, &evmethod);
177269257Sdes	printf("linked libs: %s %s (it uses %s), %s\n",
178269257Sdes		evnm, evsys, evmethod,
179249141Sdes#ifdef HAVE_SSL
180249141Sdes		SSLeay_version(SSLEAY_VERSION)
181249141Sdes#elif defined(HAVE_NSS)
182249141Sdes		NSS_GetVersion()
183294190Sdes#elif defined(HAVE_NETTLE)
184294190Sdes		"nettle"
185249141Sdes#endif
186249141Sdes		);
187238106Sdes	printf("linked modules:");
188238106Sdes	for(m = module_list_avail(); *m; m++)
189238106Sdes		printf(" %s", *m);
190238106Sdes	printf("\n");
191238106Sdes	printf("BSD licensed, see LICENSE in source package for details.\n");
192238106Sdes	printf("Report bugs to %s\n", PACKAGE_BUGREPORT);
193238106Sdes}
194238106Sdes
195238106Sdes#ifndef unbound_testbound
196238106Sdesint replay_var_compare(const void* ATTR_UNUSED(a), const void* ATTR_UNUSED(b))
197238106Sdes{
198238106Sdes        log_assert(0);
199238106Sdes        return 0;
200238106Sdes}
201238106Sdes#endif
202238106Sdes
203238106Sdes/** check file descriptor count */
204238106Sdesstatic void
205238106Sdescheckrlimits(struct config_file* cfg)
206238106Sdes{
207269257Sdes#ifndef S_SPLINT_S
208238106Sdes#ifdef HAVE_GETRLIMIT
209238106Sdes	/* list has number of ports to listen to, ifs number addresses */
210238106Sdes	int list = ((cfg->do_udp?1:0) + (cfg->do_tcp?1 +
211238106Sdes			(int)cfg->incoming_num_tcp:0));
212238106Sdes	size_t listen_ifs = (size_t)(cfg->num_ifs==0?
213238106Sdes		((cfg->do_ip4 && !cfg->if_automatic?1:0) +
214238106Sdes		 (cfg->do_ip6?1:0)):cfg->num_ifs);
215238106Sdes	size_t listen_num = list*listen_ifs;
216238106Sdes	size_t outudpnum = (size_t)cfg->outgoing_num_ports;
217238106Sdes	size_t outtcpnum = cfg->outgoing_num_tcp;
218238106Sdes	size_t misc = 4; /* logfile, pidfile, stdout... */
219238106Sdes	size_t perthread_noudp = listen_num + outtcpnum +
220238106Sdes		2/*cmdpipe*/ + 2/*libevent*/ + misc;
221238106Sdes	size_t perthread = perthread_noudp + outudpnum;
222238106Sdes
223238106Sdes#if !defined(HAVE_PTHREAD) && !defined(HAVE_SOLARIS_THREADS)
224238106Sdes	int numthread = 1; /* it forks */
225238106Sdes#else
226238106Sdes	int numthread = (cfg->num_threads?cfg->num_threads:1);
227238106Sdes#endif
228238106Sdes	size_t total = numthread * perthread + misc;
229238106Sdes	size_t avail;
230238106Sdes	struct rlimit rlim;
231238106Sdes
232238106Sdes	if(total > 1024 &&
233238106Sdes		strncmp(event_get_version(), "mini-event", 10) == 0) {
234238106Sdes		log_warn("too many file descriptors requested. The builtin"
235238106Sdes			"mini-event cannot handle more than 1024. Config "
236238106Sdes			"for less fds or compile with libevent");
237238106Sdes		if(numthread*perthread_noudp+15 > 1024)
238238106Sdes			fatal_exit("too much tcp. not enough fds.");
239238106Sdes		cfg->outgoing_num_ports = (int)((1024
240238106Sdes			- numthread*perthread_noudp
241238106Sdes			- 10 /* safety margin */) /numthread);
242238106Sdes		log_warn("continuing with less udp ports: %u",
243238106Sdes			cfg->outgoing_num_ports);
244238106Sdes		total = 1024;
245238106Sdes	}
246238106Sdes	if(perthread > 64 &&
247238106Sdes		strncmp(event_get_version(), "winsock-event", 13) == 0) {
248238106Sdes		log_err("too many file descriptors requested. The winsock"
249238106Sdes			" event handler cannot handle more than 64 per "
250238106Sdes			" thread. Config for less fds");
251238106Sdes		if(perthread_noudp+2 > 64)
252238106Sdes			fatal_exit("too much tcp. not enough fds.");
253238106Sdes		cfg->outgoing_num_ports = (int)((64
254238106Sdes			- perthread_noudp
255238106Sdes			- 2/* safety margin */));
256238106Sdes		log_warn("continuing with less udp ports: %u",
257238106Sdes			cfg->outgoing_num_ports);
258238106Sdes		total = numthread*(perthread_noudp+
259238106Sdes			(size_t)cfg->outgoing_num_ports)+misc;
260238106Sdes	}
261238106Sdes	if(getrlimit(RLIMIT_NOFILE, &rlim) < 0) {
262238106Sdes		log_warn("getrlimit: %s", strerror(errno));
263238106Sdes		return;
264238106Sdes	}
265238106Sdes	if(rlim.rlim_cur == (rlim_t)RLIM_INFINITY)
266238106Sdes		return;
267238106Sdes	if((size_t)rlim.rlim_cur < total) {
268238106Sdes		avail = (size_t)rlim.rlim_cur;
269238106Sdes		rlim.rlim_cur = (rlim_t)(total + 10);
270238106Sdes		rlim.rlim_max = (rlim_t)(total + 10);
271238106Sdes#ifdef HAVE_SETRLIMIT
272238106Sdes		if(setrlimit(RLIMIT_NOFILE, &rlim) < 0) {
273238106Sdes			log_warn("setrlimit: %s", strerror(errno));
274238106Sdes#endif
275238106Sdes			log_warn("cannot increase max open fds from %u to %u",
276238106Sdes				(unsigned)avail, (unsigned)total+10);
277238106Sdes			/* check that calculation below does not underflow,
278238106Sdes			 * with 15 as margin */
279238106Sdes			if(numthread*perthread_noudp+15 > avail)
280238106Sdes				fatal_exit("too much tcp. not enough fds.");
281238106Sdes			cfg->outgoing_num_ports = (int)((avail
282238106Sdes				- numthread*perthread_noudp
283238106Sdes				- 10 /* safety margin */) /numthread);
284238106Sdes			log_warn("continuing with less udp ports: %u",
285238106Sdes				cfg->outgoing_num_ports);
286238106Sdes			log_warn("increase ulimit or decrease threads, "
287238106Sdes				"ports in config to remove this warning");
288238106Sdes			return;
289285206Sdes#ifdef HAVE_SETRLIMIT
290238106Sdes		}
291285206Sdes#endif
292285206Sdes		verbose(VERB_ALGO, "increased limit(open files) from %u to %u",
293238106Sdes			(unsigned)avail, (unsigned)total+10);
294238106Sdes	}
295238106Sdes#else
296238106Sdes	(void)cfg;
297238106Sdes#endif /* HAVE_GETRLIMIT */
298269257Sdes#endif /* S_SPLINT_S */
299238106Sdes}
300238106Sdes
301238106Sdes/** set verbosity, check rlimits, cache settings */
302238106Sdesstatic void
303238106Sdesapply_settings(struct daemon* daemon, struct config_file* cfg,
304285206Sdes	int cmdline_verbose, int debug_mode)
305238106Sdes{
306238106Sdes	/* apply if they have changed */
307238106Sdes	verbosity = cmdline_verbose + cfg->verbosity;
308285206Sdes	if (debug_mode > 1) {
309285206Sdes		cfg->use_syslog = 0;
310285206Sdes		cfg->logfile = NULL;
311285206Sdes	}
312238106Sdes	daemon_apply_cfg(daemon, cfg);
313238106Sdes	checkrlimits(cfg);
314238106Sdes}
315238106Sdes
316238106Sdes#ifdef HAVE_KILL
317238106Sdes/** Read existing pid from pidfile.
318238106Sdes * @param file: file name of pid file.
319238106Sdes * @return: the pid from the file or -1 if none.
320238106Sdes */
321238106Sdesstatic pid_t
322238106Sdesreadpid (const char* file)
323238106Sdes{
324238106Sdes	int fd;
325238106Sdes	pid_t pid;
326238106Sdes	char pidbuf[32];
327238106Sdes	char* t;
328238106Sdes	ssize_t l;
329238106Sdes
330238106Sdes	if ((fd = open(file, O_RDONLY)) == -1) {
331238106Sdes		if(errno != ENOENT)
332238106Sdes			log_err("Could not read pidfile %s: %s",
333238106Sdes				file, strerror(errno));
334238106Sdes		return -1;
335238106Sdes	}
336238106Sdes
337238106Sdes	if (((l = read(fd, pidbuf, sizeof(pidbuf)))) == -1) {
338238106Sdes		if(errno != ENOENT)
339238106Sdes			log_err("Could not read pidfile %s: %s",
340238106Sdes				file, strerror(errno));
341238106Sdes		close(fd);
342238106Sdes		return -1;
343238106Sdes	}
344238106Sdes
345238106Sdes	close(fd);
346238106Sdes
347238106Sdes	/* Empty pidfile means no pidfile... */
348238106Sdes	if (l == 0) {
349238106Sdes		return -1;
350238106Sdes	}
351238106Sdes
352238106Sdes	pidbuf[sizeof(pidbuf)-1] = 0;
353238106Sdes	pid = (pid_t)strtol(pidbuf, &t, 10);
354238106Sdes
355238106Sdes	if (*t && *t != '\n') {
356238106Sdes		return -1;
357238106Sdes	}
358238106Sdes	return pid;
359238106Sdes}
360238106Sdes
361238106Sdes/** write pid to file.
362238106Sdes * @param pidfile: file name of pid file.
363238106Sdes * @param pid: pid to write to file.
364238106Sdes */
365238106Sdesstatic void
366238106Sdeswritepid (const char* pidfile, pid_t pid)
367238106Sdes{
368238106Sdes	FILE* f;
369238106Sdes
370238106Sdes	if ((f = fopen(pidfile, "w")) ==  NULL ) {
371238106Sdes		log_err("cannot open pidfile %s: %s",
372238106Sdes			pidfile, strerror(errno));
373238106Sdes		return;
374238106Sdes	}
375238106Sdes	if(fprintf(f, "%lu\n", (unsigned long)pid) < 0) {
376238106Sdes		log_err("cannot write to pidfile %s: %s",
377238106Sdes			pidfile, strerror(errno));
378238106Sdes	}
379238106Sdes	fclose(f);
380238106Sdes}
381238106Sdes
382238106Sdes/**
383238106Sdes * check old pid file.
384238106Sdes * @param pidfile: the file name of the pid file.
385238106Sdes * @param inchroot: if pidfile is inchroot and we can thus expect to
386238106Sdes *	be able to delete it.
387238106Sdes */
388238106Sdesstatic void
389238106Sdescheckoldpid(char* pidfile, int inchroot)
390238106Sdes{
391238106Sdes	pid_t old;
392238106Sdes	if((old = readpid(pidfile)) != -1) {
393238106Sdes		/* see if it is still alive */
394238106Sdes		if(kill(old, 0) == 0 || errno == EPERM)
395238106Sdes			log_warn("unbound is already running as pid %u.",
396238106Sdes				(unsigned)old);
397238106Sdes		else	if(inchroot)
398238106Sdes			log_warn("did not exit gracefully last time (%u)",
399238106Sdes				(unsigned)old);
400238106Sdes	}
401238106Sdes}
402238106Sdes#endif /* HAVE_KILL */
403238106Sdes
404238106Sdes/** detach from command line */
405238106Sdesstatic void
406238106Sdesdetach(void)
407238106Sdes{
408238106Sdes#if defined(HAVE_DAEMON) && !defined(DEPRECATED_DAEMON)
409238106Sdes	/* use POSIX daemon(3) function */
410238106Sdes	if(daemon(1, 0) != 0)
411238106Sdes		fatal_exit("daemon failed: %s", strerror(errno));
412238106Sdes#else /* no HAVE_DAEMON */
413238106Sdes#ifdef HAVE_FORK
414238106Sdes	int fd;
415238106Sdes	/* Take off... */
416238106Sdes	switch (fork()) {
417238106Sdes		case 0:
418238106Sdes			break;
419238106Sdes		case -1:
420238106Sdes			fatal_exit("fork failed: %s", strerror(errno));
421238106Sdes		default:
422238106Sdes			/* exit interactive session */
423238106Sdes			exit(0);
424238106Sdes	}
425238106Sdes	/* detach */
426238106Sdes#ifdef HAVE_SETSID
427238106Sdes	if(setsid() == -1)
428238106Sdes		fatal_exit("setsid() failed: %s", strerror(errno));
429238106Sdes#endif
430238106Sdes	if ((fd = open("/dev/null", O_RDWR, 0)) != -1) {
431238106Sdes		(void)dup2(fd, STDIN_FILENO);
432238106Sdes		(void)dup2(fd, STDOUT_FILENO);
433238106Sdes		(void)dup2(fd, STDERR_FILENO);
434238106Sdes		if (fd > 2)
435238106Sdes			(void)close(fd);
436238106Sdes	}
437238106Sdes#endif /* HAVE_FORK */
438238106Sdes#endif /* HAVE_DAEMON */
439238106Sdes}
440238106Sdes
441238106Sdes/** daemonize, drop user priviliges and chroot if needed */
442238106Sdesstatic void
443238106Sdesperform_setup(struct daemon* daemon, struct config_file* cfg, int debug_mode,
444238106Sdes	const char** cfgfile)
445238106Sdes{
446238106Sdes#ifdef HAVE_GETPWNAM
447238106Sdes	struct passwd *pwd = NULL;
448238106Sdes
449238106Sdes	if(cfg->username && cfg->username[0]) {
450238106Sdes		if((pwd = getpwnam(cfg->username)) == NULL)
451238106Sdes			fatal_exit("user '%s' does not exist.", cfg->username);
452238106Sdes		/* endpwent below, in case we need pwd for setusercontext */
453238106Sdes	}
454238106Sdes#endif
455294190Sdes#ifdef UB_ON_WINDOWS
456294190Sdes	w_config_adjust_directory(cfg);
457294190Sdes#endif
458238106Sdes
459238106Sdes	/* init syslog (as root) if needed, before daemonize, otherwise
460238106Sdes	 * a fork error could not be printed since daemonize closed stderr.*/
461238106Sdes	if(cfg->use_syslog) {
462238106Sdes		log_init(cfg->logfile, cfg->use_syslog, cfg->chrootdir);
463238106Sdes	}
464238106Sdes	/* if using a logfile, we cannot open it because the logfile would
465238106Sdes	 * be created with the wrong permissions, we cannot chown it because
466238106Sdes	 * we cannot chown system logfiles, so we do not open at all.
467238106Sdes	 * So, using a logfile, the user does not see errors unless -d is
468238106Sdes	 * given to unbound on the commandline. */
469238106Sdes
470238106Sdes	/* read ssl keys while superuser and outside chroot */
471249141Sdes#ifdef HAVE_SSL
472238106Sdes	if(!(daemon->rc = daemon_remote_create(cfg)))
473238106Sdes		fatal_exit("could not set up remote-control");
474238106Sdes	if(cfg->ssl_service_key && cfg->ssl_service_key[0]) {
475238106Sdes		if(!(daemon->listen_sslctx = listen_sslctx_create(
476238106Sdes			cfg->ssl_service_key, cfg->ssl_service_pem, NULL)))
477238106Sdes			fatal_exit("could not set up listen SSL_CTX");
478238106Sdes	}
479238106Sdes	if(!(daemon->connect_sslctx = connect_sslctx_create(NULL, NULL, NULL)))
480238106Sdes		fatal_exit("could not set up connect SSL_CTX");
481249141Sdes#endif
482238106Sdes
483238106Sdes#ifdef HAVE_KILL
484238106Sdes	/* check old pid file before forking */
485238106Sdes	if(cfg->pidfile && cfg->pidfile[0]) {
486238106Sdes		/* calculate position of pidfile */
487238106Sdes		if(cfg->pidfile[0] == '/')
488238106Sdes			daemon->pidfile = strdup(cfg->pidfile);
489238106Sdes		else	daemon->pidfile = fname_after_chroot(cfg->pidfile,
490238106Sdes				cfg, 1);
491238106Sdes		if(!daemon->pidfile)
492238106Sdes			fatal_exit("pidfile alloc: out of memory");
493238106Sdes		checkoldpid(daemon->pidfile,
494238106Sdes			/* true if pidfile is inside chrootdir, or nochroot */
495238106Sdes			!(cfg->chrootdir && cfg->chrootdir[0]) ||
496238106Sdes			(cfg->chrootdir && cfg->chrootdir[0] &&
497238106Sdes			strncmp(daemon->pidfile, cfg->chrootdir,
498238106Sdes				strlen(cfg->chrootdir))==0));
499238106Sdes	}
500238106Sdes#endif
501238106Sdes
502238106Sdes	/* daemonize because pid is needed by the writepid func */
503238106Sdes	if(!debug_mode && cfg->do_daemonize) {
504238106Sdes		detach();
505238106Sdes	}
506238106Sdes
507238106Sdes	/* write new pidfile (while still root, so can be outside chroot) */
508238106Sdes#ifdef HAVE_KILL
509238106Sdes	if(cfg->pidfile && cfg->pidfile[0]) {
510238106Sdes		writepid(daemon->pidfile, getpid());
511285206Sdes		if(cfg->username && cfg->username[0] && cfg_uid != (uid_t)-1) {
512285206Sdes#  ifdef HAVE_CHOWN
513285206Sdes			if(chown(daemon->pidfile, cfg_uid, cfg_gid) == -1) {
514238106Sdes				log_err("cannot chown %u.%u %s: %s",
515285206Sdes					(unsigned)cfg_uid, (unsigned)cfg_gid,
516238106Sdes					daemon->pidfile, strerror(errno));
517238106Sdes			}
518285206Sdes#  endif /* HAVE_CHOWN */
519238106Sdes		}
520238106Sdes	}
521238106Sdes#else
522238106Sdes	(void)daemon;
523285206Sdes#endif /* HAVE_KILL */
524238106Sdes
525238106Sdes	/* Set user context */
526238106Sdes#ifdef HAVE_GETPWNAM
527285206Sdes	if(cfg->username && cfg->username[0] && cfg_uid != (uid_t)-1) {
528238106Sdes#ifdef HAVE_SETUSERCONTEXT
529238106Sdes		/* setusercontext does initgroups, setuid, setgid, and
530238106Sdes		 * also resource limits from login config, but we
531238106Sdes		 * still call setresuid, setresgid to be sure to set all uid*/
532285206Sdes		if(setusercontext(NULL, pwd, cfg_uid, (unsigned)
533238106Sdes			LOGIN_SETALL & ~LOGIN_SETUSER & ~LOGIN_SETGROUP) != 0)
534238106Sdes			log_warn("unable to setusercontext %s: %s",
535238106Sdes				cfg->username, strerror(errno));
536238106Sdes#endif /* HAVE_SETUSERCONTEXT */
537238106Sdes	}
538238106Sdes#endif /* HAVE_GETPWNAM */
539238106Sdes
540238106Sdes	/* box into the chroot */
541238106Sdes#ifdef HAVE_CHROOT
542238106Sdes	if(cfg->chrootdir && cfg->chrootdir[0]) {
543238106Sdes		if(chdir(cfg->chrootdir)) {
544238106Sdes			fatal_exit("unable to chdir to chroot %s: %s",
545238106Sdes				cfg->chrootdir, strerror(errno));
546238106Sdes		}
547238106Sdes		verbose(VERB_QUERY, "chdir to %s", cfg->chrootdir);
548238106Sdes		if(chroot(cfg->chrootdir))
549238106Sdes			fatal_exit("unable to chroot to %s: %s",
550238106Sdes				cfg->chrootdir, strerror(errno));
551249141Sdes		if(chdir("/"))
552249141Sdes			fatal_exit("unable to chdir to / in chroot %s: %s",
553249141Sdes				cfg->chrootdir, strerror(errno));
554238106Sdes		verbose(VERB_QUERY, "chroot to %s", cfg->chrootdir);
555238106Sdes		if(strncmp(*cfgfile, cfg->chrootdir,
556238106Sdes			strlen(cfg->chrootdir)) == 0)
557238106Sdes			(*cfgfile) += strlen(cfg->chrootdir);
558238106Sdes
559238106Sdes		/* adjust stored pidfile for chroot */
560238106Sdes		if(daemon->pidfile && daemon->pidfile[0] &&
561238106Sdes			strncmp(daemon->pidfile, cfg->chrootdir,
562238106Sdes			strlen(cfg->chrootdir))==0) {
563238106Sdes			char* old = daemon->pidfile;
564238106Sdes			daemon->pidfile = strdup(old+strlen(cfg->chrootdir));
565238106Sdes			free(old);
566238106Sdes			if(!daemon->pidfile)
567238106Sdes				log_err("out of memory in pidfile adjust");
568238106Sdes		}
569238106Sdes		daemon->chroot = strdup(cfg->chrootdir);
570238106Sdes		if(!daemon->chroot)
571238106Sdes			log_err("out of memory in daemon chroot dir storage");
572238106Sdes	}
573238106Sdes#else
574238106Sdes	(void)cfgfile;
575238106Sdes#endif
576238106Sdes	/* change to working directory inside chroot */
577238106Sdes	if(cfg->directory && cfg->directory[0]) {
578238106Sdes		char* dir = cfg->directory;
579238106Sdes		if(cfg->chrootdir && cfg->chrootdir[0] &&
580238106Sdes			strncmp(dir, cfg->chrootdir,
581238106Sdes			strlen(cfg->chrootdir)) == 0)
582238106Sdes			dir += strlen(cfg->chrootdir);
583238106Sdes		if(dir[0]) {
584238106Sdes			if(chdir(dir)) {
585238106Sdes				fatal_exit("Could not chdir to %s: %s",
586238106Sdes					dir, strerror(errno));
587238106Sdes			}
588238106Sdes			verbose(VERB_QUERY, "chdir to %s", dir);
589238106Sdes		}
590238106Sdes	}
591238106Sdes
592238106Sdes	/* drop permissions after chroot, getpwnam, pidfile, syslog done*/
593238106Sdes#ifdef HAVE_GETPWNAM
594285206Sdes	if(cfg->username && cfg->username[0] && cfg_uid != (uid_t)-1) {
595238106Sdes#  ifdef HAVE_INITGROUPS
596285206Sdes		if(initgroups(cfg->username, cfg_gid) != 0)
597238106Sdes			log_warn("unable to initgroups %s: %s",
598238106Sdes				cfg->username, strerror(errno));
599238106Sdes#  endif /* HAVE_INITGROUPS */
600238106Sdes		endpwent();
601238106Sdes
602238106Sdes#ifdef HAVE_SETRESGID
603285206Sdes		if(setresgid(cfg_gid,cfg_gid,cfg_gid) != 0)
604238106Sdes#elif defined(HAVE_SETREGID) && !defined(DARWIN_BROKEN_SETREUID)
605285206Sdes		if(setregid(cfg_gid,cfg_gid) != 0)
606238106Sdes#else /* use setgid */
607285206Sdes		if(setgid(cfg_gid) != 0)
608238106Sdes#endif /* HAVE_SETRESGID */
609238106Sdes			fatal_exit("unable to set group id of %s: %s",
610238106Sdes				cfg->username, strerror(errno));
611238106Sdes#ifdef HAVE_SETRESUID
612285206Sdes		if(setresuid(cfg_uid,cfg_uid,cfg_uid) != 0)
613238106Sdes#elif defined(HAVE_SETREUID) && !defined(DARWIN_BROKEN_SETREUID)
614285206Sdes		if(setreuid(cfg_uid,cfg_uid) != 0)
615238106Sdes#else /* use setuid */
616285206Sdes		if(setuid(cfg_uid) != 0)
617238106Sdes#endif /* HAVE_SETRESUID */
618238106Sdes			fatal_exit("unable to set user id of %s: %s",
619238106Sdes				cfg->username, strerror(errno));
620238106Sdes		verbose(VERB_QUERY, "drop user privileges, run as %s",
621238106Sdes			cfg->username);
622238106Sdes	}
623238106Sdes#endif /* HAVE_GETPWNAM */
624238106Sdes	/* file logging inited after chroot,chdir,setuid is done so that
625238106Sdes	 * it would succeed on SIGHUP as well */
626238106Sdes	if(!cfg->use_syslog)
627238106Sdes		log_init(cfg->logfile, cfg->use_syslog, cfg->chrootdir);
628238106Sdes}
629238106Sdes
630238106Sdes/**
631238106Sdes * Run the daemon.
632238106Sdes * @param cfgfile: the config file name.
633238106Sdes * @param cmdline_verbose: verbosity resulting from commandline -v.
634238106Sdes *    These increase verbosity as specified in the config file.
635238106Sdes * @param debug_mode: if set, do not daemonize.
636238106Sdes */
637238106Sdesstatic void
638238106Sdesrun_daemon(const char* cfgfile, int cmdline_verbose, int debug_mode)
639238106Sdes{
640238106Sdes	struct config_file* cfg = NULL;
641238106Sdes	struct daemon* daemon = NULL;
642238106Sdes	int done_setup = 0;
643238106Sdes
644238106Sdes	if(!(daemon = daemon_init()))
645238106Sdes		fatal_exit("alloc failure");
646238106Sdes	while(!daemon->need_to_exit) {
647238106Sdes		if(done_setup)
648238106Sdes			verbose(VERB_OPS, "Restart of %s.", PACKAGE_STRING);
649238106Sdes		else	verbose(VERB_OPS, "Start of %s.", PACKAGE_STRING);
650238106Sdes
651238106Sdes		/* config stuff */
652238106Sdes		if(!(cfg = config_create()))
653238106Sdes			fatal_exit("Could not alloc config defaults");
654238106Sdes		if(!config_read(cfg, cfgfile, daemon->chroot)) {
655238106Sdes			if(errno != ENOENT)
656238106Sdes				fatal_exit("Could not read config file: %s",
657238106Sdes					cfgfile);
658238106Sdes			log_warn("Continuing with default config settings");
659238106Sdes		}
660285206Sdes		apply_settings(daemon, cfg, cmdline_verbose, debug_mode);
661285206Sdes		if(!done_setup)
662285206Sdes			config_lookup_uid(cfg);
663238106Sdes
664238106Sdes		/* prepare */
665238106Sdes		if(!daemon_open_shared_ports(daemon))
666238106Sdes			fatal_exit("could not open ports");
667238106Sdes		if(!done_setup) {
668238106Sdes			perform_setup(daemon, cfg, debug_mode, &cfgfile);
669238106Sdes			done_setup = 1;
670238106Sdes		} else {
671238106Sdes			/* reopen log after HUP to facilitate log rotation */
672238106Sdes			if(!cfg->use_syslog)
673238106Sdes				log_init(cfg->logfile, 0, cfg->chrootdir);
674238106Sdes		}
675238106Sdes		/* work */
676238106Sdes		daemon_fork(daemon);
677238106Sdes
678238106Sdes		/* clean up for restart */
679238106Sdes		verbose(VERB_ALGO, "cleanup.");
680238106Sdes		daemon_cleanup(daemon);
681238106Sdes		config_delete(cfg);
682238106Sdes	}
683238106Sdes	verbose(VERB_ALGO, "Exit cleanup.");
684238106Sdes	/* this unlink may not work if the pidfile is located outside
685238106Sdes	 * of the chroot/workdir or we no longer have permissions */
686238106Sdes	if(daemon->pidfile) {
687238106Sdes		int fd;
688238106Sdes		/* truncate pidfile */
689238106Sdes		fd = open(daemon->pidfile, O_WRONLY | O_TRUNC, 0644);
690238106Sdes		if(fd != -1)
691238106Sdes			close(fd);
692238106Sdes		/* delete pidfile */
693238106Sdes		unlink(daemon->pidfile);
694238106Sdes	}
695238106Sdes	daemon_delete(daemon);
696238106Sdes}
697238106Sdes
698238106Sdes/** getopt global, in case header files fail to declare it. */
699238106Sdesextern int optind;
700238106Sdes/** getopt global, in case header files fail to declare it. */
701238106Sdesextern char* optarg;
702238106Sdes
703238106Sdes/**
704238106Sdes * main program. Set options given commandline arguments.
705238106Sdes * @param argc: number of commandline arguments.
706238106Sdes * @param argv: array of commandline arguments.
707238106Sdes * @return: exit status of the program.
708238106Sdes */
709238106Sdesint
710238106Sdesmain(int argc, char* argv[])
711238106Sdes{
712238106Sdes	int c;
713238106Sdes	const char* cfgfile = CONFIGFILE;
714238106Sdes	const char* winopt = NULL;
715238106Sdes	int cmdline_verbose = 0;
716238106Sdes	int debug_mode = 0;
717238106Sdes#ifdef UB_ON_WINDOWS
718238106Sdes	int cmdline_cfg = 0;
719238106Sdes#endif
720238106Sdes
721238106Sdes#ifdef HAVE_SBRK
722238106Sdes	/* take debug snapshot of heap */
723238106Sdes	unbound_start_brk = sbrk(0);
724238106Sdes#endif
725238106Sdes
726238106Sdes	log_init(NULL, 0, NULL);
727269257Sdes	log_ident_set(strrchr(argv[0],'/')?strrchr(argv[0],'/')+1:argv[0]);
728238106Sdes	/* parse the options */
729238106Sdes	while( (c=getopt(argc, argv, "c:dhvw:")) != -1) {
730238106Sdes		switch(c) {
731238106Sdes		case 'c':
732238106Sdes			cfgfile = optarg;
733238106Sdes#ifdef UB_ON_WINDOWS
734238106Sdes			cmdline_cfg = 1;
735238106Sdes#endif
736238106Sdes			break;
737238106Sdes		case 'v':
738238106Sdes			cmdline_verbose ++;
739238106Sdes			verbosity++;
740238106Sdes			break;
741238106Sdes		case 'd':
742285206Sdes			debug_mode++;
743238106Sdes			break;
744238106Sdes		case 'w':
745238106Sdes			winopt = optarg;
746238106Sdes			break;
747238106Sdes		case '?':
748238106Sdes		case 'h':
749238106Sdes		default:
750238106Sdes			usage();
751238106Sdes			return 1;
752238106Sdes		}
753238106Sdes	}
754238106Sdes	argc -= optind;
755238106Sdes	argv += optind;
756238106Sdes
757238106Sdes	if(winopt) {
758238106Sdes#ifdef UB_ON_WINDOWS
759238106Sdes		wsvc_command_option(winopt, cfgfile, cmdline_verbose,
760238106Sdes			cmdline_cfg);
761238106Sdes#else
762238106Sdes		fatal_exit("option not supported");
763238106Sdes#endif
764238106Sdes	}
765238106Sdes
766238106Sdes	if(argc != 0) {
767238106Sdes		usage();
768238106Sdes		return 1;
769238106Sdes	}
770238106Sdes
771238106Sdes	run_daemon(cfgfile, cmdline_verbose, debug_mode);
772238106Sdes	log_init(NULL, 0, NULL); /* close logfile */
773238106Sdes	return 0;
774238106Sdes}
775