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