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