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