xref: /freebsd/contrib/unbound/daemon/unbound.c (revision 5dae51da3da0cc94d17bd67b308fad304ebec7e0)
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 #ifdef HAVE_SBRK
91 /** global debug value to keep track of heap memory allocation */
92 void* unbound_start_brk = 0;
93 #endif
94 
95 /** print usage. */
96 static void usage(void)
97 {
98 	const char** m;
99 	const char *evnm="event", *evsys="", *evmethod="";
100 	time_t t;
101 	struct timeval now;
102 	struct ub_event_base* base;
103 	printf("usage:  unbound [options]\n");
104 	printf("	start unbound daemon DNS resolver.\n");
105 	printf("-h	this help\n");
106 	printf("-c file	config file to read instead of %s\n", CONFIGFILE);
107 	printf("	file format is described in unbound.conf(5).\n");
108 	printf("-d	do not fork into the background.\n");
109 	printf("-v	verbose (more times to increase verbosity)\n");
110 #ifdef UB_ON_WINDOWS
111 	printf("-w opt	windows option: \n");
112 	printf("   	install, remove - manage the services entry\n");
113 	printf("   	service - used to start from services control panel\n");
114 #endif
115 	printf("Version %s\n", PACKAGE_VERSION);
116 	base = ub_default_event_base(0,&t,&now);
117 	ub_get_event_sys(base, &evnm, &evsys, &evmethod);
118 	printf("linked libs: %s %s (it uses %s), %s\n",
119 		evnm, evsys, evmethod,
120 #ifdef HAVE_SSL
121 #  ifdef SSLEAY_VERSION
122 		SSLeay_version(SSLEAY_VERSION)
123 #  else
124 		OpenSSL_version(OPENSSL_VERSION)
125 #  endif
126 #elif defined(HAVE_NSS)
127 		NSS_GetVersion()
128 #elif defined(HAVE_NETTLE)
129 		"nettle"
130 #endif
131 		);
132 	printf("linked modules:");
133 	for(m = module_list_avail(); *m; m++)
134 		printf(" %s", *m);
135 	printf("\n");
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 verbosity, check rlimits, cache settings */
248 static void
249 apply_settings(struct daemon* daemon, struct config_file* cfg,
250 	int cmdline_verbose, int debug_mode)
251 {
252 	/* apply if they have changed */
253 	verbosity = cmdline_verbose + cfg->verbosity;
254 	if (debug_mode > 1) {
255 		cfg->use_syslog = 0;
256 		cfg->logfile = NULL;
257 	}
258 	daemon_apply_cfg(daemon, cfg);
259 	checkrlimits(cfg);
260 }
261 
262 #ifdef HAVE_KILL
263 /** Read existing pid from pidfile.
264  * @param file: file name of pid file.
265  * @return: the pid from the file or -1 if none.
266  */
267 static pid_t
268 readpid (const char* file)
269 {
270 	int fd;
271 	pid_t pid;
272 	char pidbuf[32];
273 	char* t;
274 	ssize_t l;
275 
276 	if ((fd = open(file, O_RDONLY)) == -1) {
277 		if(errno != ENOENT)
278 			log_err("Could not read pidfile %s: %s",
279 				file, strerror(errno));
280 		return -1;
281 	}
282 
283 	if (((l = read(fd, pidbuf, sizeof(pidbuf)))) == -1) {
284 		if(errno != ENOENT)
285 			log_err("Could not read pidfile %s: %s",
286 				file, strerror(errno));
287 		close(fd);
288 		return -1;
289 	}
290 
291 	close(fd);
292 
293 	/* Empty pidfile means no pidfile... */
294 	if (l == 0) {
295 		return -1;
296 	}
297 
298 	pidbuf[sizeof(pidbuf)-1] = 0;
299 	pid = (pid_t)strtol(pidbuf, &t, 10);
300 
301 	if (*t && *t != '\n') {
302 		return -1;
303 	}
304 	return pid;
305 }
306 
307 /** write pid to file.
308  * @param pidfile: file name of pid file.
309  * @param pid: pid to write to file.
310  */
311 static void
312 writepid (const char* pidfile, pid_t pid)
313 {
314 	FILE* f;
315 
316 	if ((f = fopen(pidfile, "w")) ==  NULL ) {
317 		log_err("cannot open pidfile %s: %s",
318 			pidfile, strerror(errno));
319 		return;
320 	}
321 	if(fprintf(f, "%lu\n", (unsigned long)pid) < 0) {
322 		log_err("cannot write to pidfile %s: %s",
323 			pidfile, strerror(errno));
324 	}
325 	fclose(f);
326 }
327 
328 /**
329  * check old pid file.
330  * @param pidfile: the file name of the pid file.
331  * @param inchroot: if pidfile is inchroot and we can thus expect to
332  *	be able to delete it.
333  */
334 static void
335 checkoldpid(char* pidfile, int inchroot)
336 {
337 	pid_t old;
338 	if((old = readpid(pidfile)) != -1) {
339 		/* see if it is still alive */
340 		if(kill(old, 0) == 0 || errno == EPERM)
341 			log_warn("unbound is already running as pid %u.",
342 				(unsigned)old);
343 		else	if(inchroot)
344 			log_warn("did not exit gracefully last time (%u)",
345 				(unsigned)old);
346 	}
347 }
348 #endif /* HAVE_KILL */
349 
350 /** detach from command line */
351 static void
352 detach(void)
353 {
354 #if defined(HAVE_DAEMON) && !defined(DEPRECATED_DAEMON)
355 	/* use POSIX daemon(3) function */
356 	if(daemon(1, 0) != 0)
357 		fatal_exit("daemon failed: %s", strerror(errno));
358 #else /* no HAVE_DAEMON */
359 #ifdef HAVE_FORK
360 	int fd;
361 	/* Take off... */
362 	switch (fork()) {
363 		case 0:
364 			break;
365 		case -1:
366 			fatal_exit("fork failed: %s", strerror(errno));
367 		default:
368 			/* exit interactive session */
369 			exit(0);
370 	}
371 	/* detach */
372 #ifdef HAVE_SETSID
373 	if(setsid() == -1)
374 		fatal_exit("setsid() failed: %s", strerror(errno));
375 #endif
376 	if ((fd = open("/dev/null", O_RDWR, 0)) != -1) {
377 		(void)dup2(fd, STDIN_FILENO);
378 		(void)dup2(fd, STDOUT_FILENO);
379 		(void)dup2(fd, STDERR_FILENO);
380 		if (fd > 2)
381 			(void)close(fd);
382 	}
383 #endif /* HAVE_FORK */
384 #endif /* HAVE_DAEMON */
385 }
386 
387 /** daemonize, drop user priviliges and chroot if needed */
388 static void
389 perform_setup(struct daemon* daemon, struct config_file* cfg, int debug_mode,
390 	const char** cfgfile)
391 {
392 #ifdef HAVE_KILL
393 	int pidinchroot;
394 #endif
395 #ifdef HAVE_GETPWNAM
396 	struct passwd *pwd = NULL;
397 
398 	if(cfg->username && cfg->username[0]) {
399 		if((pwd = getpwnam(cfg->username)) == NULL)
400 			fatal_exit("user '%s' does not exist.", cfg->username);
401 		/* endpwent below, in case we need pwd for setusercontext */
402 	}
403 #endif
404 #ifdef UB_ON_WINDOWS
405 	w_config_adjust_directory(cfg);
406 #endif
407 
408 	/* init syslog (as root) if needed, before daemonize, otherwise
409 	 * a fork error could not be printed since daemonize closed stderr.*/
410 	if(cfg->use_syslog) {
411 		log_init(cfg->logfile, cfg->use_syslog, cfg->chrootdir);
412 	}
413 	/* if using a logfile, we cannot open it because the logfile would
414 	 * be created with the wrong permissions, we cannot chown it because
415 	 * we cannot chown system logfiles, so we do not open at all.
416 	 * So, using a logfile, the user does not see errors unless -d is
417 	 * given to unbound on the commandline. */
418 
419 	/* read ssl keys while superuser and outside chroot */
420 #ifdef HAVE_SSL
421 	if(!(daemon->rc = daemon_remote_create(cfg)))
422 		fatal_exit("could not set up remote-control");
423 	if(cfg->ssl_service_key && cfg->ssl_service_key[0]) {
424 		if(!(daemon->listen_sslctx = listen_sslctx_create(
425 			cfg->ssl_service_key, cfg->ssl_service_pem, NULL)))
426 			fatal_exit("could not set up listen SSL_CTX");
427 	}
428 	if(!(daemon->connect_sslctx = connect_sslctx_create(NULL, NULL, NULL)))
429 		fatal_exit("could not set up connect SSL_CTX");
430 #endif
431 
432 #ifdef HAVE_KILL
433 	/* true if pidfile is inside chrootdir, or nochroot */
434 	pidinchroot = !(cfg->chrootdir && cfg->chrootdir[0]) ||
435 				(cfg->chrootdir && cfg->chrootdir[0] &&
436 				strncmp(cfg->pidfile, cfg->chrootdir,
437 				strlen(cfg->chrootdir))==0);
438 
439 	/* check old pid file before forking */
440 	if(cfg->pidfile && cfg->pidfile[0]) {
441 		/* calculate position of pidfile */
442 		if(cfg->pidfile[0] == '/')
443 			daemon->pidfile = strdup(cfg->pidfile);
444 		else	daemon->pidfile = fname_after_chroot(cfg->pidfile,
445 				cfg, 1);
446 		if(!daemon->pidfile)
447 			fatal_exit("pidfile alloc: out of memory");
448 		checkoldpid(daemon->pidfile, pidinchroot);
449 	}
450 #endif
451 
452 	/* daemonize because pid is needed by the writepid func */
453 	if(!debug_mode && cfg->do_daemonize) {
454 		detach();
455 	}
456 
457 	/* write new pidfile (while still root, so can be outside chroot) */
458 #ifdef HAVE_KILL
459 	if(cfg->pidfile && cfg->pidfile[0]) {
460 		writepid(daemon->pidfile, getpid());
461 		if(cfg->username && cfg->username[0] && cfg_uid != (uid_t)-1 &&
462 			pidinchroot) {
463 #  ifdef HAVE_CHOWN
464 			if(chown(daemon->pidfile, cfg_uid, cfg_gid) == -1) {
465 				verbose(VERB_QUERY, "cannot chown %u.%u %s: %s",
466 					(unsigned)cfg_uid, (unsigned)cfg_gid,
467 					daemon->pidfile, strerror(errno));
468 			}
469 #  endif /* HAVE_CHOWN */
470 		}
471 	}
472 #else
473 	(void)daemon;
474 #endif /* HAVE_KILL */
475 
476 	/* Set user context */
477 #ifdef HAVE_GETPWNAM
478 	if(cfg->username && cfg->username[0] && cfg_uid != (uid_t)-1) {
479 #ifdef HAVE_SETUSERCONTEXT
480 		/* setusercontext does initgroups, setuid, setgid, and
481 		 * also resource limits from login config, but we
482 		 * still call setresuid, setresgid to be sure to set all uid*/
483 		if(setusercontext(NULL, pwd, cfg_uid, (unsigned)
484 			LOGIN_SETALL & ~LOGIN_SETUSER & ~LOGIN_SETGROUP) != 0)
485 			log_warn("unable to setusercontext %s: %s",
486 				cfg->username, strerror(errno));
487 #endif /* HAVE_SETUSERCONTEXT */
488 	}
489 #endif /* HAVE_GETPWNAM */
490 
491 	/* box into the chroot */
492 #ifdef HAVE_CHROOT
493 	if(cfg->chrootdir && cfg->chrootdir[0]) {
494 		if(chdir(cfg->chrootdir)) {
495 			fatal_exit("unable to chdir to chroot %s: %s",
496 				cfg->chrootdir, strerror(errno));
497 		}
498 		verbose(VERB_QUERY, "chdir to %s", cfg->chrootdir);
499 		if(chroot(cfg->chrootdir))
500 			fatal_exit("unable to chroot to %s: %s",
501 				cfg->chrootdir, strerror(errno));
502 		if(chdir("/"))
503 			fatal_exit("unable to chdir to / in chroot %s: %s",
504 				cfg->chrootdir, strerror(errno));
505 		verbose(VERB_QUERY, "chroot to %s", cfg->chrootdir);
506 		if(strncmp(*cfgfile, cfg->chrootdir,
507 			strlen(cfg->chrootdir)) == 0)
508 			(*cfgfile) += strlen(cfg->chrootdir);
509 
510 		/* adjust stored pidfile for chroot */
511 		if(daemon->pidfile && daemon->pidfile[0] &&
512 			strncmp(daemon->pidfile, cfg->chrootdir,
513 			strlen(cfg->chrootdir))==0) {
514 			char* old = daemon->pidfile;
515 			daemon->pidfile = strdup(old+strlen(cfg->chrootdir));
516 			free(old);
517 			if(!daemon->pidfile)
518 				log_err("out of memory in pidfile adjust");
519 		}
520 		daemon->chroot = strdup(cfg->chrootdir);
521 		if(!daemon->chroot)
522 			log_err("out of memory in daemon chroot dir storage");
523 	}
524 #else
525 	(void)cfgfile;
526 #endif
527 	/* change to working directory inside chroot */
528 	if(cfg->directory && cfg->directory[0]) {
529 		char* dir = cfg->directory;
530 		if(cfg->chrootdir && cfg->chrootdir[0] &&
531 			strncmp(dir, cfg->chrootdir,
532 			strlen(cfg->chrootdir)) == 0)
533 			dir += strlen(cfg->chrootdir);
534 		if(dir[0]) {
535 			if(chdir(dir)) {
536 				fatal_exit("Could not chdir to %s: %s",
537 					dir, strerror(errno));
538 			}
539 			verbose(VERB_QUERY, "chdir to %s", dir);
540 		}
541 	}
542 
543 	/* drop permissions after chroot, getpwnam, pidfile, syslog done*/
544 #ifdef HAVE_GETPWNAM
545 	if(cfg->username && cfg->username[0] && cfg_uid != (uid_t)-1) {
546 #  ifdef HAVE_INITGROUPS
547 		if(initgroups(cfg->username, cfg_gid) != 0)
548 			log_warn("unable to initgroups %s: %s",
549 				cfg->username, strerror(errno));
550 #  endif /* HAVE_INITGROUPS */
551 #  ifdef HAVE_ENDPWENT
552 		endpwent();
553 #  endif
554 
555 #ifdef HAVE_SETRESGID
556 		if(setresgid(cfg_gid,cfg_gid,cfg_gid) != 0)
557 #elif defined(HAVE_SETREGID) && !defined(DARWIN_BROKEN_SETREUID)
558 		if(setregid(cfg_gid,cfg_gid) != 0)
559 #else /* use setgid */
560 		if(setgid(cfg_gid) != 0)
561 #endif /* HAVE_SETRESGID */
562 			fatal_exit("unable to set group id of %s: %s",
563 				cfg->username, strerror(errno));
564 #ifdef HAVE_SETRESUID
565 		if(setresuid(cfg_uid,cfg_uid,cfg_uid) != 0)
566 #elif defined(HAVE_SETREUID) && !defined(DARWIN_BROKEN_SETREUID)
567 		if(setreuid(cfg_uid,cfg_uid) != 0)
568 #else /* use setuid */
569 		if(setuid(cfg_uid) != 0)
570 #endif /* HAVE_SETRESUID */
571 			fatal_exit("unable to set user id of %s: %s",
572 				cfg->username, strerror(errno));
573 		verbose(VERB_QUERY, "drop user privileges, run as %s",
574 			cfg->username);
575 	}
576 #endif /* HAVE_GETPWNAM */
577 	/* file logging inited after chroot,chdir,setuid is done so that
578 	 * it would succeed on SIGHUP as well */
579 	if(!cfg->use_syslog)
580 		log_init(cfg->logfile, cfg->use_syslog, cfg->chrootdir);
581 }
582 
583 /**
584  * Run the daemon.
585  * @param cfgfile: the config file name.
586  * @param cmdline_verbose: verbosity resulting from commandline -v.
587  *    These increase verbosity as specified in the config file.
588  * @param debug_mode: if set, do not daemonize.
589  */
590 static void
591 run_daemon(const char* cfgfile, int cmdline_verbose, int debug_mode)
592 {
593 	struct config_file* cfg = NULL;
594 	struct daemon* daemon = NULL;
595 	int done_setup = 0;
596 
597 	if(!(daemon = daemon_init()))
598 		fatal_exit("alloc failure");
599 	while(!daemon->need_to_exit) {
600 		if(done_setup)
601 			verbose(VERB_OPS, "Restart of %s.", PACKAGE_STRING);
602 		else	verbose(VERB_OPS, "Start of %s.", PACKAGE_STRING);
603 
604 		/* config stuff */
605 		if(!(cfg = config_create()))
606 			fatal_exit("Could not alloc config defaults");
607 		if(!config_read(cfg, cfgfile, daemon->chroot)) {
608 			if(errno != ENOENT)
609 				fatal_exit("Could not read config file: %s",
610 					cfgfile);
611 			log_warn("Continuing with default config settings");
612 		}
613 		apply_settings(daemon, cfg, cmdline_verbose, debug_mode);
614 		if(!done_setup)
615 			config_lookup_uid(cfg);
616 
617 		/* prepare */
618 		if(!daemon_open_shared_ports(daemon))
619 			fatal_exit("could not open ports");
620 		if(!done_setup) {
621 			perform_setup(daemon, cfg, debug_mode, &cfgfile);
622 			done_setup = 1;
623 		} else {
624 			/* reopen log after HUP to facilitate log rotation */
625 			if(!cfg->use_syslog)
626 				log_init(cfg->logfile, 0, cfg->chrootdir);
627 		}
628 		/* work */
629 		daemon_fork(daemon);
630 
631 		/* clean up for restart */
632 		verbose(VERB_ALGO, "cleanup.");
633 		daemon_cleanup(daemon);
634 		config_delete(cfg);
635 	}
636 	verbose(VERB_ALGO, "Exit cleanup.");
637 	/* this unlink may not work if the pidfile is located outside
638 	 * of the chroot/workdir or we no longer have permissions */
639 	if(daemon->pidfile) {
640 		int fd;
641 		/* truncate pidfile */
642 		fd = open(daemon->pidfile, O_WRONLY | O_TRUNC, 0644);
643 		if(fd != -1)
644 			close(fd);
645 		/* delete pidfile */
646 		unlink(daemon->pidfile);
647 	}
648 	daemon_delete(daemon);
649 }
650 
651 /** getopt global, in case header files fail to declare it. */
652 extern int optind;
653 /** getopt global, in case header files fail to declare it. */
654 extern char* optarg;
655 
656 /**
657  * main program. Set options given commandline arguments.
658  * @param argc: number of commandline arguments.
659  * @param argv: array of commandline arguments.
660  * @return: exit status of the program.
661  */
662 int
663 main(int argc, char* argv[])
664 {
665 	int c;
666 	const char* cfgfile = CONFIGFILE;
667 	const char* winopt = NULL;
668 	int cmdline_verbose = 0;
669 	int debug_mode = 0;
670 #ifdef UB_ON_WINDOWS
671 	int cmdline_cfg = 0;
672 #endif
673 
674 #ifdef HAVE_SBRK
675 	/* take debug snapshot of heap */
676 	unbound_start_brk = sbrk(0);
677 #endif
678 
679 	log_init(NULL, 0, NULL);
680 	log_ident_set(strrchr(argv[0],'/')?strrchr(argv[0],'/')+1:argv[0]);
681 	/* parse the options */
682 	while( (c=getopt(argc, argv, "c:dhvw:")) != -1) {
683 		switch(c) {
684 		case 'c':
685 			cfgfile = optarg;
686 #ifdef UB_ON_WINDOWS
687 			cmdline_cfg = 1;
688 #endif
689 			break;
690 		case 'v':
691 			cmdline_verbose++;
692 			verbosity++;
693 			break;
694 		case 'd':
695 			debug_mode++;
696 			break;
697 		case 'w':
698 			winopt = optarg;
699 			break;
700 		case '?':
701 		case 'h':
702 		default:
703 			usage();
704 			return 1;
705 		}
706 	}
707 	argc -= optind;
708 	argv += optind;
709 
710 	if(winopt) {
711 #ifdef UB_ON_WINDOWS
712 		wsvc_command_option(winopt, cfgfile, cmdline_verbose,
713 			cmdline_cfg);
714 #else
715 		fatal_exit("option not supported");
716 #endif
717 	}
718 
719 	if(argc != 0) {
720 		usage();
721 		return 1;
722 	}
723 
724 	run_daemon(cfgfile, cmdline_verbose, debug_mode);
725 	log_init(NULL, 0, NULL); /* close logfile */
726 	return 0;
727 }
728