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