xref: /openbsd/usr.sbin/unbound/daemon/unbound.c (revision cca36db2)
1 /*
2  * daemon/unbound.c - main program for unbound DNS resolver daemon.
3  *
4  * Copyright (c) 2007, NLnet Labs. All rights reserved.
5  *
6  * This software is open source.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  *
12  * Redistributions of source code must retain the above copyright notice,
13  * this list of conditions and the following disclaimer.
14  *
15  * Redistributions in binary form must reproduce the above copyright notice,
16  * this list of conditions and the following disclaimer in the documentation
17  * and/or other materials provided with the distribution.
18  *
19  * Neither the name of the NLNET LABS nor the names of its contributors may
20  * be used to endorse or promote products derived from this software without
21  * specific prior written permission.
22  *
23  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
24  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
25  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
26  * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE
27  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
28  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
29  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
30  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
31  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
32  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
33  * POSSIBILITY OF SUCH DAMAGE.
34  *
35  */
36 
37 /**
38  * \file
39  *
40  * Main program to start the DNS resolver daemon.
41  */
42 
43 #include "config.h"
44 #ifdef HAVE_GETOPT_H
45 #include <getopt.h>
46 #endif
47 #include <sys/time.h>
48 #include "util/log.h"
49 #include "daemon/daemon.h"
50 #include "daemon/remote.h"
51 #include "util/config_file.h"
52 #include "util/storage/slabhash.h"
53 #include "services/listen_dnsport.h"
54 #include "services/cache/rrset.h"
55 #include "services/cache/infra.h"
56 #include "util/data/msgreply.h"
57 #include "util/module.h"
58 #include "util/net_help.h"
59 #include <signal.h>
60 #include <fcntl.h>
61 #include <openssl/crypto.h>
62 #ifdef HAVE_PWD_H
63 #include <pwd.h>
64 #endif
65 #ifdef HAVE_GRP_H
66 #include <grp.h>
67 #endif
68 
69 #ifdef HAVE_SYS_RESOURCE_H
70 #include <sys/resource.h>
71 #endif
72 #ifdef HAVE_LOGIN_CAP_H
73 #include <login_cap.h>
74 #endif
75 
76 #ifdef USE_MINI_EVENT
77 #  ifdef USE_WINSOCK
78 #    include "util/winsock_event.h"
79 #  else
80 #    include "util/mini_event.h"
81 #  endif
82 #else
83 #  include <event.h>
84 #endif
85 
86 #ifdef UB_ON_WINDOWS
87 #  include "winrc/win_svc.h"
88 #endif
89 
90 /** global debug value to keep track of heap memory allocation */
91 void* unbound_start_brk = 0;
92 
93 #if !defined(HAVE_EVENT_BASE_GET_METHOD) && (defined(HAVE_EV_LOOP) || defined(HAVE_EV_DEFAULT_LOOP))
94 static const char* ev_backend2str(int b)
95 {
96 	switch(b) {
97 	case EVBACKEND_SELECT:	return "select";
98 	case EVBACKEND_POLL:	return "poll";
99 	case EVBACKEND_EPOLL:	return "epoll";
100 	case EVBACKEND_KQUEUE:	return "kqueue";
101 	case EVBACKEND_DEVPOLL: return "devpoll";
102 	case EVBACKEND_PORT:	return "evport";
103 	}
104 	return "unknown";
105 }
106 #endif
107 
108 /** get the event system in use */
109 static void get_event_sys(const char** n, const char** s, const char** m)
110 {
111 #ifdef USE_WINSOCK
112 	*n = "event";
113 	*s = "winsock";
114 	*m = "WSAWaitForMultipleEvents";
115 #elif defined(USE_MINI_EVENT)
116 	*n = "mini-event";
117 	*s = "internal";
118 	*m = "select";
119 #else
120 	struct event_base* b;
121 	*s = event_get_version();
122 #  ifdef HAVE_EVENT_BASE_GET_METHOD
123 	*n = "libevent";
124 	b = event_base_new();
125 	*m = event_base_get_method(b);
126 #  elif defined(HAVE_EV_LOOP) || defined(HAVE_EV_DEFAULT_LOOP)
127 	*n = "libev";
128 	b = (struct event_base*)ev_default_loop(EVFLAG_AUTO);
129 	*m = ev_backend2str(ev_backend((struct ev_loop*)b));
130 #  else
131 	*n = "unknown";
132 	*m = "not obtainable";
133 	b = NULL;
134 #  endif
135 #  ifdef HAVE_EVENT_BASE_FREE
136 	event_base_free(b);
137 #  endif
138 #endif
139 }
140 
141 /** print usage. */
142 static void usage()
143 {
144 	const char** m;
145 	const char *evnm="event", *evsys="", *evmethod="";
146 	printf("usage:  unbound [options]\n");
147 	printf("	start unbound daemon DNS resolver.\n");
148 	printf("-h	this help\n");
149 	printf("-c file	config file to read instead of %s\n", CONFIGFILE);
150 	printf("	file format is described in unbound.conf(5).\n");
151 	printf("-d	do not fork into the background.\n");
152 	printf("-v	verbose (more times to increase verbosity)\n");
153 #ifdef UB_ON_WINDOWS
154 	printf("-w opt	windows option: \n");
155 	printf("   	install, remove - manage the services entry\n");
156 	printf("   	service - used to start from services control panel\n");
157 #endif
158 	printf("Version %s\n", PACKAGE_VERSION);
159 	get_event_sys(&evnm, &evsys, &evmethod);
160 	printf("linked libs: %s %s (it uses %s), ldns %s, %s\n",
161 		evnm, evsys, evmethod, ldns_version(),
162 		SSLeay_version(SSLEAY_VERSION));
163 	printf("linked modules:");
164 	for(m = module_list_avail(); *m; m++)
165 		printf(" %s", *m);
166 	printf("\n");
167 	printf("configured for %s on %s with options:%s\n",
168 		CONFIGURE_TARGET, CONFIGURE_DATE, CONFIGURE_BUILD_WITH);
169 	printf("BSD licensed, see LICENSE in source package for details.\n");
170 	printf("Report bugs to %s\n", PACKAGE_BUGREPORT);
171 }
172 
173 #ifndef unbound_testbound
174 int replay_var_compare(const void* ATTR_UNUSED(a), const void* ATTR_UNUSED(b))
175 {
176         log_assert(0);
177         return 0;
178 }
179 #endif
180 
181 /** check file descriptor count */
182 static void
183 checkrlimits(struct config_file* cfg)
184 {
185 #ifdef HAVE_GETRLIMIT
186 	/* list has number of ports to listen to, ifs number addresses */
187 	int list = ((cfg->do_udp?1:0) + (cfg->do_tcp?1 +
188 			(int)cfg->incoming_num_tcp:0));
189 	size_t listen_ifs = (size_t)(cfg->num_ifs==0?
190 		((cfg->do_ip4 && !cfg->if_automatic?1:0) +
191 		 (cfg->do_ip6?1:0)):cfg->num_ifs);
192 	size_t listen_num = list*listen_ifs;
193 	size_t outudpnum = (size_t)cfg->outgoing_num_ports;
194 	size_t outtcpnum = cfg->outgoing_num_tcp;
195 	size_t misc = 4; /* logfile, pidfile, stdout... */
196 	size_t perthread_noudp = listen_num + outtcpnum +
197 		2/*cmdpipe*/ + 2/*libevent*/ + misc;
198 	size_t perthread = perthread_noudp + outudpnum;
199 
200 #if !defined(HAVE_PTHREAD) && !defined(HAVE_SOLARIS_THREADS)
201 	int numthread = 1; /* it forks */
202 #else
203 	int numthread = (cfg->num_threads?cfg->num_threads:1);
204 #endif
205 	size_t total = numthread * perthread + misc;
206 	size_t avail;
207 	struct rlimit rlim;
208 
209 	if(total > 1024 &&
210 		strncmp(event_get_version(), "mini-event", 10) == 0) {
211 		log_warn("too many file descriptors requested. The builtin"
212 			"mini-event cannot handle more than 1024. Config "
213 			"for less fds or compile with libevent");
214 		if(numthread*perthread_noudp+15 > 1024)
215 			fatal_exit("too much tcp. not enough fds.");
216 		cfg->outgoing_num_ports = (int)((1024
217 			- numthread*perthread_noudp
218 			- 10 /* safety margin */) /numthread);
219 		log_warn("continuing with less udp ports: %u",
220 			cfg->outgoing_num_ports);
221 		total = 1024;
222 	}
223 	if(perthread > 64 &&
224 		strncmp(event_get_version(), "winsock-event", 13) == 0) {
225 		log_err("too many file descriptors requested. The winsock"
226 			" event handler cannot handle more than 64 per "
227 			" thread. Config for less fds");
228 		if(perthread_noudp+2 > 64)
229 			fatal_exit("too much tcp. not enough fds.");
230 		cfg->outgoing_num_ports = (int)((64
231 			- perthread_noudp
232 			- 2/* safety margin */));
233 		log_warn("continuing with less udp ports: %u",
234 			cfg->outgoing_num_ports);
235 		total = numthread*(perthread_noudp+
236 			(size_t)cfg->outgoing_num_ports)+misc;
237 	}
238 	if(getrlimit(RLIMIT_NOFILE, &rlim) < 0) {
239 		log_warn("getrlimit: %s", strerror(errno));
240 		return;
241 	}
242 	if(rlim.rlim_cur == (rlim_t)RLIM_INFINITY)
243 		return;
244 	if((size_t)rlim.rlim_cur < total) {
245 		avail = (size_t)rlim.rlim_cur;
246 		rlim.rlim_cur = (rlim_t)(total + 10);
247 		rlim.rlim_max = (rlim_t)(total + 10);
248 #ifdef HAVE_SETRLIMIT
249 		if(setrlimit(RLIMIT_NOFILE, &rlim) < 0) {
250 			log_warn("setrlimit: %s", strerror(errno));
251 #else
252 		if(1) {
253 #endif
254 			log_warn("cannot increase max open fds from %u to %u",
255 				(unsigned)avail, (unsigned)total+10);
256 			/* check that calculation below does not underflow,
257 			 * with 15 as margin */
258 			if(numthread*perthread_noudp+15 > avail)
259 				fatal_exit("too much tcp. not enough fds.");
260 			cfg->outgoing_num_ports = (int)((avail
261 				- numthread*perthread_noudp
262 				- 10 /* safety margin */) /numthread);
263 			log_warn("continuing with less udp ports: %u",
264 				cfg->outgoing_num_ports);
265 			log_warn("increase ulimit or decrease threads, "
266 				"ports in config to remove this warning");
267 			return;
268 		}
269 		log_warn("increased limit(open files) from %u to %u",
270 			(unsigned)avail, (unsigned)total+10);
271 	}
272 #else
273 	(void)cfg;
274 #endif /* HAVE_GETRLIMIT */
275 }
276 
277 /** set verbosity, check rlimits, cache settings */
278 static void
279 apply_settings(struct daemon* daemon, struct config_file* cfg,
280 	int cmdline_verbose)
281 {
282 	/* apply if they have changed */
283 	verbosity = cmdline_verbose + cfg->verbosity;
284 	daemon_apply_cfg(daemon, cfg);
285 	checkrlimits(cfg);
286 }
287 
288 #ifdef HAVE_KILL
289 /** Read existing pid from pidfile.
290  * @param file: file name of pid file.
291  * @return: the pid from the file or -1 if none.
292  */
293 static pid_t
294 readpid (const char* file)
295 {
296 	int fd;
297 	pid_t pid;
298 	char pidbuf[32];
299 	char* t;
300 	ssize_t l;
301 
302 	if ((fd = open(file, O_RDONLY)) == -1) {
303 		if(errno != ENOENT)
304 			log_err("Could not read pidfile %s: %s",
305 				file, strerror(errno));
306 		return -1;
307 	}
308 
309 	if (((l = read(fd, pidbuf, sizeof(pidbuf)))) == -1) {
310 		if(errno != ENOENT)
311 			log_err("Could not read pidfile %s: %s",
312 				file, strerror(errno));
313 		close(fd);
314 		return -1;
315 	}
316 
317 	close(fd);
318 
319 	/* Empty pidfile means no pidfile... */
320 	if (l == 0) {
321 		return -1;
322 	}
323 
324 	pidbuf[sizeof(pidbuf)-1] = 0;
325 	pid = (pid_t)strtol(pidbuf, &t, 10);
326 
327 	if (*t && *t != '\n') {
328 		return -1;
329 	}
330 	return pid;
331 }
332 
333 /** write pid to file.
334  * @param pidfile: file name of pid file.
335  * @param pid: pid to write to file.
336  */
337 static void
338 writepid (const char* pidfile, pid_t pid)
339 {
340 	FILE* f;
341 
342 	if ((f = fopen(pidfile, "w")) ==  NULL ) {
343 		log_err("cannot open pidfile %s: %s",
344 			pidfile, strerror(errno));
345 		return;
346 	}
347 	if(fprintf(f, "%lu\n", (unsigned long)pid) < 0) {
348 		log_err("cannot write to pidfile %s: %s",
349 			pidfile, strerror(errno));
350 	}
351 	fclose(f);
352 }
353 
354 /**
355  * check old pid file.
356  * @param pidfile: the file name of the pid file.
357  * @param inchroot: if pidfile is inchroot and we can thus expect to
358  *	be able to delete it.
359  */
360 static void
361 checkoldpid(char* pidfile, int inchroot)
362 {
363 	pid_t old;
364 	if((old = readpid(pidfile)) != -1) {
365 		/* see if it is still alive */
366 		if(kill(old, 0) == 0 || errno == EPERM)
367 			log_warn("unbound is already running as pid %u.",
368 				(unsigned)old);
369 		else	if(inchroot)
370 			log_warn("did not exit gracefully last time (%u)",
371 				(unsigned)old);
372 	}
373 }
374 #endif /* HAVE_KILL */
375 
376 /** detach from command line */
377 static void
378 detach(void)
379 {
380 #if defined(HAVE_DAEMON) && !defined(DEPRECATED_DAEMON)
381 	/* use POSIX daemon(3) function */
382 	if(daemon(1, 0) != 0)
383 		fatal_exit("daemon failed: %s", strerror(errno));
384 #else /* no HAVE_DAEMON */
385 #ifdef HAVE_FORK
386 	int fd;
387 	/* Take off... */
388 	switch (fork()) {
389 		case 0:
390 			break;
391 		case -1:
392 			fatal_exit("fork failed: %s", strerror(errno));
393 		default:
394 			/* exit interactive session */
395 			exit(0);
396 	}
397 	/* detach */
398 #ifdef HAVE_SETSID
399 	if(setsid() == -1)
400 		fatal_exit("setsid() failed: %s", strerror(errno));
401 #endif
402 	if ((fd = open("/dev/null", O_RDWR, 0)) != -1) {
403 		(void)dup2(fd, STDIN_FILENO);
404 		(void)dup2(fd, STDOUT_FILENO);
405 		(void)dup2(fd, STDERR_FILENO);
406 		if (fd > 2)
407 			(void)close(fd);
408 	}
409 #endif /* HAVE_FORK */
410 #endif /* HAVE_DAEMON */
411 }
412 
413 /** daemonize, drop user priviliges and chroot if needed */
414 static void
415 perform_setup(struct daemon* daemon, struct config_file* cfg, int debug_mode,
416 	const char** cfgfile)
417 {
418 #ifdef HAVE_GETPWNAM
419 	struct passwd *pwd = NULL;
420 	uid_t uid;
421 	gid_t gid;
422 	/* initialize, but not to 0 (root) */
423 	memset(&uid, 112, sizeof(uid));
424 	memset(&gid, 112, sizeof(gid));
425 	log_assert(cfg);
426 
427 	if(cfg->username && cfg->username[0]) {
428 		if((pwd = getpwnam(cfg->username)) == NULL)
429 			fatal_exit("user '%s' does not exist.", cfg->username);
430 		uid = pwd->pw_uid;
431 		gid = pwd->pw_gid;
432 		/* endpwent below, in case we need pwd for setusercontext */
433 	}
434 #endif
435 
436 	/* init syslog (as root) if needed, before daemonize, otherwise
437 	 * a fork error could not be printed since daemonize closed stderr.*/
438 	if(cfg->use_syslog) {
439 		log_init(cfg->logfile, cfg->use_syslog, cfg->chrootdir);
440 	}
441 	/* if using a logfile, we cannot open it because the logfile would
442 	 * be created with the wrong permissions, we cannot chown it because
443 	 * we cannot chown system logfiles, so we do not open at all.
444 	 * So, using a logfile, the user does not see errors unless -d is
445 	 * given to unbound on the commandline. */
446 
447 	/* read ssl keys while superuser and outside chroot */
448 	if(!(daemon->rc = daemon_remote_create(cfg)))
449 		fatal_exit("could not set up remote-control");
450 	if(cfg->ssl_service_key && cfg->ssl_service_key[0]) {
451 		if(!(daemon->listen_sslctx = listen_sslctx_create(
452 			cfg->ssl_service_key, cfg->ssl_service_pem, NULL)))
453 			fatal_exit("could not set up listen SSL_CTX");
454 	}
455 	if(!(daemon->connect_sslctx = connect_sslctx_create(NULL, NULL, NULL)))
456 		fatal_exit("could not set up connect SSL_CTX");
457 
458 #ifdef HAVE_KILL
459 	/* check old pid file before forking */
460 	if(cfg->pidfile && cfg->pidfile[0]) {
461 		/* calculate position of pidfile */
462 		if(cfg->pidfile[0] == '/')
463 			daemon->pidfile = strdup(cfg->pidfile);
464 		else	daemon->pidfile = fname_after_chroot(cfg->pidfile,
465 				cfg, 1);
466 		if(!daemon->pidfile)
467 			fatal_exit("pidfile alloc: out of memory");
468 		checkoldpid(daemon->pidfile,
469 			/* true if pidfile is inside chrootdir, or nochroot */
470 			!(cfg->chrootdir && cfg->chrootdir[0]) ||
471 			(cfg->chrootdir && cfg->chrootdir[0] &&
472 			strncmp(daemon->pidfile, cfg->chrootdir,
473 				strlen(cfg->chrootdir))==0));
474 	}
475 #endif
476 
477 	/* daemonize because pid is needed by the writepid func */
478 	if(!debug_mode && cfg->do_daemonize) {
479 		detach();
480 	}
481 
482 	/* write new pidfile (while still root, so can be outside chroot) */
483 #ifdef HAVE_KILL
484 	if(cfg->pidfile && cfg->pidfile[0]) {
485 		writepid(daemon->pidfile, getpid());
486 		if(!(cfg->chrootdir && cfg->chrootdir[0]) ||
487 			(cfg->chrootdir && cfg->chrootdir[0] &&
488 			strncmp(daemon->pidfile, cfg->chrootdir,
489 			strlen(cfg->chrootdir))==0)) {
490 			/* delete of pidfile could potentially work,
491 			 * chown to get permissions */
492 			if(cfg->username && cfg->username[0]) {
493 			  if(chown(daemon->pidfile, uid, gid) == -1) {
494 				log_err("cannot chown %u.%u %s: %s",
495 					(unsigned)uid, (unsigned)gid,
496 					daemon->pidfile, strerror(errno));
497 			  }
498 			}
499 		}
500 	}
501 #else
502 	(void)daemon;
503 #endif
504 
505 	/* Set user context */
506 #ifdef HAVE_GETPWNAM
507 	if(cfg->username && cfg->username[0]) {
508 #ifdef HAVE_SETUSERCONTEXT
509 		/* setusercontext does initgroups, setuid, setgid, and
510 		 * also resource limits from login config, but we
511 		 * still call setresuid, setresgid to be sure to set all uid*/
512 		if(setusercontext(NULL, pwd, uid,
513 			LOGIN_SETALL & ~LOGIN_SETUSER & ~LOGIN_SETGROUP) != 0)
514 			log_warn("unable to setusercontext %s: %s",
515 				cfg->username, strerror(errno));
516 #endif /* HAVE_SETUSERCONTEXT */
517 	}
518 #endif /* HAVE_GETPWNAM */
519 
520 	/* box into the chroot */
521 #ifdef HAVE_CHROOT
522 	if(cfg->chrootdir && cfg->chrootdir[0]) {
523 		if(chdir(cfg->chrootdir)) {
524 			fatal_exit("unable to chdir to chroot %s: %s",
525 				cfg->chrootdir, strerror(errno));
526 		}
527 		verbose(VERB_QUERY, "chdir to %s", cfg->chrootdir);
528 		if(chroot(cfg->chrootdir))
529 			fatal_exit("unable to chroot to %s: %s",
530 				cfg->chrootdir, strerror(errno));
531 		verbose(VERB_QUERY, "chroot to %s", cfg->chrootdir);
532 		if(strncmp(*cfgfile, cfg->chrootdir,
533 			strlen(cfg->chrootdir)) == 0)
534 			(*cfgfile) += strlen(cfg->chrootdir);
535 
536 		/* adjust stored pidfile for chroot */
537 		if(daemon->pidfile && daemon->pidfile[0] &&
538 			strncmp(daemon->pidfile, cfg->chrootdir,
539 			strlen(cfg->chrootdir))==0) {
540 			char* old = daemon->pidfile;
541 			daemon->pidfile = strdup(old+strlen(cfg->chrootdir));
542 			free(old);
543 			if(!daemon->pidfile)
544 				log_err("out of memory in pidfile adjust");
545 		}
546 		daemon->chroot = strdup(cfg->chrootdir);
547 		if(!daemon->chroot)
548 			log_err("out of memory in daemon chroot dir storage");
549 	}
550 #else
551 	(void)cfgfile;
552 #endif
553 	/* change to working directory inside chroot */
554 	if(cfg->directory && cfg->directory[0]) {
555 		char* dir = cfg->directory;
556 		if(cfg->chrootdir && cfg->chrootdir[0] &&
557 			strncmp(dir, cfg->chrootdir,
558 			strlen(cfg->chrootdir)) == 0)
559 			dir += strlen(cfg->chrootdir);
560 		if(dir[0]) {
561 			if(chdir(dir)) {
562 				fatal_exit("Could not chdir to %s: %s",
563 					dir, strerror(errno));
564 			}
565 			verbose(VERB_QUERY, "chdir to %s", dir);
566 		}
567 	}
568 
569 	/* drop permissions after chroot, getpwnam, pidfile, syslog done*/
570 #ifdef HAVE_GETPWNAM
571 	if(cfg->username && cfg->username[0]) {
572 #  ifdef HAVE_INITGROUPS
573 		if(initgroups(cfg->username, gid) != 0)
574 			log_warn("unable to initgroups %s: %s",
575 				cfg->username, strerror(errno));
576 #  endif /* HAVE_INITGROUPS */
577 		endpwent();
578 
579 #ifdef HAVE_SETRESGID
580 		if(setresgid(gid,gid,gid) != 0)
581 #elif defined(HAVE_SETREGID) && !defined(DARWIN_BROKEN_SETREUID)
582 		if(setregid(gid,gid) != 0)
583 #else /* use setgid */
584 		if(setgid(gid) != 0)
585 #endif /* HAVE_SETRESGID */
586 			fatal_exit("unable to set group id of %s: %s",
587 				cfg->username, strerror(errno));
588 #ifdef HAVE_SETRESUID
589 		if(setresuid(uid,uid,uid) != 0)
590 #elif defined(HAVE_SETREUID) && !defined(DARWIN_BROKEN_SETREUID)
591 		if(setreuid(uid,uid) != 0)
592 #else /* use setuid */
593 		if(setuid(uid) != 0)
594 #endif /* HAVE_SETRESUID */
595 			fatal_exit("unable to set user id of %s: %s",
596 				cfg->username, strerror(errno));
597 		verbose(VERB_QUERY, "drop user privileges, run as %s",
598 			cfg->username);
599 	}
600 #endif /* HAVE_GETPWNAM */
601 	/* file logging inited after chroot,chdir,setuid is done so that
602 	 * it would succeed on SIGHUP as well */
603 	if(!cfg->use_syslog)
604 		log_init(cfg->logfile, cfg->use_syslog, cfg->chrootdir);
605 }
606 
607 /**
608  * Run the daemon.
609  * @param cfgfile: the config file name.
610  * @param cmdline_verbose: verbosity resulting from commandline -v.
611  *    These increase verbosity as specified in the config file.
612  * @param debug_mode: if set, do not daemonize.
613  */
614 static void
615 run_daemon(const char* cfgfile, int cmdline_verbose, int debug_mode)
616 {
617 	struct config_file* cfg = NULL;
618 	struct daemon* daemon = NULL;
619 	int done_setup = 0;
620 
621 	if(!(daemon = daemon_init()))
622 		fatal_exit("alloc failure");
623 	while(!daemon->need_to_exit) {
624 		if(done_setup)
625 			verbose(VERB_OPS, "Restart of %s.", PACKAGE_STRING);
626 		else	verbose(VERB_OPS, "Start of %s.", PACKAGE_STRING);
627 
628 		/* config stuff */
629 		if(!(cfg = config_create()))
630 			fatal_exit("Could not alloc config defaults");
631 		if(!config_read(cfg, cfgfile, daemon->chroot)) {
632 			if(errno != ENOENT)
633 				fatal_exit("Could not read config file: %s",
634 					cfgfile);
635 			log_warn("Continuing with default config settings");
636 		}
637 		apply_settings(daemon, cfg, cmdline_verbose);
638 
639 		/* prepare */
640 		if(!daemon_open_shared_ports(daemon))
641 			fatal_exit("could not open ports");
642 		if(!done_setup) {
643 			perform_setup(daemon, cfg, debug_mode, &cfgfile);
644 			done_setup = 1;
645 		} else {
646 			/* reopen log after HUP to facilitate log rotation */
647 			if(!cfg->use_syslog)
648 				log_init(cfg->logfile, 0, cfg->chrootdir);
649 		}
650 		/* work */
651 		daemon_fork(daemon);
652 
653 		/* clean up for restart */
654 		verbose(VERB_ALGO, "cleanup.");
655 		daemon_cleanup(daemon);
656 		config_delete(cfg);
657 	}
658 	verbose(VERB_ALGO, "Exit cleanup.");
659 	/* this unlink may not work if the pidfile is located outside
660 	 * of the chroot/workdir or we no longer have permissions */
661 	if(daemon->pidfile) {
662 		int fd;
663 		/* truncate pidfile */
664 		fd = open(daemon->pidfile, O_WRONLY | O_TRUNC, 0644);
665 		if(fd != -1)
666 			close(fd);
667 		/* delete pidfile */
668 		unlink(daemon->pidfile);
669 	}
670 	daemon_delete(daemon);
671 }
672 
673 /** getopt global, in case header files fail to declare it. */
674 extern int optind;
675 /** getopt global, in case header files fail to declare it. */
676 extern char* optarg;
677 
678 /**
679  * main program. Set options given commandline arguments.
680  * @param argc: number of commandline arguments.
681  * @param argv: array of commandline arguments.
682  * @return: exit status of the program.
683  */
684 int
685 main(int argc, char* argv[])
686 {
687 	int c;
688 	const char* cfgfile = CONFIGFILE;
689 	const char* winopt = NULL;
690 	int cmdline_verbose = 0;
691 	int debug_mode = 0;
692 #ifdef UB_ON_WINDOWS
693 	int cmdline_cfg = 0;
694 #endif
695 
696 #ifdef HAVE_SBRK
697 	/* take debug snapshot of heap */
698 	unbound_start_brk = sbrk(0);
699 #endif
700 
701 	log_init(NULL, 0, NULL);
702 	/* parse the options */
703 	while( (c=getopt(argc, argv, "c:dhvw:")) != -1) {
704 		switch(c) {
705 		case 'c':
706 			cfgfile = optarg;
707 #ifdef UB_ON_WINDOWS
708 			cmdline_cfg = 1;
709 #endif
710 			break;
711 		case 'v':
712 			cmdline_verbose ++;
713 			verbosity++;
714 			break;
715 		case 'd':
716 			debug_mode = 1;
717 			break;
718 		case 'w':
719 			winopt = optarg;
720 			break;
721 		case '?':
722 		case 'h':
723 		default:
724 			usage();
725 			return 1;
726 		}
727 	}
728 	argc -= optind;
729 	argv += optind;
730 
731 	if(winopt) {
732 #ifdef UB_ON_WINDOWS
733 		wsvc_command_option(winopt, cfgfile, cmdline_verbose,
734 			cmdline_cfg);
735 #else
736 		fatal_exit("option not supported");
737 #endif
738 	}
739 
740 	if(argc != 0) {
741 		usage();
742 		return 1;
743 	}
744 
745 	run_daemon(cfgfile, cmdline_verbose, debug_mode);
746 	log_init(NULL, 0, NULL); /* close logfile */
747 	return 0;
748 }
749