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