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