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