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