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