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