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