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