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