Import bind 9.5.2 vendor sources.
[dragonfly.git] / contrib / bind-9.5.2 / lib / dns / zone.c
1 /*
2  * Copyright (C) 2004-2009  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: zone.c,v 1.470.12.12 2009/07/11 04:28:14 marka Exp $ */
19
20 /*! \file */
21
22 #include <config.h>
23 #include <errno.h>
24
25 #include <isc/file.h>
26 #include <isc/mutex.h>
27 #include <isc/print.h>
28 #include <isc/random.h>
29 #include <isc/ratelimiter.h>
30 #include <isc/refcount.h>
31 #include <isc/rwlock.h>
32 #include <isc/serial.h>
33 #include <isc/strerror.h>
34 #include <isc/stats.h>
35 #include <isc/string.h>
36 #include <isc/taskpool.h>
37 #include <isc/timer.h>
38 #include <isc/util.h>
39
40 #include <dns/acache.h>
41 #include <dns/acl.h>
42 #include <dns/adb.h>
43 #include <dns/callbacks.h>
44 #include <dns/db.h>
45 #include <dns/dbiterator.h>
46 #include <dns/events.h>
47 #include <dns/journal.h>
48 #include <dns/log.h>
49 #include <dns/master.h>
50 #include <dns/masterdump.h>
51 #include <dns/message.h>
52 #include <dns/name.h>
53 #include <dns/peer.h>
54 #include <dns/rcode.h>
55 #include <dns/rdataclass.h>
56 #include <dns/rdatalist.h>
57 #include <dns/rdataset.h>
58 #include <dns/rdatastruct.h>
59 #include <dns/rdatatype.h>
60 #include <dns/request.h>
61 #include <dns/resolver.h>
62 #include <dns/result.h>
63 #include <dns/stats.h>
64 #include <dns/ssu.h>
65 #include <dns/tsig.h>
66 #include <dns/xfrin.h>
67 #include <dns/zone.h>
68
69 #define ZONE_MAGIC                      ISC_MAGIC('Z', 'O', 'N', 'E')
70 #define DNS_ZONE_VALID(zone)            ISC_MAGIC_VALID(zone, ZONE_MAGIC)
71
72 #define NOTIFY_MAGIC                    ISC_MAGIC('N', 't', 'f', 'y')
73 #define DNS_NOTIFY_VALID(notify)        ISC_MAGIC_VALID(notify, NOTIFY_MAGIC)
74
75 #define STUB_MAGIC                      ISC_MAGIC('S', 't', 'u', 'b')
76 #define DNS_STUB_VALID(stub)            ISC_MAGIC_VALID(stub, STUB_MAGIC)
77
78 #define ZONEMGR_MAGIC                   ISC_MAGIC('Z', 'm', 'g', 'r')
79 #define DNS_ZONEMGR_VALID(stub)         ISC_MAGIC_VALID(stub, ZONEMGR_MAGIC)
80
81 #define LOAD_MAGIC                      ISC_MAGIC('L', 'o', 'a', 'd')
82 #define DNS_LOAD_VALID(load)            ISC_MAGIC_VALID(load, LOAD_MAGIC)
83
84 #define FORWARD_MAGIC                   ISC_MAGIC('F', 'o', 'r', 'w')
85 #define DNS_FORWARD_VALID(load)         ISC_MAGIC_VALID(load, FORWARD_MAGIC)
86
87 #define IO_MAGIC                        ISC_MAGIC('Z', 'm', 'I', 'O')
88 #define DNS_IO_VALID(load)              ISC_MAGIC_VALID(load, IO_MAGIC)
89
90 /*%
91  * Ensure 'a' is at least 'min' but not more than 'max'.
92  */
93 #define RANGE(a, min, max) \
94                 (((a) < (min)) ? (min) : ((a) < (max) ? (a) : (max)))
95
96 /*
97  * Default values.
98  */
99 #define DNS_DEFAULT_IDLEIN 3600         /*%< 1 hour */
100 #define DNS_DEFAULT_IDLEOUT 3600        /*%< 1 hour */
101 #define MAX_XFER_TIME (2*3600)          /*%< Documented default is 2 hours */
102
103 #ifndef DNS_MAX_EXPIRE
104 #define DNS_MAX_EXPIRE  14515200        /*%< 24 weeks */
105 #endif
106
107 #ifndef DNS_DUMP_DELAY
108 #define DNS_DUMP_DELAY 900              /*%< 15 minutes */
109 #endif
110
111 typedef struct dns_notify dns_notify_t;
112 typedef struct dns_stub dns_stub_t;
113 typedef struct dns_load dns_load_t;
114 typedef struct dns_forward dns_forward_t;
115 typedef struct dns_io dns_io_t;
116 typedef ISC_LIST(dns_io_t) dns_iolist_t;
117
118 #define DNS_ZONE_CHECKLOCK
119 #ifdef DNS_ZONE_CHECKLOCK
120 #define LOCK_ZONE(z) \
121          do { LOCK(&(z)->lock); \
122               INSIST((z)->locked == ISC_FALSE); \
123              (z)->locked = ISC_TRUE; \
124                 } while (0)
125 #define UNLOCK_ZONE(z) \
126         do { (z)->locked = ISC_FALSE; UNLOCK(&(z)->lock); } while (0)
127 #define LOCKED_ZONE(z) ((z)->locked)
128 #else
129 #define LOCK_ZONE(z) LOCK(&(z)->lock)
130 #define UNLOCK_ZONE(z) UNLOCK(&(z)->lock)
131 #define LOCKED_ZONE(z) ISC_TRUE
132 #endif
133
134 #ifdef ISC_RWLOCK_USEATOMIC
135 #define ZONEDB_INITLOCK(l)      isc_rwlock_init((l), 0, 0)
136 #define ZONEDB_DESTROYLOCK(l)   isc_rwlock_destroy(l)
137 #define ZONEDB_LOCK(l, t)       RWLOCK((l), (t))
138 #define ZONEDB_UNLOCK(l, t)     RWUNLOCK((l), (t))
139 #else
140 #define ZONEDB_INITLOCK(l)      isc_mutex_init(l)
141 #define ZONEDB_DESTROYLOCK(l)   DESTROYLOCK(l)
142 #define ZONEDB_LOCK(l, t)       LOCK(l)
143 #define ZONEDB_UNLOCK(l, t)     UNLOCK(l)
144 #endif
145
146 struct dns_zone {
147         /* Unlocked */
148         unsigned int            magic;
149         isc_mutex_t             lock;
150 #ifdef DNS_ZONE_CHECKLOCK
151         isc_boolean_t           locked;
152 #endif
153         isc_mem_t               *mctx;
154         isc_refcount_t          erefs;
155
156 #ifdef ISC_RWLOCK_USEATOMIC
157         isc_rwlock_t            dblock;
158 #else
159         isc_mutex_t             dblock;
160 #endif
161         dns_db_t                *db;            /* Locked by dblock */
162
163         /* Locked */
164         dns_zonemgr_t           *zmgr;
165         ISC_LINK(dns_zone_t)    link;           /* Used by zmgr. */
166         isc_timer_t             *timer;
167         unsigned int            irefs;
168         dns_name_t              origin;
169         char                    *masterfile;
170         dns_masterformat_t      masterformat;
171         char                    *journal;
172         isc_int32_t             journalsize;
173         dns_rdataclass_t        rdclass;
174         dns_zonetype_t          type;
175         unsigned int            flags;
176         unsigned int            options;
177         unsigned int            db_argc;
178         char                    **db_argv;
179         isc_time_t              expiretime;
180         isc_time_t              refreshtime;
181         isc_time_t              dumptime;
182         isc_time_t              loadtime;
183         isc_time_t              notifytime;
184         isc_uint32_t            serial;
185         isc_uint32_t            refresh;
186         isc_uint32_t            retry;
187         isc_uint32_t            expire;
188         isc_uint32_t            minimum;
189         char                    *keydirectory;
190
191         isc_uint32_t            maxrefresh;
192         isc_uint32_t            minrefresh;
193         isc_uint32_t            maxretry;
194         isc_uint32_t            minretry;
195
196         isc_sockaddr_t          *masters;
197         dns_name_t              **masterkeynames;
198         isc_boolean_t           *mastersok;
199         unsigned int            masterscnt;
200         unsigned int            curmaster;
201         isc_sockaddr_t          masteraddr;
202         dns_notifytype_t        notifytype;
203         isc_sockaddr_t          *notify;
204         unsigned int            notifycnt;
205         isc_sockaddr_t          notifyfrom;
206         isc_task_t              *task;
207         isc_sockaddr_t          notifysrc4;
208         isc_sockaddr_t          notifysrc6;
209         isc_sockaddr_t          xfrsource4;
210         isc_sockaddr_t          xfrsource6;
211         isc_sockaddr_t          altxfrsource4;
212         isc_sockaddr_t          altxfrsource6;
213         isc_sockaddr_t          sourceaddr;
214         dns_xfrin_ctx_t         *xfr;           /* task locked */
215         dns_tsigkey_t           *tsigkey;       /* key used for xfr */
216         /* Access Control Lists */
217         dns_acl_t               *update_acl;
218         dns_acl_t               *forward_acl;
219         dns_acl_t               *notify_acl;
220         dns_acl_t               *query_acl;
221         dns_acl_t               *queryon_acl;
222         dns_acl_t               *xfr_acl;
223         isc_boolean_t           update_disabled;
224         isc_boolean_t           zero_no_soa_ttl;
225         dns_severity_t          check_names;
226         ISC_LIST(dns_notify_t)  notifies;
227         dns_request_t           *request;
228         dns_loadctx_t           *lctx;
229         dns_io_t                *readio;
230         dns_dumpctx_t           *dctx;
231         dns_io_t                *writeio;
232         isc_uint32_t            maxxfrin;
233         isc_uint32_t            maxxfrout;
234         isc_uint32_t            idlein;
235         isc_uint32_t            idleout;
236         isc_event_t             ctlevent;
237         dns_ssutable_t          *ssutable;
238         isc_uint32_t            sigvalidityinterval;
239         dns_view_t              *view;
240         dns_acache_t            *acache;
241         dns_checkmxfunc_t       checkmx;
242         dns_checksrvfunc_t      checksrv;
243         dns_checknsfunc_t       checkns;
244         /*%
245          * Zones in certain states such as "waiting for zone transfer"
246          * or "zone transfer in progress" are kept on per-state linked lists
247          * in the zone manager using the 'statelink' field.  The 'statelist'
248          * field points at the list the zone is currently on.  It the zone
249          * is not on any such list, statelist is NULL.
250          */
251         ISC_LINK(dns_zone_t)    statelink;
252         dns_zonelist_t          *statelist;
253         /*%
254          * Statistics counters about zone management.
255          */
256         isc_stats_t             *stats;
257         /*%
258          * Optional per-zone statistics counters.  Counted outside of this
259          * module.
260          */
261         isc_boolean_t           requeststats_on;
262         isc_stats_t             *requeststats;
263         isc_uint32_t            notifydelay;
264         dns_isselffunc_t        isself;
265         void                    *isselfarg;
266
267         char *                  strnamerd;
268         char *                  strname;
269         char *                  strrdclass;
270         char *                  strviewname;
271
272         /*%
273          * Serial number for deferred journal compaction.
274          */
275         isc_uint32_t            compact_serial;
276 };
277
278 #define DNS_ZONE_FLAG(z,f) (ISC_TF(((z)->flags & (f)) != 0))
279 #define DNS_ZONE_SETFLAG(z,f) do { \
280                 INSIST(LOCKED_ZONE(z)); \
281                 (z)->flags |= (f); \
282                 } while (0)
283 #define DNS_ZONE_CLRFLAG(z,f) do { \
284                 INSIST(LOCKED_ZONE(z)); \
285                 (z)->flags &= ~(f); \
286                 } while (0)
287         /* XXX MPA these may need to go back into zone.h */
288 #define DNS_ZONEFLG_REFRESH     0x00000001U     /*%< refresh check in progress */
289 #define DNS_ZONEFLG_NEEDDUMP    0x00000002U     /*%< zone need consolidation */
290 #define DNS_ZONEFLG_USEVC       0x00000004U     /*%< use tcp for refresh query */
291 #define DNS_ZONEFLG_DUMPING     0x00000008U     /*%< a dump is in progress */
292 #define DNS_ZONEFLG_HASINCLUDE  0x00000010U     /*%< $INCLUDE in zone file */
293 #define DNS_ZONEFLG_LOADED      0x00000020U     /*%< database has loaded */
294 #define DNS_ZONEFLG_EXITING     0x00000040U     /*%< zone is being destroyed */
295 #define DNS_ZONEFLG_EXPIRED     0x00000080U     /*%< zone has expired */
296 #define DNS_ZONEFLG_NEEDREFRESH 0x00000100U     /*%< refresh check needed */
297 #define DNS_ZONEFLG_UPTODATE    0x00000200U     /*%< zone contents are
298                                                  * uptodate */
299 #define DNS_ZONEFLG_NEEDNOTIFY  0x00000400U     /*%< need to send out notify
300                                                  * messages */
301 #define DNS_ZONEFLG_DIFFONRELOAD 0x00000800U    /*%< generate a journal diff on
302                                                  * reload */
303 #define DNS_ZONEFLG_NOMASTERS   0x00001000U     /*%< an attempt to refresh a
304                                                  * zone with no masters
305                                                  * occurred */
306 #define DNS_ZONEFLG_LOADING     0x00002000U     /*%< load from disk in progress*/
307 #define DNS_ZONEFLG_HAVETIMERS  0x00004000U     /*%< timer values have been set
308                                                  * from SOA (if not set, we
309                                                  * are still using
310                                                  * default timer values) */
311 #define DNS_ZONEFLG_FORCEXFER   0x00008000U     /*%< Force a zone xfer */
312 #define DNS_ZONEFLG_NOREFRESH   0x00010000U
313 #define DNS_ZONEFLG_DIALNOTIFY  0x00020000U
314 #define DNS_ZONEFLG_DIALREFRESH 0x00040000U
315 #define DNS_ZONEFLG_SHUTDOWN    0x00080000U
316 #define DNS_ZONEFLAG_NOIXFR     0x00100000U     /*%< IXFR failed, force AXFR */
317 #define DNS_ZONEFLG_FLUSH       0x00200000U
318 #define DNS_ZONEFLG_NOEDNS      0x00400000U
319 #define DNS_ZONEFLG_USEALTXFRSRC 0x00800000U
320 #define DNS_ZONEFLG_SOABEFOREAXFR 0x01000000U
321 #define DNS_ZONEFLG_NEEDCOMPACT 0x02000000U
322 #define DNS_ZONEFLG_REFRESHING  0x04000000U     /*%< Refreshing keydata */
323 #define DNS_ZONEFLG_THAW        0x08000000U
324
325 #define DNS_ZONE_OPTION(z,o) (((z)->options & (o)) != 0)
326
327 /* Flags for zone_load() */
328 #define DNS_ZONELOADFLAG_NOSTAT 0x00000001U     /* Do not stat() master files */
329 #define DNS_ZONELOADFLAG_THAW   0x00000002U     /* Thaw the zone on successful
330                                                    load. */
331
332 #define UNREACH_CHACHE_SIZE     10U
333 #define UNREACH_HOLD_TIME       600     /* 10 minutes */
334
335 struct dns_unreachable {
336         isc_sockaddr_t  remote;
337         isc_sockaddr_t  local;
338         isc_uint32_t    expire;
339         isc_uint32_t    last;
340 };
341
342 struct dns_zonemgr {
343         unsigned int            magic;
344         isc_mem_t *             mctx;
345         int                     refs;           /* Locked by rwlock */
346         isc_taskmgr_t *         taskmgr;
347         isc_timermgr_t *        timermgr;
348         isc_socketmgr_t *       socketmgr;
349         isc_taskpool_t *        zonetasks;
350         isc_task_t *            task;
351         isc_ratelimiter_t *     rl;
352         isc_rwlock_t            rwlock;
353         isc_mutex_t             iolock;
354
355         /* Locked by rwlock. */
356         dns_zonelist_t          zones;
357         dns_zonelist_t          waiting_for_xfrin;
358         dns_zonelist_t          xfrin_in_progress;
359
360         /* Configuration data. */
361         isc_uint32_t            transfersin;
362         isc_uint32_t            transfersperns;
363         unsigned int            serialqueryrate;
364
365         /* Locked by iolock */
366         isc_uint32_t            iolimit;
367         isc_uint32_t            ioactive;
368         dns_iolist_t            high;
369         dns_iolist_t            low;
370
371         /* Locked by rwlock. */
372         /* LRU cache */
373         struct dns_unreachable  unreachable[UNREACH_CHACHE_SIZE];
374 };
375
376 /*%
377  * Hold notify state.
378  */
379 struct dns_notify {
380         unsigned int            magic;
381         unsigned int            flags;
382         isc_mem_t               *mctx;
383         dns_zone_t              *zone;
384         dns_adbfind_t           *find;
385         dns_request_t           *request;
386         dns_name_t              ns;
387         isc_sockaddr_t          dst;
388         ISC_LINK(dns_notify_t)  link;
389 };
390
391 #define DNS_NOTIFY_NOSOA        0x0001U
392
393 /*%
394  *      dns_stub holds state while performing a 'stub' transfer.
395  *      'db' is the zone's 'db' or a new one if this is the initial
396  *      transfer.
397  */
398
399 struct dns_stub {
400         unsigned int            magic;
401         isc_mem_t               *mctx;
402         dns_zone_t              *zone;
403         dns_db_t                *db;
404         dns_dbversion_t         *version;
405 };
406
407 /*%
408  *      Hold load state.
409  */
410 struct dns_load {
411         unsigned int            magic;
412         isc_mem_t               *mctx;
413         dns_zone_t              *zone;
414         dns_db_t                *db;
415         isc_time_t              loadtime;
416         dns_rdatacallbacks_t    callbacks;
417 };
418
419 /*%
420  *      Hold forward state.
421  */
422 struct dns_forward {
423         unsigned int            magic;
424         isc_mem_t               *mctx;
425         dns_zone_t              *zone;
426         isc_buffer_t            *msgbuf;
427         dns_request_t           *request;
428         isc_uint32_t            which;
429         isc_sockaddr_t          addr;
430         dns_updatecallback_t    callback;
431         void                    *callback_arg;
432 };
433
434 /*%
435  *      Hold IO request state.
436  */
437 struct dns_io {
438         unsigned int    magic;
439         dns_zonemgr_t   *zmgr;
440         isc_boolean_t   high;
441         isc_task_t      *task;
442         ISC_LINK(dns_io_t) link;
443         isc_event_t     *event;
444 };
445
446 #define SEND_BUFFER_SIZE 2048
447
448 static void zone_settimer(dns_zone_t *, isc_time_t *);
449 static void cancel_refresh(dns_zone_t *);
450 static void zone_debuglog(dns_zone_t *zone, const char *, int debuglevel,
451                           const char *msg, ...) ISC_FORMAT_PRINTF(4, 5);
452 static void notify_log(dns_zone_t *zone, int level, const char *fmt, ...)
453      ISC_FORMAT_PRINTF(3, 4);
454 static void queue_xfrin(dns_zone_t *zone);
455 static void zone_unload(dns_zone_t *zone);
456 static void zone_expire(dns_zone_t *zone);
457 static void zone_iattach(dns_zone_t *source, dns_zone_t **target);
458 static void zone_idetach(dns_zone_t **zonep);
459 static isc_result_t zone_replacedb(dns_zone_t *zone, dns_db_t *db,
460                                    isc_boolean_t dump);
461 static inline void zone_attachdb(dns_zone_t *zone, dns_db_t *db);
462 static inline void zone_detachdb(dns_zone_t *zone);
463 static isc_result_t default_journal(dns_zone_t *zone);
464 static void zone_xfrdone(dns_zone_t *zone, isc_result_t result);
465 static isc_result_t zone_postload(dns_zone_t *zone, dns_db_t *db,
466                                   isc_time_t loadtime, isc_result_t result);
467 static void zone_needdump(dns_zone_t *zone, unsigned int delay);
468 static void zone_shutdown(isc_task_t *, isc_event_t *);
469 static void zone_loaddone(void *arg, isc_result_t result);
470 static isc_result_t zone_startload(dns_db_t *db, dns_zone_t *zone,
471                                    isc_time_t loadtime);
472 static void zone_namerd_tostr(dns_zone_t *zone, char *buf, size_t length);
473 static void zone_name_tostr(dns_zone_t *zone, char *buf, size_t length);
474 static void zone_rdclass_tostr(dns_zone_t *zone, char *buf, size_t length);
475 static void zone_viewname_tostr(dns_zone_t *zone, char *buf, size_t length);
476
477 #if 0
478 /* ondestroy example */
479 static void dns_zonemgr_dbdestroyed(isc_task_t *task, isc_event_t *event);
480 #endif
481
482 static void refresh_callback(isc_task_t *, isc_event_t *);
483 static void stub_callback(isc_task_t *, isc_event_t *);
484 static void queue_soa_query(dns_zone_t *zone);
485 static void soa_query(isc_task_t *, isc_event_t *);
486 static void ns_query(dns_zone_t *zone, dns_rdataset_t *soardataset,
487                      dns_stub_t *stub);
488 static int message_count(dns_message_t *msg, dns_section_t section,
489                          dns_rdatatype_t type);
490 static void notify_cancel(dns_zone_t *zone);
491 static void notify_find_address(dns_notify_t *notify);
492 static void notify_send(dns_notify_t *notify);
493 static isc_result_t notify_createmessage(dns_zone_t *zone,
494                                          unsigned int flags,
495                                          dns_message_t **messagep);
496 static void notify_done(isc_task_t *task, isc_event_t *event);
497 static void notify_send_toaddr(isc_task_t *task, isc_event_t *event);
498 static isc_result_t zone_dump(dns_zone_t *, isc_boolean_t);
499 static void got_transfer_quota(isc_task_t *task, isc_event_t *event);
500 static isc_result_t zmgr_start_xfrin_ifquota(dns_zonemgr_t *zmgr,
501                                              dns_zone_t *zone);
502 static void zmgr_resume_xfrs(dns_zonemgr_t *zmgr, isc_boolean_t multi);
503 static void zonemgr_free(dns_zonemgr_t *zmgr);
504 static isc_result_t zonemgr_getio(dns_zonemgr_t *zmgr, isc_boolean_t high,
505                                   isc_task_t *task, isc_taskaction_t action,
506                                   void *arg, dns_io_t **iop);
507 static void zonemgr_putio(dns_io_t **iop);
508 static void zonemgr_cancelio(dns_io_t *io);
509
510 static isc_result_t
511 zone_get_from_db(dns_zone_t *zone, dns_db_t *db, unsigned int *nscount,
512                  unsigned int *soacount, isc_uint32_t *serial,
513                  isc_uint32_t *refresh, isc_uint32_t *retry,
514                  isc_uint32_t *expire, isc_uint32_t *minimum,
515                  unsigned int *errors);
516
517 static void zone_freedbargs(dns_zone_t *zone);
518 static void forward_callback(isc_task_t *task, isc_event_t *event);
519 static void zone_saveunique(dns_zone_t *zone, const char *path,
520                             const char *templat);
521 static void zone_maintenance(dns_zone_t *zone);
522 static void zone_notify(dns_zone_t *zone, isc_time_t *now);
523 static void dump_done(void *arg, isc_result_t result);
524 static isc_boolean_t dns_zonemgr_unreachable(dns_zonemgr_t *zmgr,
525                                              isc_sockaddr_t *remote,
526                                              isc_sockaddr_t *local,
527                                              isc_time_t *now);
528
529 #define ENTER zone_debuglog(zone, me, 1, "enter")
530
531 static const unsigned int dbargc_default = 1;
532 static const char *dbargv_default[] = { "rbt" };
533
534 #define DNS_ZONE_JITTER_ADD(a, b, c) \
535         do { \
536                 isc_interval_t _i; \
537                 isc_uint32_t _j; \
538                 _j = isc_random_jitter((b), (b)/4); \
539                 isc_interval_set(&_i, _j, 0); \
540                 if (isc_time_add((a), &_i, (c)) != ISC_R_SUCCESS) { \
541                         dns_zone_log(zone, ISC_LOG_WARNING, \
542                                      "epoch approaching: upgrade required: " \
543                                      "now + %s failed", #b); \
544                         isc_interval_set(&_i, _j/2, 0); \
545                         (void)isc_time_add((a), &_i, (c)); \
546                 } \
547         } while (0)
548
549 #define DNS_ZONE_TIME_ADD(a, b, c) \
550         do { \
551                 isc_interval_t _i; \
552                 isc_interval_set(&_i, (b), 0); \
553                 if (isc_time_add((a), &_i, (c)) != ISC_R_SUCCESS) { \
554                         dns_zone_log(zone, ISC_LOG_WARNING, \
555                                      "epoch approaching: upgrade required: " \
556                                      "now + %s failed", #b); \
557                         isc_interval_set(&_i, (b)/2, 0); \
558                         (void)isc_time_add((a), &_i, (c)); \
559                 } \
560         } while (0)
561
562 /*%
563  * Increment resolver-related statistics counters.  Zone must be locked.
564  */
565 static inline void
566 inc_stats(dns_zone_t *zone, isc_statscounter_t counter) {
567         if (zone->stats != NULL)
568                 isc_stats_increment(zone->stats, counter);
569 }
570
571 /***
572  ***    Public functions.
573  ***/
574
575 isc_result_t
576 dns_zone_create(dns_zone_t **zonep, isc_mem_t *mctx) {
577         isc_result_t result;
578         dns_zone_t *zone;
579         isc_time_t now;
580
581         REQUIRE(zonep != NULL && *zonep == NULL);
582         REQUIRE(mctx != NULL);
583
584         TIME_NOW(&now);
585         zone = isc_mem_get(mctx, sizeof(*zone));
586         if (zone == NULL)
587                 return (ISC_R_NOMEMORY);
588
589         zone->mctx = NULL;
590         isc_mem_attach(mctx, &zone->mctx);
591
592         result = isc_mutex_init(&zone->lock);
593         if (result != ISC_R_SUCCESS)
594                 goto free_zone;
595
596         result = ZONEDB_INITLOCK(&zone->dblock);
597         if (result != ISC_R_SUCCESS)
598                 goto free_mutex;
599
600         /* XXX MPA check that all elements are initialised */
601 #ifdef DNS_ZONE_CHECKLOCK
602         zone->locked = ISC_FALSE;
603 #endif
604         zone->db = NULL;
605         zone->zmgr = NULL;
606         ISC_LINK_INIT(zone, link);
607         result = isc_refcount_init(&zone->erefs, 1);    /* Implicit attach. */
608         if (result != ISC_R_SUCCESS)
609                 goto free_dblock;
610         zone->irefs = 0;
611         dns_name_init(&zone->origin, NULL);
612         zone->strnamerd = NULL;
613         zone->strname = NULL;
614         zone->strrdclass = NULL;
615         zone->strviewname = NULL;
616         zone->masterfile = NULL;
617         zone->masterformat =  dns_masterformat_none;
618         zone->keydirectory = NULL;
619         zone->journalsize = -1;
620         zone->journal = NULL;
621         zone->rdclass = dns_rdataclass_none;
622         zone->type = dns_zone_none;
623         zone->flags = 0;
624         zone->options = 0;
625         zone->db_argc = 0;
626         zone->db_argv = NULL;
627         isc_time_settoepoch(&zone->expiretime);
628         isc_time_settoepoch(&zone->refreshtime);
629         isc_time_settoepoch(&zone->dumptime);
630         isc_time_settoepoch(&zone->loadtime);
631         zone->notifytime = now;
632         zone->serial = 0;
633         zone->refresh = DNS_ZONE_DEFAULTREFRESH;
634         zone->retry = DNS_ZONE_DEFAULTRETRY;
635         zone->expire = 0;
636         zone->minimum = 0;
637         zone->maxrefresh = DNS_ZONE_MAXREFRESH;
638         zone->minrefresh = DNS_ZONE_MINREFRESH;
639         zone->maxretry = DNS_ZONE_MAXRETRY;
640         zone->minretry = DNS_ZONE_MINRETRY;
641         zone->masters = NULL;
642         zone->masterkeynames = NULL;
643         zone->mastersok = NULL;
644         zone->masterscnt = 0;
645         zone->curmaster = 0;
646         zone->notify = NULL;
647         zone->notifytype = dns_notifytype_yes;
648         zone->notifycnt = 0;
649         zone->task = NULL;
650         zone->update_acl = NULL;
651         zone->forward_acl = NULL;
652         zone->notify_acl = NULL;
653         zone->query_acl = NULL;
654         zone->queryon_acl = NULL;
655         zone->xfr_acl = NULL;
656         zone->update_disabled = ISC_FALSE;
657         zone->zero_no_soa_ttl = ISC_TRUE;
658         zone->check_names = dns_severity_ignore;
659         zone->request = NULL;
660         zone->lctx = NULL;
661         zone->readio = NULL;
662         zone->dctx = NULL;
663         zone->writeio = NULL;
664         zone->timer = NULL;
665         zone->idlein = DNS_DEFAULT_IDLEIN;
666         zone->idleout = DNS_DEFAULT_IDLEOUT;
667         ISC_LIST_INIT(zone->notifies);
668         isc_sockaddr_any(&zone->notifysrc4);
669         isc_sockaddr_any6(&zone->notifysrc6);
670         isc_sockaddr_any(&zone->xfrsource4);
671         isc_sockaddr_any6(&zone->xfrsource6);
672         isc_sockaddr_any(&zone->altxfrsource4);
673         isc_sockaddr_any6(&zone->altxfrsource6);
674         zone->xfr = NULL;
675         zone->tsigkey = NULL;
676         zone->maxxfrin = MAX_XFER_TIME;
677         zone->maxxfrout = MAX_XFER_TIME;
678         zone->ssutable = NULL;
679         zone->sigvalidityinterval = 30 * 24 * 3600;
680         zone->view = NULL;
681         zone->acache = NULL;
682         zone->checkmx = NULL;
683         zone->checksrv = NULL;
684         zone->checkns = NULL;
685         ISC_LINK_INIT(zone, statelink);
686         zone->statelist = NULL;
687         zone->stats = NULL;
688         zone->requeststats_on = ISC_FALSE;
689         zone->requeststats = NULL;
690         zone->notifydelay = 5;
691         zone->isself = NULL;
692         zone->isselfarg = NULL;
693
694         zone->magic = ZONE_MAGIC;
695
696         /* Must be after magic is set. */
697         result = dns_zone_setdbtype(zone, dbargc_default, dbargv_default);
698         if (result != ISC_R_SUCCESS)
699                 goto free_erefs;
700
701         ISC_EVENT_INIT(&zone->ctlevent, sizeof(zone->ctlevent), 0, NULL,
702                        DNS_EVENT_ZONECONTROL, zone_shutdown, zone, zone,
703                        NULL, NULL);
704         *zonep = zone;
705         return (ISC_R_SUCCESS);
706
707  free_erefs:
708         isc_refcount_decrement(&zone->erefs, NULL);
709         isc_refcount_destroy(&zone->erefs);
710
711  free_dblock:
712         ZONEDB_DESTROYLOCK(&zone->dblock);
713
714  free_mutex:
715         DESTROYLOCK(&zone->lock);
716
717  free_zone:
718         isc_mem_putanddetach(&zone->mctx, zone, sizeof(*zone));
719         return (result);
720 }
721
722 /*
723  * Free a zone.  Because we require that there be no more
724  * outstanding events or references, no locking is necessary.
725  */
726 static void
727 zone_free(dns_zone_t *zone) {
728         isc_mem_t *mctx = NULL;
729
730         REQUIRE(DNS_ZONE_VALID(zone));
731         REQUIRE(isc_refcount_current(&zone->erefs) == 0);
732         REQUIRE(zone->irefs == 0);
733         REQUIRE(!LOCKED_ZONE(zone));
734         REQUIRE(zone->timer == NULL);
735
736         /*
737          * Managed objects.  Order is important.
738          */
739         if (zone->request != NULL)
740                 dns_request_destroy(&zone->request); /* XXXMPA */
741         INSIST(zone->readio == NULL);
742         INSIST(zone->statelist == NULL);
743         INSIST(zone->writeio == NULL);
744
745         if (zone->task != NULL)
746                 isc_task_detach(&zone->task);
747         if (zone->zmgr != NULL)
748                 dns_zonemgr_releasezone(zone->zmgr, zone);
749
750         /* Unmanaged objects */
751         if (zone->masterfile != NULL)
752                 isc_mem_free(zone->mctx, zone->masterfile);
753         zone->masterfile = NULL;
754         if (zone->keydirectory != NULL)
755                 isc_mem_free(zone->mctx, zone->keydirectory);
756         zone->keydirectory = NULL;
757         zone->journalsize = -1;
758         if (zone->journal != NULL)
759                 isc_mem_free(zone->mctx, zone->journal);
760         zone->journal = NULL;
761         if (zone->stats != NULL)
762                 isc_stats_detach(&zone->stats);
763         if (zone->requeststats != NULL)
764                 isc_stats_detach(&zone->requeststats);
765         if (zone->db != NULL)
766                 zone_detachdb(zone);
767         if (zone->acache != NULL)
768                 dns_acache_detach(&zone->acache);
769         zone_freedbargs(zone);
770         RUNTIME_CHECK(dns_zone_setmasterswithkeys(zone, NULL, NULL, 0)
771                       == ISC_R_SUCCESS);
772         RUNTIME_CHECK(dns_zone_setalsonotify(zone, NULL, 0)
773                       == ISC_R_SUCCESS);
774         zone->check_names = dns_severity_ignore;
775         if (zone->update_acl != NULL)
776                 dns_acl_detach(&zone->update_acl);
777         if (zone->forward_acl != NULL)
778                 dns_acl_detach(&zone->forward_acl);
779         if (zone->notify_acl != NULL)
780                 dns_acl_detach(&zone->notify_acl);
781         if (zone->query_acl != NULL)
782                 dns_acl_detach(&zone->query_acl);
783         if (zone->queryon_acl != NULL)
784                 dns_acl_detach(&zone->queryon_acl);
785         if (zone->xfr_acl != NULL)
786                 dns_acl_detach(&zone->xfr_acl);
787         if (dns_name_dynamic(&zone->origin))
788                 dns_name_free(&zone->origin, zone->mctx);
789         if (zone->strnamerd != NULL)
790                 isc_mem_free(zone->mctx, zone->strnamerd);
791         if (zone->strname != NULL)
792                 isc_mem_free(zone->mctx, zone->strname);
793         if (zone->strrdclass != NULL)
794                 isc_mem_free(zone->mctx, zone->strrdclass);
795         if (zone->strviewname != NULL)
796                 isc_mem_free(zone->mctx, zone->strviewname);
797         if (zone->ssutable != NULL)
798                 dns_ssutable_detach(&zone->ssutable);
799
800         /* last stuff */
801         ZONEDB_DESTROYLOCK(&zone->dblock);
802         DESTROYLOCK(&zone->lock);
803         isc_refcount_destroy(&zone->erefs);
804         zone->magic = 0;
805         mctx = zone->mctx;
806         isc_mem_put(mctx, zone, sizeof(*zone));
807         isc_mem_detach(&mctx);
808 }
809
810 /*
811  *      Single shot.
812  */
813 void
814 dns_zone_setclass(dns_zone_t *zone, dns_rdataclass_t rdclass) {
815         char namebuf[1024];
816
817         REQUIRE(DNS_ZONE_VALID(zone));
818         REQUIRE(rdclass != dns_rdataclass_none);
819
820         /*
821          * Test and set.
822          */
823         LOCK_ZONE(zone);
824         REQUIRE(zone->rdclass == dns_rdataclass_none ||
825                 zone->rdclass == rdclass);
826         zone->rdclass = rdclass;
827
828         if (zone->strnamerd != NULL)
829                 isc_mem_free(zone->mctx, zone->strnamerd);
830         if (zone->strrdclass != NULL)
831                 isc_mem_free(zone->mctx, zone->strrdclass);
832
833         zone_namerd_tostr(zone, namebuf, sizeof namebuf);
834         zone->strnamerd = isc_mem_strdup(zone->mctx, namebuf);
835         zone_rdclass_tostr(zone, namebuf, sizeof namebuf);
836         zone->strrdclass = isc_mem_strdup(zone->mctx, namebuf);
837
838         UNLOCK_ZONE(zone);
839 }
840
841 dns_rdataclass_t
842 dns_zone_getclass(dns_zone_t *zone) {
843         REQUIRE(DNS_ZONE_VALID(zone));
844
845         return (zone->rdclass);
846 }
847
848 void
849 dns_zone_setnotifytype(dns_zone_t *zone, dns_notifytype_t notifytype) {
850         REQUIRE(DNS_ZONE_VALID(zone));
851
852         LOCK_ZONE(zone);
853         zone->notifytype = notifytype;
854         UNLOCK_ZONE(zone);
855 }
856
857 isc_uint32_t
858 dns_zone_getserial(dns_zone_t *zone) {
859         isc_uint32_t serial;
860
861         REQUIRE(DNS_ZONE_VALID(zone));
862
863         LOCK_ZONE(zone);
864         serial = zone->serial;
865         UNLOCK_ZONE(zone);
866
867         return (serial);
868 }
869
870 /*
871  *      Single shot.
872  */
873 void
874 dns_zone_settype(dns_zone_t *zone, dns_zonetype_t type) {
875
876         REQUIRE(DNS_ZONE_VALID(zone));
877         REQUIRE(type != dns_zone_none);
878
879         /*
880          * Test and set.
881          */
882         LOCK_ZONE(zone);
883         REQUIRE(zone->type == dns_zone_none || zone->type == type);
884         zone->type = type;
885         UNLOCK_ZONE(zone);
886 }
887
888 static void
889 zone_freedbargs(dns_zone_t *zone) {
890         unsigned int i;
891
892         /* Free the old database argument list. */
893         if (zone->db_argv != NULL) {
894                 for (i = 0; i < zone->db_argc; i++)
895                         isc_mem_free(zone->mctx, zone->db_argv[i]);
896                 isc_mem_put(zone->mctx, zone->db_argv,
897                             zone->db_argc * sizeof(*zone->db_argv));
898         }
899         zone->db_argc = 0;
900         zone->db_argv = NULL;
901 }
902
903 isc_result_t
904 dns_zone_getdbtype(dns_zone_t *zone, char ***argv, isc_mem_t *mctx) {
905         size_t size = 0;
906         unsigned int i;
907         isc_result_t result = ISC_R_SUCCESS;
908         void *mem;
909         char **tmp, *tmp2;
910
911         REQUIRE(DNS_ZONE_VALID(zone));
912         REQUIRE(argv != NULL && *argv == NULL);
913
914         LOCK_ZONE(zone);
915         size = (zone->db_argc + 1) * sizeof(char *);
916         for (i = 0; i < zone->db_argc; i++)
917                 size += strlen(zone->db_argv[i]) + 1;
918         mem = isc_mem_allocate(mctx, size);
919         if (mem != NULL) {
920                 tmp = mem;
921                 tmp2 = mem;
922                 tmp2 += (zone->db_argc + 1) * sizeof(char *);
923                 for (i = 0; i < zone->db_argc; i++) {
924                         *tmp++ = tmp2;
925                         strcpy(tmp2, zone->db_argv[i]);
926                         tmp2 += strlen(tmp2) + 1;
927                 }
928                 *tmp = NULL;
929         } else
930                 result = ISC_R_NOMEMORY;
931         UNLOCK_ZONE(zone);
932         *argv = mem;
933         return (result);
934 }
935
936 isc_result_t
937 dns_zone_setdbtype(dns_zone_t *zone,
938                    unsigned int dbargc, const char * const *dbargv) {
939         isc_result_t result = ISC_R_SUCCESS;
940         char **new = NULL;
941         unsigned int i;
942
943         REQUIRE(DNS_ZONE_VALID(zone));
944         REQUIRE(dbargc >= 1);
945         REQUIRE(dbargv != NULL);
946
947         LOCK_ZONE(zone);
948
949         /* Set up a new database argument list. */
950         new = isc_mem_get(zone->mctx, dbargc * sizeof(*new));
951         if (new == NULL)
952                 goto nomem;
953         for (i = 0; i < dbargc; i++)
954                 new[i] = NULL;
955         for (i = 0; i < dbargc; i++) {
956                 new[i] = isc_mem_strdup(zone->mctx, dbargv[i]);
957                 if (new[i] == NULL)
958                         goto nomem;
959         }
960
961         /* Free the old list. */
962         zone_freedbargs(zone);
963
964         zone->db_argc = dbargc;
965         zone->db_argv = new;
966         result = ISC_R_SUCCESS;
967         goto unlock;
968
969  nomem:
970         if (new != NULL) {
971                 for (i = 0; i < dbargc; i++)
972                         if (new[i] != NULL)
973                                 isc_mem_free(zone->mctx, new[i]);
974                 isc_mem_put(zone->mctx, new, dbargc * sizeof(*new));
975         }
976         result = ISC_R_NOMEMORY;
977
978  unlock:
979         UNLOCK_ZONE(zone);
980         return (result);
981 }
982
983 void
984 dns_zone_setview(dns_zone_t *zone, dns_view_t *view) {
985         char namebuf[1024];
986         REQUIRE(DNS_ZONE_VALID(zone));
987
988         LOCK_ZONE(zone);
989         if (zone->view != NULL)
990                 dns_view_weakdetach(&zone->view);
991         dns_view_weakattach(view, &zone->view);
992
993         if (zone->strviewname != NULL)
994                 isc_mem_free(zone->mctx, zone->strviewname);
995         if (zone->strnamerd != NULL)
996                 isc_mem_free(zone->mctx, zone->strnamerd);
997
998         zone_namerd_tostr(zone, namebuf, sizeof namebuf);
999         zone->strnamerd = isc_mem_strdup(zone->mctx, namebuf);
1000         zone_viewname_tostr(zone, namebuf, sizeof namebuf);
1001         zone->strviewname = isc_mem_strdup(zone->mctx, namebuf);
1002
1003         UNLOCK_ZONE(zone);
1004 }
1005
1006
1007 dns_view_t *
1008 dns_zone_getview(dns_zone_t *zone) {
1009         REQUIRE(DNS_ZONE_VALID(zone));
1010
1011         return (zone->view);
1012 }
1013
1014
1015 isc_result_t
1016 dns_zone_setorigin(dns_zone_t *zone, const dns_name_t *origin) {
1017         isc_result_t result;
1018         char namebuf[1024];
1019
1020         REQUIRE(DNS_ZONE_VALID(zone));
1021         REQUIRE(origin != NULL);
1022
1023         LOCK_ZONE(zone);
1024         if (dns_name_dynamic(&zone->origin)) {
1025                 dns_name_free(&zone->origin, zone->mctx);
1026                 dns_name_init(&zone->origin, NULL);
1027         }
1028         result = dns_name_dup(origin, zone->mctx, &zone->origin);
1029
1030         if (zone->strnamerd != NULL)
1031                 isc_mem_free(zone->mctx, zone->strnamerd);
1032         if (zone->strname != NULL)
1033                 isc_mem_free(zone->mctx, zone->strname);
1034
1035         zone_namerd_tostr(zone, namebuf, sizeof namebuf);
1036         zone->strnamerd = isc_mem_strdup(zone->mctx, namebuf);
1037         zone_name_tostr(zone, namebuf, sizeof namebuf);
1038         zone->strname = isc_mem_strdup(zone->mctx, namebuf);
1039
1040         UNLOCK_ZONE(zone);
1041         return (result);
1042 }
1043
1044 void
1045 dns_zone_setacache(dns_zone_t *zone, dns_acache_t *acache) {
1046         REQUIRE(DNS_ZONE_VALID(zone));
1047         REQUIRE(acache != NULL);
1048
1049         LOCK_ZONE(zone);
1050         if (zone->acache != NULL)
1051                 dns_acache_detach(&zone->acache);
1052         dns_acache_attach(acache, &zone->acache);
1053         ZONEDB_LOCK(&zone->dblock, isc_rwlocktype_read);
1054         if (zone->db != NULL) {
1055                 isc_result_t result;
1056
1057                 /*
1058                  * If the zone reuses an existing DB, the DB needs to be
1059                  * set in the acache explicitly.  We can safely ignore the
1060                  * case where the DB is already set.  If other error happens,
1061                  * the acache will not work effectively.
1062                  */
1063                 result = dns_acache_setdb(acache, zone->db);
1064                 if (result != ISC_R_SUCCESS && result != ISC_R_EXISTS) {
1065                         UNEXPECTED_ERROR(__FILE__, __LINE__,
1066                                          "dns_acache_setdb() failed: %s",
1067                                          isc_result_totext(result));
1068                 }
1069         }
1070         ZONEDB_UNLOCK(&zone->dblock, isc_rwlocktype_read);
1071         UNLOCK_ZONE(zone);
1072 }
1073
1074 static isc_result_t
1075 dns_zone_setstring(dns_zone_t *zone, char **field, const char *value) {
1076         char *copy;
1077
1078         if (value != NULL) {
1079                 copy = isc_mem_strdup(zone->mctx, value);
1080                 if (copy == NULL)
1081                         return (ISC_R_NOMEMORY);
1082         } else {
1083                 copy = NULL;
1084         }
1085
1086         if (*field != NULL)
1087                 isc_mem_free(zone->mctx, *field);
1088
1089         *field = copy;
1090         return (ISC_R_SUCCESS);
1091 }
1092
1093 isc_result_t
1094 dns_zone_setfile(dns_zone_t *zone, const char *file) {
1095         return (dns_zone_setfile2(zone, file, dns_masterformat_text));
1096 }
1097
1098 isc_result_t
1099 dns_zone_setfile2(dns_zone_t *zone, const char *file,
1100                   dns_masterformat_t format) {
1101         isc_result_t result = ISC_R_SUCCESS;
1102
1103         REQUIRE(DNS_ZONE_VALID(zone));
1104
1105         LOCK_ZONE(zone);
1106         result = dns_zone_setstring(zone, &zone->masterfile, file);
1107         if (result == ISC_R_SUCCESS) {
1108                 zone->masterformat = format;
1109                 result = default_journal(zone);
1110         }
1111         UNLOCK_ZONE(zone);
1112
1113         return (result);
1114 }
1115
1116 const char *
1117 dns_zone_getfile(dns_zone_t *zone) {
1118         REQUIRE(DNS_ZONE_VALID(zone));
1119
1120         return (zone->masterfile);
1121 }
1122
1123 static isc_result_t
1124 default_journal(dns_zone_t *zone) {
1125         isc_result_t result;
1126         char *journal;
1127
1128         REQUIRE(DNS_ZONE_VALID(zone));
1129         REQUIRE(LOCKED_ZONE(zone));
1130
1131         if (zone->masterfile != NULL) {
1132                 /* Calculate string length including '\0'. */
1133                 int len = strlen(zone->masterfile) + sizeof(".jnl");
1134                 journal = isc_mem_allocate(zone->mctx, len);
1135                 if (journal == NULL)
1136                         return (ISC_R_NOMEMORY);
1137                 strcpy(journal, zone->masterfile);
1138                 strcat(journal, ".jnl");
1139         } else {
1140                 journal = NULL;
1141         }
1142         result = dns_zone_setstring(zone, &zone->journal, journal);
1143         if (journal != NULL)
1144                 isc_mem_free(zone->mctx, journal);
1145         return (result);
1146 }
1147
1148 isc_result_t
1149 dns_zone_setjournal(dns_zone_t *zone, const char *journal) {
1150         isc_result_t result = ISC_R_SUCCESS;
1151
1152         REQUIRE(DNS_ZONE_VALID(zone));
1153
1154         LOCK_ZONE(zone);
1155         result = dns_zone_setstring(zone, &zone->journal, journal);
1156         UNLOCK_ZONE(zone);
1157
1158         return (result);
1159 }
1160
1161 char *
1162 dns_zone_getjournal(dns_zone_t *zone) {
1163         REQUIRE(DNS_ZONE_VALID(zone));
1164
1165         return (zone->journal);
1166 }
1167
1168 /*
1169  * Return true iff the zone is "dynamic", in the sense that the zone's
1170  * master file (if any) is written by the server, rather than being
1171  * updated manually and read by the server.
1172  *
1173  * This is true for slave zones, stub zones, and zones that allow
1174  * dynamic updates either by having an update policy ("ssutable")
1175  * or an "allow-update" ACL with a value other than exactly "{ none; }".
1176  */
1177 static isc_boolean_t
1178 zone_isdynamic(dns_zone_t *zone) {
1179         REQUIRE(DNS_ZONE_VALID(zone));
1180
1181         return (ISC_TF(zone->type == dns_zone_slave ||
1182                        zone->type == dns_zone_stub ||
1183                        (!zone->update_disabled && zone->ssutable != NULL) ||
1184                        (!zone->update_disabled && zone->update_acl != NULL &&
1185                         !dns_acl_isnone(zone->update_acl))));
1186 }
1187
1188
1189 static isc_result_t
1190 zone_load(dns_zone_t *zone, unsigned int flags) {
1191         isc_result_t result;
1192         isc_time_t now;
1193         isc_time_t loadtime, filetime;
1194         dns_db_t *db = NULL;
1195
1196         REQUIRE(DNS_ZONE_VALID(zone));
1197
1198         LOCK_ZONE(zone);
1199         TIME_NOW(&now);
1200
1201         INSIST(zone->type != dns_zone_none);
1202
1203         if (DNS_ZONE_FLAG(zone, DNS_ZONEFLG_LOADING)) {
1204                 if ((flags & DNS_ZONELOADFLAG_THAW) != 0)
1205                         DNS_ZONE_SETFLAG(zone, DNS_ZONEFLG_THAW);
1206                 result = DNS_R_CONTINUE;
1207                 goto cleanup;
1208         }
1209
1210         if (zone->db != NULL && zone->masterfile == NULL) {
1211                 /*
1212                  * The zone has no master file configured, but it already
1213                  * has a database.  It could be the built-in
1214                  * version.bind. CH zone, a zone with a persistent
1215                  * database being reloaded, or maybe a zone that
1216                  * used to have a master file but whose configuration
1217                  * was changed so that it no longer has one.  Do nothing.
1218                  */
1219                 result = ISC_R_SUCCESS;
1220                 goto cleanup;
1221         }
1222
1223         if (zone->db != NULL && zone_isdynamic(zone)) {
1224                 /*
1225                  * This is a slave, stub, or dynamically updated
1226                  * zone being reloaded.  Do nothing - the database
1227                  * we already have is guaranteed to be up-to-date.
1228                  */
1229                 if (zone->type == dns_zone_master)
1230                         result = DNS_R_DYNAMIC;
1231                 else
1232                         result = ISC_R_SUCCESS;
1233                 goto cleanup;
1234         }
1235
1236
1237         /*
1238          * Store the current time before the zone is loaded, so that if the
1239          * file changes between the time of the load and the time that
1240          * zone->loadtime is set, then the file will still be reloaded
1241          * the next time dns_zone_load is called.
1242          */
1243         TIME_NOW(&loadtime);
1244
1245         /*
1246          * Don't do the load if the file that stores the zone is older
1247          * than the last time the zone was loaded.  If the zone has not
1248          * been loaded yet, zone->loadtime will be the epoch.
1249          */
1250         if (zone->masterfile != NULL) {
1251                 /*
1252                  * The file is already loaded.  If we are just doing a
1253                  * "rndc reconfig", we are done.
1254                  */
1255                 if (!isc_time_isepoch(&zone->loadtime) &&
1256                     (flags & DNS_ZONELOADFLAG_NOSTAT) != 0) {
1257                         result = ISC_R_SUCCESS;
1258                         goto cleanup;
1259                 }
1260
1261                 result = isc_file_getmodtime(zone->masterfile, &filetime);
1262                 if (result == ISC_R_SUCCESS) {
1263                         if (DNS_ZONE_FLAG(zone, DNS_ZONEFLG_LOADED) &&
1264                             !DNS_ZONE_FLAG(zone, DNS_ZONEFLG_HASINCLUDE) &&
1265                             isc_time_compare(&filetime, &zone->loadtime) <= 0) {
1266                                 dns_zone_log(zone, ISC_LOG_DEBUG(1),
1267                                              "skipping load: master file "
1268                                              "older than last load");
1269                                 result = DNS_R_UPTODATE;
1270                                 goto cleanup;
1271                         }
1272                         loadtime = filetime;
1273                 }
1274         }
1275
1276         INSIST(zone->db_argc >= 1);
1277
1278         /*
1279          * Built in zones don't need to be reloaded.
1280          */
1281         if (zone->type == dns_zone_master &&
1282             strcmp(zone->db_argv[0], "_builtin") == 0 &&
1283             DNS_ZONE_FLAG(zone, DNS_ZONEFLG_LOADED)) {
1284                 result = ISC_R_SUCCESS;
1285                 goto cleanup;
1286         }
1287
1288         if ((zone->type == dns_zone_slave || zone->type == dns_zone_stub) &&
1289             (strcmp(zone->db_argv[0], "rbt") == 0 ||
1290              strcmp(zone->db_argv[0], "rbt64") == 0)) {
1291                 if (zone->masterfile == NULL ||
1292                     !isc_file_exists(zone->masterfile)) {
1293                         if (zone->masterfile != NULL) {
1294                                 dns_zone_log(zone, ISC_LOG_DEBUG(1),
1295                                              "no master file");
1296                         }
1297                         zone->refreshtime = now;
1298                         if (zone->task != NULL)
1299                                 zone_settimer(zone, &now);
1300                         result = ISC_R_SUCCESS;
1301                         goto cleanup;
1302                 }
1303         }
1304
1305         dns_zone_log(zone, ISC_LOG_DEBUG(1), "starting load");
1306
1307         result = dns_db_create(zone->mctx, zone->db_argv[0],
1308                                &zone->origin, (zone->type == dns_zone_stub) ?
1309                                dns_dbtype_stub : dns_dbtype_zone,
1310                                zone->rdclass,
1311                                zone->db_argc - 1, zone->db_argv + 1,
1312                                &db);
1313
1314         if (result != ISC_R_SUCCESS) {
1315                 dns_zone_log(zone, ISC_LOG_ERROR,
1316                              "loading zone: creating database: %s",
1317                              isc_result_totext(result));
1318                 goto cleanup;
1319         }
1320         dns_db_settask(db, zone->task);
1321
1322         if (! dns_db_ispersistent(db)) {
1323                 if (zone->masterfile != NULL) {
1324                         result = zone_startload(db, zone, loadtime);
1325                 } else {
1326                         result = DNS_R_NOMASTERFILE;
1327                         if (zone->type == dns_zone_master) {
1328                                 dns_zone_log(zone, ISC_LOG_ERROR,
1329                                              "loading zone: "
1330                                              "no master file configured");
1331                                 goto cleanup;
1332                         }
1333                         dns_zone_log(zone, ISC_LOG_INFO, "loading zone: "
1334                                      "no master file configured: continuing");
1335                 }
1336         }
1337
1338         if (result == DNS_R_CONTINUE) {
1339                 DNS_ZONE_SETFLAG(zone, DNS_ZONEFLG_LOADING);
1340                 if ((flags & DNS_ZONELOADFLAG_THAW) != 0)
1341                         DNS_ZONE_SETFLAG(zone, DNS_ZONEFLG_THAW);
1342                 goto cleanup;
1343         }
1344
1345         result = zone_postload(zone, db, loadtime, result);
1346
1347  cleanup:
1348         UNLOCK_ZONE(zone);
1349         if (db != NULL)
1350                 dns_db_detach(&db);
1351         return (result);
1352 }
1353
1354 isc_result_t
1355 dns_zone_load(dns_zone_t *zone) {
1356         return (zone_load(zone, 0));
1357 }
1358
1359 isc_result_t
1360 dns_zone_loadnew(dns_zone_t *zone) {
1361         return (zone_load(zone, DNS_ZONELOADFLAG_NOSTAT));
1362 }
1363
1364 isc_result_t
1365 dns_zone_loadandthaw(dns_zone_t *zone) {
1366         isc_result_t result;
1367
1368         result = zone_load(zone, DNS_ZONELOADFLAG_THAW);
1369         switch (result) {
1370         case DNS_R_CONTINUE:
1371                 /* Deferred thaw. */
1372                 break;
1373         case ISC_R_SUCCESS:
1374         case DNS_R_UPTODATE:
1375         case DNS_R_SEENINCLUDE:
1376                 zone->update_disabled = ISC_FALSE;
1377                 break;
1378         case DNS_R_NOMASTERFILE:
1379                 zone->update_disabled = ISC_FALSE;
1380                 break;
1381         default:
1382                 /* Error, remain in disabled state. */
1383                 break;
1384         }
1385         return (result);
1386 }
1387
1388 static void
1389 zone_gotreadhandle(isc_task_t *task, isc_event_t *event) {
1390         dns_load_t *load = event->ev_arg;
1391         isc_result_t result = ISC_R_SUCCESS;
1392         unsigned int options;
1393
1394         REQUIRE(DNS_LOAD_VALID(load));
1395
1396         if ((event->ev_attributes & ISC_EVENTATTR_CANCELED) != 0)
1397                 result = ISC_R_CANCELED;
1398         isc_event_free(&event);
1399         if (result == ISC_R_CANCELED)
1400                 goto fail;
1401
1402         options = DNS_MASTER_ZONE;
1403         if (load->zone->type == dns_zone_slave)
1404                 options |= DNS_MASTER_SLAVE;
1405         if (DNS_ZONE_OPTION(load->zone, DNS_ZONEOPT_CHECKNS))
1406                 options |= DNS_MASTER_CHECKNS;
1407         if (DNS_ZONE_OPTION(load->zone, DNS_ZONEOPT_FATALNS))
1408                 options |= DNS_MASTER_FATALNS;
1409         if (DNS_ZONE_OPTION(load->zone, DNS_ZONEOPT_CHECKNAMES))
1410                 options |= DNS_MASTER_CHECKNAMES;
1411         if (DNS_ZONE_OPTION(load->zone, DNS_ZONEOPT_CHECKNAMESFAIL))
1412                 options |= DNS_MASTER_CHECKNAMESFAIL;
1413         if (DNS_ZONE_OPTION(load->zone, DNS_ZONEOPT_CHECKMX))
1414                 options |= DNS_MASTER_CHECKMX;
1415         if (DNS_ZONE_OPTION(load->zone, DNS_ZONEOPT_CHECKMXFAIL))
1416                 options |= DNS_MASTER_CHECKMXFAIL;
1417         if (DNS_ZONE_OPTION(load->zone, DNS_ZONEOPT_CHECKWILDCARD))
1418                 options |= DNS_MASTER_CHECKWILDCARD;
1419         result = dns_master_loadfileinc2(load->zone->masterfile,
1420                                          dns_db_origin(load->db),
1421                                          dns_db_origin(load->db),
1422                                          load->zone->rdclass,
1423                                          options,
1424                                          &load->callbacks, task,
1425                                          zone_loaddone, load,
1426                                          &load->zone->lctx, load->zone->mctx,
1427                                          load->zone->masterformat);
1428         if (result != ISC_R_SUCCESS && result != DNS_R_CONTINUE &&
1429             result != DNS_R_SEENINCLUDE)
1430                 goto fail;
1431         return;
1432
1433  fail:
1434         zone_loaddone(load, result);
1435 }
1436
1437 static void
1438 zone_gotwritehandle(isc_task_t *task, isc_event_t *event) {
1439         const char me[] = "zone_gotwritehandle";
1440         dns_zone_t *zone = event->ev_arg;
1441         isc_result_t result = ISC_R_SUCCESS;
1442         dns_dbversion_t *version = NULL;
1443
1444         REQUIRE(DNS_ZONE_VALID(zone));
1445         INSIST(task == zone->task);
1446         ENTER;
1447
1448         if ((event->ev_attributes & ISC_EVENTATTR_CANCELED) != 0)
1449                 result = ISC_R_CANCELED;
1450         isc_event_free(&event);
1451         if (result == ISC_R_CANCELED)
1452                 goto fail;
1453
1454         LOCK_ZONE(zone);
1455         ZONEDB_LOCK(&zone->dblock, isc_rwlocktype_read);
1456         dns_db_currentversion(zone->db, &version);
1457         result = dns_master_dumpinc2(zone->mctx, zone->db, version,
1458                                      &dns_master_style_default,
1459                                      zone->masterfile, zone->task, dump_done,
1460                                      zone, &zone->dctx, zone->masterformat);
1461         dns_db_closeversion(zone->db, &version, ISC_FALSE);
1462         ZONEDB_UNLOCK(&zone->dblock, isc_rwlocktype_read);
1463         UNLOCK_ZONE(zone);
1464         if (result != DNS_R_CONTINUE)
1465                 goto fail;
1466         return;
1467
1468  fail:
1469         dump_done(zone, result);
1470 }
1471
1472 static isc_result_t
1473 zone_startload(dns_db_t *db, dns_zone_t *zone, isc_time_t loadtime) {
1474         dns_load_t *load;
1475         isc_result_t result;
1476         isc_result_t tresult;
1477         unsigned int options;
1478
1479         options = DNS_MASTER_ZONE;
1480         if (DNS_ZONE_OPTION(zone, DNS_ZONEOPT_MANYERRORS))
1481                 options |= DNS_MASTER_MANYERRORS;
1482         if (DNS_ZONE_OPTION(zone, DNS_ZONEOPT_CHECKNS))
1483                 options |= DNS_MASTER_CHECKNS;
1484         if (DNS_ZONE_OPTION(zone, DNS_ZONEOPT_FATALNS))
1485                 options |= DNS_MASTER_FATALNS;
1486         if (zone->type == dns_zone_slave)
1487                 options |= DNS_MASTER_SLAVE;
1488         if (DNS_ZONE_OPTION(zone, DNS_ZONEOPT_CHECKNAMES))
1489                 options |= DNS_MASTER_CHECKNAMES;
1490         if (DNS_ZONE_OPTION(zone, DNS_ZONEOPT_CHECKNAMESFAIL))
1491                 options |= DNS_MASTER_CHECKNAMESFAIL;
1492         if (DNS_ZONE_OPTION(zone, DNS_ZONEOPT_CHECKMX))
1493                 options |= DNS_MASTER_CHECKMX;
1494         if (DNS_ZONE_OPTION(zone, DNS_ZONEOPT_CHECKMXFAIL))
1495                 options |= DNS_MASTER_CHECKMXFAIL;
1496         if (DNS_ZONE_OPTION(zone, DNS_ZONEOPT_CHECKWILDCARD))
1497                 options |= DNS_MASTER_CHECKWILDCARD;
1498
1499         if (zone->zmgr != NULL && zone->db != NULL && zone->task != NULL) {
1500                 load = isc_mem_get(zone->mctx, sizeof(*load));
1501                 if (load == NULL)
1502                         return (ISC_R_NOMEMORY);
1503
1504                 load->mctx = NULL;
1505                 load->zone = NULL;
1506                 load->db = NULL;
1507                 load->loadtime = loadtime;
1508                 load->magic = LOAD_MAGIC;
1509
1510                 isc_mem_attach(zone->mctx, &load->mctx);
1511                 zone_iattach(zone, &load->zone);
1512                 dns_db_attach(db, &load->db);
1513                 dns_rdatacallbacks_init(&load->callbacks);
1514                 result = dns_db_beginload(db, &load->callbacks.add,
1515                                           &load->callbacks.add_private);
1516                 if (result != ISC_R_SUCCESS)
1517                         goto cleanup;
1518                 result = zonemgr_getio(zone->zmgr, ISC_TRUE, zone->task,
1519                                        zone_gotreadhandle, load,
1520                                        &zone->readio);
1521                 if (result != ISC_R_SUCCESS) {
1522                         /*
1523                          * We can't report multiple errors so ignore
1524                          * the result of dns_db_endload().
1525                          */
1526                         (void)dns_db_endload(load->db,
1527                                              &load->callbacks.add_private);
1528                         goto cleanup;
1529                 } else
1530                         result = DNS_R_CONTINUE;
1531         } else {
1532                 dns_rdatacallbacks_t callbacks;
1533
1534                 dns_rdatacallbacks_init(&callbacks);
1535                 result = dns_db_beginload(db, &callbacks.add,
1536                                           &callbacks.add_private);
1537                 if (result != ISC_R_SUCCESS)
1538                         return (result);
1539                 result = dns_master_loadfile2(zone->masterfile, &zone->origin,
1540                                               &zone->origin, zone->rdclass,
1541                                               options, &callbacks, zone->mctx,
1542                                               zone->masterformat);
1543                 tresult = dns_db_endload(db, &callbacks.add_private);
1544                 if (result == ISC_R_SUCCESS)
1545                         result = tresult;
1546         }
1547
1548         return (result);
1549
1550  cleanup:
1551         load->magic = 0;
1552         dns_db_detach(&load->db);
1553         zone_idetach(&load->zone);
1554         isc_mem_detach(&load->mctx);
1555         isc_mem_put(zone->mctx, load, sizeof(*load));
1556         return (result);
1557 }
1558
1559 static isc_boolean_t
1560 zone_check_mx(dns_zone_t *zone, dns_db_t *db, dns_name_t *name,
1561               dns_name_t *owner)
1562 {
1563         isc_result_t result;
1564         char ownerbuf[DNS_NAME_FORMATSIZE];
1565         char namebuf[DNS_NAME_FORMATSIZE];
1566         char altbuf[DNS_NAME_FORMATSIZE];
1567         dns_fixedname_t fixed;
1568         dns_name_t *foundname;
1569         int level;
1570
1571         /*
1572          * Outside of zone.
1573          */
1574         if (!dns_name_issubdomain(name, &zone->origin)) {
1575                 if (zone->checkmx != NULL)
1576                         return ((zone->checkmx)(zone, name, owner));
1577                 return (ISC_TRUE);
1578         }
1579
1580         if (zone->type == dns_zone_master)
1581                 level = ISC_LOG_ERROR;
1582         else
1583                 level = ISC_LOG_WARNING;
1584
1585         dns_fixedname_init(&fixed);
1586         foundname = dns_fixedname_name(&fixed);
1587
1588         result = dns_db_find(db, name, NULL, dns_rdatatype_a,
1589                              0, 0, NULL, foundname, NULL, NULL);
1590         if (result == ISC_R_SUCCESS)
1591                 return (ISC_TRUE);
1592
1593         if (result == DNS_R_NXRRSET) {
1594                 result = dns_db_find(db, name, NULL, dns_rdatatype_aaaa,
1595                                      0, 0, NULL, foundname, NULL, NULL);
1596                 if (result == ISC_R_SUCCESS)
1597                         return (ISC_TRUE);
1598         }
1599
1600         dns_name_format(owner, ownerbuf, sizeof ownerbuf);
1601         dns_name_format(name, namebuf, sizeof namebuf);
1602         if (result == DNS_R_NXRRSET || result == DNS_R_NXDOMAIN ||
1603             result == DNS_R_EMPTYNAME) {
1604                 dns_zone_log(zone, level,
1605                              "%s/MX '%s' has no address records (A or AAAA)",
1606                              ownerbuf, namebuf);
1607                 /* XXX950 make fatal for 9.5.0. */
1608                 return (ISC_TRUE);
1609         }
1610
1611         if (result == DNS_R_CNAME) {
1612                 if (DNS_ZONE_OPTION(zone, DNS_ZONEOPT_WARNMXCNAME) ||
1613                     DNS_ZONE_OPTION(zone, DNS_ZONEOPT_IGNOREMXCNAME))
1614                         level = ISC_LOG_WARNING;
1615                 if (!DNS_ZONE_OPTION(zone, DNS_ZONEOPT_IGNOREMXCNAME))
1616                         dns_zone_log(zone, level,
1617                                      "%s/MX '%s' is a CNAME (illegal)",
1618                                      ownerbuf, namebuf);
1619                 return ((level == ISC_LOG_WARNING) ? ISC_TRUE : ISC_FALSE);
1620         }
1621
1622         if (result == DNS_R_DNAME) {
1623                 if (DNS_ZONE_OPTION(zone, DNS_ZONEOPT_WARNMXCNAME) ||
1624                     DNS_ZONE_OPTION(zone, DNS_ZONEOPT_IGNOREMXCNAME))
1625                         level = ISC_LOG_WARNING;
1626                 if (!DNS_ZONE_OPTION(zone, DNS_ZONEOPT_IGNOREMXCNAME)) {
1627                         dns_name_format(foundname, altbuf, sizeof altbuf);
1628                         dns_zone_log(zone, level, "%s/MX '%s' is below a DNAME"
1629                                      " '%s' (illegal)", ownerbuf, namebuf,
1630                                      altbuf);
1631                 }
1632                 return ((level == ISC_LOG_WARNING) ? ISC_TRUE : ISC_FALSE);
1633         }
1634
1635         if (zone->checkmx != NULL && result == DNS_R_DELEGATION)
1636                 return ((zone->checkmx)(zone, name, owner));
1637
1638         return (ISC_TRUE);
1639 }
1640
1641 static isc_boolean_t
1642 zone_check_srv(dns_zone_t *zone, dns_db_t *db, dns_name_t *name,
1643                dns_name_t *owner)
1644 {
1645         isc_result_t result;
1646         char ownerbuf[DNS_NAME_FORMATSIZE];
1647         char namebuf[DNS_NAME_FORMATSIZE];
1648         char altbuf[DNS_NAME_FORMATSIZE];
1649         dns_fixedname_t fixed;
1650         dns_name_t *foundname;
1651         int level;
1652
1653         /*
1654          * "." means the services does not exist.
1655          */
1656         if (dns_name_equal(name, dns_rootname))
1657                 return (ISC_TRUE);
1658
1659         /*
1660          * Outside of zone.
1661          */
1662         if (!dns_name_issubdomain(name, &zone->origin)) {
1663                 if (zone->checksrv != NULL)
1664                         return ((zone->checksrv)(zone, name, owner));
1665                 return (ISC_TRUE);
1666         }
1667
1668         if (zone->type == dns_zone_master)
1669                 level = ISC_LOG_ERROR;
1670         else
1671                 level = ISC_LOG_WARNING;
1672
1673         dns_fixedname_init(&fixed);
1674         foundname = dns_fixedname_name(&fixed);
1675
1676         result = dns_db_find(db, name, NULL, dns_rdatatype_a,
1677                              0, 0, NULL, foundname, NULL, NULL);
1678         if (result == ISC_R_SUCCESS)
1679                 return (ISC_TRUE);
1680
1681         if (result == DNS_R_NXRRSET) {
1682                 result = dns_db_find(db, name, NULL, dns_rdatatype_aaaa,
1683                                      0, 0, NULL, foundname, NULL, NULL);
1684                 if (result == ISC_R_SUCCESS)
1685                         return (ISC_TRUE);
1686         }
1687
1688         dns_name_format(owner, ownerbuf, sizeof ownerbuf);
1689         dns_name_format(name, namebuf, sizeof namebuf);
1690         if (result == DNS_R_NXRRSET || result == DNS_R_NXDOMAIN ||
1691             result == DNS_R_EMPTYNAME) {
1692                 dns_zone_log(zone, level,
1693                              "%s/SRV '%s' has no address records (A or AAAA)",
1694                              ownerbuf, namebuf);
1695                 /* XXX950 make fatal for 9.5.0. */
1696                 return (ISC_TRUE);
1697         }
1698
1699         if (result == DNS_R_CNAME) {
1700                 if (DNS_ZONE_OPTION(zone, DNS_ZONEOPT_WARNSRVCNAME) ||
1701                     DNS_ZONE_OPTION(zone, DNS_ZONEOPT_IGNORESRVCNAME))
1702                         level = ISC_LOG_WARNING;
1703                 if (!DNS_ZONE_OPTION(zone, DNS_ZONEOPT_IGNORESRVCNAME))
1704                         dns_zone_log(zone, level,
1705                                      "%s/SRV '%s' is a CNAME (illegal)",
1706                                      ownerbuf, namebuf);
1707                 return ((level == ISC_LOG_WARNING) ? ISC_TRUE : ISC_FALSE);
1708         }
1709
1710         if (result == DNS_R_DNAME) {
1711                 if (DNS_ZONE_OPTION(zone, DNS_ZONEOPT_WARNSRVCNAME) ||
1712                     DNS_ZONE_OPTION(zone, DNS_ZONEOPT_IGNORESRVCNAME))
1713                         level = ISC_LOG_WARNING;
1714                 if (!DNS_ZONE_OPTION(zone, DNS_ZONEOPT_IGNORESRVCNAME)) {
1715                         dns_name_format(foundname, altbuf, sizeof altbuf);
1716                         dns_zone_log(zone, level, "%s/SRV '%s' is below a "
1717                                      "DNAME '%s' (illegal)", ownerbuf, namebuf,
1718                                      altbuf);
1719                 }
1720                 return ((level == ISC_LOG_WARNING) ? ISC_TRUE : ISC_FALSE);
1721         }
1722
1723         if (zone->checksrv != NULL && result == DNS_R_DELEGATION)
1724                 return ((zone->checksrv)(zone, name, owner));
1725
1726         return (ISC_TRUE);
1727 }
1728
1729 static isc_boolean_t
1730 zone_check_glue(dns_zone_t *zone, dns_db_t *db, dns_name_t *name,
1731                 dns_name_t *owner)
1732 {
1733         isc_boolean_t answer = ISC_TRUE;
1734         isc_result_t result, tresult;
1735         char ownerbuf[DNS_NAME_FORMATSIZE];
1736         char namebuf[DNS_NAME_FORMATSIZE];
1737         char altbuf[DNS_NAME_FORMATSIZE];
1738         dns_fixedname_t fixed;
1739         dns_name_t *foundname;
1740         dns_rdataset_t a;
1741         dns_rdataset_t aaaa;
1742         int level;
1743
1744         /*
1745          * Outside of zone.
1746          */
1747         if (!dns_name_issubdomain(name, &zone->origin)) {
1748                 if (zone->checkns != NULL)
1749                         return ((zone->checkns)(zone, name, owner, NULL, NULL));
1750                 return (ISC_TRUE);
1751         }
1752
1753         if (zone->type == dns_zone_master)
1754                 level = ISC_LOG_ERROR;
1755         else
1756                 level = ISC_LOG_WARNING;
1757
1758         dns_fixedname_init(&fixed);
1759         foundname = dns_fixedname_name(&fixed);
1760         dns_rdataset_init(&a);
1761         dns_rdataset_init(&aaaa);
1762
1763         result = dns_db_find(db, name, NULL, dns_rdatatype_a,
1764                              DNS_DBFIND_GLUEOK, 0, NULL,
1765                              foundname, &a, NULL);
1766
1767         if (result == ISC_R_SUCCESS) {
1768                 dns_rdataset_disassociate(&a);
1769                 return (ISC_TRUE);
1770         } else if (result == DNS_R_DELEGATION)
1771                 dns_rdataset_disassociate(&a);
1772
1773         if (result == DNS_R_NXRRSET || result == DNS_R_DELEGATION ||
1774             result == DNS_R_GLUE) {
1775                 tresult = dns_db_find(db, name, NULL, dns_rdatatype_aaaa,
1776                                      DNS_DBFIND_GLUEOK, 0, NULL,
1777                                      foundname, &aaaa, NULL);
1778                 if (tresult == ISC_R_SUCCESS) {
1779                         dns_rdataset_disassociate(&aaaa);
1780                         return (ISC_TRUE);
1781                 }
1782                 if (tresult == DNS_R_DELEGATION)
1783                         dns_rdataset_disassociate(&aaaa);
1784                 if (result == DNS_R_GLUE || tresult == DNS_R_GLUE) {
1785                         /*
1786                          * Check glue against child zone.
1787                          */
1788                         if (zone->checkns != NULL)
1789                                 answer = (zone->checkns)(zone, name, owner,
1790                                                          &a, &aaaa);
1791                         if (dns_rdataset_isassociated(&a))
1792                                 dns_rdataset_disassociate(&a);
1793                         if (dns_rdataset_isassociated(&aaaa))
1794                                 dns_rdataset_disassociate(&aaaa);
1795                         return (answer);
1796                 }
1797         } else
1798                 tresult = result;
1799
1800         dns_name_format(owner, ownerbuf, sizeof ownerbuf);
1801         dns_name_format(name, namebuf, sizeof namebuf);
1802         if (result == DNS_R_NXRRSET || result == DNS_R_NXDOMAIN ||
1803             result == DNS_R_EMPTYNAME || result == DNS_R_DELEGATION) {
1804                 const char *what;
1805                 isc_boolean_t required = ISC_FALSE;
1806                 if (dns_name_issubdomain(name, owner)) {
1807                         what = "REQUIRED GLUE ";
1808                         required = ISC_TRUE;
1809                  } else if (result == DNS_R_DELEGATION)
1810                         what = "SIBLING GLUE ";
1811                 else
1812                         what = "";
1813
1814                 if (result != DNS_R_DELEGATION || required ||
1815                     DNS_ZONE_OPTION(zone, DNS_ZONEOPT_CHECKSIBLING)) {
1816                         dns_zone_log(zone, level, "%s/NS '%s' has no %s"
1817                                      "address records (A or AAAA)",
1818                                      ownerbuf, namebuf, what);
1819                         /*
1820                          * Log missing address record.
1821                          */
1822                         if (result == DNS_R_DELEGATION && zone->checkns != NULL)
1823                                 (void)(zone->checkns)(zone, name, owner,
1824                                                       &a, &aaaa);
1825                         /* XXX950 make fatal for 9.5.0. */
1826                         /* answer = ISC_FALSE; */
1827                 }
1828         } else if (result == DNS_R_CNAME) {
1829                 dns_zone_log(zone, level, "%s/NS '%s' is a CNAME (illegal)",
1830                              ownerbuf, namebuf);
1831                 /* XXX950 make fatal for 9.5.0. */
1832                 /* answer = ISC_FALSE; */
1833         } else if (result == DNS_R_DNAME) {
1834                 dns_name_format(foundname, altbuf, sizeof altbuf);
1835                 dns_zone_log(zone, level,
1836                              "%s/NS '%s' is below a DNAME '%s' (illegal)",
1837                              ownerbuf, namebuf, altbuf);
1838                 /* XXX950 make fatal for 9.5.0. */
1839                 /* answer = ISC_FALSE; */
1840         }
1841
1842         if (dns_rdataset_isassociated(&a))
1843                 dns_rdataset_disassociate(&a);
1844         if (dns_rdataset_isassociated(&aaaa))
1845                 dns_rdataset_disassociate(&aaaa);
1846         return (answer);
1847 }
1848
1849 static isc_boolean_t
1850 integrity_checks(dns_zone_t *zone, dns_db_t *db) {
1851         dns_dbiterator_t *dbiterator = NULL;
1852         dns_dbnode_t *node = NULL;
1853         dns_rdataset_t rdataset;
1854         dns_fixedname_t fixed;
1855         dns_fixedname_t fixedbottom;
1856         dns_rdata_mx_t mx;
1857         dns_rdata_ns_t ns;
1858         dns_rdata_in_srv_t srv;
1859         dns_rdata_t rdata;
1860         dns_name_t *name;
1861         dns_name_t *bottom;
1862         isc_result_t result;
1863         isc_boolean_t ok = ISC_TRUE;
1864
1865         dns_fixedname_init(&fixed);
1866         name = dns_fixedname_name(&fixed);
1867         dns_fixedname_init(&fixedbottom);
1868         bottom = dns_fixedname_name(&fixedbottom);
1869         dns_rdataset_init(&rdataset);
1870         dns_rdata_init(&rdata);
1871
1872         result = dns_db_createiterator(db, ISC_FALSE, &dbiterator);
1873         if (result != ISC_R_SUCCESS)
1874                 return (ISC_TRUE);
1875
1876         result = dns_dbiterator_first(dbiterator);
1877         while (result == ISC_R_SUCCESS) {
1878                 result = dns_dbiterator_current(dbiterator, &node, name);
1879                 if (result != ISC_R_SUCCESS)
1880                         goto cleanup;
1881
1882                 /*
1883                  * Is this name visible in the zone?
1884                  */
1885                 if (!dns_name_issubdomain(name, &zone->origin) ||
1886                     (dns_name_countlabels(bottom) > 0 &&
1887                      dns_name_issubdomain(name, bottom)))
1888                         goto next;
1889
1890                 /*
1891                  * Don't check the NS records at the origin.
1892                  */
1893                 if (dns_name_equal(name, &zone->origin))
1894                         goto checkmx;
1895
1896                 result = dns_db_findrdataset(db, node, NULL, dns_rdatatype_ns,
1897                                              0, 0, &rdataset, NULL);
1898                 if (result != ISC_R_SUCCESS)
1899                         goto checkmx;
1900                 /*
1901                  * Remember bottom of zone.
1902                  */
1903                 dns_name_copy(name, bottom, NULL);
1904
1905                 result = dns_rdataset_first(&rdataset);
1906                 while (result == ISC_R_SUCCESS) {
1907                         dns_rdataset_current(&rdataset, &rdata);
1908                         result = dns_rdata_tostruct(&rdata, &ns, NULL);
1909                         RUNTIME_CHECK(result == ISC_R_SUCCESS);
1910                         if (!zone_check_glue(zone, db, &ns.name, name))
1911                                 ok = ISC_FALSE;
1912                         dns_rdata_reset(&rdata);
1913                         result = dns_rdataset_next(&rdataset);
1914                 }
1915                 dns_rdataset_disassociate(&rdataset);
1916
1917  checkmx:
1918                 result = dns_db_findrdataset(db, node, NULL, dns_rdatatype_mx,
1919                                              0, 0, &rdataset, NULL);
1920                 if (result != ISC_R_SUCCESS)
1921                         goto checksrv;
1922                 result = dns_rdataset_first(&rdataset);
1923                 while (result == ISC_R_SUCCESS) {
1924                         dns_rdataset_current(&rdataset, &rdata);
1925                         result = dns_rdata_tostruct(&rdata, &mx, NULL);
1926                         RUNTIME_CHECK(result == ISC_R_SUCCESS);
1927                         if (!zone_check_mx(zone, db, &mx.mx, name))
1928                                 ok = ISC_FALSE;
1929                         dns_rdata_reset(&rdata);
1930                         result = dns_rdataset_next(&rdataset);
1931                 }
1932                 dns_rdataset_disassociate(&rdataset);
1933
1934  checksrv:
1935                 if (zone->rdclass != dns_rdataclass_in)
1936                         goto next;
1937                 result = dns_db_findrdataset(db, node, NULL, dns_rdatatype_srv,
1938                                              0, 0, &rdataset, NULL);
1939                 if (result != ISC_R_SUCCESS)
1940                         goto next;
1941                 result = dns_rdataset_first(&rdataset);
1942                 while (result == ISC_R_SUCCESS) {
1943                         dns_rdataset_current(&rdataset, &rdata);
1944                         result = dns_rdata_tostruct(&rdata, &srv, NULL);
1945                         RUNTIME_CHECK(result == ISC_R_SUCCESS);
1946                         if (!zone_check_srv(zone, db, &srv.target, name))
1947                                 ok = ISC_FALSE;
1948                         dns_rdata_reset(&rdata);
1949                         result = dns_rdataset_next(&rdataset);
1950                 }
1951                 dns_rdataset_disassociate(&rdataset);
1952
1953  next:
1954                 dns_db_detachnode(db, &node);
1955                 result = dns_dbiterator_next(dbiterator);
1956         }
1957
1958  cleanup:
1959         if (node != NULL)
1960                 dns_db_detachnode(db, &node);
1961         dns_dbiterator_destroy(&dbiterator);
1962
1963         return (ok);
1964 }
1965
1966 /*
1967  * OpenSSL verification of RSA keys with exponent 3 is known to be
1968  * broken prior OpenSSL 0.9.8c/0.9.7k.  Look for such keys and warn
1969  * if they are in use.
1970  */
1971 static void
1972 zone_check_dnskeys(dns_zone_t *zone, dns_db_t *db) {
1973         dns_dbnode_t *node = NULL;
1974         dns_dbversion_t *version = NULL;
1975         dns_rdata_dnskey_t dnskey;
1976         dns_rdata_t rdata = DNS_RDATA_INIT;
1977         dns_rdataset_t rdataset;
1978         isc_result_t result;
1979         isc_boolean_t logit, foundrsa = ISC_FALSE, foundmd5 = ISC_FALSE;
1980         const char *algorithm;
1981
1982         result = dns_db_findnode(db, &zone->origin, ISC_FALSE, &node);
1983         if (result != ISC_R_SUCCESS)
1984                 goto cleanup;
1985
1986         dns_db_currentversion(db, &version);
1987         dns_rdataset_init(&rdataset);
1988         result = dns_db_findrdataset(db, node, version, dns_rdatatype_dnskey,
1989                                      dns_rdatatype_none, 0, &rdataset, NULL);
1990         if (result != ISC_R_SUCCESS)
1991                 goto cleanup;
1992
1993         for (result = dns_rdataset_first(&rdataset);
1994              result == ISC_R_SUCCESS;
1995              result = dns_rdataset_next(&rdataset))
1996         {
1997                 dns_rdataset_current(&rdataset, &rdata);
1998                 result = dns_rdata_tostruct(&rdata, &dnskey, NULL);
1999                 INSIST(result == ISC_R_SUCCESS);
2000
2001                 if ((dnskey.algorithm == DST_ALG_RSASHA1 ||
2002                      dnskey.algorithm == DST_ALG_RSAMD5) &&
2003                      dnskey.datalen > 1 && dnskey.data[0] == 1 &&
2004                      dnskey.data[1] == 3)
2005                 {
2006                         if (dnskey.algorithm == DST_ALG_RSASHA1) {
2007                                 logit = !foundrsa;
2008                                 foundrsa = ISC_TRUE;
2009                                 algorithm = "RSASHA1";
2010                         } else {
2011                                 logit = !foundmd5;
2012                                 foundmd5 = ISC_TRUE;
2013                                 algorithm = "RSAMD5";
2014                         }
2015                         if (logit)
2016                                 dns_zone_log(zone, ISC_LOG_WARNING,
2017                                              "weak %s (%u) key found "
2018                                              "(exponent=3)", algorithm,
2019                                              dnskey.algorithm);
2020                         if (foundrsa && foundmd5)
2021                                 break;
2022                 }
2023                 dns_rdata_reset(&rdata);
2024         }
2025         dns_rdataset_disassociate(&rdataset);
2026
2027  cleanup:
2028         if (node != NULL)
2029                 dns_db_detachnode(db, &node);
2030         if (version != NULL)
2031                 dns_db_closeversion(db, &version, ISC_FALSE);
2032
2033 }
2034
2035 static isc_result_t
2036 zone_postload(dns_zone_t *zone, dns_db_t *db, isc_time_t loadtime,
2037               isc_result_t result)
2038 {
2039         unsigned int soacount = 0;
2040         unsigned int nscount = 0;
2041         unsigned int errors = 0;
2042         isc_uint32_t serial, refresh, retry, expire, minimum;
2043         isc_time_t now;
2044         isc_boolean_t needdump = ISC_FALSE;
2045         isc_boolean_t hasinclude = DNS_ZONE_FLAG(zone, DNS_ZONEFLG_HASINCLUDE);
2046
2047         TIME_NOW(&now);
2048
2049         /*
2050          * Initiate zone transfer?  We may need a error code that
2051          * indicates that the "permanent" form does not exist.
2052          * XXX better error feedback to log.
2053          */
2054         if (result != ISC_R_SUCCESS && result != DNS_R_SEENINCLUDE) {
2055                 if (zone->type == dns_zone_slave ||
2056                     zone->type == dns_zone_stub) {
2057                         if (result == ISC_R_FILENOTFOUND)
2058                                 dns_zone_log(zone, ISC_LOG_DEBUG(1),
2059                                              "no master file");
2060                         else if (result != DNS_R_NOMASTERFILE)
2061                                 dns_zone_log(zone, ISC_LOG_ERROR,
2062                                              "loading from master file %s "
2063                                              "failed: %s",
2064                                              zone->masterfile,
2065                                              dns_result_totext(result));
2066                 } else
2067                         dns_zone_log(zone, ISC_LOG_ERROR,
2068                                      "loading from master file %s failed: %s",
2069                                      zone->masterfile,
2070                                      dns_result_totext(result));
2071                 goto cleanup;
2072         }
2073
2074         dns_zone_log(zone, ISC_LOG_DEBUG(2),
2075                      "number of nodes in database: %u",
2076                      dns_db_nodecount(db));
2077
2078         if (result == DNS_R_SEENINCLUDE)
2079                 DNS_ZONE_SETFLAG(zone, DNS_ZONEFLG_HASINCLUDE);
2080         else
2081                 DNS_ZONE_CLRFLAG(zone, DNS_ZONEFLG_HASINCLUDE);
2082
2083         /*
2084          * Apply update log, if any, on initial load.
2085          */
2086         if (zone->journal != NULL &&
2087             ! DNS_ZONE_OPTION(zone, DNS_ZONEOPT_NOMERGE) &&
2088             ! DNS_ZONE_FLAG(zone, DNS_ZONEFLG_LOADED))
2089         {
2090                 result = dns_journal_rollforward(zone->mctx, db,
2091                                                  zone->journal);
2092                 if (result != ISC_R_SUCCESS && result != ISC_R_NOTFOUND &&
2093                     result != DNS_R_UPTODATE && result != DNS_R_NOJOURNAL &&
2094                     result != ISC_R_RANGE) {
2095                         dns_zone_log(zone, ISC_LOG_ERROR,
2096                                      "journal rollforward failed: %s",
2097                                      dns_result_totext(result));
2098                         goto cleanup;
2099                 }
2100                 if (result == ISC_R_NOTFOUND || result == ISC_R_RANGE) {
2101                         dns_zone_log(zone, ISC_LOG_ERROR,
2102                                      "journal rollforward failed: "
2103                                      "journal out of sync with zone");
2104                         goto cleanup;
2105                 }
2106                 dns_zone_log(zone, ISC_LOG_DEBUG(1),
2107                              "journal rollforward completed "
2108                              "successfully: %s",
2109                              dns_result_totext(result));
2110                 if (result == ISC_R_SUCCESS)
2111                         needdump = ISC_TRUE;
2112         }
2113
2114         zone->loadtime = loadtime;
2115
2116         dns_zone_log(zone, ISC_LOG_DEBUG(1), "loaded");
2117
2118         /*
2119          * Obtain ns, soa and cname counts for top of zone.
2120          */
2121         INSIST(db != NULL);
2122         result = zone_get_from_db(zone, db, &nscount, &soacount, &serial,
2123                                   &refresh, &retry, &expire, &minimum,
2124                                   &errors);
2125         if (result != ISC_R_SUCCESS) {
2126                 dns_zone_log(zone, ISC_LOG_ERROR,
2127                              "could not find NS and/or SOA records");
2128         }
2129
2130         /*
2131          * Master / Slave / Stub zones require both NS and SOA records at
2132          * the top of the zone.
2133          */
2134
2135         switch (zone->type) {
2136         case dns_zone_master:
2137         case dns_zone_slave:
2138         case dns_zone_stub:
2139                 if (soacount != 1) {
2140                         dns_zone_log(zone, ISC_LOG_ERROR,
2141                                      "has %d SOA records", soacount);
2142                         result = DNS_R_BADZONE;
2143                 }
2144                 if (nscount == 0) {
2145                         dns_zone_log(zone, ISC_LOG_ERROR,
2146                                      "has no NS records");
2147                         result = DNS_R_BADZONE;
2148                 }
2149                 if (result != ISC_R_SUCCESS)
2150                         goto cleanup;
2151                 if (zone->type == dns_zone_master && errors != 0) {
2152                         result = DNS_R_BADZONE;
2153                         goto cleanup;
2154                 }
2155                 if (zone->type == dns_zone_master &&
2156                     DNS_ZONE_OPTION(zone, DNS_ZONEOPT_CHECKINTEGRITY) &&
2157                     !integrity_checks(zone, db)) {
2158                         result = DNS_R_BADZONE;
2159                         goto cleanup;
2160                 }
2161
2162                 if (zone->db != NULL) {
2163                         /*
2164                          * This is checked in zone_replacedb() for slave zones
2165                          * as they don't reload from disk.
2166                          */
2167                         if (DNS_ZONE_OPTION(zone, DNS_ZONEOPT_IXFRFROMDIFFS) &&
2168                             !isc_serial_gt(serial, zone->serial)) {
2169                                 isc_uint32_t serialmin, serialmax;
2170
2171                                 INSIST(zone->type == dns_zone_master);
2172
2173                                 serialmin = (zone->serial + 1) & 0xffffffffU;
2174                                 serialmax = (zone->serial + 0x7fffffffU) &
2175                                              0xffffffffU;
2176                                 dns_zone_log(zone, ISC_LOG_ERROR,
2177                                              "ixfr-from-differences: "
2178                                              "new serial (%u) out of range "
2179                                              "[%u - %u]", serial, serialmin,
2180                                              serialmax);
2181                                 result = DNS_R_BADZONE;
2182                                 goto cleanup;
2183                         } else if (!isc_serial_ge(serial, zone->serial))
2184                                 dns_zone_log(zone, ISC_LOG_ERROR,
2185                                              "zone serial has gone backwards");
2186                         else if (serial == zone->serial && !hasinclude)
2187                                 dns_zone_log(zone, ISC_LOG_ERROR,
2188                                              "zone serial unchanged. "
2189                                              "zone may fail to transfer "
2190                                              "to slaves.");
2191                 }
2192                 zone->serial = serial;
2193                 zone->refresh = RANGE(refresh,
2194                                       zone->minrefresh, zone->maxrefresh);
2195                 zone->retry = RANGE(retry,
2196                                     zone->minretry, zone->maxretry);
2197                 zone->expire = RANGE(expire, zone->refresh + zone->retry,
2198                                      DNS_MAX_EXPIRE);
2199                 zone->minimum = minimum;
2200                 DNS_ZONE_SETFLAG(zone, DNS_ZONEFLG_HAVETIMERS);
2201
2202                 if (zone->type == dns_zone_slave ||
2203                     zone->type == dns_zone_stub) {
2204                         isc_time_t t;
2205                         isc_uint32_t delay;
2206
2207                         result = isc_file_getmodtime(zone->journal, &t);
2208                         if (result != ISC_R_SUCCESS)
2209                                 result = isc_file_getmodtime(zone->masterfile,
2210                                                              &t);
2211                         if (result == ISC_R_SUCCESS)
2212                                 DNS_ZONE_TIME_ADD(&t, zone->expire,
2213                                                   &zone->expiretime);
2214                         else
2215                                 DNS_ZONE_TIME_ADD(&now, zone->retry,
2216                                                   &zone->expiretime);
2217
2218                         delay = isc_random_jitter(zone->retry,
2219                                                   (zone->retry * 3) / 4);
2220                         DNS_ZONE_TIME_ADD(&now, delay, &zone->refreshtime);
2221                         if (isc_time_compare(&zone->refreshtime,
2222                                              &zone->expiretime) >= 0)
2223                                 zone->refreshtime = now;
2224                 }
2225                 break;
2226         default:
2227                 UNEXPECTED_ERROR(__FILE__, __LINE__,
2228                                  "unexpected zone type %d", zone->type);
2229                 result = ISC_R_UNEXPECTED;
2230                 goto cleanup;
2231         }
2232
2233         /*
2234          * Check for weak DNSKEY's.
2235          */
2236         if (zone->type == dns_zone_master)
2237                 zone_check_dnskeys(zone, db);
2238
2239 #if 0
2240         /* destroy notification example. */
2241         {
2242                 isc_event_t *e = isc_event_allocate(zone->mctx, NULL,
2243                                                     DNS_EVENT_DBDESTROYED,
2244                                                     dns_zonemgr_dbdestroyed,
2245                                                     zone,
2246                                                     sizeof(isc_event_t));
2247                 dns_db_ondestroy(db, zone->task, &e);
2248         }
2249 #endif
2250
2251         ZONEDB_LOCK(&zone->dblock, isc_rwlocktype_write);
2252         if (zone->db != NULL) {
2253                 result = zone_replacedb(zone, db, ISC_FALSE);
2254                 ZONEDB_UNLOCK(&zone->dblock, isc_rwlocktype_write);
2255                 if (result != ISC_R_SUCCESS)
2256                         goto cleanup;
2257         } else {
2258                 zone_attachdb(zone, db);
2259                 ZONEDB_UNLOCK(&zone->dblock, isc_rwlocktype_write);
2260                 DNS_ZONE_SETFLAG(zone,
2261                                  DNS_ZONEFLG_LOADED|DNS_ZONEFLG_NEEDNOTIFY);
2262         }
2263         result = ISC_R_SUCCESS;
2264         if (needdump)
2265                 zone_needdump(zone, DNS_DUMP_DELAY);
2266         if (zone->task != NULL)
2267                 zone_settimer(zone, &now);
2268
2269         if (! dns_db_ispersistent(db))
2270                 dns_zone_log(zone, ISC_LOG_INFO, "loaded serial %u%s",
2271                              zone->serial,
2272                              dns_db_issecure(db) ? " (signed)" : "");
2273
2274         return (result);
2275
2276  cleanup:
2277         if (zone->type == dns_zone_slave ||
2278             zone->type == dns_zone_stub) {
2279                 if (zone->journal != NULL)
2280                         zone_saveunique(zone, zone->journal, "jn-XXXXXXXX");
2281                 if (zone->masterfile != NULL)
2282                         zone_saveunique(zone, zone->masterfile, "db-XXXXXXXX");
2283
2284                 /* Mark the zone for immediate refresh. */
2285                 zone->refreshtime = now;
2286                 if (zone->task != NULL)
2287                         zone_settimer(zone, &now);
2288                 result = ISC_R_SUCCESS;
2289         }
2290         return (result);
2291 }
2292
2293 static isc_boolean_t
2294 exit_check(dns_zone_t *zone) {
2295
2296         REQUIRE(LOCKED_ZONE(zone));
2297
2298         if (DNS_ZONE_FLAG(zone, DNS_ZONEFLG_SHUTDOWN) &&
2299             zone->irefs == 0)
2300         {
2301                 /*
2302                  * DNS_ZONEFLG_SHUTDOWN can only be set if erefs == 0.
2303                  */
2304                 INSIST(isc_refcount_current(&zone->erefs) == 0);
2305                 return (ISC_TRUE);
2306         }
2307         return (ISC_FALSE);
2308 }
2309
2310 static isc_boolean_t
2311 zone_check_ns(dns_zone_t *zone, dns_db_t *db, dns_name_t *name) {
2312         isc_result_t result;
2313         char namebuf[DNS_NAME_FORMATSIZE];
2314         char altbuf[DNS_NAME_FORMATSIZE];
2315         dns_fixedname_t fixed;
2316         dns_name_t *foundname;
2317         int level;
2318
2319         if (DNS_ZONE_OPTION(zone, DNS_ZONEOPT_NOCHECKNS))
2320                 return (ISC_TRUE);
2321
2322         if (zone->type == dns_zone_master)
2323                 level = ISC_LOG_ERROR;
2324         else
2325                 level = ISC_LOG_WARNING;
2326
2327         dns_fixedname_init(&fixed);
2328         foundname = dns_fixedname_name(&fixed);
2329
2330         result = dns_db_find(db, name, NULL, dns_rdatatype_a,
2331                              0, 0, NULL, foundname, NULL, NULL);
2332         if (result == ISC_R_SUCCESS)
2333                 return (ISC_TRUE);
2334
2335         if (result == DNS_R_NXRRSET) {
2336                 result = dns_db_find(db, name, NULL, dns_rdatatype_aaaa,
2337                                      0, 0, NULL, foundname, NULL, NULL);
2338                 if (result == ISC_R_SUCCESS)
2339                         return (ISC_TRUE);
2340         }
2341
2342         dns_name_format(name, namebuf, sizeof namebuf);
2343         if (result == DNS_R_NXRRSET || result == DNS_R_NXDOMAIN ||
2344             result == DNS_R_EMPTYNAME) {
2345                 dns_zone_log(zone, level,
2346                              "NS '%s' has no address records (A or AAAA)",
2347                              namebuf);
2348                 /* XXX950 Make fatal ISC_FALSE for 9.5.0. */
2349                 return (ISC_TRUE);
2350         }
2351
2352         if (result == DNS_R_CNAME) {
2353                 dns_zone_log(zone, level, "NS '%s' is a CNAME (illegal)",
2354                              namebuf);
2355                 /* XXX950 Make fatal ISC_FALSE for 9.5.0. */
2356                 return (ISC_TRUE);
2357         }
2358
2359         if (result == DNS_R_DNAME) {
2360                 dns_name_format(foundname, altbuf, sizeof altbuf);
2361                 dns_zone_log(zone, level,
2362                              "NS '%s' is below a DNAME '%s' (illegal)",
2363                              namebuf, altbuf);
2364                 /* XXX950 Make fatal ISC_FALSE for 9.5.0. */
2365                 return (ISC_TRUE);
2366         }
2367
2368         return (ISC_TRUE);
2369 }
2370
2371 static isc_result_t
2372 zone_count_ns_rr(dns_zone_t *zone, dns_db_t *db, dns_dbnode_t *node,
2373                  dns_dbversion_t *version, unsigned int *nscount,
2374                  unsigned int *errors)
2375 {
2376         isc_result_t result;
2377         unsigned int count = 0;
2378         unsigned int ecount = 0;
2379         dns_rdataset_t rdataset;
2380         dns_rdata_t rdata;
2381         dns_rdata_ns_t ns;
2382
2383         dns_rdataset_init(&rdataset);
2384         result = dns_db_findrdataset(db, node, version, dns_rdatatype_ns,
2385                                      dns_rdatatype_none, 0, &rdataset, NULL);
2386         if (result == ISC_R_NOTFOUND)
2387                 goto success;
2388         if (result != ISC_R_SUCCESS)
2389                 goto invalidate_rdataset;
2390
2391         result = dns_rdataset_first(&rdataset);
2392         while (result == ISC_R_SUCCESS) {
2393                 if (errors != NULL && zone->rdclass == dns_rdataclass_in &&
2394                     (zone->type == dns_zone_master ||
2395                      zone->type == dns_zone_slave)) {
2396                         dns_rdata_init(&rdata);
2397                         dns_rdataset_current(&rdataset, &rdata);
2398                         result = dns_rdata_tostruct(&rdata, &ns, NULL);
2399                         RUNTIME_CHECK(result == ISC_R_SUCCESS);
2400                         if (dns_name_issubdomain(&ns.name, &zone->origin) &&
2401                             !zone_check_ns(zone, db, &ns.name))
2402                                 ecount++;
2403                 }
2404                 count++;
2405                 result = dns_rdataset_next(&rdataset);
2406         }
2407         dns_rdataset_disassociate(&rdataset);
2408
2409  success:
2410         if (nscount != NULL)
2411                 *nscount = count;
2412         if (errors != NULL)
2413                 *errors = ecount;
2414
2415         result = ISC_R_SUCCESS;
2416
2417  invalidate_rdataset:
2418         dns_rdataset_invalidate(&rdataset);
2419
2420         return (result);
2421 }
2422
2423 static isc_result_t
2424 zone_load_soa_rr(dns_db_t *db, dns_dbnode_t *node, dns_dbversion_t *version,
2425                  unsigned int *soacount,
2426                  isc_uint32_t *serial, isc_uint32_t *refresh,
2427                  isc_uint32_t *retry, isc_uint32_t *expire,
2428                  isc_uint32_t *minimum)
2429 {
2430         isc_result_t result;
2431         unsigned int count;
2432         dns_rdataset_t rdataset;
2433         dns_rdata_t rdata = DNS_RDATA_INIT;
2434         dns_rdata_soa_t soa;
2435
2436         dns_rdataset_init(&rdataset);
2437         result = dns_db_findrdataset(db, node, version, dns_rdatatype_soa,
2438                                      dns_rdatatype_none, 0, &rdataset, NULL);
2439         if (result == ISC_R_NOTFOUND) {
2440                 if (soacount != NULL)
2441                         *soacount = 0;
2442                 if (serial != NULL)
2443                         *serial = 0;
2444                 if (refresh != NULL)
2445                         *refresh = 0;
2446                 if (retry != NULL)
2447                         *retry = 0;
2448                 if (expire != NULL)
2449                         *expire = 0;
2450                 if (minimum != NULL)
2451                         *minimum = 0;
2452                 result = ISC_R_SUCCESS;
2453                 goto invalidate_rdataset;
2454         }
2455         if (result != ISC_R_SUCCESS)
2456                 goto invalidate_rdataset;
2457
2458         count = 0;
2459         result = dns_rdataset_first(&rdataset);
2460         while (result == ISC_R_SUCCESS) {
2461                 dns_rdata_init(&rdata);
2462                 dns_rdataset_current(&rdataset, &rdata);
2463                 count++;
2464                 if (count == 1) {
2465                         result = dns_rdata_tostruct(&rdata, &soa, NULL);
2466                         RUNTIME_CHECK(result == ISC_R_SUCCESS);
2467                 }
2468
2469                 result = dns_rdataset_next(&rdataset);
2470                 dns_rdata_reset(&rdata);
2471         }
2472         dns_rdataset_disassociate(&rdataset);
2473
2474         if (soacount != NULL)
2475                 *soacount = count;
2476
2477         if (count > 0) {
2478                 if (serial != NULL)
2479                         *serial = soa.serial;
2480                 if (refresh != NULL)
2481                         *refresh = soa.refresh;
2482                 if (retry != NULL)
2483                         *retry = soa.retry;
2484                 if (expire != NULL)
2485                         *expire = soa.expire;
2486                 if (minimum != NULL)
2487                         *minimum = soa.minimum;
2488         }
2489
2490         result = ISC_R_SUCCESS;
2491
2492  invalidate_rdataset:
2493         dns_rdataset_invalidate(&rdataset);
2494
2495         return (result);
2496 }
2497
2498 /*
2499  * zone must be locked.
2500  */
2501 static isc_result_t
2502 zone_get_from_db(dns_zone_t *zone, dns_db_t *db, unsigned int *nscount,
2503                  unsigned int *soacount, isc_uint32_t *serial,
2504                  isc_uint32_t *refresh, isc_uint32_t *retry,
2505                  isc_uint32_t *expire, isc_uint32_t *minimum,
2506                  unsigned int *errors)
2507 {
2508         dns_dbversion_t *version;
2509         isc_result_t result;
2510         isc_result_t answer = ISC_R_SUCCESS;
2511         dns_dbnode_t *node;
2512
2513         REQUIRE(db != NULL);
2514         REQUIRE(zone != NULL);
2515
2516         version = NULL;
2517         dns_db_currentversion(db, &version);
2518
2519         node = NULL;
2520         result = dns_db_findnode(db, &zone->origin, ISC_FALSE, &node);
2521         if (result != ISC_R_SUCCESS) {
2522                 answer = result;
2523                 goto closeversion;
2524         }
2525
2526         if (nscount != NULL || errors != NULL) {
2527                 result = zone_count_ns_rr(zone, db, node, version,
2528                                           nscount, errors);
2529                 if (result != ISC_R_SUCCESS)
2530                         answer = result;
2531         }
2532
2533         if (soacount != NULL || serial != NULL || refresh != NULL
2534             || retry != NULL || expire != NULL || minimum != NULL) {
2535                 result = zone_load_soa_rr(db, node, version, soacount,
2536                                           serial, refresh, retry, expire,
2537                                           minimum);
2538                 if (result != ISC_R_SUCCESS)
2539                         answer = result;
2540         }
2541
2542         dns_db_detachnode(db, &node);
2543  closeversion:
2544         dns_db_closeversion(db, &version, ISC_FALSE);
2545
2546         return (answer);
2547 }
2548
2549 void
2550 dns_zone_attach(dns_zone_t *source, dns_zone_t **target) {
2551         REQUIRE(DNS_ZONE_VALID(source));
2552         REQUIRE(target != NULL && *target == NULL);
2553         isc_refcount_increment(&source->erefs, NULL);
2554         *target = source;
2555 }
2556
2557 void
2558 dns_zone_detach(dns_zone_t **zonep) {
2559         dns_zone_t *zone;
2560         unsigned int refs;
2561         isc_boolean_t free_now = ISC_FALSE;
2562
2563         REQUIRE(zonep != NULL && DNS_ZONE_VALID(*zonep));
2564
2565         zone = *zonep;
2566
2567         isc_refcount_decrement(&zone->erefs, &refs);
2568
2569         if (refs == 0) {
2570                 LOCK_ZONE(zone);
2571                 /*
2572                  * We just detached the last external reference.
2573                  */
2574                 if (zone->task != NULL) {
2575                         /*
2576                          * This zone is being managed.  Post
2577                          * its control event and let it clean
2578                          * up synchronously in the context of
2579                          * its task.
2580                          */
2581                         isc_event_t *ev = &zone->ctlevent;
2582                         isc_task_send(zone->task, &ev);
2583                 } else {
2584                         /*
2585                          * This zone is not being managed; it has
2586                          * no task and can have no outstanding
2587                          * events.  Free it immediately.
2588                          */
2589                         /*
2590                          * Unmanaged zones should not have non-null views;
2591                          * we have no way of detaching from the view here
2592                          * without causing deadlock because this code is called
2593                          * with the view already locked.
2594                          */
2595                         INSIST(zone->view == NULL);
2596                         free_now = ISC_TRUE;
2597                 }
2598                 UNLOCK_ZONE(zone);
2599         }
2600         *zonep = NULL;
2601         if (free_now)
2602                 zone_free(zone);
2603 }
2604
2605 void
2606 dns_zone_iattach(dns_zone_t *source, dns_zone_t **target) {
2607         REQUIRE(DNS_ZONE_VALID(source));
2608         REQUIRE(target != NULL && *target == NULL);
2609         LOCK_ZONE(source);
2610         zone_iattach(source, target);
2611         UNLOCK_ZONE(source);
2612 }
2613
2614 static void
2615 zone_iattach(dns_zone_t *source, dns_zone_t **target) {
2616
2617         /*
2618          * 'source' locked by caller.
2619          */
2620         REQUIRE(LOCKED_ZONE(source));
2621         REQUIRE(DNS_ZONE_VALID(source));
2622         REQUIRE(target != NULL && *target == NULL);
2623         INSIST(source->irefs + isc_refcount_current(&source->erefs) > 0);
2624         source->irefs++;
2625         INSIST(source->irefs != 0);
2626         *target = source;
2627 }
2628
2629 static void
2630 zone_idetach(dns_zone_t **zonep) {
2631         dns_zone_t *zone;
2632
2633         /*
2634          * 'zone' locked by caller.
2635          */
2636         REQUIRE(zonep != NULL && DNS_ZONE_VALID(*zonep));
2637         zone = *zonep;
2638         REQUIRE(LOCKED_ZONE(*zonep));
2639         *zonep = NULL;
2640
2641         INSIST(zone->irefs > 0);
2642         zone->irefs--;
2643         INSIST(zone->irefs + isc_refcount_current(&zone->erefs) > 0);
2644 }
2645
2646 void
2647 dns_zone_idetach(dns_zone_t **zonep) {
2648         dns_zone_t *zone;
2649         isc_boolean_t free_needed;
2650
2651         REQUIRE(zonep != NULL && DNS_ZONE_VALID(*zonep));
2652         zone = *zonep;
2653         *zonep = NULL;
2654
2655         LOCK_ZONE(zone);
2656         INSIST(zone->irefs > 0);
2657         zone->irefs--;
2658         free_needed = exit_check(zone);
2659         UNLOCK_ZONE(zone);
2660         if (free_needed)
2661                 zone_free(zone);
2662 }
2663
2664 isc_mem_t *
2665 dns_zone_getmctx(dns_zone_t *zone) {
2666         REQUIRE(DNS_ZONE_VALID(zone));
2667
2668         return (zone->mctx);
2669 }
2670
2671 dns_zonemgr_t *
2672 dns_zone_getmgr(dns_zone_t *zone) {
2673         REQUIRE(DNS_ZONE_VALID(zone));
2674
2675         return (zone->zmgr);
2676 }
2677
2678 void
2679 dns_zone_setflag(dns_zone_t *zone, unsigned int flags, isc_boolean_t value) {
2680         REQUIRE(DNS_ZONE_VALID(zone));
2681
2682         LOCK_ZONE(zone);
2683         if (value)
2684                 DNS_ZONE_SETFLAG(zone, flags);
2685         else
2686                 DNS_ZONE_CLRFLAG(zone, flags);
2687         UNLOCK_ZONE(zone);
2688 }
2689
2690 void
2691 dns_zone_setoption(dns_zone_t *zone, unsigned int option, isc_boolean_t value)
2692 {
2693         REQUIRE(DNS_ZONE_VALID(zone));
2694
2695         LOCK_ZONE(zone);
2696         if (value)
2697                 zone->options |= option;
2698         else
2699                 zone->options &= ~option;
2700         UNLOCK_ZONE(zone);
2701 }
2702
2703 unsigned int
2704 dns_zone_getoptions(dns_zone_t *zone) {
2705
2706         REQUIRE(DNS_ZONE_VALID(zone));
2707
2708         return (zone->options);
2709 }
2710
2711 isc_result_t
2712 dns_zone_setxfrsource4(dns_zone_t *zone, const isc_sockaddr_t *xfrsource) {
2713         REQUIRE(DNS_ZONE_VALID(zone));
2714
2715         LOCK_ZONE(zone);
2716         zone->xfrsource4 = *xfrsource;
2717         UNLOCK_ZONE(zone);
2718
2719         return (ISC_R_SUCCESS);
2720 }
2721
2722 isc_sockaddr_t *
2723 dns_zone_getxfrsource4(dns_zone_t *zone) {
2724         REQUIRE(DNS_ZONE_VALID(zone));
2725         return (&zone->xfrsource4);
2726 }
2727
2728 isc_result_t
2729 dns_zone_setxfrsource6(dns_zone_t *zone, const isc_sockaddr_t *xfrsource) {
2730         REQUIRE(DNS_ZONE_VALID(zone));
2731
2732         LOCK_ZONE(zone);
2733         zone->xfrsource6 = *xfrsource;
2734         UNLOCK_ZONE(zone);
2735
2736         return (ISC_R_SUCCESS);
2737 }
2738
2739 isc_sockaddr_t *
2740 dns_zone_getxfrsource6(dns_zone_t *zone) {
2741         REQUIRE(DNS_ZONE_VALID(zone));
2742         return (&zone->xfrsource6);
2743 }
2744
2745 isc_result_t
2746 dns_zone_setaltxfrsource4(dns_zone_t *zone,
2747                           const isc_sockaddr_t *altxfrsource)
2748 {
2749         REQUIRE(DNS_ZONE_VALID(zone));
2750
2751         LOCK_ZONE(zone);
2752         zone->altxfrsource4 = *altxfrsource;
2753         UNLOCK_ZONE(zone);
2754
2755         return (ISC_R_SUCCESS);
2756 }
2757
2758 isc_sockaddr_t *
2759 dns_zone_getaltxfrsource4(dns_zone_t *zone) {
2760         REQUIRE(DNS_ZONE_VALID(zone));
2761         return (&zone->altxfrsource4);
2762 }
2763
2764 isc_result_t
2765 dns_zone_setaltxfrsource6(dns_zone_t *zone,
2766                           const isc_sockaddr_t *altxfrsource)
2767 {
2768         REQUIRE(DNS_ZONE_VALID(zone));
2769
2770         LOCK_ZONE(zone);
2771         zone->altxfrsource6 = *altxfrsource;
2772         UNLOCK_ZONE(zone);
2773
2774         return (ISC_R_SUCCESS);
2775 }
2776
2777 isc_sockaddr_t *
2778 dns_zone_getaltxfrsource6(dns_zone_t *zone) {
2779         REQUIRE(DNS_ZONE_VALID(zone));
2780         return (&zone->altxfrsource6);
2781 }
2782
2783 isc_result_t
2784 dns_zone_setnotifysrc4(dns_zone_t *zone, const isc_sockaddr_t *notifysrc) {
2785         REQUIRE(DNS_ZONE_VALID(zone));
2786
2787         LOCK_ZONE(zone);
2788         zone->notifysrc4 = *notifysrc;
2789         UNLOCK_ZONE(zone);
2790
2791         return (ISC_R_SUCCESS);
2792 }
2793
2794 isc_sockaddr_t *
2795 dns_zone_getnotifysrc4(dns_zone_t *zone) {
2796         REQUIRE(DNS_ZONE_VALID(zone));
2797         return (&zone->notifysrc4);
2798 }
2799
2800 isc_result_t
2801 dns_zone_setnotifysrc6(dns_zone_t *zone, const isc_sockaddr_t *notifysrc) {
2802         REQUIRE(DNS_ZONE_VALID(zone));
2803
2804         LOCK_ZONE(zone);
2805         zone->notifysrc6 = *notifysrc;
2806         UNLOCK_ZONE(zone);
2807
2808         return (ISC_R_SUCCESS);
2809 }
2810
2811 isc_sockaddr_t *
2812 dns_zone_getnotifysrc6(dns_zone_t *zone) {
2813         REQUIRE(DNS_ZONE_VALID(zone));
2814         return (&zone->notifysrc6);
2815 }
2816
2817 isc_result_t
2818 dns_zone_setalsonotify(dns_zone_t *zone, const isc_sockaddr_t *notify,
2819                        isc_uint32_t count)
2820 {
2821         isc_sockaddr_t *new;
2822
2823         REQUIRE(DNS_ZONE_VALID(zone));
2824         REQUIRE(count == 0 || notify != NULL);
2825
2826         LOCK_ZONE(zone);
2827         if (zone->notify != NULL) {
2828                 isc_mem_put(zone->mctx, zone->notify,
2829                             zone->notifycnt * sizeof(*new));
2830                 zone->notify = NULL;
2831                 zone->notifycnt = 0;
2832         }
2833         if (count != 0) {
2834                 new = isc_mem_get(zone->mctx, count * sizeof(*new));
2835                 if (new == NULL) {
2836                         UNLOCK_ZONE(zone);
2837                         return (ISC_R_NOMEMORY);
2838                 }
2839                 memcpy(new, notify, count * sizeof(*new));
2840                 zone->notify = new;
2841                 zone->notifycnt = count;
2842         }
2843         UNLOCK_ZONE(zone);
2844         return (ISC_R_SUCCESS);
2845 }
2846
2847 isc_result_t
2848 dns_zone_setmasters(dns_zone_t *zone, const isc_sockaddr_t *masters,
2849                     isc_uint32_t count)
2850 {
2851         isc_result_t result;
2852
2853         result = dns_zone_setmasterswithkeys(zone, masters, NULL, count);
2854         return (result);
2855 }
2856
2857 static isc_boolean_t
2858 same_masters(const isc_sockaddr_t *old, const isc_sockaddr_t *new,
2859              isc_uint32_t count)
2860 {
2861         unsigned int i;
2862
2863         for (i = 0; i < count; i++)
2864                 if (!isc_sockaddr_equal(&old[i], &new[i]))
2865                         return (ISC_FALSE);
2866         return (ISC_TRUE);
2867 }
2868
2869 static isc_boolean_t
2870 same_keynames(dns_name_t **old, dns_name_t **new, isc_uint32_t count) {
2871         unsigned int i;
2872
2873         if (old == NULL && new == NULL)
2874                 return (ISC_TRUE);
2875         if (old == NULL || new == NULL)
2876                 return (ISC_FALSE);
2877
2878         for (i = 0; i < count; i++) {
2879                 if (old[i] == NULL && new[i] == NULL)
2880                         continue;
2881                 if (old[i] == NULL || new[i] == NULL ||
2882                      !dns_name_equal(old[i], new[i]))
2883                         return (ISC_FALSE);
2884         }
2885         return (ISC_TRUE);
2886 }
2887
2888 isc_result_t
2889 dns_zone_setmasterswithkeys(dns_zone_t *zone,
2890                             const isc_sockaddr_t *masters,
2891                             dns_name_t **keynames,
2892                             isc_uint32_t count)
2893 {
2894         isc_sockaddr_t *new;
2895         isc_result_t result = ISC_R_SUCCESS;
2896         dns_name_t **newname;
2897         isc_boolean_t *newok;
2898         unsigned int i;
2899
2900         REQUIRE(DNS_ZONE_VALID(zone));
2901         REQUIRE(count == 0 || masters != NULL);
2902         if (keynames != NULL) {
2903                 REQUIRE(count != 0);
2904         }
2905
2906         LOCK_ZONE(zone);
2907         /*
2908          * The refresh code assumes that 'masters' wouldn't change under it.
2909          * If it will change then kill off any current refresh in progress
2910          * and update the masters info.  If it won't change then we can just
2911          * unlock and exit.
2912          */
2913         if (count != zone->masterscnt ||
2914             !same_masters(zone->masters, masters, count) ||
2915             !same_keynames(zone->masterkeynames, keynames, count)) {
2916                 if (zone->request != NULL)
2917                         dns_request_cancel(zone->request);
2918         } else
2919                 goto unlock;
2920         if (zone->masters != NULL) {
2921                 isc_mem_put(zone->mctx, zone->masters,
2922                             zone->masterscnt * sizeof(*new));
2923                 zone->masters = NULL;
2924         }
2925         if (zone->masterkeynames != NULL) {
2926                 for (i = 0; i < zone->masterscnt; i++) {
2927                         if (zone->masterkeynames[i] != NULL) {
2928                                 dns_name_free(zone->masterkeynames[i],
2929                                               zone->mctx);
2930                                 isc_mem_put(zone->mctx,
2931                                             zone->masterkeynames[i],
2932                                             sizeof(dns_name_t));
2933                                 zone->masterkeynames[i] = NULL;
2934                         }
2935                 }
2936                 isc_mem_put(zone->mctx, zone->masterkeynames,
2937                             zone->masterscnt * sizeof(dns_name_t *));
2938                 zone->masterkeynames = NULL;
2939         }
2940         if (zone->mastersok != NULL) {
2941                 isc_mem_put(zone->mctx, zone->mastersok,
2942                             zone->masterscnt * sizeof(isc_boolean_t));
2943                 zone->mastersok = NULL;
2944         }
2945         zone->masterscnt = 0;
2946         /*
2947          * If count == 0, don't allocate any space for masters, mastersok or
2948          * keynames so internally, those pointers are NULL if count == 0
2949          */
2950         if (count == 0)
2951                 goto unlock;
2952
2953         /*
2954          * masters must contain count elements!
2955          */
2956         new = isc_mem_get(zone->mctx, count * sizeof(*new));
2957         if (new == NULL) {
2958                 result = ISC_R_NOMEMORY;
2959                 goto unlock;
2960         }
2961         memcpy(new, masters, count * sizeof(*new));
2962
2963         /*
2964          * Similarly for mastersok.
2965          */
2966         newok = isc_mem_get(zone->mctx, count * sizeof(*newok));
2967         if (newok == NULL) {
2968                 result = ISC_R_NOMEMORY;
2969                 isc_mem_put(zone->mctx, new, count * sizeof(*new));
2970                 goto unlock;
2971         };
2972         for (i = 0; i < count; i++)
2973                 newok[i] = ISC_FALSE;
2974
2975         /*
2976          * if keynames is non-NULL, it must contain count elements!
2977          */
2978         newname = NULL;
2979         if (keynames != NULL) {
2980                 newname = isc_mem_get(zone->mctx, count * sizeof(*newname));
2981                 if (newname == NULL) {
2982                         result = ISC_R_NOMEMORY;
2983                         isc_mem_put(zone->mctx, new, count * sizeof(*new));
2984                         isc_mem_put(zone->mctx, newok, count * sizeof(*newok));
2985                         goto unlock;
2986                 }
2987                 for (i = 0; i < count; i++)
2988                         newname[i] = NULL;
2989                 for (i = 0; i < count; i++) {
2990                         if (keynames[i] != NULL) {
2991                                 newname[i] = isc_mem_get(zone->mctx,
2992                                                          sizeof(dns_name_t));
2993                                 if (newname[i] == NULL)
2994                                         goto allocfail;
2995                                 dns_name_init(newname[i], NULL);
2996                                 result = dns_name_dup(keynames[i], zone->mctx,
2997                                                       newname[i]);
2998                                 if (result != ISC_R_SUCCESS) {
2999                                 allocfail:
3000                                         for (i = 0; i < count; i++)
3001                                                 if (newname[i] != NULL)
3002                                                         dns_name_free(
3003                                                                newname[i],
3004                                                                zone->mctx);
3005                                         isc_mem_put(zone->mctx, new,
3006                                                     count * sizeof(*new));
3007                                         isc_mem_put(zone->mctx, newok,
3008                                                     count * sizeof(*newok));
3009                                         isc_mem_put(zone->mctx, newname,
3010                                                     count * sizeof(*newname));
3011                                         goto unlock;
3012                                 }
3013                         }
3014                 }
3015         }
3016
3017         /*
3018          * Everything is ok so attach to the zone.
3019          */
3020         zone->masters = new;
3021         zone->mastersok = newok;
3022         zone->masterkeynames = newname;
3023         zone->masterscnt = count;
3024         DNS_ZONE_CLRFLAG(zone, DNS_ZONEFLG_NOMASTERS);
3025
3026  unlock:
3027         UNLOCK_ZONE(zone);
3028         return (result);
3029 }
3030
3031 isc_result_t
3032 dns_zone_getdb(dns_zone_t *zone, dns_db_t **dpb) {
3033         isc_result_t result = ISC_R_SUCCESS;
3034
3035         REQUIRE(DNS_ZONE_VALID(zone));
3036
3037         ZONEDB_LOCK(&zone->dblock, isc_rwlocktype_read);
3038         if (zone->db == NULL)
3039                 result = DNS_R_NOTLOADED;
3040         else
3041                 dns_db_attach(zone->db, dpb);
3042         ZONEDB_UNLOCK(&zone->dblock, isc_rwlocktype_read);
3043
3044         return (result);
3045 }
3046
3047 /*
3048  * Co-ordinates the starting of routine jobs.
3049  */
3050
3051 void
3052 dns_zone_maintenance(dns_zone_t *zone) {
3053         const char me[] = "dns_zone_maintenance";
3054         isc_time_t now;
3055
3056         REQUIRE(DNS_ZONE_VALID(zone));
3057         ENTER;
3058
3059         LOCK_ZONE(zone);
3060         TIME_NOW(&now);
3061         zone_settimer(zone, &now);
3062         UNLOCK_ZONE(zone);
3063 }
3064
3065 static inline isc_boolean_t
3066 was_dumping(dns_zone_t *zone) {
3067         isc_boolean_t dumping;
3068
3069         REQUIRE(LOCKED_ZONE(zone));
3070
3071         dumping = DNS_ZONE_FLAG(zone, DNS_ZONEFLG_DUMPING);
3072         DNS_ZONE_SETFLAG(zone, DNS_ZONEFLG_DUMPING);
3073         if (!dumping) {
3074                 DNS_ZONE_CLRFLAG(zone, DNS_ZONEFLG_NEEDDUMP);
3075                 isc_time_settoepoch(&zone->dumptime);
3076         }
3077         return (dumping);
3078 }
3079
3080 static void
3081 zone_maintenance(dns_zone_t *zone) {
3082         const char me[] = "zone_maintenance";
3083         isc_time_t now;
3084         isc_result_t result;
3085         isc_boolean_t dumping;
3086
3087         REQUIRE(DNS_ZONE_VALID(zone));
3088         ENTER;
3089
3090         /*
3091          * Configuring the view of this zone may have
3092          * failed, for example because the config file
3093          * had a syntax error.  In that case, the view
3094          * adb or resolver, and we had better not try
3095          * to do maintenance on it.
3096          */
3097         if (zone->view == NULL || zone->view->adb == NULL)
3098                 return;
3099
3100         TIME_NOW(&now);
3101
3102         /*
3103          * Expire check.
3104          */
3105         switch (zone->type) {
3106         case dns_zone_slave:
3107         case dns_zone_stub:
3108                 LOCK_ZONE(zone);
3109                 if (isc_time_compare(&now, &zone->expiretime) >= 0 &&
3110                     DNS_ZONE_FLAG(zone, DNS_ZONEFLG_LOADED)) {
3111                         zone_expire(zone);
3112                         zone->refreshtime = now;
3113                 }
3114                 UNLOCK_ZONE(zone);
3115                 break;
3116         default:
3117                 break;
3118         }
3119
3120         /*
3121          * Up to date check.
3122          */
3123         switch (zone->type) {
3124         case dns_zone_slave:
3125         case dns_zone_stub:
3126                 if (!DNS_ZONE_FLAG(zone, DNS_ZONEFLG_DIALREFRESH) &&
3127                     isc_time_compare(&now, &zone->refreshtime) >= 0)
3128                         dns_zone_refresh(zone);
3129                 break;
3130         default:
3131                 break;
3132         }
3133
3134         /*
3135          * Do we need to consolidate the backing store?
3136          */
3137         switch (zone->type) {
3138         case dns_zone_master:
3139         case dns_zone_slave:
3140                 LOCK_ZONE(zone);
3141                 if (zone->masterfile != NULL &&
3142                     isc_time_compare(&now, &zone->dumptime) >= 0 &&
3143                     DNS_ZONE_FLAG(zone, DNS_ZONEFLG_LOADED) &&
3144                     DNS_ZONE_FLAG(zone, DNS_ZONEFLG_NEEDDUMP)) {
3145                         dumping = was_dumping(zone);
3146                 } else
3147                         dumping = ISC_TRUE;
3148                 UNLOCK_ZONE(zone);
3149                 if (!dumping) {
3150                         result = zone_dump(zone, ISC_TRUE); /* task locked */
3151                         if (result != ISC_R_SUCCESS)
3152                                 dns_zone_log(zone, ISC_LOG_WARNING,
3153                                              "dump failed: %s",
3154                                              dns_result_totext(result));
3155                 }
3156                 break;
3157         default:
3158                 break;
3159         }
3160
3161         /*
3162          * Do we need to send out notify messages?
3163          */
3164         switch (zone->type) {
3165         case dns_zone_master:
3166         case dns_zone_slave:
3167                 if (DNS_ZONE_FLAG(zone, DNS_ZONEFLG_NEEDNOTIFY) &&
3168                     isc_time_compare(&now, &zone->notifytime) >= 0)
3169                         zone_notify(zone, &now);
3170                 break;
3171         default:
3172                 break;
3173         }
3174         zone_settimer(zone, &now);
3175 }
3176
3177 void
3178 dns_zone_markdirty(dns_zone_t *zone) {
3179
3180         LOCK_ZONE(zone);
3181         zone_needdump(zone, DNS_DUMP_DELAY);
3182         UNLOCK_ZONE(zone);
3183 }
3184
3185 void
3186 dns_zone_expire(dns_zone_t *zone) {
3187         REQUIRE(DNS_ZONE_VALID(zone));
3188
3189         LOCK_ZONE(zone);
3190         zone_expire(zone);
3191         UNLOCK_ZONE(zone);
3192 }
3193
3194 static void
3195 zone_expire(dns_zone_t *zone) {
3196         /*
3197          * 'zone' locked by caller.
3198          */
3199
3200         REQUIRE(LOCKED_ZONE(zone));
3201
3202         dns_zone_log(zone, ISC_LOG_WARNING, "expired");
3203
3204         DNS_ZONE_SETFLAG(zone, DNS_ZONEFLG_EXPIRED);
3205         zone->refresh = DNS_ZONE_DEFAULTREFRESH;
3206         zone->retry = DNS_ZONE_DEFAULTRETRY;
3207         DNS_ZONE_CLRFLAG(zone, DNS_ZONEFLG_HAVETIMERS);
3208         zone_unload(zone);
3209 }
3210
3211 void
3212 dns_zone_refresh(dns_zone_t *zone) {
3213         isc_interval_t i;
3214         isc_uint32_t oldflags;
3215         unsigned int j;
3216         isc_result_t result;
3217
3218         REQUIRE(DNS_ZONE_VALID(zone));
3219
3220         if (DNS_ZONE_FLAG(zone, DNS_ZONEFLG_EXITING))
3221                 return;
3222
3223         /*
3224          * Set DNS_ZONEFLG_REFRESH so that there is only one refresh operation
3225          * in progress at a time.
3226          */
3227
3228         LOCK_ZONE(zone);
3229         oldflags = zone->flags;
3230         if (zone->masterscnt == 0) {
3231                 DNS_ZONE_SETFLAG(zone, DNS_ZONEFLG_NOMASTERS);
3232                 if ((oldflags & DNS_ZONEFLG_NOMASTERS) == 0)
3233                         dns_zone_log(zone, ISC_LOG_ERROR,
3234                                      "cannot refresh: no masters");
3235                 goto unlock;
3236         }
3237         DNS_ZONE_SETFLAG(zone, DNS_ZONEFLG_REFRESH);
3238         DNS_ZONE_CLRFLAG(zone, DNS_ZONEFLG_NOEDNS);
3239         DNS_ZONE_CLRFLAG(zone, DNS_ZONEFLG_USEALTXFRSRC);
3240         if ((oldflags & (DNS_ZONEFLG_REFRESH|DNS_ZONEFLG_LOADING)) != 0)
3241                 goto unlock;
3242
3243         /*
3244          * Set the next refresh time as if refresh check has failed.
3245          * Setting this to the retry time will do that.  XXXMLG
3246          * If we are successful it will be reset using zone->refresh.
3247          */
3248         isc_interval_set(&i, isc_random_jitter(zone->retry, zone->retry / 4),
3249                          0);
3250         result = isc_time_nowplusinterval(&zone->refreshtime, &i);
3251         if (result |= ISC_R_SUCCESS)
3252                 dns_zone_log(zone, ISC_LOG_WARNING,
3253                              "isc_time_nowplusinterval() failed: %s",
3254                              dns_result_totext(result));
3255
3256         /*
3257          * When lacking user-specified timer values from the SOA,
3258          * do exponential backoff of the retry time up to a
3259          * maximum of six hours.
3260          */
3261         if (! DNS_ZONE_FLAG(zone, DNS_ZONEFLG_HAVETIMERS))
3262                 zone->retry = ISC_MIN(zone->retry * 2, 6 * 3600);
3263
3264         zone->curmaster = 0;
3265         for (j = 0; j < zone->masterscnt; j++)
3266                 zone->mastersok[j] = ISC_FALSE;
3267         /* initiate soa query */
3268         queue_soa_query(zone);
3269  unlock:
3270         UNLOCK_ZONE(zone);
3271 }
3272
3273 isc_result_t
3274 dns_zone_flush(dns_zone_t *zone) {
3275         isc_result_t result = ISC_R_SUCCESS;
3276         isc_boolean_t dumping;
3277
3278         REQUIRE(DNS_ZONE_VALID(zone));
3279
3280         LOCK_ZONE(zone);
3281         DNS_ZONE_SETFLAG(zone, DNS_ZONEFLG_FLUSH);
3282         if (DNS_ZONE_FLAG(zone, DNS_ZONEFLG_NEEDDUMP) &&
3283             zone->masterfile != NULL) {
3284                 result = ISC_R_ALREADYRUNNING;
3285                 dumping = was_dumping(zone);
3286         } else
3287                 dumping = ISC_TRUE;
3288         UNLOCK_ZONE(zone);
3289         if (!dumping)
3290                 result = zone_dump(zone, ISC_FALSE);    /* Unknown task. */
3291         return (result);
3292 }
3293
3294 isc_result_t
3295 dns_zone_dump(dns_zone_t *zone) {
3296         isc_result_t result = ISC_R_ALREADYRUNNING;
3297         isc_boolean_t dumping;
3298
3299         REQUIRE(DNS_ZONE_VALID(zone));
3300
3301         LOCK_ZONE(zone);
3302         dumping = was_dumping(zone);
3303         UNLOCK_ZONE(zone);
3304         if (!dumping)
3305                 result = zone_dump(zone, ISC_FALSE);    /* Unknown task. */
3306         return (result);
3307 }
3308
3309 static void
3310 zone_needdump(dns_zone_t *zone, unsigned int delay) {
3311         isc_time_t dumptime;
3312         isc_time_t now;
3313
3314         /*
3315          * 'zone' locked by caller
3316          */
3317
3318         REQUIRE(DNS_ZONE_VALID(zone));
3319         REQUIRE(LOCKED_ZONE(zone));
3320
3321         /*
3322          * Do we have a place to dump to and are we loaded?
3323          */
3324         if (zone->masterfile == NULL ||
3325             DNS_ZONE_FLAG(zone, DNS_ZONEFLG_LOADED) == 0)
3326                 return;
3327
3328         TIME_NOW(&now);
3329         /* add some noise */
3330         DNS_ZONE_JITTER_ADD(&now, delay, &dumptime);
3331
3332         DNS_ZONE_SETFLAG(zone, DNS_ZONEFLG_NEEDDUMP);
3333         if (isc_time_isepoch(&zone->dumptime) ||
3334             isc_time_compare(&zone->dumptime, &dumptime) > 0)
3335                 zone->dumptime = dumptime;
3336         if (zone->task != NULL)
3337                 zone_settimer(zone, &now);
3338 }
3339
3340 static void
3341 dump_done(void *arg, isc_result_t result) {
3342         const char me[] = "dump_done";
3343         dns_zone_t *zone = arg;
3344         dns_db_t *db;
3345         dns_dbversion_t *version;
3346         isc_boolean_t again = ISC_FALSE;
3347         isc_boolean_t compact = ISC_FALSE;
3348         isc_uint32_t serial;
3349         isc_result_t tresult;
3350
3351         REQUIRE(DNS_ZONE_VALID(zone));
3352
3353         ENTER;
3354
3355         if (result == ISC_R_SUCCESS && zone->journal != NULL &&
3356             zone->journalsize != -1) {
3357
3358                 /*
3359                  * We don't own these, zone->dctx must stay valid.
3360                  */
3361                 db = dns_dumpctx_db(zone->dctx);
3362                 version = dns_dumpctx_version(zone->dctx);
3363
3364                 tresult = dns_db_getsoaserial(db, version, &serial);
3365                 /*
3366                  * Note: we are task locked here so we can test
3367                  * zone->xfr safely.
3368                  */
3369                 if (tresult == ISC_R_SUCCESS && zone->xfr == NULL) {
3370                         tresult = dns_journal_compact(zone->mctx,
3371                                                       zone->journal,
3372                                                       serial,
3373                                                       zone->journalsize);
3374                         switch (tresult) {
3375                         case ISC_R_SUCCESS:
3376                         case ISC_R_NOSPACE:
3377                         case ISC_R_NOTFOUND:
3378                                 dns_zone_log(zone, ISC_LOG_DEBUG(3),
3379                                              "dns_journal_compact: %s",
3380                                              dns_result_totext(tresult));
3381                                 break;
3382                         default:
3383                                 dns_zone_log(zone, ISC_LOG_ERROR,
3384                                              "dns_journal_compact failed: %s",
3385                                              dns_result_totext(tresult));
3386                                 break;
3387                         }
3388                 } else if (tresult == ISC_R_SUCCESS) {
3389                         compact = ISC_TRUE;
3390                         zone->compact_serial = serial;
3391                 }
3392         }
3393
3394         LOCK_ZONE(zone);
3395         DNS_ZONE_CLRFLAG(zone, DNS_ZONEFLG_DUMPING);
3396         if (compact)
3397                 DNS_ZONE_SETFLAG(zone, DNS_ZONEFLG_NEEDCOMPACT);
3398         if (result != ISC_R_SUCCESS && result != ISC_R_CANCELED) {
3399                 /*
3400                  * Try again in a short while.
3401                  */
3402                 zone_needdump(zone, DNS_DUMP_DELAY);
3403         } else if (result == ISC_R_SUCCESS &&
3404                    DNS_ZONE_FLAG(zone, DNS_ZONEFLG_FLUSH) &&
3405                    DNS_ZONE_FLAG(zone, DNS_ZONEFLG_NEEDDUMP) &&
3406                    DNS_ZONE_FLAG(zone, DNS_ZONEFLG_LOADED)) {
3407                 DNS_ZONE_CLRFLAG(zone, DNS_ZONEFLG_NEEDDUMP);
3408                 DNS_ZONE_SETFLAG(zone, DNS_ZONEFLG_DUMPING);
3409                 isc_time_settoepoch(&zone->dumptime);
3410                 again = ISC_TRUE;
3411         } else if (result == ISC_R_SUCCESS)
3412                 DNS_ZONE_CLRFLAG(zone, DNS_ZONEFLG_FLUSH);
3413
3414         if (zone->dctx != NULL)
3415                 dns_dumpctx_detach(&zone->dctx);
3416         zonemgr_putio(&zone->writeio);
3417         UNLOCK_ZONE(zone);
3418         if (again)
3419                 (void)zone_dump(zone, ISC_FALSE);
3420         dns_zone_idetach(&zone);
3421 }
3422
3423 static isc_result_t
3424 zone_dump(dns_zone_t *zone, isc_boolean_t compact) {
3425         const char me[] = "zone_dump";
3426         isc_result_t result;
3427         dns_dbversion_t *version = NULL;
3428         isc_boolean_t again;
3429         dns_db_t *db = NULL;
3430         char *masterfile = NULL;
3431         dns_masterformat_t masterformat = dns_masterformat_none;
3432
3433 /*
3434  * 'compact' MUST only be set if we are task locked.
3435  */
3436
3437         REQUIRE(DNS_ZONE_VALID(zone));
3438         ENTER;
3439
3440  redo:
3441         ZONEDB_LOCK(&zone->dblock, isc_rwlocktype_read);
3442         if (zone->db != NULL)
3443                 dns_db_attach(zone->db, &db);
3444         ZONEDB_UNLOCK(&zone->dblock, isc_rwlocktype_read);
3445         LOCK_ZONE(zone);
3446         if (zone->masterfile != NULL) {
3447                 masterfile = isc_mem_strdup(zone->mctx, zone->masterfile);
3448                 masterformat = zone->masterformat;
3449         }
3450         UNLOCK_ZONE(zone);
3451         if (db == NULL) {
3452                 result = DNS_R_NOTLOADED;
3453                 goto fail;
3454         }
3455         if (masterfile == NULL) {
3456                 result = DNS_R_NOMASTERFILE;
3457                 goto fail;
3458         }
3459
3460         if (compact) {
3461                 dns_zone_t *dummy = NULL;
3462                 LOCK_ZONE(zone);
3463                 zone_iattach(zone, &dummy);
3464                 result = zonemgr_getio(zone->zmgr, ISC_FALSE, zone->task,
3465                                        zone_gotwritehandle, zone,
3466                                        &zone->writeio);
3467                 if (result != ISC_R_SUCCESS)
3468                         zone_idetach(&dummy);
3469                 else
3470                         result = DNS_R_CONTINUE;
3471                 UNLOCK_ZONE(zone);
3472         } else {
3473                 dns_db_currentversion(db, &version);
3474                 result = dns_master_dump2(zone->mctx, db, version,
3475                                           &dns_master_style_default,
3476                                           masterfile, masterformat);
3477                 dns_db_closeversion(db, &version, ISC_FALSE);
3478         }
3479  fail:
3480         if (db != NULL)
3481                 dns_db_detach(&db);
3482         if (masterfile != NULL)
3483                 isc_mem_free(zone->mctx, masterfile);
3484         masterfile = NULL;
3485
3486         if (result == DNS_R_CONTINUE)
3487                 return (ISC_R_SUCCESS); /* XXXMPA */
3488
3489         again = ISC_FALSE;
3490         LOCK_ZONE(zone);
3491         DNS_ZONE_CLRFLAG(zone, DNS_ZONEFLG_DUMPING);
3492         if (result != ISC_R_SUCCESS) {
3493                 /*
3494                  * Try again in a short while.
3495                  */
3496                 zone_needdump(zone, DNS_DUMP_DELAY);
3497         } else if (DNS_ZONE_FLAG(zone, DNS_ZONEFLG_FLUSH) &&
3498                    DNS_ZONE_FLAG(zone, DNS_ZONEFLG_NEEDDUMP) &&
3499                    DNS_ZONE_FLAG(zone, DNS_ZONEFLG_LOADED)) {
3500                 DNS_ZONE_CLRFLAG(zone, DNS_ZONEFLG_NEEDDUMP);
3501                 DNS_ZONE_SETFLAG(zone, DNS_ZONEFLG_DUMPING);
3502                 isc_time_settoepoch(&zone->dumptime);
3503                 again = ISC_TRUE;
3504         } else
3505                 DNS_ZONE_CLRFLAG(zone, DNS_ZONEFLG_FLUSH);
3506         UNLOCK_ZONE(zone);
3507         if (again)
3508                 goto redo;
3509
3510         return (result);
3511 }
3512
3513 static isc_result_t
3514 dumptostream(dns_zone_t *zone, FILE *fd, const dns_master_style_t *style,
3515              dns_masterformat_t format)
3516 {
3517         isc_result_t result;
3518         dns_dbversion_t *version = NULL;
3519         dns_db_t *db = NULL;
3520
3521         REQUIRE(DNS_ZONE_VALID(zone));
3522
3523         ZONEDB_LOCK(&zone->dblock, isc_rwlocktype_read);
3524         if (zone->db != NULL)
3525                 dns_db_attach(zone->db, &db);
3526         ZONEDB_UNLOCK(&zone->dblock, isc_rwlocktype_read);
3527         if (db == NULL)
3528                 return (DNS_R_NOTLOADED);
3529
3530         dns_db_currentversion(db, &version);
3531         result = dns_master_dumptostream2(zone->mctx, db, version, style,
3532                                           format, fd);
3533         dns_db_closeversion(db, &version, ISC_FALSE);
3534         dns_db_detach(&db);
3535         return (result);
3536 }
3537
3538 isc_result_t
3539 dns_zone_dumptostream2(dns_zone_t *zone, FILE *fd, dns_masterformat_t format,
3540                        const dns_master_style_t *style) {
3541         return dumptostream(zone, fd, style, format);
3542 }
3543
3544 isc_result_t
3545 dns_zone_dumptostream(dns_zone_t *zone, FILE *fd) {
3546         return dumptostream(zone, fd, &dns_master_style_default,
3547                             dns_masterformat_text);
3548 }
3549
3550 isc_result_t
3551 dns_zone_fulldumptostream(dns_zone_t *zone, FILE *fd) {
3552         return dumptostream(zone, fd, &dns_master_style_full,
3553                             dns_masterformat_text);
3554 }
3555
3556 void
3557 dns_zone_unload(dns_zone_t *zone) {
3558         REQUIRE(DNS_ZONE_VALID(zone));
3559
3560         LOCK_ZONE(zone);
3561         zone_unload(zone);
3562         UNLOCK_ZONE(zone);
3563 }
3564
3565 static void
3566 notify_cancel(dns_zone_t *zone) {
3567         dns_notify_t *notify;
3568
3569         /*
3570          * 'zone' locked by caller.
3571          */
3572
3573         REQUIRE(LOCKED_ZONE(zone));
3574
3575         for (notify = ISC_LIST_HEAD(zone->notifies);
3576              notify != NULL;
3577              notify = ISC_LIST_NEXT(notify, link)) {
3578                 if (notify->find != NULL)
3579                         dns_adb_cancelfind(notify->find);
3580                 if (notify->request != NULL)
3581                         dns_request_cancel(notify->request);
3582         }
3583 }
3584
3585 static void
3586 zone_unload(dns_zone_t *zone) {
3587
3588         /*
3589          * 'zone' locked by caller.
3590          */
3591
3592         REQUIRE(LOCKED_ZONE(zone));
3593
3594         ZONEDB_LOCK(&zone->dblock, isc_rwlocktype_write);
3595         zone_detachdb(zone);
3596         ZONEDB_UNLOCK(&zone->dblock, isc_rwlocktype_write);
3597         DNS_ZONE_CLRFLAG(zone, DNS_ZONEFLG_LOADED);
3598         DNS_ZONE_CLRFLAG(zone, DNS_ZONEFLG_NEEDDUMP);
3599 }
3600
3601 void
3602 dns_zone_setminrefreshtime(dns_zone_t *zone, isc_uint32_t val) {
3603         REQUIRE(DNS_ZONE_VALID(zone));
3604         REQUIRE(val > 0);
3605
3606         zone->minrefresh = val;
3607 }
3608
3609 void
3610 dns_zone_setmaxrefreshtime(dns_zone_t *zone, isc_uint32_t val) {
3611         REQUIRE(DNS_ZONE_VALID(zone));
3612         REQUIRE(val > 0);
3613
3614         zone->maxrefresh = val;
3615 }
3616
3617 void
3618 dns_zone_setminretrytime(dns_zone_t *zone, isc_uint32_t val) {
3619         REQUIRE(DNS_ZONE_VALID(zone));
3620         REQUIRE(val > 0);
3621
3622         zone->minretry = val;
3623 }
3624
3625 void
3626 dns_zone_setmaxretrytime(dns_zone_t *zone, isc_uint32_t val) {
3627         REQUIRE(DNS_ZONE_VALID(zone));
3628         REQUIRE(val > 0);
3629
3630         zone->maxretry = val;
3631 }
3632
3633 static isc_boolean_t
3634 notify_isqueued(dns_zone_t *zone, dns_name_t *name, isc_sockaddr_t *addr) {
3635         dns_notify_t *notify;
3636
3637         for (notify = ISC_LIST_HEAD(zone->notifies);
3638              notify != NULL;
3639              notify = ISC_LIST_NEXT(notify, link)) {
3640                 if (notify->request != NULL)
3641                         continue;
3642                 if (name != NULL && dns_name_dynamic(&notify->ns) &&
3643                     dns_name_equal(name, &notify->ns))
3644                         return (ISC_TRUE);
3645                 if (addr != NULL && isc_sockaddr_equal(addr, &notify->dst))
3646                         return (ISC_TRUE);
3647         }
3648         return (ISC_FALSE);
3649 }
3650
3651 static isc_boolean_t
3652 notify_isself(dns_zone_t *zone, isc_sockaddr_t *dst) {
3653         dns_tsigkey_t *key = NULL;
3654         isc_sockaddr_t src;
3655         isc_sockaddr_t any;
3656         isc_boolean_t isself;
3657         isc_netaddr_t dstaddr;
3658
3659         if (zone->view == NULL || zone->isself == NULL)
3660                 return (ISC_FALSE);
3661
3662         switch (isc_sockaddr_pf(dst)) {
3663         case PF_INET:
3664                 src = zone->notifysrc4;
3665                 isc_sockaddr_any(&any);
3666                 break;
3667         case PF_INET6:
3668                 src = zone->notifysrc6;
3669                 isc_sockaddr_any6(&any);
3670                 break;
3671         default:
3672                 return (ISC_FALSE);
3673         }
3674
3675         /*
3676          * When sending from any the kernel will assign a source address
3677          * that matches the destination address.
3678          */
3679         if (isc_sockaddr_eqaddr(&any, &src))
3680                 src = *dst;
3681
3682         isc_netaddr_fromsockaddr(&dstaddr, dst);
3683         (void)dns_view_getpeertsig(zone->view, &dstaddr, &key);
3684         isself = (zone->isself)(zone->view, key, &src, dst, zone->rdclass,
3685                                 zone->isselfarg);
3686         if (key != NULL)
3687                 dns_tsigkey_detach(&key);
3688         return (isself);
3689 }
3690
3691 static void
3692 notify_destroy(dns_notify_t *notify, isc_boolean_t locked) {
3693         isc_mem_t *mctx;
3694
3695         /*
3696          * Caller holds zone lock.
3697          */
3698         REQUIRE(DNS_NOTIFY_VALID(notify));
3699
3700         if (notify->zone != NULL) {
3701                 if (!locked)
3702                         LOCK_ZONE(notify->zone);
3703                 REQUIRE(LOCKED_ZONE(notify->zone));
3704                 if (ISC_LINK_LINKED(notify, link))
3705                         ISC_LIST_UNLINK(notify->zone->notifies, notify, link);
3706                 if (!locked)
3707                         UNLOCK_ZONE(notify->zone);
3708                 if (locked)
3709                         zone_idetach(&notify->zone);
3710                 else
3711                         dns_zone_idetach(&notify->zone);
3712         }
3713         if (notify->find != NULL)
3714                 dns_adb_destroyfind(&notify->find);
3715         if (notify->request != NULL)
3716                 dns_request_destroy(&notify->request);
3717         if (dns_name_dynamic(&notify->ns))
3718                 dns_name_free(&notify->ns, notify->mctx);
3719         mctx = notify->mctx;
3720         isc_mem_put(notify->mctx, notify, sizeof(*notify));
3721         isc_mem_detach(&mctx);
3722 }
3723
3724 static isc_result_t
3725 notify_create(isc_mem_t *mctx, unsigned int flags, dns_notify_t **notifyp) {
3726         dns_notify_t *notify;
3727