]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/unbound/daemon/unbound.c
Upgrade Unbound to 1.6.1. 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
268         if (cfg->use_systemd && cfg->do_daemonize) {
269                 log_warn("use-systemd and do-daemonize should not be enabled at the same time");
270         }
271
272         log_ident_set_fromdefault(cfg, log_default_identity);
273 }
274
275 #ifdef HAVE_KILL
276 /** Read existing pid from pidfile. 
277  * @param file: file name of pid file.
278  * @return: the pid from the file or -1 if none.
279  */
280 static pid_t
281 readpid (const char* file)
282 {
283         int fd;
284         pid_t pid;
285         char pidbuf[32];
286         char* t;
287         ssize_t l;
288
289         if ((fd = open(file, O_RDONLY)) == -1) {
290                 if(errno != ENOENT)
291                         log_err("Could not read pidfile %s: %s",
292                                 file, strerror(errno));
293                 return -1;
294         }
295
296         if (((l = read(fd, pidbuf, sizeof(pidbuf)))) == -1) {
297                 if(errno != ENOENT)
298                         log_err("Could not read pidfile %s: %s",
299                                 file, strerror(errno));
300                 close(fd);
301                 return -1;
302         }
303
304         close(fd);
305
306         /* Empty pidfile means no pidfile... */
307         if (l == 0) {
308                 return -1;
309         }
310
311         pidbuf[sizeof(pidbuf)-1] = 0;
312         pid = (pid_t)strtol(pidbuf, &t, 10);
313         
314         if (*t && *t != '\n') {
315                 return -1;
316         }
317         return pid;
318 }
319
320 /** write pid to file. 
321  * @param pidfile: file name of pid file.
322  * @param pid: pid to write to file.
323  */
324 static void
325 writepid (const char* pidfile, pid_t pid)
326 {
327         FILE* f;
328
329         if ((f = fopen(pidfile, "w")) ==  NULL ) {
330                 log_err("cannot open pidfile %s: %s", 
331                         pidfile, strerror(errno));
332                 return;
333         }
334         if(fprintf(f, "%lu\n", (unsigned long)pid) < 0) {
335                 log_err("cannot write to pidfile %s: %s", 
336                         pidfile, strerror(errno));
337         }
338         fclose(f);
339 }
340
341 /**
342  * check old pid file.
343  * @param pidfile: the file name of the pid file.
344  * @param inchroot: if pidfile is inchroot and we can thus expect to
345  *      be able to delete it.
346  */
347 static void
348 checkoldpid(char* pidfile, int inchroot)
349 {
350         pid_t old;
351         if((old = readpid(pidfile)) != -1) {
352                 /* see if it is still alive */
353                 if(kill(old, 0) == 0 || errno == EPERM)
354                         log_warn("unbound is already running as pid %u.", 
355                                 (unsigned)old);
356                 else    if(inchroot)
357                         log_warn("did not exit gracefully last time (%u)", 
358                                 (unsigned)old);
359         }
360 }
361 #endif /* HAVE_KILL */
362
363 /** detach from command line */
364 static void
365 detach(void)
366 {
367 #if defined(HAVE_DAEMON) && !defined(DEPRECATED_DAEMON)
368         /* use POSIX daemon(3) function */
369         if(daemon(1, 0) != 0)
370                 fatal_exit("daemon failed: %s", strerror(errno));
371 #else /* no HAVE_DAEMON */
372 #ifdef HAVE_FORK
373         int fd;
374         /* Take off... */
375         switch (fork()) {
376                 case 0:
377                         break;
378                 case -1:
379                         fatal_exit("fork failed: %s", strerror(errno));
380                 default:
381                         /* exit interactive session */
382                         exit(0);
383         }
384         /* detach */
385 #ifdef HAVE_SETSID
386         if(setsid() == -1)
387                 fatal_exit("setsid() failed: %s", strerror(errno));
388 #endif
389         if ((fd = open("/dev/null", O_RDWR, 0)) != -1) {
390                 (void)dup2(fd, STDIN_FILENO);
391                 (void)dup2(fd, STDOUT_FILENO);
392                 (void)dup2(fd, STDERR_FILENO);
393                 if (fd > 2)
394                         (void)close(fd);
395         }
396 #endif /* HAVE_FORK */
397 #endif /* HAVE_DAEMON */
398 }
399
400 /** daemonize, drop user priviliges and chroot if needed */
401 static void
402 perform_setup(struct daemon* daemon, struct config_file* cfg, int debug_mode,
403         const char** cfgfile)
404 {
405 #ifdef HAVE_KILL
406         int pidinchroot;
407 #endif
408 #ifdef HAVE_GETPWNAM
409         struct passwd *pwd = NULL;
410
411         if(cfg->username && cfg->username[0]) {
412                 if((pwd = getpwnam(cfg->username)) == NULL)
413                         fatal_exit("user '%s' does not exist.", cfg->username);
414                 /* endpwent below, in case we need pwd for setusercontext */
415         }
416 #endif
417 #ifdef UB_ON_WINDOWS
418         w_config_adjust_directory(cfg);
419 #endif
420
421         /* init syslog (as root) if needed, before daemonize, otherwise
422          * a fork error could not be printed since daemonize closed stderr.*/
423         if(cfg->use_syslog) {
424                 log_init(cfg->logfile, cfg->use_syslog, cfg->chrootdir);
425         }
426         /* if using a logfile, we cannot open it because the logfile would
427          * be created with the wrong permissions, we cannot chown it because
428          * we cannot chown system logfiles, so we do not open at all.
429          * So, using a logfile, the user does not see errors unless -d is
430          * given to unbound on the commandline. */
431
432         /* read ssl keys while superuser and outside chroot */
433 #ifdef HAVE_SSL
434         if(!(daemon->rc = daemon_remote_create(cfg)))
435                 fatal_exit("could not set up remote-control");
436         if(cfg->ssl_service_key && cfg->ssl_service_key[0]) {
437                 if(!(daemon->listen_sslctx = listen_sslctx_create(
438                         cfg->ssl_service_key, cfg->ssl_service_pem, NULL)))
439                         fatal_exit("could not set up listen SSL_CTX");
440         }
441         if(!(daemon->connect_sslctx = connect_sslctx_create(NULL, NULL, NULL)))
442                 fatal_exit("could not set up connect SSL_CTX");
443 #endif
444
445 #ifdef HAVE_KILL
446         /* true if pidfile is inside chrootdir, or nochroot */
447         pidinchroot = !(cfg->chrootdir && cfg->chrootdir[0]) ||
448                                 (cfg->chrootdir && cfg->chrootdir[0] &&
449                                 strncmp(cfg->pidfile, cfg->chrootdir,
450                                 strlen(cfg->chrootdir))==0);
451
452         /* check old pid file before forking */
453         if(cfg->pidfile && cfg->pidfile[0]) {
454                 /* calculate position of pidfile */
455                 if(cfg->pidfile[0] == '/')
456                         daemon->pidfile = strdup(cfg->pidfile);
457                 else    daemon->pidfile = fname_after_chroot(cfg->pidfile, 
458                                 cfg, 1);
459                 if(!daemon->pidfile)
460                         fatal_exit("pidfile alloc: out of memory");
461                 checkoldpid(daemon->pidfile, pidinchroot);
462         }
463 #endif
464
465         /* daemonize because pid is needed by the writepid func */
466         if(!debug_mode && cfg->do_daemonize) {
467                 detach();
468         }
469
470         /* write new pidfile (while still root, so can be outside chroot) */
471 #ifdef HAVE_KILL
472         if(cfg->pidfile && cfg->pidfile[0]) {
473                 writepid(daemon->pidfile, getpid());
474                 if(cfg->username && cfg->username[0] && cfg_uid != (uid_t)-1 &&
475                         pidinchroot) {
476 #  ifdef HAVE_CHOWN
477                         if(chown(daemon->pidfile, cfg_uid, cfg_gid) == -1) {
478                                 verbose(VERB_QUERY, "cannot chown %u.%u %s: %s",
479                                         (unsigned)cfg_uid, (unsigned)cfg_gid,
480                                         daemon->pidfile, strerror(errno));
481                         }
482 #  endif /* HAVE_CHOWN */
483                 }
484         }
485 #else
486         (void)daemon;
487 #endif /* HAVE_KILL */
488
489         /* Set user context */
490 #ifdef HAVE_GETPWNAM
491         if(cfg->username && cfg->username[0] && cfg_uid != (uid_t)-1) {
492 #ifdef HAVE_SETUSERCONTEXT
493                 /* setusercontext does initgroups, setuid, setgid, and
494                  * also resource limits from login config, but we
495                  * still call setresuid, setresgid to be sure to set all uid*/
496                 if(setusercontext(NULL, pwd, cfg_uid, (unsigned)
497                         LOGIN_SETALL & ~LOGIN_SETUSER & ~LOGIN_SETGROUP) != 0)
498                         log_warn("unable to setusercontext %s: %s",
499                                 cfg->username, strerror(errno));
500 #endif /* HAVE_SETUSERCONTEXT */
501         }
502 #endif /* HAVE_GETPWNAM */
503
504         /* box into the chroot */
505 #ifdef HAVE_CHROOT
506         if(cfg->chrootdir && cfg->chrootdir[0]) {
507                 if(chdir(cfg->chrootdir)) {
508                         fatal_exit("unable to chdir to chroot %s: %s",
509                                 cfg->chrootdir, strerror(errno));
510                 }
511                 verbose(VERB_QUERY, "chdir to %s", cfg->chrootdir);
512                 if(chroot(cfg->chrootdir))
513                         fatal_exit("unable to chroot to %s: %s", 
514                                 cfg->chrootdir, strerror(errno));
515                 if(chdir("/"))
516                         fatal_exit("unable to chdir to / in chroot %s: %s",
517                                 cfg->chrootdir, strerror(errno));
518                 verbose(VERB_QUERY, "chroot to %s", cfg->chrootdir);
519                 if(strncmp(*cfgfile, cfg->chrootdir, 
520                         strlen(cfg->chrootdir)) == 0) 
521                         (*cfgfile) += strlen(cfg->chrootdir);
522
523                 /* adjust stored pidfile for chroot */
524                 if(daemon->pidfile && daemon->pidfile[0] && 
525                         strncmp(daemon->pidfile, cfg->chrootdir,
526                         strlen(cfg->chrootdir))==0) {
527                         char* old = daemon->pidfile;
528                         daemon->pidfile = strdup(old+strlen(cfg->chrootdir));
529                         free(old);
530                         if(!daemon->pidfile)
531                                 log_err("out of memory in pidfile adjust");
532                 }
533                 daemon->chroot = strdup(cfg->chrootdir);
534                 if(!daemon->chroot)
535                         log_err("out of memory in daemon chroot dir storage");
536         }
537 #else
538         (void)cfgfile;
539 #endif
540         /* change to working directory inside chroot */
541         if(cfg->directory && cfg->directory[0]) {
542                 char* dir = cfg->directory;
543                 if(cfg->chrootdir && cfg->chrootdir[0] &&
544                         strncmp(dir, cfg->chrootdir, 
545                         strlen(cfg->chrootdir)) == 0)
546                         dir += strlen(cfg->chrootdir);
547                 if(dir[0]) {
548                         if(chdir(dir)) {
549                                 fatal_exit("Could not chdir to %s: %s",
550                                         dir, strerror(errno));
551                         }
552                         verbose(VERB_QUERY, "chdir to %s", dir);
553                 }
554         }
555
556         /* drop permissions after chroot, getpwnam, pidfile, syslog done*/
557 #ifdef HAVE_GETPWNAM
558         if(cfg->username && cfg->username[0] && cfg_uid != (uid_t)-1) {
559 #  ifdef HAVE_INITGROUPS
560                 if(initgroups(cfg->username, cfg_gid) != 0)
561                         log_warn("unable to initgroups %s: %s",
562                                 cfg->username, strerror(errno));
563 #  endif /* HAVE_INITGROUPS */
564 #  ifdef HAVE_ENDPWENT
565                 endpwent();
566 #  endif
567
568 #ifdef HAVE_SETRESGID
569                 if(setresgid(cfg_gid,cfg_gid,cfg_gid) != 0)
570 #elif defined(HAVE_SETREGID) && !defined(DARWIN_BROKEN_SETREUID)
571                 if(setregid(cfg_gid,cfg_gid) != 0)
572 #else /* use setgid */
573                 if(setgid(cfg_gid) != 0)
574 #endif /* HAVE_SETRESGID */
575                         fatal_exit("unable to set group id of %s: %s", 
576                                 cfg->username, strerror(errno));
577 #ifdef HAVE_SETRESUID
578                 if(setresuid(cfg_uid,cfg_uid,cfg_uid) != 0)
579 #elif defined(HAVE_SETREUID) && !defined(DARWIN_BROKEN_SETREUID)
580                 if(setreuid(cfg_uid,cfg_uid) != 0)
581 #else /* use setuid */
582                 if(setuid(cfg_uid) != 0)
583 #endif /* HAVE_SETRESUID */
584                         fatal_exit("unable to set user id of %s: %s", 
585                                 cfg->username, strerror(errno));
586                 verbose(VERB_QUERY, "drop user privileges, run as %s", 
587                         cfg->username);
588         }
589 #endif /* HAVE_GETPWNAM */
590         /* file logging inited after chroot,chdir,setuid is done so that 
591          * it would succeed on SIGHUP as well */
592         if(!cfg->use_syslog)
593                 log_init(cfg->logfile, cfg->use_syslog, cfg->chrootdir);
594 }
595
596 /**
597  * Run the daemon. 
598  * @param cfgfile: the config file name.
599  * @param cmdline_verbose: verbosity resulting from commandline -v.
600  *    These increase verbosity as specified in the config file.
601  * @param debug_mode: if set, do not daemonize.
602  * @param log_default_identity: Default identity to report in logs
603  */
604 static void 
605 run_daemon(const char* cfgfile, int cmdline_verbose, int debug_mode, const char* log_default_identity)
606 {
607         struct config_file* cfg = NULL;
608         struct daemon* daemon = NULL;
609         int done_setup = 0;
610
611         if(!(daemon = daemon_init()))
612                 fatal_exit("alloc failure");
613         while(!daemon->need_to_exit) {
614                 if(done_setup)
615                         verbose(VERB_OPS, "Restart of %s.", PACKAGE_STRING);
616                 else    verbose(VERB_OPS, "Start of %s.", PACKAGE_STRING);
617
618                 /* config stuff */
619                 if(!(cfg = config_create()))
620                         fatal_exit("Could not alloc config defaults");
621                 if(!config_read(cfg, cfgfile, daemon->chroot)) {
622                         if(errno != ENOENT)
623                                 fatal_exit("Could not read config file: %s",
624                                         cfgfile);
625                         log_warn("Continuing with default config settings");
626                 }
627                 apply_settings(daemon, cfg, cmdline_verbose, debug_mode, log_default_identity);
628                 if(!done_setup)
629                         config_lookup_uid(cfg);
630         
631                 /* prepare */
632                 if(!daemon_open_shared_ports(daemon))
633                         fatal_exit("could not open ports");
634                 if(!done_setup) { 
635                         perform_setup(daemon, cfg, debug_mode, &cfgfile);
636                         done_setup = 1; 
637                 } else {
638                         /* reopen log after HUP to facilitate log rotation */
639                         if(!cfg->use_syslog)
640                                 log_init(cfg->logfile, 0, cfg->chrootdir);
641                 }
642                 /* work */
643                 daemon_fork(daemon);
644
645                 /* clean up for restart */
646                 verbose(VERB_ALGO, "cleanup.");
647                 daemon_cleanup(daemon);
648                 config_delete(cfg);
649         }
650         verbose(VERB_ALGO, "Exit cleanup.");
651         /* this unlink may not work if the pidfile is located outside
652          * of the chroot/workdir or we no longer have permissions */
653         if(daemon->pidfile) {
654                 int fd;
655                 /* truncate pidfile */
656                 fd = open(daemon->pidfile, O_WRONLY | O_TRUNC, 0644);
657                 if(fd != -1)
658                         close(fd);
659                 /* delete pidfile */
660                 unlink(daemon->pidfile);
661         }
662         daemon_delete(daemon);
663 }
664
665 /** getopt global, in case header files fail to declare it. */
666 extern int optind;
667 /** getopt global, in case header files fail to declare it. */
668 extern char* optarg;
669
670 /**
671  * main program. Set options given commandline arguments.
672  * @param argc: number of commandline arguments.
673  * @param argv: array of commandline arguments.
674  * @return: exit status of the program.
675  */
676 int 
677 main(int argc, char* argv[])
678 {
679         int c;
680         const char* cfgfile = CONFIGFILE;
681         const char* winopt = NULL;
682         const char* log_ident_default;
683         int cmdline_verbose = 0;
684         int debug_mode = 0;
685 #ifdef UB_ON_WINDOWS
686         int cmdline_cfg = 0;
687 #endif
688
689         log_init(NULL, 0, NULL);
690         log_ident_default = strrchr(argv[0],'/')?strrchr(argv[0],'/')+1:argv[0];
691         log_ident_set(log_ident_default);
692         /* parse the options */
693         while( (c=getopt(argc, argv, "c:dhvw:")) != -1) {
694                 switch(c) {
695                 case 'c':
696                         cfgfile = optarg;
697 #ifdef UB_ON_WINDOWS
698                         cmdline_cfg = 1;
699 #endif
700                         break;
701                 case 'v':
702                         cmdline_verbose++;
703                         verbosity++;
704                         break;
705                 case 'd':
706                         debug_mode++;
707                         break;
708                 case 'w':
709                         winopt = optarg;
710                         break;
711                 case '?':
712                 case 'h':
713                 default:
714                         usage();
715                         return 1;
716                 }
717         }
718         argc -= optind;
719         argv += optind;
720
721         if(winopt) {
722 #ifdef UB_ON_WINDOWS
723                 wsvc_command_option(winopt, cfgfile, cmdline_verbose, 
724                         cmdline_cfg);
725 #else
726                 fatal_exit("option not supported");
727 #endif
728         }
729
730         if(argc != 0) {
731                 usage();
732                 return 1;
733         }
734
735         run_daemon(cfgfile, cmdline_verbose, debug_mode, log_ident_default);
736         log_init(NULL, 0, NULL); /* close logfile */
737         return 0;
738 }