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