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