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