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