xref: /openbsd/usr.sbin/unbound/daemon/unbound.c (revision 91f110e0)
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/data/msgreply.h"
57 #include "util/module.h"
58 #include "util/net_help.h"
59 #include <signal.h>
60 #include <fcntl.h>
61 #include <openssl/crypto.h>
62 #ifdef HAVE_PWD_H
63 #include <pwd.h>
64 #endif
65 #ifdef HAVE_GRP_H
66 #include <grp.h>
67 #endif
68 
69 #ifndef S_SPLINT_S
70 /* splint chokes on this system header file */
71 #ifdef HAVE_SYS_RESOURCE_H
72 #include <sys/resource.h>
73 #endif
74 #endif /* S_SPLINT_S */
75 #ifdef HAVE_LOGIN_CAP_H
76 #include <login_cap.h>
77 #endif
78 
79 #ifdef USE_MINI_EVENT
80 #  ifdef USE_WINSOCK
81 #    include "util/winsock_event.h"
82 #  else
83 #    include "util/mini_event.h"
84 #  endif
85 #else
86 #  include <event.h>
87 #endif
88 
89 #ifdef UB_ON_WINDOWS
90 #  include "winrc/win_svc.h"
91 #endif
92 
93 #ifdef HAVE_NSS
94 /* nss3 */
95 #  include "nss.h"
96 #endif
97 
98 /** global debug value to keep track of heap memory allocation */
99 void* unbound_start_brk = 0;
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), %s\n",
169 		evnm, evsys, evmethod,
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 #ifndef S_SPLINT_S
199 #ifdef HAVE_GETRLIMIT
200 	/* list has number of ports to listen to, ifs number addresses */
201 	int list = ((cfg->do_udp?1:0) + (cfg->do_tcp?1 +
202 			(int)cfg->incoming_num_tcp:0));
203 	size_t listen_ifs = (size_t)(cfg->num_ifs==0?
204 		((cfg->do_ip4 && !cfg->if_automatic?1:0) +
205 		 (cfg->do_ip6?1:0)):cfg->num_ifs);
206 	size_t listen_num = list*listen_ifs;
207 	size_t outudpnum = (size_t)cfg->outgoing_num_ports;
208 	size_t outtcpnum = cfg->outgoing_num_tcp;
209 	size_t misc = 4; /* logfile, pidfile, stdout... */
210 	size_t perthread_noudp = listen_num + outtcpnum +
211 		2/*cmdpipe*/ + 2/*libevent*/ + misc;
212 	size_t perthread = perthread_noudp + outudpnum;
213 
214 #if !defined(HAVE_PTHREAD) && !defined(HAVE_SOLARIS_THREADS)
215 	int numthread = 1; /* it forks */
216 #else
217 	int numthread = (cfg->num_threads?cfg->num_threads:1);
218 #endif
219 	size_t total = numthread * perthread + misc;
220 	size_t avail;
221 	struct rlimit rlim;
222 
223 	if(total > 1024 &&
224 		strncmp(event_get_version(), "mini-event", 10) == 0) {
225 		log_warn("too many file descriptors requested. The builtin"
226 			"mini-event cannot handle more than 1024. Config "
227 			"for less fds or compile with libevent");
228 		if(numthread*perthread_noudp+15 > 1024)
229 			fatal_exit("too much tcp. not enough fds.");
230 		cfg->outgoing_num_ports = (int)((1024
231 			- numthread*perthread_noudp
232 			- 10 /* safety margin */) /numthread);
233 		log_warn("continuing with less udp ports: %u",
234 			cfg->outgoing_num_ports);
235 		total = 1024;
236 	}
237 	if(perthread > 64 &&
238 		strncmp(event_get_version(), "winsock-event", 13) == 0) {
239 		log_err("too many file descriptors requested. The winsock"
240 			" event handler cannot handle more than 64 per "
241 			" thread. Config for less fds");
242 		if(perthread_noudp+2 > 64)
243 			fatal_exit("too much tcp. not enough fds.");
244 		cfg->outgoing_num_ports = (int)((64
245 			- perthread_noudp
246 			- 2/* safety margin */));
247 		log_warn("continuing with less udp ports: %u",
248 			cfg->outgoing_num_ports);
249 		total = numthread*(perthread_noudp+
250 			(size_t)cfg->outgoing_num_ports)+misc;
251 	}
252 	if(getrlimit(RLIMIT_NOFILE, &rlim) < 0) {
253 		log_warn("getrlimit: %s", strerror(errno));
254 		return;
255 	}
256 	if(rlim.rlim_cur == (rlim_t)RLIM_INFINITY)
257 		return;
258 	if((size_t)rlim.rlim_cur < total) {
259 		avail = (size_t)rlim.rlim_cur;
260 		rlim.rlim_cur = (rlim_t)(total + 10);
261 		rlim.rlim_max = (rlim_t)(total + 10);
262 #ifdef HAVE_SETRLIMIT
263 		if(setrlimit(RLIMIT_NOFILE, &rlim) < 0) {
264 			log_warn("setrlimit: %s", strerror(errno));
265 #else
266 		if(1) {
267 #endif
268 			log_warn("cannot increase max open fds from %u to %u",
269 				(unsigned)avail, (unsigned)total+10);
270 			/* check that calculation below does not underflow,
271 			 * with 15 as margin */
272 			if(numthread*perthread_noudp+15 > avail)
273 				fatal_exit("too much tcp. not enough fds.");
274 			cfg->outgoing_num_ports = (int)((avail
275 				- numthread*perthread_noudp
276 				- 10 /* safety margin */) /numthread);
277 			log_warn("continuing with less udp ports: %u",
278 				cfg->outgoing_num_ports);
279 			log_warn("increase ulimit or decrease threads, "
280 				"ports in config to remove this warning");
281 			return;
282 		}
283 		log_warn("increased limit(open files) from %u to %u",
284 			(unsigned)avail, (unsigned)total+10);
285 	}
286 #else
287 	(void)cfg;
288 #endif /* HAVE_GETRLIMIT */
289 #endif /* S_SPLINT_S */
290 }
291 
292 /** set verbosity, check rlimits, cache settings */
293 static void
294 apply_settings(struct daemon* daemon, struct config_file* cfg,
295 	int cmdline_verbose)
296 {
297 	/* apply if they have changed */
298 	verbosity = cmdline_verbose + cfg->verbosity;
299 	daemon_apply_cfg(daemon, cfg);
300 	checkrlimits(cfg);
301 }
302 
303 #ifdef HAVE_KILL
304 /** Read existing pid from pidfile.
305  * @param file: file name of pid file.
306  * @return: the pid from the file or -1 if none.
307  */
308 static pid_t
309 readpid (const char* file)
310 {
311 	int fd;
312 	pid_t pid;
313 	char pidbuf[32];
314 	char* t;
315 	ssize_t l;
316 
317 	if ((fd = open(file, O_RDONLY)) == -1) {
318 		if(errno != ENOENT)
319 			log_err("Could not read pidfile %s: %s",
320 				file, strerror(errno));
321 		return -1;
322 	}
323 
324 	if (((l = read(fd, pidbuf, sizeof(pidbuf)))) == -1) {
325 		if(errno != ENOENT)
326 			log_err("Could not read pidfile %s: %s",
327 				file, strerror(errno));
328 		close(fd);
329 		return -1;
330 	}
331 
332 	close(fd);
333 
334 	/* Empty pidfile means no pidfile... */
335 	if (l == 0) {
336 		return -1;
337 	}
338 
339 	pidbuf[sizeof(pidbuf)-1] = 0;
340 	pid = (pid_t)strtol(pidbuf, &t, 10);
341 
342 	if (*t && *t != '\n') {
343 		return -1;
344 	}
345 	return pid;
346 }
347 
348 /** write pid to file.
349  * @param pidfile: file name of pid file.
350  * @param pid: pid to write to file.
351  */
352 static void
353 writepid (const char* pidfile, pid_t pid)
354 {
355 	FILE* f;
356 
357 	if ((f = fopen(pidfile, "w")) ==  NULL ) {
358 		log_err("cannot open pidfile %s: %s",
359 			pidfile, strerror(errno));
360 		return;
361 	}
362 	if(fprintf(f, "%lu\n", (unsigned long)pid) < 0) {
363 		log_err("cannot write to pidfile %s: %s",
364 			pidfile, strerror(errno));
365 	}
366 	fclose(f);
367 }
368 
369 /**
370  * check old pid file.
371  * @param pidfile: the file name of the pid file.
372  * @param inchroot: if pidfile is inchroot and we can thus expect to
373  *	be able to delete it.
374  */
375 static void
376 checkoldpid(char* pidfile, int inchroot)
377 {
378 	pid_t old;
379 	if((old = readpid(pidfile)) != -1) {
380 		/* see if it is still alive */
381 		if(kill(old, 0) == 0 || errno == EPERM)
382 			log_warn("unbound is already running as pid %u.",
383 				(unsigned)old);
384 		else	if(inchroot)
385 			log_warn("did not exit gracefully last time (%u)",
386 				(unsigned)old);
387 	}
388 }
389 #endif /* HAVE_KILL */
390 
391 /** detach from command line */
392 static void
393 detach(void)
394 {
395 #if defined(HAVE_DAEMON) && !defined(DEPRECATED_DAEMON)
396 	/* use POSIX daemon(3) function */
397 	if(daemon(1, 0) != 0)
398 		fatal_exit("daemon failed: %s", strerror(errno));
399 #else /* no HAVE_DAEMON */
400 #ifdef HAVE_FORK
401 	int fd;
402 	/* Take off... */
403 	switch (fork()) {
404 		case 0:
405 			break;
406 		case -1:
407 			fatal_exit("fork failed: %s", strerror(errno));
408 		default:
409 			/* exit interactive session */
410 			exit(0);
411 	}
412 	/* detach */
413 #ifdef HAVE_SETSID
414 	if(setsid() == -1)
415 		fatal_exit("setsid() failed: %s", strerror(errno));
416 #endif
417 	if ((fd = open("/dev/null", O_RDWR, 0)) != -1) {
418 		(void)dup2(fd, STDIN_FILENO);
419 		(void)dup2(fd, STDOUT_FILENO);
420 		(void)dup2(fd, STDERR_FILENO);
421 		if (fd > 2)
422 			(void)close(fd);
423 	}
424 #endif /* HAVE_FORK */
425 #endif /* HAVE_DAEMON */
426 }
427 
428 /** daemonize, drop user priviliges and chroot if needed */
429 static void
430 perform_setup(struct daemon* daemon, struct config_file* cfg, int debug_mode,
431 	const char** cfgfile)
432 {
433 #ifdef HAVE_GETPWNAM
434 	struct passwd *pwd = NULL;
435 	uid_t uid;
436 	gid_t gid;
437 	/* initialize, but not to 0 (root) */
438 	memset(&uid, 112, sizeof(uid));
439 	memset(&gid, 112, sizeof(gid));
440 	log_assert(cfg);
441 
442 	if(cfg->username && cfg->username[0]) {
443 		if((pwd = getpwnam(cfg->username)) == NULL)
444 			fatal_exit("user '%s' does not exist.", cfg->username);
445 		uid = pwd->pw_uid;
446 		gid = pwd->pw_gid;
447 		/* endpwent below, in case we need pwd for setusercontext */
448 	}
449 #endif
450 
451 	/* init syslog (as root) if needed, before daemonize, otherwise
452 	 * a fork error could not be printed since daemonize closed stderr.*/
453 	if(cfg->use_syslog) {
454 		log_init(cfg->logfile, cfg->use_syslog, cfg->chrootdir);
455 	}
456 	/* if using a logfile, we cannot open it because the logfile would
457 	 * be created with the wrong permissions, we cannot chown it because
458 	 * we cannot chown system logfiles, so we do not open at all.
459 	 * So, using a logfile, the user does not see errors unless -d is
460 	 * given to unbound on the commandline. */
461 
462 	/* read ssl keys while superuser and outside chroot */
463 #ifdef HAVE_SSL
464 	if(!(daemon->rc = daemon_remote_create(cfg)))
465 		fatal_exit("could not set up remote-control");
466 	if(cfg->ssl_service_key && cfg->ssl_service_key[0]) {
467 		if(!(daemon->listen_sslctx = listen_sslctx_create(
468 			cfg->ssl_service_key, cfg->ssl_service_pem, NULL)))
469 			fatal_exit("could not set up listen SSL_CTX");
470 	}
471 	if(!(daemon->connect_sslctx = connect_sslctx_create(NULL, NULL, NULL)))
472 		fatal_exit("could not set up connect SSL_CTX");
473 #endif
474 
475 #ifdef HAVE_KILL
476 	/* check old pid file before forking */
477 	if(cfg->pidfile && cfg->pidfile[0]) {
478 		/* calculate position of pidfile */
479 		if(cfg->pidfile[0] == '/')
480 			daemon->pidfile = strdup(cfg->pidfile);
481 		else	daemon->pidfile = fname_after_chroot(cfg->pidfile,
482 				cfg, 1);
483 		if(!daemon->pidfile)
484 			fatal_exit("pidfile alloc: out of memory");
485 		checkoldpid(daemon->pidfile,
486 			/* true if pidfile is inside chrootdir, or nochroot */
487 			!(cfg->chrootdir && cfg->chrootdir[0]) ||
488 			(cfg->chrootdir && cfg->chrootdir[0] &&
489 			strncmp(daemon->pidfile, cfg->chrootdir,
490 				strlen(cfg->chrootdir))==0));
491 	}
492 #endif
493 
494 	/* daemonize because pid is needed by the writepid func */
495 	if(!debug_mode && cfg->do_daemonize) {
496 		detach();
497 	}
498 
499 	/* write new pidfile (while still root, so can be outside chroot) */
500 #ifdef HAVE_KILL
501 	if(cfg->pidfile && cfg->pidfile[0]) {
502 		writepid(daemon->pidfile, getpid());
503 		if(!(cfg->chrootdir && cfg->chrootdir[0]) ||
504 			(cfg->chrootdir && cfg->chrootdir[0] &&
505 			strncmp(daemon->pidfile, cfg->chrootdir,
506 			strlen(cfg->chrootdir))==0)) {
507 			/* delete of pidfile could potentially work,
508 			 * chown to get permissions */
509 			if(cfg->username && cfg->username[0]) {
510 			  if(chown(daemon->pidfile, uid, gid) == -1) {
511 				log_err("cannot chown %u.%u %s: %s",
512 					(unsigned)uid, (unsigned)gid,
513 					daemon->pidfile, strerror(errno));
514 			  }
515 			}
516 		}
517 	}
518 #else
519 	(void)daemon;
520 #endif
521 
522 	/* Set user context */
523 #ifdef HAVE_GETPWNAM
524 	if(cfg->username && cfg->username[0]) {
525 #ifdef HAVE_SETUSERCONTEXT
526 		/* setusercontext does initgroups, setuid, setgid, and
527 		 * also resource limits from login config, but we
528 		 * still call setresuid, setresgid to be sure to set all uid*/
529 		if(setusercontext(NULL, pwd, uid, (unsigned)
530 			LOGIN_SETALL & ~LOGIN_SETUSER & ~LOGIN_SETGROUP) != 0)
531 			log_warn("unable to setusercontext %s: %s",
532 				cfg->username, strerror(errno));
533 #endif /* HAVE_SETUSERCONTEXT */
534 	}
535 #endif /* HAVE_GETPWNAM */
536 
537 	/* box into the chroot */
538 #ifdef HAVE_CHROOT
539 	if(cfg->chrootdir && cfg->chrootdir[0]) {
540 		if(chdir(cfg->chrootdir)) {
541 			fatal_exit("unable to chdir to chroot %s: %s",
542 				cfg->chrootdir, strerror(errno));
543 		}
544 		verbose(VERB_QUERY, "chdir to %s", cfg->chrootdir);
545 		if(chroot(cfg->chrootdir))
546 			fatal_exit("unable to chroot to %s: %s",
547 				cfg->chrootdir, strerror(errno));
548 		if(chdir("/"))
549 			fatal_exit("unable to chdir to / in chroot %s: %s",
550 				cfg->chrootdir, strerror(errno));
551 		verbose(VERB_QUERY, "chroot to %s", cfg->chrootdir);
552 		if(strncmp(*cfgfile, cfg->chrootdir,
553 			strlen(cfg->chrootdir)) == 0)
554 			(*cfgfile) += strlen(cfg->chrootdir);
555 
556 		/* adjust stored pidfile for chroot */
557 		if(daemon->pidfile && daemon->pidfile[0] &&
558 			strncmp(daemon->pidfile, cfg->chrootdir,
559 			strlen(cfg->chrootdir))==0) {
560 			char* old = daemon->pidfile;
561 			daemon->pidfile = strdup(old+strlen(cfg->chrootdir));
562 			free(old);
563 			if(!daemon->pidfile)
564 				log_err("out of memory in pidfile adjust");
565 		}
566 		daemon->chroot = strdup(cfg->chrootdir);
567 		if(!daemon->chroot)
568 			log_err("out of memory in daemon chroot dir storage");
569 	}
570 #else
571 	(void)cfgfile;
572 #endif
573 	/* change to working directory inside chroot */
574 	if(cfg->directory && cfg->directory[0]) {
575 		char* dir = cfg->directory;
576 		if(cfg->chrootdir && cfg->chrootdir[0] &&
577 			strncmp(dir, cfg->chrootdir,
578 			strlen(cfg->chrootdir)) == 0)
579 			dir += strlen(cfg->chrootdir);
580 		if(dir[0]) {
581 			if(chdir(dir)) {
582 				fatal_exit("Could not chdir to %s: %s",
583 					dir, strerror(errno));
584 			}
585 			verbose(VERB_QUERY, "chdir to %s", dir);
586 		}
587 	}
588 
589 	/* drop permissions after chroot, getpwnam, pidfile, syslog done*/
590 #ifdef HAVE_GETPWNAM
591 	if(cfg->username && cfg->username[0]) {
592 #  ifdef HAVE_INITGROUPS
593 		if(initgroups(cfg->username, gid) != 0)
594 			log_warn("unable to initgroups %s: %s",
595 				cfg->username, strerror(errno));
596 #  endif /* HAVE_INITGROUPS */
597 		endpwent();
598 
599 #ifdef HAVE_SETRESGID
600 		if(setresgid(gid,gid,gid) != 0)
601 #elif defined(HAVE_SETREGID) && !defined(DARWIN_BROKEN_SETREUID)
602 		if(setregid(gid,gid) != 0)
603 #else /* use setgid */
604 		if(setgid(gid) != 0)
605 #endif /* HAVE_SETRESGID */
606 			fatal_exit("unable to set group id of %s: %s",
607 				cfg->username, strerror(errno));
608 #ifdef HAVE_SETRESUID
609 		if(setresuid(uid,uid,uid) != 0)
610 #elif defined(HAVE_SETREUID) && !defined(DARWIN_BROKEN_SETREUID)
611 		if(setreuid(uid,uid) != 0)
612 #else /* use setuid */
613 		if(setuid(uid) != 0)
614 #endif /* HAVE_SETRESUID */
615 			fatal_exit("unable to set user id of %s: %s",
616 				cfg->username, strerror(errno));
617 		verbose(VERB_QUERY, "drop user privileges, run as %s",
618 			cfg->username);
619 	}
620 #endif /* HAVE_GETPWNAM */
621 	/* file logging inited after chroot,chdir,setuid is done so that
622 	 * it would succeed on SIGHUP as well */
623 	if(!cfg->use_syslog)
624 		log_init(cfg->logfile, cfg->use_syslog, cfg->chrootdir);
625 }
626 
627 /**
628  * Run the daemon.
629  * @param cfgfile: the config file name.
630  * @param cmdline_verbose: verbosity resulting from commandline -v.
631  *    These increase verbosity as specified in the config file.
632  * @param debug_mode: if set, do not daemonize.
633  */
634 static void
635 run_daemon(const char* cfgfile, int cmdline_verbose, int debug_mode)
636 {
637 	struct config_file* cfg = NULL;
638 	struct daemon* daemon = NULL;
639 	int done_setup = 0;
640 
641 	if(!(daemon = daemon_init()))
642 		fatal_exit("alloc failure");
643 	while(!daemon->need_to_exit) {
644 		if(done_setup)
645 			verbose(VERB_OPS, "Restart of %s.", PACKAGE_STRING);
646 		else	verbose(VERB_OPS, "Start of %s.", PACKAGE_STRING);
647 
648 		/* config stuff */
649 		if(!(cfg = config_create()))
650 			fatal_exit("Could not alloc config defaults");
651 		if(!config_read(cfg, cfgfile, daemon->chroot)) {
652 			if(errno != ENOENT)
653 				fatal_exit("Could not read config file: %s",
654 					cfgfile);
655 			log_warn("Continuing with default config settings");
656 		}
657 		apply_settings(daemon, cfg, cmdline_verbose);
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 = 1;
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