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