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