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