]> CyberLeo.Net >> Repos - FreeBSD/releng/8.1.git/blob - contrib/bind9/lib/dns/resolver.c
Copy stable/8 to releng/8.1 in preparation for 8.1-RC1.
[FreeBSD/releng/8.1.git] / contrib / bind9 / lib / dns / resolver.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: resolver.c,v 1.384.14.20.8.2 2010/02/25 10:57:12 tbox Exp $ */
19
20 /*! \file */
21
22 #include <config.h>
23
24 #include <isc/platform.h>
25 #include <isc/print.h>
26 #include <isc/string.h>
27 #include <isc/random.h>
28 #include <isc/task.h>
29 #include <isc/stats.h>
30 #include <isc/timer.h>
31 #include <isc/util.h>
32
33 #include <dns/acl.h>
34 #include <dns/adb.h>
35 #include <dns/cache.h>
36 #include <dns/db.h>
37 #include <dns/dispatch.h>
38 #include <dns/ds.h>
39 #include <dns/events.h>
40 #include <dns/forward.h>
41 #include <dns/keytable.h>
42 #include <dns/log.h>
43 #include <dns/message.h>
44 #include <dns/ncache.h>
45 #include <dns/opcode.h>
46 #include <dns/peer.h>
47 #include <dns/rbt.h>
48 #include <dns/rcode.h>
49 #include <dns/rdata.h>
50 #include <dns/rdataclass.h>
51 #include <dns/rdatalist.h>
52 #include <dns/rdataset.h>
53 #include <dns/rdatastruct.h>
54 #include <dns/rdatatype.h>
55 #include <dns/resolver.h>
56 #include <dns/result.h>
57 #include <dns/rootns.h>
58 #include <dns/stats.h>
59 #include <dns/tsig.h>
60 #include <dns/validator.h>
61
62 #define DNS_RESOLVER_TRACE
63 #ifdef DNS_RESOLVER_TRACE
64 #define RTRACE(m)       isc_log_write(dns_lctx, \
65                                       DNS_LOGCATEGORY_RESOLVER, \
66                                       DNS_LOGMODULE_RESOLVER, \
67                                       ISC_LOG_DEBUG(3), \
68                                       "res %p: %s", res, (m))
69 #define RRTRACE(r, m)   isc_log_write(dns_lctx, \
70                                       DNS_LOGCATEGORY_RESOLVER, \
71                                       DNS_LOGMODULE_RESOLVER, \
72                                       ISC_LOG_DEBUG(3), \
73                                       "res %p: %s", (r), (m))
74 #define FCTXTRACE(m)    isc_log_write(dns_lctx, \
75                                       DNS_LOGCATEGORY_RESOLVER, \
76                                       DNS_LOGMODULE_RESOLVER, \
77                                       ISC_LOG_DEBUG(3), \
78                                       "fctx %p(%s'): %s", fctx, fctx->info, (m))
79 #define FCTXTRACE2(m1, m2) \
80                         isc_log_write(dns_lctx, \
81                                       DNS_LOGCATEGORY_RESOLVER, \
82                                       DNS_LOGMODULE_RESOLVER, \
83                                       ISC_LOG_DEBUG(3), \
84                                       "fctx %p(%s): %s %s", \
85                                       fctx, fctx->info, (m1), (m2))
86 #define FTRACE(m)       isc_log_write(dns_lctx, \
87                                       DNS_LOGCATEGORY_RESOLVER, \
88                                       DNS_LOGMODULE_RESOLVER, \
89                                       ISC_LOG_DEBUG(3), \
90                                       "fetch %p (fctx %p(%s)): %s", \
91                                       fetch, fetch->private, \
92                                       fetch->private->info, (m))
93 #define QTRACE(m)       isc_log_write(dns_lctx, \
94                                       DNS_LOGCATEGORY_RESOLVER, \
95                                       DNS_LOGMODULE_RESOLVER, \
96                                       ISC_LOG_DEBUG(3), \
97                                       "resquery %p (fctx %p(%s)): %s", \
98                                       query, query->fctx, \
99                                       query->fctx->info, (m))
100 #else
101 #define RTRACE(m)
102 #define RRTRACE(r, m)
103 #define FCTXTRACE(m)
104 #define FTRACE(m)
105 #define QTRACE(m)
106 #endif
107
108 /*%
109  * Maximum EDNS0 input packet size.
110  */
111 #define RECV_BUFFER_SIZE                4096            /* XXXRTH  Constant. */
112
113 /*%
114  * This defines the maximum number of timeouts we will permit before we
115  * disable EDNS0 on the query.
116  */
117 #define MAX_EDNS0_TIMEOUTS      3
118
119 typedef struct fetchctx fetchctx_t;
120
121 typedef struct query {
122         /* Locked by task event serialization. */
123         unsigned int                    magic;
124         fetchctx_t *                    fctx;
125         isc_mem_t *                     mctx;
126         dns_dispatchmgr_t *             dispatchmgr;
127         dns_dispatch_t *                dispatch;
128         isc_boolean_t                   exclusivesocket;
129         dns_adbaddrinfo_t *             addrinfo;
130         isc_socket_t *                  tcpsocket;
131         isc_time_t                      start;
132         dns_messageid_t                 id;
133         dns_dispentry_t *               dispentry;
134         ISC_LINK(struct query)          link;
135         isc_buffer_t                    buffer;
136         isc_buffer_t                    *tsig;
137         dns_tsigkey_t                   *tsigkey;
138         unsigned int                    options;
139         unsigned int                    attributes;
140         unsigned int                    sends;
141         unsigned int                    connects;
142         unsigned char                   data[512];
143 } resquery_t;
144
145 #define QUERY_MAGIC                     ISC_MAGIC('Q', '!', '!', '!')
146 #define VALID_QUERY(query)              ISC_MAGIC_VALID(query, QUERY_MAGIC)
147
148 #define RESQUERY_ATTR_CANCELED          0x02
149
150 #define RESQUERY_CONNECTING(q)          ((q)->connects > 0)
151 #define RESQUERY_CANCELED(q)            (((q)->attributes & \
152                                           RESQUERY_ATTR_CANCELED) != 0)
153 #define RESQUERY_SENDING(q)             ((q)->sends > 0)
154
155 typedef enum {
156         fetchstate_init = 0,            /*%< Start event has not run yet. */
157         fetchstate_active,
158         fetchstate_done                 /*%< FETCHDONE events posted. */
159 } fetchstate;
160
161 typedef enum {
162         badns_unreachable = 0,
163         badns_response,
164         badns_validation
165 } badnstype_t;
166
167 struct fetchctx {
168         /*% Not locked. */
169         unsigned int                    magic;
170         dns_resolver_t *                res;
171         dns_name_t                      name;
172         dns_rdatatype_t                 type;
173         unsigned int                    options;
174         unsigned int                    bucketnum;
175         char *                  info;
176         /*% Locked by appropriate bucket lock. */
177         fetchstate                      state;
178         isc_boolean_t                   want_shutdown;
179         isc_boolean_t                   cloned;
180         isc_boolean_t                   spilled;
181         unsigned int                    references;
182         isc_event_t                     control_event;
183         ISC_LINK(struct fetchctx)       link;
184         ISC_LIST(dns_fetchevent_t)      events;
185         /*% Locked by task event serialization. */
186         dns_name_t                      domain;
187         dns_rdataset_t                  nameservers;
188         unsigned int                    attributes;
189         isc_timer_t *                   timer;
190         isc_time_t                      expires;
191         isc_interval_t                  interval;
192         dns_message_t *                 qmessage;
193         dns_message_t *                 rmessage;
194         ISC_LIST(resquery_t)            queries;
195         dns_adbfindlist_t               finds;
196         dns_adbfind_t *                 find;
197         dns_adbfindlist_t               altfinds;
198         dns_adbfind_t *                 altfind;
199         dns_adbaddrinfolist_t           forwaddrs;
200         dns_adbaddrinfolist_t           altaddrs;
201         isc_sockaddrlist_t              forwarders;
202         dns_fwdpolicy_t                 fwdpolicy;
203         isc_sockaddrlist_t              bad;
204         isc_sockaddrlist_t              edns;
205         isc_sockaddrlist_t              edns512;
206         dns_validator_t                 *validator;
207         ISC_LIST(dns_validator_t)       validators;
208         dns_db_t *                      cache;
209         dns_adb_t *                     adb;
210
211         /*%
212          * The number of events we're waiting for.
213          */
214         unsigned int                    pending;
215
216         /*%
217          * The number of times we've "restarted" the current
218          * nameserver set.  This acts as a failsafe to prevent
219          * us from pounding constantly on a particular set of
220          * servers that, for whatever reason, are not giving
221          * us useful responses, but are responding in such a
222          * way that they are not marked "bad".
223          */
224         unsigned int                    restarts;
225
226         /*%
227          * The number of timeouts that have occurred since we
228          * last successfully received a response packet.  This
229          * is used for EDNS0 black hole detection.
230          */
231         unsigned int                    timeouts;
232
233         /*%
234          * Look aside state for DS lookups.
235          */
236         dns_name_t                      nsname;
237         dns_fetch_t *                   nsfetch;
238         dns_rdataset_t                  nsrrset;
239
240         /*%
241          * Number of queries that reference this context.
242          */
243         unsigned int                    nqueries;
244
245         /*%
246          * The reason to print when logging a successful
247          * response to a query.
248          */
249         const char *                    reason;
250
251         /*%
252          * Random numbers to use for mixing up server addresses.
253          */
254         isc_uint32_t                    rand_buf;
255         isc_uint32_t                    rand_bits;
256
257         /*%
258          * Fetch-local statistics for detailed logging.
259          */
260         isc_result_t                    result; /*%< fetch result  */
261         isc_result_t                    vresult; /*%< validation result  */
262         int                             exitline;
263         isc_time_t                      start;
264         isc_uint64_t                    duration;
265         isc_boolean_t                   logged;
266         unsigned int                    querysent;
267         unsigned int                    referrals;
268         unsigned int                    lamecount;
269         unsigned int                    neterr;
270         unsigned int                    badresp;
271         unsigned int                    adberr;
272         unsigned int                    findfail;
273         unsigned int                    valfail;
274         isc_boolean_t                   timeout;
275 };
276
277 #define FCTX_MAGIC                      ISC_MAGIC('F', '!', '!', '!')
278 #define VALID_FCTX(fctx)                ISC_MAGIC_VALID(fctx, FCTX_MAGIC)
279
280 #define FCTX_ATTR_HAVEANSWER            0x0001
281 #define FCTX_ATTR_GLUING                0x0002
282 #define FCTX_ATTR_ADDRWAIT              0x0004
283 #define FCTX_ATTR_SHUTTINGDOWN          0x0008
284 #define FCTX_ATTR_WANTCACHE             0x0010
285 #define FCTX_ATTR_WANTNCACHE            0x0020
286 #define FCTX_ATTR_NEEDEDNS0             0x0040
287 #define FCTX_ATTR_TRIEDFIND             0x0080
288 #define FCTX_ATTR_TRIEDALT              0x0100
289
290 #define HAVE_ANSWER(f)          (((f)->attributes & FCTX_ATTR_HAVEANSWER) != \
291                                  0)
292 #define GLUING(f)               (((f)->attributes & FCTX_ATTR_GLUING) != \
293                                  0)
294 #define ADDRWAIT(f)             (((f)->attributes & FCTX_ATTR_ADDRWAIT) != \
295                                  0)
296 #define SHUTTINGDOWN(f)         (((f)->attributes & FCTX_ATTR_SHUTTINGDOWN) \
297                                  != 0)
298 #define WANTCACHE(f)            (((f)->attributes & FCTX_ATTR_WANTCACHE) != 0)
299 #define WANTNCACHE(f)           (((f)->attributes & FCTX_ATTR_WANTNCACHE) != 0)
300 #define NEEDEDNS0(f)            (((f)->attributes & FCTX_ATTR_NEEDEDNS0) != 0)
301 #define TRIEDFIND(f)            (((f)->attributes & FCTX_ATTR_TRIEDFIND) != 0)
302 #define TRIEDALT(f)             (((f)->attributes & FCTX_ATTR_TRIEDALT) != 0)
303
304 typedef struct {
305         dns_adbaddrinfo_t *             addrinfo;
306         fetchctx_t *                    fctx;
307 } dns_valarg_t;
308
309 struct dns_fetch {
310         unsigned int                    magic;
311         fetchctx_t *                    private;
312 };
313
314 #define DNS_FETCH_MAGIC                 ISC_MAGIC('F', 't', 'c', 'h')
315 #define DNS_FETCH_VALID(fetch)          ISC_MAGIC_VALID(fetch, DNS_FETCH_MAGIC)
316
317 typedef struct fctxbucket {
318         isc_task_t *                    task;
319         isc_mutex_t                     lock;
320         ISC_LIST(fetchctx_t)            fctxs;
321         isc_boolean_t                   exiting;
322         isc_mem_t *                     mctx;
323 } fctxbucket_t;
324
325 typedef struct alternate {
326         isc_boolean_t                   isaddress;
327         union   {
328                 isc_sockaddr_t          addr;
329                 struct {
330                         dns_name_t      name;
331                         in_port_t       port;
332                 } _n;
333         } _u;
334         ISC_LINK(struct alternate)      link;
335 } alternate_t;
336
337 typedef struct dns_badcache dns_badcache_t;
338 struct dns_badcache {
339         dns_badcache_t *        next;
340         dns_rdatatype_t         type;
341         isc_time_t              expire;
342         unsigned int            hashval;
343         dns_name_t              name;
344 };
345 #define DNS_BADCACHE_SIZE 1021
346 #define DNS_BADCACHE_TTL(fctx) \
347         (((fctx)->res->lame_ttl > 30 ) ? (fctx)->res->lame_ttl : 30)
348
349 struct dns_resolver {
350         /* Unlocked. */
351         unsigned int                    magic;
352         isc_mem_t *                     mctx;
353         isc_mutex_t                     lock;
354         isc_mutex_t                     nlock;
355         isc_mutex_t                     primelock;
356         dns_rdataclass_t                rdclass;
357         isc_socketmgr_t *               socketmgr;
358         isc_timermgr_t *                timermgr;
359         isc_taskmgr_t *                 taskmgr;
360         dns_view_t *                    view;
361         isc_boolean_t                   frozen;
362         unsigned int                    options;
363         dns_dispatchmgr_t *             dispatchmgr;
364         dns_dispatch_t *                dispatchv4;
365         isc_boolean_t                   exclusivev4;
366         dns_dispatch_t *                dispatchv6;
367         isc_boolean_t                   exclusivev6;
368         unsigned int                    ndisps;
369         unsigned int                    nbuckets;
370         fctxbucket_t *                  buckets;
371         isc_uint32_t                    lame_ttl;
372         ISC_LIST(alternate_t)           alternates;
373         isc_uint16_t                    udpsize;
374 #if USE_ALGLOCK
375         isc_rwlock_t                    alglock;
376 #endif
377         dns_rbt_t *                     algorithms;
378 #if USE_MBSLOCK
379         isc_rwlock_t                    mbslock;
380 #endif
381         dns_rbt_t *                     mustbesecure;
382         unsigned int                    spillatmax;
383         unsigned int                    spillatmin;
384         isc_timer_t *                   spillattimer;
385         isc_boolean_t                   zero_no_soa_ttl;
386
387         /* Locked by lock. */
388         unsigned int                    references;
389         isc_boolean_t                   exiting;
390         isc_eventlist_t                 whenshutdown;
391         unsigned int                    activebuckets;
392         isc_boolean_t                   priming;
393         unsigned int                    spillat;        /* clients-per-query */
394         unsigned int                    nextdisp;
395
396         /* Bad cache. */
397         dns_badcache_t  **              badcache;
398         unsigned int                    badcount;
399         unsigned int                    badhash;
400         unsigned int                    badsweep;
401
402         /* Locked by primelock. */
403         dns_fetch_t *                   primefetch;
404         /* Locked by nlock. */
405         unsigned int                    nfctx;
406 };
407
408 #define RES_MAGIC                       ISC_MAGIC('R', 'e', 's', '!')
409 #define VALID_RESOLVER(res)             ISC_MAGIC_VALID(res, RES_MAGIC)
410
411 /*%
412  * Private addrinfo flags.  These must not conflict with DNS_FETCHOPT_NOEDNS0,
413  * which we also use as an addrinfo flag.
414  */
415 #define FCTX_ADDRINFO_MARK              0x0001
416 #define FCTX_ADDRINFO_FORWARDER         0x1000
417 #define FCTX_ADDRINFO_TRIED             0x2000
418 #define UNMARKED(a)                     (((a)->flags & FCTX_ADDRINFO_MARK) \
419                                          == 0)
420 #define ISFORWARDER(a)                  (((a)->flags & \
421                                          FCTX_ADDRINFO_FORWARDER) != 0)
422 #define TRIED(a)                        (((a)->flags & \
423                                          FCTX_ADDRINFO_TRIED) != 0)
424
425 #define NXDOMAIN(r) (((r)->attributes & DNS_RDATASETATTR_NXDOMAIN) != 0)
426
427 static void destroy(dns_resolver_t *res);
428 static void empty_bucket(dns_resolver_t *res);
429 static isc_result_t resquery_send(resquery_t *query);
430 static void resquery_response(isc_task_t *task, isc_event_t *event);
431 static void resquery_connected(isc_task_t *task, isc_event_t *event);
432 static void fctx_try(fetchctx_t *fctx, isc_boolean_t retrying,
433                      isc_boolean_t badcache);
434 static isc_boolean_t fctx_destroy(fetchctx_t *fctx);
435 static isc_result_t ncache_adderesult(dns_message_t *message,
436                                       dns_db_t *cache, dns_dbnode_t *node,
437                                       dns_rdatatype_t covers,
438                                       isc_stdtime_t now, dns_ttl_t maxttl,
439                                       isc_boolean_t optout,
440                                       dns_rdataset_t *ardataset,
441                                       isc_result_t *eresultp);
442 static void validated(isc_task_t *task, isc_event_t *event);
443 static void maybe_destroy(fetchctx_t *fctx);
444 static void add_bad(fetchctx_t *fctx, dns_adbaddrinfo_t *addrinfo,
445                     isc_result_t reason, badnstype_t badtype);
446
447 /*%
448  * Increment resolver-related statistics counters.
449  */
450 static inline void
451 inc_stats(dns_resolver_t *res, isc_statscounter_t counter) {
452         if (res->view->resstats != NULL)
453                 isc_stats_increment(res->view->resstats, counter);
454 }
455
456 static isc_result_t
457 valcreate(fetchctx_t *fctx, dns_adbaddrinfo_t *addrinfo, dns_name_t *name,
458           dns_rdatatype_t type, dns_rdataset_t *rdataset,
459           dns_rdataset_t *sigrdataset, unsigned int valoptions,
460           isc_task_t *task)
461 {
462         dns_validator_t *validator = NULL;
463         dns_valarg_t *valarg;
464         isc_result_t result;
465
466         valarg = isc_mem_get(fctx->res->buckets[fctx->bucketnum].mctx,
467                              sizeof(*valarg));
468         if (valarg == NULL)
469                 return (ISC_R_NOMEMORY);
470
471         valarg->fctx = fctx;
472         valarg->addrinfo = addrinfo;
473
474         if (!ISC_LIST_EMPTY(fctx->validators))
475                 INSIST((valoptions & DNS_VALIDATOR_DEFER) != 0);
476
477         result = dns_validator_create(fctx->res->view, name, type, rdataset,
478                                       sigrdataset, fctx->rmessage,
479                                       valoptions, task, validated, valarg,
480                                       &validator);
481         if (result == ISC_R_SUCCESS) {
482                 inc_stats(fctx->res, dns_resstatscounter_val);
483                 if ((valoptions & DNS_VALIDATOR_DEFER) == 0) {
484                         INSIST(fctx->validator == NULL);
485                         fctx->validator  = validator;
486                 }
487                 ISC_LIST_APPEND(fctx->validators, validator, link);
488         } else
489                 isc_mem_put(fctx->res->buckets[fctx->bucketnum].mctx,
490                             valarg, sizeof(*valarg));
491         return (result);
492 }
493
494 static isc_boolean_t
495 rrsig_fromchildzone(fetchctx_t *fctx, dns_rdataset_t *rdataset) {
496         dns_namereln_t namereln;
497         dns_rdata_rrsig_t rrsig;
498         dns_rdata_t rdata = DNS_RDATA_INIT;
499         int order;
500         isc_result_t result;
501         unsigned int labels;
502
503         for (result = dns_rdataset_first(rdataset);
504              result == ISC_R_SUCCESS;
505              result = dns_rdataset_next(rdataset)) {
506                 dns_rdataset_current(rdataset, &rdata);
507                 result = dns_rdata_tostruct(&rdata, &rrsig, NULL);
508                 RUNTIME_CHECK(result == ISC_R_SUCCESS);
509                 namereln = dns_name_fullcompare(&rrsig.signer, &fctx->domain,
510                                                 &order, &labels);
511                 if (namereln == dns_namereln_subdomain)
512                         return (ISC_TRUE);
513                 dns_rdata_reset(&rdata);
514         }
515         return (ISC_FALSE);
516 }
517
518 static isc_boolean_t
519 fix_mustbedelegationornxdomain(dns_message_t *message, fetchctx_t *fctx) {
520         dns_name_t *name;
521         dns_name_t *domain = &fctx->domain;
522         dns_rdataset_t *rdataset;
523         dns_rdatatype_t type;
524         isc_result_t result;
525         isc_boolean_t keep_auth = ISC_FALSE;
526
527         if (message->rcode == dns_rcode_nxdomain)
528                 return (ISC_FALSE);
529
530         /*
531          * A DS RRset can appear anywhere in a zone, even for a delegation-only
532          * zone.  So a response to an explicit query for this type should be
533          * excluded from delegation-only fixup.
534          *
535          * SOA, NS, and DNSKEY can only exist at a zone apex, so a postive
536          * response to a query for these types can never violate the
537          * delegation-only assumption: if the query name is below a
538          * zone cut, the response should normally be a referral, which should
539          * be accepted; if the query name is below a zone cut but the server
540          * happens to have authority for the zone of the query name, the
541          * response is a (non-referral) answer.  But this does not violate
542          * delegation-only because the query name must be in a different zone
543          * due to the "apex-only" nature of these types.  Note that if the
544          * remote server happens to have authority for a child zone of a
545          * delegation-only zone, we may still incorrectly "fix" the response
546          * with NXDOMAIN for queries for other types.  Unfortunately it's
547          * generally impossible to differentiate this case from violation of
548          * the delegation-only assumption.  Once the resolver learns the
549          * correct zone cut, possibly via a separate query for an "apex-only"
550          * type, queries for other types will be resolved correctly.
551          *
552          * A query for type ANY will be accepted if it hits an exceptional
553          * type above in the answer section as it should be from a child
554          * zone.
555          *
556          * Also accept answers with RRSIG records from the child zone.
557          * Direct queries for RRSIG records should not be answered from
558          * the parent zone.
559          */
560
561         if (message->counts[DNS_SECTION_ANSWER] != 0 &&
562             (fctx->type == dns_rdatatype_ns ||
563              fctx->type == dns_rdatatype_ds ||
564              fctx->type == dns_rdatatype_soa ||
565              fctx->type == dns_rdatatype_any ||
566              fctx->type == dns_rdatatype_rrsig ||
567              fctx->type == dns_rdatatype_dnskey)) {
568                 result = dns_message_firstname(message, DNS_SECTION_ANSWER);
569                 while (result == ISC_R_SUCCESS) {
570                         name = NULL;
571                         dns_message_currentname(message, DNS_SECTION_ANSWER,
572                                                 &name);
573                         for (rdataset = ISC_LIST_HEAD(name->list);
574                              rdataset != NULL;
575                              rdataset = ISC_LIST_NEXT(rdataset, link)) {
576                                 if (!dns_name_equal(name, &fctx->name))
577                                         continue;
578                                 type = rdataset->type;
579                                 /*
580                                  * RRsig from child?
581                                  */
582                                 if (type == dns_rdatatype_rrsig &&
583                                     rrsig_fromchildzone(fctx, rdataset))
584                                         return (ISC_FALSE);
585                                 /*
586                                  * Direct query for apex records or DS.
587                                  */
588                                 if (fctx->type == type &&
589                                     (type == dns_rdatatype_ds ||
590                                      type == dns_rdatatype_ns ||
591                                      type == dns_rdatatype_soa ||
592                                      type == dns_rdatatype_dnskey))
593                                         return (ISC_FALSE);
594                                 /*
595                                  * Indirect query for apex records or DS.
596                                  */
597                                 if (fctx->type == dns_rdatatype_any &&
598                                     (type == dns_rdatatype_ns ||
599                                      type == dns_rdatatype_ds ||
600                                      type == dns_rdatatype_soa ||
601                                      type == dns_rdatatype_dnskey))
602                                         return (ISC_FALSE);
603                         }
604                         result = dns_message_nextname(message,
605                                                       DNS_SECTION_ANSWER);
606                 }
607         }
608
609         /*
610          * A NODATA response to a DS query?
611          */
612         if (fctx->type == dns_rdatatype_ds &&
613             message->counts[DNS_SECTION_ANSWER] == 0)
614                 return (ISC_FALSE);
615
616         /* Look for referral or indication of answer from child zone? */
617         if (message->counts[DNS_SECTION_AUTHORITY] == 0)
618                 goto munge;
619
620         result = dns_message_firstname(message, DNS_SECTION_AUTHORITY);
621         while (result == ISC_R_SUCCESS) {
622                 name = NULL;
623                 dns_message_currentname(message, DNS_SECTION_AUTHORITY, &name);
624                 for (rdataset = ISC_LIST_HEAD(name->list);
625                      rdataset != NULL;
626                      rdataset = ISC_LIST_NEXT(rdataset, link)) {
627                         type = rdataset->type;
628                         if (type == dns_rdatatype_soa &&
629                             dns_name_equal(name, domain))
630                                 keep_auth = ISC_TRUE;
631
632                         if (type != dns_rdatatype_ns &&
633                             type != dns_rdatatype_soa &&
634                             type != dns_rdatatype_rrsig)
635                                 continue;
636
637                         if (type == dns_rdatatype_rrsig) {
638                                 if (rrsig_fromchildzone(fctx, rdataset))
639                                         return (ISC_FALSE);
640                                 else
641                                         continue;
642                         }
643
644                         /* NS or SOA records. */
645                         if (dns_name_equal(name, domain)) {
646                                 /*
647                                  * If a query for ANY causes a negative
648                                  * response, we can be sure that this is
649                                  * an empty node.  For other type of queries
650                                  * we cannot differentiate an empty node
651                                  * from a node that just doesn't have that
652                                  * type of record.  We only accept the former
653                                  * case.
654                                  */
655                                 if (message->counts[DNS_SECTION_ANSWER] == 0 &&
656                                     fctx->type == dns_rdatatype_any)
657                                         return (ISC_FALSE);
658                         } else if (dns_name_issubdomain(name, domain)) {
659                                 /* Referral or answer from child zone. */
660                                 return (ISC_FALSE);
661                         }
662                 }
663                 result = dns_message_nextname(message, DNS_SECTION_AUTHORITY);
664         }
665
666  munge:
667         message->rcode = dns_rcode_nxdomain;
668         message->counts[DNS_SECTION_ANSWER] = 0;
669         if (!keep_auth)
670                 message->counts[DNS_SECTION_AUTHORITY] = 0;
671         message->counts[DNS_SECTION_ADDITIONAL] = 0;
672         return (ISC_TRUE);
673 }
674
675 static inline isc_result_t
676 fctx_starttimer(fetchctx_t *fctx) {
677         /*
678          * Start the lifetime timer for fctx.
679          *
680          * This is also used for stopping the idle timer; in that
681          * case we must purge events already posted to ensure that
682          * no further idle events are delivered.
683          */
684         return (isc_timer_reset(fctx->timer, isc_timertype_once,
685                                 &fctx->expires, NULL, ISC_TRUE));
686 }
687
688 static inline void
689 fctx_stoptimer(fetchctx_t *fctx) {
690         isc_result_t result;
691
692         /*
693          * We don't return a result if resetting the timer to inactive fails
694          * since there's nothing to be done about it.  Resetting to inactive
695          * should never fail anyway, since the code as currently written
696          * cannot fail in that case.
697          */
698         result = isc_timer_reset(fctx->timer, isc_timertype_inactive,
699                                   NULL, NULL, ISC_TRUE);
700         if (result != ISC_R_SUCCESS) {
701                 UNEXPECTED_ERROR(__FILE__, __LINE__,
702                                  "isc_timer_reset(): %s",
703                                  isc_result_totext(result));
704         }
705 }
706
707
708 static inline isc_result_t
709 fctx_startidletimer(fetchctx_t *fctx, isc_interval_t *interval) {
710         /*
711          * Start the idle timer for fctx.  The lifetime timer continues
712          * to be in effect.
713          */
714         return (isc_timer_reset(fctx->timer, isc_timertype_once,
715                                 &fctx->expires, interval, ISC_FALSE));
716 }
717
718 /*
719  * Stopping the idle timer is equivalent to calling fctx_starttimer(), but
720  * we use fctx_stopidletimer for readability in the code below.
721  */
722 #define fctx_stopidletimer      fctx_starttimer
723
724
725 static inline void
726 resquery_destroy(resquery_t **queryp) {
727         resquery_t *query;
728
729         REQUIRE(queryp != NULL);
730         query = *queryp;
731         REQUIRE(!ISC_LINK_LINKED(query, link));
732
733         INSIST(query->tcpsocket == NULL);
734
735         query->fctx->nqueries--;
736         if (SHUTTINGDOWN(query->fctx))
737                 maybe_destroy(query->fctx);     /* Locks bucket. */
738         query->magic = 0;
739         isc_mem_put(query->mctx, query, sizeof(*query));
740         *queryp = NULL;
741 }
742
743 static void
744 fctx_cancelquery(resquery_t **queryp, dns_dispatchevent_t **deventp,
745                  isc_time_t *finish, isc_boolean_t no_response)
746 {
747         fetchctx_t *fctx;
748         resquery_t *query;
749         unsigned int rtt, rttms;
750         unsigned int factor;
751         dns_adbfind_t *find;
752         dns_adbaddrinfo_t *addrinfo;
753         isc_socket_t *socket;
754
755         query = *queryp;
756         fctx = query->fctx;
757
758         FCTXTRACE("cancelquery");
759
760         REQUIRE(!RESQUERY_CANCELED(query));
761
762         query->attributes |= RESQUERY_ATTR_CANCELED;
763
764         /*
765          * Should we update the RTT?
766          */
767         if (finish != NULL || no_response) {
768                 if (finish != NULL) {
769                         /*
770                          * We have both the start and finish times for this
771                          * packet, so we can compute a real RTT.
772                          */
773                         rtt = (unsigned int)isc_time_microdiff(finish,
774                                                                &query->start);
775                         factor = DNS_ADB_RTTADJDEFAULT;
776
777                         rttms = rtt / 1000;
778                         if (rttms < DNS_RESOLVER_QRYRTTCLASS0) {
779                                 inc_stats(fctx->res,
780                                           dns_resstatscounter_queryrtt0);
781                         } else if (rttms < DNS_RESOLVER_QRYRTTCLASS1) {
782                                 inc_stats(fctx->res,
783                                           dns_resstatscounter_queryrtt1);
784                         } else if (rttms < DNS_RESOLVER_QRYRTTCLASS2) {
785                                 inc_stats(fctx->res,
786                                           dns_resstatscounter_queryrtt2);
787                         } else if (rttms < DNS_RESOLVER_QRYRTTCLASS3) {
788                                 inc_stats(fctx->res,
789                                           dns_resstatscounter_queryrtt3);
790                         } else if (rttms < DNS_RESOLVER_QRYRTTCLASS4) {
791                                 inc_stats(fctx->res,
792                                           dns_resstatscounter_queryrtt4);
793                         } else {
794                                 inc_stats(fctx->res,
795                                           dns_resstatscounter_queryrtt5);
796                         }
797                 } else {
798                         /*
799                          * We don't have an RTT for this query.  Maybe the
800                          * packet was lost, or maybe this server is very
801                          * slow.  We don't know.  Increase the RTT.
802                          */
803                         INSIST(no_response);
804                         rtt = query->addrinfo->srtt + 200000;
805                         if (rtt > 10000000)
806                                 rtt = 10000000;
807                         /*
808                          * Replace the current RTT with our value.
809                          */
810                         factor = DNS_ADB_RTTADJREPLACE;
811                 }
812                 dns_adb_adjustsrtt(fctx->adb, query->addrinfo, rtt, factor);
813         }
814
815         /* Remember that the server has been tried. */
816         if (!TRIED(query->addrinfo)) {
817                 dns_adb_changeflags(fctx->adb, query->addrinfo,
818                                     FCTX_ADDRINFO_TRIED, FCTX_ADDRINFO_TRIED);
819         }
820
821         /*
822          * Age RTTs of servers not tried.
823          */
824         factor = DNS_ADB_RTTADJAGE;
825         if (finish != NULL)
826                 for (addrinfo = ISC_LIST_HEAD(fctx->forwaddrs);
827                      addrinfo != NULL;
828                      addrinfo = ISC_LIST_NEXT(addrinfo, publink))
829                         if (UNMARKED(addrinfo))
830                                 dns_adb_adjustsrtt(fctx->adb, addrinfo,
831                                                    0, factor);
832
833         if (finish != NULL && TRIEDFIND(fctx))
834                 for (find = ISC_LIST_HEAD(fctx->finds);
835                      find != NULL;
836                      find = ISC_LIST_NEXT(find, publink))
837                         for (addrinfo = ISC_LIST_HEAD(find->list);
838                              addrinfo != NULL;
839                              addrinfo = ISC_LIST_NEXT(addrinfo, publink))
840                                 if (UNMARKED(addrinfo))
841                                         dns_adb_adjustsrtt(fctx->adb, addrinfo,
842                                                            0, factor);
843
844         if (finish != NULL && TRIEDALT(fctx)) {
845                 for (addrinfo = ISC_LIST_HEAD(fctx->altaddrs);
846                      addrinfo != NULL;
847                      addrinfo = ISC_LIST_NEXT(addrinfo, publink))
848                         if (UNMARKED(addrinfo))
849                                 dns_adb_adjustsrtt(fctx->adb, addrinfo,
850                                                    0, factor);
851                 for (find = ISC_LIST_HEAD(fctx->altfinds);
852                      find != NULL;
853                      find = ISC_LIST_NEXT(find, publink))
854                         for (addrinfo = ISC_LIST_HEAD(find->list);
855                              addrinfo != NULL;
856                              addrinfo = ISC_LIST_NEXT(addrinfo, publink))
857                                 if (UNMARKED(addrinfo))
858                                         dns_adb_adjustsrtt(fctx->adb, addrinfo,
859                                                            0, factor);
860         }
861
862         /*
863          * Check for any outstanding socket events.  If they exist, cancel
864          * them and let the event handlers finish the cleanup.  The resolver
865          * only needs to worry about managing the connect and send events;
866          * the dispatcher manages the recv events.
867          */
868         if (RESQUERY_CONNECTING(query)) {
869                 /*
870                  * Cancel the connect.
871                  */
872                 if (query->tcpsocket != NULL) {
873                         isc_socket_cancel(query->tcpsocket, NULL,
874                                           ISC_SOCKCANCEL_CONNECT);
875                 } else if (query->dispentry != NULL) {
876                         INSIST(query->exclusivesocket);
877                         socket = dns_dispatch_getentrysocket(query->dispentry);
878                         if (socket != NULL)
879                                 isc_socket_cancel(socket, NULL,
880                                                   ISC_SOCKCANCEL_CONNECT);
881                 }
882         } else if (RESQUERY_SENDING(query)) {
883                 /*
884                  * Cancel the pending send.
885                  */
886                 if (query->exclusivesocket && query->dispentry != NULL)
887                         socket = dns_dispatch_getentrysocket(query->dispentry);
888                 else
889                         socket = dns_dispatch_getsocket(query->dispatch);
890                 if (socket != NULL)
891                         isc_socket_cancel(socket, NULL, ISC_SOCKCANCEL_SEND);
892         }
893
894         if (query->dispentry != NULL)
895                 dns_dispatch_removeresponse(&query->dispentry, deventp);
896
897         ISC_LIST_UNLINK(fctx->queries, query, link);
898
899         if (query->tsig != NULL)
900                 isc_buffer_free(&query->tsig);
901
902         if (query->tsigkey != NULL)
903                 dns_tsigkey_detach(&query->tsigkey);
904
905         if (query->dispatch != NULL)
906                 dns_dispatch_detach(&query->dispatch);
907
908         if (! (RESQUERY_CONNECTING(query) || RESQUERY_SENDING(query)))
909                 /*
910                  * It's safe to destroy the query now.
911                  */
912                 resquery_destroy(&query);
913 }
914
915 static void
916 fctx_cancelqueries(fetchctx_t *fctx, isc_boolean_t no_response) {
917         resquery_t *query, *next_query;
918
919         FCTXTRACE("cancelqueries");
920
921         for (query = ISC_LIST_HEAD(fctx->queries);
922              query != NULL;
923              query = next_query) {
924                 next_query = ISC_LIST_NEXT(query, link);
925                 fctx_cancelquery(&query, NULL, NULL, no_response);
926         }
927 }
928
929 static void
930 fctx_cleanupfinds(fetchctx_t *fctx) {
931         dns_adbfind_t *find, *next_find;
932
933         REQUIRE(ISC_LIST_EMPTY(fctx->queries));
934
935         for (find = ISC_LIST_HEAD(fctx->finds);
936              find != NULL;
937              find = next_find) {
938                 next_find = ISC_LIST_NEXT(find, publink);
939                 ISC_LIST_UNLINK(fctx->finds, find, publink);
940                 dns_adb_destroyfind(&find);
941         }
942         fctx->find = NULL;
943 }
944
945 static void
946 fctx_cleanupaltfinds(fetchctx_t *fctx) {
947         dns_adbfind_t *find, *next_find;
948
949         REQUIRE(ISC_LIST_EMPTY(fctx->queries));
950
951         for (find = ISC_LIST_HEAD(fctx->altfinds);
952              find != NULL;
953              find = next_find) {
954                 next_find = ISC_LIST_NEXT(find, publink);
955                 ISC_LIST_UNLINK(fctx->altfinds, find, publink);
956                 dns_adb_destroyfind(&find);
957         }
958         fctx->altfind = NULL;
959 }
960
961 static void
962 fctx_cleanupforwaddrs(fetchctx_t *fctx) {
963         dns_adbaddrinfo_t *addr, *next_addr;
964
965         REQUIRE(ISC_LIST_EMPTY(fctx->queries));
966
967         for (addr = ISC_LIST_HEAD(fctx->forwaddrs);
968              addr != NULL;
969              addr = next_addr) {
970                 next_addr = ISC_LIST_NEXT(addr, publink);
971                 ISC_LIST_UNLINK(fctx->forwaddrs, addr, publink);
972                 dns_adb_freeaddrinfo(fctx->adb, &addr);
973         }
974 }
975
976 static void
977 fctx_cleanupaltaddrs(fetchctx_t *fctx) {
978         dns_adbaddrinfo_t *addr, *next_addr;
979
980         REQUIRE(ISC_LIST_EMPTY(fctx->queries));
981
982         for (addr = ISC_LIST_HEAD(fctx->altaddrs);
983              addr != NULL;
984              addr = next_addr) {
985                 next_addr = ISC_LIST_NEXT(addr, publink);
986                 ISC_LIST_UNLINK(fctx->altaddrs, addr, publink);
987                 dns_adb_freeaddrinfo(fctx->adb, &addr);
988         }
989 }
990
991 static inline void
992 fctx_stopeverything(fetchctx_t *fctx, isc_boolean_t no_response) {
993         FCTXTRACE("stopeverything");
994         fctx_cancelqueries(fctx, no_response);
995         fctx_cleanupfinds(fctx);
996         fctx_cleanupaltfinds(fctx);
997         fctx_cleanupforwaddrs(fctx);
998         fctx_cleanupaltaddrs(fctx);
999         fctx_stoptimer(fctx);
1000 }
1001
1002 static inline void
1003 fctx_sendevents(fetchctx_t *fctx, isc_result_t result, int line) {
1004         dns_fetchevent_t *event, *next_event;
1005         isc_task_t *task;
1006         unsigned int count = 0;
1007         isc_interval_t i;
1008         isc_boolean_t logit = ISC_FALSE;
1009         isc_time_t now;
1010         unsigned int old_spillat;
1011         unsigned int new_spillat = 0;   /* initialized to silence
1012                                            compiler warnings */
1013
1014         /*
1015          * Caller must be holding the appropriate bucket lock.
1016          */
1017         REQUIRE(fctx->state == fetchstate_done);
1018
1019         FCTXTRACE("sendevents");
1020
1021         /*
1022          * Keep some record of fetch result for logging later (if required).
1023          */
1024         fctx->result = result;
1025         fctx->exitline = line;
1026         TIME_NOW(&now);
1027         fctx->duration = isc_time_microdiff(&now, &fctx->start);
1028
1029         for (event = ISC_LIST_HEAD(fctx->events);
1030              event != NULL;
1031              event = next_event) {
1032                 next_event = ISC_LIST_NEXT(event, ev_link);
1033                 ISC_LIST_UNLINK(fctx->events, event, ev_link);
1034                 task = event->ev_sender;
1035                 event->ev_sender = fctx;
1036                 if (!HAVE_ANSWER(fctx))
1037                         event->result = result;
1038
1039                 INSIST(result != ISC_R_SUCCESS ||
1040                        dns_rdataset_isassociated(event->rdataset) ||
1041                        fctx->type == dns_rdatatype_any ||
1042                        fctx->type == dns_rdatatype_rrsig ||
1043                        fctx->type == dns_rdatatype_sig);
1044
1045                 /*
1046                  * Negative results must be indicated in event->result.
1047                  */
1048                 if (dns_rdataset_isassociated(event->rdataset) &&
1049                     event->rdataset->type == dns_rdatatype_none) {
1050                         INSIST(event->result == DNS_R_NCACHENXDOMAIN ||
1051                                event->result == DNS_R_NCACHENXRRSET);
1052                 }
1053
1054                 isc_task_sendanddetach(&task, ISC_EVENT_PTR(&event));
1055                 count++;
1056         }
1057
1058         if ((fctx->attributes & FCTX_ATTR_HAVEANSWER) != 0 &&
1059             fctx->spilled &&
1060             (count < fctx->res->spillatmax || fctx->res->spillatmax == 0)) {
1061                 LOCK(&fctx->res->lock);
1062                 if (count == fctx->res->spillat && !fctx->res->exiting) {
1063                         old_spillat = fctx->res->spillat;
1064                         fctx->res->spillat += 5;
1065                         if (fctx->res->spillat > fctx->res->spillatmax &&
1066                             fctx->res->spillatmax != 0)
1067                                 fctx->res->spillat = fctx->res->spillatmax;
1068                         new_spillat = fctx->res->spillat;
1069                         if (new_spillat != old_spillat) {
1070                                 logit = ISC_TRUE;
1071                         }
1072                         isc_interval_set(&i, 20 * 60, 0);
1073                         result = isc_timer_reset(fctx->res->spillattimer,
1074                                                  isc_timertype_ticker, NULL,
1075                                                  &i, ISC_TRUE);
1076                         RUNTIME_CHECK(result == ISC_R_SUCCESS);
1077                 }
1078                 UNLOCK(&fctx->res->lock);
1079                 if (logit)
1080                         isc_log_write(dns_lctx, DNS_LOGCATEGORY_RESOLVER,
1081                                       DNS_LOGMODULE_RESOLVER, ISC_LOG_NOTICE,
1082                                       "clients-per-query increased to %u",
1083                                       new_spillat);
1084         }
1085 }
1086
1087 static inline void
1088 log_edns(fetchctx_t *fctx) {
1089         char domainbuf[DNS_NAME_FORMATSIZE];
1090
1091         if (fctx->reason == NULL)
1092                 return;
1093
1094         dns_name_format(&fctx->domain, domainbuf, sizeof(domainbuf));
1095         isc_log_write(dns_lctx, DNS_LOGCATEGORY_EDNS_DISABLED,
1096                       DNS_LOGMODULE_RESOLVER, ISC_LOG_INFO,
1097                       "success resolving '%s' (in '%s'?) after %s",
1098                       fctx->info, domainbuf, fctx->reason);
1099
1100         fctx->reason = NULL;
1101 }
1102
1103 static void
1104 fctx_done(fetchctx_t *fctx, isc_result_t result, int line) {
1105         dns_resolver_t *res;
1106         isc_boolean_t no_response;
1107
1108         REQUIRE(line >= 0);
1109
1110         FCTXTRACE("done");
1111
1112         res = fctx->res;
1113
1114         if (result == ISC_R_SUCCESS) {
1115                 /*%
1116                  * Log any deferred EDNS timeout messages.
1117                  */
1118                 log_edns(fctx);
1119                 no_response = ISC_TRUE;
1120          } else
1121                 no_response = ISC_FALSE;
1122
1123         fctx->reason = NULL;
1124         fctx_stopeverything(fctx, no_response);
1125
1126         LOCK(&res->buckets[fctx->bucketnum].lock);
1127
1128         fctx->state = fetchstate_done;
1129         fctx->attributes &= ~FCTX_ATTR_ADDRWAIT;
1130         fctx_sendevents(fctx, result, line);
1131
1132         UNLOCK(&res->buckets[fctx->bucketnum].lock);
1133 }
1134
1135 static void
1136 process_sendevent(resquery_t *query, isc_event_t *event) {
1137         isc_socketevent_t *sevent = (isc_socketevent_t *)event;
1138         isc_boolean_t retry = ISC_FALSE;
1139         isc_result_t result;
1140         fetchctx_t *fctx;
1141
1142         fctx = query->fctx;
1143
1144         if (RESQUERY_CANCELED(query)) {
1145                 if (query->sends == 0 && query->connects == 0) {
1146                         /*
1147                          * This query was canceled while the
1148                          * isc_socket_sendto/connect() was in progress.
1149                          */
1150                         if (query->tcpsocket != NULL)
1151                                 isc_socket_detach(&query->tcpsocket);
1152                         resquery_destroy(&query);
1153                 }
1154         } else {
1155                 switch (sevent->result) {
1156                 case ISC_R_SUCCESS:
1157                         break;
1158
1159                 case ISC_R_HOSTUNREACH:
1160                 case ISC_R_NETUNREACH:
1161                 case ISC_R_NOPERM:
1162                 case ISC_R_ADDRNOTAVAIL:
1163                 case ISC_R_CONNREFUSED:
1164
1165                         /*
1166                          * No route to remote.
1167                          */
1168                         add_bad(fctx, query->addrinfo, sevent->result,
1169                                 badns_unreachable);
1170                         fctx_cancelquery(&query, NULL, NULL, ISC_TRUE);
1171                         retry = ISC_TRUE;
1172                         break;
1173
1174                 default:
1175                         fctx_cancelquery(&query, NULL, NULL, ISC_FALSE);
1176                         break;
1177                 }
1178         }
1179
1180         isc_event_free(&event);
1181
1182         if (retry) {
1183                 /*
1184                  * Behave as if the idle timer has expired.  For TCP
1185                  * this may not actually reflect the latest timer.
1186                  */
1187                 fctx->attributes &= ~FCTX_ATTR_ADDRWAIT;
1188                 result = fctx_stopidletimer(fctx);
1189                 if (result != ISC_R_SUCCESS)
1190                         fctx_done(fctx, result, __LINE__);
1191                 else
1192                         fctx_try(fctx, ISC_TRUE, ISC_FALSE);
1193         }
1194 }
1195
1196 static void
1197 resquery_udpconnected(isc_task_t *task, isc_event_t *event) {
1198         resquery_t *query = event->ev_arg;
1199
1200         REQUIRE(event->ev_type == ISC_SOCKEVENT_CONNECT);
1201
1202         QTRACE("udpconnected");
1203
1204         UNUSED(task);
1205
1206         INSIST(RESQUERY_CONNECTING(query));
1207
1208         query->connects--;
1209
1210         process_sendevent(query, event);
1211 }
1212
1213 static void
1214 resquery_senddone(isc_task_t *task, isc_event_t *event) {
1215         resquery_t *query = event->ev_arg;
1216
1217         REQUIRE(event->ev_type == ISC_SOCKEVENT_SENDDONE);
1218
1219         QTRACE("senddone");
1220
1221         /*
1222          * XXXRTH
1223          *
1224          * Currently we don't wait for the senddone event before retrying
1225          * a query.  This means that if we get really behind, we may end
1226          * up doing extra work!
1227          */
1228
1229         UNUSED(task);
1230
1231         INSIST(RESQUERY_SENDING(query));
1232
1233         query->sends--;
1234
1235         process_sendevent(query, event);
1236 }
1237
1238 static inline isc_result_t
1239 fctx_addopt(dns_message_t *message, unsigned int version,
1240             isc_uint16_t udpsize, isc_boolean_t request_nsid)
1241 {
1242         dns_rdataset_t *rdataset;
1243         dns_rdatalist_t *rdatalist;
1244         dns_rdata_t *rdata;
1245         isc_result_t result;
1246
1247         rdatalist = NULL;
1248         result = dns_message_gettemprdatalist(message, &rdatalist);
1249         if (result != ISC_R_SUCCESS)
1250                 return (result);
1251         rdata = NULL;
1252         result = dns_message_gettemprdata(message, &rdata);
1253         if (result != ISC_R_SUCCESS)
1254                 return (result);
1255         rdataset = NULL;
1256         result = dns_message_gettemprdataset(message, &rdataset);
1257         if (result != ISC_R_SUCCESS)
1258                 return (result);
1259         dns_rdataset_init(rdataset);
1260
1261         rdatalist->type = dns_rdatatype_opt;
1262         rdatalist->covers = 0;
1263
1264         /*
1265          * Set Maximum UDP buffer size.
1266          */
1267         rdatalist->rdclass = udpsize;
1268
1269         /*
1270          * Set EXTENDED-RCODE and Z to 0, DO to 1.
1271          */
1272         rdatalist->ttl = (version << 16);
1273         rdatalist->ttl |= DNS_MESSAGEEXTFLAG_DO;
1274
1275         /*
1276          * Set EDNS options if applicable
1277          */
1278         if (request_nsid) {
1279                 /* Send empty NSID option (RFC5001) */
1280                 unsigned char data[4];
1281                 isc_buffer_t buf;
1282
1283                 isc_buffer_init(&buf, data, sizeof(data));
1284                 isc_buffer_putuint16(&buf, DNS_OPT_NSID);
1285                 isc_buffer_putuint16(&buf, 0);
1286                 rdata->data = data;
1287                 rdata->length = sizeof(data);
1288         } else {
1289                 rdata->data = NULL;
1290                 rdata->length = 0;
1291         }
1292
1293         rdata->rdclass = rdatalist->rdclass;
1294         rdata->type = rdatalist->type;
1295         rdata->flags = 0;
1296
1297         ISC_LIST_INIT(rdatalist->rdata);
1298         ISC_LIST_APPEND(rdatalist->rdata, rdata, link);
1299         RUNTIME_CHECK(dns_rdatalist_tordataset(rdatalist, rdataset) == ISC_R_SUCCESS);
1300
1301         return (dns_message_setopt(message, rdataset));
1302 }
1303
1304 static inline void
1305 fctx_setretryinterval(fetchctx_t *fctx, unsigned int rtt) {
1306         unsigned int seconds;
1307         unsigned int us;
1308
1309         /*
1310          * We retry every .8 seconds the first two times through the address
1311          * list, and then we do exponential back-off.
1312          */
1313         if (fctx->restarts < 3)
1314                 us = 800000;
1315         else
1316                 us = (800000 << (fctx->restarts - 2));
1317
1318         /*
1319          * Double the round-trip time.
1320          */
1321         rtt *= 2;
1322
1323         /*
1324          * Always wait for at least the doubled round-trip time.
1325          */
1326         if (us < rtt)
1327                 us = rtt;
1328
1329         /*
1330          * But don't ever wait for more than 10 seconds.
1331          */
1332         if (us > 10000000)
1333                 us = 10000000;
1334
1335         seconds = us / 1000000;
1336         us -= seconds * 1000000;
1337         isc_interval_set(&fctx->interval, seconds, us * 1000);
1338 }
1339
1340 static isc_result_t
1341 fctx_query(fetchctx_t *fctx, dns_adbaddrinfo_t *addrinfo,
1342            unsigned int options)
1343 {
1344         dns_resolver_t *res;
1345         isc_task_t *task;
1346         isc_result_t result;
1347         resquery_t *query;
1348         isc_sockaddr_t addr;
1349         isc_boolean_t have_addr = ISC_FALSE;
1350         unsigned int srtt;
1351
1352         FCTXTRACE("query");
1353
1354         res = fctx->res;
1355         task = res->buckets[fctx->bucketnum].task;
1356
1357         srtt = addrinfo->srtt;
1358         if (ISFORWARDER(addrinfo) && srtt < 1000000)
1359                 srtt = 1000000;
1360
1361         fctx_setretryinterval(fctx, srtt);
1362         result = fctx_startidletimer(fctx, &fctx->interval);
1363         if (result != ISC_R_SUCCESS)
1364                 return (result);
1365
1366         INSIST(ISC_LIST_EMPTY(fctx->validators));
1367
1368         dns_message_reset(fctx->rmessage, DNS_MESSAGE_INTENTPARSE);
1369
1370         query = isc_mem_get(res->buckets[fctx->bucketnum].mctx,
1371                             sizeof(*query));
1372         if (query == NULL) {
1373                 result = ISC_R_NOMEMORY;
1374                 goto stop_idle_timer;
1375         }
1376         query->mctx = res->buckets[fctx->bucketnum].mctx;
1377         query->options = options;
1378         query->attributes = 0;
1379         query->sends = 0;
1380         query->connects = 0;
1381         /*
1382          * Note that the caller MUST guarantee that 'addrinfo' will remain
1383          * valid until this query is canceled.
1384          */
1385         query->addrinfo = addrinfo;
1386         TIME_NOW(&query->start);
1387
1388         /*
1389          * If this is a TCP query, then we need to make a socket and
1390          * a dispatch for it here.  Otherwise we use the resolver's
1391          * shared dispatch.
1392          */
1393         query->dispatchmgr = res->dispatchmgr;
1394         query->dispatch = NULL;
1395         query->exclusivesocket = ISC_FALSE;
1396         query->tcpsocket = NULL;
1397         if (res->view->peers != NULL) {
1398                 dns_peer_t *peer = NULL;
1399                 isc_netaddr_t dstip;
1400                 isc_netaddr_fromsockaddr(&dstip, &addrinfo->sockaddr);
1401                 result = dns_peerlist_peerbyaddr(res->view->peers,
1402                                                  &dstip, &peer);
1403                 if (result == ISC_R_SUCCESS) {
1404                         result = dns_peer_getquerysource(peer, &addr);
1405                         if (result == ISC_R_SUCCESS)
1406                                 have_addr = ISC_TRUE;
1407                 }
1408         }
1409
1410         if ((query->options & DNS_FETCHOPT_TCP) != 0) {
1411                 int pf;
1412
1413                 pf = isc_sockaddr_pf(&addrinfo->sockaddr);
1414                 if (!have_addr) {
1415                         switch (pf) {
1416                         case PF_INET:
1417                                 result =
1418                                   dns_dispatch_getlocaladdress(res->dispatchv4,
1419                                                                &addr);
1420                                 break;
1421                         case PF_INET6:
1422                                 result =
1423                                   dns_dispatch_getlocaladdress(res->dispatchv6,
1424                                                                &addr);
1425                                 break;
1426                         default:
1427                                 result = ISC_R_NOTIMPLEMENTED;
1428                                 break;
1429                         }
1430                         if (result != ISC_R_SUCCESS)
1431                                 goto cleanup_query;
1432                 }
1433                 isc_sockaddr_setport(&addr, 0);
1434
1435                 result = isc_socket_create(res->socketmgr, pf,
1436                                            isc_sockettype_tcp,
1437                                            &query->tcpsocket);
1438                 if (result != ISC_R_SUCCESS)
1439                         goto cleanup_query;
1440
1441 #ifndef BROKEN_TCP_BIND_BEFORE_CONNECT
1442                 result = isc_socket_bind(query->tcpsocket, &addr, 0);
1443                 if (result != ISC_R_SUCCESS)
1444                         goto cleanup_socket;
1445 #endif
1446
1447                 /*
1448                  * A dispatch will be created once the connect succeeds.
1449                  */
1450         } else {
1451                 if (have_addr) {
1452                         unsigned int attrs, attrmask;
1453                         attrs = DNS_DISPATCHATTR_UDP;
1454                         switch (isc_sockaddr_pf(&addr)) {
1455                         case AF_INET:
1456                                 attrs |= DNS_DISPATCHATTR_IPV4;
1457                                 break;
1458                         case AF_INET6:
1459                                 attrs |= DNS_DISPATCHATTR_IPV6;
1460                                 break;
1461                         default:
1462                                 result = ISC_R_NOTIMPLEMENTED;
1463                                 goto cleanup_query;
1464                         }
1465                         attrmask = DNS_DISPATCHATTR_UDP;
1466                         attrmask |= DNS_DISPATCHATTR_TCP;
1467                         attrmask |= DNS_DISPATCHATTR_IPV4;
1468                         attrmask |= DNS_DISPATCHATTR_IPV6;
1469                         result = dns_dispatch_getudp(res->dispatchmgr,
1470                                                      res->socketmgr,
1471                                                      res->taskmgr, &addr,
1472                                                      4096, 1000, 32768, 16411,
1473                                                      16433, attrs, attrmask,
1474                                                      &query->dispatch);
1475                         if (result != ISC_R_SUCCESS)
1476                                 goto cleanup_query;
1477                 } else {
1478                         switch (isc_sockaddr_pf(&addrinfo->sockaddr)) {
1479                         case PF_INET:
1480                                 dns_dispatch_attach(res->dispatchv4,
1481                                                     &query->dispatch);
1482                                 query->exclusivesocket = res->exclusivev4;
1483                                 break;
1484                         case PF_INET6:
1485                                 dns_dispatch_attach(res->dispatchv6,
1486                                                     &query->dispatch);
1487                                 query->exclusivesocket = res->exclusivev6;
1488                                 break;
1489                         default:
1490                                 result = ISC_R_NOTIMPLEMENTED;
1491                                 goto cleanup_query;
1492                         }
1493                 }
1494                 /*
1495                  * We should always have a valid dispatcher here.  If we
1496                  * don't support a protocol family, then its dispatcher
1497                  * will be NULL, but we shouldn't be finding addresses for
1498                  * protocol types we don't support, so the dispatcher
1499                  * we found should never be NULL.
1500                  */
1501                 INSIST(query->dispatch != NULL);
1502         }
1503
1504         query->dispentry = NULL;
1505         query->fctx = fctx;
1506         query->tsig = NULL;
1507         query->tsigkey = NULL;
1508         ISC_LINK_INIT(query, link);
1509         query->magic = QUERY_MAGIC;
1510
1511         if ((query->options & DNS_FETCHOPT_TCP) != 0) {
1512                 /*
1513                  * Connect to the remote server.
1514                  *
1515                  * XXXRTH  Should we attach to the socket?
1516                  */
1517                 result = isc_socket_connect(query->tcpsocket,
1518                                             &addrinfo->sockaddr, task,
1519                                             resquery_connected, query);
1520                 if (result != ISC_R_SUCCESS)
1521                         goto cleanup_socket;
1522                 query->connects++;
1523                 QTRACE("connecting via TCP");
1524         } else {
1525                 result = resquery_send(query);
1526                 if (result != ISC_R_SUCCESS)
1527                         goto cleanup_dispatch;
1528         }
1529         fctx->querysent++;
1530
1531         ISC_LIST_APPEND(fctx->queries, query, link);
1532         query->fctx->nqueries++;
1533         if (isc_sockaddr_pf(&addrinfo->sockaddr) == PF_INET)
1534                 inc_stats(res, dns_resstatscounter_queryv4);
1535         else
1536                 inc_stats(res, dns_resstatscounter_queryv6);
1537         if (res->view->resquerystats != NULL)
1538                 dns_rdatatypestats_increment(res->view->resquerystats,
1539                                              fctx->type);
1540
1541         return (ISC_R_SUCCESS);
1542
1543  cleanup_socket:
1544         isc_socket_detach(&query->tcpsocket);
1545
1546  cleanup_dispatch:
1547         if (query->dispatch != NULL)
1548                 dns_dispatch_detach(&query->dispatch);
1549
1550  cleanup_query:
1551         query->magic = 0;
1552         isc_mem_put(res->buckets[fctx->bucketnum].mctx,
1553                     query, sizeof(*query));
1554
1555  stop_idle_timer:
1556         RUNTIME_CHECK(fctx_stopidletimer(fctx) == ISC_R_SUCCESS);
1557
1558         return (result);
1559 }
1560
1561 static isc_boolean_t
1562 triededns(fetchctx_t *fctx, isc_sockaddr_t *address) {
1563         isc_sockaddr_t *sa;
1564
1565         for (sa = ISC_LIST_HEAD(fctx->edns);
1566              sa != NULL;
1567              sa = ISC_LIST_NEXT(sa, link)) {
1568                 if (isc_sockaddr_equal(sa, address))
1569                         return (ISC_TRUE);
1570         }
1571
1572         return (ISC_FALSE);
1573 }
1574
1575 static void
1576 add_triededns(fetchctx_t *fctx, isc_sockaddr_t *address) {
1577         isc_sockaddr_t *sa;
1578
1579         if (triededns(fctx, address))
1580                 return;
1581
1582         sa = isc_mem_get(fctx->res->buckets[fctx->bucketnum].mctx,
1583                          sizeof(*sa));
1584         if (sa == NULL)
1585                 return;
1586
1587         *sa = *address;
1588         ISC_LIST_INITANDAPPEND(fctx->edns, sa, link);
1589 }
1590
1591 static isc_boolean_t
1592 triededns512(fetchctx_t *fctx, isc_sockaddr_t *address) {
1593         isc_sockaddr_t *sa;
1594
1595         for (sa = ISC_LIST_HEAD(fctx->edns512);
1596              sa != NULL;
1597              sa = ISC_LIST_NEXT(sa, link)) {
1598                 if (isc_sockaddr_equal(sa, address))
1599                         return (ISC_TRUE);
1600         }
1601
1602         return (ISC_FALSE);
1603 }
1604
1605 static void
1606 add_triededns512(fetchctx_t *fctx, isc_sockaddr_t *address) {
1607         isc_sockaddr_t *sa;
1608
1609         if (triededns512(fctx, address))
1610                 return;
1611
1612         sa = isc_mem_get(fctx->res->buckets[fctx->bucketnum].mctx,
1613                          sizeof(*sa));
1614         if (sa == NULL)
1615                 return;
1616
1617         *sa = *address;
1618         ISC_LIST_INITANDAPPEND(fctx->edns512, sa, link);
1619 }
1620
1621 static isc_result_t
1622 resquery_send(resquery_t *query) {
1623         fetchctx_t *fctx;
1624         isc_result_t result;
1625         dns_name_t *qname = NULL;
1626         dns_rdataset_t *qrdataset = NULL;
1627         isc_region_t r;
1628         dns_resolver_t *res;
1629         isc_task_t *task;
1630         isc_socket_t *socket;
1631         isc_buffer_t tcpbuffer;
1632         isc_sockaddr_t *address;
1633         isc_buffer_t *buffer;
1634         isc_netaddr_t ipaddr;
1635         dns_tsigkey_t *tsigkey = NULL;
1636         dns_peer_t *peer = NULL;
1637         isc_boolean_t useedns;
1638         dns_compress_t cctx;
1639         isc_boolean_t cleanup_cctx = ISC_FALSE;
1640         isc_boolean_t secure_domain;
1641
1642         fctx = query->fctx;
1643         QTRACE("send");
1644
1645         res = fctx->res;
1646         task = res->buckets[fctx->bucketnum].task;
1647         address = NULL;
1648
1649         if ((query->options & DNS_FETCHOPT_TCP) != 0) {
1650                 /*
1651                  * Reserve space for the TCP message length.
1652                  */
1653                 isc_buffer_init(&tcpbuffer, query->data, sizeof(query->data));
1654                 isc_buffer_init(&query->buffer, query->data + 2,
1655                                 sizeof(query->data) - 2);
1656                 buffer = &tcpbuffer;
1657         } else {
1658                 isc_buffer_init(&query->buffer, query->data,
1659                                 sizeof(query->data));
1660                 buffer = &query->buffer;
1661         }
1662
1663         result = dns_message_gettempname(fctx->qmessage, &qname);
1664         if (result != ISC_R_SUCCESS)
1665                 goto cleanup_temps;
1666         result = dns_message_gettemprdataset(fctx->qmessage, &qrdataset);
1667         if (result != ISC_R_SUCCESS)
1668                 goto cleanup_temps;
1669
1670         /*
1671          * Get a query id from the dispatch.
1672          */
1673         result = dns_dispatch_addresponse2(query->dispatch,
1674                                            &query->addrinfo->sockaddr,
1675                                            task,
1676                                            resquery_response,
1677                                            query,
1678                                            &query->id,
1679                                            &query->dispentry,
1680                                            res->socketmgr);
1681         if (result != ISC_R_SUCCESS)
1682                 goto cleanup_temps;
1683
1684         fctx->qmessage->opcode = dns_opcode_query;
1685
1686         /*
1687          * Set up question.
1688          */
1689         dns_name_init(qname, NULL);
1690         dns_name_clone(&fctx->name, qname);
1691         dns_rdataset_init(qrdataset);
1692         dns_rdataset_makequestion(qrdataset, res->rdclass, fctx->type);
1693         ISC_LIST_APPEND(qname->list, qrdataset, link);
1694         dns_message_addname(fctx->qmessage, qname, DNS_SECTION_QUESTION);
1695         qname = NULL;
1696         qrdataset = NULL;
1697
1698         /*
1699          * Set RD if the client has requested that we do a recursive query,
1700          * or if we're sending to a forwarder.
1701          */
1702         if ((query->options & DNS_FETCHOPT_RECURSIVE) != 0 ||
1703             ISFORWARDER(query->addrinfo))
1704                 fctx->qmessage->flags |= DNS_MESSAGEFLAG_RD;
1705
1706         /*
1707          * Set CD if the client says don't validate or the question is
1708          * under a secure entry point.
1709          */
1710         if ((query->options & DNS_FETCHOPT_NOVALIDATE) != 0) {
1711                 fctx->qmessage->flags |= DNS_MESSAGEFLAG_CD;
1712         } else if (res->view->enablevalidation) {
1713                 result = dns_keytable_issecuredomain(res->view->secroots,
1714                                                      &fctx->name,
1715                                                      &secure_domain);
1716                 if (result != ISC_R_SUCCESS)
1717                         secure_domain = ISC_FALSE;
1718                 if (res->view->dlv != NULL)
1719                         secure_domain = ISC_TRUE;
1720                 if (secure_domain)
1721                         fctx->qmessage->flags |= DNS_MESSAGEFLAG_CD;
1722         }
1723
1724         /*
1725          * We don't have to set opcode because it defaults to query.
1726          */
1727         fctx->qmessage->id = query->id;
1728
1729         /*
1730          * Convert the question to wire format.
1731          */
1732         result = dns_compress_init(&cctx, -1, fctx->res->mctx);
1733         if (result != ISC_R_SUCCESS)
1734                 goto cleanup_message;
1735         cleanup_cctx = ISC_TRUE;
1736
1737         result = dns_message_renderbegin(fctx->qmessage, &cctx,
1738                                          &query->buffer);
1739         if (result != ISC_R_SUCCESS)
1740                 goto cleanup_message;
1741
1742         result = dns_message_rendersection(fctx->qmessage,
1743                                            DNS_SECTION_QUESTION, 0);
1744         if (result != ISC_R_SUCCESS)
1745                 goto cleanup_message;
1746
1747         peer = NULL;
1748         isc_netaddr_fromsockaddr(&ipaddr, &query->addrinfo->sockaddr);
1749         (void) dns_peerlist_peerbyaddr(fctx->res->view->peers, &ipaddr, &peer);
1750
1751         /*
1752          * The ADB does not know about servers with "edns no".  Check this,
1753          * and then inform the ADB for future use.
1754          */
1755         if ((query->addrinfo->flags & DNS_FETCHOPT_NOEDNS0) == 0 &&
1756             peer != NULL &&
1757             dns_peer_getsupportedns(peer, &useedns) == ISC_R_SUCCESS &&
1758             !useedns)
1759         {
1760                 query->options |= DNS_FETCHOPT_NOEDNS0;
1761                 dns_adb_changeflags(fctx->adb, query->addrinfo,
1762                                     DNS_FETCHOPT_NOEDNS0,
1763                                     DNS_FETCHOPT_NOEDNS0);
1764         }
1765
1766         /* Sync NOEDNS0 flag in addrinfo->flags and options now. */
1767         if ((query->addrinfo->flags & DNS_FETCHOPT_NOEDNS0) != 0)
1768                 query->options |= DNS_FETCHOPT_NOEDNS0;
1769
1770         /*
1771          * Handle timeouts by reducing the UDP response size to 512 bytes
1772          * then if that doesn't work disabling EDNS (includes DO) and CD.
1773          *
1774          * These timeout can be due to:
1775          *      * broken nameservers that don't respond to EDNS queries.
1776          *      * broken/misconfigured firewalls and NAT implementations
1777          *        that don't handle IP fragmentation.
1778          *      * broken/misconfigured firewalls that don't handle responses
1779          *        greater than 512 bytes.
1780          *      * broken/misconfigured firewalls that don't handle EDNS, DO
1781          *        or CD.
1782          *      * packet loss / link outage.
1783          */
1784         if (fctx->timeout) {
1785                 if ((triededns512(fctx, &query->addrinfo->sockaddr) ||
1786                      fctx->timeouts >= (MAX_EDNS0_TIMEOUTS * 2)) &&
1787                     (query->options & DNS_FETCHOPT_NOEDNS0) == 0) {
1788                         query->options |= DNS_FETCHOPT_NOEDNS0;
1789                         fctx->reason = "disabling EDNS";
1790                 } else if ((triededns(fctx, &query->addrinfo->sockaddr) ||
1791                             fctx->timeouts >= MAX_EDNS0_TIMEOUTS) &&
1792                            (query->options & DNS_FETCHOPT_NOEDNS0) == 0) {
1793                         query->options |= DNS_FETCHOPT_EDNS512;
1794                         fctx->reason = "reducing the advertised EDNS UDP "
1795                                        "packet size to 512 octets";
1796                 }
1797                 fctx->timeout = ISC_FALSE;
1798         }
1799
1800         /*
1801          * Use EDNS0, unless the caller doesn't want it, or we know that
1802          * the remote server doesn't like it.
1803          */
1804         if ((query->options & DNS_FETCHOPT_NOEDNS0) == 0) {
1805                 if ((query->addrinfo->flags & DNS_FETCHOPT_NOEDNS0) == 0) {
1806                         unsigned int version = 0;       /* Default version. */
1807                         unsigned int flags;
1808                         isc_uint16_t udpsize = res->udpsize;
1809                         isc_boolean_t reqnsid = res->view->requestnsid;
1810
1811                         flags = query->addrinfo->flags;
1812                         if ((flags & DNS_FETCHOPT_EDNSVERSIONSET) != 0) {
1813                                 version = flags & DNS_FETCHOPT_EDNSVERSIONMASK;
1814                                 version >>= DNS_FETCHOPT_EDNSVERSIONSHIFT;
1815                         }
1816                         if ((query->options & DNS_FETCHOPT_EDNS512) != 0)
1817                                 udpsize = 512;
1818                         else if (peer != NULL)
1819                                 (void)dns_peer_getudpsize(peer, &udpsize);
1820
1821                         /* request NSID for current view or peer? */
1822                         if (peer != NULL)
1823                                 (void) dns_peer_getrequestnsid(peer, &reqnsid);
1824                         result = fctx_addopt(fctx->qmessage, version,
1825                                              udpsize, reqnsid);
1826                         if (reqnsid && result == ISC_R_SUCCESS) {
1827                                 query->options |= DNS_FETCHOPT_WANTNSID;
1828                         } else if (result != ISC_R_SUCCESS) {
1829                                 /*
1830                                  * We couldn't add the OPT, but we'll press on.
1831                                  * We're not using EDNS0, so set the NOEDNS0
1832                                  * bit.
1833                                  */
1834                                 query->options |= DNS_FETCHOPT_NOEDNS0;
1835                         }
1836                 } else {
1837                         /*
1838                          * We know this server doesn't like EDNS0, so we
1839                          * won't use it.  Set the NOEDNS0 bit since we're
1840                          * not using EDNS0.
1841                          */
1842                         query->options |= DNS_FETCHOPT_NOEDNS0;
1843                 }
1844         }
1845
1846         /*
1847          * If we need EDNS0 to do this query and aren't using it, we lose.
1848          */
1849         if (NEEDEDNS0(fctx) && (query->options & DNS_FETCHOPT_NOEDNS0) != 0) {
1850                 result = DNS_R_SERVFAIL;
1851                 goto cleanup_message;
1852         }
1853
1854         if ((query->options & DNS_FETCHOPT_NOEDNS0) == 0)
1855                 add_triededns(fctx, &query->addrinfo->sockaddr);
1856
1857         if ((query->options & DNS_FETCHOPT_EDNS512) != 0)
1858                 add_triededns512(fctx, &query->addrinfo->sockaddr);
1859
1860         /*
1861          * Clear CD if EDNS is not in use.
1862          */
1863         if ((query->options & DNS_FETCHOPT_NOEDNS0) != 0)
1864                 fctx->qmessage->flags &= ~DNS_MESSAGEFLAG_CD;
1865
1866         /*
1867          * Add TSIG record tailored to the current recipient.
1868          */
1869         result = dns_view_getpeertsig(fctx->res->view, &ipaddr, &tsigkey);
1870         if (result != ISC_R_SUCCESS && result != ISC_R_NOTFOUND)
1871                 goto cleanup_message;
1872
1873         if (tsigkey != NULL) {
1874                 result = dns_message_settsigkey(fctx->qmessage, tsigkey);
1875                 dns_tsigkey_detach(&tsigkey);
1876                 if (result != ISC_R_SUCCESS)
1877                         goto cleanup_message;
1878         }
1879
1880         result = dns_message_rendersection(fctx->qmessage,
1881                                            DNS_SECTION_ADDITIONAL, 0);
1882         if (result != ISC_R_SUCCESS)
1883                 goto cleanup_message;
1884
1885         result = dns_message_renderend(fctx->qmessage);
1886         if (result != ISC_R_SUCCESS)
1887                 goto cleanup_message;
1888
1889         dns_compress_invalidate(&cctx);
1890         cleanup_cctx = ISC_FALSE;
1891
1892         if (dns_message_gettsigkey(fctx->qmessage) != NULL) {
1893                 dns_tsigkey_attach(dns_message_gettsigkey(fctx->qmessage),
1894                                    &query->tsigkey);
1895                 result = dns_message_getquerytsig(fctx->qmessage,
1896                                                   fctx->res->mctx,
1897                                                   &query->tsig);
1898                 if (result != ISC_R_SUCCESS)
1899                         goto cleanup_message;
1900         }
1901
1902         /*
1903          * If using TCP, write the length of the message at the beginning
1904          * of the buffer.
1905          */
1906         if ((query->options & DNS_FETCHOPT_TCP) != 0) {
1907                 isc_buffer_usedregion(&query->buffer, &r);
1908                 isc_buffer_putuint16(&tcpbuffer, (isc_uint16_t)r.length);
1909                 isc_buffer_add(&tcpbuffer, r.length);
1910         }
1911
1912         /*
1913          * We're now done with the query message.
1914          */
1915         dns_message_reset(fctx->qmessage, DNS_MESSAGE_INTENTRENDER);
1916
1917         if (query->exclusivesocket)
1918                 socket = dns_dispatch_getentrysocket(query->dispentry);
1919         else
1920                 socket = dns_dispatch_getsocket(query->dispatch);
1921         /*
1922          * Send the query!
1923          */
1924         if ((query->options & DNS_FETCHOPT_TCP) == 0) {
1925                 address = &query->addrinfo->sockaddr;
1926                 if (query->exclusivesocket) {
1927                         result = isc_socket_connect(socket, address, task,
1928                                                     resquery_udpconnected,
1929                                                     query);
1930                         if (result != ISC_R_SUCCESS)
1931                                 goto cleanup_message;
1932                         query->connects++;
1933                 }
1934         }
1935         isc_buffer_usedregion(buffer, &r);
1936
1937         /*
1938          * XXXRTH  Make sure we don't send to ourselves!  We should probably
1939          *              prune out these addresses when we get them from the ADB.
1940          */
1941         result = isc_socket_sendto(socket, &r, task, resquery_senddone,
1942                                    query, address, NULL);
1943         if (result != ISC_R_SUCCESS)
1944                 goto cleanup_message;
1945
1946         query->sends++;
1947
1948         QTRACE("sent");
1949
1950         return (ISC_R_SUCCESS);
1951
1952  cleanup_message:
1953         if (cleanup_cctx)
1954                 dns_compress_invalidate(&cctx);
1955
1956         dns_message_reset(fctx->qmessage, DNS_MESSAGE_INTENTRENDER);
1957
1958         /*
1959          * Stop the dispatcher from listening.
1960          */
1961         dns_dispatch_removeresponse(&query->dispentry, NULL);
1962
1963  cleanup_temps:
1964         if (qname != NULL)
1965                 dns_message_puttempname(fctx->qmessage, &qname);
1966         if (qrdataset != NULL)
1967                 dns_message_puttemprdataset(fctx->qmessage, &qrdataset);
1968
1969         return (result);
1970 }
1971
1972 static void
1973 resquery_connected(isc_task_t *task, isc_event_t *event) {
1974         isc_socketevent_t *sevent = (isc_socketevent_t *)event;
1975         resquery_t *query = event->ev_arg;
1976         isc_boolean_t retry = ISC_FALSE;
1977         isc_interval_t interval;
1978         isc_result_t result;
1979         unsigned int attrs;
1980         fetchctx_t *fctx;
1981
1982         REQUIRE(event->ev_type == ISC_SOCKEVENT_CONNECT);
1983         REQUIRE(VALID_QUERY(query));
1984
1985         QTRACE("connected");
1986
1987         UNUSED(task);
1988
1989         /*
1990          * XXXRTH
1991          *
1992          * Currently we don't wait for the connect event before retrying
1993          * a query.  This means that if we get really behind, we may end
1994          * up doing extra work!
1995          */
1996
1997         query->connects--;
1998         fctx = query->fctx;
1999
2000         if (RESQUERY_CANCELED(query)) {
2001                 /*
2002                  * This query was canceled while the connect() was in
2003                  * progress.
2004                  */
2005                 isc_socket_detach(&query->tcpsocket);
2006                 resquery_destroy(&query);
2007         } else {
2008                 switch (sevent->result) {
2009                 case ISC_R_SUCCESS:
2010
2011                         /*
2012                          * Extend the idle timer for TCP.  20 seconds
2013                          * should be long enough for a TCP connection to be
2014                          * established, a single DNS request to be sent,
2015                          * and the response received.
2016                          */
2017                         isc_interval_set(&interval, 20, 0);
2018                         result = fctx_startidletimer(query->fctx, &interval);
2019                         if (result != ISC_R_SUCCESS) {
2020                                 fctx_cancelquery(&query, NULL, NULL, ISC_FALSE);
2021                                 fctx_done(fctx, result, __LINE__);
2022                                 break;
2023                         }
2024                         /*
2025                          * We are connected.  Create a dispatcher and
2026                          * send the query.
2027                          */
2028                         attrs = 0;
2029                         attrs |= DNS_DISPATCHATTR_TCP;
2030                         attrs |= DNS_DISPATCHATTR_PRIVATE;
2031                         attrs |= DNS_DISPATCHATTR_CONNECTED;
2032                         if (isc_sockaddr_pf(&query->addrinfo->sockaddr) ==
2033                             AF_INET)
2034                                 attrs |= DNS_DISPATCHATTR_IPV4;
2035                         else
2036                                 attrs |= DNS_DISPATCHATTR_IPV6;
2037                         attrs |= DNS_DISPATCHATTR_MAKEQUERY;
2038
2039                         result = dns_dispatch_createtcp(query->dispatchmgr,
2040                                                      query->tcpsocket,
2041                                                      query->fctx->res->taskmgr,
2042                                                      4096, 2, 1, 1, 3, attrs,
2043                                                      &query->dispatch);
2044
2045                         /*
2046                          * Regardless of whether dns_dispatch_create()
2047                          * succeeded or not, we don't need our reference
2048                          * to the socket anymore.
2049                          */
2050                         isc_socket_detach(&query->tcpsocket);
2051
2052                         if (result == ISC_R_SUCCESS)
2053                                 result = resquery_send(query);
2054
2055                         if (result != ISC_R_SUCCESS) {
2056                                 fctx_cancelquery(&query, NULL, NULL, ISC_FALSE);
2057                                 fctx_done(fctx, result, __LINE__);
2058                         }
2059                         break;
2060
2061                 case ISC_R_NETUNREACH:
2062                 case ISC_R_HOSTUNREACH:
2063                 case ISC_R_CONNREFUSED:
2064                 case ISC_R_NOPERM:
2065                 case ISC_R_ADDRNOTAVAIL:
2066                 case ISC_R_CONNECTIONRESET:
2067                         /*
2068                          * No route to remote.
2069                          */
2070                         isc_socket_detach(&query->tcpsocket);
2071                         fctx_cancelquery(&query, NULL, NULL, ISC_TRUE);
2072                         retry = ISC_TRUE;
2073                         break;
2074
2075                 default:
2076                         isc_socket_detach(&query->tcpsocket);
2077                         fctx_cancelquery(&query, NULL, NULL, ISC_FALSE);
2078                         break;
2079                 }
2080         }
2081
2082         isc_event_free(&event);
2083
2084         if (retry) {
2085                 /*
2086                  * Behave as if the idle timer has expired.  For TCP
2087                  * connections this may not actually reflect the latest timer.
2088                  */
2089                 fctx->attributes &= ~FCTX_ATTR_ADDRWAIT;
2090                 result = fctx_stopidletimer(fctx);
2091                 if (result != ISC_R_SUCCESS)
2092                         fctx_done(fctx, result, __LINE__);
2093                 else
2094                         fctx_try(fctx, ISC_TRUE, ISC_FALSE);
2095         }
2096 }
2097
2098 static void
2099 fctx_finddone(isc_task_t *task, isc_event_t *event) {
2100         fetchctx_t *fctx;
2101         dns_adbfind_t *find;
2102         dns_resolver_t *res;
2103         isc_boolean_t want_try = ISC_FALSE;
2104         isc_boolean_t want_done = ISC_FALSE;
2105         isc_boolean_t bucket_empty = ISC_FALSE;
2106         unsigned int bucketnum;
2107
2108         find = event->ev_sender;
2109         fctx = event->ev_arg;
2110         REQUIRE(VALID_FCTX(fctx));
2111         res = fctx->res;
2112
2113         UNUSED(task);
2114
2115         FCTXTRACE("finddone");
2116
2117         INSIST(fctx->pending > 0);
2118         fctx->pending--;
2119
2120         if (ADDRWAIT(fctx)) {
2121                 /*
2122                  * The fetch is waiting for a name to be found.
2123                  */
2124                 INSIST(!SHUTTINGDOWN(fctx));
2125                 fctx->attributes &= ~FCTX_ATTR_ADDRWAIT;
2126                 if (event->ev_type == DNS_EVENT_ADBMOREADDRESSES)
2127                         want_try = ISC_TRUE;
2128                 else {
2129                         fctx->findfail++;
2130                         if (fctx->pending == 0) {
2131                                 /*
2132                                  * We've got nothing else to wait for and don't
2133                                  * know the answer.  There's nothing to do but
2134                                  * fail the fctx.
2135                                  */
2136                                 want_done = ISC_TRUE;
2137                         }
2138                 }
2139         } else if (SHUTTINGDOWN(fctx) && fctx->pending == 0 &&
2140                    fctx->nqueries == 0 && ISC_LIST_EMPTY(fctx->validators)) {
2141                 bucketnum = fctx->bucketnum;
2142                 LOCK(&res->buckets[bucketnum].lock);
2143                 /*
2144                  * Note that we had to wait until we had the lock before
2145                  * looking at fctx->references.
2146                  */
2147                 if (fctx->references == 0)
2148                         bucket_empty = fctx_destroy(fctx);
2149                 UNLOCK(&res->buckets[bucketnum].lock);
2150         }
2151
2152         isc_event_free(&event);
2153         dns_adb_destroyfind(&find);
2154
2155         if (want_try)
2156                 fctx_try(fctx, ISC_TRUE, ISC_FALSE);
2157         else if (want_done)
2158                 fctx_done(fctx, ISC_R_FAILURE, __LINE__);
2159         else if (bucket_empty)
2160                 empty_bucket(res);
2161 }
2162
2163
2164 static inline isc_boolean_t
2165 bad_server(fetchctx_t *fctx, isc_sockaddr_t *address) {
2166         isc_sockaddr_t *sa;
2167
2168         for (sa = ISC_LIST_HEAD(fctx->bad);
2169              sa != NULL;
2170              sa = ISC_LIST_NEXT(sa, link)) {
2171                 if (isc_sockaddr_equal(sa, address))
2172                         return (ISC_TRUE);
2173         }
2174
2175         return (ISC_FALSE);
2176 }
2177
2178 static inline isc_boolean_t
2179 mark_bad(fetchctx_t *fctx) {
2180         dns_adbfind_t *curr;
2181         dns_adbaddrinfo_t *addrinfo;
2182         isc_boolean_t all_bad = ISC_TRUE;
2183
2184         /*
2185          * Mark all known bad servers, so we don't try to talk to them
2186          * again.
2187          */
2188
2189         /*
2190          * Mark any bad nameservers.
2191          */
2192         for (curr = ISC_LIST_HEAD(fctx->finds);
2193              curr != NULL;
2194              curr = ISC_LIST_NEXT(curr, publink)) {
2195                 for (addrinfo = ISC_LIST_HEAD(curr->list);
2196                      addrinfo != NULL;
2197                      addrinfo = ISC_LIST_NEXT(addrinfo, publink)) {
2198                         if (bad_server(fctx, &addrinfo->sockaddr))
2199                                 addrinfo->flags |= FCTX_ADDRINFO_MARK;
2200                         else
2201                                 all_bad = ISC_FALSE;
2202                 }
2203         }
2204
2205         /*
2206          * Mark any bad forwarders.
2207          */
2208         for (addrinfo = ISC_LIST_HEAD(fctx->forwaddrs);
2209              addrinfo != NULL;
2210              addrinfo = ISC_LIST_NEXT(addrinfo, publink)) {
2211                 if (bad_server(fctx, &addrinfo->sockaddr))
2212                         addrinfo->flags |= FCTX_ADDRINFO_MARK;
2213                 else
2214                         all_bad = ISC_FALSE;
2215         }
2216
2217         /*
2218          * Mark any bad alternates.
2219          */
2220         for (curr = ISC_LIST_HEAD(fctx->altfinds);
2221              curr != NULL;
2222              curr = ISC_LIST_NEXT(curr, publink)) {
2223                 for (addrinfo = ISC_LIST_HEAD(curr->list);
2224                      addrinfo != NULL;
2225                      addrinfo = ISC_LIST_NEXT(addrinfo, publink)) {
2226                         if (bad_server(fctx, &addrinfo->sockaddr))
2227                                 addrinfo->flags |= FCTX_ADDRINFO_MARK;
2228                         else
2229                                 all_bad = ISC_FALSE;
2230                 }
2231         }
2232
2233         for (addrinfo = ISC_LIST_HEAD(fctx->altaddrs);
2234              addrinfo != NULL;
2235              addrinfo = ISC_LIST_NEXT(addrinfo, publink)) {
2236                 if (bad_server(fctx, &addrinfo->sockaddr))
2237                         addrinfo->flags |= FCTX_ADDRINFO_MARK;
2238                 else
2239                         all_bad = ISC_FALSE;
2240         }
2241
2242         return (all_bad);
2243 }
2244
2245 static void
2246 add_bad(fetchctx_t *fctx, dns_adbaddrinfo_t *addrinfo, isc_result_t reason,
2247         badnstype_t badtype)
2248 {
2249         char namebuf[DNS_NAME_FORMATSIZE];
2250         char addrbuf[ISC_SOCKADDR_FORMATSIZE];
2251         char classbuf[64];
2252         char typebuf[64];
2253         char code[64];
2254         isc_buffer_t b;
2255         isc_sockaddr_t *sa;
2256         const char *sep1, *sep2;
2257         isc_sockaddr_t *address = &addrinfo->sockaddr;
2258
2259         if (reason == DNS_R_LAME)
2260                 fctx->lamecount++;
2261         else {
2262                 switch (badtype) {
2263                 case badns_unreachable:
2264                         fctx->neterr++;
2265                         break;
2266                 case badns_response:
2267                         fctx->badresp++;
2268                         break;
2269                 case badns_validation:
2270                         break;  /* counted as 'valfail' */
2271                 }
2272         }
2273
2274         if (bad_server(fctx, address)) {
2275                 /*
2276                  * We already know this server is bad.
2277                  */
2278                 return;
2279         }
2280
2281         FCTXTRACE("add_bad");
2282
2283         sa = isc_mem_get(fctx->res->buckets[fctx->bucketnum].mctx,
2284                          sizeof(*sa));
2285         if (sa == NULL)
2286                 return;
2287         *sa = *address;
2288         ISC_LIST_INITANDAPPEND(fctx->bad, sa, link);
2289
2290         if (reason == DNS_R_LAME)       /* already logged */
2291                 return;
2292
2293         if (reason == DNS_R_UNEXPECTEDRCODE &&
2294             fctx->rmessage->rcode == dns_rcode_servfail &&
2295             ISFORWARDER(addrinfo))
2296                 return;
2297
2298         if (reason == DNS_R_UNEXPECTEDRCODE) {
2299                 isc_buffer_init(&b, code, sizeof(code) - 1);
2300                 dns_rcode_totext(fctx->rmessage->rcode, &b);
2301                 code[isc_buffer_usedlength(&b)] = '\0';
2302                 sep1 = "(";
2303                 sep2 = ") ";
2304         } else if (reason == DNS_R_UNEXPECTEDOPCODE) {
2305                 isc_buffer_init(&b, code, sizeof(code) - 1);
2306                 dns_opcode_totext((dns_opcode_t)fctx->rmessage->opcode, &b);
2307                 code[isc_buffer_usedlength(&b)] = '\0';
2308                 sep1 = "(";
2309                 sep2 = ") ";
2310         } else {
2311                 code[0] = '\0';
2312                 sep1 = "";
2313                 sep2 = "";
2314         }
2315         dns_name_format(&fctx->name, namebuf, sizeof(namebuf));
2316         dns_rdatatype_format(fctx->type, typebuf, sizeof(typebuf));
2317         dns_rdataclass_format(fctx->res->rdclass, classbuf, sizeof(classbuf));
2318         isc_sockaddr_format(address, addrbuf, sizeof(addrbuf));
2319         isc_log_write(dns_lctx, DNS_LOGCATEGORY_LAME_SERVERS,
2320                       DNS_LOGMODULE_RESOLVER, ISC_LOG_INFO,
2321                       "%s %s%s%sresolving '%s/%s/%s': %s",
2322                       dns_result_totext(reason), sep1, code, sep2,
2323                       namebuf, typebuf, classbuf, addrbuf);
2324 }
2325
2326 /*
2327  * Return 'bits' bits of random entropy from fctx->rand_buf,
2328  * refreshing it by calling isc_random_get() whenever the requested
2329  * number of bits is greater than the number in the buffer.
2330  */
2331 static inline isc_uint32_t
2332 random_bits(fetchctx_t *fctx, isc_uint32_t bits) {
2333         isc_uint32_t ret = 0;
2334
2335         REQUIRE(VALID_FCTX(fctx));
2336         REQUIRE(bits <= 32);
2337         if (bits == 0)
2338                 return (0);
2339
2340         if (bits >= fctx->rand_bits) {
2341                 /* if rand_bits == 0, this is unnecessary but harmless */
2342                 bits -= fctx->rand_bits;
2343                 ret = fctx->rand_buf << bits;
2344
2345                 /* refresh random buffer now */
2346                 isc_random_get(&fctx->rand_buf);
2347                 fctx->rand_bits = sizeof(fctx->rand_buf) * CHAR_BIT;
2348         }
2349
2350         if (bits > 0) {
2351                 isc_uint32_t mask = 0xffffffff;
2352                 if (bits < 32) {
2353                         mask = (1 << bits) - 1;
2354                 }
2355
2356                 ret |= fctx->rand_buf & mask;
2357                 fctx->rand_buf >>= bits;
2358                 fctx->rand_bits -= bits;
2359         }
2360
2361         return (ret);
2362 }
2363
2364 /*
2365  * Add some random jitter to a server's RTT value so that the
2366  * order of queries will be unpredictable.
2367  *
2368  * RTT values of servers which have been tried are fuzzed by 128 ms.
2369  * Servers that haven't been tried yet have their RTT set to a random
2370  * value between 0 ms and 7 ms; they should get to go first, but in
2371  * unpredictable order.
2372  */
2373 static inline void
2374 randomize_srtt(fetchctx_t *fctx, dns_adbaddrinfo_t *ai) {
2375         if (TRIED(ai)) {
2376                 ai->srtt >>= 10; /* convert to milliseconds, near enough */
2377                 ai->srtt |= (ai->srtt & 0x80) | random_bits(fctx, 7);
2378                 ai->srtt <<= 10; /* now back to microseconds */
2379         } else
2380                 ai->srtt = random_bits(fctx, 3) << 10;
2381 }
2382
2383 /*
2384  * Sort addrinfo list by RTT (with random jitter)
2385  */
2386 static void
2387 sort_adbfind(fetchctx_t *fctx, dns_adbfind_t *find) {
2388         dns_adbaddrinfo_t *best, *curr;
2389         dns_adbaddrinfolist_t sorted;
2390
2391         /* Add jitter to SRTT values */
2392         curr = ISC_LIST_HEAD(find->list);
2393         while (curr != NULL) {
2394                 randomize_srtt(fctx, curr);
2395                 curr = ISC_LIST_NEXT(curr, publink);
2396         }
2397
2398         /* Lame N^2 bubble sort. */
2399         ISC_LIST_INIT(sorted);
2400         while (!ISC_LIST_EMPTY(find->list)) {
2401                 best = ISC_LIST_HEAD(find->list);
2402                 curr = ISC_LIST_NEXT(best, publink);
2403                 while (curr != NULL) {
2404                         if (curr->srtt < best->srtt)
2405                                 best = curr;
2406                         curr = ISC_LIST_NEXT(curr, publink);
2407                 }
2408                 ISC_LIST_UNLINK(find->list, best, publink);
2409                 ISC_LIST_APPEND(sorted, best, publink);
2410         }
2411         find->list = sorted;
2412 }
2413
2414 /*
2415  * Sort a list of finds by server RTT (with random jitter)
2416  */
2417 static void
2418 sort_finds(fetchctx_t *fctx, dns_adbfindlist_t *findlist) {
2419         dns_adbfind_t *best, *curr;
2420         dns_adbfindlist_t sorted;
2421         dns_adbaddrinfo_t *addrinfo, *bestaddrinfo;
2422
2423         /* Sort each find's addrinfo list by SRTT (after adding jitter) */
2424         for (curr = ISC_LIST_HEAD(*findlist);
2425              curr != NULL;
2426              curr = ISC_LIST_NEXT(curr, publink))
2427                 sort_adbfind(fctx, curr);
2428
2429         /* Lame N^2 bubble sort. */
2430         ISC_LIST_INIT(sorted);
2431         while (!ISC_LIST_EMPTY(*findlist)) {
2432                 best = ISC_LIST_HEAD(*findlist);
2433                 bestaddrinfo = ISC_LIST_HEAD(best->list);
2434                 INSIST(bestaddrinfo != NULL);
2435                 curr = ISC_LIST_NEXT(best, publink);
2436                 while (curr != NULL) {
2437                         addrinfo = ISC_LIST_HEAD(curr->list);
2438                         INSIST(addrinfo != NULL);
2439                         if (addrinfo->srtt < bestaddrinfo->srtt) {
2440                                 best = curr;
2441                                 bestaddrinfo = addrinfo;
2442                         }
2443                         curr = ISC_LIST_NEXT(curr, publink);
2444                 }
2445                 ISC_LIST_UNLINK(*findlist, best, publink);
2446                 ISC_LIST_APPEND(sorted, best, publink);
2447         }
2448         *findlist = sorted;
2449 }
2450
2451 static void
2452 findname(fetchctx_t *fctx, dns_name_t *name, in_port_t port,
2453          unsigned int options, unsigned int flags, isc_stdtime_t now,
2454          isc_boolean_t *need_alternate)
2455 {
2456         dns_adbaddrinfo_t *ai;
2457         dns_adbfind_t *find;
2458         dns_resolver_t *res;
2459         isc_boolean_t unshared;
2460         isc_result_t result;
2461
2462         res = fctx->res;
2463         unshared = ISC_TF((fctx->options | DNS_FETCHOPT_UNSHARED) != 0);
2464         /*
2465          * If this name is a subdomain of the query domain, tell
2466          * the ADB to start looking using zone/hint data. This keeps us
2467          * from getting stuck if the nameserver is beneath the zone cut
2468          * and we don't know its address (e.g. because the A record has
2469          * expired).
2470          */
2471         if (dns_name_issubdomain(name, &fctx->domain))
2472                 options |= DNS_ADBFIND_STARTATZONE;
2473         options |= DNS_ADBFIND_GLUEOK;
2474         options |= DNS_ADBFIND_HINTOK;
2475
2476         /*
2477          * See what we know about this address.
2478          */
2479         find = NULL;
2480         result = dns_adb_createfind(fctx->adb,
2481                                     res->buckets[fctx->bucketnum].task,
2482                                     fctx_finddone, fctx, name,
2483                                     &fctx->name, fctx->type,
2484                                     options, now, NULL,
2485                                     res->view->dstport, &find);
2486         if (result != ISC_R_SUCCESS) {
2487                 if (result == DNS_R_ALIAS) {
2488                         /*
2489                          * XXXRTH  Follow the CNAME/DNAME chain?
2490                          */
2491                         dns_adb_destroyfind(&find);
2492                         fctx->adberr++;
2493                 }
2494         } else if (!ISC_LIST_EMPTY(find->list)) {
2495                 /*
2496                  * We have at least some of the addresses for the
2497                  * name.
2498                  */
2499                 INSIST((find->options & DNS_ADBFIND_WANTEVENT) == 0);
2500                 if (flags != 0 || port != 0) {
2501                         for (ai = ISC_LIST_HEAD(find->list);
2502                              ai != NULL;
2503                              ai = ISC_LIST_NEXT(ai, publink)) {
2504                                 ai->flags |= flags;
2505                                 if (port != 0)
2506                                         isc_sockaddr_setport(&ai->sockaddr,
2507                                                              port);
2508                         }
2509                 }
2510                 if ((flags & FCTX_ADDRINFO_FORWARDER) != 0)
2511                         ISC_LIST_APPEND(fctx->altfinds, find, publink);
2512                 else
2513                         ISC_LIST_APPEND(fctx->finds, find, publink);
2514         } else {
2515                 /*
2516                  * We don't know any of the addresses for this
2517                  * name.
2518                  */
2519                 if ((find->options & DNS_ADBFIND_WANTEVENT) != 0) {
2520                         /*
2521                          * We're looking for them and will get an
2522                          * event about it later.
2523                          */
2524                         fctx->pending++;
2525                         /*
2526                          * Bootstrap.
2527                          */
2528                         if (need_alternate != NULL &&
2529                             !*need_alternate && unshared &&
2530                             ((res->dispatchv4 == NULL &&
2531                               find->result_v6 != DNS_R_NXDOMAIN) ||
2532                              (res->dispatchv6 == NULL &&
2533                               find->result_v4 != DNS_R_NXDOMAIN)))
2534                                 *need_alternate = ISC_TRUE;
2535                 } else {
2536                         if ((find->options & DNS_ADBFIND_LAMEPRUNED) != 0)
2537                                 fctx->lamecount++; /* cached lame server */
2538                         else
2539                                 fctx->adberr++; /* unreachable server, etc. */
2540
2541                         /*
2542                          * If we know there are no addresses for
2543                          * the family we are using then try to add
2544                          * an alternative server.
2545                          */
2546                         if (need_alternate != NULL && !*need_alternate &&
2547                             ((res->dispatchv4 == NULL &&
2548                               find->result_v6 == DNS_R_NXRRSET) ||
2549                              (res->dispatchv6 == NULL &&
2550                               find->result_v4 == DNS_R_NXRRSET)))
2551                                 *need_alternate = ISC_TRUE;
2552                         dns_adb_destroyfind(&find);
2553                 }
2554         }
2555 }
2556
2557 static isc_boolean_t
2558 isstrictsubdomain(dns_name_t *name1, dns_name_t *name2) {
2559         int order;
2560         unsigned int nlabels;
2561         dns_namereln_t namereln;
2562
2563         namereln = dns_name_fullcompare(name1, name2, &order, &nlabels);
2564         return (ISC_TF(namereln == dns_namereln_subdomain));
2565 }
2566
2567 static isc_result_t
2568 fctx_getaddresses(fetchctx_t *fctx, isc_boolean_t badcache) {
2569         dns_rdata_t rdata = DNS_RDATA_INIT;
2570         isc_result_t result;
2571         dns_resolver_t *res;
2572         isc_stdtime_t now;
2573         unsigned int stdoptions;
2574         isc_sockaddr_t *sa;
2575         dns_adbaddrinfo_t *ai;
2576         isc_boolean_t all_bad;
2577         dns_rdata_ns_t ns;
2578         isc_boolean_t need_alternate = ISC_FALSE;
2579
2580         FCTXTRACE("getaddresses");
2581
2582         /*
2583          * Don't pound on remote servers.  (Failsafe!)
2584          */
2585         fctx->restarts++;
2586         if (fctx->restarts > 10) {
2587                 FCTXTRACE("too many restarts");
2588                 return (DNS_R_SERVFAIL);
2589         }
2590
2591         res = fctx->res;
2592         stdoptions = 0;         /* Keep compiler happy. */
2593
2594         /*
2595          * Forwarders.
2596          */
2597
2598         INSIST(ISC_LIST_EMPTY(fctx->forwaddrs));
2599         INSIST(ISC_LIST_EMPTY(fctx->altaddrs));
2600
2601         /*
2602          * If this fctx has forwarders, use them; otherwise use any
2603          * selective forwarders specified in the view; otherwise use the
2604          * resolver's forwarders (if any).
2605          */
2606         sa = ISC_LIST_HEAD(fctx->forwarders);
2607         if (sa == NULL) {
2608                 dns_forwarders_t *forwarders = NULL;
2609                 dns_name_t *name = &fctx->name;
2610                 dns_name_t suffix;
2611                 unsigned int labels;
2612                 dns_fixedname_t fixed;
2613                 dns_name_t *domain;
2614
2615                 /*
2616                  * DS records are found in the parent server.
2617                  * Strip label to get the correct forwarder (if any).
2618                  */
2619                 if (dns_rdatatype_atparent(fctx->type) &&
2620                     dns_name_countlabels(name) > 1) {
2621                         dns_name_init(&suffix, NULL);
2622                         labels = dns_name_countlabels(name);
2623                         dns_name_getlabelsequence(name, 1, labels - 1, &suffix);
2624                         name = &suffix;
2625                 }
2626
2627                 dns_fixedname_init(&fixed);
2628                 domain = dns_fixedname_name(&fixed);
2629                 result = dns_fwdtable_find2(fctx->res->view->fwdtable, name,
2630                                             domain, &forwarders);
2631                 if (result == ISC_R_SUCCESS) {
2632                         sa = ISC_LIST_HEAD(forwarders->addrs);
2633                         fctx->fwdpolicy = forwarders->fwdpolicy;
2634                         if (fctx->fwdpolicy == dns_fwdpolicy_only &&
2635                             isstrictsubdomain(domain, &fctx->domain)) {
2636                                 isc_mem_t *mctx;
2637
2638                                 mctx = res->buckets[fctx->bucketnum].mctx;
2639                                 dns_name_free(&fctx->domain, mctx);
2640                                 dns_name_init(&fctx->domain, NULL);
2641                                 result = dns_name_dup(domain, mctx,
2642                                                       &fctx->domain);
2643                                 if (result != ISC_R_SUCCESS)
2644                                         return (result);
2645                         }
2646                 }
2647         }
2648
2649         while (sa != NULL) {
2650                 if ((isc_sockaddr_pf(sa) == AF_INET &&
2651                          fctx->res->dispatchv4 == NULL) ||
2652                     (isc_sockaddr_pf(sa) == AF_INET6 &&
2653                         fctx->res->dispatchv6 == NULL)) {
2654                                 sa = ISC_LIST_NEXT(sa, link);
2655                                 continue;
2656                 }
2657                 ai = NULL;
2658                 result = dns_adb_findaddrinfo(fctx->adb,
2659                                               sa, &ai, 0);  /* XXXMLG */
2660                 if (result == ISC_R_SUCCESS) {
2661                         dns_adbaddrinfo_t *cur;
2662                         ai->flags |= FCTX_ADDRINFO_FORWARDER;
2663                         cur = ISC_LIST_HEAD(fctx->forwaddrs);
2664                         while (cur != NULL && cur->srtt < ai->srtt)
2665                                 cur = ISC_LIST_NEXT(cur, publink);
2666                         if (cur != NULL)
2667                                 ISC_LIST_INSERTBEFORE(fctx->forwaddrs, cur,
2668                                                       ai, publink);
2669                         else
2670                                 ISC_LIST_APPEND(fctx->forwaddrs, ai, publink);
2671                 }
2672                 sa = ISC_LIST_NEXT(sa, link);
2673         }
2674
2675         /*
2676          * If the forwarding policy is "only", we don't need the addresses
2677          * of the nameservers.
2678          */
2679         if (fctx->fwdpolicy == dns_fwdpolicy_only)
2680                 goto out;
2681
2682         /*
2683          * Normal nameservers.
2684          */
2685
2686         stdoptions = DNS_ADBFIND_WANTEVENT | DNS_ADBFIND_EMPTYEVENT;
2687         if (fctx->restarts == 1) {
2688                 /*
2689                  * To avoid sending out a flood of queries likely to
2690                  * result in NXRRSET, we suppress fetches for address
2691                  * families we don't have the first time through,
2692                  * provided that we have addresses in some family we
2693                  * can use.
2694                  *
2695                  * We don't want to set this option all the time, since
2696                  * if fctx->restarts > 1, we've clearly been having trouble
2697                  * with the addresses we had, so getting more could help.
2698                  */
2699                 stdoptions |= DNS_ADBFIND_AVOIDFETCHES;
2700         }
2701         if (res->dispatchv4 != NULL)
2702                 stdoptions |= DNS_ADBFIND_INET;
2703         if (res->dispatchv6 != NULL)
2704                 stdoptions |= DNS_ADBFIND_INET6;
2705         isc_stdtime_get(&now);
2706
2707         INSIST(ISC_LIST_EMPTY(fctx->finds));
2708         INSIST(ISC_LIST_EMPTY(fctx->altfinds));
2709
2710         for (result = dns_rdataset_first(&fctx->nameservers);
2711              result == ISC_R_SUCCESS;
2712              result = dns_rdataset_next(&fctx->nameservers))
2713         {
2714                 dns_rdataset_current(&fctx->nameservers, &rdata);
2715                 /*
2716                  * Extract the name from the NS record.
2717                  */
2718                 result = dns_rdata_tostruct(&rdata, &ns, NULL);
2719                 if (result != ISC_R_SUCCESS)
2720                         continue;
2721
2722                 findname(fctx, &ns.name, 0, stdoptions, 0, now,
2723                          &need_alternate);
2724                 dns_rdata_reset(&rdata);
2725                 dns_rdata_freestruct(&ns);
2726         }
2727         if (result != ISC_R_NOMORE)
2728                 return (result);
2729
2730         /*
2731          * Do we need to use 6 to 4?
2732          */
2733         if (need_alternate) {
2734                 int family;
2735                 alternate_t *a;
2736                 family = (res->dispatchv6 != NULL) ? AF_INET6 : AF_INET;
2737                 for (a = ISC_LIST_HEAD(fctx->res->alternates);
2738                      a != NULL;
2739                      a = ISC_LIST_NEXT(a, link)) {
2740                         if (!a->isaddress) {
2741                                 findname(fctx, &a->_u._n.name, a->_u._n.port,
2742                                          stdoptions, FCTX_ADDRINFO_FORWARDER,
2743                                          now, NULL);
2744                                 continue;
2745                         }
2746                         if (isc_sockaddr_pf(&a->_u.addr) != family)
2747                                 continue;
2748                         ai = NULL;
2749                         result = dns_adb_findaddrinfo(fctx->adb, &a->_u.addr,
2750                                                       &ai, 0);
2751                         if (result == ISC_R_SUCCESS) {
2752                                 dns_adbaddrinfo_t *cur;
2753                                 ai->flags |= FCTX_ADDRINFO_FORWARDER;
2754                                 cur = ISC_LIST_HEAD(fctx->altaddrs);
2755                                 while (cur != NULL && cur->srtt < ai->srtt)
2756                                         cur = ISC_LIST_NEXT(cur, publink);
2757                                 if (cur != NULL)
2758                                         ISC_LIST_INSERTBEFORE(fctx->altaddrs,
2759                                                               cur, ai, publink);
2760                                 else
2761                                         ISC_LIST_APPEND(fctx->altaddrs, ai,
2762                                                         publink);
2763                         }
2764                 }
2765         }
2766
2767  out:
2768         /*
2769          * Mark all known bad servers.
2770          */
2771         all_bad = mark_bad(fctx);
2772
2773         /*
2774          * How are we doing?
2775          */
2776         if (all_bad) {
2777                 /*
2778                  * We've got no addresses.
2779                  */
2780                 if (fctx->pending > 0) {
2781                         /*
2782                          * We're fetching the addresses, but don't have any
2783                          * yet.   Tell the caller to wait for an answer.
2784                          */
2785                         result = DNS_R_WAIT;
2786                 } else {
2787                         isc_time_t expire;
2788                         isc_interval_t i;
2789                         /*
2790                          * We've lost completely.  We don't know any
2791                          * addresses, and the ADB has told us it can't get
2792                          * them.
2793                          */
2794                         FCTXTRACE("no addresses");
2795                         isc_interval_set(&i, DNS_BADCACHE_TTL(fctx), 0);
2796                         result = isc_time_nowplusinterval(&expire, &i);
2797                         if (badcache &&
2798                             (fctx->type == dns_rdatatype_dnskey ||
2799                              fctx->type == dns_rdatatype_dlv ||
2800                              fctx->type == dns_rdatatype_ds) &&
2801                              result == ISC_R_SUCCESS)
2802                                 dns_resolver_addbadcache(fctx->res,
2803                                                          &fctx->name,
2804                                                          fctx->type, &expire);
2805                         result = ISC_R_FAILURE;
2806                 }
2807         } else {
2808                 /*
2809                  * We've found some addresses.  We might still be looking
2810                  * for more addresses.
2811                  */
2812                 sort_finds(fctx, &fctx->finds);
2813                 sort_finds(fctx, &fctx->altfinds);
2814                 result = ISC_R_SUCCESS;
2815         }
2816
2817         return (result);
2818 }
2819
2820 static inline void
2821 possibly_mark(fetchctx_t *fctx, dns_adbaddrinfo_t *addr)
2822 {
2823         isc_netaddr_t na;
2824         char buf[ISC_NETADDR_FORMATSIZE];
2825         isc_sockaddr_t *sa;
2826         isc_boolean_t aborted = ISC_FALSE;
2827         isc_boolean_t bogus;
2828         dns_acl_t *blackhole;
2829         isc_netaddr_t ipaddr;
2830         dns_peer_t *peer = NULL;
2831         dns_resolver_t *res;
2832         const char *msg = NULL;
2833
2834         sa = &addr->sockaddr;
2835
2836         res = fctx->res;
2837         isc_netaddr_fromsockaddr(&ipaddr, sa);
2838         blackhole = dns_dispatchmgr_getblackhole(res->dispatchmgr);
2839         (void) dns_peerlist_peerbyaddr(res->view->peers, &ipaddr, &peer);
2840
2841         if (blackhole != NULL) {
2842                 int match;
2843
2844                 if (dns_acl_match(&ipaddr, NULL, blackhole,
2845                                   &res->view->aclenv,
2846                                   &match, NULL) == ISC_R_SUCCESS &&
2847                     match > 0)
2848                         aborted = ISC_TRUE;
2849         }
2850
2851         if (peer != NULL &&
2852             dns_peer_getbogus(peer, &bogus) == ISC_R_SUCCESS &&
2853             bogus)
2854                 aborted = ISC_TRUE;
2855
2856         if (aborted) {
2857                 addr->flags |= FCTX_ADDRINFO_MARK;
2858                 msg = "ignoring blackholed / bogus server: ";
2859         } else if (isc_sockaddr_ismulticast(sa)) {
2860                 addr->flags |= FCTX_ADDRINFO_MARK;
2861                 msg = "ignoring multicast address: ";
2862         } else if (isc_sockaddr_isexperimental(sa)) {
2863                 addr->flags |= FCTX_ADDRINFO_MARK;
2864                 msg = "ignoring experimental address: ";
2865         } else if (sa->type.sa.sa_family != AF_INET6) {
2866                 return;
2867         } else if (IN6_IS_ADDR_V4MAPPED(&sa->type.sin6.sin6_addr)) {
2868                 addr->flags |= FCTX_ADDRINFO_MARK;
2869                 msg = "ignoring IPv6 mapped IPV4 address: ";
2870         } else if (IN6_IS_ADDR_V4COMPAT(&sa->type.sin6.sin6_addr)) {
2871                 addr->flags |= FCTX_ADDRINFO_MARK;
2872                 msg = "ignoring IPv6 compatibility IPV4 address: ";
2873         } else
2874                 return;
2875
2876         if (!isc_log_wouldlog(dns_lctx, ISC_LOG_DEBUG(3)))
2877                 return;
2878
2879         isc_netaddr_fromsockaddr(&na, sa);
2880         isc_netaddr_format(&na, buf, sizeof(buf));
2881         FCTXTRACE2(msg, buf);
2882 }
2883
2884 static inline dns_adbaddrinfo_t *
2885 fctx_nextaddress(fetchctx_t *fctx) {
2886         dns_adbfind_t *find, *start;
2887         dns_adbaddrinfo_t *addrinfo;
2888         dns_adbaddrinfo_t *faddrinfo;
2889
2890         /*
2891          * Return the next untried address, if any.
2892          */
2893
2894         /*
2895          * Find the first unmarked forwarder (if any).
2896          */
2897         for (addrinfo = ISC_LIST_HEAD(fctx->forwaddrs);
2898              addrinfo != NULL;
2899              addrinfo = ISC_LIST_NEXT(addrinfo, publink)) {
2900                 if (!UNMARKED(addrinfo))
2901                         continue;
2902                 possibly_mark(fctx, addrinfo);
2903                 if (UNMARKED(addrinfo)) {
2904                         addrinfo->flags |= FCTX_ADDRINFO_MARK;
2905                         fctx->find = NULL;
2906                         return (addrinfo);
2907                 }
2908         }
2909
2910         /*
2911          * No forwarders.  Move to the next find.
2912          */
2913
2914         fctx->attributes |= FCTX_ATTR_TRIEDFIND;
2915
2916         find = fctx->find;
2917         if (find == NULL)
2918                 find = ISC_LIST_HEAD(fctx->finds);
2919         else {
2920                 find = ISC_LIST_NEXT(find, publink);
2921                 if (find == NULL)
2922                         find = ISC_LIST_HEAD(fctx->finds);
2923         }
2924
2925         /*
2926          * Find the first unmarked addrinfo.
2927          */
2928         addrinfo = NULL;
2929         if (find != NULL) {
2930                 start = find;
2931                 do {
2932                         for (addrinfo = ISC_LIST_HEAD(find->list);
2933                              addrinfo != NULL;
2934                              addrinfo = ISC_LIST_NEXT(addrinfo, publink)) {
2935                                 if (!UNMARKED(addrinfo))
2936                                         continue;
2937                                 possibly_mark(fctx, addrinfo);
2938                                 if (UNMARKED(addrinfo)) {
2939                                         addrinfo->flags |= FCTX_ADDRINFO_MARK;
2940                                         break;
2941                                 }
2942                         }
2943                         if (addrinfo != NULL)
2944                                 break;
2945                         find = ISC_LIST_NEXT(find, publink);
2946                         if (find == NULL)
2947                                 find = ISC_LIST_HEAD(fctx->finds);
2948                 } while (find != start);
2949         }
2950
2951         fctx->find = find;
2952         if (addrinfo != NULL)
2953                 return (addrinfo);
2954
2955         /*
2956          * No nameservers left.  Try alternates.
2957          */
2958
2959         fctx->attributes |= FCTX_ATTR_TRIEDALT;
2960
2961         find = fctx->altfind;
2962         if (find == NULL)
2963                 find = ISC_LIST_HEAD(fctx->altfinds);
2964         else {
2965                 find = ISC_LIST_NEXT(find, publink);
2966                 if (find == NULL)
2967                         find = ISC_LIST_HEAD(fctx->altfinds);
2968         }
2969
2970         /*
2971          * Find the first unmarked addrinfo.
2972          */
2973         addrinfo = NULL;
2974         if (find != NULL) {
2975                 start = find;
2976                 do {
2977                         for (addrinfo = ISC_LIST_HEAD(find->list);
2978                              addrinfo != NULL;
2979                              addrinfo = ISC_LIST_NEXT(addrinfo, publink)) {
2980                                 if (!UNMARKED(addrinfo))
2981                                         continue;
2982                                 possibly_mark(fctx, addrinfo);
2983                                 if (UNMARKED(addrinfo)) {
2984                                         addrinfo->flags |= FCTX_ADDRINFO_MARK;
2985                                         break;
2986                                 }
2987                         }
2988                         if (addrinfo != NULL)
2989                                 break;
2990                         find = ISC_LIST_NEXT(find, publink);
2991                         if (find == NULL)
2992                                 find = ISC_LIST_HEAD(fctx->altfinds);
2993                 } while (find != start);
2994         }
2995
2996         faddrinfo = addrinfo;
2997
2998         /*
2999          * See if we have a better alternate server by address.
3000          */
3001
3002         for (addrinfo = ISC_LIST_HEAD(fctx->altaddrs);
3003              addrinfo != NULL;
3004              addrinfo = ISC_LIST_NEXT(addrinfo, publink)) {
3005                 if (!UNMARKED(addrinfo))
3006                         continue;
3007                 possibly_mark(fctx, addrinfo);
3008                 if (UNMARKED(addrinfo) &&
3009                     (faddrinfo == NULL ||
3010                      addrinfo->srtt < faddrinfo->srtt)) {
3011                         if (faddrinfo != NULL)
3012                                 faddrinfo->flags &= ~FCTX_ADDRINFO_MARK;
3013                         addrinfo->flags |= FCTX_ADDRINFO_MARK;
3014                         break;
3015                 }
3016         }
3017
3018         if (addrinfo == NULL) {
3019                 addrinfo = faddrinfo;
3020                 fctx->altfind = find;
3021         }
3022
3023         return (addrinfo);
3024 }
3025
3026 static void
3027 fctx_try(fetchctx_t *fctx, isc_boolean_t retrying, isc_boolean_t badcache) {
3028         isc_result_t result;
3029         dns_adbaddrinfo_t *addrinfo;
3030
3031         FCTXTRACE("try");
3032
3033         REQUIRE(!ADDRWAIT(fctx));
3034
3035         addrinfo = fctx_nextaddress(fctx);
3036         if (addrinfo == NULL) {
3037                 /*
3038                  * We have no more addresses.  Start over.
3039                  */
3040                 fctx_cancelqueries(fctx, ISC_TRUE);
3041                 fctx_cleanupfinds(fctx);
3042                 fctx_cleanupaltfinds(fctx);
3043                 fctx_cleanupforwaddrs(fctx);
3044                 fctx_cleanupaltaddrs(fctx);
3045                 result = fctx_getaddresses(fctx, badcache);
3046                 if (result == DNS_R_WAIT) {
3047                         /*
3048                          * Sleep waiting for addresses.
3049                          */
3050                         FCTXTRACE("addrwait");
3051                         fctx->attributes |= FCTX_ATTR_ADDRWAIT;
3052                         return;
3053                 } else if (result != ISC_R_SUCCESS) {
3054                         /*
3055                          * Something bad happened.
3056                          */
3057                         fctx_done(fctx, result, __LINE__);
3058                         return;
3059                 }
3060
3061                 addrinfo = fctx_nextaddress(fctx);
3062                 /*
3063                  * While we may have addresses from the ADB, they
3064                  * might be bad ones.  In this case, return SERVFAIL.
3065                  */
3066                 if (addrinfo == NULL) {
3067                         fctx_done(fctx, DNS_R_SERVFAIL, __LINE__);
3068                         return;
3069                 }
3070         }
3071
3072         result = fctx_query(fctx, addrinfo, fctx->options);
3073         if (result != ISC_R_SUCCESS)
3074                 fctx_done(fctx, result, __LINE__);
3075         else if (retrying)
3076                 inc_stats(fctx->res, dns_resstatscounter_retry);
3077 }
3078
3079 static isc_boolean_t
3080 fctx_destroy(fetchctx_t *fctx) {
3081         dns_resolver_t *res;
3082         unsigned int bucketnum;
3083         isc_sockaddr_t *sa, *next_sa;
3084
3085         /*
3086          * Caller must be holding the bucket lock.
3087          */
3088
3089         REQUIRE(VALID_FCTX(fctx));
3090         REQUIRE(fctx->state == fetchstate_done ||
3091                 fctx->state == fetchstate_init);
3092         REQUIRE(ISC_LIST_EMPTY(fctx->events));
3093         REQUIRE(ISC_LIST_EMPTY(fctx->queries));
3094         REQUIRE(ISC_LIST_EMPTY(fctx->finds));
3095         REQUIRE(ISC_LIST_EMPTY(fctx->altfinds));
3096         REQUIRE(fctx->pending == 0);
3097         REQUIRE(fctx->references == 0);
3098         REQUIRE(ISC_LIST_EMPTY(fctx->validators));
3099
3100         FCTXTRACE("destroy");
3101
3102         res = fctx->res;
3103         bucketnum = fctx->bucketnum;
3104
3105         ISC_LIST_UNLINK(res->buckets[bucketnum].fctxs, fctx, link);
3106
3107         /*
3108          * Free bad.
3109          */
3110         for (sa = ISC_LIST_HEAD(fctx->bad);
3111              sa != NULL;
3112              sa = next_sa) {
3113                 next_sa = ISC_LIST_NEXT(sa, link);
3114                 ISC_LIST_UNLINK(fctx->bad, sa, link);
3115                 isc_mem_put(res->buckets[bucketnum].mctx, sa, sizeof(*sa));
3116         }
3117
3118         for (sa = ISC_LIST_HEAD(fctx->edns);
3119              sa != NULL;
3120              sa = next_sa) {
3121                 next_sa = ISC_LIST_NEXT(sa, link);
3122                 ISC_LIST_UNLINK(fctx->edns, sa, link);
3123                 isc_mem_put(res->buckets[bucketnum].mctx, sa, sizeof(*sa));
3124         }
3125
3126         for (sa = ISC_LIST_HEAD(fctx->edns512);
3127              sa != NULL;
3128              sa = next_sa) {
3129                 next_sa = ISC_LIST_NEXT(sa, link);
3130                 ISC_LIST_UNLINK(fctx->edns512, sa, link);
3131                 isc_mem_put(res->buckets[bucketnum].mctx, sa, sizeof(*sa));
3132         }
3133
3134         isc_timer_detach(&fctx->timer);
3135         dns_message_destroy(&fctx->rmessage);
3136         dns_message_destroy(&fctx->qmessage);
3137         if (dns_name_countlabels(&fctx->domain) > 0)
3138                 dns_name_free(&fctx->domain, res->buckets[bucketnum].mctx);
3139         if (dns_rdataset_isassociated(&fctx->nameservers))
3140                 dns_rdataset_disassociate(&fctx->nameservers);
3141         dns_name_free(&fctx->name, res->buckets[bucketnum].mctx);
3142         dns_db_detach(&fctx->cache);
3143         dns_adb_detach(&fctx->adb);
3144         isc_mem_free(res->buckets[bucketnum].mctx, fctx->info);
3145         isc_mem_put(res->buckets[bucketnum].mctx, fctx, sizeof(*fctx));
3146
3147         LOCK(&res->nlock);
3148         res->nfctx--;
3149         UNLOCK(&res->nlock);
3150
3151         if (res->buckets[bucketnum].exiting &&
3152             ISC_LIST_EMPTY(res->buckets[bucketnum].fctxs))
3153                 return (ISC_TRUE);
3154
3155         return (ISC_FALSE);
3156 }
3157
3158 /*
3159  * Fetch event handlers.
3160  */
3161
3162 static void
3163 fctx_timeout(isc_task_t *task, isc_event_t *event) {
3164         fetchctx_t *fctx = event->ev_arg;
3165         isc_timerevent_t *tevent = (isc_timerevent_t *)event;
3166         resquery_t *query;
3167
3168         REQUIRE(VALID_FCTX(fctx));
3169
3170         UNUSED(task);
3171
3172         FCTXTRACE("timeout");
3173
3174         inc_stats(fctx->res, dns_resstatscounter_querytimeout);
3175
3176         if (event->ev_type == ISC_TIMEREVENT_LIFE) {
3177                 fctx->reason = NULL;
3178                 fctx_done(fctx, ISC_R_TIMEDOUT, __LINE__);
3179         } else {
3180                 isc_result_t result;
3181
3182                 fctx->timeouts++;
3183                 fctx->timeout = ISC_TRUE;
3184                 /*
3185                  * We could cancel the running queries here, or we could let
3186                  * them keep going.  Since we normally use separate sockets for
3187                  * different queries, we adopt the former approach to reduce
3188                  * the number of open sockets: cancel the oldest query if it
3189                  * expired after the query had started (this is usually the
3190                  * case but is not always so, depending on the task schedule
3191                  * timing).
3192                  */
3193                 query = ISC_LIST_HEAD(fctx->queries);
3194                 if (query != NULL &&
3195                     isc_time_compare(&tevent->due, &query->start) >= 0) {
3196                         fctx_cancelquery(&query, NULL, NULL, ISC_TRUE);
3197                 }
3198                 fctx->attributes &= ~FCTX_ATTR_ADDRWAIT;
3199                 /*
3200                  * Our timer has triggered.  Reestablish the fctx lifetime
3201                  * timer.
3202                  */
3203                 result = fctx_starttimer(fctx);
3204                 if (result != ISC_R_SUCCESS)
3205                         fctx_done(fctx, result, __LINE__);
3206                 else
3207                         /*
3208                          * Keep trying.
3209                          */
3210                         fctx_try(fctx, ISC_TRUE, ISC_FALSE);
3211         }
3212
3213         isc_event_free(&event);
3214 }
3215
3216 static void
3217 fctx_shutdown(fetchctx_t *fctx) {
3218         isc_event_t *cevent;
3219
3220         /*
3221          * Start the shutdown process for fctx, if it isn't already underway.
3222          */
3223
3224         FCTXTRACE("shutdown");
3225
3226         /*
3227          * The caller must be holding the appropriate bucket lock.
3228          */
3229
3230         if (fctx->want_shutdown)
3231                 return;
3232
3233         fctx->want_shutdown = ISC_TRUE;
3234
3235         /*
3236          * Unless we're still initializing (in which case the
3237          * control event is still outstanding), we need to post
3238          * the control event to tell the fetch we want it to
3239          * exit.
3240          */
3241         if (fctx->state != fetchstate_init) {
3242                 cevent = &fctx->control_event;
3243                 isc_task_send(fctx->res->buckets[fctx->bucketnum].task,
3244                               &cevent);
3245         }
3246 }
3247
3248 static void
3249 fctx_doshutdown(isc_task_t *task, isc_event_t *event) {
3250         fetchctx_t *fctx = event->ev_arg;
3251         isc_boolean_t bucket_empty = ISC_FALSE;
3252         dns_resolver_t *res;
3253         unsigned int bucketnum;
3254         dns_validator_t *validator;
3255
3256         REQUIRE(VALID_FCTX(fctx));
3257
3258         UNUSED(task);
3259
3260         res = fctx->res;
3261         bucketnum = fctx->bucketnum;
3262
3263         FCTXTRACE("doshutdown");
3264
3265         /*
3266          * An fctx that is shutting down is no longer in ADDRWAIT mode.
3267          */
3268         fctx->attributes &= ~FCTX_ATTR_ADDRWAIT;
3269
3270         /*
3271          * Cancel all pending validators.  Note that this must be done
3272          * without the bucket lock held, since that could cause deadlock.
3273          */
3274         validator = ISC_LIST_HEAD(fctx->validators);
3275         while (validator != NULL) {
3276                 dns_validator_cancel(validator);
3277                 validator = ISC_LIST_NEXT(validator, link);
3278         }
3279
3280         if (fctx->nsfetch != NULL)
3281                 dns_resolver_cancelfetch(fctx->nsfetch);
3282
3283         /*
3284          * Shut down anything that is still running on behalf of this
3285          * fetch.  To avoid deadlock with the ADB, we must do this
3286          * before we lock the bucket lock.
3287          */
3288         fctx_stopeverything(fctx, ISC_FALSE);
3289
3290         LOCK(&res->buckets[bucketnum].lock);
3291
3292         fctx->attributes |= FCTX_ATTR_SHUTTINGDOWN;
3293
3294         INSIST(fctx->state == fetchstate_active ||
3295                fctx->state == fetchstate_done);
3296         INSIST(fctx->want_shutdown);
3297
3298         if (fctx->state != fetchstate_done) {
3299                 fctx->state = fetchstate_done;
3300                 fctx_sendevents(fctx, ISC_R_CANCELED, __LINE__);
3301         }
3302
3303         if (fctx->references == 0 && fctx->pending == 0 &&
3304             fctx->nqueries == 0 && ISC_LIST_EMPTY(fctx->validators))
3305                 bucket_empty = fctx_destroy(fctx);
3306
3307         UNLOCK(&res->buckets[bucketnum].lock);
3308
3309         if (bucket_empty)
3310                 empty_bucket(res);
3311 }
3312
3313 static void
3314 fctx_start(isc_task_t *task, isc_event_t *event) {
3315         fetchctx_t *fctx = event->ev_arg;
3316         isc_boolean_t done = ISC_FALSE, bucket_empty = ISC_FALSE;
3317         dns_resolver_t *res;
3318         unsigned int bucketnum;
3319
3320         REQUIRE(VALID_FCTX(fctx));
3321
3322         UNUSED(task);
3323
3324         res = fctx->res;
3325         bucketnum = fctx->bucketnum;
3326
3327         FCTXTRACE("start");
3328
3329         LOCK(&res->buckets[bucketnum].lock);
3330
3331         INSIST(fctx->state == fetchstate_init);
3332         if (fctx->want_shutdown) {
3333                 /*
3334                  * We haven't started this fctx yet, and we've been requested
3335                  * to shut it down.
3336                  */
3337                 fctx->attributes |= FCTX_ATTR_SHUTTINGDOWN;
3338                 fctx->state = fetchstate_done;
3339                 fctx_sendevents(fctx, ISC_R_CANCELED, __LINE__);
3340                 /*
3341                  * Since we haven't started, we INSIST that we have no
3342                  * pending ADB finds and no pending validations.
3343                  */
3344                 INSIST(fctx->pending == 0);
3345                 INSIST(fctx->nqueries == 0);
3346                 INSIST(ISC_LIST_EMPTY(fctx->validators));
3347                 if (fctx->references == 0) {
3348                         /*
3349                          * It's now safe to destroy this fctx.
3350                          */
3351                         bucket_empty = fctx_destroy(fctx);
3352                 }
3353                 done = ISC_TRUE;
3354         } else {
3355                 /*
3356                  * Normal fctx startup.
3357                  */
3358                 fctx->state = fetchstate_active;
3359                 /*
3360                  * Reset the control event for later use in shutting down
3361                  * the fctx.
3362                  */
3363                 ISC_EVENT_INIT(event, sizeof(*event), 0, NULL,
3364                                DNS_EVENT_FETCHCONTROL, fctx_doshutdown, fctx,
3365                                NULL, NULL, NULL);
3366         }
3367
3368         UNLOCK(&res->buckets[bucketnum].lock);
3369
3370         if (!done) {
3371                 isc_result_t result;
3372
3373                 /*
3374                  * All is well.  Start working on the fetch.
3375                  */
3376                 result = fctx_starttimer(fctx);
3377                 if (result != ISC_R_SUCCESS)
3378                         fctx_done(fctx, result, __LINE__);
3379                 else
3380                         fctx_try(fctx, ISC_FALSE, ISC_FALSE);
3381         } else if (bucket_empty)
3382                 empty_bucket(res);
3383 }
3384
3385 /*
3386  * Fetch Creation, Joining, and Cancelation.
3387  */
3388
3389 static inline isc_result_t
3390 fctx_join(fetchctx_t *fctx, isc_task_t *task, isc_sockaddr_t *client,
3391           dns_messageid_t id, isc_taskaction_t action, void *arg,
3392           dns_rdataset_t *rdataset, dns_rdataset_t *sigrdataset,
3393           dns_fetch_t *fetch)
3394 {
3395         isc_task_t *clone;
3396         dns_fetchevent_t *event;
3397
3398         FCTXTRACE("join");
3399
3400         /*
3401          * We store the task we're going to send this event to in the
3402          * sender field.  We'll make the fetch the sender when we actually
3403          * send the event.
3404          */
3405         clone = NULL;
3406         isc_task_attach(task, &clone);
3407         event = (dns_fetchevent_t *)
3408                 isc_event_allocate(fctx->res->mctx, clone, DNS_EVENT_FETCHDONE,
3409                                    action, arg, sizeof(*event));
3410         if (event == NULL) {
3411                 isc_task_detach(&clone);
3412                 return (ISC_R_NOMEMORY);
3413         }
3414         event->result = DNS_R_SERVFAIL;
3415         event->qtype = fctx->type;
3416         event->db = NULL;
3417         event->node = NULL;
3418         event->rdataset = rdataset;
3419         event->sigrdataset = sigrdataset;
3420         event->fetch = fetch;
3421         event->client = client;
3422         event->id = id;
3423         dns_fixedname_init(&event->foundname);
3424
3425         /*
3426          * Make sure that we can store the sigrdataset in the
3427          * first event if it is needed by any of the events.
3428          */
3429         if (event->sigrdataset != NULL)
3430                 ISC_LIST_PREPEND(fctx->events, event, ev_link);
3431         else
3432                 ISC_LIST_APPEND(fctx->events, event, ev_link);
3433         fctx->references++;
3434
3435         fetch->magic = DNS_FETCH_MAGIC;
3436         fetch->private = fctx;
3437
3438         return (ISC_R_SUCCESS);
3439 }
3440
3441 static isc_result_t
3442 fctx_create(dns_resolver_t *res, dns_name_t *name, dns_rdatatype_t type,
3443             dns_name_t *domain, dns_rdataset_t *nameservers,
3444             unsigned int options, unsigned int bucketnum, fetchctx_t **fctxp)
3445 {
3446         fetchctx_t *fctx;
3447         isc_result_t result;
3448         isc_result_t iresult;
3449         isc_interval_t interval;
3450         dns_fixedname_t fixed;
3451         unsigned int findoptions = 0;
3452         char buf[DNS_NAME_FORMATSIZE + DNS_RDATATYPE_FORMATSIZE];
3453         char typebuf[DNS_RDATATYPE_FORMATSIZE];
3454         dns_name_t suffix;
3455
3456         /*
3457          * Caller must be holding the lock for bucket number 'bucketnum'.
3458          */
3459         REQUIRE(fctxp != NULL && *fctxp == NULL);
3460
3461         fctx = isc_mem_get(res->buckets[bucketnum].mctx, sizeof(*fctx));
3462         if (fctx == NULL)
3463                 return (ISC_R_NOMEMORY);
3464         dns_name_format(name, buf, sizeof(buf));
3465         dns_rdatatype_format(type, typebuf, sizeof(typebuf));
3466         strcat(buf, "/");       /* checked */
3467         strcat(buf, typebuf);   /* checked */
3468         fctx->info = isc_mem_strdup(res->buckets[bucketnum].mctx, buf);
3469         if (fctx->info == NULL) {
3470                 result = ISC_R_NOMEMORY;
3471                 goto cleanup_fetch;
3472         }
3473         FCTXTRACE("create");
3474         dns_name_init(&fctx->name, NULL);
3475         result = dns_name_dup(name, res->buckets[bucketnum].mctx, &fctx->name);
3476         if (result != ISC_R_SUCCESS)
3477                 goto cleanup_info;
3478         dns_name_init(&fctx->domain, NULL);
3479         dns_rdataset_init(&fctx->nameservers);
3480
3481         fctx->type = type;
3482         fctx->options = options;
3483         /*
3484          * Note!  We do not attach to the task.  We are relying on the
3485          * resolver to ensure that this task doesn't go away while we are
3486          * using it.
3487          */
3488         fctx->res = res;
3489         fctx->references = 0;
3490         fctx->bucketnum = bucketnum;
3491         fctx->state = fetchstate_init;
3492         fctx->want_shutdown = ISC_FALSE;
3493         fctx->cloned = ISC_FALSE;
3494         ISC_LIST_INIT(fctx->queries);
3495         ISC_LIST_INIT(fctx->finds);
3496         ISC_LIST_INIT(fctx->altfinds);
3497         ISC_LIST_INIT(fctx->forwaddrs);
3498         ISC_LIST_INIT(fctx->altaddrs);
3499         ISC_LIST_INIT(fctx->forwarders);
3500         fctx->fwdpolicy = dns_fwdpolicy_none;
3501         ISC_LIST_INIT(fctx->bad);
3502         ISC_LIST_INIT(fctx->edns);
3503         ISC_LIST_INIT(fctx->edns512);
3504         ISC_LIST_INIT(fctx->validators);
3505         fctx->validator = NULL;
3506         fctx->find = NULL;
3507         fctx->altfind = NULL;
3508         fctx->pending = 0;
3509         fctx->restarts = 0;
3510         fctx->querysent = 0;
3511         fctx->referrals = 0;
3512         TIME_NOW(&fctx->start);
3513         fctx->timeouts = 0;
3514         fctx->lamecount = 0;
3515         fctx->adberr = 0;
3516         fctx->neterr = 0;
3517         fctx->badresp = 0;
3518         fctx->findfail = 0;
3519         fctx->valfail = 0;
3520         fctx->result = ISC_R_FAILURE;
3521         fctx->vresult = ISC_R_SUCCESS;
3522         fctx->exitline = -1;    /* sentinel */
3523         fctx->logged = ISC_FALSE;
3524         fctx->attributes = 0;
3525         fctx->spilled = ISC_FALSE;
3526         fctx->nqueries = 0;
3527         fctx->reason = NULL;
3528         fctx->rand_buf = 0;
3529         fctx->rand_bits = 0;
3530         fctx->timeout = ISC_FALSE;
3531
3532         dns_name_init(&fctx->nsname, NULL);
3533         fctx->nsfetch = NULL;
3534         dns_rdataset_init(&fctx->nsrrset);
3535
3536         if (domain == NULL) {
3537                 dns_forwarders_t *forwarders = NULL;
3538                 unsigned int labels;
3539                 dns_name_t *fwdname = name;
3540
3541                 /*
3542                  * DS records are found in the parent server.
3543                  * Strip label to get the correct forwarder (if any).
3544                  */
3545                 if (dns_rdatatype_atparent(fctx->type) &&
3546                     dns_name_countlabels(name) > 1) {
3547                         dns_name_init(&suffix, NULL);
3548                         labels = dns_name_countlabels(name);
3549                         dns_name_getlabelsequence(name, 1, labels - 1, &suffix);
3550                         fwdname = &suffix;
3551                 }
3552                 dns_fixedname_init(&fixed);
3553                 domain = dns_fixedname_name(&fixed);
3554                 result = dns_fwdtable_find2(fctx->res->view->fwdtable, fwdname,
3555                                             domain, &forwarders);
3556                 if (result == ISC_R_SUCCESS)
3557                         fctx->fwdpolicy = forwarders->fwdpolicy;
3558
3559                 if (fctx->fwdpolicy != dns_fwdpolicy_only) {
3560                         /*
3561                          * The caller didn't supply a query domain and
3562                          * nameservers, and we're not in forward-only mode,
3563                          * so find the best nameservers to use.
3564                          */
3565                         if (dns_rdatatype_atparent(fctx->type))
3566                                 findoptions |= DNS_DBFIND_NOEXACT;
3567                         result = dns_view_findzonecut(res->view, name, domain,
3568                                                       0, findoptions, ISC_TRUE,
3569                                                       &fctx->nameservers,
3570                                                       NULL);
3571                         if (result != ISC_R_SUCCESS)
3572                                 goto cleanup_name;
3573                         result = dns_name_dup(domain,
3574                                               res->buckets[bucketnum].mctx,
3575                                               &fctx->domain);
3576                         if (result != ISC_R_SUCCESS) {
3577                                 dns_rdataset_disassociate(&fctx->nameservers);
3578                                 goto cleanup_name;
3579                         }
3580                 } else {
3581                         /*
3582                          * We're in forward-only mode.  Set the query domain.
3583                          */
3584                         result = dns_name_dup(domain,
3585                                               res->buckets[bucketnum].mctx,
3586                                               &fctx->domain);
3587                         if (result != ISC_R_SUCCESS)
3588                                 goto cleanup_name;
3589                 }
3590         } else {
3591                 result = dns_name_dup(domain,
3592                                       res->buckets[bucketnum].mctx,
3593                                       &fctx->domain);
3594                 if (result != ISC_R_SUCCESS)
3595                         goto cleanup_name;
3596                 dns_rdataset_clone(nameservers, &fctx->nameservers);
3597         }
3598
3599         INSIST(dns_name_issubdomain(&fctx->name, &fctx->domain));
3600
3601         fctx->qmessage = NULL;
3602         result = dns_message_create(res->buckets[bucketnum].mctx,
3603                                     DNS_MESSAGE_INTENTRENDER,
3604                                     &fctx->qmessage);
3605
3606         if (result != ISC_R_SUCCESS)
3607                 goto cleanup_domain;
3608
3609         fctx->rmessage = NULL;
3610         result = dns_message_create(res->buckets[bucketnum].mctx,
3611                                     DNS_MESSAGE_INTENTPARSE,
3612                                     &fctx->rmessage);
3613
3614         if (result != ISC_R_SUCCESS)
3615                 goto cleanup_qmessage;
3616
3617         /*
3618          * Compute an expiration time for the entire fetch.
3619          */
3620         isc_interval_set(&interval, 30, 0);             /* XXXRTH constant */
3621         iresult = isc_time_nowplusinterval(&fctx->expires, &interval);
3622         if (iresult != ISC_R_SUCCESS) {
3623                 UNEXPECTED_ERROR(__FILE__, __LINE__,
3624                                  "isc_time_nowplusinterval: %s",
3625                                  isc_result_totext(iresult));
3626                 result = ISC_R_UNEXPECTED;
3627                 goto cleanup_rmessage;
3628         }
3629
3630         /*
3631          * Default retry interval initialization.  We set the interval now
3632          * mostly so it won't be uninitialized.  It will be set to the
3633          * correct value before a query is issued.
3634          */
3635         isc_interval_set(&fctx->interval, 2, 0);
3636
3637         /*
3638          * Create an inactive timer.  It will be made active when the fetch
3639          * is actually started.
3640          */
3641         fctx->timer = NULL;
3642         iresult = isc_timer_create(res->timermgr, isc_timertype_inactive,
3643                                    NULL, NULL,
3644                                    res->buckets[bucketnum].task, fctx_timeout,
3645                                    fctx, &fctx->timer);
3646         if (iresult != ISC_R_SUCCESS) {
3647                 UNEXPECTED_ERROR(__FILE__, __LINE__,
3648                                  "isc_timer_create: %s",
3649                                  isc_result_totext(iresult));
3650                 result = ISC_R_UNEXPECTED;
3651                 goto cleanup_rmessage;
3652         }
3653
3654         /*
3655          * Attach to the view's cache and adb.
3656          */
3657         fctx->cache = NULL;
3658         dns_db_attach(res->view->cachedb, &fctx->cache);
3659         fctx->adb = NULL;
3660         dns_adb_attach(res->view->adb, &fctx->adb);
3661
3662         ISC_LIST_INIT(fctx->events);
3663         ISC_LINK_INIT(fctx, link);
3664         fctx->magic = FCTX_MAGIC;
3665
3666         ISC_LIST_APPEND(res->buckets[bucketnum].fctxs, fctx, link);
3667
3668         LOCK(&res->nlock);
3669         res->nfctx++;
3670         UNLOCK(&res->nlock);
3671
3672         *fctxp = fctx;
3673
3674         return (ISC_R_SUCCESS);
3675
3676  cleanup_rmessage:
3677         dns_message_destroy(&fctx->rmessage);
3678
3679  cleanup_qmessage:
3680         dns_message_destroy(&fctx->qmessage);
3681
3682  cleanup_domain:
3683         if (dns_name_countlabels(&fctx->domain) > 0)
3684                 dns_name_free(&fctx->domain, res->buckets[bucketnum].mctx);
3685         if (dns_rdataset_isassociated(&fctx->nameservers))
3686                 dns_rdataset_disassociate(&fctx->nameservers);
3687
3688  cleanup_name:
3689         dns_name_free(&fctx->name, res->buckets[bucketnum].mctx);
3690
3691  cleanup_info:
3692         isc_mem_free(res->buckets[bucketnum].mctx, fctx->info);
3693
3694  cleanup_fetch:
3695         isc_mem_put(res->buckets[bucketnum].mctx, fctx, sizeof(*fctx));
3696
3697         return (result);
3698 }
3699
3700 /*
3701  * Handle Responses
3702  */
3703 static inline isc_boolean_t
3704 is_lame(fetchctx_t *fctx) {
3705         dns_message_t *message = fctx->rmessage;
3706         dns_name_t *name;
3707         dns_rdataset_t *rdataset;
3708         isc_result_t result;
3709
3710         if (message->rcode != dns_rcode_noerror &&
3711             message->rcode != dns_rcode_nxdomain)
3712                 return (ISC_FALSE);
3713
3714         if (message->counts[DNS_SECTION_ANSWER] != 0)
3715                 return (ISC_FALSE);
3716
3717         if (message->counts[DNS_SECTION_AUTHORITY] == 0)
3718                 return (ISC_FALSE);
3719
3720         result = dns_message_firstname(message, DNS_SECTION_AUTHORITY);
3721         while (result == ISC_R_SUCCESS) {
3722                 name = NULL;
3723                 dns_message_currentname(message, DNS_SECTION_AUTHORITY, &name);
3724                 for (rdataset = ISC_LIST_HEAD(name->list);
3725                      rdataset != NULL;
3726                      rdataset = ISC_LIST_NEXT(rdataset, link)) {
3727                         dns_namereln_t namereln;
3728                         int order;
3729                         unsigned int labels;
3730                         if (rdataset->type != dns_rdatatype_ns)
3731                                 continue;
3732                         namereln = dns_name_fullcompare(name, &fctx->domain,
3733                                                         &order, &labels);
3734                         if (namereln == dns_namereln_equal &&
3735                             (message->flags & DNS_MESSAGEFLAG_AA) != 0)
3736                                 return (ISC_FALSE);
3737                         if (namereln == dns_namereln_subdomain)
3738                                 return (ISC_FALSE);
3739                         return (ISC_TRUE);
3740                 }
3741                 result = dns_message_nextname(message, DNS_SECTION_AUTHORITY);
3742         }
3743
3744         return (ISC_FALSE);
3745 }
3746
3747 static inline void
3748 log_lame(fetchctx_t *fctx, dns_adbaddrinfo_t *addrinfo) {
3749         char namebuf[DNS_NAME_FORMATSIZE];
3750         char domainbuf[DNS_NAME_FORMATSIZE];
3751         char addrbuf[ISC_SOCKADDR_FORMATSIZE];
3752
3753         dns_name_format(&fctx->name, namebuf, sizeof(namebuf));
3754         dns_name_format(&fctx->domain, domainbuf, sizeof(domainbuf));
3755         isc_sockaddr_format(&addrinfo->sockaddr, addrbuf, sizeof(addrbuf));
3756         isc_log_write(dns_lctx, DNS_LOGCATEGORY_LAME_SERVERS,
3757                       DNS_LOGMODULE_RESOLVER, ISC_LOG_INFO,
3758                       "lame server resolving '%s' (in '%s'?): %s",
3759                       namebuf, domainbuf, addrbuf);
3760 }
3761
3762 static inline isc_result_t
3763 same_question(fetchctx_t *fctx) {
3764         isc_result_t result;
3765         dns_message_t *message = fctx->rmessage;
3766         dns_name_t *name;
3767         dns_rdataset_t *rdataset;
3768
3769         /*
3770          * Caller must be holding the fctx lock.
3771          */
3772
3773         /*
3774          * XXXRTH  Currently we support only one question.
3775          */
3776         if (message->counts[DNS_SECTION_QUESTION] != 1)
3777                 return (DNS_R_FORMERR);
3778
3779         result = dns_message_firstname(message, DNS_SECTION_QUESTION);
3780         if (result != ISC_R_SUCCESS)
3781                 return (result);
3782         name = NULL;
3783         dns_message_currentname(message, DNS_SECTION_QUESTION, &name);
3784         rdataset = ISC_LIST_HEAD(name->list);
3785         INSIST(rdataset != NULL);
3786         INSIST(ISC_LIST_NEXT(rdataset, link) == NULL);
3787         if (fctx->type != rdataset->type ||
3788             fctx->res->rdclass != rdataset->rdclass ||
3789             !dns_name_equal(&fctx->name, name))
3790                 return (DNS_R_FORMERR);
3791
3792         return (ISC_R_SUCCESS);
3793 }
3794
3795 static void
3796 clone_results(fetchctx_t *fctx) {
3797         dns_fetchevent_t *event, *hevent;
3798         isc_result_t result;
3799         dns_name_t *name, *hname;
3800
3801         FCTXTRACE("clone_results");
3802
3803         /*
3804          * Set up any other events to have the same data as the first
3805          * event.
3806          *
3807          * Caller must be holding the appropriate lock.
3808          */
3809
3810         fctx->cloned = ISC_TRUE;
3811         hevent = ISC_LIST_HEAD(fctx->events);
3812         if (hevent == NULL)
3813                 return;
3814         hname = dns_fixedname_name(&hevent->foundname);
3815         for (event = ISC_LIST_NEXT(hevent, ev_link);
3816              event != NULL;
3817              event = ISC_LIST_NEXT(event, ev_link)) {
3818                 name = dns_fixedname_name(&event->foundname);
3819                 result = dns_name_copy(hname, name, NULL);
3820                 if (result != ISC_R_SUCCESS)
3821                         event->result = result;
3822                 else
3823                         event->result = hevent->result;
3824                 dns_db_attach(hevent->db, &event->db);
3825                 dns_db_attachnode(hevent->db, hevent->node, &event->node);
3826                 INSIST(hevent->rdataset != NULL);
3827                 INSIST(event->rdataset != NULL);
3828                 if (dns_rdataset_isassociated(hevent->rdataset))
3829                         dns_rdataset_clone(hevent->rdataset, event->rdataset);
3830                 INSIST(! (hevent->sigrdataset == NULL &&
3831                           event->sigrdataset != NULL));
3832                 if (hevent->sigrdataset != NULL &&
3833                     dns_rdataset_isassociated(hevent->sigrdataset) &&
3834                     event->sigrdataset != NULL)
3835                         dns_rdataset_clone(hevent->sigrdataset,
3836                                            event->sigrdataset);
3837         }
3838 }
3839
3840 #define CACHE(r)        (((r)->attributes & DNS_RDATASETATTR_CACHE) != 0)
3841 #define ANSWER(r)       (((r)->attributes & DNS_RDATASETATTR_ANSWER) != 0)
3842 #define ANSWERSIG(r)    (((r)->attributes & DNS_RDATASETATTR_ANSWERSIG) != 0)
3843 #define EXTERNAL(r)     (((r)->attributes & DNS_RDATASETATTR_EXTERNAL) != 0)
3844 #define CHAINING(r)     (((r)->attributes & DNS_RDATASETATTR_CHAINING) != 0)
3845 #define CHASE(r)        (((r)->attributes & DNS_RDATASETATTR_CHASE) != 0)
3846 #define CHECKNAMES(r)   (((r)->attributes & DNS_RDATASETATTR_CHECKNAMES) != 0)
3847
3848
3849 /*
3850  * Destroy '*fctx' if it is ready to be destroyed (i.e., if it has
3851  * no references and is no longer waiting for any events).  If this
3852  * was the last fctx in the resolver, destroy the resolver.
3853  *
3854  * Requires:
3855  *      '*fctx' is shutting down.
3856  */
3857 static void
3858 maybe_destroy(fetchctx_t *fctx) {
3859         unsigned int bucketnum;
3860         isc_boolean_t bucket_empty = ISC_FALSE;
3861         dns_resolver_t *res = fctx->res;
3862         dns_validator_t *validator, *next_validator;
3863
3864         REQUIRE(SHUTTINGDOWN(fctx));
3865
3866         if (fctx->pending != 0 || fctx->nqueries != 0)
3867                 return;
3868
3869         for (validator = ISC_LIST_HEAD(fctx->validators);
3870              validator != NULL; validator = next_validator) {
3871                 next_validator = ISC_LIST_NEXT(validator, link);
3872                 dns_validator_cancel(validator);
3873                 /*
3874                  * If this is a active validator wait for the cancel
3875                  * to complete before calling dns_validator_destroy().
3876                  */
3877                 if (validator == fctx->validator)
3878                         continue;
3879                 ISC_LIST_UNLINK(fctx->validators, validator, link);
3880                 dns_validator_destroy(&validator);
3881         }
3882
3883         bucketnum = fctx->bucketnum;
3884         LOCK(&res->buckets[bucketnum].lock);
3885         if (fctx->references == 0 && ISC_LIST_EMPTY(fctx->validators))
3886                 bucket_empty = fctx_destroy(fctx);
3887         UNLOCK(&res->buckets[bucketnum].lock);
3888
3889         if (bucket_empty)
3890                 empty_bucket(res);
3891 }
3892
3893 /*
3894  * The validator has finished.
3895  */
3896 static void
3897 validated(isc_task_t *task, isc_event_t *event) {
3898         isc_result_t result = ISC_R_SUCCESS;
3899         isc_result_t eresult = ISC_R_SUCCESS;
3900         isc_stdtime_t now;
3901         fetchctx_t *fctx;
3902         dns_validatorevent_t *vevent;
3903         dns_fetchevent_t *hevent;
3904         dns_rdataset_t *ardataset = NULL;
3905         dns_rdataset_t *asigrdataset = NULL;
3906         dns_dbnode_t *node = NULL;
3907         isc_boolean_t negative;
3908         isc_boolean_t chaining;
3909         isc_boolean_t sentresponse;
3910         isc_uint32_t ttl;
3911         dns_dbnode_t *nsnode = NULL;
3912         dns_name_t *name;
3913         dns_rdataset_t *rdataset;
3914         dns_rdataset_t *sigrdataset;
3915         dns_valarg_t *valarg;
3916         dns_adbaddrinfo_t *addrinfo;
3917
3918         UNUSED(task); /* for now */
3919
3920         REQUIRE(event->ev_type == DNS_EVENT_VALIDATORDONE);
3921         valarg = event->ev_arg;
3922         fctx = valarg->fctx;
3923         addrinfo = valarg->addrinfo;
3924         REQUIRE(VALID_FCTX(fctx));
3925         REQUIRE(!ISC_LIST_EMPTY(fctx->validators));
3926
3927         vevent = (dns_validatorevent_t *)event;
3928
3929         FCTXTRACE("received validation completion event");
3930
3931         ISC_LIST_UNLINK(fctx->validators, vevent->validator, link);
3932         fctx->validator = NULL;
3933
3934         /*
3935          * Destroy the validator early so that we can
3936          * destroy the fctx if necessary.
3937          */
3938         dns_validator_destroy(&vevent->validator);
3939         isc_mem_put(fctx->res->buckets[fctx->bucketnum].mctx,
3940                     valarg, sizeof(*valarg));
3941
3942         negative = ISC_TF(vevent->rdataset == NULL);
3943
3944         sentresponse = ISC_TF((fctx->options & DNS_FETCHOPT_NOVALIDATE) != 0);
3945
3946         /*
3947          * If shutting down, ignore the results.  Check to see if we're
3948          * done waiting for validator completions and ADB pending events; if
3949          * so, destroy the fctx.
3950          */
3951         if (SHUTTINGDOWN(fctx) && !sentresponse) {
3952                 maybe_destroy(fctx);    /* Locks bucket. */
3953                 goto cleanup_event;
3954         }
3955
3956         LOCK(&fctx->res->buckets[fctx->bucketnum].lock);
3957
3958         isc_stdtime_get(&now);
3959
3960         /*
3961          * If chaining, we need to make sure that the right result code is
3962          * returned, and that the rdatasets are bound.
3963          */
3964         if (vevent->result == ISC_R_SUCCESS &&
3965             !negative &&
3966             vevent->rdataset != NULL &&
3967             CHAINING(vevent->rdataset))
3968         {
3969                 if (vevent->rdataset->type == dns_rdatatype_cname)
3970                         eresult = DNS_R_CNAME;
3971                 else {
3972                         INSIST(vevent->rdataset->type == dns_rdatatype_dname);
3973                         eresult = DNS_R_DNAME;
3974                 }
3975                 chaining = ISC_TRUE;
3976         } else
3977                 chaining = ISC_FALSE;
3978
3979         /*
3980          * Either we're not shutting down, or we are shutting down but want
3981          * to cache the result anyway (if this was a validation started by
3982          * a query with cd set)
3983          */
3984
3985         hevent = ISC_LIST_HEAD(fctx->events);
3986         if (hevent != NULL) {
3987                 if (!negative && !chaining &&
3988                     (fctx->type == dns_rdatatype_any ||
3989                      fctx->type == dns_rdatatype_rrsig ||
3990                      fctx->type == dns_rdatatype_sig)) {
3991                         /*
3992                          * Don't bind rdatasets; the caller
3993                          * will iterate the node.
3994                          */
3995                 } else {
3996                         ardataset = hevent->rdataset;
3997                         asigrdataset = hevent->sigrdataset;
3998                 }
3999         }
4000
4001         if (vevent->result != ISC_R_SUCCESS) {
4002                 FCTXTRACE("validation failed");
4003                 inc_stats(fctx->res, dns_resstatscounter_valfail);
4004                 fctx->valfail++;
4005                 fctx->vresult = vevent->result;
4006                 if (fctx->vresult != DNS_R_BROKENCHAIN) {
4007                         result = ISC_R_NOTFOUND;
4008                         if (vevent->rdataset != NULL)
4009                                 result = dns_db_findnode(fctx->cache,
4010                                                          vevent->name,
4011                                                          ISC_TRUE, &node);
4012                         if (result == ISC_R_SUCCESS)
4013                                 (void)dns_db_deleterdataset(fctx->cache, node,
4014                                                              NULL,
4015                                                             vevent->type, 0);
4016                         if (result == ISC_R_SUCCESS &&
4017                              vevent->sigrdataset != NULL)
4018                                 (void)dns_db_deleterdataset(fctx->cache, node,
4019                                                             NULL,
4020                                                             dns_rdatatype_rrsig,
4021                                                             vevent->type);
4022                         if (result == ISC_R_SUCCESS)
4023                                 dns_db_detachnode(fctx->cache, &node);
4024                 }
4025                 if (fctx->vresult == DNS_R_BROKENCHAIN && !negative) {
4026                         /*
4027                          * Cache the data as pending for later validation.
4028                          */
4029                         result = ISC_R_NOTFOUND;
4030                         if (vevent->rdataset != NULL)
4031                                 result = dns_db_findnode(fctx->cache,
4032                                                          vevent->name,
4033                                                          ISC_TRUE, &node);
4034                         if (result == ISC_R_SUCCESS) {
4035                                 (void)dns_db_addrdataset(fctx->cache, node,
4036                                                          NULL, now,
4037                                                          vevent->rdataset, 0,
4038                                                          NULL);
4039                         }
4040                         if (result == ISC_R_SUCCESS &&
4041                             vevent->sigrdataset != NULL)
4042                                 (void)dns_db_addrdataset(fctx->cache, node,
4043                                                          NULL, now,
4044                                                          vevent->sigrdataset,
4045                                                          0, NULL);
4046                         if (result == ISC_R_SUCCESS)
4047                                 dns_db_detachnode(fctx->cache, &node);
4048                 }
4049                 result = fctx->vresult;
4050                 add_bad(fctx, addrinfo, result, badns_validation);
4051                 isc_event_free(&event);
4052                 UNLOCK(&fctx->res->buckets[fctx->bucketnum].lock);
4053                 INSIST(fctx->validator == NULL);
4054                 fctx->validator = ISC_LIST_HEAD(fctx->validators);
4055                 if (fctx->validator != NULL)
4056                         dns_validator_send(fctx->validator);
4057                 else if (sentresponse)
4058                         fctx_done(fctx, result, __LINE__); /* Locks bucket. */
4059                 else if (result == DNS_R_BROKENCHAIN) {
4060                         isc_result_t tresult;
4061                         isc_time_t expire;
4062                         isc_interval_t i;
4063
4064                         isc_interval_set(&i, DNS_BADCACHE_TTL(fctx), 0);
4065                         tresult = isc_time_nowplusinterval(&expire, &i);
4066                         if (negative &&
4067                             (fctx->type == dns_rdatatype_dnskey ||
4068                              fctx->type == dns_rdatatype_dlv ||
4069                              fctx->type == dns_rdatatype_ds) &&
4070                              tresult == ISC_R_SUCCESS)
4071                                 dns_resolver_addbadcache(fctx->res,
4072                                                          &fctx->name,
4073                                                          fctx->type, &expire);
4074                         fctx_done(fctx, result, __LINE__); /* Locks bucket. */
4075                 } else
4076                         fctx_try(fctx, ISC_TRUE, ISC_TRUE); /* Locks bucket. */
4077                 return;
4078         }
4079
4080
4081         if (negative) {
4082                 dns_rdatatype_t covers;
4083                 FCTXTRACE("nonexistence validation OK");
4084
4085                 inc_stats(fctx->res, dns_resstatscounter_valnegsuccess);
4086
4087                 if (fctx->rmessage->rcode == dns_rcode_nxdomain)
4088                         covers = dns_rdatatype_any;
4089                 else
4090                         covers = fctx->type;
4091
4092                 result = dns_db_findnode(fctx->cache, vevent->name, ISC_TRUE,
4093                                          &node);
4094                 if (result != ISC_R_SUCCESS)
4095                         goto noanswer_response;
4096
4097                 /*
4098                  * If we are asking for a SOA record set the cache time
4099                  * to zero to facilitate locating the containing zone of
4100                  * a arbitrary zone.
4101                  */
4102                 ttl = fctx->res->view->maxncachettl;
4103                 if (fctx->type == dns_rdatatype_soa &&
4104                     covers == dns_rdatatype_any &&
4105                     fctx->res->zero_no_soa_ttl)
4106                         ttl = 0;
4107
4108                 result = ncache_adderesult(fctx->rmessage, fctx->cache, node,
4109                                            covers, now, ttl, vevent->optout,
4110                                            ardataset, &eresult);
4111                 if (result != ISC_R_SUCCESS)
4112                         goto noanswer_response;
4113                 goto answer_response;
4114         } else
4115                 inc_stats(fctx->res, dns_resstatscounter_valsuccess);
4116
4117         FCTXTRACE("validation OK");
4118
4119         if (vevent->proofs[DNS_VALIDATOR_NOQNAMEPROOF] != NULL) {
4120
4121                 result = dns_rdataset_addnoqname(vevent->rdataset,
4122                                    vevent->proofs[DNS_VALIDATOR_NOQNAMEPROOF]);
4123                 RUNTIME_CHECK(result == ISC_R_SUCCESS);
4124                 INSIST(vevent->sigrdataset != NULL);
4125                 vevent->sigrdataset->ttl = vevent->rdataset->ttl;
4126                 if (vevent->proofs[DNS_VALIDATOR_CLOSESTENCLOSER] != NULL) {
4127                         result = dns_rdataset_addclosest(vevent->rdataset,
4128                                  vevent->proofs[DNS_VALIDATOR_CLOSESTENCLOSER]);
4129                         RUNTIME_CHECK(result == ISC_R_SUCCESS);
4130                 }
4131         }
4132
4133         /*
4134          * The data was already cached as pending data.
4135          * Re-cache it as secure and bind the cached
4136          * rdatasets to the first event on the fetch
4137          * event list.
4138          */
4139         result = dns_db_findnode(fctx->cache, vevent->name, ISC_TRUE, &node);
4140         if (result != ISC_R_SUCCESS)
4141                 goto noanswer_response;
4142
4143         result = dns_db_addrdataset(fctx->cache, node, NULL, now,
4144                                     vevent->rdataset, 0, ardataset);
4145         if (result != ISC_R_SUCCESS &&
4146             result != DNS_R_UNCHANGED)
4147                 goto noanswer_response;
4148         if (ardataset != NULL && ardataset->type == 0) {
4149                 if (NXDOMAIN(ardataset))
4150                         eresult = DNS_R_NCACHENXDOMAIN;
4151                 else
4152                         eresult = DNS_R_NCACHENXRRSET;
4153         } else if (vevent->sigrdataset != NULL) {
4154                 result = dns_db_addrdataset(fctx->cache, node, NULL, now,
4155                                             vevent->sigrdataset, 0,
4156                                             asigrdataset);
4157                 if (result != ISC_R_SUCCESS &&
4158                     result != DNS_R_UNCHANGED)
4159                         goto noanswer_response;
4160         }
4161
4162         if (sentresponse) {
4163                 /*
4164                  * If we only deferred the destroy because we wanted to cache
4165                  * the data, destroy now.
4166                  */
4167                 dns_db_detachnode(fctx->cache, &node);
4168                 UNLOCK(&fctx->res->buckets[fctx->bucketnum].lock);
4169                 if (SHUTTINGDOWN(fctx))
4170                         maybe_destroy(fctx);    /* Locks bucket. */
4171                 goto cleanup_event;
4172         }
4173
4174         if (!ISC_LIST_EMPTY(fctx->validators)) {
4175                 INSIST(!negative);
4176                 INSIST(fctx->type == dns_rdatatype_any ||
4177                        fctx->type == dns_rdatatype_rrsig ||
4178                        fctx->type == dns_rdatatype_sig);
4179                 /*
4180                  * Don't send a response yet - we have
4181                  * more rdatasets that still need to
4182                  * be validated.
4183                  */
4184                 dns_db_detachnode(fctx->cache, &node);
4185                 UNLOCK(&fctx->res->buckets[fctx->bucketnum].lock);
4186                 dns_validator_send(ISC_LIST_HEAD(fctx->validators));
4187                 goto cleanup_event;
4188         }
4189
4190  answer_response:
4191         /*
4192          * Cache any NS/NSEC records that happened to be validated.
4193          */
4194         result = dns_message_firstname(fctx->rmessage, DNS_SECTION_AUTHORITY);
4195         while (result == ISC_R_SUCCESS) {
4196                 name = NULL;
4197                 dns_message_currentname(fctx->rmessage, DNS_SECTION_AUTHORITY,
4198                                         &name);
4199                 for (rdataset = ISC_LIST_HEAD(name->list);
4200                      rdataset != NULL;
4201                      rdataset = ISC_LIST_NEXT(rdataset, link)) {
4202                         if ((rdataset->type != dns_rdatatype_ns &&
4203                              rdataset->type != dns_rdatatype_nsec) ||
4204                             rdataset->trust != dns_trust_secure)
4205                                 continue;
4206                         for (sigrdataset = ISC_LIST_HEAD(name->list);
4207                              sigrdataset != NULL;
4208                              sigrdataset = ISC_LIST_NEXT(sigrdataset, link)) {
4209                                 if (sigrdataset->type != dns_rdatatype_rrsig ||
4210                                     sigrdataset->covers != rdataset->type)
4211                                         continue;
4212                                 break;
4213                         }
4214                         if (sigrdataset == NULL ||
4215                             sigrdataset->trust != dns_trust_secure)
4216                                 continue;
4217                         result = dns_db_findnode(fctx->cache, name, ISC_TRUE,
4218                                                  &nsnode);
4219                         if (result != ISC_R_SUCCESS)
4220                                 continue;
4221
4222                         result = dns_db_addrdataset(fctx->cache, nsnode, NULL,
4223                                                     now, rdataset, 0, NULL);
4224                         if (result == ISC_R_SUCCESS)
4225                                 result = dns_db_addrdataset(fctx->cache, nsnode,
4226                                                             NULL, now,
4227                                                             sigrdataset, 0,
4228                                                             NULL);
4229                         dns_db_detachnode(fctx->cache, &nsnode);
4230                 }
4231                 result = dns_message_nextname(fctx->rmessage,
4232                                               DNS_SECTION_AUTHORITY);
4233         }
4234
4235         result = ISC_R_SUCCESS;
4236
4237         /*
4238          * Respond with an answer, positive or negative,
4239          * as opposed to an error.  'node' must be non-NULL.
4240          */
4241
4242         fctx->attributes |= FCTX_ATTR_HAVEANSWER;
4243
4244         if (hevent != NULL) {
4245                 hevent->result = eresult;
4246                 RUNTIME_CHECK(dns_name_copy(vevent->name,
4247                               dns_fixedname_name(&hevent->foundname), NULL)
4248                               == ISC_R_SUCCESS);
4249                 dns_db_attach(fctx->cache, &hevent->db);
4250                 dns_db_transfernode(fctx->cache, &node, &hevent->node);
4251                 clone_results(fctx);
4252         }
4253
4254  noanswer_response:
4255         if (node != NULL)
4256                 dns_db_detachnode(fctx->cache, &node);
4257
4258         UNLOCK(&fctx->res->buckets[fctx->bucketnum].lock);
4259
4260         fctx_done(fctx, result, __LINE__); /* Locks bucket. */
4261
4262  cleanup_event:
4263         INSIST(node == NULL);
4264         isc_event_free(&event);
4265 }
4266
4267 static inline isc_result_t
4268 cache_name(fetchctx_t *fctx, dns_name_t *name, dns_adbaddrinfo_t *addrinfo,
4269            isc_stdtime_t now)
4270 {
4271         dns_rdataset_t *rdataset, *sigrdataset;
4272         dns_rdataset_t *addedrdataset, *ardataset, *asigrdataset;
4273         dns_rdataset_t *valrdataset = NULL, *valsigrdataset = NULL;
4274         dns_dbnode_t *node, **anodep;
4275         dns_db_t **adbp;
4276         dns_name_t *aname;
4277         dns_resolver_t *res;
4278         isc_boolean_t need_validation, secure_domain, have_answer;
4279         isc_result_t result, eresult;
4280         dns_fetchevent_t *event;
4281         unsigned int options;
4282         isc_task_t *task;
4283         isc_boolean_t fail;
4284         unsigned int valoptions = 0;
4285
4286         /*
4287          * The appropriate bucket lock must be held.
4288          */
4289
4290         res = fctx->res;
4291         need_validation = ISC_FALSE;
4292         secure_domain = ISC_FALSE;
4293         have_answer = ISC_FALSE;
4294         eresult = ISC_R_SUCCESS;
4295         task = res->buckets[fctx->bucketnum].task;
4296
4297         /*
4298          * Is DNSSEC validation required for this name?
4299          */
4300         if (res->view->enablevalidation) {
4301                 result = dns_keytable_issecuredomain(res->view->secroots, name,
4302                                                      &secure_domain);
4303                 if (result != ISC_R_SUCCESS)
4304                         return (result);
4305
4306                 if (!secure_domain && res->view->dlv != NULL) {
4307                         valoptions = DNS_VALIDATOR_DLV;
4308                         secure_domain = ISC_TRUE;
4309                 }
4310         }
4311
4312         if ((fctx->options & DNS_FETCHOPT_NOVALIDATE) != 0)
4313                 need_validation = ISC_FALSE;
4314         else
4315                 need_validation = secure_domain;
4316
4317         adbp = NULL;
4318         aname = NULL;
4319         anodep = NULL;
4320         ardataset = NULL;
4321         asigrdataset = NULL;
4322         event = NULL;
4323         if ((name->attributes & DNS_NAMEATTR_ANSWER) != 0 &&
4324             !need_validation) {
4325                 have_answer = ISC_TRUE;
4326                 event = ISC_LIST_HEAD(fctx->events);
4327                 if (event != NULL) {
4328                         adbp = &event->db;
4329                         aname = dns_fixedname_name(&event->foundname);
4330                         result = dns_name_copy(name, aname, NULL);
4331                         if (result != ISC_R_SUCCESS)
4332                                 return (result);
4333                         anodep = &event->node;
4334                         /*
4335                          * If this is an ANY, SIG or RRSIG query, we're not
4336                          * going to return any rdatasets, unless we encountered
4337                          * a CNAME or DNAME as "the answer".  In this case,
4338                          * we're going to return DNS_R_CNAME or DNS_R_DNAME
4339                          * and we must set up the rdatasets.
4340                          */
4341                         if ((fctx->type != dns_rdatatype_any &&
4342                              fctx->type != dns_rdatatype_rrsig &&
4343                              fctx->type != dns_rdatatype_sig) ||
4344                             (name->attributes & DNS_NAMEATTR_CHAINING) != 0) {
4345                                 ardataset = event->rdataset;
4346                                 asigrdataset = event->sigrdataset;
4347                         }
4348                 }
4349         }
4350
4351         /*
4352          * Find or create the cache node.
4353          */
4354         node = NULL;
4355         result = dns_db_findnode(fctx->cache, name, ISC_TRUE, &node);
4356         if (result != ISC_R_SUCCESS)
4357                 return (result);
4358
4359         /*
4360          * Cache or validate each cacheable rdataset.
4361          */
4362         fail = ISC_TF((fctx->res->options & DNS_RESOLVER_CHECKNAMESFAIL) != 0);
4363         for (rdataset = ISC_LIST_HEAD(name->list);
4364              rdataset != NULL;
4365              rdataset = ISC_LIST_NEXT(rdataset, link)) {
4366                 if (!CACHE(rdataset))
4367                         continue;
4368                 if (CHECKNAMES(rdataset)) {
4369                         char namebuf[DNS_NAME_FORMATSIZE];
4370                         char typebuf[DNS_RDATATYPE_FORMATSIZE];
4371                         char classbuf[DNS_RDATATYPE_FORMATSIZE];
4372
4373                         dns_name_format(name, namebuf, sizeof(namebuf));
4374                         dns_rdatatype_format(rdataset->type, typebuf,
4375                                              sizeof(typebuf));
4376                         dns_rdataclass_format(rdataset->rdclass, classbuf,
4377                                               sizeof(classbuf));
4378                         isc_log_write(dns_lctx, DNS_LOGCATEGORY_RESOLVER,
4379                                       DNS_LOGMODULE_RESOLVER, ISC_LOG_NOTICE,
4380                                       "check-names %s %s/%s/%s",
4381                                       fail ? "failure" : "warning",
4382                                       namebuf, typebuf, classbuf);
4383                         if (fail) {
4384                                 if (ANSWER(rdataset)) {
4385                                         dns_db_detachnode(fctx->cache, &node);
4386                                         return (DNS_R_BADNAME);
4387                                 }
4388                                 continue;
4389                         }
4390                 }
4391
4392                 /*
4393                  * Enforce the configure maximum cache TTL.
4394                  */
4395                 if (rdataset->ttl > res->view->maxcachettl)
4396                         rdataset->ttl = res->view->maxcachettl;
4397
4398                 /*
4399                  * If this RRset is in a secure domain, is in bailiwick,
4400                  * and is not glue, attempt DNSSEC validation.  (We do not
4401                  * attempt to validate glue or out-of-bailiwick data--even
4402                  * though there might be some performance benefit to doing
4403                  * so--because it makes it simpler and safer to ensure that
4404                  * records from a secure domain are only cached if validated
4405                  * within the context of a query to the domain that owns
4406                  * them.)
4407                  */
4408                 if (secure_domain && rdataset->trust != dns_trust_glue &&
4409                     !EXTERNAL(rdataset)) {
4410                         dns_trust_t trust;
4411
4412                         /*
4413                          * RRSIGs are validated as part of validating the
4414                          * type they cover.
4415                          */
4416                         if (rdataset->type == dns_rdatatype_rrsig)
4417                                 continue;
4418                         /*
4419                          * Find the SIG for this rdataset, if we have it.
4420                          */
4421                         for (sigrdataset = ISC_LIST_HEAD(name->list);
4422                              sigrdataset != NULL;
4423                              sigrdataset = ISC_LIST_NEXT(sigrdataset, link)) {
4424                                 if (sigrdataset->type == dns_rdatatype_rrsig &&
4425                                     sigrdataset->covers == rdataset->type)
4426                                         break;
4427                         }
4428                         if (sigrdataset == NULL) {
4429                                 if (!ANSWER(rdataset) && need_validation) {
4430                                         /*
4431                                          * Ignore non-answer rdatasets that
4432                                          * are missing signatures.
4433                                          */
4434                                         continue;
4435                                 }
4436                         }
4437
4438                         /*
4439                          * Normalize the rdataset and sigrdataset TTLs.
4440                          */
4441                         if (sigrdataset != NULL) {
4442                                 rdataset->ttl = ISC_MIN(rdataset->ttl,
4443                                                         sigrdataset->ttl);
4444                                 sigrdataset->ttl = rdataset->ttl;
4445                         }
4446
4447                         /*
4448                          * Cache this rdataset/sigrdataset pair as
4449                          * pending data.  Track whether it was additional
4450                          * or not.
4451                          */
4452                         if (rdataset->trust == dns_trust_additional)
4453                                 trust = dns_trust_pending_additional;
4454                         else
4455                                 trust = dns_trust_pending_answer;
4456
4457                         rdataset->trust = trust;
4458                         if (sigrdataset != NULL)
4459                                 sigrdataset->trust = trust;
4460                         if (!need_validation || !ANSWER(rdataset)) {
4461                                 addedrdataset = ardataset;
4462                                 result = dns_db_addrdataset(fctx->cache, node,
4463                                                             NULL, now, rdataset,
4464                                                             0, addedrdataset);
4465                                 if (result == DNS_R_UNCHANGED) {
4466                                         result = ISC_R_SUCCESS;
4467                                         if (!need_validation &&
4468                                             ardataset != NULL &&
4469                                             ardataset->type == 0) {
4470                                                 /*
4471                                                  * The answer in the cache is
4472                                                  * better than the answer we
4473                                                  * found, and is a negative
4474                                                  * cache entry, so we must set
4475                                                  * eresult appropriately.
4476                                                  */
4477                                                 if (NXDOMAIN(ardataset))
4478                                                         eresult =
4479                                                            DNS_R_NCACHENXDOMAIN;
4480                                                 else
4481                                                         eresult =
4482                                                            DNS_R_NCACHENXRRSET;
4483                                                 /*
4484                                                  * We have a negative response
4485                                                  * from the cache so don't
4486                                                  * attempt to add the RRSIG
4487                                                  * rrset.
4488                                                  */
4489                                                 continue;
4490                                         }
4491                                 }
4492                                 if (result != ISC_R_SUCCESS)
4493                                         break;
4494                                 if (sigrdataset != NULL) {
4495                                         addedrdataset = asigrdataset;
4496                                         result = dns_db_addrdataset(fctx->cache,
4497                                                                 node, NULL, now,
4498                                                                 sigrdataset, 0,
4499                                                                 addedrdataset);
4500                                         if (result == DNS_R_UNCHANGED)
4501                                                 result = ISC_R_SUCCESS;
4502                                         if (result != ISC_R_SUCCESS)
4503                                                 break;
4504                                 } else if (!ANSWER(rdataset))
4505                                         continue;
4506                         }
4507
4508                         if (ANSWER(rdataset) && need_validation) {
4509                                 if (fctx->type != dns_rdatatype_any &&
4510                                     fctx->type != dns_rdatatype_rrsig &&
4511                                     fctx->type != dns_rdatatype_sig) {
4512                                         /*
4513                                          * This is The Answer.  We will
4514                                          * validate it, but first we cache
4515                                          * the rest of the response - it may
4516                                          * contain useful keys.
4517                                          */
4518                                         INSIST(valrdataset == NULL &&
4519                                                valsigrdataset == NULL);
4520                                         valrdataset = rdataset;
4521                                         valsigrdataset = sigrdataset;
4522                                 } else {
4523                                         /*
4524                                          * This is one of (potentially)
4525                                          * multiple answers to an ANY
4526                                          * or SIG query.  To keep things
4527                                          * simple, we just start the
4528                                          * validator right away rather
4529                                          * than caching first and
4530                                          * having to remember which
4531                                          * rdatasets needed validation.
4532                                          */
4533                                         result = valcreate(fctx, addrinfo,
4534                                                            name, rdataset->type,
4535                                                            rdataset,
4536                                                            sigrdataset,
4537                                                            valoptions, task);
4538                                         /*
4539                                          * Defer any further validations.
4540                                          * This prevents multiple validators
4541                                          * from manipulating fctx->rmessage
4542                                          * simultaneously.
4543                                          */
4544                                         valoptions |= DNS_VALIDATOR_DEFER;
4545                                 }
4546                         } else if (CHAINING(rdataset)) {
4547                                 if (rdataset->type == dns_rdatatype_cname)
4548                                         eresult = DNS_R_CNAME;
4549                                 else {
4550                                         INSIST(rdataset->type ==
4551                                                dns_rdatatype_dname);
4552                                         eresult = DNS_R_DNAME;
4553                                 }
4554                         }
4555                 } else if (!EXTERNAL(rdataset)) {
4556                         /*
4557                          * It's OK to cache this rdataset now.
4558                          */
4559                         if (ANSWER(rdataset))
4560                                 addedrdataset = ardataset;
4561                         else if (ANSWERSIG(rdataset))
4562                                 addedrdataset = asigrdataset;
4563                         else
4564                                 addedrdataset = NULL;
4565                         if (CHAINING(rdataset)) {
4566                                 if (rdataset->type == dns_rdatatype_cname)
4567                                         eresult = DNS_R_CNAME;
4568                                 else {
4569                                         INSIST(rdataset->type ==
4570                                                dns_rdatatype_dname);
4571                                         eresult = DNS_R_DNAME;
4572                                 }
4573                         }
4574                         if (rdataset->trust == dns_trust_glue &&
4575                             (rdataset->type == dns_rdatatype_ns ||
4576                              (rdataset->type == dns_rdatatype_rrsig &&
4577                               rdataset->covers == dns_rdatatype_ns))) {
4578                                 /*
4579                                  * If the trust level is 'dns_trust_glue'
4580                                  * then we are adding data from a referral
4581                                  * we got while executing the search algorithm.
4582                                  * New referral data always takes precedence
4583                                  * over the existing cache contents.
4584                                  */
4585                                 options = DNS_DBADD_FORCE;
4586                         } else
4587                                 options = 0;
4588                         /*
4589                          * Now we can add the rdataset.
4590                          */
4591                         result = dns_db_addrdataset(fctx->cache,
4592                                                     node, NULL, now,
4593                                                     rdataset,
4594                                                     options,
4595                                                     addedrdataset);
4596                         if (result == DNS_R_UNCHANGED) {
4597                                 if (ANSWER(rdataset) &&
4598                                     ardataset != NULL &&
4599                                     ardataset->type == 0) {
4600                                         /*
4601                                          * The answer in the cache is better
4602                                          * than the answer we found, and is
4603                                          * a negative cache entry, so we
4604                                          * must set eresult appropriately.
4605                                          */
4606                                         if (NXDOMAIN(ardataset))
4607                                                 eresult = DNS_R_NCACHENXDOMAIN;
4608                                         else
4609                                                 eresult = DNS_R_NCACHENXRRSET;
4610                                 }
4611                                 result = ISC_R_SUCCESS;
4612                         } else if (result != ISC_R_SUCCESS)
4613                                 break;
4614                 }
4615         }
4616
4617         if (valrdataset != NULL)
4618                 result = valcreate(fctx, addrinfo, name, fctx->type,
4619                                    valrdataset, valsigrdataset, valoptions,
4620                                    task);
4621
4622         if (result == ISC_R_SUCCESS && have_answer) {
4623                 fctx->attributes |= FCTX_ATTR_HAVEANSWER;
4624                 if (event != NULL) {
4625                         /*
4626                          * Negative results must be indicated in event->result.
4627                          */
4628                         if (dns_rdataset_isassociated(event->rdataset) &&
4629                             event->rdataset->type == dns_rdatatype_none) {
4630                                 INSIST(eresult == DNS_R_NCACHENXDOMAIN ||
4631                                        eresult == DNS_R_NCACHENXRRSET);
4632                         }
4633                         event->result = eresult;
4634                         dns_db_attach(fctx->cache, adbp);
4635                         dns_db_transfernode(fctx->cache, &node, anodep);
4636                         clone_results(fctx);
4637                 }
4638         }
4639
4640         if (node != NULL)
4641                 dns_db_detachnode(fctx->cache, &node);
4642
4643         return (result);
4644 }
4645
4646 static inline isc_result_t
4647 cache_message(fetchctx_t *fctx, dns_adbaddrinfo_t *addrinfo, isc_stdtime_t now)
4648 {
4649         isc_result_t result;
4650         dns_section_t section;
4651         dns_name_t *name;
4652
4653         FCTXTRACE("cache_message");
4654
4655         fctx->attributes &= ~FCTX_ATTR_WANTCACHE;
4656
4657         LOCK(&fctx->res->buckets[fctx->bucketnum].lock);
4658
4659         for (section = DNS_SECTION_ANSWER;
4660              section <= DNS_SECTION_ADDITIONAL;
4661              section++) {
4662                 result = dns_message_firstname(fctx->rmessage, section);
4663                 while (result == ISC_R_SUCCESS) {
4664                         name = NULL;
4665                         dns_message_currentname(fctx->rmessage, section,
4666                                                 &name);
4667                         if ((name->attributes & DNS_NAMEATTR_CACHE) != 0) {
4668                                 result = cache_name(fctx, name, addrinfo, now);
4669                                 if (result != ISC_R_SUCCESS)
4670                                         break;
4671                         }
4672                         result = dns_message_nextname(fctx->rmessage, section);
4673                 }
4674                 if (result != ISC_R_NOMORE)
4675                         break;
4676         }
4677         if (result == ISC_R_NOMORE)
4678                 result = ISC_R_SUCCESS;
4679
4680         UNLOCK(&fctx->res->buckets[fctx->bucketnum].lock);
4681
4682         return (result);
4683 }
4684
4685 /*
4686  * Do what dns_ncache_addoptout() does, and then compute an appropriate eresult.
4687  */
4688 static isc_result_t
4689 ncache_adderesult(dns_message_t *message, dns_db_t *cache, dns_dbnode_t *node,
4690                   dns_rdatatype_t covers, isc_stdtime_t now, dns_ttl_t maxttl,
4691                   isc_boolean_t optout, dns_rdataset_t *ardataset,
4692                   isc_result_t *eresultp)
4693 {
4694         isc_result_t result;
4695         dns_rdataset_t rdataset;
4696
4697         if (ardataset == NULL) {
4698                 dns_rdataset_init(&rdataset);
4699                 ardataset = &rdataset;
4700         }
4701         result = dns_ncache_addoptout(message, cache, node, covers, now,
4702                                      maxttl, optout, ardataset);
4703         if (result == DNS_R_UNCHANGED || result == ISC_R_SUCCESS) {
4704                 /*
4705                  * If the cache now contains a negative entry and we
4706                  * care about whether it is DNS_R_NCACHENXDOMAIN or
4707                  * DNS_R_NCACHENXRRSET then extract it.
4708                  */
4709                 if (ardataset->type == 0) {
4710                         /*
4711                          * The cache data is a negative cache entry.
4712                          */
4713                         if (NXDOMAIN(ardataset))
4714                                 *eresultp = DNS_R_NCACHENXDOMAIN;
4715                         else
4716                                 *eresultp = DNS_R_NCACHENXRRSET;
4717                 } else {
4718                         /*
4719                          * Either we don't care about the nature of the
4720                          * cache rdataset (because no fetch is interested
4721                          * in the outcome), or the cache rdataset is not
4722                          * a negative cache entry.  Whichever case it is,
4723                          * we can return success.
4724                          *
4725                          * XXXRTH  There's a CNAME/DNAME problem here.
4726                          */
4727                         *eresultp = ISC_R_SUCCESS;
4728                 }
4729                 result = ISC_R_SUCCESS;
4730         }
4731         if (ardataset == &rdataset && dns_rdataset_isassociated(ardataset))
4732                 dns_rdataset_disassociate(ardataset);
4733
4734         return (result);
4735 }
4736
4737 static inline isc_result_t
4738 ncache_message(fetchctx_t *fctx, dns_adbaddrinfo_t *addrinfo,
4739                dns_rdatatype_t covers, isc_stdtime_t now)
4740 {
4741         isc_result_t result, eresult;
4742         dns_name_t *name;
4743         dns_resolver_t *res;
4744         dns_db_t **adbp;
4745         dns_dbnode_t *node, **anodep;
4746         dns_rdataset_t *ardataset;
4747         isc_boolean_t need_validation, secure_domain;
4748         dns_name_t *aname;
4749         dns_fetchevent_t *event;
4750         isc_uint32_t ttl;
4751         unsigned int valoptions = 0;
4752
4753         FCTXTRACE("ncache_message");
4754
4755         fctx->attributes &= ~FCTX_ATTR_WANTNCACHE;
4756
4757         res = fctx->res;
4758         need_validation = ISC_FALSE;
4759         secure_domain = ISC_FALSE;
4760         eresult = ISC_R_SUCCESS;
4761         name = &fctx->name;
4762         node = NULL;
4763
4764         /*
4765          * XXXMPA remove when we follow cnames and adjust the setting
4766          * of FCTX_ATTR_WANTNCACHE in noanswer_response().
4767          */
4768         INSIST(fctx->rmessage->counts[DNS_SECTION_ANSWER] == 0);
4769
4770         /*
4771          * Is DNSSEC validation required for this name?
4772          */
4773         if (fctx->res->view->enablevalidation) {
4774                 result = dns_keytable_issecuredomain(res->view->secroots, name,
4775                                                      &secure_domain);
4776                 if (result != ISC_R_SUCCESS)
4777                         return (result);
4778
4779                 if (!secure_domain && res->view->dlv != NULL) {
4780                         valoptions = DNS_VALIDATOR_DLV;
4781                         secure_domain = ISC_TRUE;
4782                 }
4783         }
4784
4785         if ((fctx->options & DNS_FETCHOPT_NOVALIDATE) != 0)
4786                 need_validation = ISC_FALSE;
4787         else
4788                 need_validation = secure_domain;
4789
4790         if (secure_domain) {
4791                 /*
4792                  * Mark all rdatasets as pending.
4793                  */
4794                 dns_rdataset_t *trdataset;
4795                 dns_name_t *tname;
4796
4797                 result = dns_message_firstname(fctx->rmessage,
4798                                                DNS_SECTION_AUTHORITY);
4799                 while (result == ISC_R_SUCCESS) {
4800                         tname = NULL;
4801                         dns_message_currentname(fctx->rmessage,
4802                                                 DNS_SECTION_AUTHORITY,
4803                                                 &tname);
4804                         for (trdataset = ISC_LIST_HEAD(tname->list);
4805                              trdataset != NULL;
4806                              trdataset = ISC_LIST_NEXT(trdataset, link))
4807                                 trdataset->trust = dns_trust_pending_answer;
4808                         result = dns_message_nextname(fctx->rmessage,
4809                                                       DNS_SECTION_AUTHORITY);
4810                 }
4811                 if (result != ISC_R_NOMORE)
4812                         return (result);
4813
4814         }
4815
4816         if (need_validation) {
4817                 /*
4818                  * Do negative response validation.
4819                  */
4820                 result = valcreate(fctx, addrinfo, name, fctx->type,
4821                                    NULL, NULL, valoptions,
4822                                    res->buckets[fctx->bucketnum].task);
4823                 /*
4824                  * If validation is necessary, return now.  Otherwise continue
4825                  * to process the message, letting the validation complete
4826                  * in its own good time.
4827                  */
4828                 return (result);
4829         }
4830
4831         LOCK(&res->buckets[fctx->bucketnum].lock);
4832
4833         adbp = NULL;
4834         aname = NULL;
4835         anodep = NULL;
4836         ardataset = NULL;
4837         if (!HAVE_ANSWER(fctx)) {
4838                 event = ISC_LIST_HEAD(fctx->events);
4839                 if (event != NULL) {
4840                         adbp = &event->db;
4841                         aname = dns_fixedname_name(&event->foundname);
4842                         result = dns_name_copy(name, aname, NULL);
4843                         if (result != ISC_R_SUCCESS)
4844                                 goto unlock;
4845                         anodep = &event->node;
4846                         ardataset = event->rdataset;
4847                 }
4848         } else
4849                 event = NULL;
4850
4851         result = dns_db_findnode(fctx->cache, name, ISC_TRUE, &node);
4852         if (result != ISC_R_SUCCESS)
4853                 goto unlock;
4854
4855         /*
4856          * If we are asking for a SOA record set the cache time
4857          * to zero to facilitate locating the containing zone of
4858          * a arbitrary zone.
4859          */
4860         ttl = fctx->res->view->maxncachettl;
4861         if (fctx->type == dns_rdatatype_soa &&
4862             covers == dns_rdatatype_any &&
4863             fctx->res->zero_no_soa_ttl)
4864                 ttl = 0;
4865
4866         result = ncache_adderesult(fctx->rmessage, fctx->cache, node,
4867                                    covers, now, ttl, ISC_FALSE,
4868                                    ardataset, &eresult);
4869         if (result != ISC_R_SUCCESS)
4870                 goto unlock;
4871
4872         if (!HAVE_ANSWER(fctx)) {
4873                 fctx->attributes |= FCTX_ATTR_HAVEANSWER;
4874                 if (event != NULL) {
4875                         event->result = eresult;
4876                         dns_db_attach(fctx->cache, adbp);
4877                         dns_db_transfernode(fctx->cache, &node, anodep);
4878                         clone_results(fctx);
4879                 }
4880         }
4881
4882  unlock:
4883         UNLOCK(&res->buckets[fctx->bucketnum].lock);
4884
4885         if (node != NULL)
4886                 dns_db_detachnode(fctx->cache, &node);
4887
4888         return (result);
4889 }
4890
4891 static inline void
4892 mark_related(dns_name_t *name, dns_rdataset_t *rdataset,
4893              isc_boolean_t external, isc_boolean_t gluing)
4894 {
4895         name->attributes |= DNS_NAMEATTR_CACHE;
4896         if (gluing) {
4897                 rdataset->trust = dns_trust_glue;
4898                 /*
4899                  * Glue with 0 TTL causes problems.  We force the TTL to
4900                  * 1 second to prevent this.
4901                  */
4902                 if (rdataset->ttl == 0)
4903                         rdataset->ttl = 1;
4904         } else
4905                 rdataset->trust = dns_trust_additional;
4906         /*
4907          * Avoid infinite loops by only marking new rdatasets.
4908          */
4909         if (!CACHE(rdataset)) {
4910                 name->attributes |= DNS_NAMEATTR_CHASE;
4911                 rdataset->attributes |= DNS_RDATASETATTR_CHASE;
4912         }
4913         rdataset->attributes |= DNS_RDATASETATTR_CACHE;
4914         if (external)
4915                 rdataset->attributes |= DNS_RDATASETATTR_EXTERNAL;
4916 }
4917
4918 static isc_result_t
4919 check_related(void *arg, dns_name_t *addname, dns_rdatatype_t type) {
4920         fetchctx_t *fctx = arg;
4921         isc_result_t result;
4922         dns_name_t *name;
4923         dns_rdataset_t *rdataset;
4924         isc_boolean_t external;
4925         dns_rdatatype_t rtype;
4926         isc_boolean_t gluing;
4927
4928         REQUIRE(VALID_FCTX(fctx));
4929
4930         if (GLUING(fctx))
4931                 gluing = ISC_TRUE;
4932         else
4933                 gluing = ISC_FALSE;
4934         name = NULL;
4935         rdataset = NULL;
4936         result = dns_message_findname(fctx->rmessage, DNS_SECTION_ADDITIONAL,
4937                                       addname, dns_rdatatype_any, 0, &name,
4938                                       NULL);
4939         if (result == ISC_R_SUCCESS) {
4940                 external = ISC_TF(!dns_name_issubdomain(name, &fctx->domain));
4941                 if (type == dns_rdatatype_a) {
4942                         for (rdataset = ISC_LIST_HEAD(name->list);
4943                              rdataset != NULL;
4944                              rdataset = ISC_LIST_NEXT(rdataset, link)) {
4945                                 if (rdataset->type == dns_rdatatype_rrsig)
4946                                         rtype = rdataset->covers;
4947                                 else
4948                                         rtype = rdataset->type;
4949                                 if (rtype == dns_rdatatype_a ||
4950                                     rtype == dns_rdatatype_aaaa)
4951                                         mark_related(name, rdataset, external,
4952                                                      gluing);
4953                         }
4954                 } else {
4955                         result = dns_message_findtype(name, type, 0,
4956                                                       &rdataset);
4957                         if (result == ISC_R_SUCCESS) {
4958                                 mark_related(name, rdataset, external, gluing);
4959                                 /*
4960                                  * Do we have its SIG too?
4961                                  */
4962                                 rdataset = NULL;
4963                                 result = dns_message_findtype(name,
4964                                                       dns_rdatatype_rrsig,
4965                                                       type, &rdataset);
4966                                 if (result == ISC_R_SUCCESS)
4967                                         mark_related(name, rdataset, external,
4968                                                      gluing);
4969                         }
4970                 }
4971         }
4972
4973         return (ISC_R_SUCCESS);
4974 }
4975
4976 static void
4977 chase_additional(fetchctx_t *fctx) {
4978         isc_boolean_t rescan;
4979         dns_section_t section = DNS_SECTION_ADDITIONAL;
4980         isc_result_t result;
4981
4982  again:
4983         rescan = ISC_FALSE;
4984
4985         for (result = dns_message_firstname(fctx->rmessage, section);
4986              result == ISC_R_SUCCESS;
4987              result = dns_message_nextname(fctx->rmessage, section)) {
4988                 dns_name_t *name = NULL;
4989                 dns_rdataset_t *rdataset;
4990                 dns_message_currentname(fctx->rmessage, DNS_SECTION_ADDITIONAL,
4991                                         &name);
4992                 if ((name->attributes & DNS_NAMEATTR_CHASE) == 0)
4993                         continue;
4994                 name->attributes &= ~DNS_NAMEATTR_CHASE;
4995                 for (rdataset = ISC_LIST_HEAD(name->list);
4996                      rdataset != NULL;
4997                      rdataset = ISC_LIST_NEXT(rdataset, link)) {
4998                         if (CHASE(rdataset)) {
4999                                 rdataset->attributes &= ~DNS_RDATASETATTR_CHASE;
5000                                 (void)dns_rdataset_additionaldata(rdataset,
5001                                                                   check_related,
5002                                                                   fctx);
5003                                 rescan = ISC_TRUE;
5004                         }
5005                 }
5006         }
5007         if (rescan)
5008                 goto again;
5009 }
5010
5011 static inline isc_result_t
5012 cname_target(dns_rdataset_t *rdataset, dns_name_t *tname) {
5013         isc_result_t result;
5014         dns_rdata_t rdata = DNS_RDATA_INIT;
5015         dns_rdata_cname_t cname;
5016
5017         result = dns_rdataset_first(rdataset);
5018         if (result != ISC_R_SUCCESS)
5019                 return (result);
5020         dns_rdataset_current(rdataset, &rdata);
5021         result = dns_rdata_tostruct(&rdata, &cname, NULL);
5022         if (result != ISC_R_SUCCESS)
5023                 return (result);
5024         dns_name_init(tname, NULL);
5025         dns_name_clone(&cname.cname, tname);
5026         dns_rdata_freestruct(&cname);
5027
5028         return (ISC_R_SUCCESS);
5029 }
5030
5031 static inline isc_result_t
5032 dname_target(dns_rdataset_t *rdataset, dns_name_t *qname, dns_name_t *oname,
5033              dns_fixedname_t *fixeddname)
5034 {
5035         isc_result_t result;
5036         dns_rdata_t rdata = DNS_RDATA_INIT;
5037         unsigned int nlabels;
5038         int order;
5039         dns_namereln_t namereln;
5040         dns_rdata_dname_t dname;
5041         dns_fixedname_t prefix;
5042
5043         /*
5044          * Get the target name of the DNAME.
5045          */
5046
5047         result = dns_rdataset_first(rdataset);
5048         if (result != ISC_R_SUCCESS)
5049                 return (result);
5050         dns_rdataset_current(rdataset, &rdata);
5051         result = dns_rdata_tostruct(&rdata, &dname, NULL);
5052         if (result != ISC_R_SUCCESS)
5053                 return (result);
5054
5055         /*
5056          * Get the prefix of qname.
5057          */
5058         namereln = dns_name_fullcompare(qname, oname, &order, &nlabels);
5059         if (namereln != dns_namereln_subdomain) {
5060                 dns_rdata_freestruct(&dname);
5061                 return (DNS_R_FORMERR);
5062         }
5063         dns_fixedname_init(&prefix);
5064         dns_name_split(qname, nlabels, dns_fixedname_name(&prefix), NULL);
5065         dns_fixedname_init(fixeddname);
5066         result = dns_name_concatenate(dns_fixedname_name(&prefix),
5067                                       &dname.dname,
5068                                       dns_fixedname_name(fixeddname), NULL);
5069         dns_rdata_freestruct(&dname);
5070         return (result);
5071 }
5072
5073 /*
5074  * Handle a no-answer response (NXDOMAIN, NXRRSET, or referral).
5075  * If bind8_ns_resp is ISC_TRUE, this is a suspected BIND 8
5076  * response to an NS query that should be treated as a referral
5077  * even though the NS records occur in the answer section
5078  * rather than the authority section.
5079  */
5080 static isc_result_t
5081 noanswer_response(fetchctx_t *fctx, dns_name_t *oqname,
5082                   isc_boolean_t bind8_ns_resp)
5083 {
5084         isc_result_t result;
5085         dns_message_t *message;
5086         dns_name_t *name, *qname, *ns_name, *soa_name, *ds_name;
5087         dns_rdataset_t *rdataset, *ns_rdataset;
5088         isc_boolean_t aa, negative_response;
5089         dns_rdatatype_t type;
5090         dns_section_t section =
5091                 bind8_ns_resp ? DNS_SECTION_ANSWER : DNS_SECTION_AUTHORITY;
5092
5093         FCTXTRACE("noanswer_response");
5094
5095         message = fctx->rmessage;
5096
5097         /*
5098          * Setup qname.
5099          */
5100         if (oqname == NULL) {
5101                 /*
5102                  * We have a normal, non-chained negative response or
5103                  * referral.
5104                  */
5105                 if ((message->flags & DNS_MESSAGEFLAG_AA) != 0)
5106                         aa = ISC_TRUE;
5107                 else
5108                         aa = ISC_FALSE;
5109                 qname = &fctx->name;
5110         } else {
5111                 /*
5112                  * We're being invoked by answer_response() after it has
5113                  * followed a CNAME/DNAME chain.
5114                  */
5115                 qname = oqname;
5116                 aa = ISC_FALSE;
5117                 /*
5118                  * If the current qname is not a subdomain of the query
5119                  * domain, there's no point in looking at the authority
5120                  * section without doing DNSSEC validation.
5121                  *
5122                  * Until we do that validation, we'll just return success
5123                  * in this case.
5124                  */
5125                 if (!dns_name_issubdomain(qname, &fctx->domain))
5126                         return (ISC_R_SUCCESS);
5127         }
5128
5129         /*
5130          * We have to figure out if this is a negative response, or a
5131          * referral.
5132          */
5133
5134         /*
5135          * Sometimes we can tell if its a negative response by looking at
5136          * the message header.
5137          */
5138         negative_response = ISC_FALSE;
5139         if (message->rcode == dns_rcode_nxdomain ||
5140             (message->counts[DNS_SECTION_ANSWER] == 0 &&
5141              message->counts[DNS_SECTION_AUTHORITY] == 0))
5142                 negative_response = ISC_TRUE;
5143
5144         /*
5145          * Process the authority section.
5146          */
5147         ns_name = NULL;
5148         ns_rdataset = NULL;
5149         soa_name = NULL;
5150         ds_name = NULL;
5151         result = dns_message_firstname(message, section);
5152         while (result == ISC_R_SUCCESS) {
5153                 name = NULL;
5154                 dns_message_currentname(message, section, &name);
5155                 if (dns_name_issubdomain(name, &fctx->domain)) {
5156                         /*
5157                          * Look for NS/SOA RRsets first.
5158                          */
5159                         for (rdataset = ISC_LIST_HEAD(name->list);
5160                              rdataset != NULL;
5161                              rdataset = ISC_LIST_NEXT(rdataset, link)) {
5162                                 type = rdataset->type;
5163                                 if (type == dns_rdatatype_rrsig)
5164                                         type = rdataset->covers;
5165                                 if (((type == dns_rdatatype_ns ||
5166                                       type == dns_rdatatype_soa) &&
5167                                      !dns_name_issubdomain(qname, name)))
5168                                         return (DNS_R_FORMERR);
5169                                 if (type == dns_rdatatype_ns) {
5170                                         /*
5171                                          * NS or RRSIG NS.
5172                                          *
5173                                          * Only one set of NS RRs is allowed.
5174                                          */
5175                                         if (rdataset->type ==
5176                                             dns_rdatatype_ns) {
5177                                                 if (ns_name != NULL &&
5178                                                     name != ns_name)
5179                                                         return (DNS_R_FORMERR);
5180                                                 ns_name = name;
5181                                                 ns_rdataset = rdataset;
5182                                         }
5183                                         name->attributes |=
5184                                                 DNS_NAMEATTR_CACHE;
5185                                         rdataset->attributes |=
5186                                                 DNS_RDATASETATTR_CACHE;
5187                                         rdataset->trust = dns_trust_glue;
5188                                 }
5189                                 if (type == dns_rdatatype_soa) {
5190                                         /*
5191                                          * SOA, or RRSIG SOA.
5192                                          *
5193                                          * Only one SOA is allowed.
5194                                          */
5195                                         if (rdataset->type ==
5196                                             dns_rdatatype_soa) {
5197                                                 if (soa_name != NULL &&
5198                                                     name != soa_name)
5199                                                         return (DNS_R_FORMERR);
5200                                                 soa_name = name;
5201                                         }
5202                                         name->attributes |=
5203                                                 DNS_NAMEATTR_NCACHE;
5204                                         rdataset->attributes |=
5205                                                 DNS_RDATASETATTR_NCACHE;
5206                                         if (aa)
5207                                                 rdataset->trust =
5208                                                     dns_trust_authauthority;
5209                                         else
5210                                                 rdataset->trust =
5211                                                         dns_trust_additional;
5212                                 }
5213                         }
5214                 }
5215                 result = dns_message_nextname(message, section);
5216                 if (result == ISC_R_NOMORE)
5217                         break;
5218                 else if (result != ISC_R_SUCCESS)
5219                         return (result);
5220         }
5221
5222         /*
5223          * A negative response has a SOA record (Type 2)
5224          * and a optional NS RRset (Type 1) or it has neither
5225          * a SOA or a NS RRset (Type 3, handled above) or
5226          * rcode is NXDOMAIN (handled above) in which case
5227          * the NS RRset is allowed (Type 4).
5228          */
5229         if (soa_name != NULL)
5230                 negative_response = ISC_TRUE;
5231
5232         result = dns_message_firstname(message, section);
5233         while (result == ISC_R_SUCCESS) {
5234                 name = NULL;
5235                 dns_message_currentname(message, section, &name);
5236                 if (dns_name_issubdomain(name, &fctx->domain)) {
5237                         for (rdataset = ISC_LIST_HEAD(name->list);
5238                              rdataset != NULL;
5239                              rdataset = ISC_LIST_NEXT(rdataset, link)) {
5240                                 type = rdataset->type;
5241                                 if (type == dns_rdatatype_rrsig)
5242                                         type = rdataset->covers;
5243                                 if (type == dns_rdatatype_nsec ||
5244                                     type == dns_rdatatype_nsec3) {
5245                                         /*
5246                                          * NSEC or RRSIG NSEC.
5247                                          */
5248                                         if (negative_response) {
5249                                                 name->attributes |=
5250                                                         DNS_NAMEATTR_NCACHE;
5251                                                 rdataset->attributes |=
5252                                                         DNS_RDATASETATTR_NCACHE;
5253                                         } else if (type == dns_rdatatype_nsec) {
5254                                                 name->attributes |=
5255                                                         DNS_NAMEATTR_CACHE;
5256                                                 rdataset->attributes |=
5257                                                         DNS_RDATASETATTR_CACHE;
5258                                         }
5259                                         if (aa)
5260                                                 rdataset->trust =
5261                                                     dns_trust_authauthority;
5262                                         else
5263                                                 rdataset->trust =
5264                                                         dns_trust_additional;
5265                                         /*
5266                                          * No additional data needs to be
5267                                          * marked.
5268                                          */
5269                                 } else if (type == dns_rdatatype_ds) {
5270                                         /*
5271                                          * DS or SIG DS.
5272                                          *
5273                                          * These should only be here if
5274                                          * this is a referral, and there
5275                                          * should only be one DS.
5276                                          */
5277                                         if (ns_name == NULL)
5278                                                 return (DNS_R_FORMERR);
5279                                         if (rdataset->type ==
5280                                             dns_rdatatype_ds) {
5281                                                 if (ds_name != NULL &&
5282                                                     name != ds_name)
5283                                                         return (DNS_R_FORMERR);
5284                                                 ds_name = name;
5285                                         }
5286                                         name->attributes |=
5287                                                 DNS_NAMEATTR_CACHE;
5288                                         rdataset->attributes |=
5289                                                 DNS_RDATASETATTR_CACHE;
5290                                         if (aa)
5291                                                 rdataset->trust =
5292                                                     dns_trust_authauthority;
5293                                         else
5294                                                 rdataset->trust =
5295                                                         dns_trust_additional;
5296                                 }
5297                         }
5298                 }
5299                 result = dns_message_nextname(message, section);
5300                 if (result == ISC_R_NOMORE)
5301                         break;
5302                 else if (result != ISC_R_SUCCESS)
5303                         return (result);
5304         }
5305
5306         /*
5307          * Trigger lookups for DNS nameservers.
5308          */
5309         if (negative_response && message->rcode == dns_rcode_noerror &&
5310             fctx->type == dns_rdatatype_ds && soa_name != NULL &&
5311             dns_name_equal(soa_name, qname) &&
5312             !dns_name_equal(qname, dns_rootname))
5313                 return (DNS_R_CHASEDSSERVERS);
5314
5315         /*
5316          * Did we find anything?
5317          */
5318         if (!negative_response && ns_name == NULL) {
5319                 /*
5320                  * Nope.
5321                  */
5322                 if (oqname != NULL) {
5323                         /*
5324                          * We've already got a partial CNAME/DNAME chain,
5325                          * and haven't found else anything useful here, but
5326                          * no error has occurred since we have an answer.
5327                          */
5328                         return (ISC_R_SUCCESS);
5329                 } else {
5330                         /*
5331                          * The responder is insane.
5332                          */
5333                         return (DNS_R_FORMERR);
5334                 }
5335         }
5336
5337         /*
5338          * If we found both NS and SOA, they should be the same name.
5339          */
5340         if (ns_name != NULL && soa_name != NULL && ns_name != soa_name)
5341                 return (DNS_R_FORMERR);
5342
5343         /*
5344          * Do we have a referral?  (We only want to follow a referral if
5345          * we're not following a chain.)
5346          */
5347         if (!negative_response && ns_name != NULL && oqname == NULL) {
5348                 /*
5349                  * We already know ns_name is a subdomain of fctx->domain.
5350                  * If ns_name is equal to fctx->domain, we're not making
5351                  * progress.  We return DNS_R_FORMERR so that we'll keep
5352                  * trying other servers.
5353                  */
5354                 if (dns_name_equal(ns_name, &fctx->domain))
5355                         return (DNS_R_FORMERR);
5356
5357                 /*
5358                  * If the referral name is not a parent of the query
5359                  * name, consider the responder insane.
5360                  */
5361                 if (! dns_name_issubdomain(&fctx->name, ns_name)) {
5362                         FCTXTRACE("referral to non-parent");
5363                         return (DNS_R_FORMERR);
5364                 }
5365
5366                 /*
5367                  * Mark any additional data related to this rdataset.
5368                  * It's important that we do this before we change the
5369                  * query domain.
5370                  */
5371                 INSIST(ns_rdataset != NULL);
5372                 fctx->attributes |= FCTX_ATTR_GLUING;
5373                 (void)dns_rdataset_additionaldata(ns_rdataset, check_related,
5374                                                   fctx);
5375                 fctx->attributes &= ~FCTX_ATTR_GLUING;
5376                 /*
5377                  * NS rdatasets with 0 TTL cause problems.
5378                  * dns_view_findzonecut() will not find them when we
5379                  * try to follow the referral, and we'll SERVFAIL
5380                  * because the best nameservers are now above QDOMAIN.
5381                  * We force the TTL to 1 second to prevent this.
5382                  */
5383                 if (ns_rdataset->ttl == 0)
5384                         ns_rdataset->ttl = 1;
5385                 /*
5386                  * Set the current query domain to the referral name.
5387                  *
5388                  * XXXRTH  We should check if we're in forward-only mode, and
5389                  *              if so we should bail out.
5390                  */
5391                 INSIST(dns_name_countlabels(&fctx->domain) > 0);
5392                 dns_name_free(&fctx->domain,
5393                               fctx->res->buckets[fctx->bucketnum].mctx);
5394                 if (dns_rdataset_isassociated(&fctx->nameservers))
5395                         dns_rdataset_disassociate(&fctx->nameservers);
5396                 dns_name_init(&fctx->domain, NULL);
5397                 result = dns_name_dup(ns_name,
5398                                       fctx->res->buckets[fctx->bucketnum].mctx,
5399                                       &fctx->domain);
5400                 if (result != ISC_R_SUCCESS)
5401                         return (result);
5402                 fctx->attributes |= FCTX_ATTR_WANTCACHE;
5403                 return (DNS_R_DELEGATION);
5404         }
5405
5406         /*
5407          * Since we're not doing a referral, we don't want to cache any
5408          * NS RRs we may have found.
5409          */
5410         if (ns_name != NULL)
5411                 ns_name->attributes &= ~DNS_NAMEATTR_CACHE;
5412
5413         if (negative_response && oqname == NULL)
5414                 fctx->attributes |= FCTX_ATTR_WANTNCACHE;
5415
5416         return (ISC_R_SUCCESS);
5417 }
5418
5419 static isc_result_t
5420 answer_response(fetchctx_t *fctx) {
5421         isc_result_t result;
5422         dns_message_t *message;
5423         dns_name_t *name, *qname, tname;
5424         dns_rdataset_t *rdataset;
5425         isc_boolean_t done, external, chaining, aa, found, want_chaining;
5426         isc_boolean_t have_answer, found_cname, found_type, wanted_chaining;
5427         unsigned int aflag;
5428         dns_rdatatype_t type;
5429         dns_fixedname_t dname, fqname;
5430
5431         FCTXTRACE("answer_response");
5432
5433         message = fctx->rmessage;
5434
5435         /*
5436          * Examine the answer section, marking those rdatasets which are
5437          * part of the answer and should be cached.
5438          */
5439
5440         done = ISC_FALSE;
5441         found_cname = ISC_FALSE;
5442         found_type = ISC_FALSE;
5443         chaining = ISC_FALSE;
5444         have_answer = ISC_FALSE;
5445         want_chaining = ISC_FALSE;
5446         if ((message->flags & DNS_MESSAGEFLAG_AA) != 0)
5447                 aa = ISC_TRUE;
5448         else
5449                 aa = ISC_FALSE;
5450         qname = &fctx->name;
5451         type = fctx->type;
5452         result = dns_message_firstname(message, DNS_SECTION_ANSWER);
5453         while (!done && result == ISC_R_SUCCESS) {
5454                 name = NULL;
5455                 dns_message_currentname(message, DNS_SECTION_ANSWER, &name);
5456                 external = ISC_TF(!dns_name_issubdomain(name, &fctx->domain));
5457                 if (dns_name_equal(name, qname)) {
5458                         wanted_chaining = ISC_FALSE;
5459                         for (rdataset = ISC_LIST_HEAD(name->list);
5460                              rdataset != NULL;
5461                              rdataset = ISC_LIST_NEXT(rdataset, link)) {
5462                                 found = ISC_FALSE;
5463                                 want_chaining = ISC_FALSE;
5464                                 aflag = 0;
5465                                 if (rdataset->type == dns_rdatatype_nsec3) {
5466                                         /*
5467                                          * NSEC3 records are not allowed to
5468                                          * appear in the answer section.
5469                                          */
5470                                         return (DNS_R_FORMERR);
5471                                 }
5472                                 if (rdataset->type == type && !found_cname) {
5473                                         /*
5474                                          * We've found an ordinary answer.
5475                                          */
5476                                         found = ISC_TRUE;
5477                                         found_type = ISC_TRUE;
5478                                         done = ISC_TRUE;
5479                                         aflag = DNS_RDATASETATTR_ANSWER;
5480                                 } else if (type == dns_rdatatype_any) {
5481                                         /*
5482                                          * We've found an answer matching
5483                                          * an ANY query.  There may be
5484                                          * more.
5485                                          */
5486                                         found = ISC_TRUE;
5487                                         aflag = DNS_RDATASETATTR_ANSWER;
5488                                 } else if (rdataset->type == dns_rdatatype_rrsig
5489                                            && rdataset->covers == type
5490                                            && !found_cname) {
5491                                         /*
5492                                          * We've found a signature that
5493                                          * covers the type we're looking for.
5494                                          */
5495                                         found = ISC_TRUE;
5496                                         found_type = ISC_TRUE;
5497                                         aflag = DNS_RDATASETATTR_ANSWERSIG;
5498                                 } else if (rdataset->type ==
5499                                            dns_rdatatype_cname
5500                                            && !found_type) {
5501                                         /*
5502                                          * We're looking for something else,
5503                                          * but we found a CNAME.
5504                                          *
5505                                          * Getting a CNAME response for some
5506                                          * query types is an error.
5507                                          */
5508                                         if (type == dns_rdatatype_rrsig ||
5509                                             type == dns_rdatatype_dnskey ||
5510                                             type == dns_rdatatype_nsec)
5511                                                 return (DNS_R_FORMERR);
5512                                         found = ISC_TRUE;
5513                                         found_cname = ISC_TRUE;
5514                                         want_chaining = ISC_TRUE;
5515                                         aflag = DNS_RDATASETATTR_ANSWER;
5516                                         result = cname_target(rdataset,
5517                                                               &tname);
5518                                         if (result != ISC_R_SUCCESS)
5519                                                 return (result);
5520                                 } else if (rdataset->type == dns_rdatatype_rrsig
5521                                            && rdataset->covers ==
5522                                            dns_rdatatype_cname
5523                                            && !found_type) {
5524                                         /*
5525                                          * We're looking for something else,
5526                                          * but we found a SIG CNAME.
5527                                          */
5528                                         found = ISC_TRUE;
5529                                         found_cname = ISC_TRUE;
5530                                         aflag = DNS_RDATASETATTR_ANSWERSIG;
5531                                 }
5532
5533                                 if (found) {
5534                                         /*
5535                                          * We've found an answer to our
5536                                          * question.
5537                                          */
5538                                         name->attributes |=
5539                                                 DNS_NAMEATTR_CACHE;
5540                                         rdataset->attributes |=
5541                                                 DNS_RDATASETATTR_CACHE;
5542                                         rdataset->trust = dns_trust_answer;
5543                                         if (!chaining) {
5544                                                 /*
5545                                                  * This data is "the" answer
5546                                                  * to our question only if
5547                                                  * we're not chaining (i.e.
5548                                                  * if we haven't followed
5549                                                  * a CNAME or DNAME).
5550                                                  */
5551                                                 INSIST(!external);
5552                                                 if (aflag ==
5553                                                     DNS_RDATASETATTR_ANSWER)
5554                                                         have_answer = ISC_TRUE;
5555                                                 name->attributes |=
5556                                                         DNS_NAMEATTR_ANSWER;
5557                                                 rdataset->attributes |= aflag;
5558                                                 if (aa)
5559                                                         rdataset->trust =
5560                                                           dns_trust_authanswer;
5561                                         } else if (external) {
5562                                                 /*
5563                                                  * This data is outside of
5564                                                  * our query domain, and
5565                                                  * may not be cached.
5566                                                  */
5567                                                 rdataset->attributes |=
5568                                                     DNS_RDATASETATTR_EXTERNAL;
5569                                         }
5570
5571                                         /*
5572                                          * Mark any additional data related
5573                                          * to this rdataset.
5574                                          */
5575                                         (void)dns_rdataset_additionaldata(
5576                                                         rdataset,
5577                                                         check_related,
5578                                                         fctx);
5579
5580                                         /*
5581                                          * CNAME chaining.
5582                                          */
5583                                         if (want_chaining) {
5584                                                 wanted_chaining = ISC_TRUE;
5585                                                 name->attributes |=
5586                                                         DNS_NAMEATTR_CHAINING;
5587                                                 rdataset->attributes |=
5588                                                     DNS_RDATASETATTR_CHAINING;
5589                                                 qname = &tname;
5590                                         }
5591                                 }
5592                                 /*
5593                                  * We could add an "else" clause here and
5594                                  * log that we're ignoring this rdataset.
5595                                  */
5596                         }
5597                         /*
5598                          * If wanted_chaining is true, we've done
5599                          * some chaining as the result of processing
5600                          * this node, and thus we need to set
5601                          * chaining to true.
5602                          *
5603                          * We don't set chaining inside of the
5604                          * rdataset loop because doing that would
5605                          * cause us to ignore the signatures of
5606                          * CNAMEs.
5607                          */
5608                         if (wanted_chaining)
5609                                 chaining = ISC_TRUE;
5610                 } else {
5611                         /*
5612                          * Look for a DNAME (or its SIG).  Anything else is
5613                          * ignored.
5614                          */
5615                         wanted_chaining = ISC_FALSE;
5616                         for (rdataset = ISC_LIST_HEAD(name->list);
5617                              rdataset != NULL;
5618                              rdataset = ISC_LIST_NEXT(rdataset, link)) {
5619                                 isc_boolean_t found_dname = ISC_FALSE;
5620                                 found = ISC_FALSE;
5621                                 aflag = 0;
5622                                 if (rdataset->type == dns_rdatatype_dname) {
5623                                         /*
5624                                          * We're looking for something else,
5625                                          * but we found a DNAME.
5626                                          *
5627                                          * If we're not chaining, then the
5628                                          * DNAME should not be external.
5629                                          */
5630                                         if (!chaining && external)
5631                                                 return (DNS_R_FORMERR);
5632                                         found = ISC_TRUE;
5633                                         want_chaining = ISC_TRUE;
5634                                         aflag = DNS_RDATASETATTR_ANSWER;
5635                                         result = dname_target(rdataset,
5636                                                               qname, name,
5637                                                               &dname);
5638                                         if (result == ISC_R_NOSPACE) {
5639                                                 /*
5640                                                  * We can't construct the
5641                                                  * DNAME target.  Do not
5642                                                  * try to continue.
5643                                                  */
5644                                                 want_chaining = ISC_FALSE;
5645                                         } else if (result != ISC_R_SUCCESS)
5646                                                 return (result);
5647                                         else
5648                                                 found_dname = ISC_TRUE;
5649                                 } else if (rdataset->type == dns_rdatatype_rrsig
5650                                            && rdataset->covers ==
5651                                            dns_rdatatype_dname) {
5652                                         /*
5653                                          * We've found a signature that
5654                                          * covers the DNAME.
5655                                          */
5656                                         found = ISC_TRUE;
5657                                         aflag = DNS_RDATASETATTR_ANSWERSIG;
5658                                 }
5659
5660                                 if (found) {
5661                                         /*
5662                                          * We've found an answer to our
5663                                          * question.
5664                                          */
5665                                         name->attributes |=
5666                                                 DNS_NAMEATTR_CACHE;
5667                                         rdataset->attributes |=
5668                                                 DNS_RDATASETATTR_CACHE;
5669                                         rdataset->trust = dns_trust_answer;
5670                                         if (!chaining) {
5671                                                 /*
5672                                                  * This data is "the" answer
5673                                                  * to our question only if
5674                                                  * we're not chaining.
5675                                                  */
5676                                                 INSIST(!external);
5677                                                 if (aflag ==
5678                                                     DNS_RDATASETATTR_ANSWER)
5679                                                         have_answer = ISC_TRUE;
5680                                                 name->attributes |=
5681                                                         DNS_NAMEATTR_ANSWER;
5682                                                 rdataset->attributes |= aflag;
5683                                                 if (aa)
5684                                                         rdataset->trust =
5685                                                           dns_trust_authanswer;
5686                                         } else if (external) {
5687                                                 rdataset->attributes |=
5688                                                     DNS_RDATASETATTR_EXTERNAL;
5689                                         }
5690
5691                                         /*
5692                                          * DNAME chaining.
5693                                          */
5694                                         if (found_dname) {
5695                                                 /*
5696                                                  * Copy the dname into the
5697                                                  * qname fixed name.
5698                                                  *
5699                                                  * Although we check for
5700                                                  * failure of the copy
5701                                                  * operation, in practice it
5702                                                  * should never fail since
5703                                                  * we already know that the
5704                                                  * result fits in a fixedname.
5705                                                  */
5706                                                 dns_fixedname_init(&fqname);
5707                                                 result = dns_name_copy(
5708                                                   dns_fixedname_name(&dname),
5709                                                   dns_fixedname_name(&fqname),
5710                                                   NULL);
5711                                                 if (result != ISC_R_SUCCESS)
5712                                                         return (result);
5713                                                 wanted_chaining = ISC_TRUE;
5714                                                 name->attributes |=
5715                                                         DNS_NAMEATTR_CHAINING;
5716                                                 rdataset->attributes |=
5717                                                     DNS_RDATASETATTR_CHAINING;
5718                                                 qname = dns_fixedname_name(
5719                                                                    &fqname);
5720                                         }
5721                                 }
5722                         }
5723                         if (wanted_chaining)
5724                                 chaining = ISC_TRUE;
5725                 }
5726                 result = dns_message_nextname(message, DNS_SECTION_ANSWER);
5727         }
5728         if (result == ISC_R_NOMORE)
5729                 result = ISC_R_SUCCESS;
5730         if (result != ISC_R_SUCCESS)
5731                 return (result);
5732
5733         /*
5734          * We should have found an answer.
5735          */
5736         if (!have_answer)
5737                 return (DNS_R_FORMERR);
5738
5739         /*
5740          * This response is now potentially cacheable.
5741          */
5742         fctx->attributes |= FCTX_ATTR_WANTCACHE;
5743
5744         /*
5745          * Did chaining end before we got the final answer?
5746          */
5747         if (chaining) {
5748                 /*
5749                  * Yes.  This may be a negative reply, so hand off
5750                  * authority section processing to the noanswer code.
5751                  * If it isn't a noanswer response, no harm will be
5752                  * done.
5753                  */
5754                 return (noanswer_response(fctx, qname, ISC_FALSE));
5755         }
5756
5757         /*
5758          * We didn't end with an incomplete chain, so the rcode should be
5759          * "no error".
5760          */
5761         if (message->rcode != dns_rcode_noerror)
5762                 return (DNS_R_FORMERR);
5763
5764         /*
5765          * Examine the authority section (if there is one).
5766          *
5767          * We expect there to be only one owner name for all the rdatasets
5768          * in this section, and we expect that it is not external.
5769          */
5770         done = ISC_FALSE;
5771         result = dns_message_firstname(message, DNS_SECTION_AUTHORITY);
5772         while (!done && result == ISC_R_SUCCESS) {
5773                 name = NULL;
5774                 dns_message_currentname(message, DNS_SECTION_AUTHORITY, &name);
5775                 external = ISC_TF(!dns_name_issubdomain(name, &fctx->domain));
5776                 if (!external) {
5777                         /*
5778                          * We expect to find NS or SIG NS rdatasets, and
5779                          * nothing else.
5780                          */
5781                         for (rdataset = ISC_LIST_HEAD(name->list);
5782                              rdataset != NULL;
5783                              rdataset = ISC_LIST_NEXT(rdataset, link)) {
5784                                 if (rdataset->type == dns_rdatatype_ns ||
5785                                     (rdataset->type == dns_rdatatype_rrsig &&
5786                                      rdataset->covers == dns_rdatatype_ns)) {
5787                                         name->attributes |=
5788                                                 DNS_NAMEATTR_CACHE;
5789                                         rdataset->attributes |=
5790                                                 DNS_RDATASETATTR_CACHE;
5791                                         if (aa && !chaining)
5792                                                 rdataset->trust =
5793                                                     dns_trust_authauthority;
5794                                         else
5795                                                 rdataset->trust =
5796                                                     dns_trust_additional;
5797
5798                                         /*
5799                                          * Mark any additional data related
5800                                          * to this rdataset.
5801                                          */
5802                                         (void)dns_rdataset_additionaldata(
5803                                                         rdataset,
5804                                                         check_related,
5805                                                         fctx);
5806                                         done = ISC_TRUE;
5807                                 }
5808                         }
5809                 }
5810                 result = dns_message_nextname(message, DNS_SECTION_AUTHORITY);
5811         }
5812         if (result == ISC_R_NOMORE)
5813                 result = ISC_R_SUCCESS;
5814
5815         return (result);
5816 }
5817
5818 static void
5819 resume_dslookup(isc_task_t *task, isc_event_t *event) {
5820         dns_fetchevent_t *fevent;
5821         dns_resolver_t *res;
5822         fetchctx_t *fctx;
5823         isc_result_t result;
5824         isc_boolean_t bucket_empty = ISC_FALSE;
5825         isc_boolean_t locked = ISC_FALSE;
5826         unsigned int bucketnum;
5827         dns_rdataset_t nameservers;
5828         dns_fixedname_t fixed;
5829         dns_name_t *domain;
5830
5831         REQUIRE(event->ev_type == DNS_EVENT_FETCHDONE);
5832         fevent = (dns_fetchevent_t *)event;
5833         fctx = event->ev_arg;
5834         REQUIRE(VALID_FCTX(fctx));
5835         res = fctx->res;
5836
5837         UNUSED(task);
5838         FCTXTRACE("resume_dslookup");
5839
5840         if (fevent->node != NULL)
5841                 dns_db_detachnode(fevent->db, &fevent->node);
5842         if (fevent->db != NULL)
5843                 dns_db_detach(&fevent->db);
5844
5845         dns_rdataset_init(&nameservers);
5846
5847         bucketnum = fctx->bucketnum;
5848         if (fevent->result == ISC_R_CANCELED) {
5849                 dns_resolver_destroyfetch(&fctx->nsfetch);
5850                 fctx_done(fctx, ISC_R_CANCELED, __LINE__);
5851         } else if (fevent->result == ISC_R_SUCCESS) {
5852
5853                 FCTXTRACE("resuming DS lookup");
5854
5855                 dns_resolver_destroyfetch(&fctx->nsfetch);
5856                 if (dns_rdataset_isassociated(&fctx->nameservers))
5857                         dns_rdataset_disassociate(&fctx->nameservers);
5858                 dns_rdataset_clone(fevent->rdataset, &fctx->nameservers);
5859                 dns_name_free(&fctx->domain,
5860                               fctx->res->buckets[bucketnum].mctx);
5861                 dns_name_init(&fctx->domain, NULL);
5862                 result = dns_name_dup(&fctx->nsname,
5863                                       fctx->res->buckets[bucketnum].mctx,
5864                                       &fctx->domain);
5865                 if (result != ISC_R_SUCCESS) {
5866                         fctx_done(fctx, DNS_R_SERVFAIL, __LINE__);
5867                         goto cleanup;
5868                 }
5869                 /*
5870                  * Try again.
5871                  */
5872                 fctx_try(fctx, ISC_TRUE, ISC_FALSE);
5873         } else {
5874                 unsigned int n;
5875                 dns_rdataset_t *nsrdataset = NULL;
5876
5877                 /*
5878                  * Retrieve state from fctx->nsfetch before we destroy it.
5879                  */
5880                 dns_fixedname_init(&fixed);
5881                 domain = dns_fixedname_name(&fixed);
5882                 dns_name_copy(&fctx->nsfetch->private->domain, domain, NULL);
5883                 if (dns_name_equal(&fctx->nsname, domain)) {
5884                         fctx_done(fctx, DNS_R_SERVFAIL, __LINE__);
5885                         dns_resolver_destroyfetch(&fctx->nsfetch);
5886                         goto cleanup;
5887                 }
5888                 if (dns_rdataset_isassociated(
5889                     &fctx->nsfetch->private->nameservers)) {
5890                         dns_rdataset_clone(
5891                             &fctx->nsfetch->private->nameservers,
5892                             &nameservers);
5893                         nsrdataset = &nameservers;
5894                 } else
5895                         domain = NULL;
5896                 dns_resolver_destroyfetch(&fctx->nsfetch);
5897                 n = dns_name_countlabels(&fctx->nsname);
5898                 dns_name_getlabelsequence(&fctx->nsname, 1, n - 1,
5899                                           &fctx->nsname);
5900
5901                 if (dns_rdataset_isassociated(fevent->rdataset))
5902                         dns_rdataset_disassociate(fevent->rdataset);
5903                 FCTXTRACE("continuing to look for parent's NS records");
5904                 result = dns_resolver_createfetch(fctx->res, &fctx->nsname,
5905                                                   dns_rdatatype_ns, domain,
5906                                                   nsrdataset, NULL, 0, task,
5907                                                   resume_dslookup, fctx,
5908                                                   &fctx->nsrrset, NULL,
5909                                                   &fctx->nsfetch);
5910                 if (result != ISC_R_SUCCESS)
5911                         fctx_done(fctx, result, __LINE__);
5912                 else {
5913                         LOCK(&res->buckets[bucketnum].lock);
5914                         locked = ISC_TRUE;
5915                         fctx->references++;
5916                 }
5917         }
5918
5919  cleanup:
5920         if (dns_rdataset_isassociated(&nameservers))
5921                 dns_rdataset_disassociate(&nameservers);
5922         if (dns_rdataset_isassociated(fevent->rdataset))
5923                 dns_rdataset_disassociate(fevent->rdataset);
5924         INSIST(fevent->sigrdataset == NULL);
5925         isc_event_free(&event);
5926         if (!locked)
5927                 LOCK(&res->buckets[bucketnum].lock);
5928         fctx->references--;
5929         if (fctx->references == 0)
5930                 bucket_empty = fctx_destroy(fctx);
5931         UNLOCK(&res->buckets[bucketnum].lock);
5932         if (bucket_empty)
5933                 empty_bucket(res);
5934 }
5935
5936 static inline void
5937 checknamessection(dns_message_t *message, dns_section_t section) {
5938         isc_result_t result;
5939         dns_name_t *name;
5940         dns_rdata_t rdata = DNS_RDATA_INIT;
5941         dns_rdataset_t *rdataset;
5942
5943         for (result = dns_message_firstname(message, section);
5944              result == ISC_R_SUCCESS;
5945              result = dns_message_nextname(message, section))
5946         {
5947                 name = NULL;
5948                 dns_message_currentname(message, section, &name);
5949                 for (rdataset = ISC_LIST_HEAD(name->list);
5950                      rdataset != NULL;
5951                      rdataset = ISC_LIST_NEXT(rdataset, link)) {
5952                         for (result = dns_rdataset_first(rdataset);
5953                              result == ISC_R_SUCCESS;
5954                              result = dns_rdataset_next(rdataset)) {
5955                                 dns_rdataset_current(rdataset, &rdata);
5956                                 if (!dns_rdata_checkowner(name, rdata.rdclass,
5957                                                           rdata.type,
5958                                                           ISC_FALSE) ||
5959                                     !dns_rdata_checknames(&rdata, name, NULL))
5960                                 {
5961                                         rdataset->attributes |=
5962                                                 DNS_RDATASETATTR_CHECKNAMES;
5963                                 }
5964                                 dns_rdata_reset(&rdata);
5965                         }
5966                 }
5967         }
5968 }
5969
5970 static void
5971 checknames(dns_message_t *message) {
5972
5973         checknamessection(message, DNS_SECTION_ANSWER);
5974         checknamessection(message, DNS_SECTION_AUTHORITY);
5975         checknamessection(message, DNS_SECTION_ADDITIONAL);
5976 }
5977
5978 /*
5979  * Log server NSID at log level 'level'
5980  */
5981 static isc_result_t
5982 log_nsid(dns_rdataset_t *opt, resquery_t *query, int level, isc_mem_t *mctx)
5983 {
5984         static const char hex[17] = "0123456789abcdef";
5985         char addrbuf[ISC_SOCKADDR_FORMATSIZE];
5986         isc_uint16_t optcode, nsid_len, buflen, i;
5987         isc_result_t result;
5988         isc_buffer_t nsidbuf;
5989         dns_rdata_t rdata;
5990         unsigned char *p, *buf, *nsid;
5991
5992         /* Extract rdata from OPT rdataset */
5993         result = dns_rdataset_first(opt);
5994         if (result != ISC_R_SUCCESS)
5995                 return (ISC_R_FAILURE);
5996
5997         dns_rdata_init(&rdata);
5998         dns_rdataset_current(opt, &rdata);
5999         if (rdata.length < 4)
6000                 return (ISC_R_FAILURE);
6001
6002         /* Check for NSID */
6003         isc_buffer_init(&nsidbuf, rdata.data, rdata.length);
6004         isc_buffer_add(&nsidbuf, rdata.length);
6005         optcode = isc_buffer_getuint16(&nsidbuf);
6006         nsid_len = isc_buffer_getuint16(&nsidbuf);
6007         if (optcode != DNS_OPT_NSID || nsid_len == 0)
6008                 return (ISC_R_FAILURE);
6009
6010         /* Allocate buffer for storing hex version of the NSID */
6011         buflen = nsid_len * 2 + 1;
6012         buf = isc_mem_get(mctx, buflen);
6013         if (buf == NULL)
6014                 return (ISC_R_NOSPACE);
6015
6016         /* Convert to hex */
6017         p = buf;
6018         nsid = rdata.data + 4;
6019         for (i = 0; i < nsid_len; i++) {
6020                 *p++ = hex[(nsid[0] >> 4) & 0xf];
6021                 *p++ = hex[nsid[0] & 0xf];
6022                 nsid++;
6023         }
6024         *p = '\0';
6025
6026         isc_sockaddr_format(&query->addrinfo->sockaddr, addrbuf,
6027                             sizeof(addrbuf));
6028         isc_log_write(dns_lctx, DNS_LOGCATEGORY_RESOLVER,
6029                       DNS_LOGMODULE_RESOLVER, level,
6030                       "received NSID '%s' from %s", buf, addrbuf);
6031
6032         /* Clean up */
6033         isc_mem_put(mctx, buf, buflen);
6034         return (ISC_R_SUCCESS);
6035 }
6036
6037 static void
6038 log_packet(dns_message_t *message, int level, isc_mem_t *mctx) {
6039         isc_buffer_t buffer;
6040         char *buf = NULL;
6041         int len = 1024;
6042         isc_result_t result;
6043
6044         if (! isc_log_wouldlog(dns_lctx, level))
6045                 return;
6046
6047         /*
6048          * Note that these are multiline debug messages.  We want a newline
6049          * to appear in the log after each message.
6050          */
6051
6052         do {
6053                 buf = isc_mem_get(mctx, len);
6054                 if (buf == NULL)
6055                         break;
6056                 isc_buffer_init(&buffer, buf, len);
6057                 result = dns_message_totext(message, &dns_master_style_debug,
6058                                             0, &buffer);
6059                 if (result == ISC_R_NOSPACE) {
6060                         isc_mem_put(mctx, buf, len);
6061                         len += 1024;
6062                 } else if (result == ISC_R_SUCCESS)
6063                         isc_log_write(dns_lctx, DNS_LOGCATEGORY_RESOLVER,
6064                                       DNS_LOGMODULE_RESOLVER, level,
6065                                       "received packet:\n%.*s",
6066                                       (int)isc_buffer_usedlength(&buffer),
6067                                       buf);
6068         } while (result == ISC_R_NOSPACE);
6069
6070         if (buf != NULL)
6071                 isc_mem_put(mctx, buf, len);
6072 }
6073
6074 static void
6075 resquery_response(isc_task_t *task, isc_event_t *event) {
6076         isc_result_t result = ISC_R_SUCCESS;
6077         resquery_t *query = event->ev_arg;
6078         dns_dispatchevent_t *devent = (dns_dispatchevent_t *)event;
6079         isc_boolean_t keep_trying, get_nameservers, resend;
6080         isc_boolean_t truncated;
6081         dns_message_t *message;
6082         dns_rdataset_t *opt;
6083         fetchctx_t *fctx;
6084         dns_name_t *fname;
6085         dns_fixedname_t foundname;
6086         isc_stdtime_t now;
6087         isc_time_t tnow, *finish;
6088         dns_adbaddrinfo_t *addrinfo;
6089         unsigned int options;
6090         unsigned int findoptions;
6091         isc_result_t broken_server;
6092         badnstype_t broken_type = badns_response;
6093
6094         REQUIRE(VALID_QUERY(query));
6095         fctx = query->fctx;
6096         options = query->options;
6097         REQUIRE(VALID_FCTX(fctx));
6098         REQUIRE(event->ev_type == DNS_EVENT_DISPATCH);
6099
6100         QTRACE("response");
6101
6102         if (isc_sockaddr_pf(&query->addrinfo->sockaddr) == PF_INET)
6103                 inc_stats(fctx->res, dns_resstatscounter_responsev4);
6104         else
6105                 inc_stats(fctx->res, dns_resstatscounter_responsev6);
6106
6107         (void)isc_timer_touch(fctx->timer);
6108
6109         keep_trying = ISC_FALSE;
6110         broken_server = ISC_R_SUCCESS;
6111         get_nameservers = ISC_FALSE;
6112         resend = ISC_FALSE;
6113         truncated = ISC_FALSE;
6114         finish = NULL;
6115
6116         if (fctx->res->exiting) {
6117                 result = ISC_R_SHUTTINGDOWN;
6118                 goto done;
6119         }
6120
6121         fctx->timeouts = 0;
6122         fctx->timeout = ISC_FALSE;
6123
6124         /*
6125          * XXXRTH  We should really get the current time just once.  We
6126          *              need a routine to convert from an isc_time_t to an
6127          *              isc_stdtime_t.
6128          */
6129         TIME_NOW(&tnow);
6130         finish = &tnow;
6131         isc_stdtime_get(&now);
6132
6133         /*
6134          * Did the dispatcher have a problem?
6135          */
6136         if (devent->result != ISC_R_SUCCESS) {
6137                 if (devent->result == ISC_R_EOF &&
6138                     (query->options & DNS_FETCHOPT_NOEDNS0) == 0) {
6139                         /*
6140                          * The problem might be that they
6141                          * don't understand EDNS0.  Turn it
6142                          * off and try again.
6143                          */
6144                         options |= DNS_FETCHOPT_NOEDNS0;
6145                         resend = ISC_TRUE;
6146                         /*
6147                          * Remember that they don't like EDNS0.
6148                          */
6149                         dns_adb_changeflags(fctx->adb,
6150                                             query->addrinfo,
6151                                             DNS_FETCHOPT_NOEDNS0,
6152                                             DNS_FETCHOPT_NOEDNS0);
6153                 } else {
6154                         /*
6155                          * There's no hope for this query.
6156                          */
6157                         keep_trying = ISC_TRUE;
6158
6159                         /*
6160                          * If this is a network error on an exclusive query
6161                          * socket, mark the server as bad so that we won't try
6162                          * it for this fetch again.
6163                          */
6164                         if (query->exclusivesocket &&
6165                             (devent->result == ISC_R_HOSTUNREACH ||
6166                              devent->result == ISC_R_NETUNREACH ||
6167                              devent->result == ISC_R_CONNREFUSED ||
6168                              devent->result == ISC_R_CANCELED)) {
6169                                     broken_server = devent->result;
6170                                     broken_type = badns_unreachable;
6171                         }
6172                 }
6173                 goto done;
6174         }
6175
6176         message = fctx->rmessage;
6177
6178         if (query->tsig != NULL) {
6179                 result = dns_message_setquerytsig(message, query->tsig);
6180                 if (result != ISC_R_SUCCESS)
6181                         goto done;
6182         }
6183
6184         if (query->tsigkey) {
6185                 result = dns_message_settsigkey(message, query->tsigkey);
6186                 if (result != ISC_R_SUCCESS)
6187                         goto done;
6188         }
6189
6190         result = dns_message_parse(message, &devent->buffer, 0);
6191         if (result != ISC_R_SUCCESS) {
6192                 switch (result) {
6193                 case ISC_R_UNEXPECTEDEND:
6194                         if (!message->question_ok ||
6195                             (message->flags & DNS_MESSAGEFLAG_TC) == 0 ||
6196                             (options & DNS_FETCHOPT_TCP) != 0) {
6197                                 /*
6198                                  * Either the message ended prematurely,
6199                                  * and/or wasn't marked as being truncated,
6200                                  * and/or this is a response to a query we
6201                                  * sent over TCP.  In all of these cases,
6202                                  * something is wrong with the remote
6203                                  * server and we don't want to retry using
6204                                  * TCP.
6205                                  */
6206                                 if ((query->options & DNS_FETCHOPT_NOEDNS0)
6207                                     == 0) {
6208                                         /*
6209                                          * The problem might be that they
6210                                          * don't understand EDNS0.  Turn it
6211                                          * off and try again.
6212                                          */
6213                                         options |= DNS_FETCHOPT_NOEDNS0;
6214                                         resend = ISC_TRUE;
6215                                         /*
6216                                          * Remember that they don't like EDNS0.
6217                                          */
6218                                         dns_adb_changeflags(
6219                                                         fctx->adb,
6220                                                         query->addrinfo,
6221                                                         DNS_FETCHOPT_NOEDNS0,
6222                                                         DNS_FETCHOPT_NOEDNS0);
6223                                         inc_stats(fctx->res,
6224                                                  dns_resstatscounter_edns0fail);
6225                                 } else {
6226                                         broken_server = result;
6227                                         keep_trying = ISC_TRUE;
6228                                 }
6229                                 goto done;
6230                         }
6231                         /*
6232                          * We defer retrying via TCP for a bit so we can
6233                          * check out this message further.
6234                          */
6235                         truncated = ISC_TRUE;
6236                         break;
6237                 case DNS_R_FORMERR:
6238                         if ((query->options & DNS_FETCHOPT_NOEDNS0) == 0) {
6239                                 /*
6240                                  * The problem might be that they
6241                                  * don't understand EDNS0.  Turn it
6242                                  * off and try again.
6243                                  */
6244                                 options |= DNS_FETCHOPT_NOEDNS0;
6245                                 resend = ISC_TRUE;
6246                                 /*
6247                                  * Remember that they don't like EDNS0.
6248                                  */
6249                                 dns_adb_changeflags(fctx->adb,
6250                                                     query->addrinfo,
6251                                                     DNS_FETCHOPT_NOEDNS0,
6252                                                     DNS_FETCHOPT_NOEDNS0);
6253                                 inc_stats(fctx->res,
6254                                                  dns_resstatscounter_edns0fail);
6255                         } else {
6256                                 broken_server = DNS_R_UNEXPECTEDRCODE;
6257                                 keep_trying = ISC_TRUE;
6258                         }
6259                         goto done;
6260                 default:
6261                         /*
6262                          * Something bad has happened.
6263                          */
6264                         goto done;
6265                 }
6266         }
6267
6268
6269         /*
6270          * Log the incoming packet.
6271          */
6272         log_packet(message, ISC_LOG_DEBUG(10), fctx->res->mctx);
6273
6274         /*
6275          * Did we request NSID?  If so, and if the response contains
6276          * NSID data, log it at INFO level.
6277          */
6278         opt = dns_message_getopt(message);
6279         if (opt != NULL && (query->options & DNS_FETCHOPT_WANTNSID) != 0)
6280                 log_nsid(opt, query, ISC_LOG_INFO, fctx->res->mctx);
6281
6282         /*
6283          * If the message is signed, check the signature.  If not, this
6284          * returns success anyway.
6285          */
6286         result = dns_message_checksig(message, fctx->res->view);
6287         if (result != ISC_R_SUCCESS)
6288                 goto done;
6289
6290         /*
6291          * The dispatcher should ensure we only get responses with QR set.
6292          */
6293         INSIST((message->flags & DNS_MESSAGEFLAG_QR) != 0);
6294         /*
6295          * INSIST() that the message comes from the place we sent it to,
6296          * since the dispatch code should ensure this.
6297          *
6298          * INSIST() that the message id is correct (this should also be
6299          * ensured by the dispatch code).
6300          */
6301
6302
6303         /*
6304          * Deal with truncated responses by retrying using TCP.
6305          */
6306         if ((message->flags & DNS_MESSAGEFLAG_TC) != 0)
6307                 truncated = ISC_TRUE;
6308
6309         if (truncated) {
6310                 inc_stats(fctx->res, dns_resstatscounter_truncated);
6311                 if ((options & DNS_FETCHOPT_TCP) != 0) {
6312                         broken_server = DNS_R_TRUNCATEDTCP;
6313                         keep_trying = ISC_TRUE;
6314                 } else {
6315                         options |= DNS_FETCHOPT_TCP;
6316                         resend = ISC_TRUE;
6317                 }
6318                 goto done;
6319         }
6320
6321         /*
6322          * Is it a query response?
6323          */
6324         if (message->opcode != dns_opcode_query) {
6325                 /* XXXRTH Log */
6326                 broken_server = DNS_R_UNEXPECTEDOPCODE;
6327                 keep_trying = ISC_TRUE;
6328                 goto done;
6329         }
6330
6331         /*
6332          * Update statistics about erroneous responses.
6333          */
6334         if (message->rcode != dns_rcode_noerror) {
6335                 switch (message->rcode) {
6336                 case dns_rcode_nxdomain:
6337                         inc_stats(fctx->res, dns_resstatscounter_nxdomain);
6338                         break;
6339                 case dns_rcode_servfail:
6340                         inc_stats(fctx->res, dns_resstatscounter_servfail);
6341                         break;
6342                 case dns_rcode_formerr:
6343                         inc_stats(fctx->res, dns_resstatscounter_formerr);
6344                         break;
6345                 default:
6346                         inc_stats(fctx->res, dns_resstatscounter_othererror);
6347                         break;
6348                 }
6349         }
6350
6351         /*
6352          * Is the remote server broken, or does it dislike us?
6353          */
6354         if (message->rcode != dns_rcode_noerror &&
6355             message->rcode != dns_rcode_nxdomain) {
6356                 if (((message->rcode == dns_rcode_formerr ||
6357                      message->rcode == dns_rcode_notimp) ||
6358                     (message->rcode == dns_rcode_servfail &&
6359                      dns_message_getopt(message) == NULL)) &&
6360                     (query->options & DNS_FETCHOPT_NOEDNS0) == 0) {
6361                         /*
6362                          * It's very likely they don't like EDNS0.
6363                          * If the response code is SERVFAIL, also check if the
6364                          * response contains an OPT RR and don't cache the
6365                          * failure since it can be returned for various other
6366                          * reasons.
6367                          *
6368                          * XXXRTH  We should check if the question
6369                          *              we're asking requires EDNS0, and
6370                          *              if so, we should bail out.
6371                          */
6372                         options |= DNS_FETCHOPT_NOEDNS0;
6373                         resend = ISC_TRUE;
6374                         /*
6375                          * Remember that they don't like EDNS0.
6376                          */
6377                         if (message->rcode != dns_rcode_servfail)
6378                                 dns_adb_changeflags(fctx->adb, query->addrinfo,
6379                                                     DNS_FETCHOPT_NOEDNS0,
6380                                                     DNS_FETCHOPT_NOEDNS0);
6381                         inc_stats(fctx->res, dns_resstatscounter_edns0fail);
6382                 } else if (message->rcode == dns_rcode_formerr) {
6383                         if (ISFORWARDER(query->addrinfo)) {
6384                                 /*
6385                                  * This forwarder doesn't understand us,
6386                                  * but other forwarders might.  Keep trying.
6387                                  */
6388                                 broken_server = DNS_R_REMOTEFORMERR;
6389                                 keep_trying = ISC_TRUE;
6390                         } else {
6391                                 /*
6392                                  * The server doesn't understand us.  Since
6393                                  * all servers for a zone need similar
6394                                  * capabilities, we assume that we will get
6395                                  * FORMERR from all servers, and thus we
6396                                  * cannot make any more progress with this
6397                                  * fetch.
6398                                  */
6399                                 result = DNS_R_FORMERR;
6400                         }
6401                 } else if (message->rcode == dns_rcode_yxdomain) {
6402                         /*
6403                          * DNAME mapping failed because the new name
6404                          * was too long.  There's no chance of success
6405                          * for this fetch.
6406                          */
6407                         result = DNS_R_YXDOMAIN;
6408                 } else if (message->rcode == dns_rcode_badvers) {
6409                         unsigned int flags, mask;
6410                         unsigned int version;
6411
6412                         resend = ISC_TRUE;
6413                         version = (opt->ttl >> 16) & 0xff;
6414                         flags = (version << DNS_FETCHOPT_EDNSVERSIONSHIFT) |
6415                                 DNS_FETCHOPT_EDNSVERSIONSET;
6416                         mask = DNS_FETCHOPT_EDNSVERSIONMASK |
6417                                DNS_FETCHOPT_EDNSVERSIONSET;
6418                         switch (version) {
6419                         case 0:
6420                                 dns_adb_changeflags(fctx->adb, query->addrinfo,
6421                                                     flags, mask);
6422                                 break;
6423                         default:
6424                                 broken_server = DNS_R_BADVERS;
6425                                 keep_trying = ISC_TRUE;
6426                                 break;
6427                         }
6428                 } else {
6429                         /*
6430                          * XXXRTH log.
6431                          */
6432                         broken_server = DNS_R_UNEXPECTEDRCODE;
6433                         INSIST(broken_server != ISC_R_SUCCESS);
6434                         keep_trying = ISC_TRUE;
6435                 }
6436                 goto done;
6437         }
6438
6439         /*
6440          * Is the question the same as the one we asked?
6441          */
6442         result = same_question(fctx);
6443         if (result != ISC_R_SUCCESS) {
6444                 /* XXXRTH Log */
6445                 if (result == DNS_R_FORMERR)
6446                         keep_trying = ISC_TRUE;
6447                 goto done;
6448         }
6449
6450         /*
6451          * Is the server lame?
6452          */
6453         if (fctx->res->lame_ttl != 0 && !ISFORWARDER(query->addrinfo) &&
6454             is_lame(fctx)) {
6455                 inc_stats(fctx->res, dns_resstatscounter_lame);
6456                 log_lame(fctx, query->addrinfo);
6457                 result = dns_adb_marklame(fctx->adb, query->addrinfo,
6458                                           &fctx->name, fctx->type,
6459                                           now + fctx->res->lame_ttl);
6460                 if (result != ISC_R_SUCCESS)
6461                         isc_log_write(dns_lctx, DNS_LOGCATEGORY_RESOLVER,
6462                                       DNS_LOGMODULE_RESOLVER, ISC_LOG_ERROR,
6463                                       "could not mark server as lame: %s",
6464                                       isc_result_totext(result));
6465                 broken_server = DNS_R_LAME;
6466                 keep_trying = ISC_TRUE;
6467                 goto done;
6468         }
6469
6470         /*
6471          * Enforce delegations only zones like NET and COM.
6472          */
6473         if (!ISFORWARDER(query->addrinfo) &&
6474             dns_view_isdelegationonly(fctx->res->view, &fctx->domain) &&
6475             !dns_name_equal(&fctx->domain, &fctx->name) &&
6476             fix_mustbedelegationornxdomain(message, fctx)) {
6477                 char namebuf[DNS_NAME_FORMATSIZE];
6478                 char domainbuf[DNS_NAME_FORMATSIZE];
6479                 char addrbuf[ISC_SOCKADDR_FORMATSIZE];
6480                 char classbuf[64];
6481                 char typebuf[64];
6482
6483                 dns_name_format(&fctx->name, namebuf, sizeof(namebuf));
6484                 dns_name_format(&fctx->domain, domainbuf, sizeof(domainbuf));
6485                 dns_rdatatype_format(fctx->type, typebuf, sizeof(typebuf));
6486                 dns_rdataclass_format(fctx->res->rdclass, classbuf,
6487                                       sizeof(classbuf));
6488                 isc_sockaddr_format(&query->addrinfo->sockaddr, addrbuf,
6489                                     sizeof(addrbuf));
6490
6491                 isc_log_write(dns_lctx, DNS_LOGCATEGORY_DELEGATION_ONLY,
6492                              DNS_LOGMODULE_RESOLVER, ISC_LOG_NOTICE,
6493                              "enforced delegation-only for '%s' (%s/%s/%s) "
6494                              "from %s",
6495                              domainbuf, namebuf, typebuf, classbuf, addrbuf);
6496         }
6497
6498         if ((fctx->res->options & DNS_RESOLVER_CHECKNAMES) != 0)
6499                 checknames(message);
6500
6501         /*
6502          * Clear cache bits.
6503          */
6504         fctx->attributes &= ~(FCTX_ATTR_WANTNCACHE | FCTX_ATTR_WANTCACHE);
6505
6506         /*
6507          * Did we get any answers?
6508          */
6509         if (message->counts[DNS_SECTION_ANSWER] > 0 &&
6510             (message->rcode == dns_rcode_noerror ||
6511              message->rcode == dns_rcode_nxdomain)) {
6512                 /*
6513                  * We've got answers.  However, if we sent
6514                  * a BIND 8 server an NS query, it may have
6515                  * incorrectly responded with a non-authoritative
6516                  * answer instead of a referral.  Since this
6517                  * answer lacks the SIGs necessary to do DNSSEC
6518                  * validation, we must invoke the following special
6519                  * kludge to treat it as a referral.
6520                  */
6521                 if (fctx->type == dns_rdatatype_ns &&
6522                     (message->flags & DNS_MESSAGEFLAG_AA) == 0 &&
6523                     !ISFORWARDER(query->addrinfo))
6524                 {
6525                         result = noanswer_response(fctx, NULL, ISC_TRUE);
6526                         if (result != DNS_R_DELEGATION) {
6527                                 /*
6528                                  * The answer section must have contained
6529                                  * something other than the NS records
6530                                  * we asked for.  Since AA is not set
6531                                  * and the server is not a forwarder,
6532                                  * it is technically lame and it's easier
6533                                  * to treat it as such than to figure out
6534                                  * some more elaborate course of action.
6535                                  */
6536                                 broken_server = DNS_R_LAME;
6537                                 keep_trying = ISC_TRUE;
6538                                 goto done;
6539                         }
6540                         goto force_referral;
6541                 }
6542                 result = answer_response(fctx);
6543                 if (result != ISC_R_SUCCESS) {
6544                         if (result == DNS_R_FORMERR)
6545                                 keep_trying = ISC_TRUE;
6546                         goto done;
6547                 }
6548         } else if (message->counts[DNS_SECTION_AUTHORITY] > 0 ||
6549                    message->rcode == dns_rcode_noerror ||
6550                    message->rcode == dns_rcode_nxdomain) {
6551                 /*
6552                  * NXDOMAIN, NXRDATASET, or referral.
6553                  */
6554                 result = noanswer_response(fctx, NULL, ISC_FALSE);
6555                 if (result == DNS_R_CHASEDSSERVERS) {
6556                 } else if (result == DNS_R_DELEGATION) {
6557                 force_referral:
6558                         /*
6559                          * We don't have the answer, but we know a better
6560                          * place to look.
6561                          */
6562                         get_nameservers = ISC_TRUE;
6563                         keep_trying = ISC_TRUE;
6564                         /*
6565                          * We have a new set of name servers, and it
6566                          * has not experienced any restarts yet.
6567                          */
6568                         fctx->restarts = 0;
6569
6570                         /*
6571                          * Update local statistics counters collected for each
6572                          * new zone.
6573                          */
6574                         fctx->referrals++;
6575                         fctx->querysent = 0;
6576                         fctx->lamecount = 0;
6577                         fctx->neterr = 0;
6578                         fctx->badresp = 0;
6579                         fctx->adberr = 0;
6580
6581                         result = ISC_R_SUCCESS;
6582                 } else if (result != ISC_R_SUCCESS) {
6583                         /*
6584                          * Something has gone wrong.
6585                          */
6586                         if (result == DNS_R_FORMERR)
6587                                 keep_trying = ISC_TRUE;
6588                         goto done;
6589                 }
6590         } else {
6591                 /*
6592                  * The server is insane.
6593                  */
6594                 /* XXXRTH Log */
6595                 broken_server = DNS_R_UNEXPECTEDRCODE;
6596                 keep_trying = ISC_TRUE;
6597                 goto done;
6598         }
6599
6600         /*
6601          * Follow additional section data chains.
6602          */
6603         chase_additional(fctx);
6604
6605         /*
6606          * Cache the cacheable parts of the message.  This may also cause
6607          * work to be queued to the DNSSEC validator.
6608          */
6609         if (WANTCACHE(fctx)) {
6610                 result = cache_message(fctx, query->addrinfo, now);
6611                 if (result != ISC_R_SUCCESS)
6612                         goto done;
6613         }
6614
6615         /*
6616          * Ncache the negatively cacheable parts of the message.  This may
6617          * also cause work to be queued to the DNSSEC validator.
6618          */
6619         if (WANTNCACHE(fctx)) {
6620                 dns_rdatatype_t covers;
6621                 if (message->rcode == dns_rcode_nxdomain)
6622                         covers = dns_rdatatype_any;
6623                 else
6624                         covers = fctx->type;
6625
6626                 /*
6627                  * Cache any negative cache entries in the message.
6628                  */
6629                 result = ncache_message(fctx, query->addrinfo, covers, now);
6630         }
6631
6632  done:
6633         /*
6634          * Remember the query's addrinfo, in case we need to mark the
6635          * server as broken.
6636          */
6637         addrinfo = query->addrinfo;
6638
6639         /*
6640          * Cancel the query.
6641          *
6642          * XXXRTH  Don't cancel the query if waiting for validation?
6643          */
6644         fctx_cancelquery(&query, &devent, finish, ISC_FALSE);
6645
6646         if (keep_trying) {
6647                 if (result == DNS_R_FORMERR)
6648                         broken_server = DNS_R_FORMERR;
6649                 if (broken_server != ISC_R_SUCCESS) {
6650                         /*
6651                          * Add this server to the list of bad servers for
6652                          * this fctx.
6653                          */
6654                         add_bad(fctx, addrinfo, broken_server, broken_type);
6655                 }
6656
6657                 if (get_nameservers) {
6658                         dns_name_t *name;
6659                         dns_fixedname_init(&foundname);
6660                         fname = dns_fixedname_name(&foundname);
6661                         if (result != ISC_R_SUCCESS) {
6662                                 fctx_done(fctx, DNS_R_SERVFAIL, __LINE__);
6663                                 return;
6664                         }
6665                         findoptions = 0;
6666                         if (dns_rdatatype_atparent(fctx->type))
6667                                 findoptions |= DNS_DBFIND_NOEXACT;
6668                         if ((options & DNS_FETCHOPT_UNSHARED) == 0)
6669                                 name = &fctx->name;
6670                         else
6671                                 name = &fctx->domain;
6672                         result = dns_view_findzonecut(fctx->res->view,
6673                                                       name, fname,
6674                                                       now, findoptions,
6675                                                       ISC_TRUE,
6676                                                       &fctx->nameservers,
6677                                                       NULL);
6678                         if (result != ISC_R_SUCCESS) {
6679                                 FCTXTRACE("couldn't find a zonecut");
6680                                 fctx_done(fctx, DNS_R_SERVFAIL, __LINE__);
6681                                 return;
6682                         }
6683                         if (!dns_name_issubdomain(fname, &fctx->domain)) {
6684                                 /*
6685                                  * The best nameservers are now above our
6686                                  * QDOMAIN.
6687                                  */
6688                                 FCTXTRACE("nameservers now above QDOMAIN");
6689                                 fctx_done(fctx, DNS_R_SERVFAIL, __LINE__);
6690                                 return;
6691                         }
6692                         dns_name_free(&fctx->domain,
6693                                       fctx->res->buckets[fctx->bucketnum].mctx);
6694                         dns_name_init(&fctx->domain, NULL);
6695                         result = dns_name_dup(fname,
6696                                               fctx->res->buckets[fctx->bucketnum].mctx,
6697                                               &fctx->domain);
6698                         if (result != ISC_R_SUCCESS) {
6699                                 fctx_done(fctx, DNS_R_SERVFAIL, __LINE__);
6700                                 return;
6701                         }
6702                         fctx_cancelqueries(fctx, ISC_TRUE);
6703                         fctx_cleanupfinds(fctx);
6704                         fctx_cleanupaltfinds(fctx);
6705                         fctx_cleanupforwaddrs(fctx);
6706                         fctx_cleanupaltaddrs(fctx);
6707                 }
6708                 /*
6709                  * Try again.
6710                  */
6711                 fctx_try(fctx, !get_nameservers, ISC_FALSE);
6712         } else if (resend) {
6713                 /*
6714                  * Resend (probably with changed options).
6715                  */
6716                 FCTXTRACE("resend");
6717                 inc_stats(fctx->res, dns_resstatscounter_retry);
6718                 result = fctx_query(fctx, addrinfo, options);
6719                 if (result != ISC_R_SUCCESS)
6720                         fctx_done(fctx, result, __LINE__);
6721         } else if (result == ISC_R_SUCCESS && !HAVE_ANSWER(fctx)) {
6722                 /*
6723                  * All has gone well so far, but we are waiting for the
6724                  * DNSSEC validator to validate the answer.
6725                  */
6726                 FCTXTRACE("wait for validator");
6727                 fctx_cancelqueries(fctx, ISC_TRUE);
6728                 /*
6729                  * We must not retransmit while the validator is working;
6730                  * it has references to the current rmessage.
6731                  */
6732                 result = fctx_stopidletimer(fctx);
6733                 if (result != ISC_R_SUCCESS)
6734                         fctx_done(fctx, result, __LINE__);
6735         } else if (result == DNS_R_CHASEDSSERVERS) {
6736                 unsigned int n;
6737                 add_bad(fctx, addrinfo, result, broken_type);
6738                 fctx_cancelqueries(fctx, ISC_TRUE);
6739                 fctx_cleanupfinds(fctx);
6740                 fctx_cleanupforwaddrs(fctx);
6741
6742                 n = dns_name_countlabels(&fctx->name);
6743                 dns_name_getlabelsequence(&fctx->name, 1, n - 1, &fctx->nsname);
6744
6745                 FCTXTRACE("suspending DS lookup to find parent's NS records");
6746
6747                 result = dns_resolver_createfetch(fctx->res, &fctx->nsname,
6748                                                   dns_rdatatype_ns,
6749                                                   NULL, NULL, NULL, 0, task,
6750                                                   resume_dslookup, fctx,
6751                                                   &fctx->nsrrset, NULL,
6752                                                   &fctx->nsfetch);
6753                 if (result != ISC_R_SUCCESS)
6754                         fctx_done(fctx, result, __LINE__);
6755                 LOCK(&fctx->res->buckets[fctx->bucketnum].lock);
6756                 fctx->references++;
6757                 UNLOCK(&fctx->res->buckets[fctx->bucketnum].lock);
6758                 result = fctx_stopidletimer(fctx);
6759                 if (result != ISC_R_SUCCESS)
6760                         fctx_done(fctx, result, __LINE__);
6761         } else {
6762                 /*
6763                  * We're done.
6764                  */
6765                 fctx_done(fctx, result, __LINE__);
6766         }
6767 }
6768
6769
6770 /***
6771  *** Resolver Methods
6772  ***/
6773 static void
6774 destroy_badcache(dns_resolver_t *res) {
6775         dns_badcache_t *bad, *next;
6776         unsigned int i;
6777
6778         if (res->badcache != NULL) {
6779                 for (i = 0; i < res->badhash; i++)
6780                         for (bad = res->badcache[i]; bad != NULL;
6781                              bad = next) {
6782                                 next = bad->next;
6783                                 isc_mem_put(res->mctx, bad, sizeof(*bad) +
6784                                             bad->name.length);
6785                                 res->badcount--;
6786                         }
6787                 isc_mem_put(res->mctx, res->badcache,
6788                             sizeof(*res->badcache) * res->badhash);
6789                 res->badcache = NULL;
6790                 res->badhash = 0;
6791                 INSIST(res->badcount == 0);
6792         }
6793 }
6794
6795 static void
6796 destroy(dns_resolver_t *res) {
6797         unsigned int i;
6798         alternate_t *a;
6799
6800         REQUIRE(res->references == 0);
6801         REQUIRE(!res->priming);
6802         REQUIRE(res->primefetch == NULL);
6803
6804         RTRACE("destroy");
6805
6806         INSIST(res->nfctx == 0);
6807
6808         DESTROYLOCK(&res->primelock);
6809         DESTROYLOCK(&res->nlock);
6810         DESTROYLOCK(&res->lock);
6811         for (i = 0; i < res->nbuckets; i++) {
6812                 INSIST(ISC_LIST_EMPTY(res->buckets[i].fctxs));
6813                 isc_task_shutdown(res->buckets[i].task);
6814                 isc_task_detach(&res->buckets[i].task);
6815                 DESTROYLOCK(&res->buckets[i].lock);
6816                 isc_mem_detach(&res->buckets[i].mctx);
6817         }
6818         isc_mem_put(res->mctx, res->buckets,
6819                     res->nbuckets * sizeof(fctxbucket_t));
6820         if (res->dispatchv4 != NULL)
6821                 dns_dispatch_detach(&res->dispatchv4);
6822         if (res->dispatchv6 != NULL)
6823                 dns_dispatch_detach(&res->dispatchv6);
6824         while ((a = ISC_LIST_HEAD(res->alternates)) != NULL) {
6825                 ISC_LIST_UNLINK(res->alternates, a, link);
6826                 if (!a->isaddress)
6827                         dns_name_free(&a->_u._n.name, res->mctx);
6828                 isc_mem_put(res->mctx, a, sizeof(*a));
6829         }
6830         dns_resolver_reset_algorithms(res);
6831         destroy_badcache(res);
6832         dns_resolver_resetmustbesecure(res);
6833 #if USE_ALGLOCK
6834         isc_rwlock_destroy(&res->alglock);
6835 #endif
6836 #if USE_MBSLOCK
6837         isc_rwlock_destroy(&res->mbslock);
6838 #endif
6839         isc_timer_detach(&res->spillattimer);
6840         res->magic = 0;
6841         isc_mem_put(res->mctx, res, sizeof(*res));
6842 }
6843
6844 static void
6845 send_shutdown_events(dns_resolver_t *res) {
6846         isc_event_t *event, *next_event;
6847         isc_task_t *etask;
6848
6849         /*
6850          * Caller must be holding the resolver lock.
6851          */
6852
6853         for (event = ISC_LIST_HEAD(res->whenshutdown);
6854              event != NULL;
6855              event = next_event) {
6856                 next_event = ISC_LIST_NEXT(event, ev_link);
6857                 ISC_LIST_UNLINK(res->whenshutdown, event, ev_link);
6858                 etask = event->ev_sender;
6859                 event->ev_sender = res;
6860                 isc_task_sendanddetach(&etask, &event);
6861         }
6862 }
6863
6864 static void
6865 empty_bucket(dns_resolver_t *res) {
6866         RTRACE("empty_bucket");
6867
6868         LOCK(&res->lock);
6869
6870         INSIST(res->activebuckets > 0);
6871         res->activebuckets--;
6872         if (res->activebuckets == 0)
6873                 send_shutdown_events(res);
6874
6875         UNLOCK(&res->lock);
6876 }
6877
6878 static void
6879 spillattimer_countdown(isc_task_t *task, isc_event_t *event) {
6880         dns_resolver_t *res = event->ev_arg;
6881         isc_result_t result;
6882         unsigned int count;
6883         isc_boolean_t logit = ISC_FALSE;
6884
6885         REQUIRE(VALID_RESOLVER(res));
6886
6887         UNUSED(task);
6888
6889         LOCK(&res->lock);
6890         INSIST(!res->exiting);
6891         if (res->spillat > res->spillatmin) {
6892                 res->spillat--;
6893                 logit = ISC_TRUE;
6894         }
6895         if (res->spillat <= res->spillatmin) {
6896                 result = isc_timer_reset(res->spillattimer,
6897                                          isc_timertype_inactive, NULL,
6898                                          NULL, ISC_TRUE);
6899                 RUNTIME_CHECK(result == ISC_R_SUCCESS);
6900         }
6901         count = res->spillat;
6902         UNLOCK(&res->lock);
6903         if (logit)
6904                 isc_log_write(dns_lctx, DNS_LOGCATEGORY_RESOLVER,
6905                               DNS_LOGMODULE_RESOLVER, ISC_LOG_NOTICE,
6906                               "clients-per-query decreased to %u", count);
6907
6908         isc_event_free(&event);
6909 }
6910
6911 isc_result_t
6912 dns_resolver_create(dns_view_t *view,
6913                     isc_taskmgr_t *taskmgr, unsigned int ntasks,
6914                     isc_socketmgr_t *socketmgr,
6915                     isc_timermgr_t *timermgr,
6916                     unsigned int options,
6917                     dns_dispatchmgr_t *dispatchmgr,
6918                     dns_dispatch_t *dispatchv4,
6919                     dns_dispatch_t *dispatchv6,
6920                     dns_resolver_t **resp)
6921 {
6922         dns_resolver_t *res;
6923         isc_result_t result = ISC_R_SUCCESS;
6924         unsigned int i, buckets_created = 0;
6925         isc_task_t *task = NULL;
6926         char name[16];
6927         unsigned dispattr;
6928
6929         /*
6930          * Create a resolver.
6931          */
6932
6933         REQUIRE(DNS_VIEW_VALID(view));
6934         REQUIRE(ntasks > 0);
6935         REQUIRE(resp != NULL && *resp == NULL);
6936         REQUIRE(dispatchmgr != NULL);
6937         REQUIRE(dispatchv4 != NULL || dispatchv6 != NULL);
6938
6939         res = isc_mem_get(view->mctx, sizeof(*res));
6940         if (res == NULL)
6941                 return (ISC_R_NOMEMORY);
6942         RTRACE("create");
6943         res->mctx = view->mctx;
6944         res->rdclass = view->rdclass;
6945         res->socketmgr = socketmgr;
6946         res->timermgr = timermgr;
6947         res->taskmgr = taskmgr;
6948         res->dispatchmgr = dispatchmgr;
6949         res->view = view;
6950         res->options = options;
6951         res->lame_ttl = 0;
6952         ISC_LIST_INIT(res->alternates);
6953         res->udpsize = RECV_BUFFER_SIZE;
6954         res->algorithms = NULL;
6955         res->badcache = NULL;
6956         res->badcount = 0;
6957         res->badhash = 0;
6958         res->badsweep = 0;
6959         res->mustbesecure = NULL;
6960         res->spillatmin = res->spillat = 10;
6961         res->spillatmax = 100;
6962         res->spillattimer = NULL;
6963         res->zero_no_soa_ttl = ISC_FALSE;
6964         res->ndisps = 0;
6965         res->nextdisp = 0; /* meaningless at this point, but init it */
6966         res->nbuckets = ntasks;
6967         res->activebuckets = ntasks;
6968         res->buckets = isc_mem_get(view->mctx,
6969                                    ntasks * sizeof(fctxbucket_t));
6970         if (res->buckets == NULL) {
6971                 result = ISC_R_NOMEMORY;
6972                 goto cleanup_res;
6973         }
6974         for (i = 0; i < ntasks; i++) {
6975                 result = isc_mutex_init(&res->buckets[i].lock);
6976                 if (result != ISC_R_SUCCESS)
6977                         goto cleanup_buckets;
6978                 res->buckets[i].task = NULL;
6979                 result = isc_task_create(taskmgr, 0, &res->buckets[i].task);
6980                 if (result != ISC_R_SUCCESS) {
6981                         DESTROYLOCK(&res->buckets[i].lock);
6982                         goto cleanup_buckets;
6983                 }
6984                 res->buckets[i].mctx = NULL;
6985                 snprintf(name, sizeof(name), "res%u", i);
6986 #ifdef ISC_PLATFORM_USETHREADS
6987                 /*
6988                  * Use a separate memory context for each bucket to reduce
6989                  * contention among multiple threads.  Do this only when
6990                  * enabling threads because it will be require more memory.
6991                  */
6992                 result = isc_mem_create(0, 0, &res->buckets[i].mctx);
6993                 if (result != ISC_R_SUCCESS) {
6994                         isc_task_detach(&res->buckets[i].task);
6995                         DESTROYLOCK(&res->buckets[i].lock);
6996                         goto cleanup_buckets;
6997                 }
6998                 isc_mem_setname(res->buckets[i].mctx, name, NULL);
6999 #else
7000                 isc_mem_attach(view->mctx, &res->buckets[i].mctx);
7001 #endif
7002                 isc_task_setname(res->buckets[i].task, name, res);
7003                 ISC_LIST_INIT(res->buckets[i].fctxs);
7004                 res->buckets[i].exiting = ISC_FALSE;
7005                 buckets_created++;
7006         }
7007
7008         res->dispatchv4 = NULL;
7009         if (dispatchv4 != NULL) {
7010                 dns_dispatch_attach(dispatchv4, &res->dispatchv4);
7011                 dispattr = dns_dispatch_getattributes(dispatchv4);
7012                 res->exclusivev4 =
7013                         ISC_TF((dispattr & DNS_DISPATCHATTR_EXCLUSIVE) != 0);
7014         }
7015
7016         res->dispatchv6 = NULL;
7017         if (dispatchv6 != NULL) {
7018                 dns_dispatch_attach(dispatchv6, &res->dispatchv6);
7019                 dispattr = dns_dispatch_getattributes(dispatchv6);
7020                 res->exclusivev6 =
7021                         ISC_TF((dispattr & DNS_DISPATCHATTR_EXCLUSIVE) != 0);
7022         }
7023
7024         res->references = 1;
7025         res->exiting = ISC_FALSE;
7026         res->frozen = ISC_FALSE;
7027         ISC_LIST_INIT(res->whenshutdown);
7028         res->priming = ISC_FALSE;
7029         res->primefetch = NULL;
7030         res->nfctx = 0;
7031
7032         result = isc_mutex_init(&res->lock);
7033         if (result != ISC_R_SUCCESS)
7034                 goto cleanup_dispatches;
7035
7036         result = isc_mutex_init(&res->nlock);
7037         if (result != ISC_R_SUCCESS)
7038                 goto cleanup_lock;
7039
7040         result = isc_mutex_init(&res->primelock);
7041         if (result != ISC_R_SUCCESS)
7042                 goto cleanup_nlock;
7043
7044         task = NULL;
7045         result = isc_task_create(taskmgr, 0, &task);
7046         if (result != ISC_R_SUCCESS)
7047                 goto cleanup_primelock;
7048
7049         result = isc_timer_create(timermgr, isc_timertype_inactive, NULL, NULL,
7050                                   task, spillattimer_countdown, res,
7051                                   &res->spillattimer);
7052         isc_task_detach(&task);
7053         if (result != ISC_R_SUCCESS)
7054                 goto cleanup_primelock;
7055
7056 #if USE_ALGLOCK
7057         result = isc_rwlock_init(&res->alglock, 0, 0);
7058         if (result != ISC_R_SUCCESS)
7059                 goto cleanup_spillattimer;
7060 #endif
7061 #if USE_MBSLOCK
7062         result = isc_rwlock_init(&res->mbslock, 0, 0);
7063         if (result != ISC_R_SUCCESS)
7064                 goto cleanup_alglock;
7065 #endif
7066
7067         res->magic = RES_MAGIC;
7068
7069         *resp = res;
7070
7071         return (ISC_R_SUCCESS);
7072
7073 #if USE_MBSLOCK
7074  cleanup_alglock:
7075 #if USE_ALGLOCK
7076         isc_rwlock_destroy(&res->alglock);
7077 #endif
7078 #endif
7079 #if USE_ALGLOCK || USE_MBSLOCK
7080  cleanup_spillattimer:
7081         isc_timer_detach(&res->spillattimer);
7082 #endif
7083
7084  cleanup_primelock:
7085         DESTROYLOCK(&res->primelock);
7086
7087  cleanup_nlock:
7088         DESTROYLOCK(&res->nlock);
7089
7090  cleanup_lock:
7091         DESTROYLOCK(&res->lock);
7092
7093  cleanup_dispatches:
7094         if (res->dispatchv6 != NULL)
7095                 dns_dispatch_detach(&res->dispatchv6);
7096         if (res->dispatchv4 != NULL)
7097                 dns_dispatch_detach(&res->dispatchv4);
7098
7099  cleanup_buckets:
7100         for (i = 0; i < buckets_created; i++) {
7101                 isc_mem_detach(&res->buckets[i].mctx);
7102                 DESTROYLOCK(&res->buckets[i].lock);
7103                 isc_task_shutdown(res->buckets[i].task);
7104                 isc_task_detach(&res->buckets[i].task);
7105         }
7106         isc_mem_put(view->mctx, res->buckets,
7107                     res->nbuckets * sizeof(fctxbucket_t));
7108
7109  cleanup_res:
7110         isc_mem_put(view->mctx, res, sizeof(*res));
7111
7112         return (result);
7113 }
7114
7115 static void
7116 prime_done(isc_task_t *task, isc_event_t *event) {
7117         dns_resolver_t *res;
7118         dns_fetchevent_t *fevent;
7119         dns_fetch_t *fetch;
7120         dns_db_t *db = NULL;
7121
7122         REQUIRE(event->ev_type == DNS_EVENT_FETCHDONE);
7123         fevent = (dns_fetchevent_t *)event;
7124         res = event->ev_arg;
7125         REQUIRE(VALID_RESOLVER(res));
7126
7127         UNUSED(task);
7128
7129         LOCK(&res->lock);
7130
7131         INSIST(res->priming);
7132         res->priming = ISC_FALSE;
7133         LOCK(&res->primelock);
7134         fetch = res->primefetch;
7135         res->primefetch = NULL;
7136         UNLOCK(&res->primelock);
7137
7138         UNLOCK(&res->lock);
7139
7140         if (fevent->result == ISC_R_SUCCESS &&
7141             res->view->cache != NULL && res->view->hints != NULL) {
7142                 dns_cache_attachdb(res->view->cache, &db);
7143                 dns_root_checkhints(res->view, res->view->hints, db);
7144                 dns_db_detach(&db);
7145         }
7146
7147         if (fevent->node != NULL)
7148                 dns_db_detachnode(fevent->db, &fevent->node);
7149         if (fevent->db != NULL)
7150                 dns_db_detach(&fevent->db);
7151         if (dns_rdataset_isassociated(fevent->rdataset))
7152                 dns_rdataset_disassociate(fevent->rdataset);
7153         INSIST(fevent->sigrdataset == NULL);
7154
7155         isc_mem_put(res->mctx, fevent->rdataset, sizeof(*fevent->rdataset));
7156
7157         isc_event_free(&event);
7158         dns_resolver_destroyfetch(&fetch);
7159 }
7160
7161 void
7162 dns_resolver_prime(dns_resolver_t *res) {
7163         isc_boolean_t want_priming = ISC_FALSE;
7164         dns_rdataset_t *rdataset;
7165         isc_result_t result;
7166
7167         REQUIRE(VALID_RESOLVER(res));
7168         REQUIRE(res->frozen);
7169
7170         RTRACE("dns_resolver_prime");
7171
7172         LOCK(&res->lock);
7173
7174         if (!res->exiting && !res->priming) {
7175                 INSIST(res->primefetch == NULL);
7176                 res->priming = ISC_TRUE;
7177                 want_priming = ISC_TRUE;
7178         }
7179
7180         UNLOCK(&res->lock);
7181
7182         if (want_priming) {
7183                 /*
7184                  * To avoid any possible recursive locking problems, we
7185                  * start the priming fetch like any other fetch, and holding
7186                  * no resolver locks.  No one else will try to start it
7187                  * because we're the ones who set res->priming to true.
7188                  * Any other callers of dns_resolver_prime() while we're
7189                  * running will see that res->priming is already true and
7190                  * do nothing.
7191                  */
7192                 RTRACE("priming");
7193                 rdataset = isc_mem_get(res->mctx, sizeof(*rdataset));
7194                 if (rdataset == NULL) {
7195                         LOCK(&res->lock);
7196                         INSIST(res->priming);
7197                         INSIST(res->primefetch == NULL);
7198                         res->priming = ISC_FALSE;
7199                         UNLOCK(&res->lock);
7200                         return;
7201                 }
7202                 dns_rdataset_init(rdataset);
7203                 LOCK(&res->primelock);
7204                 result = dns_resolver_createfetch(res, dns_rootname,
7205                                                   dns_rdatatype_ns,
7206                                                   NULL, NULL, NULL, 0,
7207                                                   res->buckets[0].task,
7208                                                   prime_done,
7209                                                   res, rdataset, NULL,
7210                                                   &res->primefetch);
7211                 UNLOCK(&res->primelock);
7212                 if (result != ISC_R_SUCCESS) {
7213                         LOCK(&res->lock);
7214                         INSIST(res->priming);
7215                         res->priming = ISC_FALSE;
7216                         UNLOCK(&res->lock);
7217                 }
7218         }
7219 }
7220
7221 void
7222 dns_resolver_freeze(dns_resolver_t *res) {
7223
7224         /*
7225          * Freeze resolver.
7226          */
7227
7228         REQUIRE(VALID_RESOLVER(res));
7229         REQUIRE(!res->frozen);
7230
7231         res->frozen = ISC_TRUE;
7232 }
7233
7234 void
7235 dns_resolver_attach(dns_resolver_t *source, dns_resolver_t **targetp) {
7236         REQUIRE(VALID_RESOLVER(source));
7237         REQUIRE(targetp != NULL && *targetp == NULL);
7238
7239         RRTRACE(source, "attach");
7240         LOCK(&source->lock);
7241         REQUIRE(!source->exiting);
7242
7243         INSIST(source->references > 0);
7244         source->references++;
7245         INSIST(source->references != 0);
7246         UNLOCK(&source->lock);
7247
7248         *targetp = source;
7249 }
7250
7251 void
7252 dns_resolver_whenshutdown(dns_resolver_t *res, isc_task_t *task,
7253                           isc_event_t **eventp)
7254 {
7255         isc_task_t *clone;
7256         isc_event_t *event;
7257
7258         REQUIRE(VALID_RESOLVER(res));
7259         REQUIRE(eventp != NULL);
7260
7261         event = *eventp;
7262         *eventp = NULL;
7263
7264         LOCK(&res->lock);
7265
7266         if (res->exiting && res->activebuckets == 0) {
7267                 /*
7268                  * We're already shutdown.  Send the event.
7269                  */
7270                 event->ev_sender = res;
7271                 isc_task_send(task, &event);
7272         } else {
7273                 clone = NULL;
7274                 isc_task_attach(task, &clone);
7275                 event->ev_sender = clone;
7276                 ISC_LIST_APPEND(res->whenshutdown, event, ev_link);
7277         }
7278
7279         UNLOCK(&res->lock);
7280 }
7281
7282 void
7283 dns_resolver_shutdown(dns_resolver_t *res) {
7284         unsigned int i;
7285         fetchctx_t *fctx;
7286         isc_socket_t *sock;
7287         isc_result_t result;
7288
7289         REQUIRE(VALID_RESOLVER(res));
7290
7291         RTRACE("shutdown");
7292
7293         LOCK(&res->lock);
7294
7295         if (!res->exiting) {
7296                 RTRACE("exiting");
7297                 res->exiting = ISC_TRUE;
7298
7299                 for (i = 0; i < res->nbuckets; i++) {
7300                         LOCK(&res->buckets[i].lock);
7301                         for (fctx = ISC_LIST_HEAD(res->buckets[i].fctxs);
7302                              fctx != NULL;
7303                              fctx = ISC_LIST_NEXT(fctx, link))
7304                                 fctx_shutdown(fctx);
7305                         if (res->dispatchv4 != NULL && !res->exclusivev4) {
7306                                 sock = dns_dispatch_getsocket(res->dispatchv4);
7307                                 isc_socket_cancel(sock, res->buckets[i].task,
7308                                                   ISC_SOCKCANCEL_ALL);
7309                         }
7310                         if (res->dispatchv6 != NULL && !res->exclusivev6) {
7311                                 sock = dns_dispatch_getsocket(res->dispatchv6);
7312                                 isc_socket_cancel(sock, res->buckets[i].task,
7313                                                   ISC_SOCKCANCEL_ALL);
7314                         }
7315                         res->buckets[i].exiting = ISC_TRUE;
7316                         if (ISC_LIST_EMPTY(res->buckets[i].fctxs)) {
7317                                 INSIST(res->activebuckets > 0);
7318                                 res->activebuckets--;
7319                         }
7320                         UNLOCK(&res->buckets[i].lock);
7321                 }
7322                 if (res->activebuckets == 0)
7323                         send_shutdown_events(res);
7324                 result = isc_timer_reset(res->spillattimer,
7325                                          isc_timertype_inactive, NULL,
7326                                          NULL, ISC_TRUE);
7327                 RUNTIME_CHECK(result == ISC_R_SUCCESS);
7328         }
7329
7330         UNLOCK(&res->lock);
7331 }
7332
7333 void
7334 dns_resolver_detach(dns_resolver_t **resp) {
7335         dns_resolver_t *res;
7336         isc_boolean_t need_destroy = ISC_FALSE;
7337
7338         REQUIRE(resp != NULL);
7339         res = *resp;
7340         REQUIRE(VALID_RESOLVER(res));
7341
7342         RTRACE("detach");
7343
7344         LOCK(&res->lock);
7345
7346         INSIST(res->references > 0);
7347         res->references--;
7348         if (res->references == 0) {
7349                 INSIST(res->exiting && res->activebuckets == 0);
7350                 need_destroy = ISC_TRUE;
7351         }
7352
7353         UNLOCK(&res->lock);
7354
7355         if (need_destroy)
7356                 destroy(res);
7357
7358         *resp = NULL;
7359 }
7360
7361 static inline isc_boolean_t
7362 fctx_match(fetchctx_t *fctx, dns_name_t *name, dns_rdatatype_t type,
7363            unsigned int options)
7364 {
7365         if (fctx->type != type || fctx->options != options)
7366                 return (ISC_FALSE);
7367         return (dns_name_equal(&fctx->name, name));
7368 }
7369
7370 static inline void
7371 log_fetch(dns_name_t *name, dns_rdatatype_t type) {
7372         char namebuf[DNS_NAME_FORMATSIZE];
7373         char typebuf[DNS_RDATATYPE_FORMATSIZE];
7374         int level = ISC_LOG_DEBUG(1);
7375
7376         if (! isc_log_wouldlog(dns_lctx, level))
7377                 return;
7378
7379         dns_name_format(name, namebuf, sizeof(namebuf));
7380         dns_rdatatype_format(type, typebuf, sizeof(typebuf));
7381
7382         isc_log_write(dns_lctx, DNS_LOGCATEGORY_RESOLVER,
7383                       DNS_LOGMODULE_RESOLVER, level,
7384                       "createfetch: %s %s", namebuf, typebuf);
7385 }
7386
7387 isc_result_t
7388 dns_resolver_createfetch(dns_resolver_t *res, dns_name_t *name,
7389                          dns_rdatatype_t type,
7390                          dns_name_t *domain, dns_rdataset_t *nameservers,
7391                          dns_forwarders_t *forwarders,
7392                          unsigned int options, isc_task_t *task,
7393                          isc_taskaction_t action, void *arg,
7394                          dns_rdataset_t *rdataset,
7395                          dns_rdataset_t *sigrdataset,
7396                          dns_fetch_t **fetchp)
7397 {
7398         return (dns_resolver_createfetch2(res, name, type, domain,
7399                                           nameservers, forwarders, NULL, 0,
7400                                           options, task, action, arg,
7401                                           rdataset, sigrdataset, fetchp));
7402 }
7403
7404 isc_result_t
7405 dns_resolver_createfetch2(dns_resolver_t *res, dns_name_t *name,
7406                           dns_rdatatype_t type,
7407                           dns_name_t *domain, dns_rdataset_t *nameservers,
7408                           dns_forwarders_t *forwarders,
7409                           isc_sockaddr_t *client, dns_messageid_t id,
7410                           unsigned int options, isc_task_t *task,
7411                           isc_taskaction_t action, void *arg,
7412                           dns_rdataset_t *rdataset,
7413                           dns_rdataset_t *sigrdataset,
7414                           dns_fetch_t **fetchp)
7415 {
7416         dns_fetch_t *fetch;
7417         fetchctx_t *fctx = NULL;
7418         isc_result_t result = ISC_R_SUCCESS;
7419         unsigned int bucketnum;
7420         isc_boolean_t new_fctx = ISC_FALSE;
7421         isc_event_t *event;
7422         unsigned int count = 0;
7423         unsigned int spillat;
7424         unsigned int spillatmin;
7425
7426         UNUSED(forwarders);
7427
7428         REQUIRE(VALID_RESOLVER(res));
7429         REQUIRE(res->frozen);
7430         /* XXXRTH  Check for meta type */
7431         if (domain != NULL) {
7432                 REQUIRE(DNS_RDATASET_VALID(nameservers));
7433                 REQUIRE(nameservers->type == dns_rdatatype_ns);
7434         } else
7435                 REQUIRE(nameservers == NULL);
7436         REQUIRE(forwarders == NULL);
7437         REQUIRE(!dns_rdataset_isassociated(rdataset));
7438         REQUIRE(sigrdataset == NULL ||
7439                 !dns_rdataset_isassociated(sigrdataset));
7440         REQUIRE(fetchp != NULL && *fetchp == NULL);
7441
7442         log_fetch(name, type);
7443
7444         /*
7445          * XXXRTH  use a mempool?
7446          */
7447         fetch = isc_mem_get(res->mctx, sizeof(*fetch));
7448         if (fetch == NULL)
7449                 return (ISC_R_NOMEMORY);
7450
7451         bucketnum = dns_name_fullhash(name, ISC_FALSE) % res->nbuckets;
7452
7453         LOCK(&res->lock);
7454         spillat = res->spillat;
7455         spillatmin = res->spillatmin;
7456         UNLOCK(&res->lock);
7457         LOCK(&res->buckets[bucketnum].lock);
7458
7459         if (res->buckets[bucketnum].exiting) {
7460                 result = ISC_R_SHUTTINGDOWN;
7461                 goto unlock;
7462         }
7463
7464         if ((options & DNS_FETCHOPT_UNSHARED) == 0) {
7465                 for (fctx = ISC_LIST_HEAD(res->buckets[bucketnum].fctxs);
7466                      fctx != NULL;
7467                      fctx = ISC_LIST_NEXT(fctx, link)) {
7468                         if (fctx_match(fctx, name, type, options))
7469                                 break;
7470                 }
7471         }
7472
7473         /*
7474          * Is this a duplicate?
7475          */
7476         if (fctx != NULL && client != NULL) {
7477                 dns_fetchevent_t *fevent;
7478                 for (fevent = ISC_LIST_HEAD(fctx->events);
7479                      fevent != NULL;
7480                      fevent = ISC_LIST_NEXT(fevent, ev_link)) {
7481                         if (fevent->client != NULL && fevent->id == id &&
7482                             isc_sockaddr_equal(fevent->client, client)) {
7483                                 result = DNS_R_DUPLICATE;
7484                                 goto unlock;
7485                         }
7486                         count++;
7487                 }
7488         }
7489         if (count >= spillatmin && spillatmin != 0) {
7490                 INSIST(fctx != NULL);
7491                 if (count >= spillat)
7492                         fctx->spilled = ISC_TRUE;
7493                 if (fctx->spilled) {
7494                         result = DNS_R_DROP;
7495                         goto unlock;
7496                 }
7497         }
7498
7499         /*
7500          * If we didn't have a fetch, would attach to a done fetch, this
7501          * fetch has already cloned its results, or if the fetch has gone
7502          * "idle" (no one was interested in it), we need to start a new
7503          * fetch instead of joining with the existing one.
7504          */
7505         if (fctx == NULL ||
7506             fctx->state == fetchstate_done ||
7507             fctx->cloned ||
7508             ISC_LIST_EMPTY(fctx->events)) {
7509                 fctx = NULL;
7510                 result = fctx_create(res, name, type, domain, nameservers,
7511                                      options, bucketnum, &fctx);
7512                 if (result != ISC_R_SUCCESS)
7513                         goto unlock;
7514                 new_fctx = ISC_TRUE;
7515         }
7516
7517         result = fctx_join(fctx, task, client, id, action, arg,
7518                            rdataset, sigrdataset, fetch);
7519         if (new_fctx) {
7520                 if (result == ISC_R_SUCCESS) {
7521                         /*
7522                          * Launch this fctx.
7523                          */
7524                         event = &fctx->control_event;
7525                         ISC_EVENT_INIT(event, sizeof(*event), 0, NULL,
7526                                        DNS_EVENT_FETCHCONTROL,
7527                                        fctx_start, fctx, NULL,
7528                                        NULL, NULL);
7529                         isc_task_send(res->buckets[bucketnum].task, &event);
7530                 } else {
7531                         /*
7532                          * We don't care about the result of fctx_destroy()
7533                          * since we know we're not exiting.
7534                          */
7535                         (void)fctx_destroy(fctx);
7536                 }
7537         }
7538
7539  unlock:
7540         UNLOCK(&res->buckets[bucketnum].lock);
7541
7542         if (result == ISC_R_SUCCESS) {
7543                 FTRACE("created");
7544                 *fetchp = fetch;
7545         } else
7546                 isc_mem_put(res->mctx, fetch, sizeof(*fetch));
7547
7548         return (result);
7549 }
7550
7551 void
7552 dns_resolver_cancelfetch(dns_fetch_t *fetch) {
7553         fetchctx_t *fctx;
7554         dns_resolver_t *res;
7555         dns_fetchevent_t *event, *next_event;
7556         isc_task_t *etask;
7557
7558         REQUIRE(DNS_FETCH_VALID(fetch));
7559         fctx = fetch->private;
7560         REQUIRE(VALID_FCTX(fctx));
7561         res = fctx->res;
7562
7563         FTRACE("cancelfetch");
7564
7565         LOCK(&res->buckets[fctx->bucketnum].lock);
7566
7567         /*
7568          * Find the completion event for this fetch (as opposed
7569          * to those for other fetches that have joined the same
7570          * fctx) and send it with result = ISC_R_CANCELED.
7571          */
7572         event = NULL;
7573         if (fctx->state != fetchstate_done) {
7574                 for (event = ISC_LIST_HEAD(fctx->events);
7575                      event != NULL;
7576                      event = next_event) {
7577                         next_event = ISC_LIST_NEXT(event, ev_link);
7578                         if (event->fetch == fetch) {
7579                                 ISC_LIST_UNLINK(fctx->events, event, ev_link);
7580                                 break;
7581                         }
7582                 }
7583         }
7584         if (event != NULL) {
7585                 etask = event->ev_sender;
7586                 event->ev_sender = fctx;
7587                 event->result = ISC_R_CANCELED;
7588                 isc_task_sendanddetach(&etask, ISC_EVENT_PTR(&event));
7589         }
7590         /*
7591          * The fctx continues running even if no fetches remain;
7592          * the answer is still cached.
7593          */
7594
7595         UNLOCK(&res->buckets[fctx->bucketnum].lock);
7596 }
7597
7598 void
7599 dns_resolver_destroyfetch(dns_fetch_t **fetchp) {
7600         dns_fetch_t *fetch;
7601         dns_resolver_t *res;
7602         dns_fetchevent_t *event, *next_event;
7603         fetchctx_t *fctx;
7604         unsigned int bucketnum;
7605         isc_boolean_t bucket_empty = ISC_FALSE;
7606
7607         REQUIRE(fetchp != NULL);
7608         fetch = *fetchp;
7609         REQUIRE(DNS_FETCH_VALID(fetch));
7610         fctx = fetch->private;
7611         REQUIRE(VALID_FCTX(fctx));
7612         res = fctx->res;
7613
7614         FTRACE("destroyfetch");
7615
7616         bucketnum = fctx->bucketnum;
7617         LOCK(&res->buckets[bucketnum].lock);
7618
7619         /*
7620          * Sanity check: the caller should have gotten its event before
7621          * trying to destroy the fetch.
7622          */
7623         event = NULL;
7624         if (fctx->state != fetchstate_done) {
7625                 for (event = ISC_LIST_HEAD(fctx->events);
7626                      event != NULL;
7627                      event = next_event) {
7628                         next_event = ISC_LIST_NEXT(event, ev_link);
7629                         RUNTIME_CHECK(event->fetch != fetch);
7630                 }
7631         }
7632
7633         INSIST(fctx->references > 0);
7634         fctx->references--;
7635         if (fctx->references == 0) {
7636                 /*
7637                  * No one cares about the result of this fetch anymore.
7638                  */
7639                 if (fctx->pending == 0 && fctx->nqueries == 0 &&
7640                     ISC_LIST_EMPTY(fctx->validators) &&
7641                     SHUTTINGDOWN(fctx)) {
7642                         /*
7643                          * This fctx is already shutdown; we were just
7644                          * waiting for the last reference to go away.
7645                          */
7646                         bucket_empty = fctx_destroy(fctx);
7647                 } else {
7648                         /*
7649                          * Initiate shutdown.
7650                          */
7651                         fctx_shutdown(fctx);
7652                 }
7653         }
7654
7655         UNLOCK(&res->buckets[bucketnum].lock);
7656
7657         isc_mem_put(res->mctx, fetch, sizeof(*fetch));
7658         *fetchp = NULL;
7659
7660         if (bucket_empty)
7661                 empty_bucket(res);
7662 }
7663
7664 void
7665 dns_resolver_logfetch(dns_fetch_t *fetch, isc_log_t *lctx,
7666                       isc_logcategory_t *category, isc_logmodule_t *module,
7667                       int level, isc_boolean_t duplicateok)
7668 {
7669         fetchctx_t *fctx;
7670         dns_resolver_t *res;
7671         char domainbuf[DNS_NAME_FORMATSIZE];
7672
7673         REQUIRE(DNS_FETCH_VALID(fetch));
7674         fctx = fetch->private;
7675         REQUIRE(VALID_FCTX(fctx));
7676         res = fctx->res;
7677
7678         LOCK(&res->buckets[fctx->bucketnum].lock);
7679
7680         INSIST(fctx->exitline >= 0);
7681         if (!fctx->logged || duplicateok) {
7682                 dns_name_format(&fctx->domain, domainbuf, sizeof(domainbuf));
7683                 isc_log_write(lctx, category, module, level,
7684                               "fetch completed at %s:%d for %s in "
7685                               "%" ISC_PRINT_QUADFORMAT "u."
7686                               "%06" ISC_PRINT_QUADFORMAT "u: %s/%s "
7687                               "[domain:%s,referral:%u,restart:%u,qrysent:%u,"
7688                               "timeout:%u,lame:%u,neterr:%u,badresp:%u,"
7689                               "adberr:%u,findfail:%u,valfail:%u]",
7690                               __FILE__, fctx->exitline, fctx->info,
7691                               fctx->duration / 1000000,
7692                               fctx->duration % 1000000,
7693                               isc_result_totext(fctx->result),
7694                               isc_result_totext(fctx->vresult), domainbuf,
7695                               fctx->referrals, fctx->restarts,
7696                               fctx->querysent, fctx->timeouts, fctx->lamecount,
7697                               fctx->neterr, fctx->badresp, fctx->adberr,
7698                               fctx->findfail, fctx->valfail);
7699                 fctx->logged = ISC_TRUE;
7700         }
7701
7702         UNLOCK(&res->buckets[fctx->bucketnum].lock);
7703 }
7704
7705 dns_dispatchmgr_t *
7706 dns_resolver_dispatchmgr(dns_resolver_t *resolver) {
7707         REQUIRE(VALID_RESOLVER(resolver));
7708         return (resolver->dispatchmgr);
7709 }
7710
7711 dns_dispatch_t *
7712 dns_resolver_dispatchv4(dns_resolver_t *resolver) {
7713         REQUIRE(VALID_RESOLVER(resolver));
7714         return (resolver->dispatchv4);
7715 }
7716
7717 dns_dispatch_t *
7718 dns_resolver_dispatchv6(dns_resolver_t *resolver) {
7719         REQUIRE(VALID_RESOLVER(resolver));
7720         return (resolver->dispatchv6);
7721 }
7722
7723 isc_socketmgr_t *
7724 dns_resolver_socketmgr(dns_resolver_t *resolver) {
7725         REQUIRE(VALID_RESOLVER(resolver));
7726         return (resolver->socketmgr);
7727 }
7728
7729 isc_taskmgr_t *
7730 dns_resolver_taskmgr(dns_resolver_t *resolver) {
7731         REQUIRE(VALID_RESOLVER(resolver));
7732         return (resolver->taskmgr);
7733 }
7734
7735 isc_uint32_t
7736 dns_resolver_getlamettl(dns_resolver_t *resolver) {
7737         REQUIRE(VALID_RESOLVER(resolver));
7738         return (resolver->lame_ttl);
7739 }
7740
7741 void
7742 dns_resolver_setlamettl(dns_resolver_t *resolver, isc_uint32_t lame_ttl) {
7743         REQUIRE(VALID_RESOLVER(resolver));
7744         resolver->lame_ttl = lame_ttl;
7745 }
7746
7747 unsigned int
7748 dns_resolver_nrunning(dns_resolver_t *resolver) {
7749         unsigned int n;
7750         LOCK(&resolver->nlock);
7751         n = resolver->nfctx;
7752         UNLOCK(&resolver->nlock);
7753         return (n);
7754 }
7755
7756 isc_result_t
7757 dns_resolver_addalternate(dns_resolver_t *resolver, isc_sockaddr_t *alt,
7758                           dns_name_t *name, in_port_t port) {
7759         alternate_t *a;
7760         isc_result_t result;
7761
7762         REQUIRE(VALID_RESOLVER(resolver));
7763         REQUIRE(!resolver->frozen);
7764         REQUIRE((alt == NULL) ^ (name == NULL));
7765
7766         a = isc_mem_get(resolver->mctx, sizeof(*a));
7767         if (a == NULL)
7768                 return (ISC_R_NOMEMORY);
7769         if (alt != NULL) {
7770                 a->isaddress = ISC_TRUE;
7771                 a->_u.addr = *alt;
7772         } else {
7773                 a->isaddress = ISC_FALSE;
7774                 a->_u._n.port = port;
7775                 dns_name_init(&a->_u._n.name, NULL);
7776                 result = dns_name_dup(name, resolver->mctx, &a->_u._n.name);
7777                 if (result != ISC_R_SUCCESS) {
7778                         isc_mem_put(resolver->mctx, a, sizeof(*a));
7779                         return (result);
7780                 }
7781         }
7782         ISC_LINK_INIT(a, link);
7783         ISC_LIST_APPEND(resolver->alternates, a, link);
7784
7785         return (ISC_R_SUCCESS);
7786 }
7787
7788 void
7789 dns_resolver_setudpsize(dns_resolver_t *resolver, isc_uint16_t udpsize) {
7790         REQUIRE(VALID_RESOLVER(resolver));
7791         resolver->udpsize = udpsize;
7792 }
7793
7794 isc_uint16_t
7795 dns_resolver_getudpsize(dns_resolver_t *resolver) {
7796         REQUIRE(VALID_RESOLVER(resolver));
7797         return (resolver->udpsize);
7798 }
7799
7800 void
7801 dns_resolver_flushbadcache(dns_resolver_t *resolver, dns_name_t *name) {
7802         unsigned int i;
7803         dns_badcache_t *bad, *prev, *next;
7804
7805         REQUIRE(VALID_RESOLVER(resolver));
7806
7807         LOCK(&resolver->lock);
7808         if (resolver->badcache == NULL)
7809                 goto unlock;
7810
7811         if (name != NULL) {
7812                 isc_time_t now;
7813                 isc_result_t result;
7814                 result = isc_time_now(&now);
7815                 if (result != ISC_R_SUCCESS)
7816                         isc_time_settoepoch(&now);
7817                 i = dns_name_hash(name, ISC_FALSE) % resolver->badhash;
7818                 prev = NULL;
7819                 for (bad = resolver->badcache[i]; bad != NULL; bad = next) {
7820                         int n;
7821                         next = bad->next;
7822                         n = isc_time_compare(&bad->expire, &now);
7823                         if (n < 0 || dns_name_equal(name, &bad->name)) {
7824                                 if (prev == NULL)
7825                                         resolver->badcache[i] = bad->next;
7826                                 else
7827                                         prev->next = bad->next;
7828                                 isc_mem_put(resolver->mctx, bad, sizeof(*bad) +
7829                                             bad->name.length);
7830                                 resolver->badcount--;
7831                         } else
7832                                 prev = bad;
7833                 }
7834         } else
7835                 destroy_badcache(resolver);
7836
7837  unlock:
7838         UNLOCK(&resolver->lock);
7839
7840 }
7841
7842 static void
7843 resizehash(dns_resolver_t *resolver, isc_time_t *now, isc_boolean_t grow) {
7844         unsigned int newsize;
7845         dns_badcache_t **new, *bad, *next;
7846         unsigned int i;
7847
7848         if (grow)
7849                 newsize = resolver->badhash * 2 + 1;
7850         else
7851                 newsize = (resolver->badhash - 1) / 2;
7852
7853         new = isc_mem_get(resolver->mctx,
7854                           sizeof(*resolver->badcache) * newsize);
7855         if (new == NULL)
7856                 return;
7857         memset(new, 0, sizeof(*resolver->badcache) * newsize);
7858         for (i = 0; i < resolver->badhash; i++) {
7859                 for (bad = resolver->badcache[i]; bad != NULL; bad = next) {
7860                         next = bad->next;
7861                         if (isc_time_compare(&bad->expire, now) < 0) {
7862                                 isc_mem_put(resolver->mctx, bad, sizeof(*bad) +
7863                                             bad->name.length);
7864                                 resolver->badcount--;
7865                         } else {
7866                                 bad->next = new[bad->hashval % newsize];
7867                                 new[bad->hashval % newsize] = bad;
7868                         }
7869                 }
7870         }
7871         isc_mem_put(resolver->mctx, resolver->badcache,
7872                     sizeof(*resolver->badcache) * resolver->badhash);
7873         resolver->badhash = newsize;
7874         resolver->badcache = new;
7875 }
7876
7877 void
7878 dns_resolver_addbadcache(dns_resolver_t *resolver, dns_name_t *name,
7879                          dns_rdatatype_t type, isc_time_t *expire)
7880 {
7881         isc_time_t now;
7882         isc_result_t result = ISC_R_SUCCESS;
7883         unsigned int i, hashval;
7884         dns_badcache_t *bad, *prev, *next;
7885
7886         REQUIRE(VALID_RESOLVER(resolver));
7887
7888         LOCK(&resolver->lock);
7889         if (resolver->badcache == NULL) {
7890                 resolver->badcache = isc_mem_get(resolver->mctx,
7891                                                  sizeof(*resolver->badcache) *
7892                                                  DNS_BADCACHE_SIZE);
7893                 if (resolver->badcache == NULL) {
7894                         result = ISC_R_NOMEMORY;
7895                         goto cleanup;
7896                 }
7897                 resolver->badhash = DNS_BADCACHE_SIZE;
7898                 memset(resolver->badcache, 0, sizeof(*resolver->badcache) *
7899                        resolver->badhash);
7900         }
7901
7902         result = isc_time_now(&now);
7903         if (result != ISC_R_SUCCESS)
7904                 isc_time_settoepoch(&now);
7905         hashval = dns_name_hash(name, ISC_FALSE);
7906         i = hashval % resolver->badhash;
7907         prev = NULL;
7908         for (bad = resolver->badcache[i]; bad != NULL; bad = next) {
7909                 next = bad->next;
7910                 if (bad->type == type && dns_name_equal(name, &bad->name))
7911                         break;
7912                 if (isc_time_compare(&bad->expire, &now) < 0) {
7913                         if (prev == NULL)
7914                                 resolver->badcache[i] = bad->next;
7915                         else
7916                                 prev->next = bad->next;
7917                         isc_mem_put(resolver->mctx, bad, sizeof(*bad) +
7918                                     bad->name.length);
7919                         resolver->badcount--;
7920                 } else
7921                         prev = bad;
7922         }
7923         if (bad == NULL) {
7924                 isc_buffer_t buffer;
7925                 bad = isc_mem_get(resolver->mctx, sizeof(*bad) + name->length);
7926                 if (bad == NULL) {
7927                         result = ISC_R_NOMEMORY;
7928                         goto cleanup;
7929                 }
7930                 bad->type = type;
7931                 bad->hashval = hashval;
7932                 isc_buffer_init(&buffer, bad + 1, name->length);
7933                 dns_name_init(&bad->name, NULL);
7934                 dns_name_copy(name, &bad->name, &buffer);
7935                 bad->next = resolver->badcache[i];
7936                 resolver->badcache[i] = bad;
7937                 resolver->badcount++;
7938                 if (resolver->badcount > resolver->badhash * 8)
7939                         resizehash(resolver, &now, ISC_TRUE);
7940                 if (resolver->badcount < resolver->badhash * 2 &&
7941                     resolver->badhash > DNS_BADCACHE_SIZE)
7942                         resizehash(resolver, &now, ISC_FALSE);
7943         }
7944         bad->expire = *expire;
7945  cleanup:
7946         UNLOCK(&resolver->lock);
7947 }
7948
7949 isc_boolean_t
7950 dns_resolver_getbadcache(dns_resolver_t *resolver, dns_name_t *name,
7951                          dns_rdatatype_t type, isc_time_t *now)
7952 {
7953         dns_badcache_t *bad, *prev, *next;
7954         isc_boolean_t answer = ISC_FALSE;
7955         unsigned int i;
7956
7957         REQUIRE(VALID_RESOLVER(resolver));
7958
7959         LOCK(&resolver->lock);
7960         if (resolver->badcache == NULL)
7961                 goto unlock;
7962
7963         i = dns_name_hash(name, ISC_FALSE) % resolver->badhash;
7964         prev = NULL;
7965         for (bad = resolver->badcache[i]; bad != NULL; bad = next) {
7966                 next = bad->next;
7967                 /*
7968                  * Search the hash list. Clean out expired records as we go.
7969                  */
7970                 if (isc_time_compare(&bad->expire, now) < 0) {
7971                         if (prev != NULL)
7972                                 prev->next = bad->next;
7973                         else
7974                                 resolver->badcache[i] = bad->next;
7975                         isc_mem_put(resolver->mctx, bad, sizeof(*bad) +
7976                                     bad->name.length);
7977                         resolver->badcount--;
7978                         continue;
7979                 }
7980                 if (bad->type == type && dns_name_equal(name, &bad->name)) {
7981                         answer = ISC_TRUE;
7982                         break;
7983                 }
7984                 prev = bad;
7985         }
7986
7987         /*
7988          * Slow sweep to clean out stale records.
7989          */
7990         i = resolver->badsweep++ % resolver->badhash;
7991         bad = resolver->badcache[i];
7992         if (bad != NULL && isc_time_compare(&bad->expire, now) < 0) {
7993                 resolver->badcache[i] = bad->next;
7994                 isc_mem_put(resolver->mctx, bad, sizeof(*bad) +
7995                             bad->name.length);
7996                 resolver->badcount--;
7997         }
7998
7999  unlock:
8000         UNLOCK(&resolver->lock);
8001         return (answer);
8002 }
8003
8004 void
8005 dns_resolver_printbadcache(dns_resolver_t *resolver, FILE *fp) {
8006         char namebuf[DNS_NAME_FORMATSIZE];
8007         char typebuf[DNS_RDATATYPE_FORMATSIZE];
8008         dns_badcache_t *bad, *next, *prev;
8009         isc_time_t now;
8010         unsigned int i;
8011         isc_uint64_t t;
8012
8013         LOCK(&resolver->lock);
8014         fprintf(fp, ";\n; Bad cache\n;\n");
8015
8016         if (resolver->badcache == NULL)
8017                 goto unlock;
8018
8019         TIME_NOW(&now);
8020         for (i = 0; i < resolver->badhash; i++) {
8021                 prev = NULL;
8022                 for (bad = resolver->badcache[i]; bad != NULL; bad = next) {
8023                         next = bad->next;
8024                         if (isc_time_compare(&bad->expire, &now) < 0) {
8025                                 if (prev != NULL)
8026                                         prev->next = bad->next;
8027                                 else
8028                                         resolver->badcache[i] = bad->next;
8029                                 isc_mem_put(resolver->mctx, bad, sizeof(*bad) +
8030                                             bad->name.length);
8031                                 resolver->badcount--;
8032                                 continue;
8033                         }
8034                         prev = bad;
8035                         dns_name_format(&bad->name, namebuf, sizeof(namebuf));
8036                         dns_rdatatype_format(bad->type, typebuf,
8037                                              sizeof(typebuf));
8038                         t = isc_time_microdiff(&bad->expire, &now);
8039                         t /= 1000;
8040                         fprintf(fp, "; %s/%s [ttl "
8041                                 "%" ISC_PLATFORM_QUADFORMAT "u]\n",
8042                                 namebuf, typebuf, t);
8043                 }
8044         }
8045
8046  unlock:
8047         UNLOCK(&resolver->lock);
8048 }
8049
8050 static void
8051 free_algorithm(void *node, void *arg) {
8052         unsigned char *algorithms = node;
8053         isc_mem_t *mctx = arg;
8054
8055         isc_mem_put(mctx, algorithms, *algorithms);
8056 }
8057
8058 void
8059 dns_resolver_reset_algorithms(dns_resolver_t *resolver) {
8060
8061         REQUIRE(VALID_RESOLVER(resolver));
8062
8063 #if USE_ALGLOCK
8064         RWLOCK(&resolver->alglock, isc_rwlocktype_write);
8065 #endif
8066         if (resolver->algorithms != NULL)
8067                 dns_rbt_destroy(&resolver->algorithms);
8068 #if USE_ALGLOCK
8069         RWUNLOCK(&resolver->alglock, isc_rwlocktype_write);
8070 #endif
8071 }
8072
8073 isc_result_t
8074 dns_resolver_disable_algorithm(dns_resolver_t *resolver, dns_name_t *name,
8075                                unsigned int alg)
8076 {
8077         unsigned int len, mask;
8078         unsigned char *new;
8079         unsigned char *algorithms;
8080         isc_result_t result;
8081         dns_rbtnode_t *node = NULL;
8082
8083         REQUIRE(VALID_RESOLVER(resolver));
8084         if (alg > 255)
8085                 return (ISC_R_RANGE);
8086
8087 #if USE_ALGLOCK
8088         RWLOCK(&resolver->alglock, isc_rwlocktype_write);
8089 #endif
8090         if (resolver->algorithms == NULL) {
8091                 result = dns_rbt_create(resolver->mctx, free_algorithm,
8092                                         resolver->mctx, &resolver->algorithms);
8093                 if (result != ISC_R_SUCCESS)
8094                         goto cleanup;
8095         }
8096
8097         len = alg/8 + 2;
8098         mask = 1 << (alg%8);
8099
8100         result = dns_rbt_addnode(resolver->algorithms, name, &node);
8101
8102         if (result == ISC_R_SUCCESS || result == ISC_R_EXISTS) {
8103                 algorithms = node->data;
8104                 if (algorithms == NULL || len > *algorithms) {
8105                         new = isc_mem_get(resolver->mctx, len);
8106                         if (new == NULL) {
8107                                 result = ISC_R_NOMEMORY;
8108                                 goto cleanup;
8109                         }
8110                         memset(new, 0, len);
8111                         if (algorithms != NULL)
8112                                 memcpy(new, algorithms, *algorithms);
8113                         new[len-1] |= mask;
8114                         *new = len;
8115                         node->data = new;
8116                         if (algorithms != NULL)
8117                                 isc_mem_put(resolver->mctx, algorithms,
8118                                             *algorithms);
8119                 } else
8120                         algorithms[len-1] |= mask;
8121         }
8122         result = ISC_R_SUCCESS;
8123  cleanup:
8124 #if USE_ALGLOCK
8125         RWUNLOCK(&resolver->alglock, isc_rwlocktype_write);
8126 #endif
8127         return (result);
8128 }
8129
8130 isc_boolean_t
8131 dns_resolver_algorithm_supported(dns_resolver_t *resolver, dns_name_t *name,
8132                                  unsigned int alg)
8133 {
8134         unsigned int len, mask;
8135         unsigned char *algorithms;
8136         void *data = NULL;
8137         isc_result_t result;
8138         isc_boolean_t found = ISC_FALSE;
8139
8140         REQUIRE(VALID_RESOLVER(resolver));
8141
8142 #if USE_ALGLOCK
8143         RWLOCK(&resolver->alglock, isc_rwlocktype_read);
8144 #endif
8145         if (resolver->algorithms == NULL)
8146                 goto unlock;
8147         result = dns_rbt_findname(resolver->algorithms, name, 0, NULL, &data);
8148         if (result == ISC_R_SUCCESS || result == DNS_R_PARTIALMATCH) {
8149                 len = alg/8 + 2;
8150                 mask = 1 << (alg%8);
8151                 algorithms = data;
8152                 if (len <= *algorithms && (algorithms[len-1] & mask) != 0)
8153                         found = ISC_TRUE;
8154         }
8155  unlock:
8156 #if USE_ALGLOCK
8157         RWUNLOCK(&resolver->alglock, isc_rwlocktype_read);
8158 #endif
8159         if (found)
8160                 return (ISC_FALSE);
8161         return (dst_algorithm_supported(alg));
8162 }
8163
8164 isc_boolean_t
8165 dns_resolver_digest_supported(dns_resolver_t *resolver, unsigned int digest) {
8166
8167         UNUSED(resolver);
8168         return (dns_ds_digest_supported(digest));
8169 }
8170
8171 void
8172 dns_resolver_resetmustbesecure(dns_resolver_t *resolver) {
8173
8174         REQUIRE(VALID_RESOLVER(resolver));
8175
8176 #if USE_MBSLOCK
8177         RWLOCK(&resolver->mbslock, isc_rwlocktype_write);
8178 #endif
8179         if (resolver->mustbesecure != NULL)
8180                 dns_rbt_destroy(&resolver->mustbesecure);
8181 #if USE_MBSLOCK
8182         RWUNLOCK(&resolver->mbslock, isc_rwlocktype_write);
8183 #endif
8184 }
8185
8186 static isc_boolean_t yes = ISC_TRUE, no = ISC_FALSE;
8187
8188 isc_result_t
8189 dns_resolver_setmustbesecure(dns_resolver_t *resolver, dns_name_t *name,
8190                              isc_boolean_t value)
8191 {
8192         isc_result_t result;
8193
8194         REQUIRE(VALID_RESOLVER(resolver));
8195
8196 #if USE_MBSLOCK
8197         RWLOCK(&resolver->mbslock, isc_rwlocktype_write);
8198 #endif
8199         if (resolver->mustbesecure == NULL) {
8200                 result = dns_rbt_create(resolver->mctx, NULL, NULL,
8201                                         &resolver->mustbesecure);
8202                 if (result != ISC_R_SUCCESS)
8203                         goto cleanup;
8204         }
8205         result = dns_rbt_addname(resolver->mustbesecure, name,
8206                                  value ? &yes : &no);
8207  cleanup:
8208 #if USE_MBSLOCK
8209         RWUNLOCK(&resolver->mbslock, isc_rwlocktype_write);
8210 #endif
8211         return (result);
8212 }
8213
8214 isc_boolean_t
8215 dns_resolver_getmustbesecure(dns_resolver_t *resolver, dns_name_t *name) {
8216         void *data = NULL;
8217         isc_boolean_t value = ISC_FALSE;
8218         isc_result_t result;
8219
8220         REQUIRE(VALID_RESOLVER(resolver));
8221
8222 #if USE_MBSLOCK
8223         RWLOCK(&resolver->mbslock, isc_rwlocktype_read);
8224 #endif
8225         if (resolver->mustbesecure == NULL)
8226                 goto unlock;
8227         result = dns_rbt_findname(resolver->mustbesecure, name, 0, NULL, &data);
8228         if (result == ISC_R_SUCCESS || result == DNS_R_PARTIALMATCH)
8229                 value = *(isc_boolean_t*)data;
8230  unlock:
8231 #if USE_MBSLOCK
8232         RWUNLOCK(&resolver->mbslock, isc_rwlocktype_read);
8233 #endif
8234         return (value);
8235 }
8236
8237 void
8238 dns_resolver_getclientsperquery(dns_resolver_t *resolver, isc_uint32_t *cur,
8239                                 isc_uint32_t *min, isc_uint32_t *max)
8240 {
8241         REQUIRE(VALID_RESOLVER(resolver));
8242
8243         LOCK(&resolver->lock);
8244         if (cur != NULL)
8245                 *cur = resolver->spillat;
8246         if (min != NULL)
8247                 *min = resolver->spillatmin;
8248         if (max != NULL)
8249                 *max = resolver->spillatmax;
8250         UNLOCK(&resolver->lock);
8251 }
8252
8253 void
8254 dns_resolver_setclientsperquery(dns_resolver_t *resolver, isc_uint32_t min,
8255                                 isc_uint32_t max)
8256 {
8257         REQUIRE(VALID_RESOLVER(resolver));
8258
8259         LOCK(&resolver->lock);
8260         resolver->spillatmin = resolver->spillat = min;
8261         resolver->spillatmax = max;
8262         UNLOCK(&resolver->lock);
8263 }
8264
8265 isc_boolean_t
8266 dns_resolver_getzeronosoattl(dns_resolver_t *resolver) {
8267         REQUIRE(VALID_RESOLVER(resolver));
8268
8269         return (resolver->zero_no_soa_ttl);
8270 }
8271
8272 void
8273 dns_resolver_setzeronosoattl(dns_resolver_t *resolver, isc_boolean_t state) {
8274         REQUIRE(VALID_RESOLVER(resolver));
8275
8276         resolver->zero_no_soa_ttl = state;
8277 }
8278
8279 unsigned int
8280 dns_resolver_getoptions(dns_resolver_t *resolver) {
8281         REQUIRE(VALID_RESOLVER(resolver));
8282
8283         return (resolver->options);
8284 }