]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/unbound/daemon/unbound.c
MFV r368464:
[FreeBSD/FreeBSD.git] / contrib / unbound / daemon / unbound.c
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
201         if(total > 1024 && 
202                 strncmp(ub_event_get_version(), "mini-event", 10) == 0) {
203                 log_warn("too many file descriptors requested. The builtin"
204                         "mini-event cannot handle more than 1024. Config "
205                         "for less fds or compile with libevent");
206                 if(numthread*perthread_noudp+15 > 1024)
207                         fatal_exit("too much tcp. not enough fds.");
208                 cfg->outgoing_num_ports = (int)((1024 
209                         - numthread*perthread_noudp 
210                         - 10 /* safety margin */) /numthread);
211                 log_warn("continuing with less udp ports: %u",
212                         cfg->outgoing_num_ports);
213                 total = 1024;
214         }
215         if(perthread > 64 && 
216                 strncmp(ub_event_get_version(), "winsock-event", 13) == 0) {
217                 log_err("too many file descriptors requested. The winsock"
218                         " event handler cannot handle more than 64 per "
219                         " thread. Config for less fds");
220                 if(perthread_noudp+2 > 64)
221                         fatal_exit("too much tcp. not enough fds.");
222                 cfg->outgoing_num_ports = (int)((64 
223                         - perthread_noudp 
224                         - 2/* safety margin */));
225                 log_warn("continuing with less udp ports: %u",
226                         cfg->outgoing_num_ports);
227                 total = numthread*(perthread_noudp+
228                         (size_t)cfg->outgoing_num_ports)+misc;
229         }
230         if(getrlimit(RLIMIT_NOFILE, &rlim) < 0) {
231                 log_warn("getrlimit: %s", strerror(errno));
232                 return;
233         }
234         if(rlim.rlim_cur == (rlim_t)RLIM_INFINITY)
235                 return;
236         if((size_t)rlim.rlim_cur < total) {
237                 avail = (size_t)rlim.rlim_cur;
238                 rlim.rlim_cur = (rlim_t)(total + 10);
239                 rlim.rlim_max = (rlim_t)(total + 10);
240 #ifdef HAVE_SETRLIMIT
241                 if(setrlimit(RLIMIT_NOFILE, &rlim) < 0) {
242                         log_warn("setrlimit: %s", strerror(errno));
243 #endif
244                         log_warn("cannot increase max open fds from %u to %u",
245                                 (unsigned)avail, (unsigned)total+10);
246                         /* check that calculation below does not underflow,
247                          * with 15 as margin */
248                         if(numthread*perthread_noudp+15 > avail)
249                                 fatal_exit("too much tcp. not enough fds.");
250                         cfg->outgoing_num_ports = (int)((avail 
251                                 - numthread*perthread_noudp 
252                                 - 10 /* safety margin */) /numthread);
253                         log_warn("continuing with less udp ports: %u",
254                                 cfg->outgoing_num_ports);
255                         log_warn("increase ulimit or decrease threads, "
256                                 "ports in config to remove this warning");
257                         return;
258 #ifdef HAVE_SETRLIMIT
259                 }
260 #endif
261                 verbose(VERB_ALGO, "increased limit(open files) from %u to %u",
262                         (unsigned)avail, (unsigned)total+10);
263         }
264 #else   
265         (void)cfg;
266 #endif /* HAVE_GETRLIMIT */
267 #endif /* S_SPLINT_S */
268 }
269
270 /** set verbosity, check rlimits, cache settings */
271 static void
272 apply_settings(struct daemon* daemon, struct config_file* cfg,
273         int cmdline_verbose, int debug_mode)
274 {
275         /* apply if they have changed */
276         verbosity = cmdline_verbose + cfg->verbosity;
277         if (debug_mode > 1) {
278                 cfg->use_syslog = 0;
279                 free(cfg->logfile);
280                 cfg->logfile = NULL;
281         }
282         daemon_apply_cfg(daemon, cfg);
283         checkrlimits(cfg);
284
285         if (cfg->use_systemd && cfg->do_daemonize) {
286                 log_warn("use-systemd and do-daemonize should not be enabled at the same time");
287         }
288
289         log_ident_set_or_default(cfg->log_identity);
290 }
291
292 #ifdef HAVE_KILL
293 /** Read existing pid from pidfile. 
294  * @param file: file name of pid file.
295  * @return: the pid from the file or -1 if none.
296  */
297 static pid_t
298 readpid (const char* file)
299 {
300         int fd;
301         pid_t pid;
302         char pidbuf[32];
303         char* t;
304         ssize_t l;
305
306         if ((fd = open(file, O_RDONLY)) == -1) {
307                 if(errno != ENOENT)
308                         log_err("Could not read pidfile %s: %s",
309                                 file, strerror(errno));
310                 return -1;
311         }
312
313         if (((l = read(fd, pidbuf, sizeof(pidbuf)))) == -1) {
314                 if(errno != ENOENT)
315                         log_err("Could not read pidfile %s: %s",
316                                 file, strerror(errno));
317                 close(fd);
318                 return -1;
319         }
320
321         close(fd);
322
323         /* Empty pidfile means no pidfile... */
324         if (l == 0) {
325                 return -1;
326         }
327
328         pidbuf[sizeof(pidbuf)-1] = 0;
329         pid = (pid_t)strtol(pidbuf, &t, 10);
330         
331         if (*t && *t != '\n') {
332                 return -1;
333         }
334         return pid;
335 }
336
337 /** write pid to file. 
338  * @param pidfile: file name of pid file.
339  * @param pid: pid to write to file.
340  * @return false on failure
341  */
342 static int
343 writepid (const char* pidfile, pid_t pid)
344 {
345         int fd;
346         char pidbuf[32];
347         size_t count = 0;
348         snprintf(pidbuf, sizeof(pidbuf), "%lu\n", (unsigned long)pid);
349
350         if((fd = open(pidfile, O_WRONLY | O_CREAT | O_TRUNC
351 #ifdef O_NOFOLLOW
352                 | O_NOFOLLOW
353 #endif
354                 , 0644)) == -1) {
355                 log_err("cannot open pidfile %s: %s", 
356                         pidfile, strerror(errno));
357                 return 0;
358         }
359         while(count < strlen(pidbuf)) {
360                 ssize_t r = write(fd, pidbuf+count, strlen(pidbuf)-count);
361                 if(r == -1) {
362                         if(errno == EAGAIN || errno == EINTR)
363                                 continue;
364                         log_err("cannot write to pidfile %s: %s",
365                                 pidfile, strerror(errno));
366                         close(fd);
367                         return 0;
368                 } else if(r == 0) {
369                         log_err("cannot write any bytes to pidfile %s: "
370                                 "write returns 0 bytes written", pidfile);
371                         close(fd);
372                         return 0;
373                 }
374                 count += r;
375         }
376         close(fd);
377         return 1;
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 privileges and chroot if needed */
440 static void
441 perform_setup(struct daemon* daemon, struct config_file* cfg, int debug_mode,
442         const char** cfgfile, int need_pidfile)
443 {
444 #ifdef HAVE_KILL
445         int pidinchroot;
446 #endif
447 #ifdef HAVE_GETPWNAM
448         struct passwd *pwd = NULL;
449
450         if(cfg->username && cfg->username[0]) {
451                 if((pwd = getpwnam(cfg->username)) == NULL)
452                         fatal_exit("user '%s' does not exist.", cfg->username);
453                 /* endpwent below, in case we need pwd for setusercontext */
454         }
455 #endif
456 #ifdef UB_ON_WINDOWS
457         w_config_adjust_directory(cfg);
458 #endif
459
460         /* read ssl keys while superuser and outside chroot */
461 #ifdef HAVE_SSL
462         if(!(daemon->rc = daemon_remote_create(cfg)))
463                 fatal_exit("could not set up remote-control");
464         if(cfg->ssl_service_key && cfg->ssl_service_key[0]) {
465                 if(!(daemon->listen_sslctx = listen_sslctx_create(
466                         cfg->ssl_service_key, cfg->ssl_service_pem, NULL)))
467                         fatal_exit("could not set up listen SSL_CTX");
468                 if(cfg->tls_ciphers && cfg->tls_ciphers[0]) {
469                         if (!SSL_CTX_set_cipher_list(daemon->listen_sslctx, cfg->tls_ciphers)) {
470                                 fatal_exit("failed to set tls-cipher %s", cfg->tls_ciphers);
471                         }
472                 }
473 #ifdef HAVE_SSL_CTX_SET_CIPHERSUITES
474                 if(cfg->tls_ciphersuites && cfg->tls_ciphersuites[0]) {
475                         if (!SSL_CTX_set_ciphersuites(daemon->listen_sslctx, cfg->tls_ciphersuites)) {
476                                 fatal_exit("failed to set tls-ciphersuites %s", cfg->tls_ciphersuites);
477                         }
478                 }
479 #endif
480                 if(cfg->tls_session_ticket_keys.first &&
481                         cfg->tls_session_ticket_keys.first->str[0] != 0) {
482                         if(!listen_sslctx_setup_ticket_keys(daemon->listen_sslctx, cfg->tls_session_ticket_keys.first)) {
483                                 fatal_exit("could not set session ticket SSL_CTX");
484                         }
485                 }
486         }
487         if(!(daemon->connect_sslctx = connect_sslctx_create(NULL, NULL,
488                 cfg->tls_cert_bundle, cfg->tls_win_cert)))
489                 fatal_exit("could not set up connect SSL_CTX");
490 #endif
491
492         /* init syslog (as root) if needed, before daemonize, otherwise
493          * a fork error could not be printed since daemonize closed stderr.*/
494         if(cfg->use_syslog) {
495                 log_init(cfg->logfile, cfg->use_syslog, cfg->chrootdir);
496         }
497         /* if using a logfile, we cannot open it because the logfile would
498          * be created with the wrong permissions, we cannot chown it because
499          * we cannot chown system logfiles, so we do not open at all.
500          * So, using a logfile, the user does not see errors unless -d is
501          * given to unbound on the commandline. */
502
503 #ifdef HAVE_KILL
504         /* true if pidfile is inside chrootdir, or nochroot */
505         pidinchroot = need_pidfile && (!(cfg->chrootdir && cfg->chrootdir[0]) ||
506                                 (cfg->chrootdir && cfg->chrootdir[0] &&
507                                 strncmp(cfg->pidfile, cfg->chrootdir,
508                                 strlen(cfg->chrootdir))==0));
509
510         /* check old pid file before forking */
511         if(cfg->pidfile && cfg->pidfile[0] && need_pidfile) {
512                 /* calculate position of pidfile */
513                 if(cfg->pidfile[0] == '/')
514                         daemon->pidfile = strdup(cfg->pidfile);
515                 else    daemon->pidfile = fname_after_chroot(cfg->pidfile, 
516                                 cfg, 1);
517                 if(!daemon->pidfile)
518                         fatal_exit("pidfile alloc: out of memory");
519                 checkoldpid(daemon->pidfile, pidinchroot);
520         }
521 #endif
522
523         /* daemonize because pid is needed by the writepid func */
524         if(!debug_mode && cfg->do_daemonize) {
525                 detach();
526         }
527
528         /* write new pidfile (while still root, so can be outside chroot) */
529 #ifdef HAVE_KILL
530         if(cfg->pidfile && cfg->pidfile[0] && need_pidfile) {
531                 if(writepid(daemon->pidfile, getpid())) {
532                         if(cfg->username && cfg->username[0] && cfg_uid != (uid_t)-1 &&
533                                 pidinchroot) {
534 #  ifdef HAVE_CHOWN
535                                 if(chown(daemon->pidfile, cfg_uid, cfg_gid) == -1) {
536                                         verbose(VERB_QUERY, "cannot chown %u.%u %s: %s",
537                                                 (unsigned)cfg_uid, (unsigned)cfg_gid,
538                                                 daemon->pidfile, strerror(errno));
539                                 }
540 #  endif /* HAVE_CHOWN */
541                         }
542                 }
543         }
544 #else
545         (void)daemon;
546         (void)need_pidfile;
547 #endif /* HAVE_KILL */
548
549         /* Set user context */
550 #ifdef HAVE_GETPWNAM
551         if(cfg->username && cfg->username[0] && cfg_uid != (uid_t)-1) {
552 #ifdef HAVE_SETUSERCONTEXT
553                 /* setusercontext does initgroups, setuid, setgid, and
554                  * also resource limits from login config, but we
555                  * still call setresuid, setresgid to be sure to set all uid*/
556                 if(setusercontext(NULL, pwd, cfg_uid, (unsigned)
557                         LOGIN_SETALL & ~LOGIN_SETUSER & ~LOGIN_SETGROUP) != 0)
558                         log_warn("unable to setusercontext %s: %s",
559                                 cfg->username, strerror(errno));
560 #else
561                 (void)pwd;
562 #endif /* HAVE_SETUSERCONTEXT */
563         }
564 #endif /* HAVE_GETPWNAM */
565
566         /* box into the chroot */
567 #ifdef HAVE_CHROOT
568         if(cfg->chrootdir && cfg->chrootdir[0]) {
569                 if(chdir(cfg->chrootdir)) {
570                         fatal_exit("unable to chdir to chroot %s: %s",
571                                 cfg->chrootdir, strerror(errno));
572                 }
573                 verbose(VERB_QUERY, "chdir to %s", cfg->chrootdir);
574                 if(chroot(cfg->chrootdir))
575                         fatal_exit("unable to chroot to %s: %s", 
576                                 cfg->chrootdir, strerror(errno));
577                 if(chdir("/"))
578                         fatal_exit("unable to chdir to / in chroot %s: %s",
579                                 cfg->chrootdir, strerror(errno));
580                 verbose(VERB_QUERY, "chroot to %s", cfg->chrootdir);
581                 if(strncmp(*cfgfile, cfg->chrootdir, 
582                         strlen(cfg->chrootdir)) == 0) 
583                         (*cfgfile) += strlen(cfg->chrootdir);
584
585                 /* adjust stored pidfile for chroot */
586                 if(daemon->pidfile && daemon->pidfile[0] && 
587                         strncmp(daemon->pidfile, cfg->chrootdir,
588                         strlen(cfg->chrootdir))==0) {
589                         char* old = daemon->pidfile;
590                         daemon->pidfile = strdup(old+strlen(cfg->chrootdir));
591                         free(old);
592                         if(!daemon->pidfile)
593                                 log_err("out of memory in pidfile adjust");
594                 }
595                 daemon->chroot = strdup(cfg->chrootdir);
596                 if(!daemon->chroot)
597                         log_err("out of memory in daemon chroot dir storage");
598         }
599 #else
600         (void)cfgfile;
601 #endif
602         /* change to working directory inside chroot */
603         if(cfg->directory && cfg->directory[0]) {
604                 char* dir = cfg->directory;
605                 if(cfg->chrootdir && cfg->chrootdir[0] &&
606                         strncmp(dir, cfg->chrootdir, 
607                         strlen(cfg->chrootdir)) == 0)
608                         dir += strlen(cfg->chrootdir);
609                 if(dir[0]) {
610                         if(chdir(dir)) {
611                                 fatal_exit("Could not chdir to %s: %s",
612                                         dir, strerror(errno));
613                         }
614                         verbose(VERB_QUERY, "chdir to %s", dir);
615                 }
616         }
617
618         /* drop permissions after chroot, getpwnam, pidfile, syslog done*/
619 #ifdef HAVE_GETPWNAM
620         if(cfg->username && cfg->username[0] && cfg_uid != (uid_t)-1) {
621 #  ifdef HAVE_INITGROUPS
622                 if(initgroups(cfg->username, cfg_gid) != 0)
623                         log_warn("unable to initgroups %s: %s",
624                                 cfg->username, strerror(errno));
625 #  endif /* HAVE_INITGROUPS */
626 #  ifdef HAVE_ENDPWENT
627                 endpwent();
628 #  endif
629
630 #ifdef HAVE_SETRESGID
631                 if(setresgid(cfg_gid,cfg_gid,cfg_gid) != 0)
632 #elif defined(HAVE_SETREGID) && !defined(DARWIN_BROKEN_SETREUID)
633                 if(setregid(cfg_gid,cfg_gid) != 0)
634 #else /* use setgid */
635                 if(setgid(cfg_gid) != 0)
636 #endif /* HAVE_SETRESGID */
637                         fatal_exit("unable to set group id of %s: %s", 
638                                 cfg->username, strerror(errno));
639 #ifdef HAVE_SETRESUID
640                 if(setresuid(cfg_uid,cfg_uid,cfg_uid) != 0)
641 #elif defined(HAVE_SETREUID) && !defined(DARWIN_BROKEN_SETREUID)
642                 if(setreuid(cfg_uid,cfg_uid) != 0)
643 #else /* use setuid */
644                 if(setuid(cfg_uid) != 0)
645 #endif /* HAVE_SETRESUID */
646                         fatal_exit("unable to set user id of %s: %s", 
647                                 cfg->username, strerror(errno));
648                 verbose(VERB_QUERY, "drop user privileges, run as %s", 
649                         cfg->username);
650         }
651 #endif /* HAVE_GETPWNAM */
652         /* file logging inited after chroot,chdir,setuid is done so that 
653          * it would succeed on SIGHUP as well */
654         if(!cfg->use_syslog)
655                 log_init(cfg->logfile, cfg->use_syslog, cfg->chrootdir);
656 }
657
658 /**
659  * Run the daemon. 
660  * @param cfgfile: the config file name.
661  * @param cmdline_verbose: verbosity resulting from commandline -v.
662  *    These increase verbosity as specified in the config file.
663  * @param debug_mode: if set, do not daemonize.
664  * @param need_pidfile: if false, no pidfile is checked or created.
665  */
666 static void 
667 run_daemon(const char* cfgfile, int cmdline_verbose, int debug_mode, int need_pidfile)
668 {
669         struct config_file* cfg = NULL;
670         struct daemon* daemon = NULL;
671         int done_setup = 0;
672
673         if(!(daemon = daemon_init()))
674                 fatal_exit("alloc failure");
675         while(!daemon->need_to_exit) {
676                 if(done_setup)
677                         verbose(VERB_OPS, "Restart of %s.", PACKAGE_STRING);
678                 else    verbose(VERB_OPS, "Start of %s.", PACKAGE_STRING);
679
680                 /* config stuff */
681                 if(!(cfg = config_create()))
682                         fatal_exit("Could not alloc config defaults");
683                 if(!config_read(cfg, cfgfile, daemon->chroot)) {
684                         if(errno != ENOENT)
685                                 fatal_exit("Could not read config file: %s."
686                                         " Maybe try unbound -dd, it stays on "
687                                         "the commandline to see more errors, "
688                                         "or unbound-checkconf", cfgfile);
689                         log_warn("Continuing with default config settings");
690                 }
691                 apply_settings(daemon, cfg, cmdline_verbose, debug_mode);
692                 if(!done_setup)
693                         config_lookup_uid(cfg);
694         
695                 /* prepare */
696                 if(!daemon_open_shared_ports(daemon))
697                         fatal_exit("could not open ports");
698                 if(!done_setup) { 
699                         perform_setup(daemon, cfg, debug_mode, &cfgfile, need_pidfile);
700                         done_setup = 1; 
701                 } else {
702                         /* reopen log after HUP to facilitate log rotation */
703                         if(!cfg->use_syslog)
704                                 log_init(cfg->logfile, 0, cfg->chrootdir);
705                 }
706                 /* work */
707                 daemon_fork(daemon);
708
709                 /* clean up for restart */
710                 verbose(VERB_ALGO, "cleanup.");
711                 daemon_cleanup(daemon);
712                 config_delete(cfg);
713         }
714         verbose(VERB_ALGO, "Exit cleanup.");
715         /* this unlink may not work if the pidfile is located outside
716          * of the chroot/workdir or we no longer have permissions */
717         if(daemon->pidfile) {
718                 int fd;
719                 /* truncate pidfile */
720                 fd = open(daemon->pidfile, O_WRONLY | O_TRUNC, 0644);
721                 if(fd != -1)
722                         close(fd);
723                 /* delete pidfile */
724                 unlink(daemon->pidfile);
725         }
726         daemon_delete(daemon);
727 }
728
729 /** getopt global, in case header files fail to declare it. */
730 extern int optind;
731 /** getopt global, in case header files fail to declare it. */
732 extern char* optarg;
733
734 /**
735  * main program. Set options given commandline arguments.
736  * @param argc: number of commandline arguments.
737  * @param argv: array of commandline arguments.
738  * @return: exit status of the program.
739  */
740 int 
741 main(int argc, char* argv[])
742 {
743         int c;
744         const char* cfgfile = CONFIGFILE;
745         const char* winopt = NULL;
746         const char* log_ident_default;
747         int cmdline_verbose = 0;
748         int debug_mode = 0;
749         int need_pidfile = 1;
750
751 #ifdef UB_ON_WINDOWS
752         int cmdline_cfg = 0;
753 #endif
754
755         log_init(NULL, 0, NULL);
756         log_ident_default = strrchr(argv[0],'/')?strrchr(argv[0],'/')+1:argv[0];
757         log_ident_set_default(log_ident_default);
758         log_ident_set(log_ident_default);
759         /* parse the options */
760         while( (c=getopt(argc, argv, "c:dhpvw:V")) != -1) {
761                 switch(c) {
762                 case 'c':
763                         cfgfile = optarg;
764 #ifdef UB_ON_WINDOWS
765                         cmdline_cfg = 1;
766 #endif
767                         break;
768                 case 'v':
769                         cmdline_verbose++;
770                         verbosity++;
771                         break;
772                 case 'p':
773                         need_pidfile = 0;
774                         break;
775                 case 'd':
776                         debug_mode++;
777                         break;
778                 case 'w':
779                         winopt = optarg;
780                         break;
781                 case 'V':
782                         print_build_options();
783                         return 0;
784                 case '?':
785                 case 'h':
786                 default:
787                         usage();
788                         return 1;
789                 }
790         }
791         argc -= optind;
792         /* argv += optind; not using further arguments */
793
794         if(winopt) {
795 #ifdef UB_ON_WINDOWS
796                 wsvc_command_option(winopt, cfgfile, cmdline_verbose, 
797                         cmdline_cfg);
798 #else
799                 fatal_exit("option not supported");
800 #endif
801         }
802
803         if(argc != 0) {
804                 usage();
805                 return 1;
806         }
807
808         run_daemon(cfgfile, cmdline_verbose, debug_mode, need_pidfile);
809         log_init(NULL, 0, NULL); /* close logfile */
810 #ifndef unbound_testbound
811         if(log_get_lock()) {
812                 lock_basic_destroy((lock_basic_type*)log_get_lock());
813         }
814 #endif
815         return 0;
816 }