xref: /freebsd/contrib/unbound/daemon/unbound.c (revision a812392203d7c4c3f0db9d8a0f3391374c49c71f)
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 <signal.h>
61 #include <fcntl.h>
62 #include <openssl/crypto.h>
63 #ifdef HAVE_PWD_H
64 #include <pwd.h>
65 #endif
66 #ifdef HAVE_GRP_H
67 #include <grp.h>
68 #endif
69 
70 #ifndef S_SPLINT_S
71 /* splint chokes on this system header file */
72 #ifdef HAVE_SYS_RESOURCE_H
73 #include <sys/resource.h>
74 #endif
75 #endif /* S_SPLINT_S */
76 #ifdef HAVE_LOGIN_CAP_H
77 #include <login_cap.h>
78 #endif
79 
80 #ifdef USE_MINI_EVENT
81 #  ifdef USE_WINSOCK
82 #    include "util/winsock_event.h"
83 #  else
84 #    include "util/mini_event.h"
85 #  endif
86 #else
87 #  ifdef HAVE_EVENT_H
88 #    include <event.h>
89 #  else
90 #    include "event2/event.h"
91 #    include "event2/event_struct.h"
92 #    include "event2/event_compat.h"
93 #  endif
94 #endif
95 
96 #ifdef UB_ON_WINDOWS
97 #  include "winrc/win_svc.h"
98 #endif
99 
100 #ifdef HAVE_NSS
101 /* nss3 */
102 #  include "nss.h"
103 #endif
104 
105 #ifdef HAVE_SBRK
106 /** global debug value to keep track of heap memory allocation */
107 void* unbound_start_brk = 0;
108 #endif
109 
110 #if !defined(HAVE_EVENT_BASE_GET_METHOD) && (defined(HAVE_EV_LOOP) || defined(HAVE_EV_DEFAULT_LOOP))
111 static const char* ev_backend2str(int b)
112 {
113 	switch(b) {
114 	case EVBACKEND_SELECT:	return "select";
115 	case EVBACKEND_POLL:	return "poll";
116 	case EVBACKEND_EPOLL:	return "epoll";
117 	case EVBACKEND_KQUEUE:	return "kqueue";
118 	case EVBACKEND_DEVPOLL: return "devpoll";
119 	case EVBACKEND_PORT:	return "evport";
120 	}
121 	return "unknown";
122 }
123 #endif
124 
125 /** get the event system in use */
126 static void get_event_sys(const char** n, const char** s, const char** m)
127 {
128 #ifdef USE_WINSOCK
129 	*n = "event";
130 	*s = "winsock";
131 	*m = "WSAWaitForMultipleEvents";
132 #elif defined(USE_MINI_EVENT)
133 	*n = "mini-event";
134 	*s = "internal";
135 	*m = "select";
136 #else
137 	struct event_base* b;
138 	*s = event_get_version();
139 #  ifdef HAVE_EVENT_BASE_GET_METHOD
140 	*n = "libevent";
141 	b = event_base_new();
142 	*m = event_base_get_method(b);
143 #  elif defined(HAVE_EV_LOOP) || defined(HAVE_EV_DEFAULT_LOOP)
144 	*n = "libev";
145 	b = (struct event_base*)ev_default_loop(EVFLAG_AUTO);
146 	*m = ev_backend2str(ev_backend((struct ev_loop*)b));
147 #  else
148 	*n = "unknown";
149 	*m = "not obtainable";
150 	b = NULL;
151 #  endif
152 #  ifdef HAVE_EVENT_BASE_FREE
153 	event_base_free(b);
154 #  endif
155 #endif
156 }
157 
158 /** print usage. */
159 static void usage()
160 {
161 	const char** m;
162 	const char *evnm="event", *evsys="", *evmethod="";
163 	printf("usage:  unbound [options]\n");
164 	printf("	start unbound daemon DNS resolver.\n");
165 	printf("-h	this help\n");
166 	printf("-c file	config file to read instead of %s\n", CONFIGFILE);
167 	printf("	file format is described in unbound.conf(5).\n");
168 	printf("-d	do not fork into the background.\n");
169 	printf("-v	verbose (more times to increase verbosity)\n");
170 #ifdef UB_ON_WINDOWS
171 	printf("-w opt	windows option: \n");
172 	printf("   	install, remove - manage the services entry\n");
173 	printf("   	service - used to start from services control panel\n");
174 #endif
175 	printf("Version %s\n", PACKAGE_VERSION);
176 	get_event_sys(&evnm, &evsys, &evmethod);
177 	printf("linked libs: %s %s (it uses %s), %s\n",
178 		evnm, evsys, evmethod,
179 #ifdef HAVE_SSL
180 		SSLeay_version(SSLEAY_VERSION)
181 #elif defined(HAVE_NSS)
182 		NSS_GetVersion()
183 #endif
184 		);
185 	printf("linked modules:");
186 	for(m = module_list_avail(); *m; m++)
187 		printf(" %s", *m);
188 	printf("\n");
189 	printf("BSD licensed, see LICENSE in source package for details.\n");
190 	printf("Report bugs to %s\n", PACKAGE_BUGREPORT);
191 }
192 
193 #ifndef unbound_testbound
194 int replay_var_compare(const void* ATTR_UNUSED(a), const void* ATTR_UNUSED(b))
195 {
196         log_assert(0);
197         return 0;
198 }
199 #endif
200 
201 /** check file descriptor count */
202 static void
203 checkrlimits(struct config_file* cfg)
204 {
205 #ifndef S_SPLINT_S
206 #ifdef HAVE_GETRLIMIT
207 	/* list has number of ports to listen to, ifs number addresses */
208 	int list = ((cfg->do_udp?1:0) + (cfg->do_tcp?1 +
209 			(int)cfg->incoming_num_tcp:0));
210 	size_t listen_ifs = (size_t)(cfg->num_ifs==0?
211 		((cfg->do_ip4 && !cfg->if_automatic?1:0) +
212 		 (cfg->do_ip6?1:0)):cfg->num_ifs);
213 	size_t listen_num = list*listen_ifs;
214 	size_t outudpnum = (size_t)cfg->outgoing_num_ports;
215 	size_t outtcpnum = cfg->outgoing_num_tcp;
216 	size_t misc = 4; /* logfile, pidfile, stdout... */
217 	size_t perthread_noudp = listen_num + outtcpnum +
218 		2/*cmdpipe*/ + 2/*libevent*/ + misc;
219 	size_t perthread = perthread_noudp + outudpnum;
220 
221 #if !defined(HAVE_PTHREAD) && !defined(HAVE_SOLARIS_THREADS)
222 	int numthread = 1; /* it forks */
223 #else
224 	int numthread = (cfg->num_threads?cfg->num_threads:1);
225 #endif
226 	size_t total = numthread * perthread + misc;
227 	size_t avail;
228 	struct rlimit rlim;
229 
230 	if(total > 1024 &&
231 		strncmp(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(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 		cfg->logfile = NULL;
309 	}
310 	daemon_apply_cfg(daemon, cfg);
311 	checkrlimits(cfg);
312 }
313 
314 #ifdef HAVE_KILL
315 /** Read existing pid from pidfile.
316  * @param file: file name of pid file.
317  * @return: the pid from the file or -1 if none.
318  */
319 static pid_t
320 readpid (const char* file)
321 {
322 	int fd;
323 	pid_t pid;
324 	char pidbuf[32];
325 	char* t;
326 	ssize_t l;
327 
328 	if ((fd = open(file, O_RDONLY)) == -1) {
329 		if(errno != ENOENT)
330 			log_err("Could not read pidfile %s: %s",
331 				file, strerror(errno));
332 		return -1;
333 	}
334 
335 	if (((l = read(fd, pidbuf, sizeof(pidbuf)))) == -1) {
336 		if(errno != ENOENT)
337 			log_err("Could not read pidfile %s: %s",
338 				file, strerror(errno));
339 		close(fd);
340 		return -1;
341 	}
342 
343 	close(fd);
344 
345 	/* Empty pidfile means no pidfile... */
346 	if (l == 0) {
347 		return -1;
348 	}
349 
350 	pidbuf[sizeof(pidbuf)-1] = 0;
351 	pid = (pid_t)strtol(pidbuf, &t, 10);
352 
353 	if (*t && *t != '\n') {
354 		return -1;
355 	}
356 	return pid;
357 }
358 
359 /** write pid to file.
360  * @param pidfile: file name of pid file.
361  * @param pid: pid to write to file.
362  */
363 static void
364 writepid (const char* pidfile, pid_t pid)
365 {
366 	FILE* f;
367 
368 	if ((f = fopen(pidfile, "w")) ==  NULL ) {
369 		log_err("cannot open pidfile %s: %s",
370 			pidfile, strerror(errno));
371 		return;
372 	}
373 	if(fprintf(f, "%lu\n", (unsigned long)pid) < 0) {
374 		log_err("cannot write to pidfile %s: %s",
375 			pidfile, strerror(errno));
376 	}
377 	fclose(f);
378 }
379 
380 /**
381  * check old pid file.
382  * @param pidfile: the file name of the pid file.
383  * @param inchroot: if pidfile is inchroot and we can thus expect to
384  *	be able to delete it.
385  */
386 static void
387 checkoldpid(char* pidfile, int inchroot)
388 {
389 	pid_t old;
390 	if((old = readpid(pidfile)) != -1) {
391 		/* see if it is still alive */
392 		if(kill(old, 0) == 0 || errno == EPERM)
393 			log_warn("unbound is already running as pid %u.",
394 				(unsigned)old);
395 		else	if(inchroot)
396 			log_warn("did not exit gracefully last time (%u)",
397 				(unsigned)old);
398 	}
399 }
400 #endif /* HAVE_KILL */
401 
402 /** detach from command line */
403 static void
404 detach(void)
405 {
406 #if defined(HAVE_DAEMON) && !defined(DEPRECATED_DAEMON)
407 	/* use POSIX daemon(3) function */
408 	if(daemon(1, 0) != 0)
409 		fatal_exit("daemon failed: %s", strerror(errno));
410 #else /* no HAVE_DAEMON */
411 #ifdef HAVE_FORK
412 	int fd;
413 	/* Take off... */
414 	switch (fork()) {
415 		case 0:
416 			break;
417 		case -1:
418 			fatal_exit("fork failed: %s", strerror(errno));
419 		default:
420 			/* exit interactive session */
421 			exit(0);
422 	}
423 	/* detach */
424 #ifdef HAVE_SETSID
425 	if(setsid() == -1)
426 		fatal_exit("setsid() failed: %s", strerror(errno));
427 #endif
428 	if ((fd = open("/dev/null", O_RDWR, 0)) != -1) {
429 		(void)dup2(fd, STDIN_FILENO);
430 		(void)dup2(fd, STDOUT_FILENO);
431 		(void)dup2(fd, STDERR_FILENO);
432 		if (fd > 2)
433 			(void)close(fd);
434 	}
435 #endif /* HAVE_FORK */
436 #endif /* HAVE_DAEMON */
437 }
438 
439 /** daemonize, drop user priviliges and chroot if needed */
440 static void
441 perform_setup(struct daemon* daemon, struct config_file* cfg, int debug_mode,
442 	const char** cfgfile)
443 {
444 #ifdef HAVE_GETPWNAM
445 	struct passwd *pwd = NULL;
446 	uid_t uid;
447 	gid_t gid;
448 	/* initialize, but not to 0 (root) */
449 	memset(&uid, 112, sizeof(uid));
450 	memset(&gid, 112, sizeof(gid));
451 	log_assert(cfg);
452 
453 	if(cfg->username && cfg->username[0]) {
454 		if((pwd = getpwnam(cfg->username)) == NULL)
455 			fatal_exit("user '%s' does not exist.", cfg->username);
456 		uid = pwd->pw_uid;
457 		gid = pwd->pw_gid;
458 		/* endpwent below, in case we need pwd for setusercontext */
459 	}
460 #endif
461 
462 	/* init syslog (as root) if needed, before daemonize, otherwise
463 	 * a fork error could not be printed since daemonize closed stderr.*/
464 	if(cfg->use_syslog) {
465 		log_init(cfg->logfile, cfg->use_syslog, cfg->chrootdir);
466 	}
467 	/* if using a logfile, we cannot open it because the logfile would
468 	 * be created with the wrong permissions, we cannot chown it because
469 	 * we cannot chown system logfiles, so we do not open at all.
470 	 * So, using a logfile, the user does not see errors unless -d is
471 	 * given to unbound on the commandline. */
472 
473 	/* read ssl keys while superuser and outside chroot */
474 #ifdef HAVE_SSL
475 	if(!(daemon->rc = daemon_remote_create(cfg)))
476 		fatal_exit("could not set up remote-control");
477 	if(cfg->ssl_service_key && cfg->ssl_service_key[0]) {
478 		if(!(daemon->listen_sslctx = listen_sslctx_create(
479 			cfg->ssl_service_key, cfg->ssl_service_pem, NULL)))
480 			fatal_exit("could not set up listen SSL_CTX");
481 	}
482 	if(!(daemon->connect_sslctx = connect_sslctx_create(NULL, NULL, NULL)))
483 		fatal_exit("could not set up connect SSL_CTX");
484 #endif
485 
486 #ifdef HAVE_KILL
487 	/* check old pid file before forking */
488 	if(cfg->pidfile && cfg->pidfile[0]) {
489 		/* calculate position of pidfile */
490 		if(cfg->pidfile[0] == '/')
491 			daemon->pidfile = strdup(cfg->pidfile);
492 		else	daemon->pidfile = fname_after_chroot(cfg->pidfile,
493 				cfg, 1);
494 		if(!daemon->pidfile)
495 			fatal_exit("pidfile alloc: out of memory");
496 		checkoldpid(daemon->pidfile,
497 			/* true if pidfile is inside chrootdir, or nochroot */
498 			!(cfg->chrootdir && cfg->chrootdir[0]) ||
499 			(cfg->chrootdir && cfg->chrootdir[0] &&
500 			strncmp(daemon->pidfile, cfg->chrootdir,
501 				strlen(cfg->chrootdir))==0));
502 	}
503 #endif
504 
505 	/* daemonize because pid is needed by the writepid func */
506 	if(!debug_mode && cfg->do_daemonize) {
507 		detach();
508 	}
509 
510 	/* write new pidfile (while still root, so can be outside chroot) */
511 #ifdef HAVE_KILL
512 	if(cfg->pidfile && cfg->pidfile[0]) {
513 		writepid(daemon->pidfile, getpid());
514 		if(!(cfg->chrootdir && cfg->chrootdir[0]) ||
515 			(cfg->chrootdir && cfg->chrootdir[0] &&
516 			strncmp(daemon->pidfile, cfg->chrootdir,
517 			strlen(cfg->chrootdir))==0)) {
518 			/* delete of pidfile could potentially work,
519 			 * chown to get permissions */
520 			if(cfg->username && cfg->username[0]) {
521 			  if(chown(daemon->pidfile, uid, gid) == -1) {
522 				log_err("cannot chown %u.%u %s: %s",
523 					(unsigned)uid, (unsigned)gid,
524 					daemon->pidfile, strerror(errno));
525 			  }
526 			}
527 		}
528 	}
529 #else
530 	(void)daemon;
531 #endif
532 
533 	/* Set user context */
534 #ifdef HAVE_GETPWNAM
535 	if(cfg->username && cfg->username[0]) {
536 #ifdef HAVE_SETUSERCONTEXT
537 		/* setusercontext does initgroups, setuid, setgid, and
538 		 * also resource limits from login config, but we
539 		 * still call setresuid, setresgid to be sure to set all uid*/
540 		if(setusercontext(NULL, pwd, uid, (unsigned)
541 			LOGIN_SETALL & ~LOGIN_SETUSER & ~LOGIN_SETGROUP) != 0)
542 			log_warn("unable to setusercontext %s: %s",
543 				cfg->username, strerror(errno));
544 #endif /* HAVE_SETUSERCONTEXT */
545 	}
546 #endif /* HAVE_GETPWNAM */
547 
548 	/* box into the chroot */
549 #ifdef HAVE_CHROOT
550 	if(cfg->chrootdir && cfg->chrootdir[0]) {
551 		if(chdir(cfg->chrootdir)) {
552 			fatal_exit("unable to chdir to chroot %s: %s",
553 				cfg->chrootdir, strerror(errno));
554 		}
555 		verbose(VERB_QUERY, "chdir to %s", cfg->chrootdir);
556 		if(chroot(cfg->chrootdir))
557 			fatal_exit("unable to chroot to %s: %s",
558 				cfg->chrootdir, strerror(errno));
559 		if(chdir("/"))
560 			fatal_exit("unable to chdir to / in chroot %s: %s",
561 				cfg->chrootdir, strerror(errno));
562 		verbose(VERB_QUERY, "chroot to %s", cfg->chrootdir);
563 		if(strncmp(*cfgfile, cfg->chrootdir,
564 			strlen(cfg->chrootdir)) == 0)
565 			(*cfgfile) += strlen(cfg->chrootdir);
566 
567 		/* adjust stored pidfile for chroot */
568 		if(daemon->pidfile && daemon->pidfile[0] &&
569 			strncmp(daemon->pidfile, cfg->chrootdir,
570 			strlen(cfg->chrootdir))==0) {
571 			char* old = daemon->pidfile;
572 			daemon->pidfile = strdup(old+strlen(cfg->chrootdir));
573 			free(old);
574 			if(!daemon->pidfile)
575 				log_err("out of memory in pidfile adjust");
576 		}
577 		daemon->chroot = strdup(cfg->chrootdir);
578 		if(!daemon->chroot)
579 			log_err("out of memory in daemon chroot dir storage");
580 	}
581 #else
582 	(void)cfgfile;
583 #endif
584 	/* change to working directory inside chroot */
585 	if(cfg->directory && cfg->directory[0]) {
586 		char* dir = cfg->directory;
587 		if(cfg->chrootdir && cfg->chrootdir[0] &&
588 			strncmp(dir, cfg->chrootdir,
589 			strlen(cfg->chrootdir)) == 0)
590 			dir += strlen(cfg->chrootdir);
591 		if(dir[0]) {
592 			if(chdir(dir)) {
593 				fatal_exit("Could not chdir to %s: %s",
594 					dir, strerror(errno));
595 			}
596 			verbose(VERB_QUERY, "chdir to %s", dir);
597 		}
598 	}
599 
600 	/* drop permissions after chroot, getpwnam, pidfile, syslog done*/
601 #ifdef HAVE_GETPWNAM
602 	if(cfg->username && cfg->username[0]) {
603 #  ifdef HAVE_INITGROUPS
604 		if(initgroups(cfg->username, gid) != 0)
605 			log_warn("unable to initgroups %s: %s",
606 				cfg->username, strerror(errno));
607 #  endif /* HAVE_INITGROUPS */
608 		endpwent();
609 
610 #ifdef HAVE_SETRESGID
611 		if(setresgid(gid,gid,gid) != 0)
612 #elif defined(HAVE_SETREGID) && !defined(DARWIN_BROKEN_SETREUID)
613 		if(setregid(gid,gid) != 0)
614 #else /* use setgid */
615 		if(setgid(gid) != 0)
616 #endif /* HAVE_SETRESGID */
617 			fatal_exit("unable to set group id of %s: %s",
618 				cfg->username, strerror(errno));
619 #ifdef HAVE_SETRESUID
620 		if(setresuid(uid,uid,uid) != 0)
621 #elif defined(HAVE_SETREUID) && !defined(DARWIN_BROKEN_SETREUID)
622 		if(setreuid(uid,uid) != 0)
623 #else /* use setuid */
624 		if(setuid(uid) != 0)
625 #endif /* HAVE_SETRESUID */
626 			fatal_exit("unable to set user id of %s: %s",
627 				cfg->username, strerror(errno));
628 		verbose(VERB_QUERY, "drop user privileges, run as %s",
629 			cfg->username);
630 	}
631 #endif /* HAVE_GETPWNAM */
632 	/* file logging inited after chroot,chdir,setuid is done so that
633 	 * it would succeed on SIGHUP as well */
634 	if(!cfg->use_syslog)
635 		log_init(cfg->logfile, cfg->use_syslog, cfg->chrootdir);
636 }
637 
638 /**
639  * Run the daemon.
640  * @param cfgfile: the config file name.
641  * @param cmdline_verbose: verbosity resulting from commandline -v.
642  *    These increase verbosity as specified in the config file.
643  * @param debug_mode: if set, do not daemonize.
644  */
645 static void
646 run_daemon(const char* cfgfile, int cmdline_verbose, int debug_mode)
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 					cfgfile);
666 			log_warn("Continuing with default config settings");
667 		}
668 		apply_settings(daemon, cfg, cmdline_verbose, debug_mode);
669 
670 		/* prepare */
671 		if(!daemon_open_shared_ports(daemon))
672 			fatal_exit("could not open ports");
673 		if(!done_setup) {
674 			perform_setup(daemon, cfg, debug_mode, &cfgfile);
675 			done_setup = 1;
676 		} else {
677 			/* reopen log after HUP to facilitate log rotation */
678 			if(!cfg->use_syslog)
679 				log_init(cfg->logfile, 0, cfg->chrootdir);
680 		}
681 		/* work */
682 		daemon_fork(daemon);
683 
684 		/* clean up for restart */
685 		verbose(VERB_ALGO, "cleanup.");
686 		daemon_cleanup(daemon);
687 		config_delete(cfg);
688 	}
689 	verbose(VERB_ALGO, "Exit cleanup.");
690 	/* this unlink may not work if the pidfile is located outside
691 	 * of the chroot/workdir or we no longer have permissions */
692 	if(daemon->pidfile) {
693 		int fd;
694 		/* truncate pidfile */
695 		fd = open(daemon->pidfile, O_WRONLY | O_TRUNC, 0644);
696 		if(fd != -1)
697 			close(fd);
698 		/* delete pidfile */
699 		unlink(daemon->pidfile);
700 	}
701 	daemon_delete(daemon);
702 }
703 
704 /** getopt global, in case header files fail to declare it. */
705 extern int optind;
706 /** getopt global, in case header files fail to declare it. */
707 extern char* optarg;
708 
709 /**
710  * main program. Set options given commandline arguments.
711  * @param argc: number of commandline arguments.
712  * @param argv: array of commandline arguments.
713  * @return: exit status of the program.
714  */
715 int
716 main(int argc, char* argv[])
717 {
718 	int c;
719 	const char* cfgfile = CONFIGFILE;
720 	const char* winopt = NULL;
721 	int cmdline_verbose = 0;
722 	int debug_mode = 0;
723 #ifdef UB_ON_WINDOWS
724 	int cmdline_cfg = 0;
725 #endif
726 
727 #ifdef HAVE_SBRK
728 	/* take debug snapshot of heap */
729 	unbound_start_brk = sbrk(0);
730 #endif
731 
732 	log_init(NULL, 0, NULL);
733 	log_ident_set(strrchr(argv[0],'/')?strrchr(argv[0],'/')+1:argv[0]);
734 	/* parse the options */
735 	while( (c=getopt(argc, argv, "c:dhvw:")) != -1) {
736 		switch(c) {
737 		case 'c':
738 			cfgfile = optarg;
739 #ifdef UB_ON_WINDOWS
740 			cmdline_cfg = 1;
741 #endif
742 			break;
743 		case 'v':
744 			cmdline_verbose ++;
745 			verbosity++;
746 			break;
747 		case 'd':
748 			debug_mode++;
749 			break;
750 		case 'w':
751 			winopt = optarg;
752 			break;
753 		case '?':
754 		case 'h':
755 		default:
756 			usage();
757 			return 1;
758 		}
759 	}
760 	argc -= optind;
761 	argv += optind;
762 
763 	if(winopt) {
764 #ifdef UB_ON_WINDOWS
765 		wsvc_command_option(winopt, cfgfile, cmdline_verbose,
766 			cmdline_cfg);
767 #else
768 		fatal_exit("option not supported");
769 #endif
770 	}
771 
772 	if(argc != 0) {
773 		usage();
774 		return 1;
775 	}
776 
777 	run_daemon(cfgfile, cmdline_verbose, debug_mode);
778 	log_init(NULL, 0, NULL); /* close logfile */
779 	return 0;
780 }
781