No empty .Rs/.Re
[netbsd-mini2440.git] / external / bsd / bind / dist / bin / named / main.c
blob1e6352af5989ed6599dbbf34eb204cd5eec7adf5
1 /* $NetBSD: main.c,v 1.1.1.3 2009/10/25 00:01:32 christos Exp $ */
3 /*
4 * Copyright (C) 2004-2009 Internet Systems Consortium, Inc. ("ISC")
5 * Copyright (C) 1999-2003 Internet Software Consortium.
7 * Permission to use, copy, modify, and/or distribute this software for any
8 * purpose with or without fee is hereby granted, provided that the above
9 * copyright notice and this permission notice appear in all copies.
11 * THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES WITH
12 * REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
13 * AND FITNESS. IN NO EVENT SHALL ISC BE LIABLE FOR ANY SPECIAL, DIRECT,
14 * INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
15 * LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE
16 * OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
17 * PERFORMANCE OF THIS SOFTWARE.
20 /* Id: main.c,v 1.175 2009/10/05 17:30:49 fdupont Exp */
22 /*! \file */
24 #include <config.h>
26 #include <ctype.h>
27 #include <stdlib.h>
28 #include <string.h>
30 #include <isc/app.h>
31 #include <isc/backtrace.h>
32 #include <isc/commandline.h>
33 #include <isc/dir.h>
34 #include <isc/entropy.h>
35 #include <isc/file.h>
36 #include <isc/hash.h>
37 #include <isc/os.h>
38 #include <isc/platform.h>
39 #include <isc/print.h>
40 #include <isc/resource.h>
41 #include <isc/stdio.h>
42 #include <isc/string.h>
43 #include <isc/task.h>
44 #include <isc/timer.h>
45 #include <isc/util.h>
47 #include <isccc/result.h>
49 #include <dns/dispatch.h>
50 #include <dns/name.h>
51 #include <dns/result.h>
52 #include <dns/view.h>
54 #include <dst/result.h>
57 * Defining NS_MAIN provides storage declarations (rather than extern)
58 * for variables in named/globals.h.
60 #define NS_MAIN 1
62 #include <named/builtin.h>
63 #include <named/control.h>
64 #include <named/globals.h> /* Explicit, though named/log.h includes it. */
65 #include <named/interfacemgr.h>
66 #include <named/log.h>
67 #include <named/os.h>
68 #include <named/server.h>
69 #include <named/lwresd.h>
70 #include <named/main.h>
71 #ifdef HAVE_LIBSCF
72 #include <named/ns_smf_globals.h>
73 #endif
76 * Include header files for database drivers here.
78 /* #include "xxdb.h" */
81 * Include DLZ drivers if appropriate.
83 #ifdef DLZ
84 #include <dlz/dlz_drivers.h>
85 #endif
88 * The maximum number of stack frames to dump on assertion failure.
90 #ifndef BACKTRACE_MAXFRAME
91 #define BACKTRACE_MAXFRAME 128
92 #endif
94 static isc_boolean_t want_stats = ISC_FALSE;
95 static char program_name[ISC_DIR_NAMEMAX] = "named";
96 static char absolute_conffile[ISC_DIR_PATHMAX];
97 static char saved_command_line[512];
98 static char version[512];
99 static unsigned int maxsocks = 0;
100 static int maxudp = 0;
102 void
103 ns_main_earlywarning(const char *format, ...) {
104 va_list args;
106 va_start(args, format);
107 if (ns_g_lctx != NULL) {
108 isc_log_vwrite(ns_g_lctx, NS_LOGCATEGORY_GENERAL,
109 NS_LOGMODULE_MAIN, ISC_LOG_WARNING,
110 format, args);
111 } else {
112 fprintf(stderr, "%s: ", program_name);
113 vfprintf(stderr, format, args);
114 fprintf(stderr, "\n");
115 fflush(stderr);
117 va_end(args);
120 void
121 ns_main_earlyfatal(const char *format, ...) {
122 va_list args;
124 va_start(args, format);
125 if (ns_g_lctx != NULL) {
126 isc_log_vwrite(ns_g_lctx, NS_LOGCATEGORY_GENERAL,
127 NS_LOGMODULE_MAIN, ISC_LOG_CRITICAL,
128 format, args);
129 isc_log_write(ns_g_lctx, NS_LOGCATEGORY_GENERAL,
130 NS_LOGMODULE_MAIN, ISC_LOG_CRITICAL,
131 "exiting (due to early fatal error)");
132 } else {
133 fprintf(stderr, "%s: ", program_name);
134 vfprintf(stderr, format, args);
135 fprintf(stderr, "\n");
136 fflush(stderr);
138 va_end(args);
140 exit(1);
143 ISC_PLATFORM_NORETURN_PRE static void
144 assertion_failed(const char *file, int line, isc_assertiontype_t type,
145 const char *cond) ISC_PLATFORM_NORETURN_POST;
147 static void
148 assertion_failed(const char *file, int line, isc_assertiontype_t type,
149 const char *cond)
151 void *tracebuf[BACKTRACE_MAXFRAME];
152 int i, nframes;
153 isc_result_t result;
154 const char *logsuffix = "";
155 const char *fname;
158 * Handle assertion failures.
161 if (ns_g_lctx != NULL) {
163 * Reset the assertion callback in case it is the log
164 * routines causing the assertion.
166 isc_assertion_setcallback(NULL);
168 result = isc_backtrace_gettrace(tracebuf, BACKTRACE_MAXFRAME,
169 &nframes);
170 if (result == ISC_R_SUCCESS && nframes > 0)
171 logsuffix = ", back trace";
172 isc_log_write(ns_g_lctx, NS_LOGCATEGORY_GENERAL,
173 NS_LOGMODULE_MAIN, ISC_LOG_CRITICAL,
174 "%s:%d: %s(%s) failed%s", file, line,
175 isc_assertion_typetotext(type), cond, logsuffix);
176 if (result == ISC_R_SUCCESS) {
177 for (i = 0; i < nframes; i++) {
178 unsigned long offset;
180 fname = NULL;
181 result = isc_backtrace_getsymbol(tracebuf[i],
182 &fname,
183 &offset);
184 if (result == ISC_R_SUCCESS) {
185 isc_log_write(ns_g_lctx,
186 NS_LOGCATEGORY_GENERAL,
187 NS_LOGMODULE_MAIN,
188 ISC_LOG_CRITICAL,
189 "#%d %p in %s()+0x%lx", i,
190 tracebuf[i], fname,
191 offset);
192 } else {
193 isc_log_write(ns_g_lctx,
194 NS_LOGCATEGORY_GENERAL,
195 NS_LOGMODULE_MAIN,
196 ISC_LOG_CRITICAL,
197 "#%d %p in ??", i,
198 tracebuf[i]);
202 isc_log_write(ns_g_lctx, NS_LOGCATEGORY_GENERAL,
203 NS_LOGMODULE_MAIN, ISC_LOG_CRITICAL,
204 "exiting (due to assertion failure)");
205 } else {
206 fprintf(stderr, "%s:%d: %s(%s) failed\n",
207 file, line, isc_assertion_typetotext(type), cond);
208 fflush(stderr);
211 if (ns_g_coreok)
212 abort();
213 exit(1);
216 ISC_PLATFORM_NORETURN_PRE static void
217 library_fatal_error(const char *file, int line, const char *format,
218 va_list args)
219 ISC_FORMAT_PRINTF(3, 0) ISC_PLATFORM_NORETURN_POST;
221 static void
222 library_fatal_error(const char *file, int line, const char *format,
223 va_list args)
226 * Handle isc_error_fatal() calls from our libraries.
229 if (ns_g_lctx != NULL) {
231 * Reset the error callback in case it is the log
232 * routines causing the assertion.
234 isc_error_setfatal(NULL);
236 isc_log_write(ns_g_lctx, NS_LOGCATEGORY_GENERAL,
237 NS_LOGMODULE_MAIN, ISC_LOG_CRITICAL,
238 "%s:%d: fatal error:", file, line);
239 isc_log_vwrite(ns_g_lctx, NS_LOGCATEGORY_GENERAL,
240 NS_LOGMODULE_MAIN, ISC_LOG_CRITICAL,
241 format, args);
242 isc_log_write(ns_g_lctx, NS_LOGCATEGORY_GENERAL,
243 NS_LOGMODULE_MAIN, ISC_LOG_CRITICAL,
244 "exiting (due to fatal error in library)");
245 } else {
246 fprintf(stderr, "%s:%d: fatal error: ", file, line);
247 vfprintf(stderr, format, args);
248 fprintf(stderr, "\n");
249 fflush(stderr);
252 if (ns_g_coreok)
253 abort();
254 exit(1);
257 static void
258 library_unexpected_error(const char *file, int line, const char *format,
259 va_list args) ISC_FORMAT_PRINTF(3, 0);
261 static void
262 library_unexpected_error(const char *file, int line, const char *format,
263 va_list args)
266 * Handle isc_error_unexpected() calls from our libraries.
269 if (ns_g_lctx != NULL) {
270 isc_log_write(ns_g_lctx, NS_LOGCATEGORY_GENERAL,
271 NS_LOGMODULE_MAIN, ISC_LOG_ERROR,
272 "%s:%d: unexpected error:", file, line);
273 isc_log_vwrite(ns_g_lctx, NS_LOGCATEGORY_GENERAL,
274 NS_LOGMODULE_MAIN, ISC_LOG_ERROR,
275 format, args);
276 } else {
277 fprintf(stderr, "%s:%d: fatal error: ", file, line);
278 vfprintf(stderr, format, args);
279 fprintf(stderr, "\n");
280 fflush(stderr);
284 static void
285 lwresd_usage(void) {
286 fprintf(stderr,
287 "usage: lwresd [-4|-6] [-c conffile | -C resolvconffile] "
288 "[-d debuglevel]\n"
289 " [-f|-g] [-n number_of_cpus] [-p port] "
290 "[-P listen-port] [-s]\n"
291 " [-t chrootdir] [-u username] [-i pidfile]\n"
292 " [-m {usage|trace|record|size|mctx}]\n");
295 static void
296 usage(void) {
297 if (ns_g_lwresdonly) {
298 lwresd_usage();
299 return;
301 fprintf(stderr,
302 "usage: named [-4|-6] [-c conffile] [-d debuglevel] "
303 "[-E engine] [-f|-g]\n"
304 " [-n number_of_cpus] [-p port] [-s] "
305 "[-t chrootdir] [-u username]\n"
306 " [-m {usage|trace|record|size|mctx}]\n");
309 static void
310 save_command_line(int argc, char *argv[]) {
311 int i;
312 char *src;
313 char *dst;
314 char *eob;
315 const char truncated[] = "...";
316 isc_boolean_t quoted = ISC_FALSE;
318 dst = saved_command_line;
319 eob = saved_command_line + sizeof(saved_command_line);
321 for (i = 1; i < argc && dst < eob; i++) {
322 *dst++ = ' ';
324 src = argv[i];
325 while (*src != '\0' && dst < eob) {
327 * This won't perfectly produce a shell-independent
328 * pastable command line in all circumstances, but
329 * comes close, and for practical purposes will
330 * nearly always be fine.
332 if (quoted || isalnum(*src & 0xff) ||
333 *src == '-' || *src == '_' ||
334 *src == '.' || *src == '/') {
335 *dst++ = *src++;
336 quoted = ISC_FALSE;
337 } else {
338 *dst++ = '\\';
339 quoted = ISC_TRUE;
344 INSIST(sizeof(saved_command_line) >= sizeof(truncated));
346 if (dst == eob)
347 strcpy(eob - sizeof(truncated), truncated);
348 else
349 *dst = '\0';
352 static int
353 parse_int(char *arg, const char *desc) {
354 char *endp;
355 int tmp;
356 long int ltmp;
358 ltmp = strtol(arg, &endp, 10);
359 tmp = (int) ltmp;
360 if (*endp != '\0')
361 ns_main_earlyfatal("%s '%s' must be numeric", desc, arg);
362 if (tmp < 0 || tmp != ltmp)
363 ns_main_earlyfatal("%s '%s' out of range", desc, arg);
364 return (tmp);
367 static struct flag_def {
368 const char *name;
369 unsigned int value;
370 } mem_debug_flags[] = {
371 { "trace", ISC_MEM_DEBUGTRACE },
372 { "record", ISC_MEM_DEBUGRECORD },
373 { "usage", ISC_MEM_DEBUGUSAGE },
374 { "size", ISC_MEM_DEBUGSIZE },
375 { "mctx", ISC_MEM_DEBUGCTX },
376 { NULL, 0 }
379 static void
380 set_flags(const char *arg, struct flag_def *defs, unsigned int *ret) {
381 for (;;) {
382 const struct flag_def *def;
383 const char *end = strchr(arg, ',');
384 int arglen;
385 if (end == NULL)
386 end = arg + strlen(arg);
387 arglen = end - arg;
388 for (def = defs; def->name != NULL; def++) {
389 if (arglen == (int)strlen(def->name) &&
390 memcmp(arg, def->name, arglen) == 0) {
391 *ret |= def->value;
392 goto found;
395 ns_main_earlyfatal("unrecognized flag '%.*s'", arglen, arg);
396 found:
397 if (*end == '\0')
398 break;
399 arg = end + 1;
403 static void
404 parse_command_line(int argc, char *argv[]) {
405 int ch;
406 int port;
407 isc_boolean_t disable6 = ISC_FALSE;
408 isc_boolean_t disable4 = ISC_FALSE;
410 save_command_line(argc, argv);
412 isc_commandline_errprint = ISC_FALSE;
413 while ((ch = isc_commandline_parse(argc, argv,
414 "46c:C:d:E:fFgi:lm:n:N:p:P:"
415 "sS:t:T:u:vVx:")) != -1) {
416 switch (ch) {
417 case '4':
418 if (disable4)
419 ns_main_earlyfatal("cannot specify -4 and -6");
420 if (isc_net_probeipv4() != ISC_R_SUCCESS)
421 ns_main_earlyfatal("IPv4 not supported by OS");
422 isc_net_disableipv6();
423 disable6 = ISC_TRUE;
424 break;
425 case '6':
426 if (disable6)
427 ns_main_earlyfatal("cannot specify -4 and -6");
428 if (isc_net_probeipv6() != ISC_R_SUCCESS)
429 ns_main_earlyfatal("IPv6 not supported by OS");
430 isc_net_disableipv4();
431 disable4 = ISC_TRUE;
432 break;
433 case 'c':
434 ns_g_conffile = isc_commandline_argument;
435 lwresd_g_conffile = isc_commandline_argument;
436 if (lwresd_g_useresolvconf)
437 ns_main_earlyfatal("cannot specify -c and -C");
438 ns_g_conffileset = ISC_TRUE;
439 break;
440 case 'C':
441 lwresd_g_resolvconffile = isc_commandline_argument;
442 if (ns_g_conffileset)
443 ns_main_earlyfatal("cannot specify -c and -C");
444 lwresd_g_useresolvconf = ISC_TRUE;
445 break;
446 case 'd':
447 ns_g_debuglevel = parse_int(isc_commandline_argument,
448 "debug level");
449 break;
450 case 'E':
451 ns_g_engine = isc_commandline_argument;
452 break;
453 case 'f':
454 ns_g_foreground = ISC_TRUE;
455 break;
456 case 'g':
457 ns_g_foreground = ISC_TRUE;
458 ns_g_logstderr = ISC_TRUE;
459 break;
460 /* XXXBEW -i should be removed */
461 case 'i':
462 lwresd_g_defaultpidfile = isc_commandline_argument;
463 break;
464 case 'l':
465 ns_g_lwresdonly = ISC_TRUE;
466 break;
467 case 'm':
468 set_flags(isc_commandline_argument, mem_debug_flags,
469 &isc_mem_debugging);
470 break;
471 case 'N': /* Deprecated. */
472 case 'n':
473 ns_g_cpus = parse_int(isc_commandline_argument,
474 "number of cpus");
475 if (ns_g_cpus == 0)
476 ns_g_cpus = 1;
477 break;
478 case 'p':
479 port = parse_int(isc_commandline_argument, "port");
480 if (port < 1 || port > 65535)
481 ns_main_earlyfatal("port '%s' out of range",
482 isc_commandline_argument);
483 ns_g_port = port;
484 break;
485 /* XXXBEW Should -P be removed? */
486 case 'P':
487 port = parse_int(isc_commandline_argument, "port");
488 if (port < 1 || port > 65535)
489 ns_main_earlyfatal("port '%s' out of range",
490 isc_commandline_argument);
491 lwresd_g_listenport = port;
492 break;
493 case 's':
494 /* XXXRTH temporary syntax */
495 want_stats = ISC_TRUE;
496 break;
497 case 'S':
498 maxsocks = parse_int(isc_commandline_argument,
499 "max number of sockets");
500 break;
501 case 't':
502 /* XXXJAB should we make a copy? */
503 ns_g_chrootdir = isc_commandline_argument;
504 break;
505 case 'T':
507 * clienttest: make clients single shot with their
508 * own memory context.
510 if (!strcmp(isc_commandline_argument, "clienttest"))
511 ns_g_clienttest = ISC_TRUE;
512 else if (!strcmp(isc_commandline_argument, "maxudp512"))
513 maxudp = 512;
514 else if (!strcmp(isc_commandline_argument, "maxudp1460"))
515 maxudp = 1460;
516 else
517 fprintf(stderr, "unknown -T flag '%s\n",
518 isc_commandline_argument);
519 break;
520 case 'u':
521 ns_g_username = isc_commandline_argument;
522 break;
523 case 'v':
524 printf("BIND %s\n", ns_g_version);
525 exit(0);
526 case 'V':
527 printf("BIND %s built with %s\n", ns_g_version,
528 ns_g_configargs);
529 exit(0);
530 case 'F':
531 /* Reserved for FIPS mode */
532 /* FALLTHROUGH */
533 case '?':
534 usage();
535 if (isc_commandline_option == '?')
536 exit(0);
537 ns_main_earlyfatal("unknown option '-%c'",
538 isc_commandline_option);
539 /* FALLTHROUGH */
540 default:
541 ns_main_earlyfatal("parsing options returned %d", ch);
545 argc -= isc_commandline_index;
546 argv += isc_commandline_index;
548 if (argc > 0) {
549 usage();
550 ns_main_earlyfatal("extra command line arguments");
554 static isc_result_t
555 create_managers(void) {
556 isc_result_t result;
557 unsigned int socks;
559 #ifdef ISC_PLATFORM_USETHREADS
560 if (ns_g_cpus == 0)
561 ns_g_cpus = ns_g_cpus_detected;
562 isc_log_write(ns_g_lctx, NS_LOGCATEGORY_GENERAL, NS_LOGMODULE_SERVER,
563 ISC_LOG_INFO, "found %u CPU%s, using %u worker thread%s",
564 ns_g_cpus_detected, ns_g_cpus_detected == 1 ? "" : "s",
565 ns_g_cpus, ns_g_cpus == 1 ? "" : "s");
566 #else
567 ns_g_cpus = 1;
568 #endif
569 result = isc_taskmgr_create(ns_g_mctx, ns_g_cpus, 0, &ns_g_taskmgr);
570 if (result != ISC_R_SUCCESS) {
571 UNEXPECTED_ERROR(__FILE__, __LINE__,
572 "isc_taskmgr_create() failed: %s",
573 isc_result_totext(result));
574 return (ISC_R_UNEXPECTED);
577 result = isc_timermgr_create(ns_g_mctx, &ns_g_timermgr);
578 if (result != ISC_R_SUCCESS) {
579 UNEXPECTED_ERROR(__FILE__, __LINE__,
580 "isc_timermgr_create() failed: %s",
581 isc_result_totext(result));
582 return (ISC_R_UNEXPECTED);
585 result = isc_socketmgr_create2(ns_g_mctx, &ns_g_socketmgr, maxsocks);
586 if (result != ISC_R_SUCCESS) {
587 UNEXPECTED_ERROR(__FILE__, __LINE__,
588 "isc_socketmgr_create() failed: %s",
589 isc_result_totext(result));
590 return (ISC_R_UNEXPECTED);
592 isc__socketmgr_maxudp(ns_g_socketmgr, maxudp);
593 result = isc_socketmgr_getmaxsockets(ns_g_socketmgr, &socks);
594 if (result == ISC_R_SUCCESS) {
595 isc_log_write(ns_g_lctx, NS_LOGCATEGORY_GENERAL,
596 NS_LOGMODULE_SERVER,
597 ISC_LOG_INFO, "using up to %u sockets", socks);
600 result = isc_entropy_create(ns_g_mctx, &ns_g_entropy);
601 if (result != ISC_R_SUCCESS) {
602 UNEXPECTED_ERROR(__FILE__, __LINE__,
603 "isc_entropy_create() failed: %s",
604 isc_result_totext(result));
605 return (ISC_R_UNEXPECTED);
608 result = isc_hash_create(ns_g_mctx, ns_g_entropy, DNS_NAME_MAXWIRE);
609 if (result != ISC_R_SUCCESS) {
610 UNEXPECTED_ERROR(__FILE__, __LINE__,
611 "isc_hash_create() failed: %s",
612 isc_result_totext(result));
613 return (ISC_R_UNEXPECTED);
616 return (ISC_R_SUCCESS);
619 static void
620 destroy_managers(void) {
621 ns_lwresd_shutdown();
623 isc_entropy_detach(&ns_g_entropy);
624 if (ns_g_fallbackentropy != NULL)
625 isc_entropy_detach(&ns_g_fallbackentropy);
628 * isc_taskmgr_destroy() will block until all tasks have exited,
630 isc_taskmgr_destroy(&ns_g_taskmgr);
631 isc_timermgr_destroy(&ns_g_timermgr);
632 isc_socketmgr_destroy(&ns_g_socketmgr);
635 * isc_hash_destroy() cannot be called as long as a resolver may be
636 * running. Calling this after isc_taskmgr_destroy() ensures the
637 * call is safe.
639 isc_hash_destroy();
642 static void
643 dump_symboltable(void) {
644 int i;
645 isc_result_t result;
646 const char *fname;
647 const void *addr;
649 if (isc__backtrace_nsymbols == 0)
650 return;
652 if (!isc_log_wouldlog(ns_g_lctx, ISC_LOG_DEBUG(99)))
653 return;
655 isc_log_write(ns_g_lctx, NS_LOGCATEGORY_GENERAL, NS_LOGMODULE_MAIN,
656 ISC_LOG_DEBUG(99), "Symbol table:");
658 for (i = 0, result = ISC_R_SUCCESS; result == ISC_R_SUCCESS; i++) {
659 addr = NULL;
660 fname = NULL;
661 result = isc_backtrace_getsymbolfromindex(i, &addr, &fname);
662 if (result == ISC_R_SUCCESS) {
663 isc_log_write(ns_g_lctx, NS_LOGCATEGORY_GENERAL,
664 NS_LOGMODULE_MAIN, ISC_LOG_DEBUG(99),
665 "[%d] %p %s", i, addr, fname);
670 static void
671 setup(void) {
672 isc_result_t result;
673 isc_resourcevalue_t old_openfiles;
674 #ifdef HAVE_LIBSCF
675 char *instance = NULL;
676 #endif
679 * Get the user and group information before changing the root
680 * directory, so the administrator does not need to keep a copy
681 * of the user and group databases in the chroot'ed environment.
683 ns_os_inituserinfo(ns_g_username);
686 * Initialize time conversion information
688 ns_os_tzset();
690 ns_os_opendevnull();
692 #ifdef HAVE_LIBSCF
693 /* Check if named is under smf control, before chroot. */
694 result = ns_smf_get_instance(&instance, 0, ns_g_mctx);
695 /* We don't care about instance, just check if we got one. */
696 if (result == ISC_R_SUCCESS)
697 ns_smf_got_instance = 1;
698 else
699 ns_smf_got_instance = 0;
700 if (instance != NULL)
701 isc_mem_free(ns_g_mctx, instance);
702 #endif /* HAVE_LIBSCF */
704 #ifdef PATH_RANDOMDEV
706 * Initialize system's random device as fallback entropy source
707 * if running chroot'ed.
709 if (ns_g_chrootdir != NULL) {
710 result = isc_entropy_create(ns_g_mctx, &ns_g_fallbackentropy);
711 if (result != ISC_R_SUCCESS)
712 ns_main_earlyfatal("isc_entropy_create() failed: %s",
713 isc_result_totext(result));
715 result = isc_entropy_createfilesource(ns_g_fallbackentropy,
716 PATH_RANDOMDEV);
717 if (result != ISC_R_SUCCESS) {
718 ns_main_earlywarning("could not open pre-chroot "
719 "entropy source %s: %s",
720 PATH_RANDOMDEV,
721 isc_result_totext(result));
722 isc_entropy_detach(&ns_g_fallbackentropy);
725 #endif
727 #ifdef ISC_PLATFORM_USETHREADS
729 * Check for the number of cpu's before ns_os_chroot().
731 ns_g_cpus_detected = isc_os_ncpus();
732 #endif
734 ns_os_chroot(ns_g_chrootdir);
737 * For operating systems which have a capability mechanism, now
738 * is the time to switch to minimal privs and change our user id.
739 * On traditional UNIX systems, this call will be a no-op, and we
740 * will change the user ID after reading the config file the first
741 * time. (We need to read the config file to know which possibly
742 * privileged ports to bind() to.)
744 ns_os_minprivs();
746 result = ns_log_init(ISC_TF(ns_g_username != NULL));
747 if (result != ISC_R_SUCCESS)
748 ns_main_earlyfatal("ns_log_init() failed: %s",
749 isc_result_totext(result));
752 * Now is the time to daemonize (if we're not running in the
753 * foreground). We waited until now because we wanted to get
754 * a valid logging context setup. We cannot daemonize any later,
755 * because calling create_managers() will create threads, which
756 * would be lost after fork().
758 if (!ns_g_foreground)
759 ns_os_daemonize();
762 * We call isc_app_start() here as some versions of FreeBSD's fork()
763 * destroys all the signal handling it sets up.
765 result = isc_app_start();
766 if (result != ISC_R_SUCCESS)
767 ns_main_earlyfatal("isc_app_start() failed: %s",
768 isc_result_totext(result));
770 isc_log_write(ns_g_lctx, NS_LOGCATEGORY_GENERAL, NS_LOGMODULE_MAIN,
771 ISC_LOG_NOTICE, "starting BIND %s%s", ns_g_version,
772 saved_command_line);
774 isc_log_write(ns_g_lctx, NS_LOGCATEGORY_GENERAL, NS_LOGMODULE_MAIN,
775 ISC_LOG_NOTICE, "built with %s", ns_g_configargs);
777 dump_symboltable();
780 * Get the initial resource limits.
782 (void)isc_resource_getlimit(isc_resource_stacksize,
783 &ns_g_initstacksize);
784 (void)isc_resource_getlimit(isc_resource_datasize,
785 &ns_g_initdatasize);
786 (void)isc_resource_getlimit(isc_resource_coresize,
787 &ns_g_initcoresize);
788 (void)isc_resource_getlimit(isc_resource_openfiles,
789 &ns_g_initopenfiles);
792 * System resources cannot effectively be tuned on some systems.
793 * Raise the limit in such cases for safety.
795 old_openfiles = ns_g_initopenfiles;
796 ns_os_adjustnofile();
797 (void)isc_resource_getlimit(isc_resource_openfiles,
798 &ns_g_initopenfiles);
799 if (old_openfiles != ns_g_initopenfiles) {
800 isc_log_write(ns_g_lctx, NS_LOGCATEGORY_GENERAL,
801 NS_LOGMODULE_MAIN, ISC_LOG_NOTICE,
802 "adjusted limit on open files from "
803 "%" ISC_PRINT_QUADFORMAT "u to "
804 "%" ISC_PRINT_QUADFORMAT "u",
805 old_openfiles, ns_g_initopenfiles);
809 * If the named configuration filename is relative, prepend the current
810 * directory's name before possibly changing to another directory.
812 if (! isc_file_isabsolute(ns_g_conffile)) {
813 result = isc_file_absolutepath(ns_g_conffile,
814 absolute_conffile,
815 sizeof(absolute_conffile));
816 if (result != ISC_R_SUCCESS)
817 ns_main_earlyfatal("could not construct absolute path "
818 "of configuration file: %s",
819 isc_result_totext(result));
820 ns_g_conffile = absolute_conffile;
824 * Record the server's startup time.
826 result = isc_time_now(&ns_g_boottime);
827 if (result != ISC_R_SUCCESS)
828 ns_main_earlyfatal("isc_time_now() failed: %s",
829 isc_result_totext(result));
831 result = create_managers();
832 if (result != ISC_R_SUCCESS)
833 ns_main_earlyfatal("create_managers() failed: %s",
834 isc_result_totext(result));
836 ns_builtin_init();
839 * Add calls to register sdb drivers here.
841 /* xxdb_init(); */
843 #ifdef DLZ
845 * Register any DLZ drivers.
847 result = dlz_drivers_init();
848 if (result != ISC_R_SUCCESS)
849 ns_main_earlyfatal("dlz_drivers_init() failed: %s",
850 isc_result_totext(result));
851 #endif
853 ns_server_create(ns_g_mctx, &ns_g_server);
856 static void
857 cleanup(void) {
858 destroy_managers();
860 ns_server_destroy(&ns_g_server);
862 ns_builtin_deinit();
865 * Add calls to unregister sdb drivers here.
867 /* xxdb_clear(); */
869 #ifdef DLZ
871 * Unregister any DLZ drivers.
873 dlz_drivers_clear();
874 #endif
876 dns_name_destroy();
878 isc_log_write(ns_g_lctx, NS_LOGCATEGORY_GENERAL, NS_LOGMODULE_MAIN,
879 ISC_LOG_NOTICE, "exiting");
880 ns_log_shutdown();
883 static char *memstats = NULL;
885 void
886 ns_main_setmemstats(const char *filename) {
888 * Caller has to ensure locking.
891 if (memstats != NULL) {
892 free(memstats);
893 memstats = NULL;
895 if (filename == NULL)
896 return;
897 memstats = malloc(strlen(filename) + 1);
898 if (memstats)
899 strcpy(memstats, filename);
902 #ifdef HAVE_LIBSCF
904 * Get FMRI for the named process.
906 isc_result_t
907 ns_smf_get_instance(char **ins_name, int debug, isc_mem_t *mctx) {
908 scf_handle_t *h = NULL;
909 int namelen;
910 char *instance;
912 REQUIRE(ins_name != NULL && *ins_name == NULL);
914 if ((h = scf_handle_create(SCF_VERSION)) == NULL) {
915 if (debug)
916 UNEXPECTED_ERROR(__FILE__, __LINE__,
917 "scf_handle_create() failed: %s",
918 scf_strerror(scf_error()));
919 return (ISC_R_FAILURE);
922 if (scf_handle_bind(h) == -1) {
923 if (debug)
924 UNEXPECTED_ERROR(__FILE__, __LINE__,
925 "scf_handle_bind() failed: %s",
926 scf_strerror(scf_error()));
927 scf_handle_destroy(h);
928 return (ISC_R_FAILURE);
931 if ((namelen = scf_myname(h, NULL, 0)) == -1) {
932 if (debug)
933 UNEXPECTED_ERROR(__FILE__, __LINE__,
934 "scf_myname() failed: %s",
935 scf_strerror(scf_error()));
936 scf_handle_destroy(h);
937 return (ISC_R_FAILURE);
940 if ((instance = isc_mem_allocate(mctx, namelen + 1)) == NULL) {
941 UNEXPECTED_ERROR(__FILE__, __LINE__,
942 "ns_smf_get_instance memory "
943 "allocation failed: %s",
944 isc_result_totext(ISC_R_NOMEMORY));
945 scf_handle_destroy(h);
946 return (ISC_R_FAILURE);
949 if (scf_myname(h, instance, namelen + 1) == -1) {
950 if (debug)
951 UNEXPECTED_ERROR(__FILE__, __LINE__,
952 "scf_myname() failed: %s",
953 scf_strerror(scf_error()));
954 scf_handle_destroy(h);
955 isc_mem_free(mctx, instance);
956 return (ISC_R_FAILURE);
959 scf_handle_destroy(h);
960 *ins_name = instance;
961 return (ISC_R_SUCCESS);
963 #endif /* HAVE_LIBSCF */
966 main(int argc, char *argv[]) {
967 isc_result_t result;
968 #ifdef HAVE_LIBSCF
969 char *instance = NULL;
970 #endif
973 * Record version in core image.
974 * strings named.core | grep "named version:"
976 strlcat(version,
977 #if defined(NO_VERSION_DATE) || !defined(__DATE__)
978 "named version: BIND " VERSION,
979 #else
980 "named version: BIND " VERSION " (" __DATE__ ")",
981 #endif
982 sizeof(version));
983 result = isc_file_progname(*argv, program_name, sizeof(program_name));
984 if (result != ISC_R_SUCCESS)
985 ns_main_earlyfatal("program name too long");
987 if (strcmp(program_name, "lwresd") == 0)
988 ns_g_lwresdonly = ISC_TRUE;
990 if (result != ISC_R_SUCCESS)
991 ns_main_earlyfatal("failed to build internal symbol table");
993 isc_assertion_setcallback(assertion_failed);
994 isc_error_setfatal(library_fatal_error);
995 isc_error_setunexpected(library_unexpected_error);
997 ns_os_init(program_name);
999 dns_result_register();
1000 dst_result_register();
1001 isccc_result_register();
1003 parse_command_line(argc, argv);
1006 * Warn about common configuration error.
1008 if (ns_g_chrootdir != NULL) {
1009 int len = strlen(ns_g_chrootdir);
1010 if (strncmp(ns_g_chrootdir, ns_g_conffile, len) == 0 &&
1011 (ns_g_conffile[len] == '/' || ns_g_conffile[len] == '\\'))
1012 ns_main_earlywarning("config filename (-c %s) contains "
1013 "chroot path (-t %s)",
1014 ns_g_conffile, ns_g_chrootdir);
1017 result = isc_mem_create(0, 0, &ns_g_mctx);
1018 if (result != ISC_R_SUCCESS)
1019 ns_main_earlyfatal("isc_mem_create() failed: %s",
1020 isc_result_totext(result));
1021 isc_mem_setname(ns_g_mctx, "main", NULL);
1023 setup();
1026 * Start things running and then wait for a shutdown request
1027 * or reload.
1029 do {
1030 result = isc_app_run();
1032 if (result == ISC_R_RELOAD) {
1033 ns_server_reloadwanted(ns_g_server);
1034 } else if (result != ISC_R_SUCCESS) {
1035 UNEXPECTED_ERROR(__FILE__, __LINE__,
1036 "isc_app_run(): %s",
1037 isc_result_totext(result));
1039 * Force exit.
1041 result = ISC_R_SUCCESS;
1043 } while (result != ISC_R_SUCCESS);
1045 #ifdef HAVE_LIBSCF
1046 if (ns_smf_want_disable == 1) {
1047 result = ns_smf_get_instance(&instance, 1, ns_g_mctx);
1048 if (result == ISC_R_SUCCESS && instance != NULL) {
1049 if (smf_disable_instance(instance, 0) != 0)
1050 UNEXPECTED_ERROR(__FILE__, __LINE__,
1051 "smf_disable_instance() "
1052 "failed for %s : %s",
1053 instance,
1054 scf_strerror(scf_error()));
1056 if (instance != NULL)
1057 isc_mem_free(ns_g_mctx, instance);
1059 #endif /* HAVE_LIBSCF */
1061 cleanup();
1063 if (want_stats) {
1064 isc_mem_stats(ns_g_mctx, stdout);
1065 isc_mutex_stats(stdout);
1068 if (ns_g_memstatistics && memstats != NULL) {
1069 FILE *fp = NULL;
1070 result = isc_stdio_open(memstats, "w", &fp);
1071 if (result == ISC_R_SUCCESS) {
1072 isc_mem_stats(ns_g_mctx, fp);
1073 isc_mutex_stats(fp);
1074 isc_stdio_close(fp);
1077 isc_mem_destroy(&ns_g_mctx);
1078 isc_mem_checkdestroyed(stderr);
1080 ns_main_setmemstats(NULL);
1082 isc_app_finish();
1084 ns_os_closedevnull();
1086 ns_os_shutdown();
1088 return (0);