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