]> CyberLeo.Net >> Repos - FreeBSD/stable/8.git/blob - contrib/bind9/bin/named/main.c
MFC r362623:
[FreeBSD/stable/8.git] / contrib / bind9 / bin / named / main.c
1 /*
2  * Copyright (C) 2004-2013  Internet Systems Consortium, Inc. ("ISC")
3  * Copyright (C) 1999-2003  Internet Software Consortium.
4  *
5  * Permission to use, copy, modify, and/or distribute this software for any
6  * purpose with or without fee is hereby granted, provided that the above
7  * copyright notice and this permission notice appear in all copies.
8  *
9  * THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES WITH
10  * REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
11  * AND FITNESS.  IN NO EVENT SHALL ISC BE LIABLE FOR ANY SPECIAL, DIRECT,
12  * INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
13  * LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE
14  * OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
15  * PERFORMANCE OF THIS SOFTWARE.
16  */
17
18 /* $Id: main.c,v 1.180.14.4 2011/11/05 00:45:52 each Exp $ */
19
20 /*! \file */
21
22 #include <config.h>
23
24 #include <ctype.h>
25 #include <stdlib.h>
26 #include <string.h>
27
28 #include <isc/app.h>
29 #include <isc/backtrace.h>
30 #include <isc/commandline.h>
31 #include <isc/dir.h>
32 #include <isc/entropy.h>
33 #include <isc/file.h>
34 #include <isc/hash.h>
35 #include <isc/os.h>
36 #include <isc/platform.h>
37 #include <isc/print.h>
38 #include <isc/resource.h>
39 #include <isc/stdio.h>
40 #include <isc/string.h>
41 #include <isc/task.h>
42 #include <isc/timer.h>
43 #include <isc/util.h>
44
45 #include <isccc/result.h>
46
47 #include <dns/dispatch.h>
48 #include <dns/name.h>
49 #include <dns/result.h>
50 #include <dns/view.h>
51
52 #include <dst/result.h>
53
54 #include <dlz/dlz_dlopen_driver.h>
55
56 /*
57  * Defining NS_MAIN provides storage declarations (rather than extern)
58  * for variables in named/globals.h.
59  */
60 #define NS_MAIN 1
61
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
74
75 #ifdef OPENSSL
76 #include <openssl/opensslv.h>
77 #endif
78 #ifdef HAVE_LIBXML2
79 #include <libxml/xmlversion.h>
80 #endif
81 /*
82  * Include header files for database drivers here.
83  */
84 /* #include "xxdb.h" */
85
86 #ifdef CONTRIB_DLZ
87 /*
88  * Include contributed DLZ drivers if appropriate.
89  */
90 #include <dlz/dlz_drivers.h>
91 #endif
92
93 /*
94  * The maximum number of stack frames to dump on assertion failure.
95  */
96 #ifndef BACKTRACE_MAXFRAME
97 #define BACKTRACE_MAXFRAME 128
98 #endif
99
100 static isc_boolean_t    want_stats = ISC_FALSE;
101 static char             program_name[ISC_DIR_NAMEMAX] = "named";
102 static char             absolute_conffile[ISC_DIR_PATHMAX];
103 static char             saved_command_line[512];
104 static char             version[512];
105 static unsigned int     maxsocks = 0;
106 static int              maxudp = 0;
107
108 void
109 ns_main_earlywarning(const char *format, ...) {
110         va_list args;
111
112         va_start(args, format);
113         if (ns_g_lctx != NULL) {
114                 isc_log_vwrite(ns_g_lctx, NS_LOGCATEGORY_GENERAL,
115                                NS_LOGMODULE_MAIN, ISC_LOG_WARNING,
116                                format, args);
117         } else {
118                 fprintf(stderr, "%s: ", program_name);
119                 vfprintf(stderr, format, args);
120                 fprintf(stderr, "\n");
121                 fflush(stderr);
122         }
123         va_end(args);
124 }
125
126 void
127 ns_main_earlyfatal(const char *format, ...) {
128         va_list args;
129
130         va_start(args, format);
131         if (ns_g_lctx != NULL) {
132                 isc_log_vwrite(ns_g_lctx, NS_LOGCATEGORY_GENERAL,
133                                NS_LOGMODULE_MAIN, ISC_LOG_CRITICAL,
134                                format, args);
135                 isc_log_write(ns_g_lctx, NS_LOGCATEGORY_GENERAL,
136                                NS_LOGMODULE_MAIN, ISC_LOG_CRITICAL,
137                                "exiting (due to early fatal error)");
138         } else {
139                 fprintf(stderr, "%s: ", program_name);
140                 vfprintf(stderr, format, args);
141                 fprintf(stderr, "\n");
142                 fflush(stderr);
143         }
144         va_end(args);
145
146         exit(1);
147 }
148
149 ISC_PLATFORM_NORETURN_PRE static void
150 assertion_failed(const char *file, int line, isc_assertiontype_t type,
151                  const char *cond) ISC_PLATFORM_NORETURN_POST;
152
153 static void
154 assertion_failed(const char *file, int line, isc_assertiontype_t type,
155                  const char *cond)
156 {
157         void *tracebuf[BACKTRACE_MAXFRAME];
158         int i, nframes;
159         isc_result_t result;
160         const char *logsuffix = "";
161         const char *fname;
162
163         /*
164          * Handle assertion failures.
165          */
166
167         if (ns_g_lctx != NULL) {
168                 /*
169                  * Reset the assertion callback in case it is the log
170                  * routines causing the assertion.
171                  */
172                 isc_assertion_setcallback(NULL);
173
174                 result = isc_backtrace_gettrace(tracebuf, BACKTRACE_MAXFRAME,
175                                                 &nframes);
176                 if (result == ISC_R_SUCCESS && nframes > 0)
177                         logsuffix = ", back trace";
178                 isc_log_write(ns_g_lctx, NS_LOGCATEGORY_GENERAL,
179                               NS_LOGMODULE_MAIN, ISC_LOG_CRITICAL,
180                               "%s:%d: %s(%s) failed%s", file, line,
181                               isc_assertion_typetotext(type), cond, logsuffix);
182                 if (result == ISC_R_SUCCESS) {
183                         for (i = 0; i < nframes; i++) {
184                                 unsigned long offset;
185
186                                 fname = NULL;
187                                 result = isc_backtrace_getsymbol(tracebuf[i],
188                                                                  &fname,
189                                                                  &offset);
190                                 if (result == ISC_R_SUCCESS) {
191                                         isc_log_write(ns_g_lctx,
192                                                       NS_LOGCATEGORY_GENERAL,
193                                                       NS_LOGMODULE_MAIN,
194                                                       ISC_LOG_CRITICAL,
195                                                       "#%d %p in %s()+0x%lx", i,
196                                                       tracebuf[i], fname,
197                                                       offset);
198                                 } else {
199                                         isc_log_write(ns_g_lctx,
200                                                       NS_LOGCATEGORY_GENERAL,
201                                                       NS_LOGMODULE_MAIN,
202                                                       ISC_LOG_CRITICAL,
203                                                       "#%d %p in ??", i,
204                                                       tracebuf[i]);
205                                 }
206                         }
207                 }
208                 isc_log_write(ns_g_lctx, NS_LOGCATEGORY_GENERAL,
209                               NS_LOGMODULE_MAIN, ISC_LOG_CRITICAL,
210                               "exiting (due to assertion failure)");
211         } else {
212                 fprintf(stderr, "%s:%d: %s(%s) failed\n",
213                         file, line, isc_assertion_typetotext(type), cond);
214                 fflush(stderr);
215         }
216
217         if (ns_g_coreok)
218                 abort();
219         exit(1);
220 }
221
222 ISC_PLATFORM_NORETURN_PRE static void
223 library_fatal_error(const char *file, int line, const char *format,
224                     va_list args)
225 ISC_FORMAT_PRINTF(3, 0) ISC_PLATFORM_NORETURN_POST;
226
227 static void
228 library_fatal_error(const char *file, int line, const char *format,
229                     va_list args)
230 {
231         /*
232          * Handle isc_error_fatal() calls from our libraries.
233          */
234
235         if (ns_g_lctx != NULL) {
236                 /*
237                  * Reset the error callback in case it is the log
238                  * routines causing the assertion.
239                  */
240                 isc_error_setfatal(NULL);
241
242                 isc_log_write(ns_g_lctx, NS_LOGCATEGORY_GENERAL,
243                               NS_LOGMODULE_MAIN, ISC_LOG_CRITICAL,
244                               "%s:%d: fatal error:", file, line);
245                 isc_log_vwrite(ns_g_lctx, NS_LOGCATEGORY_GENERAL,
246                                NS_LOGMODULE_MAIN, ISC_LOG_CRITICAL,
247                                format, args);
248                 isc_log_write(ns_g_lctx, NS_LOGCATEGORY_GENERAL,
249                               NS_LOGMODULE_MAIN, ISC_LOG_CRITICAL,
250                               "exiting (due to fatal error in library)");
251         } else {
252                 fprintf(stderr, "%s:%d: fatal error: ", file, line);
253                 vfprintf(stderr, format, args);
254                 fprintf(stderr, "\n");
255                 fflush(stderr);
256         }
257
258         if (ns_g_coreok)
259                 abort();
260         exit(1);
261 }
262
263 static void
264 library_unexpected_error(const char *file, int line, const char *format,
265                          va_list args) ISC_FORMAT_PRINTF(3, 0);
266
267 static void
268 library_unexpected_error(const char *file, int line, const char *format,
269                          va_list args)
270 {
271         /*
272          * Handle isc_error_unexpected() calls from our libraries.
273          */
274
275         if (ns_g_lctx != NULL) {
276                 isc_log_write(ns_g_lctx, NS_LOGCATEGORY_GENERAL,
277                               NS_LOGMODULE_MAIN, ISC_LOG_ERROR,
278                               "%s:%d: unexpected error:", file, line);
279                 isc_log_vwrite(ns_g_lctx, NS_LOGCATEGORY_GENERAL,
280                                NS_LOGMODULE_MAIN, ISC_LOG_ERROR,
281                                format, args);
282         } else {
283                 fprintf(stderr, "%s:%d: fatal error: ", file, line);
284                 vfprintf(stderr, format, args);
285                 fprintf(stderr, "\n");
286                 fflush(stderr);
287         }
288 }
289
290 static void
291 lwresd_usage(void) {
292         fprintf(stderr,
293                 "usage: lwresd [-4|-6] [-c conffile | -C resolvconffile] "
294                 "[-d debuglevel]\n"
295                 "              [-f|-g] [-n number_of_cpus] [-p port] "
296                 "[-P listen-port] [-s]\n"
297                 "              [-t chrootdir] [-u username] [-i pidfile]\n"
298                 "              [-m {usage|trace|record|size|mctx}]\n");
299 }
300
301 static void
302 usage(void) {
303         if (ns_g_lwresdonly) {
304                 lwresd_usage();
305                 return;
306         }
307         fprintf(stderr,
308                 "usage: named [-4|-6] [-c conffile] [-d debuglevel] "
309                 "[-E engine] [-f|-g]\n"
310                 "             [-n number_of_cpus] [-p port] [-s] "
311                 "[-t chrootdir] [-u username]\n"
312                 "             [-m {usage|trace|record|size|mctx}]\n");
313 }
314
315 static void
316 save_command_line(int argc, char *argv[]) {
317         int i;
318         char *src;
319         char *dst;
320         char *eob;
321         const char truncated[] = "...";
322         isc_boolean_t quoted = ISC_FALSE;
323
324         dst = saved_command_line;
325         eob = saved_command_line + sizeof(saved_command_line);
326
327         for (i = 1; i < argc && dst < eob; i++) {
328                 *dst++ = ' ';
329
330                 src = argv[i];
331                 while (*src != '\0' && dst < eob) {
332                         /*
333                          * This won't perfectly produce a shell-independent
334                          * pastable command line in all circumstances, but
335                          * comes close, and for practical purposes will
336                          * nearly always be fine.
337                          */
338                         if (quoted || isalnum(*src & 0xff) ||
339                             *src == '-' || *src == '_' ||
340                             *src == '.' || *src == '/') {
341                                 *dst++ = *src++;
342                                 quoted = ISC_FALSE;
343                         } else {
344                                 *dst++ = '\\';
345                                 quoted = ISC_TRUE;
346                         }
347                 }
348         }
349
350         INSIST(sizeof(saved_command_line) >= sizeof(truncated));
351
352         if (dst == eob)
353                 strcpy(eob - sizeof(truncated), truncated);
354         else
355                 *dst = '\0';
356 }
357
358 static int
359 parse_int(char *arg, const char *desc) {
360         char *endp;
361         int tmp;
362         long int ltmp;
363
364         ltmp = strtol(arg, &endp, 10);
365         tmp = (int) ltmp;
366         if (*endp != '\0')
367                 ns_main_earlyfatal("%s '%s' must be numeric", desc, arg);
368         if (tmp < 0 || tmp != ltmp)
369                 ns_main_earlyfatal("%s '%s' out of range", desc, arg);
370         return (tmp);
371 }
372
373 static struct flag_def {
374         const char *name;
375         unsigned int value;
376 } mem_debug_flags[] = {
377         { "trace",  ISC_MEM_DEBUGTRACE },
378         { "record", ISC_MEM_DEBUGRECORD },
379         { "usage", ISC_MEM_DEBUGUSAGE },
380         { "size", ISC_MEM_DEBUGSIZE },
381         { "mctx", ISC_MEM_DEBUGCTX },
382         { NULL, 0 }
383 };
384
385 static void
386 set_flags(const char *arg, struct flag_def *defs, unsigned int *ret) {
387         for (;;) {
388                 const struct flag_def *def;
389                 const char *end = strchr(arg, ',');
390                 int arglen;
391                 if (end == NULL)
392                         end = arg + strlen(arg);
393                 arglen = (int)(end - arg);
394                 for (def = defs; def->name != NULL; def++) {
395                         if (arglen == (int)strlen(def->name) &&
396                             memcmp(arg, def->name, arglen) == 0) {
397                                 *ret |= def->value;
398                                 goto found;
399                         }
400                 }
401                 ns_main_earlyfatal("unrecognized flag '%.*s'", arglen, arg);
402          found:
403                 if (*end == '\0')
404                         break;
405                 arg = end + 1;
406         }
407 }
408
409 static void
410 parse_command_line(int argc, char *argv[]) {
411         int ch;
412         int port;
413         isc_boolean_t disable6 = ISC_FALSE;
414         isc_boolean_t disable4 = ISC_FALSE;
415
416         save_command_line(argc, argv);
417
418         /* PLEASE keep options synchronized when main is hooked! */
419         isc_commandline_errprint = ISC_FALSE;
420         while ((ch = isc_commandline_parse(argc, argv,
421                                            "46c:C:d:E:fFgi:lm:n:N:p:P:"
422                                            "sS:t:T:u:vVx:")) != -1) {
423                 switch (ch) {
424                 case '4':
425                         if (disable4)
426                                 ns_main_earlyfatal("cannot specify -4 and -6");
427                         if (isc_net_probeipv4() != ISC_R_SUCCESS)
428                                 ns_main_earlyfatal("IPv4 not supported by OS");
429                         isc_net_disableipv6();
430                         disable6 = ISC_TRUE;
431                         break;
432                 case '6':
433                         if (disable6)
434                                 ns_main_earlyfatal("cannot specify -4 and -6");
435                         if (isc_net_probeipv6() != ISC_R_SUCCESS)
436                                 ns_main_earlyfatal("IPv6 not supported by OS");
437                         isc_net_disableipv4();
438                         disable4 = ISC_TRUE;
439                         break;
440                 case 'c':
441                         ns_g_conffile = isc_commandline_argument;
442                         lwresd_g_conffile = isc_commandline_argument;
443                         if (lwresd_g_useresolvconf)
444                                 ns_main_earlyfatal("cannot specify -c and -C");
445                         ns_g_conffileset = ISC_TRUE;
446                         break;
447                 case 'C':
448                         lwresd_g_resolvconffile = isc_commandline_argument;
449                         if (ns_g_conffileset)
450                                 ns_main_earlyfatal("cannot specify -c and -C");
451                         lwresd_g_useresolvconf = ISC_TRUE;
452                         break;
453                 case 'd':
454                         ns_g_debuglevel = parse_int(isc_commandline_argument,
455                                                     "debug level");
456                         break;
457                 case 'E':
458                         ns_g_engine = isc_commandline_argument;
459                         break;
460                 case 'f':
461                         ns_g_foreground = ISC_TRUE;
462                         break;
463                 case 'g':
464                         ns_g_foreground = ISC_TRUE;
465                         ns_g_logstderr = ISC_TRUE;
466                         break;
467                 /* XXXBEW -i should be removed */
468                 case 'i':
469                         lwresd_g_defaultpidfile = isc_commandline_argument;
470                         break;
471                 case 'l':
472                         ns_g_lwresdonly = ISC_TRUE;
473                         break;
474                 case 'm':
475                         set_flags(isc_commandline_argument, mem_debug_flags,
476                                   &isc_mem_debugging);
477                         break;
478                 case 'N': /* Deprecated. */
479                 case 'n':
480                         ns_g_cpus = parse_int(isc_commandline_argument,
481                                               "number of cpus");
482                         if (ns_g_cpus == 0)
483                                 ns_g_cpus = 1;
484                         break;
485                 case 'p':
486                         port = parse_int(isc_commandline_argument, "port");
487                         if (port < 1 || port > 65535)
488                                 ns_main_earlyfatal("port '%s' out of range",
489                                                    isc_commandline_argument);
490                         ns_g_port = port;
491                         break;
492                 /* XXXBEW Should -P be removed? */
493                 case 'P':
494                         port = parse_int(isc_commandline_argument, "port");
495                         if (port < 1 || port > 65535)
496                                 ns_main_earlyfatal("port '%s' out of range",
497                                                    isc_commandline_argument);
498                         lwresd_g_listenport = port;
499                         break;
500                 case 's':
501                         /* XXXRTH temporary syntax */
502                         want_stats = ISC_TRUE;
503                         break;
504                 case 'S':
505                         maxsocks = parse_int(isc_commandline_argument,
506                                              "max number of sockets");
507                         break;
508                 case 't':
509                         /* XXXJAB should we make a copy? */
510                         ns_g_chrootdir = isc_commandline_argument;
511                         break;
512                 case 'T':       /* NOT DOCUMENTED */
513                         /*
514                          * clienttest: make clients single shot with their
515                          *             own memory context.
516                          */
517                         if (!strcmp(isc_commandline_argument, "clienttest"))
518                                 ns_g_clienttest = ISC_TRUE;
519                         else if (!strcmp(isc_commandline_argument, "nosoa"))
520                                 ns_g_nosoa = ISC_TRUE;
521                         else if (!strcmp(isc_commandline_argument, "noaa"))
522                                 ns_g_noaa = ISC_TRUE;
523                         else if (!strcmp(isc_commandline_argument, "maxudp512"))
524                                 maxudp = 512;
525                         else if (!strcmp(isc_commandline_argument, "maxudp1460"))
526                                 maxudp = 1460;
527                         else if (!strcmp(isc_commandline_argument, "nosyslog"))
528                                 ns_g_nosyslog = ISC_TRUE;
529                         else if (!strcmp(isc_commandline_argument, "nonearest"))
530                                 ns_g_nonearest = ISC_TRUE;
531                         else
532                                 fprintf(stderr, "unknown -T flag '%s\n",
533                                         isc_commandline_argument);
534                         break;
535                 case 'u':
536                         ns_g_username = isc_commandline_argument;
537                         break;
538                 case 'v':
539                         printf("%s %s", ns_g_product, ns_g_version);
540                         if (*ns_g_description != 0)
541                                 printf(" %s", ns_g_description);
542                         printf("\n");
543                         exit(0);
544                 case 'V':
545                         printf("%s %s", ns_g_product, ns_g_version);
546                         if (*ns_g_description != 0)
547                                 printf(" %s", ns_g_description);
548                         printf(" <id:%s> built by %s with %s\n", ns_g_srcid,
549                                ns_g_builder, ns_g_configargs);
550 #ifdef __clang__
551                         printf("compiled by CLANG %s\n", __VERSION__);
552 #else
553 #if defined(__ICC) || defined(__INTEL_COMPILER)
554                         printf("compiled by ICC %s\n", __VERSION__);
555 #else
556 #ifdef __GNUC__
557                         printf("compiled by GCC %s\n", __VERSION__);
558 #endif
559 #endif
560 #endif
561 #ifdef _MSC_VER
562                         printf("compiled by MSVC %d\n", _MSC_VER);
563 #endif
564 #ifdef __SUNPRO_C
565                         printf("compiled by Solaris Studio %x\n", __SUNPRO_C);
566 #endif
567 #ifdef OPENSSL
568                         printf("using OpenSSL version: %s\n",
569                                OPENSSL_VERSION_TEXT);
570 #endif
571 #ifdef HAVE_LIBXML2
572                         printf("using libxml2 version: %s\n",
573                                LIBXML_DOTTED_VERSION);
574 #endif
575                         exit(0);
576                 case 'F':
577                         /* Reserved for FIPS mode */
578                         /* FALLTHROUGH */
579                 case '?':
580                         usage();
581                         if (isc_commandline_option == '?')
582                                 exit(0);
583                         ns_main_earlyfatal("unknown option '-%c'",
584                                            isc_commandline_option);
585                         /* FALLTHROUGH */
586                 default:
587                         ns_main_earlyfatal("parsing options returned %d", ch);
588                 }
589         }
590
591         argc -= isc_commandline_index;
592         argv += isc_commandline_index;
593         POST(argv);
594
595         if (argc > 0) {
596                 usage();
597                 ns_main_earlyfatal("extra command line arguments");
598         }
599 }
600
601 static isc_result_t
602 create_managers(void) {
603         isc_result_t result;
604         unsigned int socks;
605
606 #ifdef ISC_PLATFORM_USETHREADS
607         if (ns_g_cpus == 0)
608                 ns_g_cpus = ns_g_cpus_detected;
609         isc_log_write(ns_g_lctx, NS_LOGCATEGORY_GENERAL, NS_LOGMODULE_SERVER,
610                       ISC_LOG_INFO, "found %u CPU%s, using %u worker thread%s",
611                       ns_g_cpus_detected, ns_g_cpus_detected == 1 ? "" : "s",
612                       ns_g_cpus, ns_g_cpus == 1 ? "" : "s");
613 #else
614         ns_g_cpus = 1;
615 #endif
616         result = isc_taskmgr_create(ns_g_mctx, ns_g_cpus, 0, &ns_g_taskmgr);
617         if (result != ISC_R_SUCCESS) {
618                 UNEXPECTED_ERROR(__FILE__, __LINE__,
619                                  "isc_taskmgr_create() failed: %s",
620                                  isc_result_totext(result));
621                 return (ISC_R_UNEXPECTED);
622         }
623
624         result = isc_timermgr_create(ns_g_mctx, &ns_g_timermgr);
625         if (result != ISC_R_SUCCESS) {
626                 UNEXPECTED_ERROR(__FILE__, __LINE__,
627                                  "isc_timermgr_create() failed: %s",
628                                  isc_result_totext(result));
629                 return (ISC_R_UNEXPECTED);
630         }
631
632         result = isc_socketmgr_create2(ns_g_mctx, &ns_g_socketmgr, maxsocks);
633         if (result != ISC_R_SUCCESS) {
634                 UNEXPECTED_ERROR(__FILE__, __LINE__,
635                                  "isc_socketmgr_create() failed: %s",
636                                  isc_result_totext(result));
637                 return (ISC_R_UNEXPECTED);
638         }
639         isc__socketmgr_maxudp(ns_g_socketmgr, maxudp);
640         result = isc_socketmgr_getmaxsockets(ns_g_socketmgr, &socks);
641         if (result == ISC_R_SUCCESS) {
642                 isc_log_write(ns_g_lctx, NS_LOGCATEGORY_GENERAL,
643                               NS_LOGMODULE_SERVER,
644                               ISC_LOG_INFO, "using up to %u sockets", socks);
645         }
646
647         result = isc_entropy_create(ns_g_mctx, &ns_g_entropy);
648         if (result != ISC_R_SUCCESS) {
649                 UNEXPECTED_ERROR(__FILE__, __LINE__,
650                                  "isc_entropy_create() failed: %s",
651                                  isc_result_totext(result));
652                 return (ISC_R_UNEXPECTED);
653         }
654
655         result = isc_hash_create(ns_g_mctx, ns_g_entropy, DNS_NAME_MAXWIRE);
656         if (result != ISC_R_SUCCESS) {
657                 UNEXPECTED_ERROR(__FILE__, __LINE__,
658                                  "isc_hash_create() failed: %s",
659                                  isc_result_totext(result));
660                 return (ISC_R_UNEXPECTED);
661         }
662
663         return (ISC_R_SUCCESS);
664 }
665
666 static void
667 destroy_managers(void) {
668         ns_lwresd_shutdown();
669
670         isc_entropy_detach(&ns_g_entropy);
671         if (ns_g_fallbackentropy != NULL)
672                 isc_entropy_detach(&ns_g_fallbackentropy);
673
674         /*
675          * isc_taskmgr_destroy() will block until all tasks have exited,
676          */
677         isc_taskmgr_destroy(&ns_g_taskmgr);
678         isc_timermgr_destroy(&ns_g_timermgr);
679         isc_socketmgr_destroy(&ns_g_socketmgr);
680
681         /*
682          * isc_hash_destroy() cannot be called as long as a resolver may be
683          * running.  Calling this after isc_taskmgr_destroy() ensures the
684          * call is safe.
685          */
686         isc_hash_destroy();
687 }
688
689 static void
690 dump_symboltable() {
691         int i;
692         isc_result_t result;
693         const char *fname;
694         const void *addr;
695
696         if (isc__backtrace_nsymbols == 0)
697                 return;
698
699         if (!isc_log_wouldlog(ns_g_lctx, ISC_LOG_DEBUG(99)))
700                 return;
701
702         isc_log_write(ns_g_lctx, NS_LOGCATEGORY_GENERAL, NS_LOGMODULE_MAIN,
703                       ISC_LOG_DEBUG(99), "Symbol table:");
704
705         for (i = 0, result = ISC_R_SUCCESS; result == ISC_R_SUCCESS; i++) {
706                 addr = NULL;
707                 fname = NULL;
708                 result = isc_backtrace_getsymbolfromindex(i, &addr, &fname);
709                 if (result == ISC_R_SUCCESS) {
710                         isc_log_write(ns_g_lctx, NS_LOGCATEGORY_GENERAL,
711                                       NS_LOGMODULE_MAIN, ISC_LOG_DEBUG(99),
712                                       "[%d] %p %s", i, addr, fname);
713                 }
714         }
715 }
716
717 static void
718 setup(void) {
719         isc_result_t result;
720         isc_resourcevalue_t old_openfiles;
721 #ifdef HAVE_LIBSCF
722         char *instance = NULL;
723 #endif
724
725         /*
726          * Get the user and group information before changing the root
727          * directory, so the administrator does not need to keep a copy
728          * of the user and group databases in the chroot'ed environment.
729          */
730         ns_os_inituserinfo(ns_g_username);
731
732         /*
733          * Initialize time conversion information
734          */
735         ns_os_tzset();
736
737         ns_os_opendevnull();
738
739 #ifdef HAVE_LIBSCF
740         /* Check if named is under smf control, before chroot. */
741         result = ns_smf_get_instance(&instance, 0, ns_g_mctx);
742         /* We don't care about instance, just check if we got one. */
743         if (result == ISC_R_SUCCESS)
744                 ns_smf_got_instance = 1;
745         else
746                 ns_smf_got_instance = 0;
747         if (instance != NULL)
748                 isc_mem_free(ns_g_mctx, instance);
749 #endif /* HAVE_LIBSCF */
750
751 #ifdef PATH_RANDOMDEV
752         /*
753          * Initialize system's random device as fallback entropy source
754          * if running chroot'ed.
755          */
756         if (ns_g_chrootdir != NULL) {
757                 result = isc_entropy_create(ns_g_mctx, &ns_g_fallbackentropy);
758                 if (result != ISC_R_SUCCESS)
759                         ns_main_earlyfatal("isc_entropy_create() failed: %s",
760                                            isc_result_totext(result));
761
762                 result = isc_entropy_createfilesource(ns_g_fallbackentropy,
763                                                       PATH_RANDOMDEV);
764                 if (result != ISC_R_SUCCESS) {
765                         ns_main_earlywarning("could not open pre-chroot "
766                                              "entropy source %s: %s",
767                                              PATH_RANDOMDEV,
768                                              isc_result_totext(result));
769                         isc_entropy_detach(&ns_g_fallbackentropy);
770                 }
771         }
772 #endif
773
774 #ifdef ISC_PLATFORM_USETHREADS
775         /*
776          * Check for the number of cpu's before ns_os_chroot().
777          */
778         ns_g_cpus_detected = isc_os_ncpus();
779 #endif
780
781         ns_os_chroot(ns_g_chrootdir);
782
783         /*
784          * For operating systems which have a capability mechanism, now
785          * is the time to switch to minimal privs and change our user id.
786          * On traditional UNIX systems, this call will be a no-op, and we
787          * will change the user ID after reading the config file the first
788          * time.  (We need to read the config file to know which possibly
789          * privileged ports to bind() to.)
790          */
791         ns_os_minprivs();
792
793         result = ns_log_init(ISC_TF(ns_g_username != NULL));
794         if (result != ISC_R_SUCCESS)
795                 ns_main_earlyfatal("ns_log_init() failed: %s",
796                                    isc_result_totext(result));
797
798         /*
799          * Now is the time to daemonize (if we're not running in the
800          * foreground).  We waited until now because we wanted to get
801          * a valid logging context setup.  We cannot daemonize any later,
802          * because calling create_managers() will create threads, which
803          * would be lost after fork().
804          */
805         if (!ns_g_foreground)
806                 ns_os_daemonize();
807
808         /*
809          * We call isc_app_start() here as some versions of FreeBSD's fork()
810          * destroys all the signal handling it sets up.
811          */
812         result = isc_app_start();
813         if (result != ISC_R_SUCCESS)
814                 ns_main_earlyfatal("isc_app_start() failed: %s",
815                                    isc_result_totext(result));
816
817         isc_log_write(ns_g_lctx, NS_LOGCATEGORY_GENERAL, NS_LOGMODULE_MAIN,
818                       ISC_LOG_NOTICE, "starting %s %s%s", ns_g_product,
819                       ns_g_version, saved_command_line);
820
821         isc_log_write(ns_g_lctx, NS_LOGCATEGORY_GENERAL, NS_LOGMODULE_MAIN,
822                       ISC_LOG_NOTICE, "built with %s", ns_g_configargs);
823
824         isc_log_write(ns_g_lctx, NS_LOGCATEGORY_GENERAL, NS_LOGMODULE_MAIN,
825                       ISC_LOG_NOTICE,
826                       "----------------------------------------------------");
827         isc_log_write(ns_g_lctx, NS_LOGCATEGORY_GENERAL, NS_LOGMODULE_MAIN,
828                       ISC_LOG_NOTICE,
829                       "BIND 9 is maintained by Internet Systems Consortium,");
830         isc_log_write(ns_g_lctx, NS_LOGCATEGORY_GENERAL, NS_LOGMODULE_MAIN,
831                       ISC_LOG_NOTICE,
832                       "Inc. (ISC), a non-profit 501(c)(3) public-benefit ");
833         isc_log_write(ns_g_lctx, NS_LOGCATEGORY_GENERAL, NS_LOGMODULE_MAIN,
834                       ISC_LOG_NOTICE,
835                       "corporation.  Support and training for BIND 9 are ");
836         isc_log_write(ns_g_lctx, NS_LOGCATEGORY_GENERAL, NS_LOGMODULE_MAIN,
837                       ISC_LOG_NOTICE,
838                       "available at https://www.isc.org/support");
839         isc_log_write(ns_g_lctx, NS_LOGCATEGORY_GENERAL, NS_LOGMODULE_MAIN,
840                       ISC_LOG_NOTICE,
841                       "----------------------------------------------------");
842
843         dump_symboltable();
844
845         /*
846          * Get the initial resource limits.
847          */
848         (void)isc_resource_getlimit(isc_resource_stacksize,
849                                     &ns_g_initstacksize);
850         (void)isc_resource_getlimit(isc_resource_datasize,
851                                     &ns_g_initdatasize);
852         (void)isc_resource_getlimit(isc_resource_coresize,
853                                     &ns_g_initcoresize);
854         (void)isc_resource_getlimit(isc_resource_openfiles,
855                                     &ns_g_initopenfiles);
856
857         /*
858          * System resources cannot effectively be tuned on some systems.
859          * Raise the limit in such cases for safety.
860          */
861         old_openfiles = ns_g_initopenfiles;
862         ns_os_adjustnofile();
863         (void)isc_resource_getlimit(isc_resource_openfiles,
864                                     &ns_g_initopenfiles);
865         if (old_openfiles != ns_g_initopenfiles) {
866                 isc_log_write(ns_g_lctx, NS_LOGCATEGORY_GENERAL,
867                               NS_LOGMODULE_MAIN, ISC_LOG_NOTICE,
868                               "adjusted limit on open files from "
869                               "%" ISC_PRINT_QUADFORMAT "u to "
870                               "%" ISC_PRINT_QUADFORMAT "u",
871                               old_openfiles, ns_g_initopenfiles);
872         }
873
874         /*
875          * If the named configuration filename is relative, prepend the current
876          * directory's name before possibly changing to another directory.
877          */
878         if (! isc_file_isabsolute(ns_g_conffile)) {
879                 result = isc_file_absolutepath(ns_g_conffile,
880                                                absolute_conffile,
881                                                sizeof(absolute_conffile));
882                 if (result != ISC_R_SUCCESS)
883                         ns_main_earlyfatal("could not construct absolute path "
884                                            "of configuration file: %s",
885                                            isc_result_totext(result));
886                 ns_g_conffile = absolute_conffile;
887         }
888
889         /*
890          * Record the server's startup time.
891          */
892         result = isc_time_now(&ns_g_boottime);
893         if (result != ISC_R_SUCCESS)
894                 ns_main_earlyfatal("isc_time_now() failed: %s",
895                                    isc_result_totext(result));
896
897         result = create_managers();
898         if (result != ISC_R_SUCCESS)
899                 ns_main_earlyfatal("create_managers() failed: %s",
900                                    isc_result_totext(result));
901
902         ns_builtin_init();
903
904         /*
905          * Add calls to register sdb drivers here.
906          */
907         /* xxdb_init(); */
908
909 #ifdef ISC_DLZ_DLOPEN
910         /*
911          * Register the DLZ "dlopen" driver.
912          */
913         result = dlz_dlopen_init(ns_g_mctx);
914         if (result != ISC_R_SUCCESS)
915                 ns_main_earlyfatal("dlz_dlopen_init() failed: %s",
916                                    isc_result_totext(result));
917 #endif
918
919 #if CONTRIB_DLZ
920         /*
921          * Register any other contributed DLZ drivers.
922          */
923         result = dlz_drivers_init();
924         if (result != ISC_R_SUCCESS)
925                 ns_main_earlyfatal("dlz_drivers_init() failed: %s",
926                                    isc_result_totext(result));
927 #endif
928
929         ns_server_create(ns_g_mctx, &ns_g_server);
930 }
931
932 static void
933 cleanup(void) {
934         destroy_managers();
935
936         ns_server_destroy(&ns_g_server);
937
938         ns_builtin_deinit();
939
940         /*
941          * Add calls to unregister sdb drivers here.
942          */
943         /* xxdb_clear(); */
944
945 #ifdef CONTRIB_DLZ
946         /*
947          * Unregister contributed DLZ drivers.
948          */
949         dlz_drivers_clear();
950 #endif
951 #ifdef ISC_DLZ_DLOPEN
952         /*
953          * Unregister "dlopen" DLZ driver.
954          */
955         dlz_dlopen_clear();
956 #endif
957
958         dns_name_destroy();
959
960         isc_log_write(ns_g_lctx, NS_LOGCATEGORY_GENERAL, NS_LOGMODULE_MAIN,
961                       ISC_LOG_NOTICE, "exiting");
962         ns_log_shutdown();
963 }
964
965 static char *memstats = NULL;
966
967 void
968 ns_main_setmemstats(const char *filename) {
969         /*
970          * Caller has to ensure locking.
971          */
972
973         if (memstats != NULL) {
974                 free(memstats);
975                 memstats = NULL;
976         }
977         if (filename == NULL)
978                 return;
979         memstats = malloc(strlen(filename) + 1);
980         if (memstats)
981                 strcpy(memstats, filename);
982 }
983
984 #ifdef HAVE_LIBSCF
985 /*
986  * Get FMRI for the named process.
987  */
988 isc_result_t
989 ns_smf_get_instance(char **ins_name, int debug, isc_mem_t *mctx) {
990         scf_handle_t *h = NULL;
991         int namelen;
992         char *instance;
993
994         REQUIRE(ins_name != NULL && *ins_name == NULL);
995
996         if ((h = scf_handle_create(SCF_VERSION)) == NULL) {
997                 if (debug)
998                         UNEXPECTED_ERROR(__FILE__, __LINE__,
999                                          "scf_handle_create() failed: %s",
1000                                          scf_strerror(scf_error()));
1001                 return (ISC_R_FAILURE);
1002         }
1003
1004         if (scf_handle_bind(h) == -1) {
1005                 if (debug)
1006                         UNEXPECTED_ERROR(__FILE__, __LINE__,
1007                                          "scf_handle_bind() failed: %s",
1008                                          scf_strerror(scf_error()));
1009                 scf_handle_destroy(h);
1010                 return (ISC_R_FAILURE);
1011         }
1012
1013         if ((namelen = scf_myname(h, NULL, 0)) == -1) {
1014                 if (debug)
1015                         UNEXPECTED_ERROR(__FILE__, __LINE__,
1016                                          "scf_myname() failed: %s",
1017                                          scf_strerror(scf_error()));
1018                 scf_handle_destroy(h);
1019                 return (ISC_R_FAILURE);
1020         }
1021
1022         if ((instance = isc_mem_allocate(mctx, namelen + 1)) == NULL) {
1023                 UNEXPECTED_ERROR(__FILE__, __LINE__,
1024                                  "ns_smf_get_instance memory "
1025                                  "allocation failed: %s",
1026                                  isc_result_totext(ISC_R_NOMEMORY));
1027                 scf_handle_destroy(h);
1028                 return (ISC_R_FAILURE);
1029         }
1030
1031         if (scf_myname(h, instance, namelen + 1) == -1) {
1032                 if (debug)
1033                         UNEXPECTED_ERROR(__FILE__, __LINE__,
1034                                          "scf_myname() failed: %s",
1035                                          scf_strerror(scf_error()));
1036                 scf_handle_destroy(h);
1037                 isc_mem_free(mctx, instance);
1038                 return (ISC_R_FAILURE);
1039         }
1040
1041         scf_handle_destroy(h);
1042         *ins_name = instance;
1043         return (ISC_R_SUCCESS);
1044 }
1045 #endif /* HAVE_LIBSCF */
1046
1047 /* main entry point, possibly hooked */
1048
1049 int
1050 main(int argc, char *argv[]) {
1051         isc_result_t result;
1052 #ifdef HAVE_LIBSCF
1053         char *instance = NULL;
1054 #endif
1055
1056         /*
1057          * Record version in core image.
1058          * strings named.core | grep "named version:"
1059          */
1060         strlcat(version,
1061 #if defined(NO_VERSION_DATE) || !defined(__DATE__)
1062                 "named version: BIND " VERSION " <" SRCID ">",
1063 #else
1064                 "named version: BIND " VERSION " <" SRCID "> (" __DATE__ ")",
1065 #endif
1066                 sizeof(version));
1067         result = isc_file_progname(*argv, program_name, sizeof(program_name));
1068         if (result != ISC_R_SUCCESS)
1069                 ns_main_earlyfatal("program name too long");
1070
1071         if (strcmp(program_name, "lwresd") == 0)
1072                 ns_g_lwresdonly = ISC_TRUE;
1073
1074         if (result != ISC_R_SUCCESS)
1075                 ns_main_earlyfatal("failed to build internal symbol table");
1076
1077         isc_assertion_setcallback(assertion_failed);
1078         isc_error_setfatal(library_fatal_error);
1079         isc_error_setunexpected(library_unexpected_error);
1080
1081         ns_os_init(program_name);
1082
1083         dns_result_register();
1084         dst_result_register();
1085         isccc_result_register();
1086
1087         parse_command_line(argc, argv);
1088
1089         /*
1090          * Warn about common configuration error.
1091          */
1092         if (ns_g_chrootdir != NULL) {
1093                 int len = strlen(ns_g_chrootdir);
1094                 if (strncmp(ns_g_chrootdir, ns_g_conffile, len) == 0 &&
1095                     (ns_g_conffile[len] == '/' || ns_g_conffile[len] == '\\'))
1096                         ns_main_earlywarning("config filename (-c %s) contains "
1097                                              "chroot path (-t %s)",
1098                                              ns_g_conffile, ns_g_chrootdir);
1099         }
1100
1101         result = isc_mem_create(0, 0, &ns_g_mctx);
1102         if (result != ISC_R_SUCCESS)
1103                 ns_main_earlyfatal("isc_mem_create() failed: %s",
1104                                    isc_result_totext(result));
1105         isc_mem_setname(ns_g_mctx, "main", NULL);
1106
1107         setup();
1108
1109         /*
1110          * Start things running and then wait for a shutdown request
1111          * or reload.
1112          */
1113         do {
1114                 result = isc_app_run();
1115
1116                 if (result == ISC_R_RELOAD) {
1117                         ns_server_reloadwanted(ns_g_server);
1118                 } else if (result != ISC_R_SUCCESS) {
1119                         UNEXPECTED_ERROR(__FILE__, __LINE__,
1120                                          "isc_app_run(): %s",
1121                                          isc_result_totext(result));
1122                         /*
1123                          * Force exit.
1124                          */
1125                         result = ISC_R_SUCCESS;
1126                 }
1127         } while (result != ISC_R_SUCCESS);
1128
1129 #ifdef HAVE_LIBSCF
1130         if (ns_smf_want_disable == 1) {
1131                 result = ns_smf_get_instance(&instance, 1, ns_g_mctx);
1132                 if (result == ISC_R_SUCCESS && instance != NULL) {
1133                         if (smf_disable_instance(instance, 0) != 0)
1134                                 UNEXPECTED_ERROR(__FILE__, __LINE__,
1135                                                  "smf_disable_instance() "
1136                                                  "failed for %s : %s",
1137                                                  instance,
1138                                                  scf_strerror(scf_error()));
1139                 }
1140                 if (instance != NULL)
1141                         isc_mem_free(ns_g_mctx, instance);
1142         }
1143 #endif /* HAVE_LIBSCF */
1144
1145         cleanup();
1146
1147         if (want_stats) {
1148                 isc_mem_stats(ns_g_mctx, stdout);
1149                 isc_mutex_stats(stdout);
1150         }
1151
1152         if (ns_g_memstatistics && memstats != NULL) {
1153                 FILE *fp = NULL;
1154                 result = isc_stdio_open(memstats, "w", &fp);
1155                 if (result == ISC_R_SUCCESS) {
1156                         isc_mem_stats(ns_g_mctx, fp);
1157                         isc_mutex_stats(fp);
1158                         isc_stdio_close(fp);
1159                 }
1160         }
1161         isc_mem_destroy(&ns_g_mctx);
1162         isc_mem_checkdestroyed(stderr);
1163
1164         ns_main_setmemstats(NULL);
1165
1166         isc_app_finish();
1167
1168         ns_os_closedevnull();
1169
1170         ns_os_shutdown();
1171
1172         return (0);
1173 }