]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/bind9/bin/named/main.c
Update Bind to 9.8.5-P2
[FreeBSD/FreeBSD.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 = 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         isc_commandline_errprint = ISC_FALSE;
419         while ((ch = isc_commandline_parse(argc, argv,
420                                            "46c:C:d:E:fFgi:lm:n:N:p:P:"
421                                            "sS:t:T:u:vVx:")) != -1) {
422                 switch (ch) {
423                 case '4':
424                         if (disable4)
425                                 ns_main_earlyfatal("cannot specify -4 and -6");
426                         if (isc_net_probeipv4() != ISC_R_SUCCESS)
427                                 ns_main_earlyfatal("IPv4 not supported by OS");
428                         isc_net_disableipv6();
429                         disable6 = ISC_TRUE;
430                         break;
431                 case '6':
432                         if (disable6)
433                                 ns_main_earlyfatal("cannot specify -4 and -6");
434                         if (isc_net_probeipv6() != ISC_R_SUCCESS)
435                                 ns_main_earlyfatal("IPv6 not supported by OS");
436                         isc_net_disableipv4();
437                         disable4 = ISC_TRUE;
438                         break;
439                 case 'c':
440                         ns_g_conffile = isc_commandline_argument;
441                         lwresd_g_conffile = isc_commandline_argument;
442                         if (lwresd_g_useresolvconf)
443                                 ns_main_earlyfatal("cannot specify -c and -C");
444                         ns_g_conffileset = ISC_TRUE;
445                         break;
446                 case 'C':
447                         lwresd_g_resolvconffile = isc_commandline_argument;
448                         if (ns_g_conffileset)
449                                 ns_main_earlyfatal("cannot specify -c and -C");
450                         lwresd_g_useresolvconf = ISC_TRUE;
451                         break;
452                 case 'd':
453                         ns_g_debuglevel = parse_int(isc_commandline_argument,
454                                                     "debug level");
455                         break;
456                 case 'E':
457                         ns_g_engine = isc_commandline_argument;
458                         break;
459                 case 'f':
460                         ns_g_foreground = ISC_TRUE;
461                         break;
462                 case 'g':
463                         ns_g_foreground = ISC_TRUE;
464                         ns_g_logstderr = ISC_TRUE;
465                         break;
466                 /* XXXBEW -i should be removed */
467                 case 'i':
468                         lwresd_g_defaultpidfile = isc_commandline_argument;
469                         break;
470                 case 'l':
471                         ns_g_lwresdonly = ISC_TRUE;
472                         break;
473                 case 'm':
474                         set_flags(isc_commandline_argument, mem_debug_flags,
475                                   &isc_mem_debugging);
476                         break;
477                 case 'N': /* Deprecated. */
478                 case 'n':
479                         ns_g_cpus = parse_int(isc_commandline_argument,
480                                               "number of cpus");
481                         if (ns_g_cpus == 0)
482                                 ns_g_cpus = 1;
483                         break;
484                 case 'p':
485                         port = parse_int(isc_commandline_argument, "port");
486                         if (port < 1 || port > 65535)
487                                 ns_main_earlyfatal("port '%s' out of range",
488                                                    isc_commandline_argument);
489                         ns_g_port = port;
490                         break;
491                 /* XXXBEW Should -P be removed? */
492                 case 'P':
493                         port = parse_int(isc_commandline_argument, "port");
494                         if (port < 1 || port > 65535)
495                                 ns_main_earlyfatal("port '%s' out of range",
496                                                    isc_commandline_argument);
497                         lwresd_g_listenport = port;
498                         break;
499                 case 's':
500                         /* XXXRTH temporary syntax */
501                         want_stats = ISC_TRUE;
502                         break;
503                 case 'S':
504                         maxsocks = parse_int(isc_commandline_argument,
505                                              "max number of sockets");
506                         break;
507                 case 't':
508                         /* XXXJAB should we make a copy? */
509                         ns_g_chrootdir = isc_commandline_argument;
510                         break;
511                 case 'T':       /* NOT DOCUMENTED */
512                         /*
513                          * clienttest: make clients single shot with their
514                          *             own memory context.
515                          */
516                         if (!strcmp(isc_commandline_argument, "clienttest"))
517                                 ns_g_clienttest = ISC_TRUE;
518                         else if (!strcmp(isc_commandline_argument, "nosoa"))
519                                 ns_g_nosoa = ISC_TRUE;
520                         else if (!strcmp(isc_commandline_argument, "noaa"))
521                                 ns_g_noaa = ISC_TRUE;
522                         else if (!strcmp(isc_commandline_argument, "maxudp512"))
523                                 maxudp = 512;
524                         else if (!strcmp(isc_commandline_argument, "maxudp1460"))
525                                 maxudp = 1460;
526                         else if (!strcmp(isc_commandline_argument, "nosyslog"))
527                                 ns_g_nosyslog = ISC_TRUE;
528                         else if (!strcmp(isc_commandline_argument, "nonearest"))
529                                 ns_g_nonearest = ISC_TRUE;
530                         else
531                                 fprintf(stderr, "unknown -T flag '%s\n",
532                                         isc_commandline_argument);
533                         break;
534                 case 'u':
535                         ns_g_username = isc_commandline_argument;
536                         break;
537                 case 'v':
538                         printf("%s %s", ns_g_product, ns_g_version);
539                         if (*ns_g_description != 0)
540                                 printf(" %s", ns_g_description);
541                         printf("\n");
542                         exit(0);
543                 case 'V':
544                         printf("%s %s", ns_g_product, ns_g_version);
545                         if (*ns_g_description != 0)
546                                 printf(" %s", ns_g_description);
547                         printf(" <id:%s> built with %s\n", ns_g_srcid,
548                                 ns_g_configargs);
549 #ifdef OPENSSL
550                         printf("using OpenSSL version: %s\n",
551                                OPENSSL_VERSION_TEXT);
552 #endif
553 #ifdef HAVE_LIBXML2
554                         printf("using libxml2 version: %s\n",
555                                LIBXML_DOTTED_VERSION);
556 #endif
557                         exit(0);
558                 case 'F':
559                         /* Reserved for FIPS mode */
560                         /* FALLTHROUGH */
561                 case '?':
562                         usage();
563                         if (isc_commandline_option == '?')
564                                 exit(0);
565                         ns_main_earlyfatal("unknown option '-%c'",
566                                            isc_commandline_option);
567                         /* FALLTHROUGH */
568                 default:
569                         ns_main_earlyfatal("parsing options returned %d", ch);
570                 }
571         }
572
573         argc -= isc_commandline_index;
574         argv += isc_commandline_index;
575         POST(argv);
576
577         if (argc > 0) {
578                 usage();
579                 ns_main_earlyfatal("extra command line arguments");
580         }
581 }
582
583 static isc_result_t
584 create_managers(void) {
585         isc_result_t result;
586         unsigned int socks;
587
588 #ifdef ISC_PLATFORM_USETHREADS
589         if (ns_g_cpus == 0)
590                 ns_g_cpus = ns_g_cpus_detected;
591         isc_log_write(ns_g_lctx, NS_LOGCATEGORY_GENERAL, NS_LOGMODULE_SERVER,
592                       ISC_LOG_INFO, "found %u CPU%s, using %u worker thread%s",
593                       ns_g_cpus_detected, ns_g_cpus_detected == 1 ? "" : "s",
594                       ns_g_cpus, ns_g_cpus == 1 ? "" : "s");
595 #else
596         ns_g_cpus = 1;
597 #endif
598         result = isc_taskmgr_create(ns_g_mctx, ns_g_cpus, 0, &ns_g_taskmgr);
599         if (result != ISC_R_SUCCESS) {
600                 UNEXPECTED_ERROR(__FILE__, __LINE__,
601                                  "isc_taskmgr_create() failed: %s",
602                                  isc_result_totext(result));
603                 return (ISC_R_UNEXPECTED);
604         }
605
606         result = isc_timermgr_create(ns_g_mctx, &ns_g_timermgr);
607         if (result != ISC_R_SUCCESS) {
608                 UNEXPECTED_ERROR(__FILE__, __LINE__,
609                                  "isc_timermgr_create() failed: %s",
610                                  isc_result_totext(result));
611                 return (ISC_R_UNEXPECTED);
612         }
613
614         result = isc_socketmgr_create2(ns_g_mctx, &ns_g_socketmgr, maxsocks);
615         if (result != ISC_R_SUCCESS) {
616                 UNEXPECTED_ERROR(__FILE__, __LINE__,
617                                  "isc_socketmgr_create() failed: %s",
618                                  isc_result_totext(result));
619                 return (ISC_R_UNEXPECTED);
620         }
621         isc__socketmgr_maxudp(ns_g_socketmgr, maxudp);
622         result = isc_socketmgr_getmaxsockets(ns_g_socketmgr, &socks);
623         if (result == ISC_R_SUCCESS) {
624                 isc_log_write(ns_g_lctx, NS_LOGCATEGORY_GENERAL,
625                               NS_LOGMODULE_SERVER,
626                               ISC_LOG_INFO, "using up to %u sockets", socks);
627         }
628
629         result = isc_entropy_create(ns_g_mctx, &ns_g_entropy);
630         if (result != ISC_R_SUCCESS) {
631                 UNEXPECTED_ERROR(__FILE__, __LINE__,
632                                  "isc_entropy_create() failed: %s",
633                                  isc_result_totext(result));
634                 return (ISC_R_UNEXPECTED);
635         }
636
637         result = isc_hash_create(ns_g_mctx, ns_g_entropy, DNS_NAME_MAXWIRE);
638         if (result != ISC_R_SUCCESS) {
639                 UNEXPECTED_ERROR(__FILE__, __LINE__,
640                                  "isc_hash_create() failed: %s",
641                                  isc_result_totext(result));
642                 return (ISC_R_UNEXPECTED);
643         }
644
645         return (ISC_R_SUCCESS);
646 }
647
648 static void
649 destroy_managers(void) {
650         ns_lwresd_shutdown();
651
652         isc_entropy_detach(&ns_g_entropy);
653         if (ns_g_fallbackentropy != NULL)
654                 isc_entropy_detach(&ns_g_fallbackentropy);
655
656         /*
657          * isc_taskmgr_destroy() will block until all tasks have exited,
658          */
659         isc_taskmgr_destroy(&ns_g_taskmgr);
660         isc_timermgr_destroy(&ns_g_timermgr);
661         isc_socketmgr_destroy(&ns_g_socketmgr);
662
663         /*
664          * isc_hash_destroy() cannot be called as long as a resolver may be
665          * running.  Calling this after isc_taskmgr_destroy() ensures the
666          * call is safe.
667          */
668         isc_hash_destroy();
669 }
670
671 static void
672 dump_symboltable() {
673         int i;
674         isc_result_t result;
675         const char *fname;
676         const void *addr;
677
678         if (isc__backtrace_nsymbols == 0)
679                 return;
680
681         if (!isc_log_wouldlog(ns_g_lctx, ISC_LOG_DEBUG(99)))
682                 return;
683
684         isc_log_write(ns_g_lctx, NS_LOGCATEGORY_GENERAL, NS_LOGMODULE_MAIN,
685                       ISC_LOG_DEBUG(99), "Symbol table:");
686
687         for (i = 0, result = ISC_R_SUCCESS; result == ISC_R_SUCCESS; i++) {
688                 addr = NULL;
689                 fname = NULL;
690                 result = isc_backtrace_getsymbolfromindex(i, &addr, &fname);
691                 if (result == ISC_R_SUCCESS) {
692                         isc_log_write(ns_g_lctx, NS_LOGCATEGORY_GENERAL,
693                                       NS_LOGMODULE_MAIN, ISC_LOG_DEBUG(99),
694                                       "[%d] %p %s", i, addr, fname);
695                 }
696         }
697 }
698
699 static void
700 setup(void) {
701         isc_result_t result;
702         isc_resourcevalue_t old_openfiles;
703 #ifdef HAVE_LIBSCF
704         char *instance = NULL;
705 #endif
706
707         /*
708          * Get the user and group information before changing the root
709          * directory, so the administrator does not need to keep a copy
710          * of the user and group databases in the chroot'ed environment.
711          */
712         ns_os_inituserinfo(ns_g_username);
713
714         /*
715          * Initialize time conversion information
716          */
717         ns_os_tzset();
718
719         ns_os_opendevnull();
720
721 #ifdef HAVE_LIBSCF
722         /* Check if named is under smf control, before chroot. */
723         result = ns_smf_get_instance(&instance, 0, ns_g_mctx);
724         /* We don't care about instance, just check if we got one. */
725         if (result == ISC_R_SUCCESS)
726                 ns_smf_got_instance = 1;
727         else
728                 ns_smf_got_instance = 0;
729         if (instance != NULL)
730                 isc_mem_free(ns_g_mctx, instance);
731 #endif /* HAVE_LIBSCF */
732
733 #ifdef PATH_RANDOMDEV
734         /*
735          * Initialize system's random device as fallback entropy source
736          * if running chroot'ed.
737          */
738         if (ns_g_chrootdir != NULL) {
739                 result = isc_entropy_create(ns_g_mctx, &ns_g_fallbackentropy);
740                 if (result != ISC_R_SUCCESS)
741                         ns_main_earlyfatal("isc_entropy_create() failed: %s",
742                                            isc_result_totext(result));
743
744                 result = isc_entropy_createfilesource(ns_g_fallbackentropy,
745                                                       PATH_RANDOMDEV);
746                 if (result != ISC_R_SUCCESS) {
747                         ns_main_earlywarning("could not open pre-chroot "
748                                              "entropy source %s: %s",
749                                              PATH_RANDOMDEV,
750                                              isc_result_totext(result));
751                         isc_entropy_detach(&ns_g_fallbackentropy);
752                 }
753         }
754 #endif
755
756 #ifdef ISC_PLATFORM_USETHREADS
757         /*
758          * Check for the number of cpu's before ns_os_chroot().
759          */
760         ns_g_cpus_detected = isc_os_ncpus();
761 #endif
762
763         ns_os_chroot(ns_g_chrootdir);
764
765         /*
766          * For operating systems which have a capability mechanism, now
767          * is the time to switch to minimal privs and change our user id.
768          * On traditional UNIX systems, this call will be a no-op, and we
769          * will change the user ID after reading the config file the first
770          * time.  (We need to read the config file to know which possibly
771          * privileged ports to bind() to.)
772          */
773         ns_os_minprivs();
774
775         result = ns_log_init(ISC_TF(ns_g_username != NULL));
776         if (result != ISC_R_SUCCESS)
777                 ns_main_earlyfatal("ns_log_init() failed: %s",
778                                    isc_result_totext(result));
779
780         /*
781          * Now is the time to daemonize (if we're not running in the
782          * foreground).  We waited until now because we wanted to get
783          * a valid logging context setup.  We cannot daemonize any later,
784          * because calling create_managers() will create threads, which
785          * would be lost after fork().
786          */
787         if (!ns_g_foreground)
788                 ns_os_daemonize();
789
790         /*
791          * We call isc_app_start() here as some versions of FreeBSD's fork()
792          * destroys all the signal handling it sets up.
793          */
794         result = isc_app_start();
795         if (result != ISC_R_SUCCESS)
796                 ns_main_earlyfatal("isc_app_start() failed: %s",
797                                    isc_result_totext(result));
798
799         isc_log_write(ns_g_lctx, NS_LOGCATEGORY_GENERAL, NS_LOGMODULE_MAIN,
800                       ISC_LOG_NOTICE, "starting %s %s%s", ns_g_product,
801                       ns_g_version, saved_command_line);
802
803         isc_log_write(ns_g_lctx, NS_LOGCATEGORY_GENERAL, NS_LOGMODULE_MAIN,
804                       ISC_LOG_NOTICE, "built with %s", ns_g_configargs);
805
806         isc_log_write(ns_g_lctx, NS_LOGCATEGORY_GENERAL, NS_LOGMODULE_MAIN,
807                       ISC_LOG_NOTICE,
808                       "----------------------------------------------------");
809         isc_log_write(ns_g_lctx, NS_LOGCATEGORY_GENERAL, NS_LOGMODULE_MAIN,
810                       ISC_LOG_NOTICE,
811                       "BIND 9 is maintained by Internet Systems Consortium,");
812         isc_log_write(ns_g_lctx, NS_LOGCATEGORY_GENERAL, NS_LOGMODULE_MAIN,
813                       ISC_LOG_NOTICE,
814                       "Inc. (ISC), a non-profit 501(c)(3) public-benefit ");
815         isc_log_write(ns_g_lctx, NS_LOGCATEGORY_GENERAL, NS_LOGMODULE_MAIN,
816                       ISC_LOG_NOTICE,
817                       "corporation.  Support and training for BIND 9 are ");
818         isc_log_write(ns_g_lctx, NS_LOGCATEGORY_GENERAL, NS_LOGMODULE_MAIN,
819                       ISC_LOG_NOTICE,
820                       "available at https://www.isc.org/support");
821         isc_log_write(ns_g_lctx, NS_LOGCATEGORY_GENERAL, NS_LOGMODULE_MAIN,
822                       ISC_LOG_NOTICE,
823                       "----------------------------------------------------");
824
825         dump_symboltable();
826
827         /*
828          * Get the initial resource limits.
829          */
830         (void)isc_resource_getlimit(isc_resource_stacksize,
831                                     &ns_g_initstacksize);
832         (void)isc_resource_getlimit(isc_resource_datasize,
833                                     &ns_g_initdatasize);
834         (void)isc_resource_getlimit(isc_resource_coresize,
835                                     &ns_g_initcoresize);
836         (void)isc_resource_getlimit(isc_resource_openfiles,
837                                     &ns_g_initopenfiles);
838
839         /*
840          * System resources cannot effectively be tuned on some systems.
841          * Raise the limit in such cases for safety.
842          */
843         old_openfiles = ns_g_initopenfiles;
844         ns_os_adjustnofile();
845         (void)isc_resource_getlimit(isc_resource_openfiles,
846                                     &ns_g_initopenfiles);
847         if (old_openfiles != ns_g_initopenfiles) {
848                 isc_log_write(ns_g_lctx, NS_LOGCATEGORY_GENERAL,
849                               NS_LOGMODULE_MAIN, ISC_LOG_NOTICE,
850                               "adjusted limit on open files from "
851                               "%" ISC_PRINT_QUADFORMAT "u to "
852                               "%" ISC_PRINT_QUADFORMAT "u",
853                               old_openfiles, ns_g_initopenfiles);
854         }
855
856         /*
857          * If the named configuration filename is relative, prepend the current
858          * directory's name before possibly changing to another directory.
859          */
860         if (! isc_file_isabsolute(ns_g_conffile)) {
861                 result = isc_file_absolutepath(ns_g_conffile,
862                                                absolute_conffile,
863                                                sizeof(absolute_conffile));
864                 if (result != ISC_R_SUCCESS)
865                         ns_main_earlyfatal("could not construct absolute path "
866                                            "of configuration file: %s",
867                                            isc_result_totext(result));
868                 ns_g_conffile = absolute_conffile;
869         }
870
871         /*
872          * Record the server's startup time.
873          */
874         result = isc_time_now(&ns_g_boottime);
875         if (result != ISC_R_SUCCESS)
876                 ns_main_earlyfatal("isc_time_now() failed: %s",
877                                    isc_result_totext(result));
878
879         result = create_managers();
880         if (result != ISC_R_SUCCESS)
881                 ns_main_earlyfatal("create_managers() failed: %s",
882                                    isc_result_totext(result));
883
884         ns_builtin_init();
885
886         /*
887          * Add calls to register sdb drivers here.
888          */
889         /* xxdb_init(); */
890
891 #ifdef ISC_DLZ_DLOPEN
892         /*
893          * Register the DLZ "dlopen" driver.
894          */
895         result = dlz_dlopen_init(ns_g_mctx);
896         if (result != ISC_R_SUCCESS)
897                 ns_main_earlyfatal("dlz_dlopen_init() failed: %s",
898                                    isc_result_totext(result));
899 #endif
900
901 #if CONTRIB_DLZ
902         /*
903          * Register any other contributed DLZ drivers.
904          */
905         result = dlz_drivers_init();
906         if (result != ISC_R_SUCCESS)
907                 ns_main_earlyfatal("dlz_drivers_init() failed: %s",
908                                    isc_result_totext(result));
909 #endif
910
911         ns_server_create(ns_g_mctx, &ns_g_server);
912 }
913
914 static void
915 cleanup(void) {
916         destroy_managers();
917
918         ns_server_destroy(&ns_g_server);
919
920         ns_builtin_deinit();
921
922         /*
923          * Add calls to unregister sdb drivers here.
924          */
925         /* xxdb_clear(); */
926
927 #ifdef CONTRIB_DLZ
928         /*
929          * Unregister contributed DLZ drivers.
930          */
931         dlz_drivers_clear();
932 #endif
933 #ifdef ISC_DLZ_DLOPEN
934         /*
935          * Unregister "dlopen" DLZ driver.
936          */
937         dlz_dlopen_clear();
938 #endif
939
940         dns_name_destroy();
941
942         isc_log_write(ns_g_lctx, NS_LOGCATEGORY_GENERAL, NS_LOGMODULE_MAIN,
943                       ISC_LOG_NOTICE, "exiting");
944         ns_log_shutdown();
945 }
946
947 static char *memstats = NULL;
948
949 void
950 ns_main_setmemstats(const char *filename) {
951         /*
952          * Caller has to ensure locking.
953          */
954
955         if (memstats != NULL) {
956                 free(memstats);
957                 memstats = NULL;
958         }
959         if (filename == NULL)
960                 return;
961         memstats = malloc(strlen(filename) + 1);
962         if (memstats)
963                 strcpy(memstats, filename);
964 }
965
966 #ifdef HAVE_LIBSCF
967 /*
968  * Get FMRI for the named process.
969  */
970 isc_result_t
971 ns_smf_get_instance(char **ins_name, int debug, isc_mem_t *mctx) {
972         scf_handle_t *h = NULL;
973         int namelen;
974         char *instance;
975
976         REQUIRE(ins_name != NULL && *ins_name == NULL);
977
978         if ((h = scf_handle_create(SCF_VERSION)) == NULL) {
979                 if (debug)
980                         UNEXPECTED_ERROR(__FILE__, __LINE__,
981                                          "scf_handle_create() failed: %s",
982                                          scf_strerror(scf_error()));
983                 return (ISC_R_FAILURE);
984         }
985
986         if (scf_handle_bind(h) == -1) {
987                 if (debug)
988                         UNEXPECTED_ERROR(__FILE__, __LINE__,
989                                          "scf_handle_bind() failed: %s",
990                                          scf_strerror(scf_error()));
991                 scf_handle_destroy(h);
992                 return (ISC_R_FAILURE);
993         }
994
995         if ((namelen = scf_myname(h, NULL, 0)) == -1) {
996                 if (debug)
997                         UNEXPECTED_ERROR(__FILE__, __LINE__,
998                                          "scf_myname() failed: %s",
999                                          scf_strerror(scf_error()));
1000                 scf_handle_destroy(h);
1001                 return (ISC_R_FAILURE);
1002         }
1003
1004         if ((instance = isc_mem_allocate(mctx, namelen + 1)) == NULL) {
1005                 UNEXPECTED_ERROR(__FILE__, __LINE__,
1006                                  "ns_smf_get_instance memory "
1007                                  "allocation failed: %s",
1008                                  isc_result_totext(ISC_R_NOMEMORY));
1009                 scf_handle_destroy(h);
1010                 return (ISC_R_FAILURE);
1011         }
1012
1013         if (scf_myname(h, instance, namelen + 1) == -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                 isc_mem_free(mctx, instance);
1020                 return (ISC_R_FAILURE);
1021         }
1022
1023         scf_handle_destroy(h);
1024         *ins_name = instance;
1025         return (ISC_R_SUCCESS);
1026 }
1027 #endif /* HAVE_LIBSCF */
1028
1029 int
1030 main(int argc, char *argv[]) {
1031         isc_result_t result;
1032 #ifdef HAVE_LIBSCF
1033         char *instance = NULL;
1034 #endif
1035
1036         /*
1037          * Record version in core image.
1038          * strings named.core | grep "named version:"
1039          */
1040         strlcat(version,
1041 #if defined(NO_VERSION_DATE) || !defined(__DATE__)
1042                 "named version: BIND " VERSION " <" SRCID ">",
1043 #else
1044                 "named version: BIND " VERSION " <" SRCID "> (" __DATE__ ")",
1045 #endif
1046                 sizeof(version));
1047         result = isc_file_progname(*argv, program_name, sizeof(program_name));
1048         if (result != ISC_R_SUCCESS)
1049                 ns_main_earlyfatal("program name too long");
1050
1051         if (strcmp(program_name, "lwresd") == 0)
1052                 ns_g_lwresdonly = ISC_TRUE;
1053
1054         if (result != ISC_R_SUCCESS)
1055                 ns_main_earlyfatal("failed to build internal symbol table");
1056
1057         isc_assertion_setcallback(assertion_failed);
1058         isc_error_setfatal(library_fatal_error);
1059         isc_error_setunexpected(library_unexpected_error);
1060
1061         ns_os_init(program_name);
1062
1063         dns_result_register();
1064         dst_result_register();
1065         isccc_result_register();
1066
1067         parse_command_line(argc, argv);
1068
1069         /*
1070          * Warn about common configuration error.
1071          */
1072         if (ns_g_chrootdir != NULL) {
1073                 int len = strlen(ns_g_chrootdir);
1074                 if (strncmp(ns_g_chrootdir, ns_g_conffile, len) == 0 &&
1075                     (ns_g_conffile[len] == '/' || ns_g_conffile[len] == '\\'))
1076                         ns_main_earlywarning("config filename (-c %s) contains "
1077                                              "chroot path (-t %s)",
1078                                              ns_g_conffile, ns_g_chrootdir);
1079         }
1080
1081         result = isc_mem_create(0, 0, &ns_g_mctx);
1082         if (result != ISC_R_SUCCESS)
1083                 ns_main_earlyfatal("isc_mem_create() failed: %s",
1084                                    isc_result_totext(result));
1085         isc_mem_setname(ns_g_mctx, "main", NULL);
1086
1087         setup();
1088
1089         /*
1090          * Start things running and then wait for a shutdown request
1091          * or reload.
1092          */
1093         do {
1094                 result = isc_app_run();
1095
1096                 if (result == ISC_R_RELOAD) {
1097                         ns_server_reloadwanted(ns_g_server);
1098                 } else if (result != ISC_R_SUCCESS) {
1099                         UNEXPECTED_ERROR(__FILE__, __LINE__,
1100                                          "isc_app_run(): %s",
1101                                          isc_result_totext(result));
1102                         /*
1103                          * Force exit.
1104                          */
1105                         result = ISC_R_SUCCESS;
1106                 }
1107         } while (result != ISC_R_SUCCESS);
1108
1109 #ifdef HAVE_LIBSCF
1110         if (ns_smf_want_disable == 1) {
1111                 result = ns_smf_get_instance(&instance, 1, ns_g_mctx);
1112                 if (result == ISC_R_SUCCESS && instance != NULL) {
1113                         if (smf_disable_instance(instance, 0) != 0)
1114                                 UNEXPECTED_ERROR(__FILE__, __LINE__,
1115                                                  "smf_disable_instance() "
1116                                                  "failed for %s : %s",
1117                                                  instance,
1118                                                  scf_strerror(scf_error()));
1119                 }
1120                 if (instance != NULL)
1121                         isc_mem_free(ns_g_mctx, instance);
1122         }
1123 #endif /* HAVE_LIBSCF */
1124
1125         cleanup();
1126
1127         if (want_stats) {
1128                 isc_mem_stats(ns_g_mctx, stdout);
1129                 isc_mutex_stats(stdout);
1130         }
1131
1132         if (ns_g_memstatistics && memstats != NULL) {
1133                 FILE *fp = NULL;
1134                 result = isc_stdio_open(memstats, "w", &fp);
1135                 if (result == ISC_R_SUCCESS) {
1136                         isc_mem_stats(ns_g_mctx, fp);
1137                         isc_mutex_stats(fp);
1138                         isc_stdio_close(fp);
1139                 }
1140         }
1141         isc_mem_destroy(&ns_g_mctx);
1142         isc_mem_checkdestroyed(stderr);
1143
1144         ns_main_setmemstats(NULL);
1145
1146         isc_app_finish();
1147
1148         ns_os_closedevnull();
1149
1150         ns_os_shutdown();
1151
1152         return (0);
1153 }