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