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