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()
183249141Sdes#endif
184249141Sdes		);
185238106Sdes	printf("linked modules:");
186238106Sdes	for(m = module_list_avail(); *m; m++)
187238106Sdes		printf(" %s", *m);
188238106Sdes	printf("\n");
189238106Sdes	printf("BSD licensed, see LICENSE in source package for details.\n");
190238106Sdes	printf("Report bugs to %s\n", PACKAGE_BUGREPORT);
191238106Sdes}
192238106Sdes
193238106Sdes#ifndef unbound_testbound
194238106Sdesint replay_var_compare(const void* ATTR_UNUSED(a), const void* ATTR_UNUSED(b))
195238106Sdes{
196238106Sdes        log_assert(0);
197238106Sdes        return 0;
198238106Sdes}
199238106Sdes#endif
200238106Sdes
201238106Sdes/** check file descriptor count */
202238106Sdesstatic void
203238106Sdescheckrlimits(struct config_file* cfg)
204238106Sdes{
205269257Sdes#ifndef S_SPLINT_S
206238106Sdes#ifdef HAVE_GETRLIMIT
207238106Sdes	/* list has number of ports to listen to, ifs number addresses */
208238106Sdes	int list = ((cfg->do_udp?1:0) + (cfg->do_tcp?1 +
209238106Sdes			(int)cfg->incoming_num_tcp:0));
210238106Sdes	size_t listen_ifs = (size_t)(cfg->num_ifs==0?
211238106Sdes		((cfg->do_ip4 && !cfg->if_automatic?1:0) +
212238106Sdes		 (cfg->do_ip6?1:0)):cfg->num_ifs);
213238106Sdes	size_t listen_num = list*listen_ifs;
214238106Sdes	size_t outudpnum = (size_t)cfg->outgoing_num_ports;
215238106Sdes	size_t outtcpnum = cfg->outgoing_num_tcp;
216238106Sdes	size_t misc = 4; /* logfile, pidfile, stdout... */
217238106Sdes	size_t perthread_noudp = listen_num + outtcpnum +
218238106Sdes		2/*cmdpipe*/ + 2/*libevent*/ + misc;
219238106Sdes	size_t perthread = perthread_noudp + outudpnum;
220238106Sdes
221238106Sdes#if !defined(HAVE_PTHREAD) && !defined(HAVE_SOLARIS_THREADS)
222238106Sdes	int numthread = 1; /* it forks */
223238106Sdes#else
224238106Sdes	int numthread = (cfg->num_threads?cfg->num_threads:1);
225238106Sdes#endif
226238106Sdes	size_t total = numthread * perthread + misc;
227238106Sdes	size_t avail;
228238106Sdes	struct rlimit rlim;
229238106Sdes
230238106Sdes	if(total > 1024 &&
231238106Sdes		strncmp(event_get_version(), "mini-event", 10) == 0) {
232238106Sdes		log_warn("too many file descriptors requested. The builtin"
233238106Sdes			"mini-event cannot handle more than 1024. Config "
234238106Sdes			"for less fds or compile with libevent");
235238106Sdes		if(numthread*perthread_noudp+15 > 1024)
236238106Sdes			fatal_exit("too much tcp. not enough fds.");
237238106Sdes		cfg->outgoing_num_ports = (int)((1024
238238106Sdes			- numthread*perthread_noudp
239238106Sdes			- 10 /* safety margin */) /numthread);
240238106Sdes		log_warn("continuing with less udp ports: %u",
241238106Sdes			cfg->outgoing_num_ports);
242238106Sdes		total = 1024;
243238106Sdes	}
244238106Sdes	if(perthread > 64 &&
245238106Sdes		strncmp(event_get_version(), "winsock-event", 13) == 0) {
246238106Sdes		log_err("too many file descriptors requested. The winsock"
247238106Sdes			" event handler cannot handle more than 64 per "
248238106Sdes			" thread. Config for less fds");
249238106Sdes		if(perthread_noudp+2 > 64)
250238106Sdes			fatal_exit("too much tcp. not enough fds.");
251238106Sdes		cfg->outgoing_num_ports = (int)((64
252238106Sdes			- perthread_noudp
253238106Sdes			- 2/* safety margin */));
254238106Sdes		log_warn("continuing with less udp ports: %u",
255238106Sdes			cfg->outgoing_num_ports);
256238106Sdes		total = numthread*(perthread_noudp+
257238106Sdes			(size_t)cfg->outgoing_num_ports)+misc;
258238106Sdes	}
259238106Sdes	if(getrlimit(RLIMIT_NOFILE, &rlim) < 0) {
260238106Sdes		log_warn("getrlimit: %s", strerror(errno));
261238106Sdes		return;
262238106Sdes	}
263238106Sdes	if(rlim.rlim_cur == (rlim_t)RLIM_INFINITY)
264238106Sdes		return;
265238106Sdes	if((size_t)rlim.rlim_cur < total) {
266238106Sdes		avail = (size_t)rlim.rlim_cur;
267238106Sdes		rlim.rlim_cur = (rlim_t)(total + 10);
268238106Sdes		rlim.rlim_max = (rlim_t)(total + 10);
269238106Sdes#ifdef HAVE_SETRLIMIT
270238106Sdes		if(setrlimit(RLIMIT_NOFILE, &rlim) < 0) {
271238106Sdes			log_warn("setrlimit: %s", strerror(errno));
272238106Sdes#endif
273238106Sdes			log_warn("cannot increase max open fds from %u to %u",
274238106Sdes				(unsigned)avail, (unsigned)total+10);
275238106Sdes			/* check that calculation below does not underflow,
276238106Sdes			 * with 15 as margin */
277238106Sdes			if(numthread*perthread_noudp+15 > avail)
278238106Sdes				fatal_exit("too much tcp. not enough fds.");
279238106Sdes			cfg->outgoing_num_ports = (int)((avail
280238106Sdes				- numthread*perthread_noudp
281238106Sdes				- 10 /* safety margin */) /numthread);
282238106Sdes			log_warn("continuing with less udp ports: %u",
283238106Sdes				cfg->outgoing_num_ports);
284238106Sdes			log_warn("increase ulimit or decrease threads, "
285238106Sdes				"ports in config to remove this warning");
286238106Sdes			return;
287285206Sdes#ifdef HAVE_SETRLIMIT
288238106Sdes		}
289285206Sdes#endif
290285206Sdes		verbose(VERB_ALGO, "increased limit(open files) from %u to %u",
291238106Sdes			(unsigned)avail, (unsigned)total+10);
292238106Sdes	}
293238106Sdes#else
294238106Sdes	(void)cfg;
295238106Sdes#endif /* HAVE_GETRLIMIT */
296269257Sdes#endif /* S_SPLINT_S */
297238106Sdes}
298238106Sdes
299238106Sdes/** set verbosity, check rlimits, cache settings */
300238106Sdesstatic void
301238106Sdesapply_settings(struct daemon* daemon, struct config_file* cfg,
302285206Sdes	int cmdline_verbose, int debug_mode)
303238106Sdes{
304238106Sdes	/* apply if they have changed */
305238106Sdes	verbosity = cmdline_verbose + cfg->verbosity;
306285206Sdes	if (debug_mode > 1) {
307285206Sdes		cfg->use_syslog = 0;
308285206Sdes		cfg->logfile = NULL;
309285206Sdes	}
310238106Sdes	daemon_apply_cfg(daemon, cfg);
311238106Sdes	checkrlimits(cfg);
312238106Sdes}
313238106Sdes
314238106Sdes#ifdef HAVE_KILL
315238106Sdes/** Read existing pid from pidfile.
316238106Sdes * @param file: file name of pid file.
317238106Sdes * @return: the pid from the file or -1 if none.
318238106Sdes */
319238106Sdesstatic pid_t
320238106Sdesreadpid (const char* file)
321238106Sdes{
322238106Sdes	int fd;
323238106Sdes	pid_t pid;
324238106Sdes	char pidbuf[32];
325238106Sdes	char* t;
326238106Sdes	ssize_t l;
327238106Sdes
328238106Sdes	if ((fd = open(file, O_RDONLY)) == -1) {
329238106Sdes		if(errno != ENOENT)
330238106Sdes			log_err("Could not read pidfile %s: %s",
331238106Sdes				file, strerror(errno));
332238106Sdes		return -1;
333238106Sdes	}
334238106Sdes
335238106Sdes	if (((l = read(fd, pidbuf, sizeof(pidbuf)))) == -1) {
336238106Sdes		if(errno != ENOENT)
337238106Sdes			log_err("Could not read pidfile %s: %s",
338238106Sdes				file, strerror(errno));
339238106Sdes		close(fd);
340238106Sdes		return -1;
341238106Sdes	}
342238106Sdes
343238106Sdes	close(fd);
344238106Sdes
345238106Sdes	/* Empty pidfile means no pidfile... */
346238106Sdes	if (l == 0) {
347238106Sdes		return -1;
348238106Sdes	}
349238106Sdes
350238106Sdes	pidbuf[sizeof(pidbuf)-1] = 0;
351238106Sdes	pid = (pid_t)strtol(pidbuf, &t, 10);
352238106Sdes
353238106Sdes	if (*t && *t != '\n') {
354238106Sdes		return -1;
355238106Sdes	}
356238106Sdes	return pid;
357238106Sdes}
358238106Sdes
359238106Sdes/** write pid to file.
360238106Sdes * @param pidfile: file name of pid file.
361238106Sdes * @param pid: pid to write to file.
362238106Sdes */
363238106Sdesstatic void
364238106Sdeswritepid (const char* pidfile, pid_t pid)
365238106Sdes{
366238106Sdes	FILE* f;
367238106Sdes
368238106Sdes	if ((f = fopen(pidfile, "w")) ==  NULL ) {
369238106Sdes		log_err("cannot open pidfile %s: %s",
370238106Sdes			pidfile, strerror(errno));
371238106Sdes		return;
372238106Sdes	}
373238106Sdes	if(fprintf(f, "%lu\n", (unsigned long)pid) < 0) {
374238106Sdes		log_err("cannot write to pidfile %s: %s",
375238106Sdes			pidfile, strerror(errno));
376238106Sdes	}
377238106Sdes	fclose(f);
378238106Sdes}
379238106Sdes
380238106Sdes/**
381238106Sdes * check old pid file.
382238106Sdes * @param pidfile: the file name of the pid file.
383238106Sdes * @param inchroot: if pidfile is inchroot and we can thus expect to
384238106Sdes *	be able to delete it.
385238106Sdes */
386238106Sdesstatic void
387238106Sdescheckoldpid(char* pidfile, int inchroot)
388238106Sdes{
389238106Sdes	pid_t old;
390238106Sdes	if((old = readpid(pidfile)) != -1) {
391238106Sdes		/* see if it is still alive */
392238106Sdes		if(kill(old, 0) == 0 || errno == EPERM)
393238106Sdes			log_warn("unbound is already running as pid %u.",
394238106Sdes				(unsigned)old);
395238106Sdes		else	if(inchroot)
396238106Sdes			log_warn("did not exit gracefully last time (%u)",
397238106Sdes				(unsigned)old);
398238106Sdes	}
399238106Sdes}
400238106Sdes#endif /* HAVE_KILL */
401238106Sdes
402238106Sdes/** detach from command line */
403238106Sdesstatic void
404238106Sdesdetach(void)
405238106Sdes{
406238106Sdes#if defined(HAVE_DAEMON) && !defined(DEPRECATED_DAEMON)
407238106Sdes	/* use POSIX daemon(3) function */
408238106Sdes	if(daemon(1, 0) != 0)
409238106Sdes		fatal_exit("daemon failed: %s", strerror(errno));
410238106Sdes#else /* no HAVE_DAEMON */
411238106Sdes#ifdef HAVE_FORK
412238106Sdes	int fd;
413238106Sdes	/* Take off... */
414238106Sdes	switch (fork()) {
415238106Sdes		case 0:
416238106Sdes			break;
417238106Sdes		case -1:
418238106Sdes			fatal_exit("fork failed: %s", strerror(errno));
419238106Sdes		default:
420238106Sdes			/* exit interactive session */
421238106Sdes			exit(0);
422238106Sdes	}
423238106Sdes	/* detach */
424238106Sdes#ifdef HAVE_SETSID
425238106Sdes	if(setsid() == -1)
426238106Sdes		fatal_exit("setsid() failed: %s", strerror(errno));
427238106Sdes#endif
428238106Sdes	if ((fd = open("/dev/null", O_RDWR, 0)) != -1) {
429238106Sdes		(void)dup2(fd, STDIN_FILENO);
430238106Sdes		(void)dup2(fd, STDOUT_FILENO);
431238106Sdes		(void)dup2(fd, STDERR_FILENO);
432238106Sdes		if (fd > 2)
433238106Sdes			(void)close(fd);
434238106Sdes	}
435238106Sdes#endif /* HAVE_FORK */
436238106Sdes#endif /* HAVE_DAEMON */
437238106Sdes}
438238106Sdes
439238106Sdes/** daemonize, drop user priviliges and chroot if needed */
440238106Sdesstatic void
441238106Sdesperform_setup(struct daemon* daemon, struct config_file* cfg, int debug_mode,
442238106Sdes	const char** cfgfile)
443238106Sdes{
444238106Sdes#ifdef HAVE_GETPWNAM
445238106Sdes	struct passwd *pwd = NULL;
446238106Sdes
447238106Sdes	if(cfg->username && cfg->username[0]) {
448238106Sdes		if((pwd = getpwnam(cfg->username)) == NULL)
449238106Sdes			fatal_exit("user '%s' does not exist.", cfg->username);
450238106Sdes		/* endpwent below, in case we need pwd for setusercontext */
451238106Sdes	}
452238106Sdes#endif
453238106Sdes
454238106Sdes	/* init syslog (as root) if needed, before daemonize, otherwise
455238106Sdes	 * a fork error could not be printed since daemonize closed stderr.*/
456238106Sdes	if(cfg->use_syslog) {
457238106Sdes		log_init(cfg->logfile, cfg->use_syslog, cfg->chrootdir);
458238106Sdes	}
459238106Sdes	/* if using a logfile, we cannot open it because the logfile would
460238106Sdes	 * be created with the wrong permissions, we cannot chown it because
461238106Sdes	 * we cannot chown system logfiles, so we do not open at all.
462238106Sdes	 * So, using a logfile, the user does not see errors unless -d is
463238106Sdes	 * given to unbound on the commandline. */
464238106Sdes
465238106Sdes	/* read ssl keys while superuser and outside chroot */
466249141Sdes#ifdef HAVE_SSL
467238106Sdes	if(!(daemon->rc = daemon_remote_create(cfg)))
468238106Sdes		fatal_exit("could not set up remote-control");
469238106Sdes	if(cfg->ssl_service_key && cfg->ssl_service_key[0]) {
470238106Sdes		if(!(daemon->listen_sslctx = listen_sslctx_create(
471238106Sdes			cfg->ssl_service_key, cfg->ssl_service_pem, NULL)))
472238106Sdes			fatal_exit("could not set up listen SSL_CTX");
473238106Sdes	}
474238106Sdes	if(!(daemon->connect_sslctx = connect_sslctx_create(NULL, NULL, NULL)))
475238106Sdes		fatal_exit("could not set up connect SSL_CTX");
476249141Sdes#endif
477238106Sdes
478238106Sdes#ifdef HAVE_KILL
479238106Sdes	/* check old pid file before forking */
480238106Sdes	if(cfg->pidfile && cfg->pidfile[0]) {
481238106Sdes		/* calculate position of pidfile */
482238106Sdes		if(cfg->pidfile[0] == '/')
483238106Sdes			daemon->pidfile = strdup(cfg->pidfile);
484238106Sdes		else	daemon->pidfile = fname_after_chroot(cfg->pidfile,
485238106Sdes				cfg, 1);
486238106Sdes		if(!daemon->pidfile)
487238106Sdes			fatal_exit("pidfile alloc: out of memory");
488238106Sdes		checkoldpid(daemon->pidfile,
489238106Sdes			/* true if pidfile is inside chrootdir, or nochroot */
490238106Sdes			!(cfg->chrootdir && cfg->chrootdir[0]) ||
491238106Sdes			(cfg->chrootdir && cfg->chrootdir[0] &&
492238106Sdes			strncmp(daemon->pidfile, cfg->chrootdir,
493238106Sdes				strlen(cfg->chrootdir))==0));
494238106Sdes	}
495238106Sdes#endif
496238106Sdes
497238106Sdes	/* daemonize because pid is needed by the writepid func */
498238106Sdes	if(!debug_mode && cfg->do_daemonize) {
499238106Sdes		detach();
500238106Sdes	}
501238106Sdes
502238106Sdes	/* write new pidfile (while still root, so can be outside chroot) */
503238106Sdes#ifdef HAVE_KILL
504238106Sdes	if(cfg->pidfile && cfg->pidfile[0]) {
505238106Sdes		writepid(daemon->pidfile, getpid());
506285206Sdes		if(cfg->username && cfg->username[0] && cfg_uid != (uid_t)-1) {
507285206Sdes#  ifdef HAVE_CHOWN
508285206Sdes			if(chown(daemon->pidfile, cfg_uid, cfg_gid) == -1) {
509238106Sdes				log_err("cannot chown %u.%u %s: %s",
510285206Sdes					(unsigned)cfg_uid, (unsigned)cfg_gid,
511238106Sdes					daemon->pidfile, strerror(errno));
512238106Sdes			}
513285206Sdes#  endif /* HAVE_CHOWN */
514238106Sdes		}
515238106Sdes	}
516238106Sdes#else
517238106Sdes	(void)daemon;
518285206Sdes#endif /* HAVE_KILL */
519238106Sdes
520238106Sdes	/* Set user context */
521238106Sdes#ifdef HAVE_GETPWNAM
522285206Sdes	if(cfg->username && cfg->username[0] && cfg_uid != (uid_t)-1) {
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*/
527285206Sdes		if(setusercontext(NULL, pwd, cfg_uid, (unsigned)
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
589285206Sdes	if(cfg->username && cfg->username[0] && cfg_uid != (uid_t)-1) {
590238106Sdes#  ifdef HAVE_INITGROUPS
591285206Sdes		if(initgroups(cfg->username, cfg_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
598285206Sdes		if(setresgid(cfg_gid,cfg_gid,cfg_gid) != 0)
599238106Sdes#elif defined(HAVE_SETREGID) && !defined(DARWIN_BROKEN_SETREUID)
600285206Sdes		if(setregid(cfg_gid,cfg_gid) != 0)
601238106Sdes#else /* use setgid */
602285206Sdes		if(setgid(cfg_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
607285206Sdes		if(setresuid(cfg_uid,cfg_uid,cfg_uid) != 0)
608238106Sdes#elif defined(HAVE_SETREUID) && !defined(DARWIN_BROKEN_SETREUID)
609285206Sdes		if(setreuid(cfg_uid,cfg_uid) != 0)
610238106Sdes#else /* use setuid */
611285206Sdes		if(setuid(cfg_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		}
655285206Sdes		apply_settings(daemon, cfg, cmdline_verbose, debug_mode);
656285206Sdes		if(!done_setup)
657285206Sdes			config_lookup_uid(cfg);
658238106Sdes
659238106Sdes		/* prepare */
660238106Sdes		if(!daemon_open_shared_ports(daemon))
661238106Sdes			fatal_exit("could not open ports");
662238106Sdes		if(!done_setup) {
663238106Sdes			perform_setup(daemon, cfg, debug_mode, &cfgfile);
664238106Sdes			done_setup = 1;
665238106Sdes		} else {
666238106Sdes			/* reopen log after HUP to facilitate log rotation */
667238106Sdes			if(!cfg->use_syslog)
668238106Sdes				log_init(cfg->logfile, 0, cfg->chrootdir);
669238106Sdes		}
670238106Sdes		/* work */
671238106Sdes		daemon_fork(daemon);
672238106Sdes
673238106Sdes		/* clean up for restart */
674238106Sdes		verbose(VERB_ALGO, "cleanup.");
675238106Sdes		daemon_cleanup(daemon);
676238106Sdes		config_delete(cfg);
677238106Sdes	}
678238106Sdes	verbose(VERB_ALGO, "Exit cleanup.");
679238106Sdes	/* this unlink may not work if the pidfile is located outside
680238106Sdes	 * of the chroot/workdir or we no longer have permissions */
681238106Sdes	if(daemon->pidfile) {
682238106Sdes		int fd;
683238106Sdes		/* truncate pidfile */
684238106Sdes		fd = open(daemon->pidfile, O_WRONLY | O_TRUNC, 0644);
685238106Sdes		if(fd != -1)
686238106Sdes			close(fd);
687238106Sdes		/* delete pidfile */
688238106Sdes		unlink(daemon->pidfile);
689238106Sdes	}
690238106Sdes	daemon_delete(daemon);
691238106Sdes}
692238106Sdes
693238106Sdes/** getopt global, in case header files fail to declare it. */
694238106Sdesextern int optind;
695238106Sdes/** getopt global, in case header files fail to declare it. */
696238106Sdesextern char* optarg;
697238106Sdes
698238106Sdes/**
699238106Sdes * main program. Set options given commandline arguments.
700238106Sdes * @param argc: number of commandline arguments.
701238106Sdes * @param argv: array of commandline arguments.
702238106Sdes * @return: exit status of the program.
703238106Sdes */
704238106Sdesint
705238106Sdesmain(int argc, char* argv[])
706238106Sdes{
707238106Sdes	int c;
708238106Sdes	const char* cfgfile = CONFIGFILE;
709238106Sdes	const char* winopt = NULL;
710238106Sdes	int cmdline_verbose = 0;
711238106Sdes	int debug_mode = 0;
712238106Sdes#ifdef UB_ON_WINDOWS
713238106Sdes	int cmdline_cfg = 0;
714238106Sdes#endif
715238106Sdes
716238106Sdes#ifdef HAVE_SBRK
717238106Sdes	/* take debug snapshot of heap */
718238106Sdes	unbound_start_brk = sbrk(0);
719238106Sdes#endif
720238106Sdes
721238106Sdes	log_init(NULL, 0, NULL);
722269257Sdes	log_ident_set(strrchr(argv[0],'/')?strrchr(argv[0],'/')+1:argv[0]);
723238106Sdes	/* parse the options */
724238106Sdes	while( (c=getopt(argc, argv, "c:dhvw:")) != -1) {
725238106Sdes		switch(c) {
726238106Sdes		case 'c':
727238106Sdes			cfgfile = optarg;
728238106Sdes#ifdef UB_ON_WINDOWS
729238106Sdes			cmdline_cfg = 1;
730238106Sdes#endif
731238106Sdes			break;
732238106Sdes		case 'v':
733238106Sdes			cmdline_verbose ++;
734238106Sdes			verbosity++;
735238106Sdes			break;
736238106Sdes		case 'd':
737285206Sdes			debug_mode++;
738238106Sdes			break;
739238106Sdes		case 'w':
740238106Sdes			winopt = optarg;
741238106Sdes			break;
742238106Sdes		case '?':
743238106Sdes		case 'h':
744238106Sdes		default:
745238106Sdes			usage();
746238106Sdes			return 1;
747238106Sdes		}
748238106Sdes	}
749238106Sdes	argc -= optind;
750238106Sdes	argv += optind;
751238106Sdes
752238106Sdes	if(winopt) {
753238106Sdes#ifdef UB_ON_WINDOWS
754238106Sdes		wsvc_command_option(winopt, cfgfile, cmdline_verbose,
755238106Sdes			cmdline_cfg);
756238106Sdes#else
757238106Sdes		fatal_exit("option not supported");
758238106Sdes#endif
759238106Sdes	}
760238106Sdes
761238106Sdes	if(argc != 0) {
762238106Sdes		usage();
763238106Sdes		return 1;
764238106Sdes	}
765238106Sdes
766238106Sdes	run_daemon(cfgfile, cmdline_verbose, debug_mode);
767238106Sdes	log_init(NULL, 0, NULL); /* close logfile */
768238106Sdes	return 0;
769238106Sdes}
770