]> CyberLeo.Net >> Repos - FreeBSD/releng/8.2.git/blob - contrib/bind9/bin/named/query.c
Copy stable/8 to releng/8.2 in preparation for FreeBSD-8.2 release.
[FreeBSD/releng/8.2.git] / contrib / bind9 / bin / named / query.c
1 /*
2  * Copyright (C) 2004-2010  Internet Systems Consortium, Inc. ("ISC")
3  * Copyright (C) 1999-2003  Internet Software Consortium.
4  *
5  * Permission to use, copy, modify, and/or distribute this software for any
6  * purpose with or without fee is hereby granted, provided that the above
7  * copyright notice and this permission notice appear in all copies.
8  *
9  * THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES WITH
10  * REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
11  * AND FITNESS.  IN NO EVENT SHALL ISC BE LIABLE FOR ANY SPECIAL, DIRECT,
12  * INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
13  * LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE
14  * OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
15  * PERFORMANCE OF THIS SOFTWARE.
16  */
17
18 /* $Id: query.c,v 1.313.20.16.10.3 2010/09/29 00:03:32 marka Exp $ */
19
20 /*! \file */
21
22 #include <config.h>
23
24 #include <string.h>
25
26 #include <isc/hex.h>
27 #include <isc/mem.h>
28 #include <isc/stats.h>
29 #include <isc/util.h>
30
31 #include <dns/adb.h>
32 #include <dns/byaddr.h>
33 #include <dns/db.h>
34 #ifdef DLZ
35 #include <dns/dlz.h>
36 #endif
37 #include <dns/dnssec.h>
38 #include <dns/events.h>
39 #include <dns/message.h>
40 #include <dns/ncache.h>
41 #include <dns/nsec3.h>
42 #include <dns/order.h>
43 #include <dns/rdata.h>
44 #include <dns/rdataclass.h>
45 #include <dns/rdatalist.h>
46 #include <dns/rdataset.h>
47 #include <dns/rdatasetiter.h>
48 #include <dns/rdatastruct.h>
49 #include <dns/rdatatype.h>
50 #include <dns/resolver.h>
51 #include <dns/result.h>
52 #include <dns/stats.h>
53 #include <dns/tkey.h>
54 #include <dns/view.h>
55 #include <dns/zone.h>
56 #include <dns/zt.h>
57
58 #include <named/client.h>
59 #include <named/globals.h>
60 #include <named/log.h>
61 #include <named/server.h>
62 #include <named/sortlist.h>
63 #include <named/xfrout.h>
64
65 /*% Partial answer? */
66 #define PARTIALANSWER(c)        (((c)->query.attributes & \
67                                   NS_QUERYATTR_PARTIALANSWER) != 0)
68 /*% Use Cache? */
69 #define USECACHE(c)             (((c)->query.attributes & \
70                                   NS_QUERYATTR_CACHEOK) != 0)
71 /*% Recursion OK? */
72 #define RECURSIONOK(c)          (((c)->query.attributes & \
73                                   NS_QUERYATTR_RECURSIONOK) != 0)
74 /*% Recursing? */
75 #define RECURSING(c)            (((c)->query.attributes & \
76                                   NS_QUERYATTR_RECURSING) != 0)
77 /*% Cache glue ok? */
78 #define CACHEGLUEOK(c)          (((c)->query.attributes & \
79                                   NS_QUERYATTR_CACHEGLUEOK) != 0)
80 /*% Want Recursion? */
81 #define WANTRECURSION(c)        (((c)->query.attributes & \
82                                   NS_QUERYATTR_WANTRECURSION) != 0)
83 /*% Want DNSSEC? */
84 #define WANTDNSSEC(c)           (((c)->attributes & \
85                                   NS_CLIENTATTR_WANTDNSSEC) != 0)
86 /*% No authority? */
87 #define NOAUTHORITY(c)          (((c)->query.attributes & \
88                                   NS_QUERYATTR_NOAUTHORITY) != 0)
89 /*% No additional? */
90 #define NOADDITIONAL(c)         (((c)->query.attributes & \
91                                   NS_QUERYATTR_NOADDITIONAL) != 0)
92 /*% Secure? */
93 #define SECURE(c)               (((c)->query.attributes & \
94                                   NS_QUERYATTR_SECURE) != 0)
95
96 /*% No QNAME Proof? */
97 #define NOQNAME(r)              (((r)->attributes & \
98                                   DNS_RDATASETATTR_NOQNAME) != 0)
99
100 #if 0
101 #define CTRACE(m)       isc_log_write(ns_g_lctx, \
102                                       NS_LOGCATEGORY_CLIENT, \
103                                       NS_LOGMODULE_QUERY, \
104                                       ISC_LOG_DEBUG(3), \
105                                       "client %p: %s", client, (m))
106 #define QTRACE(m)       isc_log_write(ns_g_lctx, \
107                                       NS_LOGCATEGORY_GENERAL, \
108                                       NS_LOGMODULE_QUERY, \
109                                       ISC_LOG_DEBUG(3), \
110                                       "query %p: %s", query, (m))
111 #else
112 #define CTRACE(m) ((void)m)
113 #define QTRACE(m) ((void)m)
114 #endif
115
116 #define DNS_GETDB_NOEXACT 0x01U
117 #define DNS_GETDB_NOLOG 0x02U
118 #define DNS_GETDB_PARTIAL 0x04U
119
120 #define PENDINGOK(x)    (((x) & DNS_DBFIND_PENDINGOK) != 0)
121
122 typedef struct client_additionalctx {
123         ns_client_t *client;
124         dns_rdataset_t *rdataset;
125 } client_additionalctx_t;
126
127 static isc_result_t
128 query_find(ns_client_t *client, dns_fetchevent_t *event, dns_rdatatype_t qtype);
129
130 static isc_boolean_t
131 validate(ns_client_t *client, dns_db_t *db, dns_name_t *name,
132          dns_rdataset_t *rdataset, dns_rdataset_t *sigrdataset);
133
134 static void
135 query_findclosestnsec3(dns_name_t *qname, dns_db_t *db,
136                        dns_dbversion_t *version, ns_client_t *client,
137                        dns_rdataset_t *rdataset, dns_rdataset_t *sigrdataset,
138                        dns_name_t *fname, isc_boolean_t exact,
139                        dns_name_t *found);
140
141 static inline void
142 log_queryerror(ns_client_t *client, isc_result_t result, int line, int level);
143
144 /*%
145  * Increment query statistics counters.
146  */
147 static inline void
148 inc_stats(ns_client_t *client, isc_statscounter_t counter) {
149         dns_zone_t *zone = client->query.authzone;
150
151         isc_stats_increment(ns_g_server->nsstats, counter);
152
153         if (zone != NULL) {
154                 isc_stats_t *zonestats = dns_zone_getrequeststats(zone);
155                 if (zonestats != NULL)
156                         isc_stats_increment(zonestats, counter);
157         }
158 }
159
160 static void
161 query_send(ns_client_t *client) {
162         isc_statscounter_t counter;
163         if ((client->message->flags & DNS_MESSAGEFLAG_AA) == 0)
164                 inc_stats(client, dns_nsstatscounter_nonauthans);
165         else
166                 inc_stats(client, dns_nsstatscounter_authans);
167         if (client->message->rcode == dns_rcode_noerror) {
168                 if (ISC_LIST_EMPTY(client->message->sections[DNS_SECTION_ANSWER])) {
169                         if (client->query.isreferral) {
170                                 counter = dns_nsstatscounter_referral;
171                         } else {
172                                 counter = dns_nsstatscounter_nxrrset;
173                         }
174                 } else {
175                         counter = dns_nsstatscounter_success;
176                 }
177         } else if (client->message->rcode == dns_rcode_nxdomain) {
178                 counter = dns_nsstatscounter_nxdomain;
179         } else {
180                 /* We end up here in case of YXDOMAIN, and maybe others */
181                 counter = dns_nsstatscounter_failure;
182         }
183         inc_stats(client, counter);
184         ns_client_send(client);
185 }
186
187 static void
188 query_error(ns_client_t *client, isc_result_t result, int line) {
189         int loglevel = ISC_LOG_DEBUG(3);
190
191         switch (result) {
192         case DNS_R_SERVFAIL:
193                 loglevel = ISC_LOG_DEBUG(1);
194                 inc_stats(client, dns_nsstatscounter_servfail);
195                 break;
196         case DNS_R_FORMERR:
197                 inc_stats(client, dns_nsstatscounter_formerr);
198                 break;
199         default:
200                 inc_stats(client, dns_nsstatscounter_failure);
201                 break;
202         }
203
204         log_queryerror(client, result, line, loglevel);
205
206         ns_client_error(client, result);
207 }
208
209 static void
210 query_next(ns_client_t *client, isc_result_t result) {
211         if (result == DNS_R_DUPLICATE)
212                 inc_stats(client, dns_nsstatscounter_duplicate);
213         else if (result == DNS_R_DROP)
214                 inc_stats(client, dns_nsstatscounter_dropped);
215         else
216                 inc_stats(client, dns_nsstatscounter_failure);
217         ns_client_next(client, result);
218 }
219
220 static inline void
221 query_freefreeversions(ns_client_t *client, isc_boolean_t everything) {
222         ns_dbversion_t *dbversion, *dbversion_next;
223         unsigned int i;
224
225         for (dbversion = ISC_LIST_HEAD(client->query.freeversions), i = 0;
226              dbversion != NULL;
227              dbversion = dbversion_next, i++)
228         {
229                 dbversion_next = ISC_LIST_NEXT(dbversion, link);
230                 /*
231                  * If we're not freeing everything, we keep the first three
232                  * dbversions structures around.
233                  */
234                 if (i > 3 || everything) {
235                         ISC_LIST_UNLINK(client->query.freeversions, dbversion,
236                                         link);
237                         isc_mem_put(client->mctx, dbversion,
238                                     sizeof(*dbversion));
239                 }
240         }
241 }
242
243 void
244 ns_query_cancel(ns_client_t *client) {
245         LOCK(&client->query.fetchlock);
246         if (client->query.fetch != NULL) {
247                 dns_resolver_cancelfetch(client->query.fetch);
248
249                 client->query.fetch = NULL;
250         }
251         UNLOCK(&client->query.fetchlock);
252 }
253
254 static inline void
255 query_reset(ns_client_t *client, isc_boolean_t everything) {
256         isc_buffer_t *dbuf, *dbuf_next;
257         ns_dbversion_t *dbversion, *dbversion_next;
258
259         /*%
260          * Reset the query state of a client to its default state.
261          */
262
263         /*
264          * Cancel the fetch if it's running.
265          */
266         ns_query_cancel(client);
267
268         /*
269          * Cleanup any active versions.
270          */
271         for (dbversion = ISC_LIST_HEAD(client->query.activeversions);
272              dbversion != NULL;
273              dbversion = dbversion_next) {
274                 dbversion_next = ISC_LIST_NEXT(dbversion, link);
275                 dns_db_closeversion(dbversion->db, &dbversion->version,
276                                     ISC_FALSE);
277                 dns_db_detach(&dbversion->db);
278                 ISC_LIST_INITANDAPPEND(client->query.freeversions,
279                                       dbversion, link);
280         }
281         ISC_LIST_INIT(client->query.activeversions);
282
283         if (client->query.authdb != NULL)
284                 dns_db_detach(&client->query.authdb);
285         if (client->query.authzone != NULL)
286                 dns_zone_detach(&client->query.authzone);
287
288         query_freefreeversions(client, everything);
289
290         for (dbuf = ISC_LIST_HEAD(client->query.namebufs);
291              dbuf != NULL;
292              dbuf = dbuf_next) {
293                 dbuf_next = ISC_LIST_NEXT(dbuf, link);
294                 if (dbuf_next != NULL || everything) {
295                         ISC_LIST_UNLINK(client->query.namebufs, dbuf, link);
296                         isc_buffer_free(&dbuf);
297                 }
298         }
299
300         if (client->query.restarts > 0) {
301                 /*
302                  * client->query.qname was dynamically allocated.
303                  */
304                 dns_message_puttempname(client->message,
305                                         &client->query.qname);
306         }
307         client->query.qname = NULL;
308         client->query.attributes = (NS_QUERYATTR_RECURSIONOK |
309                                     NS_QUERYATTR_CACHEOK |
310                                     NS_QUERYATTR_SECURE);
311         client->query.restarts = 0;
312         client->query.timerset = ISC_FALSE;
313         client->query.origqname = NULL;
314         client->query.qname = NULL;
315         client->query.dboptions = 0;
316         client->query.fetchoptions = 0;
317         client->query.gluedb = NULL;
318         client->query.authdbset = ISC_FALSE;
319         client->query.isreferral = ISC_FALSE;
320 }
321
322 static void
323 query_next_callback(ns_client_t *client) {
324         query_reset(client, ISC_FALSE);
325 }
326
327 void
328 ns_query_free(ns_client_t *client) {
329         query_reset(client, ISC_TRUE);
330 }
331
332 static inline isc_result_t
333 query_newnamebuf(ns_client_t *client) {
334         isc_buffer_t *dbuf;
335         isc_result_t result;
336
337         CTRACE("query_newnamebuf");
338         /*%
339          * Allocate a name buffer.
340          */
341
342         dbuf = NULL;
343         result = isc_buffer_allocate(client->mctx, &dbuf, 1024);
344         if (result != ISC_R_SUCCESS) {
345                 CTRACE("query_newnamebuf: isc_buffer_allocate failed: done");
346                 return (result);
347         }
348         ISC_LIST_APPEND(client->query.namebufs, dbuf, link);
349
350         CTRACE("query_newnamebuf: done");
351         return (ISC_R_SUCCESS);
352 }
353
354 static inline isc_buffer_t *
355 query_getnamebuf(ns_client_t *client) {
356         isc_buffer_t *dbuf;
357         isc_result_t result;
358         isc_region_t r;
359
360         CTRACE("query_getnamebuf");
361         /*%
362          * Return a name buffer with space for a maximal name, allocating
363          * a new one if necessary.
364          */
365
366         if (ISC_LIST_EMPTY(client->query.namebufs)) {
367                 result = query_newnamebuf(client);
368                 if (result != ISC_R_SUCCESS) {
369                     CTRACE("query_getnamebuf: query_newnamebuf failed: done");
370                         return (NULL);
371                 }
372         }
373
374         dbuf = ISC_LIST_TAIL(client->query.namebufs);
375         INSIST(dbuf != NULL);
376         isc_buffer_availableregion(dbuf, &r);
377         if (r.length < 255) {
378                 result = query_newnamebuf(client);
379                 if (result != ISC_R_SUCCESS) {
380                     CTRACE("query_getnamebuf: query_newnamebuf failed: done");
381                         return (NULL);
382
383                 }
384                 dbuf = ISC_LIST_TAIL(client->query.namebufs);
385                 isc_buffer_availableregion(dbuf, &r);
386                 INSIST(r.length >= 255);
387         }
388         CTRACE("query_getnamebuf: done");
389         return (dbuf);
390 }
391
392 static inline void
393 query_keepname(ns_client_t *client, dns_name_t *name, isc_buffer_t *dbuf) {
394         isc_region_t r;
395
396         CTRACE("query_keepname");
397         /*%
398          * 'name' is using space in 'dbuf', but 'dbuf' has not yet been
399          * adjusted to take account of that.  We do the adjustment.
400          */
401
402         REQUIRE((client->query.attributes & NS_QUERYATTR_NAMEBUFUSED) != 0);
403
404         dns_name_toregion(name, &r);
405         isc_buffer_add(dbuf, r.length);
406         dns_name_setbuffer(name, NULL);
407         client->query.attributes &= ~NS_QUERYATTR_NAMEBUFUSED;
408 }
409
410 static inline void
411 query_releasename(ns_client_t *client, dns_name_t **namep) {
412         dns_name_t *name = *namep;
413
414         /*%
415          * 'name' is no longer needed.  Return it to our pool of temporary
416          * names.  If it is using a name buffer, relinquish its exclusive
417          * rights on the buffer.
418          */
419
420         CTRACE("query_releasename");
421         if (dns_name_hasbuffer(name)) {
422                 INSIST((client->query.attributes & NS_QUERYATTR_NAMEBUFUSED)
423                        != 0);
424                 client->query.attributes &= ~NS_QUERYATTR_NAMEBUFUSED;
425         }
426         dns_message_puttempname(client->message, namep);
427         CTRACE("query_releasename: done");
428 }
429
430 static inline dns_name_t *
431 query_newname(ns_client_t *client, isc_buffer_t *dbuf,
432               isc_buffer_t *nbuf)
433 {
434         dns_name_t *name;
435         isc_region_t r;
436         isc_result_t result;
437
438         REQUIRE((client->query.attributes & NS_QUERYATTR_NAMEBUFUSED) == 0);
439
440         CTRACE("query_newname");
441         name = NULL;
442         result = dns_message_gettempname(client->message, &name);
443         if (result != ISC_R_SUCCESS) {
444                 CTRACE("query_newname: dns_message_gettempname failed: done");
445                 return (NULL);
446         }
447         isc_buffer_availableregion(dbuf, &r);
448         isc_buffer_init(nbuf, r.base, r.length);
449         dns_name_init(name, NULL);
450         dns_name_setbuffer(name, nbuf);
451         client->query.attributes |= NS_QUERYATTR_NAMEBUFUSED;
452
453         CTRACE("query_newname: done");
454         return (name);
455 }
456
457 static inline dns_rdataset_t *
458 query_newrdataset(ns_client_t *client) {
459         dns_rdataset_t *rdataset;
460         isc_result_t result;
461
462         CTRACE("query_newrdataset");
463         rdataset = NULL;
464         result = dns_message_gettemprdataset(client->message, &rdataset);
465         if (result != ISC_R_SUCCESS) {
466           CTRACE("query_newrdataset: "
467                  "dns_message_gettemprdataset failed: done");
468                 return (NULL);
469         }
470         dns_rdataset_init(rdataset);
471
472         CTRACE("query_newrdataset: done");
473         return (rdataset);
474 }
475
476 static inline void
477 query_putrdataset(ns_client_t *client, dns_rdataset_t **rdatasetp) {
478         dns_rdataset_t *rdataset = *rdatasetp;
479
480         CTRACE("query_putrdataset");
481         if (rdataset != NULL) {
482                 if (dns_rdataset_isassociated(rdataset))
483                         dns_rdataset_disassociate(rdataset);
484                 dns_message_puttemprdataset(client->message, rdatasetp);
485         }
486         CTRACE("query_putrdataset: done");
487 }
488
489
490 static inline isc_result_t
491 query_newdbversion(ns_client_t *client, unsigned int n) {
492         unsigned int i;
493         ns_dbversion_t *dbversion;
494
495         for (i = 0; i < n; i++) {
496                 dbversion = isc_mem_get(client->mctx, sizeof(*dbversion));
497                 if (dbversion != NULL) {
498                         dbversion->db = NULL;
499                         dbversion->version = NULL;
500                         ISC_LIST_INITANDAPPEND(client->query.freeversions,
501                                               dbversion, link);
502                 } else {
503                         /*
504                          * We only return ISC_R_NOMEMORY if we couldn't
505                          * allocate anything.
506                          */
507                         if (i == 0)
508                                 return (ISC_R_NOMEMORY);
509                         else
510                                 return (ISC_R_SUCCESS);
511                 }
512         }
513
514         return (ISC_R_SUCCESS);
515 }
516
517 static inline ns_dbversion_t *
518 query_getdbversion(ns_client_t *client) {
519         isc_result_t result;
520         ns_dbversion_t *dbversion;
521
522         if (ISC_LIST_EMPTY(client->query.freeversions)) {
523                 result = query_newdbversion(client, 1);
524                 if (result != ISC_R_SUCCESS)
525                         return (NULL);
526         }
527         dbversion = ISC_LIST_HEAD(client->query.freeversions);
528         INSIST(dbversion != NULL);
529         ISC_LIST_UNLINK(client->query.freeversions, dbversion, link);
530
531         return (dbversion);
532 }
533
534 isc_result_t
535 ns_query_init(ns_client_t *client) {
536         isc_result_t result;
537
538         ISC_LIST_INIT(client->query.namebufs);
539         ISC_LIST_INIT(client->query.activeversions);
540         ISC_LIST_INIT(client->query.freeversions);
541         client->query.restarts = 0;
542         client->query.timerset = ISC_FALSE;
543         client->query.qname = NULL;
544         result = isc_mutex_init(&client->query.fetchlock);
545         if (result != ISC_R_SUCCESS)
546                 return (result);
547         client->query.fetch = NULL;
548         client->query.authdb = NULL;
549         client->query.authzone = NULL;
550         client->query.authdbset = ISC_FALSE;
551         client->query.isreferral = ISC_FALSE;
552         query_reset(client, ISC_FALSE);
553         result = query_newdbversion(client, 3);
554         if (result != ISC_R_SUCCESS) {
555                 DESTROYLOCK(&client->query.fetchlock);
556                 return (result);
557         }
558         result = query_newnamebuf(client);
559         if (result != ISC_R_SUCCESS)
560                 query_freefreeversions(client, ISC_TRUE);
561
562         return (result);
563 }
564
565 static inline ns_dbversion_t *
566 query_findversion(ns_client_t *client, dns_db_t *db,
567                   isc_boolean_t *newzonep)
568 {
569         ns_dbversion_t *dbversion;
570
571         /*%
572          * We may already have done a query related to this
573          * database.  If so, we must be sure to make subsequent
574          * queries from the same version.
575          */
576         for (dbversion = ISC_LIST_HEAD(client->query.activeversions);
577              dbversion != NULL;
578              dbversion = ISC_LIST_NEXT(dbversion, link)) {
579                 if (dbversion->db == db)
580                         break;
581         }
582
583         if (dbversion == NULL) {
584                 /*
585                  * This is a new zone for this query.  Add it to
586                  * the active list.
587                  */
588                 dbversion = query_getdbversion(client);
589                 if (dbversion == NULL)
590                         return (NULL);
591                 dns_db_attach(db, &dbversion->db);
592                 dns_db_currentversion(db, &dbversion->version);
593                 dbversion->queryok = ISC_FALSE;
594                 ISC_LIST_APPEND(client->query.activeversions,
595                                 dbversion, link);
596                 *newzonep = ISC_TRUE;
597         } else
598                 *newzonep = ISC_FALSE;
599
600         return (dbversion);
601 }
602
603 static inline isc_result_t
604 query_validatezonedb(ns_client_t *client, dns_name_t *name,
605                      dns_rdatatype_t qtype, unsigned int options,
606                      dns_zone_t *zone, dns_db_t *db,
607                      dns_dbversion_t **versionp)
608 {
609         isc_result_t result;
610         isc_boolean_t check_acl, new_zone;
611         dns_acl_t *queryacl;
612         ns_dbversion_t *dbversion;
613
614         REQUIRE(zone != NULL);
615         REQUIRE(db != NULL);
616
617         /*
618          * This limits our searching to the zone where the first name
619          * (the query target) was looked for.  This prevents following
620          * CNAMES or DNAMES into other zones and prevents returning
621          * additional data from other zones.
622          */
623         if (!client->view->additionalfromauth &&
624             client->query.authdbset &&
625             db != client->query.authdb)
626                 goto refuse;
627
628         /*
629          * If the zone has an ACL, we'll check it, otherwise
630          * we use the view's "allow-query" ACL.  Each ACL is only checked
631          * once per query.
632          *
633          * Also, get the database version to use.
634          */
635
636         check_acl = ISC_TRUE;   /* Keep compiler happy. */
637         queryacl = NULL;
638
639         /*
640          * Get the current version of this database.
641          */
642         dbversion = query_findversion(client, db, &new_zone);
643         if (dbversion == NULL) {
644                 result = DNS_R_SERVFAIL;
645                 goto fail;
646         }
647         if (new_zone) {
648                 check_acl = ISC_TRUE;
649         } else if (!dbversion->queryok) {
650                 goto refuse;
651         } else {
652                 check_acl = ISC_FALSE;
653         }
654
655         queryacl = dns_zone_getqueryacl(zone);
656         if (queryacl == NULL) {
657                 queryacl = client->view->queryacl;
658                 if ((client->query.attributes &
659                      NS_QUERYATTR_QUERYOKVALID) != 0) {
660                         /*
661                          * We've evaluated the view's queryacl already.  If
662                          * NS_QUERYATTR_QUERYOK is set, then the client is
663                          * allowed to make queries, otherwise the query should
664                          * be refused.
665                          */
666                         check_acl = ISC_FALSE;
667                         if ((client->query.attributes &
668                              NS_QUERYATTR_QUERYOK) == 0)
669                                 goto refuse;
670                 } else {
671                         /*
672                          * We haven't evaluated the view's queryacl yet.
673                          */
674                         check_acl = ISC_TRUE;
675                 }
676         }
677
678         if (check_acl) {
679                 isc_boolean_t log = ISC_TF((options & DNS_GETDB_NOLOG) == 0);
680
681                 result = ns_client_checkaclsilent(client, NULL, queryacl,
682                                                   ISC_TRUE);
683                 if (log) {
684                         char msg[NS_CLIENT_ACLMSGSIZE("query")];
685                         if (result == ISC_R_SUCCESS) {
686                                 if (isc_log_wouldlog(ns_g_lctx,
687                                                      ISC_LOG_DEBUG(3)))
688                                 {
689                                         ns_client_aclmsg("query", name, qtype,
690                                                          client->view->rdclass,
691                                                          msg, sizeof(msg));
692                                         ns_client_log(client,
693                                                       DNS_LOGCATEGORY_SECURITY,
694                                                       NS_LOGMODULE_QUERY,
695                                                       ISC_LOG_DEBUG(3),
696                                                       "%s approved", msg);
697                                 }
698                         } else {
699                                 ns_client_aclmsg("query", name, qtype,
700                                                  client->view->rdclass,
701                                                  msg, sizeof(msg));
702                                 ns_client_log(client, DNS_LOGCATEGORY_SECURITY,
703                                               NS_LOGMODULE_QUERY, ISC_LOG_INFO,
704                                               "%s denied", msg);
705                         }
706                 }
707
708                 if (queryacl == client->view->queryacl) {
709                         if (result == ISC_R_SUCCESS) {
710                                 /*
711                                  * We were allowed by the default
712                                  * "allow-query" ACL.  Remember this so we
713                                  * don't have to check again.
714                                  */
715                                 client->query.attributes |=
716                                         NS_QUERYATTR_QUERYOK;
717                         }
718                         /*
719                          * We've now evaluated the view's query ACL, and
720                          * the NS_QUERYATTR_QUERYOK attribute is now valid.
721                          */
722                         client->query.attributes |= NS_QUERYATTR_QUERYOKVALID;
723                 }
724
725                 if (result != ISC_R_SUCCESS)
726                         goto refuse;
727         }
728
729         /* Approved. */
730
731         /*
732          * Remember the result of the ACL check so we
733          * don't have to check again.
734          */
735         dbversion->queryok = ISC_TRUE;
736
737         /* Transfer ownership, if necessary. */
738         if (versionp != NULL)
739                 *versionp = dbversion->version;
740
741         return (ISC_R_SUCCESS);
742
743  refuse:
744         return (DNS_R_REFUSED);
745
746  fail:
747         return (result);
748 }
749
750 static inline isc_result_t
751 query_getzonedb(ns_client_t *client, dns_name_t *name, dns_rdatatype_t qtype,
752                 unsigned int options, dns_zone_t **zonep, dns_db_t **dbp,
753                 dns_dbversion_t **versionp)
754 {
755         isc_result_t result;
756         unsigned int ztoptions;
757         dns_zone_t *zone = NULL;
758         dns_db_t *db = NULL;
759         isc_boolean_t partial = ISC_FALSE;
760
761         REQUIRE(zonep != NULL && *zonep == NULL);
762         REQUIRE(dbp != NULL && *dbp == NULL);
763
764         /*%
765          * Find a zone database to answer the query.
766          */
767         ztoptions = ((options & DNS_GETDB_NOEXACT) != 0) ?
768                 DNS_ZTFIND_NOEXACT : 0;
769
770         result = dns_zt_find(client->view->zonetable, name, ztoptions, NULL,
771                              &zone);
772         if (result == DNS_R_PARTIALMATCH)
773                 partial = ISC_TRUE;
774         if (result == ISC_R_SUCCESS || result == DNS_R_PARTIALMATCH)
775                 result = dns_zone_getdb(zone, &db);
776
777         if (result != ISC_R_SUCCESS)
778                 goto fail;
779
780         result = query_validatezonedb(client, name, qtype, options, zone, db,
781                                       versionp);
782
783         if (result != ISC_R_SUCCESS)
784                 goto fail;
785
786         /* Transfer ownership. */
787         *zonep = zone;
788         *dbp = db;
789
790         if (partial && (options & DNS_GETDB_PARTIAL) != 0)
791                 return (DNS_R_PARTIALMATCH);
792         return (ISC_R_SUCCESS);
793
794  fail:
795         if (zone != NULL)
796                 dns_zone_detach(&zone);
797         if (db != NULL)
798                 dns_db_detach(&db);
799
800         return (result);
801 }
802
803 static inline isc_result_t
804 query_getcachedb(ns_client_t *client, dns_name_t *name, dns_rdatatype_t qtype,
805                  dns_db_t **dbp, unsigned int options)
806 {
807         isc_result_t result;
808         isc_boolean_t check_acl;
809         dns_db_t *db = NULL;
810
811         REQUIRE(dbp != NULL && *dbp == NULL);
812
813         /*%
814          * Find a cache database to answer the query.
815          * This may fail with DNS_R_REFUSED if the client
816          * is not allowed to use the cache.
817          */
818
819         if (!USECACHE(client))
820                 return (DNS_R_REFUSED);
821         dns_db_attach(client->view->cachedb, &db);
822
823         if ((client->query.attributes & NS_QUERYATTR_CACHEACLOKVALID) != 0) {
824                 /*
825                  * We've evaluated the view's cacheacl already.  If
826                  * NS_QUERYATTR_CACHEACLOK is set, then the client is
827                  * allowed to make queries, otherwise the query should
828                  * be refused.
829                  */
830                 check_acl = ISC_FALSE;
831                 if ((client->query.attributes & NS_QUERYATTR_CACHEACLOK) == 0)
832                         goto refuse;
833         } else {
834                 /*
835                  * We haven't evaluated the view's queryacl yet.
836                  */
837                 check_acl = ISC_TRUE;
838         }
839
840         if (check_acl) {
841                 isc_boolean_t log = ISC_TF((options & DNS_GETDB_NOLOG) == 0);
842                 char msg[NS_CLIENT_ACLMSGSIZE("query (cache)")];
843
844                 result = ns_client_checkaclsilent(client, NULL,
845                                                   client->view->cacheacl,
846                                                   ISC_TRUE);
847                 if (result == ISC_R_SUCCESS) {
848                         /*
849                          * We were allowed by the "allow-query-cache" ACL.
850                          * Remember this so we don't have to check again.
851                          */
852                         client->query.attributes |=
853                                 NS_QUERYATTR_CACHEACLOK;
854                         if (log && isc_log_wouldlog(ns_g_lctx,
855                                                      ISC_LOG_DEBUG(3)))
856                         {
857                                 ns_client_aclmsg("query (cache)", name, qtype,
858                                                  client->view->rdclass,
859                                                  msg, sizeof(msg));
860                                 ns_client_log(client,
861                                               DNS_LOGCATEGORY_SECURITY,
862                                               NS_LOGMODULE_QUERY,
863                                               ISC_LOG_DEBUG(3),
864                                               "%s approved", msg);
865                         }
866                 } else if (log) {
867                         ns_client_aclmsg("query (cache)", name, qtype,
868                                          client->view->rdclass, msg,
869                                          sizeof(msg));
870                         ns_client_log(client, DNS_LOGCATEGORY_SECURITY,
871                                       NS_LOGMODULE_QUERY, ISC_LOG_INFO,
872                                       "%s denied", msg);
873                 }
874                 /*
875                  * We've now evaluated the view's query ACL, and
876                  * the NS_QUERYATTR_CACHEACLOKVALID attribute is now valid.
877                  */
878                 client->query.attributes |= NS_QUERYATTR_CACHEACLOKVALID;
879
880                 if (result != ISC_R_SUCCESS)
881                         goto refuse;
882         }
883
884         /* Approved. */
885
886         /* Transfer ownership. */
887         *dbp = db;
888
889         return (ISC_R_SUCCESS);
890
891  refuse:
892         result = DNS_R_REFUSED;
893
894         if (db != NULL)
895                 dns_db_detach(&db);
896
897         return (result);
898 }
899
900
901 static inline isc_result_t
902 query_getdb(ns_client_t *client, dns_name_t *name, dns_rdatatype_t qtype,
903             unsigned int options, dns_zone_t **zonep, dns_db_t **dbp,
904             dns_dbversion_t **versionp, isc_boolean_t *is_zonep)
905 {
906         isc_result_t result;
907
908 #ifdef DLZ
909         isc_result_t tresult;
910         unsigned int namelabels;
911         unsigned int zonelabels;
912         dns_zone_t *zone = NULL;
913         dns_db_t *tdbp;
914
915         REQUIRE(zonep != NULL && *zonep == NULL);
916
917         tdbp = NULL;
918
919         /* Calculate how many labels are in name. */
920         namelabels = dns_name_countlabels(name);
921         zonelabels = 0;
922
923         /* Try to find name in bind's standard database. */
924         result = query_getzonedb(client, name, qtype, options, &zone,
925                                  dbp, versionp);
926
927         /* See how many labels are in the zone's name.    */
928         if (result == ISC_R_SUCCESS && zone != NULL)
929                 zonelabels = dns_name_countlabels(dns_zone_getorigin(zone));
930         /*
931          * If # zone labels < # name labels, try to find an even better match
932          * Only try if a DLZ driver is loaded for this view
933          */
934         if (zonelabels < namelabels && client->view->dlzdatabase != NULL) {
935                 tresult = dns_dlzfindzone(client->view, name,
936                                           zonelabels, &tdbp);
937                  /* If we successful, we found a better match. */
938                 if (tresult == ISC_R_SUCCESS) {
939                         /*
940                          * If the previous search returned a zone, detach it.
941                          */
942                         if (zone != NULL)
943                                 dns_zone_detach(&zone);
944
945                         /*
946                          * If the previous search returned a database,
947                          * detach it.
948                          */
949                         if (*dbp != NULL)
950                                 dns_db_detach(dbp);
951
952                         /*
953                          * If the previous search returned a version, clear it.
954                          */
955                         *versionp = NULL;
956
957                         /*
958                          * Get our database version.
959                          */
960                         dns_db_currentversion(tdbp, versionp);
961
962                         /*
963                          * Be sure to return our database.
964                          */
965                         *dbp = tdbp;
966
967                         /*
968                          * We return a null zone, No stats for DLZ zones.
969                          */
970                         zone = NULL;
971                         result = tresult;
972                 }
973         }
974 #else
975         result = query_getzonedb(client, name, qtype, options,
976                                  zonep, dbp, versionp);
977 #endif
978
979         /* If successful, Transfer ownership of zone. */
980         if (result == ISC_R_SUCCESS) {
981 #ifdef DLZ
982                 *zonep = zone;
983 #endif
984                 /*
985                  * If neither attempt above succeeded, return the cache instead
986                  */
987                 *is_zonep = ISC_TRUE;
988         } else if (result == ISC_R_NOTFOUND) {
989                 result = query_getcachedb(client, name, qtype, dbp, options);
990                 *is_zonep = ISC_FALSE;
991         }
992         return (result);
993 }
994
995 static inline isc_boolean_t
996 query_isduplicate(ns_client_t *client, dns_name_t *name,
997                   dns_rdatatype_t type, dns_name_t **mnamep)
998 {
999         dns_section_t section;
1000         dns_name_t *mname = NULL;
1001         isc_result_t result;
1002
1003         CTRACE("query_isduplicate");
1004
1005         for (section = DNS_SECTION_ANSWER;
1006              section <= DNS_SECTION_ADDITIONAL;
1007              section++) {
1008                 result = dns_message_findname(client->message, section,
1009                                               name, type, 0, &mname, NULL);
1010                 if (result == ISC_R_SUCCESS) {
1011                         /*
1012                          * We've already got this RRset in the response.
1013                          */
1014                         CTRACE("query_isduplicate: true: done");
1015                         return (ISC_TRUE);
1016                 } else if (result == DNS_R_NXRRSET) {
1017                         /*
1018                          * The name exists, but the rdataset does not.
1019                          */
1020                         if (section == DNS_SECTION_ADDITIONAL)
1021                                 break;
1022                 } else
1023                         RUNTIME_CHECK(result == DNS_R_NXDOMAIN);
1024                 mname = NULL;
1025         }
1026
1027         /*
1028          * If the dns_name_t we're looking up is already in the message,
1029          * we don't want to trigger the caller's name replacement logic.
1030          */
1031         if (name == mname)
1032                 mname = NULL;
1033
1034         *mnamep = mname;
1035
1036         CTRACE("query_isduplicate: false: done");
1037         return (ISC_FALSE);
1038 }
1039
1040 static isc_result_t
1041 query_addadditional(void *arg, dns_name_t *name, dns_rdatatype_t qtype) {
1042         ns_client_t *client = arg;
1043         isc_result_t result, eresult;
1044         dns_dbnode_t *node;
1045         dns_db_t *db;
1046         dns_name_t *fname, *mname;
1047         dns_rdataset_t *rdataset, *sigrdataset, *trdataset;
1048         isc_buffer_t *dbuf;
1049         isc_buffer_t b;
1050         dns_dbversion_t *version;
1051         isc_boolean_t added_something, need_addname;
1052         dns_zone_t *zone;
1053         dns_rdatatype_t type;
1054
1055         REQUIRE(NS_CLIENT_VALID(client));
1056         REQUIRE(qtype != dns_rdatatype_any);
1057
1058         if (!WANTDNSSEC(client) && dns_rdatatype_isdnssec(qtype))
1059                 return (ISC_R_SUCCESS);
1060
1061         CTRACE("query_addadditional");
1062
1063         /*
1064          * Initialization.
1065          */
1066         eresult = ISC_R_SUCCESS;
1067         fname = NULL;
1068         rdataset = NULL;
1069         sigrdataset = NULL;
1070         trdataset = NULL;
1071         db = NULL;
1072         version = NULL;
1073         node = NULL;
1074         added_something = ISC_FALSE;
1075         need_addname = ISC_FALSE;
1076         zone = NULL;
1077
1078         /*
1079          * We treat type A additional section processing as if it
1080          * were "any address type" additional section processing.
1081          * To avoid multiple lookups, we do an 'any' database
1082          * lookup and iterate over the node.
1083          */
1084         if (qtype == dns_rdatatype_a)
1085                 type = dns_rdatatype_any;
1086         else
1087                 type = qtype;
1088
1089         /*
1090          * Get some resources.
1091          */
1092         dbuf = query_getnamebuf(client);
1093         if (dbuf == NULL)
1094                 goto cleanup;
1095         fname = query_newname(client, dbuf, &b);
1096         rdataset = query_newrdataset(client);
1097         if (fname == NULL || rdataset == NULL)
1098                 goto cleanup;
1099         if (WANTDNSSEC(client)) {
1100                 sigrdataset = query_newrdataset(client);
1101                 if (sigrdataset == NULL)
1102                         goto cleanup;
1103         }
1104
1105         /*
1106          * Look for a zone database that might contain authoritative
1107          * additional data.
1108          */
1109         result = query_getzonedb(client, name, qtype, DNS_GETDB_NOLOG,
1110                                  &zone, &db, &version);
1111         if (result != ISC_R_SUCCESS)
1112                 goto try_cache;
1113
1114         CTRACE("query_addadditional: db_find");
1115
1116         /*
1117          * Since we are looking for authoritative data, we do not set
1118          * the GLUEOK flag.  Glue will be looked for later, but not
1119          * necessarily in the same database.
1120          */
1121         node = NULL;
1122         result = dns_db_find(db, name, version, type, client->query.dboptions,
1123                              client->now, &node, fname, rdataset,
1124                              sigrdataset);
1125         if (result == ISC_R_SUCCESS) {
1126                 if (sigrdataset != NULL && !dns_db_issecure(db) &&
1127                     dns_rdataset_isassociated(sigrdataset))
1128                         dns_rdataset_disassociate(sigrdataset);
1129                 goto found;
1130         }
1131
1132         if (dns_rdataset_isassociated(rdataset))
1133                 dns_rdataset_disassociate(rdataset);
1134         if (sigrdataset != NULL && dns_rdataset_isassociated(sigrdataset))
1135                 dns_rdataset_disassociate(sigrdataset);
1136         if (node != NULL)
1137                 dns_db_detachnode(db, &node);
1138         version = NULL;
1139         dns_db_detach(&db);
1140
1141         /*
1142          * No authoritative data was found.  The cache is our next best bet.
1143          */
1144
1145  try_cache:
1146         result = query_getcachedb(client, name, qtype, &db, DNS_GETDB_NOLOG);
1147         if (result != ISC_R_SUCCESS)
1148                 /*
1149                  * Most likely the client isn't allowed to query the cache.
1150                  */
1151                 goto try_glue;
1152         /*
1153          * Attempt to validate glue.
1154          */
1155         if (sigrdataset == NULL) {
1156                 sigrdataset = query_newrdataset(client);
1157                 if (sigrdataset == NULL)
1158                         goto cleanup;
1159         }
1160         result = dns_db_find(db, name, version, type,
1161                              client->query.dboptions |
1162                              DNS_DBFIND_GLUEOK | DNS_DBFIND_ADDITIONALOK,
1163                              client->now, &node, fname, rdataset,
1164                              sigrdataset);
1165         if (result == DNS_R_GLUE &&
1166             validate(client, db, fname, rdataset, sigrdataset))
1167                 result = ISC_R_SUCCESS;
1168         if (!WANTDNSSEC(client))
1169                 query_putrdataset(client, &sigrdataset);
1170         if (result == ISC_R_SUCCESS)
1171                 goto found;
1172
1173         if (dns_rdataset_isassociated(rdataset))
1174                 dns_rdataset_disassociate(rdataset);
1175         if (sigrdataset != NULL && dns_rdataset_isassociated(sigrdataset))
1176                 dns_rdataset_disassociate(sigrdataset);
1177         if (node != NULL)
1178                 dns_db_detachnode(db, &node);
1179         dns_db_detach(&db);
1180
1181  try_glue:
1182         /*
1183          * No cached data was found.  Glue is our last chance.
1184          * RFC1035 sayeth:
1185          *
1186          *      NS records cause both the usual additional section
1187          *      processing to locate a type A record, and, when used
1188          *      in a referral, a special search of the zone in which
1189          *      they reside for glue information.
1190          *
1191          * This is the "special search".  Note that we must search
1192          * the zone where the NS record resides, not the zone it
1193          * points to, and that we only do the search in the delegation
1194          * case (identified by client->query.gluedb being set).
1195          */
1196
1197         if (client->query.gluedb == NULL)
1198                 goto cleanup;
1199
1200         /*
1201          * Don't poison caches using the bailiwick protection model.
1202          */
1203         if (!dns_name_issubdomain(name, dns_db_origin(client->query.gluedb)))
1204                 goto cleanup;
1205
1206         dns_db_attach(client->query.gluedb, &db);
1207         result = dns_db_find(db, name, version, type,
1208                              client->query.dboptions | DNS_DBFIND_GLUEOK,
1209                              client->now, &node, fname, rdataset,
1210                              sigrdataset);
1211         if (!(result == ISC_R_SUCCESS ||
1212               result == DNS_R_ZONECUT ||
1213               result == DNS_R_GLUE))
1214                 goto cleanup;
1215
1216  found:
1217         /*
1218          * We have found a potential additional data rdataset, or
1219          * at least a node to iterate over.
1220          */
1221         query_keepname(client, fname, dbuf);
1222
1223         /*
1224          * If we have an rdataset, add it to the additional data
1225          * section.
1226          */
1227         mname = NULL;
1228         if (dns_rdataset_isassociated(rdataset) &&
1229             !query_isduplicate(client, fname, type, &mname)) {
1230                 if (mname != NULL) {
1231                         query_releasename(client, &fname);
1232                         fname = mname;
1233                 } else
1234                         need_addname = ISC_TRUE;
1235                 ISC_LIST_APPEND(fname->list, rdataset, link);
1236                 trdataset = rdataset;
1237                 rdataset = NULL;
1238                 added_something = ISC_TRUE;
1239                 /*
1240                  * Note: we only add SIGs if we've added the type they cover,
1241                  * so we do not need to check if the SIG rdataset is already
1242                  * in the response.
1243                  */
1244                 if (sigrdataset != NULL &&
1245                     dns_rdataset_isassociated(sigrdataset))
1246                 {
1247                         ISC_LIST_APPEND(fname->list, sigrdataset, link);
1248                         sigrdataset = NULL;
1249                 }
1250         }
1251
1252         if (qtype == dns_rdatatype_a) {
1253                 /*
1254                  * We now go looking for A and AAAA records, along with
1255                  * their signatures.
1256                  *
1257                  * XXXRTH  This code could be more efficient.
1258                  */
1259                 if (rdataset != NULL) {
1260                         if (dns_rdataset_isassociated(rdataset))
1261                                 dns_rdataset_disassociate(rdataset);
1262                 } else {
1263                         rdataset = query_newrdataset(client);
1264                         if (rdataset == NULL)
1265                                 goto addname;
1266                 }
1267                 if (sigrdataset != NULL) {
1268                         if (dns_rdataset_isassociated(sigrdataset))
1269                                 dns_rdataset_disassociate(sigrdataset);
1270                 } else if (WANTDNSSEC(client)) {
1271                         sigrdataset = query_newrdataset(client);
1272                         if (sigrdataset == NULL)
1273                                 goto addname;
1274                 }
1275                 result = dns_db_findrdataset(db, node, version,
1276                                              dns_rdatatype_a, 0,
1277                                              client->now, rdataset,
1278                                              sigrdataset);
1279                 if (result == DNS_R_NCACHENXDOMAIN)
1280                         goto addname;
1281                 if (result == DNS_R_NCACHENXRRSET) {
1282                         dns_rdataset_disassociate(rdataset);
1283                         /*
1284                          * Negative cache entries don't have sigrdatasets.
1285                          */
1286                         INSIST(sigrdataset == NULL ||
1287                                ! dns_rdataset_isassociated(sigrdataset));
1288                 }
1289                 if (result == ISC_R_SUCCESS) {
1290                         mname = NULL;
1291                         if (!query_isduplicate(client, fname,
1292                                                dns_rdatatype_a, &mname)) {
1293                                 if (mname != NULL) {
1294                                         query_releasename(client, &fname);
1295                                         fname = mname;
1296                                 } else
1297                                         need_addname = ISC_TRUE;
1298                                 ISC_LIST_APPEND(fname->list, rdataset, link);
1299                                 added_something = ISC_TRUE;
1300                                 if (sigrdataset != NULL &&
1301                                     dns_rdataset_isassociated(sigrdataset))
1302                                 {
1303                                         ISC_LIST_APPEND(fname->list,
1304                                                         sigrdataset, link);
1305                                         sigrdataset =
1306                                                 query_newrdataset(client);
1307                                 }
1308                                 rdataset = query_newrdataset(client);
1309                                 if (rdataset == NULL)
1310                                         goto addname;
1311                                 if (WANTDNSSEC(client) && sigrdataset == NULL)
1312                                         goto addname;
1313                         } else {
1314                                 dns_rdataset_disassociate(rdataset);
1315                                 if (sigrdataset != NULL &&
1316                                     dns_rdataset_isassociated(sigrdataset))
1317                                         dns_rdataset_disassociate(sigrdataset);
1318                         }
1319                 }
1320                 result = dns_db_findrdataset(db, node, version,
1321                                              dns_rdatatype_aaaa, 0,
1322                                              client->now, rdataset,
1323                                              sigrdataset);
1324                 if (result == DNS_R_NCACHENXDOMAIN)
1325                         goto addname;
1326                 if (result == DNS_R_NCACHENXRRSET) {
1327                         dns_rdataset_disassociate(rdataset);
1328                         INSIST(sigrdataset == NULL ||
1329                                ! dns_rdataset_isassociated(sigrdataset));
1330                 }
1331                 if (result == ISC_R_SUCCESS) {
1332                         mname = NULL;
1333                         if (!query_isduplicate(client, fname,
1334                                                dns_rdatatype_aaaa, &mname)) {
1335                                 if (mname != NULL) {
1336                                         query_releasename(client, &fname);
1337                                         fname = mname;
1338                                 } else
1339                                         need_addname = ISC_TRUE;
1340                                 ISC_LIST_APPEND(fname->list, rdataset, link);
1341                                 added_something = ISC_TRUE;
1342                                 if (sigrdataset != NULL &&
1343                                     dns_rdataset_isassociated(sigrdataset))
1344                                 {
1345                                         ISC_LIST_APPEND(fname->list,
1346                                                         sigrdataset, link);
1347                                         sigrdataset = NULL;
1348                                 }
1349                                 rdataset = NULL;
1350                         }
1351                 }
1352         }
1353
1354  addname:
1355         CTRACE("query_addadditional: addname");
1356         /*
1357          * If we haven't added anything, then we're done.
1358          */
1359         if (!added_something)
1360                 goto cleanup;
1361
1362         /*
1363          * We may have added our rdatasets to an existing name, if so, then
1364          * need_addname will be ISC_FALSE.  Whether we used an existing name
1365          * or a new one, we must set fname to NULL to prevent cleanup.
1366          */
1367         if (need_addname)
1368                 dns_message_addname(client->message, fname,
1369                                     DNS_SECTION_ADDITIONAL);
1370         fname = NULL;
1371
1372         /*
1373          * In a few cases, we want to add additional data for additional
1374          * data.  It's simpler to just deal with special cases here than
1375          * to try to create a general purpose mechanism and allow the
1376          * rdata implementations to do it themselves.
1377          *
1378          * This involves recursion, but the depth is limited.  The
1379          * most complex case is adding a SRV rdataset, which involves
1380          * recursing to add address records, which in turn can cause
1381          * recursion to add KEYs.
1382          */
1383         if (type == dns_rdatatype_srv && trdataset != NULL) {
1384                 /*
1385                  * If we're adding SRV records to the additional data
1386                  * section, it's helpful if we add the SRV additional data
1387                  * as well.
1388                  */
1389                 eresult = dns_rdataset_additionaldata(trdataset,
1390                                                       query_addadditional,
1391                                                       client);
1392         }
1393
1394  cleanup:
1395         CTRACE("query_addadditional: cleanup");
1396         query_putrdataset(client, &rdataset);
1397         if (sigrdataset != NULL)
1398                 query_putrdataset(client, &sigrdataset);
1399         if (fname != NULL)
1400                 query_releasename(client, &fname);
1401         if (node != NULL)
1402                 dns_db_detachnode(db, &node);
1403         if (db != NULL)
1404                 dns_db_detach(&db);
1405         if (zone != NULL)
1406                 dns_zone_detach(&zone);
1407
1408         CTRACE("query_addadditional: done");
1409         return (eresult);
1410 }
1411
1412 static inline void
1413 query_discardcache(ns_client_t *client, dns_rdataset_t *rdataset_base,
1414                    dns_rdatasetadditional_t additionaltype,
1415                    dns_rdatatype_t type, dns_zone_t **zonep, dns_db_t **dbp,
1416                    dns_dbversion_t **versionp, dns_dbnode_t **nodep,
1417                    dns_name_t *fname)
1418 {
1419         dns_rdataset_t *rdataset;
1420
1421         while  ((rdataset = ISC_LIST_HEAD(fname->list)) != NULL) {
1422                 ISC_LIST_UNLINK(fname->list, rdataset, link);
1423                 query_putrdataset(client, &rdataset);
1424         }
1425         if (*versionp != NULL)
1426                 dns_db_closeversion(*dbp, versionp, ISC_FALSE);
1427         if (*nodep != NULL)
1428                 dns_db_detachnode(*dbp, nodep);
1429         if (*dbp != NULL)
1430                 dns_db_detach(dbp);
1431         if (*zonep != NULL)
1432                 dns_zone_detach(zonep);
1433         (void)dns_rdataset_putadditional(client->view->acache, rdataset_base,
1434                                          additionaltype, type);
1435 }
1436
1437 static inline isc_result_t
1438 query_iscachevalid(dns_zone_t *zone, dns_db_t *db, dns_db_t *db0,
1439                    dns_dbversion_t *version)
1440 {
1441         isc_result_t result = ISC_R_SUCCESS;
1442         dns_dbversion_t *version_current = NULL;
1443         dns_db_t *db_current = db0;
1444
1445         if (db_current == NULL) {
1446                 result = dns_zone_getdb(zone, &db_current);
1447                 if (result != ISC_R_SUCCESS)
1448                         return (result);
1449         }
1450         dns_db_currentversion(db_current, &version_current);
1451         if (db_current != db || version_current != version) {
1452                 result = ISC_R_FAILURE;
1453                 goto cleanup;
1454         }
1455
1456  cleanup:
1457         dns_db_closeversion(db_current, &version_current, ISC_FALSE);
1458         if (db0 == NULL && db_current != NULL)
1459                 dns_db_detach(&db_current);
1460
1461         return (result);
1462 }
1463
1464 static isc_result_t
1465 query_addadditional2(void *arg, dns_name_t *name, dns_rdatatype_t qtype) {
1466         client_additionalctx_t *additionalctx = arg;
1467         dns_rdataset_t *rdataset_base;
1468         ns_client_t *client;
1469         isc_result_t result, eresult;
1470         dns_dbnode_t *node, *cnode;
1471         dns_db_t *db, *cdb;
1472         dns_name_t *fname, *mname0, cfname;
1473         dns_rdataset_t *rdataset, *sigrdataset;
1474         dns_rdataset_t *crdataset, *crdataset_next;
1475         isc_buffer_t *dbuf;
1476         isc_buffer_t b;
1477         dns_dbversion_t *version, *cversion;
1478         isc_boolean_t added_something, need_addname, needadditionalcache;
1479         isc_boolean_t need_sigrrset;
1480         dns_zone_t *zone;
1481         dns_rdatatype_t type;
1482         dns_rdatasetadditional_t additionaltype;
1483
1484         if (qtype != dns_rdatatype_a) {
1485                 /*
1486                  * This function is optimized for "address" types.  For other
1487                  * types, use a generic routine.
1488                  * XXX: ideally, this function should be generic enough.
1489                  */
1490                 return (query_addadditional(additionalctx->client,
1491                                             name, qtype));
1492         }
1493
1494         /*
1495          * Initialization.
1496          */
1497         rdataset_base = additionalctx->rdataset;
1498         client = additionalctx->client;
1499         REQUIRE(NS_CLIENT_VALID(client));
1500         eresult = ISC_R_SUCCESS;
1501         fname = NULL;
1502         rdataset = NULL;
1503         sigrdataset = NULL;
1504         db = NULL;
1505         cdb = NULL;
1506         version = NULL;
1507         cversion = NULL;
1508         node = NULL;
1509         cnode = NULL;
1510         added_something = ISC_FALSE;
1511         need_addname = ISC_FALSE;
1512         zone = NULL;
1513         needadditionalcache = ISC_FALSE;
1514         additionaltype = dns_rdatasetadditional_fromauth;
1515         dns_name_init(&cfname, NULL);
1516
1517         CTRACE("query_addadditional2");
1518
1519         /*
1520          * We treat type A additional section processing as if it
1521          * were "any address type" additional section processing.
1522          * To avoid multiple lookups, we do an 'any' database
1523          * lookup and iterate over the node.
1524          * XXXJT: this approach can cause a suboptimal result when the cache
1525          * DB only has partial address types and the glue DB has remaining
1526          * ones.
1527          */
1528         type = dns_rdatatype_any;
1529
1530         /*
1531          * Get some resources.
1532          */
1533         dbuf = query_getnamebuf(client);
1534         if (dbuf == NULL)
1535                 goto cleanup;
1536         fname = query_newname(client, dbuf, &b);
1537         if (fname == NULL)
1538                 goto cleanup;
1539         dns_name_setbuffer(&cfname, &b); /* share the buffer */
1540
1541         /* Check additional cache */
1542         result = dns_rdataset_getadditional(rdataset_base, additionaltype,
1543                                             type, client->view->acache, &zone,
1544                                             &cdb, &cversion, &cnode, &cfname,
1545                                             client->message, client->now);
1546         if (result != ISC_R_SUCCESS)
1547                 goto findauthdb;
1548         if (zone == NULL) {
1549                 CTRACE("query_addadditional2: auth zone not found");
1550                 goto try_cache;
1551         }
1552
1553         /* Is the cached DB up-to-date? */
1554         result = query_iscachevalid(zone, cdb, NULL, cversion);
1555         if (result != ISC_R_SUCCESS) {
1556                 CTRACE("query_addadditional2: old auth additional cache");
1557                 query_discardcache(client, rdataset_base, additionaltype,
1558                                    type, &zone, &cdb, &cversion, &cnode,
1559                                    &cfname);
1560                 goto findauthdb;
1561         }
1562
1563         if (cnode == NULL) {
1564                 /*
1565                  * We have a negative cache.  We don't have to check the zone
1566                  * ACL, since the result (not using this zone) would be same
1567                  * regardless of the result.
1568                  */
1569                 CTRACE("query_addadditional2: negative auth additional cache");
1570                 dns_db_closeversion(cdb, &cversion, ISC_FALSE);
1571                 dns_db_detach(&cdb);
1572                 dns_zone_detach(&zone);
1573                 goto try_cache;
1574         }
1575
1576         result = query_validatezonedb(client, name, qtype, DNS_GETDB_NOLOG,
1577                                       zone, cdb, NULL);
1578         if (result != ISC_R_SUCCESS) {
1579                 query_discardcache(client, rdataset_base, additionaltype,
1580                                    type, &zone, &cdb, &cversion, &cnode,
1581                                    &cfname);
1582                 goto try_cache;
1583         }
1584
1585         /* We've got an active cache. */
1586         CTRACE("query_addadditional2: auth additional cache");
1587         dns_db_closeversion(cdb, &cversion, ISC_FALSE);
1588         db = cdb;
1589         node = cnode;
1590         dns_name_clone(&cfname, fname);
1591         query_keepname(client, fname, dbuf);
1592         goto foundcache;
1593
1594         /*
1595          * Look for a zone database that might contain authoritative
1596          * additional data.
1597          */
1598  findauthdb:
1599         result = query_getzonedb(client, name, qtype, DNS_GETDB_NOLOG,
1600                                  &zone, &db, &version);
1601         if (result != ISC_R_SUCCESS) {
1602                 /* Cache the negative result */
1603                 (void)dns_rdataset_setadditional(rdataset_base, additionaltype,
1604                                                  type, client->view->acache,
1605                                                  NULL, NULL, NULL, NULL,
1606                                                  NULL);
1607                 goto try_cache;
1608         }
1609
1610         CTRACE("query_addadditional2: db_find");
1611
1612         /*
1613          * Since we are looking for authoritative data, we do not set
1614          * the GLUEOK flag.  Glue will be looked for later, but not
1615          * necessarily in the same database.
1616          */
1617         node = NULL;
1618         result = dns_db_find(db, name, version, type, client->query.dboptions,
1619                              client->now, &node, fname, NULL, NULL);
1620         if (result == ISC_R_SUCCESS)
1621                 goto found;
1622
1623         /* Cache the negative result */
1624         (void)dns_rdataset_setadditional(rdataset_base, additionaltype,
1625                                          type, client->view->acache, zone, db,
1626                                          version, NULL, fname);
1627
1628         if (node != NULL)
1629                 dns_db_detachnode(db, &node);
1630         version = NULL;
1631         dns_db_detach(&db);
1632
1633         /*
1634          * No authoritative data was found.  The cache is our next best bet.
1635          */
1636
1637  try_cache:
1638         additionaltype = dns_rdatasetadditional_fromcache;
1639         result = query_getcachedb(client, name, qtype, &db, DNS_GETDB_NOLOG);
1640         if (result != ISC_R_SUCCESS)
1641                 /*
1642                  * Most likely the client isn't allowed to query the cache.
1643                  */
1644                 goto try_glue;
1645
1646         result = dns_db_find(db, name, version, type,
1647                              client->query.dboptions |
1648                              DNS_DBFIND_GLUEOK | DNS_DBFIND_ADDITIONALOK,
1649                              client->now, &node, fname, NULL, NULL);
1650         if (result == ISC_R_SUCCESS)
1651                 goto found;
1652
1653         if (node != NULL)
1654                 dns_db_detachnode(db, &node);
1655         dns_db_detach(&db);
1656
1657  try_glue:
1658         /*
1659          * No cached data was found.  Glue is our last chance.
1660          * RFC1035 sayeth:
1661          *
1662          *      NS records cause both the usual additional section
1663          *      processing to locate a type A record, and, when used
1664          *      in a referral, a special search of the zone in which
1665          *      they reside for glue information.
1666          *
1667          * This is the "special search".  Note that we must search
1668          * the zone where the NS record resides, not the zone it
1669          * points to, and that we only do the search in the delegation
1670          * case (identified by client->query.gluedb being set).
1671          */
1672         if (client->query.gluedb == NULL)
1673                 goto cleanup;
1674
1675         /*
1676          * Don't poison caches using the bailiwick protection model.
1677          */
1678         if (!dns_name_issubdomain(name, dns_db_origin(client->query.gluedb)))
1679                 goto cleanup;
1680
1681         /* Check additional cache */
1682         additionaltype = dns_rdatasetadditional_fromglue;
1683         result = dns_rdataset_getadditional(rdataset_base, additionaltype,
1684                                             type, client->view->acache, NULL,
1685                                             &cdb, &cversion, &cnode, &cfname,
1686                                             client->message, client->now);
1687         if (result != ISC_R_SUCCESS)
1688                 goto findglue;
1689
1690         result = query_iscachevalid(zone, cdb, client->query.gluedb, cversion);
1691         if (result != ISC_R_SUCCESS) {
1692                 CTRACE("query_addadditional2: old glue additional cache");
1693                 query_discardcache(client, rdataset_base, additionaltype,
1694                                    type, &zone, &cdb, &cversion, &cnode,
1695                                    &cfname);
1696                 goto findglue;
1697         }
1698
1699         if (cnode == NULL) {
1700                 /* We have a negative cache. */
1701                 CTRACE("query_addadditional2: negative glue additional cache");
1702                 dns_db_closeversion(cdb, &cversion, ISC_FALSE);
1703                 dns_db_detach(&cdb);
1704                 goto cleanup;
1705         }
1706
1707         /* Cache hit. */
1708         CTRACE("query_addadditional2: glue additional cache");
1709         dns_db_closeversion(cdb, &cversion, ISC_FALSE);
1710         db = cdb;
1711         node = cnode;
1712         dns_name_clone(&cfname, fname);
1713         query_keepname(client, fname, dbuf);
1714         goto foundcache;
1715
1716  findglue:
1717         dns_db_attach(client->query.gluedb, &db);
1718         result = dns_db_find(db, name, version, type,
1719                              client->query.dboptions | DNS_DBFIND_GLUEOK,
1720                              client->now, &node, fname, NULL, NULL);
1721         if (!(result == ISC_R_SUCCESS ||
1722               result == DNS_R_ZONECUT ||
1723               result == DNS_R_GLUE)) {
1724                 /* cache the negative result */
1725                 (void)dns_rdataset_setadditional(rdataset_base, additionaltype,
1726                                                  type, client->view->acache,
1727                                                  NULL, db, version, NULL,
1728                                                  fname);
1729                 goto cleanup;
1730         }
1731
1732  found:
1733         /*
1734          * We have found a DB node to iterate over from a DB.
1735          * We are going to look for address RRsets (i.e., A and AAAA) in the DB
1736          * node we've just found.  We'll then store the complete information
1737          * in the additional data cache.
1738          */
1739         dns_name_clone(fname, &cfname);
1740         query_keepname(client, fname, dbuf);
1741         needadditionalcache = ISC_TRUE;
1742
1743         rdataset = query_newrdataset(client);
1744         if (rdataset == NULL)
1745                 goto cleanup;
1746
1747         sigrdataset = query_newrdataset(client);
1748         if (sigrdataset == NULL)
1749                 goto cleanup;
1750
1751         /*
1752          * Find A RRset with sig RRset.  Even if we don't find a sig RRset
1753          * for a client using DNSSEC, we'll continue the process to make a
1754          * complete list to be cached.  However, we need to cancel the
1755          * caching when something unexpected happens, in order to avoid
1756          * caching incomplete information.
1757          */
1758         result = dns_db_findrdataset(db, node, version, dns_rdatatype_a, 0,
1759                                      client->now, rdataset, sigrdataset);
1760         /*
1761          * If we can't promote glue/pending from the cache to secure
1762          * then drop it.
1763          */
1764         if (result == ISC_R_SUCCESS &&
1765             additionaltype == dns_rdatasetadditional_fromcache &&
1766             (DNS_TRUST_PENDING(rdataset->trust) ||
1767              DNS_TRUST_GLUE(rdataset->trust)) &&
1768             !validate(client, db, fname, rdataset, sigrdataset)) {
1769                 dns_rdataset_disassociate(rdataset);
1770                 if (dns_rdataset_isassociated(sigrdataset))
1771                         dns_rdataset_disassociate(sigrdataset);
1772                 result = ISC_R_NOTFOUND;
1773         }
1774         if (result == DNS_R_NCACHENXDOMAIN)
1775                 goto setcache;
1776         if (result == DNS_R_NCACHENXRRSET) {
1777                 dns_rdataset_disassociate(rdataset);
1778                 /*
1779                  * Negative cache entries don't have sigrdatasets.
1780                  */
1781                 INSIST(! dns_rdataset_isassociated(sigrdataset));
1782         }
1783         if (result == ISC_R_SUCCESS) {
1784                 /* Remember the result as a cache */
1785                 ISC_LIST_APPEND(cfname.list, rdataset, link);
1786                 if (dns_rdataset_isassociated(sigrdataset)) {
1787                         ISC_LIST_APPEND(cfname.list, sigrdataset, link);
1788                         sigrdataset = query_newrdataset(client);
1789                 }
1790                 rdataset = query_newrdataset(client);
1791                 if (sigrdataset == NULL || rdataset == NULL) {
1792                         /* do not cache incomplete information */
1793                         goto foundcache;
1794                 }
1795         }
1796
1797         /* Find AAAA RRset with sig RRset */
1798         result = dns_db_findrdataset(db, node, version, dns_rdatatype_aaaa,
1799                                      0, client->now, rdataset, sigrdataset);
1800         /*
1801          * If we can't promote glue/pending from the cache to secure
1802          * then drop it.
1803          */
1804         if (result == ISC_R_SUCCESS &&
1805             additionaltype == dns_rdatasetadditional_fromcache &&
1806             (DNS_TRUST_PENDING(rdataset->trust) ||
1807              DNS_TRUST_GLUE(rdataset->trust)) &&
1808             !validate(client, db, fname, rdataset, sigrdataset)) {
1809                 dns_rdataset_disassociate(rdataset);
1810                 if (dns_rdataset_isassociated(sigrdataset))
1811                         dns_rdataset_disassociate(sigrdataset);
1812                 result = ISC_R_NOTFOUND;
1813         }
1814         if (result == ISC_R_SUCCESS) {
1815                 ISC_LIST_APPEND(cfname.list, rdataset, link);
1816                 rdataset = NULL;
1817                 if (dns_rdataset_isassociated(sigrdataset)) {
1818                         ISC_LIST_APPEND(cfname.list, sigrdataset, link);
1819                         sigrdataset = NULL;
1820                 }
1821         }
1822
1823  setcache:
1824         /*
1825          * Set the new result in the cache if required.  We do not support
1826          * caching additional data from a cache DB.
1827          */
1828         if (needadditionalcache == ISC_TRUE &&
1829             (additionaltype == dns_rdatasetadditional_fromauth ||
1830              additionaltype == dns_rdatasetadditional_fromglue)) {
1831                 (void)dns_rdataset_setadditional(rdataset_base, additionaltype,
1832                                                  type, client->view->acache,
1833                                                  zone, db, version, node,
1834                                                  &cfname);
1835         }
1836
1837  foundcache:
1838         need_sigrrset = ISC_FALSE;
1839         mname0 = NULL;
1840         for (crdataset = ISC_LIST_HEAD(cfname.list);
1841              crdataset != NULL;
1842              crdataset = crdataset_next) {
1843                 dns_name_t *mname;
1844
1845                 crdataset_next = ISC_LIST_NEXT(crdataset, link);
1846
1847                 mname = NULL;
1848                 if (crdataset->type == dns_rdatatype_a ||
1849                     crdataset->type == dns_rdatatype_aaaa) {
1850                         if (!query_isduplicate(client, fname, crdataset->type,
1851                                                &mname)) {
1852                                 if (mname != NULL) {
1853                                         /*
1854                                          * A different type of this name is
1855                                          * already stored in the additional
1856                                          * section.  We'll reuse the name.
1857                                          * Note that this should happen at most
1858                                          * once.  Otherwise, fname->link could
1859                                          * leak below.
1860                                          */
1861                                         INSIST(mname0 == NULL);
1862
1863                                         query_releasename(client, &fname);
1864                                         fname = mname;
1865                                         mname0 = mname;
1866                                 } else
1867                                         need_addname = ISC_TRUE;
1868                                 ISC_LIST_UNLINK(cfname.list, crdataset, link);
1869                                 ISC_LIST_APPEND(fname->list, crdataset, link);
1870                                 added_something = ISC_TRUE;
1871                                 need_sigrrset = ISC_TRUE;
1872                         } else
1873                                 need_sigrrset = ISC_FALSE;
1874                 } else if (crdataset->type == dns_rdatatype_rrsig &&
1875                            need_sigrrset && WANTDNSSEC(client)) {
1876                         ISC_LIST_UNLINK(cfname.list, crdataset, link);
1877                         ISC_LIST_APPEND(fname->list, crdataset, link);
1878                         added_something = ISC_TRUE; /* just in case */
1879                         need_sigrrset = ISC_FALSE;
1880                 }
1881         }
1882
1883         CTRACE("query_addadditional2: addname");
1884
1885         /*
1886          * If we haven't added anything, then we're done.
1887          */
1888         if (!added_something)
1889                 goto cleanup;
1890
1891         /*
1892          * We may have added our rdatasets to an existing name, if so, then
1893          * need_addname will be ISC_FALSE.  Whether we used an existing name
1894          * or a new one, we must set fname to NULL to prevent cleanup.
1895          */
1896         if (need_addname)
1897                 dns_message_addname(client->message, fname,
1898                                     DNS_SECTION_ADDITIONAL);
1899         fname = NULL;
1900
1901  cleanup:
1902         CTRACE("query_addadditional2: cleanup");
1903
1904         if (rdataset != NULL)
1905                 query_putrdataset(client, &rdataset);
1906         if (sigrdataset != NULL)
1907                 query_putrdataset(client, &sigrdataset);
1908         while  ((crdataset = ISC_LIST_HEAD(cfname.list)) != NULL) {
1909                 ISC_LIST_UNLINK(cfname.list, crdataset, link);
1910                 query_putrdataset(client, &crdataset);
1911         }
1912         if (fname != NULL)
1913                 query_releasename(client, &fname);
1914         if (node != NULL)
1915                 dns_db_detachnode(db, &node);
1916         if (db != NULL)
1917                 dns_db_detach(&db);
1918         if (zone != NULL)
1919                 dns_zone_detach(&zone);
1920
1921         CTRACE("query_addadditional2: done");
1922         return (eresult);
1923 }
1924
1925 static inline void
1926 query_addrdataset(ns_client_t *client, dns_name_t *fname,
1927                   dns_rdataset_t *rdataset)
1928 {
1929         client_additionalctx_t additionalctx;
1930
1931         /*
1932          * Add 'rdataset' and any pertinent additional data to
1933          * 'fname', a name in the response message for 'client'.
1934          */
1935
1936         CTRACE("query_addrdataset");
1937
1938         ISC_LIST_APPEND(fname->list, rdataset, link);
1939
1940         if (client->view->order != NULL)
1941                 rdataset->attributes |= dns_order_find(client->view->order,
1942                                                        fname, rdataset->type,
1943                                                        rdataset->rdclass);
1944         rdataset->attributes |= DNS_RDATASETATTR_LOADORDER;
1945
1946         if (NOADDITIONAL(client))
1947                 return;
1948
1949         /*
1950          * Add additional data.
1951          *
1952          * We don't care if dns_rdataset_additionaldata() fails.
1953          */
1954         additionalctx.client = client;
1955         additionalctx.rdataset = rdataset;
1956         (void)dns_rdataset_additionaldata(rdataset, query_addadditional2,
1957                                           &additionalctx);
1958         CTRACE("query_addrdataset: done");
1959 }
1960
1961 static void
1962 query_addrrset(ns_client_t *client, dns_name_t **namep,
1963                dns_rdataset_t **rdatasetp, dns_rdataset_t **sigrdatasetp,
1964                isc_buffer_t *dbuf, dns_section_t section)
1965 {
1966         dns_name_t *name, *mname;
1967         dns_rdataset_t *rdataset, *mrdataset, *sigrdataset;
1968         isc_result_t result;
1969
1970         /*%
1971          * To the current response for 'client', add the answer RRset
1972          * '*rdatasetp' and an optional signature set '*sigrdatasetp', with
1973          * owner name '*namep', to section 'section', unless they are
1974          * already there.  Also add any pertinent additional data.
1975          *
1976          * If 'dbuf' is not NULL, then '*namep' is the name whose data is
1977          * stored in 'dbuf'.  In this case, query_addrrset() guarantees that
1978          * when it returns the name will either have been kept or released.
1979          */
1980         CTRACE("query_addrrset");
1981         name = *namep;
1982         rdataset = *rdatasetp;
1983         if (sigrdatasetp != NULL)
1984                 sigrdataset = *sigrdatasetp;
1985         else
1986                 sigrdataset = NULL;
1987         mname = NULL;
1988         mrdataset = NULL;
1989         result = dns_message_findname(client->message, section,
1990                                       name, rdataset->type, rdataset->covers,
1991                                       &mname, &mrdataset);
1992         if (result == ISC_R_SUCCESS) {
1993                 /*
1994                  * We've already got an RRset of the given name and type.
1995                  * There's nothing else to do;
1996                  */
1997                 CTRACE("query_addrrset: dns_message_findname succeeded: done");
1998                 if (dbuf != NULL)
1999                         query_releasename(client, namep);
2000                 return;
2001         } else if (result == DNS_R_NXDOMAIN) {
2002                 /*
2003                  * The name doesn't exist.
2004                  */
2005                 if (dbuf != NULL)
2006                         query_keepname(client, name, dbuf);
2007                 dns_message_addname(client->message, name, section);
2008                 *namep = NULL;
2009                 mname = name;
2010         } else {
2011                 RUNTIME_CHECK(result == DNS_R_NXRRSET);
2012                 if (dbuf != NULL)
2013                         query_releasename(client, namep);
2014         }
2015
2016         if (rdataset->trust != dns_trust_secure &&
2017             (section == DNS_SECTION_ANSWER ||
2018              section == DNS_SECTION_AUTHORITY))
2019                 client->query.attributes &= ~NS_QUERYATTR_SECURE;
2020         /*
2021          * Note: we only add SIGs if we've added the type they cover, so
2022          * we do not need to check if the SIG rdataset is already in the
2023          * response.
2024          */
2025         query_addrdataset(client, mname, rdataset);
2026         *rdatasetp = NULL;
2027         if (sigrdataset != NULL && dns_rdataset_isassociated(sigrdataset)) {
2028                 /*
2029                  * We have a signature.  Add it to the response.
2030                  */
2031                 ISC_LIST_APPEND(mname->list, sigrdataset, link);
2032                 *sigrdatasetp = NULL;
2033         }
2034         CTRACE("query_addrrset: done");
2035 }
2036
2037 static inline isc_result_t
2038 query_addsoa(ns_client_t *client, dns_db_t *db, dns_dbversion_t *version,
2039              isc_boolean_t zero_ttl, isc_boolean_t isassociated)
2040 {
2041         dns_name_t *name;
2042         dns_dbnode_t *node;
2043         isc_result_t result, eresult;
2044         dns_rdataset_t *rdataset = NULL, *sigrdataset = NULL;
2045         dns_rdataset_t **sigrdatasetp = NULL;
2046
2047         CTRACE("query_addsoa");
2048         /*
2049          * Initialization.
2050          */
2051         eresult = ISC_R_SUCCESS;
2052         name = NULL;
2053         rdataset = NULL;
2054         node = NULL;
2055
2056         /*
2057          * Don't add the SOA record for test which set "-T nosoa".
2058          */
2059         if (ns_g_nosoa && (!WANTDNSSEC(client) || !isassociated))
2060                 return (ISC_R_SUCCESS);
2061
2062         /*
2063          * Get resources and make 'name' be the database origin.
2064          */
2065         result = dns_message_gettempname(client->message, &name);
2066         if (result != ISC_R_SUCCESS)
2067                 return (result);
2068         dns_name_init(name, NULL);
2069         dns_name_clone(dns_db_origin(db), name);
2070         rdataset = query_newrdataset(client);
2071         if (rdataset == NULL) {
2072                 eresult = DNS_R_SERVFAIL;
2073                 goto cleanup;
2074         }
2075         if (WANTDNSSEC(client) && dns_db_issecure(db)) {
2076                 sigrdataset = query_newrdataset(client);
2077                 if (sigrdataset == NULL) {
2078                         eresult = DNS_R_SERVFAIL;
2079                         goto cleanup;
2080                 }
2081         }
2082
2083         /*
2084          * Find the SOA.
2085          */
2086         result = dns_db_getoriginnode(db, &node);
2087         if (result == ISC_R_SUCCESS) {
2088                 result = dns_db_findrdataset(db, node, version,
2089                                              dns_rdatatype_soa,
2090                                              0, client->now, rdataset,
2091                                              sigrdataset);
2092         } else {
2093                 dns_fixedname_t foundname;
2094                 dns_name_t *fname;
2095
2096                 dns_fixedname_init(&foundname);
2097                 fname = dns_fixedname_name(&foundname);
2098
2099                 result = dns_db_find(db, name, version, dns_rdatatype_soa,
2100                                      client->query.dboptions, 0, &node,
2101                                      fname, rdataset, sigrdataset);
2102         }
2103         if (result != ISC_R_SUCCESS) {
2104                 /*
2105                  * This is bad.  We tried to get the SOA RR at the zone top
2106                  * and it didn't work!
2107                  */
2108                 eresult = DNS_R_SERVFAIL;
2109         } else {
2110                 /*
2111                  * Extract the SOA MINIMUM.
2112                  */
2113                 dns_rdata_soa_t soa;
2114                 dns_rdata_t rdata = DNS_RDATA_INIT;
2115                 result = dns_rdataset_first(rdataset);
2116                 RUNTIME_CHECK(result == ISC_R_SUCCESS);
2117                 dns_rdataset_current(rdataset, &rdata);
2118                 result = dns_rdata_tostruct(&rdata, &soa, NULL);
2119                 if (result != ISC_R_SUCCESS)
2120                         goto cleanup;
2121
2122                 if (zero_ttl) {
2123                         rdataset->ttl = 0;
2124                         if (sigrdataset != NULL)
2125                                 sigrdataset->ttl = 0;
2126                 }
2127
2128                 /*
2129                  * Add the SOA and its SIG to the response, with the
2130                  * TTLs adjusted per RFC2308 section 3.
2131                  */
2132                 if (rdataset->ttl > soa.minimum)
2133                         rdataset->ttl = soa.minimum;
2134                 if (sigrdataset != NULL && sigrdataset->ttl > soa.minimum)
2135                         sigrdataset->ttl = soa.minimum;
2136
2137                 if (sigrdataset != NULL)
2138                         sigrdatasetp = &sigrdataset;
2139                 else
2140                         sigrdatasetp = NULL;
2141                 query_addrrset(client, &name, &rdataset, sigrdatasetp, NULL,
2142                                DNS_SECTION_AUTHORITY);
2143         }
2144
2145  cleanup:
2146         query_putrdataset(client, &rdataset);
2147         if (sigrdataset != NULL)
2148                 query_putrdataset(client, &sigrdataset);
2149         if (name != NULL)
2150                 query_releasename(client, &name);
2151         if (node != NULL)
2152                 dns_db_detachnode(db, &node);
2153
2154         return (eresult);
2155 }
2156
2157 static inline isc_result_t
2158 query_addns(ns_client_t *client, dns_db_t *db, dns_dbversion_t *version) {
2159         dns_name_t *name, *fname;
2160         dns_dbnode_t *node;
2161         isc_result_t result, eresult;
2162         dns_fixedname_t foundname;
2163         dns_rdataset_t *rdataset = NULL, *sigrdataset = NULL;
2164         dns_rdataset_t **sigrdatasetp = NULL;
2165
2166         CTRACE("query_addns");
2167         /*
2168          * Initialization.
2169          */
2170         eresult = ISC_R_SUCCESS;
2171         name = NULL;
2172         rdataset = NULL;
2173         node = NULL;
2174         dns_fixedname_init(&foundname);
2175         fname = dns_fixedname_name(&foundname);
2176
2177         /*
2178          * Get resources and make 'name' be the database origin.
2179          */
2180         result = dns_message_gettempname(client->message, &name);
2181         if (result != ISC_R_SUCCESS) {
2182                 CTRACE("query_addns: dns_message_gettempname failed: done");
2183                 return (result);
2184         }
2185         dns_name_init(name, NULL);
2186         dns_name_clone(dns_db_origin(db), name);
2187         rdataset = query_newrdataset(client);
2188         if (rdataset == NULL) {
2189                 CTRACE("query_addns: query_newrdataset failed");
2190                 eresult = DNS_R_SERVFAIL;
2191                 goto cleanup;
2192         }
2193         if (WANTDNSSEC(client) && dns_db_issecure(db)) {
2194                 sigrdataset = query_newrdataset(client);
2195                 if (sigrdataset == NULL) {
2196                         CTRACE("query_addns: query_newrdataset failed");
2197                         eresult = DNS_R_SERVFAIL;
2198                         goto cleanup;
2199                 }
2200         }
2201
2202         /*
2203          * Find the NS rdataset.
2204          */
2205         result = dns_db_getoriginnode(db, &node);
2206         if (result == ISC_R_SUCCESS) {
2207                 result = dns_db_findrdataset(db, node, version,
2208                                              dns_rdatatype_ns,
2209                                              0, client->now, rdataset,
2210                                              sigrdataset);
2211         } else {
2212                 CTRACE("query_addns: calling dns_db_find");
2213                 result = dns_db_find(db, name, NULL, dns_rdatatype_ns,
2214                                      client->query.dboptions, 0, &node,
2215                                      fname, rdataset, sigrdataset);
2216                 CTRACE("query_addns: dns_db_find complete");
2217         }
2218         if (result != ISC_R_SUCCESS) {
2219                 CTRACE("query_addns: "
2220                        "dns_db_findrdataset or dns_db_find failed");
2221                 /*
2222                  * This is bad.  We tried to get the NS rdataset at the zone
2223                  * top and it didn't work!
2224                  */
2225                 eresult = DNS_R_SERVFAIL;
2226         } else {
2227                 if (sigrdataset != NULL)
2228                         sigrdatasetp = &sigrdataset;
2229                 else
2230                         sigrdatasetp = NULL;
2231                 query_addrrset(client, &name, &rdataset, sigrdatasetp, NULL,
2232                                DNS_SECTION_AUTHORITY);
2233         }
2234
2235  cleanup:
2236         CTRACE("query_addns: cleanup");
2237         query_putrdataset(client, &rdataset);
2238         if (sigrdataset != NULL)
2239                 query_putrdataset(client, &sigrdataset);
2240         if (name != NULL)
2241                 query_releasename(client, &name);
2242         if (node != NULL)
2243                 dns_db_detachnode(db, &node);
2244
2245         CTRACE("query_addns: done");
2246         return (eresult);
2247 }
2248
2249 static inline isc_result_t
2250 query_addcnamelike(ns_client_t *client, dns_name_t *qname, dns_name_t *tname,
2251                    dns_rdataset_t *dname, dns_name_t **anamep,
2252                    dns_rdatatype_t type)
2253 {
2254         dns_rdataset_t *rdataset;
2255         dns_rdatalist_t *rdatalist;
2256         dns_rdata_t *rdata;
2257         isc_result_t result;
2258         isc_region_t r;
2259
2260         /*
2261          * We assume the name data referred to by tname won't go away.
2262          */
2263
2264         REQUIRE(anamep != NULL);
2265
2266         rdatalist = NULL;
2267         result = dns_message_gettemprdatalist(client->message, &rdatalist);
2268         if (result != ISC_R_SUCCESS)
2269                 return (result);
2270         rdata = NULL;
2271         result = dns_message_gettemprdata(client->message, &rdata);
2272         if (result != ISC_R_SUCCESS)
2273                 return (result);
2274         rdataset = NULL;
2275         result = dns_message_gettemprdataset(client->message, &rdataset);
2276         if (result != ISC_R_SUCCESS)
2277                 return (result);
2278         dns_rdataset_init(rdataset);
2279         result = dns_name_dup(qname, client->mctx, *anamep);
2280         if (result != ISC_R_SUCCESS) {
2281                 dns_message_puttemprdataset(client->message, &rdataset);
2282                 return (result);
2283         }
2284
2285         rdatalist->type = type;
2286         rdatalist->covers = 0;
2287         rdatalist->rdclass = client->message->rdclass;
2288         rdatalist->ttl = dname->ttl;
2289
2290         dns_name_toregion(tname, &r);
2291         rdata->data = r.base;
2292         rdata->length = r.length;
2293         rdata->rdclass = client->message->rdclass;
2294         rdata->type = type;
2295
2296         ISC_LIST_INIT(rdatalist->rdata);
2297         ISC_LIST_APPEND(rdatalist->rdata, rdata, link);
2298         RUNTIME_CHECK(dns_rdatalist_tordataset(rdatalist, rdataset)
2299                       == ISC_R_SUCCESS);
2300         rdataset->trust = dname->trust;
2301
2302         query_addrrset(client, anamep, &rdataset, NULL, NULL,
2303                        DNS_SECTION_ANSWER);
2304
2305         if (rdataset != NULL) {
2306                 if (dns_rdataset_isassociated(rdataset))
2307                         dns_rdataset_disassociate(rdataset);
2308                 dns_message_puttemprdataset(client->message, &rdataset);
2309         }
2310
2311         return (ISC_R_SUCCESS);
2312 }
2313
2314 /*
2315  * Mark the RRsets as secure.  Update the cache (db) to reflect the
2316  * change in trust level.
2317  */
2318 static void
2319 mark_secure(ns_client_t *client, dns_db_t *db, dns_name_t *name,
2320             isc_uint32_t ttl, dns_rdataset_t *rdataset,
2321             dns_rdataset_t *sigrdataset)
2322 {
2323         isc_result_t result;
2324         dns_dbnode_t *node = NULL;
2325
2326         rdataset->trust = dns_trust_secure;
2327         sigrdataset->trust = dns_trust_secure;
2328
2329         /*
2330          * Save the updated secure state.  Ignore failures.
2331          */
2332         result = dns_db_findnode(db, name, ISC_TRUE, &node);
2333         if (result != ISC_R_SUCCESS)
2334                 return;
2335         /*
2336          * Bound the validated ttls then minimise.
2337          */
2338         if (sigrdataset->ttl > ttl)
2339                 sigrdataset->ttl = ttl;
2340         if (rdataset->ttl > ttl)
2341                 rdataset->ttl = ttl;
2342         if (rdataset->ttl > sigrdataset->ttl)
2343                 rdataset->ttl = sigrdataset->ttl;
2344         else
2345                 sigrdataset->ttl = rdataset->ttl;
2346
2347         (void)dns_db_addrdataset(db, node, NULL, client->now, rdataset,
2348                                  0, NULL);
2349         (void)dns_db_addrdataset(db, node, NULL, client->now, sigrdataset,
2350                                  0, NULL);
2351         dns_db_detachnode(db, &node);
2352 }
2353
2354 /*
2355  * Find the secure key that corresponds to rrsig.
2356  * Note: 'keyrdataset' maintains state between successive calls,
2357  * there may be multiple keys with the same keyid.
2358  * Return ISC_FALSE if we have exhausted all the possible keys.
2359  */
2360 static isc_boolean_t
2361 get_key(ns_client_t *client, dns_db_t *db, dns_rdata_rrsig_t *rrsig,
2362         dns_rdataset_t *keyrdataset, dst_key_t **keyp)
2363 {
2364         isc_result_t result;
2365         dns_dbnode_t *node = NULL;
2366         isc_boolean_t secure = ISC_FALSE;
2367
2368         if (!dns_rdataset_isassociated(keyrdataset)) {
2369                 result = dns_db_findnode(db, &rrsig->signer, ISC_FALSE, &node);
2370                 if (result != ISC_R_SUCCESS)
2371                         return (ISC_FALSE);
2372
2373                 result = dns_db_findrdataset(db, node, NULL,
2374                                              dns_rdatatype_dnskey, 0,
2375                                              client->now, keyrdataset, NULL);
2376                 dns_db_detachnode(db, &node);
2377                 if (result != ISC_R_SUCCESS)
2378                         return (ISC_FALSE);
2379
2380                 if (keyrdataset->trust != dns_trust_secure)
2381                         return (ISC_FALSE);
2382
2383                 result = dns_rdataset_first(keyrdataset);
2384         } else
2385                 result = dns_rdataset_next(keyrdataset);
2386
2387         for ( ; result == ISC_R_SUCCESS;
2388              result = dns_rdataset_next(keyrdataset)) {
2389                 dns_rdata_t rdata = DNS_RDATA_INIT;
2390                 isc_buffer_t b;
2391
2392                 dns_rdataset_current(keyrdataset, &rdata);
2393                 isc_buffer_init(&b, rdata.data, rdata.length);
2394                 isc_buffer_add(&b, rdata.length);
2395                 result = dst_key_fromdns(&rrsig->signer, rdata.rdclass, &b,
2396                                          client->mctx, keyp);
2397                 if (result != ISC_R_SUCCESS)
2398                         continue;
2399                 if (rrsig->algorithm == (dns_secalg_t)dst_key_alg(*keyp) &&
2400                     rrsig->keyid == (dns_keytag_t)dst_key_id(*keyp) &&
2401                     dst_key_iszonekey(*keyp)) {
2402                         secure = ISC_TRUE;
2403                         break;
2404                 }
2405                 dst_key_free(keyp);
2406         }
2407         return (secure);
2408 }
2409
2410 static isc_boolean_t
2411 verify(dst_key_t *key, dns_name_t *name, dns_rdataset_t *rdataset,
2412        dns_rdata_t *rdata, isc_mem_t *mctx, isc_boolean_t acceptexpired)
2413 {
2414         isc_result_t result;
2415         dns_fixedname_t fixed;
2416         isc_boolean_t ignore = ISC_FALSE;
2417
2418         dns_fixedname_init(&fixed);
2419
2420 again:
2421         result = dns_dnssec_verify2(name, rdataset, key, ignore, mctx,
2422                                     rdata, NULL);
2423         if (result == DNS_R_SIGEXPIRED && acceptexpired) {
2424                 ignore = ISC_TRUE;
2425                 goto again;
2426         }
2427         if (result == ISC_R_SUCCESS || result == DNS_R_FROMWILDCARD)
2428                 return (ISC_TRUE);
2429         return (ISC_FALSE);
2430 }
2431
2432 /*
2433  * Validate the rdataset if possible with available records.
2434  */
2435 static isc_boolean_t
2436 validate(ns_client_t *client, dns_db_t *db, dns_name_t *name,
2437          dns_rdataset_t *rdataset, dns_rdataset_t *sigrdataset)
2438 {
2439         isc_result_t result;
2440         dns_rdata_t rdata = DNS_RDATA_INIT;
2441         dns_rdata_rrsig_t rrsig;
2442         dst_key_t *key = NULL;
2443         dns_rdataset_t keyrdataset;
2444
2445         if (sigrdataset == NULL || !dns_rdataset_isassociated(sigrdataset))
2446                 return (ISC_FALSE);
2447
2448         for (result = dns_rdataset_first(sigrdataset);
2449              result == ISC_R_SUCCESS;
2450              result = dns_rdataset_next(sigrdataset)) {
2451
2452                 dns_rdata_reset(&rdata);
2453                 dns_rdataset_current(sigrdataset, &rdata);
2454                 result = dns_rdata_tostruct(&rdata, &rrsig, NULL);
2455                 if (result != ISC_R_SUCCESS)
2456                         return (ISC_FALSE);
2457                 if (!dns_resolver_algorithm_supported(client->view->resolver,
2458                                                       name, rrsig.algorithm))
2459                         continue;
2460                 if (!dns_name_issubdomain(name, &rrsig.signer))
2461                         continue;
2462                 dns_rdataset_init(&keyrdataset);
2463                 do {
2464                         if (!get_key(client, db, &rrsig, &keyrdataset, &key))
2465                                 break;
2466                         if (verify(key, name, rdataset, &rdata, client->mctx,
2467                                    client->view->acceptexpired)) {
2468                                 dst_key_free(&key);
2469                                 dns_rdataset_disassociate(&keyrdataset);
2470                                 mark_secure(client, db, name,
2471                                             rrsig.originalttl,
2472                                             rdataset, sigrdataset);
2473                                 return (ISC_TRUE);
2474                         }
2475                         dst_key_free(&key);
2476                 } while (1);
2477                 if (dns_rdataset_isassociated(&keyrdataset))
2478                         dns_rdataset_disassociate(&keyrdataset);
2479         }
2480         return (ISC_FALSE);
2481 }
2482
2483 static void
2484 query_addbestns(ns_client_t *client) {
2485         dns_db_t *db, *zdb;
2486         dns_dbnode_t *node;
2487         dns_name_t *fname, *zfname;
2488         dns_rdataset_t *rdataset, *sigrdataset, *zrdataset, *zsigrdataset;
2489         isc_boolean_t is_zone, use_zone;
2490         isc_buffer_t *dbuf;
2491         isc_result_t result;
2492         dns_dbversion_t *version;
2493         dns_zone_t *zone;
2494         isc_buffer_t b;
2495
2496         CTRACE("query_addbestns");
2497         fname = NULL;
2498         zfname = NULL;
2499         rdataset = NULL;
2500         zrdataset = NULL;
2501         sigrdataset = NULL;
2502         zsigrdataset = NULL;
2503         node = NULL;
2504         db = NULL;
2505         zdb = NULL;
2506         version = NULL;
2507         zone = NULL;
2508         is_zone = ISC_FALSE;
2509         use_zone = ISC_FALSE;
2510
2511         /*
2512          * Find the right database.
2513          */
2514         result = query_getdb(client, client->query.qname, dns_rdatatype_ns, 0,
2515                              &zone, &db, &version, &is_zone);
2516         if (result != ISC_R_SUCCESS)
2517                 goto cleanup;
2518
2519  db_find:
2520         /*
2521          * We'll need some resources...
2522          */
2523         dbuf = query_getnamebuf(client);
2524         if (dbuf == NULL)
2525                 goto cleanup;
2526         fname = query_newname(client, dbuf, &b);
2527         rdataset = query_newrdataset(client);
2528         if (fname == NULL || rdataset == NULL)
2529                 goto cleanup;
2530         /*
2531          * Get the RRSIGs if the client requested them or if we may
2532          * need to validate answers from the cache.
2533          */
2534         if (WANTDNSSEC(client) || !is_zone) {
2535                 sigrdataset = query_newrdataset(client);
2536                 if (sigrdataset == NULL)
2537                         goto cleanup;
2538         }
2539
2540         /*
2541          * Now look for the zonecut.
2542          */
2543         if (is_zone) {
2544                 result = dns_db_find(db, client->query.qname, version,
2545                                      dns_rdatatype_ns, client->query.dboptions,
2546                                      client->now, &node, fname,
2547                                      rdataset, sigrdataset);
2548                 if (result != DNS_R_DELEGATION)
2549                         goto cleanup;
2550                 if (USECACHE(client)) {
2551                         query_keepname(client, fname, dbuf);
2552                         zdb = db;
2553                         zfname = fname;
2554                         fname = NULL;
2555                         zrdataset = rdataset;
2556                         rdataset = NULL;
2557                         zsigrdataset = sigrdataset;
2558                         sigrdataset = NULL;
2559                         dns_db_detachnode(db, &node);
2560                         version = NULL;
2561                         db = NULL;
2562                         dns_db_attach(client->view->cachedb, &db);
2563                         is_zone = ISC_FALSE;
2564                         goto db_find;
2565                 }
2566         } else {
2567                 result = dns_db_findzonecut(db, client->query.qname,
2568                                             client->query.dboptions,
2569                                             client->now, &node, fname,
2570                                             rdataset, sigrdataset);
2571                 if (result == ISC_R_SUCCESS) {
2572                         if (zfname != NULL &&
2573                             !dns_name_issubdomain(fname, zfname)) {
2574                                 /*
2575                                  * We found a zonecut in the cache, but our
2576                                  * zone delegation is better.
2577                                  */
2578                                 use_zone = ISC_TRUE;
2579                         }
2580                 } else if (result == ISC_R_NOTFOUND && zfname != NULL) {
2581                         /*
2582                          * We didn't find anything in the cache, but we
2583                          * have a zone delegation, so use it.
2584                          */
2585                         use_zone = ISC_TRUE;
2586                 } else
2587                         goto cleanup;
2588         }
2589
2590         if (use_zone) {
2591                 query_releasename(client, &fname);
2592                 fname = zfname;
2593                 zfname = NULL;
2594                 /*
2595                  * We've already done query_keepname() on
2596                  * zfname, so we must set dbuf to NULL to
2597                  * prevent query_addrrset() from trying to
2598                  * call query_keepname() again.
2599                  */
2600                 dbuf = NULL;
2601                 query_putrdataset(client, &rdataset);
2602                 if (sigrdataset != NULL)
2603                         query_putrdataset(client, &sigrdataset);
2604                 rdataset = zrdataset;
2605                 zrdataset = NULL;
2606                 sigrdataset = zsigrdataset;
2607                 zsigrdataset = NULL;
2608         }
2609
2610         /*
2611          * Attempt to validate RRsets that are pending or that are glue.
2612          */
2613         if ((DNS_TRUST_PENDING(rdataset->trust) ||
2614              (sigrdataset != NULL && DNS_TRUST_PENDING(sigrdataset->trust)))
2615             && !validate(client, db, fname, rdataset, sigrdataset) &&
2616             !PENDINGOK(client->query.dboptions))
2617                 goto cleanup;
2618
2619         if ((DNS_TRUST_GLUE(rdataset->trust) ||
2620              (sigrdataset != NULL && DNS_TRUST_GLUE(sigrdataset->trust))) &&
2621             !validate(client, db, fname, rdataset, sigrdataset) &&
2622             SECURE(client) && WANTDNSSEC(client))
2623                 goto cleanup;
2624
2625         /*
2626          * If the client doesn't want DNSSEC we can discard the sigrdataset
2627          * now.
2628          */
2629         if (!WANTDNSSEC(client))
2630                 query_putrdataset(client, &sigrdataset);
2631         query_addrrset(client, &fname, &rdataset, &sigrdataset, dbuf,
2632                        DNS_SECTION_AUTHORITY);
2633
2634  cleanup:
2635         if (rdataset != NULL)
2636                 query_putrdataset(client, &rdataset);
2637         if (sigrdataset != NULL)
2638                 query_putrdataset(client, &sigrdataset);
2639         if (fname != NULL)
2640                 query_releasename(client, &fname);
2641         if (node != NULL)
2642                 dns_db_detachnode(db, &node);
2643         if (db != NULL)
2644                 dns_db_detach(&db);
2645         if (zone != NULL)
2646                 dns_zone_detach(&zone);
2647         if (zdb != NULL) {
2648                 query_putrdataset(client, &zrdataset);
2649                 if (zsigrdataset != NULL)
2650                         query_putrdataset(client, &zsigrdataset);
2651                 if (zfname != NULL)
2652                         query_releasename(client, &zfname);
2653                 dns_db_detach(&zdb);
2654         }
2655 }
2656
2657 static void
2658 fixrdataset(ns_client_t *client, dns_rdataset_t **rdataset) {
2659         if (*rdataset == NULL)
2660                 *rdataset = query_newrdataset(client);
2661         else  if (dns_rdataset_isassociated(*rdataset))
2662                 dns_rdataset_disassociate(*rdataset);
2663 }
2664
2665 static void
2666 fixfname(ns_client_t *client, dns_name_t **fname, isc_buffer_t **dbuf,
2667          isc_buffer_t *nbuf)
2668 {
2669         if (*fname == NULL) {
2670                 *dbuf = query_getnamebuf(client);
2671                 if (*dbuf == NULL)
2672                         return;
2673                 *fname = query_newname(client, *dbuf, nbuf);
2674         }
2675 }
2676
2677 static void
2678 query_addds(ns_client_t *client, dns_db_t *db, dns_dbnode_t *node,
2679             dns_dbversion_t *version, dns_name_t *name)
2680 {
2681         dns_fixedname_t fixed;
2682         dns_name_t *fname = NULL;
2683         dns_name_t *rname;
2684         dns_rdataset_t *rdataset, *sigrdataset;
2685         isc_buffer_t *dbuf, b;
2686         isc_result_t result;
2687         unsigned int count;
2688
2689         CTRACE("query_addds");
2690         rname = NULL;
2691         rdataset = NULL;
2692         sigrdataset = NULL;
2693
2694         /*
2695          * We'll need some resources...
2696          */
2697         rdataset = query_newrdataset(client);
2698         sigrdataset = query_newrdataset(client);
2699         if (rdataset == NULL || sigrdataset == NULL)
2700                 goto cleanup;
2701
2702         /*
2703          * Look for the DS record, which may or may not be present.
2704          */
2705         result = dns_db_findrdataset(db, node, version, dns_rdatatype_ds, 0,
2706                                      client->now, rdataset, sigrdataset);
2707         /*
2708          * If we didn't find it, look for an NSEC.
2709          */
2710         if (result == ISC_R_NOTFOUND)
2711                 result = dns_db_findrdataset(db, node, version,
2712                                              dns_rdatatype_nsec, 0, client->now,
2713                                              rdataset, sigrdataset);
2714         if (result != ISC_R_SUCCESS && result != ISC_R_NOTFOUND)
2715                 goto addnsec3;
2716         if (!dns_rdataset_isassociated(rdataset) ||
2717             !dns_rdataset_isassociated(sigrdataset))
2718                 goto addnsec3;
2719
2720         /*
2721          * We've already added the NS record, so if the name's not there,
2722          * we have other problems.  Use this name rather than calling
2723          * query_addrrset().
2724          */
2725         result = dns_message_firstname(client->message, DNS_SECTION_AUTHORITY);
2726         if (result != ISC_R_SUCCESS)
2727                 goto cleanup;
2728
2729         rname = NULL;
2730         dns_message_currentname(client->message, DNS_SECTION_AUTHORITY,
2731                                 &rname);
2732         result = dns_message_findtype(rname, dns_rdatatype_ns, 0, NULL);
2733         if (result != ISC_R_SUCCESS)
2734                 goto cleanup;
2735
2736         ISC_LIST_APPEND(rname->list, rdataset, link);
2737         ISC_LIST_APPEND(rname->list, sigrdataset, link);
2738         rdataset = NULL;
2739         sigrdataset = NULL;
2740         return;
2741
2742    addnsec3:
2743         if (!dns_db_iszone(db))
2744                 goto cleanup;
2745         /*
2746          * Add the NSEC3 which proves the DS does not exist.
2747          */
2748         dbuf = query_getnamebuf(client);
2749         if (dbuf == NULL)
2750                 goto cleanup;
2751         fname = query_newname(client, dbuf, &b);
2752         dns_fixedname_init(&fixed);
2753         if (dns_rdataset_isassociated(rdataset))
2754                 dns_rdataset_disassociate(rdataset);
2755         if (dns_rdataset_isassociated(sigrdataset))
2756                 dns_rdataset_disassociate(sigrdataset);
2757         query_findclosestnsec3(name, db, version, client, rdataset,
2758                                sigrdataset, fname, ISC_TRUE,
2759                                dns_fixedname_name(&fixed));
2760         if (!dns_rdataset_isassociated(rdataset))
2761                 goto cleanup;
2762         query_addrrset(client, &fname, &rdataset, &sigrdataset, dbuf,
2763                        DNS_SECTION_AUTHORITY);
2764         /*
2765          * Did we find the closest provable encloser instead?
2766          * If so add the nearest to the closest provable encloser.
2767          */
2768         if (!dns_name_equal(name, dns_fixedname_name(&fixed))) {
2769                 count = dns_name_countlabels(dns_fixedname_name(&fixed)) + 1;
2770                 dns_name_getlabelsequence(name,
2771                                           dns_name_countlabels(name) - count,
2772                                           count, dns_fixedname_name(&fixed));
2773                 fixfname(client, &fname, &dbuf, &b);
2774                 fixrdataset(client, &rdataset);
2775                 fixrdataset(client, &sigrdataset);
2776                 if (fname == NULL || rdataset == NULL || sigrdataset == NULL)
2777                                 goto cleanup;
2778                 query_findclosestnsec3(dns_fixedname_name(&fixed), db, version,
2779                                        client, rdataset, sigrdataset, fname,
2780                                        ISC_FALSE, NULL);
2781                 if (!dns_rdataset_isassociated(rdataset))
2782                         goto cleanup;
2783                 query_addrrset(client, &fname, &rdataset, &sigrdataset, dbuf,
2784                                DNS_SECTION_AUTHORITY);
2785         }
2786
2787  cleanup:
2788         if (rdataset != NULL)
2789                 query_putrdataset(client, &rdataset);
2790         if (sigrdataset != NULL)
2791                 query_putrdataset(client, &sigrdataset);
2792         if (fname != NULL)
2793                 query_releasename(client, &fname);
2794 }
2795
2796 static void
2797 query_addwildcardproof(ns_client_t *client, dns_db_t *db,
2798                        dns_dbversion_t *version, dns_name_t *name,
2799                        isc_boolean_t ispositive)
2800 {
2801         isc_buffer_t *dbuf, b;
2802         dns_name_t *fname;
2803         dns_rdataset_t *rdataset, *sigrdataset;
2804         dns_fixedname_t wfixed;
2805         dns_name_t *wname;
2806         dns_dbnode_t *node;
2807         unsigned int options;
2808         unsigned int olabels, nlabels, labels;
2809         isc_result_t result;
2810         dns_rdata_t rdata = DNS_RDATA_INIT;
2811         dns_rdata_nsec_t nsec;
2812         isc_boolean_t have_wname;
2813         int order;
2814         dns_fixedname_t cfixed;
2815         dns_name_t *cname;
2816
2817         CTRACE("query_addwildcardproof");
2818         fname = NULL;
2819         rdataset = NULL;
2820         sigrdataset = NULL;
2821         node = NULL;
2822
2823         /*
2824          * Get the NOQNAME proof then if !ispositive
2825          * get the NOWILDCARD proof.
2826          *
2827          * DNS_DBFIND_NOWILD finds the NSEC records that covers the
2828          * name ignoring any wildcard.  From the owner and next names
2829          * of this record you can compute which wildcard (if it exists)
2830          * will match by finding the longest common suffix of the
2831          * owner name and next names with the qname and prefixing that
2832          * with the wildcard label.
2833          *
2834          * e.g.
2835          *   Given:
2836          *      example SOA
2837          *      example NSEC b.example
2838          *      b.example A
2839          *      b.example NSEC a.d.example
2840          *      a.d.example A
2841          *      a.d.example NSEC g.f.example
2842          *      g.f.example A
2843          *      g.f.example NSEC z.i.example
2844          *      z.i.example A
2845          *      z.i.example NSEC example
2846          *
2847          *   QNAME:
2848          *   a.example -> example NSEC b.example
2849          *      owner common example
2850          *      next common example
2851          *      wild *.example
2852          *   d.b.example -> b.example NSEC a.d.example
2853          *      owner common b.example
2854          *      next common example
2855          *      wild *.b.example
2856          *   a.f.example -> a.d.example NSEC g.f.example
2857          *      owner common example
2858          *      next common f.example
2859          *      wild *.f.example
2860          *  j.example -> z.i.example NSEC example
2861          *      owner common example
2862          *      next common example
2863          *      wild *.f.example
2864          */
2865         options = client->query.dboptions | DNS_DBFIND_NOWILD;
2866         dns_fixedname_init(&wfixed);
2867         wname = dns_fixedname_name(&wfixed);
2868  again:
2869         have_wname = ISC_FALSE;
2870         /*
2871          * We'll need some resources...
2872          */
2873         dbuf = query_getnamebuf(client);
2874         if (dbuf == NULL)
2875                 goto cleanup;
2876         fname = query_newname(client, dbuf, &b);
2877         rdataset = query_newrdataset(client);
2878         sigrdataset = query_newrdataset(client);
2879         if (fname == NULL || rdataset == NULL || sigrdataset == NULL)
2880                 goto cleanup;
2881
2882         result = dns_db_find(db, name, version, dns_rdatatype_nsec, options,
2883                              0, &node, fname, rdataset, sigrdataset);
2884         if (node != NULL)
2885                 dns_db_detachnode(db, &node);
2886
2887         if (!dns_rdataset_isassociated(rdataset)) {
2888                 /*
2889                  * No NSEC proof available, return NSEC3 proofs instead.
2890                  */
2891                 dns_fixedname_init(&cfixed);
2892                 cname = dns_fixedname_name(&cfixed);
2893                 /*
2894                  * Find the closest encloser.
2895                  */
2896                 dns_name_copy(name, cname, NULL);
2897                 while (result == DNS_R_NXDOMAIN) {
2898                         labels = dns_name_countlabels(cname) - 1;
2899                         dns_name_split(cname, labels, NULL, cname);
2900                         result = dns_db_find(db, cname, version,
2901                                              dns_rdatatype_nsec,
2902                                              options, 0, NULL, fname,
2903                                              NULL, NULL);
2904                 }
2905                 /*
2906                  * Add closest (provable) encloser NSEC3.
2907                  */
2908                 query_findclosestnsec3(cname, db, NULL, client, rdataset,
2909                                        sigrdataset, fname, ISC_TRUE, cname);
2910                 if (!dns_rdataset_isassociated(rdataset))
2911                         goto cleanup;
2912                 query_addrrset(client, &fname, &rdataset, &sigrdataset,
2913                                dbuf, DNS_SECTION_AUTHORITY);
2914
2915                 /*
2916                  * Replace resources which were consumed by query_addrrset.
2917                  */
2918                 if (fname == NULL) {
2919                         dbuf = query_getnamebuf(client);
2920                         if (dbuf == NULL)
2921                                 goto cleanup;
2922                         fname = query_newname(client, dbuf, &b);
2923                 }
2924
2925                 if (rdataset == NULL)
2926                         rdataset = query_newrdataset(client);
2927                 else if (dns_rdataset_isassociated(rdataset))
2928                         dns_rdataset_disassociate(rdataset);
2929
2930                 if (sigrdataset == NULL)
2931                         sigrdataset = query_newrdataset(client);
2932                 else if (dns_rdataset_isassociated(sigrdataset))
2933                         dns_rdataset_disassociate(sigrdataset);
2934
2935                 if (fname == NULL || rdataset == NULL || sigrdataset == NULL)
2936                         goto cleanup;
2937                 /*
2938                  * Add no qname proof.
2939                  */
2940                 labels = dns_name_countlabels(cname) + 1;
2941                 if (dns_name_countlabels(name) == labels)
2942                         dns_name_copy(name, wname, NULL);
2943                 else
2944                         dns_name_split(name, labels, NULL, wname);
2945
2946                 query_findclosestnsec3(wname, db, NULL, client, rdataset,
2947                                        sigrdataset, fname, ISC_FALSE, NULL);
2948                 if (!dns_rdataset_isassociated(rdataset))
2949                         goto cleanup;
2950                 query_addrrset(client, &fname, &rdataset, &sigrdataset,
2951                                dbuf, DNS_SECTION_AUTHORITY);
2952
2953                 if (ispositive)
2954                         goto cleanup;
2955
2956                 /*
2957                  * Replace resources which were consumed by query_addrrset.
2958                  */
2959                 if (fname == NULL) {
2960                         dbuf = query_getnamebuf(client);
2961                         if (dbuf == NULL)
2962                                 goto cleanup;
2963                         fname = query_newname(client, dbuf, &b);
2964                 }
2965
2966                 if (rdataset == NULL)
2967                         rdataset = query_newrdataset(client);
2968                 else if (dns_rdataset_isassociated(rdataset))
2969                         dns_rdataset_disassociate(rdataset);
2970
2971                 if (sigrdataset == NULL)
2972                         sigrdataset = query_newrdataset(client);
2973                 else if (dns_rdataset_isassociated(sigrdataset))
2974                         dns_rdataset_disassociate(sigrdataset);
2975
2976                 if (fname == NULL || rdataset == NULL || sigrdataset == NULL)
2977                         goto cleanup;
2978                 /*
2979                  * Add the no wildcard proof.
2980                  */
2981                 result = dns_name_concatenate(dns_wildcardname,
2982                                               cname, wname, NULL);
2983                 if (result != ISC_R_SUCCESS)
2984                         goto cleanup;
2985
2986                 query_findclosestnsec3(wname, db, NULL, client, rdataset,
2987                                        sigrdataset, fname, ISC_FALSE, NULL);
2988                 if (!dns_rdataset_isassociated(rdataset))
2989                         goto cleanup;
2990                 query_addrrset(client, &fname, &rdataset, &sigrdataset,
2991                                dbuf, DNS_SECTION_AUTHORITY);
2992
2993                 goto cleanup;
2994         } else if (result == DNS_R_NXDOMAIN) {
2995                 if (!ispositive)
2996                         result = dns_rdataset_first(rdataset);
2997                 if (result == ISC_R_SUCCESS) {
2998                         dns_rdataset_current(rdataset, &rdata);
2999                         result = dns_rdata_tostruct(&rdata, &nsec, NULL);
3000                 }
3001                 if (result == ISC_R_SUCCESS) {
3002                         (void)dns_name_fullcompare(name, fname, &order,
3003                                                    &olabels);
3004                         (void)dns_name_fullcompare(name, &nsec.next, &order,
3005                                                    &nlabels);
3006                         /*
3007                          * Check for a pathological condition created when
3008                          * serving some malformed signed zones and bail out.
3009                          */
3010                         if (dns_name_countlabels(name) == nlabels)
3011                                 goto cleanup;
3012
3013                         if (olabels > nlabels)
3014                                 dns_name_split(name, olabels, NULL, wname);
3015                         else
3016                                 dns_name_split(name, nlabels, NULL, wname);
3017                         result = dns_name_concatenate(dns_wildcardname,
3018                                                       wname, wname, NULL);
3019                         if (result == ISC_R_SUCCESS)
3020                                 have_wname = ISC_TRUE;
3021                         dns_rdata_freestruct(&nsec);
3022                 }
3023                 query_addrrset(client, &fname, &rdataset, &sigrdataset,
3024                                dbuf, DNS_SECTION_AUTHORITY);
3025         }
3026         if (rdataset != NULL)
3027                 query_putrdataset(client, &rdataset);
3028         if (sigrdataset != NULL)
3029                 query_putrdataset(client, &sigrdataset);
3030         if (fname != NULL)
3031                 query_releasename(client, &fname);
3032         if (have_wname) {
3033                 ispositive = ISC_TRUE;  /* prevent loop */
3034                 if (!dns_name_equal(name, wname)) {
3035                         name = wname;
3036                         goto again;
3037                 }
3038         }
3039  cleanup:
3040         if (rdataset != NULL)
3041                 query_putrdataset(client, &rdataset);
3042         if (sigrdataset != NULL)
3043                 query_putrdataset(client, &sigrdataset);
3044         if (fname != NULL)
3045                 query_releasename(client, &fname);
3046 }
3047
3048 static void
3049 query_addnxrrsetnsec(ns_client_t *client, dns_db_t *db,
3050                      dns_dbversion_t *version, dns_name_t **namep,
3051                      dns_rdataset_t **rdatasetp, dns_rdataset_t **sigrdatasetp)
3052 {
3053         dns_name_t *name;
3054         dns_rdataset_t *sigrdataset;
3055         dns_rdata_t sigrdata;
3056         dns_rdata_rrsig_t sig;
3057         unsigned int labels;
3058         isc_buffer_t *dbuf, b;
3059         dns_name_t *fname;
3060         isc_result_t result;
3061
3062         name = *namep;
3063         if ((name->attributes & DNS_NAMEATTR_WILDCARD) == 0) {
3064                 query_addrrset(client, namep, rdatasetp, sigrdatasetp,
3065                                NULL, DNS_SECTION_AUTHORITY);
3066                 return;
3067         }
3068
3069         if (sigrdatasetp == NULL)
3070                 return;
3071
3072         sigrdataset = *sigrdatasetp;
3073         if (sigrdataset == NULL || !dns_rdataset_isassociated(sigrdataset))
3074                 return;
3075         result = dns_rdataset_first(sigrdataset);
3076         if (result != ISC_R_SUCCESS)
3077                 return;
3078         dns_rdata_init(&sigrdata);
3079         dns_rdataset_current(sigrdataset, &sigrdata);
3080         result = dns_rdata_tostruct(&sigrdata, &sig, NULL);
3081         if (result != ISC_R_SUCCESS)
3082                 return;
3083
3084         labels = dns_name_countlabels(name);
3085         if ((unsigned int)sig.labels + 1 >= labels)
3086                 return;
3087
3088         /* XXX */
3089         query_addwildcardproof(client, db, version, client->query.qname,
3090                                ISC_TRUE);
3091
3092         /*
3093          * We'll need some resources...
3094          */
3095         dbuf = query_getnamebuf(client);
3096         if (dbuf == NULL)
3097                 return;
3098         fname = query_newname(client, dbuf, &b);
3099         if (fname == NULL)
3100                 return;
3101         dns_name_split(name, sig.labels + 1, NULL, fname);
3102         /* This will succeed, since we've stripped labels. */
3103         RUNTIME_CHECK(dns_name_concatenate(dns_wildcardname, fname, fname,
3104                                            NULL) == ISC_R_SUCCESS);
3105         query_addrrset(client, &fname, rdatasetp, sigrdatasetp,
3106                        dbuf, DNS_SECTION_AUTHORITY);
3107 }
3108
3109 static void
3110 query_resume(isc_task_t *task, isc_event_t *event) {
3111         dns_fetchevent_t *devent = (dns_fetchevent_t *)event;
3112         dns_fetch_t *fetch;
3113         ns_client_t *client;
3114         isc_boolean_t fetch_canceled, client_shuttingdown;
3115         isc_result_t result;
3116         isc_logcategory_t *logcategory = NS_LOGCATEGORY_QUERY_EERRORS;
3117         int errorloglevel;
3118
3119         /*
3120          * Resume a query after recursion.
3121          */
3122
3123         UNUSED(task);
3124
3125         REQUIRE(event->ev_type == DNS_EVENT_FETCHDONE);
3126         client = devent->ev_arg;
3127         REQUIRE(NS_CLIENT_VALID(client));
3128         REQUIRE(task == client->task);
3129         REQUIRE(RECURSING(client));
3130
3131         LOCK(&client->query.fetchlock);
3132         if (client->query.fetch != NULL) {
3133                 /*
3134                  * This is the fetch we've been waiting for.
3135                  */
3136                 INSIST(devent->fetch == client->query.fetch);
3137                 client->query.fetch = NULL;
3138                 fetch_canceled = ISC_FALSE;
3139                 /*
3140                  * Update client->now.
3141                  */
3142                 isc_stdtime_get(&client->now);
3143         } else {
3144                 /*
3145                  * This is a fetch completion event for a canceled fetch.
3146                  * Clean up and don't resume the find.
3147                  */
3148                 fetch_canceled = ISC_TRUE;
3149         }
3150         UNLOCK(&client->query.fetchlock);
3151         INSIST(client->query.fetch == NULL);
3152
3153         client->query.attributes &= ~NS_QUERYATTR_RECURSING;
3154         fetch = devent->fetch;
3155         devent->fetch = NULL;
3156
3157         /*
3158          * If this client is shutting down, or this transaction
3159          * has timed out, do not resume the find.
3160          */
3161         client_shuttingdown = ns_client_shuttingdown(client);
3162         if (fetch_canceled || client_shuttingdown) {
3163                 if (devent->node != NULL)
3164                         dns_db_detachnode(devent->db, &devent->node);
3165                 if (devent->db != NULL)
3166                         dns_db_detach(&devent->db);
3167                 query_putrdataset(client, &devent->rdataset);
3168                 if (devent->sigrdataset != NULL)
3169                         query_putrdataset(client, &devent->sigrdataset);
3170                 isc_event_free(&event);
3171                 if (fetch_canceled)
3172                         query_error(client, DNS_R_SERVFAIL, __LINE__);
3173                 else
3174                         query_next(client, ISC_R_CANCELED);
3175                 /*
3176                  * This may destroy the client.
3177                  */
3178                 ns_client_detach(&client);
3179         } else {
3180                 result = query_find(client, devent, 0);
3181                 if (result != ISC_R_SUCCESS) {
3182                         if (result == DNS_R_SERVFAIL)
3183                                 errorloglevel = ISC_LOG_DEBUG(2);
3184                         else
3185                                 errorloglevel = ISC_LOG_DEBUG(4);
3186                         if (isc_log_wouldlog(ns_g_lctx, errorloglevel)) {
3187                                 dns_resolver_logfetch(fetch, ns_g_lctx,
3188                                                       logcategory,
3189                                                       NS_LOGMODULE_QUERY,
3190                                                       errorloglevel, ISC_FALSE);
3191                         }
3192                 }
3193         }
3194
3195         dns_resolver_destroyfetch(&fetch);
3196 }
3197
3198 static isc_result_t
3199 query_recurse(ns_client_t *client, dns_rdatatype_t qtype, dns_name_t *qdomain,
3200               dns_rdataset_t *nameservers, isc_boolean_t resuming)
3201 {
3202         isc_result_t result;
3203         dns_rdataset_t *rdataset, *sigrdataset;
3204         isc_sockaddr_t *peeraddr;
3205
3206         if (!resuming)
3207                 inc_stats(client, dns_nsstatscounter_recursion);
3208
3209         /*
3210          * We are about to recurse, which means that this client will
3211          * be unavailable for serving new requests for an indeterminate
3212          * amount of time.  If this client is currently responsible
3213          * for handling incoming queries, set up a new client
3214          * object to handle them while we are waiting for a
3215          * response.  There is no need to replace TCP clients
3216          * because those have already been replaced when the
3217          * connection was accepted (if allowed by the TCP quota).
3218          */
3219         if (client->recursionquota == NULL) {
3220                 result = isc_quota_attach(&ns_g_server->recursionquota,
3221                                           &client->recursionquota);
3222                 if  (result == ISC_R_SOFTQUOTA) {
3223                         static isc_stdtime_t last = 0;
3224                         isc_stdtime_t now;
3225                         isc_stdtime_get(&now);
3226                         if (now != last) {
3227                                 last = now;
3228                                 ns_client_log(client, NS_LOGCATEGORY_CLIENT,
3229                                               NS_LOGMODULE_QUERY,
3230                                               ISC_LOG_WARNING,
3231                                               "recursive-clients soft limit "
3232                                               "exceeded, aborting oldest query");
3233                         }
3234                         ns_client_killoldestquery(client);
3235                         result = ISC_R_SUCCESS;
3236                 } else if (result == ISC_R_QUOTA) {
3237                         static isc_stdtime_t last = 0;
3238                         isc_stdtime_t now;
3239                         isc_stdtime_get(&now);
3240                         if (now != last) {
3241                                 last = now;
3242                                 ns_client_log(client, NS_LOGCATEGORY_CLIENT,
3243                                               NS_LOGMODULE_QUERY,
3244                                               ISC_LOG_WARNING,
3245                                               "no more recursive clients: %s",
3246                                               isc_result_totext(result));
3247                         }
3248                         ns_client_killoldestquery(client);
3249                 }
3250                 if (result == ISC_R_SUCCESS && !client->mortal &&
3251                     (client->attributes & NS_CLIENTATTR_TCP) == 0) {
3252                         result = ns_client_replace(client);
3253                         if (result != ISC_R_SUCCESS) {
3254                                 ns_client_log(client, NS_LOGCATEGORY_CLIENT,
3255                                               NS_LOGMODULE_QUERY,
3256                                               ISC_LOG_WARNING,
3257                                               "ns_client_replace() failed: %s",
3258                                               isc_result_totext(result));
3259                                 isc_quota_detach(&client->recursionquota);
3260                         }
3261                 }
3262                 if (result != ISC_R_SUCCESS)
3263                         return (result);
3264                 ns_client_recursing(client);
3265         }
3266
3267         /*
3268          * Invoke the resolver.
3269          */
3270         REQUIRE(nameservers == NULL || nameservers->type == dns_rdatatype_ns);
3271         REQUIRE(client->query.fetch == NULL);
3272
3273         rdataset = query_newrdataset(client);
3274         if (rdataset == NULL)
3275                 return (ISC_R_NOMEMORY);
3276         if (WANTDNSSEC(client)) {
3277                 sigrdataset = query_newrdataset(client);
3278                 if (sigrdataset == NULL) {
3279                         query_putrdataset(client, &rdataset);
3280                         return (ISC_R_NOMEMORY);
3281                 }
3282         } else
3283                 sigrdataset = NULL;
3284
3285         if (client->query.timerset == ISC_FALSE)
3286                 ns_client_settimeout(client, 60);
3287         if ((client->attributes & NS_CLIENTATTR_TCP) == 0)
3288                 peeraddr = &client->peeraddr;
3289         else
3290                 peeraddr = NULL;
3291         result = dns_resolver_createfetch2(client->view->resolver,
3292                                            client->query.qname,
3293                                            qtype, qdomain, nameservers,
3294                                            NULL, peeraddr, client->message->id,
3295                                            client->query.fetchoptions,
3296                                            client->task,
3297                                            query_resume, client,
3298                                            rdataset, sigrdataset,
3299                                            &client->query.fetch);
3300
3301         if (result == ISC_R_SUCCESS) {
3302                 /*
3303                  * Record that we're waiting for an event.  A client which
3304                  * is shutting down will not be destroyed until all the
3305                  * events have been received.
3306                  */
3307         } else {
3308                 query_putrdataset(client, &rdataset);
3309                 if (sigrdataset != NULL)
3310                         query_putrdataset(client, &sigrdataset);
3311         }
3312
3313         return (result);
3314 }
3315
3316 #define MAX_RESTARTS 16
3317
3318 #define QUERY_ERROR(r) \
3319 do { \
3320         eresult = r; \
3321         want_restart = ISC_FALSE; \
3322         line = __LINE__; \
3323 } while (0)
3324
3325 #define RECURSE_ERROR(r) \
3326 do { \
3327         if ((r) == DNS_R_DUPLICATE || (r) == DNS_R_DROP) \
3328                 QUERY_ERROR(r); \
3329         else \
3330                 QUERY_ERROR(DNS_R_SERVFAIL); \
3331 } while (0)
3332
3333 /*
3334  * Extract a network address from the RDATA of an A or AAAA
3335  * record.
3336  *
3337  * Returns:
3338  *      ISC_R_SUCCESS
3339  *      ISC_R_NOTIMPLEMENTED    The rdata is not a known address type.
3340  */
3341 static isc_result_t
3342 rdata_tonetaddr(const dns_rdata_t *rdata, isc_netaddr_t *netaddr) {
3343         struct in_addr ina;
3344         struct in6_addr in6a;
3345
3346         switch (rdata->type) {
3347         case dns_rdatatype_a:
3348                 INSIST(rdata->length == 4);
3349                 memcpy(&ina.s_addr, rdata->data, 4);
3350                 isc_netaddr_fromin(netaddr, &ina);
3351                 return (ISC_R_SUCCESS);
3352         case dns_rdatatype_aaaa:
3353                 INSIST(rdata->length == 16);
3354                 memcpy(in6a.s6_addr, rdata->data, 16);
3355                 isc_netaddr_fromin6(netaddr, &in6a);
3356                 return (ISC_R_SUCCESS);
3357         default:
3358                 return (ISC_R_NOTIMPLEMENTED);
3359         }
3360 }
3361
3362 /*
3363  * Find the sort order of 'rdata' in the topology-like
3364  * ACL forming the second element in a 2-element top-level
3365  * sortlist statement.
3366  */
3367 static int
3368 query_sortlist_order_2element(const dns_rdata_t *rdata, const void *arg) {
3369         isc_netaddr_t netaddr;
3370
3371         if (rdata_tonetaddr(rdata, &netaddr) != ISC_R_SUCCESS)
3372                 return (INT_MAX);
3373         return (ns_sortlist_addrorder2(&netaddr, arg));
3374 }
3375
3376 /*
3377  * Find the sort order of 'rdata' in the matching element
3378  * of a 1-element top-level sortlist statement.
3379  */
3380 static int
3381 query_sortlist_order_1element(const dns_rdata_t *rdata, const void *arg) {
3382         isc_netaddr_t netaddr;
3383
3384         if (rdata_tonetaddr(rdata, &netaddr) != ISC_R_SUCCESS)
3385                 return (INT_MAX);
3386         return (ns_sortlist_addrorder1(&netaddr, arg));
3387 }
3388
3389 /*
3390  * Find the sortlist statement that applies to 'client' and set up
3391  * the sortlist info in in client->message appropriately.
3392  */
3393 static void
3394 setup_query_sortlist(ns_client_t *client) {
3395         isc_netaddr_t netaddr;
3396         dns_rdatasetorderfunc_t order = NULL;
3397         const void *order_arg = NULL;
3398
3399         isc_netaddr_fromsockaddr(&netaddr, &client->peeraddr);
3400         switch (ns_sortlist_setup(client->view->sortlist,
3401                                &netaddr, &order_arg)) {
3402         case NS_SORTLISTTYPE_1ELEMENT:
3403                 order = query_sortlist_order_1element;
3404                 break;
3405         case NS_SORTLISTTYPE_2ELEMENT:
3406                 order = query_sortlist_order_2element;
3407                 break;
3408         case NS_SORTLISTTYPE_NONE:
3409                 order = NULL;
3410                 break;
3411         default:
3412                 INSIST(0);
3413                 break;
3414         }
3415         dns_message_setsortorder(client->message, order, order_arg);
3416 }
3417
3418 static void
3419 query_addnoqnameproof(ns_client_t *client, dns_rdataset_t *rdataset) {
3420         isc_buffer_t *dbuf, b;
3421         dns_name_t *fname;
3422         dns_rdataset_t *neg, *negsig;
3423         isc_result_t result = ISC_R_NOMEMORY;
3424
3425         CTRACE("query_addnoqnameproof");
3426
3427         fname = NULL;
3428         neg = NULL;
3429         negsig = NULL;
3430
3431         dbuf = query_getnamebuf(client);
3432         if (dbuf == NULL)
3433                 goto cleanup;
3434         fname = query_newname(client, dbuf, &b);
3435         neg = query_newrdataset(client);
3436         negsig = query_newrdataset(client);
3437         if (fname == NULL || neg == NULL || negsig == NULL)
3438                 goto cleanup;
3439
3440         result = dns_rdataset_getnoqname(rdataset, fname, neg, negsig);
3441         RUNTIME_CHECK(result == ISC_R_SUCCESS);
3442
3443         query_addrrset(client, &fname, &neg, &negsig, dbuf,
3444                        DNS_SECTION_AUTHORITY);
3445
3446         if ((rdataset->attributes & DNS_RDATASETATTR_CLOSEST) == 0)
3447                 goto cleanup;
3448
3449         if (fname == NULL) {
3450                 dbuf = query_getnamebuf(client);
3451                 if (dbuf == NULL)
3452                         goto cleanup;
3453                 fname = query_newname(client, dbuf, &b);
3454         }
3455         if (neg == NULL)
3456                 neg = query_newrdataset(client);
3457         else if (dns_rdataset_isassociated(neg))
3458                 dns_rdataset_disassociate(neg);
3459         if (negsig == NULL)
3460                 negsig = query_newrdataset(client);
3461         else if (dns_rdataset_isassociated(negsig))
3462                 dns_rdataset_disassociate(negsig);
3463         if (fname == NULL || neg == NULL || negsig == NULL)
3464                 goto cleanup;
3465         result = dns_rdataset_getclosest(rdataset, fname, neg, negsig);
3466         RUNTIME_CHECK(result == ISC_R_SUCCESS);
3467
3468         query_addrrset(client, &fname, &neg, &negsig, dbuf,
3469                        DNS_SECTION_AUTHORITY);
3470
3471  cleanup:
3472         if (neg != NULL)
3473                 query_putrdataset(client, &neg);
3474         if (negsig != NULL)
3475                 query_putrdataset(client, &negsig);
3476         if (fname != NULL)
3477                 query_releasename(client, &fname);
3478 }
3479
3480 static inline void
3481 answer_in_glue(ns_client_t *client, dns_rdatatype_t qtype) {
3482         dns_name_t *name;
3483         dns_message_t *msg;
3484         dns_section_t section = DNS_SECTION_ADDITIONAL;
3485         dns_rdataset_t *rdataset = NULL;
3486
3487         msg = client->message;
3488         for (name = ISC_LIST_HEAD(msg->sections[section]);
3489              name != NULL;
3490              name = ISC_LIST_NEXT(name, link))
3491                 if (dns_name_equal(name, client->query.qname)) {
3492                         for (rdataset = ISC_LIST_HEAD(name->list);
3493                              rdataset != NULL;
3494                              rdataset = ISC_LIST_NEXT(rdataset, link))
3495                                 if (rdataset->type == qtype)
3496                                         break;
3497                         break;
3498                 }
3499         if (rdataset != NULL) {
3500                 ISC_LIST_UNLINK(msg->sections[section], name, link);
3501                 ISC_LIST_PREPEND(msg->sections[section], name, link);
3502                 ISC_LIST_UNLINK(name->list, rdataset, link);
3503                 ISC_LIST_PREPEND(name->list, rdataset, link);
3504                 rdataset->attributes |= DNS_RDATASETATTR_REQUIREDGLUE;
3505         }
3506 }
3507
3508 #define NS_NAME_INIT(A,B) \
3509          { \
3510                 DNS_NAME_MAGIC, \
3511                 A, sizeof(A), sizeof(B), \
3512                 DNS_NAMEATTR_READONLY | DNS_NAMEATTR_ABSOLUTE, \
3513                 B, NULL, { (void *)-1, (void *)-1}, \
3514                 {NULL, NULL} \
3515         }
3516
3517 static unsigned char inaddr10_offsets[] = { 0, 3, 11, 16 };
3518 static unsigned char inaddr172_offsets[] = { 0, 3, 7, 15, 20 };
3519 static unsigned char inaddr192_offsets[] = { 0, 4, 8, 16, 21 };
3520
3521 static unsigned char inaddr10[] = "\00210\007IN-ADDR\004ARPA";
3522
3523 static unsigned char inaddr16172[] = "\00216\003172\007IN-ADDR\004ARPA";
3524 static unsigned char inaddr17172[] = "\00217\003172\007IN-ADDR\004ARPA";
3525 static unsigned char inaddr18172[] = "\00218\003172\007IN-ADDR\004ARPA";
3526 static unsigned char inaddr19172[] = "\00219\003172\007IN-ADDR\004ARPA";
3527 static unsigned char inaddr20172[] = "\00220\003172\007IN-ADDR\004ARPA";
3528 static unsigned char inaddr21172[] = "\00221\003172\007IN-ADDR\004ARPA";
3529 static unsigned char inaddr22172[] = "\00222\003172\007IN-ADDR\004ARPA";
3530 static unsigned char inaddr23172[] = "\00223\003172\007IN-ADDR\004ARPA";
3531 static unsigned char inaddr24172[] = "\00224\003172\007IN-ADDR\004ARPA";
3532 static unsigned char inaddr25172[] = "\00225\003172\007IN-ADDR\004ARPA";
3533 static unsigned char inaddr26172[] = "\00226\003172\007IN-ADDR\004ARPA";
3534 static unsigned char inaddr27172[] = "\00227\003172\007IN-ADDR\004ARPA";
3535 static unsigned char inaddr28172[] = "\00228\003172\007IN-ADDR\004ARPA";
3536 static unsigned char inaddr29172[] = "\00229\003172\007IN-ADDR\004ARPA";
3537 static unsigned char inaddr30172[] = "\00230\003172\007IN-ADDR\004ARPA";
3538 static unsigned char inaddr31172[] = "\00231\003172\007IN-ADDR\004ARPA";
3539
3540 static unsigned char inaddr168192[] = "\003168\003192\007IN-ADDR\004ARPA";
3541
3542 static dns_name_t rfc1918names[] = {
3543         NS_NAME_INIT(inaddr10, inaddr10_offsets),
3544         NS_NAME_INIT(inaddr16172, inaddr172_offsets),
3545         NS_NAME_INIT(inaddr17172, inaddr172_offsets),
3546         NS_NAME_INIT(inaddr18172, inaddr172_offsets),
3547         NS_NAME_INIT(inaddr19172, inaddr172_offsets),
3548         NS_NAME_INIT(inaddr20172, inaddr172_offsets),
3549         NS_NAME_INIT(inaddr21172, inaddr172_offsets),
3550         NS_NAME_INIT(inaddr22172, inaddr172_offsets),
3551         NS_NAME_INIT(inaddr23172, inaddr172_offsets),
3552         NS_NAME_INIT(inaddr24172, inaddr172_offsets),
3553         NS_NAME_INIT(inaddr25172, inaddr172_offsets),
3554         NS_NAME_INIT(inaddr26172, inaddr172_offsets),
3555         NS_NAME_INIT(inaddr27172, inaddr172_offsets),
3556         NS_NAME_INIT(inaddr28172, inaddr172_offsets),
3557         NS_NAME_INIT(inaddr29172, inaddr172_offsets),
3558         NS_NAME_INIT(inaddr30172, inaddr172_offsets),
3559         NS_NAME_INIT(inaddr31172, inaddr172_offsets),
3560         NS_NAME_INIT(inaddr168192, inaddr192_offsets)
3561 };
3562
3563
3564 static unsigned char prisoner_data[] = "\010prisoner\004iana\003org";
3565 static unsigned char hostmaster_data[] = "\012hostmaster\014root-servers\003org";
3566
3567 static unsigned char prisoner_offsets[] = { 0, 9, 14, 18 };
3568 static unsigned char hostmaster_offsets[] = { 0, 11, 24, 28 };
3569
3570 static dns_name_t prisoner = NS_NAME_INIT(prisoner_data, prisoner_offsets);
3571 static dns_name_t hostmaster = NS_NAME_INIT(hostmaster_data, hostmaster_offsets);
3572
3573 static void
3574 warn_rfc1918(ns_client_t *client, dns_name_t *fname, dns_rdataset_t *rdataset) {
3575         unsigned int i;
3576         dns_rdata_t rdata = DNS_RDATA_INIT;
3577         dns_rdata_soa_t soa;
3578         dns_rdataset_t found;
3579         isc_result_t result;
3580
3581         for (i = 0; i < (sizeof(rfc1918names)/sizeof(*rfc1918names)); i++) {
3582                 if (dns_name_issubdomain(fname, &rfc1918names[i])) {
3583                         dns_rdataset_init(&found);
3584                         result = dns_ncache_getrdataset(rdataset,
3585                                                         &rfc1918names[i],
3586                                                         dns_rdatatype_soa,
3587                                                         &found);
3588                         if (result != ISC_R_SUCCESS)
3589                                 return;
3590
3591                         result = dns_rdataset_first(&found);
3592                         RUNTIME_CHECK(result == ISC_R_SUCCESS);
3593                         dns_rdataset_current(&found, &rdata);
3594                         result = dns_rdata_tostruct(&rdata, &soa, NULL);
3595                         RUNTIME_CHECK(result == ISC_R_SUCCESS);
3596                         if (dns_name_equal(&soa.origin, &prisoner) &&
3597                             dns_name_equal(&soa.contact, &hostmaster)) {
3598                                 char buf[DNS_NAME_FORMATSIZE];
3599                                 dns_name_format(fname, buf, sizeof(buf));
3600                                 ns_client_log(client, DNS_LOGCATEGORY_SECURITY,
3601                                               NS_LOGMODULE_QUERY,
3602                                               ISC_LOG_WARNING,
3603                                               "RFC 1918 response from "
3604                                               "Internet for %s", buf);
3605                         }
3606                         dns_rdataset_disassociate(&found);
3607                         return;
3608                 }
3609         }
3610 }
3611
3612 static void
3613 query_findclosestnsec3(dns_name_t *qname, dns_db_t *db,
3614                        dns_dbversion_t *version, ns_client_t *client,
3615                        dns_rdataset_t *rdataset, dns_rdataset_t *sigrdataset,
3616                        dns_name_t *fname, isc_boolean_t exact,
3617                        dns_name_t *found)
3618 {
3619         unsigned char salt[256];
3620         size_t salt_length;
3621         isc_uint16_t iterations;
3622         isc_result_t result;
3623         unsigned int dboptions;
3624         dns_fixedname_t fixed;
3625         dns_hash_t hash;
3626         dns_name_t name;
3627         int order;
3628         unsigned int count;
3629         dns_rdata_nsec3_t nsec3;
3630         dns_rdata_t rdata = DNS_RDATA_INIT;
3631         isc_boolean_t optout;
3632
3633         salt_length = sizeof(salt);
3634         result = dns_db_getnsec3parameters(db, version, &hash, NULL,
3635                                            &iterations, salt, &salt_length);
3636         if (result != ISC_R_SUCCESS)
3637                 return;
3638
3639         dns_name_init(&name, NULL);
3640         dns_name_clone(qname, &name);
3641
3642         /*
3643          * Map unknown algorithm to known value.
3644          */
3645         if (hash == DNS_NSEC3_UNKNOWNALG)
3646                 hash = 1;
3647
3648  again:
3649         dns_fixedname_init(&fixed);
3650         result = dns_nsec3_hashname(&fixed, NULL, NULL, &name,
3651                                     dns_db_origin(db), hash,
3652                                     iterations, salt, salt_length);
3653         if (result != ISC_R_SUCCESS)
3654                 return;
3655
3656         dboptions = client->query.dboptions | DNS_DBFIND_FORCENSEC3;
3657         result = dns_db_find(db, dns_fixedname_name(&fixed), version,
3658                              dns_rdatatype_nsec3, dboptions, client->now,
3659                              NULL, fname, rdataset, sigrdataset);
3660
3661         if (result == DNS_R_NXDOMAIN) {
3662                 if (!dns_rdataset_isassociated(rdataset)) {
3663                         return;
3664                 }
3665                 result = dns_rdataset_first(rdataset);
3666                 INSIST(result == ISC_R_SUCCESS);
3667                 dns_rdataset_current(rdataset, &rdata);
3668                 dns_rdata_tostruct(&rdata, &nsec3, NULL);
3669                 dns_rdata_reset(&rdata);
3670                 optout = ISC_TF((nsec3.flags & DNS_NSEC3FLAG_OPTOUT) != 0);
3671                 if (found != NULL && optout &&
3672                     dns_name_fullcompare(&name, dns_db_origin(db), &order,
3673                                          &count) == dns_namereln_subdomain) {
3674                         dns_rdataset_disassociate(rdataset);
3675                         if (dns_rdataset_isassociated(sigrdataset))
3676                                 dns_rdataset_disassociate(sigrdataset);
3677                         count = dns_name_countlabels(&name) - 1;
3678                         dns_name_getlabelsequence(&name, 1, count, &name);
3679                         ns_client_log(client, DNS_LOGCATEGORY_DNSSEC,
3680                                       NS_LOGMODULE_QUERY, ISC_LOG_DEBUG(3),
3681                                       "looking for closest provable encloser");
3682                         goto again;
3683                 }
3684                 if (exact)
3685                         ns_client_log(client, DNS_LOGCATEGORY_DNSSEC,
3686                                       NS_LOGMODULE_QUERY, ISC_LOG_WARNING,
3687                                       "expected a exact match NSEC3, got "
3688                                       "a covering record");
3689
3690         } else if (result != ISC_R_SUCCESS) {
3691                 return;
3692         } else if (!exact)
3693                 ns_client_log(client, DNS_LOGCATEGORY_DNSSEC,
3694                               NS_LOGMODULE_QUERY, ISC_LOG_WARNING,
3695                               "expected covering NSEC3, got an exact match");
3696         if (found != NULL)
3697                 dns_name_copy(&name, found, NULL);
3698         return;
3699 }
3700
3701 /*
3702  * Do the bulk of query processing for the current query of 'client'.
3703  * If 'event' is non-NULL, we are returning from recursion and 'qtype'
3704  * is ignored.  Otherwise, 'qtype' is the query type.
3705  */
3706 static isc_result_t
3707 query_find(ns_client_t *client, dns_fetchevent_t *event, dns_rdatatype_t qtype)
3708 {
3709         dns_db_t *db, *zdb;
3710         dns_dbnode_t *node;
3711         dns_rdatatype_t type;
3712         dns_name_t *fname, *zfname, *tname, *prefix;
3713         dns_rdataset_t *rdataset, *trdataset;
3714         dns_rdataset_t *sigrdataset, *zrdataset, *zsigrdataset;
3715         dns_rdataset_t **sigrdatasetp;
3716         dns_rdata_t rdata = DNS_RDATA_INIT;
3717         dns_rdatasetiter_t *rdsiter;
3718         isc_boolean_t want_restart, authoritative, is_zone, need_wildcardproof;
3719         unsigned int n, nlabels;
3720         dns_namereln_t namereln;
3721         int order;
3722         isc_buffer_t *dbuf;
3723         isc_buffer_t b;
3724         isc_result_t result, eresult;
3725         dns_fixedname_t fixed;
3726         dns_fixedname_t wildcardname;
3727         dns_dbversion_t *version, *zversion;
3728         dns_zone_t *zone;
3729         dns_rdata_cname_t cname;
3730         dns_rdata_dname_t dname;
3731         unsigned int options;
3732         isc_boolean_t empty_wild;
3733         dns_rdataset_t *noqname;
3734         isc_boolean_t resuming;
3735         int line = -1;
3736
3737         CTRACE("query_find");
3738
3739         /*
3740          * One-time initialization.
3741          *
3742          * It's especially important to initialize anything that the cleanup
3743          * code might cleanup.
3744          */
3745
3746         eresult = ISC_R_SUCCESS;
3747         fname = NULL;
3748         zfname = NULL;
3749         rdataset = NULL;
3750         zrdataset = NULL;
3751         sigrdataset = NULL;
3752         zsigrdataset = NULL;
3753         zversion = NULL;
3754         node = NULL;
3755         db = NULL;
3756         zdb = NULL;
3757         version = NULL;
3758         zone = NULL;
3759         need_wildcardproof = ISC_FALSE;
3760         empty_wild = ISC_FALSE;
3761         options = 0;
3762         resuming = ISC_FALSE;
3763         is_zone = ISC_FALSE;
3764
3765         if (event != NULL) {
3766                 /*
3767                  * We're returning from recursion.  Restore the query context
3768                  * and resume.
3769                  */
3770
3771                 want_restart = ISC_FALSE;
3772                 authoritative = ISC_FALSE;
3773
3774                 qtype = event->qtype;
3775                 if (qtype == dns_rdatatype_rrsig || qtype == dns_rdatatype_sig)
3776                         type = dns_rdatatype_any;
3777                 else
3778                         type = qtype;
3779                 db = event->db;
3780                 node = event->node;
3781                 rdataset = event->rdataset;
3782                 sigrdataset = event->sigrdataset;
3783
3784                 /*
3785                  * We'll need some resources...
3786                  */
3787                 dbuf = query_getnamebuf(client);
3788                 if (dbuf == NULL) {
3789                         QUERY_ERROR(DNS_R_SERVFAIL);
3790                         goto cleanup;
3791                 }
3792                 fname = query_newname(client, dbuf, &b);
3793                 if (fname == NULL) {
3794                         QUERY_ERROR(DNS_R_SERVFAIL);
3795                         goto cleanup;
3796                 }
3797                 tname = dns_fixedname_name(&event->foundname);
3798                 result = dns_name_copy(tname, fname, NULL);
3799                 if (result != ISC_R_SUCCESS) {
3800                         QUERY_ERROR(DNS_R_SERVFAIL);
3801                         goto cleanup;
3802                 }
3803
3804                 result = event->result;
3805                 resuming = ISC_TRUE;
3806
3807                 goto resume;
3808         }
3809
3810         /*
3811          * Not returning from recursion.
3812          */
3813
3814         /*
3815          * If it's a SIG query, we'll iterate the node.
3816          */
3817         if (qtype == dns_rdatatype_rrsig || qtype == dns_rdatatype_sig)
3818                 type = dns_rdatatype_any;
3819         else
3820                 type = qtype;
3821
3822  restart:
3823         CTRACE("query_find: restart");
3824         want_restart = ISC_FALSE;
3825         authoritative = ISC_FALSE;
3826         version = NULL;
3827         need_wildcardproof = ISC_FALSE;
3828
3829         if (client->view->checknames &&
3830             !dns_rdata_checkowner(client->query.qname,
3831                                   client->message->rdclass,
3832                                   qtype, ISC_FALSE)) {
3833                 char namebuf[DNS_NAME_FORMATSIZE];
3834                 char typename[DNS_RDATATYPE_FORMATSIZE];
3835                 char classname[DNS_RDATACLASS_FORMATSIZE];
3836
3837                 dns_name_format(client->query.qname, namebuf, sizeof(namebuf));
3838                 dns_rdatatype_format(qtype, typename, sizeof(typename));
3839                 dns_rdataclass_format(client->message->rdclass, classname,
3840                                       sizeof(classname));
3841                 ns_client_log(client, DNS_LOGCATEGORY_SECURITY,
3842                               NS_LOGMODULE_QUERY, ISC_LOG_ERROR,
3843                               "check-names failure %s/%s/%s", namebuf,
3844                               typename, classname);
3845                 QUERY_ERROR(DNS_R_REFUSED);
3846                 goto cleanup;
3847         }
3848
3849         /*
3850          * First we must find the right database.
3851          */
3852         options &= DNS_GETDB_NOLOG; /* Preserve DNS_GETDB_NOLOG. */
3853         if (dns_rdatatype_atparent(qtype) &&
3854             !dns_name_equal(client->query.qname, dns_rootname))
3855                 options |= DNS_GETDB_NOEXACT;
3856         result = query_getdb(client, client->query.qname, qtype, options,
3857                              &zone, &db, &version, &is_zone);
3858         if ((result != ISC_R_SUCCESS || !is_zone) && !RECURSIONOK(client) &&
3859             (options & DNS_GETDB_NOEXACT) != 0 && qtype == dns_rdatatype_ds) {
3860                 /*
3861                  * Look to see if we are authoritative for the
3862                  * child zone if the query type is DS.
3863                  */
3864                 dns_db_t *tdb = NULL;
3865                 dns_zone_t *tzone = NULL;
3866                 dns_dbversion_t *tversion = NULL;
3867                 isc_result_t tresult;
3868
3869                 tresult = query_getzonedb(client, client->query.qname, qtype,
3870                                          DNS_GETDB_PARTIAL, &tzone, &tdb,
3871                                          &tversion);
3872                 if (tresult == ISC_R_SUCCESS) {
3873                         options &= ~DNS_GETDB_NOEXACT;
3874                         query_putrdataset(client, &rdataset);
3875                         if (db != NULL)
3876                                 dns_db_detach(&db);
3877                         if (zone != NULL)
3878                                 dns_zone_detach(&zone);
3879                         version = tversion;
3880                         db = tdb;
3881                         zone = tzone;
3882                         is_zone = ISC_TRUE;
3883                         result = ISC_R_SUCCESS;
3884                 } else {
3885                         if (tdb != NULL)
3886                                 dns_db_detach(&tdb);
3887                         if (tzone != NULL)
3888                                 dns_zone_detach(&tzone);
3889                 }
3890         }
3891         if (result != ISC_R_SUCCESS) {
3892                 if (result == DNS_R_REFUSED) {
3893                         if (WANTRECURSION(client)) {
3894                                 inc_stats(client,
3895                                           dns_nsstatscounter_recurserej);
3896                         } else
3897                                 inc_stats(client, dns_nsstatscounter_authrej);
3898                         if (!PARTIALANSWER(client))
3899                                 QUERY_ERROR(DNS_R_REFUSED);
3900                 } else
3901                         QUERY_ERROR(DNS_R_SERVFAIL);
3902                 goto cleanup;
3903         }
3904
3905         if (is_zone)
3906                 authoritative = ISC_TRUE;
3907
3908         if (event == NULL && client->query.restarts == 0) {
3909                 if (is_zone) {
3910 #ifdef DLZ
3911                         if (zone != NULL) {
3912                                 /*
3913                                  * if is_zone = true, zone = NULL then this is
3914                                  * a DLZ zone.  Don't attempt to attach zone.
3915                                  */
3916 #endif
3917                                 dns_zone_attach(zone, &client->query.authzone);
3918 #ifdef DLZ
3919                         }
3920 #endif
3921                         dns_db_attach(db, &client->query.authdb);
3922                 }
3923                 client->query.authdbset = ISC_TRUE;
3924         }
3925
3926  db_find:
3927         CTRACE("query_find: db_find");
3928         /*
3929          * We'll need some resources...
3930          */
3931         dbuf = query_getnamebuf(client);
3932         if (dbuf == NULL) {
3933                 QUERY_ERROR(DNS_R_SERVFAIL);
3934                 goto cleanup;
3935         }
3936         fname = query_newname(client, dbuf, &b);
3937         rdataset = query_newrdataset(client);
3938         if (fname == NULL || rdataset == NULL) {
3939                 QUERY_ERROR(DNS_R_SERVFAIL);
3940                 goto cleanup;
3941         }
3942         if (WANTDNSSEC(client) && (!is_zone || dns_db_issecure(db))) {
3943                 sigrdataset = query_newrdataset(client);
3944                 if (sigrdataset == NULL) {
3945                         QUERY_ERROR(DNS_R_SERVFAIL);
3946                         goto cleanup;
3947                 }
3948         }
3949
3950         /*
3951          * Now look for an answer in the database.
3952          */
3953         result = dns_db_find(db, client->query.qname, version, type,
3954                              client->query.dboptions, client->now,
3955                              &node, fname, rdataset, sigrdataset);
3956
3957  resume:
3958         CTRACE("query_find: resume");
3959         switch (result) {
3960         case ISC_R_SUCCESS:
3961                 /*
3962                  * This case is handled in the main line below.
3963                  */
3964                 break;
3965         case DNS_R_GLUE:
3966         case DNS_R_ZONECUT:
3967                 /*
3968                  * These cases are handled in the main line below.
3969                  */
3970                 INSIST(is_zone);
3971                 authoritative = ISC_FALSE;
3972                 break;
3973         case ISC_R_NOTFOUND:
3974                 /*
3975                  * The cache doesn't even have the root NS.  Get them from
3976                  * the hints DB.
3977                  */
3978                 INSIST(!is_zone);
3979                 if (db != NULL)
3980                         dns_db_detach(&db);
3981
3982                 if (client->view->hints == NULL) {
3983                         /* We have no hints. */
3984                         result = ISC_R_FAILURE;
3985                 } else {
3986                         dns_db_attach(client->view->hints, &db);
3987                         result = dns_db_find(db, dns_rootname,
3988                                              NULL, dns_rdatatype_ns,
3989                                              0, client->now, &node, fname,
3990                                              rdataset, sigrdataset);
3991                 }
3992                 if (result != ISC_R_SUCCESS) {
3993                         /*
3994                          * Nonsensical root hints may require cleanup.
3995                          */
3996                         if (dns_rdataset_isassociated(rdataset))
3997                                 dns_rdataset_disassociate(rdataset);
3998                         if (sigrdataset != NULL &&
3999                             dns_rdataset_isassociated(sigrdataset))
4000                                 dns_rdataset_disassociate(sigrdataset);
4001                         if (node != NULL)
4002                                 dns_db_detachnode(db, &node);
4003
4004                         /*
4005                          * We don't have any root server hints, but
4006                          * we may have working forwarders, so try to
4007                          * recurse anyway.
4008                          */
4009                         if (RECURSIONOK(client)) {
4010                                 result = query_recurse(client, qtype,
4011                                                        NULL, NULL, resuming);
4012                                 if (result == ISC_R_SUCCESS)
4013                                         client->query.attributes |=
4014                                                 NS_QUERYATTR_RECURSING;
4015                                 else
4016                                         RECURSE_ERROR(result);
4017                                 goto cleanup;
4018                         } else {
4019                                 /* Unable to give root server referral. */
4020                                 QUERY_ERROR(DNS_R_SERVFAIL);
4021                                 goto cleanup;
4022                         }
4023                 }
4024                 /*
4025                  * XXXRTH  We should trigger root server priming here.
4026                  */
4027                 /* FALLTHROUGH */
4028         case DNS_R_DELEGATION:
4029                 authoritative = ISC_FALSE;
4030                 if (is_zone) {
4031                         /*
4032                          * Look to see if we are authoritative for the
4033                          * child zone if the query type is DS.
4034                          */
4035                         if (!RECURSIONOK(client) &&
4036                             (options & DNS_GETDB_NOEXACT) != 0 &&
4037                             qtype == dns_rdatatype_ds) {
4038                                 dns_db_t *tdb = NULL;
4039                                 dns_zone_t *tzone = NULL;
4040                                 dns_dbversion_t *tversion = NULL;
4041                                 result = query_getzonedb(client,
4042                                                          client->query.qname,
4043                                                          qtype,
4044                                                          DNS_GETDB_PARTIAL,
4045                                                          &tzone, &tdb,
4046                                                          &tversion);
4047                                 if (result == ISC_R_SUCCESS) {
4048                                         options &= ~DNS_GETDB_NOEXACT;
4049                                         query_putrdataset(client, &rdataset);
4050                                         if (sigrdataset != NULL)
4051                                                 query_putrdataset(client,
4052                                                                   &sigrdataset);
4053                                         if (fname != NULL)
4054                                                 query_releasename(client,
4055                                                                   &fname);
4056                                         if (node != NULL)
4057                                                 dns_db_detachnode(db, &node);
4058                                         if (db != NULL)
4059                                                 dns_db_detach(&db);
4060                                         if (zone != NULL)
4061                                                 dns_zone_detach(&zone);
4062                                         version = tversion;
4063                                         db = tdb;
4064                                         zone = tzone;
4065                                         authoritative = ISC_TRUE;
4066                                         goto db_find;
4067                                 }
4068                                 if (tdb != NULL)
4069                                         dns_db_detach(&tdb);
4070                                 if (tzone != NULL)
4071                                         dns_zone_detach(&tzone);
4072                         }
4073                         /*
4074                          * We're authoritative for an ancestor of QNAME.
4075                          */
4076                         if (!USECACHE(client) || !RECURSIONOK(client)) {
4077                                 dns_fixedname_t fixed;
4078
4079                                 dns_fixedname_init(&fixed);
4080                                 dns_name_copy(fname,
4081                                               dns_fixedname_name(&fixed), NULL);
4082
4083                                 /*
4084                                  * If we don't have a cache, this is the best
4085                                  * answer.
4086                                  *
4087                                  * If the client is making a nonrecursive
4088                                  * query we always give out the authoritative
4089                                  * delegation.  This way even if we get
4090                                  * junk in our cache, we won't fail in our
4091                                  * role as the delegating authority if another
4092                                  * nameserver asks us about a delegated
4093                                  * subzone.
4094                                  *
4095                                  * We enable the retrieval of glue for this
4096                                  * database by setting client->query.gluedb.
4097                                  */
4098                                 client->query.gluedb = db;
4099                                 client->query.isreferral = ISC_TRUE;
4100                                 /*
4101                                  * We must ensure NOADDITIONAL is off,
4102                                  * because the generation of
4103                                  * additional data is required in
4104                                  * delegations.
4105                                  */
4106                                 client->query.attributes &=
4107                                         ~NS_QUERYATTR_NOADDITIONAL;
4108                                 if (sigrdataset != NULL)
4109                                         sigrdatasetp = &sigrdataset;
4110                                 else
4111                                         sigrdatasetp = NULL;
4112                                 query_addrrset(client, &fname,
4113                                                &rdataset, sigrdatasetp,
4114                                                dbuf, DNS_SECTION_AUTHORITY);
4115                                 client->query.gluedb = NULL;
4116                                 if (WANTDNSSEC(client))
4117                                         query_addds(client, db, node, version,
4118                                                    dns_fixedname_name(&fixed));
4119                         } else {
4120                                 /*
4121                                  * We might have a better answer or delegation
4122                                  * in the cache.  We'll remember the current
4123                                  * values of fname, rdataset, and sigrdataset.
4124                                  * We'll then go looking for QNAME in the
4125                                  * cache.  If we find something better, we'll
4126                                  * use it instead.
4127                                  */
4128                                 query_keepname(client, fname, dbuf);
4129                                 zdb = db;
4130                                 zfname = fname;
4131                                 fname = NULL;
4132                                 zrdataset = rdataset;
4133                                 rdataset = NULL;
4134                                 zsigrdataset = sigrdataset;
4135                                 sigrdataset = NULL;
4136                                 dns_db_detachnode(db, &node);
4137                                 zversion = version;
4138                                 version = NULL;
4139                                 db = NULL;
4140                                 dns_db_attach(client->view->cachedb, &db);
4141                                 is_zone = ISC_FALSE;
4142                                 goto db_find;
4143                         }
4144                 } else {
4145                         if (zfname != NULL &&
4146                             !dns_name_issubdomain(fname, zfname)) {
4147                                 /*
4148                                  * We've already got a delegation from
4149                                  * authoritative data, and it is better
4150                                  * than what we found in the cache.  Use
4151                                  * it instead of the cache delegation.
4152                                  */
4153                                 query_releasename(client, &fname);
4154                                 fname = zfname;
4155                                 zfname = NULL;
4156                                 /*
4157                                  * We've already done query_keepname() on
4158                                  * zfname, so we must set dbuf to NULL to
4159                                  * prevent query_addrrset() from trying to
4160                                  * call query_keepname() again.
4161                                  */
4162                                 dbuf = NULL;
4163                                 query_putrdataset(client, &rdataset);
4164                                 if (sigrdataset != NULL)
4165                                         query_putrdataset(client,
4166                                                           &sigrdataset);
4167                                 rdataset = zrdataset;
4168                                 zrdataset = NULL;
4169                                 sigrdataset = zsigrdataset;
4170                                 zsigrdataset = NULL;
4171                                 version = zversion;
4172                                 zversion = NULL;
4173                                 /*
4174                                  * We don't clean up zdb here because we
4175                                  * may still need it.  It will get cleaned
4176                                  * up by the main cleanup code.
4177                                  */
4178                         }
4179
4180                         if (RECURSIONOK(client)) {
4181                                 /*
4182                                  * Recurse!
4183                                  */
4184                                 if (dns_rdatatype_atparent(type))
4185                                         result = query_recurse(client, qtype,
4186                                                                NULL, NULL,
4187                                                                resuming);
4188                                 else
4189                                         result = query_recurse(client, qtype,
4190                                                                fname, rdataset,
4191                                                                resuming);
4192                                 if (result == ISC_R_SUCCESS)
4193                                         client->query.attributes |=
4194                                                 NS_QUERYATTR_RECURSING;
4195                                 else
4196                                         RECURSE_ERROR(result);
4197                         } else {
4198                                 dns_fixedname_t fixed;
4199
4200                                 dns_fixedname_init(&fixed);
4201                                 dns_name_copy(fname,
4202                                               dns_fixedname_name(&fixed), NULL);
4203                                 /*
4204                                  * This is the best answer.
4205                                  */
4206                                 client->query.attributes |=
4207                                         NS_QUERYATTR_CACHEGLUEOK;
4208                                 client->query.gluedb = zdb;
4209                                 client->query.isreferral = ISC_TRUE;
4210                                 /*
4211                                  * We must ensure NOADDITIONAL is off,
4212                                  * because the generation of
4213                                  * additional data is required in
4214                                  * delegations.
4215                                  */
4216                                 client->query.attributes &=
4217                                         ~NS_QUERYATTR_NOADDITIONAL;
4218                                 if (sigrdataset != NULL)
4219                                         sigrdatasetp = &sigrdataset;
4220                                 else
4221                                         sigrdatasetp = NULL;
4222                                 query_addrrset(client, &fname,
4223                                                &rdataset, sigrdatasetp,
4224                                                dbuf, DNS_SECTION_AUTHORITY);
4225                                 client->query.gluedb = NULL;
4226                                 client->query.attributes &=
4227                                         ~NS_QUERYATTR_CACHEGLUEOK;
4228                                 if (WANTDNSSEC(client))
4229                                         query_addds(client, db, node, version,
4230                                                    dns_fixedname_name(&fixed));
4231                         }
4232                 }
4233                 goto cleanup;
4234         case DNS_R_EMPTYNAME:
4235                 result = DNS_R_NXRRSET;
4236                 /* FALLTHROUGH */
4237         case DNS_R_NXRRSET:
4238                 INSIST(is_zone);
4239                 /*
4240                  * Look for a NSEC3 record if we don't have a NSEC record.
4241                  */
4242                 if (!dns_rdataset_isassociated(rdataset) &&
4243                      WANTDNSSEC(client)) {
4244                         if ((fname->attributes & DNS_NAMEATTR_WILDCARD) == 0) {
4245                                 dns_name_t *found;
4246                                 dns_name_t *qname;
4247
4248                                 dns_fixedname_init(&fixed);
4249                                 found = dns_fixedname_name(&fixed);
4250                                 qname = client->query.qname;
4251
4252                                 query_findclosestnsec3(qname, db, version,
4253                                                        client, rdataset,
4254                                                        sigrdataset, fname,
4255                                                        ISC_TRUE, found);
4256                                 /*
4257                                  * Did we find the closest provable encloser
4258                                  * instead? If so add the nearest to the
4259                                  * closest provable encloser.
4260                                  */
4261                                 if (found &&
4262                                     dns_rdataset_isassociated(rdataset) &&
4263                                     !dns_name_equal(qname, found))
4264                                 {
4265                                         unsigned int count;
4266                                         unsigned int skip;
4267
4268                                         /*
4269                                          * Add the closest provable encloser.
4270                                          */
4271                                         query_addrrset(client, &fname,
4272                                                        &rdataset, &sigrdataset,
4273                                                        dbuf,
4274                                                        DNS_SECTION_AUTHORITY);
4275
4276                                         count = dns_name_countlabels(found)
4277                                                          + 1;
4278                                         skip = dns_name_countlabels(qname) -
4279                                                          count;
4280                                         dns_name_getlabelsequence(qname, skip,
4281                                                                   count,
4282                                                                   found);
4283
4284                                         fixfname(client, &fname, &dbuf, &b);
4285                                         fixrdataset(client, &rdataset);
4286                                         fixrdataset(client, &sigrdataset);
4287                                         if (fname == NULL ||
4288                                             rdataset == NULL ||
4289                                             sigrdataset == NULL) {
4290                                                 QUERY_ERROR(DNS_R_SERVFAIL);
4291                                                 goto cleanup;
4292                                         }
4293                                         /*
4294                                          * 'nearest' doesn't exist so
4295                                          * 'exist' is set to ISC_FALSE.
4296                                          */
4297                                         query_findclosestnsec3(found, db,
4298                                                                version,
4299                                                                client,
4300                                                                rdataset,
4301                                                                sigrdataset,
4302                                                                fname,
4303                                                                ISC_FALSE,
4304                                                                NULL);
4305                                 }
4306                         } else {
4307                                 query_releasename(client, &fname);
4308                                 query_addwildcardproof(client, db, version,
4309                                                        client->query.qname,
4310                                                        ISC_FALSE);
4311                         }
4312                 }
4313                 if (dns_rdataset_isassociated(rdataset)) {
4314                         /*
4315                          * If we've got a NSEC record, we need to save the
4316                          * name now because we're going call query_addsoa()
4317                          * below, and it needs to use the name buffer.
4318                          */
4319                         query_keepname(client, fname, dbuf);
4320                 } else if (fname != NULL) {
4321                         /*
4322                          * We're not going to use fname, and need to release
4323                          * our hold on the name buffer so query_addsoa()
4324                          * may use it.
4325                          */
4326                         query_releasename(client, &fname);
4327                 }
4328                 /*
4329                  * Add SOA.
4330                  */
4331                 result = query_addsoa(client, db, version, ISC_FALSE,
4332                                       dns_rdataset_isassociated(rdataset));
4333                 if (result != ISC_R_SUCCESS) {
4334                         QUERY_ERROR(result);
4335                         goto cleanup;
4336                 }
4337                 /*
4338                  * Add NSEC record if we found one.
4339                  */
4340                 if (WANTDNSSEC(client)) {
4341                         if (dns_rdataset_isassociated(rdataset))
4342                                 query_addnxrrsetnsec(client, db, version,
4343                                                      &fname, &rdataset,
4344                                                      &sigrdataset);
4345                 }
4346                 goto cleanup;
4347
4348         case DNS_R_EMPTYWILD:
4349                 empty_wild = ISC_TRUE;
4350                 /* FALLTHROUGH */
4351
4352         case DNS_R_NXDOMAIN:
4353                 INSIST(is_zone);
4354                 if (dns_rdataset_isassociated(rdataset)) {
4355                         /*
4356                          * If we've got a NSEC record, we need to save the
4357                          * name now because we're going call query_addsoa()
4358                          * below, and it needs to use the name buffer.
4359                          */
4360                         query_keepname(client, fname, dbuf);
4361                 } else if (fname != NULL) {
4362                         /*
4363                          * We're not going to use fname, and need to release
4364                          * our hold on the name buffer so query_addsoa()
4365                          * may use it.
4366                          */
4367                         query_releasename(client, &fname);
4368                 }
4369                 /*
4370                  * Add SOA.  If the query was for a SOA record force the
4371                  * ttl to zero so that it is possible for clients to find
4372                  * the containing zone of an arbitrary name with a stub
4373                  * resolver and not have it cached.
4374                  */
4375                 if (qtype == dns_rdatatype_soa &&
4376 #ifdef DLZ
4377                     zone != NULL &&
4378 #endif
4379                     dns_zone_getzeronosoattl(zone))
4380                         result = query_addsoa(client, db, version, ISC_TRUE,
4381                                           dns_rdataset_isassociated(rdataset));
4382                 else
4383                         result = query_addsoa(client, db, version, ISC_FALSE,
4384                                           dns_rdataset_isassociated(rdataset));
4385                 if (result != ISC_R_SUCCESS) {
4386                         QUERY_ERROR(result);
4387                         goto cleanup;
4388                 }
4389
4390                 if (WANTDNSSEC(client)) {
4391                         /*
4392                          * Add NSEC record if we found one.
4393                          */
4394                         if (dns_rdataset_isassociated(rdataset))
4395                                 query_addrrset(client, &fname, &rdataset,
4396                                                &sigrdataset,
4397                                                NULL, DNS_SECTION_AUTHORITY);
4398                         query_addwildcardproof(client, db, version,
4399                                                client->query.qname, ISC_FALSE);
4400                 }
4401
4402                 /*
4403                  * Set message rcode.
4404                  */
4405                 if (empty_wild)
4406                         client->message->rcode = dns_rcode_noerror;
4407                 else
4408                         client->message->rcode = dns_rcode_nxdomain;
4409                 goto cleanup;
4410
4411         case DNS_R_NCACHENXDOMAIN:
4412         case DNS_R_NCACHENXRRSET:
4413                 INSIST(!is_zone);
4414                 authoritative = ISC_FALSE;
4415                 /*
4416                  * Set message rcode, if required.
4417                  */
4418                 if (result == DNS_R_NCACHENXDOMAIN)
4419                         client->message->rcode = dns_rcode_nxdomain;
4420                 /*
4421                  * Look for RFC 1918 leakage from Internet.
4422                  */
4423                 if (result == DNS_R_NCACHENXDOMAIN &&
4424                     qtype == dns_rdatatype_ptr &&
4425                     client->message->rdclass == dns_rdataclass_in &&
4426                     dns_name_countlabels(fname) == 7)
4427                         warn_rfc1918(client, fname, rdataset);
4428                 /*
4429                  * We don't call query_addrrset() because we don't need any
4430                  * of its extra features (and things would probably break!).
4431                  */
4432                 query_keepname(client, fname, dbuf);
4433                 dns_message_addname(client->message, fname,
4434                                     DNS_SECTION_AUTHORITY);
4435                 ISC_LIST_APPEND(fname->list, rdataset, link);
4436                 fname = NULL;
4437                 rdataset = NULL;
4438                 goto cleanup;
4439
4440         case DNS_R_CNAME:
4441                 /*
4442                  * Keep a copy of the rdataset.  We have to do this because
4443                  * query_addrrset may clear 'rdataset' (to prevent the
4444                  * cleanup code from cleaning it up).
4445                  */
4446                 trdataset = rdataset;
4447                 /*
4448                  * Add the CNAME to the answer section.
4449                  */
4450                 if (sigrdataset != NULL)
4451                         sigrdatasetp = &sigrdataset;
4452                 else
4453                         sigrdatasetp = NULL;
4454                 if (WANTDNSSEC(client) &&
4455                     (fname->attributes & DNS_NAMEATTR_WILDCARD) != 0)
4456                 {
4457                         dns_fixedname_init(&wildcardname);
4458                         dns_name_copy(fname, dns_fixedname_name(&wildcardname),
4459                                       NULL);
4460                         need_wildcardproof = ISC_TRUE;
4461                 }
4462                 if (NOQNAME(rdataset) && WANTDNSSEC(client))
4463                         noqname = rdataset;
4464                 else
4465                         noqname = NULL;
4466                 query_addrrset(client, &fname, &rdataset, sigrdatasetp, dbuf,
4467                                DNS_SECTION_ANSWER);
4468                 if (noqname != NULL)
4469                         query_addnoqnameproof(client, noqname);
4470                 /*
4471                  * We set the PARTIALANSWER attribute so that if anything goes
4472                  * wrong later on, we'll return what we've got so far.
4473                  */
4474                 client->query.attributes |= NS_QUERYATTR_PARTIALANSWER;
4475                 /*
4476                  * Reset qname to be the target name of the CNAME and restart
4477                  * the query.
4478                  */
4479                 tname = NULL;
4480                 result = dns_message_gettempname(client->message, &tname);
4481                 if (result != ISC_R_SUCCESS)
4482                         goto cleanup;
4483                 result = dns_rdataset_first(trdataset);
4484                 if (result != ISC_R_SUCCESS) {
4485                         dns_message_puttempname(client->message, &tname);
4486                         goto cleanup;
4487                 }
4488                 dns_rdataset_current(trdataset, &rdata);
4489                 result = dns_rdata_tostruct(&rdata, &cname, NULL);
4490                 dns_rdata_reset(&rdata);
4491                 if (result != ISC_R_SUCCESS) {
4492                         dns_message_puttempname(client->message, &tname);
4493                         goto cleanup;
4494                 }
4495                 dns_name_init(tname, NULL);
4496                 result = dns_name_dup(&cname.cname, client->mctx, tname);
4497                 if (result != ISC_R_SUCCESS) {
4498                         dns_message_puttempname(client->message, &tname);
4499                         dns_rdata_freestruct(&cname);
4500                         goto cleanup;
4501                 }
4502                 dns_rdata_freestruct(&cname);
4503                 ns_client_qnamereplace(client, tname);
4504                 want_restart = ISC_TRUE;
4505                 if (!WANTRECURSION(client))
4506                         options |= DNS_GETDB_NOLOG;
4507                 goto addauth;
4508         case DNS_R_DNAME:
4509                 /*
4510                  * Compare the current qname to the found name.  We need
4511                  * to know how many labels and bits are in common because
4512                  * we're going to have to split qname later on.
4513                  */
4514                 namereln = dns_name_fullcompare(client->query.qname, fname,
4515                                                 &order, &nlabels);
4516                 INSIST(namereln == dns_namereln_subdomain);
4517                 /*
4518                  * Keep a copy of the rdataset.  We have to do this because
4519                  * query_addrrset may clear 'rdataset' (to prevent the
4520                  * cleanup code from cleaning it up).
4521                  */
4522                 trdataset = rdataset;
4523                 /*
4524                  * Add the DNAME to the answer section.
4525                  */
4526                 if (sigrdataset != NULL)
4527                         sigrdatasetp = &sigrdataset;
4528                 else
4529                         sigrdatasetp = NULL;
4530                 if (WANTDNSSEC(client) &&
4531                     (fname->attributes & DNS_NAMEATTR_WILDCARD) != 0)
4532                 {
4533                         dns_fixedname_init(&wildcardname);
4534                         dns_name_copy(fname, dns_fixedname_name(&wildcardname),
4535                                       NULL);
4536                         need_wildcardproof = ISC_TRUE;
4537                 }
4538                 query_addrrset(client, &fname, &rdataset, sigrdatasetp, dbuf,
4539                                DNS_SECTION_ANSWER);
4540                 /*
4541                  * We set the PARTIALANSWER attribute so that if anything goes
4542                  * wrong later on, we'll return what we've got so far.
4543                  */
4544                 client->query.attributes |= NS_QUERYATTR_PARTIALANSWER;
4545                 /*
4546                  * Get the target name of the DNAME.
4547                  */
4548                 tname = NULL;
4549                 result = dns_message_gettempname(client->message, &tname);
4550                 if (result != ISC_R_SUCCESS)
4551                         goto cleanup;
4552                 result = dns_rdataset_first(trdataset);
4553                 if (result != ISC_R_SUCCESS) {
4554                         dns_message_puttempname(client->message, &tname);
4555                         goto cleanup;
4556                 }
4557                 dns_rdataset_current(trdataset, &rdata);
4558                 result = dns_rdata_tostruct(&rdata, &dname, NULL);
4559                 dns_rdata_reset(&rdata);
4560                 if (result != ISC_R_SUCCESS) {
4561                         dns_message_puttempname(client->message, &tname);
4562                         goto cleanup;
4563                 }
4564                 dns_name_init(tname, NULL);
4565                 dns_name_clone(&dname.dname, tname);
4566                 dns_rdata_freestruct(&dname);
4567                 /*
4568                  * Construct the new qname.
4569                  */
4570                 dns_fixedname_init(&fixed);
4571                 prefix = dns_fixedname_name(&fixed);
4572                 dns_name_split(client->query.qname, nlabels, prefix, NULL);
4573                 INSIST(fname == NULL);
4574                 dbuf = query_getnamebuf(client);
4575                 if (dbuf == NULL) {
4576                         dns_message_puttempname(client->message, &tname);
4577                         goto cleanup;
4578                 }
4579                 fname = query_newname(client, dbuf, &b);
4580                 if (fname == NULL) {
4581                         dns_message_puttempname(client->message, &tname);
4582                         goto cleanup;
4583                 }
4584                 result = dns_name_concatenate(prefix, tname, fname, NULL);
4585                 if (result != ISC_R_SUCCESS) {
4586                         dns_message_puttempname(client->message, &tname);
4587                         if (result == ISC_R_NOSPACE) {
4588                                 /*
4589                                  * RFC2672, section 4.1, subsection 3c says
4590                                  * we should return YXDOMAIN if the constructed
4591                                  * name would be too long.
4592                                  */
4593                                 client->message->rcode = dns_rcode_yxdomain;
4594                         }
4595                         goto cleanup;
4596                 }
4597                 query_keepname(client, fname, dbuf);
4598                 /*
4599                  * Synthesize a CNAME for this DNAME.
4600                  *
4601                  * We want to synthesize a CNAME since if we don't
4602                  * then older software that doesn't understand DNAME
4603                  * will not chain like it should.
4604                  *
4605                  * We do not try to synthesize a signature because we hope
4606                  * that security aware servers will understand DNAME.  Also,
4607                  * even if we had an online key, making a signature
4608                  * on-the-fly is costly, and not really legitimate anyway
4609                  * since the synthesized CNAME is NOT in the zone.
4610                  */
4611                 dns_name_init(tname, NULL);
4612                 (void)query_addcnamelike(client, client->query.qname, fname,
4613                                          trdataset, &tname,
4614                                          dns_rdatatype_cname);
4615                 if (tname != NULL)
4616                         dns_message_puttempname(client->message, &tname);
4617                 /*
4618                  * Switch to the new qname and restart.
4619                  */
4620                 ns_client_qnamereplace(client, fname);
4621                 fname = NULL;
4622                 want_restart = ISC_TRUE;
4623                 if (!WANTRECURSION(client))
4624                         options |= DNS_GETDB_NOLOG;
4625                 goto addauth;
4626         default:
4627                 /*
4628                  * Something has gone wrong.
4629                  */
4630                 QUERY_ERROR(DNS_R_SERVFAIL);
4631                 goto cleanup;
4632         }
4633
4634         if (WANTDNSSEC(client) &&
4635             (fname->attributes & DNS_NAMEATTR_WILDCARD) != 0)
4636         {
4637                 dns_fixedname_init(&wildcardname);
4638                 dns_name_copy(fname, dns_fixedname_name(&wildcardname), NULL);
4639                 need_wildcardproof = ISC_TRUE;
4640         }
4641
4642         if (type == dns_rdatatype_any) {
4643                 /*
4644                  * XXXRTH  Need to handle zonecuts with special case
4645                  * code.
4646                  */
4647                 n = 0;
4648                 rdsiter = NULL;
4649                 result = dns_db_allrdatasets(db, node, version, 0, &rdsiter);
4650                 if (result != ISC_R_SUCCESS) {
4651                         QUERY_ERROR(DNS_R_SERVFAIL);
4652                         goto cleanup;
4653                 }
4654                 /*
4655                  * Calling query_addrrset() with a non-NULL dbuf is going
4656                  * to either keep or release the name.  We don't want it to
4657                  * release fname, since we may have to call query_addrrset()
4658                  * more than once.  That means we have to call query_keepname()
4659                  * now, and pass a NULL dbuf to query_addrrset().
4660                  *
4661                  * If we do a query_addrrset() below, we must set fname to
4662                  * NULL before leaving this block, otherwise we might try to
4663                  * cleanup fname even though we're using it!
4664                  */
4665                 query_keepname(client, fname, dbuf);
4666                 tname = fname;
4667                 result = dns_rdatasetiter_first(rdsiter);
4668                 while (result == ISC_R_SUCCESS) {
4669                         dns_rdatasetiter_current(rdsiter, rdataset);
4670                         if (is_zone && qtype == dns_rdatatype_any &&
4671                             !dns_db_issecure(db) &&
4672                             dns_rdatatype_isdnssec(rdataset->type)) {
4673                                 /*
4674                                  * The zone is transitioning from insecure
4675                                  * to secure. Hide the dnssec records from
4676                                  * ANY queries.
4677                                  */
4678                                 dns_rdataset_disassociate(rdataset);
4679                         } else if ((qtype == dns_rdatatype_any ||
4680                              rdataset->type == qtype) && rdataset->type != 0) {
4681                                 if (NOQNAME(rdataset) && WANTDNSSEC(client))
4682                                         noqname = rdataset;
4683                                 else
4684                                         noqname = NULL;
4685                                 query_addrrset(client,
4686                                                fname != NULL ? &fname : &tname,
4687                                                &rdataset, NULL,
4688                                                NULL, DNS_SECTION_ANSWER);
4689                                 if (noqname != NULL)
4690                                         query_addnoqnameproof(client, noqname);
4691                                 n++;
4692                                 INSIST(tname != NULL);
4693                                 /*
4694                                  * rdataset is non-NULL only in certain
4695                                  * pathological cases involving DNAMEs.
4696                                  */
4697                                 if (rdataset != NULL)
4698                                         query_putrdataset(client, &rdataset);
4699                                 rdataset = query_newrdataset(client);
4700                                 if (rdataset == NULL)
4701                                         break;
4702                         } else {
4703                                 /*
4704                                  * We're not interested in this rdataset.
4705                                  */
4706                                 dns_rdataset_disassociate(rdataset);
4707                         }
4708                         result = dns_rdatasetiter_next(rdsiter);
4709                 }
4710
4711                 if (fname != NULL)
4712                         dns_message_puttempname(client->message, &fname);
4713
4714                 if (n == 0 && is_zone) {
4715                         /*
4716                          * We didn't match any rdatasets.
4717                          */
4718                         if (qtype == dns_rdatatype_rrsig &&
4719                             result == ISC_R_NOMORE) {
4720                                 /*
4721                                  * XXXRTH  If this is a secure zone and we
4722                                  * didn't find any SIGs, we should generate
4723                                  * an error unless we were searching for
4724                                  * glue.  Ugh.
4725                                  */
4726                                 if (!is_zone) {
4727                                         authoritative = ISC_FALSE;
4728                                         dns_rdatasetiter_destroy(&rdsiter);
4729                                         if (RECURSIONOK(client)) {
4730                                                 result = query_recurse(client,
4731                                                                        qtype,
4732                                                                        NULL,
4733                                                                        NULL,
4734                                                                        resuming);
4735                                                 if (result == ISC_R_SUCCESS)
4736                                                     client->query.attributes |=
4737                                                         NS_QUERYATTR_RECURSING;
4738                                                 else
4739                                                     RECURSE_ERROR(result);
4740                                         }
4741                                         goto addauth;
4742                                 }
4743                                 /*
4744                                  * We were searching for SIG records in
4745                                  * a nonsecure zone.  Send a "no error,
4746                                  * no data" response.
4747                                  */
4748                                 /*
4749                                  * Add SOA.
4750                                  */
4751                                 result = query_addsoa(client, db, version,
4752                                                       ISC_FALSE, ISC_FALSE);
4753                                 if (result == ISC_R_SUCCESS)
4754                                         result = ISC_R_NOMORE;
4755                         } else {
4756                                 /*
4757                                  * Something went wrong.
4758                                  */
4759                                 result = DNS_R_SERVFAIL;
4760                         }
4761                 }
4762                 dns_rdatasetiter_destroy(&rdsiter);
4763                 if (result != ISC_R_NOMORE) {
4764                         QUERY_ERROR(DNS_R_SERVFAIL);
4765                         goto cleanup;
4766                 }
4767         } else {
4768                 /*
4769                  * This is the "normal" case -- an ordinary question to which
4770                  * we know the answer.
4771                  */
4772                 if (sigrdataset != NULL)
4773                         sigrdatasetp = &sigrdataset;
4774                 else
4775                         sigrdatasetp = NULL;
4776                 if (NOQNAME(rdataset) && WANTDNSSEC(client))
4777                         noqname = rdataset;
4778                 else
4779                         noqname = NULL;
4780                 /*
4781                  * BIND 8 priming queries need the additional section.
4782                  */
4783                 if (is_zone && qtype == dns_rdatatype_ns &&
4784                     dns_name_equal(client->query.qname, dns_rootname))
4785                         client->query.attributes &= ~NS_QUERYATTR_NOADDITIONAL;
4786
4787                 query_addrrset(client, &fname, &rdataset, sigrdatasetp, dbuf,
4788                                DNS_SECTION_ANSWER);
4789                 if (noqname != NULL)
4790                         query_addnoqnameproof(client, noqname);
4791                 /*
4792                  * We shouldn't ever fail to add 'rdataset'
4793                  * because it's already in the answer.
4794                  */
4795                 INSIST(rdataset == NULL);
4796         }
4797
4798  addauth:
4799         CTRACE("query_find: addauth");
4800         /*
4801          * Add NS records to the authority section (if we haven't already
4802          * added them to the answer section).
4803          */
4804         if (!want_restart && !NOAUTHORITY(client)) {
4805                 if (is_zone) {
4806                         if (!((qtype == dns_rdatatype_ns ||
4807                                qtype == dns_rdatatype_any) &&
4808                               dns_name_equal(client->query.qname,
4809                                              dns_db_origin(db))))
4810                                 (void)query_addns(client, db, version);
4811                 } else if (qtype != dns_rdatatype_ns) {
4812                         if (fname != NULL)
4813                                 query_releasename(client, &fname);
4814                         query_addbestns(client);
4815                 }
4816         }
4817
4818         /*
4819          * Add NSEC records to the authority section if they're needed for
4820          * DNSSEC wildcard proofs.
4821          */
4822         if (need_wildcardproof && dns_db_issecure(db))
4823                 query_addwildcardproof(client, db, version,
4824                                        dns_fixedname_name(&wildcardname),
4825                                        ISC_TRUE);
4826  cleanup:
4827         CTRACE("query_find: cleanup");
4828         /*
4829          * General cleanup.
4830          */
4831         if (rdataset != NULL)
4832                 query_putrdataset(client, &rdataset);
4833         if (sigrdataset != NULL)
4834                 query_putrdataset(client, &sigrdataset);
4835         if (fname != NULL)
4836                 query_releasename(client, &fname);
4837         if (node != NULL)
4838                 dns_db_detachnode(db, &node);
4839         if (db != NULL)
4840                 dns_db_detach(&db);
4841         if (zone != NULL)
4842                 dns_zone_detach(&zone);
4843         if (zdb != NULL) {
4844                 query_putrdataset(client, &zrdataset);
4845                 if (zsigrdataset != NULL)
4846                         query_putrdataset(client, &zsigrdataset);
4847                 if (zfname != NULL)
4848                         query_releasename(client, &zfname);
4849                 dns_db_detach(&zdb);
4850         }
4851         if (event != NULL)
4852                 isc_event_free(ISC_EVENT_PTR(&event));
4853
4854         /*
4855          * AA bit.
4856          */
4857         if (client->query.restarts == 0 && !authoritative) {
4858                 /*
4859                  * We're not authoritative, so we must ensure the AA bit
4860                  * isn't set.
4861                  */
4862                 client->message->flags &= ~DNS_MESSAGEFLAG_AA;
4863         }
4864
4865         /*
4866          * Restart the query?
4867          */
4868         if (want_restart && client->query.restarts < MAX_RESTARTS) {
4869                 client->query.restarts++;
4870                 goto restart;
4871         }
4872
4873         if (eresult != ISC_R_SUCCESS &&
4874             (!PARTIALANSWER(client) || WANTRECURSION(client))) {
4875                 if (eresult == DNS_R_DUPLICATE || eresult == DNS_R_DROP) {
4876                         /*
4877                          * This was a duplicate query that we are
4878                          * recursing on.  Don't send a response now.
4879                          * The original query will still cause a response.
4880                          */
4881                         query_next(client, eresult);
4882                 } else {
4883                         /*
4884                          * If we don't have any answer to give the client,
4885                          * or if the client requested recursion and thus wanted
4886                          * the complete answer, send an error response.
4887                          */
4888                         INSIST(line >= 0);
4889                         query_error(client, eresult, line);
4890                 }
4891                 ns_client_detach(&client);
4892         } else if (!RECURSING(client)) {
4893                 /*
4894                  * We are done.  Set up sortlist data for the message
4895                  * rendering code, make a final tweak to the AA bit if the
4896                  * auth-nxdomain config option says so, then render and
4897                  * send the response.
4898                  */
4899                 setup_query_sortlist(client);
4900
4901                 /*
4902                  * If this is a referral and the answer to the question
4903                  * is in the glue sort it to the start of the additional
4904                  * section.
4905                  */
4906                 if (ISC_LIST_EMPTY(client->message->sections[DNS_SECTION_ANSWER]) &&
4907                     client->message->rcode == dns_rcode_noerror &&
4908                     (qtype == dns_rdatatype_a || qtype == dns_rdatatype_aaaa))
4909                         answer_in_glue(client, qtype);
4910
4911                 if (client->message->rcode == dns_rcode_nxdomain &&
4912                     client->view->auth_nxdomain == ISC_TRUE)
4913                         client->message->flags |= DNS_MESSAGEFLAG_AA;
4914
4915                 /*
4916                  * If the response is somehow unexpected for the client and this
4917                  * is a result of recursion, return an error to the caller
4918                  * to indicate it may need to be logged.
4919                  */
4920                 if (resuming &&
4921                     (ISC_LIST_EMPTY(client->message->sections[DNS_SECTION_ANSWER]) ||
4922                      client->message->rcode != dns_rcode_noerror))
4923                         eresult = ISC_R_FAILURE;
4924
4925                 query_send(client);
4926                 ns_client_detach(&client);
4927         }
4928         CTRACE("query_find: done");
4929
4930         return (eresult);
4931 }
4932
4933 static inline void
4934 log_query(ns_client_t *client, unsigned int flags, unsigned int extflags) {
4935         char namebuf[DNS_NAME_FORMATSIZE];
4936         char typename[DNS_RDATATYPE_FORMATSIZE];
4937         char classname[DNS_RDATACLASS_FORMATSIZE];
4938         dns_rdataset_t *rdataset;
4939         int level = ISC_LOG_INFO;
4940
4941         if (! isc_log_wouldlog(ns_g_lctx, level))
4942                 return;
4943
4944         rdataset = ISC_LIST_HEAD(client->query.qname->list);
4945         INSIST(rdataset != NULL);
4946         dns_name_format(client->query.qname, namebuf, sizeof(namebuf));
4947         dns_rdataclass_format(rdataset->rdclass, classname, sizeof(classname));
4948         dns_rdatatype_format(rdataset->type, typename, sizeof(typename));
4949
4950         ns_client_log(client, NS_LOGCATEGORY_QUERIES, NS_LOGMODULE_QUERY,
4951                       level, "query: %s %s %s %s%s%s%s%s", namebuf, classname,
4952                       typename, WANTRECURSION(client) ? "+" : "-",
4953                       (client->signer != NULL) ? "S": "",
4954                       (client->opt != NULL) ? "E" : "",
4955                       ((extflags & DNS_MESSAGEEXTFLAG_DO) != 0) ? "D" : "",
4956                       ((flags & DNS_MESSAGEFLAG_CD) != 0) ? "C" : "");
4957 }
4958
4959 static inline void
4960 log_queryerror(ns_client_t *client, isc_result_t result, int line, int level) {
4961         char namebuf[DNS_NAME_FORMATSIZE];
4962         char typename[DNS_RDATATYPE_FORMATSIZE];
4963         char classname[DNS_RDATACLASS_FORMATSIZE];
4964         const char *namep, *typep, *classp, *sep1, *sep2;
4965         dns_rdataset_t *rdataset;
4966
4967         if (!isc_log_wouldlog(ns_g_lctx, level))
4968                 return;
4969
4970         namep = typep = classp = sep1 = sep2 = "";
4971
4972         /*
4973          * Query errors can happen for various reasons.  In some cases we cannot
4974          * even assume the query contains a valid question section, so we should
4975          * expect exceptional cases.
4976          */
4977         if (client->query.origqname != NULL) {
4978                 dns_name_format(client->query.origqname, namebuf,
4979                                 sizeof(namebuf));
4980                 namep = namebuf;
4981                 sep1 = " for ";
4982
4983                 rdataset = ISC_LIST_HEAD(client->query.origqname->list);
4984                 if (rdataset != NULL) {
4985                         dns_rdataclass_format(rdataset->rdclass, classname,
4986                                               sizeof(classname));
4987                         classp = classname;
4988                         dns_rdatatype_format(rdataset->type, typename,
4989                                              sizeof(typename));
4990                         typep = typename;
4991                         sep2 = "/";
4992                 }
4993         }
4994
4995         ns_client_log(client, NS_LOGCATEGORY_QUERY_EERRORS, NS_LOGMODULE_QUERY,
4996                       level, "query failed (%s)%s%s%s%s%s%s at %s:%d",
4997                       isc_result_totext(result), sep1, namep, sep2,
4998                       classp, sep2, typep, __FILE__, line);
4999 }
5000
5001 void
5002 ns_query_start(ns_client_t *client) {
5003         isc_result_t result;
5004         dns_message_t *message = client->message;
5005         dns_rdataset_t *rdataset;
5006         ns_client_t *qclient;
5007         dns_rdatatype_t qtype;
5008         unsigned int saved_extflags = client->extflags;
5009         unsigned int saved_flags = client->message->flags;
5010         isc_boolean_t want_ad;
5011
5012         CTRACE("ns_query_start");
5013
5014         /*
5015          * Test only.
5016          */
5017         if (ns_g_clienttest && (client->attributes & NS_CLIENTATTR_TCP) == 0)
5018                 RUNTIME_CHECK(ns_client_replace(client) == ISC_R_SUCCESS);
5019
5020         /*
5021          * Ensure that appropriate cleanups occur.
5022          */
5023         client->next = query_next_callback;
5024
5025         /*
5026          * Behave as if we don't support DNSSEC if not enabled.
5027          */
5028         if (!client->view->enablednssec) {
5029                 message->flags &= ~DNS_MESSAGEFLAG_CD;
5030                 client->extflags &= ~DNS_MESSAGEEXTFLAG_DO;
5031                 if (client->opt != NULL)
5032                         client->opt->ttl &= ~DNS_MESSAGEEXTFLAG_DO;
5033         }
5034
5035         if ((message->flags & DNS_MESSAGEFLAG_RD) != 0)
5036                 client->query.attributes |= NS_QUERYATTR_WANTRECURSION;
5037
5038         if ((client->extflags & DNS_MESSAGEEXTFLAG_DO) != 0)
5039                 client->attributes |= NS_CLIENTATTR_WANTDNSSEC;
5040
5041         if (client->view->minimalresponses)
5042                 client->query.attributes |= (NS_QUERYATTR_NOAUTHORITY |
5043                                              NS_QUERYATTR_NOADDITIONAL);
5044
5045         if ((client->view->cachedb == NULL)
5046             || (!client->view->additionalfromcache)) {
5047                 /*
5048                  * We don't have a cache.  Turn off cache support and
5049                  * recursion.
5050                  */
5051                 client->query.attributes &=
5052                         ~(NS_QUERYATTR_RECURSIONOK|NS_QUERYATTR_CACHEOK);
5053         } else if ((client->attributes & NS_CLIENTATTR_RA) == 0 ||
5054                    (message->flags & DNS_MESSAGEFLAG_RD) == 0) {
5055                 /*
5056                  * If the client isn't allowed to recurse (due to
5057                  * "recursion no", the allow-recursion ACL, or the
5058                  * lack of a resolver in this view), or if it
5059                  * doesn't want recursion, turn recursion off.
5060                  */
5061                 client->query.attributes &= ~NS_QUERYATTR_RECURSIONOK;
5062         }
5063
5064         /*
5065          * Get the question name.
5066          */
5067         result = dns_message_firstname(message, DNS_SECTION_QUESTION);
5068         if (result != ISC_R_SUCCESS) {
5069                 query_error(client, result, __LINE__);
5070                 return;
5071         }
5072         dns_message_currentname(message, DNS_SECTION_QUESTION,
5073                                 &client->query.qname);
5074         client->query.origqname = client->query.qname;
5075         result = dns_message_nextname(message, DNS_SECTION_QUESTION);
5076         if (result != ISC_R_NOMORE) {
5077                 if (result == ISC_R_SUCCESS) {
5078                         /*
5079                          * There's more than one QNAME in the question
5080                          * section.
5081                          */
5082                         query_error(client, DNS_R_FORMERR, __LINE__);
5083                 } else
5084                         query_error(client, result, __LINE__);
5085                 return;
5086         }
5087
5088         if (ns_g_server->log_queries)
5089                 log_query(client, saved_flags, saved_extflags);
5090
5091         /*
5092          * Check for multiple question queries, since edns1 is dead.
5093          */
5094         if (message->counts[DNS_SECTION_QUESTION] > 1) {
5095                 query_error(client, DNS_R_FORMERR, __LINE__);
5096                 return;
5097         }
5098
5099         /*
5100          * Check for meta-queries like IXFR and AXFR.
5101          */
5102         rdataset = ISC_LIST_HEAD(client->query.qname->list);
5103         INSIST(rdataset != NULL);
5104         qtype = rdataset->type;
5105         dns_rdatatypestats_increment(ns_g_server->rcvquerystats, qtype);
5106         if (dns_rdatatype_ismeta(qtype)) {
5107                 switch (qtype) {
5108                 case dns_rdatatype_any:
5109                         break; /* Let query_find handle it. */
5110                 case dns_rdatatype_ixfr:
5111                 case dns_rdatatype_axfr:
5112                         ns_xfr_start(client, rdataset->type);
5113                         return;
5114                 case dns_rdatatype_maila:
5115                 case dns_rdatatype_mailb:
5116                         query_error(client, DNS_R_NOTIMP, __LINE__);
5117                         return;
5118                 case dns_rdatatype_tkey:
5119                         result = dns_tkey_processquery(client->message,
5120                                                 ns_g_server->tkeyctx,
5121                                                 client->view->dynamickeys);
5122                         if (result == ISC_R_SUCCESS)
5123                                 query_send(client);
5124                         else
5125                                 query_error(client, result, __LINE__);
5126                         return;
5127                 default: /* TSIG, etc. */
5128                         query_error(client, DNS_R_FORMERR, __LINE__);
5129                         return;
5130                 }
5131         }
5132
5133         /*
5134          * Turn on minimal response for DNSKEY and DS queries.
5135          */
5136         if (qtype == dns_rdatatype_dnskey || qtype == dns_rdatatype_ds)
5137                 client->query.attributes |= (NS_QUERYATTR_NOAUTHORITY |
5138                                              NS_QUERYATTR_NOADDITIONAL);
5139
5140         /*
5141          * Turn on minimal responses for EDNS/UDP bufsize 512 queries.
5142          */
5143         if (client->opt != NULL && client->udpsize <= 512U &&
5144             (client->attributes & NS_CLIENTATTR_TCP) == 0)
5145                 client->query.attributes |= (NS_QUERYATTR_NOAUTHORITY |
5146                                              NS_QUERYATTR_NOADDITIONAL);
5147
5148         /*
5149          * If the client has requested that DNSSEC checking be disabled,
5150          * allow lookups to return pending data and instruct the resolver
5151          * to return data before validation has completed.
5152          *
5153          * We don't need to set DNS_DBFIND_PENDINGOK when validation is
5154          * disabled as there will be no pending data.
5155          */
5156         if (message->flags & DNS_MESSAGEFLAG_CD ||
5157             qtype == dns_rdatatype_rrsig)
5158         {
5159                 client->query.dboptions |= DNS_DBFIND_PENDINGOK;
5160                 client->query.fetchoptions |= DNS_FETCHOPT_NOVALIDATE;
5161         } else if (!client->view->enablevalidation)
5162                 client->query.fetchoptions |= DNS_FETCHOPT_NOVALIDATE;
5163
5164         /*
5165          * Allow glue NS records to be added to the authority section
5166          * if the answer is secure.
5167          */
5168         if (message->flags & DNS_MESSAGEFLAG_CD)
5169                 client->query.attributes &= ~NS_QUERYATTR_SECURE;
5170
5171         /*
5172          * Set 'want_ad' if the client has set AD in the query.
5173          * This allows AD to be returned on queries without DO set.
5174          */
5175         if ((message->flags & DNS_MESSAGEFLAG_AD) != 0)
5176                 want_ad = ISC_TRUE;
5177         else
5178                 want_ad = ISC_FALSE;
5179
5180         /*
5181          * This is an ordinary query.
5182          */
5183         result = dns_message_reply(message, ISC_TRUE);
5184         if (result != ISC_R_SUCCESS) {
5185                 query_next(client, result);
5186                 return;
5187         }
5188
5189         /*
5190          * Assume authoritative response until it is known to be
5191          * otherwise.
5192          */
5193         message->flags |= DNS_MESSAGEFLAG_AA;
5194
5195         /*
5196          * Set AD.  We must clear it if we add non-validated data to a
5197          * response.
5198          */
5199         if (WANTDNSSEC(client) || want_ad)
5200                 message->flags |= DNS_MESSAGEFLAG_AD;
5201
5202         qclient = NULL;
5203         ns_client_attach(client, &qclient);
5204         (void)query_find(qclient, NULL, qtype);
5205 }