]> CyberLeo.Net >> Repos - FreeBSD/releng/9.2.git/blob - contrib/bind9/bin/named/server.c
- Copy stable/9 to releng/9.2 as part of the 9.2-RELEASE cycle.
[FreeBSD/releng/9.2.git] / contrib / bind9 / bin / named / server.c
1 /*
2  * Copyright (C) 2004-2012  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: server.c,v 1.599.8.19 2012/02/22 00:33:32 each Exp $ */
19
20 /*! \file */
21
22 #include <config.h>
23
24 #include <stdlib.h>
25 #include <unistd.h>
26 #include <limits.h>
27 #include <ctype.h>
28 #include <sys/types.h>
29 #include <sys/stat.h>
30
31 #include <isc/app.h>
32 #include <isc/base64.h>
33 #include <isc/dir.h>
34 #include <isc/entropy.h>
35 #include <isc/file.h>
36 #include <isc/hash.h>
37 #include <isc/httpd.h>
38 #include <isc/lex.h>
39 #include <isc/parseint.h>
40 #include <isc/portset.h>
41 #include <isc/print.h>
42 #include <isc/resource.h>
43 #include <isc/sha2.h>
44 #include <isc/socket.h>
45 #include <isc/stat.h>
46 #include <isc/stats.h>
47 #include <isc/stdio.h>
48 #include <isc/string.h>
49 #include <isc/task.h>
50 #include <isc/timer.h>
51 #include <isc/util.h>
52 #include <isc/xml.h>
53
54 #include <isccfg/namedconf.h>
55
56 #include <bind9/check.h>
57
58 #include <dns/acache.h>
59 #include <dns/adb.h>
60 #include <dns/cache.h>
61 #include <dns/db.h>
62 #include <dns/dispatch.h>
63 #include <dns/dlz.h>
64 #include <dns/dns64.h>
65 #include <dns/forward.h>
66 #include <dns/journal.h>
67 #include <dns/keytable.h>
68 #include <dns/keyvalues.h>
69 #include <dns/lib.h>
70 #include <dns/master.h>
71 #include <dns/masterdump.h>
72 #include <dns/order.h>
73 #include <dns/peer.h>
74 #include <dns/portlist.h>
75 #include <dns/rbt.h>
76 #include <dns/rdataclass.h>
77 #include <dns/rdataset.h>
78 #include <dns/rdatastruct.h>
79 #include <dns/resolver.h>
80 #include <dns/rootns.h>
81 #include <dns/secalg.h>
82 #include <dns/stats.h>
83 #include <dns/tkey.h>
84 #include <dns/tsig.h>
85 #include <dns/view.h>
86 #include <dns/zone.h>
87 #include <dns/zt.h>
88
89 #include <dst/dst.h>
90 #include <dst/result.h>
91
92 #include <named/client.h>
93 #include <named/config.h>
94 #include <named/control.h>
95 #include <named/interfacemgr.h>
96 #include <named/log.h>
97 #include <named/logconf.h>
98 #include <named/lwresd.h>
99 #include <named/main.h>
100 #include <named/os.h>
101 #include <named/server.h>
102 #include <named/statschannel.h>
103 #include <named/tkeyconf.h>
104 #include <named/tsigconf.h>
105 #include <named/zoneconf.h>
106 #ifdef HAVE_LIBSCF
107 #include <named/ns_smf_globals.h>
108 #include <stdlib.h>
109 #endif
110
111 #ifndef PATH_MAX
112 #define PATH_MAX 1024
113 #endif
114
115 /*%
116  * Check an operation for failure.  Assumes that the function
117  * using it has a 'result' variable and a 'cleanup' label.
118  */
119 #define CHECK(op) \
120         do { result = (op);                                      \
121                if (result != ISC_R_SUCCESS) goto cleanup;        \
122         } while (0)
123
124 #define CHECKM(op, msg) \
125         do { result = (op);                                       \
126                if (result != ISC_R_SUCCESS) {                     \
127                         isc_log_write(ns_g_lctx,                  \
128                                       NS_LOGCATEGORY_GENERAL,     \
129                                       NS_LOGMODULE_SERVER,        \
130                                       ISC_LOG_ERROR,              \
131                                       "%s: %s", msg,              \
132                                       isc_result_totext(result)); \
133                         goto cleanup;                             \
134                 }                                                 \
135         } while (0)                                               \
136
137 #define CHECKMF(op, msg, file) \
138         do { result = (op);                                       \
139                if (result != ISC_R_SUCCESS) {                     \
140                         isc_log_write(ns_g_lctx,                  \
141                                       NS_LOGCATEGORY_GENERAL,     \
142                                       NS_LOGMODULE_SERVER,        \
143                                       ISC_LOG_ERROR,              \
144                                       "%s '%s': %s", msg, file,   \
145                                       isc_result_totext(result)); \
146                         goto cleanup;                             \
147                 }                                                 \
148         } while (0)                                               \
149
150 #define CHECKFATAL(op, msg) \
151         do { result = (op);                                       \
152                if (result != ISC_R_SUCCESS)                       \
153                         fatal(msg, result);                       \
154         } while (0)                                               \
155
156 /*%
157  * Maximum ADB size for views that share a cache.  Use this limit to suppress
158  * the total of memory footprint, which should be the main reason for sharing
159  * a cache.  Only effective when a finite max-cache-size is specified.
160  * This is currently defined to be 8MB.
161  */
162 #define MAX_ADB_SIZE_FOR_CACHESHARE     8388608
163
164 struct ns_dispatch {
165         isc_sockaddr_t                  addr;
166         unsigned int                    dispatchgen;
167         dns_dispatch_t                  *dispatch;
168         ISC_LINK(struct ns_dispatch)    link;
169 };
170
171 struct ns_cache {
172         dns_cache_t                     *cache;
173         dns_view_t                      *primaryview;
174         isc_boolean_t                   needflush;
175         isc_boolean_t                   adbsizeadjusted;
176         ISC_LINK(ns_cache_t)            link;
177 };
178
179 struct dumpcontext {
180         isc_mem_t                       *mctx;
181         isc_boolean_t                   dumpcache;
182         isc_boolean_t                   dumpzones;
183         FILE                            *fp;
184         ISC_LIST(struct viewlistentry)  viewlist;
185         struct viewlistentry            *view;
186         struct zonelistentry            *zone;
187         dns_dumpctx_t                   *mdctx;
188         dns_db_t                        *db;
189         dns_db_t                        *cache;
190         isc_task_t                      *task;
191         dns_dbversion_t                 *version;
192 };
193
194 struct viewlistentry {
195         dns_view_t                      *view;
196         ISC_LINK(struct viewlistentry)  link;
197         ISC_LIST(struct zonelistentry)  zonelist;
198 };
199
200 struct zonelistentry {
201         dns_zone_t                      *zone;
202         ISC_LINK(struct zonelistentry)  link;
203 };
204
205 /*%
206  * Configuration context to retain for each view that allows
207  * new zones to be added at runtime.
208  */
209 struct cfg_context {
210         isc_mem_t *                     mctx;
211         cfg_parser_t *                  parser;
212         cfg_obj_t *                     config;
213         cfg_parser_t *                  nzparser;
214         cfg_obj_t *                     nzconfig;
215         cfg_aclconfctx_t *              actx;
216 };
217
218 /*
219  * These zones should not leak onto the Internet.
220  */
221 static const struct {
222         const char      *zone;
223         isc_boolean_t   rfc1918;
224 } empty_zones[] = {
225         /* RFC 1918 */
226         { "10.IN-ADDR.ARPA", ISC_TRUE },
227         { "16.172.IN-ADDR.ARPA", ISC_TRUE },
228         { "17.172.IN-ADDR.ARPA", ISC_TRUE },
229         { "18.172.IN-ADDR.ARPA", ISC_TRUE },
230         { "19.172.IN-ADDR.ARPA", ISC_TRUE },
231         { "20.172.IN-ADDR.ARPA", ISC_TRUE },
232         { "21.172.IN-ADDR.ARPA", ISC_TRUE },
233         { "22.172.IN-ADDR.ARPA", ISC_TRUE },
234         { "23.172.IN-ADDR.ARPA", ISC_TRUE },
235         { "24.172.IN-ADDR.ARPA", ISC_TRUE },
236         { "25.172.IN-ADDR.ARPA", ISC_TRUE },
237         { "26.172.IN-ADDR.ARPA", ISC_TRUE },
238         { "27.172.IN-ADDR.ARPA", ISC_TRUE },
239         { "28.172.IN-ADDR.ARPA", ISC_TRUE },
240         { "29.172.IN-ADDR.ARPA", ISC_TRUE },
241         { "30.172.IN-ADDR.ARPA", ISC_TRUE },
242         { "31.172.IN-ADDR.ARPA", ISC_TRUE },
243         { "168.192.IN-ADDR.ARPA", ISC_TRUE },
244
245         /* RFC 5735 and RFC 5737 */
246         { "0.IN-ADDR.ARPA", ISC_FALSE },        /* THIS NETWORK */
247         { "127.IN-ADDR.ARPA", ISC_FALSE },      /* LOOPBACK */
248         { "254.169.IN-ADDR.ARPA", ISC_FALSE },  /* LINK LOCAL */
249         { "2.0.192.IN-ADDR.ARPA", ISC_FALSE },  /* TEST NET */
250         { "100.51.198.IN-ADDR.ARPA", ISC_FALSE },       /* TEST NET 2 */
251         { "113.0.203.IN-ADDR.ARPA", ISC_FALSE },        /* TEST NET 3 */
252         { "255.255.255.255.IN-ADDR.ARPA", ISC_FALSE },  /* BROADCAST */
253
254         /* Local IPv6 Unicast Addresses */
255         { "0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.IP6.ARPA", ISC_FALSE },
256         { "1.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.IP6.ARPA", ISC_FALSE },
257         /* LOCALLY ASSIGNED LOCAL ADDRESS SCOPE */
258         { "D.F.IP6.ARPA", ISC_FALSE },
259         { "8.E.F.IP6.ARPA", ISC_FALSE },        /* LINK LOCAL */
260         { "9.E.F.IP6.ARPA", ISC_FALSE },        /* LINK LOCAL */
261         { "A.E.F.IP6.ARPA", ISC_FALSE },        /* LINK LOCAL */
262         { "B.E.F.IP6.ARPA", ISC_FALSE },        /* LINK LOCAL */
263
264         /* Example Prefix, RFC 3849. */
265         { "8.B.D.0.1.0.0.2.IP6.ARPA", ISC_FALSE },
266
267         { NULL, ISC_FALSE }
268 };
269
270 ISC_PLATFORM_NORETURN_PRE static void
271 fatal(const char *msg, isc_result_t result) ISC_PLATFORM_NORETURN_POST;
272
273 static void
274 ns_server_reload(isc_task_t *task, isc_event_t *event);
275
276 static isc_result_t
277 ns_listenelt_fromconfig(const cfg_obj_t *listener, const cfg_obj_t *config,
278                         cfg_aclconfctx_t *actx,
279                         isc_mem_t *mctx, ns_listenelt_t **target);
280 static isc_result_t
281 ns_listenlist_fromconfig(const cfg_obj_t *listenlist, const cfg_obj_t *config,
282                          cfg_aclconfctx_t *actx,
283                          isc_mem_t *mctx, ns_listenlist_t **target);
284
285 static isc_result_t
286 configure_forward(const cfg_obj_t *config, dns_view_t *view, dns_name_t *origin,
287                   const cfg_obj_t *forwarders, const cfg_obj_t *forwardtype);
288
289 static isc_result_t
290 configure_alternates(const cfg_obj_t *config, dns_view_t *view,
291                      const cfg_obj_t *alternates);
292
293 static isc_result_t
294 configure_zone(const cfg_obj_t *config, const cfg_obj_t *zconfig,
295                const cfg_obj_t *vconfig, isc_mem_t *mctx, dns_view_t *view,
296                cfg_aclconfctx_t *aclconf, isc_boolean_t added);
297
298 static isc_result_t
299 add_keydata_zone(dns_view_t *view, const char *directory, isc_mem_t *mctx);
300
301 static void
302 end_reserved_dispatches(ns_server_t *server, isc_boolean_t all);
303
304 static void
305 newzone_cfgctx_destroy(void **cfgp);
306
307 /*%
308  * Configure a single view ACL at '*aclp'.  Get its configuration from
309  * 'vconfig' (for per-view configuration) and maybe from 'config'
310  */
311 static isc_result_t
312 configure_view_acl(const cfg_obj_t *vconfig, const cfg_obj_t *config,
313                    const char *aclname, const char *acltuplename,
314                    cfg_aclconfctx_t *actx, isc_mem_t *mctx, dns_acl_t **aclp)
315 {
316         isc_result_t result;
317         const cfg_obj_t *maps[3];
318         const cfg_obj_t *aclobj = NULL;
319         int i = 0;
320
321         if (*aclp != NULL)
322                 dns_acl_detach(aclp);
323         if (vconfig != NULL)
324                 maps[i++] = cfg_tuple_get(vconfig, "options");
325         if (config != NULL) {
326                 const cfg_obj_t *options = NULL;
327                 (void)cfg_map_get(config, "options", &options);
328                 if (options != NULL)
329                         maps[i++] = options;
330         }
331         maps[i] = NULL;
332
333         (void)ns_config_get(maps, aclname, &aclobj);
334         if (aclobj == NULL)
335                 /*
336                  * No value available.  *aclp == NULL.
337                  */
338                 return (ISC_R_SUCCESS);
339
340         if (acltuplename != NULL) {
341                 /*
342                  * If the ACL is given in an optional tuple, retrieve it.
343                  * The parser should have ensured that a valid object be
344                  * returned.
345                  */
346                 aclobj = cfg_tuple_get(aclobj, acltuplename);
347         }
348
349         result = cfg_acl_fromconfig(aclobj, config, ns_g_lctx,
350                                     actx, mctx, 0, aclp);
351
352         return (result);
353 }
354
355 /*%
356  * Configure a sortlist at '*aclp'.  Essentially the same as
357  * configure_view_acl() except it calls cfg_acl_fromconfig with a
358  * nest_level value of 2.
359  */
360 static isc_result_t
361 configure_view_sortlist(const cfg_obj_t *vconfig, const cfg_obj_t *config,
362                         cfg_aclconfctx_t *actx, isc_mem_t *mctx,
363                         dns_acl_t **aclp)
364 {
365         isc_result_t result;
366         const cfg_obj_t *maps[3];
367         const cfg_obj_t *aclobj = NULL;
368         int i = 0;
369
370         if (*aclp != NULL)
371                 dns_acl_detach(aclp);
372         if (vconfig != NULL)
373                 maps[i++] = cfg_tuple_get(vconfig, "options");
374         if (config != NULL) {
375                 const cfg_obj_t *options = NULL;
376                 (void)cfg_map_get(config, "options", &options);
377                 if (options != NULL)
378                         maps[i++] = options;
379         }
380         maps[i] = NULL;
381
382         (void)ns_config_get(maps, "sortlist", &aclobj);
383         if (aclobj == NULL)
384                 return (ISC_R_SUCCESS);
385
386         /*
387          * Use a nest level of 3 for the "top level" of the sortlist;
388          * this means each entry in the top three levels will be stored
389          * as lists of separate, nested ACLs, rather than merged together
390          * into IP tables as is usually done with ACLs.
391          */
392         result = cfg_acl_fromconfig(aclobj, config, ns_g_lctx,
393                                     actx, mctx, 3, aclp);
394
395         return (result);
396 }
397
398 static isc_result_t
399 configure_view_nametable(const cfg_obj_t *vconfig, const cfg_obj_t *config,
400                          const char *confname, const char *conftuplename,
401                          isc_mem_t *mctx, dns_rbt_t **rbtp)
402 {
403         isc_result_t result;
404         const cfg_obj_t *maps[3];
405         const cfg_obj_t *obj = NULL;
406         const cfg_listelt_t *element;
407         int i = 0;
408         dns_fixedname_t fixed;
409         dns_name_t *name;
410         isc_buffer_t b;
411         const char *str;
412         const cfg_obj_t *nameobj;
413
414         if (*rbtp != NULL)
415                 dns_rbt_destroy(rbtp);
416         if (vconfig != NULL)
417                 maps[i++] = cfg_tuple_get(vconfig, "options");
418         if (config != NULL) {
419                 const cfg_obj_t *options = NULL;
420                 (void)cfg_map_get(config, "options", &options);
421                 if (options != NULL)
422                         maps[i++] = options;
423         }
424         maps[i] = NULL;
425
426         (void)ns_config_get(maps, confname, &obj);
427         if (obj == NULL)
428                 /*
429                  * No value available.  *rbtp == NULL.
430                  */
431                 return (ISC_R_SUCCESS);
432
433         if (conftuplename != NULL) {
434                 obj = cfg_tuple_get(obj, conftuplename);
435                 if (cfg_obj_isvoid(obj))
436                         return (ISC_R_SUCCESS);
437         }
438
439         result = dns_rbt_create(mctx, NULL, NULL, rbtp);
440         if (result != ISC_R_SUCCESS)
441                 return (result);
442
443         dns_fixedname_init(&fixed);
444         name = dns_fixedname_name(&fixed);
445         for (element = cfg_list_first(obj);
446              element != NULL;
447              element = cfg_list_next(element)) {
448                 nameobj = cfg_listelt_value(element);
449                 str = cfg_obj_asstring(nameobj);
450                 isc_buffer_init(&b, str, strlen(str));
451                 isc_buffer_add(&b, strlen(str));
452                 CHECK(dns_name_fromtext(name, &b, dns_rootname, 0, NULL));
453                 /*
454                  * We don't need the node data, but need to set dummy data to
455                  * avoid a partial match with an empty node.  For example, if
456                  * we have foo.example.com and bar.example.com, we'd get a match
457                  * for baz.example.com, which is not the expected result.
458                  * We simply use (void *)1 as the dummy data.
459                  */
460                 result = dns_rbt_addname(*rbtp, name, (void *)1);
461                 if (result != ISC_R_SUCCESS) {
462                         cfg_obj_log(nameobj, ns_g_lctx, ISC_LOG_ERROR,
463                                     "failed to add %s for %s: %s",
464                                     str, confname, isc_result_totext(result));
465                         goto cleanup;
466                 }
467
468         }
469
470         return (result);
471
472   cleanup:
473         dns_rbt_destroy(rbtp);
474         return (result);
475
476 }
477
478 static isc_result_t
479 dstkey_fromconfig(const cfg_obj_t *vconfig, const cfg_obj_t *key,
480                   isc_boolean_t managed, dst_key_t **target, isc_mem_t *mctx)
481 {
482         dns_rdataclass_t viewclass;
483         dns_rdata_dnskey_t keystruct;
484         isc_uint32_t flags, proto, alg;
485         const char *keystr, *keynamestr;
486         unsigned char keydata[4096];
487         isc_buffer_t keydatabuf;
488         unsigned char rrdata[4096];
489         isc_buffer_t rrdatabuf;
490         isc_region_t r;
491         dns_fixedname_t fkeyname;
492         dns_name_t *keyname;
493         isc_buffer_t namebuf;
494         isc_result_t result;
495         dst_key_t *dstkey = NULL;
496
497         INSIST(target != NULL && *target == NULL);
498
499         flags = cfg_obj_asuint32(cfg_tuple_get(key, "flags"));
500         proto = cfg_obj_asuint32(cfg_tuple_get(key, "protocol"));
501         alg = cfg_obj_asuint32(cfg_tuple_get(key, "algorithm"));
502         keyname = dns_fixedname_name(&fkeyname);
503         keynamestr = cfg_obj_asstring(cfg_tuple_get(key, "name"));
504
505         if (managed) {
506                 const char *initmethod;
507                 initmethod = cfg_obj_asstring(cfg_tuple_get(key, "init"));
508
509                 if (strcasecmp(initmethod, "initial-key") != 0) {
510                         cfg_obj_log(key, ns_g_lctx, ISC_LOG_ERROR,
511                                     "managed key '%s': "
512                                     "invalid initialization method '%s'",
513                                     keynamestr, initmethod);
514                         result = ISC_R_FAILURE;
515                         goto cleanup;
516                 }
517         }
518
519         if (vconfig == NULL)
520                 viewclass = dns_rdataclass_in;
521         else {
522                 const cfg_obj_t *classobj = cfg_tuple_get(vconfig, "class");
523                 CHECK(ns_config_getclass(classobj, dns_rdataclass_in,
524                                          &viewclass));
525         }
526         keystruct.common.rdclass = viewclass;
527         keystruct.common.rdtype = dns_rdatatype_dnskey;
528         /*
529          * The key data in keystruct is not dynamically allocated.
530          */
531         keystruct.mctx = NULL;
532
533         ISC_LINK_INIT(&keystruct.common, link);
534
535         if (flags > 0xffff)
536                 CHECKM(ISC_R_RANGE, "key flags");
537         if (proto > 0xff)
538                 CHECKM(ISC_R_RANGE, "key protocol");
539         if (alg > 0xff)
540                 CHECKM(ISC_R_RANGE, "key algorithm");
541         keystruct.flags = (isc_uint16_t)flags;
542         keystruct.protocol = (isc_uint8_t)proto;
543         keystruct.algorithm = (isc_uint8_t)alg;
544
545         isc_buffer_init(&keydatabuf, keydata, sizeof(keydata));
546         isc_buffer_init(&rrdatabuf, rrdata, sizeof(rrdata));
547
548         keystr = cfg_obj_asstring(cfg_tuple_get(key, "key"));
549         CHECK(isc_base64_decodestring(keystr, &keydatabuf));
550         isc_buffer_usedregion(&keydatabuf, &r);
551         keystruct.datalen = r.length;
552         keystruct.data = r.base;
553
554         if ((keystruct.algorithm == DST_ALG_RSASHA1 ||
555              keystruct.algorithm == DST_ALG_RSAMD5) &&
556             r.length > 1 && r.base[0] == 1 && r.base[1] == 3)
557                 cfg_obj_log(key, ns_g_lctx, ISC_LOG_WARNING,
558                             "%s key '%s' has a weak exponent",
559                             managed ? "managed" : "trusted",
560                             keynamestr);
561
562         CHECK(dns_rdata_fromstruct(NULL,
563                                    keystruct.common.rdclass,
564                                    keystruct.common.rdtype,
565                                    &keystruct, &rrdatabuf));
566         dns_fixedname_init(&fkeyname);
567         isc_buffer_init(&namebuf, keynamestr, strlen(keynamestr));
568         isc_buffer_add(&namebuf, strlen(keynamestr));
569         CHECK(dns_name_fromtext(keyname, &namebuf, dns_rootname, 0, NULL));
570         CHECK(dst_key_fromdns(keyname, viewclass, &rrdatabuf,
571                               mctx, &dstkey));
572
573         *target = dstkey;
574         return (ISC_R_SUCCESS);
575
576  cleanup:
577         if (result == DST_R_NOCRYPTO) {
578                 cfg_obj_log(key, ns_g_lctx, ISC_LOG_ERROR,
579                             "ignoring %s key for '%s': no crypto support",
580                             managed ? "managed" : "trusted",
581                             keynamestr);
582         } else if (result == DST_R_UNSUPPORTEDALG) {
583                 cfg_obj_log(key, ns_g_lctx, ISC_LOG_WARNING,
584                             "skipping %s key for '%s': %s",
585                             managed ? "managed" : "trusted",
586                             keynamestr, isc_result_totext(result));
587         } else {
588                 cfg_obj_log(key, ns_g_lctx, ISC_LOG_ERROR,
589                             "configuring %s key for '%s': %s",
590                             managed ? "managed" : "trusted",
591                             keynamestr, isc_result_totext(result));
592                 result = ISC_R_FAILURE;
593         }
594
595         if (dstkey != NULL)
596                 dst_key_free(&dstkey);
597
598         return (result);
599 }
600
601 static isc_result_t
602 load_view_keys(const cfg_obj_t *keys, const cfg_obj_t *vconfig,
603                dns_view_t *view, isc_boolean_t managed,
604                dns_name_t *keyname, isc_mem_t *mctx)
605 {
606         const cfg_listelt_t *elt, *elt2;
607         const cfg_obj_t *key, *keylist;
608         dst_key_t *dstkey = NULL;
609         isc_result_t result;
610         dns_keytable_t *secroots = NULL;
611
612         CHECK(dns_view_getsecroots(view, &secroots));
613
614         for (elt = cfg_list_first(keys);
615              elt != NULL;
616              elt = cfg_list_next(elt)) {
617                 keylist = cfg_listelt_value(elt);
618
619                 for (elt2 = cfg_list_first(keylist);
620                      elt2 != NULL;
621                      elt2 = cfg_list_next(elt2)) {
622                         key = cfg_listelt_value(elt2);
623                         result = dstkey_fromconfig(vconfig, key, managed,
624                                                    &dstkey, mctx);
625                         if (result ==  DST_R_UNSUPPORTEDALG) {
626                                 result = ISC_R_SUCCESS;
627                                 continue;
628                         }
629                         if (result != ISC_R_SUCCESS)
630                                 goto cleanup;
631
632                         /*
633                          * If keyname was specified, we only add that key.
634                          */
635                         if (keyname != NULL &&
636                             !dns_name_equal(keyname, dst_key_name(dstkey)))
637                         {
638                                 dst_key_free(&dstkey);
639                                 continue;
640                         }
641
642                         CHECK(dns_keytable_add(secroots, managed, &dstkey));
643                 }
644         }
645
646  cleanup:
647         if (dstkey != NULL)
648                 dst_key_free(&dstkey);
649         if (secroots != NULL)
650                 dns_keytable_detach(&secroots);
651         if (result == DST_R_NOCRYPTO)
652                 result = ISC_R_SUCCESS;
653         return (result);
654 }
655
656 /*%
657  * Configure DNSSEC keys for a view.
658  *
659  * The per-view configuration values and the server-global defaults are read
660  * from 'vconfig' and 'config'.
661  */
662 static isc_result_t
663 configure_view_dnsseckeys(dns_view_t *view, const cfg_obj_t *vconfig,
664                           const cfg_obj_t *config, const cfg_obj_t *bindkeys,
665                           isc_boolean_t auto_dlv, isc_boolean_t auto_root,
666                           isc_mem_t *mctx)
667 {
668         isc_result_t result = ISC_R_SUCCESS;
669         const cfg_obj_t *view_keys = NULL;
670         const cfg_obj_t *global_keys = NULL;
671         const cfg_obj_t *view_managed_keys = NULL;
672         const cfg_obj_t *global_managed_keys = NULL;
673         const cfg_obj_t *maps[4];
674         const cfg_obj_t *voptions = NULL;
675         const cfg_obj_t *options = NULL;
676         const cfg_obj_t *obj = NULL;
677         const char *directory;
678         int i = 0;
679
680         /* We don't need trust anchors for the _bind view */
681         if (strcmp(view->name, "_bind") == 0 &&
682             view->rdclass == dns_rdataclass_chaos) {
683                 return (ISC_R_SUCCESS);
684         }
685
686         if (vconfig != NULL) {
687                 voptions = cfg_tuple_get(vconfig, "options");
688                 if (voptions != NULL) {
689                         (void) cfg_map_get(voptions, "trusted-keys",
690                                            &view_keys);
691                         (void) cfg_map_get(voptions, "managed-keys",
692                                            &view_managed_keys);
693                         maps[i++] = voptions;
694                 }
695         }
696
697         if (config != NULL) {
698                 (void)cfg_map_get(config, "trusted-keys", &global_keys);
699                 (void)cfg_map_get(config, "managed-keys", &global_managed_keys);
700                 (void)cfg_map_get(config, "options", &options);
701                 if (options != NULL) {
702                         maps[i++] = options;
703                 }
704         }
705
706         maps[i++] = ns_g_defaults;
707         maps[i] = NULL;
708
709         result = dns_view_initsecroots(view, mctx);
710         if (result != ISC_R_SUCCESS) {
711                 isc_log_write(ns_g_lctx, NS_LOGCATEGORY_GENERAL,
712                               NS_LOGMODULE_SERVER, ISC_LOG_ERROR,
713                               "couldn't create keytable");
714                 return (ISC_R_UNEXPECTED);
715         }
716
717         if (auto_dlv && view->rdclass == dns_rdataclass_in) {
718                 const cfg_obj_t *builtin_keys = NULL;
719                 const cfg_obj_t *builtin_managed_keys = NULL;
720
721                 isc_log_write(ns_g_lctx, DNS_LOGCATEGORY_SECURITY,
722                               NS_LOGMODULE_SERVER, ISC_LOG_WARNING,
723                               "using built-in DLV key for view %s",
724                               view->name);
725
726                 /*
727                  * If bind.keys exists, it overrides the managed-keys
728                  * clause hard-coded in ns_g_config.
729                  */
730                 if (bindkeys != NULL) {
731                         (void)cfg_map_get(bindkeys, "trusted-keys",
732                                           &builtin_keys);
733                         (void)cfg_map_get(bindkeys, "managed-keys",
734                                           &builtin_managed_keys);
735                 } else {
736                         (void)cfg_map_get(ns_g_config, "trusted-keys",
737                                           &builtin_keys);
738                         (void)cfg_map_get(ns_g_config, "managed-keys",
739                                           &builtin_managed_keys);
740                 }
741
742                 if (builtin_keys != NULL)
743                         CHECK(load_view_keys(builtin_keys, vconfig, view,
744                                              ISC_FALSE, view->dlv, mctx));
745                 if (builtin_managed_keys != NULL)
746                         CHECK(load_view_keys(builtin_managed_keys, vconfig,
747                                              view, ISC_TRUE, view->dlv, mctx));
748         }
749
750         if (auto_root && view->rdclass == dns_rdataclass_in) {
751                 const cfg_obj_t *builtin_keys = NULL;
752                 const cfg_obj_t *builtin_managed_keys = NULL;
753
754                 isc_log_write(ns_g_lctx, DNS_LOGCATEGORY_SECURITY,
755                               NS_LOGMODULE_SERVER, ISC_LOG_WARNING,
756                               "using built-in root key for view %s",
757                               view->name);
758
759                 /*
760                  * If bind.keys exists, it overrides the managed-keys
761                  * clause hard-coded in ns_g_config.
762                  */
763                 if (bindkeys != NULL) {
764                         (void)cfg_map_get(bindkeys, "trusted-keys",
765                                           &builtin_keys);
766                         (void)cfg_map_get(bindkeys, "managed-keys",
767                                           &builtin_managed_keys);
768                 } else {
769                         (void)cfg_map_get(ns_g_config, "trusted-keys",
770                                           &builtin_keys);
771                         (void)cfg_map_get(ns_g_config, "managed-keys",
772                                           &builtin_managed_keys);
773                 }
774
775                 if (builtin_keys != NULL)
776                         CHECK(load_view_keys(builtin_keys, vconfig, view,
777                                              ISC_FALSE, dns_rootname, mctx));
778                 if (builtin_managed_keys != NULL)
779                         CHECK(load_view_keys(builtin_managed_keys, vconfig,
780                                              view, ISC_TRUE, dns_rootname,
781                                              mctx));
782         }
783
784         CHECK(load_view_keys(view_keys, vconfig, view, ISC_FALSE,
785                              NULL, mctx));
786         CHECK(load_view_keys(view_managed_keys, vconfig, view, ISC_TRUE,
787                              NULL, mctx));
788
789         if (view->rdclass == dns_rdataclass_in) {
790                 CHECK(load_view_keys(global_keys, vconfig, view, ISC_FALSE,
791                                      NULL, mctx));
792                 CHECK(load_view_keys(global_managed_keys, vconfig, view,
793                                      ISC_TRUE, NULL, mctx));
794         }
795
796         /*
797          * Add key zone for managed-keys.
798          */
799         obj = NULL;
800         (void)ns_config_get(maps, "managed-keys-directory", &obj);
801         directory = obj != NULL ? cfg_obj_asstring(obj) : NULL;
802         CHECK(add_keydata_zone(view, directory, ns_g_mctx));
803
804   cleanup:
805         return (result);
806 }
807
808 static isc_result_t
809 mustbesecure(const cfg_obj_t *mbs, dns_resolver_t *resolver) {
810         const cfg_listelt_t *element;
811         const cfg_obj_t *obj;
812         const char *str;
813         dns_fixedname_t fixed;
814         dns_name_t *name;
815         isc_boolean_t value;
816         isc_result_t result;
817         isc_buffer_t b;
818
819         dns_fixedname_init(&fixed);
820         name = dns_fixedname_name(&fixed);
821         for (element = cfg_list_first(mbs);
822              element != NULL;
823              element = cfg_list_next(element))
824         {
825                 obj = cfg_listelt_value(element);
826                 str = cfg_obj_asstring(cfg_tuple_get(obj, "name"));
827                 isc_buffer_init(&b, str, strlen(str));
828                 isc_buffer_add(&b, strlen(str));
829                 CHECK(dns_name_fromtext(name, &b, dns_rootname, 0, NULL));
830                 value = cfg_obj_asboolean(cfg_tuple_get(obj, "value"));
831                 CHECK(dns_resolver_setmustbesecure(resolver, name, value));
832         }
833
834         result = ISC_R_SUCCESS;
835
836  cleanup:
837         return (result);
838 }
839
840 /*%
841  * Get a dispatch appropriate for the resolver of a given view.
842  */
843 static isc_result_t
844 get_view_querysource_dispatch(const cfg_obj_t **maps,
845                               int af, dns_dispatch_t **dispatchp,
846                               isc_boolean_t is_firstview)
847 {
848         isc_result_t result = ISC_R_FAILURE;
849         dns_dispatch_t *disp;
850         isc_sockaddr_t sa;
851         unsigned int attrs, attrmask;
852         const cfg_obj_t *obj = NULL;
853         unsigned int maxdispatchbuffers;
854
855         switch (af) {
856         case AF_INET:
857                 result = ns_config_get(maps, "query-source", &obj);
858                 INSIST(result == ISC_R_SUCCESS);
859                 break;
860         case AF_INET6:
861                 result = ns_config_get(maps, "query-source-v6", &obj);
862                 INSIST(result == ISC_R_SUCCESS);
863                 break;
864         default:
865                 INSIST(0);
866         }
867
868         sa = *(cfg_obj_assockaddr(obj));
869         INSIST(isc_sockaddr_pf(&sa) == af);
870
871         /*
872          * If we don't support this address family, we're done!
873          */
874         switch (af) {
875         case AF_INET:
876                 result = isc_net_probeipv4();
877                 break;
878         case AF_INET6:
879                 result = isc_net_probeipv6();
880                 break;
881         default:
882                 INSIST(0);
883         }
884         if (result != ISC_R_SUCCESS)
885                 return (ISC_R_SUCCESS);
886
887         /*
888          * Try to find a dispatcher that we can share.
889          */
890         attrs = 0;
891         attrs |= DNS_DISPATCHATTR_UDP;
892         switch (af) {
893         case AF_INET:
894                 attrs |= DNS_DISPATCHATTR_IPV4;
895                 break;
896         case AF_INET6:
897                 attrs |= DNS_DISPATCHATTR_IPV6;
898                 break;
899         }
900         if (isc_sockaddr_getport(&sa) == 0) {
901                 attrs |= DNS_DISPATCHATTR_EXCLUSIVE;
902                 maxdispatchbuffers = 4096;
903         } else {
904                 INSIST(obj != NULL);
905                 if (is_firstview) {
906                         cfg_obj_log(obj, ns_g_lctx, ISC_LOG_INFO,
907                                     "using specific query-source port "
908                                     "suppresses port randomization and can be "
909                                     "insecure.");
910                 }
911                 maxdispatchbuffers = 1000;
912         }
913
914         attrmask = 0;
915         attrmask |= DNS_DISPATCHATTR_UDP;
916         attrmask |= DNS_DISPATCHATTR_TCP;
917         attrmask |= DNS_DISPATCHATTR_IPV4;
918         attrmask |= DNS_DISPATCHATTR_IPV6;
919
920         disp = NULL;
921         result = dns_dispatch_getudp(ns_g_dispatchmgr, ns_g_socketmgr,
922                                      ns_g_taskmgr, &sa, 4096,
923                                      maxdispatchbuffers, 32768, 16411, 16433,
924                                      attrs, attrmask, &disp);
925         if (result != ISC_R_SUCCESS) {
926                 isc_sockaddr_t any;
927                 char buf[ISC_SOCKADDR_FORMATSIZE];
928
929                 switch (af) {
930                 case AF_INET:
931                         isc_sockaddr_any(&any);
932                         break;
933                 case AF_INET6:
934                         isc_sockaddr_any6(&any);
935                         break;
936                 }
937                 if (isc_sockaddr_equal(&sa, &any))
938                         return (ISC_R_SUCCESS);
939                 isc_sockaddr_format(&sa, buf, sizeof(buf));
940                 isc_log_write(ns_g_lctx, NS_LOGCATEGORY_GENERAL,
941                               NS_LOGMODULE_SERVER, ISC_LOG_ERROR,
942                               "could not get query source dispatcher (%s)",
943                               buf);
944                 return (result);
945         }
946
947         *dispatchp = disp;
948
949         return (ISC_R_SUCCESS);
950 }
951
952 static isc_result_t
953 configure_order(dns_order_t *order, const cfg_obj_t *ent) {
954         dns_rdataclass_t rdclass;
955         dns_rdatatype_t rdtype;
956         const cfg_obj_t *obj;
957         dns_fixedname_t fixed;
958         unsigned int mode = 0;
959         const char *str;
960         isc_buffer_t b;
961         isc_result_t result;
962         isc_boolean_t addroot;
963
964         result = ns_config_getclass(cfg_tuple_get(ent, "class"),
965                                     dns_rdataclass_any, &rdclass);
966         if (result != ISC_R_SUCCESS)
967                 return (result);
968
969         result = ns_config_gettype(cfg_tuple_get(ent, "type"),
970                                    dns_rdatatype_any, &rdtype);
971         if (result != ISC_R_SUCCESS)
972                 return (result);
973
974         obj = cfg_tuple_get(ent, "name");
975         if (cfg_obj_isstring(obj))
976                 str = cfg_obj_asstring(obj);
977         else
978                 str = "*";
979         addroot = ISC_TF(strcmp(str, "*") == 0);
980         isc_buffer_init(&b, str, strlen(str));
981         isc_buffer_add(&b, strlen(str));
982         dns_fixedname_init(&fixed);
983         result = dns_name_fromtext(dns_fixedname_name(&fixed), &b,
984                                    dns_rootname, 0, NULL);
985         if (result != ISC_R_SUCCESS)
986                 return (result);
987
988         obj = cfg_tuple_get(ent, "ordering");
989         INSIST(cfg_obj_isstring(obj));
990         str = cfg_obj_asstring(obj);
991         if (!strcasecmp(str, "fixed"))
992                 mode = DNS_RDATASETATTR_FIXEDORDER;
993         else if (!strcasecmp(str, "random"))
994                 mode = DNS_RDATASETATTR_RANDOMIZE;
995         else if (!strcasecmp(str, "cyclic"))
996                 mode = 0;
997         else
998                 INSIST(0);
999
1000         /*
1001          * "*" should match everything including the root (BIND 8 compat).
1002          * As dns_name_matcheswildcard(".", "*.") returns FALSE add a
1003          * explicit entry for "." when the name is "*".
1004          */
1005         if (addroot) {
1006                 result = dns_order_add(order, dns_rootname,
1007                                        rdtype, rdclass, mode);
1008                 if (result != ISC_R_SUCCESS)
1009                         return (result);
1010         }
1011
1012         return (dns_order_add(order, dns_fixedname_name(&fixed),
1013                               rdtype, rdclass, mode));
1014 }
1015
1016 static isc_result_t
1017 configure_peer(const cfg_obj_t *cpeer, isc_mem_t *mctx, dns_peer_t **peerp) {
1018         isc_netaddr_t na;
1019         dns_peer_t *peer;
1020         const cfg_obj_t *obj;
1021         const char *str;
1022         isc_result_t result;
1023         unsigned int prefixlen;
1024
1025         cfg_obj_asnetprefix(cfg_map_getname(cpeer), &na, &prefixlen);
1026
1027         peer = NULL;
1028         result = dns_peer_newprefix(mctx, &na, prefixlen, &peer);
1029         if (result != ISC_R_SUCCESS)
1030                 return (result);
1031
1032         obj = NULL;
1033         (void)cfg_map_get(cpeer, "bogus", &obj);
1034         if (obj != NULL)
1035                 CHECK(dns_peer_setbogus(peer, cfg_obj_asboolean(obj)));
1036
1037         obj = NULL;
1038         (void)cfg_map_get(cpeer, "provide-ixfr", &obj);
1039         if (obj != NULL)
1040                 CHECK(dns_peer_setprovideixfr(peer, cfg_obj_asboolean(obj)));
1041
1042         obj = NULL;
1043         (void)cfg_map_get(cpeer, "request-ixfr", &obj);
1044         if (obj != NULL)
1045                 CHECK(dns_peer_setrequestixfr(peer, cfg_obj_asboolean(obj)));
1046
1047         obj = NULL;
1048         (void)cfg_map_get(cpeer, "request-nsid", &obj);
1049         if (obj != NULL)
1050                 CHECK(dns_peer_setrequestnsid(peer, cfg_obj_asboolean(obj)));
1051
1052         obj = NULL;
1053         (void)cfg_map_get(cpeer, "edns", &obj);
1054         if (obj != NULL)
1055                 CHECK(dns_peer_setsupportedns(peer, cfg_obj_asboolean(obj)));
1056
1057         obj = NULL;
1058         (void)cfg_map_get(cpeer, "edns-udp-size", &obj);
1059         if (obj != NULL) {
1060                 isc_uint32_t udpsize = cfg_obj_asuint32(obj);
1061                 if (udpsize < 512)
1062                         udpsize = 512;
1063                 if (udpsize > 4096)
1064                         udpsize = 4096;
1065                 CHECK(dns_peer_setudpsize(peer, (isc_uint16_t)udpsize));
1066         }
1067
1068         obj = NULL;
1069         (void)cfg_map_get(cpeer, "max-udp-size", &obj);
1070         if (obj != NULL) {
1071                 isc_uint32_t udpsize = cfg_obj_asuint32(obj);
1072                 if (udpsize < 512)
1073                         udpsize = 512;
1074                 if (udpsize > 4096)
1075                         udpsize = 4096;
1076                 CHECK(dns_peer_setmaxudp(peer, (isc_uint16_t)udpsize));
1077         }
1078
1079         obj = NULL;
1080         (void)cfg_map_get(cpeer, "transfers", &obj);
1081         if (obj != NULL)
1082                 CHECK(dns_peer_settransfers(peer, cfg_obj_asuint32(obj)));
1083
1084         obj = NULL;
1085         (void)cfg_map_get(cpeer, "transfer-format", &obj);
1086         if (obj != NULL) {
1087                 str = cfg_obj_asstring(obj);
1088                 if (strcasecmp(str, "many-answers") == 0)
1089                         CHECK(dns_peer_settransferformat(peer,
1090                                                          dns_many_answers));
1091                 else if (strcasecmp(str, "one-answer") == 0)
1092                         CHECK(dns_peer_settransferformat(peer,
1093                                                          dns_one_answer));
1094                 else
1095                         INSIST(0);
1096         }
1097
1098         obj = NULL;
1099         (void)cfg_map_get(cpeer, "keys", &obj);
1100         if (obj != NULL) {
1101                 result = dns_peer_setkeybycharp(peer, cfg_obj_asstring(obj));
1102                 if (result != ISC_R_SUCCESS)
1103                         goto cleanup;
1104         }
1105
1106         obj = NULL;
1107         if (na.family == AF_INET)
1108                 (void)cfg_map_get(cpeer, "transfer-source", &obj);
1109         else
1110                 (void)cfg_map_get(cpeer, "transfer-source-v6", &obj);
1111         if (obj != NULL) {
1112                 result = dns_peer_settransfersource(peer,
1113                                                     cfg_obj_assockaddr(obj));
1114                 if (result != ISC_R_SUCCESS)
1115                         goto cleanup;
1116                 ns_add_reserved_dispatch(ns_g_server, cfg_obj_assockaddr(obj));
1117         }
1118
1119         obj = NULL;
1120         if (na.family == AF_INET)
1121                 (void)cfg_map_get(cpeer, "notify-source", &obj);
1122         else
1123                 (void)cfg_map_get(cpeer, "notify-source-v6", &obj);
1124         if (obj != NULL) {
1125                 result = dns_peer_setnotifysource(peer,
1126                                                   cfg_obj_assockaddr(obj));
1127                 if (result != ISC_R_SUCCESS)
1128                         goto cleanup;
1129                 ns_add_reserved_dispatch(ns_g_server, cfg_obj_assockaddr(obj));
1130         }
1131
1132         obj = NULL;
1133         if (na.family == AF_INET)
1134                 (void)cfg_map_get(cpeer, "query-source", &obj);
1135         else
1136                 (void)cfg_map_get(cpeer, "query-source-v6", &obj);
1137         if (obj != NULL) {
1138                 result = dns_peer_setquerysource(peer,
1139                                                  cfg_obj_assockaddr(obj));
1140                 if (result != ISC_R_SUCCESS)
1141                         goto cleanup;
1142                 ns_add_reserved_dispatch(ns_g_server, cfg_obj_assockaddr(obj));
1143         }
1144
1145         *peerp = peer;
1146         return (ISC_R_SUCCESS);
1147
1148  cleanup:
1149         dns_peer_detach(&peer);
1150         return (result);
1151 }
1152
1153 static isc_result_t
1154 disable_algorithms(const cfg_obj_t *disabled, dns_resolver_t *resolver) {
1155         isc_result_t result;
1156         const cfg_obj_t *algorithms;
1157         const cfg_listelt_t *element;
1158         const char *str;
1159         dns_fixedname_t fixed;
1160         dns_name_t *name;
1161         isc_buffer_t b;
1162
1163         dns_fixedname_init(&fixed);
1164         name = dns_fixedname_name(&fixed);
1165         str = cfg_obj_asstring(cfg_tuple_get(disabled, "name"));
1166         isc_buffer_init(&b, str, strlen(str));
1167         isc_buffer_add(&b, strlen(str));
1168         CHECK(dns_name_fromtext(name, &b, dns_rootname, 0, NULL));
1169
1170         algorithms = cfg_tuple_get(disabled, "algorithms");
1171         for (element = cfg_list_first(algorithms);
1172              element != NULL;
1173              element = cfg_list_next(element))
1174         {
1175                 isc_textregion_t r;
1176                 dns_secalg_t alg;
1177
1178                 DE_CONST(cfg_obj_asstring(cfg_listelt_value(element)), r.base);
1179                 r.length = strlen(r.base);
1180
1181                 result = dns_secalg_fromtext(&alg, &r);
1182                 if (result != ISC_R_SUCCESS) {
1183                         isc_uint8_t ui;
1184                         result = isc_parse_uint8(&ui, r.base, 10);
1185                         alg = ui;
1186                 }
1187                 if (result != ISC_R_SUCCESS) {
1188                         cfg_obj_log(cfg_listelt_value(element),
1189                                     ns_g_lctx, ISC_LOG_ERROR,
1190                                     "invalid algorithm");
1191                         CHECK(result);
1192                 }
1193                 CHECK(dns_resolver_disable_algorithm(resolver, name, alg));
1194         }
1195  cleanup:
1196         return (result);
1197 }
1198
1199 static isc_boolean_t
1200 on_disable_list(const cfg_obj_t *disablelist, dns_name_t *zonename) {
1201         const cfg_listelt_t *element;
1202         dns_fixedname_t fixed;
1203         dns_name_t *name;
1204         isc_result_t result;
1205         const cfg_obj_t *value;
1206         const char *str;
1207         isc_buffer_t b;
1208
1209         dns_fixedname_init(&fixed);
1210         name = dns_fixedname_name(&fixed);
1211
1212         for (element = cfg_list_first(disablelist);
1213              element != NULL;
1214              element = cfg_list_next(element))
1215         {
1216                 value = cfg_listelt_value(element);
1217                 str = cfg_obj_asstring(value);
1218                 isc_buffer_init(&b, str, strlen(str));
1219                 isc_buffer_add(&b, strlen(str));
1220                 result = dns_name_fromtext(name, &b, dns_rootname,
1221                                            0, NULL);
1222                 RUNTIME_CHECK(result == ISC_R_SUCCESS);
1223                 if (dns_name_equal(name, zonename))
1224                         return (ISC_TRUE);
1225         }
1226         return (ISC_FALSE);
1227 }
1228
1229 static void
1230 check_dbtype(dns_zone_t **zonep, unsigned int dbtypec, const char **dbargv,
1231              isc_mem_t *mctx)
1232 {
1233         char **argv = NULL;
1234         unsigned int i;
1235         isc_result_t result;
1236
1237         result = dns_zone_getdbtype(*zonep, &argv, mctx);
1238         if (result != ISC_R_SUCCESS) {
1239                 dns_zone_detach(zonep);
1240                 return;
1241         }
1242
1243         /*
1244          * Check that all the arguments match.
1245          */
1246         for (i = 0; i < dbtypec; i++)
1247                 if (argv[i] == NULL || strcmp(argv[i], dbargv[i]) != 0) {
1248                         dns_zone_detach(zonep);
1249                         break;
1250                 }
1251
1252         /*
1253          * Check that there are not extra arguments.
1254          */
1255         if (i == dbtypec && argv[i] != NULL)
1256                 dns_zone_detach(zonep);
1257         isc_mem_free(mctx, argv);
1258 }
1259
1260 static isc_result_t
1261 setquerystats(dns_zone_t *zone, isc_mem_t *mctx, isc_boolean_t on) {
1262         isc_result_t result;
1263         isc_stats_t *zoneqrystats;
1264
1265         zoneqrystats = NULL;
1266         if (on) {
1267                 result = isc_stats_create(mctx, &zoneqrystats,
1268                                           dns_nsstatscounter_max);
1269                 if (result != ISC_R_SUCCESS)
1270                         return (result);
1271         }
1272         dns_zone_setrequeststats(zone, zoneqrystats);
1273         if (zoneqrystats != NULL)
1274                 isc_stats_detach(&zoneqrystats);
1275
1276         return (ISC_R_SUCCESS);
1277 }
1278
1279 static ns_cache_t *
1280 cachelist_find(ns_cachelist_t *cachelist, const char *cachename) {
1281         ns_cache_t *nsc;
1282
1283         for (nsc = ISC_LIST_HEAD(*cachelist);
1284              nsc != NULL;
1285              nsc = ISC_LIST_NEXT(nsc, link)) {
1286                 if (strcmp(dns_cache_getname(nsc->cache), cachename) == 0)
1287                         return (nsc);
1288         }
1289
1290         return (NULL);
1291 }
1292
1293 static isc_boolean_t
1294 cache_reusable(dns_view_t *originview, dns_view_t *view,
1295                isc_boolean_t new_zero_no_soattl)
1296 {
1297         if (originview->checknames != view->checknames ||
1298             dns_resolver_getzeronosoattl(originview->resolver) !=
1299             new_zero_no_soattl ||
1300             originview->acceptexpired != view->acceptexpired ||
1301             originview->enablevalidation != view->enablevalidation ||
1302             originview->maxcachettl != view->maxcachettl ||
1303             originview->maxncachettl != view->maxncachettl) {
1304                 return (ISC_FALSE);
1305         }
1306
1307         return (ISC_TRUE);
1308 }
1309
1310 static isc_boolean_t
1311 cache_sharable(dns_view_t *originview, dns_view_t *view,
1312                isc_boolean_t new_zero_no_soattl,
1313                unsigned int new_cleaning_interval,
1314                isc_uint32_t new_max_cache_size)
1315 {
1316         /*
1317          * If the cache cannot even reused for the same view, it cannot be
1318          * shared with other views.
1319          */
1320         if (!cache_reusable(originview, view, new_zero_no_soattl))
1321                 return (ISC_FALSE);
1322
1323         /*
1324          * Check other cache related parameters that must be consistent among
1325          * the sharing views.
1326          */
1327         if (dns_cache_getcleaninginterval(originview->cache) !=
1328             new_cleaning_interval ||
1329             dns_cache_getcachesize(originview->cache) != new_max_cache_size) {
1330                 return (ISC_FALSE);
1331         }
1332
1333         return (ISC_TRUE);
1334 }
1335
1336 /*
1337  * Callback from DLZ configure when the driver sets up a writeable zone
1338  */
1339 static isc_result_t
1340 dlzconfigure_callback(dns_view_t *view, dns_zone_t *zone) {
1341         dns_name_t *origin = dns_zone_getorigin(zone);
1342         dns_rdataclass_t zclass = view->rdclass;
1343         isc_result_t result;
1344
1345         result = dns_zonemgr_managezone(ns_g_server->zonemgr, zone);
1346         if (result != ISC_R_SUCCESS)
1347                 return result;
1348         dns_zone_setstats(zone, ns_g_server->zonestats);
1349
1350         return ns_zone_configure_writeable_dlz(view->dlzdatabase,
1351                                                zone, zclass, origin);
1352 }
1353
1354 static isc_result_t
1355 dns64_reverse(dns_view_t *view, isc_mem_t *mctx, isc_netaddr_t *na,
1356               unsigned int prefixlen, const char *server,
1357               const char *contact)
1358 {
1359         char *cp;
1360         char reverse[48+sizeof("ip6.arpa.")];
1361         const char *dns64_dbtype[4] = { "_dns64", "dns64", ".", "." };
1362         const char *sep = ": view ";
1363         const char *viewname = view->name;
1364         const unsigned char *s6;
1365         dns_fixedname_t fixed;
1366         dns_name_t *name;
1367         dns_zone_t *zone = NULL;
1368         int dns64_dbtypec = 4;
1369         isc_buffer_t b;
1370         isc_result_t result;
1371
1372         REQUIRE(prefixlen == 32 || prefixlen == 40 || prefixlen == 48 ||
1373                 prefixlen == 56 || prefixlen == 64 || prefixlen == 96);
1374
1375         if (!strcmp(viewname, "_default")) {
1376                 sep = "";
1377                 viewname = "";
1378         }
1379
1380         /*
1381          * Construct the reverse name of the zone.
1382          */
1383         cp = reverse;
1384         s6 = na->type.in6.s6_addr;
1385         while (prefixlen > 0) {
1386                 prefixlen -= 8;
1387                 sprintf(cp, "%x.%x.", s6[prefixlen/8] & 0xf,
1388                         (s6[prefixlen/8] >> 4) & 0xf);
1389                 cp += 4;
1390         }
1391         strcat(cp, "ip6.arpa.");
1392
1393         /*
1394          * Create the actual zone.
1395          */
1396         if (server != NULL)
1397                 dns64_dbtype[2] = server;
1398         if (contact != NULL)
1399                 dns64_dbtype[3] = contact;
1400         dns_fixedname_init(&fixed);
1401         name = dns_fixedname_name(&fixed);
1402         isc_buffer_init(&b, reverse, strlen(reverse));
1403         isc_buffer_add(&b, strlen(reverse));
1404         CHECK(dns_name_fromtext(name, &b, dns_rootname, 0, NULL));
1405         CHECK(dns_zone_create(&zone, mctx));
1406         CHECK(dns_zone_setorigin(zone, name));
1407         dns_zone_setview(zone, view);
1408         CHECK(dns_zonemgr_managezone(ns_g_server->zonemgr, zone));
1409         dns_zone_setclass(zone, view->rdclass);
1410         dns_zone_settype(zone, dns_zone_master);
1411         dns_zone_setstats(zone, ns_g_server->zonestats);
1412         CHECK(dns_zone_setdbtype(zone, dns64_dbtypec, dns64_dbtype));
1413         if (view->queryacl != NULL)
1414                 dns_zone_setqueryacl(zone, view->queryacl);
1415         if (view->queryonacl != NULL)
1416                 dns_zone_setqueryonacl(zone, view->queryonacl);
1417         dns_zone_setdialup(zone, dns_dialuptype_no);
1418         dns_zone_setnotifytype(zone, dns_notifytype_no);
1419         dns_zone_setoption(zone, DNS_ZONEOPT_NOCHECKNS, ISC_TRUE);
1420         CHECK(setquerystats(zone, mctx, ISC_FALSE));    /* XXXMPA */
1421         CHECK(dns_view_addzone(view, zone));
1422         isc_log_write(ns_g_lctx, NS_LOGCATEGORY_GENERAL, NS_LOGMODULE_SERVER,
1423                       ISC_LOG_INFO, "dns64 reverse zone%s%s: %s", sep,
1424                       viewname, reverse);
1425
1426 cleanup:
1427         if (zone != NULL)
1428                 dns_zone_detach(&zone);
1429         return (result);
1430 }
1431
1432 static isc_result_t
1433 configure_rpz(dns_view_t *view, const cfg_listelt_t *element,
1434               isc_boolean_t recursive_only_def, dns_ttl_t ttl_def)
1435 {
1436         const cfg_obj_t *rpz_obj, *policy_obj, *obj;
1437         const char *str;
1438         dns_rpz_zone_t *old, *new;
1439         dns_zone_t *zone = NULL;
1440         isc_result_t result;
1441
1442         new = isc_mem_get(view->mctx, sizeof(*new));
1443         if (new == NULL) {
1444                 result = ISC_R_NOMEMORY;
1445                 goto cleanup;
1446         }
1447
1448         memset(new, 0, sizeof(*new));
1449         dns_name_init(&new->origin, NULL);
1450         dns_name_init(&new->nsdname, NULL);
1451         dns_name_init(&new->cname, NULL);
1452         dns_name_init(&new->passthru, NULL);
1453         ISC_LIST_INITANDAPPEND(view->rpz_zones, new, link);
1454
1455         rpz_obj = cfg_listelt_value(element);
1456         policy_obj = cfg_tuple_get(rpz_obj, "policy");
1457         if (cfg_obj_isvoid(policy_obj)) {
1458                 new->policy = DNS_RPZ_POLICY_GIVEN;
1459         } else {
1460                 str = cfg_obj_asstring(cfg_tuple_get(policy_obj,
1461                                                      "policy name"));
1462                 new->policy = dns_rpz_str2policy(str);
1463                 INSIST(new->policy != DNS_RPZ_POLICY_ERROR);
1464         }
1465
1466         obj = cfg_tuple_get(rpz_obj, "recursive-only");
1467         if (cfg_obj_isvoid(obj)) {
1468                 new->recursive_only = recursive_only_def;
1469         } else {
1470                 new->recursive_only = cfg_obj_asboolean(obj);
1471         }
1472         if (!new->recursive_only)
1473                 view->rpz_recursive_only = ISC_FALSE;
1474
1475         obj = cfg_tuple_get(rpz_obj, "max-policy-ttl");
1476         if (cfg_obj_isuint32(obj)) {
1477                 new->max_policy_ttl = cfg_obj_asuint32(obj);
1478         } else {
1479                 new->max_policy_ttl = ttl_def;
1480         }
1481
1482         str = cfg_obj_asstring(cfg_tuple_get(rpz_obj, "zone name"));
1483         result = dns_name_fromstring(&new->origin, str, DNS_NAME_DOWNCASE,
1484                                      view->mctx);
1485         if (result != ISC_R_SUCCESS) {
1486                 cfg_obj_log(rpz_obj, ns_g_lctx, DNS_RPZ_ERROR_LEVEL,
1487                             "invalid zone '%s'", str);
1488                 goto cleanup;
1489         }
1490
1491         result = dns_name_fromstring2(&new->nsdname, DNS_RPZ_NSDNAME_ZONE,
1492                                       &new->origin, DNS_NAME_DOWNCASE,
1493                                       view->mctx);
1494         if (result != ISC_R_SUCCESS) {
1495                 cfg_obj_log(rpz_obj, ns_g_lctx, DNS_RPZ_ERROR_LEVEL,
1496                             "invalid zone '%s'", str);
1497                 goto cleanup;
1498         }
1499
1500         result = dns_name_fromstring(&new->passthru, DNS_RPZ_PASSTHRU_ZONE,
1501                                      DNS_NAME_DOWNCASE, view->mctx);
1502         if (result != ISC_R_SUCCESS) {
1503                 cfg_obj_log(rpz_obj, ns_g_lctx, DNS_RPZ_ERROR_LEVEL,
1504                             "invalid zone '%s'", str);
1505                 goto cleanup;
1506         }
1507
1508         result = dns_view_findzone(view, &new->origin, &zone);
1509         if (result != ISC_R_SUCCESS) {
1510                 cfg_obj_log(rpz_obj, ns_g_lctx, DNS_RPZ_ERROR_LEVEL,
1511                             "unknown zone '%s'", str);
1512                 goto cleanup;
1513         }
1514         if (dns_zone_gettype(zone) != dns_zone_master &&
1515             dns_zone_gettype(zone) != dns_zone_slave) {
1516                 cfg_obj_log(rpz_obj, ns_g_lctx, DNS_RPZ_ERROR_LEVEL,
1517                              "zone '%s' is neither master nor slave", str);
1518                 dns_zone_detach(&zone);
1519                 result = DNS_R_NOTMASTER;
1520                 goto cleanup;
1521         }
1522         dns_zone_detach(&zone);
1523
1524         for (old = ISC_LIST_HEAD(view->rpz_zones);
1525              old != new;
1526              old = ISC_LIST_NEXT(old, link)) {
1527                 ++new->num;
1528                 if (dns_name_equal(&old->origin, &new->origin)) {
1529                         cfg_obj_log(rpz_obj, ns_g_lctx, DNS_RPZ_ERROR_LEVEL,
1530                                     "duplicate '%s'", str);
1531                         result = DNS_R_DUPLICATE;
1532                         goto cleanup;
1533                 }
1534         }
1535
1536         if (new->policy == DNS_RPZ_POLICY_CNAME) {
1537                 str = cfg_obj_asstring(cfg_tuple_get(policy_obj, "cname"));
1538                 result = dns_name_fromstring(&new->cname, str,
1539                                              DNS_NAME_DOWNCASE, view->mctx);
1540                 if (result != ISC_R_SUCCESS) {
1541                         cfg_obj_log(rpz_obj, ns_g_lctx, DNS_RPZ_ERROR_LEVEL,
1542                                     "invalid cname '%s'", str);
1543                         goto cleanup;
1544                 }
1545         }
1546
1547         return (ISC_R_SUCCESS);
1548
1549  cleanup:
1550         dns_rpz_view_destroy(view);
1551         return (result);
1552 }
1553
1554 /*
1555  * Configure 'view' according to 'vconfig', taking defaults from 'config'
1556  * where values are missing in 'vconfig'.
1557  *
1558  * When configuring the default view, 'vconfig' will be NULL and the
1559  * global defaults in 'config' used exclusively.
1560  */
1561 static isc_result_t
1562 configure_view(dns_view_t *view, cfg_obj_t *config, cfg_obj_t *vconfig,
1563                ns_cachelist_t *cachelist, const cfg_obj_t *bindkeys,
1564                isc_mem_t *mctx, cfg_aclconfctx_t *actx,
1565                isc_boolean_t need_hints)
1566 {
1567         const cfg_obj_t *maps[4];
1568         const cfg_obj_t *cfgmaps[3];
1569         const cfg_obj_t *optionmaps[3];
1570         const cfg_obj_t *options = NULL;
1571         const cfg_obj_t *voptions = NULL;
1572         const cfg_obj_t *forwardtype;
1573         const cfg_obj_t *forwarders;
1574         const cfg_obj_t *alternates;
1575         const cfg_obj_t *zonelist;
1576         const cfg_obj_t *dlz;
1577         unsigned int dlzargc;
1578         char **dlzargv;
1579         const cfg_obj_t *disabled;
1580         const cfg_obj_t *obj;
1581         const cfg_listelt_t *element;
1582         in_port_t port;
1583         dns_cache_t *cache = NULL;
1584         isc_result_t result;
1585         isc_uint32_t max_adb_size;
1586         unsigned int cleaning_interval;
1587         isc_uint32_t max_cache_size;
1588         isc_uint32_t max_acache_size;
1589         isc_uint32_t lame_ttl;
1590         dns_tsig_keyring_t *ring = NULL;
1591         dns_view_t *pview = NULL;       /* Production view */
1592         isc_mem_t *cmctx = NULL, *hmctx = NULL;
1593         dns_dispatch_t *dispatch4 = NULL;
1594         dns_dispatch_t *dispatch6 = NULL;
1595         isc_boolean_t reused_cache = ISC_FALSE;
1596         isc_boolean_t shared_cache = ISC_FALSE;
1597         int i = 0, j = 0, k = 0;
1598         const char *str;
1599         const char *cachename = NULL;
1600         dns_order_t *order = NULL;
1601         isc_uint32_t udpsize;
1602         unsigned int resopts = 0;
1603         dns_zone_t *zone = NULL;
1604         isc_uint32_t max_clients_per_query;
1605         const char *sep = ": view ";
1606         const char *viewname = view->name;
1607         const char *forview = " for view ";
1608         isc_boolean_t rfc1918;
1609         isc_boolean_t empty_zones_enable;
1610         const cfg_obj_t *disablelist = NULL;
1611         isc_stats_t *resstats = NULL;
1612         dns_stats_t *resquerystats = NULL;
1613         isc_boolean_t auto_dlv = ISC_FALSE;
1614         isc_boolean_t auto_root = ISC_FALSE;
1615         ns_cache_t *nsc;
1616         isc_boolean_t zero_no_soattl;
1617         dns_acl_t *clients = NULL, *mapped = NULL, *excluded = NULL;
1618         unsigned int query_timeout;
1619         struct cfg_context *nzctx;
1620
1621         REQUIRE(DNS_VIEW_VALID(view));
1622
1623         if (config != NULL)
1624                 (void)cfg_map_get(config, "options", &options);
1625
1626         /*
1627          * maps: view options, options, defaults
1628          * cfgmaps: view options, config
1629          * optionmaps: view options, options
1630          */
1631         if (vconfig != NULL) {
1632                 voptions = cfg_tuple_get(vconfig, "options");
1633                 maps[i++] = voptions;
1634                 optionmaps[j++] = voptions;
1635                 cfgmaps[k++] = voptions;
1636         }
1637         if (options != NULL) {
1638                 maps[i++] = options;
1639                 optionmaps[j++] = options;
1640         }
1641
1642         maps[i++] = ns_g_defaults;
1643         maps[i] = NULL;
1644         optionmaps[j] = NULL;
1645         if (config != NULL)
1646                 cfgmaps[k++] = config;
1647         cfgmaps[k] = NULL;
1648
1649         if (!strcmp(viewname, "_default")) {
1650                 sep = "";
1651                 viewname = "";
1652                 forview = "";
1653                 POST(forview);
1654         }
1655
1656         /*
1657          * Set the view's port number for outgoing queries.
1658          */
1659         CHECKM(ns_config_getport(config, &port), "port");
1660         dns_view_setdstport(view, port);
1661
1662         /*
1663          * Create additional cache for this view and zones under the view
1664          * if explicitly enabled.
1665          * XXX950 default to on.
1666          */
1667         obj = NULL;
1668         (void)ns_config_get(maps, "acache-enable", &obj);
1669         if (obj != NULL && cfg_obj_asboolean(obj)) {
1670                 cmctx = NULL;
1671                 CHECK(isc_mem_create(0, 0, &cmctx));
1672                 CHECK(dns_acache_create(&view->acache, cmctx, ns_g_taskmgr,
1673                                         ns_g_timermgr));
1674                 isc_mem_setname(cmctx, "acache", NULL);
1675                 isc_mem_detach(&cmctx);
1676         }
1677         if (view->acache != NULL) {
1678                 obj = NULL;
1679                 result = ns_config_get(maps, "acache-cleaning-interval", &obj);
1680                 INSIST(result == ISC_R_SUCCESS);
1681                 dns_acache_setcleaninginterval(view->acache,
1682                                                cfg_obj_asuint32(obj) * 60);
1683
1684                 obj = NULL;
1685                 result = ns_config_get(maps, "max-acache-size", &obj);
1686                 INSIST(result == ISC_R_SUCCESS);
1687                 if (cfg_obj_isstring(obj)) {
1688                         str = cfg_obj_asstring(obj);
1689                         INSIST(strcasecmp(str, "unlimited") == 0);
1690                         max_acache_size = ISC_UINT32_MAX;
1691                 } else {
1692                         isc_resourcevalue_t value;
1693
1694                         value = cfg_obj_asuint64(obj);
1695                         if (value > ISC_UINT32_MAX) {
1696                                 cfg_obj_log(obj, ns_g_lctx, ISC_LOG_ERROR,
1697                                             "'max-acache-size "
1698                                             "%" ISC_PRINT_QUADFORMAT
1699                                             "d' is too large",
1700                                             value);
1701                                 result = ISC_R_RANGE;
1702                                 goto cleanup;
1703                         }
1704                         max_acache_size = (isc_uint32_t)value;
1705                 }
1706                 dns_acache_setcachesize(view->acache, max_acache_size);
1707         }
1708
1709         CHECK(configure_view_acl(vconfig, config, "allow-query", NULL, actx,
1710                                  ns_g_mctx, &view->queryacl));
1711         if (view->queryacl == NULL) {
1712                 CHECK(configure_view_acl(NULL, ns_g_config, "allow-query",
1713                                          NULL, actx, ns_g_mctx,
1714                                          &view->queryacl));
1715         }
1716
1717         /*
1718          * Configure the zones.
1719          */
1720         zonelist = NULL;
1721         if (voptions != NULL)
1722                 (void)cfg_map_get(voptions, "zone", &zonelist);
1723         else
1724                 (void)cfg_map_get(config, "zone", &zonelist);
1725
1726         /*
1727          * Load zone configuration
1728          */
1729         for (element = cfg_list_first(zonelist);
1730              element != NULL;
1731              element = cfg_list_next(element))
1732         {
1733                 const cfg_obj_t *zconfig = cfg_listelt_value(element);
1734                 CHECK(configure_zone(config, zconfig, vconfig, mctx, view,
1735                                      actx, ISC_FALSE));
1736         }
1737
1738         /*
1739          * If we're allowing added zones, then load zone configuration
1740          * from the newzone file for zones that were added during previous
1741          * runs.
1742          */
1743         nzctx = view->new_zone_config;
1744         if (nzctx != NULL && nzctx->nzconfig != NULL) {
1745                 isc_log_write(ns_g_lctx, NS_LOGCATEGORY_GENERAL,
1746                               NS_LOGMODULE_SERVER, ISC_LOG_INFO,
1747                               "loading additional zones for view '%s'",
1748                               view->name);
1749
1750                 zonelist = NULL;
1751                 cfg_map_get(nzctx->nzconfig, "zone", &zonelist);
1752
1753                 for (element = cfg_list_first(zonelist);
1754                      element != NULL;
1755                      element = cfg_list_next(element))
1756                 {
1757                         const cfg_obj_t *zconfig = cfg_listelt_value(element);
1758                         CHECK(configure_zone(config, zconfig, vconfig,
1759                                              mctx, view, actx,
1760                                              ISC_TRUE));
1761                 }
1762         }
1763
1764         /*
1765          * Create Dynamically Loadable Zone driver.
1766          */
1767         dlz = NULL;
1768         if (voptions != NULL)
1769                 (void)cfg_map_get(voptions, "dlz", &dlz);
1770         else
1771                 (void)cfg_map_get(config, "dlz", &dlz);
1772
1773         obj = NULL;
1774         if (dlz != NULL) {
1775                 (void)cfg_map_get(cfg_tuple_get(dlz, "options"),
1776                                   "database", &obj);
1777                 if (obj != NULL) {
1778                         char *s = isc_mem_strdup(mctx, cfg_obj_asstring(obj));
1779                         if (s == NULL) {
1780                                 result = ISC_R_NOMEMORY;
1781                                 goto cleanup;
1782                         }
1783
1784                         result = dns_dlzstrtoargv(mctx, s, &dlzargc, &dlzargv);
1785                         if (result != ISC_R_SUCCESS) {
1786                                 isc_mem_free(mctx, s);
1787                                 goto cleanup;
1788                         }
1789
1790                         obj = cfg_tuple_get(dlz, "name");
1791                         result = dns_dlzcreate(mctx, cfg_obj_asstring(obj),
1792                                                dlzargv[0], dlzargc, dlzargv,
1793                                                &view->dlzdatabase);
1794                         isc_mem_free(mctx, s);
1795                         isc_mem_put(mctx, dlzargv, dlzargc * sizeof(*dlzargv));
1796                         if (result != ISC_R_SUCCESS)
1797                                 goto cleanup;
1798
1799                         /*
1800                          * If the dlz backend supports configuration,
1801                          * then call its configure method now.
1802                          */
1803                         result = dns_dlzconfigure(view, dlzconfigure_callback);
1804                         if (result != ISC_R_SUCCESS)
1805                                 goto cleanup;
1806                 }
1807         }
1808
1809         /*
1810          * Obtain configuration parameters that affect the decision of whether
1811          * we can reuse/share an existing cache.
1812          */
1813         obj = NULL;
1814         result = ns_config_get(maps, "cleaning-interval", &obj);
1815         INSIST(result == ISC_R_SUCCESS);
1816         cleaning_interval = cfg_obj_asuint32(obj) * 60;
1817
1818         obj = NULL;
1819         result = ns_config_get(maps, "max-cache-size", &obj);
1820         INSIST(result == ISC_R_SUCCESS);
1821         if (cfg_obj_isstring(obj)) {
1822                 str = cfg_obj_asstring(obj);
1823                 INSIST(strcasecmp(str, "unlimited") == 0);
1824                 max_cache_size = ISC_UINT32_MAX;
1825         } else {
1826                 isc_resourcevalue_t value;
1827                 value = cfg_obj_asuint64(obj);
1828                 if (value > ISC_UINT32_MAX) {
1829                         cfg_obj_log(obj, ns_g_lctx, ISC_LOG_ERROR,
1830                                     "'max-cache-size "
1831                                     "%" ISC_PRINT_QUADFORMAT "d' is too large",
1832                                     value);
1833                         result = ISC_R_RANGE;
1834                         goto cleanup;
1835                 }
1836                 max_cache_size = (isc_uint32_t)value;
1837         }
1838
1839         /* Check-names. */
1840         obj = NULL;
1841         result = ns_checknames_get(maps, "response", &obj);
1842         INSIST(result == ISC_R_SUCCESS);
1843
1844         str = cfg_obj_asstring(obj);
1845         if (strcasecmp(str, "fail") == 0) {
1846                 resopts |= DNS_RESOLVER_CHECKNAMES |
1847                         DNS_RESOLVER_CHECKNAMESFAIL;
1848                 view->checknames = ISC_TRUE;
1849         } else if (strcasecmp(str, "warn") == 0) {
1850                 resopts |= DNS_RESOLVER_CHECKNAMES;
1851                 view->checknames = ISC_FALSE;
1852         } else if (strcasecmp(str, "ignore") == 0) {
1853                 view->checknames = ISC_FALSE;
1854         } else
1855                 INSIST(0);
1856
1857         obj = NULL;
1858         result = ns_config_get(maps, "zero-no-soa-ttl-cache", &obj);
1859         INSIST(result == ISC_R_SUCCESS);
1860         zero_no_soattl = cfg_obj_asboolean(obj);
1861
1862         obj = NULL;
1863         result = ns_config_get(maps, "dns64", &obj);
1864         if (result == ISC_R_SUCCESS && strcmp(view->name, "_bind") &&
1865             strcmp(view->name, "_meta")) {
1866                 const cfg_listelt_t *element;
1867                 isc_netaddr_t na, suffix, *sp;
1868                 unsigned int prefixlen;
1869                 const char *server, *contact;
1870                 const cfg_obj_t *myobj;
1871
1872                 myobj = NULL;
1873                 result = ns_config_get(maps, "dns64-server", &myobj);
1874                 if (result == ISC_R_SUCCESS)
1875                         server = cfg_obj_asstring(myobj);
1876                 else
1877                         server = NULL;
1878
1879                 myobj = NULL;
1880                 result = ns_config_get(maps, "dns64-contact", &myobj);
1881                 if (result == ISC_R_SUCCESS)
1882                         contact = cfg_obj_asstring(myobj);
1883                 else
1884                         contact = NULL;
1885
1886                 for (element = cfg_list_first(obj);
1887                      element != NULL;
1888                      element = cfg_list_next(element))
1889                 {
1890                         const cfg_obj_t *map = cfg_listelt_value(element);
1891                         dns_dns64_t *dns64 = NULL;
1892                         unsigned int dns64options = 0;
1893
1894                         cfg_obj_asnetprefix(cfg_map_getname(map), &na,
1895                                             &prefixlen);
1896
1897                         obj = NULL;
1898                         (void)cfg_map_get(map, "suffix", &obj);
1899                         if (obj != NULL) {
1900                                 sp = &suffix;
1901                                 isc_netaddr_fromsockaddr(sp,
1902                                                       cfg_obj_assockaddr(obj));
1903                         } else
1904                                 sp = NULL;
1905
1906                         clients = mapped = excluded = NULL;
1907                         obj = NULL;
1908                         (void)cfg_map_get(map, "clients", &obj);
1909                         if (obj != NULL) {
1910                                 result = cfg_acl_fromconfig(obj, config,
1911                                                             ns_g_lctx, actx,
1912                                                             mctx, 0, &clients);
1913                                 if (result != ISC_R_SUCCESS)
1914                                         goto cleanup;
1915                         }
1916                         obj = NULL;
1917                         (void)cfg_map_get(map, "mapped", &obj);
1918                         if (obj != NULL) {
1919                                 result = cfg_acl_fromconfig(obj, config,
1920                                                             ns_g_lctx, actx,
1921                                                             mctx, 0, &mapped);
1922                                 if (result != ISC_R_SUCCESS)
1923                                         goto cleanup;
1924                         }
1925                         obj = NULL;
1926                         (void)cfg_map_get(map, "exclude", &obj);
1927                         if (obj != NULL) {
1928                                 result = cfg_acl_fromconfig(obj, config,
1929                                                             ns_g_lctx, actx,
1930                                                             mctx, 0, &excluded);
1931                                 if (result != ISC_R_SUCCESS)
1932                                         goto cleanup;
1933                         }
1934
1935                         obj = NULL;
1936                         (void)cfg_map_get(map, "recursive-only", &obj);
1937                         if (obj != NULL && cfg_obj_asboolean(obj))
1938                                 dns64options |= DNS_DNS64_RECURSIVE_ONLY;
1939
1940                         obj = NULL;
1941                         (void)cfg_map_get(map, "break-dnssec", &obj);
1942                         if (obj != NULL && cfg_obj_asboolean(obj))
1943                                 dns64options |= DNS_DNS64_BREAK_DNSSEC;
1944
1945                         result = dns_dns64_create(mctx, &na, prefixlen, sp,
1946                                                   clients, mapped, excluded,
1947                                                   dns64options, &dns64);
1948                         if (result != ISC_R_SUCCESS)
1949                                 goto cleanup;
1950                         dns_dns64_append(&view->dns64, dns64);
1951                         view->dns64cnt++;
1952                         result = dns64_reverse(view, mctx, &na, prefixlen,
1953                                                server, contact);
1954                         if (result != ISC_R_SUCCESS)
1955                                 goto cleanup;
1956                         if (clients != NULL)
1957                                 dns_acl_detach(&clients);
1958                         if (mapped != NULL)
1959                                 dns_acl_detach(&mapped);
1960                         if (excluded != NULL)
1961                                 dns_acl_detach(&excluded);
1962                 }
1963         }
1964
1965         obj = NULL;
1966         result = ns_config_get(maps, "dnssec-accept-expired", &obj);
1967         INSIST(result == ISC_R_SUCCESS);
1968         view->acceptexpired = cfg_obj_asboolean(obj);
1969
1970         obj = NULL;
1971         result = ns_config_get(maps, "dnssec-validation", &obj);
1972         INSIST(result == ISC_R_SUCCESS);
1973         if (cfg_obj_isboolean(obj)) {
1974                 view->enablevalidation = cfg_obj_asboolean(obj);
1975         } else {
1976                 /* If dnssec-validation is not boolean, it must be "auto" */
1977                 view->enablevalidation = ISC_TRUE;
1978                 auto_root = ISC_TRUE;
1979         }
1980
1981         obj = NULL;
1982         result = ns_config_get(maps, "max-cache-ttl", &obj);
1983         INSIST(result == ISC_R_SUCCESS);
1984         view->maxcachettl = cfg_obj_asuint32(obj);
1985
1986         obj = NULL;
1987         result = ns_config_get(maps, "max-ncache-ttl", &obj);
1988         INSIST(result == ISC_R_SUCCESS);
1989         view->maxncachettl = cfg_obj_asuint32(obj);
1990         if (view->maxncachettl > 7 * 24 * 3600)
1991                 view->maxncachettl = 7 * 24 * 3600;
1992
1993         /*
1994          * Configure the view's cache.
1995          *
1996          * First, check to see if there are any attach-cache options.  If yes,
1997          * attempt to lookup an existing cache at attach it to the view.  If
1998          * there is not one, then try to reuse an existing cache if possible;
1999          * otherwise create a new cache.
2000          *
2001          * Note that the ADB is not preserved or shared in either case.
2002          *
2003          * When a matching view is found, the associated statistics are also
2004          * retrieved and reused.
2005          *
2006          * XXX Determining when it is safe to reuse or share a cache is tricky.
2007          * When the view's configuration changes, the cached data may become
2008          * invalid because it reflects our old view of the world.  We check
2009          * some of the configuration parameters that could invalidate the cache
2010          * or otherwise make it unsharable, but there are other configuration
2011          * options that should be checked.  For example, if a view uses a
2012          * forwarder, changes in the forwarder configuration may invalidate
2013          * the cache.  At the moment, it's the administrator's responsibility to
2014          * ensure these configuration options don't invalidate reusing/sharing.
2015          */
2016         obj = NULL;
2017         result = ns_config_get(maps, "attach-cache", &obj);
2018         if (result == ISC_R_SUCCESS)
2019                 cachename = cfg_obj_asstring(obj);
2020         else
2021                 cachename = view->name;
2022         cache = NULL;
2023         nsc = cachelist_find(cachelist, cachename);
2024         if (nsc != NULL) {
2025                 if (!cache_sharable(nsc->primaryview, view, zero_no_soattl,
2026                                     cleaning_interval, max_cache_size)) {
2027                         isc_log_write(ns_g_lctx, NS_LOGCATEGORY_GENERAL,
2028                                       NS_LOGMODULE_SERVER, ISC_LOG_ERROR,
2029                                       "views %s and %s can't share the cache "
2030                                       "due to configuration parameter mismatch",
2031                                       nsc->primaryview->name, view->name);
2032                         result = ISC_R_FAILURE;
2033                         goto cleanup;
2034                 }
2035                 dns_cache_attach(nsc->cache, &cache);
2036                 shared_cache = ISC_TRUE;
2037         } else {
2038                 if (strcmp(cachename, view->name) == 0) {
2039                         result = dns_viewlist_find(&ns_g_server->viewlist,
2040                                                    cachename, view->rdclass,
2041                                                    &pview);
2042                         if (result != ISC_R_NOTFOUND && result != ISC_R_SUCCESS)
2043                                 goto cleanup;
2044                         if (pview != NULL) {
2045                                 if (!cache_reusable(pview, view,
2046                                                     zero_no_soattl)) {
2047                                         isc_log_write(ns_g_lctx,
2048                                                       NS_LOGCATEGORY_GENERAL,
2049                                                       NS_LOGMODULE_SERVER,
2050                                                       ISC_LOG_DEBUG(1),
2051                                                       "cache cannot be reused "
2052                                                       "for view %s due to "
2053                                                       "configuration parameter "
2054                                                       "mismatch", view->name);
2055                                 } else {
2056                                         INSIST(pview->cache != NULL);
2057                                         isc_log_write(ns_g_lctx,
2058                                                       NS_LOGCATEGORY_GENERAL,
2059                                                       NS_LOGMODULE_SERVER,
2060                                                       ISC_LOG_DEBUG(3),
2061                                                       "reusing existing cache");
2062                                         reused_cache = ISC_TRUE;
2063                                         dns_cache_attach(pview->cache, &cache);
2064                                 }
2065                                 dns_view_getresstats(pview, &resstats);
2066                                 dns_view_getresquerystats(pview,
2067                                                           &resquerystats);
2068                                 dns_view_detach(&pview);
2069                         }
2070                 }
2071                 if (cache == NULL) {
2072                         /*
2073                          * Create a cache with the desired name.  This normally
2074                          * equals the view name, but may also be a forward
2075                          * reference to a view that share the cache with this
2076                          * view but is not yet configured.  If it is not the
2077                          * view name but not a forward reference either, then it
2078                          * is simply a named cache that is not shared.
2079                          *
2080                          * We use two separate memory contexts for the
2081                          * cache, for the main cache memory and the heap
2082                          * memory.
2083                          */
2084                         CHECK(isc_mem_create(0, 0, &cmctx));
2085                         isc_mem_setname(cmctx, "cache", NULL);
2086                         CHECK(isc_mem_create(0, 0, &hmctx));
2087                         isc_mem_setname(hmctx, "cache_heap", NULL);
2088                         CHECK(dns_cache_create3(cmctx, hmctx, ns_g_taskmgr,
2089                                                 ns_g_timermgr, view->rdclass,
2090                                                 cachename, "rbt", 0, NULL,
2091                                                 &cache));
2092                         isc_mem_detach(&cmctx);
2093                         isc_mem_detach(&hmctx);
2094                 }
2095                 nsc = isc_mem_get(mctx, sizeof(*nsc));
2096                 if (nsc == NULL) {
2097                         result = ISC_R_NOMEMORY;
2098                         goto cleanup;
2099                 }
2100                 nsc->cache = NULL;
2101                 dns_cache_attach(cache, &nsc->cache);
2102                 nsc->primaryview = view;
2103                 nsc->needflush = ISC_FALSE;
2104                 nsc->adbsizeadjusted = ISC_FALSE;
2105                 ISC_LINK_INIT(nsc, link);
2106                 ISC_LIST_APPEND(*cachelist, nsc, link);
2107         }
2108         dns_view_setcache2(view, cache, shared_cache);
2109
2110         /*
2111          * cache-file cannot be inherited if views are present, but this
2112          * should be caught by the configuration checking stage.
2113          */
2114         obj = NULL;
2115         result = ns_config_get(maps, "cache-file", &obj);
2116         if (result == ISC_R_SUCCESS && strcmp(view->name, "_bind") != 0) {
2117                 CHECK(dns_cache_setfilename(cache, cfg_obj_asstring(obj)));
2118                 if (!reused_cache && !shared_cache)
2119                         CHECK(dns_cache_load(cache));
2120         }
2121
2122         dns_cache_setcleaninginterval(cache, cleaning_interval);
2123         dns_cache_setcachesize(cache, max_cache_size);
2124
2125         dns_cache_detach(&cache);
2126
2127         /*
2128          * Resolver.
2129          *
2130          * XXXRTH  Hardwired number of tasks.
2131          */
2132         CHECK(get_view_querysource_dispatch(maps, AF_INET, &dispatch4,
2133                                             ISC_TF(ISC_LIST_PREV(view, link)
2134                                                    == NULL)));
2135         CHECK(get_view_querysource_dispatch(maps, AF_INET6, &dispatch6,
2136                                             ISC_TF(ISC_LIST_PREV(view, link)
2137                                                    == NULL)));
2138         if (dispatch4 == NULL && dispatch6 == NULL) {
2139                 UNEXPECTED_ERROR(__FILE__, __LINE__,
2140                                  "unable to obtain neither an IPv4 nor"
2141                                  " an IPv6 dispatch");
2142                 result = ISC_R_UNEXPECTED;
2143                 goto cleanup;
2144         }
2145         CHECK(dns_view_createresolver(view, ns_g_taskmgr, 31,
2146                                       ns_g_socketmgr, ns_g_timermgr,
2147                                       resopts, ns_g_dispatchmgr,
2148                                       dispatch4, dispatch6));
2149
2150         if (resstats == NULL) {
2151                 CHECK(isc_stats_create(mctx, &resstats,
2152                                        dns_resstatscounter_max));
2153         }
2154         dns_view_setresstats(view, resstats);
2155         if (resquerystats == NULL)
2156                 CHECK(dns_rdatatypestats_create(mctx, &resquerystats));
2157         dns_view_setresquerystats(view, resquerystats);
2158
2159         /*
2160          * Set the ADB cache size to 1/8th of the max-cache-size or
2161          * MAX_ADB_SIZE_FOR_CACHESHARE when the cache is shared.
2162          */
2163         max_adb_size = 0;
2164         if (max_cache_size != 0) {
2165                 max_adb_size = max_cache_size / 8;
2166                 if (max_adb_size == 0)
2167                         max_adb_size = 1;       /* Force minimum. */
2168                 if (view != nsc->primaryview &&
2169                     max_adb_size > MAX_ADB_SIZE_FOR_CACHESHARE) {
2170                         max_adb_size = MAX_ADB_SIZE_FOR_CACHESHARE;
2171                         if (!nsc->adbsizeadjusted) {
2172                                 dns_adb_setadbsize(nsc->primaryview->adb,
2173                                                    MAX_ADB_SIZE_FOR_CACHESHARE);
2174                                 nsc->adbsizeadjusted = ISC_TRUE;
2175                         }
2176                 }
2177         }
2178         dns_adb_setadbsize(view->adb, max_adb_size);
2179
2180         /*
2181          * Set resolver's lame-ttl.
2182          */
2183         obj = NULL;
2184         result = ns_config_get(maps, "lame-ttl", &obj);
2185         INSIST(result == ISC_R_SUCCESS);
2186         lame_ttl = cfg_obj_asuint32(obj);
2187         if (lame_ttl > 1800)
2188                 lame_ttl = 1800;
2189         dns_resolver_setlamettl(view->resolver, lame_ttl);
2190
2191         /*
2192          * Set the resolver's query timeout.
2193          */
2194         obj = NULL;
2195         result = ns_config_get(maps, "resolver-query-timeout", &obj);
2196         INSIST(result == ISC_R_SUCCESS);
2197         query_timeout = cfg_obj_asuint32(obj);
2198         dns_resolver_settimeout(view->resolver, query_timeout);
2199
2200         /* Specify whether to use 0-TTL for negative response for SOA query */
2201         dns_resolver_setzeronosoattl(view->resolver, zero_no_soattl);
2202
2203         /*
2204          * Set the resolver's EDNS UDP size.
2205          */
2206         obj = NULL;
2207         result = ns_config_get(maps, "edns-udp-size", &obj);
2208         INSIST(result == ISC_R_SUCCESS);
2209         udpsize = cfg_obj_asuint32(obj);
2210         if (udpsize < 512)
2211                 udpsize = 512;
2212         if (udpsize > 4096)
2213                 udpsize = 4096;
2214         dns_resolver_setudpsize(view->resolver, (isc_uint16_t)udpsize);
2215
2216         /*
2217          * Set the maximum UDP response size.
2218          */
2219         obj = NULL;
2220         result = ns_config_get(maps, "max-udp-size", &obj);
2221         INSIST(result == ISC_R_SUCCESS);
2222         udpsize = cfg_obj_asuint32(obj);
2223         if (udpsize < 512)
2224                 udpsize = 512;
2225         if (udpsize > 4096)
2226                 udpsize = 4096;
2227         view->maxudp = udpsize;
2228
2229         /*
2230          * Set supported DNSSEC algorithms.
2231          */
2232         dns_resolver_reset_algorithms(view->resolver);
2233         disabled = NULL;
2234         (void)ns_config_get(maps, "disable-algorithms", &disabled);
2235         if (disabled != NULL) {
2236                 for (element = cfg_list_first(disabled);
2237                      element != NULL;
2238                      element = cfg_list_next(element))
2239                         CHECK(disable_algorithms(cfg_listelt_value(element),
2240                                                  view->resolver));
2241         }
2242
2243         /*
2244          * A global or view "forwarders" option, if present,
2245          * creates an entry for "." in the forwarding table.
2246          */
2247         forwardtype = NULL;
2248         forwarders = NULL;
2249         (void)ns_config_get(maps, "forward", &forwardtype);
2250         (void)ns_config_get(maps, "forwarders", &forwarders);
2251         if (forwarders != NULL)
2252                 CHECK(configure_forward(config, view, dns_rootname,
2253                                         forwarders, forwardtype));
2254
2255         /*
2256          * Dual Stack Servers.
2257          */
2258         alternates = NULL;
2259         (void)ns_config_get(maps, "dual-stack-servers", &alternates);
2260         if (alternates != NULL)
2261                 CHECK(configure_alternates(config, view, alternates));
2262
2263         /*
2264          * We have default hints for class IN if we need them.
2265          */
2266         if (view->rdclass == dns_rdataclass_in && view->hints == NULL)
2267                 dns_view_sethints(view, ns_g_server->in_roothints);
2268
2269         /*
2270          * If we still have no hints, this is a non-IN view with no
2271          * "hints zone" configured.  Issue a warning, except if this
2272          * is a root server.  Root servers never need to consult
2273          * their hints, so it's no point requiring users to configure
2274          * them.
2275          */
2276         if (view->hints == NULL) {
2277                 dns_zone_t *rootzone = NULL;
2278                 (void)dns_view_findzone(view, dns_rootname, &rootzone);
2279                 if (rootzone != NULL) {
2280                         dns_zone_detach(&rootzone);
2281                         need_hints = ISC_FALSE;
2282                 }
2283                 if (need_hints)
2284                         isc_log_write(ns_g_lctx, NS_LOGCATEGORY_GENERAL,
2285                                       NS_LOGMODULE_SERVER, ISC_LOG_WARNING,
2286                                       "no root hints for view '%s'",
2287                                       view->name);
2288         }
2289
2290         /*
2291          * Configure the view's TSIG keys.
2292          */
2293         CHECK(ns_tsigkeyring_fromconfig(config, vconfig, view->mctx, &ring));
2294         if (ns_g_server->sessionkey != NULL) {
2295                 CHECK(dns_tsigkeyring_add(ring, ns_g_server->session_keyname,
2296                                           ns_g_server->sessionkey));
2297         }
2298         dns_view_setkeyring(view, ring);
2299         dns_tsigkeyring_detach(&ring);
2300
2301         /*
2302          * See if we can re-use a dynamic key ring.
2303          */
2304         result = dns_viewlist_find(&ns_g_server->viewlist, view->name,
2305                                    view->rdclass, &pview);
2306         if (result != ISC_R_NOTFOUND && result != ISC_R_SUCCESS)
2307                 goto cleanup;
2308         if (pview != NULL) {
2309                 dns_view_getdynamickeyring(pview, &ring);
2310                 if (ring != NULL)
2311                         dns_view_setdynamickeyring(view, ring);
2312                 dns_tsigkeyring_detach(&ring);
2313                 dns_view_detach(&pview);
2314         } else
2315                 dns_view_restorekeyring(view);
2316
2317         /*
2318          * Configure the view's peer list.
2319          */
2320         {
2321                 const cfg_obj_t *peers = NULL;
2322                 const cfg_listelt_t *element;
2323                 dns_peerlist_t *newpeers = NULL;
2324
2325                 (void)ns_config_get(cfgmaps, "server", &peers);
2326                 CHECK(dns_peerlist_new(mctx, &newpeers));
2327                 for (element = cfg_list_first(peers);
2328                      element != NULL;
2329                      element = cfg_list_next(element))
2330                 {
2331                         const cfg_obj_t *cpeer = cfg_listelt_value(element);
2332                         dns_peer_t *peer;
2333
2334                         CHECK(configure_peer(cpeer, mctx, &peer));
2335                         dns_peerlist_addpeer(newpeers, peer);
2336                         dns_peer_detach(&peer);
2337                 }
2338                 dns_peerlist_detach(&view->peers);
2339                 view->peers = newpeers; /* Transfer ownership. */
2340         }
2341
2342         /*
2343          *      Configure the views rrset-order.
2344          */
2345         {
2346                 const cfg_obj_t *rrsetorder = NULL;
2347                 const cfg_listelt_t *element;
2348
2349                 (void)ns_config_get(maps, "rrset-order", &rrsetorder);
2350                 CHECK(dns_order_create(mctx, &order));
2351                 for (element = cfg_list_first(rrsetorder);
2352                      element != NULL;
2353                      element = cfg_list_next(element))
2354                 {
2355                         const cfg_obj_t *ent = cfg_listelt_value(element);
2356
2357                         CHECK(configure_order(order, ent));
2358                 }
2359                 if (view->order != NULL)
2360                         dns_order_detach(&view->order);
2361                 dns_order_attach(order, &view->order);
2362                 dns_order_detach(&order);
2363         }
2364         /*
2365          * Copy the aclenv object.
2366          */
2367         dns_aclenv_copy(&view->aclenv, &ns_g_server->aclenv);
2368
2369         /*
2370          * Configure the "match-clients" and "match-destinations" ACL.
2371          */
2372         CHECK(configure_view_acl(vconfig, config, "match-clients", NULL, actx,
2373                                  ns_g_mctx, &view->matchclients));
2374         CHECK(configure_view_acl(vconfig, config, "match-destinations", NULL,
2375                                  actx, ns_g_mctx, &view->matchdestinations));
2376
2377         /*
2378          * Configure the "match-recursive-only" option.
2379          */
2380         obj = NULL;
2381         (void)ns_config_get(maps, "match-recursive-only", &obj);
2382         if (obj != NULL && cfg_obj_asboolean(obj))
2383                 view->matchrecursiveonly = ISC_TRUE;
2384         else
2385                 view->matchrecursiveonly = ISC_FALSE;
2386
2387         /*
2388          * Configure other configurable data.
2389          */
2390         obj = NULL;
2391         result = ns_config_get(maps, "recursion", &obj);
2392         INSIST(result == ISC_R_SUCCESS);
2393         view->recursion = cfg_obj_asboolean(obj);
2394
2395         obj = NULL;
2396         result = ns_config_get(maps, "auth-nxdomain", &obj);
2397         INSIST(result == ISC_R_SUCCESS);
2398         view->auth_nxdomain = cfg_obj_asboolean(obj);
2399
2400         obj = NULL;
2401         result = ns_config_get(maps, "minimal-responses", &obj);
2402         INSIST(result == ISC_R_SUCCESS);
2403         view->minimalresponses = cfg_obj_asboolean(obj);
2404
2405         obj = NULL;
2406         result = ns_config_get(maps, "transfer-format", &obj);
2407         INSIST(result == ISC_R_SUCCESS);
2408         str = cfg_obj_asstring(obj);
2409         if (strcasecmp(str, "many-answers") == 0)
2410                 view->transfer_format = dns_many_answers;
2411         else if (strcasecmp(str, "one-answer") == 0)
2412                 view->transfer_format = dns_one_answer;
2413         else
2414                 INSIST(0);
2415
2416         /*
2417          * Set sources where additional data and CNAME/DNAME
2418          * targets for authoritative answers may be found.
2419          */
2420         obj = NULL;
2421         result = ns_config_get(maps, "additional-from-auth", &obj);
2422         INSIST(result == ISC_R_SUCCESS);
2423         view->additionalfromauth = cfg_obj_asboolean(obj);
2424         if (view->recursion && ! view->additionalfromauth) {
2425                 cfg_obj_log(obj, ns_g_lctx, ISC_LOG_WARNING,
2426                             "'additional-from-auth no' is only supported "
2427                             "with 'recursion no'");
2428                 view->additionalfromauth = ISC_TRUE;
2429         }
2430
2431         obj = NULL;
2432         result = ns_config_get(maps, "additional-from-cache", &obj);
2433         INSIST(result == ISC_R_SUCCESS);
2434         view->additionalfromcache = cfg_obj_asboolean(obj);
2435         if (view->recursion && ! view->additionalfromcache) {
2436                 cfg_obj_log(obj, ns_g_lctx, ISC_LOG_WARNING,
2437                             "'additional-from-cache no' is only supported "
2438                             "with 'recursion no'");
2439                 view->additionalfromcache = ISC_TRUE;
2440         }
2441
2442         /*
2443          * Set "allow-query-cache", "allow-query-cache-on",
2444          * "allow-recursion", and "allow-recursion-on" acls if
2445          * configured in named.conf.
2446          */
2447         CHECK(configure_view_acl(vconfig, config, "allow-query-cache", NULL,
2448                                  actx, ns_g_mctx, &view->cacheacl));
2449         CHECK(configure_view_acl(vconfig, config, "allow-query-cache-on", NULL,
2450                                  actx, ns_g_mctx, &view->cacheonacl));
2451         if (view->cacheonacl == NULL)
2452                 CHECK(configure_view_acl(NULL, ns_g_config,
2453                                          "allow-query-cache-on", NULL, actx,
2454                                          ns_g_mctx, &view->cacheonacl));
2455         if (strcmp(view->name, "_bind") != 0) {
2456                 CHECK(configure_view_acl(vconfig, config, "allow-recursion",
2457                                          NULL, actx, ns_g_mctx,
2458                                          &view->recursionacl));
2459                 CHECK(configure_view_acl(vconfig, config, "allow-recursion-on",
2460                                          NULL, actx, ns_g_mctx,
2461                                          &view->recursiononacl));
2462         }
2463
2464         /*
2465          * "allow-query-cache" inherits from "allow-recursion" if set,
2466          * otherwise from "allow-query" if set.
2467          * "allow-recursion" inherits from "allow-query-cache" if set,
2468          * otherwise from "allow-query" if set.
2469          */
2470         if (view->cacheacl == NULL && view->recursionacl != NULL)
2471                 dns_acl_attach(view->recursionacl, &view->cacheacl);
2472         /*
2473          * XXXEACH: This call to configure_view_acl() is redundant.  We
2474          * are leaving it as it is because we are making a minimal change
2475          * for a patch release.  In the future this should be changed to
2476          * dns_acl_attach(view->queryacl, &view->cacheacl).
2477          */
2478         if (view->cacheacl == NULL && view->recursion)
2479                 CHECK(configure_view_acl(vconfig, config, "allow-query", NULL,
2480                                          actx, ns_g_mctx, &view->cacheacl));
2481         if (view->recursion &&
2482             view->recursionacl == NULL && view->cacheacl != NULL)
2483                 dns_acl_attach(view->cacheacl, &view->recursionacl);
2484
2485         /*
2486          * Set default "allow-recursion", "allow-recursion-on" and
2487          * "allow-query-cache" acls.
2488          */
2489         if (view->recursionacl == NULL && view->recursion)
2490                 CHECK(configure_view_acl(NULL, ns_g_config,
2491                                          "allow-recursion", NULL,
2492                                          actx, ns_g_mctx,
2493                                          &view->recursionacl));
2494         if (view->recursiononacl == NULL && view->recursion)
2495                 CHECK(configure_view_acl(NULL, ns_g_config,
2496                                          "allow-recursion-on", NULL,
2497                                          actx, ns_g_mctx,
2498                                          &view->recursiononacl));
2499         if (view->cacheacl == NULL) {
2500                 if (view->recursion)
2501                         CHECK(configure_view_acl(NULL, ns_g_config,
2502                                                  "allow-query-cache", NULL,
2503                                                  actx, ns_g_mctx,
2504                                                  &view->cacheacl));
2505                 else
2506                         CHECK(dns_acl_none(mctx, &view->cacheacl));
2507         }
2508
2509         /*
2510          * Filter setting on addresses in the answer section.
2511          */
2512         CHECK(configure_view_acl(vconfig, config, "deny-answer-addresses",
2513                                  "acl", actx, ns_g_mctx, &view->denyansweracl));
2514         CHECK(configure_view_nametable(vconfig, config, "deny-answer-addresses",
2515                                        "except-from", ns_g_mctx,
2516                                        &view->answeracl_exclude));
2517
2518         /*
2519          * Filter setting on names (CNAME/DNAME targets) in the answer section.
2520          */
2521         CHECK(configure_view_nametable(vconfig, config, "deny-answer-aliases",
2522                                        "name", ns_g_mctx,
2523                                        &view->denyanswernames));
2524         CHECK(configure_view_nametable(vconfig, config, "deny-answer-aliases",
2525                                        "except-from", ns_g_mctx,
2526                                        &view->answernames_exclude));
2527
2528         /*
2529          * Configure sortlist, if set
2530          */
2531         CHECK(configure_view_sortlist(vconfig, config, actx, ns_g_mctx,
2532                                       &view->sortlist));
2533
2534         /*
2535          * Configure default allow-transfer, allow-notify, allow-update
2536          * and allow-update-forwarding ACLs, if set, so they can be
2537          * inherited by zones.
2538          */
2539         if (view->notifyacl == NULL)
2540                 CHECK(configure_view_acl(NULL, ns_g_config,
2541                                          "allow-notify", NULL, actx,
2542                                          ns_g_mctx, &view->notifyacl));
2543         if (view->transferacl == NULL)
2544                 CHECK(configure_view_acl(NULL, ns_g_config,
2545                                          "allow-transfer", NULL, actx,
2546                                          ns_g_mctx, &view->transferacl));
2547         if (view->updateacl == NULL)
2548                 CHECK(configure_view_acl(NULL, ns_g_config,
2549                                          "allow-update", NULL, actx,
2550                                          ns_g_mctx, &view->updateacl));
2551         if (view->upfwdacl == NULL)
2552                 CHECK(configure_view_acl(NULL, ns_g_config,
2553                                          "allow-update-forwarding", NULL, actx,
2554                                          ns_g_mctx, &view->upfwdacl));
2555
2556         obj = NULL;
2557         result = ns_config_get(maps, "request-ixfr", &obj);
2558         INSIST(result == ISC_R_SUCCESS);
2559         view->requestixfr = cfg_obj_asboolean(obj);
2560
2561         obj = NULL;
2562         result = ns_config_get(maps, "provide-ixfr", &obj);
2563         INSIST(result == ISC_R_SUCCESS);
2564         view->provideixfr = cfg_obj_asboolean(obj);
2565
2566         obj = NULL;
2567         result = ns_config_get(maps, "request-nsid", &obj);
2568         INSIST(result == ISC_R_SUCCESS);
2569         view->requestnsid = cfg_obj_asboolean(obj);
2570
2571         obj = NULL;
2572         result = ns_config_get(maps, "max-clients-per-query", &obj);
2573         INSIST(result == ISC_R_SUCCESS);
2574         max_clients_per_query = cfg_obj_asuint32(obj);
2575
2576         obj = NULL;
2577         result = ns_config_get(maps, "clients-per-query", &obj);
2578         INSIST(result == ISC_R_SUCCESS);
2579         dns_resolver_setclientsperquery(view->resolver,
2580                                         cfg_obj_asuint32(obj),
2581                                         max_clients_per_query);
2582
2583 #ifdef ALLOW_FILTER_AAAA_ON_V4
2584         obj = NULL;
2585         result = ns_config_get(maps, "filter-aaaa-on-v4", &obj);
2586         INSIST(result == ISC_R_SUCCESS);
2587         if (cfg_obj_isboolean(obj)) {
2588                 if (cfg_obj_asboolean(obj))
2589                         view->v4_aaaa = dns_v4_aaaa_filter;
2590                 else
2591                         view->v4_aaaa = dns_v4_aaaa_ok;
2592         } else {
2593                 const char *v4_aaaastr = cfg_obj_asstring(obj);
2594                 if (strcasecmp(v4_aaaastr, "break-dnssec") == 0)
2595                         view->v4_aaaa = dns_v4_aaaa_break_dnssec;
2596                 else
2597                         INSIST(0);
2598         }
2599         CHECK(configure_view_acl(vconfig, config, "filter-aaaa", NULL,
2600                                  actx, ns_g_mctx, &view->v4_aaaa_acl));
2601 #endif
2602
2603         obj = NULL;
2604         result = ns_config_get(maps, "dnssec-enable", &obj);
2605         INSIST(result == ISC_R_SUCCESS);
2606         view->enablednssec = cfg_obj_asboolean(obj);
2607
2608         obj = NULL;
2609         result = ns_config_get(optionmaps, "dnssec-lookaside", &obj);
2610         if (result == ISC_R_SUCCESS) {
2611                 /* If set to "auto", use the version from the defaults */
2612                 const cfg_obj_t *dlvobj;
2613                 const char *dom;
2614                 dlvobj = cfg_listelt_value(cfg_list_first(obj));
2615                 dom = cfg_obj_asstring(cfg_tuple_get(dlvobj, "domain"));
2616                 if (cfg_obj_isvoid(cfg_tuple_get(dlvobj, "trust-anchor"))) {
2617                         /* If "no", skip; if "auto", use global default */
2618                         if (!strcasecmp(dom, "no"))
2619                                 result = ISC_R_NOTFOUND;
2620                         else if (!strcasecmp(dom, "auto")) {
2621                                 auto_dlv = ISC_TRUE;
2622                                 obj = NULL;
2623                                 result = cfg_map_get(ns_g_defaults,
2624                                                      "dnssec-lookaside", &obj);
2625                         }
2626                 }
2627         }
2628
2629         if (result == ISC_R_SUCCESS) {
2630                 for (element = cfg_list_first(obj);
2631                      element != NULL;
2632                      element = cfg_list_next(element))
2633                 {
2634                         const char *str;
2635                         isc_buffer_t b;
2636                         dns_name_t *dlv;
2637
2638                         obj = cfg_listelt_value(element);
2639                         str = cfg_obj_asstring(cfg_tuple_get(obj,
2640                                                              "trust-anchor"));
2641                         isc_buffer_init(&b, str, strlen(str));
2642                         isc_buffer_add(&b, strlen(str));
2643                         dlv = dns_fixedname_name(&view->dlv_fixed);
2644                         CHECK(dns_name_fromtext(dlv, &b, dns_rootname,
2645                                                 DNS_NAME_DOWNCASE, NULL));
2646                         view->dlv = dns_fixedname_name(&view->dlv_fixed);
2647                 }
2648         } else
2649                 view->dlv = NULL;
2650
2651         /*
2652          * For now, there is only one kind of trusted keys, the
2653          * "security roots".
2654          */
2655         CHECK(configure_view_dnsseckeys(view, vconfig, config, bindkeys,
2656                                         auto_dlv, auto_root, mctx));
2657         dns_resolver_resetmustbesecure(view->resolver);
2658         obj = NULL;
2659         result = ns_config_get(maps, "dnssec-must-be-secure", &obj);
2660         if (result == ISC_R_SUCCESS)
2661                 CHECK(mustbesecure(obj, view->resolver));
2662
2663         obj = NULL;
2664         result = ns_config_get(maps, "preferred-glue", &obj);
2665         if (result == ISC_R_SUCCESS) {
2666                 str = cfg_obj_asstring(obj);
2667                 if (strcasecmp(str, "a") == 0)
2668                         view->preferred_glue = dns_rdatatype_a;
2669                 else if (strcasecmp(str, "aaaa") == 0)
2670                         view->preferred_glue = dns_rdatatype_aaaa;
2671                 else
2672                         view->preferred_glue = 0;
2673         } else
2674                 view->preferred_glue = 0;
2675
2676         obj = NULL;
2677         result = ns_config_get(maps, "root-delegation-only", &obj);
2678         if (result == ISC_R_SUCCESS) {
2679                 dns_view_setrootdelonly(view, ISC_TRUE);
2680                 if (!cfg_obj_isvoid(obj)) {
2681                         dns_fixedname_t fixed;
2682                         dns_name_t *name;
2683                         isc_buffer_t b;
2684                         const char *str;
2685                         const cfg_obj_t *exclude;
2686
2687                         dns_fixedname_init(&fixed);
2688                         name = dns_fixedname_name(&fixed);
2689                         for (element = cfg_list_first(obj);
2690                              element != NULL;
2691                              element = cfg_list_next(element)) {
2692                                 exclude = cfg_listelt_value(element);
2693                                 str = cfg_obj_asstring(exclude);
2694                                 isc_buffer_init(&b, str, strlen(str));
2695                                 isc_buffer_add(&b, strlen(str));
2696                                 CHECK(dns_name_fromtext(name, &b, dns_rootname,
2697                                                         0, NULL));
2698                                 CHECK(dns_view_excludedelegationonly(view,
2699                                                                      name));
2700                         }
2701                 }
2702         } else
2703                 dns_view_setrootdelonly(view, ISC_FALSE);
2704
2705         /*
2706          * Setup automatic empty zones.  If recursion is off then
2707          * they are disabled by default.
2708          */
2709         obj = NULL;
2710         (void)ns_config_get(maps, "empty-zones-enable", &obj);
2711         (void)ns_config_get(maps, "disable-empty-zone", &disablelist);
2712         if (obj == NULL && disablelist == NULL &&
2713             view->rdclass == dns_rdataclass_in) {
2714                 rfc1918 = ISC_FALSE;
2715                 empty_zones_enable = view->recursion;
2716         } else if (view->rdclass == dns_rdataclass_in) {
2717                 rfc1918 = ISC_TRUE;
2718                 if (obj != NULL)
2719                         empty_zones_enable = cfg_obj_asboolean(obj);
2720                 else
2721                         empty_zones_enable = view->recursion;
2722         } else {
2723                 rfc1918 = ISC_FALSE;
2724                 empty_zones_enable = ISC_FALSE;
2725         }
2726         if (empty_zones_enable && !lwresd_g_useresolvconf) {
2727                 const char *empty;
2728                 int empty_zone = 0;
2729                 dns_fixedname_t fixed;
2730                 dns_name_t *name;
2731                 isc_buffer_t buffer;
2732                 const char *str;
2733                 char server[DNS_NAME_FORMATSIZE + 1];
2734                 char contact[DNS_NAME_FORMATSIZE + 1];
2735                 isc_boolean_t logit;
2736                 const char *empty_dbtype[4] =
2737                                     { "_builtin", "empty", NULL, NULL };
2738                 int empty_dbtypec = 4;
2739                 isc_boolean_t zonestats_on;
2740
2741                 dns_fixedname_init(&fixed);
2742                 name = dns_fixedname_name(&fixed);
2743
2744                 obj = NULL;
2745                 result = ns_config_get(maps, "empty-server", &obj);
2746                 if (result == ISC_R_SUCCESS) {
2747                         str = cfg_obj_asstring(obj);
2748                         isc_buffer_init(&buffer, str, strlen(str));
2749                         isc_buffer_add(&buffer, strlen(str));
2750                         CHECK(dns_name_fromtext(name, &buffer, dns_rootname, 0,
2751                                                 NULL));
2752                         isc_buffer_init(&buffer, server, sizeof(server) - 1);
2753                         CHECK(dns_name_totext(name, ISC_FALSE, &buffer));
2754                         server[isc_buffer_usedlength(&buffer)] = 0;
2755                         empty_dbtype[2] = server;
2756                 } else
2757                         empty_dbtype[2] = "@";
2758
2759                 obj = NULL;
2760                 result = ns_config_get(maps, "empty-contact", &obj);
2761                 if (result == ISC_R_SUCCESS) {
2762                         str = cfg_obj_asstring(obj);
2763                         isc_buffer_init(&buffer, str, strlen(str));
2764                         isc_buffer_add(&buffer, strlen(str));
2765                         CHECK(dns_name_fromtext(name, &buffer, dns_rootname, 0,
2766                                                 NULL));
2767                         isc_buffer_init(&buffer, contact, sizeof(contact) - 1);
2768                         CHECK(dns_name_totext(name, ISC_FALSE, &buffer));
2769                         contact[isc_buffer_usedlength(&buffer)] = 0;
2770                         empty_dbtype[3] = contact;
2771                 } else
2772                         empty_dbtype[3] = ".";
2773
2774                 obj = NULL;
2775                 result = ns_config_get(maps, "zone-statistics", &obj);
2776                 INSIST(result == ISC_R_SUCCESS);
2777                 zonestats_on = cfg_obj_asboolean(obj);
2778
2779                 logit = ISC_TRUE;
2780                 for (empty = empty_zones[empty_zone].zone;
2781                      empty != NULL;
2782                      empty = empty_zones[++empty_zone].zone)
2783                 {
2784                         dns_forwarders_t *forwarders = NULL;
2785                         dns_view_t *pview = NULL;
2786
2787                         isc_buffer_init(&buffer, empty, strlen(empty));
2788                         isc_buffer_add(&buffer, strlen(empty));
2789                         /*
2790                          * Look for zone on drop list.
2791                          */
2792                         CHECK(dns_name_fromtext(name, &buffer, dns_rootname, 0,
2793                                                 NULL));
2794                         if (disablelist != NULL &&
2795                             on_disable_list(disablelist, name))
2796                                 continue;
2797
2798                         /*
2799                          * This zone already exists.
2800                          */
2801                         (void)dns_view_findzone(view, name, &zone);
2802                         if (zone != NULL) {
2803                                 CHECK(setquerystats(zone, mctx, zonestats_on));
2804                                 dns_zone_detach(&zone);
2805                                 continue;
2806                         }
2807
2808                         /*
2809                          * If we would forward this name don't add a
2810                          * empty zone for it.
2811                          */
2812                         result = dns_fwdtable_find(view->fwdtable, name,
2813                                                    &forwarders);
2814                         if (result == ISC_R_SUCCESS &&
2815                             forwarders->fwdpolicy == dns_fwdpolicy_only)
2816                                 continue;
2817
2818                         if (!rfc1918 && empty_zones[empty_zone].rfc1918) {
2819                                 if (logit) {
2820                                         isc_log_write(ns_g_lctx,
2821                                                       NS_LOGCATEGORY_GENERAL,
2822                                                       NS_LOGMODULE_SERVER,
2823                                                       ISC_LOG_WARNING,
2824                                                       "Warning%s%s: "
2825                                                       "'empty-zones-enable/"
2826                                                       "disable-empty-zone' "
2827                                                       "not set: disabling "
2828                                                       "RFC 1918 empty zones",
2829                                                       sep, viewname);
2830                                         logit = ISC_FALSE;
2831                                 }
2832                                 continue;
2833                         }
2834
2835                         /*
2836                          * See if we can re-use a existing zone.
2837                          */
2838                         result = dns_viewlist_find(&ns_g_server->viewlist,
2839                                                    view->name, view->rdclass,
2840                                                    &pview);
2841                         if (result != ISC_R_NOTFOUND &&
2842                             result != ISC_R_SUCCESS)
2843                                 goto cleanup;
2844
2845                         if (pview != NULL) {
2846                                 (void)dns_view_findzone(pview, name, &zone);
2847                                 dns_view_detach(&pview);
2848                                 if (zone != NULL)
2849                                         check_dbtype(&zone, empty_dbtypec,
2850                                                      empty_dbtype, mctx);
2851                                 if (zone != NULL) {
2852                                         dns_zone_setview(zone, view);
2853                                         CHECK(dns_view_addzone(view, zone));
2854                                         CHECK(setquerystats(zone, mctx,
2855                                                             zonestats_on));
2856                                         dns_zone_detach(&zone);
2857                                         continue;
2858                                 }
2859                         }
2860
2861                         CHECK(dns_zone_create(&zone, mctx));
2862                         CHECK(dns_zone_setorigin(zone, name));
2863                         dns_zone_setview(zone, view);
2864                         CHECK(dns_zonemgr_managezone(ns_g_server->zonemgr,
2865                                                      zone));
2866                         dns_zone_setclass(zone, view->rdclass);
2867                         dns_zone_settype(zone, dns_zone_master);
2868                         dns_zone_setstats(zone, ns_g_server->zonestats);
2869                         CHECK(dns_zone_setdbtype(zone, empty_dbtypec,
2870                                                  empty_dbtype));
2871                         if (view->queryacl != NULL)
2872                                 dns_zone_setqueryacl(zone, view->queryacl);
2873                         if (view->queryonacl != NULL)
2874                                 dns_zone_setqueryonacl(zone, view->queryonacl);
2875                         dns_zone_setdialup(zone, dns_dialuptype_no);
2876                         dns_zone_setnotifytype(zone, dns_notifytype_no);
2877                         dns_zone_setoption(zone, DNS_ZONEOPT_NOCHECKNS,
2878                                            ISC_TRUE);
2879                         CHECK(setquerystats(zone, mctx, zonestats_on));
2880                         CHECK(dns_view_addzone(view, zone));
2881                         isc_log_write(ns_g_lctx, NS_LOGCATEGORY_GENERAL,
2882                                       NS_LOGMODULE_SERVER, ISC_LOG_INFO,
2883                                       "automatic empty zone%s%s: %s",
2884                                       sep, viewname,  empty);
2885                         dns_zone_detach(&zone);
2886                 }
2887         }
2888
2889         /*
2890          * Make the list of response policy zone names for views that
2891          * are used for real lookups and so care about hints.
2892          */
2893         obj = NULL;
2894         if (view->rdclass == dns_rdataclass_in && need_hints &&
2895             ns_config_get(maps, "response-policy", &obj) == ISC_R_SUCCESS) {
2896                 const cfg_obj_t *recursive_only_obj;
2897                 const cfg_obj_t *break_dnssec_obj, *ttl_obj;
2898                 isc_boolean_t recursive_only_def;
2899                 dns_ttl_t ttl_def;
2900
2901                 recursive_only_obj = cfg_tuple_get(obj, "recursive-only");
2902                 if (!cfg_obj_isvoid(recursive_only_obj) &&
2903                     !cfg_obj_asboolean(recursive_only_obj))
2904                         recursive_only_def = ISC_FALSE;
2905                 else
2906                         recursive_only_def = ISC_TRUE;
2907
2908                 break_dnssec_obj = cfg_tuple_get(obj, "break-dnssec");
2909                 if (!cfg_obj_isvoid(break_dnssec_obj) &&
2910                     cfg_obj_asboolean(break_dnssec_obj))
2911                         view->rpz_break_dnssec = ISC_TRUE;
2912                 else
2913                         view->rpz_break_dnssec = ISC_FALSE;
2914
2915                 ttl_obj = cfg_tuple_get(obj, "max-policy-ttl");
2916                 if (cfg_obj_isuint32(ttl_obj))
2917                         ttl_def = cfg_obj_asuint32(ttl_obj);
2918                 else
2919                         ttl_def = DNS_RPZ_MAX_TTL_DEFAULT;
2920
2921                 for (element = cfg_list_first(cfg_tuple_get(obj, "zone list"));
2922                      element != NULL;
2923                      element = cfg_list_next(element)) {
2924                         result = configure_rpz(view, element,
2925                                                recursive_only_def, ttl_def);
2926                         if (result != ISC_R_SUCCESS)
2927                                 goto cleanup;
2928                         dns_rpz_set_need(ISC_TRUE);
2929                 }
2930         }
2931
2932         result = ISC_R_SUCCESS;
2933
2934  cleanup:
2935         if (clients != NULL)
2936                 dns_acl_detach(&clients);
2937         if (mapped != NULL)
2938                 dns_acl_detach(&mapped);
2939         if (excluded != NULL)
2940                 dns_acl_detach(&excluded);
2941         if (ring != NULL)
2942                 dns_tsigkeyring_detach(&ring);
2943         if (zone != NULL)
2944                 dns_zone_detach(&zone);
2945         if (dispatch4 != NULL)
2946                 dns_dispatch_detach(&dispatch4);
2947         if (dispatch6 != NULL)
2948                 dns_dispatch_detach(&dispatch6);
2949         if (resstats != NULL)
2950                 isc_stats_detach(&resstats);
2951         if (resquerystats != NULL)
2952                 dns_stats_detach(&resquerystats);
2953         if (order != NULL)
2954                 dns_order_detach(&order);
2955         if (cmctx != NULL)
2956                 isc_mem_detach(&cmctx);
2957         if (hmctx != NULL)
2958                 isc_mem_detach(&hmctx);
2959
2960         if (cache != NULL)
2961                 dns_cache_detach(&cache);
2962
2963         return (result);
2964 }
2965
2966 static isc_result_t
2967 configure_hints(dns_view_t *view, const char *filename) {
2968         isc_result_t result;
2969         dns_db_t *db;
2970
2971         db = NULL;
2972         result = dns_rootns_create(view->mctx, view->rdclass, filename, &db);
2973         if (result == ISC_R_SUCCESS) {
2974                 dns_view_sethints(view, db);
2975                 dns_db_detach(&db);
2976         }
2977
2978         return (result);
2979 }
2980
2981 static isc_result_t
2982 configure_alternates(const cfg_obj_t *config, dns_view_t *view,
2983                      const cfg_obj_t *alternates)
2984 {
2985         const cfg_obj_t *portobj;
2986         const cfg_obj_t *addresses;
2987         const cfg_listelt_t *element;
2988         isc_result_t result = ISC_R_SUCCESS;
2989         in_port_t port;
2990
2991         /*
2992          * Determine which port to send requests to.
2993          */
2994         if (ns_g_lwresdonly && ns_g_port != 0)
2995                 port = ns_g_port;
2996         else
2997                 CHECKM(ns_config_getport(config, &port), "port");
2998
2999         if (alternates != NULL) {
3000                 portobj = cfg_tuple_get(alternates, "port");
3001                 if (cfg_obj_isuint32(portobj)) {
3002                         isc_uint32_t val = cfg_obj_asuint32(portobj);
3003                         if (val > ISC_UINT16_MAX) {
3004                                 cfg_obj_log(portobj, ns_g_lctx, ISC_LOG_ERROR,
3005                                             "port '%u' out of range", val);
3006                                 return (ISC_R_RANGE);
3007                         }
3008                         port = (in_port_t) val;
3009                 }
3010         }
3011
3012         addresses = NULL;
3013         if (alternates != NULL)
3014                 addresses = cfg_tuple_get(alternates, "addresses");
3015
3016         for (element = cfg_list_first(addresses);
3017              element != NULL;
3018              element = cfg_list_next(element))
3019         {
3020                 const cfg_obj_t *alternate = cfg_listelt_value(element);
3021                 isc_sockaddr_t sa;
3022
3023                 if (!cfg_obj_issockaddr(alternate)) {
3024                         dns_fixedname_t fixed;
3025                         dns_name_t *name;
3026                         const char *str = cfg_obj_asstring(cfg_tuple_get(
3027                                                            alternate, "name"));
3028                         isc_buffer_t buffer;
3029                         in_port_t myport = port;
3030
3031                         isc_buffer_init(&buffer, str, strlen(str));
3032                         isc_buffer_add(&buffer, strlen(str));
3033                         dns_fixedname_init(&fixed);
3034                         name = dns_fixedname_name(&fixed);
3035                         CHECK(dns_name_fromtext(name, &buffer, dns_rootname, 0,
3036                                                 NULL));
3037
3038                         portobj = cfg_tuple_get(alternate, "port");
3039                         if (cfg_obj_isuint32(portobj)) {
3040                                 isc_uint32_t val = cfg_obj_asuint32(portobj);
3041                                 if (val > ISC_UINT16_MAX) {
3042                                         cfg_obj_log(portobj, ns_g_lctx,
3043                                                     ISC_LOG_ERROR,
3044                                                     "port '%u' out of range",
3045                                                      val);
3046                                         return (ISC_R_RANGE);
3047                                 }
3048                                 myport = (in_port_t) val;
3049                         }
3050                         CHECK(dns_resolver_addalternate(view->resolver, NULL,
3051                                                         name, myport));
3052                         continue;
3053                 }
3054
3055                 sa = *cfg_obj_assockaddr(alternate);
3056                 if (isc_sockaddr_getport(&sa) == 0)
3057                         isc_sockaddr_setport(&sa, port);
3058                 CHECK(dns_resolver_addalternate(view->resolver, &sa,
3059                                                 NULL, 0));
3060         }
3061
3062  cleanup:
3063         return (result);
3064 }
3065
3066 static isc_result_t
3067 configure_forward(const cfg_obj_t *config, dns_view_t *view, dns_name_t *origin,
3068                   const cfg_obj_t *forwarders, const cfg_obj_t *forwardtype)
3069 {
3070         const cfg_obj_t *portobj;
3071         const cfg_obj_t *faddresses;
3072         const cfg_listelt_t *element;
3073         dns_fwdpolicy_t fwdpolicy = dns_fwdpolicy_none;
3074         isc_sockaddrlist_t addresses;
3075         isc_sockaddr_t *sa;
3076         isc_result_t result;
3077         in_port_t port;
3078
3079         ISC_LIST_INIT(addresses);
3080
3081         /*
3082          * Determine which port to send forwarded requests to.
3083          */
3084         if (ns_g_lwresdonly && ns_g_port != 0)
3085                 port = ns_g_port;
3086         else
3087                 CHECKM(ns_config_getport(config, &port), "port");
3088
3089         if (forwarders != NULL) {
3090                 portobj = cfg_tuple_get(forwarders, "port");
3091                 if (cfg_obj_isuint32(portobj)) {
3092                         isc_uint32_t val = cfg_obj_asuint32(portobj);
3093                         if (val > ISC_UINT16_MAX) {
3094                                 cfg_obj_log(portobj, ns_g_lctx, ISC_LOG_ERROR,
3095                                             "port '%u' out of range", val);
3096                                 return (ISC_R_RANGE);
3097                         }
3098                         port = (in_port_t) val;
3099                 }
3100         }
3101
3102         faddresses = NULL;
3103         if (forwarders != NULL)
3104                 faddresses = cfg_tuple_get(forwarders, "addresses");
3105
3106         for (element = cfg_list_first(faddresses);
3107              element != NULL;
3108              element = cfg_list_next(element))
3109         {
3110                 const cfg_obj_t *forwarder = cfg_listelt_value(element);
3111                 sa = isc_mem_get(view->mctx, sizeof(isc_sockaddr_t));
3112                 if (sa == NULL) {
3113                         result = ISC_R_NOMEMORY;
3114                         goto cleanup;
3115                 }
3116                 *sa = *cfg_obj_assockaddr(forwarder);
3117                 if (isc_sockaddr_getport(sa) == 0)
3118                         isc_sockaddr_setport(sa, port);
3119                 ISC_LINK_INIT(sa, link);
3120                 ISC_LIST_APPEND(addresses, sa, link);
3121         }
3122
3123         if (ISC_LIST_EMPTY(addresses)) {
3124                 if (forwardtype != NULL)
3125                         cfg_obj_log(forwarders, ns_g_lctx, ISC_LOG_WARNING,
3126                                     "no forwarders seen; disabling "
3127                                     "forwarding");
3128                 fwdpolicy = dns_fwdpolicy_none;
3129         } else {
3130                 if (forwardtype == NULL)
3131                         fwdpolicy = dns_fwdpolicy_first;
3132                 else {
3133                         const char *forwardstr = cfg_obj_asstring(forwardtype);
3134                         if (strcasecmp(forwardstr, "first") == 0)
3135                                 fwdpolicy = dns_fwdpolicy_first;
3136                         else if (strcasecmp(forwardstr, "only") == 0)
3137                                 fwdpolicy = dns_fwdpolicy_only;
3138                         else
3139                                 INSIST(0);
3140                 }
3141         }
3142
3143         result = dns_fwdtable_add(view->fwdtable, origin, &addresses,
3144                                   fwdpolicy);
3145         if (result != ISC_R_SUCCESS) {
3146                 char namebuf[DNS_NAME_FORMATSIZE];
3147                 dns_name_format(origin, namebuf, sizeof(namebuf));
3148                 cfg_obj_log(forwarders, ns_g_lctx, ISC_LOG_WARNING,
3149                             "could not set up forwarding for domain '%s': %s",
3150                             namebuf, isc_result_totext(result));
3151                 goto cleanup;
3152         }
3153
3154         result = ISC_R_SUCCESS;
3155
3156  cleanup:
3157
3158         while (!ISC_LIST_EMPTY(addresses)) {
3159                 sa = ISC_LIST_HEAD(addresses);
3160                 ISC_LIST_UNLINK(addresses, sa, link);
3161                 isc_mem_put(view->mctx, sa, sizeof(isc_sockaddr_t));
3162         }
3163
3164         return (result);
3165 }
3166
3167 static isc_result_t
3168 get_viewinfo(const cfg_obj_t *vconfig, const char **namep,
3169              dns_rdataclass_t *classp)
3170 {
3171         isc_result_t result = ISC_R_SUCCESS;
3172         const char *viewname;
3173         dns_rdataclass_t viewclass;
3174
3175         REQUIRE(namep != NULL && *namep == NULL);
3176         REQUIRE(classp != NULL);
3177
3178         if (vconfig != NULL) {
3179                 const cfg_obj_t *classobj = NULL;
3180
3181                 viewname = cfg_obj_asstring(cfg_tuple_get(vconfig, "name"));
3182                 classobj = cfg_tuple_get(vconfig, "class");
3183                 result = ns_config_getclass(classobj, dns_rdataclass_in,
3184                                             &viewclass);
3185         } else {
3186                 viewname = "_default";
3187                 viewclass = dns_rdataclass_in;
3188         }
3189
3190         *namep = viewname;
3191         *classp = viewclass;
3192
3193         return (result);
3194 }
3195
3196 /*
3197  * Find a view based on its configuration info and attach to it.
3198  *
3199  * If 'vconfig' is NULL, attach to the default view.
3200  */
3201 static isc_result_t
3202 find_view(const cfg_obj_t *vconfig, dns_viewlist_t *viewlist,
3203           dns_view_t **viewp)
3204 {
3205         isc_result_t result;
3206         const char *viewname = NULL;
3207         dns_rdataclass_t viewclass;
3208         dns_view_t *view = NULL;
3209
3210         result = get_viewinfo(vconfig, &viewname, &viewclass);
3211         if (result != ISC_R_SUCCESS)
3212                 return (result);
3213
3214         result = dns_viewlist_find(viewlist, viewname, viewclass, &view);
3215         if (result != ISC_R_SUCCESS)
3216                 return (result);
3217
3218         *viewp = view;
3219         return (ISC_R_SUCCESS);
3220 }
3221
3222 /*
3223  * Create a new view and add it to the list.
3224  *
3225  * If 'vconfig' is NULL, create the default view.
3226  *
3227  * The view created is attached to '*viewp'.
3228  */
3229 static isc_result_t
3230 create_view(const cfg_obj_t *vconfig, dns_viewlist_t *viewlist,
3231             dns_view_t **viewp)
3232 {
3233         isc_result_t result;
3234         const char *viewname = NULL;
3235         dns_rdataclass_t viewclass;
3236         dns_view_t *view = NULL;
3237
3238         result = get_viewinfo(vconfig, &viewname, &viewclass);
3239         if (result != ISC_R_SUCCESS)
3240                 return (result);
3241
3242         result = dns_viewlist_find(viewlist, viewname, viewclass, &view);
3243         if (result == ISC_R_SUCCESS)
3244                 return (ISC_R_EXISTS);
3245         if (result != ISC_R_NOTFOUND)
3246                 return (result);
3247         INSIST(view == NULL);
3248
3249         result = dns_view_create(ns_g_mctx, viewclass, viewname, &view);
3250         if (result != ISC_R_SUCCESS)
3251                 return (result);
3252
3253         ISC_LIST_APPEND(*viewlist, view, link);
3254         dns_view_attach(view, viewp);
3255         return (ISC_R_SUCCESS);
3256 }
3257
3258 /*
3259  * Configure or reconfigure a zone.
3260  */
3261 static isc_result_t
3262 configure_zone(const cfg_obj_t *config, const cfg_obj_t *zconfig,
3263                const cfg_obj_t *vconfig, isc_mem_t *mctx, dns_view_t *view,
3264                cfg_aclconfctx_t *aclconf, isc_boolean_t added)
3265 {
3266         dns_view_t *pview = NULL;       /* Production view */
3267         dns_zone_t *zone = NULL;        /* New or reused zone */
3268         dns_zone_t *dupzone = NULL;
3269         const cfg_obj_t *options = NULL;
3270         const cfg_obj_t *zoptions = NULL;
3271         const cfg_obj_t *typeobj = NULL;
3272         const cfg_obj_t *forwarders = NULL;
3273         const cfg_obj_t *forwardtype = NULL;
3274         const cfg_obj_t *only = NULL;
3275         isc_result_t result;
3276         isc_result_t tresult;
3277         isc_buffer_t buffer;
3278         dns_fixedname_t fixorigin;
3279         dns_name_t *origin;
3280         const char *zname;
3281         dns_rdataclass_t zclass;
3282         const char *ztypestr;
3283
3284         options = NULL;
3285         (void)cfg_map_get(config, "options", &options);
3286
3287         zoptions = cfg_tuple_get(zconfig, "options");
3288
3289         /*
3290          * Get the zone origin as a dns_name_t.
3291          */
3292         zname = cfg_obj_asstring(cfg_tuple_get(zconfig, "name"));
3293         isc_buffer_init(&buffer, zname, strlen(zname));
3294         isc_buffer_add(&buffer, strlen(zname));
3295         dns_fixedname_init(&fixorigin);
3296         CHECK(dns_name_fromtext(dns_fixedname_name(&fixorigin),
3297                                 &buffer, dns_rootname, 0, NULL));
3298         origin = dns_fixedname_name(&fixorigin);
3299
3300         CHECK(ns_config_getclass(cfg_tuple_get(zconfig, "class"),
3301                                  view->rdclass, &zclass));
3302         if (zclass != view->rdclass) {
3303                 const char *vname = NULL;
3304                 if (vconfig != NULL)
3305                         vname = cfg_obj_asstring(cfg_tuple_get(vconfig,
3306                                                                "name"));
3307                 else
3308                         vname = "<default view>";
3309
3310                 isc_log_write(ns_g_lctx, NS_LOGCATEGORY_GENERAL,
3311                               NS_LOGMODULE_SERVER, ISC_LOG_ERROR,
3312                               "zone '%s': wrong class for view '%s'",
3313                               zname, vname);
3314                 result = ISC_R_FAILURE;
3315                 goto cleanup;
3316         }
3317
3318         (void)cfg_map_get(zoptions, "type", &typeobj);
3319         if (typeobj == NULL) {
3320                 cfg_obj_log(zconfig, ns_g_lctx, ISC_LOG_ERROR,
3321                             "zone '%s' 'type' not specified", zname);
3322                 return (ISC_R_FAILURE);
3323         }
3324         ztypestr = cfg_obj_asstring(typeobj);
3325
3326         /*
3327          * "hints zones" aren't zones.  If we've got one,
3328          * configure it and return.
3329          */
3330         if (strcasecmp(ztypestr, "hint") == 0) {
3331                 const cfg_obj_t *fileobj = NULL;
3332                 if (cfg_map_get(zoptions, "file", &fileobj) != ISC_R_SUCCESS) {
3333                         isc_log_write(ns_g_lctx, NS_LOGCATEGORY_GENERAL,
3334                                       NS_LOGMODULE_SERVER, ISC_LOG_ERROR,
3335                                       "zone '%s': 'file' not specified",
3336                                       zname);
3337                         result = ISC_R_FAILURE;
3338                         goto cleanup;
3339                 }
3340                 if (dns_name_equal(origin, dns_rootname)) {
3341                         const char *hintsfile = cfg_obj_asstring(fileobj);
3342
3343                         result = configure_hints(view, hintsfile);
3344                         if (result != ISC_R_SUCCESS) {
3345                                 isc_log_write(ns_g_lctx, NS_LOGCATEGORY_GENERAL,
3346                                               NS_LOGMODULE_SERVER,
3347                                               ISC_LOG_ERROR,
3348                                               "could not configure root hints "
3349                                               "from '%s': %s", hintsfile,
3350                                               isc_result_totext(result));
3351                                 goto cleanup;
3352                         }
3353                         /*
3354                          * Hint zones may also refer to delegation only points.
3355                          */
3356                         only = NULL;
3357                         tresult = cfg_map_get(zoptions, "delegation-only",
3358                                               &only);
3359                         if (tresult == ISC_R_SUCCESS && cfg_obj_asboolean(only))
3360                                 CHECK(dns_view_adddelegationonly(view, origin));
3361                 } else {
3362                         isc_log_write(ns_g_lctx, NS_LOGCATEGORY_GENERAL,
3363                                       NS_LOGMODULE_SERVER, ISC_LOG_WARNING,
3364                                       "ignoring non-root hint zone '%s'",
3365                                       zname);
3366                         result = ISC_R_SUCCESS;
3367                 }
3368                 /* Skip ordinary zone processing. */
3369                 goto cleanup;
3370         }
3371
3372         /*
3373          * "forward zones" aren't zones either.  Translate this syntax into
3374          * the appropriate selective forwarding configuration and return.
3375          */
3376         if (strcasecmp(ztypestr, "forward") == 0) {
3377                 forwardtype = NULL;
3378                 forwarders = NULL;
3379
3380                 (void)cfg_map_get(zoptions, "forward", &forwardtype);
3381                 (void)cfg_map_get(zoptions, "forwarders", &forwarders);
3382                 result = configure_forward(config, view, origin, forwarders,
3383                                            forwardtype);
3384                 goto cleanup;
3385         }
3386
3387         /*
3388          * "delegation-only zones" aren't zones either.
3389          */
3390         if (strcasecmp(ztypestr, "delegation-only") == 0) {
3391                 result = dns_view_adddelegationonly(view, origin);
3392                 goto cleanup;
3393         }
3394
3395         /*
3396          * Check for duplicates in the new zone table.
3397          */
3398         result = dns_view_findzone(view, origin, &dupzone);
3399         if (result == ISC_R_SUCCESS) {
3400                 /*
3401                  * We already have this zone!
3402                  */
3403                 cfg_obj_log(zconfig, ns_g_lctx, ISC_LOG_ERROR,
3404                             "zone '%s' already exists", zname);
3405                 dns_zone_detach(&dupzone);
3406                 result = ISC_R_EXISTS;
3407                 goto cleanup;
3408         }
3409         INSIST(dupzone == NULL);
3410
3411         /*
3412          * See if we can reuse an existing zone.  This is
3413          * only possible if all of these are true:
3414          *   - The zone's view exists
3415          *   - A zone with the right name exists in the view
3416          *   - The zone is compatible with the config
3417          *     options (e.g., an existing master zone cannot
3418          *     be reused if the options specify a slave zone)
3419          */
3420         result = dns_viewlist_find(&ns_g_server->viewlist,
3421                                    view->name, view->rdclass,
3422                                    &pview);
3423         if (result != ISC_R_NOTFOUND && result != ISC_R_SUCCESS)
3424                 goto cleanup;
3425         if (pview != NULL)
3426                 result = dns_view_findzone(pview, origin, &zone);
3427         if (result != ISC_R_NOTFOUND && result != ISC_R_SUCCESS)
3428                 goto cleanup;
3429         if (zone != NULL && !ns_zone_reusable(zone, zconfig))
3430                 dns_zone_detach(&zone);
3431
3432         if (zone != NULL) {
3433                 /*
3434                  * We found a reusable zone.  Make it use the
3435                  * new view.
3436                  */
3437                 dns_zone_setview(zone, view);
3438                 if (view->acache != NULL)
3439                         dns_zone_setacache(zone, view->acache);
3440         } else {
3441                 /*
3442                  * We cannot reuse an existing zone, we have
3443                  * to create a new one.
3444                  */
3445                 CHECK(dns_zone_create(&zone, mctx));
3446                 CHECK(dns_zone_setorigin(zone, origin));
3447                 dns_zone_setview(zone, view);
3448                 if (view->acache != NULL)
3449                         dns_zone_setacache(zone, view->acache);
3450                 CHECK(dns_zonemgr_managezone(ns_g_server->zonemgr, zone));
3451                 dns_zone_setstats(zone, ns_g_server->zonestats);
3452         }
3453
3454         /*
3455          * If the zone contains a 'forwarders' statement, configure
3456          * selective forwarding.
3457          */
3458         forwarders = NULL;
3459         if (cfg_map_get(zoptions, "forwarders", &forwarders) == ISC_R_SUCCESS)
3460         {
3461                 forwardtype = NULL;
3462                 (void)cfg_map_get(zoptions, "forward", &forwardtype);
3463                 CHECK(configure_forward(config, view, origin, forwarders,
3464                                         forwardtype));
3465         }
3466
3467         /*
3468          * Stub and forward zones may also refer to delegation only points.
3469          */
3470         only = NULL;
3471         if (cfg_map_get(zoptions, "delegation-only", &only) == ISC_R_SUCCESS)
3472         {
3473                 if (cfg_obj_asboolean(only))
3474                         CHECK(dns_view_adddelegationonly(view, origin));
3475         }
3476
3477         /*
3478          * Mark whether the zone was originally added at runtime or not
3479          */
3480         dns_zone_setadded(zone, added);
3481
3482         /*
3483          * Configure the zone.
3484          */
3485         CHECK(ns_zone_configure(config, vconfig, zconfig, aclconf, zone));
3486
3487         /*
3488          * Add the zone to its view in the new view list.
3489          */
3490         CHECK(dns_view_addzone(view, zone));
3491
3492         /*
3493          * Ensure that zone keys are reloaded on reconfig
3494          */
3495         if ((dns_zone_getkeyopts(zone) & DNS_ZONEKEY_MAINTAIN) != 0)
3496                 dns_zone_rekey(zone, ISC_FALSE);
3497
3498  cleanup:
3499         if (zone != NULL)
3500                 dns_zone_detach(&zone);
3501         if (pview != NULL)
3502                 dns_view_detach(&pview);
3503
3504         return (result);
3505 }
3506
3507 /*
3508  * Configure built-in zone for storing managed-key data.
3509  */
3510
3511 #define KEYZONE "managed-keys.bind"
3512 #define MKEYS ".mkeys"
3513
3514 static isc_result_t
3515 add_keydata_zone(dns_view_t *view, const char *directory, isc_mem_t *mctx) {
3516         isc_result_t result;
3517         dns_view_t *pview = NULL;
3518         dns_zone_t *zone = NULL;
3519         dns_acl_t *none = NULL;
3520         char filename[PATH_MAX];
3521         char buffer[ISC_SHA256_DIGESTSTRINGLENGTH + sizeof(MKEYS)];
3522         int n;
3523
3524         REQUIRE(view != NULL);
3525
3526         /* See if we can re-use an existing keydata zone. */
3527         result = dns_viewlist_find(&ns_g_server->viewlist,
3528                                    view->name, view->rdclass,
3529                                    &pview);
3530         if (result != ISC_R_NOTFOUND &&
3531             result != ISC_R_SUCCESS)
3532                 return (result);
3533
3534         if (pview != NULL && pview->managed_keys != NULL) {
3535                 dns_zone_attach(pview->managed_keys, &view->managed_keys);
3536                 dns_zone_setview(pview->managed_keys, view);
3537                 dns_view_detach(&pview);
3538                 dns_zone_synckeyzone(view->managed_keys);
3539                 return (ISC_R_SUCCESS);
3540         }
3541
3542         /* No existing keydata zone was found; create one */
3543         CHECK(dns_zone_create(&zone, mctx));
3544         CHECK(dns_zone_setorigin(zone, dns_rootname));
3545
3546         isc_sha256_data((void *)view->name, strlen(view->name), buffer);
3547         strcat(buffer, MKEYS);
3548         n = snprintf(filename, sizeof(filename), "%s%s%s",
3549                      directory ? directory : "", directory ? "/" : "",
3550                      strcmp(view->name, "_default") == 0 ? KEYZONE : buffer);
3551         if (n < 0 || (size_t)n >= sizeof(filename)) {
3552                 result = (n < 0) ? ISC_R_FAILURE : ISC_R_NOSPACE;
3553                 goto cleanup;
3554         }
3555         CHECK(dns_zone_setfile(zone, filename));
3556
3557         dns_zone_setview(zone, view);
3558         dns_zone_settype(zone, dns_zone_key);
3559         dns_zone_setclass(zone, view->rdclass);
3560
3561         CHECK(dns_zonemgr_managezone(ns_g_server->zonemgr, zone));
3562
3563         if (view->acache != NULL)
3564                 dns_zone_setacache(zone, view->acache);
3565
3566         CHECK(dns_acl_none(mctx, &none));
3567         dns_zone_setqueryacl(zone, none);
3568         dns_zone_setqueryonacl(zone, none);
3569         dns_acl_detach(&none);
3570
3571         dns_zone_setdialup(zone, dns_dialuptype_no);
3572         dns_zone_setnotifytype(zone, dns_notifytype_no);
3573         dns_zone_setoption(zone, DNS_ZONEOPT_NOCHECKNS, ISC_TRUE);
3574         dns_zone_setjournalsize(zone, 0);
3575
3576         dns_zone_setstats(zone, ns_g_server->zonestats);
3577         CHECK(setquerystats(zone, mctx, ISC_FALSE));
3578
3579         if (view->managed_keys != NULL)
3580                 dns_zone_detach(&view->managed_keys);
3581         dns_zone_attach(zone, &view->managed_keys);
3582
3583         isc_log_write(ns_g_lctx, NS_LOGCATEGORY_GENERAL,
3584                       NS_LOGMODULE_SERVER, ISC_LOG_INFO,
3585                       "set up managed keys zone for view %s, file '%s'",
3586                       view->name, filename);
3587
3588 cleanup:
3589         if (zone != NULL)
3590                 dns_zone_detach(&zone);
3591         if (none != NULL)
3592                 dns_acl_detach(&none);
3593
3594         return (result);
3595 }
3596
3597 /*
3598  * Configure a single server quota.
3599  */
3600 static void
3601 configure_server_quota(const cfg_obj_t **maps, const char *name,
3602                        isc_quota_t *quota)
3603 {
3604         const cfg_obj_t *obj = NULL;
3605         isc_result_t result;
3606
3607         result = ns_config_get(maps, name, &obj);
3608         INSIST(result == ISC_R_SUCCESS);
3609         isc_quota_max(quota, cfg_obj_asuint32(obj));
3610 }
3611
3612 /*
3613  * This function is called as soon as the 'directory' statement has been
3614  * parsed.  This can be extended to support other options if necessary.
3615  */
3616 static isc_result_t
3617 directory_callback(const char *clausename, const cfg_obj_t *obj, void *arg) {
3618         isc_result_t result;
3619         const char *directory;
3620
3621         REQUIRE(strcasecmp("directory", clausename) == 0);
3622
3623         UNUSED(arg);
3624         UNUSED(clausename);
3625
3626         /*
3627          * Change directory.
3628          */
3629         directory = cfg_obj_asstring(obj);
3630
3631         if (! isc_file_ischdiridempotent(directory))
3632                 cfg_obj_log(obj, ns_g_lctx, ISC_LOG_WARNING,
3633                             "option 'directory' contains relative path '%s'",
3634                             directory);
3635
3636         result = isc_dir_chdir(directory);
3637         if (result != ISC_R_SUCCESS) {
3638                 cfg_obj_log(obj, ns_g_lctx, ISC_LOG_ERROR,
3639                             "change directory to '%s' failed: %s",
3640                             directory, isc_result_totext(result));
3641                 return (result);
3642         }
3643
3644         return (ISC_R_SUCCESS);
3645 }
3646
3647 static void
3648 scan_interfaces(ns_server_t *server, isc_boolean_t verbose) {
3649         isc_boolean_t match_mapped = server->aclenv.match_mapped;
3650
3651         ns_interfacemgr_scan(server->interfacemgr, verbose);
3652         /*
3653          * Update the "localhost" and "localnets" ACLs to match the
3654          * current set of network interfaces.
3655          */
3656         dns_aclenv_copy(&server->aclenv,
3657                         ns_interfacemgr_getaclenv(server->interfacemgr));
3658
3659         server->aclenv.match_mapped = match_mapped;
3660 }
3661
3662 static isc_result_t
3663 add_listenelt(isc_mem_t *mctx, ns_listenlist_t *list, isc_sockaddr_t *addr,
3664               isc_boolean_t wcardport_ok)
3665 {
3666         ns_listenelt_t *lelt = NULL;
3667         dns_acl_t *src_acl = NULL;
3668         isc_result_t result;
3669         isc_sockaddr_t any_sa6;
3670         isc_netaddr_t netaddr;
3671
3672         REQUIRE(isc_sockaddr_pf(addr) == AF_INET6);
3673
3674         isc_sockaddr_any6(&any_sa6);
3675         if (!isc_sockaddr_equal(&any_sa6, addr) &&
3676             (wcardport_ok || isc_sockaddr_getport(addr) != 0)) {
3677                 isc_netaddr_fromin6(&netaddr, &addr->type.sin6.sin6_addr);
3678
3679                 result = dns_acl_create(mctx, 0, &src_acl);
3680                 if (result != ISC_R_SUCCESS)
3681                         return (result);
3682
3683                 result = dns_iptable_addprefix(src_acl->iptable,
3684                                                &netaddr, 128, ISC_TRUE);
3685                 if (result != ISC_R_SUCCESS)
3686                         goto clean;
3687
3688                 result = ns_listenelt_create(mctx, isc_sockaddr_getport(addr),
3689                                              src_acl, &lelt);
3690                 if (result != ISC_R_SUCCESS)
3691                         goto clean;
3692                 ISC_LIST_APPEND(list->elts, lelt, link);
3693         }
3694
3695         return (ISC_R_SUCCESS);
3696
3697  clean:
3698         INSIST(lelt == NULL);
3699         dns_acl_detach(&src_acl);
3700
3701         return (result);
3702 }
3703
3704 /*
3705  * Make a list of xxx-source addresses and call ns_interfacemgr_adjust()
3706  * to update the listening interfaces accordingly.
3707  * We currently only consider IPv6, because this only affects IPv6 wildcard
3708  * sockets.
3709  */
3710 static void
3711 adjust_interfaces(ns_server_t *server, isc_mem_t *mctx) {
3712         isc_result_t result;
3713         ns_listenlist_t *list = NULL;
3714         dns_view_t *view;
3715         dns_zone_t *zone, *next;
3716         isc_sockaddr_t addr, *addrp;
3717
3718         result = ns_listenlist_create(mctx, &list);
3719         if (result != ISC_R_SUCCESS)
3720                 return;
3721
3722         for (view = ISC_LIST_HEAD(server->viewlist);
3723              view != NULL;
3724              view = ISC_LIST_NEXT(view, link)) {
3725                 dns_dispatch_t *dispatch6;
3726
3727                 dispatch6 = dns_resolver_dispatchv6(view->resolver);
3728                 if (dispatch6 == NULL)
3729                         continue;
3730                 result = dns_dispatch_getlocaladdress(dispatch6, &addr);
3731                 if (result != ISC_R_SUCCESS)
3732                         goto fail;
3733
3734                 /*
3735                  * We always add non-wildcard address regardless of whether
3736                  * the port is 'any' (the fourth arg is TRUE): if the port is
3737                  * specific, we need to add it since it may conflict with a
3738                  * listening interface; if it's zero, we'll dynamically open
3739                  * query ports, and some of them may override an existing
3740                  * wildcard IPv6 port.
3741                  */
3742                 result = add_listenelt(mctx, list, &addr, ISC_TRUE);
3743                 if (result != ISC_R_SUCCESS)
3744                         goto fail;
3745         }
3746
3747         zone = NULL;
3748         for (result = dns_zone_first(server->zonemgr, &zone);
3749              result == ISC_R_SUCCESS;
3750              next = NULL, result = dns_zone_next(zone, &next), zone = next) {
3751                 dns_view_t *zoneview;
3752
3753                 /*
3754                  * At this point the zone list may contain a stale zone
3755                  * just removed from the configuration.  To see the validity,
3756                  * check if the corresponding view is in our current view list.
3757                  * There may also be old zones that are still in the process
3758                  * of shutting down and have detached from their old view
3759                  * (zoneview == NULL).
3760                  */
3761                 zoneview = dns_zone_getview(zone);
3762                 if (zoneview == NULL)
3763                         continue;
3764                 for (view = ISC_LIST_HEAD(server->viewlist);
3765                      view != NULL && view != zoneview;
3766                      view = ISC_LIST_NEXT(view, link))
3767                         ;
3768                 if (view == NULL)
3769                         continue;
3770
3771                 addrp = dns_zone_getnotifysrc6(zone);
3772                 result = add_listenelt(mctx, list, addrp, ISC_FALSE);
3773                 if (result != ISC_R_SUCCESS)
3774                         goto fail;
3775
3776                 addrp = dns_zone_getxfrsource6(zone);
3777                 result = add_listenelt(mctx, list, addrp, ISC_FALSE);
3778                 if (result != ISC_R_SUCCESS)
3779                         goto fail;
3780         }
3781
3782         ns_interfacemgr_adjust(server->interfacemgr, list, ISC_TRUE);
3783
3784  clean:
3785         ns_listenlist_detach(&list);
3786         return;
3787
3788  fail:
3789         /*
3790          * Even when we failed the procedure, most of other interfaces
3791          * should work correctly.  We therefore just warn it.
3792          */
3793         isc_log_write(ns_g_lctx, NS_LOGCATEGORY_GENERAL,
3794                       NS_LOGMODULE_SERVER, ISC_LOG_WARNING,
3795                       "could not adjust the listen-on list; "
3796                       "some interfaces may not work");
3797         goto clean;
3798 }
3799
3800 /*
3801  * This event callback is invoked to do periodic network
3802  * interface scanning.
3803  */
3804 static void
3805 interface_timer_tick(isc_task_t *task, isc_event_t *event) {
3806         isc_result_t result;
3807         ns_server_t *server = (ns_server_t *) event->ev_arg;
3808         INSIST(task == server->task);
3809         UNUSED(task);
3810         isc_event_free(&event);
3811         /*
3812          * XXX should scan interfaces unlocked and get exclusive access
3813          * only to replace ACLs.
3814          */
3815         result = isc_task_beginexclusive(server->task);
3816         RUNTIME_CHECK(result == ISC_R_SUCCESS);
3817         scan_interfaces(server, ISC_FALSE);
3818         isc_task_endexclusive(server->task);
3819 }
3820
3821 static void
3822 heartbeat_timer_tick(isc_task_t *task, isc_event_t *event) {
3823         ns_server_t *server = (ns_server_t *) event->ev_arg;
3824         dns_view_t *view;
3825
3826         UNUSED(task);
3827         isc_event_free(&event);
3828         view = ISC_LIST_HEAD(server->viewlist);
3829         while (view != NULL) {
3830                 dns_view_dialup(view);
3831                 view = ISC_LIST_NEXT(view, link);
3832         }
3833 }
3834
3835 static void
3836 pps_timer_tick(isc_task_t *task, isc_event_t *event) {
3837         static unsigned int oldrequests = 0;
3838         unsigned int requests = ns_client_requests;
3839
3840         UNUSED(task);
3841         isc_event_free(&event);
3842
3843         /*
3844          * Don't worry about wrapping as the overflow result will be right.
3845          */
3846         dns_pps = (requests - oldrequests) / 1200;
3847         oldrequests = requests;
3848 }
3849
3850 /*
3851  * Replace the current value of '*field', a dynamically allocated
3852  * string or NULL, with a dynamically allocated copy of the
3853  * null-terminated string pointed to by 'value', or NULL.
3854  */
3855 static isc_result_t
3856 setstring(ns_server_t *server, char **field, const char *value) {
3857         char *copy;
3858
3859         if (value != NULL) {
3860                 copy = isc_mem_strdup(server->mctx, value);
3861                 if (copy == NULL)
3862                         return (ISC_R_NOMEMORY);
3863         } else {
3864                 copy = NULL;
3865         }
3866
3867         if (*field != NULL)
3868                 isc_mem_free(server->mctx, *field);
3869
3870         *field = copy;
3871         return (ISC_R_SUCCESS);
3872 }
3873
3874 /*
3875  * Replace the current value of '*field', a dynamically allocated
3876  * string or NULL, with another dynamically allocated string
3877  * or NULL if whether 'obj' is a string or void value, respectively.
3878  */
3879 static isc_result_t
3880 setoptstring(ns_server_t *server, char **field, const cfg_obj_t *obj) {
3881         if (cfg_obj_isvoid(obj))
3882                 return (setstring(server, field, NULL));
3883         else
3884                 return (setstring(server, field, cfg_obj_asstring(obj)));
3885 }
3886
3887 static void
3888 set_limit(const cfg_obj_t **maps, const char *configname,
3889           const char *description, isc_resource_t resourceid,
3890           isc_resourcevalue_t defaultvalue)
3891 {
3892         const cfg_obj_t *obj = NULL;
3893         const char *resource;
3894         isc_resourcevalue_t value;
3895         isc_result_t result;
3896
3897         if (ns_config_get(maps, configname, &obj) != ISC_R_SUCCESS)
3898                 return;
3899
3900         if (cfg_obj_isstring(obj)) {
3901                 resource = cfg_obj_asstring(obj);
3902                 if (strcasecmp(resource, "unlimited") == 0)
3903                         value = ISC_RESOURCE_UNLIMITED;
3904                 else {
3905                         INSIST(strcasecmp(resource, "default") == 0);
3906                         value = defaultvalue;
3907                 }
3908         } else
3909                 value = cfg_obj_asuint64(obj);
3910
3911         result = isc_resource_setlimit(resourceid, value);
3912         isc_log_write(ns_g_lctx, NS_LOGCATEGORY_GENERAL, NS_LOGMODULE_SERVER,
3913                       result == ISC_R_SUCCESS ?
3914                         ISC_LOG_DEBUG(3) : ISC_LOG_WARNING,
3915                       "set maximum %s to %" ISC_PRINT_QUADFORMAT "u: %s",
3916                       description, value, isc_result_totext(result));
3917 }
3918
3919 #define SETLIMIT(cfgvar, resource, description) \
3920         set_limit(maps, cfgvar, description, isc_resource_ ## resource, \
3921                   ns_g_init ## resource)
3922
3923 static void
3924 set_limits(const cfg_obj_t **maps) {
3925         SETLIMIT("stacksize", stacksize, "stack size");
3926         SETLIMIT("datasize", datasize, "data size");
3927         SETLIMIT("coresize", coresize, "core size");
3928         SETLIMIT("files", openfiles, "open files");
3929 }
3930
3931 static void
3932 portset_fromconf(isc_portset_t *portset, const cfg_obj_t *ports,
3933                  isc_boolean_t positive)
3934 {
3935         const cfg_listelt_t *element;
3936
3937         for (element = cfg_list_first(ports);
3938              element != NULL;
3939              element = cfg_list_next(element)) {
3940                 const cfg_obj_t *obj = cfg_listelt_value(element);
3941
3942                 if (cfg_obj_isuint32(obj)) {
3943                         in_port_t port = (in_port_t)cfg_obj_asuint32(obj);
3944
3945                         if (positive)
3946                                 isc_portset_add(portset, port);
3947                         else
3948                                 isc_portset_remove(portset, port);
3949                 } else {
3950                         const cfg_obj_t *obj_loport, *obj_hiport;
3951                         in_port_t loport, hiport;
3952
3953                         obj_loport = cfg_tuple_get(obj, "loport");
3954                         loport = (in_port_t)cfg_obj_asuint32(obj_loport);
3955                         obj_hiport = cfg_tuple_get(obj, "hiport");
3956                         hiport = (in_port_t)cfg_obj_asuint32(obj_hiport);
3957
3958                         if (positive)
3959                                 isc_portset_addrange(portset, loport, hiport);
3960                         else {
3961                                 isc_portset_removerange(portset, loport,
3962                                                         hiport);
3963                         }
3964                 }
3965         }
3966 }
3967
3968 static isc_result_t
3969 removed(dns_zone_t *zone, void *uap) {
3970         const char *type;
3971
3972         if (dns_zone_getview(zone) != uap)
3973                 return (ISC_R_SUCCESS);
3974
3975         switch (dns_zone_gettype(zone)) {
3976         case dns_zone_master:
3977                 type = "master";
3978                 break;
3979         case dns_zone_slave:
3980                 type = "slave";
3981                 break;
3982         case dns_zone_stub:
3983                 type = "stub";
3984                 break;
3985         default:
3986                 type = "other";
3987                 break;
3988         }
3989         dns_zone_log(zone, ISC_LOG_INFO, "(%s) removed", type);
3990         return (ISC_R_SUCCESS);
3991 }
3992
3993 static void
3994 cleanup_session_key(ns_server_t *server, isc_mem_t *mctx) {
3995         if (server->session_keyfile != NULL) {
3996                 isc_file_remove(server->session_keyfile);
3997                 isc_mem_free(mctx, server->session_keyfile);
3998                 server->session_keyfile = NULL;
3999         }
4000
4001         if (server->session_keyname != NULL) {
4002                 if (dns_name_dynamic(server->session_keyname))
4003                         dns_name_free(server->session_keyname, mctx);
4004                 isc_mem_put(mctx, server->session_keyname, sizeof(dns_name_t));
4005                 server->session_keyname = NULL;
4006         }
4007
4008         if (server->sessionkey != NULL)
4009                 dns_tsigkey_detach(&server->sessionkey);
4010
4011         server->session_keyalg = DST_ALG_UNKNOWN;
4012         server->session_keybits = 0;
4013 }
4014
4015 static isc_result_t
4016 generate_session_key(const char *filename, const char *keynamestr,
4017                      dns_name_t *keyname, const char *algstr,
4018                      dns_name_t *algname, unsigned int algtype,
4019                      isc_uint16_t bits, isc_mem_t *mctx,
4020                      dns_tsigkey_t **tsigkeyp)
4021 {
4022         isc_result_t result = ISC_R_SUCCESS;
4023         dst_key_t *key = NULL;
4024         isc_buffer_t key_txtbuffer;
4025         isc_buffer_t key_rawbuffer;
4026         char key_txtsecret[256];
4027         char key_rawsecret[64];
4028         isc_region_t key_rawregion;
4029         isc_stdtime_t now;
4030         dns_tsigkey_t *tsigkey = NULL;
4031         FILE *fp = NULL;
4032
4033         isc_log_write(ns_g_lctx, NS_LOGCATEGORY_GENERAL,
4034                       NS_LOGMODULE_SERVER, ISC_LOG_INFO,
4035                       "generating session key for dynamic DNS");
4036
4037         /* generate key */
4038         result = dst_key_generate(keyname, algtype, bits, 1, 0,
4039                                   DNS_KEYPROTO_ANY, dns_rdataclass_in,
4040                                   mctx, &key);
4041         if (result != ISC_R_SUCCESS)
4042                 return (result);
4043
4044         /*
4045          * Dump the key to the buffer for later use.  Should be done before
4046          * we transfer the ownership of key to tsigkey.
4047          */
4048         isc_buffer_init(&key_rawbuffer, &key_rawsecret, sizeof(key_rawsecret));
4049         CHECK(dst_key_tobuffer(key, &key_rawbuffer));
4050
4051         isc_buffer_usedregion(&key_rawbuffer, &key_rawregion);
4052         isc_buffer_init(&key_txtbuffer, &key_txtsecret, sizeof(key_txtsecret));
4053         CHECK(isc_base64_totext(&key_rawregion, -1, "", &key_txtbuffer));
4054
4055         /* Store the key in tsigkey. */
4056         isc_stdtime_get(&now);
4057         CHECK(dns_tsigkey_createfromkey(dst_key_name(key), algname, key,
4058                                         ISC_FALSE, NULL, now, now, mctx, NULL,
4059                                         &tsigkey));
4060
4061         /* Dump the key to the key file. */
4062         fp = ns_os_openfile(filename, S_IRUSR|S_IWUSR, ISC_TRUE);
4063         if (fp == NULL) {
4064                 isc_log_write(ns_g_lctx, NS_LOGCATEGORY_GENERAL,
4065                               NS_LOGMODULE_SERVER, ISC_LOG_ERROR,
4066                               "could not create %s", filename);
4067                 result = ISC_R_NOPERM;
4068                 goto cleanup;
4069         }
4070
4071         fprintf(fp, "key \"%s\" {\n"
4072                 "\talgorithm %s;\n"
4073                 "\tsecret \"%.*s\";\n};\n", keynamestr, algstr,
4074                 (int) isc_buffer_usedlength(&key_txtbuffer),
4075                 (char*) isc_buffer_base(&key_txtbuffer));
4076
4077         RUNTIME_CHECK(isc_stdio_flush(fp) == ISC_R_SUCCESS);
4078         RUNTIME_CHECK(isc_stdio_close(fp) == ISC_R_SUCCESS);
4079
4080         dst_key_free(&key);
4081
4082         *tsigkeyp = tsigkey;
4083
4084         return (ISC_R_SUCCESS);
4085
4086   cleanup:
4087         isc_log_write(ns_g_lctx, NS_LOGCATEGORY_GENERAL,
4088                       NS_LOGMODULE_SERVER, ISC_LOG_ERROR,
4089                       "failed to generate session key "
4090                       "for dynamic DNS: %s", isc_result_totext(result));
4091         if (tsigkey != NULL)
4092                 dns_tsigkey_detach(&tsigkey);
4093         if (key != NULL)
4094                 dst_key_free(&key);
4095
4096         return (result);
4097 }
4098
4099 static isc_result_t
4100 configure_session_key(const cfg_obj_t **maps, ns_server_t *server,
4101                       isc_mem_t *mctx)
4102 {
4103         const char *keyfile, *keynamestr, *algstr;
4104         unsigned int algtype;
4105         dns_fixedname_t fname;
4106         dns_name_t *keyname, *algname;
4107         isc_buffer_t buffer;
4108         isc_uint16_t bits;
4109         const cfg_obj_t *obj;
4110         isc_boolean_t need_deleteold = ISC_FALSE;
4111         isc_boolean_t need_createnew = ISC_FALSE;
4112         isc_result_t result;
4113
4114         obj = NULL;
4115         result = ns_config_get(maps, "session-keyfile", &obj);
4116         if (result == ISC_R_SUCCESS) {
4117                 if (cfg_obj_isvoid(obj))
4118                         keyfile = NULL; /* disable it */
4119                 else
4120                         keyfile = cfg_obj_asstring(obj);
4121         } else
4122                 keyfile = ns_g_defaultsessionkeyfile;
4123
4124         obj = NULL;
4125         result = ns_config_get(maps, "session-keyname", &obj);
4126         INSIST(result == ISC_R_SUCCESS);
4127         keynamestr = cfg_obj_asstring(obj);
4128         dns_fixedname_init(&fname);
4129         isc_buffer_init(&buffer, keynamestr, strlen(keynamestr));
4130         isc_buffer_add(&buffer, strlen(keynamestr));
4131         keyname = dns_fixedname_name(&fname);
4132         result = dns_name_fromtext(keyname, &buffer, dns_rootname, 0, NULL);
4133         if (result != ISC_R_SUCCESS)
4134                 return (result);
4135
4136         obj = NULL;
4137         result = ns_config_get(maps, "session-keyalg", &obj);
4138         INSIST(result == ISC_R_SUCCESS);
4139         algstr = cfg_obj_asstring(obj);
4140         algname = NULL;
4141         result = ns_config_getkeyalgorithm2(algstr, &algname, &algtype, &bits);
4142         if (result != ISC_R_SUCCESS) {
4143                 const char *s = " (keeping current key)";
4144
4145                 cfg_obj_log(obj, ns_g_lctx, ISC_LOG_ERROR, "session-keyalg: "
4146                             "unsupported or unknown algorithm '%s'%s",
4147                             algstr,
4148                             server->session_keyfile != NULL ? s : "");
4149                 return (result);
4150         }
4151
4152         /* See if we need to (re)generate a new key. */
4153         if (keyfile == NULL) {
4154                 if (server->session_keyfile != NULL)
4155                         need_deleteold = ISC_TRUE;
4156         } else if (server->session_keyfile == NULL)
4157                 need_createnew = ISC_TRUE;
4158         else if (strcmp(keyfile, server->session_keyfile) != 0 ||
4159                  !dns_name_equal(server->session_keyname, keyname) ||
4160                  server->session_keyalg != algtype ||
4161                  server->session_keybits != bits) {
4162                 need_deleteold = ISC_TRUE;
4163                 need_createnew = ISC_TRUE;
4164         }
4165
4166         if (need_deleteold) {
4167                 INSIST(server->session_keyfile != NULL);
4168                 INSIST(server->session_keyname != NULL);
4169                 INSIST(server->sessionkey != NULL);
4170
4171                 cleanup_session_key(server, mctx);
4172         }
4173
4174         if (need_createnew) {
4175                 INSIST(server->sessionkey == NULL);
4176                 INSIST(server->session_keyfile == NULL);
4177                 INSIST(server->session_keyname == NULL);
4178                 INSIST(server->session_keyalg == DST_ALG_UNKNOWN);
4179                 INSIST(server->session_keybits == 0);
4180
4181                 server->session_keyname = isc_mem_get(mctx, sizeof(dns_name_t));
4182                 if (server->session_keyname == NULL)
4183                         goto cleanup;
4184                 dns_name_init(server->session_keyname, NULL);
4185                 CHECK(dns_name_dup(keyname, mctx, server->session_keyname));
4186
4187                 server->session_keyfile = isc_mem_strdup(mctx, keyfile);
4188                 if (server->session_keyfile == NULL)
4189                         goto cleanup;
4190
4191                 server->session_keyalg = algtype;
4192                 server->session_keybits = bits;
4193
4194                 CHECK(generate_session_key(keyfile, keynamestr, keyname, algstr,
4195                                            algname, algtype, bits, mctx,
4196                                            &server->sessionkey));
4197         }
4198
4199         return (result);
4200
4201   cleanup:
4202         cleanup_session_key(server, mctx);
4203         return (result);
4204 }
4205
4206 static isc_result_t
4207 setup_newzones(dns_view_t *view, cfg_obj_t *config, cfg_obj_t *vconfig,
4208                cfg_parser_t *parser, cfg_aclconfctx_t *actx)
4209 {
4210         isc_result_t result = ISC_R_SUCCESS;
4211         isc_boolean_t allow = ISC_FALSE;
4212         struct cfg_context *nzcfg = NULL;
4213         cfg_parser_t *nzparser = NULL;
4214         cfg_obj_t *nzconfig = NULL;
4215         const cfg_obj_t *maps[4];
4216         const cfg_obj_t *options = NULL, *voptions = NULL;
4217         const cfg_obj_t *nz = NULL;
4218         int i = 0;
4219
4220         REQUIRE (config != NULL);
4221
4222         if (vconfig != NULL)
4223                 voptions = cfg_tuple_get(vconfig, "options");
4224         if (voptions != NULL)
4225                 maps[i++] = voptions;
4226         result = cfg_map_get(config, "options", &options);
4227         if (result == ISC_R_SUCCESS)
4228                 maps[i++] = options;
4229         maps[i++] = ns_g_defaults;
4230         maps[i] = NULL;
4231
4232         result = ns_config_get(maps, "allow-new-zones", &nz);
4233         if (result == ISC_R_SUCCESS)
4234                 allow = cfg_obj_asboolean(nz);
4235
4236         if (!allow) {
4237                 dns_view_setnewzones(view, ISC_FALSE, NULL, NULL);
4238                 return (ISC_R_SUCCESS);
4239         }
4240
4241         nzcfg = isc_mem_get(view->mctx, sizeof(*nzcfg));
4242         if (nzcfg == NULL) {
4243                 dns_view_setnewzones(view, ISC_FALSE, NULL, NULL);
4244                 return (ISC_R_NOMEMORY);
4245         }
4246
4247         dns_view_setnewzones(view, allow, nzcfg, newzone_cfgctx_destroy);
4248
4249         memset(nzcfg, 0, sizeof(*nzcfg));
4250         isc_mem_attach(view->mctx, &nzcfg->mctx);
4251         cfg_obj_attach(config, &nzcfg->config);
4252         cfg_parser_attach(parser, &nzcfg->parser);
4253         cfg_aclconfctx_attach(actx, &nzcfg->actx);
4254
4255         /*
4256          * Attempt to create a parser and parse the newzones
4257          * file.  If successful, preserve both; otherwise leave
4258          * them NULL.
4259          */
4260         result = cfg_parser_create(view->mctx, ns_g_lctx, &nzparser);
4261         if (result == ISC_R_SUCCESS)
4262                 result = cfg_parse_file(nzparser, view->new_zone_file,
4263                                         &cfg_type_newzones, &nzconfig);
4264         if (result == ISC_R_SUCCESS) {
4265                 cfg_parser_attach(nzparser, &nzcfg->nzparser);
4266                 cfg_obj_attach(nzconfig, &nzcfg->nzconfig);
4267         }
4268
4269         if (nzparser != NULL) {
4270                 if (nzconfig != NULL)
4271                         cfg_obj_destroy(nzparser, &nzconfig);
4272                 cfg_parser_destroy(&nzparser);
4273         }
4274
4275         return (ISC_R_SUCCESS);
4276 }
4277
4278 static int
4279 count_zones(const cfg_obj_t *conf) {
4280         const cfg_obj_t *zonelist = NULL;
4281         const cfg_listelt_t *element;
4282         int n = 0;
4283
4284         REQUIRE(conf != NULL);
4285
4286         cfg_map_get(conf, "zone", &zonelist);
4287         for (element = cfg_list_first(zonelist);
4288              element != NULL;
4289              element = cfg_list_next(element))
4290                 n++;
4291
4292         return (n);
4293 }
4294
4295 static isc_result_t
4296 load_configuration(const char *filename, ns_server_t *server,
4297                    isc_boolean_t first_time)
4298 {
4299         cfg_obj_t *config = NULL, *bindkeys = NULL;
4300         cfg_parser_t *conf_parser = NULL, *bindkeys_parser = NULL;
4301         const cfg_listelt_t *element;
4302         const cfg_obj_t *builtin_views;
4303         const cfg_obj_t *maps[3];
4304         const cfg_obj_t *obj;
4305         const cfg_obj_t *options;
4306         const cfg_obj_t *usev4ports, *avoidv4ports, *usev6ports, *avoidv6ports;
4307         const cfg_obj_t *views;
4308         dns_view_t *view = NULL;
4309         dns_view_t *view_next;
4310         dns_viewlist_t tmpviewlist;
4311         dns_viewlist_t viewlist, builtin_viewlist;
4312         in_port_t listen_port, udpport_low, udpport_high;
4313         int i;
4314         isc_interval_t interval;
4315         isc_portset_t *v4portset = NULL;
4316         isc_portset_t *v6portset = NULL;
4317         isc_resourcevalue_t nfiles;
4318         isc_result_t result;
4319         isc_uint32_t heartbeat_interval;
4320         isc_uint32_t interface_interval;
4321         isc_uint32_t reserved;
4322         isc_uint32_t udpsize;
4323         ns_cachelist_t cachelist, tmpcachelist;
4324         unsigned int maxsocks;
4325         ns_cache_t *nsc;
4326         struct cfg_context *nzctx;
4327         int num_zones = 0;
4328         isc_boolean_t exclusive = ISC_FALSE;
4329
4330         ISC_LIST_INIT(viewlist);
4331         ISC_LIST_INIT(builtin_viewlist);
4332         ISC_LIST_INIT(cachelist);
4333
4334         /* Create the ACL configuration context */
4335         if (ns_g_aclconfctx != NULL)
4336                 cfg_aclconfctx_detach(&ns_g_aclconfctx);
4337         CHECK(cfg_aclconfctx_create(ns_g_mctx, &ns_g_aclconfctx));
4338
4339         /*
4340          * Parse the global default pseudo-config file.
4341          */
4342         if (first_time) {
4343                 CHECK(ns_config_parsedefaults(ns_g_parser, &ns_g_config));
4344                 RUNTIME_CHECK(cfg_map_get(ns_g_config, "options",
4345                                           &ns_g_defaults) == ISC_R_SUCCESS);
4346         }
4347
4348         /*
4349          * Parse the configuration file using the new config code.
4350          */
4351         result = ISC_R_FAILURE;
4352         config = NULL;
4353
4354         /*
4355          * Unless this is lwresd with the -C option, parse the config file.
4356          */
4357         if (!(ns_g_lwresdonly && lwresd_g_useresolvconf)) {
4358                 isc_log_write(ns_g_lctx,
4359                               NS_LOGCATEGORY_GENERAL, NS_LOGMODULE_SERVER,
4360                               ISC_LOG_INFO, "loading configuration from '%s'",
4361                               filename);
4362                 CHECK(cfg_parser_create(ns_g_mctx, ns_g_lctx, &conf_parser));
4363                 cfg_parser_setcallback(conf_parser, directory_callback, NULL);
4364                 result = cfg_parse_file(conf_parser, filename,
4365                                         &cfg_type_namedconf, &config);
4366         }
4367
4368         /*
4369          * If this is lwresd with the -C option, or lwresd with no -C or -c
4370          * option where the above parsing failed, parse resolv.conf.
4371          */
4372         if (ns_g_lwresdonly &&
4373             (lwresd_g_useresolvconf ||
4374              (!ns_g_conffileset && result == ISC_R_FILENOTFOUND)))
4375         {
4376                 isc_log_write(ns_g_lctx,
4377                               NS_LOGCATEGORY_GENERAL, NS_LOGMODULE_SERVER,
4378                               ISC_LOG_INFO, "loading configuration from '%s'",
4379                               lwresd_g_resolvconffile);
4380                 if (conf_parser != NULL)
4381                         cfg_parser_destroy(&conf_parser);
4382                 CHECK(cfg_parser_create(ns_g_mctx, ns_g_lctx, &conf_parser));
4383                 result = ns_lwresd_parseeresolvconf(ns_g_mctx, conf_parser,
4384                                                     &config);
4385         }
4386         CHECK(result);
4387
4388         /*
4389          * Check the validity of the configuration.
4390          */
4391         CHECK(bind9_check_namedconf(config, ns_g_lctx, ns_g_mctx));
4392
4393         /*
4394          * Fill in the maps array, used for resolving defaults.
4395          */
4396         i = 0;
4397         options = NULL;
4398         result = cfg_map_get(config, "options", &options);
4399         if (result == ISC_R_SUCCESS)
4400                 maps[i++] = options;
4401         maps[i++] = ns_g_defaults;
4402         maps[i] = NULL;
4403
4404         /*
4405          * If bind.keys exists, load it.  If "dnssec-lookaside auto"
4406          * is turned on, the keys found there will be used as default
4407          * trust anchors.
4408          */
4409         obj = NULL;
4410         result = ns_config_get(maps, "bindkeys-file", &obj);
4411         INSIST(result == ISC_R_SUCCESS);
4412         CHECKM(setstring(server, &server->bindkeysfile,
4413                cfg_obj_asstring(obj)), "strdup");
4414
4415         if (access(server->bindkeysfile, R_OK) == 0) {
4416                 isc_log_write(ns_g_lctx, NS_LOGCATEGORY_GENERAL,
4417                               NS_LOGMODULE_SERVER, ISC_LOG_INFO,
4418                               "reading built-in trusted "
4419                               "keys from file '%s'", server->bindkeysfile);
4420
4421                 CHECK(cfg_parser_create(ns_g_mctx, ns_g_lctx,
4422                                         &bindkeys_parser));
4423
4424                 result = cfg_parse_file(bindkeys_parser, server->bindkeysfile,
4425                                         &cfg_type_bindkeys, &bindkeys);
4426                 CHECK(result);
4427         }
4428
4429         /* Ensure exclusive access to configuration data. */
4430         if (!exclusive) {
4431                 result = isc_task_beginexclusive(server->task);
4432                 RUNTIME_CHECK(result == ISC_R_SUCCESS);
4433                 exclusive = ISC_TRUE;
4434         }
4435
4436         /*
4437          * Set process limits, which (usually) needs to be done as root.
4438          */
4439         set_limits(maps);
4440
4441         /*
4442          * Check if max number of open sockets that the system allows is
4443          * sufficiently large.  Failing this condition is not necessarily fatal,
4444          * but may cause subsequent runtime failures for a busy recursive
4445          * server.
4446          */
4447         result = isc_socketmgr_getmaxsockets(ns_g_socketmgr, &maxsocks);
4448         if (result != ISC_R_SUCCESS)
4449                 maxsocks = 0;
4450         result = isc_resource_getcurlimit(isc_resource_openfiles, &nfiles);
4451         if (result == ISC_R_SUCCESS && (isc_resourcevalue_t)maxsocks > nfiles) {
4452                 isc_log_write(ns_g_lctx, NS_LOGCATEGORY_GENERAL,
4453                               NS_LOGMODULE_SERVER, ISC_LOG_WARNING,
4454                               "max open files (%" ISC_PRINT_QUADFORMAT "u)"
4455                               " is smaller than max sockets (%u)",
4456                               nfiles, maxsocks);
4457         }
4458
4459         /*
4460          * Set the number of socket reserved for TCP, stdio etc.
4461          */
4462         obj = NULL;
4463         result = ns_config_get(maps, "reserved-sockets", &obj);
4464         INSIST(result == ISC_R_SUCCESS);
4465         reserved = cfg_obj_asuint32(obj);
4466         if (maxsocks != 0) {
4467                 if (maxsocks < 128U)                    /* Prevent underflow. */
4468                         reserved = 0;
4469                 else if (reserved > maxsocks - 128U)    /* Minimum UDP space. */
4470                         reserved = maxsocks - 128;
4471         }
4472         /* Minimum TCP/stdio space. */
4473         if (reserved < 128U)
4474                 reserved = 128;
4475         if (reserved + 128U > maxsocks && maxsocks != 0) {
4476                 isc_log_write(ns_g_lctx, NS_LOGCATEGORY_GENERAL,
4477                               NS_LOGMODULE_SERVER, ISC_LOG_WARNING,
4478                               "less than 128 UDP sockets available after "
4479                               "applying 'reserved-sockets' and 'maxsockets'");
4480         }
4481         isc__socketmgr_setreserved(ns_g_socketmgr, reserved);
4482
4483         /*
4484          * Configure various server options.
4485          */
4486         configure_server_quota(maps, "transfers-out", &server->xfroutquota);
4487         configure_server_quota(maps, "tcp-clients", &server->tcpquota);
4488         configure_server_quota(maps, "recursive-clients",
4489                                &server->recursionquota);
4490         if (server->recursionquota.max > 1000)
4491                 isc_quota_soft(&server->recursionquota,
4492                                server->recursionquota.max - 100);
4493         else
4494                 isc_quota_soft(&server->recursionquota, 0);
4495
4496         CHECK(configure_view_acl(NULL, config, "blackhole", NULL,
4497                                  ns_g_aclconfctx, ns_g_mctx,
4498                                  &server->blackholeacl));
4499         if (server->blackholeacl != NULL)
4500                 dns_dispatchmgr_setblackhole(ns_g_dispatchmgr,
4501                                              server->blackholeacl);
4502
4503         obj = NULL;
4504         result = ns_config_get(maps, "match-mapped-addresses", &obj);
4505         INSIST(result == ISC_R_SUCCESS);
4506         server->aclenv.match_mapped = cfg_obj_asboolean(obj);
4507
4508         CHECKM(ns_statschannels_configure(ns_g_server, config, ns_g_aclconfctx),
4509                "configuring statistics server(s)");
4510
4511         /*
4512          * Configure sets of UDP query source ports.
4513          */
4514         CHECKM(isc_portset_create(ns_g_mctx, &v4portset),
4515                "creating UDP port set");
4516         CHECKM(isc_portset_create(ns_g_mctx, &v6portset),
4517                "creating UDP port set");
4518
4519         usev4ports = NULL;
4520         usev6ports = NULL;
4521         avoidv4ports = NULL;
4522         avoidv6ports = NULL;
4523
4524         (void)ns_config_get(maps, "use-v4-udp-ports", &usev4ports);
4525         if (usev4ports != NULL)
4526                 portset_fromconf(v4portset, usev4ports, ISC_TRUE);
4527         else {
4528                 CHECKM(isc_net_getudpportrange(AF_INET, &udpport_low,
4529                                                &udpport_high),
4530                        "get the default UDP/IPv4 port range");
4531                 if (udpport_low == udpport_high)
4532                         isc_portset_add(v4portset, udpport_low);
4533                 else {
4534                         isc_portset_addrange(v4portset, udpport_low,
4535                                              udpport_high);
4536                 }
4537                 isc_log_write(ns_g_lctx, NS_LOGCATEGORY_GENERAL,
4538                               NS_LOGMODULE_SERVER, ISC_LOG_INFO,
4539                               "using default UDP/IPv4 port range: [%d, %d]",
4540                               udpport_low, udpport_high);
4541         }
4542         (void)ns_config_get(maps, "avoid-v4-udp-ports", &avoidv4ports);
4543         if (avoidv4ports != NULL)
4544                 portset_fromconf(v4portset, avoidv4ports, ISC_FALSE);
4545
4546         (void)ns_config_get(maps, "use-v6-udp-ports", &usev6ports);
4547         if (usev6ports != NULL)
4548                 portset_fromconf(v6portset, usev6ports, ISC_TRUE);
4549         else {
4550                 CHECKM(isc_net_getudpportrange(AF_INET6, &udpport_low,
4551                                                &udpport_high),
4552                        "get the default UDP/IPv6 port range");
4553                 if (udpport_low == udpport_high)
4554                         isc_portset_add(v6portset, udpport_low);
4555                 else {
4556                         isc_portset_addrange(v6portset, udpport_low,
4557                                              udpport_high);
4558                 }
4559                 isc_log_write(ns_g_lctx, NS_LOGCATEGORY_GENERAL,
4560                               NS_LOGMODULE_SERVER, ISC_LOG_INFO,
4561                               "using default UDP/IPv6 port range: [%d, %d]",
4562                               udpport_low, udpport_high);
4563         }
4564         (void)ns_config_get(maps, "avoid-v6-udp-ports", &avoidv6ports);
4565         if (avoidv6ports != NULL)
4566                 portset_fromconf(v6portset, avoidv6ports, ISC_FALSE);
4567
4568         dns_dispatchmgr_setavailports(ns_g_dispatchmgr, v4portset, v6portset);
4569
4570         /*
4571          * Set the EDNS UDP size when we don't match a view.
4572          */
4573         obj = NULL;
4574         result = ns_config_get(maps, "edns-udp-size", &obj);
4575         INSIST(result == ISC_R_SUCCESS);
4576         udpsize = cfg_obj_asuint32(obj);
4577         if (udpsize < 512)
4578                 udpsize = 512;
4579         if (udpsize > 4096)
4580                 udpsize = 4096;
4581         ns_g_udpsize = (isc_uint16_t)udpsize;
4582
4583         /*
4584          * Configure the zone manager.
4585          */
4586         obj = NULL;
4587         result = ns_config_get(maps, "transfers-in", &obj);
4588         INSIST(result == ISC_R_SUCCESS);
4589         dns_zonemgr_settransfersin(server->zonemgr, cfg_obj_asuint32(obj));
4590
4591         obj = NULL;
4592         result = ns_config_get(maps, "transfers-per-ns", &obj);
4593         INSIST(result == ISC_R_SUCCESS);
4594         dns_zonemgr_settransfersperns(server->zonemgr, cfg_obj_asuint32(obj));
4595
4596         obj = NULL;
4597         result = ns_config_get(maps, "serial-query-rate", &obj);
4598         INSIST(result == ISC_R_SUCCESS);
4599         dns_zonemgr_setserialqueryrate(server->zonemgr, cfg_obj_asuint32(obj));
4600
4601         /*
4602          * Determine which port to use for listening for incoming connections.
4603          */
4604         if (ns_g_port != 0)
4605                 listen_port = ns_g_port;
4606         else
4607                 CHECKM(ns_config_getport(config, &listen_port), "port");
4608
4609         /*
4610          * Find the listen queue depth.
4611          */
4612         obj = NULL;
4613         result = ns_config_get(maps, "tcp-listen-queue", &obj);
4614         INSIST(result == ISC_R_SUCCESS);
4615         ns_g_listen = cfg_obj_asuint32(obj);
4616         if (ns_g_listen < 3)
4617                 ns_g_listen = 3;
4618
4619         /*
4620          * Configure the interface manager according to the "listen-on"
4621          * statement.
4622          */
4623         {
4624                 const cfg_obj_t *clistenon = NULL;
4625                 ns_listenlist_t *listenon = NULL;
4626
4627                 clistenon = NULL;
4628                 /*
4629                  * Even though listen-on is present in the default
4630                  * configuration, we can't use it here, since it isn't
4631                  * used if we're in lwresd mode.  This way is easier.
4632                  */
4633                 if (options != NULL)
4634                         (void)cfg_map_get(options, "listen-on", &clistenon);
4635                 if (clistenon != NULL) {
4636                         /* check return code? */
4637                         (void)ns_listenlist_fromconfig(clistenon, config,
4638                                                        ns_g_aclconfctx,
4639                                                        ns_g_mctx, &listenon);
4640                 } else if (!ns_g_lwresdonly) {
4641                         /*
4642                          * Not specified, use default.
4643                          */
4644                         CHECK(ns_listenlist_default(ns_g_mctx, listen_port,
4645                                                     ISC_TRUE, &listenon));
4646                 }
4647                 if (listenon != NULL) {
4648                         ns_interfacemgr_setlistenon4(server->interfacemgr,
4649                                                      listenon);
4650                         ns_listenlist_detach(&listenon);
4651                 }
4652         }
4653         /*
4654          * Ditto for IPv6.
4655          */
4656         {
4657                 const cfg_obj_t *clistenon = NULL;
4658                 ns_listenlist_t *listenon = NULL;
4659
4660                 if (options != NULL)
4661                         (void)cfg_map_get(options, "listen-on-v6", &clistenon);
4662                 if (clistenon != NULL) {
4663                         /* check return code? */
4664                         (void)ns_listenlist_fromconfig(clistenon, config,
4665                                                        ns_g_aclconfctx,
4666                                                        ns_g_mctx, &listenon);
4667                 } else if (!ns_g_lwresdonly) {
4668                         isc_boolean_t enable;
4669                         /*
4670                          * Not specified, use default.
4671                          */
4672                         enable = ISC_TF(isc_net_probeipv4() != ISC_R_SUCCESS);
4673                         CHECK(ns_listenlist_default(ns_g_mctx, listen_port,
4674                                                     enable, &listenon));
4675                 }
4676                 if (listenon != NULL) {
4677                         ns_interfacemgr_setlistenon6(server->interfacemgr,
4678                                                      listenon);
4679                         ns_listenlist_detach(&listenon);
4680                 }
4681         }
4682
4683         /*
4684          * Rescan the interface list to pick up changes in the
4685          * listen-on option.  It's important that we do this before we try
4686          * to configure the query source, since the dispatcher we use might
4687          * be shared with an interface.
4688          */
4689         scan_interfaces(server, ISC_TRUE);
4690
4691         /*
4692          * Arrange for further interface scanning to occur periodically
4693          * as specified by the "interface-interval" option.
4694          */
4695         obj = NULL;
4696         result = ns_config_get(maps, "interface-interval", &obj);
4697         INSIST(result == ISC_R_SUCCESS);
4698         interface_interval = cfg_obj_asuint32(obj) * 60;
4699         if (interface_interval == 0) {
4700                 CHECK(isc_timer_reset(server->interface_timer,
4701                                       isc_timertype_inactive,
4702                                       NULL, NULL, ISC_TRUE));
4703         } else if (server->interface_interval != interface_interval) {
4704                 isc_interval_set(&interval, interface_interval, 0);
4705                 CHECK(isc_timer_reset(server->interface_timer,
4706                                       isc_timertype_ticker,
4707                                       NULL, &interval, ISC_FALSE));
4708         }
4709         server->interface_interval = interface_interval;
4710
4711         /*
4712          * Configure the dialup heartbeat timer.
4713          */
4714         obj = NULL;
4715         result = ns_config_get(maps, "heartbeat-interval", &obj);
4716         INSIST(result == ISC_R_SUCCESS);
4717         heartbeat_interval = cfg_obj_asuint32(obj) * 60;
4718         if (heartbeat_interval == 0) {
4719                 CHECK(isc_timer_reset(server->heartbeat_timer,
4720                                       isc_timertype_inactive,
4721                                       NULL, NULL, ISC_TRUE));
4722         } else if (server->heartbeat_interval != heartbeat_interval) {
4723                 isc_interval_set(&interval, heartbeat_interval, 0);
4724                 CHECK(isc_timer_reset(server->heartbeat_timer,
4725                                       isc_timertype_ticker,
4726                                       NULL, &interval, ISC_FALSE));
4727         }
4728         server->heartbeat_interval = heartbeat_interval;
4729
4730         isc_interval_set(&interval, 1200, 0);
4731         CHECK(isc_timer_reset(server->pps_timer, isc_timertype_ticker, NULL,
4732                               &interval, ISC_FALSE));
4733
4734         /*
4735          * Write the PID file.
4736          */
4737         obj = NULL;
4738         if (ns_config_get(maps, "pid-file", &obj) == ISC_R_SUCCESS)
4739                 if (cfg_obj_isvoid(obj))
4740                         ns_os_writepidfile(NULL, first_time);
4741                 else
4742                         ns_os_writepidfile(cfg_obj_asstring(obj), first_time);
4743         else if (ns_g_lwresdonly)
4744                 ns_os_writepidfile(lwresd_g_defaultpidfile, first_time);
4745         else
4746                 ns_os_writepidfile(ns_g_defaultpidfile, first_time);
4747
4748         /*
4749          * Configure the server-wide session key.  This must be done before
4750          * configure views because zone configuration may need to know
4751          * session-keyname.
4752          *
4753          * Failure of session key generation isn't fatal at this time; if it
4754          * turns out that a session key is really needed but doesn't exist,
4755          * we'll treat it as a fatal error then.
4756          */
4757         (void)configure_session_key(maps, server, ns_g_mctx);
4758
4759         views = NULL;
4760         (void)cfg_map_get(config, "view", &views);
4761
4762         /*
4763          * Create the views and count all the configured zones in
4764          * order to correctly size the zone manager's task table.
4765          * (We only count zones for configured views; the built-in
4766          * "bind" view can be ignored as it only adds a negligible
4767          * number of zones.)
4768          *
4769          * If we're allowing new zones, we need to be able to find the
4770          * new zone file and count those as well.  So we setup the new
4771          * zone configuration context, but otherwise view configuration
4772          * waits until after the zone manager's task list has been sized.
4773          */
4774         for (element = cfg_list_first(views);
4775              element != NULL;
4776              element = cfg_list_next(element))
4777         {
4778                 cfg_obj_t *vconfig = cfg_listelt_value(element);
4779                 const cfg_obj_t *voptions = cfg_tuple_get(vconfig, "options");
4780                 view = NULL;
4781
4782                 CHECK(create_view(vconfig, &viewlist, &view));
4783                 INSIST(view != NULL);
4784
4785                 num_zones += count_zones(voptions);
4786                 CHECK(setup_newzones(view, config, vconfig, conf_parser,
4787                                      ns_g_aclconfctx));
4788
4789                 nzctx = view->new_zone_config;
4790                 if (nzctx != NULL && nzctx->nzconfig != NULL)
4791                         num_zones += count_zones(nzctx->nzconfig);
4792
4793                 dns_view_detach(&view);
4794         }
4795
4796         /*
4797          * If there were no explicit views then we do the default
4798          * view here.
4799          */
4800         if (views == NULL) {
4801                 CHECK(create_view(NULL, &viewlist, &view));
4802                 INSIST(view != NULL);
4803
4804                 num_zones = count_zones(config);
4805
4806                 CHECK(setup_newzones(view, config, NULL,  conf_parser,
4807                                      ns_g_aclconfctx));
4808
4809                 nzctx = view->new_zone_config;
4810                 if (nzctx != NULL && nzctx->nzconfig != NULL)
4811                         num_zones += count_zones(nzctx->nzconfig);
4812
4813                 dns_view_detach(&view);
4814         }
4815
4816         /*
4817          * Zones have been counted; set the zone manager task pool size.
4818          */
4819         isc_log_write(ns_g_lctx, NS_LOGCATEGORY_GENERAL,
4820                       NS_LOGMODULE_SERVER, ISC_LOG_INFO,
4821                       "sizing zone task pool based on %d zones", num_zones);
4822         CHECK(dns_zonemgr_setsize(ns_g_server->zonemgr, num_zones));
4823
4824         /*
4825          * Configure and freeze all explicit views.  Explicit
4826          * views that have zones were already created at parsing
4827          * time, but views with no zones must be created here.
4828          */
4829         for (element = cfg_list_first(views);
4830              element != NULL;
4831              element = cfg_list_next(element))
4832         {
4833                 cfg_obj_t *vconfig = cfg_listelt_value(element);
4834
4835                 view = NULL;
4836                 CHECK(find_view(vconfig, &viewlist, &view));
4837                 CHECK(configure_view(view, config, vconfig,
4838                                      &cachelist, bindkeys, ns_g_mctx,
4839                                      ns_g_aclconfctx, ISC_TRUE));
4840                 dns_view_freeze(view);
4841                 dns_view_detach(&view);
4842         }
4843
4844         /*
4845          * Make sure we have a default view if and only if there
4846          * were no explicit views.
4847          */
4848         if (views == NULL) {
4849                 view = NULL;
4850                 CHECK(find_view(NULL, &viewlist, &view));
4851                 CHECK(configure_view(view, config, NULL,
4852                                      &cachelist, bindkeys,
4853                                      ns_g_mctx, ns_g_aclconfctx, ISC_TRUE));
4854                 dns_view_freeze(view);
4855                 dns_view_detach(&view);
4856         }
4857
4858         /*
4859          * Create (or recreate) the built-in views.
4860          */
4861         builtin_views = NULL;
4862         RUNTIME_CHECK(cfg_map_get(ns_g_config, "view",
4863                                   &builtin_views) == ISC_R_SUCCESS);
4864         for (element = cfg_list_first(builtin_views);
4865              element != NULL;
4866              element = cfg_list_next(element))
4867         {
4868                 cfg_obj_t *vconfig = cfg_listelt_value(element);
4869
4870                 CHECK(create_view(vconfig, &builtin_viewlist, &view));
4871                 CHECK(configure_view(view, config, vconfig,
4872                                      &cachelist, bindkeys,
4873                                      ns_g_mctx, ns_g_aclconfctx, ISC_FALSE));
4874                 dns_view_freeze(view);
4875                 dns_view_detach(&view);
4876                 view = NULL;
4877         }
4878
4879         /* Now combine the two viewlists into one */
4880         ISC_LIST_APPENDLIST(viewlist, builtin_viewlist, link);
4881
4882         /* Swap our new view list with the production one. */
4883         tmpviewlist = server->viewlist;
4884         server->viewlist = viewlist;
4885         viewlist = tmpviewlist;
4886
4887         /* Make the view list available to each of the views */
4888         view = ISC_LIST_HEAD(server->viewlist);
4889         while (view != NULL) {
4890                 view->viewlist = &server->viewlist;
4891                 view = ISC_LIST_NEXT(view, link);
4892         }
4893
4894         /* Swap our new cache list with the production one. */
4895         tmpcachelist = server->cachelist;
4896         server->cachelist = cachelist;
4897         cachelist = tmpcachelist;
4898
4899         /* Load the TKEY information from the configuration. */
4900         if (options != NULL) {
4901                 dns_tkeyctx_t *t = NULL;
4902                 CHECKM(ns_tkeyctx_fromconfig(options, ns_g_mctx, ns_g_entropy,
4903                                              &t),
4904                        "configuring TKEY");
4905                 if (server->tkeyctx != NULL)
4906                         dns_tkeyctx_destroy(&server->tkeyctx);
4907                 server->tkeyctx = t;
4908         }
4909
4910         /*
4911          * Bind the control port(s).
4912          */
4913         CHECKM(ns_controls_configure(ns_g_server->controls, config,
4914                                      ns_g_aclconfctx),
4915                "binding control channel(s)");
4916
4917         /*
4918          * Bind the lwresd port(s).
4919          */
4920         CHECKM(ns_lwresd_configure(ns_g_mctx, config),
4921                "binding lightweight resolver ports");
4922
4923         /*
4924          * Open the source of entropy.
4925          */
4926         if (first_time) {
4927                 obj = NULL;
4928                 result = ns_config_get(maps, "random-device", &obj);
4929                 if (result != ISC_R_SUCCESS) {
4930                         isc_log_write(ns_g_lctx, NS_LOGCATEGORY_GENERAL,
4931                                       NS_LOGMODULE_SERVER, ISC_LOG_INFO,
4932                                       "no source of entropy found");
4933                 } else {
4934                         const char *randomdev = cfg_obj_asstring(obj);
4935                         result = isc_entropy_createfilesource(ns_g_entropy,
4936                                                               randomdev);
4937                         if (result != ISC_R_SUCCESS)
4938                                 isc_log_write(ns_g_lctx,
4939                                               NS_LOGCATEGORY_GENERAL,
4940                                               NS_LOGMODULE_SERVER,
4941                                               ISC_LOG_INFO,
4942                                               "could not open entropy source "
4943                                               "%s: %s",
4944                                               randomdev,
4945                                               isc_result_totext(result));
4946 #ifdef PATH_RANDOMDEV
4947                         if (ns_g_fallbackentropy != NULL) {
4948                                 if (result != ISC_R_SUCCESS) {
4949                                         isc_log_write(ns_g_lctx,
4950                                                       NS_LOGCATEGORY_GENERAL,
4951                                                       NS_LOGMODULE_SERVER,
4952                                                       ISC_LOG_INFO,
4953                                                       "using pre-chroot entropy source "
4954                                                       "%s",
4955                                                       PATH_RANDOMDEV);
4956                                         isc_entropy_detach(&ns_g_entropy);
4957                                         isc_entropy_attach(ns_g_fallbackentropy,
4958                                                            &ns_g_entropy);
4959                                 }
4960                                 isc_entropy_detach(&ns_g_fallbackentropy);
4961                         }
4962 #endif
4963                 }
4964         }
4965
4966         /*
4967          * Relinquish root privileges.
4968          */
4969         if (first_time)
4970                 ns_os_changeuser();
4971
4972         /*
4973          * Check that the working directory is writable.
4974          */
4975         if (access(".", W_OK) != 0) {
4976                 isc_log_write(ns_g_lctx, NS_LOGCATEGORY_GENERAL,
4977                               NS_LOGMODULE_SERVER, ISC_LOG_ERROR,
4978                               "the working directory is not writable");
4979         }
4980
4981         /*
4982          * Configure the logging system.
4983          *
4984          * Do this after changing UID to make sure that any log
4985          * files specified in named.conf get created by the
4986          * unprivileged user, not root.
4987          */
4988         if (ns_g_logstderr) {
4989                 isc_log_write(ns_g_lctx, NS_LOGCATEGORY_GENERAL,
4990                               NS_LOGMODULE_SERVER, ISC_LOG_INFO,
4991                               "ignoring config file logging "
4992                               "statement due to -g option");
4993         } else {
4994                 const cfg_obj_t *logobj = NULL;
4995                 isc_logconfig_t *logc = NULL;
4996
4997                 CHECKM(isc_logconfig_create(ns_g_lctx, &logc),
4998                        "creating new logging configuration");
4999
5000                 logobj = NULL;
5001                 (void)cfg_map_get(config, "logging", &logobj);
5002                 if (logobj != NULL) {
5003                         CHECKM(ns_log_configure(logc, logobj),
5004                                "configuring logging");
5005                 } else {
5006                         CHECKM(ns_log_setdefaultchannels(logc),
5007                                "setting up default logging channels");
5008                         CHECKM(ns_log_setunmatchedcategory(logc),
5009                                "setting up default 'category unmatched'");
5010                         CHECKM(ns_log_setdefaultcategory(logc),
5011                                "setting up default 'category default'");
5012                 }
5013
5014                 result = isc_logconfig_use(ns_g_lctx, logc);
5015                 if (result != ISC_R_SUCCESS) {
5016                         isc_logconfig_destroy(&logc);
5017                         CHECKM(result, "installing logging configuration");
5018                 }
5019
5020                 isc_log_write(ns_g_lctx, NS_LOGCATEGORY_GENERAL,
5021                               NS_LOGMODULE_SERVER, ISC_LOG_DEBUG(1),
5022                               "now using logging configuration from "
5023                               "config file");
5024         }
5025
5026         /*
5027          * Set the default value of the query logging flag depending
5028          * whether a "queries" category has been defined.  This is
5029          * a disgusting hack, but we need to do this for BIND 8
5030          * compatibility.
5031          */
5032         if (first_time) {
5033                 const cfg_obj_t *logobj = NULL;
5034                 const cfg_obj_t *categories = NULL;
5035
5036                 obj = NULL;
5037                 if (ns_config_get(maps, "querylog", &obj) == ISC_R_SUCCESS) {
5038                         server->log_queries = cfg_obj_asboolean(obj);
5039                 } else {
5040
5041                         (void)cfg_map_get(config, "logging", &logobj);
5042                         if (logobj != NULL)
5043                                 (void)cfg_map_get(logobj, "category",
5044                                                   &categories);
5045                         if (categories != NULL) {
5046                                 const cfg_listelt_t *element;
5047                                 for (element = cfg_list_first(categories);
5048                                      element != NULL;
5049                                      element = cfg_list_next(element))
5050                                 {
5051                                         const cfg_obj_t *catobj;
5052                                         const char *str;
5053
5054                                         obj = cfg_listelt_value(element);
5055                                         catobj = cfg_tuple_get(obj, "name");
5056                                         str = cfg_obj_asstring(catobj);
5057                                         if (strcasecmp(str, "queries") == 0)
5058                                                 server->log_queries = ISC_TRUE;
5059                                 }
5060                         }
5061                 }
5062         }
5063
5064
5065         obj = NULL;
5066         if (options != NULL &&
5067             cfg_map_get(options, "memstatistics", &obj) == ISC_R_SUCCESS)
5068                 ns_g_memstatistics = cfg_obj_asboolean(obj);
5069         else
5070                 ns_g_memstatistics =
5071                         ISC_TF((isc_mem_debugging & ISC_MEM_DEBUGRECORD) != 0);
5072
5073         obj = NULL;
5074         if (ns_config_get(maps, "memstatistics-file", &obj) == ISC_R_SUCCESS)
5075                 ns_main_setmemstats(cfg_obj_asstring(obj));
5076         else if (ns_g_memstatistics)
5077                 ns_main_setmemstats("named.memstats");
5078         else
5079                 ns_main_setmemstats(NULL);
5080
5081         obj = NULL;
5082         result = ns_config_get(maps, "statistics-file", &obj);
5083         INSIST(result == ISC_R_SUCCESS);
5084         CHECKM(setstring(server, &server->statsfile, cfg_obj_asstring(obj)),
5085                "strdup");
5086
5087         obj = NULL;
5088         result = ns_config_get(maps, "dump-file", &obj);
5089         INSIST(result == ISC_R_SUCCESS);
5090         CHECKM(setstring(server, &server->dumpfile, cfg_obj_asstring(obj)),
5091                "strdup");
5092
5093         obj = NULL;
5094         result = ns_config_get(maps, "secroots-file", &obj);
5095         INSIST(result == ISC_R_SUCCESS);
5096         CHECKM(setstring(server, &server->secrootsfile, cfg_obj_asstring(obj)),
5097                "strdup");
5098
5099         obj = NULL;
5100         result = ns_config_get(maps, "recursing-file", &obj);
5101         INSIST(result == ISC_R_SUCCESS);
5102         CHECKM(setstring(server, &server->recfile, cfg_obj_asstring(obj)),
5103                "strdup");
5104
5105         obj = NULL;
5106         result = ns_config_get(maps, "version", &obj);
5107         if (result == ISC_R_SUCCESS) {
5108                 CHECKM(setoptstring(server, &server->version, obj), "strdup");
5109                 server->version_set = ISC_TRUE;
5110         } else {
5111                 server->version_set = ISC_FALSE;
5112         }
5113
5114         obj = NULL;
5115         result = ns_config_get(maps, "hostname", &obj);
5116         if (result == ISC_R_SUCCESS) {
5117                 CHECKM(setoptstring(server, &server->hostname, obj), "strdup");
5118                 server->hostname_set = ISC_TRUE;
5119         } else {
5120                 server->hostname_set = ISC_FALSE;
5121         }
5122
5123         obj = NULL;
5124         result = ns_config_get(maps, "server-id", &obj);
5125         server->server_usehostname = ISC_FALSE;
5126         if (result == ISC_R_SUCCESS && cfg_obj_isboolean(obj)) {
5127                 /* The parser translates "hostname" to ISC_TRUE */
5128                 server->server_usehostname = cfg_obj_asboolean(obj);
5129                 result = setstring(server, &server->server_id, NULL);
5130                 RUNTIME_CHECK(result == ISC_R_SUCCESS);
5131         } else if (result == ISC_R_SUCCESS) {
5132                 /* Found a quoted string */
5133                 CHECKM(setoptstring(server, &server->server_id, obj), "strdup");
5134         } else {
5135                 result = setstring(server, &server->server_id, NULL);
5136                 RUNTIME_CHECK(result == ISC_R_SUCCESS);
5137         }
5138
5139         obj = NULL;
5140         result = ns_config_get(maps, "flush-zones-on-shutdown", &obj);
5141         if (result == ISC_R_SUCCESS) {
5142                 server->flushonshutdown = cfg_obj_asboolean(obj);
5143         } else {
5144                 server->flushonshutdown = ISC_FALSE;
5145         }
5146
5147         result = ISC_R_SUCCESS;
5148
5149  cleanup:
5150         if (v4portset != NULL)
5151                 isc_portset_destroy(ns_g_mctx, &v4portset);
5152
5153         if (v6portset != NULL)
5154                 isc_portset_destroy(ns_g_mctx, &v6portset);
5155
5156         if (conf_parser != NULL) {
5157                 if (config != NULL)
5158                         cfg_obj_destroy(conf_parser, &config);
5159                 cfg_parser_destroy(&conf_parser);
5160         }
5161
5162         if (bindkeys_parser != NULL) {
5163                 if (bindkeys  != NULL)
5164                         cfg_obj_destroy(bindkeys_parser, &bindkeys);
5165                 cfg_parser_destroy(&bindkeys_parser);
5166         }
5167
5168         if (view != NULL)
5169                 dns_view_detach(&view);
5170
5171         /*
5172          * This cleans up either the old production view list
5173          * or our temporary list depending on whether they
5174          * were swapped above or not.
5175          */
5176         for (view = ISC_LIST_HEAD(viewlist);
5177              view != NULL;
5178              view = view_next) {
5179                 view_next = ISC_LIST_NEXT(view, link);
5180                 ISC_LIST_UNLINK(viewlist, view, link);
5181                 if (result == ISC_R_SUCCESS &&
5182                     strcmp(view->name, "_bind") != 0)
5183                         (void)dns_zt_apply(view->zonetable, ISC_FALSE,
5184                                            removed, view);
5185                 dns_view_detach(&view);
5186         }
5187
5188         /* Same cleanup for cache list. */
5189         while ((nsc = ISC_LIST_HEAD(cachelist)) != NULL) {
5190                 ISC_LIST_UNLINK(cachelist, nsc, link);
5191                 dns_cache_detach(&nsc->cache);
5192                 isc_mem_put(server->mctx, nsc, sizeof(*nsc));
5193         }
5194
5195         /*
5196          * Adjust the listening interfaces in accordance with the source
5197          * addresses specified in views and zones.
5198          */
5199         if (isc_net_probeipv6() == ISC_R_SUCCESS)
5200                 adjust_interfaces(server, ns_g_mctx);
5201
5202         /* Relinquish exclusive access to configuration data. */
5203         if (exclusive)
5204                 isc_task_endexclusive(server->task);
5205
5206         isc_log_write(ns_g_lctx, NS_LOGCATEGORY_GENERAL, NS_LOGMODULE_SERVER,
5207                       ISC_LOG_DEBUG(1), "load_configuration: %s",
5208                       isc_result_totext(result));
5209
5210         return (result);
5211 }
5212
5213 static isc_result_t
5214 load_zones(ns_server_t *server, isc_boolean_t stop) {
5215         isc_result_t result;
5216         dns_view_t *view;
5217
5218         result = isc_task_beginexclusive(server->task);
5219         RUNTIME_CHECK(result == ISC_R_SUCCESS);
5220
5221         /*
5222          * Load zone data from disk.
5223          */
5224         for (view = ISC_LIST_HEAD(server->viewlist);
5225              view != NULL;
5226              view = ISC_LIST_NEXT(view, link))
5227         {
5228                 CHECK(dns_view_load(view, stop));
5229                 if (view->managed_keys != NULL)
5230                         CHECK(dns_zone_load(view->managed_keys));
5231         }
5232
5233         /*
5234          * Force zone maintenance.  Do this after loading
5235          * so that we know when we need to force AXFR of
5236          * slave zones whose master files are missing.
5237          */
5238         CHECK(dns_zonemgr_forcemaint(server->zonemgr));
5239  cleanup:
5240         isc_task_endexclusive(server->task);
5241         return (result);
5242 }
5243
5244 static isc_result_t
5245 load_new_zones(ns_server_t *server, isc_boolean_t stop) {
5246         isc_result_t result;
5247         dns_view_t *view;
5248
5249         result = isc_task_beginexclusive(server->task);
5250         RUNTIME_CHECK(result == ISC_R_SUCCESS);
5251
5252         /*
5253          * Load zone data from disk.
5254          */
5255         for (view = ISC_LIST_HEAD(server->viewlist);
5256              view != NULL;
5257              view = ISC_LIST_NEXT(view, link))
5258         {
5259                 CHECK(dns_view_loadnew(view, stop));
5260
5261                 /* Load managed-keys data */
5262                 if (view->managed_keys != NULL)
5263                         CHECK(dns_zone_loadnew(view->managed_keys));
5264         }
5265
5266         /*
5267          * Resume zone XFRs.
5268          */
5269         dns_zonemgr_resumexfrs(server->zonemgr);
5270  cleanup:
5271         isc_task_endexclusive(server->task);
5272         return (result);
5273 }
5274
5275 static void
5276 run_server(isc_task_t *task, isc_event_t *event) {
5277         isc_result_t result;
5278         ns_server_t *server = (ns_server_t *)event->ev_arg;
5279
5280         INSIST(task == server->task);
5281
5282         isc_event_free(&event);
5283
5284         CHECKFATAL(dns_dispatchmgr_create(ns_g_mctx, ns_g_entropy,
5285                                           &ns_g_dispatchmgr),
5286                    "creating dispatch manager");
5287
5288         dns_dispatchmgr_setstats(ns_g_dispatchmgr, server->resolverstats);
5289
5290         CHECKFATAL(ns_interfacemgr_create(ns_g_mctx, ns_g_taskmgr,
5291                                           ns_g_socketmgr, ns_g_dispatchmgr,
5292                                           &server->interfacemgr),
5293                    "creating interface manager");
5294
5295         CHECKFATAL(isc_timer_create(ns_g_timermgr, isc_timertype_inactive,
5296                                     NULL, NULL, server->task,
5297                                     interface_timer_tick,
5298                                     server, &server->interface_timer),
5299                    "creating interface timer");
5300
5301         CHECKFATAL(isc_timer_create(ns_g_timermgr, isc_timertype_inactive,
5302                                     NULL, NULL, server->task,
5303                                     heartbeat_timer_tick,
5304                                     server, &server->heartbeat_timer),
5305                    "creating heartbeat timer");
5306
5307         CHECKFATAL(isc_timer_create(ns_g_timermgr, isc_timertype_inactive,
5308                                     NULL, NULL, server->task, pps_timer_tick,
5309                                     server, &server->pps_timer),
5310                    "creating pps timer");
5311
5312         CHECKFATAL(cfg_parser_create(ns_g_mctx, NULL, &ns_g_parser),
5313                    "creating default configuration parser");
5314
5315         if (ns_g_lwresdonly)
5316                 CHECKFATAL(load_configuration(lwresd_g_conffile, server,
5317                                               ISC_TRUE),
5318                            "loading configuration");
5319         else
5320                 CHECKFATAL(load_configuration(ns_g_conffile, server, ISC_TRUE),
5321                            "loading configuration");
5322
5323         isc_hash_init();
5324
5325         CHECKFATAL(load_zones(server, ISC_FALSE), "loading zones");
5326
5327         ns_os_started();
5328         isc_log_write(ns_g_lctx, NS_LOGCATEGORY_GENERAL, NS_LOGMODULE_SERVER,
5329                       ISC_LOG_NOTICE, "running");
5330 }
5331
5332 void
5333 ns_server_flushonshutdown(ns_server_t *server, isc_boolean_t flush) {
5334
5335         REQUIRE(NS_SERVER_VALID(server));
5336
5337         server->flushonshutdown = flush;
5338 }
5339
5340 static void
5341 shutdown_server(isc_task_t *task, isc_event_t *event) {
5342         isc_result_t result;
5343         dns_view_t *view, *view_next;
5344         ns_server_t *server = (ns_server_t *)event->ev_arg;
5345         isc_boolean_t flush = server->flushonshutdown;
5346         ns_cache_t *nsc;
5347
5348         UNUSED(task);
5349         INSIST(task == server->task);
5350
5351         result = isc_task_beginexclusive(server->task);
5352         RUNTIME_CHECK(result == ISC_R_SUCCESS);
5353
5354         isc_log_write(ns_g_lctx, NS_LOGCATEGORY_GENERAL, NS_LOGMODULE_SERVER,
5355                       ISC_LOG_INFO, "shutting down%s",
5356                       flush ? ": flushing changes" : "");
5357
5358         ns_statschannels_shutdown(server);
5359         ns_controls_shutdown(server->controls);
5360         end_reserved_dispatches(server, ISC_TRUE);
5361         cleanup_session_key(server, server->mctx);
5362
5363         if (ns_g_aclconfctx != NULL)
5364                 cfg_aclconfctx_detach(&ns_g_aclconfctx);
5365
5366         cfg_obj_destroy(ns_g_parser, &ns_g_config);
5367         cfg_parser_destroy(&ns_g_parser);
5368
5369         for (view = ISC_LIST_HEAD(server->viewlist);
5370              view != NULL;
5371              view = view_next) {
5372                 view_next = ISC_LIST_NEXT(view, link);
5373                 ISC_LIST_UNLINK(server->viewlist, view, link);
5374                 if (flush)
5375                         dns_view_flushanddetach(&view);
5376                 else
5377                         dns_view_detach(&view);
5378         }
5379
5380         while ((nsc = ISC_LIST_HEAD(server->cachelist)) != NULL) {
5381                 ISC_LIST_UNLINK(server->cachelist, nsc, link);
5382                 dns_cache_detach(&nsc->cache);
5383                 isc_mem_put(server->mctx, nsc, sizeof(*nsc));
5384         }
5385
5386         isc_timer_detach(&server->interface_timer);
5387         isc_timer_detach(&server->heartbeat_timer);
5388         isc_timer_detach(&server->pps_timer);
5389
5390         ns_interfacemgr_shutdown(server->interfacemgr);
5391         ns_interfacemgr_detach(&server->interfacemgr);
5392
5393         dns_dispatchmgr_destroy(&ns_g_dispatchmgr);
5394
5395         dns_zonemgr_shutdown(server->zonemgr);
5396
5397         if (ns_g_sessionkey != NULL) {
5398                 dns_tsigkey_detach(&ns_g_sessionkey);
5399                 dns_name_free(&ns_g_sessionkeyname, server->mctx);
5400         }
5401
5402         if (server->blackholeacl != NULL)
5403                 dns_acl_detach(&server->blackholeacl);
5404
5405         dns_db_detach(&server->in_roothints);
5406
5407         isc_task_endexclusive(server->task);
5408
5409         isc_task_detach(&server->task);
5410
5411         isc_event_free(&event);
5412 }
5413
5414 void
5415 ns_server_create(isc_mem_t *mctx, ns_server_t **serverp) {
5416         isc_result_t result;
5417         ns_server_t *server = isc_mem_get(mctx, sizeof(*server));
5418
5419         if (server == NULL)
5420                 fatal("allocating server object", ISC_R_NOMEMORY);
5421
5422         server->mctx = mctx;
5423         server->task = NULL;
5424
5425         /* Initialize configuration data with default values. */
5426
5427         result = isc_quota_init(&server->xfroutquota, 10);
5428         RUNTIME_CHECK(result == ISC_R_SUCCESS);
5429         result = isc_quota_init(&server->tcpquota, 10);
5430         RUNTIME_CHECK(result == ISC_R_SUCCESS);
5431         result = isc_quota_init(&server->recursionquota, 100);
5432         RUNTIME_CHECK(result == ISC_R_SUCCESS);
5433
5434         result = dns_aclenv_init(mctx, &server->aclenv);
5435         RUNTIME_CHECK(result == ISC_R_SUCCESS);
5436
5437         /* Initialize server data structures. */
5438         server->zonemgr = NULL;
5439         server->interfacemgr = NULL;
5440         ISC_LIST_INIT(server->viewlist);
5441         server->in_roothints = NULL;
5442         server->blackholeacl = NULL;
5443
5444         CHECKFATAL(dns_rootns_create(mctx, dns_rdataclass_in, NULL,
5445                                      &server->in_roothints),
5446                    "setting up root hints");
5447
5448         CHECKFATAL(isc_mutex_init(&server->reload_event_lock),
5449                    "initializing reload event lock");
5450         server->reload_event =
5451                 isc_event_allocate(ns_g_mctx, server,
5452                                    NS_EVENT_RELOAD,
5453                                    ns_server_reload,
5454                                    server,
5455                                    sizeof(isc_event_t));
5456         CHECKFATAL(server->reload_event == NULL ?
5457                    ISC_R_NOMEMORY : ISC_R_SUCCESS,
5458                    "allocating reload event");
5459
5460         CHECKFATAL(dst_lib_init2(ns_g_mctx, ns_g_entropy,
5461                                  ns_g_engine, ISC_ENTROPY_GOODONLY),
5462                    "initializing DST");
5463
5464         server->tkeyctx = NULL;
5465         CHECKFATAL(dns_tkeyctx_create(ns_g_mctx, ns_g_entropy,
5466                                       &server->tkeyctx),
5467                    "creating TKEY context");
5468
5469         /*
5470          * Setup the server task, which is responsible for coordinating
5471          * startup and shutdown of the server, as well as all exclusive
5472          * tasks.
5473          */
5474         CHECKFATAL(isc_task_create(ns_g_taskmgr, 0, &server->task),
5475                    "creating server task");
5476         isc_task_setname(server->task, "server", server);
5477         isc_taskmgr_setexcltask(ns_g_taskmgr, server->task);
5478         CHECKFATAL(isc_task_onshutdown(server->task, shutdown_server, server),
5479                    "isc_task_onshutdown");
5480         CHECKFATAL(isc_app_onrun(ns_g_mctx, server->task, run_server, server),
5481                    "isc_app_onrun");
5482
5483         server->interface_timer = NULL;
5484         server->heartbeat_timer = NULL;
5485         server->pps_timer = NULL;
5486
5487         server->interface_interval = 0;
5488         server->heartbeat_interval = 0;
5489
5490         CHECKFATAL(dns_zonemgr_create(ns_g_mctx, ns_g_taskmgr, ns_g_timermgr,
5491                                       ns_g_socketmgr, &server->zonemgr),
5492                    "dns_zonemgr_create");
5493         CHECKFATAL(dns_zonemgr_setsize(server->zonemgr, 1000),
5494                    "dns_zonemgr_setsize");
5495
5496         server->statsfile = isc_mem_strdup(server->mctx, "named.stats");
5497         CHECKFATAL(server->statsfile == NULL ? ISC_R_NOMEMORY : ISC_R_SUCCESS,
5498                    "isc_mem_strdup");
5499         server->nsstats = NULL;
5500         server->rcvquerystats = NULL;
5501         server->opcodestats = NULL;
5502         server->zonestats = NULL;
5503         server->resolverstats = NULL;
5504         server->sockstats = NULL;
5505         CHECKFATAL(isc_stats_create(server->mctx, &server->sockstats,
5506                                     isc_sockstatscounter_max),
5507                    "isc_stats_create");
5508         isc_socketmgr_setstats(ns_g_socketmgr, server->sockstats);
5509
5510         server->bindkeysfile = isc_mem_strdup(server->mctx, "bind.keys");
5511         CHECKFATAL(server->bindkeysfile == NULL ? ISC_R_NOMEMORY :
5512                                                   ISC_R_SUCCESS,
5513                    "isc_mem_strdup");
5514
5515         server->dumpfile = isc_mem_strdup(server->mctx, "named_dump.db");
5516         CHECKFATAL(server->dumpfile == NULL ? ISC_R_NOMEMORY : ISC_R_SUCCESS,
5517                    "isc_mem_strdup");
5518
5519         server->secrootsfile = isc_mem_strdup(server->mctx, "named.secroots");
5520         CHECKFATAL(server->secrootsfile == NULL ? ISC_R_NOMEMORY :
5521                                                   ISC_R_SUCCESS,
5522                    "isc_mem_strdup");
5523
5524         server->recfile = isc_mem_strdup(server->mctx, "named.recursing");
5525         CHECKFATAL(server->recfile == NULL ? ISC_R_NOMEMORY : ISC_R_SUCCESS,
5526                    "isc_mem_strdup");
5527
5528         server->hostname_set = ISC_FALSE;
5529         server->hostname = NULL;
5530         server->version_set = ISC_FALSE;
5531         server->version = NULL;
5532         server->server_usehostname = ISC_FALSE;
5533         server->server_id = NULL;
5534
5535         CHECKFATAL(isc_stats_create(ns_g_mctx, &server->nsstats,
5536                                     dns_nsstatscounter_max),
5537                    "dns_stats_create (server)");
5538
5539         CHECKFATAL(dns_rdatatypestats_create(ns_g_mctx,
5540                                              &server->rcvquerystats),
5541                    "dns_stats_create (rcvquery)");
5542
5543         CHECKFATAL(dns_opcodestats_create(ns_g_mctx, &server->opcodestats),
5544                    "dns_stats_create (opcode)");
5545
5546         CHECKFATAL(isc_stats_create(ns_g_mctx, &server->zonestats,
5547                                     dns_zonestatscounter_max),
5548                    "dns_stats_create (zone)");
5549
5550         CHECKFATAL(isc_stats_create(ns_g_mctx, &server->resolverstats,
5551                                     dns_resstatscounter_max),
5552                    "dns_stats_create (resolver)");
5553
5554         server->flushonshutdown = ISC_FALSE;
5555         server->log_queries = ISC_FALSE;
5556
5557         server->controls = NULL;
5558         CHECKFATAL(ns_controls_create(server, &server->controls),
5559                    "ns_controls_create");
5560         server->dispatchgen = 0;
5561         ISC_LIST_INIT(server->dispatches);
5562
5563         ISC_LIST_INIT(server->statschannels);
5564
5565         ISC_LIST_INIT(server->cachelist);
5566
5567         server->sessionkey = NULL;
5568         server->session_keyfile = NULL;
5569         server->session_keyname = NULL;
5570         server->session_keyalg = DST_ALG_UNKNOWN;
5571         server->session_keybits = 0;
5572
5573         server->magic = NS_SERVER_MAGIC;
5574         *serverp = server;
5575 }
5576
5577 void
5578 ns_server_destroy(ns_server_t **serverp) {
5579         ns_server_t *server = *serverp;
5580         REQUIRE(NS_SERVER_VALID(server));
5581
5582         ns_controls_destroy(&server->controls);
5583
5584         isc_stats_detach(&server->nsstats);
5585         dns_stats_detach(&server->rcvquerystats);
5586         dns_stats_detach(&server->opcodestats);
5587         isc_stats_detach(&server->zonestats);
5588         isc_stats_detach(&server->resolverstats);
5589         isc_stats_detach(&server->sockstats);
5590
5591         isc_mem_free(server->mctx, server->statsfile);
5592         isc_mem_free(server->mctx, server->bindkeysfile);
5593         isc_mem_free(server->mctx, server->dumpfile);
5594         isc_mem_free(server->mctx, server->secrootsfile);
5595         isc_mem_free(server->mctx, server->recfile);
5596
5597         if (server->version != NULL)
5598                 isc_mem_free(server->mctx, server->version);
5599         if (server->hostname != NULL)
5600                 isc_mem_free(server->mctx, server->hostname);
5601         if (server->server_id != NULL)
5602                 isc_mem_free(server->mctx, server->server_id);
5603
5604         if (server->zonemgr != NULL)
5605                 dns_zonemgr_detach(&server->zonemgr);
5606
5607         if (server->tkeyctx != NULL)
5608                 dns_tkeyctx_destroy(&server->tkeyctx);
5609
5610         dst_lib_destroy();
5611
5612         isc_event_free(&server->reload_event);
5613
5614         INSIST(ISC_LIST_EMPTY(server->viewlist));
5615         INSIST(ISC_LIST_EMPTY(server->cachelist));
5616
5617         dns_aclenv_destroy(&server->aclenv);
5618
5619         isc_quota_destroy(&server->recursionquota);
5620         isc_quota_destroy(&server->tcpquota);
5621         isc_quota_destroy(&server->xfroutquota);
5622
5623         server->magic = 0;
5624         isc_mem_put(server->mctx, server, sizeof(*server));
5625         *serverp = NULL;
5626 }
5627
5628 static void
5629 fatal(const char *msg, isc_result_t result) {
5630         isc_log_write(ns_g_lctx, NS_LOGCATEGORY_GENERAL, NS_LOGMODULE_SERVER,
5631                       ISC_LOG_CRITICAL, "%s: %s", msg,
5632                       isc_result_totext(result));
5633         isc_log_write(ns_g_lctx, NS_LOGCATEGORY_GENERAL, NS_LOGMODULE_SERVER,
5634                       ISC_LOG_CRITICAL, "exiting (due to fatal error)");
5635         exit(1);
5636 }
5637
5638 static void
5639 start_reserved_dispatches(ns_server_t *server) {
5640
5641         REQUIRE(NS_SERVER_VALID(server));
5642
5643         server->dispatchgen++;
5644 }
5645
5646 static void
5647 end_reserved_dispatches(ns_server_t *server, isc_boolean_t all) {
5648         ns_dispatch_t *dispatch, *nextdispatch;
5649
5650         REQUIRE(NS_SERVER_VALID(server));
5651
5652         for (dispatch = ISC_LIST_HEAD(server->dispatches);
5653              dispatch != NULL;
5654              dispatch = nextdispatch) {
5655                 nextdispatch = ISC_LIST_NEXT(dispatch, link);
5656                 if (!all && server->dispatchgen == dispatch-> dispatchgen)
5657                         continue;
5658                 ISC_LIST_UNLINK(server->dispatches, dispatch, link);
5659                 dns_dispatch_detach(&dispatch->dispatch);
5660                 isc_mem_put(server->mctx, dispatch, sizeof(*dispatch));
5661         }
5662 }
5663
5664 void
5665 ns_add_reserved_dispatch(ns_server_t *server, const isc_sockaddr_t *addr) {
5666         ns_dispatch_t *dispatch;
5667         in_port_t port;
5668         char addrbuf[ISC_SOCKADDR_FORMATSIZE];
5669         isc_result_t result;
5670         unsigned int attrs, attrmask;
5671
5672         REQUIRE(NS_SERVER_VALID(server));
5673
5674         port = isc_sockaddr_getport(addr);
5675         if (port == 0 || port >= 1024)
5676                 return;
5677
5678         for (dispatch = ISC_LIST_HEAD(server->dispatches);
5679              dispatch != NULL;
5680              dispatch = ISC_LIST_NEXT(dispatch, link)) {
5681                 if (isc_sockaddr_equal(&dispatch->addr, addr))
5682                         break;
5683         }
5684         if (dispatch != NULL) {
5685                 dispatch->dispatchgen = server->dispatchgen;
5686                 return;
5687         }
5688
5689         dispatch = isc_mem_get(server->mctx, sizeof(*dispatch));
5690         if (dispatch == NULL) {
5691                 result = ISC_R_NOMEMORY;
5692                 goto cleanup;
5693         }
5694
5695         dispatch->addr = *addr;
5696         dispatch->dispatchgen = server->dispatchgen;
5697         dispatch->dispatch = NULL;
5698
5699         attrs = 0;
5700         attrs |= DNS_DISPATCHATTR_UDP;
5701         switch (isc_sockaddr_pf(addr)) {
5702         case AF_INET:
5703                 attrs |= DNS_DISPATCHATTR_IPV4;
5704                 break;
5705         case AF_INET6:
5706                 attrs |= DNS_DISPATCHATTR_IPV6;
5707                 break;
5708         default:
5709                 result = ISC_R_NOTIMPLEMENTED;
5710                 goto cleanup;
5711         }
5712         attrmask = 0;
5713         attrmask |= DNS_DISPATCHATTR_UDP;
5714         attrmask |= DNS_DISPATCHATTR_TCP;
5715         attrmask |= DNS_DISPATCHATTR_IPV4;
5716         attrmask |= DNS_DISPATCHATTR_IPV6;
5717
5718         result = dns_dispatch_getudp(ns_g_dispatchmgr, ns_g_socketmgr,
5719                                      ns_g_taskmgr, &dispatch->addr, 4096,
5720                                      1000, 32768, 16411, 16433,
5721                                      attrs, attrmask, &dispatch->dispatch);
5722         if (result != ISC_R_SUCCESS)
5723                 goto cleanup;
5724
5725         ISC_LIST_INITANDPREPEND(server->dispatches, dispatch, link);
5726
5727         return;
5728
5729  cleanup:
5730         if (dispatch != NULL)
5731                 isc_mem_put(server->mctx, dispatch, sizeof(*dispatch));
5732         isc_sockaddr_format(addr, addrbuf, sizeof(addrbuf));
5733         isc_log_write(ns_g_lctx, NS_LOGCATEGORY_GENERAL,
5734                       NS_LOGMODULE_SERVER, ISC_LOG_WARNING,
5735                       "unable to create dispatch for reserved port %s: %s",
5736                       addrbuf, isc_result_totext(result));
5737 }
5738
5739
5740 static isc_result_t
5741 loadconfig(ns_server_t *server) {
5742         isc_result_t result;
5743         start_reserved_dispatches(server);
5744         result = load_configuration(ns_g_lwresdonly ?
5745                                     lwresd_g_conffile : ns_g_conffile,
5746                                     server, ISC_FALSE);
5747         if (result == ISC_R_SUCCESS) {
5748                 end_reserved_dispatches(server, ISC_FALSE);
5749                 isc_log_write(ns_g_lctx, NS_LOGCATEGORY_GENERAL,
5750                               NS_LOGMODULE_SERVER, ISC_LOG_INFO,
5751                               "reloading configuration succeeded");
5752         } else {
5753                 isc_log_write(ns_g_lctx, NS_LOGCATEGORY_GENERAL,
5754                               NS_LOGMODULE_SERVER, ISC_LOG_ERROR,
5755                               "reloading configuration failed: %s",
5756                               isc_result_totext(result));
5757         }
5758         return (result);
5759 }
5760
5761 static isc_result_t
5762 reload(ns_server_t *server) {
5763         isc_result_t result;
5764         CHECK(loadconfig(server));
5765
5766         result = load_zones(server, ISC_FALSE);
5767         if (result == ISC_R_SUCCESS)
5768                 isc_log_write(ns_g_lctx, NS_LOGCATEGORY_GENERAL,
5769                               NS_LOGMODULE_SERVER, ISC_LOG_INFO,
5770                               "reloading zones succeeded");
5771         else
5772                 isc_log_write(ns_g_lctx, NS_LOGCATEGORY_GENERAL,
5773                               NS_LOGMODULE_SERVER, ISC_LOG_ERROR,
5774                               "reloading zones failed: %s",
5775                               isc_result_totext(result));
5776
5777  cleanup:
5778         return (result);
5779 }
5780
5781 static void
5782 reconfig(ns_server_t *server) {
5783         isc_result_t result;
5784         CHECK(loadconfig(server));
5785
5786         result = load_new_zones(server, ISC_FALSE);
5787         if (result == ISC_R_SUCCESS)
5788                 isc_log_write(ns_g_lctx, NS_LOGCATEGORY_GENERAL,
5789                               NS_LOGMODULE_SERVER, ISC_LOG_INFO,
5790                               "any newly configured zones are now loaded");
5791         else
5792                 isc_log_write(ns_g_lctx, NS_LOGCATEGORY_GENERAL,
5793                               NS_LOGMODULE_SERVER, ISC_LOG_ERROR,
5794                               "loading new zones failed: %s",
5795                               isc_result_totext(result));
5796
5797  cleanup: ;
5798 }
5799
5800 /*
5801  * Handle a reload event (from SIGHUP).
5802  */
5803 static void
5804 ns_server_reload(isc_task_t *task, isc_event_t *event) {
5805         ns_server_t *server = (ns_server_t *)event->ev_arg;
5806
5807         INSIST(task = server->task);
5808         UNUSED(task);
5809
5810         isc_log_write(ns_g_lctx, NS_LOGCATEGORY_GENERAL,
5811                       NS_LOGMODULE_SERVER, ISC_LOG_INFO,
5812                       "received SIGHUP signal to reload zones");
5813         (void)reload(server);
5814
5815         LOCK(&server->reload_event_lock);
5816         INSIST(server->reload_event == NULL);
5817         server->reload_event = event;
5818         UNLOCK(&server->reload_event_lock);
5819 }
5820
5821 void
5822 ns_server_reloadwanted(ns_server_t *server) {
5823         LOCK(&server->reload_event_lock);
5824         if (server->reload_event != NULL)
5825                 isc_task_send(server->task, &server->reload_event);
5826         UNLOCK(&server->reload_event_lock);
5827 }
5828
5829 static char *
5830 next_token(char **stringp, const char *delim) {
5831         char *res;
5832
5833         do {
5834                 res = strsep(stringp, delim);
5835                 if (res == NULL)
5836                         break;
5837         } while (*res == '\0');
5838         return (res);
5839 }
5840
5841 /*
5842  * Find the zone specified in the control channel command 'args',
5843  * if any.  If a zone is specified, point '*zonep' at it, otherwise
5844  * set '*zonep' to NULL.
5845  */
5846 static isc_result_t
5847 zone_from_args(ns_server_t *server, char *args, dns_zone_t **zonep,
5848                const char **zonename)
5849 {
5850         char *input, *ptr;
5851         const char *zonetxt;
5852         char *classtxt;
5853         const char *viewtxt = NULL;
5854         dns_fixedname_t name;
5855         isc_result_t result;
5856         isc_buffer_t buf;
5857         dns_view_t *view = NULL;
5858         dns_rdataclass_t rdclass;
5859
5860         REQUIRE(zonep != NULL && *zonep == NULL);
5861
5862         input = args;
5863
5864         /* Skip the command name. */
5865         ptr = next_token(&input, " \t");
5866         if (ptr == NULL)
5867                 return (ISC_R_UNEXPECTEDEND);
5868
5869         /* Look for the zone name. */
5870         zonetxt = next_token(&input, " \t");
5871         if (zonetxt == NULL)
5872                 return (ISC_R_SUCCESS);
5873         if (zonename)
5874                 *zonename = zonetxt;
5875
5876         /* Look for the optional class name. */
5877         classtxt = next_token(&input, " \t");
5878         if (classtxt != NULL) {
5879                 /* Look for the optional view name. */
5880                 viewtxt = next_token(&input, " \t");
5881         }
5882
5883         isc_buffer_init(&buf, zonetxt, strlen(zonetxt));
5884         isc_buffer_add(&buf, strlen(zonetxt));
5885         dns_fixedname_init(&name);
5886         result = dns_name_fromtext(dns_fixedname_name(&name),
5887                                    &buf, dns_rootname, 0, NULL);
5888         if (result != ISC_R_SUCCESS)
5889                 goto fail1;
5890
5891         if (classtxt != NULL) {
5892                 isc_textregion_t r;
5893                 r.base = classtxt;
5894                 r.length = strlen(classtxt);
5895                 result = dns_rdataclass_fromtext(&rdclass, &r);
5896                 if (result != ISC_R_SUCCESS)
5897                         goto fail1;
5898         } else
5899                 rdclass = dns_rdataclass_in;
5900
5901         if (viewtxt == NULL) {
5902                 result = dns_viewlist_findzone(&server->viewlist,
5903                                                dns_fixedname_name(&name),
5904                                                ISC_TF(classtxt == NULL),
5905                                                rdclass, zonep);
5906         } else {
5907                 result = dns_viewlist_find(&server->viewlist, viewtxt,
5908                                            rdclass, &view);
5909                 if (result != ISC_R_SUCCESS)
5910                         goto fail1;
5911
5912                 result = dns_zt_find(view->zonetable, dns_fixedname_name(&name),
5913                                      0, NULL, zonep);
5914                 dns_view_detach(&view);
5915         }
5916
5917         /* Partial match? */
5918         if (result != ISC_R_SUCCESS && *zonep != NULL)
5919                 dns_zone_detach(zonep);
5920         if (result == DNS_R_PARTIALMATCH)
5921                 result = ISC_R_NOTFOUND;
5922  fail1:
5923         return (result);
5924 }
5925
5926 /*
5927  * Act on a "retransfer" command from the command channel.
5928  */
5929 isc_result_t
5930 ns_server_retransfercommand(ns_server_t *server, char *args) {
5931         isc_result_t result;
5932         dns_zone_t *zone = NULL;
5933         dns_zonetype_t type;
5934
5935         result = zone_from_args(server, args, &zone, NULL);
5936         if (result != ISC_R_SUCCESS)
5937                 return (result);
5938         if (zone == NULL)
5939                 return (ISC_R_UNEXPECTEDEND);
5940         type = dns_zone_gettype(zone);
5941         if (type == dns_zone_slave || type == dns_zone_stub)
5942                 dns_zone_forcereload(zone);
5943         else
5944                 result = ISC_R_NOTFOUND;
5945         dns_zone_detach(&zone);
5946         return (result);
5947 }
5948
5949 /*
5950  * Act on a "reload" command from the command channel.
5951  */
5952 isc_result_t
5953 ns_server_reloadcommand(ns_server_t *server, char *args, isc_buffer_t *text) {
5954         isc_result_t result;
5955         dns_zone_t *zone = NULL;
5956         dns_zonetype_t type;
5957         const char *msg = NULL;
5958
5959         result = zone_from_args(server, args, &zone, NULL);
5960         if (result != ISC_R_SUCCESS)
5961                 return (result);
5962         if (zone == NULL) {
5963                 result = reload(server);
5964                 if (result == ISC_R_SUCCESS)
5965                         msg = "server reload successful";
5966         } else {
5967                 type = dns_zone_gettype(zone);
5968                 if (type == dns_zone_slave || type == dns_zone_stub) {
5969                         dns_zone_refresh(zone);
5970                         dns_zone_detach(&zone);
5971                         msg = "zone refresh queued";
5972                 } else {
5973                         result = dns_zone_load(zone);
5974                         dns_zone_detach(&zone);
5975                         switch (result) {
5976                         case ISC_R_SUCCESS:
5977                                  msg = "zone reload successful";
5978                                  break;
5979                         case DNS_R_CONTINUE:
5980                                 msg = "zone reload queued";
5981                                 result = ISC_R_SUCCESS;
5982                                 break;
5983                         case DNS_R_UPTODATE:
5984                                 msg = "zone reload up-to-date";
5985                                 result = ISC_R_SUCCESS;
5986                                 break;
5987                         default:
5988                                 /* failure message will be generated by rndc */
5989                                 break;
5990                         }
5991                 }
5992         }
5993         if (msg != NULL && strlen(msg) < isc_buffer_availablelength(text))
5994                 isc_buffer_putmem(text, (const unsigned char *)msg,
5995                                   strlen(msg) + 1);
5996         return (result);
5997 }
5998
5999 /*
6000  * Act on a "reconfig" command from the command channel.
6001  */
6002 isc_result_t
6003 ns_server_reconfigcommand(ns_server_t *server, char *args) {
6004         UNUSED(args);
6005
6006         reconfig(server);
6007         return (ISC_R_SUCCESS);
6008 }
6009
6010 /*
6011  * Act on a "notify" command from the command channel.
6012  */
6013 isc_result_t
6014 ns_server_notifycommand(ns_server_t *server, char *args, isc_buffer_t *text) {
6015         isc_result_t result;
6016         dns_zone_t *zone = NULL;
6017         const unsigned char msg[] = "zone notify queued";
6018
6019         result = zone_from_args(server, args, &zone, NULL);
6020         if (result != ISC_R_SUCCESS)
6021                 return (result);
6022         if (zone == NULL)
6023                 return (ISC_R_UNEXPECTEDEND);
6024
6025         dns_zone_notify(zone);
6026         dns_zone_detach(&zone);
6027         if (sizeof(msg) <= isc_buffer_availablelength(text))
6028                 isc_buffer_putmem(text, msg, sizeof(msg));
6029
6030         return (ISC_R_SUCCESS);
6031 }
6032
6033 /*
6034  * Act on a "refresh" command from the command channel.
6035  */
6036 isc_result_t
6037 ns_server_refreshcommand(ns_server_t *server, char *args, isc_buffer_t *text) {
6038         isc_result_t result;
6039         dns_zone_t *zone = NULL;
6040         const unsigned char msg1[] = "zone refresh queued";
6041         const unsigned char msg2[] = "not a slave or stub zone";
6042         dns_zonetype_t type;
6043
6044         result = zone_from_args(server, args, &zone, NULL);
6045         if (result != ISC_R_SUCCESS)
6046                 return (result);
6047         if (zone == NULL)
6048                 return (ISC_R_UNEXPECTEDEND);
6049
6050         type = dns_zone_gettype(zone);
6051         if (type == dns_zone_slave || type == dns_zone_stub) {
6052                 dns_zone_refresh(zone);
6053                 dns_zone_detach(&zone);
6054                 if (sizeof(msg1) <= isc_buffer_availablelength(text))
6055                         isc_buffer_putmem(text, msg1, sizeof(msg1));
6056                 return (ISC_R_SUCCESS);
6057         }
6058
6059         dns_zone_detach(&zone);
6060         if (sizeof(msg2) <= isc_buffer_availablelength(text))
6061                 isc_buffer_putmem(text, msg2, sizeof(msg2));
6062         return (ISC_R_FAILURE);
6063 }
6064
6065 isc_result_t
6066 ns_server_togglequerylog(ns_server_t *server) {
6067         server->log_queries = server->log_queries ? ISC_FALSE : ISC_TRUE;
6068
6069         isc_log_write(ns_g_lctx, NS_LOGCATEGORY_GENERAL,
6070                       NS_LOGMODULE_SERVER, ISC_LOG_INFO,
6071                       "query logging is now %s",
6072                       server->log_queries ? "on" : "off");
6073         return (ISC_R_SUCCESS);
6074 }
6075
6076 static isc_result_t
6077 ns_listenlist_fromconfig(const cfg_obj_t *listenlist, const cfg_obj_t *config,
6078                          cfg_aclconfctx_t *actx,
6079                          isc_mem_t *mctx, ns_listenlist_t **target)
6080 {
6081         isc_result_t result;
6082         const cfg_listelt_t *element;
6083         ns_listenlist_t *dlist = NULL;
6084
6085         REQUIRE(target != NULL && *target == NULL);
6086
6087         result = ns_listenlist_create(mctx, &dlist);
6088         if (result != ISC_R_SUCCESS)
6089                 return (result);
6090
6091         for (element = cfg_list_first(listenlist);
6092              element != NULL;
6093              element = cfg_list_next(element))
6094         {
6095                 ns_listenelt_t *delt = NULL;
6096                 const cfg_obj_t *listener = cfg_listelt_value(element);
6097                 result = ns_listenelt_fromconfig(listener, config, actx,
6098                                                  mctx, &delt);
6099                 if (result != ISC_R_SUCCESS)
6100                         goto cleanup;
6101                 ISC_LIST_APPEND(dlist->elts, delt, link);
6102         }
6103         *target = dlist;
6104         return (ISC_R_SUCCESS);
6105
6106  cleanup:
6107         ns_listenlist_detach(&dlist);
6108         return (result);
6109 }
6110
6111 /*
6112  * Create a listen list from the corresponding configuration
6113  * data structure.
6114  */
6115 static isc_result_t
6116 ns_listenelt_fromconfig(const cfg_obj_t *listener, const cfg_obj_t *config,
6117                         cfg_aclconfctx_t *actx,
6118                         isc_mem_t *mctx, ns_listenelt_t **target)
6119 {
6120         isc_result_t result;
6121         const cfg_obj_t *portobj;
6122         in_port_t port;
6123         ns_listenelt_t *delt = NULL;
6124         REQUIRE(target != NULL && *target == NULL);
6125
6126         portobj = cfg_tuple_get(listener, "port");
6127         if (!cfg_obj_isuint32(portobj)) {
6128                 if (ns_g_port != 0) {
6129                         port = ns_g_port;
6130                 } else {
6131                         result = ns_config_getport(config, &port);
6132                         if (result != ISC_R_SUCCESS)
6133                                 return (result);
6134                 }
6135         } else {
6136                 if (cfg_obj_asuint32(portobj) >= ISC_UINT16_MAX) {
6137                         cfg_obj_log(portobj, ns_g_lctx, ISC_LOG_ERROR,
6138                                     "port value '%u' is out of range",
6139                                     cfg_obj_asuint32(portobj));
6140                         return (ISC_R_RANGE);
6141                 }
6142                 port = (in_port_t)cfg_obj_asuint32(portobj);
6143         }
6144
6145         result = ns_listenelt_create(mctx, port, NULL, &delt);
6146         if (result != ISC_R_SUCCESS)
6147                 return (result);
6148
6149         result = cfg_acl_fromconfig(cfg_tuple_get(listener, "acl"),
6150                                    config, ns_g_lctx, actx, mctx, 0,
6151                                    &delt->acl);
6152         if (result != ISC_R_SUCCESS) {
6153                 ns_listenelt_destroy(delt);
6154                 return (result);
6155         }
6156         *target = delt;
6157         return (ISC_R_SUCCESS);
6158 }
6159
6160 isc_result_t
6161 ns_server_dumpstats(ns_server_t *server) {
6162         isc_result_t result;
6163         FILE *fp = NULL;
6164
6165         CHECKMF(isc_stdio_open(server->statsfile, "a", &fp),
6166                 "could not open statistics dump file", server->statsfile);
6167
6168         result = ns_stats_dump(server, fp);
6169
6170  cleanup:
6171         if (fp != NULL)
6172                 (void)isc_stdio_close(fp);
6173         if (result == ISC_R_SUCCESS)
6174                 isc_log_write(ns_g_lctx, NS_LOGCATEGORY_GENERAL,
6175                               NS_LOGMODULE_SERVER, ISC_LOG_INFO,
6176                               "dumpstats complete");
6177         else
6178                 isc_log_write(ns_g_lctx, NS_LOGCATEGORY_GENERAL,
6179                               NS_LOGMODULE_SERVER, ISC_LOG_ERROR,
6180                               "dumpstats failed: %s",
6181                               dns_result_totext(result));
6182         return (result);
6183 }
6184
6185 static isc_result_t
6186 add_zone_tolist(dns_zone_t *zone, void *uap) {
6187         struct dumpcontext *dctx = uap;
6188         struct zonelistentry *zle;
6189
6190         zle = isc_mem_get(dctx->mctx, sizeof *zle);
6191         if (zle ==  NULL)
6192                 return (ISC_R_NOMEMORY);
6193         zle->zone = NULL;
6194         dns_zone_attach(zone, &zle->zone);
6195         ISC_LINK_INIT(zle, link);
6196         ISC_LIST_APPEND(ISC_LIST_TAIL(dctx->viewlist)->zonelist, zle, link);
6197         return (ISC_R_SUCCESS);
6198 }
6199
6200 static isc_result_t
6201 add_view_tolist(struct dumpcontext *dctx, dns_view_t *view) {
6202         struct viewlistentry *vle;
6203         isc_result_t result = ISC_R_SUCCESS;
6204
6205         /*
6206          * Prevent duplicate views.
6207          */
6208         for (vle = ISC_LIST_HEAD(dctx->viewlist);
6209              vle != NULL;
6210              vle = ISC_LIST_NEXT(vle, link))
6211                 if (vle->view == view)
6212                         return (ISC_R_SUCCESS);
6213
6214         vle = isc_mem_get(dctx->mctx, sizeof *vle);
6215         if (vle == NULL)
6216                 return (ISC_R_NOMEMORY);
6217         vle->view = NULL;
6218         dns_view_attach(view, &vle->view);
6219         ISC_LINK_INIT(vle, link);
6220         ISC_LIST_INIT(vle->zonelist);
6221         ISC_LIST_APPEND(dctx->viewlist, vle, link);
6222         if (dctx->dumpzones)
6223                 result = dns_zt_apply(view->zonetable, ISC_TRUE,
6224                                       add_zone_tolist, dctx);
6225         return (result);
6226 }
6227
6228 static void
6229 dumpcontext_destroy(struct dumpcontext *dctx) {
6230         struct viewlistentry *vle;
6231         struct zonelistentry *zle;
6232
6233         vle = ISC_LIST_HEAD(dctx->viewlist);
6234         while (vle != NULL) {
6235                 ISC_LIST_UNLINK(dctx->viewlist, vle, link);
6236                 zle = ISC_LIST_HEAD(vle->zonelist);
6237                 while (zle != NULL) {
6238                         ISC_LIST_UNLINK(vle->zonelist, zle, link);
6239                         dns_zone_detach(&zle->zone);
6240                         isc_mem_put(dctx->mctx, zle, sizeof *zle);
6241                         zle = ISC_LIST_HEAD(vle->zonelist);
6242                 }
6243                 dns_view_detach(&vle->view);
6244                 isc_mem_put(dctx->mctx, vle, sizeof *vle);
6245                 vle = ISC_LIST_HEAD(dctx->viewlist);
6246         }
6247         if (dctx->version != NULL)
6248                 dns_db_closeversion(dctx->db, &dctx->version, ISC_FALSE);
6249         if (dctx->db != NULL)
6250                 dns_db_detach(&dctx->db);
6251         if (dctx->cache != NULL)
6252                 dns_db_detach(&dctx->cache);
6253         if (dctx->task != NULL)
6254                 isc_task_detach(&dctx->task);
6255         if (dctx->fp != NULL)
6256                 (void)isc_stdio_close(dctx->fp);
6257         if (dctx->mdctx != NULL)
6258                 dns_dumpctx_detach(&dctx->mdctx);
6259         isc_mem_put(dctx->mctx, dctx, sizeof *dctx);
6260 }
6261
6262 static void
6263 dumpdone(void *arg, isc_result_t result) {
6264         struct dumpcontext *dctx = arg;
6265         char buf[1024+32];
6266         const dns_master_style_t *style;
6267
6268         if (result != ISC_R_SUCCESS)
6269                 goto cleanup;
6270         if (dctx->mdctx != NULL)
6271                 dns_dumpctx_detach(&dctx->mdctx);
6272         if (dctx->view == NULL) {
6273                 dctx->view = ISC_LIST_HEAD(dctx->viewlist);
6274                 if (dctx->view == NULL)
6275                         goto done;
6276                 INSIST(dctx->zone == NULL);
6277         } else
6278                 goto resume;
6279  nextview:
6280         fprintf(dctx->fp, ";\n; Start view %s\n;\n", dctx->view->view->name);
6281  resume:
6282         if (dctx->dumpcache && dns_view_iscacheshared(dctx->view->view)) {
6283                 fprintf(dctx->fp,
6284                         ";\n; Cache of view '%s' is shared as '%s'\n",
6285                         dctx->view->view->name,
6286                         dns_cache_getname(dctx->view->view->cache));
6287         } else if (dctx->zone == NULL && dctx->cache == NULL &&
6288                    dctx->dumpcache)
6289         {
6290                 style = &dns_master_style_cache;
6291                 /* start cache dump */
6292                 if (dctx->view->view->cachedb != NULL)
6293                         dns_db_attach(dctx->view->view->cachedb, &dctx->cache);
6294                 if (dctx->cache != NULL) {
6295                         fprintf(dctx->fp,
6296                                 ";\n; Cache dump of view '%s' (cache %s)\n;\n",
6297                                 dctx->view->view->name,
6298                                 dns_cache_getname(dctx->view->view->cache));
6299                         result = dns_master_dumptostreaminc(dctx->mctx,
6300                                                             dctx->cache, NULL,
6301                                                             style, dctx->fp,
6302                                                             dctx->task,
6303                                                             dumpdone, dctx,
6304                                                             &dctx->mdctx);
6305                         if (result == DNS_R_CONTINUE)
6306                                 return;
6307                         if (result == ISC_R_NOTIMPLEMENTED)
6308                                 fprintf(dctx->fp, "; %s\n",
6309                                         dns_result_totext(result));
6310                         else if (result != ISC_R_SUCCESS)
6311                                 goto cleanup;
6312                 }
6313         }
6314         if (dctx->cache != NULL) {
6315                 dns_adb_dump(dctx->view->view->adb, dctx->fp);
6316                 dns_resolver_printbadcache(dctx->view->view->resolver,
6317                                            dctx->fp);
6318                 dns_db_detach(&dctx->cache);
6319         }
6320         if (dctx->dumpzones) {
6321                 style = &dns_master_style_full;
6322  nextzone:
6323                 if (dctx->version != NULL)
6324                         dns_db_closeversion(dctx->db, &dctx->version,
6325                                             ISC_FALSE);
6326                 if (dctx->db != NULL)
6327                         dns_db_detach(&dctx->db);
6328                 if (dctx->zone == NULL)
6329                         dctx->zone = ISC_LIST_HEAD(dctx->view->zonelist);
6330                 else
6331                         dctx->zone = ISC_LIST_NEXT(dctx->zone, link);
6332                 if (dctx->zone != NULL) {
6333                         /* start zone dump */
6334                         dns_zone_name(dctx->zone->zone, buf, sizeof(buf));
6335                         fprintf(dctx->fp, ";\n; Zone dump of '%s'\n;\n", buf);
6336                         result = dns_zone_getdb(dctx->zone->zone, &dctx->db);
6337                         if (result != ISC_R_SUCCESS) {
6338                                 fprintf(dctx->fp, "; %s\n",
6339                                         dns_result_totext(result));
6340                                 goto nextzone;
6341                         }
6342                         dns_db_currentversion(dctx->db, &dctx->version);
6343                         result = dns_master_dumptostreaminc(dctx->mctx,
6344                                                             dctx->db,
6345                                                             dctx->version,
6346                                                             style, dctx->fp,
6347                                                             dctx->task,
6348                                                             dumpdone, dctx,
6349                                                             &dctx->mdctx);
6350                         if (result == DNS_R_CONTINUE)
6351                                 return;
6352                         if (result == ISC_R_NOTIMPLEMENTED) {
6353                                 fprintf(dctx->fp, "; %s\n",
6354                                         dns_result_totext(result));
6355                                 result = ISC_R_SUCCESS;
6356                                 POST(result);
6357                                 goto nextzone;
6358                         }
6359                         if (result != ISC_R_SUCCESS)
6360                                 goto cleanup;
6361                 }
6362         }
6363         if (dctx->view != NULL)
6364                 dctx->view = ISC_LIST_NEXT(dctx->view, link);
6365         if (dctx->view != NULL)
6366                 goto nextview;
6367  done:
6368         fprintf(dctx->fp, "; Dump complete\n");
6369         result = isc_stdio_flush(dctx->fp);
6370         if (result == ISC_R_SUCCESS)
6371                 isc_log_write(ns_g_lctx, NS_LOGCATEGORY_GENERAL,
6372                               NS_LOGMODULE_SERVER, ISC_LOG_INFO,
6373                               "dumpdb complete");
6374  cleanup:
6375         if (result != ISC_R_SUCCESS)
6376                 isc_log_write(ns_g_lctx, NS_LOGCATEGORY_GENERAL,
6377                               NS_LOGMODULE_SERVER, ISC_LOG_ERROR,
6378                               "dumpdb failed: %s", dns_result_totext(result));
6379         dumpcontext_destroy(dctx);
6380 }
6381
6382 isc_result_t
6383 ns_server_dumpdb(ns_server_t *server, char *args) {
6384         struct dumpcontext *dctx = NULL;
6385         dns_view_t *view;
6386         isc_result_t result;
6387         char *ptr;
6388         const char *sep;
6389
6390         /* Skip the command name. */
6391         ptr = next_token(&args, " \t");
6392         if (ptr == NULL)
6393                 return (ISC_R_UNEXPECTEDEND);
6394
6395         dctx = isc_mem_get(server->mctx, sizeof(*dctx));
6396         if (dctx == NULL)
6397                 return (ISC_R_NOMEMORY);
6398
6399         dctx->mctx = server->mctx;
6400         dctx->dumpcache = ISC_TRUE;
6401         dctx->dumpzones = ISC_FALSE;
6402         dctx->fp = NULL;
6403         ISC_LIST_INIT(dctx->viewlist);
6404         dctx->view = NULL;
6405         dctx->zone = NULL;
6406         dctx->cache = NULL;
6407         dctx->mdctx = NULL;
6408         dctx->db = NULL;
6409         dctx->cache = NULL;
6410         dctx->task = NULL;
6411         dctx->version = NULL;
6412         isc_task_attach(server->task, &dctx->task);
6413
6414         CHECKMF(isc_stdio_open(server->dumpfile, "w", &dctx->fp),
6415                 "could not open dump file", server->dumpfile);
6416
6417         sep = (args == NULL) ? "" : ": ";
6418         isc_log_write(ns_g_lctx, NS_LOGCATEGORY_GENERAL,
6419                       NS_LOGMODULE_SERVER, ISC_LOG_INFO,
6420                       "dumpdb started%s%s", sep, (args != NULL) ? args : "");
6421
6422         ptr = next_token(&args, " \t");
6423         if (ptr != NULL && strcmp(ptr, "-all") == 0) {
6424                 dctx->dumpzones = ISC_TRUE;
6425                 dctx->dumpcache = ISC_TRUE;
6426                 ptr = next_token(&args, " \t");
6427         } else if (ptr != NULL && strcmp(ptr, "-cache") == 0) {
6428                 dctx->dumpzones = ISC_FALSE;
6429                 dctx->dumpcache = ISC_TRUE;
6430                 ptr = next_token(&args, " \t");
6431         } else if (ptr != NULL && strcmp(ptr, "-zones") == 0) {
6432                 dctx->dumpzones = ISC_TRUE;
6433                 dctx->dumpcache = ISC_FALSE;
6434                 ptr = next_token(&args, " \t");
6435         }
6436
6437  nextview:
6438         for (view = ISC_LIST_HEAD(server->viewlist);
6439              view != NULL;
6440              view = ISC_LIST_NEXT(view, link))
6441         {
6442                 if (ptr != NULL && strcmp(view->name, ptr) != 0)
6443                         continue;
6444                 CHECK(add_view_tolist(dctx, view));
6445         }
6446         if (ptr != NULL) {
6447                 ptr = next_token(&args, " \t");
6448                 if (ptr != NULL)
6449                         goto nextview;
6450         }
6451         dumpdone(dctx, ISC_R_SUCCESS);
6452         return (ISC_R_SUCCESS);
6453
6454  cleanup:
6455         if (dctx != NULL)
6456                 dumpcontext_destroy(dctx);
6457         return (result);
6458 }
6459
6460 isc_result_t
6461 ns_server_dumpsecroots(ns_server_t *server, char *args) {
6462         dns_view_t *view;
6463         dns_keytable_t *secroots = NULL;
6464         isc_result_t result;
6465         char *ptr;
6466         FILE *fp = NULL;
6467         isc_time_t now;
6468         char tbuf[64];
6469
6470         /* Skip the command name. */
6471         ptr = next_token(&args, " \t");
6472         if (ptr == NULL)
6473                 return (ISC_R_UNEXPECTEDEND);
6474         ptr = next_token(&args, " \t");
6475
6476         CHECKMF(isc_stdio_open(server->secrootsfile, "w", &fp),
6477                 "could not open secroots dump file", server->secrootsfile);
6478         TIME_NOW(&now);
6479         isc_time_formattimestamp(&now, tbuf, sizeof(tbuf));
6480         fprintf(fp, "%s\n", tbuf);
6481
6482         do {
6483                 for (view = ISC_LIST_HEAD(server->viewlist);
6484                      view != NULL;
6485                      view = ISC_LIST_NEXT(view, link))
6486                 {
6487                         if (ptr != NULL && strcmp(view->name, ptr) != 0)
6488                                 continue;
6489                         if (secroots != NULL)
6490                                 dns_keytable_detach(&secroots);
6491                         result = dns_view_getsecroots(view, &secroots);
6492                         if (result == ISC_R_NOTFOUND) {
6493                                 result = ISC_R_SUCCESS;
6494                                 continue;
6495                         }
6496                         fprintf(fp, "\n Start view %s\n\n", view->name);
6497                         result = dns_keytable_dump(secroots, fp);
6498                         if (result != ISC_R_SUCCESS)
6499                                 fprintf(fp, " dumpsecroots failed: %s\n",
6500                                         isc_result_totext(result));
6501                 }
6502                 if (ptr != NULL)
6503                         ptr = next_token(&args, " \t");
6504         } while (ptr != NULL);
6505
6506  cleanup:
6507         if (secroots != NULL)
6508                 dns_keytable_detach(&secroots);
6509         if (fp != NULL)
6510                 (void)isc_stdio_close(fp);
6511         if (result == ISC_R_SUCCESS)
6512                 isc_log_write(ns_g_lctx, NS_LOGCATEGORY_GENERAL,
6513                               NS_LOGMODULE_SERVER, ISC_LOG_INFO,
6514                               "dumpsecroots complete");
6515         else
6516                 isc_log_write(ns_g_lctx, NS_LOGCATEGORY_GENERAL,
6517                               NS_LOGMODULE_SERVER, ISC_LOG_ERROR,
6518                               "dumpsecroots failed: %s",
6519                               dns_result_totext(result));
6520         return (result);
6521 }
6522
6523 isc_result_t
6524 ns_server_dumprecursing(ns_server_t *server) {
6525         FILE *fp = NULL;
6526         isc_result_t result;
6527
6528         CHECKMF(isc_stdio_open(server->recfile, "w", &fp),
6529                 "could not open dump file", server->recfile);
6530         fprintf(fp,";\n; Recursing Queries\n;\n");
6531         ns_interfacemgr_dumprecursing(fp, server->interfacemgr);
6532         fprintf(fp, "; Dump complete\n");
6533
6534  cleanup:
6535         if (fp != NULL)
6536                 result = isc_stdio_close(fp);
6537         if (result == ISC_R_SUCCESS)
6538                 isc_log_write(ns_g_lctx, NS_LOGCATEGORY_GENERAL,
6539                               NS_LOGMODULE_SERVER, ISC_LOG_INFO,
6540                               "dumprecursing complete");
6541         else
6542                 isc_log_write(ns_g_lctx, NS_LOGCATEGORY_GENERAL,
6543                               NS_LOGMODULE_SERVER, ISC_LOG_ERROR,
6544                               "dumprecursing failed: %s",
6545                               dns_result_totext(result));
6546         return (result);
6547 }
6548
6549 isc_result_t
6550 ns_server_setdebuglevel(ns_server_t *server, char *args) {
6551         char *ptr;
6552         char *levelstr;
6553         char *endp;
6554         long newlevel;
6555
6556         UNUSED(server);
6557
6558         /* Skip the command name. */
6559         ptr = next_token(&args, " \t");
6560         if (ptr == NULL)
6561                 return (ISC_R_UNEXPECTEDEND);
6562
6563         /* Look for the new level name. */
6564         levelstr = next_token(&args, " \t");
6565         if (levelstr == NULL) {
6566                 if (ns_g_debuglevel < 99)
6567                         ns_g_debuglevel++;
6568         } else {
6569                 newlevel = strtol(levelstr, &endp, 10);
6570                 if (*endp != '\0' || newlevel < 0 || newlevel > 99)
6571                         return (ISC_R_RANGE);
6572                 ns_g_debuglevel = (unsigned int)newlevel;
6573         }
6574         isc_log_setdebuglevel(ns_g_lctx, ns_g_debuglevel);
6575         isc_log_write(ns_g_lctx, NS_LOGCATEGORY_GENERAL,
6576                       NS_LOGMODULE_SERVER, ISC_LOG_INFO,
6577                       "debug level is now %d", ns_g_debuglevel);
6578         return (ISC_R_SUCCESS);
6579 }
6580
6581 isc_result_t
6582 ns_server_validation(ns_server_t *server, char *args) {
6583         char *ptr, *viewname;
6584         dns_view_t *view;
6585         isc_boolean_t changed = ISC_FALSE;
6586         isc_result_t result;
6587         isc_boolean_t enable;
6588
6589         /* Skip the command name. */
6590         ptr = next_token(&args, " \t");
6591         if (ptr == NULL)
6592                 return (ISC_R_UNEXPECTEDEND);
6593
6594         /* Find out what we are to do. */
6595         ptr = next_token(&args, " \t");
6596         if (ptr == NULL)
6597                 return (ISC_R_UNEXPECTEDEND);
6598
6599         if (!strcasecmp(ptr, "on") || !strcasecmp(ptr, "yes") ||
6600             !strcasecmp(ptr, "enable") || !strcasecmp(ptr, "true"))
6601                 enable = ISC_TRUE;
6602         else if (!strcasecmp(ptr, "off") || !strcasecmp(ptr, "no") ||
6603                  !strcasecmp(ptr, "disable") || !strcasecmp(ptr, "false"))
6604                 enable = ISC_FALSE;
6605         else
6606                 return (DNS_R_SYNTAX);
6607
6608         /* Look for the view name. */
6609         viewname = next_token(&args, " \t");
6610
6611         result = isc_task_beginexclusive(server->task);
6612         RUNTIME_CHECK(result == ISC_R_SUCCESS);
6613         for (view = ISC_LIST_HEAD(server->viewlist);
6614              view != NULL;
6615              view = ISC_LIST_NEXT(view, link))
6616         {
6617                 if (viewname != NULL && strcasecmp(viewname, view->name) != 0)
6618                         continue;
6619                 result = dns_view_flushcache(view);
6620                 if (result != ISC_R_SUCCESS)
6621                         goto out;
6622                 view->enablevalidation = enable;
6623                 changed = ISC_TRUE;
6624         }
6625         if (changed)
6626                 result = ISC_R_SUCCESS;
6627         else
6628                 result = ISC_R_FAILURE;
6629  out:
6630         isc_task_endexclusive(server->task);
6631         return (result);
6632 }
6633
6634 isc_result_t
6635 ns_server_flushcache(ns_server_t *server, char *args) {
6636         char *ptr, *viewname;
6637         dns_view_t *view;
6638         isc_boolean_t flushed;
6639         isc_boolean_t found;
6640         isc_result_t result;
6641         ns_cache_t *nsc;
6642
6643         /* Skip the command name. */
6644         ptr = next_token(&args, " \t");
6645         if (ptr == NULL)
6646                 return (ISC_R_UNEXPECTEDEND);
6647
6648         /* Look for the view name. */
6649         viewname = next_token(&args, " \t");
6650
6651         result = isc_task_beginexclusive(server->task);
6652         RUNTIME_CHECK(result == ISC_R_SUCCESS);
6653         flushed = ISC_TRUE;
6654         found = ISC_FALSE;
6655
6656         /*
6657          * Flushing a cache is tricky when caches are shared by multiple views.
6658          * We first identify which caches should be flushed in the local cache
6659          * list, flush these caches, and then update other views that refer to
6660          * the flushed cache DB.
6661          */
6662         if (viewname != NULL) {
6663                 /*
6664                  * Mark caches that need to be flushed.  This is an O(#view^2)
6665                  * operation in the very worst case, but should be normally
6666                  * much more lightweight because only a few (most typically just
6667                  * one) views will match.
6668                  */
6669                 for (view = ISC_LIST_HEAD(server->viewlist);
6670                      view != NULL;
6671                      view = ISC_LIST_NEXT(view, link))
6672                 {
6673                         if (strcasecmp(viewname, view->name) != 0)
6674                                 continue;
6675                         found = ISC_TRUE;
6676                         for (nsc = ISC_LIST_HEAD(server->cachelist);
6677                              nsc != NULL;
6678                              nsc = ISC_LIST_NEXT(nsc, link)) {
6679                                 if (nsc->cache == view->cache)
6680                                         break;
6681                         }
6682                         INSIST(nsc != NULL);
6683                         nsc->needflush = ISC_TRUE;
6684                 }
6685         } else
6686                 found = ISC_TRUE;
6687
6688         /* Perform flush */
6689         for (nsc = ISC_LIST_HEAD(server->cachelist);
6690              nsc != NULL;
6691              nsc = ISC_LIST_NEXT(nsc, link)) {
6692                 if (viewname != NULL && !nsc->needflush)
6693                         continue;
6694                 nsc->needflush = ISC_TRUE;
6695                 result = dns_view_flushcache2(nsc->primaryview, ISC_FALSE);
6696                 if (result != ISC_R_SUCCESS) {
6697                         flushed = ISC_FALSE;
6698                         isc_log_write(ns_g_lctx, NS_LOGCATEGORY_GENERAL,
6699                                       NS_LOGMODULE_SERVER, ISC_LOG_ERROR,
6700                                       "flushing cache in view '%s' failed: %s",
6701                                       nsc->primaryview->name,
6702                                       isc_result_totext(result));
6703                 }
6704         }
6705
6706         /*
6707          * Fix up views that share a flushed cache: let the views update the
6708          * cache DB they're referring to.  This could also be an expensive
6709          * operation, but should typically be marginal: the inner loop is only
6710          * necessary for views that share a cache, and if there are many such
6711          * views the number of shared cache should normally be small.
6712          * A worst case is that we have n views and n/2 caches, each shared by
6713          * two views.  Then this will be a O(n^2/4) operation.
6714          */
6715         for (view = ISC_LIST_HEAD(server->viewlist);
6716              view != NULL;
6717              view = ISC_LIST_NEXT(view, link))
6718         {
6719                 if (!dns_view_iscacheshared(view))
6720                         continue;
6721                 for (nsc = ISC_LIST_HEAD(server->cachelist);
6722                      nsc != NULL;
6723                      nsc = ISC_LIST_NEXT(nsc, link)) {
6724                         if (!nsc->needflush || nsc->cache != view->cache)
6725                                 continue;
6726                         result = dns_view_flushcache2(view, ISC_TRUE);
6727                         if (result != ISC_R_SUCCESS) {
6728                                 flushed = ISC_FALSE;
6729                                 isc_log_write(ns_g_lctx, NS_LOGCATEGORY_GENERAL,
6730                                               NS_LOGMODULE_SERVER, ISC_LOG_ERROR,
6731                                               "fixing cache in view '%s' "
6732                                               "failed: %s", view->name,
6733                                               isc_result_totext(result));
6734                         }
6735                 }
6736         }
6737
6738         /* Cleanup the cache list. */
6739         for (nsc = ISC_LIST_HEAD(server->cachelist);
6740              nsc != NULL;
6741              nsc = ISC_LIST_NEXT(nsc, link)) {
6742                 nsc->needflush = ISC_FALSE;
6743         }
6744
6745         if (flushed && found) {
6746                 if (viewname != NULL)
6747                         isc_log_write(ns_g_lctx, NS_LOGCATEGORY_GENERAL,
6748                                       NS_LOGMODULE_SERVER, ISC_LOG_INFO,
6749                                       "flushing cache in view '%s' succeeded",
6750                                       viewname);
6751                 else
6752                         isc_log_write(ns_g_lctx, NS_LOGCATEGORY_GENERAL,
6753                                       NS_LOGMODULE_SERVER, ISC_LOG_INFO,
6754                                       "flushing caches in all views succeeded");
6755                 result = ISC_R_SUCCESS;
6756         } else {
6757                 if (!found) {
6758                         isc_log_write(ns_g_lctx, NS_LOGCATEGORY_GENERAL,
6759                                       NS_LOGMODULE_SERVER, ISC_LOG_ERROR,
6760                                       "flushing cache in view '%s' failed: "
6761                                       "view not found", viewname);
6762                         result = ISC_R_NOTFOUND;
6763                 } else
6764                         result = ISC_R_FAILURE;
6765         }
6766         isc_task_endexclusive(server->task);
6767         return (result);
6768 }
6769
6770 isc_result_t
6771 ns_server_flushname(ns_server_t *server, char *args) {
6772         char *ptr, *target, *viewname;
6773         dns_view_t *view;
6774         isc_boolean_t flushed;
6775         isc_boolean_t found;
6776         isc_result_t result;
6777         isc_buffer_t b;
6778         dns_fixedname_t fixed;
6779         dns_name_t *name;
6780
6781         /* Skip the command name. */
6782         ptr = next_token(&args, " \t");
6783         if (ptr == NULL)
6784                 return (ISC_R_UNEXPECTEDEND);
6785
6786         /* Find the domain name to flush. */
6787         target = next_token(&args, " \t");
6788         if (target == NULL)
6789                 return (ISC_R_UNEXPECTEDEND);
6790
6791         isc_buffer_init(&b, target, strlen(target));
6792         isc_buffer_add(&b, strlen(target));
6793         dns_fixedname_init(&fixed);
6794         name = dns_fixedname_name(&fixed);
6795         result = dns_name_fromtext(name, &b, dns_rootname, 0, NULL);
6796         if (result != ISC_R_SUCCESS)
6797                 return (result);
6798
6799         /* Look for the view name. */
6800         viewname = next_token(&args, " \t");
6801
6802         result = isc_task_beginexclusive(server->task);
6803         RUNTIME_CHECK(result == ISC_R_SUCCESS);
6804         flushed = ISC_TRUE;
6805         found = ISC_FALSE;
6806         for (view = ISC_LIST_HEAD(server->viewlist);
6807              view != NULL;
6808              view = ISC_LIST_NEXT(view, link))
6809         {
6810                 if (viewname != NULL && strcasecmp(viewname, view->name) != 0)
6811                         continue;
6812                 found = ISC_TRUE;
6813                 /*
6814                  * It's a little inefficient to try flushing name for all views
6815                  * if some of the views share a single cache.  But since the
6816                  * operation is lightweight we prefer simplicity here.
6817                  */
6818                 result = dns_view_flushname(view, name);
6819                 if (result != ISC_R_SUCCESS) {
6820                         flushed = ISC_FALSE;
6821                         isc_log_write(ns_g_lctx, NS_LOGCATEGORY_GENERAL,
6822                                       NS_LOGMODULE_SERVER, ISC_LOG_ERROR,
6823                                       "flushing name '%s' in cache view '%s' "
6824                                       "failed: %s", target, view->name,
6825                                       isc_result_totext(result));
6826                 }
6827         }
6828         if (flushed && found) {
6829                 if (viewname != NULL)
6830                         isc_log_write(ns_g_lctx, NS_LOGCATEGORY_GENERAL,
6831                                       NS_LOGMODULE_SERVER, ISC_LOG_INFO,
6832                                       "flushing name '%s' in cache view '%s' "
6833                                       "succeeded", target, viewname);
6834                 else
6835                         isc_log_write(ns_g_lctx, NS_LOGCATEGORY_GENERAL,
6836                                       NS_LOGMODULE_SERVER, ISC_LOG_INFO,
6837                                       "flushing name '%s' in all cache views "
6838                                       "succeeded", target);
6839                 result = ISC_R_SUCCESS;
6840         } else {
6841                 if (!found)
6842                         isc_log_write(ns_g_lctx, NS_LOGCATEGORY_GENERAL,
6843                                       NS_LOGMODULE_SERVER, ISC_LOG_ERROR,
6844                                       "flushing name '%s' in cache view '%s' "
6845                                       "failed: view not found", target,
6846                                       viewname);
6847                 result = ISC_R_FAILURE;
6848         }
6849         isc_task_endexclusive(server->task);
6850         return (result);
6851 }
6852
6853 isc_result_t
6854 ns_server_status(ns_server_t *server, isc_buffer_t *text) {
6855         int zonecount, xferrunning, xferdeferred, soaqueries;
6856         unsigned int n;
6857         const char *ob = "", *cb = "", *alt = "";
6858
6859         if (ns_g_server->version_set) {
6860                 ob = " (";
6861                 cb = ")";
6862                 if (ns_g_server->version == NULL)
6863                         alt = "version.bind/txt/ch disabled";
6864                 else
6865                         alt = ns_g_server->version;
6866         }
6867         zonecount = dns_zonemgr_getcount(server->zonemgr, DNS_ZONESTATE_ANY);
6868         xferrunning = dns_zonemgr_getcount(server->zonemgr,
6869                                            DNS_ZONESTATE_XFERRUNNING);
6870         xferdeferred = dns_zonemgr_getcount(server->zonemgr,
6871                                             DNS_ZONESTATE_XFERDEFERRED);
6872         soaqueries = dns_zonemgr_getcount(server->zonemgr,
6873                                           DNS_ZONESTATE_SOAQUERY);
6874
6875         n = snprintf((char *)isc_buffer_used(text),
6876                      isc_buffer_availablelength(text),
6877                      "version: %s%s%s%s\n"
6878 #ifdef ISC_PLATFORM_USETHREADS
6879                      "CPUs found: %u\n"
6880                      "worker threads: %u\n"
6881 #endif
6882                      "number of zones: %u\n"
6883                      "debug level: %d\n"
6884                      "xfers running: %u\n"
6885                      "xfers deferred: %u\n"
6886                      "soa queries in progress: %u\n"
6887                      "query logging is %s\n"
6888                      "recursive clients: %d/%d/%d\n"
6889                      "tcp clients: %d/%d\n"
6890                      "server is up and running",
6891                      ns_g_version, ob, alt, cb,
6892 #ifdef ISC_PLATFORM_USETHREADS
6893                      ns_g_cpus_detected, ns_g_cpus,
6894 #endif
6895                      zonecount, ns_g_debuglevel, xferrunning, xferdeferred,
6896                      soaqueries, server->log_queries ? "ON" : "OFF",
6897                      server->recursionquota.used, server->recursionquota.soft,
6898                      server->recursionquota.max,
6899                      server->tcpquota.used, server->tcpquota.max);
6900         if (n >= isc_buffer_availablelength(text))
6901                 return (ISC_R_NOSPACE);
6902         isc_buffer_add(text, n);
6903         return (ISC_R_SUCCESS);
6904 }
6905
6906 static isc_result_t
6907 delete_keynames(dns_tsig_keyring_t *ring, char *target,
6908                 unsigned int *foundkeys)
6909 {
6910         char namestr[DNS_NAME_FORMATSIZE];
6911         isc_result_t result;
6912         dns_rbtnodechain_t chain;
6913         dns_name_t foundname;
6914         dns_fixedname_t fixedorigin;
6915         dns_name_t *origin;
6916         dns_rbtnode_t *node;
6917         dns_tsigkey_t *tkey;
6918
6919         dns_name_init(&foundname, NULL);
6920         dns_fixedname_init(&fixedorigin);
6921         origin = dns_fixedname_name(&fixedorigin);
6922
6923  again:
6924         dns_rbtnodechain_init(&chain, ring->mctx);
6925         result = dns_rbtnodechain_first(&chain, ring->keys, &foundname,
6926                                         origin);
6927         if (result == ISC_R_NOTFOUND) {
6928                 dns_rbtnodechain_invalidate(&chain);
6929                 return (ISC_R_SUCCESS);
6930         }
6931         if (result != ISC_R_SUCCESS && result != DNS_R_NEWORIGIN) {
6932                 dns_rbtnodechain_invalidate(&chain);
6933                 return (result);
6934         }
6935
6936         for (;;) {
6937                 node = NULL;
6938                 dns_rbtnodechain_current(&chain, &foundname, origin, &node);
6939                 tkey = node->data;
6940
6941                 if (tkey != NULL) {
6942                         if (!tkey->generated)
6943                                 goto nextkey;
6944
6945                         dns_name_format(&tkey->name, namestr, sizeof(namestr));
6946                         if (strcmp(namestr, target) == 0) {
6947                                 (*foundkeys)++;
6948                                 dns_rbtnodechain_invalidate(&chain);
6949                                 (void)dns_rbt_deletename(ring->keys,
6950                                                          &tkey->name,
6951                                                          ISC_FALSE);
6952                                 goto again;
6953                         }
6954                 }
6955
6956         nextkey:
6957                 result = dns_rbtnodechain_next(&chain, &foundname, origin);
6958                 if (result == ISC_R_NOMORE)
6959                         break;
6960                 if (result != ISC_R_SUCCESS && result != DNS_R_NEWORIGIN) {
6961                         dns_rbtnodechain_invalidate(&chain);
6962                         return (result);
6963                 }
6964         }
6965
6966         return (ISC_R_SUCCESS);
6967 }
6968
6969 isc_result_t
6970 ns_server_tsigdelete(ns_server_t *server, char *command, isc_buffer_t *text) {
6971         isc_result_t result;
6972         unsigned int n;
6973         dns_view_t *view;
6974         unsigned int foundkeys = 0;
6975         char *target;
6976         char *viewname;
6977
6978         (void)next_token(&command, " \t");  /* skip command name */
6979         target = next_token(&command, " \t");
6980         if (target == NULL)
6981                 return (ISC_R_UNEXPECTEDEND);
6982         viewname = next_token(&command, " \t");
6983
6984         result = isc_task_beginexclusive(server->task);
6985         RUNTIME_CHECK(result == ISC_R_SUCCESS);
6986         for (view = ISC_LIST_HEAD(server->viewlist);
6987              view != NULL;
6988              view = ISC_LIST_NEXT(view, link)) {
6989                 if (viewname == NULL || strcmp(view->name, viewname) == 0) {
6990                         RWLOCK(&view->dynamickeys->lock, isc_rwlocktype_write);
6991                         result = delete_keynames(view->dynamickeys, target,
6992                                                  &foundkeys);
6993                         RWUNLOCK(&view->dynamickeys->lock,
6994                                  isc_rwlocktype_write);
6995                         if (result != ISC_R_SUCCESS) {
6996                                 isc_task_endexclusive(server->task);
6997                                 return (result);
6998                         }
6999                 }
7000         }
7001         isc_task_endexclusive(server->task);
7002
7003         n = snprintf((char *)isc_buffer_used(text),
7004                      isc_buffer_availablelength(text),
7005                      "%d tsig keys deleted.\n", foundkeys);
7006         if (n >= isc_buffer_availablelength(text))
7007                 return (ISC_R_NOSPACE);
7008         isc_buffer_add(text, n);
7009
7010         return (ISC_R_SUCCESS);
7011 }
7012
7013 static isc_result_t
7014 list_keynames(dns_view_t *view, dns_tsig_keyring_t *ring, isc_buffer_t *text,
7015              unsigned int *foundkeys)
7016 {
7017         char namestr[DNS_NAME_FORMATSIZE];
7018         char creatorstr[DNS_NAME_FORMATSIZE];
7019         isc_result_t result;
7020         dns_rbtnodechain_t chain;
7021         dns_name_t foundname;
7022         dns_fixedname_t fixedorigin;
7023         dns_name_t *origin;
7024         dns_rbtnode_t *node;
7025         dns_tsigkey_t *tkey;
7026         unsigned int n;
7027         const char *viewname;
7028
7029         if (view != NULL)
7030                 viewname = view->name;
7031         else
7032                 viewname = "(global)";
7033
7034         dns_name_init(&foundname, NULL);
7035         dns_fixedname_init(&fixedorigin);
7036         origin = dns_fixedname_name(&fixedorigin);
7037         dns_rbtnodechain_init(&chain, ring->mctx);
7038         result = dns_rbtnodechain_first(&chain, ring->keys, &foundname,
7039                                         origin);
7040         if (result == ISC_R_NOTFOUND) {
7041                 dns_rbtnodechain_invalidate(&chain);
7042                 return (ISC_R_SUCCESS);
7043         }
7044         if (result != ISC_R_SUCCESS && result != DNS_R_NEWORIGIN) {
7045                 dns_rbtnodechain_invalidate(&chain);
7046                 return (result);
7047         }
7048
7049         for (;;) {
7050                 node = NULL;
7051                 dns_rbtnodechain_current(&chain, &foundname, origin, &node);
7052                 tkey = node->data;
7053
7054                 if (tkey != NULL) {
7055                         (*foundkeys)++;
7056                         dns_name_format(&tkey->name, namestr, sizeof(namestr));
7057                         if (tkey->generated) {
7058                                 dns_name_format(tkey->creator, creatorstr,
7059                                                 sizeof(creatorstr));
7060                                 n = snprintf((char *)isc_buffer_used(text),
7061                                              isc_buffer_availablelength(text),
7062                                              "view \"%s\"; type \"dynamic\"; key \"%s\"; creator \"%s\";\n",
7063                                              viewname, namestr, creatorstr);
7064                         } else {
7065                                 n = snprintf((char *)isc_buffer_used(text),
7066                                              isc_buffer_availablelength(text),
7067                                              "view \"%s\"; type \"static\"; key \"%s\";\n",
7068                                              viewname, namestr);
7069                         }
7070                         if (n >= isc_buffer_availablelength(text)) {
7071                                 dns_rbtnodechain_invalidate(&chain);
7072                                 return (ISC_R_NOSPACE);
7073                         }
7074                         isc_buffer_add(text, n);
7075                 }
7076                 result = dns_rbtnodechain_next(&chain, &foundname, origin);
7077                 if (result == ISC_R_NOMORE)
7078                         break;
7079                 if (result != ISC_R_SUCCESS && result != DNS_R_NEWORIGIN) {
7080                         dns_rbtnodechain_invalidate(&chain);
7081                         return (result);
7082                 }
7083         }
7084
7085         return (ISC_R_SUCCESS);
7086 }
7087
7088 isc_result_t
7089 ns_server_tsiglist(ns_server_t *server, isc_buffer_t *text) {
7090         isc_result_t result;
7091         unsigned int n;
7092         dns_view_t *view;
7093         unsigned int foundkeys = 0;
7094
7095         result = isc_task_beginexclusive(server->task);
7096         RUNTIME_CHECK(result == ISC_R_SUCCESS);
7097         for (view = ISC_LIST_HEAD(server->viewlist);
7098              view != NULL;
7099              view = ISC_LIST_NEXT(view, link)) {
7100                 RWLOCK(&view->statickeys->lock, isc_rwlocktype_read);
7101                 result = list_keynames(view, view->statickeys, text,
7102                                        &foundkeys);
7103                 RWUNLOCK(&view->statickeys->lock, isc_rwlocktype_read);
7104                 if (result != ISC_R_SUCCESS) {
7105                         isc_task_endexclusive(server->task);
7106                         return (result);
7107                 }
7108                 RWLOCK(&view->dynamickeys->lock, isc_rwlocktype_read);
7109                 result = list_keynames(view, view->dynamickeys, text,
7110                                        &foundkeys);
7111                 RWUNLOCK(&view->dynamickeys->lock, isc_rwlocktype_read);
7112                 if (result != ISC_R_SUCCESS) {
7113                         isc_task_endexclusive(server->task);
7114                         return (result);
7115                 }
7116         }
7117         isc_task_endexclusive(server->task);
7118
7119         if (foundkeys == 0) {
7120                 n = snprintf((char *)isc_buffer_used(text),
7121                              isc_buffer_availablelength(text),
7122                              "no tsig keys found.\n");
7123                 if (n >= isc_buffer_availablelength(text))
7124                         return (ISC_R_NOSPACE);
7125                 isc_buffer_add(text, n);
7126         }
7127
7128         return (ISC_R_SUCCESS);
7129 }
7130
7131 /*
7132  * Act on a "sign" or "loadkeys" command from the command channel.
7133  */
7134 isc_result_t
7135 ns_server_rekey(ns_server_t *server, char *args) {
7136         isc_result_t result;
7137         dns_zone_t *zone = NULL;
7138         dns_zonetype_t type;
7139         isc_uint16_t keyopts;
7140         isc_boolean_t fullsign = ISC_FALSE;
7141
7142         if (strncasecmp(args, NS_COMMAND_SIGN, strlen(NS_COMMAND_SIGN)) == 0)
7143             fullsign = ISC_TRUE;
7144
7145         result = zone_from_args(server, args, &zone, NULL);
7146         if (result != ISC_R_SUCCESS)
7147                 return (result);
7148         if (zone == NULL)
7149                 return (ISC_R_UNEXPECTEDEND);   /* XXX: or do all zones? */
7150
7151         type = dns_zone_gettype(zone);
7152         if (type != dns_zone_master) {
7153                 dns_zone_detach(&zone);
7154                 return (DNS_R_NOTMASTER);
7155         }
7156
7157         keyopts = dns_zone_getkeyopts(zone);
7158
7159         /* "rndc loadkeys" requires "auto-dnssec maintain". */
7160         if ((keyopts & DNS_ZONEKEY_ALLOW) == 0)
7161                 result = ISC_R_NOPERM;
7162         else if ((keyopts & DNS_ZONEKEY_MAINTAIN) == 0 && !fullsign)
7163                 result = ISC_R_NOPERM;
7164         else
7165                 dns_zone_rekey(zone, fullsign);
7166
7167         dns_zone_detach(&zone);
7168         return (result);
7169 }
7170
7171 /*
7172  * Act on a "freeze" or "thaw" command from the command channel.
7173  */
7174 isc_result_t
7175 ns_server_freeze(ns_server_t *server, isc_boolean_t freeze, char *args,
7176                  isc_buffer_t *text)
7177 {
7178         isc_result_t result, tresult;
7179         dns_zone_t *zone = NULL;
7180         dns_zonetype_t type;
7181         char classstr[DNS_RDATACLASS_FORMATSIZE];
7182         char zonename[DNS_NAME_FORMATSIZE];
7183         dns_view_t *view;
7184         char *journal;
7185         const char *vname, *sep;
7186         isc_boolean_t frozen;
7187         const char *msg = NULL;
7188
7189         result = zone_from_args(server, args, &zone, NULL);
7190         if (result != ISC_R_SUCCESS)
7191                 return (result);
7192         if (zone == NULL) {
7193                 result = isc_task_beginexclusive(server->task);
7194                 RUNTIME_CHECK(result == ISC_R_SUCCESS);
7195                 tresult = ISC_R_SUCCESS;
7196                 for (view = ISC_LIST_HEAD(server->viewlist);
7197                      view != NULL;
7198                      view = ISC_LIST_NEXT(view, link)) {
7199                         result = dns_view_freezezones(view, freeze);
7200                         if (result != ISC_R_SUCCESS &&
7201                             tresult == ISC_R_SUCCESS)
7202                                 tresult = result;
7203                 }
7204                 isc_task_endexclusive(server->task);
7205                 isc_log_write(ns_g_lctx, NS_LOGCATEGORY_GENERAL,
7206                               NS_LOGMODULE_SERVER, ISC_LOG_INFO,
7207                               "%s all zones: %s",
7208                               freeze ? "freezing" : "thawing",
7209                               isc_result_totext(tresult));
7210                 return (tresult);
7211         }
7212         type = dns_zone_gettype(zone);
7213         if (type != dns_zone_master) {
7214                 dns_zone_detach(&zone);
7215                 return (DNS_R_NOTMASTER);
7216         }
7217
7218         result = isc_task_beginexclusive(server->task);
7219         RUNTIME_CHECK(result == ISC_R_SUCCESS);
7220         frozen = dns_zone_getupdatedisabled(zone);
7221         if (freeze) {
7222                 if (frozen) {
7223                         msg = "WARNING: The zone was already frozen.\n"
7224                               "Someone else may be editing it or "
7225                               "it may still be re-loading.";
7226                         result = DNS_R_FROZEN;
7227                 }
7228                 if (result == ISC_R_SUCCESS) {
7229                         result = dns_zone_flush(zone);
7230                         if (result != ISC_R_SUCCESS)
7231                                 msg = "Flushing the zone updates to "
7232                                       "disk failed.";
7233                 }
7234                 if (result == ISC_R_SUCCESS) {
7235                         journal = dns_zone_getjournal(zone);
7236                         if (journal != NULL)
7237                                 (void)isc_file_remove(journal);
7238                 }
7239                 if (result == ISC_R_SUCCESS)
7240                         dns_zone_setupdatedisabled(zone, freeze);
7241         } else {
7242                 if (frozen) {
7243                         result = dns_zone_loadandthaw(zone);
7244                         switch (result) {
7245                         case ISC_R_SUCCESS:
7246                         case DNS_R_UPTODATE:
7247                                 msg = "The zone reload and thaw was "
7248                                       "successful.";
7249                                 result = ISC_R_SUCCESS;
7250                                 break;
7251                         case DNS_R_CONTINUE:
7252                                 msg = "A zone reload and thaw was started.\n"
7253                                       "Check the logs to see the result.";
7254                                 result = ISC_R_SUCCESS;
7255                                 break;
7256                         }
7257                 }
7258         }
7259         isc_task_endexclusive(server->task);
7260
7261         if (msg != NULL && strlen(msg) < isc_buffer_availablelength(text))
7262                 isc_buffer_putmem(text, (const unsigned char *)msg,
7263                                   strlen(msg) + 1);
7264
7265         view = dns_zone_getview(zone);
7266         if (strcmp(view->name, "_default") == 0 ||
7267             strcmp(view->name, "_bind") == 0)
7268         {
7269                 vname = "";
7270                 sep = "";
7271         } else {
7272                 vname = view->name;
7273                 sep = " ";
7274         }
7275         dns_rdataclass_format(dns_zone_getclass(zone), classstr,
7276                               sizeof(classstr));
7277         dns_name_format(dns_zone_getorigin(zone),
7278                         zonename, sizeof(zonename));
7279         isc_log_write(ns_g_lctx, NS_LOGCATEGORY_GENERAL,
7280                       NS_LOGMODULE_SERVER, ISC_LOG_INFO,
7281                       "%s zone '%s/%s'%s%s: %s",
7282                       freeze ? "freezing" : "thawing",
7283                       zonename, classstr, sep, vname,
7284                       isc_result_totext(result));
7285         dns_zone_detach(&zone);
7286         return (result);
7287 }
7288
7289 #ifdef HAVE_LIBSCF
7290 /*
7291  * This function adds a message for rndc to echo if named
7292  * is managed by smf and is also running chroot.
7293  */
7294 isc_result_t
7295 ns_smf_add_message(isc_buffer_t *text) {
7296         unsigned int n;
7297
7298         n = snprintf((char *)isc_buffer_used(text),
7299                 isc_buffer_availablelength(text),
7300                 "use svcadm(1M) to manage named");
7301         if (n >= isc_buffer_availablelength(text))
7302                 return (ISC_R_NOSPACE);
7303         isc_buffer_add(text, n);
7304         return (ISC_R_SUCCESS);
7305 }
7306 #endif /* HAVE_LIBSCF */
7307
7308 /*
7309  * Act on an "addzone" command from the command channel.
7310  */
7311 isc_result_t
7312 ns_server_add_zone(ns_server_t *server, char *args) {
7313         isc_result_t         result;
7314         isc_buffer_t         argbuf;
7315         size_t               arglen;
7316         cfg_parser_t        *parser = NULL;
7317         cfg_obj_t           *config = NULL;
7318         const cfg_obj_t     *vconfig = NULL;
7319         const cfg_obj_t     *views = NULL;
7320         const cfg_obj_t     *parms = NULL;
7321         const cfg_obj_t     *obj = NULL;
7322         const cfg_listelt_t *element;
7323         const char          *zonename;
7324         const char          *classname = NULL;
7325         const char          *argp;
7326         const char          *viewname = NULL;
7327         dns_rdataclass_t     rdclass;
7328         dns_view_t          *view = 0;
7329         isc_buffer_t         buf, *nbuf = NULL;
7330         dns_name_t           dnsname;
7331         dns_zone_t          *zone = NULL;
7332         FILE                *fp = NULL;
7333         struct cfg_context  *cfg = NULL;
7334
7335         /* Try to parse the argument string */
7336         arglen = strlen(args);
7337         isc_buffer_init(&argbuf, args, arglen);
7338         isc_buffer_add(&argbuf, strlen(args));
7339         CHECK(cfg_parser_create(server->mctx, ns_g_lctx, &parser));
7340         CHECK(cfg_parse_buffer(parser, &argbuf, &cfg_type_addzoneconf,
7341                                &config));
7342         CHECK(cfg_map_get(config, "addzone", &parms));
7343
7344         zonename = cfg_obj_asstring(cfg_tuple_get(parms, "name"));
7345         isc_buffer_init(&buf, zonename, strlen(zonename));
7346         isc_buffer_add(&buf, strlen(zonename));
7347         dns_name_init(&dnsname, NULL);
7348         isc_buffer_allocate(server->mctx, &nbuf, 256);
7349         dns_name_setbuffer(&dnsname, nbuf);
7350         CHECK(dns_name_fromtext(&dnsname, &buf, dns_rootname, ISC_FALSE, NULL));
7351
7352         /* Make sense of optional class argument */
7353         obj = cfg_tuple_get(parms, "class");
7354         CHECK(ns_config_getclass(obj, dns_rdataclass_in, &rdclass));
7355         if (rdclass != dns_rdataclass_in && obj)
7356                 classname = cfg_obj_asstring(obj);
7357
7358         /* Make sense of optional view argument */
7359         obj = cfg_tuple_get(parms, "view");
7360         if (obj && cfg_obj_isstring(obj))
7361                 viewname = cfg_obj_asstring(obj);
7362         if (viewname == NULL || *viewname == '\0')
7363                 viewname = "_default";
7364         CHECK(dns_viewlist_find(&server->viewlist, viewname, rdclass, &view));
7365
7366         /* Are we accepting new zones? */
7367         if (view->new_zone_file == NULL) {
7368                 result = ISC_R_NOPERM;
7369                 goto cleanup;
7370         }
7371
7372         cfg = (struct cfg_context *) view->new_zone_config;
7373         if (cfg == NULL) {
7374                 result = ISC_R_FAILURE;
7375                 goto cleanup;
7376         }
7377
7378         /* Zone shouldn't already exist */
7379         result = dns_zt_find(view->zonetable, &dnsname, 0, NULL, &zone);
7380         if (result == ISC_R_SUCCESS) {
7381                 result = ISC_R_EXISTS;
7382                 goto cleanup;
7383         } else if (result == DNS_R_PARTIALMATCH) {
7384                 /* Create our sub-zone anyway */
7385                 dns_zone_detach(&zone);
7386                 zone = NULL;
7387         }
7388         else if (result != ISC_R_NOTFOUND)
7389                 goto cleanup;
7390
7391         /* Find the view statement */
7392         cfg_map_get(cfg->config, "view", &views);
7393         for (element = cfg_list_first(views);
7394              element != NULL;
7395              element = cfg_list_next(element))
7396         {
7397                 const char *vname;
7398                 vconfig = cfg_listelt_value(element);
7399                 vname = cfg_obj_asstring(cfg_tuple_get(vconfig, "name"));
7400                 if (vname && !strcasecmp(vname, viewname))
7401                         break;
7402                 vconfig = NULL;
7403         }
7404
7405         /* Open save file for write configuration */
7406         CHECK(isc_stdio_open(view->new_zone_file, "a", &fp));
7407
7408         /* Mark view unfrozen so that zone can be added */
7409         isc_task_beginexclusive(server->task);
7410         dns_view_thaw(view);
7411         result = configure_zone(cfg->config, parms, vconfig,
7412                                 server->mctx, view, cfg->actx, ISC_FALSE);
7413         dns_view_freeze(view);
7414         isc_task_endexclusive(server->task);
7415         if (result != ISC_R_SUCCESS)
7416                 goto cleanup;
7417
7418         /* Is it there yet? */
7419         CHECK(dns_zt_find(view->zonetable, &dnsname, 0, NULL, &zone));
7420
7421         /*
7422          * Load the zone from the master file.  If this fails, we'll
7423          * need to undo the configuration we've done already.
7424          */
7425         result = dns_zone_loadnew(zone);
7426         if (result != ISC_R_SUCCESS) {
7427                 dns_db_t *dbp = NULL;
7428
7429                 isc_log_write(ns_g_lctx, NS_LOGCATEGORY_GENERAL,
7430                               NS_LOGMODULE_SERVER, ISC_LOG_INFO,
7431                               "addzone failed; reverting.");
7432
7433                 /* If the zone loaded partially, unload it */
7434                 if (dns_zone_getdb(zone, &dbp) == ISC_R_SUCCESS) {
7435                         dns_db_detach(&dbp);
7436                         dns_zone_unload(zone);
7437                 }
7438
7439                 /* Remove the zone from the zone table */
7440                 dns_zt_unmount(view->zonetable, zone);
7441                 goto cleanup;
7442         }
7443
7444         /* Flag the zone as having been added at runtime */
7445         dns_zone_setadded(zone, ISC_TRUE);
7446
7447         /* Emit just the zone name from args */
7448         CHECK(isc_stdio_write("zone ", 5, 1, fp, NULL));
7449         CHECK(isc_stdio_write(zonename, strlen(zonename), 1, fp, NULL));
7450         CHECK(isc_stdio_write(" ", 1, 1, fp, NULL));
7451
7452         /* Classname, if not default */
7453         if (classname != NULL && *classname != '\0') {
7454                 CHECK(isc_stdio_write(classname, strlen(classname), 1, fp,
7455                                       NULL));
7456                 CHECK(isc_stdio_write(" ", 1, 1, fp, NULL));
7457         }
7458
7459         /* Find beginning of option block from args */
7460         for (argp = args; *argp; argp++, arglen--) {
7461                 if (*argp == '{') {     /* Assume matching '}' */
7462                         /* Add that to our file */
7463                         CHECK(isc_stdio_write(argp, arglen, 1, fp, NULL));
7464
7465                         /* Make sure we end with a LF */
7466                         if (argp[arglen-1] != '\n') {
7467                                 CHECK(isc_stdio_write("\n", 1, 1, fp, NULL));
7468                         }
7469                         break;
7470                 }
7471         }
7472
7473         CHECK(isc_stdio_close(fp));
7474         fp = NULL;
7475         isc_log_write(ns_g_lctx, NS_LOGCATEGORY_GENERAL,
7476                                   NS_LOGMODULE_SERVER, ISC_LOG_INFO,
7477                                   "zone %s added to view %s via addzone",
7478                                   zonename, viewname);
7479
7480         result = ISC_R_SUCCESS;
7481
7482  cleanup:
7483         if (fp != NULL)
7484                 isc_stdio_close(fp);
7485         if (parser != NULL) {
7486                 if (config != NULL)
7487                         cfg_obj_destroy(parser, &config);
7488                 cfg_parser_destroy(&parser);
7489         }
7490         if (zone != NULL)
7491                 dns_zone_detach(&zone);
7492         if (view != NULL)
7493                 dns_view_detach(&view);
7494         if (nbuf != NULL)
7495                 isc_buffer_free(&nbuf);
7496
7497         return (result);
7498 }
7499
7500 /*
7501  * Act on a "delzone" command from the command channel.
7502  */
7503 isc_result_t
7504 ns_server_del_zone(ns_server_t *server, char *args) {
7505         isc_result_t           result;
7506         dns_zone_t            *zone = NULL;
7507         dns_view_t            *view = NULL;
7508         dns_db_t              *dbp = NULL;
7509         const char            *filename = NULL;
7510         char                  *tmpname = NULL;
7511         char                   buf[1024];
7512         const char            *zonename = NULL;
7513         size_t                 znamelen = 0;
7514         FILE                  *ifp = NULL, *ofp = NULL;
7515
7516         /* Parse parameters */
7517         CHECK(zone_from_args(server, args, &zone, &zonename));
7518         if (result != ISC_R_SUCCESS)
7519                 return (result);
7520         if (zone == NULL) {
7521                 result = ISC_R_UNEXPECTEDEND;
7522                 goto cleanup;
7523         }
7524
7525         /*
7526          * Was this zone originally added at runtime?
7527          * If not, we can't delete it now.
7528          */
7529         if (!dns_zone_getadded(zone)) {
7530                 result = ISC_R_NOPERM;
7531                 goto cleanup;
7532         }
7533
7534         if (zonename != NULL)
7535                 znamelen = strlen(zonename);
7536
7537         /* Dig out configuration for this zone */
7538         view = dns_zone_getview(zone);
7539         filename = view->new_zone_file;
7540         if (filename == NULL) {
7541                 /* No adding zones in this view */
7542                 result = ISC_R_FAILURE;
7543                 goto cleanup;
7544         }
7545
7546         /* Rewrite zone list */
7547         result = isc_stdio_open(filename, "r", &ifp);
7548         if (ifp != NULL && result == ISC_R_SUCCESS) {
7549                 char *found = NULL, *p = NULL;
7550                 size_t n;
7551
7552                 /* Create a temporary file */
7553                 CHECK(isc_string_printf(buf, 1023, "%s.%ld", filename,
7554                                         (long)getpid()));
7555                 if (!(tmpname = isc_mem_strdup(server->mctx, buf))) {
7556                         result = ISC_R_NOMEMORY;
7557                         goto cleanup;
7558                 }
7559                 CHECK(isc_stdio_open(tmpname, "w", &ofp));
7560
7561                 /* Look for the entry for that zone */
7562                 while (fgets(buf, 1024, ifp)) {
7563                         /* A 'zone' line */
7564                         if (strncasecmp(buf, "zone", 4)) {
7565                                 fputs(buf, ofp);
7566                                 continue;
7567                         }
7568                         p = buf+4;
7569
7570                         /* Locate a name */
7571                         while (*p &&
7572                                ((*p == '"') || isspace((unsigned char)*p)))
7573                                 p++;
7574
7575                         /* Is that the zone we're looking for */
7576                         if (strncasecmp(p, zonename, znamelen)) {
7577                                 fputs(buf, ofp);
7578                                 continue;
7579                         }
7580
7581                         /* And nothing else? */
7582                         p += znamelen;
7583                         if (isspace((unsigned char)*p) ||
7584                             *p == '"' || *p == '{') {
7585                                 /* This must be the entry */
7586                                 found = p;
7587                                 break;
7588                         }
7589
7590                         /* Spit it out, keep looking */
7591                         fputs(buf, ofp);
7592                 }
7593
7594                 /* Skip over an option block (matching # of braces) */
7595                 if (found) {
7596                         int obrace = 0, cbrace = 0;
7597                         for (;;) {
7598                                 while (*p) {
7599                                         if (*p == '{') obrace++;
7600                                         if (*p == '}') cbrace++;
7601                                         p++;
7602                                 }
7603                                 if (obrace && (obrace == cbrace))
7604                                         break;
7605                                 if (!fgets(buf, 1024, ifp))
7606                                         break;
7607                                 p = buf;
7608                         }
7609
7610                         /* Just spool the remainder of the file out */
7611                         result = isc_stdio_read(buf, 1, 1024, ifp, &n);
7612                         while (n > 0U) {
7613                                 if (result == ISC_R_EOF)
7614                                         result = ISC_R_SUCCESS;
7615                                 CHECK(result);
7616                                 isc_stdio_write(buf, 1, n, ofp, NULL);
7617                                 result = isc_stdio_read(buf, 1, 1024, ifp, &n);
7618                         }
7619
7620                         /* Move temporary into place */
7621                         CHECK(isc_file_rename(tmpname, view->new_zone_file));
7622                 } else {
7623                         isc_log_write(ns_g_lctx, NS_LOGCATEGORY_GENERAL,
7624                                       NS_LOGMODULE_SERVER, ISC_LOG_WARNING,
7625                                       "deleted zone %s was missing from "
7626                                       "new zone file", zonename);
7627                         goto cleanup;
7628                 }
7629         }
7630
7631         /* Stop answering for this zone */
7632         if (dns_zone_getdb(zone, &dbp) == ISC_R_SUCCESS) {
7633                 dns_db_detach(&dbp);
7634                 dns_zone_unload(zone);
7635         }
7636
7637         CHECK(dns_zt_unmount(view->zonetable, zone));
7638
7639         isc_log_write(ns_g_lctx, NS_LOGCATEGORY_GENERAL,
7640                                   NS_LOGMODULE_SERVER, ISC_LOG_INFO,
7641                                   "zone %s removed via delzone", zonename);
7642
7643         result = ISC_R_SUCCESS;
7644
7645  cleanup:
7646         if (ifp != NULL)
7647                 isc_stdio_close(ifp);
7648         if (ofp != NULL) {
7649                 isc_stdio_close(ofp);
7650                 isc_file_remove(tmpname);
7651         }
7652         if (tmpname != NULL)
7653                 isc_mem_free(server->mctx, tmpname);
7654         if (zone != NULL)
7655                 dns_zone_detach(&zone);
7656
7657         return (result);
7658 }
7659
7660 static void
7661 newzone_cfgctx_destroy(void **cfgp) {
7662         struct cfg_context *cfg;
7663
7664         REQUIRE(cfgp != NULL && *cfgp != NULL);
7665
7666         cfg = *cfgp;
7667
7668         if (cfg->actx != NULL)
7669                 cfg_aclconfctx_detach(&cfg->actx);
7670
7671         if (cfg->parser != NULL) {
7672                 if (cfg->config != NULL)
7673                         cfg_obj_destroy(cfg->parser, &cfg->config);
7674                 cfg_parser_destroy(&cfg->parser);
7675         }
7676         if (cfg->nzparser != NULL) {
7677                 if (cfg->nzconfig != NULL)
7678                         cfg_obj_destroy(cfg->nzparser, &cfg->nzconfig);
7679                 cfg_parser_destroy(&cfg->nzparser);
7680         }
7681
7682         isc_mem_putanddetach(&cfg->mctx, cfg, sizeof(*cfg));
7683         *cfgp = NULL;
7684 }