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