]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/bind9/lib/dns/adb.c
add -n option to suppress clearing the build tree and add -DNO_CLEAN
[FreeBSD/FreeBSD.git] / contrib / bind9 / lib / dns / adb.c
1 /*
2  * Copyright (C) 2004-2007  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: adb.c,v 1.215.18.17 2007/09/11 02:23:26 marka Exp $ */
19
20 /*! \file 
21  *
22  * \note
23  * In finds, if task == NULL, no events will be generated, and no events
24  * have been sent.  If task != NULL but taskaction == NULL, an event has been
25  * posted but not yet freed.  If neither are NULL, no event was posted.
26  *
27  */
28
29 /*%
30  * After we have cleaned all buckets, dump the database contents.
31  */
32 #if 0
33 #define DUMP_ADB_AFTER_CLEANING
34 #endif
35
36 #include <config.h>
37
38 #include <limits.h>
39
40 #include <isc/mutexblock.h>
41 #include <isc/netaddr.h>
42 #include <isc/random.h>
43 #include <isc/string.h>         /* Required for HP/UX (and others?) */
44 #include <isc/task.h>
45 #include <isc/timer.h>
46 #include <isc/util.h>
47
48 #include <dns/adb.h>
49 #include <dns/db.h>
50 #include <dns/events.h>
51 #include <dns/log.h>
52 #include <dns/rdata.h>
53 #include <dns/rdataset.h>
54 #include <dns/rdatastruct.h>
55 #include <dns/rdatatype.h>
56 #include <dns/resolver.h>
57 #include <dns/result.h>
58
59 #define DNS_ADB_MAGIC             ISC_MAGIC('D', 'a', 'd', 'b')
60 #define DNS_ADB_VALID(x)          ISC_MAGIC_VALID(x, DNS_ADB_MAGIC)
61 #define DNS_ADBNAME_MAGIC         ISC_MAGIC('a', 'd', 'b', 'N')
62 #define DNS_ADBNAME_VALID(x)      ISC_MAGIC_VALID(x, DNS_ADBNAME_MAGIC)
63 #define DNS_ADBNAMEHOOK_MAGIC     ISC_MAGIC('a', 'd', 'N', 'H')
64 #define DNS_ADBNAMEHOOK_VALID(x)  ISC_MAGIC_VALID(x, DNS_ADBNAMEHOOK_MAGIC)
65 #define DNS_ADBLAMEINFO_MAGIC     ISC_MAGIC('a', 'd', 'b', 'Z')
66 #define DNS_ADBLAMEINFO_VALID(x)  ISC_MAGIC_VALID(x, DNS_ADBLAMEINFO_MAGIC)
67 #define DNS_ADBENTRY_MAGIC        ISC_MAGIC('a', 'd', 'b', 'E')
68 #define DNS_ADBENTRY_VALID(x)     ISC_MAGIC_VALID(x, DNS_ADBENTRY_MAGIC)
69 #define DNS_ADBFETCH_MAGIC        ISC_MAGIC('a', 'd', 'F', '4')
70 #define DNS_ADBFETCH_VALID(x)     ISC_MAGIC_VALID(x, DNS_ADBFETCH_MAGIC)
71 #define DNS_ADBFETCH6_MAGIC       ISC_MAGIC('a', 'd', 'F', '6')
72 #define DNS_ADBFETCH6_VALID(x)    ISC_MAGIC_VALID(x, DNS_ADBFETCH6_MAGIC)
73
74 /*! 
75  * The number of buckets needs to be a prime (for good hashing).
76  *
77  * XXXRTH  How many buckets do we need?
78  */
79 #define NBUCKETS               1009     /*%< how many buckets for names/addrs */
80
81 /*!
82  * For type 3 negative cache entries, we will remember that the address is
83  * broken for this long.  XXXMLG This is also used for actual addresses, too.
84  * The intent is to keep us from constantly asking about A/AAAA records
85  * if the zone has extremely low TTLs.
86  */
87 #define ADB_CACHE_MINIMUM       10      /*%< seconds */
88 #define ADB_CACHE_MAXIMUM       86400   /*%< seconds (86400 = 24 hours) */
89 #define ADB_ENTRY_WINDOW        1800    /*%< seconds */
90
91 /*%
92  * Wake up every CLEAN_SECONDS and clean CLEAN_BUCKETS buckets, so that all
93  * buckets are cleaned in CLEAN_PERIOD seconds.
94  */
95 #define CLEAN_PERIOD            3600
96 /*% See #CLEAN_PERIOD */
97 #define CLEAN_SECONDS           30
98 /*% See #CLEAN_PERIOD */
99 #define CLEAN_BUCKETS           ((NBUCKETS * CLEAN_SECONDS) / CLEAN_PERIOD)
100
101 #define FREE_ITEMS              64      /*%< free count for memory pools */
102 #define FILL_COUNT              16      /*%< fill count for memory pools */
103
104 #define DNS_ADB_INVALIDBUCKET (-1)      /*%< invalid bucket address */
105
106 #define DNS_ADB_MINADBSIZE      (1024*1024)     /*%< 1 Megabyte */
107
108 typedef ISC_LIST(dns_adbname_t) dns_adbnamelist_t;
109 typedef struct dns_adbnamehook dns_adbnamehook_t;
110 typedef ISC_LIST(dns_adbnamehook_t) dns_adbnamehooklist_t;
111 typedef struct dns_adblameinfo dns_adblameinfo_t;
112 typedef ISC_LIST(dns_adbentry_t) dns_adbentrylist_t;
113 typedef struct dns_adbfetch dns_adbfetch_t;
114 typedef struct dns_adbfetch6 dns_adbfetch6_t;
115
116 /*% dns adb structure */
117 struct dns_adb {
118         unsigned int                    magic;
119
120         isc_mutex_t                     lock;
121         isc_mutex_t                     reflock; /*%< Covers irefcnt, erefcnt */
122         isc_mem_t                      *mctx;
123         dns_view_t                     *view;
124         isc_timermgr_t                 *timermgr;
125         isc_timer_t                    *timer;
126         isc_taskmgr_t                  *taskmgr;
127         isc_task_t                     *task;
128         isc_boolean_t                   overmem;
129
130         isc_interval_t                  tick_interval;
131         int                             next_cleanbucket;
132
133         unsigned int                    irefcnt;
134         unsigned int                    erefcnt;
135
136         isc_mutex_t                     mplock;
137         isc_mempool_t                  *nmp;    /*%< dns_adbname_t */
138         isc_mempool_t                  *nhmp;   /*%< dns_adbnamehook_t */
139         isc_mempool_t                  *limp;   /*%< dns_adblameinfo_t */
140         isc_mempool_t                  *emp;    /*%< dns_adbentry_t */
141         isc_mempool_t                  *ahmp;   /*%< dns_adbfind_t */
142         isc_mempool_t                  *aimp;   /*%< dns_adbaddrinfo_t */
143         isc_mempool_t                  *afmp;   /*%< dns_adbfetch_t */
144
145         /*!
146          * Bucketized locks and lists for names.
147          *
148          * XXXRTH  Have a per-bucket structure that contains all of these?
149          */
150         dns_adbnamelist_t               names[NBUCKETS];
151         /*% See dns_adbnamelist_t */
152         isc_mutex_t                     namelocks[NBUCKETS];
153         /*% See dns_adbnamelist_t */
154         isc_boolean_t                   name_sd[NBUCKETS];
155         /*% See dns_adbnamelist_t */
156         unsigned int                    name_refcnt[NBUCKETS];
157
158         /*!
159          * Bucketized locks for entries.
160          *
161          * XXXRTH  Have a per-bucket structure that contains all of these?
162          */
163         dns_adbentrylist_t              entries[NBUCKETS];
164         isc_mutex_t                     entrylocks[NBUCKETS];
165         isc_boolean_t                   entry_sd[NBUCKETS]; /*%< shutting down */
166         unsigned int                    entry_refcnt[NBUCKETS];
167
168         isc_event_t                     cevent;
169         isc_boolean_t                   cevent_sent;
170         isc_boolean_t                   shutting_down;
171         isc_eventlist_t                 whenshutdown;
172 };
173
174 /*
175  * XXXMLG  Document these structures.
176  */
177
178 /*% dns_adbname structure */
179 struct dns_adbname {
180         unsigned int                    magic;
181         dns_name_t                      name;
182         dns_adb_t                      *adb;
183         unsigned int                    partial_result;
184         unsigned int                    flags;
185         int                             lock_bucket;
186         dns_name_t                      target;
187         isc_stdtime_t                   expire_target;
188         isc_stdtime_t                   expire_v4;
189         isc_stdtime_t                   expire_v6;
190         unsigned int                    chains;
191         dns_adbnamehooklist_t           v4;
192         dns_adbnamehooklist_t           v6;
193         dns_adbfetch_t                 *fetch_a;
194         dns_adbfetch_t                 *fetch_aaaa;
195         unsigned int                    fetch_err;
196         unsigned int                    fetch6_err;
197         dns_adbfindlist_t               finds;
198         ISC_LINK(dns_adbname_t)         plink;
199 };
200
201 /*% The adbfetch structure */
202 struct dns_adbfetch {
203         unsigned int                    magic;
204         dns_adbnamehook_t              *namehook;
205         dns_adbentry_t                 *entry;
206         dns_fetch_t                    *fetch;
207         dns_rdataset_t                  rdataset;
208 };
209
210 /*%
211  * This is a small widget that dangles off a dns_adbname_t.  It contains a
212  * pointer to the address information about this host, and a link to the next
213  * namehook that will contain the next address this host has.
214  */
215 struct dns_adbnamehook {
216         unsigned int                    magic;
217         dns_adbentry_t                 *entry;
218         ISC_LINK(dns_adbnamehook_t)     plink;
219 };
220
221 /*%
222  * This is a small widget that holds qname-specific information about an
223  * address.  Currently limited to lameness, but could just as easily be
224  * extended to other types of information about zones.
225  */
226 struct dns_adblameinfo {
227         unsigned int                    magic;
228
229         dns_name_t                      qname;
230         dns_rdatatype_t                 qtype;
231         isc_stdtime_t                   lame_timer;
232
233         ISC_LINK(dns_adblameinfo_t)     plink;
234 };
235
236 /*%
237  * An address entry.  It holds quite a bit of information about addresses,
238  * including edns state (in "flags"), rtt, and of course the address of
239  * the host.
240  */
241 struct dns_adbentry {
242         unsigned int                    magic;
243
244         int                             lock_bucket;
245         unsigned int                    refcnt;
246
247         unsigned int                    flags;
248         unsigned int                    srtt;
249         isc_sockaddr_t                  sockaddr;
250
251         isc_stdtime_t                   expires;
252         /*%<
253          * A nonzero 'expires' field indicates that the entry should
254          * persist until that time.  This allows entries found
255          * using dns_adb_findaddrinfo() to persist for a limited time
256          * even though they are not necessarily associated with a
257          * name.
258          */
259
260         ISC_LIST(dns_adblameinfo_t)     lameinfo;
261         ISC_LINK(dns_adbentry_t)        plink;
262 };
263
264 /*
265  * Internal functions (and prototypes).
266  */
267 static inline dns_adbname_t *new_adbname(dns_adb_t *, dns_name_t *);
268 static inline void free_adbname(dns_adb_t *, dns_adbname_t **);
269 static inline dns_adbnamehook_t *new_adbnamehook(dns_adb_t *,
270                                                  dns_adbentry_t *);
271 static inline void free_adbnamehook(dns_adb_t *, dns_adbnamehook_t **);
272 static inline dns_adblameinfo_t *new_adblameinfo(dns_adb_t *, dns_name_t *,
273                                                  dns_rdatatype_t);
274 static inline void free_adblameinfo(dns_adb_t *, dns_adblameinfo_t **);
275 static inline dns_adbentry_t *new_adbentry(dns_adb_t *);
276 static inline void free_adbentry(dns_adb_t *, dns_adbentry_t **);
277 static inline dns_adbfind_t *new_adbfind(dns_adb_t *);
278 static inline isc_boolean_t free_adbfind(dns_adb_t *, dns_adbfind_t **);
279 static inline dns_adbaddrinfo_t *new_adbaddrinfo(dns_adb_t *, dns_adbentry_t *,
280                                                  in_port_t);
281 static inline dns_adbfetch_t *new_adbfetch(dns_adb_t *);
282 static inline void free_adbfetch(dns_adb_t *, dns_adbfetch_t **);
283 static inline dns_adbname_t *find_name_and_lock(dns_adb_t *, dns_name_t *,
284                                                 unsigned int, int *);
285 static inline dns_adbentry_t *find_entry_and_lock(dns_adb_t *,
286                                                   isc_sockaddr_t *, int *);
287 static void dump_adb(dns_adb_t *, FILE *, isc_boolean_t debug, isc_stdtime_t);
288 static void print_dns_name(FILE *, dns_name_t *);
289 static void print_namehook_list(FILE *, const char *legend,
290                                 dns_adbnamehooklist_t *list,
291                                 isc_boolean_t debug,
292                                 isc_stdtime_t now);
293 static void print_find_list(FILE *, dns_adbname_t *);
294 static void print_fetch_list(FILE *, dns_adbname_t *);
295 static inline isc_boolean_t dec_adb_irefcnt(dns_adb_t *);
296 static inline void inc_adb_irefcnt(dns_adb_t *);
297 static inline void inc_adb_erefcnt(dns_adb_t *);
298 static inline void inc_entry_refcnt(dns_adb_t *, dns_adbentry_t *,
299                                     isc_boolean_t);
300 static inline isc_boolean_t dec_entry_refcnt(dns_adb_t *, dns_adbentry_t *,
301                                              isc_boolean_t);
302 static inline void violate_locking_hierarchy(isc_mutex_t *, isc_mutex_t *);
303 static isc_boolean_t clean_namehooks(dns_adb_t *, dns_adbnamehooklist_t *);
304 static void clean_target(dns_adb_t *, dns_name_t *);
305 static void clean_finds_at_name(dns_adbname_t *, isc_eventtype_t,
306                                 unsigned int);
307 static isc_boolean_t check_expire_namehooks(dns_adbname_t *, isc_stdtime_t,
308                                             isc_boolean_t);
309 static void cancel_fetches_at_name(dns_adbname_t *);
310 static isc_result_t dbfind_name(dns_adbname_t *, isc_stdtime_t,
311                                 dns_rdatatype_t);
312 static isc_result_t fetch_name(dns_adbname_t *, isc_boolean_t,
313                                dns_rdatatype_t);
314 static inline void check_exit(dns_adb_t *);
315 static void timer_cleanup(isc_task_t *, isc_event_t *);
316 static void destroy(dns_adb_t *);
317 static isc_boolean_t shutdown_names(dns_adb_t *);
318 static isc_boolean_t shutdown_entries(dns_adb_t *);
319 static inline void link_name(dns_adb_t *, int, dns_adbname_t *);
320 static inline isc_boolean_t unlink_name(dns_adb_t *, dns_adbname_t *);
321 static inline void link_entry(dns_adb_t *, int, dns_adbentry_t *);
322 static inline isc_boolean_t unlink_entry(dns_adb_t *, dns_adbentry_t *);
323 static isc_boolean_t kill_name(dns_adbname_t **, isc_eventtype_t);
324 static void water(void *, int);
325 static void dump_entry(FILE *, dns_adbentry_t *, isc_boolean_t, isc_stdtime_t);
326
327 /*
328  * MUST NOT overlap DNS_ADBFIND_* flags!
329  */
330 #define FIND_EVENT_SENT         0x40000000
331 #define FIND_EVENT_FREED        0x80000000
332 #define FIND_EVENTSENT(h)       (((h)->flags & FIND_EVENT_SENT) != 0)
333 #define FIND_EVENTFREED(h)      (((h)->flags & FIND_EVENT_FREED) != 0)
334
335 #define NAME_NEEDS_POKE         0x80000000
336 #define NAME_IS_DEAD            0x40000000
337 #define NAME_HINT_OK            DNS_ADBFIND_HINTOK
338 #define NAME_GLUE_OK            DNS_ADBFIND_GLUEOK
339 #define NAME_STARTATZONE        DNS_ADBFIND_STARTATZONE
340 #define NAME_DEAD(n)            (((n)->flags & NAME_IS_DEAD) != 0)
341 #define NAME_NEEDSPOKE(n)       (((n)->flags & NAME_NEEDS_POKE) != 0)
342 #define NAME_GLUEOK(n)          (((n)->flags & NAME_GLUE_OK) != 0)
343 #define NAME_HINTOK(n)          (((n)->flags & NAME_HINT_OK) != 0)
344
345 /*
346  * To the name, address classes are all that really exist.  If it has a
347  * V6 address it doesn't care if it came from a AAAA query.
348  */
349 #define NAME_HAS_V4(n)          (!ISC_LIST_EMPTY((n)->v4))
350 #define NAME_HAS_V6(n)          (!ISC_LIST_EMPTY((n)->v6))
351 #define NAME_HAS_ADDRS(n)       (NAME_HAS_V4(n) || NAME_HAS_V6(n))
352
353 /*
354  * Fetches are broken out into A and AAAA types.  In some cases,
355  * however, it makes more sense to test for a particular class of fetches,
356  * like V4 or V6 above.
357  * Note: since we have removed the support of A6 in adb, FETCH_A and FETCH_AAAA
358  * are now equal to FETCH_V4 and FETCH_V6, respectively.
359  */
360 #define NAME_FETCH_A(n)         ((n)->fetch_a != NULL)
361 #define NAME_FETCH_AAAA(n)      ((n)->fetch_aaaa != NULL)
362 #define NAME_FETCH_V4(n)        (NAME_FETCH_A(n))
363 #define NAME_FETCH_V6(n)        (NAME_FETCH_AAAA(n))
364 #define NAME_FETCH(n)           (NAME_FETCH_V4(n) || NAME_FETCH_V6(n))
365
366 /*
367  * Find options and tests to see if there are addresses on the list.
368  */
369 #define FIND_WANTEVENT(fn)      (((fn)->options & DNS_ADBFIND_WANTEVENT) != 0)
370 #define FIND_WANTEMPTYEVENT(fn) (((fn)->options & DNS_ADBFIND_EMPTYEVENT) != 0)
371 #define FIND_AVOIDFETCHES(fn)   (((fn)->options & DNS_ADBFIND_AVOIDFETCHES) \
372                                  != 0)
373 #define FIND_STARTATZONE(fn)    (((fn)->options & DNS_ADBFIND_STARTATZONE) \
374                                  != 0)
375 #define FIND_HINTOK(fn)         (((fn)->options & DNS_ADBFIND_HINTOK) != 0)
376 #define FIND_GLUEOK(fn)         (((fn)->options & DNS_ADBFIND_GLUEOK) != 0)
377 #define FIND_HAS_ADDRS(fn)      (!ISC_LIST_EMPTY((fn)->list))
378 #define FIND_RETURNLAME(fn)     (((fn)->options & DNS_ADBFIND_RETURNLAME) != 0)
379
380 /*
381  * These are currently used on simple unsigned ints, so they are
382  * not really associated with any particular type.
383  */
384 #define WANT_INET(x)            (((x) & DNS_ADBFIND_INET) != 0)
385 #define WANT_INET6(x)           (((x) & DNS_ADBFIND_INET6) != 0)
386
387 #define EXPIRE_OK(exp, now)     ((exp == INT_MAX) || (exp < now))
388
389 /*
390  * Find out if the flags on a name (nf) indicate if it is a hint or
391  * glue, and compare this to the appropriate bits set in o, to see if
392  * this is ok.
393  */
394 #define GLUE_OK(nf, o) (!NAME_GLUEOK(nf) || (((o) & DNS_ADBFIND_GLUEOK) != 0))
395 #define HINT_OK(nf, o) (!NAME_HINTOK(nf) || (((o) & DNS_ADBFIND_HINTOK) != 0))
396 #define GLUEHINT_OK(nf, o) (GLUE_OK(nf, o) || HINT_OK(nf, o))
397 #define STARTATZONE_MATCHES(nf, o) (((nf)->flags & NAME_STARTATZONE) == \
398                                     ((o) & DNS_ADBFIND_STARTATZONE))
399
400 #define ENTER_LEVEL             ISC_LOG_DEBUG(50)
401 #define EXIT_LEVEL              ENTER_LEVEL
402 #define CLEAN_LEVEL             ISC_LOG_DEBUG(100)
403 #define DEF_LEVEL               ISC_LOG_DEBUG(5)
404 #define NCACHE_LEVEL            ISC_LOG_DEBUG(20)
405
406 #define NCACHE_RESULT(r)        ((r) == DNS_R_NCACHENXDOMAIN || \
407                                  (r) == DNS_R_NCACHENXRRSET)
408 #define AUTH_NX(r)              ((r) == DNS_R_NXDOMAIN || \
409                                  (r) == DNS_R_NXRRSET)
410 #define NXDOMAIN_RESULT(r)      ((r) == DNS_R_NXDOMAIN || \
411                                  (r) == DNS_R_NCACHENXDOMAIN)
412 #define NXRRSET_RESULT(r)       ((r) == DNS_R_NCACHENXRRSET || \
413                                  (r) == DNS_R_NXRRSET || \
414                                  (r) == DNS_R_HINTNXRRSET)
415
416 /*
417  * Error state rankings.
418  */
419
420 #define FIND_ERR_SUCCESS                0  /* highest rank */
421 #define FIND_ERR_CANCELED               1
422 #define FIND_ERR_FAILURE                2
423 #define FIND_ERR_NXDOMAIN               3
424 #define FIND_ERR_NXRRSET                4
425 #define FIND_ERR_UNEXPECTED             5
426 #define FIND_ERR_NOTFOUND               6
427 #define FIND_ERR_MAX                    7
428
429 static const char *errnames[] = {
430         "success",
431         "canceled",
432         "failure",
433         "nxdomain",
434         "nxrrset",
435         "unexpected",
436         "not_found"
437 };
438
439 #define NEWERR(old, new)        (ISC_MIN((old), (new)))
440
441 static isc_result_t find_err_map[FIND_ERR_MAX] = {
442         ISC_R_SUCCESS,
443         ISC_R_CANCELED,
444         ISC_R_FAILURE,
445         DNS_R_NXDOMAIN,
446         DNS_R_NXRRSET,
447         ISC_R_UNEXPECTED,
448         ISC_R_NOTFOUND          /* not YET found */
449 };
450
451 static void
452 DP(int level, const char *format, ...) ISC_FORMAT_PRINTF(2, 3);
453
454 static void
455 DP(int level, const char *format, ...) {
456         va_list args;
457
458         va_start(args, format);
459         isc_log_vwrite(dns_lctx,
460                        DNS_LOGCATEGORY_DATABASE, DNS_LOGMODULE_ADB,
461                        level, format, args);
462         va_end(args);
463 }
464
465 static inline dns_ttl_t
466 ttlclamp(dns_ttl_t ttl) {
467         if (ttl < ADB_CACHE_MINIMUM)
468                 ttl = ADB_CACHE_MINIMUM;
469         if (ttl > ADB_CACHE_MAXIMUM)
470                 ttl = ADB_CACHE_MAXIMUM;
471
472         return (ttl);
473 }
474
475 /*
476  * Requires the adbname bucket be locked and that no entry buckets be locked.
477  *
478  * This code handles A and AAAA rdatasets only.
479  */
480 static isc_result_t
481 import_rdataset(dns_adbname_t *adbname, dns_rdataset_t *rdataset,
482                 isc_stdtime_t now)
483 {
484         isc_result_t result;
485         dns_adb_t *adb;
486         dns_adbnamehook_t *nh;
487         dns_adbnamehook_t *anh;
488         dns_rdata_t rdata = DNS_RDATA_INIT;
489         struct in_addr ina;
490         struct in6_addr in6a;
491         isc_sockaddr_t sockaddr;
492         dns_adbentry_t *foundentry;  /* NO CLEAN UP! */
493         int addr_bucket;
494         isc_boolean_t new_addresses_added;
495         dns_rdatatype_t rdtype;
496         unsigned int findoptions;
497
498         INSIST(DNS_ADBNAME_VALID(adbname));
499         adb = adbname->adb;
500         INSIST(DNS_ADB_VALID(adb));
501
502         rdtype = rdataset->type;
503         INSIST((rdtype == dns_rdatatype_a) || (rdtype == dns_rdatatype_aaaa));
504         if (rdtype == dns_rdatatype_a)
505                 findoptions = DNS_ADBFIND_INET;
506         else
507                 findoptions = DNS_ADBFIND_INET6;
508
509         addr_bucket = DNS_ADB_INVALIDBUCKET;
510         new_addresses_added = ISC_FALSE;
511
512         nh = NULL;
513         result = dns_rdataset_first(rdataset);
514         while (result == ISC_R_SUCCESS) {
515                 dns_rdata_reset(&rdata);
516                 dns_rdataset_current(rdataset, &rdata);
517                 if (rdtype == dns_rdatatype_a) {
518                         INSIST(rdata.length == 4);
519                         memcpy(&ina.s_addr, rdata.data, 4);
520                         isc_sockaddr_fromin(&sockaddr, &ina, 0);
521                 } else {
522                         INSIST(rdata.length == 16);
523                         memcpy(in6a.s6_addr, rdata.data, 16);
524                         isc_sockaddr_fromin6(&sockaddr, &in6a, 0);
525                 }
526
527                 INSIST(nh == NULL);
528                 nh = new_adbnamehook(adb, NULL);
529                 if (nh == NULL) {
530                         adbname->partial_result |= findoptions;
531                         result = ISC_R_NOMEMORY;
532                         goto fail;
533                 }
534
535                 foundentry = find_entry_and_lock(adb, &sockaddr, &addr_bucket);
536                 if (foundentry == NULL) {
537                         dns_adbentry_t *entry;
538
539                         entry = new_adbentry(adb);
540                         if (entry == NULL) {
541                                 adbname->partial_result |= findoptions;
542                                 result = ISC_R_NOMEMORY;
543                                 goto fail;
544                         }
545
546                         entry->sockaddr = sockaddr;
547                         entry->refcnt = 1;
548
549                         nh->entry = entry;
550
551                         link_entry(adb, addr_bucket, entry);
552                 } else {
553                         for (anh = ISC_LIST_HEAD(adbname->v4);
554                              anh != NULL;
555                              anh = ISC_LIST_NEXT(anh, plink))
556                                 if (anh->entry == foundentry)
557                                         break;
558                         if (anh == NULL) {
559                                 foundentry->refcnt++;
560                                 nh->entry = foundentry;
561                         } else
562                                 free_adbnamehook(adb, &nh);
563                 }
564
565                 new_addresses_added = ISC_TRUE;
566                 if (nh != NULL) {
567                         if (rdtype == dns_rdatatype_a)
568                                 ISC_LIST_APPEND(adbname->v4, nh, plink);
569                         else
570                                 ISC_LIST_APPEND(adbname->v6, nh, plink);
571                 }
572                 nh = NULL;
573                 result = dns_rdataset_next(rdataset);
574         }
575
576  fail:
577         if (nh != NULL)
578                 free_adbnamehook(adb, &nh);
579
580         if (addr_bucket != DNS_ADB_INVALIDBUCKET)
581                 UNLOCK(&adb->entrylocks[addr_bucket]);
582
583         if (rdataset->trust == dns_trust_glue ||
584             rdataset->trust == dns_trust_additional)
585                 rdataset->ttl = ADB_CACHE_MINIMUM;
586         else
587                 rdataset->ttl = ttlclamp(rdataset->ttl);
588
589         if (rdtype == dns_rdatatype_a) {
590                 DP(NCACHE_LEVEL, "expire_v4 set to MIN(%u,%u) import_rdataset",
591                    adbname->expire_v4, now + rdataset->ttl);
592                 adbname->expire_v4 = ISC_MIN(adbname->expire_v4,
593                                              now + rdataset->ttl);
594         } else {
595                 DP(NCACHE_LEVEL, "expire_v6 set to MIN(%u,%u) import_rdataset",
596                    adbname->expire_v6, now + rdataset->ttl);
597                 adbname->expire_v6 = ISC_MIN(adbname->expire_v6,
598                                              now + rdataset->ttl);
599         }
600
601         if (new_addresses_added) {
602                 /*
603                  * Lie a little here.  This is more or less so code that cares
604                  * can find out if any new information was added or not.
605                  */
606                 return (ISC_R_SUCCESS);
607         }
608
609         return (result);
610 }
611
612 /*
613  * Requires the name's bucket be locked.
614  */
615 static isc_boolean_t
616 kill_name(dns_adbname_t **n, isc_eventtype_t ev) {
617         dns_adbname_t *name;
618         isc_boolean_t result = ISC_FALSE;
619         isc_boolean_t result4, result6;
620         dns_adb_t *adb;
621
622         INSIST(n != NULL);
623         name = *n;
624         *n = NULL;
625         INSIST(DNS_ADBNAME_VALID(name));
626         adb = name->adb;
627         INSIST(DNS_ADB_VALID(adb));
628
629         DP(DEF_LEVEL, "killing name %p", name);
630
631         /*
632          * If we're dead already, just check to see if we should go
633          * away now or not.
634          */
635         if (NAME_DEAD(name) && !NAME_FETCH(name)) {
636                 result = unlink_name(adb, name);
637                 free_adbname(adb, &name);
638                 if (result)
639                         result = dec_adb_irefcnt(adb);
640                 return (result);
641         }
642
643         /*
644          * Clean up the name's various lists.  These two are destructive
645          * in that they will always empty the list.
646          */
647         clean_finds_at_name(name, ev, DNS_ADBFIND_ADDRESSMASK);
648         result4 = clean_namehooks(adb, &name->v4);
649         result6 = clean_namehooks(adb, &name->v6);
650         clean_target(adb, &name->target);
651         result = ISC_TF(result4 || result6);
652
653         /*
654          * If fetches are running, cancel them.  If none are running, we can
655          * just kill the name here.
656          */
657         if (!NAME_FETCH(name)) {
658                 INSIST(result == ISC_FALSE);
659                 result = unlink_name(adb, name);
660                 free_adbname(adb, &name);
661                 if (result)
662                         result = dec_adb_irefcnt(adb);
663         } else {
664                 name->flags |= NAME_IS_DEAD;
665                 cancel_fetches_at_name(name);
666         }
667         return (result);
668 }
669
670 /*
671  * Requires the name's bucket be locked and no entry buckets be locked.
672  */
673 static isc_boolean_t
674 check_expire_namehooks(dns_adbname_t *name, isc_stdtime_t now,
675                        isc_boolean_t overmem)
676 {
677         dns_adb_t *adb;
678         isc_boolean_t expire;
679         isc_boolean_t result4 = ISC_FALSE;
680         isc_boolean_t result6 = ISC_FALSE;
681
682         INSIST(DNS_ADBNAME_VALID(name));
683         adb = name->adb;
684         INSIST(DNS_ADB_VALID(adb));
685
686         if (overmem) {
687                 isc_uint32_t val;
688
689                 isc_random_get(&val);
690
691                 expire = ISC_TF((val % 4) == 0);
692         } else
693                 expire = ISC_FALSE;
694
695         /*
696          * Check to see if we need to remove the v4 addresses
697          */
698         if (!NAME_FETCH_V4(name) &&
699             (expire || EXPIRE_OK(name->expire_v4, now))) {
700                 if (NAME_HAS_V4(name)) {
701                         DP(DEF_LEVEL, "expiring v4 for name %p", name);
702                         result4 = clean_namehooks(adb, &name->v4);
703                         name->partial_result &= ~DNS_ADBFIND_INET;
704                 }
705                 name->expire_v4 = INT_MAX;
706                 name->fetch_err = FIND_ERR_UNEXPECTED;
707         }
708
709         /*
710          * Check to see if we need to remove the v6 addresses
711          */
712         if (!NAME_FETCH_V6(name) &&
713             (expire || EXPIRE_OK(name->expire_v6, now))) {
714                 if (NAME_HAS_V6(name)) {
715                         DP(DEF_LEVEL, "expiring v6 for name %p", name);
716                         result6 = clean_namehooks(adb, &name->v6);
717                         name->partial_result &= ~DNS_ADBFIND_INET6;
718                 }
719                 name->expire_v6 = INT_MAX;
720                 name->fetch6_err = FIND_ERR_UNEXPECTED;
721         }
722
723         /*
724          * Check to see if we need to remove the alias target.
725          */
726         if (expire || EXPIRE_OK(name->expire_target, now)) {
727                 clean_target(adb, &name->target);
728                 name->expire_target = INT_MAX;
729         }
730         return (ISC_TF(result4 || result6));
731 }
732
733 /*
734  * Requires the name's bucket be locked.
735  */
736 static inline void
737 link_name(dns_adb_t *adb, int bucket, dns_adbname_t *name) {
738         INSIST(name->lock_bucket == DNS_ADB_INVALIDBUCKET);
739
740         ISC_LIST_PREPEND(adb->names[bucket], name, plink);
741         name->lock_bucket = bucket;
742         adb->name_refcnt[bucket]++;
743 }
744
745 /*
746  * Requires the name's bucket be locked.
747  */
748 static inline isc_boolean_t
749 unlink_name(dns_adb_t *adb, dns_adbname_t *name) {
750         int bucket;
751         isc_boolean_t result = ISC_FALSE;
752
753         bucket = name->lock_bucket;
754         INSIST(bucket != DNS_ADB_INVALIDBUCKET);
755
756         ISC_LIST_UNLINK(adb->names[bucket], name, plink);
757         name->lock_bucket = DNS_ADB_INVALIDBUCKET;
758         INSIST(adb->name_refcnt[bucket] > 0);
759         adb->name_refcnt[bucket]--;
760         if (adb->name_sd[bucket] && adb->name_refcnt[bucket] == 0)
761                 result = ISC_TRUE;
762         return (result);
763 }
764
765 /*
766  * Requires the entry's bucket be locked.
767  */
768 static inline void
769 link_entry(dns_adb_t *adb, int bucket, dns_adbentry_t *entry) {
770         ISC_LIST_PREPEND(adb->entries[bucket], entry, plink);
771         entry->lock_bucket = bucket;
772         adb->entry_refcnt[bucket]++;
773 }
774
775 /*
776  * Requires the entry's bucket be locked.
777  */
778 static inline isc_boolean_t
779 unlink_entry(dns_adb_t *adb, dns_adbentry_t *entry) {
780         int bucket;
781         isc_boolean_t result = ISC_FALSE;
782
783         bucket = entry->lock_bucket;
784         INSIST(bucket != DNS_ADB_INVALIDBUCKET);
785
786         ISC_LIST_UNLINK(adb->entries[bucket], entry, plink);
787         entry->lock_bucket = DNS_ADB_INVALIDBUCKET;
788         INSIST(adb->entry_refcnt[bucket] > 0);
789         adb->entry_refcnt[bucket]--;
790         if (adb->entry_sd[bucket] && adb->entry_refcnt[bucket] == 0)
791                 result = ISC_TRUE;
792         return (result);
793 }
794
795 static inline void
796 violate_locking_hierarchy(isc_mutex_t *have, isc_mutex_t *want) {
797         if (isc_mutex_trylock(want) != ISC_R_SUCCESS) {
798                 UNLOCK(have);
799                 LOCK(want);
800                 LOCK(have);
801         }
802 }
803
804 /*
805  * The ADB _MUST_ be locked before calling.  Also, exit conditions must be
806  * checked after calling this function.
807  */
808 static isc_boolean_t
809 shutdown_names(dns_adb_t *adb) {
810         int bucket;
811         isc_boolean_t result = ISC_FALSE;
812         dns_adbname_t *name;
813         dns_adbname_t *next_name;
814
815         for (bucket = 0; bucket < NBUCKETS; bucket++) {
816                 LOCK(&adb->namelocks[bucket]);
817                 adb->name_sd[bucket] = ISC_TRUE;
818
819                 name = ISC_LIST_HEAD(adb->names[bucket]);
820                 if (name == NULL) {
821                         /*
822                          * This bucket has no names.  We must decrement the
823                          * irefcnt ourselves, since it will not be
824                          * automatically triggered by a name being unlinked.
825                          */
826                         INSIST(result == ISC_FALSE);
827                         result = dec_adb_irefcnt(adb);
828                 } else {
829                         /*
830                          * Run through the list.  For each name, clean up finds
831                          * found there, and cancel any fetches running.  When
832                          * all the fetches are canceled, the name will destroy
833                          * itself.
834                          */
835                         while (name != NULL) {
836                                 next_name = ISC_LIST_NEXT(name, plink);
837                                 INSIST(result == ISC_FALSE);
838                                 result = kill_name(&name,
839                                                    DNS_EVENT_ADBSHUTDOWN);
840                                 name = next_name;
841                         }
842                 }
843
844                 UNLOCK(&adb->namelocks[bucket]);
845         }
846         return (result);
847 }
848
849 /*
850  * The ADB _MUST_ be locked before calling.  Also, exit conditions must be
851  * checked after calling this function.
852  */
853 static isc_boolean_t
854 shutdown_entries(dns_adb_t *adb) {
855         int bucket;
856         isc_boolean_t result = ISC_FALSE;
857         dns_adbentry_t *entry;
858         dns_adbentry_t *next_entry;
859
860         for (bucket = 0; bucket < NBUCKETS; bucket++) {
861                 LOCK(&adb->entrylocks[bucket]);
862                 adb->entry_sd[bucket] = ISC_TRUE;
863
864                 entry = ISC_LIST_HEAD(adb->entries[bucket]);
865                 if (entry == NULL) {
866                         /*
867                          * This bucket has no entries.  We must decrement the
868                          * irefcnt ourselves, since it will not be
869                          * automatically triggered by an entry being unlinked.
870                          */
871                         result = dec_adb_irefcnt(adb);
872                 } else {
873                         /*
874                          * Run through the list.  Cleanup any entries not
875                          * associated with names, and which are not in use.
876                          */
877                         while (entry != NULL) {
878                                 next_entry = ISC_LIST_NEXT(entry, plink);
879                                 if (entry->refcnt == 0 &&
880                                     entry->expires != 0) {
881                                         result = unlink_entry(adb, entry);
882                                         free_adbentry(adb, &entry);
883                                         if (result)
884                                                 result = dec_adb_irefcnt(adb);
885                                 }
886                                 entry = next_entry;
887                         }
888                 }
889
890                 UNLOCK(&adb->entrylocks[bucket]);
891         }
892         return (result);
893 }
894
895 /*
896  * Name bucket must be locked
897  */
898 static void
899 cancel_fetches_at_name(dns_adbname_t *name) {
900         if (NAME_FETCH_A(name))
901             dns_resolver_cancelfetch(name->fetch_a->fetch);
902
903         if (NAME_FETCH_AAAA(name))
904             dns_resolver_cancelfetch(name->fetch_aaaa->fetch);
905 }
906
907 /*
908  * Assumes the name bucket is locked.
909  */
910 static isc_boolean_t
911 clean_namehooks(dns_adb_t *adb, dns_adbnamehooklist_t *namehooks) {
912         dns_adbentry_t *entry;
913         dns_adbnamehook_t *namehook;
914         int addr_bucket;
915         isc_boolean_t result = ISC_FALSE;
916
917         addr_bucket = DNS_ADB_INVALIDBUCKET;
918         namehook = ISC_LIST_HEAD(*namehooks);
919         while (namehook != NULL) {
920                 INSIST(DNS_ADBNAMEHOOK_VALID(namehook));
921
922                 /*
923                  * Clean up the entry if needed.
924                  */
925                 entry = namehook->entry;
926                 if (entry != NULL) {
927                         INSIST(DNS_ADBENTRY_VALID(entry));
928
929                         if (addr_bucket != entry->lock_bucket) {
930                                 if (addr_bucket != DNS_ADB_INVALIDBUCKET)
931                                         UNLOCK(&adb->entrylocks[addr_bucket]);
932                                 addr_bucket = entry->lock_bucket;
933                                 LOCK(&adb->entrylocks[addr_bucket]);
934                         }
935
936                         result = dec_entry_refcnt(adb, entry, ISC_FALSE);
937                 }
938
939                 /*
940                  * Free the namehook
941                  */
942                 namehook->entry = NULL;
943                 ISC_LIST_UNLINK(*namehooks, namehook, plink);
944                 free_adbnamehook(adb, &namehook);
945
946                 namehook = ISC_LIST_HEAD(*namehooks);
947         }
948
949         if (addr_bucket != DNS_ADB_INVALIDBUCKET)
950                 UNLOCK(&adb->entrylocks[addr_bucket]);
951         return (result);
952 }
953
954 static void
955 clean_target(dns_adb_t *adb, dns_name_t *target) {
956         if (dns_name_countlabels(target) > 0) {
957                 dns_name_free(target, adb->mctx);
958                 dns_name_init(target, NULL);
959         }
960 }
961
962 static isc_result_t
963 set_target(dns_adb_t *adb, dns_name_t *name, dns_name_t *fname,
964            dns_rdataset_t *rdataset, dns_name_t *target)
965 {
966         isc_result_t result;
967         dns_namereln_t namereln;
968         unsigned int nlabels;
969         int order;
970         dns_rdata_t rdata = DNS_RDATA_INIT;
971         dns_fixedname_t fixed1, fixed2;
972         dns_name_t *prefix, *new_target;
973
974         REQUIRE(dns_name_countlabels(target) == 0);
975
976         if (rdataset->type == dns_rdatatype_cname) {
977                 dns_rdata_cname_t cname;
978
979                 /*
980                  * Copy the CNAME's target into the target name.
981                  */
982                 result = dns_rdataset_first(rdataset);
983                 if (result != ISC_R_SUCCESS)
984                         return (result);
985                 dns_rdataset_current(rdataset, &rdata);
986                 result = dns_rdata_tostruct(&rdata, &cname, NULL);
987                 if (result != ISC_R_SUCCESS)
988                         return (result);
989                 result = dns_name_dup(&cname.cname, adb->mctx, target);
990                 dns_rdata_freestruct(&cname);
991                 if (result != ISC_R_SUCCESS)
992                         return (result);
993         } else {
994                 dns_rdata_dname_t dname;
995
996                 INSIST(rdataset->type == dns_rdatatype_dname);
997                 namereln = dns_name_fullcompare(name, fname, &order, &nlabels);
998                 INSIST(namereln == dns_namereln_subdomain);
999                 /*
1000                  * Get the target name of the DNAME.
1001                  */
1002                 result = dns_rdataset_first(rdataset);
1003                 if (result != ISC_R_SUCCESS)
1004                         return (result);
1005                 dns_rdataset_current(rdataset, &rdata);
1006                 result = dns_rdata_tostruct(&rdata, &dname, NULL);
1007                 if (result != ISC_R_SUCCESS)
1008                         return (result);
1009                 /*
1010                  * Construct the new target name.
1011                  */
1012                 dns_fixedname_init(&fixed1);
1013                 prefix = dns_fixedname_name(&fixed1);
1014                 dns_fixedname_init(&fixed2);
1015                 new_target = dns_fixedname_name(&fixed2);
1016                 dns_name_split(name, nlabels, prefix, NULL);
1017                 result = dns_name_concatenate(prefix, &dname.dname, new_target,
1018                                               NULL);
1019                 dns_rdata_freestruct(&dname);
1020                 if (result != ISC_R_SUCCESS)
1021                         return (result);
1022                 result = dns_name_dup(new_target, adb->mctx, target);
1023                 if (result != ISC_R_SUCCESS)
1024                         return (result);
1025         }
1026
1027         return (ISC_R_SUCCESS);
1028 }
1029
1030 /*
1031  * Assumes nothing is locked, since this is called by the client.
1032  */
1033 static void
1034 event_free(isc_event_t *event) {
1035         dns_adbfind_t *find;
1036
1037         INSIST(event != NULL);
1038         find = event->ev_destroy_arg;
1039         INSIST(DNS_ADBFIND_VALID(find));
1040
1041         LOCK(&find->lock);
1042         find->flags |= FIND_EVENT_FREED;
1043         event->ev_destroy_arg = NULL;
1044         UNLOCK(&find->lock);
1045 }
1046
1047 /*
1048  * Assumes the name bucket is locked.
1049  */
1050 static void
1051 clean_finds_at_name(dns_adbname_t *name, isc_eventtype_t evtype,
1052                     unsigned int addrs)
1053 {
1054         isc_event_t *ev;
1055         isc_task_t *task;
1056         dns_adbfind_t *find;
1057         dns_adbfind_t *next_find;
1058         isc_boolean_t process;
1059         unsigned int wanted, notify;
1060
1061         DP(ENTER_LEVEL,
1062            "ENTER clean_finds_at_name, name %p, evtype %08x, addrs %08x",
1063            name, evtype, addrs);
1064
1065         find = ISC_LIST_HEAD(name->finds);
1066         while (find != NULL) {
1067                 LOCK(&find->lock);
1068                 next_find = ISC_LIST_NEXT(find, plink);
1069
1070                 process = ISC_FALSE;
1071                 wanted = find->flags & DNS_ADBFIND_ADDRESSMASK;
1072                 notify = wanted & addrs;
1073
1074                 switch (evtype) {
1075                 case DNS_EVENT_ADBMOREADDRESSES:
1076                         DP(ISC_LOG_DEBUG(3), "DNS_EVENT_ADBMOREADDRESSES");
1077                         if ((notify) != 0) {
1078                                 find->flags &= ~addrs;
1079                                 process = ISC_TRUE;
1080                         }
1081                         break;
1082                 case DNS_EVENT_ADBNOMOREADDRESSES:
1083                         DP(ISC_LOG_DEBUG(3), "DNS_EVENT_ADBNOMOREADDRESSES");
1084                         find->flags &= ~addrs;
1085                         wanted = find->flags & DNS_ADBFIND_ADDRESSMASK;
1086                         if (wanted == 0)
1087                                 process = ISC_TRUE;
1088                         break;
1089                 default:
1090                         find->flags &= ~addrs;
1091                         process = ISC_TRUE;
1092                 }
1093
1094                 if (process) {
1095                         DP(DEF_LEVEL, "cfan: processing find %p", find);
1096                         /*
1097                          * Unlink the find from the name, letting the caller
1098                          * call dns_adb_destroyfind() on it to clean it up
1099                          * later.
1100                          */
1101                         ISC_LIST_UNLINK(name->finds, find, plink);
1102                         find->adbname = NULL;
1103                         find->name_bucket = DNS_ADB_INVALIDBUCKET;
1104
1105                         INSIST(!FIND_EVENTSENT(find));
1106
1107                         ev = &find->event;
1108                         task = ev->ev_sender;
1109                         ev->ev_sender = find;
1110                         find->result_v4 = find_err_map[name->fetch_err];
1111                         find->result_v6 = find_err_map[name->fetch6_err];
1112                         ev->ev_type = evtype;
1113                         ev->ev_destroy = event_free;
1114                         ev->ev_destroy_arg = find;
1115
1116                         DP(DEF_LEVEL,
1117                            "sending event %p to task %p for find %p",
1118                            ev, task, find);
1119
1120                         isc_task_sendanddetach(&task, (isc_event_t **)&ev);
1121                 } else {
1122                         DP(DEF_LEVEL, "cfan: skipping find %p", find);
1123                 }
1124
1125                 UNLOCK(&find->lock);
1126                 find = next_find;
1127         }
1128
1129         DP(ENTER_LEVEL, "EXIT clean_finds_at_name, name %p", name);
1130 }
1131
1132 static inline void
1133 check_exit(dns_adb_t *adb) {
1134         isc_event_t *event;
1135         /*
1136          * The caller must be holding the adb lock.
1137          */
1138         if (adb->shutting_down) {
1139                 /*
1140                  * If there aren't any external references either, we're
1141                  * done.  Send the control event to initiate shutdown.
1142                  */
1143                 INSIST(!adb->cevent_sent);      /* Sanity check. */
1144                 event = &adb->cevent;
1145                 isc_task_send(adb->task, &event);
1146                 adb->cevent_sent = ISC_TRUE;
1147         }
1148 }
1149
1150 static inline isc_boolean_t
1151 dec_adb_irefcnt(dns_adb_t *adb) {
1152         isc_event_t *event;
1153         isc_task_t *etask;
1154         isc_boolean_t result = ISC_FALSE;
1155
1156         LOCK(&adb->reflock);
1157
1158         INSIST(adb->irefcnt > 0);
1159         adb->irefcnt--;
1160
1161         if (adb->irefcnt == 0) {
1162                 event = ISC_LIST_HEAD(adb->whenshutdown);
1163                 while (event != NULL) {
1164                         ISC_LIST_UNLINK(adb->whenshutdown, event, ev_link);
1165                         etask = event->ev_sender;
1166                         event->ev_sender = adb;
1167                         isc_task_sendanddetach(&etask, &event);
1168                         event = ISC_LIST_HEAD(adb->whenshutdown);
1169                 }
1170         }
1171
1172         if (adb->irefcnt == 0 && adb->erefcnt == 0)
1173                 result = ISC_TRUE;
1174         UNLOCK(&adb->reflock);
1175         return (result);
1176 }
1177
1178 static inline void
1179 inc_adb_irefcnt(dns_adb_t *adb) {
1180         LOCK(&adb->reflock);
1181         adb->irefcnt++;
1182         UNLOCK(&adb->reflock);
1183 }
1184
1185 static inline void
1186 inc_adb_erefcnt(dns_adb_t *adb) {
1187         LOCK(&adb->reflock);
1188         adb->erefcnt++;
1189         UNLOCK(&adb->reflock);
1190 }
1191
1192 static inline void
1193 inc_entry_refcnt(dns_adb_t *adb, dns_adbentry_t *entry, isc_boolean_t lock) {
1194         int bucket;
1195
1196         bucket = entry->lock_bucket;
1197
1198         if (lock)
1199                 LOCK(&adb->entrylocks[bucket]);
1200
1201         entry->refcnt++;
1202
1203         if (lock)
1204                 UNLOCK(&adb->entrylocks[bucket]);
1205 }
1206
1207 static inline isc_boolean_t
1208 dec_entry_refcnt(dns_adb_t *adb, dns_adbentry_t *entry, isc_boolean_t lock) {
1209         int bucket;
1210         isc_boolean_t destroy_entry;
1211         isc_boolean_t result = ISC_FALSE;
1212
1213         bucket = entry->lock_bucket;
1214
1215         if (lock)
1216                 LOCK(&adb->entrylocks[bucket]);
1217
1218         INSIST(entry->refcnt > 0);
1219         entry->refcnt--;
1220
1221         destroy_entry = ISC_FALSE;
1222         if (entry->refcnt == 0 &&
1223             (adb->entry_sd[bucket] || entry->expires == 0)) {
1224                 destroy_entry = ISC_TRUE;
1225                 result = unlink_entry(adb, entry);
1226         }
1227
1228         if (lock)
1229                 UNLOCK(&adb->entrylocks[bucket]);
1230
1231         if (!destroy_entry)
1232                 return (result);
1233
1234         entry->lock_bucket = DNS_ADB_INVALIDBUCKET;
1235
1236         free_adbentry(adb, &entry);
1237         if (result)
1238                 result =dec_adb_irefcnt(adb);
1239
1240         return (result);
1241 }
1242
1243 static inline dns_adbname_t *
1244 new_adbname(dns_adb_t *adb, dns_name_t *dnsname) {
1245         dns_adbname_t *name;
1246
1247         name = isc_mempool_get(adb->nmp);
1248         if (name == NULL)
1249                 return (NULL);
1250
1251         dns_name_init(&name->name, NULL);
1252         if (dns_name_dup(dnsname, adb->mctx, &name->name) != ISC_R_SUCCESS) {
1253                 isc_mempool_put(adb->nmp, name);
1254                 return (NULL);
1255         }
1256         dns_name_init(&name->target, NULL);
1257         name->magic = DNS_ADBNAME_MAGIC;
1258         name->adb = adb;
1259         name->partial_result = 0;
1260         name->flags = 0;
1261         name->expire_v4 = INT_MAX;
1262         name->expire_v6 = INT_MAX;
1263         name->expire_target = INT_MAX;
1264         name->chains = 0;
1265         name->lock_bucket = DNS_ADB_INVALIDBUCKET;
1266         ISC_LIST_INIT(name->v4);
1267         ISC_LIST_INIT(name->v6);
1268         name->fetch_a = NULL;
1269         name->fetch_aaaa = NULL;
1270         name->fetch_err = FIND_ERR_UNEXPECTED;
1271         name->fetch6_err = FIND_ERR_UNEXPECTED;
1272         ISC_LIST_INIT(name->finds);
1273         ISC_LINK_INIT(name, plink);
1274
1275         return (name);
1276 }
1277
1278 static inline void
1279 free_adbname(dns_adb_t *adb, dns_adbname_t **name) {
1280         dns_adbname_t *n;
1281
1282         INSIST(name != NULL && DNS_ADBNAME_VALID(*name));
1283         n = *name;
1284         *name = NULL;
1285
1286         INSIST(!NAME_HAS_V4(n));
1287         INSIST(!NAME_HAS_V6(n));
1288         INSIST(!NAME_FETCH(n));
1289         INSIST(ISC_LIST_EMPTY(n->finds));
1290         INSIST(!ISC_LINK_LINKED(n, plink));
1291         INSIST(n->lock_bucket == DNS_ADB_INVALIDBUCKET);
1292         INSIST(n->adb == adb);
1293
1294         n->magic = 0;
1295         dns_name_free(&n->name, adb->mctx);
1296
1297         isc_mempool_put(adb->nmp, n);
1298 }
1299
1300 static inline dns_adbnamehook_t *
1301 new_adbnamehook(dns_adb_t *adb, dns_adbentry_t *entry) {
1302         dns_adbnamehook_t *nh;
1303
1304         nh = isc_mempool_get(adb->nhmp);
1305         if (nh == NULL)
1306                 return (NULL);
1307
1308         nh->magic = DNS_ADBNAMEHOOK_MAGIC;
1309         nh->entry = entry;
1310         ISC_LINK_INIT(nh, plink);
1311
1312         return (nh);
1313 }
1314
1315 static inline void
1316 free_adbnamehook(dns_adb_t *adb, dns_adbnamehook_t **namehook) {
1317         dns_adbnamehook_t *nh;
1318
1319         INSIST(namehook != NULL && DNS_ADBNAMEHOOK_VALID(*namehook));
1320         nh = *namehook;
1321         *namehook = NULL;
1322
1323         INSIST(nh->entry == NULL);
1324         INSIST(!ISC_LINK_LINKED(nh, plink));
1325
1326         nh->magic = 0;
1327         isc_mempool_put(adb->nhmp, nh);
1328 }
1329
1330 static inline dns_adblameinfo_t *
1331 new_adblameinfo(dns_adb_t *adb, dns_name_t *qname, dns_rdatatype_t qtype) {
1332         dns_adblameinfo_t *li;
1333
1334         li = isc_mempool_get(adb->limp);
1335         if (li == NULL)
1336                 return (NULL);
1337
1338         dns_name_init(&li->qname, NULL);
1339         if (dns_name_dup(qname, adb->mctx, &li->qname) != ISC_R_SUCCESS) {
1340                 isc_mempool_put(adb->limp, li);
1341                 return (NULL);
1342         }
1343         li->magic = DNS_ADBLAMEINFO_MAGIC;
1344         li->lame_timer = 0;
1345         li->qtype = qtype;
1346         ISC_LINK_INIT(li, plink);
1347
1348         return (li);
1349 }
1350
1351 static inline void
1352 free_adblameinfo(dns_adb_t *adb, dns_adblameinfo_t **lameinfo) {
1353         dns_adblameinfo_t *li;
1354
1355         INSIST(lameinfo != NULL && DNS_ADBLAMEINFO_VALID(*lameinfo));
1356         li = *lameinfo;
1357         *lameinfo = NULL;
1358
1359         INSIST(!ISC_LINK_LINKED(li, plink));
1360
1361         dns_name_free(&li->qname, adb->mctx);
1362
1363         li->magic = 0;
1364
1365         isc_mempool_put(adb->limp, li);
1366 }
1367
1368 static inline dns_adbentry_t *
1369 new_adbentry(dns_adb_t *adb) {
1370         dns_adbentry_t *e;
1371         isc_uint32_t r;
1372
1373         e = isc_mempool_get(adb->emp);
1374         if (e == NULL)
1375                 return (NULL);
1376
1377         e->magic = DNS_ADBENTRY_MAGIC;
1378         e->lock_bucket = DNS_ADB_INVALIDBUCKET;
1379         e->refcnt = 0;
1380         e->flags = 0;
1381         isc_random_get(&r);
1382         e->srtt = (r & 0x1f) + 1;
1383         e->expires = 0;
1384         ISC_LIST_INIT(e->lameinfo);
1385         ISC_LINK_INIT(e, plink);
1386
1387         return (e);
1388 }
1389
1390 static inline void
1391 free_adbentry(dns_adb_t *adb, dns_adbentry_t **entry) {
1392         dns_adbentry_t *e;
1393         dns_adblameinfo_t *li;
1394
1395         INSIST(entry != NULL && DNS_ADBENTRY_VALID(*entry));
1396         e = *entry;
1397         *entry = NULL;
1398
1399         INSIST(e->lock_bucket == DNS_ADB_INVALIDBUCKET);
1400         INSIST(e->refcnt == 0);
1401         INSIST(!ISC_LINK_LINKED(e, plink));
1402
1403         e->magic = 0;
1404
1405         li = ISC_LIST_HEAD(e->lameinfo);
1406         while (li != NULL) {
1407                 ISC_LIST_UNLINK(e->lameinfo, li, plink);
1408                 free_adblameinfo(adb, &li);
1409                 li = ISC_LIST_HEAD(e->lameinfo);
1410         }
1411
1412         isc_mempool_put(adb->emp, e);
1413 }
1414
1415 static inline dns_adbfind_t *
1416 new_adbfind(dns_adb_t *adb) {
1417         dns_adbfind_t *h;
1418         isc_result_t result;
1419
1420         h = isc_mempool_get(adb->ahmp);
1421         if (h == NULL)
1422                 return (NULL);
1423
1424         /*
1425          * Public members.
1426          */
1427         h->magic = 0;
1428         h->adb = adb;
1429         h->partial_result = 0;
1430         h->options = 0;
1431         h->flags = 0;
1432         h->result_v4 = ISC_R_UNEXPECTED;
1433         h->result_v6 = ISC_R_UNEXPECTED;
1434         ISC_LINK_INIT(h, publink);
1435         ISC_LINK_INIT(h, plink);
1436         ISC_LIST_INIT(h->list);
1437         h->adbname = NULL;
1438         h->name_bucket = DNS_ADB_INVALIDBUCKET;
1439
1440         /*
1441          * private members
1442          */
1443         result = isc_mutex_init(&h->lock);
1444         if (result != ISC_R_SUCCESS) {
1445                 isc_mempool_put(adb->ahmp, h);
1446                 return (NULL);
1447         }
1448
1449         ISC_EVENT_INIT(&h->event, sizeof(isc_event_t), 0, 0, 0, NULL, NULL,
1450                        NULL, NULL, h);
1451
1452         inc_adb_irefcnt(adb);
1453         h->magic = DNS_ADBFIND_MAGIC;
1454         return (h);
1455 }
1456
1457 static inline dns_adbfetch_t *
1458 new_adbfetch(dns_adb_t *adb) {
1459         dns_adbfetch_t *f;
1460
1461         f = isc_mempool_get(adb->afmp);
1462         if (f == NULL)
1463                 return (NULL);
1464
1465         f->magic = 0;
1466         f->namehook = NULL;
1467         f->entry = NULL;
1468         f->fetch = NULL;
1469
1470         f->namehook = new_adbnamehook(adb, NULL);
1471         if (f->namehook == NULL)
1472                 goto err;
1473
1474         f->entry = new_adbentry(adb);
1475         if (f->entry == NULL)
1476                 goto err;
1477
1478         dns_rdataset_init(&f->rdataset);
1479
1480         f->magic = DNS_ADBFETCH_MAGIC;
1481
1482         return (f);
1483
1484  err:
1485         if (f->namehook != NULL)
1486                 free_adbnamehook(adb, &f->namehook);
1487         if (f->entry != NULL)
1488                 free_adbentry(adb, &f->entry);
1489         isc_mempool_put(adb->afmp, f);
1490         return (NULL);
1491 }
1492
1493 static inline void
1494 free_adbfetch(dns_adb_t *adb, dns_adbfetch_t **fetch) {
1495         dns_adbfetch_t *f;
1496
1497         INSIST(fetch != NULL && DNS_ADBFETCH_VALID(*fetch));
1498         f = *fetch;
1499         *fetch = NULL;
1500
1501         f->magic = 0;
1502
1503         if (f->namehook != NULL)
1504                 free_adbnamehook(adb, &f->namehook);
1505         if (f->entry != NULL)
1506                 free_adbentry(adb, &f->entry);
1507
1508         if (dns_rdataset_isassociated(&f->rdataset))
1509                 dns_rdataset_disassociate(&f->rdataset);
1510
1511         isc_mempool_put(adb->afmp, f);
1512 }
1513
1514 static inline isc_boolean_t
1515 free_adbfind(dns_adb_t *adb, dns_adbfind_t **findp) {
1516         dns_adbfind_t *find;
1517
1518         INSIST(findp != NULL && DNS_ADBFIND_VALID(*findp));
1519         find = *findp;
1520         *findp = NULL;
1521
1522         INSIST(!FIND_HAS_ADDRS(find));
1523         INSIST(!ISC_LINK_LINKED(find, publink));
1524         INSIST(!ISC_LINK_LINKED(find, plink));
1525         INSIST(find->name_bucket == DNS_ADB_INVALIDBUCKET);
1526         INSIST(find->adbname == NULL);
1527
1528         find->magic = 0;
1529
1530         DESTROYLOCK(&find->lock);
1531         isc_mempool_put(adb->ahmp, find);
1532         return (dec_adb_irefcnt(adb));
1533 }
1534
1535 /*
1536  * Copy bits from the entry into the newly allocated addrinfo.  The entry
1537  * must be locked, and the reference count must be bumped up by one
1538  * if this function returns a valid pointer.
1539  */
1540 static inline dns_adbaddrinfo_t *
1541 new_adbaddrinfo(dns_adb_t *adb, dns_adbentry_t *entry, in_port_t port) {
1542         dns_adbaddrinfo_t *ai;
1543
1544         ai = isc_mempool_get(adb->aimp);
1545         if (ai == NULL)
1546                 return (NULL);
1547
1548         ai->magic = DNS_ADBADDRINFO_MAGIC;
1549         ai->sockaddr = entry->sockaddr;
1550         isc_sockaddr_setport(&ai->sockaddr, port);
1551         ai->srtt = entry->srtt;
1552         ai->flags = entry->flags;
1553         ai->entry = entry;
1554         ISC_LINK_INIT(ai, publink);
1555
1556         return (ai);
1557 }
1558
1559 static inline void
1560 free_adbaddrinfo(dns_adb_t *adb, dns_adbaddrinfo_t **ainfo) {
1561         dns_adbaddrinfo_t *ai;
1562
1563         INSIST(ainfo != NULL && DNS_ADBADDRINFO_VALID(*ainfo));
1564         ai = *ainfo;
1565         *ainfo = NULL;
1566
1567         INSIST(ai->entry == NULL);
1568         INSIST(!ISC_LINK_LINKED(ai, publink));
1569
1570         ai->magic = 0;
1571
1572         isc_mempool_put(adb->aimp, ai);
1573 }
1574
1575 /*
1576  * Search for the name.  NOTE:  The bucket is kept locked on both
1577  * success and failure, so it must always be unlocked by the caller!
1578  *
1579  * On the first call to this function, *bucketp must be set to
1580  * DNS_ADB_INVALIDBUCKET.
1581  */
1582 static inline dns_adbname_t *
1583 find_name_and_lock(dns_adb_t *adb, dns_name_t *name,
1584                    unsigned int options, int *bucketp)
1585 {
1586         dns_adbname_t *adbname;
1587         int bucket;
1588
1589         bucket = dns_name_fullhash(name, ISC_FALSE) % NBUCKETS;
1590
1591         if (*bucketp == DNS_ADB_INVALIDBUCKET) {
1592                 LOCK(&adb->namelocks[bucket]);
1593                 *bucketp = bucket;
1594         } else if (*bucketp != bucket) {
1595                 UNLOCK(&adb->namelocks[*bucketp]);
1596                 LOCK(&adb->namelocks[bucket]);
1597                 *bucketp = bucket;
1598         }
1599
1600         adbname = ISC_LIST_HEAD(adb->names[bucket]);
1601         while (adbname != NULL) {
1602                 if (!NAME_DEAD(adbname)) {
1603                         if (dns_name_equal(name, &adbname->name)
1604                             && GLUEHINT_OK(adbname, options)
1605                             && STARTATZONE_MATCHES(adbname, options))
1606                                 return (adbname);
1607                 }
1608                 adbname = ISC_LIST_NEXT(adbname, plink);
1609         }
1610
1611         return (NULL);
1612 }
1613
1614 /*
1615  * Search for the address.  NOTE:  The bucket is kept locked on both
1616  * success and failure, so it must always be unlocked by the caller.
1617  *
1618  * On the first call to this function, *bucketp must be set to
1619  * DNS_ADB_INVALIDBUCKET.  This will cause a lock to occur.  On
1620  * later calls (within the same "lock path") it can be left alone, so
1621  * if this function is called multiple times locking is only done if
1622  * the bucket changes.
1623  */
1624 static inline dns_adbentry_t *
1625 find_entry_and_lock(dns_adb_t *adb, isc_sockaddr_t *addr, int *bucketp) {
1626         dns_adbentry_t *entry;
1627         int bucket;
1628
1629         bucket = isc_sockaddr_hash(addr, ISC_TRUE) % NBUCKETS;
1630
1631         if (*bucketp == DNS_ADB_INVALIDBUCKET) {
1632                 LOCK(&adb->entrylocks[bucket]);
1633                 *bucketp = bucket;
1634         } else if (*bucketp != bucket) {
1635                 UNLOCK(&adb->entrylocks[*bucketp]);
1636                 LOCK(&adb->entrylocks[bucket]);
1637                 *bucketp = bucket;
1638         }
1639
1640         entry = ISC_LIST_HEAD(adb->entries[bucket]);
1641         while (entry != NULL) {
1642                 if (isc_sockaddr_equal(addr, &entry->sockaddr))
1643                         return (entry);
1644                 entry = ISC_LIST_NEXT(entry, plink);
1645         }
1646
1647         return (NULL);
1648 }
1649
1650 /*
1651  * Entry bucket MUST be locked!
1652  */
1653 static isc_boolean_t
1654 entry_is_lame(dns_adb_t *adb, dns_adbentry_t *entry, dns_name_t *qname,
1655               dns_rdatatype_t qtype, isc_stdtime_t now)
1656 {
1657         dns_adblameinfo_t *li, *next_li;
1658         isc_boolean_t is_bad;
1659
1660         is_bad = ISC_FALSE;
1661
1662         li = ISC_LIST_HEAD(entry->lameinfo);
1663         if (li == NULL)
1664                 return (ISC_FALSE);
1665         while (li != NULL) {
1666                 next_li = ISC_LIST_NEXT(li, plink);
1667
1668                 /*
1669                  * Has the entry expired?
1670                  */
1671                 if (li->lame_timer < now) {
1672                         ISC_LIST_UNLINK(entry->lameinfo, li, plink);
1673                         free_adblameinfo(adb, &li);
1674                 }
1675
1676                 /*
1677                  * Order tests from least to most expensive.
1678                  *
1679                  * We do not break out of the main loop here as
1680                  * we use the loop for house keeping.
1681                  */
1682                 if (li != NULL && !is_bad && li->qtype == qtype &&
1683                     dns_name_equal(qname, &li->qname))
1684                         is_bad = ISC_TRUE;
1685
1686                 li = next_li;
1687         }
1688
1689         return (is_bad);
1690 }
1691
1692 static void
1693 copy_namehook_lists(dns_adb_t *adb, dns_adbfind_t *find, dns_name_t *qname,
1694                     dns_rdatatype_t qtype, dns_adbname_t *name,
1695                     isc_stdtime_t now)
1696 {
1697         dns_adbnamehook_t *namehook;
1698         dns_adbaddrinfo_t *addrinfo;
1699         dns_adbentry_t *entry;
1700         int bucket;
1701
1702         bucket = DNS_ADB_INVALIDBUCKET;
1703
1704         if (find->options & DNS_ADBFIND_INET) {
1705                 namehook = ISC_LIST_HEAD(name->v4);
1706                 while (namehook != NULL) {
1707                         entry = namehook->entry;
1708                         bucket = entry->lock_bucket;
1709                         LOCK(&adb->entrylocks[bucket]);
1710
1711                         if (!FIND_RETURNLAME(find)
1712                             && entry_is_lame(adb, entry, qname, qtype, now)) {
1713                                 find->options |= DNS_ADBFIND_LAMEPRUNED;
1714                                 goto nextv4;
1715                         }
1716                         addrinfo = new_adbaddrinfo(adb, entry, find->port);
1717                         if (addrinfo == NULL) {
1718                                 find->partial_result |= DNS_ADBFIND_INET;
1719                                 goto out;
1720                         }
1721                         /*
1722                          * Found a valid entry.  Add it to the find's list.
1723                          */
1724                         inc_entry_refcnt(adb, entry, ISC_FALSE);
1725                         ISC_LIST_APPEND(find->list, addrinfo, publink);
1726                         addrinfo = NULL;
1727                 nextv4:
1728                         UNLOCK(&adb->entrylocks[bucket]);
1729                         bucket = DNS_ADB_INVALIDBUCKET;
1730                         namehook = ISC_LIST_NEXT(namehook, plink);
1731                 }
1732         }
1733
1734         if (find->options & DNS_ADBFIND_INET6) {
1735                 namehook = ISC_LIST_HEAD(name->v6);
1736                 while (namehook != NULL) {
1737                         entry = namehook->entry;
1738                         bucket = entry->lock_bucket;
1739                         LOCK(&adb->entrylocks[bucket]);
1740
1741                         if (entry_is_lame(adb, entry, qname, qtype, now))
1742                                 goto nextv6;
1743                         addrinfo = new_adbaddrinfo(adb, entry, find->port);
1744                         if (addrinfo == NULL) {
1745                                 find->partial_result |= DNS_ADBFIND_INET6;
1746                                 goto out;
1747                         }
1748                         /*
1749                          * Found a valid entry.  Add it to the find's list.
1750                          */
1751                         inc_entry_refcnt(adb, entry, ISC_FALSE);
1752                         ISC_LIST_APPEND(find->list, addrinfo, publink);
1753                         addrinfo = NULL;
1754                 nextv6:
1755                         UNLOCK(&adb->entrylocks[bucket]);
1756                         bucket = DNS_ADB_INVALIDBUCKET;
1757                         namehook = ISC_LIST_NEXT(namehook, plink);
1758                 }
1759         }
1760
1761  out:
1762         if (bucket != DNS_ADB_INVALIDBUCKET)
1763                 UNLOCK(&adb->entrylocks[bucket]);
1764 }
1765
1766 static void
1767 shutdown_task(isc_task_t *task, isc_event_t *ev) {
1768         dns_adb_t *adb;
1769
1770         UNUSED(task);
1771
1772         adb = ev->ev_arg;
1773         INSIST(DNS_ADB_VALID(adb));
1774
1775         /*
1776          * Kill the timer, and then the ADB itself.  Note that this implies
1777          * that this task was the one scheduled to get timer events.  If
1778          * this is not true (and it is unfortunate there is no way to INSIST()
1779          * this) badness will occur.
1780          */
1781         LOCK(&adb->lock);
1782         isc_timer_detach(&adb->timer);
1783         UNLOCK(&adb->lock);
1784         isc_event_free(&ev);
1785         destroy(adb);
1786 }
1787
1788 /*
1789  * Name bucket must be locked; adb may be locked; no other locks held.
1790  */
1791 static isc_boolean_t
1792 check_expire_name(dns_adbname_t **namep, isc_stdtime_t now) {
1793         dns_adbname_t *name;
1794         isc_boolean_t result = ISC_FALSE;
1795
1796         INSIST(namep != NULL && DNS_ADBNAME_VALID(*namep));
1797         name = *namep;
1798
1799         if (NAME_HAS_V4(name) || NAME_HAS_V6(name))
1800                 return (result);
1801         if (NAME_FETCH(name))
1802                 return (result);
1803         if (!EXPIRE_OK(name->expire_v4, now))
1804                 return (result);
1805         if (!EXPIRE_OK(name->expire_v6, now))
1806                 return (result);
1807         if (!EXPIRE_OK(name->expire_target, now))
1808                 return (result);
1809
1810         /*
1811          * The name is empty.  Delete it.
1812          */
1813         result = kill_name(&name, DNS_EVENT_ADBEXPIRED);
1814         *namep = NULL;
1815
1816         /*
1817          * Our caller, or one of its callers, will be calling check_exit() at
1818          * some point, so we don't need to do it here.
1819          */
1820         return (result);
1821 }
1822
1823 /*
1824  * Entry bucket must be locked; adb may be locked; no other locks held.
1825  */
1826 static isc_boolean_t
1827 check_expire_entry(dns_adb_t *adb, dns_adbentry_t **entryp, isc_stdtime_t now)
1828 {
1829         dns_adbentry_t *entry;
1830         isc_boolean_t expire;
1831         isc_boolean_t result = ISC_FALSE;
1832
1833         INSIST(entryp != NULL && DNS_ADBENTRY_VALID(*entryp));
1834         entry = *entryp;
1835
1836         if (entry->refcnt != 0)
1837                 return (result);
1838
1839         if (adb->overmem) {
1840                 isc_uint32_t val;
1841
1842                 isc_random_get(&val);
1843
1844                 expire = ISC_TF((val % 4) == 0);
1845         } else
1846                 expire = ISC_FALSE;
1847
1848         if (entry->expires == 0 || (! expire && entry->expires > now))
1849                 return (result);
1850
1851         /*
1852          * The entry is not in use.  Delete it.
1853          */
1854         DP(DEF_LEVEL, "killing entry %p", entry);
1855         INSIST(ISC_LINK_LINKED(entry, plink));
1856         result = unlink_entry(adb, entry);
1857         free_adbentry(adb, &entry);
1858         if (result)
1859                 dec_adb_irefcnt(adb);
1860         *entryp = NULL;
1861         return (result);
1862 }
1863
1864 /*
1865  * ADB must be locked, and no other locks held.
1866  */
1867 static isc_boolean_t
1868 cleanup_names(dns_adb_t *adb, int bucket, isc_stdtime_t now) {
1869         dns_adbname_t *name;
1870         dns_adbname_t *next_name;
1871         isc_boolean_t result = ISC_FALSE;
1872
1873         DP(CLEAN_LEVEL, "cleaning name bucket %d", bucket);
1874
1875         LOCK(&adb->namelocks[bucket]);
1876         if (adb->name_sd[bucket]) {
1877                 UNLOCK(&adb->namelocks[bucket]);
1878                 return (result);
1879         }
1880
1881         name = ISC_LIST_HEAD(adb->names[bucket]);
1882         while (name != NULL) {
1883                 next_name = ISC_LIST_NEXT(name, plink);
1884                 INSIST(result == ISC_FALSE);
1885                 result = check_expire_namehooks(name, now, adb->overmem);
1886                 if (!result)
1887                         result = check_expire_name(&name, now);
1888                 name = next_name;
1889         }
1890         UNLOCK(&adb->namelocks[bucket]);
1891         return (result);
1892 }
1893
1894 /*
1895  * ADB must be locked, and no other locks held.
1896  */
1897 static isc_boolean_t
1898 cleanup_entries(dns_adb_t *adb, int bucket, isc_stdtime_t now) {
1899         dns_adbentry_t *entry, *next_entry;
1900         isc_boolean_t result = ISC_FALSE;
1901
1902         DP(CLEAN_LEVEL, "cleaning entry bucket %d", bucket);
1903
1904         LOCK(&adb->entrylocks[bucket]);
1905         entry = ISC_LIST_HEAD(adb->entries[bucket]);
1906         while (entry != NULL) {
1907                 next_entry = ISC_LIST_NEXT(entry, plink);
1908                 INSIST(result == ISC_FALSE);
1909                 result = check_expire_entry(adb, &entry, now);
1910                 entry = next_entry;
1911         }
1912         UNLOCK(&adb->entrylocks[bucket]);
1913         return (result);
1914 }
1915
1916 static void
1917 timer_cleanup(isc_task_t *task, isc_event_t *ev) {
1918         dns_adb_t *adb;
1919         isc_stdtime_t now;
1920         unsigned int i;
1921         isc_interval_t interval;
1922
1923         UNUSED(task);
1924
1925         adb = ev->ev_arg;
1926         INSIST(DNS_ADB_VALID(adb));
1927
1928         LOCK(&adb->lock);
1929
1930         isc_stdtime_get(&now);
1931
1932         for (i = 0; i < CLEAN_BUCKETS; i++) {
1933                 /*
1934                  * Call our cleanup routines.
1935                  */
1936                 RUNTIME_CHECK(cleanup_names(adb, adb->next_cleanbucket, now) ==
1937                               ISC_FALSE);
1938                 RUNTIME_CHECK(cleanup_entries(adb, adb->next_cleanbucket, now)
1939                               == ISC_FALSE);
1940
1941                 /*
1942                  * Set the next bucket to be cleaned.
1943                  */
1944                 adb->next_cleanbucket++;
1945                 if (adb->next_cleanbucket >= NBUCKETS) {
1946                         adb->next_cleanbucket = 0;
1947 #ifdef DUMP_ADB_AFTER_CLEANING
1948                         dump_adb(adb, stdout, ISC_TRUE, now);
1949 #endif
1950                 }
1951         }
1952
1953         /*
1954          * Reset the timer.
1955          * XXXDCL isc_timer_reset might return ISC_R_UNEXPECTED or
1956          * ISC_R_NOMEMORY, but it isn't clear what could be done here
1957          * if either one of those things happened.
1958          */
1959         interval = adb->tick_interval;
1960         if (adb->overmem)
1961                 isc_interval_set(&interval, 0, 1);
1962         (void)isc_timer_reset(adb->timer, isc_timertype_once, NULL,
1963                               &interval, ISC_FALSE);
1964
1965         UNLOCK(&adb->lock);
1966
1967         isc_event_free(&ev);
1968 }
1969
1970 static void
1971 destroy(dns_adb_t *adb) {
1972         adb->magic = 0;
1973
1974         /*
1975          * The timer is already dead, from the task's shutdown callback.
1976          */
1977         isc_task_detach(&adb->task);
1978
1979         isc_mempool_destroy(&adb->nmp);
1980         isc_mempool_destroy(&adb->nhmp);
1981         isc_mempool_destroy(&adb->limp);
1982         isc_mempool_destroy(&adb->emp);
1983         isc_mempool_destroy(&adb->ahmp);
1984         isc_mempool_destroy(&adb->aimp);
1985         isc_mempool_destroy(&adb->afmp);
1986
1987         DESTROYMUTEXBLOCK(adb->entrylocks, NBUCKETS);
1988         DESTROYMUTEXBLOCK(adb->namelocks, NBUCKETS);
1989
1990         DESTROYLOCK(&adb->reflock);
1991         DESTROYLOCK(&adb->lock);
1992         DESTROYLOCK(&adb->mplock);
1993
1994         isc_mem_putanddetach(&adb->mctx, adb, sizeof(dns_adb_t));
1995 }
1996
1997
1998 /*
1999  * Public functions.
2000  */
2001
2002 isc_result_t
2003 dns_adb_create(isc_mem_t *mem, dns_view_t *view, isc_timermgr_t *timermgr,
2004                isc_taskmgr_t *taskmgr, dns_adb_t **newadb)
2005 {
2006         dns_adb_t *adb;
2007         isc_result_t result;
2008         int i;
2009
2010         REQUIRE(mem != NULL);
2011         REQUIRE(view != NULL);
2012         REQUIRE(timermgr != NULL);
2013         REQUIRE(taskmgr != NULL);
2014         REQUIRE(newadb != NULL && *newadb == NULL);
2015
2016         adb = isc_mem_get(mem, sizeof(dns_adb_t));
2017         if (adb == NULL)
2018                 return (ISC_R_NOMEMORY);
2019
2020         /*
2021          * Initialize things here that cannot fail, and especially things
2022          * that must be NULL for the error return to work properly.
2023          */
2024         adb->magic = 0;
2025         adb->erefcnt = 1;
2026         adb->irefcnt = 0;
2027         adb->nmp = NULL;
2028         adb->nhmp = NULL;
2029         adb->limp = NULL;
2030         adb->emp = NULL;
2031         adb->ahmp = NULL;
2032         adb->aimp = NULL;
2033         adb->afmp = NULL;
2034         adb->task = NULL;
2035         adb->timer = NULL;
2036         adb->mctx = NULL;
2037         adb->view = view;
2038         adb->timermgr = timermgr;
2039         adb->taskmgr = taskmgr;
2040         adb->next_cleanbucket = 0;
2041         ISC_EVENT_INIT(&adb->cevent, sizeof(adb->cevent), 0, NULL,
2042                        DNS_EVENT_ADBCONTROL, shutdown_task, adb,
2043                        adb, NULL, NULL);
2044         adb->cevent_sent = ISC_FALSE;
2045         adb->shutting_down = ISC_FALSE;
2046         adb->overmem = ISC_FALSE;
2047         ISC_LIST_INIT(adb->whenshutdown);
2048
2049         isc_mem_attach(mem, &adb->mctx);
2050
2051         result = isc_mutex_init(&adb->lock);
2052         if (result != ISC_R_SUCCESS)
2053                 goto fail0b;
2054
2055         result = isc_mutex_init(&adb->mplock);
2056         if (result != ISC_R_SUCCESS)
2057                 goto fail0c;
2058
2059         result = isc_mutex_init(&adb->reflock);
2060         if (result != ISC_R_SUCCESS)
2061                 goto fail0d;
2062
2063         /*
2064          * Initialize the bucket locks for names and elements.
2065          * May as well initialize the list heads, too.
2066          */
2067         result = isc_mutexblock_init(adb->namelocks, NBUCKETS);
2068         if (result != ISC_R_SUCCESS)
2069                 goto fail1;
2070         for (i = 0; i < NBUCKETS; i++) {
2071                 ISC_LIST_INIT(adb->names[i]);
2072                 adb->name_sd[i] = ISC_FALSE;
2073                 adb->name_refcnt[i] = 0;
2074                 adb->irefcnt++;
2075         }
2076         for (i = 0; i < NBUCKETS; i++) {
2077                 ISC_LIST_INIT(adb->entries[i]);
2078                 adb->entry_sd[i] = ISC_FALSE;
2079                 adb->entry_refcnt[i] = 0;
2080                 adb->irefcnt++;
2081         }
2082         result = isc_mutexblock_init(adb->entrylocks, NBUCKETS);
2083         if (result != ISC_R_SUCCESS)
2084                 goto fail2;
2085
2086         /*
2087          * Memory pools
2088          */
2089 #define MPINIT(t, p, n) do { \
2090         result = isc_mempool_create(mem, sizeof(t), &(p)); \
2091         if (result != ISC_R_SUCCESS) \
2092                 goto fail3; \
2093         isc_mempool_setfreemax((p), FREE_ITEMS); \
2094         isc_mempool_setfillcount((p), FILL_COUNT); \
2095         isc_mempool_setname((p), n); \
2096         isc_mempool_associatelock((p), &adb->mplock); \
2097 } while (0)
2098
2099         MPINIT(dns_adbname_t, adb->nmp, "adbname");
2100         MPINIT(dns_adbnamehook_t, adb->nhmp, "adbnamehook");
2101         MPINIT(dns_adblameinfo_t, adb->limp, "adblameinfo");
2102         MPINIT(dns_adbentry_t, adb->emp, "adbentry");
2103         MPINIT(dns_adbfind_t, adb->ahmp, "adbfind");
2104         MPINIT(dns_adbaddrinfo_t, adb->aimp, "adbaddrinfo");
2105         MPINIT(dns_adbfetch_t, adb->afmp, "adbfetch");
2106
2107 #undef MPINIT
2108
2109         /*
2110          * Allocate a timer and a task for our periodic cleanup.
2111          */
2112         result = isc_task_create(adb->taskmgr, 0, &adb->task);
2113         if (result != ISC_R_SUCCESS)
2114                 goto fail3;
2115         isc_task_setname(adb->task, "ADB", adb);
2116         /*
2117          * XXXMLG When this is changed to be a config file option,
2118          */
2119         isc_interval_set(&adb->tick_interval, CLEAN_SECONDS, 0);
2120         result = isc_timer_create(adb->timermgr, isc_timertype_once,
2121                                   NULL, &adb->tick_interval, adb->task,
2122                                   timer_cleanup, adb, &adb->timer);
2123         if (result != ISC_R_SUCCESS)
2124                 goto fail3;
2125
2126         DP(ISC_LOG_DEBUG(5), "cleaning interval for adb: "
2127            "%u buckets every %u seconds, %u buckets in system, %u cl.interval",
2128            CLEAN_BUCKETS, CLEAN_SECONDS, NBUCKETS, CLEAN_PERIOD);
2129
2130         /*
2131          * Normal return.
2132          */
2133         adb->magic = DNS_ADB_MAGIC;
2134         *newadb = adb;
2135         return (ISC_R_SUCCESS);
2136
2137  fail3:
2138         if (adb->task != NULL)
2139                 isc_task_detach(&adb->task);
2140         if (adb->timer != NULL)
2141                 isc_timer_detach(&adb->timer);
2142
2143         /* clean up entrylocks */
2144         DESTROYMUTEXBLOCK(adb->entrylocks, NBUCKETS);
2145
2146  fail2: /* clean up namelocks */
2147         DESTROYMUTEXBLOCK(adb->namelocks, NBUCKETS);
2148
2149  fail1: /* clean up only allocated memory */
2150         if (adb->nmp != NULL)
2151                 isc_mempool_destroy(&adb->nmp);
2152         if (adb->nhmp != NULL)
2153                 isc_mempool_destroy(&adb->nhmp);
2154         if (adb->limp != NULL)
2155                 isc_mempool_destroy(&adb->limp);
2156         if (adb->emp != NULL)
2157                 isc_mempool_destroy(&adb->emp);
2158         if (adb->ahmp != NULL)
2159                 isc_mempool_destroy(&adb->ahmp);
2160         if (adb->aimp != NULL)
2161                 isc_mempool_destroy(&adb->aimp);
2162         if (adb->afmp != NULL)
2163                 isc_mempool_destroy(&adb->afmp);
2164
2165         DESTROYLOCK(&adb->reflock);
2166  fail0d:
2167         DESTROYLOCK(&adb->mplock);
2168  fail0c:
2169         DESTROYLOCK(&adb->lock);
2170  fail0b:
2171         isc_mem_putanddetach(&adb->mctx, adb, sizeof(dns_adb_t));
2172
2173         return (result);
2174 }
2175
2176 void
2177 dns_adb_attach(dns_adb_t *adb, dns_adb_t **adbx) {
2178
2179         REQUIRE(DNS_ADB_VALID(adb));
2180         REQUIRE(adbx != NULL && *adbx == NULL);
2181
2182         inc_adb_erefcnt(adb);
2183         *adbx = adb;
2184 }
2185
2186 void
2187 dns_adb_detach(dns_adb_t **adbx) {
2188         dns_adb_t *adb;
2189         isc_boolean_t need_exit_check;
2190
2191         REQUIRE(adbx != NULL && DNS_ADB_VALID(*adbx));
2192
2193         adb = *adbx;
2194         *adbx = NULL;
2195
2196         INSIST(adb->erefcnt > 0);
2197
2198         LOCK(&adb->reflock);
2199         adb->erefcnt--;
2200         need_exit_check = ISC_TF(adb->erefcnt == 0 && adb->irefcnt == 0);
2201         UNLOCK(&adb->reflock);
2202
2203         if (need_exit_check) {
2204                 LOCK(&adb->lock);
2205                 INSIST(adb->shutting_down);
2206                 check_exit(adb);
2207                 UNLOCK(&adb->lock);
2208         }
2209 }
2210
2211 void
2212 dns_adb_whenshutdown(dns_adb_t *adb, isc_task_t *task, isc_event_t **eventp) {
2213         isc_task_t *clone;
2214         isc_event_t *event;
2215         isc_boolean_t zeroirefcnt = ISC_FALSE;
2216
2217         /*
2218          * Send '*eventp' to 'task' when 'adb' has shutdown.
2219          */
2220
2221         REQUIRE(DNS_ADB_VALID(adb));
2222         REQUIRE(eventp != NULL);
2223
2224         event = *eventp;
2225         *eventp = NULL;
2226
2227         LOCK(&adb->lock);
2228
2229         LOCK(&adb->reflock);
2230         zeroirefcnt = ISC_TF(adb->irefcnt == 0);
2231
2232         if (adb->shutting_down && zeroirefcnt &&
2233             isc_mempool_getallocated(adb->ahmp) == 0) {
2234                 /*
2235                  * We're already shutdown.  Send the event.
2236                  */
2237                 event->ev_sender = adb;
2238                 isc_task_send(task, &event);
2239         } else {
2240                 clone = NULL;
2241                 isc_task_attach(task, &clone);
2242                 event->ev_sender = clone;
2243                 ISC_LIST_APPEND(adb->whenshutdown, event, ev_link);
2244         }
2245
2246         UNLOCK(&adb->reflock);
2247         UNLOCK(&adb->lock);
2248 }
2249
2250 void
2251 dns_adb_shutdown(dns_adb_t *adb) {
2252         isc_boolean_t need_check_exit;
2253
2254         /*
2255          * Shutdown 'adb'.
2256          */
2257
2258         LOCK(&adb->lock);
2259
2260         if (!adb->shutting_down) {
2261                 adb->shutting_down = ISC_TRUE;
2262                 isc_mem_setwater(adb->mctx, water, adb, 0, 0);
2263                 need_check_exit = shutdown_names(adb);
2264                 if (!need_check_exit)
2265                         need_check_exit = shutdown_entries(adb);
2266                 if (need_check_exit)
2267                         check_exit(adb);
2268         }
2269
2270         UNLOCK(&adb->lock);
2271 }
2272
2273 isc_result_t
2274 dns_adb_createfind(dns_adb_t *adb, isc_task_t *task, isc_taskaction_t action,
2275                    void *arg, dns_name_t *name, dns_name_t *qname,
2276                    dns_rdatatype_t qtype, unsigned int options,
2277                    isc_stdtime_t now, dns_name_t *target,
2278                    in_port_t port, dns_adbfind_t **findp)
2279 {
2280         dns_adbfind_t *find;
2281         dns_adbname_t *adbname;
2282         int bucket;
2283         isc_boolean_t want_event, start_at_zone, alias, have_address;
2284         isc_result_t result;
2285         unsigned int wanted_addresses;
2286         unsigned int wanted_fetches;
2287         unsigned int query_pending;
2288
2289         REQUIRE(DNS_ADB_VALID(adb));
2290         if (task != NULL) {
2291                 REQUIRE(action != NULL);
2292         }
2293         REQUIRE(name != NULL);
2294         REQUIRE(qname != NULL);
2295         REQUIRE(findp != NULL && *findp == NULL);
2296         REQUIRE(target == NULL || dns_name_hasbuffer(target));
2297
2298         REQUIRE((options & DNS_ADBFIND_ADDRESSMASK) != 0);
2299
2300         result = ISC_R_UNEXPECTED;
2301         wanted_addresses = (options & DNS_ADBFIND_ADDRESSMASK);
2302         wanted_fetches = 0;
2303         query_pending = 0;
2304         want_event = ISC_FALSE;
2305         start_at_zone = ISC_FALSE;
2306         alias = ISC_FALSE;
2307
2308         if (now == 0)
2309                 isc_stdtime_get(&now);
2310
2311         /*
2312          * XXXMLG  Move this comment somewhere else!
2313          *
2314          * Look up the name in our internal database.
2315          *
2316          * Possibilities:  Note that these are not always exclusive.
2317          *
2318          *      No name found.  In this case, allocate a new name header and
2319          *      an initial namehook or two.  If any of these allocations
2320          *      fail, clean up and return ISC_R_NOMEMORY.
2321          *
2322          *      Name found, valid addresses present.  Allocate one addrinfo
2323          *      structure for each found and append it to the linked list
2324          *      of addresses for this header.
2325          *
2326          *      Name found, queries pending.  In this case, if a task was
2327          *      passed in, allocate a job id, attach it to the name's job
2328          *      list and remember to tell the caller that there will be
2329          *      more info coming later.
2330          */
2331
2332         find = new_adbfind(adb);
2333         if (find == NULL)
2334                 return (ISC_R_NOMEMORY);
2335
2336         find->port = port;
2337
2338         /*
2339          * Remember what types of addresses we are interested in.
2340          */
2341         find->options = options;
2342         find->flags |= wanted_addresses;
2343         if (FIND_WANTEVENT(find)) {
2344                 REQUIRE(task != NULL);
2345         }
2346
2347         /*
2348          * Try to see if we know anything about this name at all.
2349          */
2350         bucket = DNS_ADB_INVALIDBUCKET;
2351         adbname = find_name_and_lock(adb, name, find->options, &bucket);
2352         if (adb->name_sd[bucket]) {
2353                 DP(DEF_LEVEL,
2354                    "dns_adb_createfind: returning ISC_R_SHUTTINGDOWN");
2355                 RUNTIME_CHECK(free_adbfind(adb, &find) == ISC_FALSE);
2356                 result = ISC_R_SHUTTINGDOWN;
2357                 goto out;
2358         }
2359
2360         /*
2361          * Nothing found.  Allocate a new adbname structure for this name.
2362          */
2363         if (adbname == NULL) {
2364                 adbname = new_adbname(adb, name);
2365                 if (adbname == NULL) {
2366                         RUNTIME_CHECK(free_adbfind(adb, &find) == ISC_FALSE);
2367                         result = ISC_R_NOMEMORY;
2368                         goto out;
2369                 }
2370                 link_name(adb, bucket, adbname);
2371                 if (FIND_HINTOK(find))
2372                         adbname->flags |= NAME_HINT_OK;
2373                 if (FIND_GLUEOK(find))
2374                         adbname->flags |= NAME_GLUE_OK;
2375                 if (FIND_STARTATZONE(find))
2376                         adbname->flags |= NAME_STARTATZONE;
2377         }
2378
2379         /*
2380          * Expire old entries, etc.
2381          */
2382         RUNTIME_CHECK(check_expire_namehooks(adbname, now, adb->overmem) ==
2383                       ISC_FALSE);
2384
2385         /*
2386          * Do we know that the name is an alias?
2387          */
2388         if (!EXPIRE_OK(adbname->expire_target, now)) {
2389                 /*
2390                  * Yes, it is.
2391                  */
2392                 DP(DEF_LEVEL,
2393                    "dns_adb_createfind: name %p is an alias (cached)",
2394                    adbname);
2395                 alias = ISC_TRUE;
2396                 goto post_copy;
2397         }
2398
2399         /*
2400          * Try to populate the name from the database and/or
2401          * start fetches.  First try looking for an A record
2402          * in the database.
2403          */
2404         if (!NAME_HAS_V4(adbname) && EXPIRE_OK(adbname->expire_v4, now)
2405             && WANT_INET(wanted_addresses)) {
2406                 result = dbfind_name(adbname, now, dns_rdatatype_a);
2407                 if (result == ISC_R_SUCCESS) {
2408                         DP(DEF_LEVEL,
2409                            "dns_adb_createfind: found A for name %p in db",
2410                            adbname);
2411                         goto v6;
2412                 }
2413
2414                 /*
2415                  * Did we get a CNAME or DNAME?
2416                  */
2417                 if (result == DNS_R_ALIAS) {
2418                         DP(DEF_LEVEL,
2419                            "dns_adb_createfind: name %p is an alias",
2420                            adbname);
2421                         alias = ISC_TRUE;
2422                         goto post_copy;
2423                 }
2424
2425                 /*
2426                  * If the name doesn't exist at all, don't bother with
2427                  * v6 queries; they won't work.
2428                  *
2429                  * If the name does exist but we didn't get our data, go
2430                  * ahead and try AAAA.
2431                  *
2432                  * If the result is neither of these, try a fetch for A.
2433                  */
2434                 if (NXDOMAIN_RESULT(result))
2435                         goto fetch;
2436                 else if (NXRRSET_RESULT(result))
2437                         goto v6;
2438
2439                 if (!NAME_FETCH_V4(adbname))
2440                         wanted_fetches |= DNS_ADBFIND_INET;
2441         }
2442
2443  v6:
2444         if (!NAME_HAS_V6(adbname) && EXPIRE_OK(adbname->expire_v6, now)
2445             && WANT_INET6(wanted_addresses)) {
2446                 result = dbfind_name(adbname, now, dns_rdatatype_aaaa);
2447                 if (result == ISC_R_SUCCESS) {
2448                         DP(DEF_LEVEL,
2449                            "dns_adb_createfind: found AAAA for name %p",
2450                            adbname);
2451                         goto fetch;
2452                 }
2453
2454                 /*
2455                  * Did we get a CNAME or DNAME?
2456                  */
2457                 if (result == DNS_R_ALIAS) {
2458                         DP(DEF_LEVEL,
2459                            "dns_adb_createfind: name %p is an alias",
2460                            adbname);
2461                         alias = ISC_TRUE;
2462                         goto post_copy;
2463                 }
2464
2465                 /*
2466                  * Listen to negative cache hints, and don't start
2467                  * another query.
2468                  */
2469                 if (NCACHE_RESULT(result) || AUTH_NX(result))
2470                         goto fetch;
2471
2472                 if (!NAME_FETCH_V6(adbname))
2473                         wanted_fetches |= DNS_ADBFIND_INET6;
2474         }
2475
2476  fetch:
2477         if ((WANT_INET(wanted_addresses) && NAME_HAS_V4(adbname)) ||
2478             (WANT_INET6(wanted_addresses) && NAME_HAS_V6(adbname)))
2479                 have_address = ISC_TRUE;
2480         else
2481                 have_address = ISC_FALSE;
2482         if (wanted_fetches != 0 &&
2483             ! (FIND_AVOIDFETCHES(find) && have_address)) {
2484                 /*
2485                  * We're missing at least one address family.  Either the
2486                  * caller hasn't instructed us to avoid fetches, or we don't
2487                  * know anything about any of the address families that would
2488                  * be acceptable so we have to launch fetches.
2489                  */
2490
2491                 if (FIND_STARTATZONE(find))
2492                         start_at_zone = ISC_TRUE;
2493
2494                 /*
2495                  * Start V4.
2496                  */
2497                 if (WANT_INET(wanted_fetches) &&
2498                     fetch_name(adbname, start_at_zone,
2499                                dns_rdatatype_a) == ISC_R_SUCCESS) {
2500                         DP(DEF_LEVEL,
2501                            "dns_adb_createfind: started A fetch for name %p",
2502                            adbname);
2503                 }
2504
2505                 /*
2506                  * Start V6.
2507                  */
2508                 if (WANT_INET6(wanted_fetches) &&
2509                     fetch_name(adbname, start_at_zone,
2510                                dns_rdatatype_aaaa) == ISC_R_SUCCESS) {
2511                         DP(DEF_LEVEL,
2512                            "dns_adb_createfind: "
2513                            "started AAAA fetch for name %p",
2514                            adbname);
2515                 }
2516         }
2517
2518         /*
2519          * Run through the name and copy out the bits we are
2520          * interested in.
2521          */
2522         copy_namehook_lists(adb, find, qname, qtype, adbname, now);
2523
2524  post_copy:
2525         if (NAME_FETCH_V4(adbname))
2526                 query_pending |= DNS_ADBFIND_INET;
2527         if (NAME_FETCH_V6(adbname))
2528                 query_pending |= DNS_ADBFIND_INET6;
2529
2530         /*
2531          * Attach to the name's query list if there are queries
2532          * already running, and we have been asked to.
2533          */
2534         want_event = ISC_TRUE;
2535         if (!FIND_WANTEVENT(find))
2536                 want_event = ISC_FALSE;
2537         if (FIND_WANTEMPTYEVENT(find) && FIND_HAS_ADDRS(find))
2538                 want_event = ISC_FALSE;
2539         if ((wanted_addresses & query_pending) == 0)
2540                 want_event = ISC_FALSE;
2541         if (alias)
2542                 want_event = ISC_FALSE;
2543         if (want_event) {
2544                 find->adbname = adbname;
2545                 find->name_bucket = bucket;
2546                 ISC_LIST_APPEND(adbname->finds, find, plink);
2547                 find->query_pending = (query_pending & wanted_addresses);
2548                 find->flags &= ~DNS_ADBFIND_ADDRESSMASK;
2549                 find->flags |= (find->query_pending & DNS_ADBFIND_ADDRESSMASK);
2550                 DP(DEF_LEVEL, "createfind: attaching find %p to adbname %p",
2551                    find, adbname);
2552         } else {
2553                 /*
2554                  * Remove the flag so the caller knows there will never
2555                  * be an event, and set internal flags to fake that
2556                  * the event was sent and freed, so dns_adb_destroyfind() will
2557                  * do the right thing.
2558                  */
2559                 find->query_pending = (query_pending & wanted_addresses);
2560                 find->options &= ~DNS_ADBFIND_WANTEVENT;
2561                 find->flags |= (FIND_EVENT_SENT | FIND_EVENT_FREED);
2562                 find->flags &= ~DNS_ADBFIND_ADDRESSMASK;
2563         }
2564
2565         find->partial_result |= (adbname->partial_result & wanted_addresses);
2566         if (alias) {
2567                 if (target != NULL) {
2568                         result = dns_name_copy(&adbname->target, target, NULL);
2569                         if (result != ISC_R_SUCCESS)
2570                                 goto out;
2571                 }
2572                 result = DNS_R_ALIAS;
2573         } else
2574                 result = ISC_R_SUCCESS;
2575
2576         /*
2577          * Copy out error flags from the name structure into the find.
2578          */
2579         find->result_v4 = find_err_map[adbname->fetch_err];
2580         find->result_v6 = find_err_map[adbname->fetch6_err];
2581
2582  out:
2583         if (find != NULL) {
2584                 *findp = find;
2585
2586                 if (want_event) {
2587                         isc_task_t *taskp;
2588
2589                         INSIST((find->flags & DNS_ADBFIND_ADDRESSMASK) != 0);
2590                         taskp = NULL;
2591                         isc_task_attach(task, &taskp);
2592                         find->event.ev_sender = taskp;
2593                         find->event.ev_action = action;
2594                         find->event.ev_arg = arg;
2595                 }
2596         }
2597
2598         UNLOCK(&adb->namelocks[bucket]);
2599
2600         return (result);
2601 }
2602
2603 void
2604 dns_adb_destroyfind(dns_adbfind_t **findp) {
2605         dns_adbfind_t *find;
2606         dns_adbentry_t *entry;
2607         dns_adbaddrinfo_t *ai;
2608         int bucket;
2609         dns_adb_t *adb;
2610
2611         REQUIRE(findp != NULL && DNS_ADBFIND_VALID(*findp));
2612         find = *findp;
2613         *findp = NULL;
2614
2615         LOCK(&find->lock);
2616
2617         DP(DEF_LEVEL, "dns_adb_destroyfind on find %p", find);
2618
2619         adb = find->adb;
2620         REQUIRE(DNS_ADB_VALID(adb));
2621
2622         REQUIRE(FIND_EVENTFREED(find));
2623
2624         bucket = find->name_bucket;
2625         INSIST(bucket == DNS_ADB_INVALIDBUCKET);
2626
2627         UNLOCK(&find->lock);
2628
2629         /*
2630          * The find doesn't exist on any list, and nothing is locked.
2631          * Return the find to the memory pool, and decrement the adb's
2632          * reference count.
2633          */
2634         ai = ISC_LIST_HEAD(find->list);
2635         while (ai != NULL) {
2636                 ISC_LIST_UNLINK(find->list, ai, publink);
2637                 entry = ai->entry;
2638                 ai->entry = NULL;
2639                 INSIST(DNS_ADBENTRY_VALID(entry));
2640                 RUNTIME_CHECK(dec_entry_refcnt(adb, entry, ISC_TRUE) ==
2641                               ISC_FALSE);
2642                 free_adbaddrinfo(adb, &ai);
2643                 ai = ISC_LIST_HEAD(find->list);
2644         }
2645
2646         /*
2647          * WARNING:  The find is freed with the adb locked.  This is done
2648          * to avoid a race condition where we free the find, some other
2649          * thread tests to see if it should be destroyed, detects it should
2650          * be, destroys it, and then we try to lock it for our check, but the
2651          * lock is destroyed.
2652          */
2653         LOCK(&adb->lock);
2654         if (free_adbfind(adb, &find))
2655                 check_exit(adb);
2656         UNLOCK(&adb->lock);
2657 }
2658
2659 void
2660 dns_adb_cancelfind(dns_adbfind_t *find) {
2661         isc_event_t *ev;
2662         isc_task_t *task;
2663         dns_adb_t *adb;
2664         int bucket;
2665         int unlock_bucket;
2666
2667         LOCK(&find->lock);
2668
2669         DP(DEF_LEVEL, "dns_adb_cancelfind on find %p", find);
2670
2671         adb = find->adb;
2672         REQUIRE(DNS_ADB_VALID(adb));
2673
2674         REQUIRE(!FIND_EVENTFREED(find));
2675         REQUIRE(FIND_WANTEVENT(find));
2676
2677         bucket = find->name_bucket;
2678         if (bucket == DNS_ADB_INVALIDBUCKET)
2679                 goto cleanup;
2680
2681         /*
2682          * We need to get the adbname's lock to unlink the find.
2683          */
2684         unlock_bucket = bucket;
2685         violate_locking_hierarchy(&find->lock, &adb->namelocks[unlock_bucket]);
2686         bucket = find->name_bucket;
2687         if (bucket != DNS_ADB_INVALIDBUCKET) {
2688                 ISC_LIST_UNLINK(find->adbname->finds, find, plink);
2689                 find->adbname = NULL;
2690                 find->name_bucket = DNS_ADB_INVALIDBUCKET;
2691         }
2692         UNLOCK(&adb->namelocks[unlock_bucket]);
2693         bucket = DNS_ADB_INVALIDBUCKET;
2694
2695  cleanup:
2696
2697         if (!FIND_EVENTSENT(find)) {
2698                 ev = &find->event;
2699                 task = ev->ev_sender;
2700                 ev->ev_sender = find;
2701                 ev->ev_type = DNS_EVENT_ADBCANCELED;
2702                 ev->ev_destroy = event_free;
2703                 ev->ev_destroy_arg = find;
2704                 find->result_v4 = ISC_R_CANCELED;
2705                 find->result_v6 = ISC_R_CANCELED;
2706
2707                 DP(DEF_LEVEL, "sending event %p to task %p for find %p",
2708                    ev, task, find);
2709
2710                 isc_task_sendanddetach(&task, (isc_event_t **)&ev);
2711         }
2712
2713         UNLOCK(&find->lock);
2714 }
2715
2716 void
2717 dns_adb_dump(dns_adb_t *adb, FILE *f) {
2718         int i;
2719         isc_stdtime_t now;
2720
2721         REQUIRE(DNS_ADB_VALID(adb));
2722         REQUIRE(f != NULL);
2723
2724         /*
2725          * Lock the adb itself, lock all the name buckets, then lock all
2726          * the entry buckets.  This should put the adb into a state where
2727          * nothing can change, so we can iterate through everything and
2728          * print at our leisure.
2729          */
2730
2731         LOCK(&adb->lock);
2732         isc_stdtime_get(&now);
2733
2734         for (i = 0; i < NBUCKETS; i++)
2735                 RUNTIME_CHECK(cleanup_names(adb, i, now) == ISC_FALSE);
2736         for (i = 0; i < NBUCKETS; i++)
2737                 RUNTIME_CHECK(cleanup_entries(adb, i, now) == ISC_FALSE);
2738
2739         dump_adb(adb, f, ISC_FALSE, now);
2740         UNLOCK(&adb->lock);
2741 }
2742
2743 static void
2744 dump_ttl(FILE *f, const char *legend, isc_stdtime_t value, isc_stdtime_t now) {
2745         if (value == INT_MAX)
2746                 return;
2747         fprintf(f, " [%s TTL %d]", legend, value - now);
2748 }
2749
2750 static void
2751 dump_adb(dns_adb_t *adb, FILE *f, isc_boolean_t debug, isc_stdtime_t now) {
2752         int i;
2753         dns_adbname_t *name;
2754         dns_adbentry_t *entry;
2755
2756         fprintf(f, ";\n; Address database dump\n;\n");
2757         if (debug)
2758                 fprintf(f, "; addr %p, erefcnt %u, irefcnt %u, finds out %u\n",
2759                         adb, adb->erefcnt, adb->irefcnt,
2760                         isc_mempool_getallocated(adb->nhmp));
2761
2762         for (i = 0; i < NBUCKETS; i++)
2763                 LOCK(&adb->namelocks[i]);
2764         for (i = 0; i < NBUCKETS; i++)
2765                 LOCK(&adb->entrylocks[i]);
2766
2767         /*
2768          * Dump the names
2769          */
2770         for (i = 0; i < NBUCKETS; i++) {
2771                 name = ISC_LIST_HEAD(adb->names[i]);
2772                 if (name == NULL)
2773                         continue;
2774                 if (debug)
2775                         fprintf(f, "; bucket %d\n", i);
2776                 for (;
2777                      name != NULL;
2778                      name = ISC_LIST_NEXT(name, plink))
2779                 {
2780                         if (debug)
2781                                 fprintf(f, "; name %p (flags %08x)\n",
2782                                         name, name->flags);
2783
2784                         fprintf(f, "; ");
2785                         print_dns_name(f, &name->name);
2786                         if (dns_name_countlabels(&name->target) > 0) {
2787                                 fprintf(f, " alias ");
2788                                 print_dns_name(f, &name->target);
2789                         }
2790
2791                         dump_ttl(f, "v4", name->expire_v4, now);
2792                         dump_ttl(f, "v6", name->expire_v6, now);
2793                         dump_ttl(f, "target", name->expire_target, now);
2794
2795                         fprintf(f, " [v4 %s] [v6 %s]",
2796                                 errnames[name->fetch_err],
2797                                 errnames[name->fetch6_err]);
2798
2799                         fprintf(f, "\n");
2800
2801                         print_namehook_list(f, "v4", &name->v4, debug, now);
2802                         print_namehook_list(f, "v6", &name->v6, debug, now);
2803
2804                         if (debug)
2805                                 print_fetch_list(f, name);
2806                         if (debug)
2807                                 print_find_list(f, name);
2808
2809                 }
2810         }
2811
2812         fprintf(f, ";\n; Unassociated entries\n;\n");
2813
2814         for (i = 0; i < NBUCKETS; i++) {
2815                 entry = ISC_LIST_HEAD(adb->entries[i]);
2816                 while (entry != NULL) {
2817                         if (entry->refcnt == 0)
2818                                 dump_entry(f, entry, debug, now);
2819                         entry = ISC_LIST_NEXT(entry, plink);
2820                 }
2821         }
2822
2823         /*
2824          * Unlock everything
2825          */
2826         for (i = 0; i < NBUCKETS; i++)
2827                 UNLOCK(&adb->entrylocks[i]);
2828         for (i = 0; i < NBUCKETS; i++)
2829                 UNLOCK(&adb->namelocks[i]);
2830 }
2831
2832 static void
2833 dump_entry(FILE *f, dns_adbentry_t *entry, isc_boolean_t debug,
2834            isc_stdtime_t now)
2835 {
2836         char addrbuf[ISC_NETADDR_FORMATSIZE];
2837         char typebuf[DNS_RDATATYPE_FORMATSIZE];
2838         isc_netaddr_t netaddr;
2839         dns_adblameinfo_t *li;
2840
2841         isc_netaddr_fromsockaddr(&netaddr, &entry->sockaddr);
2842         isc_netaddr_format(&netaddr, addrbuf, sizeof(addrbuf));
2843
2844         if (debug)
2845                 fprintf(f, ";\t%p: refcnt %u\n", entry, entry->refcnt);
2846
2847         fprintf(f, ";\t%s [srtt %u] [flags %08x]",
2848                 addrbuf, entry->srtt, entry->flags);
2849         if (entry->expires != 0)
2850                 fprintf(f, " [ttl %d]", entry->expires - now);
2851         fprintf(f, "\n");
2852         for (li = ISC_LIST_HEAD(entry->lameinfo);
2853              li != NULL;
2854              li = ISC_LIST_NEXT(li, plink)) {
2855                 fprintf(f, ";\t\t");
2856                 print_dns_name(f, &li->qname);
2857                 dns_rdatatype_format(li->qtype, typebuf, sizeof(typebuf));
2858                 fprintf(f, " %s [lame TTL %d]\n", typebuf,
2859                         li->lame_timer - now);
2860         }
2861 }
2862
2863 void
2864 dns_adb_dumpfind(dns_adbfind_t *find, FILE *f) {
2865         char tmp[512];
2866         const char *tmpp;
2867         dns_adbaddrinfo_t *ai;
2868         isc_sockaddr_t *sa;
2869
2870         /*
2871          * Not used currently, in the API Just In Case we
2872          * want to dump out the name and/or entries too.
2873          */
2874
2875         LOCK(&find->lock);
2876
2877         fprintf(f, ";Find %p\n", find);
2878         fprintf(f, ";\tqpending %08x partial %08x options %08x flags %08x\n",
2879                 find->query_pending, find->partial_result,
2880                 find->options, find->flags);
2881         fprintf(f, ";\tname_bucket %d, name %p, event sender %p\n",
2882                 find->name_bucket, find->adbname, find->event.ev_sender);
2883
2884         ai = ISC_LIST_HEAD(find->list);
2885         if (ai != NULL)
2886                 fprintf(f, "\tAddresses:\n");
2887         while (ai != NULL) {
2888                 sa = &ai->sockaddr;
2889                 switch (sa->type.sa.sa_family) {
2890                 case AF_INET:
2891                         tmpp = inet_ntop(AF_INET, &sa->type.sin.sin_addr,
2892                                          tmp, sizeof(tmp));
2893                         break;
2894                 case AF_INET6:
2895                         tmpp = inet_ntop(AF_INET6, &sa->type.sin6.sin6_addr,
2896                                          tmp, sizeof(tmp));
2897                         break;
2898                 default:
2899                         tmpp = "UnkFamily";
2900                 }
2901
2902                 if (tmpp == NULL)
2903                         tmpp = "BadAddress";
2904
2905                 fprintf(f, "\t\tentry %p, flags %08x"
2906                         " srtt %u addr %s\n",
2907                         ai->entry, ai->flags, ai->srtt, tmpp);
2908
2909                 ai = ISC_LIST_NEXT(ai, publink);
2910         }
2911
2912         UNLOCK(&find->lock);
2913 }
2914
2915 static void
2916 print_dns_name(FILE *f, dns_name_t *name) {
2917         char buf[DNS_NAME_FORMATSIZE];
2918
2919         INSIST(f != NULL);
2920
2921         dns_name_format(name, buf, sizeof(buf));
2922         fprintf(f, "%s", buf);
2923 }
2924
2925 static void
2926 print_namehook_list(FILE *f, const char *legend, dns_adbnamehooklist_t *list,
2927                     isc_boolean_t debug, isc_stdtime_t now)
2928 {
2929         dns_adbnamehook_t *nh;
2930
2931         for (nh = ISC_LIST_HEAD(*list);
2932              nh != NULL;
2933              nh = ISC_LIST_NEXT(nh, plink))
2934         {
2935                 if (debug)
2936                         fprintf(f, ";\tHook(%s) %p\n", legend, nh);
2937                 dump_entry(f, nh->entry, debug, now);
2938         }
2939 }
2940
2941 static inline void
2942 print_fetch(FILE *f, dns_adbfetch_t *ft, const char *type) {
2943         fprintf(f, "\t\tFetch(%s): %p -> { nh %p, entry %p, fetch %p }\n",
2944                 type, ft, ft->namehook, ft->entry, ft->fetch);
2945 }
2946
2947 static void
2948 print_fetch_list(FILE *f, dns_adbname_t *n) {
2949         if (NAME_FETCH_A(n))
2950                 print_fetch(f, n->fetch_a, "A");
2951         if (NAME_FETCH_AAAA(n))
2952                 print_fetch(f, n->fetch_aaaa, "AAAA");
2953 }
2954
2955 static void
2956 print_find_list(FILE *f, dns_adbname_t *name) {
2957         dns_adbfind_t *find;
2958
2959         find = ISC_LIST_HEAD(name->finds);
2960         while (find != NULL) {
2961                 dns_adb_dumpfind(find, f);
2962                 find = ISC_LIST_NEXT(find, plink);
2963         }
2964 }
2965
2966 static isc_result_t
2967 dbfind_name(dns_adbname_t *adbname, isc_stdtime_t now, dns_rdatatype_t rdtype)
2968 {
2969         isc_result_t result;
2970         dns_rdataset_t rdataset;
2971         dns_adb_t *adb;
2972         dns_fixedname_t foundname;
2973         dns_name_t *fname;
2974
2975         INSIST(DNS_ADBNAME_VALID(adbname));
2976         adb = adbname->adb;
2977         INSIST(DNS_ADB_VALID(adb));
2978         INSIST(rdtype == dns_rdatatype_a || rdtype == dns_rdatatype_aaaa);
2979
2980         dns_fixedname_init(&foundname);
2981         fname = dns_fixedname_name(&foundname);
2982         dns_rdataset_init(&rdataset);
2983
2984         if (rdtype == dns_rdatatype_a)
2985                 adbname->fetch_err = FIND_ERR_UNEXPECTED;
2986         else
2987                 adbname->fetch6_err = FIND_ERR_UNEXPECTED;
2988
2989         result = dns_view_find(adb->view, &adbname->name, rdtype, now,
2990                                NAME_GLUEOK(adbname) ? DNS_DBFIND_GLUEOK : 0,
2991                                ISC_TF(NAME_HINTOK(adbname)),
2992                                NULL, NULL, fname, &rdataset, NULL);
2993
2994         /* XXXVIX this switch statement is too sparse to gen a jump table. */
2995         switch (result) {
2996         case DNS_R_GLUE:
2997         case DNS_R_HINT:
2998         case ISC_R_SUCCESS:
2999                 /*
3000                  * Found in the database.  Even if we can't copy out
3001                  * any information, return success, or else a fetch
3002                  * will be made, which will only make things worse.
3003                  */
3004                 if (rdtype == dns_rdatatype_a)
3005                         adbname->fetch_err = FIND_ERR_SUCCESS;
3006                 else
3007                         adbname->fetch6_err = FIND_ERR_SUCCESS;
3008                 result = import_rdataset(adbname, &rdataset, now);
3009                 break;
3010         case DNS_R_NXDOMAIN:
3011         case DNS_R_NXRRSET:
3012                 /*
3013                  * We're authoritative and the data doesn't exist.
3014                  * Make up a negative cache entry so we don't ask again
3015                  * for a while.
3016                  *
3017                  * XXXRTH  What time should we use?  I'm putting in 30 seconds
3018                  * for now.
3019                  */
3020                 if (rdtype == dns_rdatatype_a) {
3021                         adbname->expire_v4 = now + 30;
3022                         DP(NCACHE_LEVEL,
3023                            "adb name %p: Caching auth negative entry for A",
3024                            adbname);
3025                         if (result == DNS_R_NXDOMAIN)
3026                                 adbname->fetch_err = FIND_ERR_NXDOMAIN;
3027                         else
3028                                 adbname->fetch_err = FIND_ERR_NXRRSET;
3029                 } else {
3030                         DP(NCACHE_LEVEL,
3031                            "adb name %p: Caching auth negative entry for AAAA",
3032                            adbname);
3033                         adbname->expire_v6 = now + 30;
3034                         if (result == DNS_R_NXDOMAIN)
3035                                 adbname->fetch6_err = FIND_ERR_NXDOMAIN;
3036                         else
3037                                 adbname->fetch6_err = FIND_ERR_NXRRSET;
3038                 }
3039                 break;
3040         case DNS_R_NCACHENXDOMAIN:
3041         case DNS_R_NCACHENXRRSET:
3042                 /*
3043                  * We found a negative cache entry.  Pull the TTL from it
3044                  * so we won't ask again for a while.
3045                  */
3046                 rdataset.ttl = ttlclamp(rdataset.ttl);
3047                 if (rdtype == dns_rdatatype_a) {
3048                         adbname->expire_v4 = rdataset.ttl + now;
3049                         if (result == DNS_R_NCACHENXDOMAIN)
3050                                 adbname->fetch_err = FIND_ERR_NXDOMAIN;
3051                         else
3052                                 adbname->fetch_err = FIND_ERR_NXRRSET;
3053                         DP(NCACHE_LEVEL,
3054                           "adb name %p: Caching negative entry for A (ttl %u)",
3055                            adbname, rdataset.ttl);
3056                 } else {
3057                         DP(NCACHE_LEVEL,
3058                        "adb name %p: Caching negative entry for AAAA (ttl %u)",
3059                            adbname, rdataset.ttl);
3060                         adbname->expire_v6 = rdataset.ttl + now;
3061                         if (result == DNS_R_NCACHENXDOMAIN)
3062                                 adbname->fetch6_err = FIND_ERR_NXDOMAIN;
3063                         else
3064                                 adbname->fetch6_err = FIND_ERR_NXRRSET;
3065                 }
3066                 break;
3067         case DNS_R_CNAME:
3068         case DNS_R_DNAME:
3069                 /*
3070                  * Clear the hint and glue flags, so this will match
3071                  * more often.
3072                  */
3073                 adbname->flags &= ~(DNS_ADBFIND_GLUEOK | DNS_ADBFIND_HINTOK);
3074
3075                 rdataset.ttl = ttlclamp(rdataset.ttl);
3076                 clean_target(adb, &adbname->target);
3077                 adbname->expire_target = INT_MAX;
3078                 result = set_target(adb, &adbname->name, fname, &rdataset,
3079                                     &adbname->target);
3080                 if (result == ISC_R_SUCCESS) {
3081                         result = DNS_R_ALIAS;
3082                         DP(NCACHE_LEVEL,
3083                            "adb name %p: caching alias target",
3084                            adbname);
3085                         adbname->expire_target = rdataset.ttl + now;
3086                 }
3087                 if (rdtype == dns_rdatatype_a)
3088                         adbname->fetch_err = FIND_ERR_SUCCESS;
3089                 else
3090                         adbname->fetch6_err = FIND_ERR_SUCCESS;
3091                 break;
3092         }
3093
3094         if (dns_rdataset_isassociated(&rdataset))
3095                 dns_rdataset_disassociate(&rdataset);
3096
3097         return (result);
3098 }
3099
3100 static void
3101 fetch_callback(isc_task_t *task, isc_event_t *ev) {
3102         dns_fetchevent_t *dev;
3103         dns_adbname_t *name;
3104         dns_adb_t *adb;
3105         dns_adbfetch_t *fetch;
3106         int bucket;
3107         isc_eventtype_t ev_status;
3108         isc_stdtime_t now;
3109         isc_result_t result;
3110         unsigned int address_type;
3111         isc_boolean_t want_check_exit = ISC_FALSE;
3112
3113         UNUSED(task);
3114
3115         INSIST(ev->ev_type == DNS_EVENT_FETCHDONE);
3116         dev = (dns_fetchevent_t *)ev;
3117         name = ev->ev_arg;
3118         INSIST(DNS_ADBNAME_VALID(name));
3119         adb = name->adb;
3120         INSIST(DNS_ADB_VALID(adb));
3121
3122         bucket = name->lock_bucket;
3123         LOCK(&adb->namelocks[bucket]);
3124
3125         INSIST(NAME_FETCH_A(name) || NAME_FETCH_AAAA(name));
3126         address_type = 0;
3127         if (NAME_FETCH_A(name) && (name->fetch_a->fetch == dev->fetch)) {
3128                 address_type = DNS_ADBFIND_INET;
3129                 fetch = name->fetch_a;
3130                 name->fetch_a = NULL;
3131         } else if (NAME_FETCH_AAAA(name)
3132                    && (name->fetch_aaaa->fetch == dev->fetch)) {
3133                 address_type = DNS_ADBFIND_INET6;
3134                 fetch = name->fetch_aaaa;
3135                 name->fetch_aaaa = NULL;
3136         }
3137         INSIST(address_type != 0);
3138
3139         dns_resolver_destroyfetch(&fetch->fetch);
3140         dev->fetch = NULL;
3141
3142         ev_status = DNS_EVENT_ADBNOMOREADDRESSES;
3143
3144         /*
3145          * Cleanup things we don't care about.
3146          */
3147         if (dev->node != NULL)
3148                 dns_db_detachnode(dev->db, &dev->node);
3149         if (dev->db != NULL)
3150                 dns_db_detach(&dev->db);
3151
3152         /*
3153          * If this name is marked as dead, clean up, throwing away
3154          * potentially good data.
3155          */
3156         if (NAME_DEAD(name)) {
3157                 free_adbfetch(adb, &fetch);
3158                 isc_event_free(&ev);
3159
3160                 want_check_exit = kill_name(&name, DNS_EVENT_ADBCANCELED);
3161
3162                 UNLOCK(&adb->namelocks[bucket]);
3163
3164                 if (want_check_exit) {
3165                         LOCK(&adb->lock);
3166                         check_exit(adb);
3167                         UNLOCK(&adb->lock);
3168                 }
3169
3170                 return;
3171         }
3172
3173         isc_stdtime_get(&now);
3174
3175         /*
3176          * If we got a negative cache response, remember it.
3177          */
3178         if (NCACHE_RESULT(dev->result)) {
3179                 dev->rdataset->ttl = ttlclamp(dev->rdataset->ttl);
3180                 if (address_type == DNS_ADBFIND_INET) {
3181                         DP(NCACHE_LEVEL, "adb fetch name %p: "
3182                            "caching negative entry for A (ttl %u)",
3183                            name, dev->rdataset->ttl);
3184                         name->expire_v4 = ISC_MIN(name->expire_v4,
3185                                                   dev->rdataset->ttl + now);
3186                         if (dev->result == DNS_R_NCACHENXDOMAIN)
3187                                 name->fetch_err = FIND_ERR_NXDOMAIN;
3188                         else
3189                                 name->fetch_err = FIND_ERR_NXRRSET;
3190                 } else {
3191                         DP(NCACHE_LEVEL, "adb fetch name %p: "
3192                            "caching negative entry for AAAA (ttl %u)",
3193                            name, dev->rdataset->ttl);
3194                         name->expire_v6 = ISC_MIN(name->expire_v6,
3195                                                   dev->rdataset->ttl + now);
3196                         if (dev->result == DNS_R_NCACHENXDOMAIN)
3197                                 name->fetch6_err = FIND_ERR_NXDOMAIN;
3198                         else
3199                                 name->fetch6_err = FIND_ERR_NXRRSET;
3200                 }
3201                 goto out;
3202         }
3203
3204         /*
3205          * Handle CNAME/DNAME.
3206          */
3207         if (dev->result == DNS_R_CNAME || dev->result == DNS_R_DNAME) {
3208                 dev->rdataset->ttl = ttlclamp(dev->rdataset->ttl);
3209                 clean_target(adb, &name->target);
3210                 name->expire_target = INT_MAX;
3211                 result = set_target(adb, &name->name,
3212                                     dns_fixedname_name(&dev->foundname),
3213                                     dev->rdataset,
3214                                     &name->target);
3215                 if (result == ISC_R_SUCCESS) {
3216                         DP(NCACHE_LEVEL,
3217                            "adb fetch name %p: caching alias target",
3218                            name);
3219                         name->expire_target = dev->rdataset->ttl + now;
3220                 }
3221                 goto check_result;
3222         }
3223
3224         /*
3225          * Did we get back junk?  If so, and there are no more fetches
3226          * sitting out there, tell all the finds about it.
3227          */
3228         if (dev->result != ISC_R_SUCCESS) {
3229                 char buf[DNS_NAME_FORMATSIZE];
3230
3231                 dns_name_format(&name->name, buf, sizeof(buf));
3232                 DP(DEF_LEVEL, "adb: fetch of '%s' %s failed: %s",
3233                    buf, address_type == DNS_ADBFIND_INET ? "A" : "AAAA",
3234                    dns_result_totext(dev->result));
3235                 /* XXXMLG Don't pound on bad servers. */
3236                 if (address_type == DNS_ADBFIND_INET) {
3237                         name->expire_v4 = ISC_MIN(name->expire_v4, now + 300);
3238                         name->fetch_err = FIND_ERR_FAILURE;
3239                 } else {
3240                         name->expire_v6 = ISC_MIN(name->expire_v6, now + 300);
3241                         name->fetch6_err = FIND_ERR_FAILURE;
3242                 }
3243                 goto out;
3244         }
3245
3246         /*
3247          * We got something potentially useful.
3248          */
3249         result = import_rdataset(name, &fetch->rdataset, now);
3250
3251  check_result:
3252         if (result == ISC_R_SUCCESS) {
3253                 ev_status = DNS_EVENT_ADBMOREADDRESSES;
3254                 if (address_type == DNS_ADBFIND_INET)
3255                         name->fetch_err = FIND_ERR_SUCCESS;
3256                 else
3257                         name->fetch6_err = FIND_ERR_SUCCESS;
3258         }
3259
3260  out:
3261         free_adbfetch(adb, &fetch);
3262         isc_event_free(&ev);
3263
3264         clean_finds_at_name(name, ev_status, address_type);
3265
3266         UNLOCK(&adb->namelocks[bucket]);
3267 }
3268
3269 static isc_result_t
3270 fetch_name(dns_adbname_t *adbname,
3271            isc_boolean_t start_at_zone,
3272            dns_rdatatype_t type)
3273 {
3274         isc_result_t result;
3275         dns_adbfetch_t *fetch = NULL;
3276         dns_adb_t *adb;
3277         dns_fixedname_t fixed;
3278         dns_name_t *name;
3279         dns_rdataset_t rdataset;
3280         dns_rdataset_t *nameservers;
3281         unsigned int options;
3282
3283         INSIST(DNS_ADBNAME_VALID(adbname));
3284         adb = adbname->adb;
3285         INSIST(DNS_ADB_VALID(adb));
3286
3287         INSIST((type == dns_rdatatype_a && !NAME_FETCH_V4(adbname)) ||
3288                (type == dns_rdatatype_aaaa && !NAME_FETCH_V6(adbname)));
3289
3290         adbname->fetch_err = FIND_ERR_NOTFOUND;
3291
3292         name = NULL;
3293         nameservers = NULL;
3294         dns_rdataset_init(&rdataset);
3295
3296         options = DNS_FETCHOPT_NOVALIDATE;
3297         if (start_at_zone) {
3298                 DP(ENTER_LEVEL,
3299                    "fetch_name: starting at zone for name %p",
3300                    adbname);
3301                 dns_fixedname_init(&fixed);
3302                 name = dns_fixedname_name(&fixed);
3303                 result = dns_view_findzonecut2(adb->view, &adbname->name, name,
3304                                                0, 0, ISC_TRUE, ISC_FALSE,
3305                                                &rdataset, NULL);
3306                 if (result != ISC_R_SUCCESS && result != DNS_R_HINT)
3307                         goto cleanup;
3308                 nameservers = &rdataset;
3309                 options |= DNS_FETCHOPT_UNSHARED;
3310         }
3311
3312         fetch = new_adbfetch(adb);
3313         if (fetch == NULL) {
3314                 result = ISC_R_NOMEMORY;
3315                 goto cleanup;
3316         }
3317
3318         result = dns_resolver_createfetch(adb->view->resolver, &adbname->name,
3319                                           type, name, nameservers, NULL,
3320                                           options, adb->task, fetch_callback,
3321                                           adbname, &fetch->rdataset, NULL,
3322                                           &fetch->fetch);
3323         if (result != ISC_R_SUCCESS)
3324                 goto cleanup;
3325
3326         if (type == dns_rdatatype_a)
3327                 adbname->fetch_a = fetch;
3328         else
3329                 adbname->fetch_aaaa = fetch;
3330         fetch = NULL;  /* Keep us from cleaning this up below. */
3331
3332  cleanup:
3333         if (fetch != NULL)
3334                 free_adbfetch(adb, &fetch);
3335         if (dns_rdataset_isassociated(&rdataset))
3336                 dns_rdataset_disassociate(&rdataset);
3337
3338         return (result);
3339 }
3340
3341 /*
3342  * XXXMLG Needs to take a find argument and an address info, no zone or adb,
3343  * since these can be extracted from the find itself.
3344  */
3345 isc_result_t
3346 dns_adb_marklame(dns_adb_t *adb, dns_adbaddrinfo_t *addr, dns_name_t *qname,
3347                  dns_rdatatype_t qtype, isc_stdtime_t expire_time)
3348 {
3349         dns_adblameinfo_t *li;
3350         int bucket;
3351         isc_result_t result = ISC_R_SUCCESS;
3352
3353         REQUIRE(DNS_ADB_VALID(adb));
3354         REQUIRE(DNS_ADBADDRINFO_VALID(addr));
3355         REQUIRE(qname != NULL);
3356
3357         bucket = addr->entry->lock_bucket;
3358         LOCK(&adb->entrylocks[bucket]);
3359         li = ISC_LIST_HEAD(addr->entry->lameinfo);
3360         while (li != NULL &&
3361                (li->qtype != qtype || !dns_name_equal(qname, &li->qname)))
3362                 li = ISC_LIST_NEXT(li, plink);
3363         if (li != NULL) {
3364                 if (expire_time > li->lame_timer)
3365                         li->lame_timer = expire_time;
3366                 goto unlock;
3367         }
3368         li = new_adblameinfo(adb, qname, qtype);
3369         if (li == NULL) {
3370                 result = ISC_R_NOMEMORY;
3371                 goto unlock;
3372         }
3373
3374         li->lame_timer = expire_time;
3375
3376         ISC_LIST_PREPEND(addr->entry->lameinfo, li, plink);
3377  unlock:
3378         UNLOCK(&adb->entrylocks[bucket]);
3379
3380         return (result);
3381 }
3382
3383 void
3384 dns_adb_adjustsrtt(dns_adb_t *adb, dns_adbaddrinfo_t *addr,
3385                    unsigned int rtt, unsigned int factor)
3386 {
3387         int bucket;
3388         unsigned int new_srtt;
3389         isc_stdtime_t now;
3390
3391         REQUIRE(DNS_ADB_VALID(adb));
3392         REQUIRE(DNS_ADBADDRINFO_VALID(addr));
3393         REQUIRE(factor <= 10);
3394
3395         bucket = addr->entry->lock_bucket;
3396         LOCK(&adb->entrylocks[bucket]);
3397
3398         if (factor == DNS_ADB_RTTADJAGE)
3399                 new_srtt = addr->entry->srtt * 98 / 100;
3400         else
3401                 new_srtt = (addr->entry->srtt / 10 * factor)
3402                         + (rtt / 10 * (10 - factor));
3403
3404         addr->entry->srtt = new_srtt;
3405         addr->srtt = new_srtt;
3406
3407         isc_stdtime_get(&now);
3408         addr->entry->expires = now + ADB_ENTRY_WINDOW;
3409
3410         UNLOCK(&adb->entrylocks[bucket]);
3411 }
3412
3413 void
3414 dns_adb_changeflags(dns_adb_t *adb, dns_adbaddrinfo_t *addr,
3415                     unsigned int bits, unsigned int mask)
3416 {
3417         int bucket;
3418
3419         REQUIRE(DNS_ADB_VALID(adb));
3420         REQUIRE(DNS_ADBADDRINFO_VALID(addr));
3421
3422         bucket = addr->entry->lock_bucket;
3423         LOCK(&adb->entrylocks[bucket]);
3424
3425         addr->entry->flags = (addr->entry->flags & ~mask) | (bits & mask);
3426         /*
3427          * Note that we do not update the other bits in addr->flags with
3428          * the most recent values from addr->entry->flags.
3429          */
3430         addr->flags = (addr->flags & ~mask) | (bits & mask);
3431
3432         UNLOCK(&adb->entrylocks[bucket]);
3433 }
3434
3435 isc_result_t
3436 dns_adb_findaddrinfo(dns_adb_t *adb, isc_sockaddr_t *sa,
3437                      dns_adbaddrinfo_t **addrp, isc_stdtime_t now)
3438 {
3439         int bucket;
3440         dns_adbentry_t *entry;
3441         dns_adbaddrinfo_t *addr;
3442         isc_result_t result;
3443         in_port_t port;
3444
3445         REQUIRE(DNS_ADB_VALID(adb));
3446         REQUIRE(addrp != NULL && *addrp == NULL);
3447
3448         UNUSED(now);
3449
3450         result = ISC_R_SUCCESS;
3451         bucket = DNS_ADB_INVALIDBUCKET;
3452         entry = find_entry_and_lock(adb, sa, &bucket);
3453         if (adb->entry_sd[bucket]) {
3454                 result = ISC_R_SHUTTINGDOWN;
3455                 goto unlock;
3456         }
3457         if (entry == NULL) {
3458                 /*
3459                  * We don't know anything about this address.
3460                  */
3461                 entry = new_adbentry(adb);
3462                 if (entry == NULL) {
3463                         result = ISC_R_NOMEMORY;
3464                         goto unlock;
3465                 }
3466                 entry->sockaddr = *sa;
3467                 link_entry(adb, bucket, entry);
3468                 DP(ENTER_LEVEL, "findaddrinfo: new entry %p", entry);
3469         } else
3470                 DP(ENTER_LEVEL, "findaddrinfo: found entry %p", entry);
3471
3472         port = isc_sockaddr_getport(sa);
3473         addr = new_adbaddrinfo(adb, entry, port);
3474         if (addr == NULL) {
3475                 result = ISC_R_NOMEMORY;
3476         } else {
3477                 inc_entry_refcnt(adb, entry, ISC_FALSE);
3478                 *addrp = addr;
3479         }
3480
3481  unlock:
3482         UNLOCK(&adb->entrylocks[bucket]);
3483
3484         return (result);
3485 }
3486
3487 void
3488 dns_adb_freeaddrinfo(dns_adb_t *adb, dns_adbaddrinfo_t **addrp) {
3489         dns_adbaddrinfo_t *addr;
3490         dns_adbentry_t *entry;
3491         int bucket;
3492         isc_stdtime_t now;
3493         isc_boolean_t want_check_exit = ISC_FALSE;
3494
3495         REQUIRE(DNS_ADB_VALID(adb));
3496         REQUIRE(addrp != NULL);
3497         addr = *addrp;
3498         REQUIRE(DNS_ADBADDRINFO_VALID(addr));
3499         entry = addr->entry;
3500         REQUIRE(DNS_ADBENTRY_VALID(entry));
3501
3502         isc_stdtime_get(&now);
3503
3504         *addrp = NULL;
3505
3506         bucket = addr->entry->lock_bucket;
3507         LOCK(&adb->entrylocks[bucket]);
3508
3509         entry->expires = now + ADB_ENTRY_WINDOW;
3510
3511         want_check_exit = dec_entry_refcnt(adb, entry, ISC_FALSE);
3512
3513         UNLOCK(&adb->entrylocks[bucket]);
3514
3515         addr->entry = NULL;
3516         free_adbaddrinfo(adb, &addr);
3517
3518         if (want_check_exit) {
3519                 LOCK(&adb->lock);
3520                 check_exit(adb);
3521                 UNLOCK(&adb->lock);
3522         }
3523 }
3524
3525 void
3526 dns_adb_flush(dns_adb_t *adb) {
3527         unsigned int i;
3528
3529         INSIST(DNS_ADB_VALID(adb));
3530
3531         LOCK(&adb->lock);
3532
3533         /*
3534          * Call our cleanup routines.
3535          */
3536         for (i = 0; i < NBUCKETS; i++)
3537                 RUNTIME_CHECK(cleanup_names(adb, i, INT_MAX) == ISC_FALSE);
3538         for (i = 0; i < NBUCKETS; i++)
3539                 RUNTIME_CHECK(cleanup_entries(adb, i, INT_MAX) == ISC_FALSE);
3540
3541 #ifdef DUMP_ADB_AFTER_CLEANING
3542         dump_adb(adb, stdout, ISC_TRUE, INT_MAX);
3543 #endif
3544
3545         UNLOCK(&adb->lock);
3546 }
3547
3548 void
3549 dns_adb_flushname(dns_adb_t *adb, dns_name_t *name) {
3550         dns_adbname_t *adbname;
3551         dns_adbname_t *nextname;
3552         int bucket;
3553
3554         INSIST(DNS_ADB_VALID(adb));
3555
3556         LOCK(&adb->lock);
3557         bucket = dns_name_hash(name, ISC_FALSE) % NBUCKETS;
3558         LOCK(&adb->namelocks[bucket]);
3559         adbname = ISC_LIST_HEAD(adb->names[bucket]);
3560         while (adbname != NULL) {
3561                 nextname = ISC_LIST_NEXT(adbname, plink);
3562                 if (!NAME_DEAD(adbname) &&
3563                     dns_name_equal(name, &adbname->name)) {
3564                         RUNTIME_CHECK(kill_name(&adbname,
3565                                                 DNS_EVENT_ADBCANCELED) ==
3566                                       ISC_FALSE);
3567                 }
3568                 adbname = nextname;
3569         }
3570         UNLOCK(&adb->namelocks[bucket]);
3571         UNLOCK(&adb->lock);
3572 }
3573
3574 static void
3575 water(void *arg, int mark) {
3576         dns_adb_t *adb = arg;
3577         isc_boolean_t overmem = ISC_TF(mark == ISC_MEM_HIWATER);
3578         isc_interval_t interval;
3579
3580         REQUIRE(DNS_ADB_VALID(adb));
3581
3582         DP(ISC_LOG_DEBUG(1),
3583            "adb reached %s water mark", overmem ? "high" : "low");
3584
3585         adb->overmem = overmem;
3586         if (overmem) {
3587                 isc_interval_set(&interval, 0, 1);
3588                 (void)isc_timer_reset(adb->timer, isc_timertype_once, NULL,
3589                                       &interval, ISC_TRUE);
3590         }
3591 }
3592
3593 void
3594 dns_adb_setadbsize(dns_adb_t *adb, isc_uint32_t size) {
3595         isc_uint32_t hiwater;
3596         isc_uint32_t lowater;
3597
3598         INSIST(DNS_ADB_VALID(adb));
3599
3600         if (size != 0 && size < DNS_ADB_MINADBSIZE)
3601                 size = DNS_ADB_MINADBSIZE;
3602
3603         hiwater = size - (size >> 3);   /* Approximately 7/8ths. */
3604         lowater = size - (size >> 2);   /* Approximately 3/4ths. */
3605
3606         if (size == 0 || hiwater == 0 || lowater == 0)
3607                 isc_mem_setwater(adb->mctx, water, adb, 0, 0);
3608         else
3609                 isc_mem_setwater(adb->mctx, water, adb, hiwater, lowater);
3610 }