]> CyberLeo.Net >> Repos - FreeBSD/releng/7.2.git/blob - contrib/bind9/bin/named/server.c
Create releng/7.2 from stable/7 in preparation for 7.2-RELEASE.
[FreeBSD/releng/7.2.git] / contrib / bind9 / bin / named / server.c
1 /*
2  * Copyright (C) 2004-2008  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.419.18.68 2008/09/04 23:46:08 tbox Exp $ */
19
20 /*! \file */
21
22 #include <config.h>
23
24 #include <stdlib.h>
25 #include <unistd.h>
26
27 #include <isc/app.h>
28 #include <isc/base64.h>
29 #include <isc/dir.h>
30 #include <isc/entropy.h>
31 #include <isc/file.h>
32 #include <isc/hash.h>
33 #include <isc/lex.h>
34 #include <isc/parseint.h>
35 #include <isc/portset.h>
36 #include <isc/print.h>
37 #include <isc/resource.h>
38 #include <isc/socket.h>
39 #include <isc/stdio.h>
40 #include <isc/string.h>
41 #include <isc/task.h>
42 #include <isc/timer.h>
43 #include <isc/util.h>
44
45 #include <isccfg/namedconf.h>
46
47 #include <bind9/check.h>
48
49 #include <dns/acache.h>
50 #include <dns/adb.h>
51 #include <dns/cache.h>
52 #include <dns/db.h>
53 #include <dns/dispatch.h>
54 #ifdef DLZ
55 #include <dns/dlz.h>
56 #endif
57 #include <dns/forward.h>
58 #include <dns/journal.h>
59 #include <dns/keytable.h>
60 #include <dns/lib.h>
61 #include <dns/master.h>
62 #include <dns/masterdump.h>
63 #include <dns/order.h>
64 #include <dns/peer.h>
65 #include <dns/portlist.h>
66 #include <dns/rdataclass.h>
67 #include <dns/rdataset.h>
68 #include <dns/rdatastruct.h>
69 #include <dns/resolver.h>
70 #include <dns/rootns.h>
71 #include <dns/secalg.h>
72 #include <dns/stats.h>
73 #include <dns/tkey.h>
74 #include <dns/view.h>
75 #include <dns/zone.h>
76 #include <dns/zt.h>
77
78 #include <dst/dst.h>
79 #include <dst/result.h>
80
81 #include <named/client.h>
82 #include <named/config.h>
83 #include <named/control.h>
84 #include <named/interfacemgr.h>
85 #include <named/log.h>
86 #include <named/logconf.h>
87 #include <named/lwresd.h>
88 #include <named/main.h>
89 #include <named/os.h>
90 #include <named/server.h>
91 #include <named/tkeyconf.h>
92 #include <named/tsigconf.h>
93 #include <named/zoneconf.h>
94 #ifdef HAVE_LIBSCF
95 #include <named/ns_smf_globals.h>
96 #include <stdlib.h>
97 #endif
98
99 /*%
100  * Check an operation for failure.  Assumes that the function
101  * using it has a 'result' variable and a 'cleanup' label.
102  */
103 #define CHECK(op) \
104         do { result = (op);                                      \
105                if (result != ISC_R_SUCCESS) goto cleanup;        \
106         } while (0)
107
108 #define CHECKM(op, msg) \
109         do { result = (op);                                       \
110                if (result != ISC_R_SUCCESS) {                     \
111                         isc_log_write(ns_g_lctx,                  \
112                                       NS_LOGCATEGORY_GENERAL,     \
113                                       NS_LOGMODULE_SERVER,        \
114                                       ISC_LOG_ERROR,              \
115                                       "%s: %s", msg,              \
116                                       isc_result_totext(result)); \
117                         goto cleanup;                             \
118                 }                                                 \
119         } while (0)                                               \
120
121 #define CHECKMF(op, msg, file) \
122         do { result = (op);                                       \
123                if (result != ISC_R_SUCCESS) {                     \
124                         isc_log_write(ns_g_lctx,                  \
125                                       NS_LOGCATEGORY_GENERAL,     \
126                                       NS_LOGMODULE_SERVER,        \
127                                       ISC_LOG_ERROR,              \
128                                       "%s '%s': %s", msg, file,   \
129                                       isc_result_totext(result)); \
130                         goto cleanup;                             \
131                 }                                                 \
132         } while (0)                                               \
133
134 #define CHECKFATAL(op, msg) \
135         do { result = (op);                                       \
136                if (result != ISC_R_SUCCESS)                       \
137                         fatal(msg, result);                       \
138         } while (0)                                               \
139
140 struct ns_dispatch {
141         isc_sockaddr_t                  addr;
142         unsigned int                    dispatchgen;
143         dns_dispatch_t                  *dispatch;
144         ISC_LINK(struct ns_dispatch)    link;
145 };
146
147 struct dumpcontext {
148         isc_mem_t                       *mctx;
149         isc_boolean_t                   dumpcache;
150         isc_boolean_t                   dumpzones;
151         FILE                            *fp;
152         ISC_LIST(struct viewlistentry)  viewlist;
153         struct viewlistentry            *view;
154         struct zonelistentry            *zone;
155         dns_dumpctx_t                   *mdctx;
156         dns_db_t                        *db;
157         dns_db_t                        *cache;
158         isc_task_t                      *task;
159         dns_dbversion_t                 *version;
160 };
161
162 struct viewlistentry {
163         dns_view_t                      *view;
164         ISC_LINK(struct viewlistentry)  link;
165         ISC_LIST(struct zonelistentry)  zonelist;
166 };
167
168 struct zonelistentry {
169         dns_zone_t                      *zone;
170         ISC_LINK(struct zonelistentry)  link;
171 };
172
173 /*
174  * These zones should not leak onto the Internet.
175  */
176 static const struct {
177         const char      *zone;
178         isc_boolean_t   rfc1918;
179 } empty_zones[] = {
180 #ifdef notyet
181         /* RFC 1918 */
182         { "10.IN-ADDR.ARPA", ISC_TRUE },
183         { "16.172.IN-ADDR.ARPA", ISC_TRUE },
184         { "17.172.IN-ADDR.ARPA", ISC_TRUE },
185         { "18.172.IN-ADDR.ARPA", ISC_TRUE },
186         { "19.172.IN-ADDR.ARPA", ISC_TRUE },
187         { "20.172.IN-ADDR.ARPA", ISC_TRUE },
188         { "21.172.IN-ADDR.ARPA", ISC_TRUE },
189         { "22.172.IN-ADDR.ARPA", ISC_TRUE },
190         { "23.172.IN-ADDR.ARPA", ISC_TRUE },
191         { "24.172.IN-ADDR.ARPA", ISC_TRUE },
192         { "25.172.IN-ADDR.ARPA", ISC_TRUE },
193         { "26.172.IN-ADDR.ARPA", ISC_TRUE },
194         { "27.172.IN-ADDR.ARPA", ISC_TRUE },
195         { "28.172.IN-ADDR.ARPA", ISC_TRUE },
196         { "29.172.IN-ADDR.ARPA", ISC_TRUE },
197         { "30.172.IN-ADDR.ARPA", ISC_TRUE },
198         { "31.172.IN-ADDR.ARPA", ISC_TRUE },
199         { "168.192.IN-ADDR.ARPA", ISC_TRUE },
200 #endif
201
202         /* RFC 3330 */
203         { "0.IN-ADDR.ARPA", ISC_FALSE },        /* THIS NETWORK */
204         { "127.IN-ADDR.ARPA", ISC_FALSE },      /* LOOPBACK */
205         { "254.169.IN-ADDR.ARPA", ISC_FALSE },  /* LINK LOCAL */
206         { "2.0.192.IN-ADDR.ARPA", ISC_FALSE },  /* TEST NET */
207         { "255.255.255.255.IN-ADDR.ARPA", ISC_FALSE },  /* BROADCAST */
208
209         /* Local IPv6 Unicast Addresses */
210         { "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 },
211         { "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 },
212         /* LOCALLY ASSIGNED LOCAL ADDRES S SCOPE */
213         { "D.F.IP6.ARPA", ISC_FALSE },
214         { "8.E.F.IP6.ARPA", ISC_FALSE },        /* LINK LOCAL */
215         { "9.E.F.IP6.ARPA", ISC_FALSE },        /* LINK LOCAL */
216         { "A.E.F.IP6.ARPA", ISC_FALSE },        /* LINK LOCAL */
217         { "B.E.F.IP6.ARPA", ISC_FALSE },        /* LINK LOCAL */
218
219         { NULL, ISC_FALSE }
220 };
221
222 static void
223 fatal(const char *msg, isc_result_t result);
224
225 static void
226 ns_server_reload(isc_task_t *task, isc_event_t *event);
227
228 static isc_result_t
229 ns_listenelt_fromconfig(const cfg_obj_t *listener, const cfg_obj_t *config,
230                         cfg_aclconfctx_t *actx,
231                         isc_mem_t *mctx, ns_listenelt_t **target);
232 static isc_result_t
233 ns_listenlist_fromconfig(const cfg_obj_t *listenlist, const cfg_obj_t *config,
234                          cfg_aclconfctx_t *actx,
235                          isc_mem_t *mctx, ns_listenlist_t **target);
236
237 static isc_result_t
238 configure_forward(const cfg_obj_t *config, dns_view_t *view, dns_name_t *origin,
239                   const cfg_obj_t *forwarders, const cfg_obj_t *forwardtype);
240
241 static isc_result_t
242 configure_alternates(const cfg_obj_t *config, dns_view_t *view,
243                      const cfg_obj_t *alternates);
244
245 static isc_result_t
246 configure_zone(const cfg_obj_t *config, const cfg_obj_t *zconfig,
247                const cfg_obj_t *vconfig, isc_mem_t *mctx, dns_view_t *view,
248                cfg_aclconfctx_t *aclconf);
249
250 static void
251 end_reserved_dispatches(ns_server_t *server, isc_boolean_t all);
252
253 /*%
254  * Configure a single view ACL at '*aclp'.  Get its configuration by
255  * calling 'getvcacl' (for per-view configuration) and maybe 'getscacl'
256  * (for a global default).
257  */
258 static isc_result_t
259 configure_view_acl(const cfg_obj_t *vconfig, const cfg_obj_t *config,
260                    const char *aclname, cfg_aclconfctx_t *actx,
261                    isc_mem_t *mctx, dns_acl_t **aclp)
262 {
263         isc_result_t result;
264         const cfg_obj_t *maps[3];
265         const cfg_obj_t *aclobj = NULL;
266         int i = 0;
267
268         if (*aclp != NULL)
269                 dns_acl_detach(aclp);
270         if (vconfig != NULL)
271                 maps[i++] = cfg_tuple_get(vconfig, "options");
272         if (config != NULL) {
273                 const cfg_obj_t *options = NULL;
274                 (void)cfg_map_get(config, "options", &options);
275                 if (options != NULL)
276                         maps[i++] = options;
277         }
278         maps[i] = NULL;
279
280         (void)ns_config_get(maps, aclname, &aclobj);
281         if (aclobj == NULL)
282                 /*
283                  * No value available.  *aclp == NULL.
284                  */
285                 return (ISC_R_SUCCESS);
286
287         result = cfg_acl_fromconfig(aclobj, config, ns_g_lctx,
288                                     actx, mctx, aclp);
289
290         return (result);
291 }
292
293 static isc_result_t
294 configure_view_dnsseckey(const cfg_obj_t *vconfig, const cfg_obj_t *key,
295                          dns_keytable_t *keytable, isc_mem_t *mctx)
296 {
297         dns_rdataclass_t viewclass;
298         dns_rdata_dnskey_t keystruct;
299         isc_uint32_t flags, proto, alg;
300         const char *keystr, *keynamestr;
301         unsigned char keydata[4096];
302         isc_buffer_t keydatabuf;
303         unsigned char rrdata[4096];
304         isc_buffer_t rrdatabuf;
305         isc_region_t r;
306         dns_fixedname_t fkeyname;
307         dns_name_t *keyname;
308         isc_buffer_t namebuf;
309         isc_result_t result;
310         dst_key_t *dstkey = NULL;
311
312         flags = cfg_obj_asuint32(cfg_tuple_get(key, "flags"));
313         proto = cfg_obj_asuint32(cfg_tuple_get(key, "protocol"));
314         alg = cfg_obj_asuint32(cfg_tuple_get(key, "algorithm"));
315         keyname = dns_fixedname_name(&fkeyname);
316         keynamestr = cfg_obj_asstring(cfg_tuple_get(key, "name"));
317
318         if (vconfig == NULL)
319                 viewclass = dns_rdataclass_in;
320         else {
321                 const cfg_obj_t *classobj = cfg_tuple_get(vconfig, "class");
322                 CHECK(ns_config_getclass(classobj, dns_rdataclass_in,
323                                          &viewclass));
324         }
325         keystruct.common.rdclass = viewclass;
326         keystruct.common.rdtype = dns_rdatatype_dnskey;
327         /*
328          * The key data in keystruct is not dynamically allocated.
329          */
330         keystruct.mctx = NULL;
331
332         ISC_LINK_INIT(&keystruct.common, link);
333
334         if (flags > 0xffff)
335                 CHECKM(ISC_R_RANGE, "key flags");
336         if (proto > 0xff)
337                 CHECKM(ISC_R_RANGE, "key protocol");
338         if (alg > 0xff)
339                 CHECKM(ISC_R_RANGE, "key algorithm");
340         keystruct.flags = (isc_uint16_t)flags;
341         keystruct.protocol = (isc_uint8_t)proto;
342         keystruct.algorithm = (isc_uint8_t)alg;
343
344         isc_buffer_init(&keydatabuf, keydata, sizeof(keydata));
345         isc_buffer_init(&rrdatabuf, rrdata, sizeof(rrdata));
346
347         keystr = cfg_obj_asstring(cfg_tuple_get(key, "key"));
348         CHECK(isc_base64_decodestring(keystr, &keydatabuf));
349         isc_buffer_usedregion(&keydatabuf, &r);
350         keystruct.datalen = r.length;
351         keystruct.data = r.base;
352
353         if ((keystruct.algorithm == DST_ALG_RSASHA1 ||
354              keystruct.algorithm == DST_ALG_RSAMD5) &&
355             r.length > 1 && r.base[0] == 1 && r.base[1] == 3)
356                 cfg_obj_log(key, ns_g_lctx, ISC_LOG_WARNING,
357                             "trusted key '%s' has a weak exponent",
358                             keynamestr);
359
360         CHECK(dns_rdata_fromstruct(NULL,
361                                    keystruct.common.rdclass,
362                                    keystruct.common.rdtype,
363                                    &keystruct, &rrdatabuf));
364         dns_fixedname_init(&fkeyname);
365         isc_buffer_init(&namebuf, keynamestr, strlen(keynamestr));
366         isc_buffer_add(&namebuf, strlen(keynamestr));
367         CHECK(dns_name_fromtext(keyname, &namebuf,
368                                 dns_rootname, ISC_FALSE,
369                                 NULL));
370         CHECK(dst_key_fromdns(keyname, viewclass, &rrdatabuf,
371                               mctx, &dstkey));
372
373         CHECK(dns_keytable_add(keytable, &dstkey));
374         INSIST(dstkey == NULL);
375         return (ISC_R_SUCCESS);
376
377  cleanup:
378         if (result == DST_R_NOCRYPTO) {
379                 cfg_obj_log(key, ns_g_lctx, ISC_LOG_ERROR,
380                             "ignoring trusted key for '%s': no crypto support",
381                             keynamestr);
382                 result = ISC_R_SUCCESS;
383         } else {
384                 cfg_obj_log(key, ns_g_lctx, ISC_LOG_ERROR,
385                             "configuring trusted key for '%s': %s",
386                             keynamestr, isc_result_totext(result));
387                 result = ISC_R_FAILURE;
388         }
389
390         if (dstkey != NULL)
391                 dst_key_free(&dstkey);
392
393         return (result);
394 }
395
396 /*%
397  * Configure DNSSEC keys for a view.  Currently used only for
398  * the security roots.
399  *
400  * The per-view configuration values and the server-global defaults are read
401  * from 'vconfig' and 'config'.  The variable to be configured is '*target'.
402  */
403 static isc_result_t
404 configure_view_dnsseckeys(const cfg_obj_t *vconfig, const cfg_obj_t *config,
405                           isc_mem_t *mctx, dns_keytable_t **target)
406 {
407         isc_result_t result;
408         const cfg_obj_t *keys = NULL;
409         const cfg_obj_t *voptions = NULL;
410         const cfg_listelt_t *element, *element2;
411         const cfg_obj_t *keylist;
412         const cfg_obj_t *key;
413         dns_keytable_t *keytable = NULL;
414
415         CHECK(dns_keytable_create(mctx, &keytable));
416
417         if (vconfig != NULL)
418                 voptions = cfg_tuple_get(vconfig, "options");
419
420         keys = NULL;
421         if (voptions != NULL)
422                 (void)cfg_map_get(voptions, "trusted-keys", &keys);
423         if (keys == NULL)
424                 (void)cfg_map_get(config, "trusted-keys", &keys);
425
426         for (element = cfg_list_first(keys);
427              element != NULL;
428              element = cfg_list_next(element))
429         {
430                 keylist = cfg_listelt_value(element);
431                 for (element2 = cfg_list_first(keylist);
432                      element2 != NULL;
433                      element2 = cfg_list_next(element2))
434                 {
435                         key = cfg_listelt_value(element2);
436                         CHECK(configure_view_dnsseckey(vconfig, key,
437                                                        keytable, mctx));
438                 }
439         }
440
441         dns_keytable_detach(target);
442         *target = keytable; /* Transfer ownership. */
443         keytable = NULL;
444         result = ISC_R_SUCCESS;
445
446  cleanup:
447         return (result);
448 }
449
450 static isc_result_t
451 mustbesecure(const cfg_obj_t *mbs, dns_resolver_t *resolver)
452 {
453         const cfg_listelt_t *element;
454         const cfg_obj_t *obj;
455         const char *str;
456         dns_fixedname_t fixed;
457         dns_name_t *name;
458         isc_boolean_t value;
459         isc_result_t result;
460         isc_buffer_t b;
461
462         dns_fixedname_init(&fixed);
463         name = dns_fixedname_name(&fixed);
464         for (element = cfg_list_first(mbs);
465              element != NULL;
466              element = cfg_list_next(element))
467         {
468                 obj = cfg_listelt_value(element);
469                 str = cfg_obj_asstring(cfg_tuple_get(obj, "name"));
470                 isc_buffer_init(&b, str, strlen(str));
471                 isc_buffer_add(&b, strlen(str));
472                 CHECK(dns_name_fromtext(name, &b, dns_rootname,
473                                         ISC_FALSE, NULL));
474                 value = cfg_obj_asboolean(cfg_tuple_get(obj, "value"));
475                 CHECK(dns_resolver_setmustbesecure(resolver, name, value));
476         }
477
478         result = ISC_R_SUCCESS;
479
480  cleanup:
481         return (result);
482 }
483
484 /*%
485  * Get a dispatch appropriate for the resolver of a given view.
486  */
487 static isc_result_t
488 get_view_querysource_dispatch(const cfg_obj_t **maps,
489                               int af, dns_dispatch_t **dispatchp,
490                               isc_boolean_t is_firstview)
491 {
492         isc_result_t result;
493         dns_dispatch_t *disp;
494         isc_sockaddr_t sa;
495         unsigned int attrs, attrmask;
496         const cfg_obj_t *obj = NULL;
497         unsigned int maxdispatchbuffers;
498
499         /*
500          * Make compiler happy.
501          */
502         result = ISC_R_FAILURE;
503
504         switch (af) {
505         case AF_INET:
506                 result = ns_config_get(maps, "query-source", &obj);
507                 INSIST(result == ISC_R_SUCCESS);
508                 break;
509         case AF_INET6:
510                 result = ns_config_get(maps, "query-source-v6", &obj);
511                 INSIST(result == ISC_R_SUCCESS);
512                 break;
513         default:
514                 INSIST(0);
515         }
516
517         sa = *(cfg_obj_assockaddr(obj));
518         INSIST(isc_sockaddr_pf(&sa) == af);
519
520         /*
521          * If we don't support this address family, we're done!
522          */
523         switch (af) {
524         case AF_INET:
525                 result = isc_net_probeipv4();
526                 break;
527         case AF_INET6:
528                 result = isc_net_probeipv6();
529                 break;
530         default:
531                 INSIST(0);
532         }
533         if (result != ISC_R_SUCCESS)
534                 return (ISC_R_SUCCESS);
535
536         /*
537          * Try to find a dispatcher that we can share.
538          */
539         attrs = 0;
540         attrs |= DNS_DISPATCHATTR_UDP;
541         switch (af) {
542         case AF_INET:
543                 attrs |= DNS_DISPATCHATTR_IPV4;
544                 break;
545         case AF_INET6:
546                 attrs |= DNS_DISPATCHATTR_IPV6;
547                 break;
548         }
549         if (isc_sockaddr_getport(&sa) == 0) {
550                 attrs |= DNS_DISPATCHATTR_EXCLUSIVE;
551                 maxdispatchbuffers = 4096;
552         } else {
553                 INSIST(obj != NULL);
554                 if (is_firstview) {
555                         cfg_obj_log(obj, ns_g_lctx, ISC_LOG_INFO,
556                                     "using specific query-source port "
557                                     "suppresses port randomization and can be "
558                                     "insecure.");
559                 }
560                 maxdispatchbuffers = 1000;
561         }
562
563         attrmask = 0;
564         attrmask |= DNS_DISPATCHATTR_UDP;
565         attrmask |= DNS_DISPATCHATTR_TCP;
566         attrmask |= DNS_DISPATCHATTR_IPV4;
567         attrmask |= DNS_DISPATCHATTR_IPV6;
568
569         disp = NULL;
570         result = dns_dispatch_getudp(ns_g_dispatchmgr, ns_g_socketmgr,
571                                      ns_g_taskmgr, &sa, 4096,
572                                      maxdispatchbuffers, 32768, 16411, 16433,
573                                      attrs, attrmask, &disp);
574         if (result != ISC_R_SUCCESS) {
575                 isc_sockaddr_t any;
576                 char buf[ISC_SOCKADDR_FORMATSIZE];
577
578                 switch (af) {
579                 case AF_INET:
580                         isc_sockaddr_any(&any);
581                         break;
582                 case AF_INET6:
583                         isc_sockaddr_any6(&any);
584                         break;
585                 }
586                 if (isc_sockaddr_equal(&sa, &any))
587                         return (ISC_R_SUCCESS);
588                 isc_sockaddr_format(&sa, buf, sizeof(buf));
589                 isc_log_write(ns_g_lctx, NS_LOGCATEGORY_GENERAL,
590                               NS_LOGMODULE_SERVER, ISC_LOG_ERROR,
591                               "could not get query source dispatcher (%s)",
592                               buf);
593                 return (result);
594         }
595
596         *dispatchp = disp;
597
598         return (ISC_R_SUCCESS);
599 }
600
601 static isc_result_t
602 configure_order(dns_order_t *order, const cfg_obj_t *ent) {
603         dns_rdataclass_t rdclass;
604         dns_rdatatype_t rdtype;
605         const cfg_obj_t *obj;
606         dns_fixedname_t fixed;
607         unsigned int mode = 0;
608         const char *str;
609         isc_buffer_t b;
610         isc_result_t result;
611         isc_boolean_t addroot;
612
613         result = ns_config_getclass(cfg_tuple_get(ent, "class"),
614                                     dns_rdataclass_any, &rdclass);
615         if (result != ISC_R_SUCCESS)
616                 return (result);
617
618         result = ns_config_gettype(cfg_tuple_get(ent, "type"),
619                                    dns_rdatatype_any, &rdtype);
620         if (result != ISC_R_SUCCESS)
621                 return (result);
622
623         obj = cfg_tuple_get(ent, "name");
624         if (cfg_obj_isstring(obj))
625                 str = cfg_obj_asstring(obj);
626         else
627                 str = "*";
628         addroot = ISC_TF(strcmp(str, "*") == 0);
629         isc_buffer_init(&b, str, strlen(str));
630         isc_buffer_add(&b, strlen(str));
631         dns_fixedname_init(&fixed);
632         result = dns_name_fromtext(dns_fixedname_name(&fixed), &b,
633                                    dns_rootname, ISC_FALSE, NULL);
634         if (result != ISC_R_SUCCESS)
635                 return (result);
636
637         obj = cfg_tuple_get(ent, "ordering");
638         INSIST(cfg_obj_isstring(obj));
639         str = cfg_obj_asstring(obj);
640         if (!strcasecmp(str, "fixed"))
641                 mode = DNS_RDATASETATTR_FIXEDORDER;
642         else if (!strcasecmp(str, "random"))
643                 mode = DNS_RDATASETATTR_RANDOMIZE;
644         else if (!strcasecmp(str, "cyclic"))
645                 mode = 0;
646         else
647                 INSIST(0);
648
649         /*
650          * "*" should match everything including the root (BIND 8 compat).
651          * As dns_name_matcheswildcard(".", "*.") returns FALSE add a
652          * explicit entry for "." when the name is "*".
653          */
654         if (addroot) {
655                 result = dns_order_add(order, dns_rootname,
656                                        rdtype, rdclass, mode);
657                 if (result != ISC_R_SUCCESS)
658                         return (result);
659         }
660
661         return (dns_order_add(order, dns_fixedname_name(&fixed),
662                               rdtype, rdclass, mode));
663 }
664
665 static isc_result_t
666 configure_peer(const cfg_obj_t *cpeer, isc_mem_t *mctx, dns_peer_t **peerp) {
667         isc_netaddr_t na;
668         dns_peer_t *peer;
669         const cfg_obj_t *obj;
670         const char *str;
671         isc_result_t result;
672         unsigned int prefixlen;
673
674         cfg_obj_asnetprefix(cfg_map_getname(cpeer), &na, &prefixlen);
675
676         peer = NULL;
677         result = dns_peer_newprefix(mctx, &na, prefixlen, &peer);
678         if (result != ISC_R_SUCCESS)
679                 return (result);
680
681         obj = NULL;
682         (void)cfg_map_get(cpeer, "bogus", &obj);
683         if (obj != NULL)
684                 CHECK(dns_peer_setbogus(peer, cfg_obj_asboolean(obj)));
685
686         obj = NULL;
687         (void)cfg_map_get(cpeer, "provide-ixfr", &obj);
688         if (obj != NULL)
689                 CHECK(dns_peer_setprovideixfr(peer, cfg_obj_asboolean(obj)));
690
691         obj = NULL;
692         (void)cfg_map_get(cpeer, "request-ixfr", &obj);
693         if (obj != NULL)
694                 CHECK(dns_peer_setrequestixfr(peer, cfg_obj_asboolean(obj)));
695
696         obj = NULL;
697         (void)cfg_map_get(cpeer, "edns", &obj);
698         if (obj != NULL)
699                 CHECK(dns_peer_setsupportedns(peer, cfg_obj_asboolean(obj)));
700
701         obj = NULL;
702         (void)cfg_map_get(cpeer, "edns-udp-size", &obj);
703         if (obj != NULL) {
704                 isc_uint32_t udpsize = cfg_obj_asuint32(obj);
705                 if (udpsize < 512)
706                         udpsize = 512;
707                 if (udpsize > 4096)
708                         udpsize = 4096;
709                 CHECK(dns_peer_setudpsize(peer, (isc_uint16_t)udpsize));
710         }
711
712         obj = NULL;
713         (void)cfg_map_get(cpeer, "max-udp-size", &obj);
714         if (obj != NULL) {
715                 isc_uint32_t udpsize = cfg_obj_asuint32(obj);
716                 if (udpsize < 512)
717                         udpsize = 512;
718                 if (udpsize > 4096)
719                         udpsize = 4096;
720                 CHECK(dns_peer_setmaxudp(peer, (isc_uint16_t)udpsize));
721         }
722
723         obj = NULL;
724         (void)cfg_map_get(cpeer, "transfers", &obj);
725         if (obj != NULL)
726                 CHECK(dns_peer_settransfers(peer, cfg_obj_asuint32(obj)));
727
728         obj = NULL;
729         (void)cfg_map_get(cpeer, "transfer-format", &obj);
730         if (obj != NULL) {
731                 str = cfg_obj_asstring(obj);
732                 if (strcasecmp(str, "many-answers") == 0)
733                         CHECK(dns_peer_settransferformat(peer,
734                                                          dns_many_answers));
735                 else if (strcasecmp(str, "one-answer") == 0)
736                         CHECK(dns_peer_settransferformat(peer,
737                                                          dns_one_answer));
738                 else
739                         INSIST(0);
740         }
741
742         obj = NULL;
743         (void)cfg_map_get(cpeer, "keys", &obj);
744         if (obj != NULL) {
745                 result = dns_peer_setkeybycharp(peer, cfg_obj_asstring(obj));
746                 if (result != ISC_R_SUCCESS)
747                         goto cleanup;
748         }
749
750         obj = NULL;
751         if (na.family == AF_INET)
752                 (void)cfg_map_get(cpeer, "transfer-source", &obj);
753         else
754                 (void)cfg_map_get(cpeer, "transfer-source-v6", &obj);
755         if (obj != NULL) {
756                 result = dns_peer_settransfersource(peer,
757                                                     cfg_obj_assockaddr(obj));
758                 if (result != ISC_R_SUCCESS)
759                         goto cleanup;
760                 ns_add_reserved_dispatch(ns_g_server, cfg_obj_assockaddr(obj));
761         }
762
763         obj = NULL;
764         if (na.family == AF_INET)
765                 (void)cfg_map_get(cpeer, "notify-source", &obj);
766         else
767                 (void)cfg_map_get(cpeer, "notify-source-v6", &obj);
768         if (obj != NULL) {
769                 result = dns_peer_setnotifysource(peer,
770                                                   cfg_obj_assockaddr(obj));
771                 if (result != ISC_R_SUCCESS)
772                         goto cleanup;
773                 ns_add_reserved_dispatch(ns_g_server, cfg_obj_assockaddr(obj));
774         }
775
776         obj = NULL;
777         if (na.family == AF_INET)
778                 (void)cfg_map_get(cpeer, "query-source", &obj);
779         else
780                 (void)cfg_map_get(cpeer, "query-source-v6", &obj);
781         if (obj != NULL) {
782                 result = dns_peer_setquerysource(peer,
783                                                  cfg_obj_assockaddr(obj));
784                 if (result != ISC_R_SUCCESS)
785                         goto cleanup;
786                 ns_add_reserved_dispatch(ns_g_server, cfg_obj_assockaddr(obj));
787         }
788
789         *peerp = peer;
790         return (ISC_R_SUCCESS);
791
792  cleanup:
793         dns_peer_detach(&peer);
794         return (result);
795 }
796
797 static isc_result_t
798 disable_algorithms(const cfg_obj_t *disabled, dns_resolver_t *resolver) {
799         isc_result_t result;
800         const cfg_obj_t *algorithms;
801         const cfg_listelt_t *element;
802         const char *str;
803         dns_fixedname_t fixed;
804         dns_name_t *name;
805         isc_buffer_t b;
806
807         dns_fixedname_init(&fixed);
808         name = dns_fixedname_name(&fixed);
809         str = cfg_obj_asstring(cfg_tuple_get(disabled, "name"));
810         isc_buffer_init(&b, str, strlen(str));
811         isc_buffer_add(&b, strlen(str));
812         CHECK(dns_name_fromtext(name, &b, dns_rootname, ISC_FALSE, NULL));
813
814         algorithms = cfg_tuple_get(disabled, "algorithms");
815         for (element = cfg_list_first(algorithms);
816              element != NULL;
817              element = cfg_list_next(element))
818         {
819                 isc_textregion_t r;
820                 dns_secalg_t alg;
821
822                 DE_CONST(cfg_obj_asstring(cfg_listelt_value(element)), r.base);
823                 r.length = strlen(r.base);
824
825                 result = dns_secalg_fromtext(&alg, &r);
826                 if (result != ISC_R_SUCCESS) {
827                         isc_uint8_t ui;
828                         result = isc_parse_uint8(&ui, r.base, 10);
829                         alg = ui;
830                 }
831                 if (result != ISC_R_SUCCESS) {
832                         cfg_obj_log(cfg_listelt_value(element),
833                                     ns_g_lctx, ISC_LOG_ERROR,
834                                     "invalid algorithm");
835                         CHECK(result);
836                 }
837                 CHECK(dns_resolver_disable_algorithm(resolver, name, alg));
838         }
839  cleanup:
840         return (result);
841 }
842
843 static isc_boolean_t
844 on_disable_list(const cfg_obj_t *disablelist, dns_name_t *zonename) {
845         const cfg_listelt_t *element;
846         dns_fixedname_t fixed;
847         dns_name_t *name;
848         isc_result_t result;
849         const cfg_obj_t *value;
850         const char *str;
851         isc_buffer_t b;
852
853         dns_fixedname_init(&fixed);
854         name = dns_fixedname_name(&fixed);
855
856         for (element = cfg_list_first(disablelist);
857              element != NULL;
858              element = cfg_list_next(element))
859         {
860                 value = cfg_listelt_value(element);
861                 str = cfg_obj_asstring(value);
862                 isc_buffer_init(&b, str, strlen(str));
863                 isc_buffer_add(&b, strlen(str));
864                 result = dns_name_fromtext(name, &b, dns_rootname,
865                                            ISC_TRUE, NULL);
866                 RUNTIME_CHECK(result == ISC_R_SUCCESS);
867                 if (dns_name_equal(name, zonename))
868                         return (ISC_TRUE);
869         }
870         return (ISC_FALSE);
871 }
872
873 static void
874 check_dbtype(dns_zone_t **zonep, unsigned int dbtypec, const char **dbargv,
875              isc_mem_t *mctx)
876 {
877         char **argv = NULL;
878         unsigned int i;
879         isc_result_t result;
880
881         result = dns_zone_getdbtype(*zonep, &argv, mctx);
882         if (result != ISC_R_SUCCESS) {
883                 dns_zone_detach(zonep);
884                 return;
885         }
886
887         /*
888          * Check that all the arguments match.
889          */
890         for (i = 0; i < dbtypec; i++)
891                 if (argv[i] == NULL || strcmp(argv[i], dbargv[i]) != 0) {
892                         dns_zone_detach(zonep);
893                         break;
894                 }
895
896         /*
897          * Check that there are not extra arguments.
898          */
899         if (i == dbtypec && argv[i] != NULL)
900                 dns_zone_detach(zonep);
901         isc_mem_free(mctx, argv);
902 }
903
904
905 /*
906  * Configure 'view' according to 'vconfig', taking defaults from 'config'
907  * where values are missing in 'vconfig'.
908  *
909  * When configuring the default view, 'vconfig' will be NULL and the
910  * global defaults in 'config' used exclusively.
911  */
912 static isc_result_t
913 configure_view(dns_view_t *view, const cfg_obj_t *config,
914                const cfg_obj_t *vconfig, isc_mem_t *mctx,
915                cfg_aclconfctx_t *actx, isc_boolean_t need_hints)
916 {
917         const cfg_obj_t *maps[4];
918         const cfg_obj_t *cfgmaps[3];
919         const cfg_obj_t *options = NULL;
920         const cfg_obj_t *voptions = NULL;
921         const cfg_obj_t *forwardtype;
922         const cfg_obj_t *forwarders;
923         const cfg_obj_t *alternates;
924         const cfg_obj_t *zonelist;
925 #ifdef DLZ
926         const cfg_obj_t *dlz;
927         unsigned int dlzargc;
928         char **dlzargv;
929 #endif
930         const cfg_obj_t *disabled;
931         const cfg_obj_t *obj;
932         const cfg_listelt_t *element;
933         in_port_t port;
934         dns_cache_t *cache = NULL;
935         isc_result_t result;
936         isc_uint32_t max_adb_size;
937         isc_uint32_t max_cache_size;
938         isc_uint32_t max_acache_size;
939         isc_uint32_t lame_ttl;
940         dns_tsig_keyring_t *ring;
941         dns_view_t *pview = NULL;       /* Production view */
942         isc_mem_t *cmctx;
943         dns_dispatch_t *dispatch4 = NULL;
944         dns_dispatch_t *dispatch6 = NULL;
945         isc_boolean_t reused_cache = ISC_FALSE;
946         int i;
947         const char *str;
948         dns_order_t *order = NULL;
949         isc_uint32_t udpsize;
950         unsigned int check = 0;
951         dns_zone_t *zone = NULL;
952         isc_uint32_t max_clients_per_query;
953         const char *sep = ": view ";
954         const char *viewname = view->name;
955         const char *forview = " for view ";
956         isc_boolean_t rfc1918;
957         isc_boolean_t empty_zones_enable;
958         const cfg_obj_t *disablelist = NULL;
959
960         REQUIRE(DNS_VIEW_VALID(view));
961
962         cmctx = NULL;
963
964         if (config != NULL)
965                 (void)cfg_map_get(config, "options", &options);
966
967         i = 0;
968         if (vconfig != NULL) {
969                 voptions = cfg_tuple_get(vconfig, "options");
970                 maps[i++] = voptions;
971         }
972         if (options != NULL)
973                 maps[i++] = options;
974         maps[i++] = ns_g_defaults;
975         maps[i] = NULL;
976
977         i = 0;
978         if (voptions != NULL)
979                 cfgmaps[i++] = voptions;
980         if (config != NULL)
981                 cfgmaps[i++] = config;
982         cfgmaps[i] = NULL;
983
984         if (!strcmp(viewname, "_default")) {
985                 sep = "";
986                 viewname = "";
987                 forview = "";
988         }
989
990         /*
991          * Set the view's port number for outgoing queries.
992          */
993         CHECKM(ns_config_getport(config, &port), "port");
994         dns_view_setdstport(view, port);
995
996         /*
997          * Create additional cache for this view and zones under the view
998          * if explicitly enabled.
999          * XXX950 default to on.
1000          */
1001         obj = NULL;
1002         (void)ns_config_get(maps, "acache-enable", &obj);
1003         if (obj != NULL && cfg_obj_asboolean(obj)) {
1004                 cmctx = NULL;
1005                 CHECK(isc_mem_create(0, 0, &cmctx));
1006                 CHECK(dns_acache_create(&view->acache, cmctx, ns_g_taskmgr,
1007                                         ns_g_timermgr));
1008                 isc_mem_detach(&cmctx);
1009         }
1010         if (view->acache != NULL) {
1011                 obj = NULL;
1012                 result = ns_config_get(maps, "acache-cleaning-interval", &obj);
1013                 INSIST(result == ISC_R_SUCCESS);
1014                 dns_acache_setcleaninginterval(view->acache,
1015                                                cfg_obj_asuint32(obj) * 60);
1016
1017                 obj = NULL;
1018                 result = ns_config_get(maps, "max-acache-size", &obj);
1019                 INSIST(result == ISC_R_SUCCESS);
1020                 if (cfg_obj_isstring(obj)) {
1021                         str = cfg_obj_asstring(obj);
1022                         INSIST(strcasecmp(str, "unlimited") == 0);
1023                         max_acache_size = ISC_UINT32_MAX;
1024                 } else {
1025                         isc_resourcevalue_t value;
1026
1027                         value = cfg_obj_asuint64(obj);
1028                         if (value > ISC_UINT32_MAX) {
1029                                 cfg_obj_log(obj, ns_g_lctx, ISC_LOG_ERROR,
1030                                             "'max-acache-size "
1031                                             "%" ISC_PRINT_QUADFORMAT
1032                                             "d' is too large",
1033                                             value);
1034                                 result = ISC_R_RANGE;
1035                                 goto cleanup;
1036                         }
1037                         max_acache_size = (isc_uint32_t)value;
1038                 }
1039                 dns_acache_setcachesize(view->acache, max_acache_size);
1040         }
1041
1042         /*
1043          * Configure the zones.
1044          */
1045         zonelist = NULL;
1046         if (voptions != NULL)
1047                 (void)cfg_map_get(voptions, "zone", &zonelist);
1048         else
1049                 (void)cfg_map_get(config, "zone", &zonelist);
1050         for (element = cfg_list_first(zonelist);
1051              element != NULL;
1052              element = cfg_list_next(element))
1053         {
1054                 const cfg_obj_t *zconfig = cfg_listelt_value(element);
1055                 CHECK(configure_zone(config, zconfig, vconfig, mctx, view,
1056                                      actx));
1057         }
1058
1059 #ifdef DLZ
1060         /*
1061          * Create Dynamically Loadable Zone driver.
1062          */
1063         dlz = NULL;
1064         if (voptions != NULL)
1065                 (void)cfg_map_get(voptions, "dlz", &dlz);
1066         else
1067                 (void)cfg_map_get(config, "dlz", &dlz);
1068
1069         obj = NULL;
1070         if (dlz != NULL) {
1071                 (void)cfg_map_get(cfg_tuple_get(dlz, "options"),
1072                                   "database", &obj);
1073                 if (obj != NULL) {
1074                         char *s = isc_mem_strdup(mctx, cfg_obj_asstring(obj));
1075                         if (s == NULL) {
1076                                 result = ISC_R_NOMEMORY;
1077                                 goto cleanup;
1078                         }
1079
1080                         result = dns_dlzstrtoargv(mctx, s, &dlzargc, &dlzargv);
1081                         if (result != ISC_R_SUCCESS) {
1082                                 isc_mem_free(mctx, s);
1083                                 goto cleanup;
1084                         }
1085
1086                         obj = cfg_tuple_get(dlz, "name");
1087                         result = dns_dlzcreate(mctx, cfg_obj_asstring(obj),
1088                                                dlzargv[0], dlzargc, dlzargv,
1089                                                &view->dlzdatabase);
1090                         isc_mem_free(mctx, s);
1091                         isc_mem_put(mctx, dlzargv, dlzargc * sizeof(*dlzargv));
1092                         if (result != ISC_R_SUCCESS)
1093                                 goto cleanup;
1094                 }
1095         }
1096 #endif
1097
1098         /*
1099          * Configure the view's cache.  Try to reuse an existing
1100          * cache if possible, otherwise create a new cache.
1101          * Note that the ADB is not preserved in either case.
1102          *
1103          * XXX Determining when it is safe to reuse a cache is
1104          * tricky.  When the view's configuration changes, the cached
1105          * data may become invalid because it reflects our old
1106          * view of the world.  As more view attributes become
1107          * configurable, we will have to add code here to check
1108          * whether they have changed in ways that could
1109          * invalidate the cache.
1110          */
1111         result = dns_viewlist_find(&ns_g_server->viewlist,
1112                                    view->name, view->rdclass,
1113                                    &pview);
1114         if (result != ISC_R_NOTFOUND && result != ISC_R_SUCCESS)
1115                 goto cleanup;
1116         if (pview != NULL) {
1117                 INSIST(pview->cache != NULL);
1118                 isc_log_write(ns_g_lctx, NS_LOGCATEGORY_GENERAL,
1119                               NS_LOGMODULE_SERVER, ISC_LOG_DEBUG(3),
1120                               "reusing existing cache");
1121                 reused_cache = ISC_TRUE;
1122                 dns_cache_attach(pview->cache, &cache);
1123                 dns_view_detach(&pview);
1124         } else {
1125                 CHECK(isc_mem_create(0, 0, &cmctx));
1126                 CHECK(dns_cache_create(cmctx, ns_g_taskmgr, ns_g_timermgr,
1127                                        view->rdclass, "rbt", 0, NULL, &cache));
1128         }
1129         dns_view_setcache(view, cache);
1130
1131         /*
1132          * cache-file cannot be inherited if views are present, but this
1133          * should be caught by the configuration checking stage.
1134          */
1135         obj = NULL;
1136         result = ns_config_get(maps, "cache-file", &obj);
1137         if (result == ISC_R_SUCCESS && strcmp(view->name, "_bind") != 0) {
1138                 CHECK(dns_cache_setfilename(cache, cfg_obj_asstring(obj)));
1139                 if (!reused_cache)
1140                         CHECK(dns_cache_load(cache));
1141         }
1142
1143         obj = NULL;
1144         result = ns_config_get(maps, "cleaning-interval", &obj);
1145         INSIST(result == ISC_R_SUCCESS);
1146         dns_cache_setcleaninginterval(cache, cfg_obj_asuint32(obj) * 60);
1147
1148         obj = NULL;
1149         result = ns_config_get(maps, "max-cache-size", &obj);
1150         INSIST(result == ISC_R_SUCCESS);
1151         if (cfg_obj_isstring(obj)) {
1152                 str = cfg_obj_asstring(obj);
1153                 INSIST(strcasecmp(str, "unlimited") == 0);
1154                 max_cache_size = ISC_UINT32_MAX;
1155         } else {
1156                 isc_resourcevalue_t value;
1157                 value = cfg_obj_asuint64(obj);
1158                 if (value > ISC_UINT32_MAX) {
1159                         cfg_obj_log(obj, ns_g_lctx, ISC_LOG_ERROR,
1160                                     "'max-cache-size "
1161                                     "%" ISC_PRINT_QUADFORMAT "d' is too large",
1162                                     value);
1163                         result = ISC_R_RANGE;
1164                         goto cleanup;
1165                 }
1166                 max_cache_size = (isc_uint32_t)value;
1167         }
1168         dns_cache_setcachesize(cache, max_cache_size);
1169
1170         dns_cache_detach(&cache);
1171
1172         /*
1173          * Check-names.
1174          */
1175         obj = NULL;
1176         result = ns_checknames_get(maps, "response", &obj);
1177         INSIST(result == ISC_R_SUCCESS);
1178
1179         str = cfg_obj_asstring(obj);
1180         if (strcasecmp(str, "fail") == 0) {
1181                 check = DNS_RESOLVER_CHECKNAMES |
1182                         DNS_RESOLVER_CHECKNAMESFAIL;
1183                 view->checknames = ISC_TRUE;
1184         } else if (strcasecmp(str, "warn") == 0) {
1185                 check = DNS_RESOLVER_CHECKNAMES;
1186                 view->checknames = ISC_FALSE;
1187         } else if (strcasecmp(str, "ignore") == 0) {
1188                 check = 0;
1189                 view->checknames = ISC_FALSE;
1190         } else
1191                 INSIST(0);
1192
1193         /*
1194          * Resolver.
1195          *
1196          * XXXRTH  Hardwired number of tasks.
1197          */
1198         CHECK(get_view_querysource_dispatch(maps, AF_INET, &dispatch4,
1199                                             ISC_TF(ISC_LIST_PREV(view, link)
1200                                                    == NULL)));
1201         CHECK(get_view_querysource_dispatch(maps, AF_INET6, &dispatch6,
1202                                             ISC_TF(ISC_LIST_PREV(view, link)
1203                                                    == NULL)));
1204         if (dispatch4 == NULL && dispatch6 == NULL) {
1205                 UNEXPECTED_ERROR(__FILE__, __LINE__,
1206                                  "unable to obtain neither an IPv4 nor"
1207                                  " an IPv6 dispatch");
1208                 result = ISC_R_UNEXPECTED;
1209                 goto cleanup;
1210         }
1211         CHECK(dns_view_createresolver(view, ns_g_taskmgr, 31,
1212                                       ns_g_socketmgr, ns_g_timermgr,
1213                                       check, ns_g_dispatchmgr,
1214                                       dispatch4, dispatch6));
1215
1216         /*
1217          * Set the ADB cache size to 1/8th of the max-cache-size.
1218          */
1219         max_adb_size = 0;
1220         if (max_cache_size != 0) {
1221                 max_adb_size = max_cache_size / 8;
1222                 if (max_adb_size == 0)
1223                         max_adb_size = 1;       /* Force minimum. */
1224         }
1225         dns_adb_setadbsize(view->adb, max_adb_size);
1226
1227         /*
1228          * Set resolver's lame-ttl.
1229          */
1230         obj = NULL;
1231         result = ns_config_get(maps, "lame-ttl", &obj);
1232         INSIST(result == ISC_R_SUCCESS);
1233         lame_ttl = cfg_obj_asuint32(obj);
1234         if (lame_ttl > 1800)
1235                 lame_ttl = 1800;
1236         dns_resolver_setlamettl(view->resolver, lame_ttl);
1237
1238         obj = NULL;
1239         result = ns_config_get(maps, "zero-no-soa-ttl-cache", &obj);
1240         INSIST(result == ISC_R_SUCCESS);
1241         dns_resolver_setzeronosoattl(view->resolver, cfg_obj_asboolean(obj));
1242
1243         /*
1244          * Set the resolver's EDNS UDP size.
1245          */
1246         obj = NULL;
1247         result = ns_config_get(maps, "edns-udp-size", &obj);
1248         INSIST(result == ISC_R_SUCCESS);
1249         udpsize = cfg_obj_asuint32(obj);
1250         if (udpsize < 512)
1251                 udpsize = 512;
1252         if (udpsize > 4096)
1253                 udpsize = 4096;
1254         dns_resolver_setudpsize(view->resolver, (isc_uint16_t)udpsize);
1255
1256         /*
1257          * Set the maximum UDP response size.
1258          */
1259         obj = NULL;
1260         result = ns_config_get(maps, "max-udp-size", &obj);
1261         INSIST(result == ISC_R_SUCCESS);
1262         udpsize = cfg_obj_asuint32(obj);
1263         if (udpsize < 512)
1264                 udpsize = 512;
1265         if (udpsize > 4096)
1266                 udpsize = 4096;
1267         view->maxudp = udpsize;
1268
1269         /*
1270          * Set supported DNSSEC algorithms.
1271          */
1272         dns_resolver_reset_algorithms(view->resolver);
1273         disabled = NULL;
1274         (void)ns_config_get(maps, "disable-algorithms", &disabled);
1275         if (disabled != NULL) {
1276                 for (element = cfg_list_first(disabled);
1277                      element != NULL;
1278                      element = cfg_list_next(element))
1279                         CHECK(disable_algorithms(cfg_listelt_value(element),
1280                                                  view->resolver));
1281         }
1282
1283         /*
1284          * A global or view "forwarders" option, if present,
1285          * creates an entry for "." in the forwarding table.
1286          */
1287         forwardtype = NULL;
1288         forwarders = NULL;
1289         (void)ns_config_get(maps, "forward", &forwardtype);
1290         (void)ns_config_get(maps, "forwarders", &forwarders);
1291         if (forwarders != NULL)
1292                 CHECK(configure_forward(config, view, dns_rootname,
1293                                         forwarders, forwardtype));
1294
1295         /*
1296          * Dual Stack Servers.
1297          */
1298         alternates = NULL;
1299         (void)ns_config_get(maps, "dual-stack-servers", &alternates);
1300         if (alternates != NULL)
1301                 CHECK(configure_alternates(config, view, alternates));
1302
1303         /*
1304          * We have default hints for class IN if we need them.
1305          */
1306         if (view->rdclass == dns_rdataclass_in && view->hints == NULL)
1307                 dns_view_sethints(view, ns_g_server->in_roothints);
1308
1309         /*
1310          * If we still have no hints, this is a non-IN view with no
1311          * "hints zone" configured.  Issue a warning, except if this
1312          * is a root server.  Root servers never need to consult
1313          * their hints, so it's no point requiring users to configure
1314          * them.
1315          */
1316         if (view->hints == NULL) {
1317                 dns_zone_t *rootzone = NULL;
1318                 (void)dns_view_findzone(view, dns_rootname, &rootzone);
1319                 if (rootzone != NULL) {
1320                         dns_zone_detach(&rootzone);
1321                         need_hints = ISC_FALSE;
1322                 }
1323                 if (need_hints)
1324                         isc_log_write(ns_g_lctx, NS_LOGCATEGORY_GENERAL,
1325                                       NS_LOGMODULE_SERVER, ISC_LOG_WARNING,
1326                                       "no root hints for view '%s'",
1327                                       view->name);
1328         }
1329
1330         /*
1331          * Configure the view's TSIG keys.
1332          */
1333         ring = NULL;
1334         CHECK(ns_tsigkeyring_fromconfig(config, vconfig, view->mctx, &ring));
1335         dns_view_setkeyring(view, ring);
1336
1337         /*
1338          * Configure the view's peer list.
1339          */
1340         {
1341                 const cfg_obj_t *peers = NULL;
1342                 const cfg_listelt_t *element;
1343                 dns_peerlist_t *newpeers = NULL;
1344
1345                 (void)ns_config_get(cfgmaps, "server", &peers);
1346                 CHECK(dns_peerlist_new(mctx, &newpeers));
1347                 for (element = cfg_list_first(peers);
1348                      element != NULL;
1349                      element = cfg_list_next(element))
1350                 {
1351                         const cfg_obj_t *cpeer = cfg_listelt_value(element);
1352                         dns_peer_t *peer;
1353
1354                         CHECK(configure_peer(cpeer, mctx, &peer));
1355                         dns_peerlist_addpeer(newpeers, peer);
1356                         dns_peer_detach(&peer);
1357                 }
1358                 dns_peerlist_detach(&view->peers);
1359                 view->peers = newpeers; /* Transfer ownership. */
1360         }
1361
1362         /*
1363          *      Configure the views rrset-order.
1364          */
1365         {
1366                 const cfg_obj_t *rrsetorder = NULL;
1367                 const cfg_listelt_t *element;
1368
1369                 (void)ns_config_get(maps, "rrset-order", &rrsetorder);
1370                 CHECK(dns_order_create(mctx, &order));
1371                 for (element = cfg_list_first(rrsetorder);
1372                      element != NULL;
1373                      element = cfg_list_next(element))
1374                 {
1375                         const cfg_obj_t *ent = cfg_listelt_value(element);
1376
1377                         CHECK(configure_order(order, ent));
1378                 }
1379                 if (view->order != NULL)
1380                         dns_order_detach(&view->order);
1381                 dns_order_attach(order, &view->order);
1382                 dns_order_detach(&order);
1383         }
1384         /*
1385          * Copy the aclenv object.
1386          */
1387         dns_aclenv_copy(&view->aclenv, &ns_g_server->aclenv);
1388
1389         /*
1390          * Configure the "match-clients" and "match-destinations" ACL.
1391          */
1392         CHECK(configure_view_acl(vconfig, config, "match-clients", actx,
1393                                  ns_g_mctx, &view->matchclients));
1394         CHECK(configure_view_acl(vconfig, config, "match-destinations", actx,
1395                                  ns_g_mctx, &view->matchdestinations));
1396
1397         /*
1398          * Configure the "match-recursive-only" option.
1399          */
1400         obj = NULL;
1401         (void)ns_config_get(maps, "match-recursive-only", &obj);
1402         if (obj != NULL && cfg_obj_asboolean(obj))
1403                 view->matchrecursiveonly = ISC_TRUE;
1404         else
1405                 view->matchrecursiveonly = ISC_FALSE;
1406
1407         /*
1408          * Configure other configurable data.
1409          */
1410         obj = NULL;
1411         result = ns_config_get(maps, "recursion", &obj);
1412         INSIST(result == ISC_R_SUCCESS);
1413         view->recursion = cfg_obj_asboolean(obj);
1414
1415         obj = NULL;
1416         result = ns_config_get(maps, "auth-nxdomain", &obj);
1417         INSIST(result == ISC_R_SUCCESS);
1418         view->auth_nxdomain = cfg_obj_asboolean(obj);
1419
1420         obj = NULL;
1421         result = ns_config_get(maps, "minimal-responses", &obj);
1422         INSIST(result == ISC_R_SUCCESS);
1423         view->minimalresponses = cfg_obj_asboolean(obj);
1424
1425         obj = NULL;
1426         result = ns_config_get(maps, "transfer-format", &obj);
1427         INSIST(result == ISC_R_SUCCESS);
1428         str = cfg_obj_asstring(obj);
1429         if (strcasecmp(str, "many-answers") == 0)
1430                 view->transfer_format = dns_many_answers;
1431         else if (strcasecmp(str, "one-answer") == 0)
1432                 view->transfer_format = dns_one_answer;
1433         else
1434                 INSIST(0);
1435
1436         /*
1437          * Set sources where additional data and CNAME/DNAME
1438          * targets for authoritative answers may be found.
1439          */
1440         obj = NULL;
1441         result = ns_config_get(maps, "additional-from-auth", &obj);
1442         INSIST(result == ISC_R_SUCCESS);
1443         view->additionalfromauth = cfg_obj_asboolean(obj);
1444         if (view->recursion && ! view->additionalfromauth) {
1445                 cfg_obj_log(obj, ns_g_lctx, ISC_LOG_WARNING,
1446                             "'additional-from-auth no' is only supported "
1447                             "with 'recursion no'");
1448                 view->additionalfromauth = ISC_TRUE;
1449         }
1450
1451         obj = NULL;
1452         result = ns_config_get(maps, "additional-from-cache", &obj);
1453         INSIST(result == ISC_R_SUCCESS);
1454         view->additionalfromcache = cfg_obj_asboolean(obj);
1455         if (view->recursion && ! view->additionalfromcache) {
1456                 cfg_obj_log(obj, ns_g_lctx, ISC_LOG_WARNING,
1457                             "'additional-from-cache no' is only supported "
1458                             "with 'recursion no'");
1459                 view->additionalfromcache = ISC_TRUE;
1460         }
1461
1462         /*
1463          * Set "allow-query-cache" and "allow-recursion" acls if
1464          * configured in named.conf.
1465          */
1466         CHECK(configure_view_acl(vconfig, config, "allow-query-cache",
1467                                  actx, ns_g_mctx, &view->queryacl));
1468
1469         if (strcmp(view->name, "_bind") != 0)
1470                 CHECK(configure_view_acl(vconfig, config, "allow-recursion",
1471                                          actx, ns_g_mctx, &view->recursionacl));
1472
1473         /*
1474          * Warning if both "recursion no;" and allow-recursion are active
1475          * except for "allow-recursion { none; };".
1476          */
1477         if (!view->recursion && view->recursionacl != NULL &&
1478             (view->recursionacl->length != 1 ||
1479              view->recursionacl->elements[0].type != dns_aclelementtype_any ||
1480              view->recursionacl->elements[0].negative != ISC_TRUE))
1481                 isc_log_write(ns_g_lctx, NS_LOGCATEGORY_GENERAL,
1482                               NS_LOGMODULE_SERVER, ISC_LOG_WARNING,
1483                               "both \"recursion no;\" and \"allow-recursion\" "
1484                               "active%s%s", forview, viewname);
1485
1486         /*
1487          * "allow-query-cache" inherits from "allow-recursion" if set,
1488          * otherwise from "allow-query" if set.
1489          * "allow-recursion" inherits from "allow-query-cache" if set,
1490          * otherwise from "allow-query" if set.
1491          */
1492         if (view->queryacl == NULL && view->recursionacl != NULL)
1493                 dns_acl_attach(view->recursionacl, &view->queryacl);
1494         if (view->queryacl == NULL)
1495                 CHECK(configure_view_acl(vconfig, config, "allow-query",
1496                                          actx, ns_g_mctx, &view->queryacl));
1497         if (view->recursionacl == NULL && view->queryacl != NULL)
1498                 dns_acl_attach(view->queryacl, &view->recursionacl);
1499
1500         /*
1501          * Set default "allow-recursion" and "allow-query-cache" acls.
1502          */
1503         if (view->recursionacl == NULL && view->recursion)
1504                 CHECK(configure_view_acl(NULL, ns_g_config, "allow-recursion",
1505                                          actx, ns_g_mctx, &view->recursionacl));
1506         if (view->queryacl == NULL)
1507                 CHECK(configure_view_acl(NULL, ns_g_config,
1508                                          "allow-query-cache", actx,
1509                                          ns_g_mctx, &view->queryacl));
1510
1511         CHECK(configure_view_acl(vconfig, config, "sortlist",
1512                                  actx, ns_g_mctx, &view->sortlist));
1513
1514         obj = NULL;
1515         result = ns_config_get(maps, "request-ixfr", &obj);
1516         INSIST(result == ISC_R_SUCCESS);
1517         view->requestixfr = cfg_obj_asboolean(obj);
1518
1519         obj = NULL;
1520         result = ns_config_get(maps, "provide-ixfr", &obj);
1521         INSIST(result == ISC_R_SUCCESS);
1522         view->provideixfr = cfg_obj_asboolean(obj);
1523
1524         obj = NULL;
1525         result = ns_config_get(maps, "max-clients-per-query", &obj);
1526         INSIST(result == ISC_R_SUCCESS);
1527         max_clients_per_query = cfg_obj_asuint32(obj);
1528
1529         obj = NULL;
1530         result = ns_config_get(maps, "clients-per-query", &obj);
1531         INSIST(result == ISC_R_SUCCESS);
1532         dns_resolver_setclientsperquery(view->resolver,
1533                                         cfg_obj_asuint32(obj),
1534                                         max_clients_per_query);
1535
1536         obj = NULL;
1537         result = ns_config_get(maps, "dnssec-enable", &obj);
1538         INSIST(result == ISC_R_SUCCESS);
1539         view->enablednssec = cfg_obj_asboolean(obj);
1540
1541         obj = NULL;
1542         result = ns_config_get(maps, "dnssec-accept-expired", &obj);
1543         INSIST(result == ISC_R_SUCCESS);
1544         view->acceptexpired = cfg_obj_asboolean(obj);
1545
1546         obj = NULL;
1547         result = ns_config_get(maps, "dnssec-validation", &obj);
1548         INSIST(result == ISC_R_SUCCESS);
1549         view->enablevalidation = cfg_obj_asboolean(obj);
1550
1551         obj = NULL;
1552         result = ns_config_get(maps, "dnssec-lookaside", &obj);
1553         if (result == ISC_R_SUCCESS) {
1554                 for (element = cfg_list_first(obj);
1555                      element != NULL;
1556                      element = cfg_list_next(element))
1557                 {
1558                         const char *str;
1559                         isc_buffer_t b;
1560                         dns_name_t *dlv;
1561
1562                         obj = cfg_listelt_value(element);
1563 #if 0
1564                         dns_fixedname_t fixed;
1565                         dns_name_t *name;
1566
1567                         /*
1568                          * When we support multiple dnssec-lookaside
1569                          * entries this is how to find the domain to be
1570                          * checked. XXXMPA
1571                          */
1572                         dns_fixedname_init(&fixed);
1573                         name = dns_fixedname_name(&fixed);
1574                         str = cfg_obj_asstring(cfg_tuple_get(obj,
1575                                                              "domain"));
1576                         isc_buffer_init(&b, str, strlen(str));
1577                         isc_buffer_add(&b, strlen(str));
1578                         CHECK(dns_name_fromtext(name, &b, dns_rootname,
1579                                                 ISC_TRUE, NULL));
1580 #endif
1581                         str = cfg_obj_asstring(cfg_tuple_get(obj,
1582                                                              "trust-anchor"));
1583                         isc_buffer_init(&b, str, strlen(str));
1584                         isc_buffer_add(&b, strlen(str));
1585                         dlv = dns_fixedname_name(&view->dlv_fixed);
1586                         CHECK(dns_name_fromtext(dlv, &b, dns_rootname,
1587                                                 ISC_TRUE, NULL));
1588                         view->dlv = dns_fixedname_name(&view->dlv_fixed);
1589                 }
1590         } else
1591                 view->dlv = NULL;
1592
1593         /*
1594          * For now, there is only one kind of trusted keys, the
1595          * "security roots".
1596          */
1597         CHECK(configure_view_dnsseckeys(vconfig, config, mctx,
1598                                         &view->secroots));
1599         dns_resolver_resetmustbesecure(view->resolver);
1600         obj = NULL;
1601         result = ns_config_get(maps, "dnssec-must-be-secure", &obj);
1602         if (result == ISC_R_SUCCESS)
1603                 CHECK(mustbesecure(obj, view->resolver));
1604
1605         obj = NULL;
1606         result = ns_config_get(maps, "max-cache-ttl", &obj);
1607         INSIST(result == ISC_R_SUCCESS);
1608         view->maxcachettl = cfg_obj_asuint32(obj);
1609
1610         obj = NULL;
1611         result = ns_config_get(maps, "max-ncache-ttl", &obj);
1612         INSIST(result == ISC_R_SUCCESS);
1613         view->maxncachettl = cfg_obj_asuint32(obj);
1614         if (view->maxncachettl > 7 * 24 * 3600)
1615                 view->maxncachettl = 7 * 24 * 3600;
1616
1617         obj = NULL;
1618         result = ns_config_get(maps, "preferred-glue", &obj);
1619         if (result == ISC_R_SUCCESS) {
1620                 str = cfg_obj_asstring(obj);
1621                 if (strcasecmp(str, "a") == 0)
1622                         view->preferred_glue = dns_rdatatype_a;
1623                 else if (strcasecmp(str, "aaaa") == 0)
1624                         view->preferred_glue = dns_rdatatype_aaaa;
1625                 else
1626                         view->preferred_glue = 0;
1627         } else
1628                 view->preferred_glue = 0;
1629
1630         obj = NULL;
1631         result = ns_config_get(maps, "root-delegation-only", &obj);
1632         if (result == ISC_R_SUCCESS) {
1633                 dns_view_setrootdelonly(view, ISC_TRUE);
1634                 if (!cfg_obj_isvoid(obj)) {
1635                         dns_fixedname_t fixed;
1636                         dns_name_t *name;
1637                         isc_buffer_t b;
1638                         const char *str;
1639                         const cfg_obj_t *exclude;
1640
1641                         dns_fixedname_init(&fixed);
1642                         name = dns_fixedname_name(&fixed);
1643                         for (element = cfg_list_first(obj);
1644                              element != NULL;
1645                              element = cfg_list_next(element)) {
1646                                 exclude = cfg_listelt_value(element);
1647                                 str = cfg_obj_asstring(exclude);
1648                                 isc_buffer_init(&b, str, strlen(str));
1649                                 isc_buffer_add(&b, strlen(str));
1650                                 CHECK(dns_name_fromtext(name, &b, dns_rootname,
1651                                                         ISC_FALSE, NULL));
1652                                 CHECK(dns_view_excludedelegationonly(view,
1653                                                                      name));
1654                         }
1655                 }
1656         } else
1657                 dns_view_setrootdelonly(view, ISC_FALSE);
1658
1659         /*
1660          * Setup automatic empty zones.  If recursion is off then
1661          * they are disabled by default.
1662          */
1663         obj = NULL;
1664         (void)ns_config_get(maps, "empty-zones-enable", &obj);
1665         (void)ns_config_get(maps, "disable-empty-zone", &disablelist);
1666         if (obj == NULL && disablelist == NULL &&
1667             view->rdclass == dns_rdataclass_in) {
1668                 rfc1918 = ISC_FALSE;
1669                 empty_zones_enable = view->recursion;
1670         } else if (view->rdclass == dns_rdataclass_in) {
1671                 rfc1918 = ISC_TRUE;
1672                 if (obj != NULL)
1673                         empty_zones_enable = cfg_obj_asboolean(obj);
1674                 else
1675                         empty_zones_enable = view->recursion;
1676         } else {
1677                 rfc1918 = ISC_FALSE;
1678                 empty_zones_enable = ISC_FALSE;
1679         }
1680         if (empty_zones_enable) {
1681                 const char *empty;
1682                 int empty_zone = 0;
1683                 dns_fixedname_t fixed;
1684                 dns_name_t *name;
1685                 isc_buffer_t buffer;
1686                 const char *str;
1687                 char server[DNS_NAME_FORMATSIZE + 1];
1688                 char contact[DNS_NAME_FORMATSIZE + 1];
1689                 isc_boolean_t logit;
1690                 const char *empty_dbtype[4] =
1691                                     { "_builtin", "empty", NULL, NULL };
1692                 int empty_dbtypec = 4;
1693
1694                 dns_fixedname_init(&fixed);
1695                 name = dns_fixedname_name(&fixed);
1696
1697                 obj = NULL;
1698                 result = ns_config_get(maps, "empty-server", &obj);
1699                 if (result == ISC_R_SUCCESS) {
1700                         str = cfg_obj_asstring(obj);
1701                         isc_buffer_init(&buffer, str, strlen(str));
1702                         isc_buffer_add(&buffer, strlen(str));
1703                         CHECK(dns_name_fromtext(name, &buffer, dns_rootname,
1704                                                 ISC_FALSE, NULL));
1705                         isc_buffer_init(&buffer, server, sizeof(server) - 1);
1706                         CHECK(dns_name_totext(name, ISC_FALSE, &buffer));
1707                         server[isc_buffer_usedlength(&buffer)] = 0;
1708                         empty_dbtype[2] = server;
1709                 } else
1710                         empty_dbtype[2] = "@";
1711
1712                 obj = NULL;
1713                 result = ns_config_get(maps, "empty-contact", &obj);
1714                 if (result == ISC_R_SUCCESS) {
1715                         str = cfg_obj_asstring(obj);
1716                         isc_buffer_init(&buffer, str, strlen(str));
1717                         isc_buffer_add(&buffer, strlen(str));
1718                         CHECK(dns_name_fromtext(name, &buffer, dns_rootname,
1719                                                 ISC_FALSE, NULL));
1720                         isc_buffer_init(&buffer, contact, sizeof(contact) - 1);
1721                         CHECK(dns_name_totext(name, ISC_FALSE, &buffer));
1722                         contact[isc_buffer_usedlength(&buffer)] = 0;
1723                         empty_dbtype[3] = contact;
1724                 } else
1725                         empty_dbtype[3] = ".";
1726
1727                 logit = ISC_TRUE;
1728                 for (empty = empty_zones[empty_zone].zone;
1729                      empty != NULL;
1730                      empty = empty_zones[++empty_zone].zone)
1731                 {
1732                         dns_forwarders_t *forwarders = NULL;
1733                         dns_view_t *pview = NULL;
1734
1735                         isc_buffer_init(&buffer, empty, strlen(empty));
1736                         isc_buffer_add(&buffer, strlen(empty));
1737                         /*
1738                          * Look for zone on drop list.
1739                          */
1740                         CHECK(dns_name_fromtext(name, &buffer, dns_rootname,
1741                                                 ISC_FALSE, NULL));
1742                         if (disablelist != NULL &&
1743                             on_disable_list(disablelist, name))
1744                                 continue;
1745
1746                         /*
1747                          * This zone already exists.
1748                          */
1749                         (void)dns_view_findzone(view, name, &zone);
1750                         if (zone != NULL) {
1751                                 dns_zone_detach(&zone);
1752                                 continue;
1753                         }
1754
1755                         /*
1756                          * If we would forward this name don't add a
1757                          * empty zone for it.
1758                          */
1759                         result = dns_fwdtable_find(view->fwdtable, name,
1760                                                    &forwarders);
1761                         if (result == ISC_R_SUCCESS &&
1762                             forwarders->fwdpolicy == dns_fwdpolicy_only)
1763                                 continue;
1764
1765                         if (!rfc1918 && empty_zones[empty_zone].rfc1918) {
1766                                 if (logit) {
1767                                         isc_log_write(ns_g_lctx,
1768                                                       NS_LOGCATEGORY_GENERAL,
1769                                                       NS_LOGMODULE_SERVER,
1770                                                       ISC_LOG_WARNING,
1771                                                       "Warning%s%s: "
1772                                                       "'empty-zones-enable/"
1773                                                       "disable-empty-zone' "
1774                                                       "not set: disabling "
1775                                                       "RFC 1918 empty zones",
1776                                                       sep, viewname);
1777                                         logit = ISC_FALSE;
1778                                 }
1779                                 continue;
1780                         }
1781
1782                         /*
1783                          * See if we can re-use a existing zone.
1784                          */
1785                         result = dns_viewlist_find(&ns_g_server->viewlist,
1786                                                    view->name, view->rdclass,
1787                                                    &pview);
1788                         if (result != ISC_R_NOTFOUND &&
1789                             result != ISC_R_SUCCESS)
1790                                 goto cleanup;
1791
1792                         if (pview != NULL) {
1793                                 (void)dns_view_findzone(pview, name, &zone);
1794                                 dns_view_detach(&pview);
1795                                 if (zone != NULL)
1796                                         check_dbtype(&zone, empty_dbtypec,
1797                                                      empty_dbtype, mctx);
1798                                 if (zone != NULL) {
1799                                         dns_zone_setview(zone, view);
1800                                         CHECK(dns_view_addzone(view, zone));
1801                                         dns_zone_detach(&zone);
1802                                         continue;
1803                                 }
1804                         }
1805
1806                         CHECK(dns_zone_create(&zone, mctx));
1807                         CHECK(dns_zone_setorigin(zone, name));
1808                         dns_zone_setview(zone, view);
1809                         CHECK(dns_zonemgr_managezone(ns_g_server->zonemgr, zone));
1810                         dns_zone_setclass(zone, view->rdclass);
1811                         dns_zone_settype(zone, dns_zone_master);
1812                         CHECK(dns_zone_setdbtype(zone, empty_dbtypec,
1813                                                  empty_dbtype));
1814                         if (view->queryacl != NULL)
1815                                 dns_zone_setqueryacl(zone, view->queryacl);
1816                         dns_zone_setdialup(zone, dns_dialuptype_no);
1817                         dns_zone_setnotifytype(zone, dns_notifytype_no);
1818                         dns_zone_setoption(zone, DNS_ZONEOPT_NOCHECKNS,
1819                                            ISC_TRUE);
1820                         CHECK(dns_view_addzone(view, zone));
1821                         isc_log_write(ns_g_lctx, NS_LOGCATEGORY_GENERAL,
1822                                       NS_LOGMODULE_SERVER, ISC_LOG_INFO,
1823                                       "automatic empty zone%s%s: %s",
1824                                       sep, viewname,  empty);
1825                         dns_zone_detach(&zone);
1826                 }
1827         }
1828
1829         result = ISC_R_SUCCESS;
1830
1831  cleanup:
1832         if (zone != NULL)
1833                 dns_zone_detach(&zone);
1834         if (dispatch4 != NULL)
1835                 dns_dispatch_detach(&dispatch4);
1836         if (dispatch6 != NULL)
1837                 dns_dispatch_detach(&dispatch6);
1838         if (order != NULL)
1839                 dns_order_detach(&order);
1840         if (cmctx != NULL)
1841                 isc_mem_detach(&cmctx);
1842
1843         if (cache != NULL)
1844                 dns_cache_detach(&cache);
1845
1846         return (result);
1847 }
1848
1849 static isc_result_t
1850 configure_hints(dns_view_t *view, const char *filename) {
1851         isc_result_t result;
1852         dns_db_t *db;
1853
1854         db = NULL;
1855         result = dns_rootns_create(view->mctx, view->rdclass, filename, &db);
1856         if (result == ISC_R_SUCCESS) {
1857                 dns_view_sethints(view, db);
1858                 dns_db_detach(&db);
1859         }
1860
1861         return (result);
1862 }
1863
1864 static isc_result_t
1865 configure_alternates(const cfg_obj_t *config, dns_view_t *view,
1866                      const cfg_obj_t *alternates)
1867 {
1868         const cfg_obj_t *portobj;
1869         const cfg_obj_t *addresses;
1870         const cfg_listelt_t *element;
1871         isc_result_t result = ISC_R_SUCCESS;
1872         in_port_t port;
1873
1874         /*
1875          * Determine which port to send requests to.
1876          */
1877         if (ns_g_lwresdonly && ns_g_port != 0)
1878                 port = ns_g_port;
1879         else
1880                 CHECKM(ns_config_getport(config, &port), "port");
1881
1882         if (alternates != NULL) {
1883                 portobj = cfg_tuple_get(alternates, "port");
1884                 if (cfg_obj_isuint32(portobj)) {
1885                         isc_uint32_t val = cfg_obj_asuint32(portobj);
1886                         if (val > ISC_UINT16_MAX) {
1887                                 cfg_obj_log(portobj, ns_g_lctx, ISC_LOG_ERROR,
1888                                             "port '%u' out of range", val);
1889                                 return (ISC_R_RANGE);
1890                         }
1891                         port = (in_port_t) val;
1892                 }
1893         }
1894
1895         addresses = NULL;
1896         if (alternates != NULL)
1897                 addresses = cfg_tuple_get(alternates, "addresses");
1898
1899         for (element = cfg_list_first(addresses);
1900              element != NULL;
1901              element = cfg_list_next(element))
1902         {
1903                 const cfg_obj_t *alternate = cfg_listelt_value(element);
1904                 isc_sockaddr_t sa;
1905
1906                 if (!cfg_obj_issockaddr(alternate)) {
1907                         dns_fixedname_t fixed;
1908                         dns_name_t *name;
1909                         const char *str = cfg_obj_asstring(cfg_tuple_get(
1910                                                            alternate, "name"));
1911                         isc_buffer_t buffer;
1912                         in_port_t myport = port;
1913
1914                         isc_buffer_init(&buffer, str, strlen(str));
1915                         isc_buffer_add(&buffer, strlen(str));
1916                         dns_fixedname_init(&fixed);
1917                         name = dns_fixedname_name(&fixed);
1918                         CHECK(dns_name_fromtext(name, &buffer, dns_rootname,
1919                                                 ISC_FALSE, NULL));
1920
1921                         portobj = cfg_tuple_get(alternate, "port");
1922                         if (cfg_obj_isuint32(portobj)) {
1923                                 isc_uint32_t val = cfg_obj_asuint32(portobj);
1924                                 if (val > ISC_UINT16_MAX) {
1925                                         cfg_obj_log(portobj, ns_g_lctx,
1926                                                     ISC_LOG_ERROR,
1927                                                     "port '%u' out of range",
1928                                                      val);
1929                                         return (ISC_R_RANGE);
1930                                 }
1931                                 myport = (in_port_t) val;
1932                         }
1933                         CHECK(dns_resolver_addalternate(view->resolver, NULL,
1934                                                         name, myport));
1935                         continue;
1936                 }
1937
1938                 sa = *cfg_obj_assockaddr(alternate);
1939                 if (isc_sockaddr_getport(&sa) == 0)
1940                         isc_sockaddr_setport(&sa, port);
1941                 CHECK(dns_resolver_addalternate(view->resolver, &sa,
1942                                                 NULL, 0));
1943         }
1944
1945  cleanup:
1946         return (result);
1947 }
1948
1949 static isc_result_t
1950 configure_forward(const cfg_obj_t *config, dns_view_t *view, dns_name_t *origin,
1951                   const cfg_obj_t *forwarders, const cfg_obj_t *forwardtype)
1952 {
1953         const cfg_obj_t *portobj;
1954         const cfg_obj_t *faddresses;
1955         const cfg_listelt_t *element;
1956         dns_fwdpolicy_t fwdpolicy = dns_fwdpolicy_none;
1957         isc_sockaddrlist_t addresses;
1958         isc_sockaddr_t *sa;
1959         isc_result_t result;
1960         in_port_t port;
1961
1962         /*
1963          * Determine which port to send forwarded requests to.
1964          */
1965         if (ns_g_lwresdonly && ns_g_port != 0)
1966                 port = ns_g_port;
1967         else
1968                 CHECKM(ns_config_getport(config, &port), "port");
1969
1970         if (forwarders != NULL) {
1971                 portobj = cfg_tuple_get(forwarders, "port");
1972                 if (cfg_obj_isuint32(portobj)) {
1973                         isc_uint32_t val = cfg_obj_asuint32(portobj);
1974                         if (val > ISC_UINT16_MAX) {
1975                                 cfg_obj_log(portobj, ns_g_lctx, ISC_LOG_ERROR,
1976                                             "port '%u' out of range", val);
1977                                 return (ISC_R_RANGE);
1978                         }
1979                         port = (in_port_t) val;
1980                 }
1981         }
1982
1983         faddresses = NULL;
1984         if (forwarders != NULL)
1985                 faddresses = cfg_tuple_get(forwarders, "addresses");
1986
1987         ISC_LIST_INIT(addresses);
1988
1989         for (element = cfg_list_first(faddresses);
1990              element != NULL;
1991              element = cfg_list_next(element))
1992         {
1993                 const cfg_obj_t *forwarder = cfg_listelt_value(element);
1994                 sa = isc_mem_get(view->mctx, sizeof(isc_sockaddr_t));
1995                 if (sa == NULL) {
1996                         result = ISC_R_NOMEMORY;
1997                         goto cleanup;
1998                 }
1999                 *sa = *cfg_obj_assockaddr(forwarder);
2000                 if (isc_sockaddr_getport(sa) == 0)
2001                         isc_sockaddr_setport(sa, port);
2002                 ISC_LINK_INIT(sa, link);
2003                 ISC_LIST_APPEND(addresses, sa, link);
2004         }
2005
2006         if (ISC_LIST_EMPTY(addresses)) {
2007                 if (forwardtype != NULL)
2008                         cfg_obj_log(forwarders, ns_g_lctx, ISC_LOG_WARNING,
2009                                     "no forwarders seen; disabling "
2010                                     "forwarding");
2011                 fwdpolicy = dns_fwdpolicy_none;
2012         } else {
2013                 if (forwardtype == NULL)
2014                         fwdpolicy = dns_fwdpolicy_first;
2015                 else {
2016                         const char *forwardstr = cfg_obj_asstring(forwardtype);
2017                         if (strcasecmp(forwardstr, "first") == 0)
2018                                 fwdpolicy = dns_fwdpolicy_first;
2019                         else if (strcasecmp(forwardstr, "only") == 0)
2020                                 fwdpolicy = dns_fwdpolicy_only;
2021                         else
2022                                 INSIST(0);
2023                 }
2024         }
2025
2026         result = dns_fwdtable_add(view->fwdtable, origin, &addresses,
2027                                   fwdpolicy);
2028         if (result != ISC_R_SUCCESS) {
2029                 char namebuf[DNS_NAME_FORMATSIZE];
2030                 dns_name_format(origin, namebuf, sizeof(namebuf));
2031                 cfg_obj_log(forwarders, ns_g_lctx, ISC_LOG_WARNING,
2032                             "could not set up forwarding for domain '%s': %s",
2033                             namebuf, isc_result_totext(result));
2034                 goto cleanup;
2035         }
2036
2037         result = ISC_R_SUCCESS;
2038
2039  cleanup:
2040
2041         while (!ISC_LIST_EMPTY(addresses)) {
2042                 sa = ISC_LIST_HEAD(addresses);
2043                 ISC_LIST_UNLINK(addresses, sa, link);
2044                 isc_mem_put(view->mctx, sa, sizeof(isc_sockaddr_t));
2045         }
2046
2047         return (result);
2048 }
2049
2050 /*
2051  * Create a new view and add it to the list.
2052  *
2053  * If 'vconfig' is NULL, create the default view.
2054  *
2055  * The view created is attached to '*viewp'.
2056  */
2057 static isc_result_t
2058 create_view(const cfg_obj_t *vconfig, dns_viewlist_t *viewlist,
2059             dns_view_t **viewp)
2060 {
2061         isc_result_t result;
2062         const char *viewname;
2063         dns_rdataclass_t viewclass;
2064         dns_view_t *view = NULL;
2065
2066         if (vconfig != NULL) {
2067                 const cfg_obj_t *classobj = NULL;
2068
2069                 viewname = cfg_obj_asstring(cfg_tuple_get(vconfig, "name"));
2070                 classobj = cfg_tuple_get(vconfig, "class");
2071                 result = ns_config_getclass(classobj, dns_rdataclass_in,
2072                                             &viewclass);
2073         } else {
2074                 viewname = "_default";
2075                 viewclass = dns_rdataclass_in;
2076         }
2077         result = dns_viewlist_find(viewlist, viewname, viewclass, &view);
2078         if (result == ISC_R_SUCCESS)
2079                 return (ISC_R_EXISTS);
2080         if (result != ISC_R_NOTFOUND)
2081                 return (result);
2082         INSIST(view == NULL);
2083
2084         result = dns_view_create(ns_g_mctx, viewclass, viewname, &view);
2085         if (result != ISC_R_SUCCESS)
2086                 return (result);
2087
2088         ISC_LIST_APPEND(*viewlist, view, link);
2089         dns_view_attach(view, viewp);
2090         return (ISC_R_SUCCESS);
2091 }
2092
2093 /*
2094  * Configure or reconfigure a zone.
2095  */
2096 static isc_result_t
2097 configure_zone(const cfg_obj_t *config, const cfg_obj_t *zconfig,
2098                const cfg_obj_t *vconfig, isc_mem_t *mctx, dns_view_t *view,
2099                cfg_aclconfctx_t *aclconf)
2100 {
2101         dns_view_t *pview = NULL;       /* Production view */
2102         dns_zone_t *zone = NULL;        /* New or reused zone */
2103         dns_zone_t *dupzone = NULL;
2104         const cfg_obj_t *options = NULL;
2105         const cfg_obj_t *zoptions = NULL;
2106         const cfg_obj_t *typeobj = NULL;
2107         const cfg_obj_t *forwarders = NULL;
2108         const cfg_obj_t *forwardtype = NULL;
2109         const cfg_obj_t *only = NULL;
2110         isc_result_t result;
2111         isc_result_t tresult;
2112         isc_buffer_t buffer;
2113         dns_fixedname_t fixorigin;
2114         dns_name_t *origin;
2115         const char *zname;
2116         dns_rdataclass_t zclass;
2117         const char *ztypestr;
2118
2119         options = NULL;
2120         (void)cfg_map_get(config, "options", &options);
2121
2122         zoptions = cfg_tuple_get(zconfig, "options");
2123
2124         /*
2125          * Get the zone origin as a dns_name_t.
2126          */
2127         zname = cfg_obj_asstring(cfg_tuple_get(zconfig, "name"));
2128         isc_buffer_init(&buffer, zname, strlen(zname));
2129         isc_buffer_add(&buffer, strlen(zname));
2130         dns_fixedname_init(&fixorigin);
2131         CHECK(dns_name_fromtext(dns_fixedname_name(&fixorigin),
2132                                 &buffer, dns_rootname, ISC_FALSE, NULL));
2133         origin = dns_fixedname_name(&fixorigin);
2134
2135         CHECK(ns_config_getclass(cfg_tuple_get(zconfig, "class"),
2136                                  view->rdclass, &zclass));
2137         if (zclass != view->rdclass) {
2138                 const char *vname = NULL;
2139                 if (vconfig != NULL)
2140                         vname = cfg_obj_asstring(cfg_tuple_get(vconfig,
2141                                                                "name"));
2142                 else
2143                         vname = "<default view>";
2144
2145                 isc_log_write(ns_g_lctx, NS_LOGCATEGORY_GENERAL,
2146                               NS_LOGMODULE_SERVER, ISC_LOG_ERROR,
2147                               "zone '%s': wrong class for view '%s'",
2148                               zname, vname);
2149                 result = ISC_R_FAILURE;
2150                 goto cleanup;
2151         }
2152
2153         (void)cfg_map_get(zoptions, "type", &typeobj);
2154         if (typeobj == NULL) {
2155                 cfg_obj_log(zconfig, ns_g_lctx, ISC_LOG_ERROR,
2156                             "zone '%s' 'type' not specified", zname);
2157                 return (ISC_R_FAILURE);
2158         }
2159         ztypestr = cfg_obj_asstring(typeobj);
2160
2161         /*
2162          * "hints zones" aren't zones.  If we've got one,
2163          * configure it and return.
2164          */
2165         if (strcasecmp(ztypestr, "hint") == 0) {
2166                 const cfg_obj_t *fileobj = NULL;
2167                 if (cfg_map_get(zoptions, "file", &fileobj) != ISC_R_SUCCESS) {
2168                         isc_log_write(ns_g_lctx, NS_LOGCATEGORY_GENERAL,
2169                                       NS_LOGMODULE_SERVER, ISC_LOG_ERROR,
2170                                       "zone '%s': 'file' not specified",
2171                                       zname);
2172                         result = ISC_R_FAILURE;
2173                         goto cleanup;
2174                 }
2175                 if (dns_name_equal(origin, dns_rootname)) {
2176                         const char *hintsfile = cfg_obj_asstring(fileobj);
2177
2178                         result = configure_hints(view, hintsfile);
2179                         if (result != ISC_R_SUCCESS) {
2180                                 isc_log_write(ns_g_lctx, NS_LOGCATEGORY_GENERAL,
2181                                               NS_LOGMODULE_SERVER,
2182                                               ISC_LOG_ERROR,
2183                                               "could not configure root hints "
2184                                               "from '%s': %s", hintsfile,
2185                                               isc_result_totext(result));
2186                                 goto cleanup;
2187                         }
2188                         /*
2189                          * Hint zones may also refer to delegation only points.
2190                          */
2191                         only = NULL;
2192                         tresult = cfg_map_get(zoptions, "delegation-only",
2193                                               &only);
2194                         if (tresult == ISC_R_SUCCESS && cfg_obj_asboolean(only))
2195                                 CHECK(dns_view_adddelegationonly(view, origin));
2196                 } else {
2197                         isc_log_write(ns_g_lctx, NS_LOGCATEGORY_GENERAL,
2198                                       NS_LOGMODULE_SERVER, ISC_LOG_WARNING,
2199                                       "ignoring non-root hint zone '%s'",
2200                                       zname);
2201                         result = ISC_R_SUCCESS;
2202                 }
2203                 /* Skip ordinary zone processing. */
2204                 goto cleanup;
2205         }
2206
2207         /*
2208          * "forward zones" aren't zones either.  Translate this syntax into
2209          * the appropriate selective forwarding configuration and return.
2210          */
2211         if (strcasecmp(ztypestr, "forward") == 0) {
2212                 forwardtype = NULL;
2213                 forwarders = NULL;
2214
2215                 (void)cfg_map_get(zoptions, "forward", &forwardtype);
2216                 (void)cfg_map_get(zoptions, "forwarders", &forwarders);
2217                 result = configure_forward(config, view, origin, forwarders,
2218                                            forwardtype);
2219                 goto cleanup;
2220         }
2221
2222         /*
2223          * "delegation-only zones" aren't zones either.
2224          */
2225         if (strcasecmp(ztypestr, "delegation-only") == 0) {
2226                 result = dns_view_adddelegationonly(view, origin);
2227                 goto cleanup;
2228         }
2229
2230         /*
2231          * Check for duplicates in the new zone table.
2232          */
2233         result = dns_view_findzone(view, origin, &dupzone);
2234         if (result == ISC_R_SUCCESS) {
2235                 /*
2236                  * We already have this zone!
2237                  */
2238                 cfg_obj_log(zconfig, ns_g_lctx, ISC_LOG_ERROR,
2239                             "zone '%s' already exists", zname);
2240                 dns_zone_detach(&dupzone);
2241                 result = ISC_R_EXISTS;
2242                 goto cleanup;
2243         }
2244         INSIST(dupzone == NULL);
2245
2246         /*
2247          * See if we can reuse an existing zone.  This is
2248          * only possible if all of these are true:
2249          *   - The zone's view exists
2250          *   - A zone with the right name exists in the view
2251          *   - The zone is compatible with the config
2252          *     options (e.g., an existing master zone cannot
2253          *     be reused if the options specify a slave zone)
2254          */
2255         result = dns_viewlist_find(&ns_g_server->viewlist,
2256                                    view->name, view->rdclass,
2257                                    &pview);
2258         if (result != ISC_R_NOTFOUND && result != ISC_R_SUCCESS)
2259                 goto cleanup;
2260         if (pview != NULL)
2261                 result = dns_view_findzone(pview, origin, &zone);
2262         if (result != ISC_R_NOTFOUND && result != ISC_R_SUCCESS)
2263                 goto cleanup;
2264         if (zone != NULL && !ns_zone_reusable(zone, zconfig))
2265                 dns_zone_detach(&zone);
2266
2267         if (zone != NULL) {
2268                 /*
2269                  * We found a reusable zone.  Make it use the
2270                  * new view.
2271                  */
2272                 dns_zone_setview(zone, view);
2273                 if (view->acache != NULL)
2274                         dns_zone_setacache(zone, view->acache);
2275         } else {
2276                 /*
2277                  * We cannot reuse an existing zone, we have
2278                  * to create a new one.
2279                  */
2280                 CHECK(dns_zone_create(&zone, mctx));
2281                 CHECK(dns_zone_setorigin(zone, origin));
2282                 dns_zone_setview(zone, view);
2283                 if (view->acache != NULL)
2284                         dns_zone_setacache(zone, view->acache);
2285                 CHECK(dns_zonemgr_managezone(ns_g_server->zonemgr, zone));
2286         }
2287
2288         /*
2289          * If the zone contains a 'forwarders' statement, configure
2290          * selective forwarding.
2291          */
2292         forwarders = NULL;
2293         if (cfg_map_get(zoptions, "forwarders", &forwarders) == ISC_R_SUCCESS)
2294         {
2295                 forwardtype = NULL;
2296                 (void)cfg_map_get(zoptions, "forward", &forwardtype);
2297                 CHECK(configure_forward(config, view, origin, forwarders,
2298                                         forwardtype));
2299         }
2300
2301         /*
2302          * Stub and forward zones may also refer to delegation only points.
2303          */
2304         only = NULL;
2305         if (cfg_map_get(zoptions, "delegation-only", &only) == ISC_R_SUCCESS)
2306         {
2307                 if (cfg_obj_asboolean(only))
2308                         CHECK(dns_view_adddelegationonly(view, origin));
2309         }
2310
2311         /*
2312          * Configure the zone.
2313          */
2314         CHECK(ns_zone_configure(config, vconfig, zconfig, aclconf, zone));
2315
2316         /*
2317          * Add the zone to its view in the new view list.
2318          */
2319         CHECK(dns_view_addzone(view, zone));
2320
2321  cleanup:
2322         if (zone != NULL)
2323                 dns_zone_detach(&zone);
2324         if (pview != NULL)
2325                 dns_view_detach(&pview);
2326
2327         return (result);
2328 }
2329
2330 /*
2331  * Configure a single server quota.
2332  */
2333 static void
2334 configure_server_quota(const cfg_obj_t **maps, const char *name,
2335                        isc_quota_t *quota)
2336 {
2337         const cfg_obj_t *obj = NULL;
2338         isc_result_t result;
2339
2340         result = ns_config_get(maps, name, &obj);
2341         INSIST(result == ISC_R_SUCCESS);
2342         isc_quota_max(quota, cfg_obj_asuint32(obj));
2343 }
2344
2345 /*
2346  * This function is called as soon as the 'directory' statement has been
2347  * parsed.  This can be extended to support other options if necessary.
2348  */
2349 static isc_result_t
2350 directory_callback(const char *clausename, const cfg_obj_t *obj, void *arg) {
2351         isc_result_t result;
2352         const char *directory;
2353
2354         REQUIRE(strcasecmp("directory", clausename) == 0);
2355
2356         UNUSED(arg);
2357         UNUSED(clausename);
2358
2359         /*
2360          * Change directory.
2361          */
2362         directory = cfg_obj_asstring(obj);
2363
2364         if (! isc_file_ischdiridempotent(directory))
2365                 cfg_obj_log(obj, ns_g_lctx, ISC_LOG_WARNING,
2366                             "option 'directory' contains relative path '%s'",
2367                             directory);
2368
2369         result = isc_dir_chdir(directory);
2370         if (result != ISC_R_SUCCESS) {
2371                 cfg_obj_log(obj, ns_g_lctx, ISC_LOG_ERROR,
2372                             "change directory to '%s' failed: %s",
2373                             directory, isc_result_totext(result));
2374                 return (result);
2375         }
2376
2377         return (ISC_R_SUCCESS);
2378 }
2379
2380 static void
2381 scan_interfaces(ns_server_t *server, isc_boolean_t verbose) {
2382         isc_boolean_t match_mapped = server->aclenv.match_mapped;
2383
2384         ns_interfacemgr_scan(server->interfacemgr, verbose);
2385         /*
2386          * Update the "localhost" and "localnets" ACLs to match the
2387          * current set of network interfaces.
2388          */
2389         dns_aclenv_copy(&server->aclenv,
2390                         ns_interfacemgr_getaclenv(server->interfacemgr));
2391
2392         server->aclenv.match_mapped = match_mapped;
2393 }
2394
2395 static isc_result_t
2396 add_listenelt(isc_mem_t *mctx, ns_listenlist_t *list, isc_sockaddr_t *addr,
2397               isc_boolean_t wcardport_ok)
2398 {
2399         ns_listenelt_t *lelt = NULL;
2400         dns_acl_t *src_acl = NULL;
2401         dns_aclelement_t aelt;
2402         isc_result_t result;
2403         isc_sockaddr_t any_sa6;
2404
2405         REQUIRE(isc_sockaddr_pf(addr) == AF_INET6);
2406
2407         isc_sockaddr_any6(&any_sa6);
2408         if (!isc_sockaddr_equal(&any_sa6, addr) &&
2409             (wcardport_ok || isc_sockaddr_getport(addr) != 0)) {
2410                 aelt.type = dns_aclelementtype_ipprefix;
2411                 aelt.negative = ISC_FALSE;
2412                 aelt.u.ip_prefix.prefixlen = 128;
2413                 isc_netaddr_fromin6(&aelt.u.ip_prefix.address,
2414                                     &addr->type.sin6.sin6_addr);
2415
2416                 result = dns_acl_create(mctx, 1, &src_acl);
2417                 if (result != ISC_R_SUCCESS)
2418                         return (result);
2419                 result = dns_acl_appendelement(src_acl, &aelt);
2420                 if (result != ISC_R_SUCCESS)
2421                         goto clean;
2422
2423                 result = ns_listenelt_create(mctx, isc_sockaddr_getport(addr),
2424                                              src_acl, &lelt);
2425                 if (result != ISC_R_SUCCESS)
2426                         goto clean;
2427                 ISC_LIST_APPEND(list->elts, lelt, link);
2428         }
2429
2430         return (ISC_R_SUCCESS);
2431
2432  clean:
2433         INSIST(lelt == NULL);
2434         dns_acl_detach(&src_acl);
2435
2436         return (result);
2437 }
2438
2439 /*
2440  * Make a list of xxx-source addresses and call ns_interfacemgr_adjust()
2441  * to update the listening interfaces accordingly.
2442  * We currently only consider IPv6, because this only affects IPv6 wildcard
2443  * sockets.
2444  */
2445 static void
2446 adjust_interfaces(ns_server_t *server, isc_mem_t *mctx) {
2447         isc_result_t result;
2448         ns_listenlist_t *list = NULL;
2449         dns_view_t *view;
2450         dns_zone_t *zone, *next;
2451         isc_sockaddr_t addr, *addrp;
2452
2453         result = ns_listenlist_create(mctx, &list);
2454         if (result != ISC_R_SUCCESS)
2455                 return;
2456
2457         for (view = ISC_LIST_HEAD(server->viewlist);
2458              view != NULL;
2459              view = ISC_LIST_NEXT(view, link)) {
2460                 dns_dispatch_t *dispatch6;
2461
2462                 dispatch6 = dns_resolver_dispatchv6(view->resolver);
2463                 if (dispatch6 == NULL)
2464                         continue;
2465                 result = dns_dispatch_getlocaladdress(dispatch6, &addr);
2466                 if (result != ISC_R_SUCCESS)
2467                         goto fail;
2468
2469                 /*
2470                  * We always add non-wildcard address regardless of whether
2471                  * the port is 'any' (the fourth arg is TRUE): if the port is
2472                  * specific, we need to add it since it may conflict with a
2473                  * listening interface; if it's zero, we'll dynamically open
2474                  * query ports, and some of them may override an existing
2475                  * wildcard IPv6 port.
2476                  */
2477                 result = add_listenelt(mctx, list, &addr, ISC_TRUE);
2478                 if (result != ISC_R_SUCCESS)
2479                         goto fail;
2480         }
2481
2482         zone = NULL;
2483         for (result = dns_zone_first(server->zonemgr, &zone);
2484              result == ISC_R_SUCCESS;
2485              next = NULL, result = dns_zone_next(zone, &next), zone = next) {
2486                 dns_view_t *zoneview;
2487
2488                 /*
2489                  * At this point the zone list may contain a stale zone
2490                  * just removed from the configuration.  To see the validity,
2491                  * check if the corresponding view is in our current view list.
2492                  * There may also be old zones that are still in the process
2493                  * of shutting down and have detached from their old view
2494                  * (zoneview == NULL).
2495                  */
2496                 zoneview = dns_zone_getview(zone);
2497                 if (zoneview == NULL)
2498                         continue;
2499                 for (view = ISC_LIST_HEAD(server->viewlist);
2500                      view != NULL && view != zoneview;
2501                      view = ISC_LIST_NEXT(view, link))
2502                         ;
2503                 if (view == NULL)
2504                         continue;
2505
2506                 addrp = dns_zone_getnotifysrc6(zone);
2507                 result = add_listenelt(mctx, list, addrp, ISC_FALSE);
2508                 if (result != ISC_R_SUCCESS)
2509                         goto fail;
2510
2511                 addrp = dns_zone_getxfrsource6(zone);
2512                 result = add_listenelt(mctx, list, addrp, ISC_FALSE);
2513                 if (result != ISC_R_SUCCESS)
2514                         goto fail;
2515         }
2516
2517         ns_interfacemgr_adjust(server->interfacemgr, list, ISC_TRUE);
2518
2519  clean:
2520         ns_listenlist_detach(&list);
2521         return;
2522
2523  fail:
2524         /*
2525          * Even when we failed the procedure, most of other interfaces
2526          * should work correctly.  We therefore just warn it.
2527          */
2528         isc_log_write(ns_g_lctx, NS_LOGCATEGORY_GENERAL,
2529                       NS_LOGMODULE_SERVER, ISC_LOG_WARNING,
2530                       "could not adjust the listen-on list; "
2531                       "some interfaces may not work");
2532         goto clean;
2533 }
2534
2535 /*
2536  * This event callback is invoked to do periodic network
2537  * interface scanning.
2538  */
2539 static void
2540 interface_timer_tick(isc_task_t *task, isc_event_t *event) {
2541         isc_result_t result;
2542         ns_server_t *server = (ns_server_t *) event->ev_arg;
2543         INSIST(task == server->task);
2544         UNUSED(task);
2545         isc_event_free(&event);
2546         /*
2547          * XXX should scan interfaces unlocked and get exclusive access
2548          * only to replace ACLs.
2549          */
2550         result = isc_task_beginexclusive(server->task);
2551         RUNTIME_CHECK(result == ISC_R_SUCCESS);
2552         scan_interfaces(server, ISC_FALSE);
2553         isc_task_endexclusive(server->task);
2554 }
2555
2556 static void
2557 heartbeat_timer_tick(isc_task_t *task, isc_event_t *event) {
2558         ns_server_t *server = (ns_server_t *) event->ev_arg;
2559         dns_view_t *view;
2560
2561         UNUSED(task);
2562         isc_event_free(&event);
2563         view = ISC_LIST_HEAD(server->viewlist);
2564         while (view != NULL) {
2565                 dns_view_dialup(view);
2566                 view = ISC_LIST_NEXT(view, link);
2567         }
2568 }
2569
2570 static void
2571 pps_timer_tick(isc_task_t *task, isc_event_t *event) {
2572         static unsigned int oldrequests = 0;
2573         unsigned int requests = ns_client_requests;
2574
2575         UNUSED(task);
2576         isc_event_free(&event);
2577
2578         /*
2579          * Don't worry about wrapping as the overflow result will be right.
2580          */
2581         dns_pps = (requests - oldrequests) / 1200;
2582         oldrequests = requests;
2583 }
2584
2585 /*
2586  * Replace the current value of '*field', a dynamically allocated
2587  * string or NULL, with a dynamically allocated copy of the
2588  * null-terminated string pointed to by 'value', or NULL.
2589  */
2590 static isc_result_t
2591 setstring(ns_server_t *server, char **field, const char *value) {
2592         char *copy;
2593
2594         if (value != NULL) {
2595                 copy = isc_mem_strdup(server->mctx, value);
2596                 if (copy == NULL)
2597                         return (ISC_R_NOMEMORY);
2598         } else {
2599                 copy = NULL;
2600         }
2601
2602         if (*field != NULL)
2603                 isc_mem_free(server->mctx, *field);
2604
2605         *field = copy;
2606         return (ISC_R_SUCCESS);
2607 }
2608
2609 /*
2610  * Replace the current value of '*field', a dynamically allocated
2611  * string or NULL, with another dynamically allocated string
2612  * or NULL if whether 'obj' is a string or void value, respectively.
2613  */
2614 static isc_result_t
2615 setoptstring(ns_server_t *server, char **field, const cfg_obj_t *obj) {
2616         if (cfg_obj_isvoid(obj))
2617                 return (setstring(server, field, NULL));
2618         else
2619                 return (setstring(server, field, cfg_obj_asstring(obj)));
2620 }
2621
2622 static void
2623 set_limit(const cfg_obj_t **maps, const char *configname,
2624           const char *description, isc_resource_t resourceid,
2625           isc_resourcevalue_t defaultvalue)
2626 {
2627         const cfg_obj_t *obj = NULL;
2628         const char *resource;
2629         isc_resourcevalue_t value;
2630         isc_result_t result;
2631
2632         if (ns_config_get(maps, configname, &obj) != ISC_R_SUCCESS)
2633                 return;
2634
2635         if (cfg_obj_isstring(obj)) {
2636                 resource = cfg_obj_asstring(obj);
2637                 if (strcasecmp(resource, "unlimited") == 0)
2638                         value = ISC_RESOURCE_UNLIMITED;
2639                 else {
2640                         INSIST(strcasecmp(resource, "default") == 0);
2641                         value = defaultvalue;
2642                 }
2643         } else
2644                 value = cfg_obj_asuint64(obj);
2645
2646         result = isc_resource_setlimit(resourceid, value);
2647         isc_log_write(ns_g_lctx, NS_LOGCATEGORY_GENERAL, NS_LOGMODULE_SERVER,
2648                       result == ISC_R_SUCCESS ?
2649                         ISC_LOG_DEBUG(3) : ISC_LOG_WARNING,
2650                       "set maximum %s to %" ISC_PRINT_QUADFORMAT "d: %s",
2651                       description, value, isc_result_totext(result));
2652 }
2653
2654 #define SETLIMIT(cfgvar, resource, description) \
2655         set_limit(maps, cfgvar, description, isc_resource_ ## resource, \
2656                   ns_g_init ## resource)
2657
2658 static void
2659 set_limits(const cfg_obj_t **maps) {
2660         SETLIMIT("stacksize", stacksize, "stack size");
2661         SETLIMIT("datasize", datasize, "data size");
2662         SETLIMIT("coresize", coresize, "core size");
2663         SETLIMIT("files", openfiles, "open files");
2664 }
2665
2666 static void
2667 portset_fromconf(isc_portset_t *portset, const cfg_obj_t *ports,
2668                  isc_boolean_t positive)
2669 {
2670         const cfg_listelt_t *element;
2671
2672         for (element = cfg_list_first(ports);
2673              element != NULL;
2674              element = cfg_list_next(element)) {
2675                 const cfg_obj_t *obj = cfg_listelt_value(element);
2676
2677                 if (cfg_obj_isuint32(obj)) {
2678                         in_port_t port = (in_port_t)cfg_obj_asuint32(obj);
2679
2680                         if (positive)
2681                                 isc_portset_add(portset, port);
2682                         else
2683                                 isc_portset_remove(portset, port);
2684                 } else {
2685                         const cfg_obj_t *obj_loport, *obj_hiport;
2686                         in_port_t loport, hiport;
2687
2688                         obj_loport = cfg_tuple_get(obj, "loport");
2689                         loport = (in_port_t)cfg_obj_asuint32(obj_loport);
2690                         obj_hiport = cfg_tuple_get(obj, "hiport");
2691                         hiport = (in_port_t)cfg_obj_asuint32(obj_hiport);
2692
2693                         if (positive)
2694                                 isc_portset_addrange(portset, loport, hiport);
2695                         else {
2696                                 isc_portset_removerange(portset, loport,
2697                                                         hiport);
2698                         }
2699                 }
2700         }
2701 }
2702
2703 static isc_result_t
2704 removed(dns_zone_t *zone, void *uap) {
2705         const char *type;
2706
2707         if (dns_zone_getview(zone) != uap)
2708                 return (ISC_R_SUCCESS);
2709
2710         switch (dns_zone_gettype(zone)) {
2711         case dns_zone_master:
2712                 type = "master";
2713                 break;
2714         case dns_zone_slave:
2715                 type = "slave";
2716                 break;
2717         case dns_zone_stub:
2718                 type = "stub";
2719                 break;
2720         default:
2721                 type = "other";
2722                 break;
2723         }
2724         dns_zone_log(zone, ISC_LOG_INFO, "(%s) removed", type);
2725         return (ISC_R_SUCCESS);
2726 }
2727
2728 static isc_result_t
2729 load_configuration(const char *filename, ns_server_t *server,
2730                    isc_boolean_t first_time)
2731 {
2732         cfg_aclconfctx_t aclconfctx;
2733         cfg_obj_t *config;
2734         cfg_parser_t *parser = NULL;
2735         const cfg_listelt_t *element;
2736         const cfg_obj_t *builtin_views;
2737         const cfg_obj_t *maps[3];
2738         const cfg_obj_t *obj;
2739         const cfg_obj_t *options;
2740         const cfg_obj_t *usev4ports, *avoidv4ports, *usev6ports, *avoidv6ports;
2741         const cfg_obj_t *views;
2742         dns_view_t *view = NULL;
2743         dns_view_t *view_next;
2744         dns_viewlist_t tmpviewlist;
2745         dns_viewlist_t viewlist;
2746         in_port_t listen_port, udpport_low, udpport_high;
2747         int i;
2748         isc_interval_t interval;
2749         isc_portset_t *v4portset = NULL;
2750         isc_portset_t *v6portset = NULL;
2751         isc_resourcevalue_t nfiles;
2752         isc_result_t result;
2753         isc_uint32_t heartbeat_interval;
2754         isc_uint32_t interface_interval;
2755         isc_uint32_t reserved;
2756         isc_uint32_t udpsize;
2757         unsigned int maxsocks;
2758
2759         cfg_aclconfctx_init(&aclconfctx);
2760         ISC_LIST_INIT(viewlist);
2761
2762         /* Ensure exclusive access to configuration data. */
2763         result = isc_task_beginexclusive(server->task);
2764         RUNTIME_CHECK(result == ISC_R_SUCCESS);
2765
2766         /*
2767          * Parse the global default pseudo-config file.
2768          */
2769         if (first_time) {
2770                 CHECK(ns_config_parsedefaults(ns_g_parser, &ns_g_config));
2771                 RUNTIME_CHECK(cfg_map_get(ns_g_config, "options",
2772                                           &ns_g_defaults) ==
2773                               ISC_R_SUCCESS);
2774         }
2775
2776         /*
2777          * Parse the configuration file using the new config code.
2778          */
2779         result = ISC_R_FAILURE;
2780         config = NULL;
2781
2782         /*
2783          * Unless this is lwresd with the -C option, parse the config file.
2784          */
2785         if (!(ns_g_lwresdonly && lwresd_g_useresolvconf)) {
2786                 isc_log_write(ns_g_lctx,
2787                               NS_LOGCATEGORY_GENERAL, NS_LOGMODULE_SERVER,
2788                               ISC_LOG_INFO, "loading configuration from '%s'",
2789                               filename);
2790                 CHECK(cfg_parser_create(ns_g_mctx, ns_g_lctx, &parser));
2791                 cfg_parser_setcallback(parser, directory_callback, NULL);
2792                 result = cfg_parse_file(parser, filename, &cfg_type_namedconf,
2793                                         &config);
2794         }
2795
2796         /*
2797          * If this is lwresd with the -C option, or lwresd with no -C or -c
2798          * option where the above parsing failed, parse resolv.conf.
2799          */
2800         if (ns_g_lwresdonly &&
2801             (lwresd_g_useresolvconf ||
2802              (!ns_g_conffileset && result == ISC_R_FILENOTFOUND)))
2803         {
2804                 isc_log_write(ns_g_lctx,
2805                               NS_LOGCATEGORY_GENERAL, NS_LOGMODULE_SERVER,
2806                               ISC_LOG_INFO, "loading configuration from '%s'",
2807                               lwresd_g_resolvconffile);
2808                 if (parser != NULL)
2809                         cfg_parser_destroy(&parser);
2810                 CHECK(cfg_parser_create(ns_g_mctx, ns_g_lctx, &parser));
2811                 result = ns_lwresd_parseeresolvconf(ns_g_mctx, parser,
2812                                                     &config);
2813         }
2814         CHECK(result);
2815
2816         /*
2817          * Check the validity of the configuration.
2818          */
2819         CHECK(bind9_check_namedconf(config, ns_g_lctx, ns_g_mctx));
2820
2821         /*
2822          * Fill in the maps array, used for resolving defaults.
2823          */
2824         i = 0;
2825         options = NULL;
2826         result = cfg_map_get(config, "options", &options);
2827         if (result == ISC_R_SUCCESS)
2828                 maps[i++] = options;
2829         maps[i++] = ns_g_defaults;
2830         maps[i++] = NULL;
2831
2832         /*
2833          * Set process limits, which (usually) needs to be done as root.
2834          */
2835         set_limits(maps);
2836
2837         /*
2838          * Check if max number of open sockets that the system allows is
2839          * sufficiently large.  Failing this condition is not necessarily fatal,
2840          * but may cause subsequent runtime failures for a busy recursive
2841          * server.
2842          */
2843         result = isc_socketmgr_getmaxsockets(ns_g_socketmgr, &maxsocks);
2844         if (result != ISC_R_SUCCESS)
2845                 maxsocks = 0;
2846         result = isc_resource_getcurlimit(isc_resource_openfiles, &nfiles);
2847         if (result == ISC_R_SUCCESS && (isc_resourcevalue_t)maxsocks > nfiles) {
2848                 isc_log_write(ns_g_lctx, NS_LOGCATEGORY_GENERAL,
2849                               NS_LOGMODULE_SERVER, ISC_LOG_WARNING,
2850                               "max open files (%" ISC_PRINT_QUADFORMAT "u)"
2851                               " is smaller than max sockets (%u)",
2852                               nfiles, maxsocks);
2853         }
2854
2855         /*
2856          * Set the number of socket reserved for TCP, stdio etc.
2857          */
2858         obj = NULL;
2859         result = ns_config_get(maps, "reserved-sockets", &obj);
2860         INSIST(result == ISC_R_SUCCESS);
2861         reserved = cfg_obj_asuint32(obj);
2862         if (maxsocks != 0) {
2863                 if (maxsocks < 128U)                    /* Prevent underflow. */
2864                         reserved = 0;
2865                 else if (reserved > maxsocks - 128U)    /* Minimum UDP space. */
2866                         reserved = maxsocks - 128;
2867         }
2868         /* Minimum TCP/stdio space. */
2869         if (reserved < 128U)
2870                 reserved = 128;
2871         if (reserved + 128U > maxsocks && maxsocks != 0) {
2872                 isc_log_write(ns_g_lctx, NS_LOGCATEGORY_GENERAL,
2873                               NS_LOGMODULE_SERVER, ISC_LOG_WARNING,
2874                               "less than 128 UDP sockets available after "
2875                               "applying 'reserved-sockets' and 'maxsockets'");
2876         }
2877         isc__socketmgr_setreserved(ns_g_socketmgr, reserved);
2878
2879         /*
2880          * Configure various server options.
2881          */
2882         configure_server_quota(maps, "transfers-out", &server->xfroutquota);
2883         configure_server_quota(maps, "tcp-clients", &server->tcpquota);
2884         configure_server_quota(maps, "recursive-clients",
2885                                &server->recursionquota);
2886         if (server->recursionquota.max > 1000)
2887                 isc_quota_soft(&server->recursionquota,
2888                                server->recursionquota.max - 100);
2889         else
2890                 isc_quota_soft(&server->recursionquota, 0);
2891
2892         CHECK(configure_view_acl(NULL, config, "blackhole", &aclconfctx,
2893                                  ns_g_mctx, &server->blackholeacl));
2894         if (server->blackholeacl != NULL)
2895                 dns_dispatchmgr_setblackhole(ns_g_dispatchmgr,
2896                                              server->blackholeacl);
2897
2898         obj = NULL;
2899         result = ns_config_get(maps, "match-mapped-addresses", &obj);
2900         INSIST(result == ISC_R_SUCCESS);
2901         server->aclenv.match_mapped = cfg_obj_asboolean(obj);
2902
2903         /*
2904          * Configure sets of UDP query source ports.
2905          */
2906         CHECKM(isc_portset_create(ns_g_mctx, &v4portset),
2907                "creating UDP port set");
2908         CHECKM(isc_portset_create(ns_g_mctx, &v6portset),
2909                "creating UDP port set");
2910
2911         usev4ports = NULL;
2912         usev6ports = NULL;
2913         avoidv4ports = NULL;
2914         avoidv6ports = NULL;
2915
2916         (void)ns_config_get(maps, "use-v4-udp-ports", &usev4ports);
2917         if (usev4ports != NULL)
2918                 portset_fromconf(v4portset, usev4ports, ISC_TRUE);
2919         else {
2920                 CHECKM(isc_net_getudpportrange(AF_INET, &udpport_low,
2921                                                &udpport_high),
2922                        "get the default UDP/IPv4 port range");
2923                 if (udpport_low == udpport_high)
2924                         isc_portset_add(v4portset, udpport_low);
2925                 else {
2926                         isc_portset_addrange(v4portset, udpport_low,
2927                                              udpport_high);
2928                 }
2929                 isc_log_write(ns_g_lctx, NS_LOGCATEGORY_GENERAL,
2930                               NS_LOGMODULE_SERVER, ISC_LOG_INFO,
2931                               "using default UDP/IPv4 port range: [%d, %d]",
2932                               udpport_low, udpport_high);
2933         }
2934         (void)ns_config_get(maps, "avoid-v4-udp-ports", &avoidv4ports);
2935         if (avoidv4ports != NULL)
2936                 portset_fromconf(v4portset, avoidv4ports, ISC_FALSE);
2937
2938         (void)ns_config_get(maps, "use-v6-udp-ports", &usev6ports);
2939         if (usev6ports != NULL)
2940                 portset_fromconf(v6portset, usev6ports, ISC_TRUE);
2941         else {
2942                 CHECKM(isc_net_getudpportrange(AF_INET6, &udpport_low,
2943                                                &udpport_high),
2944                        "get the default UDP/IPv6 port range");
2945                 if (udpport_low == udpport_high)
2946                         isc_portset_add(v6portset, udpport_low);
2947                 else {
2948                         isc_portset_addrange(v6portset, udpport_low,
2949                                              udpport_high);
2950                 }
2951                 isc_log_write(ns_g_lctx, NS_LOGCATEGORY_GENERAL,
2952                               NS_LOGMODULE_SERVER, ISC_LOG_INFO,
2953                               "using default UDP/IPv6 port range: [%d, %d]",
2954                               udpport_low, udpport_high);
2955         }
2956         (void)ns_config_get(maps, "avoid-v6-udp-ports", &avoidv6ports);
2957         if (avoidv6ports != NULL)
2958                 portset_fromconf(v6portset, avoidv6ports, ISC_FALSE);
2959
2960         dns_dispatchmgr_setavailports(ns_g_dispatchmgr, v4portset, v6portset);
2961
2962         /*
2963          * Set the EDNS UDP size when we don't match a view.
2964          */
2965         obj = NULL;
2966         result = ns_config_get(maps, "edns-udp-size", &obj);
2967         INSIST(result == ISC_R_SUCCESS);
2968         udpsize = cfg_obj_asuint32(obj);
2969         if (udpsize < 512)
2970                 udpsize = 512;
2971         if (udpsize > 4096)
2972                 udpsize = 4096;
2973         ns_g_udpsize = (isc_uint16_t)udpsize;
2974
2975         /*
2976          * Configure the zone manager.
2977          */
2978         obj = NULL;
2979         result = ns_config_get(maps, "transfers-in", &obj);
2980         INSIST(result == ISC_R_SUCCESS);
2981         dns_zonemgr_settransfersin(server->zonemgr, cfg_obj_asuint32(obj));
2982
2983         obj = NULL;
2984         result = ns_config_get(maps, "transfers-per-ns", &obj);
2985         INSIST(result == ISC_R_SUCCESS);
2986         dns_zonemgr_settransfersperns(server->zonemgr, cfg_obj_asuint32(obj));
2987
2988         obj = NULL;
2989         result = ns_config_get(maps, "serial-query-rate", &obj);
2990         INSIST(result == ISC_R_SUCCESS);
2991         dns_zonemgr_setserialqueryrate(server->zonemgr, cfg_obj_asuint32(obj));
2992
2993         /*
2994          * Determine which port to use for listening for incoming connections.
2995          */
2996         if (ns_g_port != 0)
2997                 listen_port = ns_g_port;
2998         else
2999                 CHECKM(ns_config_getport(config, &listen_port), "port");
3000
3001         /*
3002          * Find the listen queue depth.
3003          */
3004         obj = NULL;
3005         result = ns_config_get(maps, "tcp-listen-queue", &obj);
3006         INSIST(result == ISC_R_SUCCESS);
3007         ns_g_listen = cfg_obj_asuint32(obj);
3008         if (ns_g_listen < 3)
3009                 ns_g_listen = 3;
3010
3011         /*
3012          * Configure the interface manager according to the "listen-on"
3013          * statement.
3014          */
3015         {
3016                 const cfg_obj_t *clistenon = NULL;
3017                 ns_listenlist_t *listenon = NULL;
3018
3019                 clistenon = NULL;
3020                 /*
3021                  * Even though listen-on is present in the default
3022                  * configuration, we can't use it here, since it isn't
3023                  * used if we're in lwresd mode.  This way is easier.
3024                  */
3025                 if (options != NULL)
3026                         (void)cfg_map_get(options, "listen-on", &clistenon);
3027                 if (clistenon != NULL) {
3028                         result = ns_listenlist_fromconfig(clistenon,
3029                                                           config,
3030                                                           &aclconfctx,
3031                                                           ns_g_mctx,
3032                                                           &listenon);
3033                 } else if (!ns_g_lwresdonly) {
3034                         /*
3035                          * Not specified, use default.
3036                          */
3037                         CHECK(ns_listenlist_default(ns_g_mctx, listen_port,
3038                                                     ISC_TRUE, &listenon));
3039                 }
3040                 if (listenon != NULL) {
3041                         ns_interfacemgr_setlistenon4(server->interfacemgr,
3042                                                      listenon);
3043                         ns_listenlist_detach(&listenon);
3044                 }
3045         }
3046         /*
3047          * Ditto for IPv6.
3048          */
3049         {
3050                 const cfg_obj_t *clistenon = NULL;
3051                 ns_listenlist_t *listenon = NULL;
3052
3053                 if (options != NULL)
3054                         (void)cfg_map_get(options, "listen-on-v6", &clistenon);
3055                 if (clistenon != NULL) {
3056                         result = ns_listenlist_fromconfig(clistenon,
3057                                                           config,
3058                                                           &aclconfctx,
3059                                                           ns_g_mctx,
3060                                                           &listenon);
3061                 } else if (!ns_g_lwresdonly) {
3062                         /*
3063                          * Not specified, use default.
3064                          */
3065                         CHECK(ns_listenlist_default(ns_g_mctx, listen_port,
3066                                                     ISC_FALSE, &listenon));
3067                 }
3068                 if (listenon != NULL) {
3069                         ns_interfacemgr_setlistenon6(server->interfacemgr,
3070                                                      listenon);
3071                         ns_listenlist_detach(&listenon);
3072                 }
3073         }
3074
3075         /*
3076          * Rescan the interface list to pick up changes in the
3077          * listen-on option.  It's important that we do this before we try
3078          * to configure the query source, since the dispatcher we use might
3079          * be shared with an interface.
3080          */
3081         scan_interfaces(server, ISC_TRUE);
3082
3083         /*
3084          * Arrange for further interface scanning to occur periodically
3085          * as specified by the "interface-interval" option.
3086          */
3087         obj = NULL;
3088         result = ns_config_get(maps, "interface-interval", &obj);
3089         INSIST(result == ISC_R_SUCCESS);
3090         interface_interval = cfg_obj_asuint32(obj) * 60;
3091         if (interface_interval == 0) {
3092                 CHECK(isc_timer_reset(server->interface_timer,
3093                                       isc_timertype_inactive,
3094                                       NULL, NULL, ISC_TRUE));
3095         } else if (server->interface_interval != interface_interval) {
3096                 isc_interval_set(&interval, interface_interval, 0);
3097                 CHECK(isc_timer_reset(server->interface_timer,
3098                                       isc_timertype_ticker,
3099                                       NULL, &interval, ISC_FALSE));
3100         }
3101         server->interface_interval = interface_interval;
3102
3103         /*
3104          * Configure the dialup heartbeat timer.
3105          */
3106         obj = NULL;
3107         result = ns_config_get(maps, "heartbeat-interval", &obj);
3108         INSIST(result == ISC_R_SUCCESS);
3109         heartbeat_interval = cfg_obj_asuint32(obj) * 60;
3110         if (heartbeat_interval == 0) {
3111                 CHECK(isc_timer_reset(server->heartbeat_timer,
3112                                       isc_timertype_inactive,
3113                                       NULL, NULL, ISC_TRUE));
3114         } else if (server->heartbeat_interval != heartbeat_interval) {
3115                 isc_interval_set(&interval, heartbeat_interval, 0);
3116                 CHECK(isc_timer_reset(server->heartbeat_timer,
3117                                       isc_timertype_ticker,
3118                                       NULL, &interval, ISC_FALSE));
3119         }
3120         server->heartbeat_interval = heartbeat_interval;
3121
3122         isc_interval_set(&interval, 1200, 0);
3123         CHECK(isc_timer_reset(server->pps_timer, isc_timertype_ticker, NULL,
3124                               &interval, ISC_FALSE));
3125
3126         /*
3127          * Configure and freeze all explicit views.  Explicit
3128          * views that have zones were already created at parsing
3129          * time, but views with no zones must be created here.
3130          */
3131         views = NULL;
3132         (void)cfg_map_get(config, "view", &views);
3133         for (element = cfg_list_first(views);
3134              element != NULL;
3135              element = cfg_list_next(element))
3136         {
3137                 const cfg_obj_t *vconfig = cfg_listelt_value(element);
3138                 view = NULL;
3139
3140                 CHECK(create_view(vconfig, &viewlist, &view));
3141                 INSIST(view != NULL);
3142                 CHECK(configure_view(view, config, vconfig,
3143                                      ns_g_mctx, &aclconfctx, ISC_TRUE));
3144                 dns_view_freeze(view);
3145                 dns_view_detach(&view);
3146         }
3147
3148         /*
3149          * Make sure we have a default view if and only if there
3150          * were no explicit views.
3151          */
3152         if (views == NULL) {
3153                 /*
3154                  * No explicit views; there ought to be a default view.
3155                  * There may already be one created as a side effect
3156                  * of zone statements, or we may have to create one.
3157                  * In either case, we need to configure and freeze it.
3158                  */
3159                 CHECK(create_view(NULL, &viewlist, &view));
3160                 CHECK(configure_view(view, config, NULL, ns_g_mctx,
3161                                      &aclconfctx, ISC_TRUE));
3162                 dns_view_freeze(view);
3163                 dns_view_detach(&view);
3164         }
3165
3166         /*
3167          * Create (or recreate) the built-in views.  Currently
3168          * there is only one, the _bind view.
3169          */
3170         builtin_views = NULL;
3171         RUNTIME_CHECK(cfg_map_get(ns_g_config, "view",
3172                                   &builtin_views) == ISC_R_SUCCESS);
3173         for (element = cfg_list_first(builtin_views);
3174              element != NULL;
3175              element = cfg_list_next(element))
3176         {
3177                 const cfg_obj_t *vconfig = cfg_listelt_value(element);
3178                 CHECK(create_view(vconfig, &viewlist, &view));
3179                 CHECK(configure_view(view, config, vconfig, ns_g_mctx,
3180                                      &aclconfctx, ISC_FALSE));
3181                 dns_view_freeze(view);
3182                 dns_view_detach(&view);
3183                 view = NULL;
3184         }
3185
3186         /*
3187          * Swap our new view list with the production one.
3188          */
3189         tmpviewlist = server->viewlist;
3190         server->viewlist = viewlist;
3191         viewlist = tmpviewlist;
3192
3193         /*
3194          * Load the TKEY information from the configuration.
3195          */
3196         if (options != NULL) {
3197                 dns_tkeyctx_t *t = NULL;
3198                 CHECKM(ns_tkeyctx_fromconfig(options, ns_g_mctx, ns_g_entropy,
3199                                              &t),
3200                        "configuring TKEY");
3201                 if (server->tkeyctx != NULL)
3202                         dns_tkeyctx_destroy(&server->tkeyctx);
3203                 server->tkeyctx = t;
3204         }
3205
3206         /*
3207          * Bind the control port(s).
3208          */
3209         CHECKM(ns_controls_configure(ns_g_server->controls, config,
3210                                      &aclconfctx),
3211                "binding control channel(s)");
3212
3213         /*
3214          * Bind the lwresd port(s).
3215          */
3216         CHECKM(ns_lwresd_configure(ns_g_mctx, config),
3217                "binding lightweight resolver ports");
3218
3219         /*
3220          * Open the source of entropy.
3221          */
3222         if (first_time) {
3223                 obj = NULL;
3224                 result = ns_config_get(maps, "random-device", &obj);
3225                 if (result != ISC_R_SUCCESS) {
3226                         isc_log_write(ns_g_lctx, NS_LOGCATEGORY_GENERAL,
3227                                       NS_LOGMODULE_SERVER, ISC_LOG_INFO,
3228                                       "no source of entropy found");
3229                 } else {
3230                         const char *randomdev = cfg_obj_asstring(obj);
3231                         result = isc_entropy_createfilesource(ns_g_entropy,
3232                                                               randomdev);
3233                         if (result != ISC_R_SUCCESS)
3234                                 isc_log_write(ns_g_lctx,
3235                                               NS_LOGCATEGORY_GENERAL,
3236                                               NS_LOGMODULE_SERVER,
3237                                               ISC_LOG_INFO,
3238                                               "could not open entropy source "
3239                                               "%s: %s",
3240                                               randomdev,
3241                                               isc_result_totext(result));
3242 #ifdef PATH_RANDOMDEV
3243                         if (ns_g_fallbackentropy != NULL) {
3244                                 if (result != ISC_R_SUCCESS) {
3245                                         isc_log_write(ns_g_lctx,
3246                                                       NS_LOGCATEGORY_GENERAL,
3247                                                       NS_LOGMODULE_SERVER,
3248                                                       ISC_LOG_INFO,
3249                                                       "using pre-chroot entropy source "
3250                                                       "%s",
3251                                                       PATH_RANDOMDEV);
3252                                         isc_entropy_detach(&ns_g_entropy);
3253                                         isc_entropy_attach(ns_g_fallbackentropy,
3254                                                            &ns_g_entropy);
3255                                 }
3256                                 isc_entropy_detach(&ns_g_fallbackentropy);
3257                         }
3258 #endif
3259                 }
3260         }
3261
3262         /*
3263          * Relinquish root privileges.
3264          */
3265         if (first_time)
3266                 ns_os_changeuser();
3267
3268         /*
3269          * Check that the working directory is writable.
3270          */
3271         if (access(".", W_OK) != 0) {
3272                 isc_log_write(ns_g_lctx, NS_LOGCATEGORY_GENERAL,
3273                               NS_LOGMODULE_SERVER, ISC_LOG_ERROR,
3274                               "the working directory is not writable");
3275         }
3276
3277         /*
3278          * Configure the logging system.
3279          *
3280          * Do this after changing UID to make sure that any log
3281          * files specified in named.conf get created by the
3282          * unprivileged user, not root.
3283          */
3284         if (ns_g_logstderr) {
3285                 isc_log_write(ns_g_lctx, NS_LOGCATEGORY_GENERAL,
3286                               NS_LOGMODULE_SERVER, ISC_LOG_INFO,
3287                               "ignoring config file logging "
3288                               "statement due to -g option");
3289         } else {
3290                 const cfg_obj_t *logobj = NULL;
3291                 isc_logconfig_t *logc = NULL;
3292
3293                 CHECKM(isc_logconfig_create(ns_g_lctx, &logc),
3294                        "creating new logging configuration");
3295
3296                 logobj = NULL;
3297                 (void)cfg_map_get(config, "logging", &logobj);
3298                 if (logobj != NULL) {
3299                         CHECKM(ns_log_configure(logc, logobj),
3300                                "configuring logging");
3301                 } else {
3302                         CHECKM(ns_log_setdefaultchannels(logc),
3303                                "setting up default logging channels");
3304                         CHECKM(ns_log_setunmatchedcategory(logc),
3305                                "setting up default 'category unmatched'");
3306                         CHECKM(ns_log_setdefaultcategory(logc),
3307                                "setting up default 'category default'");
3308                 }
3309
3310                 result = isc_logconfig_use(ns_g_lctx, logc);
3311                 if (result != ISC_R_SUCCESS) {
3312                         isc_logconfig_destroy(&logc);
3313                         CHECKM(result, "installing logging configuration");
3314                 }
3315
3316                 isc_log_write(ns_g_lctx, NS_LOGCATEGORY_GENERAL,
3317                               NS_LOGMODULE_SERVER, ISC_LOG_DEBUG(1),
3318                               "now using logging configuration from "
3319                               "config file");
3320         }
3321
3322         /*
3323          * Set the default value of the query logging flag depending
3324          * whether a "queries" category has been defined.  This is
3325          * a disgusting hack, but we need to do this for BIND 8
3326          * compatibility.
3327          */
3328         if (first_time) {
3329                 const cfg_obj_t *logobj = NULL;
3330                 const cfg_obj_t *categories = NULL;
3331
3332                 obj = NULL;
3333                 if (ns_config_get(maps, "querylog", &obj) == ISC_R_SUCCESS) {
3334                         server->log_queries = cfg_obj_asboolean(obj);
3335                 } else {
3336
3337                         (void)cfg_map_get(config, "logging", &logobj);
3338                         if (logobj != NULL)
3339                                 (void)cfg_map_get(logobj, "category",
3340                                                   &categories);
3341                         if (categories != NULL) {
3342                                 const cfg_listelt_t *element;
3343                                 for (element = cfg_list_first(categories);
3344                                      element != NULL;
3345                                      element = cfg_list_next(element))
3346                                 {
3347                                         const cfg_obj_t *catobj;
3348                                         const char *str;
3349
3350                                         obj = cfg_listelt_value(element);
3351                                         catobj = cfg_tuple_get(obj, "name");
3352                                         str = cfg_obj_asstring(catobj);
3353                                         if (strcasecmp(str, "queries") == 0)
3354                                                 server->log_queries = ISC_TRUE;
3355                                 }
3356                         }
3357                 }
3358         }
3359
3360         obj = NULL;
3361         if (ns_config_get(maps, "pid-file", &obj) == ISC_R_SUCCESS)
3362                 if (cfg_obj_isvoid(obj))
3363                         ns_os_writepidfile(NULL, first_time);
3364                 else
3365                         ns_os_writepidfile(cfg_obj_asstring(obj), first_time);
3366         else if (ns_g_lwresdonly)
3367                 ns_os_writepidfile(lwresd_g_defaultpidfile, first_time);
3368         else
3369                 ns_os_writepidfile(ns_g_defaultpidfile, first_time);
3370
3371         obj = NULL;
3372         if (options != NULL &&
3373             cfg_map_get(options, "memstatistics-file", &obj) == ISC_R_SUCCESS)
3374                 ns_main_setmemstats(cfg_obj_asstring(obj));
3375         else
3376                 ns_main_setmemstats(NULL);
3377
3378         obj = NULL;
3379         result = ns_config_get(maps, "statistics-file", &obj);
3380         INSIST(result == ISC_R_SUCCESS);
3381         CHECKM(setstring(server, &server->statsfile, cfg_obj_asstring(obj)),
3382                "strdup");
3383
3384         obj = NULL;
3385         result = ns_config_get(maps, "dump-file", &obj);
3386         INSIST(result == ISC_R_SUCCESS);
3387         CHECKM(setstring(server, &server->dumpfile, cfg_obj_asstring(obj)),
3388                "strdup");
3389
3390         obj = NULL;
3391         result = ns_config_get(maps, "recursing-file", &obj);
3392         INSIST(result == ISC_R_SUCCESS);
3393         CHECKM(setstring(server, &server->recfile, cfg_obj_asstring(obj)),
3394                "strdup");
3395
3396         obj = NULL;
3397         result = ns_config_get(maps, "version", &obj);
3398         if (result == ISC_R_SUCCESS) {
3399                 CHECKM(setoptstring(server, &server->version, obj), "strdup");
3400                 server->version_set = ISC_TRUE;
3401         } else {
3402                 server->version_set = ISC_FALSE;
3403         }
3404
3405         obj = NULL;
3406         result = ns_config_get(maps, "hostname", &obj);
3407         if (result == ISC_R_SUCCESS) {
3408                 CHECKM(setoptstring(server, &server->hostname, obj), "strdup");
3409                 server->hostname_set = ISC_TRUE;
3410         } else {
3411                 server->hostname_set = ISC_FALSE;
3412         }
3413
3414         obj = NULL;
3415         result = ns_config_get(maps, "server-id", &obj);
3416         server->server_usehostname = ISC_FALSE;
3417         if (result == ISC_R_SUCCESS && cfg_obj_isboolean(obj)) {
3418                 server->server_usehostname = ISC_TRUE;
3419         } else if (result == ISC_R_SUCCESS) {
3420                 CHECKM(setoptstring(server, &server->server_id, obj), "strdup");
3421         } else {
3422                 result = setstring(server, &server->server_id, NULL);
3423                 RUNTIME_CHECK(result == ISC_R_SUCCESS);
3424         }
3425
3426         obj = NULL;
3427         result = ns_config_get(maps, "flush-zones-on-shutdown", &obj);
3428         if (result == ISC_R_SUCCESS) {
3429                 server->flushonshutdown = cfg_obj_asboolean(obj);
3430         } else {
3431                 server->flushonshutdown = ISC_FALSE;
3432         }
3433
3434         result = ISC_R_SUCCESS;
3435
3436  cleanup:
3437         if (v4portset != NULL)
3438                 isc_portset_destroy(ns_g_mctx, &v4portset);
3439
3440         if (v6portset != NULL)
3441                 isc_portset_destroy(ns_g_mctx, &v6portset);
3442
3443         cfg_aclconfctx_destroy(&aclconfctx);
3444
3445         if (parser != NULL) {
3446                 if (config != NULL)
3447                         cfg_obj_destroy(parser, &config);
3448                 cfg_parser_destroy(&parser);
3449         }
3450
3451         if (view != NULL)
3452                 dns_view_detach(&view);
3453
3454         /*
3455          * This cleans up either the old production view list
3456          * or our temporary list depending on whether they
3457          * were swapped above or not.
3458          */
3459         for (view = ISC_LIST_HEAD(viewlist);
3460              view != NULL;
3461              view = view_next) {
3462                 view_next = ISC_LIST_NEXT(view, link);
3463                 ISC_LIST_UNLINK(viewlist, view, link);
3464                 if (result == ISC_R_SUCCESS &&
3465                     strcmp(view->name, "_bind") != 0)
3466                         (void)dns_zt_apply(view->zonetable, ISC_FALSE,
3467                                            removed, view);
3468                 dns_view_detach(&view);
3469         }
3470
3471         /*
3472          * Adjust the listening interfaces in accordance with the source
3473          * addresses specified in views and zones.
3474          */
3475         if (isc_net_probeipv6() == ISC_R_SUCCESS)
3476                 adjust_interfaces(server, ns_g_mctx);
3477
3478         /* Relinquish exclusive access to configuration data. */
3479         isc_task_endexclusive(server->task);
3480
3481         isc_log_write(ns_g_lctx, NS_LOGCATEGORY_GENERAL, NS_LOGMODULE_SERVER,
3482                       ISC_LOG_DEBUG(1), "load_configuration: %s",
3483                       isc_result_totext(result));
3484
3485         return (result);
3486 }
3487
3488 static isc_result_t
3489 load_zones(ns_server_t *server, isc_boolean_t stop) {
3490         isc_result_t result;
3491         dns_view_t *view;
3492
3493         result = isc_task_beginexclusive(server->task);
3494         RUNTIME_CHECK(result == ISC_R_SUCCESS);
3495
3496         /*
3497          * Load zone data from disk.
3498          */
3499         for (view = ISC_LIST_HEAD(server->viewlist);
3500              view != NULL;
3501              view = ISC_LIST_NEXT(view, link))
3502         {
3503                 CHECK(dns_view_load(view, stop));
3504         }
3505
3506         /*
3507          * Force zone maintenance.  Do this after loading
3508          * so that we know when we need to force AXFR of
3509          * slave zones whose master files are missing.
3510          */
3511         CHECK(dns_zonemgr_forcemaint(server->zonemgr));
3512  cleanup:
3513         isc_task_endexclusive(server->task);
3514         return (result);
3515 }
3516
3517 static isc_result_t
3518 load_new_zones(ns_server_t *server, isc_boolean_t stop) {
3519         isc_result_t result;
3520         dns_view_t *view;
3521
3522         result = isc_task_beginexclusive(server->task);
3523         RUNTIME_CHECK(result == ISC_R_SUCCESS);
3524
3525         /*
3526          * Load zone data from disk.
3527          */
3528         for (view = ISC_LIST_HEAD(server->viewlist);
3529              view != NULL;
3530              view = ISC_LIST_NEXT(view, link))
3531         {
3532                 CHECK(dns_view_loadnew(view, stop));
3533         }
3534         /*
3535          * Force zone maintenance.  Do this after loading
3536          * so that we know when we need to force AXFR of
3537          * slave zones whose master files are missing.
3538          */
3539         dns_zonemgr_resumexfrs(server->zonemgr);
3540  cleanup:
3541         isc_task_endexclusive(server->task);
3542         return (result);
3543 }
3544
3545 static void
3546 run_server(isc_task_t *task, isc_event_t *event) {
3547         isc_result_t result;
3548         ns_server_t *server = (ns_server_t *)event->ev_arg;
3549
3550         INSIST(task == server->task);
3551
3552         isc_event_free(&event);
3553
3554         CHECKFATAL(dns_dispatchmgr_create(ns_g_mctx, ns_g_entropy,
3555                                           &ns_g_dispatchmgr),
3556                    "creating dispatch manager");
3557
3558         CHECKFATAL(ns_interfacemgr_create(ns_g_mctx, ns_g_taskmgr,
3559                                           ns_g_socketmgr, ns_g_dispatchmgr,
3560                                           &server->interfacemgr),
3561                    "creating interface manager");
3562
3563         CHECKFATAL(isc_timer_create(ns_g_timermgr, isc_timertype_inactive,
3564                                     NULL, NULL, server->task,
3565                                     interface_timer_tick,
3566                                     server, &server->interface_timer),
3567                    "creating interface timer");
3568
3569         CHECKFATAL(isc_timer_create(ns_g_timermgr, isc_timertype_inactive,
3570                                     NULL, NULL, server->task,
3571                                     heartbeat_timer_tick,
3572                                     server, &server->heartbeat_timer),
3573                    "creating heartbeat timer");
3574
3575         CHECKFATAL(isc_timer_create(ns_g_timermgr, isc_timertype_inactive,
3576                                     NULL, NULL, server->task, pps_timer_tick,
3577                                     server, &server->pps_timer),
3578                    "creating pps timer");
3579
3580         CHECKFATAL(cfg_parser_create(ns_g_mctx, NULL, &ns_g_parser),
3581                    "creating default configuration parser");
3582
3583         if (ns_g_lwresdonly)
3584                 CHECKFATAL(load_configuration(lwresd_g_conffile, server,
3585                                               ISC_TRUE),
3586                            "loading configuration");
3587         else
3588                 CHECKFATAL(load_configuration(ns_g_conffile, server, ISC_TRUE),
3589                            "loading configuration");
3590
3591         isc_hash_init();
3592
3593         CHECKFATAL(load_zones(server, ISC_FALSE), "loading zones");
3594
3595         ns_os_started();
3596         isc_log_write(ns_g_lctx, NS_LOGCATEGORY_GENERAL, NS_LOGMODULE_SERVER,
3597                       ISC_LOG_NOTICE, "running");
3598 }
3599
3600 void
3601 ns_server_flushonshutdown(ns_server_t *server, isc_boolean_t flush) {
3602
3603         REQUIRE(NS_SERVER_VALID(server));
3604
3605         server->flushonshutdown = flush;
3606 }
3607
3608 static void
3609 shutdown_server(isc_task_t *task, isc_event_t *event) {
3610         isc_result_t result;
3611         dns_view_t *view, *view_next;
3612         ns_server_t *server = (ns_server_t *)event->ev_arg;
3613         isc_boolean_t flush = server->flushonshutdown;
3614
3615         UNUSED(task);
3616         INSIST(task == server->task);
3617
3618         result = isc_task_beginexclusive(server->task);
3619         RUNTIME_CHECK(result == ISC_R_SUCCESS);
3620
3621         isc_log_write(ns_g_lctx, NS_LOGCATEGORY_GENERAL, NS_LOGMODULE_SERVER,
3622                       ISC_LOG_INFO, "shutting down%s",
3623                       flush ? ": flushing changes" : "");
3624
3625         ns_controls_shutdown(server->controls);
3626         end_reserved_dispatches(server, ISC_TRUE);
3627
3628         cfg_obj_destroy(ns_g_parser, &ns_g_config);
3629         cfg_parser_destroy(&ns_g_parser);
3630
3631         for (view = ISC_LIST_HEAD(server->viewlist);
3632              view != NULL;
3633              view = view_next) {
3634                 view_next = ISC_LIST_NEXT(view, link);
3635                 ISC_LIST_UNLINK(server->viewlist, view, link);
3636                 if (flush)
3637                         dns_view_flushanddetach(&view);
3638                 else
3639                         dns_view_detach(&view);
3640         }
3641
3642         isc_timer_detach(&server->interface_timer);
3643         isc_timer_detach(&server->heartbeat_timer);
3644         isc_timer_detach(&server->pps_timer);
3645
3646         ns_interfacemgr_shutdown(server->interfacemgr);
3647         ns_interfacemgr_detach(&server->interfacemgr);
3648
3649         dns_dispatchmgr_destroy(&ns_g_dispatchmgr);
3650
3651         dns_zonemgr_shutdown(server->zonemgr);
3652
3653         if (server->blackholeacl != NULL)
3654                 dns_acl_detach(&server->blackholeacl);
3655
3656         dns_db_detach(&server->in_roothints);
3657
3658         isc_task_endexclusive(server->task);
3659
3660         isc_task_detach(&server->task);
3661
3662         isc_event_free(&event);
3663 }
3664
3665 void
3666 ns_server_create(isc_mem_t *mctx, ns_server_t **serverp) {
3667         isc_result_t result;
3668
3669         ns_server_t *server = isc_mem_get(mctx, sizeof(*server));
3670         if (server == NULL)
3671                 fatal("allocating server object", ISC_R_NOMEMORY);
3672
3673         server->mctx = mctx;
3674         server->task = NULL;
3675
3676         /* Initialize configuration data with default values. */
3677
3678         result = isc_quota_init(&server->xfroutquota, 10);
3679         RUNTIME_CHECK(result == ISC_R_SUCCESS);
3680         result = isc_quota_init(&server->tcpquota, 10);
3681         RUNTIME_CHECK(result == ISC_R_SUCCESS);
3682         result = isc_quota_init(&server->recursionquota, 100);
3683         RUNTIME_CHECK(result == ISC_R_SUCCESS);
3684
3685         result = dns_aclenv_init(mctx, &server->aclenv);
3686         RUNTIME_CHECK(result == ISC_R_SUCCESS);
3687
3688         /* Initialize server data structures. */
3689         server->zonemgr = NULL;
3690         server->interfacemgr = NULL;
3691         ISC_LIST_INIT(server->viewlist);
3692         server->in_roothints = NULL;
3693         server->blackholeacl = NULL;
3694
3695         CHECKFATAL(dns_rootns_create(mctx, dns_rdataclass_in, NULL,
3696                                      &server->in_roothints),
3697                    "setting up root hints");
3698
3699         CHECKFATAL(isc_mutex_init(&server->reload_event_lock),
3700                    "initializing reload event lock");
3701         server->reload_event =
3702                 isc_event_allocate(ns_g_mctx, server,
3703                                    NS_EVENT_RELOAD,
3704                                    ns_server_reload,
3705                                    server,
3706                                    sizeof(isc_event_t));
3707         CHECKFATAL(server->reload_event == NULL ?
3708                    ISC_R_NOMEMORY : ISC_R_SUCCESS,
3709                    "allocating reload event");
3710
3711         CHECKFATAL(dst_lib_init(ns_g_mctx, ns_g_entropy, ISC_ENTROPY_GOODONLY),
3712                    "initializing DST");
3713
3714         server->tkeyctx = NULL;
3715         CHECKFATAL(dns_tkeyctx_create(ns_g_mctx, ns_g_entropy,
3716                                       &server->tkeyctx),
3717                    "creating TKEY context");
3718
3719         /*
3720          * Setup the server task, which is responsible for coordinating
3721          * startup and shutdown of the server.
3722          */
3723         CHECKFATAL(isc_task_create(ns_g_taskmgr, 0, &server->task),
3724                    "creating server task");
3725         isc_task_setname(server->task, "server", server);
3726         CHECKFATAL(isc_task_onshutdown(server->task, shutdown_server, server),
3727                    "isc_task_onshutdown");
3728         CHECKFATAL(isc_app_onrun(ns_g_mctx, server->task, run_server, server),
3729                    "isc_app_onrun");
3730
3731         server->interface_timer = NULL;
3732         server->heartbeat_timer = NULL;
3733         server->pps_timer = NULL;
3734
3735         server->interface_interval = 0;
3736         server->heartbeat_interval = 0;
3737
3738         CHECKFATAL(dns_zonemgr_create(ns_g_mctx, ns_g_taskmgr, ns_g_timermgr,
3739                                       ns_g_socketmgr, &server->zonemgr),
3740                    "dns_zonemgr_create");
3741
3742         server->statsfile = isc_mem_strdup(server->mctx, "named.stats");
3743         CHECKFATAL(server->statsfile == NULL ? ISC_R_NOMEMORY : ISC_R_SUCCESS,
3744                    "isc_mem_strdup");
3745         server->querystats = NULL;
3746
3747         server->dumpfile = isc_mem_strdup(server->mctx, "named_dump.db");
3748         CHECKFATAL(server->dumpfile == NULL ? ISC_R_NOMEMORY : ISC_R_SUCCESS,
3749                    "isc_mem_strdup");
3750
3751         server->recfile = isc_mem_strdup(server->mctx, "named.recursing");
3752         CHECKFATAL(server->recfile == NULL ? ISC_R_NOMEMORY : ISC_R_SUCCESS,
3753                    "isc_mem_strdup");
3754
3755         server->hostname_set = ISC_FALSE;
3756         server->hostname = NULL;
3757         server->version_set = ISC_FALSE;
3758         server->version = NULL;
3759         server->server_usehostname = ISC_FALSE;
3760         server->server_id = NULL;
3761
3762         CHECKFATAL(dns_stats_alloccounters(ns_g_mctx, &server->querystats),
3763                    "dns_stats_alloccounters");
3764
3765         server->flushonshutdown = ISC_FALSE;
3766         server->log_queries = ISC_FALSE;
3767
3768         server->controls = NULL;
3769         CHECKFATAL(ns_controls_create(server, &server->controls),
3770                    "ns_controls_create");
3771         server->dispatchgen = 0;
3772         ISC_LIST_INIT(server->dispatches);
3773
3774         server->magic = NS_SERVER_MAGIC;
3775         *serverp = server;
3776 }
3777
3778 void
3779 ns_server_destroy(ns_server_t **serverp) {
3780         ns_server_t *server = *serverp;
3781         REQUIRE(NS_SERVER_VALID(server));
3782
3783         ns_controls_destroy(&server->controls);
3784
3785         dns_stats_freecounters(server->mctx, &server->querystats);
3786
3787         isc_mem_free(server->mctx, server->statsfile);
3788         isc_mem_free(server->mctx, server->dumpfile);
3789         isc_mem_free(server->mctx, server->recfile);
3790
3791         if (server->version != NULL)
3792                 isc_mem_free(server->mctx, server->version);
3793         if (server->hostname != NULL)
3794                 isc_mem_free(server->mctx, server->hostname);
3795         if (server->server_id != NULL)
3796                 isc_mem_free(server->mctx, server->server_id);
3797
3798         dns_zonemgr_detach(&server->zonemgr);
3799
3800         if (server->tkeyctx != NULL)
3801                 dns_tkeyctx_destroy(&server->tkeyctx);
3802
3803         dst_lib_destroy();
3804
3805         isc_event_free(&server->reload_event);
3806
3807         INSIST(ISC_LIST_EMPTY(server->viewlist));
3808
3809         dns_aclenv_destroy(&server->aclenv);
3810
3811         isc_quota_destroy(&server->recursionquota);
3812         isc_quota_destroy(&server->tcpquota);
3813         isc_quota_destroy(&server->xfroutquota);
3814
3815         server->magic = 0;
3816         isc_mem_put(server->mctx, server, sizeof(*server));
3817         *serverp = NULL;
3818 }
3819
3820 static void
3821 fatal(const char *msg, isc_result_t result) {
3822         isc_log_write(ns_g_lctx, NS_LOGCATEGORY_GENERAL, NS_LOGMODULE_SERVER,
3823                       ISC_LOG_CRITICAL, "%s: %s", msg,
3824                       isc_result_totext(result));
3825         isc_log_write(ns_g_lctx, NS_LOGCATEGORY_GENERAL, NS_LOGMODULE_SERVER,
3826                       ISC_LOG_CRITICAL, "exiting (due to fatal error)");
3827         exit(1);
3828 }
3829
3830 static void
3831 start_reserved_dispatches(ns_server_t *server) {
3832
3833         REQUIRE(NS_SERVER_VALID(server));
3834
3835         server->dispatchgen++;
3836 }
3837
3838 static void
3839 end_reserved_dispatches(ns_server_t *server, isc_boolean_t all) {
3840         ns_dispatch_t *dispatch, *nextdispatch;
3841
3842         REQUIRE(NS_SERVER_VALID(server));
3843
3844         for (dispatch = ISC_LIST_HEAD(server->dispatches);
3845              dispatch != NULL;
3846              dispatch = nextdispatch) {
3847                 nextdispatch = ISC_LIST_NEXT(dispatch, link);
3848                 if (!all && server->dispatchgen == dispatch-> dispatchgen)
3849                         continue;
3850                 ISC_LIST_UNLINK(server->dispatches, dispatch, link);
3851                 dns_dispatch_detach(&dispatch->dispatch);
3852                 isc_mem_put(server->mctx, dispatch, sizeof(*dispatch));
3853         }
3854 }
3855
3856 void
3857 ns_add_reserved_dispatch(ns_server_t *server, const isc_sockaddr_t *addr) {
3858         ns_dispatch_t *dispatch;
3859         in_port_t port;
3860         char addrbuf[ISC_SOCKADDR_FORMATSIZE];
3861         isc_result_t result;
3862         unsigned int attrs, attrmask;
3863
3864         REQUIRE(NS_SERVER_VALID(server));
3865
3866         port = isc_sockaddr_getport(addr);
3867         if (port == 0 || port >= 1024)
3868                 return;
3869
3870         for (dispatch = ISC_LIST_HEAD(server->dispatches);
3871              dispatch != NULL;
3872              dispatch = ISC_LIST_NEXT(dispatch, link)) {
3873                 if (isc_sockaddr_equal(&dispatch->addr, addr))
3874                         break;
3875         }
3876         if (dispatch != NULL) {
3877                 dispatch->dispatchgen = server->dispatchgen;
3878                 return;
3879         }
3880
3881         dispatch = isc_mem_get(server->mctx, sizeof(*dispatch));
3882         if (dispatch == NULL) {
3883                 result = ISC_R_NOMEMORY;
3884                 goto cleanup;
3885         }
3886
3887         dispatch->addr = *addr;
3888         dispatch->dispatchgen = server->dispatchgen;
3889         dispatch->dispatch = NULL;
3890
3891         attrs = 0;
3892         attrs |= DNS_DISPATCHATTR_UDP;
3893         switch (isc_sockaddr_pf(addr)) {
3894         case AF_INET:
3895                 attrs |= DNS_DISPATCHATTR_IPV4;
3896                 break;
3897         case AF_INET6:
3898                 attrs |= DNS_DISPATCHATTR_IPV6;
3899                 break;
3900         default:
3901                 result = ISC_R_NOTIMPLEMENTED;
3902                 goto cleanup;
3903         }
3904         attrmask = 0;
3905         attrmask |= DNS_DISPATCHATTR_UDP;
3906         attrmask |= DNS_DISPATCHATTR_TCP;
3907         attrmask |= DNS_DISPATCHATTR_IPV4;
3908         attrmask |= DNS_DISPATCHATTR_IPV6;
3909
3910         result = dns_dispatch_getudp(ns_g_dispatchmgr, ns_g_socketmgr,
3911                                      ns_g_taskmgr, &dispatch->addr, 4096,
3912                                      1000, 32768, 16411, 16433,
3913                                      attrs, attrmask, &dispatch->dispatch);
3914         if (result != ISC_R_SUCCESS)
3915                 goto cleanup;
3916
3917         ISC_LIST_INITANDPREPEND(server->dispatches, dispatch, link);
3918
3919         return;
3920
3921  cleanup:
3922         if (dispatch != NULL)
3923                 isc_mem_put(server->mctx, dispatch, sizeof(*dispatch));
3924         isc_sockaddr_format(addr, addrbuf, sizeof(addrbuf));
3925         isc_log_write(ns_g_lctx, NS_LOGCATEGORY_GENERAL,
3926                       NS_LOGMODULE_SERVER, ISC_LOG_WARNING,
3927                       "unable to create dispatch for reserved port %s: %s",
3928                       addrbuf, isc_result_totext(result));
3929 }
3930
3931
3932 static isc_result_t
3933 loadconfig(ns_server_t *server) {
3934         isc_result_t result;
3935         start_reserved_dispatches(server);
3936         result = load_configuration(ns_g_lwresdonly ?
3937                                     lwresd_g_conffile : ns_g_conffile,
3938                                     server, ISC_FALSE);
3939         if (result == ISC_R_SUCCESS)
3940                 end_reserved_dispatches(server, ISC_FALSE);
3941         else
3942                 isc_log_write(ns_g_lctx, NS_LOGCATEGORY_GENERAL,
3943                               NS_LOGMODULE_SERVER, ISC_LOG_ERROR,
3944                               "reloading configuration failed: %s",
3945                               isc_result_totext(result));
3946         return (result);
3947 }
3948
3949 static isc_result_t
3950 reload(ns_server_t *server) {
3951         isc_result_t result;
3952         CHECK(loadconfig(server));
3953
3954         result = load_zones(server, ISC_FALSE);
3955         if (result != ISC_R_SUCCESS) {
3956                 isc_log_write(ns_g_lctx, NS_LOGCATEGORY_GENERAL,
3957                               NS_LOGMODULE_SERVER, ISC_LOG_ERROR,
3958                               "reloading zones failed: %s",
3959                               isc_result_totext(result));
3960         }
3961  cleanup:
3962         return (result);
3963 }
3964
3965 static void
3966 reconfig(ns_server_t *server) {
3967         isc_result_t result;
3968         CHECK(loadconfig(server));
3969
3970         result = load_new_zones(server, ISC_FALSE);
3971         if (result != ISC_R_SUCCESS) {
3972                 isc_log_write(ns_g_lctx, NS_LOGCATEGORY_GENERAL,
3973                               NS_LOGMODULE_SERVER, ISC_LOG_ERROR,
3974                               "loading new zones failed: %s",
3975                               isc_result_totext(result));
3976         }
3977  cleanup: ;
3978 }
3979
3980 /*
3981  * Handle a reload event (from SIGHUP).
3982  */
3983 static void
3984 ns_server_reload(isc_task_t *task, isc_event_t *event) {
3985         ns_server_t *server = (ns_server_t *)event->ev_arg;
3986
3987         INSIST(task = server->task);
3988         UNUSED(task);
3989
3990         (void)reload(server);
3991
3992         LOCK(&server->reload_event_lock);
3993         INSIST(server->reload_event == NULL);
3994         server->reload_event = event;
3995         UNLOCK(&server->reload_event_lock);
3996 }
3997
3998 void
3999 ns_server_reloadwanted(ns_server_t *server) {
4000         LOCK(&server->reload_event_lock);
4001         if (server->reload_event != NULL)
4002                 isc_task_send(server->task, &server->reload_event);
4003         UNLOCK(&server->reload_event_lock);
4004 }
4005
4006 static char *
4007 next_token(char **stringp, const char *delim) {
4008         char *res;
4009
4010         do {
4011                 res = strsep(stringp, delim);
4012                 if (res == NULL)
4013                         break;
4014         } while (*res == '\0');
4015         return (res);
4016 }
4017
4018 /*
4019  * Find the zone specified in the control channel command 'args',
4020  * if any.  If a zone is specified, point '*zonep' at it, otherwise
4021  * set '*zonep' to NULL.
4022  */
4023 static isc_result_t
4024 zone_from_args(ns_server_t *server, char *args, dns_zone_t **zonep) {
4025         char *input, *ptr;
4026         const char *zonetxt;
4027         char *classtxt;
4028         const char *viewtxt = NULL;
4029         dns_fixedname_t name;
4030         isc_result_t result;
4031         isc_buffer_t buf;
4032         dns_view_t *view = NULL;
4033         dns_rdataclass_t rdclass;
4034
4035         REQUIRE(zonep != NULL && *zonep == NULL);
4036
4037         input = args;
4038
4039         /* Skip the command name. */
4040         ptr = next_token(&input, " \t");
4041         if (ptr == NULL)
4042                 return (ISC_R_UNEXPECTEDEND);
4043
4044         /* Look for the zone name. */
4045         zonetxt = next_token(&input, " \t");
4046         if (zonetxt == NULL)
4047                 return (ISC_R_SUCCESS);
4048
4049         /* Look for the optional class name. */
4050         classtxt = next_token(&input, " \t");
4051         if (classtxt != NULL) {
4052                 /* Look for the optional view name. */
4053                 viewtxt = next_token(&input, " \t");
4054         }
4055
4056         isc_buffer_init(&buf, zonetxt, strlen(zonetxt));
4057         isc_buffer_add(&buf, strlen(zonetxt));
4058         dns_fixedname_init(&name);
4059         result = dns_name_fromtext(dns_fixedname_name(&name),
4060                                    &buf, dns_rootname, ISC_FALSE, NULL);
4061         if (result != ISC_R_SUCCESS)
4062                 goto fail1;
4063
4064         if (classtxt != NULL) {
4065                 isc_textregion_t r;
4066                 r.base = classtxt;
4067                 r.length = strlen(classtxt);
4068                 result = dns_rdataclass_fromtext(&rdclass, &r);
4069                 if (result != ISC_R_SUCCESS)
4070                         goto fail1;
4071         } else {
4072                 rdclass = dns_rdataclass_in;
4073         }
4074
4075         if (viewtxt == NULL)
4076                 viewtxt = "_default";
4077         result = dns_viewlist_find(&server->viewlist, viewtxt,
4078                                    rdclass, &view);
4079         if (result != ISC_R_SUCCESS)
4080                 goto fail1;
4081
4082         result = dns_zt_find(view->zonetable, dns_fixedname_name(&name),
4083                              0, NULL, zonep);
4084         /* Partial match? */
4085         if (result != ISC_R_SUCCESS && *zonep != NULL)
4086                 dns_zone_detach(zonep);
4087         dns_view_detach(&view);
4088  fail1:
4089         return (result);
4090 }
4091
4092 /*
4093  * Act on a "retransfer" command from the command channel.
4094  */
4095 isc_result_t
4096 ns_server_retransfercommand(ns_server_t *server, char *args) {
4097         isc_result_t result;
4098         dns_zone_t *zone = NULL;
4099         dns_zonetype_t type;
4100
4101         result = zone_from_args(server, args, &zone);
4102         if (result != ISC_R_SUCCESS)
4103                 return (result);
4104         if (zone == NULL)
4105                 return (ISC_R_UNEXPECTEDEND);
4106         type = dns_zone_gettype(zone);
4107         if (type == dns_zone_slave || type == dns_zone_stub)
4108                 dns_zone_forcereload(zone);
4109         else
4110                 result = ISC_R_NOTFOUND;
4111         dns_zone_detach(&zone);
4112         return (result);
4113 }
4114
4115 /*
4116  * Act on a "reload" command from the command channel.
4117  */
4118 isc_result_t
4119 ns_server_reloadcommand(ns_server_t *server, char *args, isc_buffer_t *text) {
4120         isc_result_t result;
4121         dns_zone_t *zone = NULL;
4122         dns_zonetype_t type;
4123         const char *msg = NULL;
4124
4125         result = zone_from_args(server, args, &zone);
4126         if (result != ISC_R_SUCCESS)
4127                 return (result);
4128         if (zone == NULL) {
4129                 result = reload(server);
4130                 if (result == ISC_R_SUCCESS)
4131                         msg = "server reload successful";
4132         } else {
4133                 type = dns_zone_gettype(zone);
4134                 if (type == dns_zone_slave || type == dns_zone_stub) {
4135                         dns_zone_refresh(zone);
4136                         dns_zone_detach(&zone);
4137                         msg = "zone refresh queued";
4138                 } else {
4139                         result = dns_zone_load(zone);
4140                         dns_zone_detach(&zone);
4141                         switch (result) {
4142                         case ISC_R_SUCCESS:
4143                                  msg = "zone reload successful";
4144                                  break;
4145                         case DNS_R_CONTINUE:
4146                                 msg = "zone reload queued";
4147                                 result = ISC_R_SUCCESS;
4148                                 break;
4149                         case DNS_R_UPTODATE:
4150                                 msg = "zone reload up-to-date";
4151                                 result = ISC_R_SUCCESS;
4152                                 break;
4153                         default:
4154                                 /* failure message will be generated by rndc */
4155                                 break;
4156                         }
4157                 }
4158         }
4159         if (msg != NULL && strlen(msg) < isc_buffer_availablelength(text))
4160                 isc_buffer_putmem(text, (const unsigned char *)msg,
4161                                   strlen(msg) + 1);
4162         return (result);
4163 }
4164
4165 /*
4166  * Act on a "reconfig" command from the command channel.
4167  */
4168 isc_result_t
4169 ns_server_reconfigcommand(ns_server_t *server, char *args) {
4170         UNUSED(args);
4171
4172         reconfig(server);
4173         return (ISC_R_SUCCESS);
4174 }
4175
4176 /*
4177  * Act on a "notify" command from the command channel.
4178  */
4179 isc_result_t
4180 ns_server_notifycommand(ns_server_t *server, char *args, isc_buffer_t *text) {
4181         isc_result_t result;
4182         dns_zone_t *zone = NULL;
4183         const unsigned char msg[] = "zone notify queued";
4184
4185         result = zone_from_args(server, args, &zone);
4186         if (result != ISC_R_SUCCESS)
4187                 return (result);
4188         if (zone == NULL)
4189                 return (ISC_R_UNEXPECTEDEND);
4190
4191         dns_zone_notify(zone);
4192         dns_zone_detach(&zone);
4193         if (sizeof(msg) <= isc_buffer_availablelength(text))
4194                 isc_buffer_putmem(text, msg, sizeof(msg));
4195
4196         return (ISC_R_SUCCESS);
4197 }
4198
4199 /*
4200  * Act on a "refresh" command from the command channel.
4201  */
4202 isc_result_t
4203 ns_server_refreshcommand(ns_server_t *server, char *args, isc_buffer_t *text) {
4204         isc_result_t result;
4205         dns_zone_t *zone = NULL;
4206         const unsigned char msg1[] = "zone refresh queued";
4207         const unsigned char msg2[] = "not a slave or stub zone";
4208         dns_zonetype_t type;
4209
4210         result = zone_from_args(server, args, &zone);
4211         if (result != ISC_R_SUCCESS)
4212                 return (result);
4213         if (zone == NULL)
4214                 return (ISC_R_UNEXPECTEDEND);
4215
4216         type = dns_zone_gettype(zone);
4217         if (type == dns_zone_slave || type == dns_zone_stub) {
4218                 dns_zone_refresh(zone);
4219                 dns_zone_detach(&zone);
4220                 if (sizeof(msg1) <= isc_buffer_availablelength(text))
4221                         isc_buffer_putmem(text, msg1, sizeof(msg1));
4222                 return (ISC_R_SUCCESS);
4223         }
4224
4225         dns_zone_detach(&zone);
4226         if (sizeof(msg2) <= isc_buffer_availablelength(text))
4227                 isc_buffer_putmem(text, msg2, sizeof(msg2));
4228         return (ISC_R_FAILURE);
4229 }
4230
4231 isc_result_t
4232 ns_server_togglequerylog(ns_server_t *server) {
4233         server->log_queries = server->log_queries ? ISC_FALSE : ISC_TRUE;
4234
4235         isc_log_write(ns_g_lctx, NS_LOGCATEGORY_GENERAL,
4236                       NS_LOGMODULE_SERVER, ISC_LOG_INFO,
4237                       "query logging is now %s",
4238                       server->log_queries ? "on" : "off");
4239         return (ISC_R_SUCCESS);
4240 }
4241
4242 static isc_result_t
4243 ns_listenlist_fromconfig(const cfg_obj_t *listenlist, const cfg_obj_t *config,
4244                          cfg_aclconfctx_t *actx,
4245                          isc_mem_t *mctx, ns_listenlist_t **target)
4246 {
4247         isc_result_t result;
4248         const cfg_listelt_t *element;
4249         ns_listenlist_t *dlist = NULL;
4250
4251         REQUIRE(target != NULL && *target == NULL);
4252
4253         result = ns_listenlist_create(mctx, &dlist);
4254         if (result != ISC_R_SUCCESS)
4255                 return (result);
4256
4257         for (element = cfg_list_first(listenlist);
4258              element != NULL;
4259              element = cfg_list_next(element))
4260         {
4261                 ns_listenelt_t *delt = NULL;
4262                 const cfg_obj_t *listener = cfg_listelt_value(element);
4263                 result = ns_listenelt_fromconfig(listener, config, actx,
4264                                                  mctx, &delt);
4265                 if (result != ISC_R_SUCCESS)
4266                         goto cleanup;
4267                 ISC_LIST_APPEND(dlist->elts, delt, link);
4268         }
4269         *target = dlist;
4270         return (ISC_R_SUCCESS);
4271
4272  cleanup:
4273         ns_listenlist_detach(&dlist);
4274         return (result);
4275 }
4276
4277 /*
4278  * Create a listen list from the corresponding configuration
4279  * data structure.
4280  */
4281 static isc_result_t
4282 ns_listenelt_fromconfig(const cfg_obj_t *listener, const cfg_obj_t *config,
4283                         cfg_aclconfctx_t *actx,
4284                         isc_mem_t *mctx, ns_listenelt_t **target)
4285 {
4286         isc_result_t result;
4287         const cfg_obj_t *portobj;
4288         in_port_t port;
4289         ns_listenelt_t *delt = NULL;
4290         REQUIRE(target != NULL && *target == NULL);
4291
4292         portobj = cfg_tuple_get(listener, "port");
4293         if (!cfg_obj_isuint32(portobj)) {
4294                 if (ns_g_port != 0) {
4295                         port = ns_g_port;
4296                 } else {
4297                         result = ns_config_getport(config, &port);
4298                         if (result != ISC_R_SUCCESS)
4299                                 return (result);
4300                 }
4301         } else {
4302                 if (cfg_obj_asuint32(portobj) >= ISC_UINT16_MAX) {
4303                         cfg_obj_log(portobj, ns_g_lctx, ISC_LOG_ERROR,
4304                                     "port value '%u' is out of range",
4305                                     cfg_obj_asuint32(portobj));
4306                         return (ISC_R_RANGE);
4307                 }
4308                 port = (in_port_t)cfg_obj_asuint32(portobj);
4309         }
4310
4311         result = ns_listenelt_create(mctx, port, NULL, &delt);
4312         if (result != ISC_R_SUCCESS)
4313                 return (result);
4314
4315         result = cfg_acl_fromconfig(cfg_tuple_get(listener, "acl"),
4316                                    config, ns_g_lctx, actx, mctx, &delt->acl);
4317         if (result != ISC_R_SUCCESS) {
4318                 ns_listenelt_destroy(delt);
4319                 return (result);
4320         }
4321         *target = delt;
4322         return (ISC_R_SUCCESS);
4323 }
4324
4325 isc_result_t
4326 ns_server_dumpstats(ns_server_t *server) {
4327         isc_result_t result;
4328         dns_zone_t *zone, *next;
4329         isc_stdtime_t now;
4330         FILE *fp = NULL;
4331         int i;
4332         int ncounters;
4333
4334         isc_stdtime_get(&now);
4335
4336         CHECKMF(isc_stdio_open(server->statsfile, "a", &fp),
4337                 "could not open statistics dump file", server->statsfile);
4338
4339         ncounters = DNS_STATS_NCOUNTERS;
4340         fprintf(fp, "+++ Statistics Dump +++ (%lu)\n", (unsigned long)now);
4341
4342         for (i = 0; i < ncounters; i++)
4343                 fprintf(fp, "%s %" ISC_PRINT_QUADFORMAT "u\n",
4344                         dns_statscounter_names[i],
4345                         server->querystats[i]);
4346
4347         zone = NULL;
4348         for (result = dns_zone_first(server->zonemgr, &zone);
4349              result == ISC_R_SUCCESS;
4350              next = NULL, result = dns_zone_next(zone, &next), zone = next)
4351         {
4352                 isc_uint64_t *zonestats = dns_zone_getstatscounters(zone);
4353                 if (zonestats != NULL) {
4354                         char zonename[DNS_NAME_FORMATSIZE];
4355                         dns_view_t *view;
4356                         char *viewname;
4357
4358                         dns_name_format(dns_zone_getorigin(zone),
4359                                         zonename, sizeof(zonename));
4360                         view = dns_zone_getview(zone);
4361                         viewname = view->name;
4362                         for (i = 0; i < ncounters; i++) {
4363                                 fprintf(fp, "%s %" ISC_PRINT_QUADFORMAT
4364                                         "u %s",
4365                                         dns_statscounter_names[i],
4366                                         zonestats[i],
4367                                         zonename);
4368                                 if (strcmp(viewname, "_default") != 0)
4369                                         fprintf(fp, " %s", viewname);
4370                                 fprintf(fp, "\n");
4371                         }
4372                 }
4373         }
4374         if (result == ISC_R_NOMORE)
4375                 result = ISC_R_SUCCESS;
4376         CHECK(result);
4377
4378         fprintf(fp, "--- Statistics Dump --- (%lu)\n", (unsigned long)now);
4379
4380  cleanup:
4381         if (fp != NULL)
4382                 (void)isc_stdio_close(fp);
4383         return (result);
4384 }
4385
4386 static isc_result_t
4387 add_zone_tolist(dns_zone_t *zone, void *uap) {
4388         struct dumpcontext *dctx = uap;
4389         struct zonelistentry *zle;
4390
4391         zle = isc_mem_get(dctx->mctx, sizeof *zle);
4392         if (zle ==  NULL)
4393                 return (ISC_R_NOMEMORY);
4394         zle->zone = NULL;
4395         dns_zone_attach(zone, &zle->zone);
4396         ISC_LINK_INIT(zle, link);
4397         ISC_LIST_APPEND(ISC_LIST_TAIL(dctx->viewlist)->zonelist, zle, link);
4398         return (ISC_R_SUCCESS);
4399 }
4400
4401 static isc_result_t
4402 add_view_tolist(struct dumpcontext *dctx, dns_view_t *view) {
4403         struct viewlistentry *vle;
4404         isc_result_t result = ISC_R_SUCCESS;
4405
4406         /*
4407          * Prevent duplicate views.
4408          */
4409         for (vle = ISC_LIST_HEAD(dctx->viewlist);
4410              vle != NULL;
4411              vle = ISC_LIST_NEXT(vle, link))
4412                 if (vle->view == view)
4413                         return (ISC_R_SUCCESS);
4414
4415         vle = isc_mem_get(dctx->mctx, sizeof *vle);
4416         if (vle == NULL)
4417                 return (ISC_R_NOMEMORY);
4418         vle->view = NULL;
4419         dns_view_attach(view, &vle->view);
4420         ISC_LINK_INIT(vle, link);
4421         ISC_LIST_INIT(vle->zonelist);
4422         ISC_LIST_APPEND(dctx->viewlist, vle, link);
4423         if (dctx->dumpzones)
4424                 result = dns_zt_apply(view->zonetable, ISC_TRUE,
4425                                       add_zone_tolist, dctx);
4426         return (result);
4427 }
4428
4429 static void
4430 dumpcontext_destroy(struct dumpcontext *dctx) {
4431         struct viewlistentry *vle;
4432         struct zonelistentry *zle;
4433
4434         vle = ISC_LIST_HEAD(dctx->viewlist);
4435         while (vle != NULL) {
4436                 ISC_LIST_UNLINK(dctx->viewlist, vle, link);
4437                 zle = ISC_LIST_HEAD(vle->zonelist);
4438                 while (zle != NULL) {
4439                         ISC_LIST_UNLINK(vle->zonelist, zle, link);
4440                         dns_zone_detach(&zle->zone);
4441                         isc_mem_put(dctx->mctx, zle, sizeof *zle);
4442                         zle = ISC_LIST_HEAD(vle->zonelist);
4443                 }
4444                 dns_view_detach(&vle->view);
4445                 isc_mem_put(dctx->mctx, vle, sizeof *vle);
4446                 vle = ISC_LIST_HEAD(dctx->viewlist);
4447         }
4448         if (dctx->version != NULL)
4449                 dns_db_closeversion(dctx->db, &dctx->version, ISC_FALSE);
4450         if (dctx->db != NULL)
4451                 dns_db_detach(&dctx->db);
4452         if (dctx->cache != NULL)
4453                 dns_db_detach(&dctx->cache);
4454         if (dctx->task != NULL)
4455                 isc_task_detach(&dctx->task);
4456         if (dctx->fp != NULL)
4457                 (void)isc_stdio_close(dctx->fp);
4458         if (dctx->mdctx != NULL)
4459                 dns_dumpctx_detach(&dctx->mdctx);
4460         isc_mem_put(dctx->mctx, dctx, sizeof *dctx);
4461 }
4462
4463 static void
4464 dumpdone(void *arg, isc_result_t result) {
4465         struct dumpcontext *dctx = arg;
4466         char buf[1024+32];
4467         const dns_master_style_t *style;
4468
4469         if (result != ISC_R_SUCCESS)
4470                 goto cleanup;
4471         if (dctx->mdctx != NULL)
4472                 dns_dumpctx_detach(&dctx->mdctx);
4473         if (dctx->view == NULL) {
4474                 dctx->view = ISC_LIST_HEAD(dctx->viewlist);
4475                 if (dctx->view == NULL)
4476                         goto done;
4477                 INSIST(dctx->zone == NULL);
4478         } else
4479                 goto resume;
4480  nextview:
4481         fprintf(dctx->fp, ";\n; Start view %s\n;\n", dctx->view->view->name);
4482  resume:
4483         if (dctx->zone == NULL && dctx->cache == NULL && dctx->dumpcache) {
4484                 style = &dns_master_style_cache;
4485                 /* start cache dump */
4486                 if (dctx->view->view->cachedb != NULL)
4487                         dns_db_attach(dctx->view->view->cachedb, &dctx->cache);
4488                 if (dctx->cache != NULL) {
4489
4490                         fprintf(dctx->fp, ";\n; Cache dump of view '%s'\n;\n",
4491                                 dctx->view->view->name);
4492                         result = dns_master_dumptostreaminc(dctx->mctx,
4493                                                             dctx->cache, NULL,
4494                                                             style, dctx->fp,
4495                                                             dctx->task,
4496                                                             dumpdone, dctx,
4497                                                             &dctx->mdctx);
4498                         if (result == DNS_R_CONTINUE)
4499                                 return;
4500                         if (result == ISC_R_NOTIMPLEMENTED)
4501                                 fprintf(dctx->fp, "; %s\n",
4502                                         dns_result_totext(result));
4503                         else if (result != ISC_R_SUCCESS)
4504                                 goto cleanup;
4505                 }
4506         }
4507         if (dctx->cache != NULL) {
4508                 dns_adb_dump(dctx->view->view->adb, dctx->fp);
4509                 dns_db_detach(&dctx->cache);
4510         }
4511         if (dctx->dumpzones) {
4512                 style = &dns_master_style_full;
4513  nextzone:
4514                 if (dctx->version != NULL)
4515                         dns_db_closeversion(dctx->db, &dctx->version,
4516                                             ISC_FALSE);
4517                 if (dctx->db != NULL)
4518                         dns_db_detach(&dctx->db);
4519                 if (dctx->zone == NULL)
4520                         dctx->zone = ISC_LIST_HEAD(dctx->view->zonelist);
4521                 else
4522                         dctx->zone = ISC_LIST_NEXT(dctx->zone, link);
4523                 if (dctx->zone != NULL) {
4524                         /* start zone dump */
4525                         dns_zone_name(dctx->zone->zone, buf, sizeof(buf));
4526                         fprintf(dctx->fp, ";\n; Zone dump of '%s'\n;\n", buf);
4527                         result = dns_zone_getdb(dctx->zone->zone, &dctx->db);
4528                         if (result != ISC_R_SUCCESS) {
4529                                 fprintf(dctx->fp, "; %s\n",
4530                                         dns_result_totext(result));
4531                                 goto nextzone;
4532                         }
4533                         dns_db_currentversion(dctx->db, &dctx->version);
4534                         result = dns_master_dumptostreaminc(dctx->mctx,
4535                                                             dctx->db,
4536                                                             dctx->version,
4537                                                             style, dctx->fp,
4538                                                             dctx->task,
4539                                                             dumpdone, dctx,
4540                                                             &dctx->mdctx);
4541                         if (result == DNS_R_CONTINUE)
4542                                 return;
4543                         if (result == ISC_R_NOTIMPLEMENTED) {
4544                                 fprintf(dctx->fp, "; %s\n",
4545                                         dns_result_totext(result));
4546                                 result = ISC_R_SUCCESS;
4547                                 goto nextzone;
4548                         }
4549                         if (result != ISC_R_SUCCESS)
4550                                 goto cleanup;
4551                 }
4552         }
4553         if (dctx->view != NULL)
4554                 dctx->view = ISC_LIST_NEXT(dctx->view, link);
4555         if (dctx->view != NULL)
4556                 goto nextview;
4557  done:
4558         fprintf(dctx->fp, "; Dump complete\n");
4559         result = isc_stdio_flush(dctx->fp);
4560         if (result == ISC_R_SUCCESS)
4561                 isc_log_write(ns_g_lctx, NS_LOGCATEGORY_GENERAL,
4562                               NS_LOGMODULE_SERVER, ISC_LOG_INFO,
4563                               "dumpdb complete");
4564  cleanup:
4565         if (result != ISC_R_SUCCESS)
4566                 isc_log_write(ns_g_lctx, NS_LOGCATEGORY_GENERAL,
4567                               NS_LOGMODULE_SERVER, ISC_LOG_INFO,
4568                               "dumpdb failed: %s", dns_result_totext(result));
4569         dumpcontext_destroy(dctx);
4570 }
4571
4572 isc_result_t
4573 ns_server_dumpdb(ns_server_t *server, char *args) {
4574         struct dumpcontext *dctx = NULL;
4575         dns_view_t *view;
4576         isc_result_t result;
4577         char *ptr;
4578         const char *sep;
4579
4580         /* Skip the command name. */
4581         ptr = next_token(&args, " \t");
4582         if (ptr == NULL)
4583                 return (ISC_R_UNEXPECTEDEND);
4584
4585         dctx = isc_mem_get(server->mctx, sizeof(*dctx));
4586         if (dctx == NULL)
4587                 return (ISC_R_NOMEMORY);
4588
4589         dctx->mctx = server->mctx;
4590         dctx->dumpcache = ISC_TRUE;
4591         dctx->dumpzones = ISC_FALSE;
4592         dctx->fp = NULL;
4593         ISC_LIST_INIT(dctx->viewlist);
4594         dctx->view = NULL;
4595         dctx->zone = NULL;
4596         dctx->cache = NULL;
4597         dctx->mdctx = NULL;
4598         dctx->db = NULL;
4599         dctx->cache = NULL;
4600         dctx->task = NULL;
4601         dctx->version = NULL;
4602         isc_task_attach(server->task, &dctx->task);
4603
4604         CHECKMF(isc_stdio_open(server->dumpfile, "w", &dctx->fp),
4605                 "could not open dump file", server->dumpfile);
4606
4607         sep = (args == NULL) ? "" : ": ";
4608         isc_log_write(ns_g_lctx, NS_LOGCATEGORY_GENERAL,
4609                       NS_LOGMODULE_SERVER, ISC_LOG_INFO,
4610                       "dumpdb started%s%s", sep, (args != NULL) ? args : "");
4611
4612         ptr = next_token(&args, " \t");
4613         if (ptr != NULL && strcmp(ptr, "-all") == 0) {
4614                 dctx->dumpzones = ISC_TRUE;
4615                 dctx->dumpcache = ISC_TRUE;
4616                 ptr = next_token(&args, " \t");
4617         } else if (ptr != NULL && strcmp(ptr, "-cache") == 0) {
4618                 dctx->dumpzones = ISC_FALSE;
4619                 dctx->dumpcache = ISC_TRUE;
4620                 ptr = next_token(&args, " \t");
4621         } else if (ptr != NULL && strcmp(ptr, "-zones") == 0) {
4622                 dctx->dumpzones = ISC_TRUE;
4623                 dctx->dumpcache = ISC_FALSE;
4624                 ptr = next_token(&args, " \t");
4625         }
4626
4627  nextview:
4628         for (view = ISC_LIST_HEAD(server->viewlist);
4629              view != NULL;
4630              view = ISC_LIST_NEXT(view, link))
4631         {
4632                 if (ptr != NULL && strcmp(view->name, ptr) != 0)
4633                         continue;
4634                 CHECK(add_view_tolist(dctx, view));
4635         }
4636         if (ptr != NULL) {
4637                 ptr = next_token(&args, " \t");
4638                 if (ptr != NULL)
4639                         goto nextview;
4640         }
4641         dumpdone(dctx, ISC_R_SUCCESS);
4642         return (ISC_R_SUCCESS);
4643
4644  cleanup:
4645         if (dctx != NULL)
4646                 dumpcontext_destroy(dctx);
4647         return (result);
4648 }
4649
4650 isc_result_t
4651 ns_server_dumprecursing(ns_server_t *server) {
4652         FILE *fp = NULL;
4653         isc_result_t result;
4654
4655         CHECKMF(isc_stdio_open(server->recfile, "w", &fp),
4656                 "could not open dump file", server->recfile);
4657         fprintf(fp,";\n; Recursing Queries\n;\n");
4658         ns_interfacemgr_dumprecursing(fp, server->interfacemgr);
4659         fprintf(fp, "; Dump complete\n");
4660
4661  cleanup:
4662         if (fp != NULL)
4663                 result = isc_stdio_close(fp);
4664         return (result);
4665 }
4666
4667 isc_result_t
4668 ns_server_setdebuglevel(ns_server_t *server, char *args) {
4669         char *ptr;
4670         char *levelstr;
4671         char *endp;
4672         long newlevel;
4673
4674         UNUSED(server);
4675
4676         /* Skip the command name. */
4677         ptr = next_token(&args, " \t");
4678         if (ptr == NULL)
4679                 return (ISC_R_UNEXPECTEDEND);
4680
4681         /* Look for the new level name. */
4682         levelstr = next_token(&args, " \t");
4683         if (levelstr == NULL) {
4684                 if (ns_g_debuglevel < 99)
4685                         ns_g_debuglevel++;
4686         } else {
4687                 newlevel = strtol(levelstr, &endp, 10);
4688                 if (*endp != '\0' || newlevel < 0 || newlevel > 99)
4689                         return (ISC_R_RANGE);
4690                 ns_g_debuglevel = (unsigned int)newlevel;
4691         }
4692         isc_log_setdebuglevel(ns_g_lctx, ns_g_debuglevel);
4693         return (ISC_R_SUCCESS);
4694 }
4695
4696 isc_result_t
4697 ns_server_validation(ns_server_t *server, char *args) {
4698         char *ptr, *viewname;
4699         dns_view_t *view;
4700         isc_boolean_t changed = ISC_FALSE;
4701         isc_result_t result;
4702         isc_boolean_t enable;
4703
4704         /* Skip the command name. */
4705         ptr = next_token(&args, " \t");
4706         if (ptr == NULL)
4707                 return (ISC_R_UNEXPECTEDEND);
4708
4709         /* Find out what we are to do. */
4710         ptr = next_token(&args, " \t");
4711         if (ptr == NULL)
4712                 return (ISC_R_UNEXPECTEDEND);
4713
4714         if (!strcasecmp(ptr, "on") || !strcasecmp(ptr, "yes") ||
4715             !strcasecmp(ptr, "enable") || !strcasecmp(ptr, "true"))
4716                 enable = ISC_TRUE;
4717         else if (!strcasecmp(ptr, "off") || !strcasecmp(ptr, "no") ||
4718                  !strcasecmp(ptr, "disable") || !strcasecmp(ptr, "false"))
4719                 enable = ISC_FALSE;
4720         else
4721                 return (DNS_R_SYNTAX);
4722
4723         /* Look for the view name. */
4724         viewname = next_token(&args, " \t");
4725
4726         result = isc_task_beginexclusive(server->task);
4727         RUNTIME_CHECK(result == ISC_R_SUCCESS);
4728         for (view = ISC_LIST_HEAD(server->viewlist);
4729              view != NULL;
4730              view = ISC_LIST_NEXT(view, link))
4731         {
4732                 if (viewname != NULL && strcasecmp(viewname, view->name) != 0)
4733                         continue;
4734                 result = dns_view_flushcache(view);
4735                 if (result != ISC_R_SUCCESS)
4736                         goto out;
4737                 view->enablevalidation = enable;
4738                 changed = ISC_TRUE;
4739         }
4740         if (changed)
4741                 result = ISC_R_SUCCESS;
4742         else
4743                 result = ISC_R_FAILURE;
4744  out:
4745         isc_task_endexclusive(server->task);
4746         return (result);
4747 }
4748
4749 isc_result_t
4750 ns_server_flushcache(ns_server_t *server, char *args) {
4751         char *ptr, *viewname;
4752         dns_view_t *view;
4753         isc_boolean_t flushed;
4754         isc_boolean_t found;
4755         isc_result_t result;
4756
4757         /* Skip the command name. */
4758         ptr = next_token(&args, " \t");
4759         if (ptr == NULL)
4760                 return (ISC_R_UNEXPECTEDEND);
4761
4762         /* Look for the view name. */
4763         viewname = next_token(&args, " \t");
4764
4765         result = isc_task_beginexclusive(server->task);
4766         RUNTIME_CHECK(result == ISC_R_SUCCESS);
4767         flushed = ISC_TRUE;
4768         found = ISC_FALSE;
4769         for (view = ISC_LIST_HEAD(server->viewlist);
4770              view != NULL;
4771              view = ISC_LIST_NEXT(view, link))
4772         {
4773                 if (viewname != NULL && strcasecmp(viewname, view->name) != 0)
4774                         continue;
4775                 found = ISC_TRUE;
4776                 result = dns_view_flushcache(view);
4777                 if (result != ISC_R_SUCCESS)
4778                         flushed = ISC_FALSE;
4779         }
4780         if (flushed && found) {
4781                 result = ISC_R_SUCCESS;
4782         } else {
4783                 if (!found)
4784                         result = ISC_R_NOTFOUND;
4785                 else
4786                         result = ISC_R_FAILURE;
4787         }
4788         isc_task_endexclusive(server->task);
4789         return (result);
4790 }
4791
4792 isc_result_t
4793 ns_server_flushname(ns_server_t *server, char *args) {
4794         char *ptr, *target, *viewname;
4795         dns_view_t *view;
4796         isc_boolean_t flushed;
4797         isc_boolean_t found;
4798         isc_result_t result;
4799         isc_buffer_t b;
4800         dns_fixedname_t fixed;
4801         dns_name_t *name;
4802
4803         /* Skip the command name. */
4804         ptr = next_token(&args, " \t");
4805         if (ptr == NULL)
4806                 return (ISC_R_UNEXPECTEDEND);
4807
4808         /* Find the domain name to flush. */
4809         target = next_token(&args, " \t");
4810         if (target == NULL)
4811                 return (ISC_R_UNEXPECTEDEND);
4812
4813         isc_buffer_init(&b, target, strlen(target));
4814         isc_buffer_add(&b, strlen(target));
4815         dns_fixedname_init(&fixed);
4816         name = dns_fixedname_name(&fixed);
4817         result = dns_name_fromtext(name, &b, dns_rootname, ISC_FALSE, NULL);
4818         if (result != ISC_R_SUCCESS)
4819                 return (result);
4820
4821         /* Look for the view name. */
4822         viewname = next_token(&args, " \t");
4823
4824         result = isc_task_beginexclusive(server->task);
4825         RUNTIME_CHECK(result == ISC_R_SUCCESS);
4826         flushed = ISC_TRUE;
4827         found = ISC_FALSE;
4828         for (view = ISC_LIST_HEAD(server->viewlist);
4829              view != NULL;
4830              view = ISC_LIST_NEXT(view, link))
4831         {
4832                 if (viewname != NULL && strcasecmp(viewname, view->name) != 0)
4833                         continue;
4834                 found = ISC_TRUE;
4835                 result = dns_view_flushname(view, name);
4836                 if (result != ISC_R_SUCCESS)
4837                         flushed = ISC_FALSE;
4838         }
4839         if (flushed && found)
4840                 result = ISC_R_SUCCESS;
4841         else if (!found)
4842                 result = ISC_R_NOTFOUND;
4843         else
4844                 result = ISC_R_FAILURE;
4845         isc_task_endexclusive(server->task);
4846         return (result);
4847 }
4848
4849 isc_result_t
4850 ns_server_status(ns_server_t *server, isc_buffer_t *text) {
4851         int zonecount, xferrunning, xferdeferred, soaqueries;
4852         unsigned int n;
4853
4854         zonecount = dns_zonemgr_getcount(server->zonemgr, DNS_ZONESTATE_ANY);
4855         xferrunning = dns_zonemgr_getcount(server->zonemgr,
4856                                            DNS_ZONESTATE_XFERRUNNING);
4857         xferdeferred = dns_zonemgr_getcount(server->zonemgr,
4858                                             DNS_ZONESTATE_XFERDEFERRED);
4859         soaqueries = dns_zonemgr_getcount(server->zonemgr,
4860                                           DNS_ZONESTATE_SOAQUERY);
4861         n = snprintf((char *)isc_buffer_used(text),
4862                      isc_buffer_availablelength(text),
4863                      "number of zones: %u\n"
4864                      "debug level: %d\n"
4865                      "xfers running: %u\n"
4866                      "xfers deferred: %u\n"
4867                      "soa queries in progress: %u\n"
4868                      "query logging is %s\n"
4869                      "recursive clients: %d/%d/%d\n"
4870                      "tcp clients: %d/%d\n"
4871                      "server is up and running",
4872                      zonecount, ns_g_debuglevel, xferrunning, xferdeferred,
4873                      soaqueries, server->log_queries ? "ON" : "OFF",
4874                      server->recursionquota.used, server->recursionquota.soft,
4875                      server->recursionquota.max,
4876                      server->tcpquota.used, server->tcpquota.max);
4877         if (n >= isc_buffer_availablelength(text))
4878                 return (ISC_R_NOSPACE);
4879         isc_buffer_add(text, n);
4880         return (ISC_R_SUCCESS);
4881 }
4882
4883 /*
4884  * Act on a "freeze" or "thaw" command from the command channel.
4885  */
4886 isc_result_t
4887 ns_server_freeze(ns_server_t *server, isc_boolean_t freeze, char *args) {
4888         isc_result_t result, tresult;
4889         dns_zone_t *zone = NULL;
4890         dns_zonetype_t type;
4891         char classstr[DNS_RDATACLASS_FORMATSIZE];
4892         char zonename[DNS_NAME_FORMATSIZE];
4893         dns_view_t *view;
4894         char *journal;
4895         const char *vname, *sep;
4896         isc_boolean_t frozen;
4897
4898         result = zone_from_args(server, args, &zone);
4899         if (result != ISC_R_SUCCESS)
4900                 return (result);
4901         if (zone == NULL) {
4902                 result = isc_task_beginexclusive(server->task);
4903                 RUNTIME_CHECK(result == ISC_R_SUCCESS);
4904                 tresult = ISC_R_SUCCESS;
4905                 for (view = ISC_LIST_HEAD(server->viewlist);
4906                      view != NULL;
4907                      view = ISC_LIST_NEXT(view, link)) {
4908                         result = dns_view_freezezones(view, freeze);
4909                         if (result != ISC_R_SUCCESS &&
4910                             tresult == ISC_R_SUCCESS)
4911                                 tresult = result;
4912                 }
4913                 isc_task_endexclusive(server->task);
4914                 isc_log_write(ns_g_lctx, NS_LOGCATEGORY_GENERAL,
4915                               NS_LOGMODULE_SERVER, ISC_LOG_INFO,
4916                               "%s all zones: %s",
4917                               freeze ? "freezing" : "thawing",
4918                               isc_result_totext(tresult));
4919                 return (tresult);
4920         }
4921         type = dns_zone_gettype(zone);
4922         if (type != dns_zone_master) {
4923                 dns_zone_detach(&zone);
4924                 return (ISC_R_NOTFOUND);
4925         }
4926
4927         frozen = dns_zone_getupdatedisabled(zone);
4928         if (freeze) {
4929                 if (frozen)
4930                         result = DNS_R_FROZEN;
4931                 if (result == ISC_R_SUCCESS)
4932                         result = dns_zone_flush(zone);
4933                 if (result == ISC_R_SUCCESS) {
4934                         journal = dns_zone_getjournal(zone);
4935                         if (journal != NULL)
4936                                 (void)isc_file_remove(journal);
4937                 }
4938         } else {
4939                 if (frozen) {
4940                         result = dns_zone_load(zone);
4941                         if (result == DNS_R_CONTINUE ||
4942                             result == DNS_R_UPTODATE)
4943                                 result = ISC_R_SUCCESS;
4944                 }
4945         }
4946         if (result == ISC_R_SUCCESS)
4947                 dns_zone_setupdatedisabled(zone, freeze);
4948
4949         view = dns_zone_getview(zone);
4950         if (strcmp(view->name, "_bind") == 0 ||
4951             strcmp(view->name, "_default") == 0)
4952         {
4953                 vname = "";
4954                 sep = "";
4955         } else {
4956                 vname = view->name;
4957                 sep = " ";
4958         }
4959         dns_rdataclass_format(dns_zone_getclass(zone), classstr,
4960                               sizeof(classstr));
4961         dns_name_format(dns_zone_getorigin(zone),
4962                         zonename, sizeof(zonename));
4963         isc_log_write(ns_g_lctx, NS_LOGCATEGORY_GENERAL,
4964                       NS_LOGMODULE_SERVER, ISC_LOG_INFO,
4965                       "%s zone '%s/%s'%s%s: %s",
4966                       freeze ? "freezing" : "thawing",
4967                       zonename, classstr, sep, vname,
4968                       isc_result_totext(result));
4969         dns_zone_detach(&zone);
4970         return (result);
4971 }
4972
4973 #ifdef HAVE_LIBSCF
4974 /*
4975  * This function adds a message for rndc to echo if named
4976  * is managed by smf and is also running chroot.
4977  */
4978 isc_result_t
4979 ns_smf_add_message(isc_buffer_t *text) {
4980         unsigned int n;
4981
4982         n = snprintf((char *)isc_buffer_used(text),
4983                 isc_buffer_availablelength(text),
4984                 "use svcadm(1M) to manage named");
4985         if (n >= isc_buffer_availablelength(text))
4986                 return (ISC_R_NOSPACE);
4987         isc_buffer_add(text, n);
4988         return (ISC_R_SUCCESS);
4989 }
4990 #endif /* HAVE_LIBSCF */