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