]> CyberLeo.Net >> Repos - FreeBSD/releng/8.2.git/blob - contrib/bind9/bin/named/query.c
Fix a problem whereby a corrupt DNS record can cause named to crash. [11:06]
[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                         if (sigrdataset != NULL &&
1284                             dns_rdataset_isassociated(sigrdataset))
1285                                 dns_rdataset_disassociate(sigrdataset);
1286                 }
1287                 if (result == ISC_R_SUCCESS) {
1288                         mname = NULL;
1289                         if (!query_isduplicate(client, fname,
1290                                                dns_rdatatype_a, &mname)) {
1291                                 if (mname != NULL) {
1292                                         query_releasename(client, &fname);
1293                                         fname = mname;
1294                                 } else
1295                                         need_addname = ISC_TRUE;
1296                                 ISC_LIST_APPEND(fname->list, rdataset, link);
1297                                 added_something = ISC_TRUE;
1298                                 if (sigrdataset != NULL &&
1299                                     dns_rdataset_isassociated(sigrdataset))
1300                                 {
1301                                         ISC_LIST_APPEND(fname->list,
1302                                                         sigrdataset, link);
1303                                         sigrdataset =
1304                                                 query_newrdataset(client);
1305                                 }
1306                                 rdataset = query_newrdataset(client);
1307                                 if (rdataset == NULL)
1308                                         goto addname;
1309                                 if (WANTDNSSEC(client) && sigrdataset == NULL)
1310                                         goto addname;
1311                         } else {
1312                                 dns_rdataset_disassociate(rdataset);
1313                                 if (sigrdataset != NULL &&
1314                                     dns_rdataset_isassociated(sigrdataset))
1315                                         dns_rdataset_disassociate(sigrdataset);
1316                         }
1317                 }
1318                 result = dns_db_findrdataset(db, node, version,
1319                                              dns_rdatatype_aaaa, 0,
1320                                              client->now, rdataset,
1321                                              sigrdataset);
1322                 if (result == DNS_R_NCACHENXDOMAIN)
1323                         goto addname;
1324                 if (result == DNS_R_NCACHENXRRSET) {
1325                         dns_rdataset_disassociate(rdataset);
1326                         if (sigrdataset != NULL &&
1327                             dns_rdataset_isassociated(sigrdataset))
1328                                 dns_rdataset_disassociate(sigrdataset);
1329                 }
1330                 if (result == ISC_R_SUCCESS) {
1331                         mname = NULL;
1332                         if (!query_isduplicate(client, fname,
1333                                                dns_rdatatype_aaaa, &mname)) {
1334                                 if (mname != NULL) {
1335                                         query_releasename(client, &fname);
1336                                         fname = mname;
1337                                 } else
1338                                         need_addname = ISC_TRUE;
1339                                 ISC_LIST_APPEND(fname->list, rdataset, link);
1340                                 added_something = ISC_TRUE;
1341                                 if (sigrdataset != NULL &&
1342                                     dns_rdataset_isassociated(sigrdataset))
1343                                 {
1344                                         ISC_LIST_APPEND(fname->list,
1345                                                         sigrdataset, link);
1346                                         sigrdataset = NULL;
1347                                 }
1348                                 rdataset = NULL;
1349                         }
1350                 }
1351         }
1352
1353  addname:
1354         CTRACE("query_addadditional: addname");
1355         /*
1356          * If we haven't added anything, then we're done.
1357          */
1358         if (!added_something)
1359                 goto cleanup;
1360
1361         /*
1362          * We may have added our rdatasets to an existing name, if so, then
1363          * need_addname will be ISC_FALSE.  Whether we used an existing name
1364          * or a new one, we must set fname to NULL to prevent cleanup.
1365          */
1366         if (need_addname)
1367                 dns_message_addname(client->message, fname,
1368                                     DNS_SECTION_ADDITIONAL);
1369         fname = NULL;
1370
1371         /*
1372          * In a few cases, we want to add additional data for additional
1373          * data.  It's simpler to just deal with special cases here than
1374          * to try to create a general purpose mechanism and allow the
1375          * rdata implementations to do it themselves.
1376          *
1377          * This involves recursion, but the depth is limited.  The
1378          * most complex case is adding a SRV rdataset, which involves
1379          * recursing to add address records, which in turn can cause
1380          * recursion to add KEYs.
1381          */
1382         if (type == dns_rdatatype_srv && trdataset != NULL) {
1383                 /*
1384                  * If we're adding SRV records to the additional data
1385                  * section, it's helpful if we add the SRV additional data
1386                  * as well.
1387                  */
1388                 eresult = dns_rdataset_additionaldata(trdataset,
1389                                                       query_addadditional,
1390                                                       client);
1391         }
1392
1393  cleanup:
1394         CTRACE("query_addadditional: cleanup");
1395         query_putrdataset(client, &rdataset);
1396         if (sigrdataset != NULL)
1397                 query_putrdataset(client, &sigrdataset);
1398         if (fname != NULL)
1399                 query_releasename(client, &fname);
1400         if (node != NULL)
1401                 dns_db_detachnode(db, &node);
1402         if (db != NULL)
1403                 dns_db_detach(&db);
1404         if (zone != NULL)
1405                 dns_zone_detach(&zone);
1406
1407         CTRACE("query_addadditional: done");
1408         return (eresult);
1409 }
1410
1411 static inline void
1412 query_discardcache(ns_client_t *client, dns_rdataset_t *rdataset_base,
1413                    dns_rdatasetadditional_t additionaltype,
1414                    dns_rdatatype_t type, dns_zone_t **zonep, dns_db_t **dbp,
1415                    dns_dbversion_t **versionp, dns_dbnode_t **nodep,
1416                    dns_name_t *fname)
1417 {
1418         dns_rdataset_t *rdataset;
1419
1420         while  ((rdataset = ISC_LIST_HEAD(fname->list)) != NULL) {
1421                 ISC_LIST_UNLINK(fname->list, rdataset, link);
1422                 query_putrdataset(client, &rdataset);
1423         }
1424         if (*versionp != NULL)
1425                 dns_db_closeversion(*dbp, versionp, ISC_FALSE);
1426         if (*nodep != NULL)
1427                 dns_db_detachnode(*dbp, nodep);
1428         if (*dbp != NULL)
1429                 dns_db_detach(dbp);
1430         if (*zonep != NULL)
1431                 dns_zone_detach(zonep);
1432         (void)dns_rdataset_putadditional(client->view->acache, rdataset_base,
1433                                          additionaltype, type);
1434 }
1435
1436 static inline isc_result_t
1437 query_iscachevalid(dns_zone_t *zone, dns_db_t *db, dns_db_t *db0,
1438                    dns_dbversion_t *version)
1439 {
1440         isc_result_t result = ISC_R_SUCCESS;
1441         dns_dbversion_t *version_current = NULL;
1442         dns_db_t *db_current = db0;
1443
1444         if (db_current == NULL) {
1445                 result = dns_zone_getdb(zone, &db_current);
1446                 if (result != ISC_R_SUCCESS)
1447                         return (result);
1448         }
1449         dns_db_currentversion(db_current, &version_current);
1450         if (db_current != db || version_current != version) {
1451                 result = ISC_R_FAILURE;
1452                 goto cleanup;
1453         }
1454
1455  cleanup:
1456         dns_db_closeversion(db_current, &version_current, ISC_FALSE);
1457         if (db0 == NULL && db_current != NULL)
1458                 dns_db_detach(&db_current);
1459
1460         return (result);
1461 }
1462
1463 static isc_result_t
1464 query_addadditional2(void *arg, dns_name_t *name, dns_rdatatype_t qtype) {
1465         client_additionalctx_t *additionalctx = arg;
1466         dns_rdataset_t *rdataset_base;
1467         ns_client_t *client;
1468         isc_result_t result, eresult;
1469         dns_dbnode_t *node, *cnode;
1470         dns_db_t *db, *cdb;
1471         dns_name_t *fname, *mname0, cfname;
1472         dns_rdataset_t *rdataset, *sigrdataset;
1473         dns_rdataset_t *crdataset, *crdataset_next;
1474         isc_buffer_t *dbuf;
1475         isc_buffer_t b;
1476         dns_dbversion_t *version, *cversion;
1477         isc_boolean_t added_something, need_addname, needadditionalcache;
1478         isc_boolean_t need_sigrrset;
1479         dns_zone_t *zone;
1480         dns_rdatatype_t type;
1481         dns_rdatasetadditional_t additionaltype;
1482
1483         if (qtype != dns_rdatatype_a) {
1484                 /*
1485                  * This function is optimized for "address" types.  For other
1486                  * types, use a generic routine.
1487                  * XXX: ideally, this function should be generic enough.
1488                  */
1489                 return (query_addadditional(additionalctx->client,
1490                                             name, qtype));
1491         }
1492
1493         /*
1494          * Initialization.
1495          */
1496         rdataset_base = additionalctx->rdataset;
1497         client = additionalctx->client;
1498         REQUIRE(NS_CLIENT_VALID(client));
1499         eresult = ISC_R_SUCCESS;
1500         fname = NULL;
1501         rdataset = NULL;
1502         sigrdataset = NULL;
1503         db = NULL;
1504         cdb = NULL;
1505         version = NULL;
1506         cversion = NULL;
1507         node = NULL;
1508         cnode = NULL;
1509         added_something = ISC_FALSE;
1510         need_addname = ISC_FALSE;
1511         zone = NULL;
1512         needadditionalcache = ISC_FALSE;
1513         additionaltype = dns_rdatasetadditional_fromauth;
1514         dns_name_init(&cfname, NULL);
1515
1516         CTRACE("query_addadditional2");
1517
1518         /*
1519          * We treat type A additional section processing as if it
1520          * were "any address type" additional section processing.
1521          * To avoid multiple lookups, we do an 'any' database
1522          * lookup and iterate over the node.
1523          * XXXJT: this approach can cause a suboptimal result when the cache
1524          * DB only has partial address types and the glue DB has remaining
1525          * ones.
1526          */
1527         type = dns_rdatatype_any;
1528
1529         /*
1530          * Get some resources.
1531          */
1532         dbuf = query_getnamebuf(client);
1533         if (dbuf == NULL)
1534                 goto cleanup;
1535         fname = query_newname(client, dbuf, &b);
1536         if (fname == NULL)
1537                 goto cleanup;
1538         dns_name_setbuffer(&cfname, &b); /* share the buffer */
1539
1540         /* Check additional cache */
1541         result = dns_rdataset_getadditional(rdataset_base, additionaltype,
1542                                             type, client->view->acache, &zone,
1543                                             &cdb, &cversion, &cnode, &cfname,
1544                                             client->message, client->now);
1545         if (result != ISC_R_SUCCESS)
1546                 goto findauthdb;
1547         if (zone == NULL) {
1548                 CTRACE("query_addadditional2: auth zone not found");
1549                 goto try_cache;
1550         }
1551
1552         /* Is the cached DB up-to-date? */
1553         result = query_iscachevalid(zone, cdb, NULL, cversion);
1554         if (result != ISC_R_SUCCESS) {
1555                 CTRACE("query_addadditional2: old auth additional cache");
1556                 query_discardcache(client, rdataset_base, additionaltype,
1557                                    type, &zone, &cdb, &cversion, &cnode,
1558                                    &cfname);
1559                 goto findauthdb;
1560         }
1561
1562         if (cnode == NULL) {
1563                 /*
1564                  * We have a negative cache.  We don't have to check the zone
1565                  * ACL, since the result (not using this zone) would be same
1566                  * regardless of the result.
1567                  */
1568                 CTRACE("query_addadditional2: negative auth additional cache");
1569                 dns_db_closeversion(cdb, &cversion, ISC_FALSE);
1570                 dns_db_detach(&cdb);
1571                 dns_zone_detach(&zone);
1572                 goto try_cache;
1573         }
1574
1575         result = query_validatezonedb(client, name, qtype, DNS_GETDB_NOLOG,
1576                                       zone, cdb, NULL);
1577         if (result != ISC_R_SUCCESS) {
1578                 query_discardcache(client, rdataset_base, additionaltype,
1579                                    type, &zone, &cdb, &cversion, &cnode,
1580                                    &cfname);
1581                 goto try_cache;
1582         }
1583
1584         /* We've got an active cache. */
1585         CTRACE("query_addadditional2: auth additional cache");
1586         dns_db_closeversion(cdb, &cversion, ISC_FALSE);
1587         db = cdb;
1588         node = cnode;
1589         dns_name_clone(&cfname, fname);
1590         query_keepname(client, fname, dbuf);
1591         goto foundcache;
1592
1593         /*
1594          * Look for a zone database that might contain authoritative
1595          * additional data.
1596          */
1597  findauthdb:
1598         result = query_getzonedb(client, name, qtype, DNS_GETDB_NOLOG,
1599                                  &zone, &db, &version);
1600         if (result != ISC_R_SUCCESS) {
1601                 /* Cache the negative result */
1602                 (void)dns_rdataset_setadditional(rdataset_base, additionaltype,
1603                                                  type, client->view->acache,
1604                                                  NULL, NULL, NULL, NULL,
1605                                                  NULL);
1606                 goto try_cache;
1607         }
1608
1609         CTRACE("query_addadditional2: db_find");
1610
1611         /*
1612          * Since we are looking for authoritative data, we do not set
1613          * the GLUEOK flag.  Glue will be looked for later, but not
1614          * necessarily in the same database.
1615          */
1616         node = NULL;
1617         result = dns_db_find(db, name, version, type, client->query.dboptions,
1618                              client->now, &node, fname, NULL, NULL);
1619         if (result == ISC_R_SUCCESS)
1620                 goto found;
1621
1622         /* Cache the negative result */
1623         (void)dns_rdataset_setadditional(rdataset_base, additionaltype,
1624                                          type, client->view->acache, zone, db,
1625                                          version, NULL, fname);
1626
1627         if (node != NULL)
1628                 dns_db_detachnode(db, &node);
1629         version = NULL;
1630         dns_db_detach(&db);
1631
1632         /*
1633          * No authoritative data was found.  The cache is our next best bet.
1634          */
1635
1636  try_cache:
1637         additionaltype = dns_rdatasetadditional_fromcache;
1638         result = query_getcachedb(client, name, qtype, &db, DNS_GETDB_NOLOG);
1639         if (result != ISC_R_SUCCESS)
1640                 /*
1641                  * Most likely the client isn't allowed to query the cache.
1642                  */
1643                 goto try_glue;
1644
1645         result = dns_db_find(db, name, version, type,
1646                              client->query.dboptions |
1647                              DNS_DBFIND_GLUEOK | DNS_DBFIND_ADDITIONALOK,
1648                              client->now, &node, fname, NULL, NULL);
1649         if (result == ISC_R_SUCCESS)
1650                 goto found;
1651
1652         if (node != NULL)
1653                 dns_db_detachnode(db, &node);
1654         dns_db_detach(&db);
1655
1656  try_glue:
1657         /*
1658          * No cached data was found.  Glue is our last chance.
1659          * RFC1035 sayeth:
1660          *
1661          *      NS records cause both the usual additional section
1662          *      processing to locate a type A record, and, when used
1663          *      in a referral, a special search of the zone in which
1664          *      they reside for glue information.
1665          *
1666          * This is the "special search".  Note that we must search
1667          * the zone where the NS record resides, not the zone it
1668          * points to, and that we only do the search in the delegation
1669          * case (identified by client->query.gluedb being set).
1670          */
1671         if (client->query.gluedb == NULL)
1672                 goto cleanup;
1673
1674         /*
1675          * Don't poison caches using the bailiwick protection model.
1676          */
1677         if (!dns_name_issubdomain(name, dns_db_origin(client->query.gluedb)))
1678                 goto cleanup;
1679
1680         /* Check additional cache */
1681         additionaltype = dns_rdatasetadditional_fromglue;
1682         result = dns_rdataset_getadditional(rdataset_base, additionaltype,
1683                                             type, client->view->acache, NULL,
1684                                             &cdb, &cversion, &cnode, &cfname,
1685                                             client->message, client->now);
1686         if (result != ISC_R_SUCCESS)
1687                 goto findglue;
1688
1689         result = query_iscachevalid(zone, cdb, client->query.gluedb, cversion);
1690         if (result != ISC_R_SUCCESS) {
1691                 CTRACE("query_addadditional2: old glue additional cache");
1692                 query_discardcache(client, rdataset_base, additionaltype,
1693                                    type, &zone, &cdb, &cversion, &cnode,
1694                                    &cfname);
1695                 goto findglue;
1696         }
1697
1698         if (cnode == NULL) {
1699                 /* We have a negative cache. */
1700                 CTRACE("query_addadditional2: negative glue additional cache");
1701                 dns_db_closeversion(cdb, &cversion, ISC_FALSE);
1702                 dns_db_detach(&cdb);
1703                 goto cleanup;
1704         }
1705
1706         /* Cache hit. */
1707         CTRACE("query_addadditional2: glue additional cache");
1708         dns_db_closeversion(cdb, &cversion, ISC_FALSE);
1709         db = cdb;
1710         node = cnode;
1711         dns_name_clone(&cfname, fname);
1712         query_keepname(client, fname, dbuf);
1713         goto foundcache;
1714
1715  findglue:
1716         dns_db_attach(client->query.gluedb, &db);
1717         result = dns_db_find(db, name, version, type,
1718                              client->query.dboptions | DNS_DBFIND_GLUEOK,
1719                              client->now, &node, fname, NULL, NULL);
1720         if (!(result == ISC_R_SUCCESS ||
1721               result == DNS_R_ZONECUT ||
1722               result == DNS_R_GLUE)) {
1723                 /* cache the negative result */
1724                 (void)dns_rdataset_setadditional(rdataset_base, additionaltype,
1725                                                  type, client->view->acache,
1726                                                  NULL, db, version, NULL,
1727                                                  fname);
1728                 goto cleanup;
1729         }
1730
1731  found:
1732         /*
1733          * We have found a DB node to iterate over from a DB.
1734          * We are going to look for address RRsets (i.e., A and AAAA) in the DB
1735          * node we've just found.  We'll then store the complete information
1736          * in the additional data cache.
1737          */
1738         dns_name_clone(fname, &cfname);
1739         query_keepname(client, fname, dbuf);
1740         needadditionalcache = ISC_TRUE;
1741
1742         rdataset = query_newrdataset(client);
1743         if (rdataset == NULL)
1744                 goto cleanup;
1745
1746         sigrdataset = query_newrdataset(client);
1747         if (sigrdataset == NULL)
1748                 goto cleanup;
1749
1750         /*
1751          * Find A RRset with sig RRset.  Even if we don't find a sig RRset
1752          * for a client using DNSSEC, we'll continue the process to make a
1753          * complete list to be cached.  However, we need to cancel the
1754          * caching when something unexpected happens, in order to avoid
1755          * caching incomplete information.
1756          */
1757         result = dns_db_findrdataset(db, node, version, dns_rdatatype_a, 0,
1758                                      client->now, rdataset, sigrdataset);
1759         /*
1760          * If we can't promote glue/pending from the cache to secure
1761          * then drop it.
1762          */
1763         if (result == ISC_R_SUCCESS &&
1764             additionaltype == dns_rdatasetadditional_fromcache &&
1765             (DNS_TRUST_PENDING(rdataset->trust) ||
1766              DNS_TRUST_GLUE(rdataset->trust)) &&
1767             !validate(client, db, fname, rdataset, sigrdataset)) {
1768                 dns_rdataset_disassociate(rdataset);
1769                 if (dns_rdataset_isassociated(sigrdataset))
1770                         dns_rdataset_disassociate(sigrdataset);
1771                 result = ISC_R_NOTFOUND;
1772         }
1773         if (result == DNS_R_NCACHENXDOMAIN)
1774                 goto setcache;
1775         if (result == DNS_R_NCACHENXRRSET) {
1776                 dns_rdataset_disassociate(rdataset);
1777                 if (dns_rdataset_isassociated(sigrdataset))
1778                         dns_rdataset_disassociate(sigrdataset);
1779         }
1780         if (result == ISC_R_SUCCESS) {
1781                 /* Remember the result as a cache */
1782                 ISC_LIST_APPEND(cfname.list, rdataset, link);
1783                 if (dns_rdataset_isassociated(sigrdataset)) {
1784                         ISC_LIST_APPEND(cfname.list, sigrdataset, link);
1785                         sigrdataset = query_newrdataset(client);
1786                 }
1787                 rdataset = query_newrdataset(client);
1788                 if (sigrdataset == NULL || rdataset == NULL) {
1789                         /* do not cache incomplete information */
1790                         goto foundcache;
1791                 }
1792         }
1793
1794         /* Find AAAA RRset with sig RRset */
1795         result = dns_db_findrdataset(db, node, version, dns_rdatatype_aaaa,
1796                                      0, client->now, rdataset, sigrdataset);
1797         /*
1798          * If we can't promote glue/pending from the cache to secure
1799          * then drop it.
1800          */
1801         if (result == ISC_R_SUCCESS &&
1802             additionaltype == dns_rdatasetadditional_fromcache &&
1803             (DNS_TRUST_PENDING(rdataset->trust) ||
1804              DNS_TRUST_GLUE(rdataset->trust)) &&
1805             !validate(client, db, fname, rdataset, sigrdataset)) {
1806                 dns_rdataset_disassociate(rdataset);
1807                 if (dns_rdataset_isassociated(sigrdataset))
1808                         dns_rdataset_disassociate(sigrdataset);
1809                 result = ISC_R_NOTFOUND;
1810         }
1811         if (result == ISC_R_SUCCESS) {
1812                 ISC_LIST_APPEND(cfname.list, rdataset, link);
1813                 rdataset = NULL;
1814                 if (dns_rdataset_isassociated(sigrdataset)) {
1815                         ISC_LIST_APPEND(cfname.list, sigrdataset, link);
1816                         sigrdataset = NULL;
1817                 }
1818         }
1819
1820  setcache:
1821         /*
1822          * Set the new result in the cache if required.  We do not support
1823          * caching additional data from a cache DB.
1824          */
1825         if (needadditionalcache == ISC_TRUE &&
1826             (additionaltype == dns_rdatasetadditional_fromauth ||
1827              additionaltype == dns_rdatasetadditional_fromglue)) {
1828                 (void)dns_rdataset_setadditional(rdataset_base, additionaltype,
1829                                                  type, client->view->acache,
1830                                                  zone, db, version, node,
1831                                                  &cfname);
1832         }
1833
1834  foundcache:
1835         need_sigrrset = ISC_FALSE;
1836         mname0 = NULL;
1837         for (crdataset = ISC_LIST_HEAD(cfname.list);
1838              crdataset != NULL;
1839              crdataset = crdataset_next) {
1840                 dns_name_t *mname;
1841
1842                 crdataset_next = ISC_LIST_NEXT(crdataset, link);
1843
1844                 mname = NULL;
1845                 if (crdataset->type == dns_rdatatype_a ||
1846                     crdataset->type == dns_rdatatype_aaaa) {
1847                         if (!query_isduplicate(client, fname, crdataset->type,
1848                                                &mname)) {
1849                                 if (mname != NULL) {
1850                                         /*
1851                                          * A different type of this name is
1852                                          * already stored in the additional
1853                                          * section.  We'll reuse the name.
1854                                          * Note that this should happen at most
1855                                          * once.  Otherwise, fname->link could
1856                                          * leak below.
1857                                          */
1858                                         INSIST(mname0 == NULL);
1859
1860                                         query_releasename(client, &fname);
1861                                         fname = mname;
1862                                         mname0 = mname;
1863                                 } else
1864                                         need_addname = ISC_TRUE;
1865                                 ISC_LIST_UNLINK(cfname.list, crdataset, link);
1866                                 ISC_LIST_APPEND(fname->list, crdataset, link);
1867                                 added_something = ISC_TRUE;
1868                                 need_sigrrset = ISC_TRUE;
1869                         } else
1870                                 need_sigrrset = ISC_FALSE;
1871                 } else if (crdataset->type == dns_rdatatype_rrsig &&
1872                            need_sigrrset && WANTDNSSEC(client)) {
1873                         ISC_LIST_UNLINK(cfname.list, crdataset, link);
1874                         ISC_LIST_APPEND(fname->list, crdataset, link);
1875                         added_something = ISC_TRUE; /* just in case */
1876                         need_sigrrset = ISC_FALSE;
1877                 }
1878         }
1879
1880         CTRACE("query_addadditional2: addname");
1881
1882         /*
1883          * If we haven't added anything, then we're done.
1884          */
1885         if (!added_something)
1886                 goto cleanup;
1887
1888         /*
1889          * We may have added our rdatasets to an existing name, if so, then
1890          * need_addname will be ISC_FALSE.  Whether we used an existing name
1891          * or a new one, we must set fname to NULL to prevent cleanup.
1892          */
1893         if (need_addname)
1894                 dns_message_addname(client->message, fname,
1895                                     DNS_SECTION_ADDITIONAL);
1896         fname = NULL;
1897
1898  cleanup:
1899         CTRACE("query_addadditional2: cleanup");
1900
1901         if (rdataset != NULL)
1902                 query_putrdataset(client, &rdataset);
1903         if (sigrdataset != NULL)
1904                 query_putrdataset(client, &sigrdataset);
1905         while  ((crdataset = ISC_LIST_HEAD(cfname.list)) != NULL) {
1906                 ISC_LIST_UNLINK(cfname.list, crdataset, link);
1907                 query_putrdataset(client, &crdataset);
1908         }
1909         if (fname != NULL)
1910                 query_releasename(client, &fname);
1911         if (node != NULL)
1912                 dns_db_detachnode(db, &node);
1913         if (db != NULL)
1914                 dns_db_detach(&db);
1915         if (zone != NULL)
1916                 dns_zone_detach(&zone);
1917
1918         CTRACE("query_addadditional2: done");
1919         return (eresult);
1920 }
1921
1922 static inline void
1923 query_addrdataset(ns_client_t *client, dns_name_t *fname,
1924                   dns_rdataset_t *rdataset)
1925 {
1926         client_additionalctx_t additionalctx;
1927
1928         /*
1929          * Add 'rdataset' and any pertinent additional data to
1930          * 'fname', a name in the response message for 'client'.
1931          */
1932
1933         CTRACE("query_addrdataset");
1934
1935         ISC_LIST_APPEND(fname->list, rdataset, link);
1936
1937         if (client->view->order != NULL)
1938                 rdataset->attributes |= dns_order_find(client->view->order,
1939                                                        fname, rdataset->type,
1940                                                        rdataset->rdclass);
1941         rdataset->attributes |= DNS_RDATASETATTR_LOADORDER;
1942
1943         if (NOADDITIONAL(client))
1944                 return;
1945
1946         /*
1947          * Add additional data.
1948          *
1949          * We don't care if dns_rdataset_additionaldata() fails.
1950          */
1951         additionalctx.client = client;
1952         additionalctx.rdataset = rdataset;
1953         (void)dns_rdataset_additionaldata(rdataset, query_addadditional2,
1954                                           &additionalctx);
1955         CTRACE("query_addrdataset: done");
1956 }
1957
1958 static void
1959 query_addrrset(ns_client_t *client, dns_name_t **namep,
1960                dns_rdataset_t **rdatasetp, dns_rdataset_t **sigrdatasetp,
1961                isc_buffer_t *dbuf, dns_section_t section)
1962 {
1963         dns_name_t *name, *mname;
1964         dns_rdataset_t *rdataset, *mrdataset, *sigrdataset;
1965         isc_result_t result;
1966
1967         /*%
1968          * To the current response for 'client', add the answer RRset
1969          * '*rdatasetp' and an optional signature set '*sigrdatasetp', with
1970          * owner name '*namep', to section 'section', unless they are
1971          * already there.  Also add any pertinent additional data.
1972          *
1973          * If 'dbuf' is not NULL, then '*namep' is the name whose data is
1974          * stored in 'dbuf'.  In this case, query_addrrset() guarantees that
1975          * when it returns the name will either have been kept or released.
1976          */
1977         CTRACE("query_addrrset");
1978         name = *namep;
1979         rdataset = *rdatasetp;
1980         if (sigrdatasetp != NULL)
1981                 sigrdataset = *sigrdatasetp;
1982         else
1983                 sigrdataset = NULL;
1984         mname = NULL;
1985         mrdataset = NULL;
1986         result = dns_message_findname(client->message, section,
1987                                       name, rdataset->type, rdataset->covers,
1988                                       &mname, &mrdataset);
1989         if (result == ISC_R_SUCCESS) {
1990                 /*
1991                  * We've already got an RRset of the given name and type.
1992                  * There's nothing else to do;
1993                  */
1994                 CTRACE("query_addrrset: dns_message_findname succeeded: done");
1995                 if (dbuf != NULL)
1996                         query_releasename(client, namep);
1997                 return;
1998         } else if (result == DNS_R_NXDOMAIN) {
1999                 /*
2000                  * The name doesn't exist.
2001                  */
2002                 if (dbuf != NULL)
2003                         query_keepname(client, name, dbuf);
2004                 dns_message_addname(client->message, name, section);
2005                 *namep = NULL;
2006                 mname = name;
2007         } else {
2008                 RUNTIME_CHECK(result == DNS_R_NXRRSET);
2009                 if (dbuf != NULL)
2010                         query_releasename(client, namep);
2011         }
2012
2013         if (rdataset->trust != dns_trust_secure &&
2014             (section == DNS_SECTION_ANSWER ||
2015              section == DNS_SECTION_AUTHORITY))
2016                 client->query.attributes &= ~NS_QUERYATTR_SECURE;
2017         /*
2018          * Note: we only add SIGs if we've added the type they cover, so
2019          * we do not need to check if the SIG rdataset is already in the
2020          * response.
2021          */
2022         query_addrdataset(client, mname, rdataset);
2023         *rdatasetp = NULL;
2024         if (sigrdataset != NULL && dns_rdataset_isassociated(sigrdataset)) {
2025                 /*
2026                  * We have a signature.  Add it to the response.
2027                  */
2028                 ISC_LIST_APPEND(mname->list, sigrdataset, link);
2029                 *sigrdatasetp = NULL;
2030         }
2031         CTRACE("query_addrrset: done");
2032 }
2033
2034 static inline isc_result_t
2035 query_addsoa(ns_client_t *client, dns_db_t *db, dns_dbversion_t *version,
2036              isc_boolean_t zero_ttl, isc_boolean_t isassociated)
2037 {
2038         dns_name_t *name;
2039         dns_dbnode_t *node;
2040         isc_result_t result, eresult;
2041         dns_rdataset_t *rdataset = NULL, *sigrdataset = NULL;
2042         dns_rdataset_t **sigrdatasetp = NULL;
2043
2044         CTRACE("query_addsoa");
2045         /*
2046          * Initialization.
2047          */
2048         eresult = ISC_R_SUCCESS;
2049         name = NULL;
2050         rdataset = NULL;
2051         node = NULL;
2052
2053         /*
2054          * Don't add the SOA record for test which set "-T nosoa".
2055          */
2056         if (ns_g_nosoa && (!WANTDNSSEC(client) || !isassociated))
2057                 return (ISC_R_SUCCESS);
2058
2059         /*
2060          * Get resources and make 'name' be the database origin.
2061          */
2062         result = dns_message_gettempname(client->message, &name);
2063         if (result != ISC_R_SUCCESS)
2064                 return (result);
2065         dns_name_init(name, NULL);
2066         dns_name_clone(dns_db_origin(db), name);
2067         rdataset = query_newrdataset(client);
2068         if (rdataset == NULL) {
2069                 eresult = DNS_R_SERVFAIL;
2070                 goto cleanup;
2071         }
2072         if (WANTDNSSEC(client) && dns_db_issecure(db)) {
2073                 sigrdataset = query_newrdataset(client);
2074                 if (sigrdataset == NULL) {
2075                         eresult = DNS_R_SERVFAIL;
2076                         goto cleanup;
2077                 }
2078         }
2079
2080         /*
2081          * Find the SOA.
2082          */
2083         result = dns_db_getoriginnode(db, &node);
2084         if (result == ISC_R_SUCCESS) {
2085                 result = dns_db_findrdataset(db, node, version,
2086                                              dns_rdatatype_soa,
2087                                              0, client->now, rdataset,
2088                                              sigrdataset);
2089         } else {
2090                 dns_fixedname_t foundname;
2091                 dns_name_t *fname;
2092
2093                 dns_fixedname_init(&foundname);
2094                 fname = dns_fixedname_name(&foundname);
2095
2096                 result = dns_db_find(db, name, version, dns_rdatatype_soa,
2097                                      client->query.dboptions, 0, &node,
2098                                      fname, rdataset, sigrdataset);
2099         }
2100         if (result != ISC_R_SUCCESS) {
2101                 /*
2102                  * This is bad.  We tried to get the SOA RR at the zone top
2103                  * and it didn't work!
2104                  */
2105                 eresult = DNS_R_SERVFAIL;
2106         } else {
2107                 /*
2108                  * Extract the SOA MINIMUM.
2109                  */
2110                 dns_rdata_soa_t soa;
2111                 dns_rdata_t rdata = DNS_RDATA_INIT;
2112                 result = dns_rdataset_first(rdataset);
2113                 RUNTIME_CHECK(result == ISC_R_SUCCESS);
2114                 dns_rdataset_current(rdataset, &rdata);
2115                 result = dns_rdata_tostruct(&rdata, &soa, NULL);
2116                 if (result != ISC_R_SUCCESS)
2117                         goto cleanup;
2118
2119                 if (zero_ttl) {
2120                         rdataset->ttl = 0;
2121                         if (sigrdataset != NULL)
2122                                 sigrdataset->ttl = 0;
2123                 }
2124
2125                 /*
2126                  * Add the SOA and its SIG to the response, with the
2127                  * TTLs adjusted per RFC2308 section 3.
2128                  */
2129                 if (rdataset->ttl > soa.minimum)
2130                         rdataset->ttl = soa.minimum;
2131                 if (sigrdataset != NULL && sigrdataset->ttl > soa.minimum)
2132                         sigrdataset->ttl = soa.minimum;
2133
2134                 if (sigrdataset != NULL)
2135                         sigrdatasetp = &sigrdataset;
2136                 else
2137                         sigrdatasetp = NULL;
2138                 query_addrrset(client, &name, &rdataset, sigrdatasetp, NULL,
2139                                DNS_SECTION_AUTHORITY);
2140         }
2141
2142  cleanup:
2143         query_putrdataset(client, &rdataset);
2144         if (sigrdataset != NULL)
2145                 query_putrdataset(client, &sigrdataset);
2146         if (name != NULL)
2147                 query_releasename(client, &name);
2148         if (node != NULL)
2149                 dns_db_detachnode(db, &node);
2150
2151         return (eresult);
2152 }
2153
2154 static inline isc_result_t
2155 query_addns(ns_client_t *client, dns_db_t *db, dns_dbversion_t *version) {
2156         dns_name_t *name, *fname;
2157         dns_dbnode_t *node;
2158         isc_result_t result, eresult;
2159         dns_fixedname_t foundname;
2160         dns_rdataset_t *rdataset = NULL, *sigrdataset = NULL;
2161         dns_rdataset_t **sigrdatasetp = NULL;
2162
2163         CTRACE("query_addns");
2164         /*
2165          * Initialization.
2166          */
2167         eresult = ISC_R_SUCCESS;
2168         name = NULL;
2169         rdataset = NULL;
2170         node = NULL;
2171         dns_fixedname_init(&foundname);
2172         fname = dns_fixedname_name(&foundname);
2173
2174         /*
2175          * Get resources and make 'name' be the database origin.
2176          */
2177         result = dns_message_gettempname(client->message, &name);
2178         if (result != ISC_R_SUCCESS) {
2179                 CTRACE("query_addns: dns_message_gettempname failed: done");
2180                 return (result);
2181         }
2182         dns_name_init(name, NULL);
2183         dns_name_clone(dns_db_origin(db), name);
2184         rdataset = query_newrdataset(client);
2185         if (rdataset == NULL) {
2186                 CTRACE("query_addns: query_newrdataset failed");
2187                 eresult = DNS_R_SERVFAIL;
2188                 goto cleanup;
2189         }
2190         if (WANTDNSSEC(client) && dns_db_issecure(db)) {
2191                 sigrdataset = query_newrdataset(client);
2192                 if (sigrdataset == NULL) {
2193                         CTRACE("query_addns: query_newrdataset failed");
2194                         eresult = DNS_R_SERVFAIL;
2195                         goto cleanup;
2196                 }
2197         }
2198
2199         /*
2200          * Find the NS rdataset.
2201          */
2202         result = dns_db_getoriginnode(db, &node);
2203         if (result == ISC_R_SUCCESS) {
2204                 result = dns_db_findrdataset(db, node, version,
2205                                              dns_rdatatype_ns,
2206                                              0, client->now, rdataset,
2207                                              sigrdataset);
2208         } else {
2209                 CTRACE("query_addns: calling dns_db_find");
2210                 result = dns_db_find(db, name, NULL, dns_rdatatype_ns,
2211                                      client->query.dboptions, 0, &node,
2212                                      fname, rdataset, sigrdataset);
2213                 CTRACE("query_addns: dns_db_find complete");
2214         }
2215         if (result != ISC_R_SUCCESS) {
2216                 CTRACE("query_addns: "
2217                        "dns_db_findrdataset or dns_db_find failed");
2218                 /*
2219                  * This is bad.  We tried to get the NS rdataset at the zone
2220                  * top and it didn't work!
2221                  */
2222                 eresult = DNS_R_SERVFAIL;
2223         } else {
2224                 if (sigrdataset != NULL)
2225                         sigrdatasetp = &sigrdataset;
2226                 else
2227                         sigrdatasetp = NULL;
2228                 query_addrrset(client, &name, &rdataset, sigrdatasetp, NULL,
2229                                DNS_SECTION_AUTHORITY);
2230         }
2231
2232  cleanup:
2233         CTRACE("query_addns: cleanup");
2234         query_putrdataset(client, &rdataset);
2235         if (sigrdataset != NULL)
2236                 query_putrdataset(client, &sigrdataset);
2237         if (name != NULL)
2238                 query_releasename(client, &name);
2239         if (node != NULL)
2240                 dns_db_detachnode(db, &node);
2241
2242         CTRACE("query_addns: done");
2243         return (eresult);
2244 }
2245
2246 static inline isc_result_t
2247 query_addcnamelike(ns_client_t *client, dns_name_t *qname, dns_name_t *tname,
2248                    dns_rdataset_t *dname, dns_name_t **anamep,
2249                    dns_rdatatype_t type)
2250 {
2251         dns_rdataset_t *rdataset;
2252         dns_rdatalist_t *rdatalist;
2253         dns_rdata_t *rdata;
2254         isc_result_t result;
2255         isc_region_t r;
2256
2257         /*
2258          * We assume the name data referred to by tname won't go away.
2259          */
2260
2261         REQUIRE(anamep != NULL);
2262
2263         rdatalist = NULL;
2264         result = dns_message_gettemprdatalist(client->message, &rdatalist);
2265         if (result != ISC_R_SUCCESS)
2266                 return (result);
2267         rdata = NULL;
2268         result = dns_message_gettemprdata(client->message, &rdata);
2269         if (result != ISC_R_SUCCESS)
2270                 return (result);
2271         rdataset = NULL;
2272         result = dns_message_gettemprdataset(client->message, &rdataset);
2273         if (result != ISC_R_SUCCESS)
2274                 return (result);
2275         dns_rdataset_init(rdataset);
2276         result = dns_name_dup(qname, client->mctx, *anamep);
2277         if (result != ISC_R_SUCCESS) {
2278                 dns_message_puttemprdataset(client->message, &rdataset);
2279                 return (result);
2280         }
2281
2282         rdatalist->type = type;
2283         rdatalist->covers = 0;
2284         rdatalist->rdclass = client->message->rdclass;
2285         rdatalist->ttl = dname->ttl;
2286
2287         dns_name_toregion(tname, &r);
2288         rdata->data = r.base;
2289         rdata->length = r.length;
2290         rdata->rdclass = client->message->rdclass;
2291         rdata->type = type;
2292
2293         ISC_LIST_INIT(rdatalist->rdata);
2294         ISC_LIST_APPEND(rdatalist->rdata, rdata, link);
2295         RUNTIME_CHECK(dns_rdatalist_tordataset(rdatalist, rdataset)
2296                       == ISC_R_SUCCESS);
2297         rdataset->trust = dname->trust;
2298
2299         query_addrrset(client, anamep, &rdataset, NULL, NULL,
2300                        DNS_SECTION_ANSWER);
2301
2302         if (rdataset != NULL) {
2303                 if (dns_rdataset_isassociated(rdataset))
2304                         dns_rdataset_disassociate(rdataset);
2305                 dns_message_puttemprdataset(client->message, &rdataset);
2306         }
2307
2308         return (ISC_R_SUCCESS);
2309 }
2310
2311 /*
2312  * Mark the RRsets as secure.  Update the cache (db) to reflect the
2313  * change in trust level.
2314  */
2315 static void
2316 mark_secure(ns_client_t *client, dns_db_t *db, dns_name_t *name,
2317             isc_uint32_t ttl, dns_rdataset_t *rdataset,
2318             dns_rdataset_t *sigrdataset)
2319 {
2320         isc_result_t result;
2321         dns_dbnode_t *node = NULL;
2322
2323         rdataset->trust = dns_trust_secure;
2324         sigrdataset->trust = dns_trust_secure;
2325
2326         /*
2327          * Save the updated secure state.  Ignore failures.
2328          */
2329         result = dns_db_findnode(db, name, ISC_TRUE, &node);
2330         if (result != ISC_R_SUCCESS)
2331                 return;
2332         /*
2333          * Bound the validated ttls then minimise.
2334          */
2335         if (sigrdataset->ttl > ttl)
2336                 sigrdataset->ttl = ttl;
2337         if (rdataset->ttl > ttl)
2338                 rdataset->ttl = ttl;
2339         if (rdataset->ttl > sigrdataset->ttl)
2340                 rdataset->ttl = sigrdataset->ttl;
2341         else
2342                 sigrdataset->ttl = rdataset->ttl;
2343
2344         (void)dns_db_addrdataset(db, node, NULL, client->now, rdataset,
2345                                  0, NULL);
2346         (void)dns_db_addrdataset(db, node, NULL, client->now, sigrdataset,
2347                                  0, NULL);
2348         dns_db_detachnode(db, &node);
2349 }
2350
2351 /*
2352  * Find the secure key that corresponds to rrsig.
2353  * Note: 'keyrdataset' maintains state between successive calls,
2354  * there may be multiple keys with the same keyid.
2355  * Return ISC_FALSE if we have exhausted all the possible keys.
2356  */
2357 static isc_boolean_t
2358 get_key(ns_client_t *client, dns_db_t *db, dns_rdata_rrsig_t *rrsig,
2359         dns_rdataset_t *keyrdataset, dst_key_t **keyp)
2360 {
2361         isc_result_t result;
2362         dns_dbnode_t *node = NULL;
2363         isc_boolean_t secure = ISC_FALSE;
2364
2365         if (!dns_rdataset_isassociated(keyrdataset)) {
2366                 result = dns_db_findnode(db, &rrsig->signer, ISC_FALSE, &node);
2367                 if (result != ISC_R_SUCCESS)
2368                         return (ISC_FALSE);
2369
2370                 result = dns_db_findrdataset(db, node, NULL,
2371                                              dns_rdatatype_dnskey, 0,
2372                                              client->now, keyrdataset, NULL);
2373                 dns_db_detachnode(db, &node);
2374                 if (result != ISC_R_SUCCESS)
2375                         return (ISC_FALSE);
2376
2377                 if (keyrdataset->trust != dns_trust_secure)
2378                         return (ISC_FALSE);
2379
2380                 result = dns_rdataset_first(keyrdataset);
2381         } else
2382                 result = dns_rdataset_next(keyrdataset);
2383
2384         for ( ; result == ISC_R_SUCCESS;
2385              result = dns_rdataset_next(keyrdataset)) {
2386                 dns_rdata_t rdata = DNS_RDATA_INIT;
2387                 isc_buffer_t b;
2388
2389                 dns_rdataset_current(keyrdataset, &rdata);
2390                 isc_buffer_init(&b, rdata.data, rdata.length);
2391                 isc_buffer_add(&b, rdata.length);
2392                 result = dst_key_fromdns(&rrsig->signer, rdata.rdclass, &b,
2393                                          client->mctx, keyp);
2394                 if (result != ISC_R_SUCCESS)
2395                         continue;
2396                 if (rrsig->algorithm == (dns_secalg_t)dst_key_alg(*keyp) &&
2397                     rrsig->keyid == (dns_keytag_t)dst_key_id(*keyp) &&
2398                     dst_key_iszonekey(*keyp)) {
2399                         secure = ISC_TRUE;
2400                         break;
2401                 }
2402                 dst_key_free(keyp);
2403         }
2404         return (secure);
2405 }
2406
2407 static isc_boolean_t
2408 verify(dst_key_t *key, dns_name_t *name, dns_rdataset_t *rdataset,
2409        dns_rdata_t *rdata, isc_mem_t *mctx, isc_boolean_t acceptexpired)
2410 {
2411         isc_result_t result;
2412         dns_fixedname_t fixed;
2413         isc_boolean_t ignore = ISC_FALSE;
2414
2415         dns_fixedname_init(&fixed);
2416
2417 again:
2418         result = dns_dnssec_verify2(name, rdataset, key, ignore, mctx,
2419                                     rdata, NULL);
2420         if (result == DNS_R_SIGEXPIRED && acceptexpired) {
2421                 ignore = ISC_TRUE;
2422                 goto again;
2423         }
2424         if (result == ISC_R_SUCCESS || result == DNS_R_FROMWILDCARD)
2425                 return (ISC_TRUE);
2426         return (ISC_FALSE);
2427 }
2428
2429 /*
2430  * Validate the rdataset if possible with available records.
2431  */
2432 static isc_boolean_t
2433 validate(ns_client_t *client, dns_db_t *db, dns_name_t *name,
2434          dns_rdataset_t *rdataset, dns_rdataset_t *sigrdataset)
2435 {
2436         isc_result_t result;
2437         dns_rdata_t rdata = DNS_RDATA_INIT;
2438         dns_rdata_rrsig_t rrsig;
2439         dst_key_t *key = NULL;
2440         dns_rdataset_t keyrdataset;
2441
2442         if (sigrdataset == NULL || !dns_rdataset_isassociated(sigrdataset))
2443                 return (ISC_FALSE);
2444
2445         for (result = dns_rdataset_first(sigrdataset);
2446              result == ISC_R_SUCCESS;
2447              result = dns_rdataset_next(sigrdataset)) {
2448
2449                 dns_rdata_reset(&rdata);
2450                 dns_rdataset_current(sigrdataset, &rdata);
2451                 result = dns_rdata_tostruct(&rdata, &rrsig, NULL);
2452                 if (result != ISC_R_SUCCESS)
2453                         return (ISC_FALSE);
2454                 if (!dns_resolver_algorithm_supported(client->view->resolver,
2455                                                       name, rrsig.algorithm))
2456                         continue;
2457                 if (!dns_name_issubdomain(name, &rrsig.signer))
2458                         continue;
2459                 dns_rdataset_init(&keyrdataset);
2460                 do {
2461                         if (!get_key(client, db, &rrsig, &keyrdataset, &key))
2462                                 break;
2463                         if (verify(key, name, rdataset, &rdata, client->mctx,
2464                                    client->view->acceptexpired)) {
2465                                 dst_key_free(&key);
2466                                 dns_rdataset_disassociate(&keyrdataset);
2467                                 mark_secure(client, db, name,
2468                                             rrsig.originalttl,
2469                                             rdataset, sigrdataset);
2470                                 return (ISC_TRUE);
2471                         }
2472                         dst_key_free(&key);
2473                 } while (1);
2474                 if (dns_rdataset_isassociated(&keyrdataset))
2475                         dns_rdataset_disassociate(&keyrdataset);
2476         }
2477         return (ISC_FALSE);
2478 }
2479
2480 static void
2481 query_addbestns(ns_client_t *client) {
2482         dns_db_t *db, *zdb;
2483         dns_dbnode_t *node;
2484         dns_name_t *fname, *zfname;
2485         dns_rdataset_t *rdataset, *sigrdataset, *zrdataset, *zsigrdataset;
2486         isc_boolean_t is_zone, use_zone;
2487         isc_buffer_t *dbuf;
2488         isc_result_t result;
2489         dns_dbversion_t *version;
2490         dns_zone_t *zone;
2491         isc_buffer_t b;
2492
2493         CTRACE("query_addbestns");
2494         fname = NULL;
2495         zfname = NULL;
2496         rdataset = NULL;
2497         zrdataset = NULL;
2498         sigrdataset = NULL;
2499         zsigrdataset = NULL;
2500         node = NULL;
2501         db = NULL;
2502         zdb = NULL;
2503         version = NULL;
2504         zone = NULL;
2505         is_zone = ISC_FALSE;
2506         use_zone = ISC_FALSE;
2507
2508         /*
2509          * Find the right database.
2510          */
2511         result = query_getdb(client, client->query.qname, dns_rdatatype_ns, 0,
2512                              &zone, &db, &version, &is_zone);
2513         if (result != ISC_R_SUCCESS)
2514                 goto cleanup;
2515
2516  db_find:
2517         /*
2518          * We'll need some resources...
2519          */
2520         dbuf = query_getnamebuf(client);
2521         if (dbuf == NULL)
2522                 goto cleanup;
2523         fname = query_newname(client, dbuf, &b);
2524         rdataset = query_newrdataset(client);
2525         if (fname == NULL || rdataset == NULL)
2526                 goto cleanup;
2527         /*
2528          * Get the RRSIGs if the client requested them or if we may
2529          * need to validate answers from the cache.
2530          */
2531         if (WANTDNSSEC(client) || !is_zone) {
2532                 sigrdataset = query_newrdataset(client);
2533                 if (sigrdataset == NULL)
2534                         goto cleanup;
2535         }
2536
2537         /*
2538          * Now look for the zonecut.
2539          */
2540         if (is_zone) {
2541                 result = dns_db_find(db, client->query.qname, version,
2542                                      dns_rdatatype_ns, client->query.dboptions,
2543                                      client->now, &node, fname,
2544                                      rdataset, sigrdataset);
2545                 if (result != DNS_R_DELEGATION)
2546                         goto cleanup;
2547                 if (USECACHE(client)) {
2548                         query_keepname(client, fname, dbuf);
2549                         zdb = db;
2550                         zfname = fname;
2551                         fname = NULL;
2552                         zrdataset = rdataset;
2553                         rdataset = NULL;
2554                         zsigrdataset = sigrdataset;
2555                         sigrdataset = NULL;
2556                         dns_db_detachnode(db, &node);
2557                         version = NULL;
2558                         db = NULL;
2559                         dns_db_attach(client->view->cachedb, &db);
2560                         is_zone = ISC_FALSE;
2561                         goto db_find;
2562                 }
2563         } else {
2564                 result = dns_db_findzonecut(db, client->query.qname,
2565                                             client->query.dboptions,
2566                                             client->now, &node, fname,
2567                                             rdataset, sigrdataset);
2568                 if (result == ISC_R_SUCCESS) {
2569                         if (zfname != NULL &&
2570                             !dns_name_issubdomain(fname, zfname)) {
2571                                 /*
2572                                  * We found a zonecut in the cache, but our
2573                                  * zone delegation is better.
2574                                  */
2575                                 use_zone = ISC_TRUE;
2576                         }
2577                 } else if (result == ISC_R_NOTFOUND && zfname != NULL) {
2578                         /*
2579                          * We didn't find anything in the cache, but we
2580                          * have a zone delegation, so use it.
2581                          */
2582                         use_zone = ISC_TRUE;
2583                 } else
2584                         goto cleanup;
2585         }
2586
2587         if (use_zone) {
2588                 query_releasename(client, &fname);
2589                 fname = zfname;
2590                 zfname = NULL;
2591                 /*
2592                  * We've already done query_keepname() on
2593                  * zfname, so we must set dbuf to NULL to
2594                  * prevent query_addrrset() from trying to
2595                  * call query_keepname() again.
2596                  */
2597                 dbuf = NULL;
2598                 query_putrdataset(client, &rdataset);
2599                 if (sigrdataset != NULL)
2600                         query_putrdataset(client, &sigrdataset);
2601                 rdataset = zrdataset;
2602                 zrdataset = NULL;
2603                 sigrdataset = zsigrdataset;
2604                 zsigrdataset = NULL;
2605         }
2606
2607         /*
2608          * Attempt to validate RRsets that are pending or that are glue.
2609          */
2610         if ((DNS_TRUST_PENDING(rdataset->trust) ||
2611              (sigrdataset != NULL && DNS_TRUST_PENDING(sigrdataset->trust)))
2612             && !validate(client, db, fname, rdataset, sigrdataset) &&
2613             !PENDINGOK(client->query.dboptions))
2614                 goto cleanup;
2615
2616         if ((DNS_TRUST_GLUE(rdataset->trust) ||
2617              (sigrdataset != NULL && DNS_TRUST_GLUE(sigrdataset->trust))) &&
2618             !validate(client, db, fname, rdataset, sigrdataset) &&
2619             SECURE(client) && WANTDNSSEC(client))
2620                 goto cleanup;
2621
2622         /*
2623          * If the client doesn't want DNSSEC we can discard the sigrdataset
2624          * now.
2625          */
2626         if (!WANTDNSSEC(client))
2627                 query_putrdataset(client, &sigrdataset);
2628         query_addrrset(client, &fname, &rdataset, &sigrdataset, dbuf,
2629                        DNS_SECTION_AUTHORITY);
2630
2631  cleanup:
2632         if (rdataset != NULL)
2633                 query_putrdataset(client, &rdataset);
2634         if (sigrdataset != NULL)
2635                 query_putrdataset(client, &sigrdataset);
2636         if (fname != NULL)
2637                 query_releasename(client, &fname);
2638         if (node != NULL)
2639                 dns_db_detachnode(db, &node);
2640         if (db != NULL)
2641                 dns_db_detach(&db);
2642         if (zone != NULL)
2643                 dns_zone_detach(&zone);
2644         if (zdb != NULL) {
2645                 query_putrdataset(client, &zrdataset);
2646                 if (zsigrdataset != NULL)
2647                         query_putrdataset(client, &zsigrdataset);
2648                 if (zfname != NULL)
2649                         query_releasename(client, &zfname);
2650                 dns_db_detach(&zdb);
2651         }
2652 }
2653
2654 static void
2655 fixrdataset(ns_client_t *client, dns_rdataset_t **rdataset) {
2656         if (*rdataset == NULL)
2657                 *rdataset = query_newrdataset(client);
2658         else  if (dns_rdataset_isassociated(*rdataset))
2659                 dns_rdataset_disassociate(*rdataset);
2660 }
2661
2662 static void
2663 fixfname(ns_client_t *client, dns_name_t **fname, isc_buffer_t **dbuf,
2664          isc_buffer_t *nbuf)
2665 {
2666         if (*fname == NULL) {
2667                 *dbuf = query_getnamebuf(client);
2668                 if (*dbuf == NULL)
2669                         return;
2670                 *fname = query_newname(client, *dbuf, nbuf);
2671         }
2672 }
2673
2674 static void
2675 query_addds(ns_client_t *client, dns_db_t *db, dns_dbnode_t *node,
2676             dns_dbversion_t *version, dns_name_t *name)
2677 {
2678         dns_fixedname_t fixed;
2679         dns_name_t *fname = NULL;
2680         dns_name_t *rname;
2681         dns_rdataset_t *rdataset, *sigrdataset;
2682         isc_buffer_t *dbuf, b;
2683         isc_result_t result;
2684         unsigned int count;
2685
2686         CTRACE("query_addds");
2687         rname = NULL;
2688         rdataset = NULL;
2689         sigrdataset = NULL;
2690
2691         /*
2692          * We'll need some resources...
2693          */
2694         rdataset = query_newrdataset(client);
2695         sigrdataset = query_newrdataset(client);
2696         if (rdataset == NULL || sigrdataset == NULL)
2697                 goto cleanup;
2698
2699         /*
2700          * Look for the DS record, which may or may not be present.
2701          */
2702         result = dns_db_findrdataset(db, node, version, dns_rdatatype_ds, 0,
2703                                      client->now, rdataset, sigrdataset);
2704         /*
2705          * If we didn't find it, look for an NSEC.
2706          */
2707         if (result == ISC_R_NOTFOUND)
2708                 result = dns_db_findrdataset(db, node, version,
2709                                              dns_rdatatype_nsec, 0, client->now,
2710                                              rdataset, sigrdataset);
2711         if (result != ISC_R_SUCCESS && result != ISC_R_NOTFOUND)
2712                 goto addnsec3;
2713         if (!dns_rdataset_isassociated(rdataset) ||
2714             !dns_rdataset_isassociated(sigrdataset))
2715                 goto addnsec3;
2716
2717         /*
2718          * We've already added the NS record, so if the name's not there,
2719          * we have other problems.  Use this name rather than calling
2720          * query_addrrset().
2721          */
2722         result = dns_message_firstname(client->message, DNS_SECTION_AUTHORITY);
2723         if (result != ISC_R_SUCCESS)
2724                 goto cleanup;
2725
2726         rname = NULL;
2727         dns_message_currentname(client->message, DNS_SECTION_AUTHORITY,
2728                                 &rname);
2729         result = dns_message_findtype(rname, dns_rdatatype_ns, 0, NULL);
2730         if (result != ISC_R_SUCCESS)
2731                 goto cleanup;
2732
2733         ISC_LIST_APPEND(rname->list, rdataset, link);
2734         ISC_LIST_APPEND(rname->list, sigrdataset, link);
2735         rdataset = NULL;
2736         sigrdataset = NULL;
2737         return;
2738
2739    addnsec3:
2740         if (!dns_db_iszone(db))
2741                 goto cleanup;
2742         /*
2743          * Add the NSEC3 which proves the DS does not exist.
2744          */
2745         dbuf = query_getnamebuf(client);
2746         if (dbuf == NULL)
2747                 goto cleanup;
2748         fname = query_newname(client, dbuf, &b);
2749         dns_fixedname_init(&fixed);
2750         if (dns_rdataset_isassociated(rdataset))
2751                 dns_rdataset_disassociate(rdataset);
2752         if (dns_rdataset_isassociated(sigrdataset))
2753                 dns_rdataset_disassociate(sigrdataset);
2754         query_findclosestnsec3(name, db, version, client, rdataset,
2755                                sigrdataset, fname, ISC_TRUE,
2756                                dns_fixedname_name(&fixed));
2757         if (!dns_rdataset_isassociated(rdataset))
2758                 goto cleanup;
2759         query_addrrset(client, &fname, &rdataset, &sigrdataset, dbuf,
2760                        DNS_SECTION_AUTHORITY);
2761         /*
2762          * Did we find the closest provable encloser instead?
2763          * If so add the nearest to the closest provable encloser.
2764          */
2765         if (!dns_name_equal(name, dns_fixedname_name(&fixed))) {
2766                 count = dns_name_countlabels(dns_fixedname_name(&fixed)) + 1;
2767                 dns_name_getlabelsequence(name,
2768                                           dns_name_countlabels(name) - count,
2769                                           count, dns_fixedname_name(&fixed));
2770                 fixfname(client, &fname, &dbuf, &b);
2771                 fixrdataset(client, &rdataset);
2772                 fixrdataset(client, &sigrdataset);
2773                 if (fname == NULL || rdataset == NULL || sigrdataset == NULL)
2774                                 goto cleanup;
2775                 query_findclosestnsec3(dns_fixedname_name(&fixed), db, version,
2776                                        client, rdataset, sigrdataset, fname,
2777                                        ISC_FALSE, NULL);
2778                 if (!dns_rdataset_isassociated(rdataset))
2779                         goto cleanup;
2780                 query_addrrset(client, &fname, &rdataset, &sigrdataset, dbuf,
2781                                DNS_SECTION_AUTHORITY);
2782         }
2783
2784  cleanup:
2785         if (rdataset != NULL)
2786                 query_putrdataset(client, &rdataset);
2787         if (sigrdataset != NULL)
2788                 query_putrdataset(client, &sigrdataset);
2789         if (fname != NULL)
2790                 query_releasename(client, &fname);
2791 }
2792
2793 static void
2794 query_addwildcardproof(ns_client_t *client, dns_db_t *db,
2795                        dns_dbversion_t *version, dns_name_t *name,
2796                        isc_boolean_t ispositive)
2797 {
2798         isc_buffer_t *dbuf, b;
2799         dns_name_t *fname;
2800         dns_rdataset_t *rdataset, *sigrdataset;
2801         dns_fixedname_t wfixed;
2802         dns_name_t *wname;
2803         dns_dbnode_t *node;
2804         unsigned int options;
2805         unsigned int olabels, nlabels, labels;
2806         isc_result_t result;
2807         dns_rdata_t rdata = DNS_RDATA_INIT;
2808         dns_rdata_nsec_t nsec;
2809         isc_boolean_t have_wname;
2810         int order;
2811         dns_fixedname_t cfixed;
2812         dns_name_t *cname;
2813
2814         CTRACE("query_addwildcardproof");
2815         fname = NULL;
2816         rdataset = NULL;
2817         sigrdataset = NULL;
2818         node = NULL;
2819
2820         /*
2821          * Get the NOQNAME proof then if !ispositive
2822          * get the NOWILDCARD proof.
2823          *
2824          * DNS_DBFIND_NOWILD finds the NSEC records that covers the
2825          * name ignoring any wildcard.  From the owner and next names
2826          * of this record you can compute which wildcard (if it exists)
2827          * will match by finding the longest common suffix of the
2828          * owner name and next names with the qname and prefixing that
2829          * with the wildcard label.
2830          *
2831          * e.g.
2832          *   Given:
2833          *      example SOA
2834          *      example NSEC b.example
2835          *      b.example A
2836          *      b.example NSEC a.d.example
2837          *      a.d.example A
2838          *      a.d.example NSEC g.f.example
2839          *      g.f.example A
2840          *      g.f.example NSEC z.i.example
2841          *      z.i.example A
2842          *      z.i.example NSEC example
2843          *
2844          *   QNAME:
2845          *   a.example -> example NSEC b.example
2846          *      owner common example
2847          *      next common example
2848          *      wild *.example
2849          *   d.b.example -> b.example NSEC a.d.example
2850          *      owner common b.example
2851          *      next common example
2852          *      wild *.b.example
2853          *   a.f.example -> a.d.example NSEC g.f.example
2854          *      owner common example
2855          *      next common f.example
2856          *      wild *.f.example
2857          *  j.example -> z.i.example NSEC example
2858          *      owner common example
2859          *      next common example
2860          *      wild *.f.example
2861          */
2862         options = client->query.dboptions | DNS_DBFIND_NOWILD;
2863         dns_fixedname_init(&wfixed);
2864         wname = dns_fixedname_name(&wfixed);
2865  again:
2866         have_wname = ISC_FALSE;
2867         /*
2868          * We'll need some resources...
2869          */
2870         dbuf = query_getnamebuf(client);
2871         if (dbuf == NULL)
2872                 goto cleanup;
2873         fname = query_newname(client, dbuf, &b);
2874         rdataset = query_newrdataset(client);
2875         sigrdataset = query_newrdataset(client);
2876         if (fname == NULL || rdataset == NULL || sigrdataset == NULL)
2877                 goto cleanup;
2878
2879         result = dns_db_find(db, name, version, dns_rdatatype_nsec, options,
2880                              0, &node, fname, rdataset, sigrdataset);
2881         if (node != NULL)
2882                 dns_db_detachnode(db, &node);
2883
2884         if (!dns_rdataset_isassociated(rdataset)) {
2885                 /*
2886                  * No NSEC proof available, return NSEC3 proofs instead.
2887                  */
2888                 dns_fixedname_init(&cfixed);
2889                 cname = dns_fixedname_name(&cfixed);
2890                 /*
2891                  * Find the closest encloser.
2892                  */
2893                 dns_name_copy(name, cname, NULL);
2894                 while (result == DNS_R_NXDOMAIN) {
2895                         labels = dns_name_countlabels(cname) - 1;
2896                         dns_name_split(cname, labels, NULL, cname);
2897                         result = dns_db_find(db, cname, version,
2898                                              dns_rdatatype_nsec,
2899                                              options, 0, NULL, fname,
2900                                              NULL, NULL);
2901                 }
2902                 /*
2903                  * Add closest (provable) encloser NSEC3.
2904                  */
2905                 query_findclosestnsec3(cname, db, NULL, client, rdataset,
2906                                        sigrdataset, fname, ISC_TRUE, cname);
2907                 if (!dns_rdataset_isassociated(rdataset))
2908                         goto cleanup;
2909                 query_addrrset(client, &fname, &rdataset, &sigrdataset,
2910                                dbuf, DNS_SECTION_AUTHORITY);
2911
2912                 /*
2913                  * Replace resources which were consumed by query_addrrset.
2914                  */
2915                 if (fname == NULL) {
2916                         dbuf = query_getnamebuf(client);
2917                         if (dbuf == NULL)
2918                                 goto cleanup;
2919                         fname = query_newname(client, dbuf, &b);
2920                 }
2921
2922                 if (rdataset == NULL)
2923                         rdataset = query_newrdataset(client);
2924                 else if (dns_rdataset_isassociated(rdataset))
2925                         dns_rdataset_disassociate(rdataset);
2926
2927                 if (sigrdataset == NULL)
2928                         sigrdataset = query_newrdataset(client);
2929                 else if (dns_rdataset_isassociated(sigrdataset))
2930                         dns_rdataset_disassociate(sigrdataset);
2931
2932                 if (fname == NULL || rdataset == NULL || sigrdataset == NULL)
2933                         goto cleanup;
2934                 /*
2935                  * Add no qname proof.
2936                  */
2937                 labels = dns_name_countlabels(cname) + 1;
2938                 if (dns_name_countlabels(name) == labels)
2939                         dns_name_copy(name, wname, NULL);
2940                 else
2941                         dns_name_split(name, labels, NULL, wname);
2942
2943                 query_findclosestnsec3(wname, db, NULL, client, rdataset,
2944                                        sigrdataset, fname, ISC_FALSE, NULL);
2945                 if (!dns_rdataset_isassociated(rdataset))
2946                         goto cleanup;
2947                 query_addrrset(client, &fname, &rdataset, &sigrdataset,
2948                                dbuf, DNS_SECTION_AUTHORITY);
2949
2950                 if (ispositive)
2951                         goto cleanup;
2952
2953                 /*
2954                  * Replace resources which were consumed by query_addrrset.
2955                  */
2956                 if (fname == NULL) {
2957                         dbuf = query_getnamebuf(client);
2958                         if (dbuf == NULL)
2959                                 goto cleanup;
2960                         fname = query_newname(client, dbuf, &b);
2961                 }
2962
2963                 if (rdataset == NULL)
2964                         rdataset = query_newrdataset(client);
2965                 else if (dns_rdataset_isassociated(rdataset))
2966                         dns_rdataset_disassociate(rdataset);
2967
2968                 if (sigrdataset == NULL)
2969                         sigrdataset = query_newrdataset(client);
2970                 else if (dns_rdataset_isassociated(sigrdataset))
2971                         dns_rdataset_disassociate(sigrdataset);
2972
2973                 if (fname == NULL || rdataset == NULL || sigrdataset == NULL)
2974                         goto cleanup;
2975                 /*
2976                  * Add the no wildcard proof.
2977                  */
2978                 result = dns_name_concatenate(dns_wildcardname,
2979                                               cname, wname, NULL);
2980                 if (result != ISC_R_SUCCESS)
2981                         goto cleanup;
2982
2983                 query_findclosestnsec3(wname, db, NULL, client, rdataset,
2984                                        sigrdataset, fname, ISC_FALSE, NULL);
2985                 if (!dns_rdataset_isassociated(rdataset))
2986                         goto cleanup;
2987                 query_addrrset(client, &fname, &rdataset, &sigrdataset,
2988                                dbuf, DNS_SECTION_AUTHORITY);
2989
2990                 goto cleanup;
2991         } else if (result == DNS_R_NXDOMAIN) {
2992                 if (!ispositive)
2993                         result = dns_rdataset_first(rdataset);
2994                 if (result == ISC_R_SUCCESS) {
2995                         dns_rdataset_current(rdataset, &rdata);
2996                         result = dns_rdata_tostruct(&rdata, &nsec, NULL);
2997                 }
2998                 if (result == ISC_R_SUCCESS) {
2999                         (void)dns_name_fullcompare(name, fname, &order,
3000                                                    &olabels);
3001                         (void)dns_name_fullcompare(name, &nsec.next, &order,
3002                                                    &nlabels);
3003                         /*
3004                          * Check for a pathological condition created when
3005                          * serving some malformed signed zones and bail out.
3006                          */
3007                         if (dns_name_countlabels(name) == nlabels)
3008                                 goto cleanup;
3009
3010                         if (olabels > nlabels)
3011                                 dns_name_split(name, olabels, NULL, wname);
3012                         else
3013                                 dns_name_split(name, nlabels, NULL, wname);
3014                         result = dns_name_concatenate(dns_wildcardname,
3015                                                       wname, wname, NULL);
3016                         if (result == ISC_R_SUCCESS)
3017                                 have_wname = ISC_TRUE;
3018                         dns_rdata_freestruct(&nsec);
3019                 }
3020                 query_addrrset(client, &fname, &rdataset, &sigrdataset,
3021                                dbuf, DNS_SECTION_AUTHORITY);
3022         }
3023         if (rdataset != NULL)
3024                 query_putrdataset(client, &rdataset);
3025         if (sigrdataset != NULL)
3026                 query_putrdataset(client, &sigrdataset);
3027         if (fname != NULL)
3028                 query_releasename(client, &fname);
3029         if (have_wname) {
3030                 ispositive = ISC_TRUE;  /* prevent loop */
3031                 if (!dns_name_equal(name, wname)) {
3032                         name = wname;
3033                         goto again;
3034                 }
3035         }
3036  cleanup:
3037         if (rdataset != NULL)
3038                 query_putrdataset(client, &rdataset);
3039         if (sigrdataset != NULL)
3040                 query_putrdataset(client, &sigrdataset);
3041         if (fname != NULL)
3042                 query_releasename(client, &fname);
3043 }
3044
3045 static void
3046 query_addnxrrsetnsec(ns_client_t *client, dns_db_t *db,
3047                      dns_dbversion_t *version, dns_name_t **namep,
3048                      dns_rdataset_t **rdatasetp, dns_rdataset_t **sigrdatasetp)
3049 {
3050         dns_name_t *name;
3051         dns_rdataset_t *sigrdataset;
3052         dns_rdata_t sigrdata;
3053         dns_rdata_rrsig_t sig;
3054         unsigned int labels;
3055         isc_buffer_t *dbuf, b;
3056         dns_name_t *fname;
3057         isc_result_t result;
3058
3059         name = *namep;
3060         if ((name->attributes & DNS_NAMEATTR_WILDCARD) == 0) {
3061                 query_addrrset(client, namep, rdatasetp, sigrdatasetp,
3062                                NULL, DNS_SECTION_AUTHORITY);
3063                 return;
3064         }
3065
3066         if (sigrdatasetp == NULL)
3067                 return;
3068
3069         sigrdataset = *sigrdatasetp;
3070         if (sigrdataset == NULL || !dns_rdataset_isassociated(sigrdataset))
3071                 return;
3072         result = dns_rdataset_first(sigrdataset);
3073         if (result != ISC_R_SUCCESS)
3074                 return;
3075         dns_rdata_init(&sigrdata);
3076         dns_rdataset_current(sigrdataset, &sigrdata);
3077         result = dns_rdata_tostruct(&sigrdata, &sig, NULL);
3078         if (result != ISC_R_SUCCESS)
3079                 return;
3080
3081         labels = dns_name_countlabels(name);
3082         if ((unsigned int)sig.labels + 1 >= labels)
3083                 return;
3084
3085         /* XXX */
3086         query_addwildcardproof(client, db, version, client->query.qname,
3087                                ISC_TRUE);
3088
3089         /*
3090          * We'll need some resources...
3091          */
3092         dbuf = query_getnamebuf(client);
3093         if (dbuf == NULL)
3094                 return;
3095         fname = query_newname(client, dbuf, &b);
3096         if (fname == NULL)
3097                 return;
3098         dns_name_split(name, sig.labels + 1, NULL, fname);
3099         /* This will succeed, since we've stripped labels. */
3100         RUNTIME_CHECK(dns_name_concatenate(dns_wildcardname, fname, fname,
3101                                            NULL) == ISC_R_SUCCESS);
3102         query_addrrset(client, &fname, rdatasetp, sigrdatasetp,
3103                        dbuf, DNS_SECTION_AUTHORITY);
3104 }
3105
3106 static void
3107 query_resume(isc_task_t *task, isc_event_t *event) {
3108         dns_fetchevent_t *devent = (dns_fetchevent_t *)event;
3109         dns_fetch_t *fetch;
3110         ns_client_t *client;
3111         isc_boolean_t fetch_canceled, client_shuttingdown;
3112         isc_result_t result;
3113         isc_logcategory_t *logcategory = NS_LOGCATEGORY_QUERY_EERRORS;
3114         int errorloglevel;
3115
3116         /*
3117          * Resume a query after recursion.
3118          */
3119
3120         UNUSED(task);
3121
3122         REQUIRE(event->ev_type == DNS_EVENT_FETCHDONE);
3123         client = devent->ev_arg;
3124         REQUIRE(NS_CLIENT_VALID(client));
3125         REQUIRE(task == client->task);
3126         REQUIRE(RECURSING(client));
3127
3128         LOCK(&client->query.fetchlock);
3129         if (client->query.fetch != NULL) {
3130                 /*
3131                  * This is the fetch we've been waiting for.
3132                  */
3133                 INSIST(devent->fetch == client->query.fetch);
3134                 client->query.fetch = NULL;
3135                 fetch_canceled = ISC_FALSE;
3136                 /*
3137                  * Update client->now.
3138                  */
3139                 isc_stdtime_get(&client->now);
3140         } else {
3141                 /*
3142                  * This is a fetch completion event for a canceled fetch.
3143                  * Clean up and don't resume the find.
3144                  */
3145                 fetch_canceled = ISC_TRUE;
3146         }
3147         UNLOCK(&client->query.fetchlock);
3148         INSIST(client->query.fetch == NULL);
3149
3150         client->query.attributes &= ~NS_QUERYATTR_RECURSING;
3151         fetch = devent->fetch;
3152         devent->fetch = NULL;
3153
3154         /*
3155          * If this client is shutting down, or this transaction
3156          * has timed out, do not resume the find.
3157          */
3158         client_shuttingdown = ns_client_shuttingdown(client);
3159         if (fetch_canceled || client_shuttingdown) {
3160                 if (devent->node != NULL)
3161                         dns_db_detachnode(devent->db, &devent->node);
3162                 if (devent->db != NULL)
3163                         dns_db_detach(&devent->db);
3164                 query_putrdataset(client, &devent->rdataset);
3165                 if (devent->sigrdataset != NULL)
3166                         query_putrdataset(client, &devent->sigrdataset);
3167                 isc_event_free(&event);
3168                 if (fetch_canceled)
3169                         query_error(client, DNS_R_SERVFAIL, __LINE__);
3170                 else
3171                         query_next(client, ISC_R_CANCELED);
3172                 /*
3173                  * This may destroy the client.
3174                  */
3175                 ns_client_detach(&client);
3176         } else {
3177                 result = query_find(client, devent, 0);
3178                 if (result != ISC_R_SUCCESS) {
3179                         if (result == DNS_R_SERVFAIL)
3180                                 errorloglevel = ISC_LOG_DEBUG(2);
3181                         else
3182                                 errorloglevel = ISC_LOG_DEBUG(4);
3183                         if (isc_log_wouldlog(ns_g_lctx, errorloglevel)) {
3184                                 dns_resolver_logfetch(fetch, ns_g_lctx,
3185                                                       logcategory,
3186                                                       NS_LOGMODULE_QUERY,
3187                                                       errorloglevel, ISC_FALSE);
3188                         }
3189                 }
3190         }
3191
3192         dns_resolver_destroyfetch(&fetch);
3193 }
3194
3195 static isc_result_t
3196 query_recurse(ns_client_t *client, dns_rdatatype_t qtype, dns_name_t *qdomain,
3197               dns_rdataset_t *nameservers, isc_boolean_t resuming)
3198 {
3199         isc_result_t result;
3200         dns_rdataset_t *rdataset, *sigrdataset;
3201         isc_sockaddr_t *peeraddr;
3202
3203         if (!resuming)
3204                 inc_stats(client, dns_nsstatscounter_recursion);
3205
3206         /*
3207          * We are about to recurse, which means that this client will
3208          * be unavailable for serving new requests for an indeterminate
3209          * amount of time.  If this client is currently responsible
3210          * for handling incoming queries, set up a new client
3211          * object to handle them while we are waiting for a
3212          * response.  There is no need to replace TCP clients
3213          * because those have already been replaced when the
3214          * connection was accepted (if allowed by the TCP quota).
3215          */
3216         if (client->recursionquota == NULL) {
3217                 result = isc_quota_attach(&ns_g_server->recursionquota,
3218                                           &client->recursionquota);
3219                 if  (result == ISC_R_SOFTQUOTA) {
3220                         static isc_stdtime_t last = 0;
3221                         isc_stdtime_t now;
3222                         isc_stdtime_get(&now);
3223                         if (now != last) {
3224                                 last = now;
3225                                 ns_client_log(client, NS_LOGCATEGORY_CLIENT,
3226                                               NS_LOGMODULE_QUERY,
3227                                               ISC_LOG_WARNING,
3228                                               "recursive-clients soft limit "
3229                                               "exceeded, aborting oldest query");
3230                         }
3231                         ns_client_killoldestquery(client);
3232                         result = ISC_R_SUCCESS;
3233                 } else if (result == ISC_R_QUOTA) {
3234                         static isc_stdtime_t last = 0;
3235                         isc_stdtime_t now;
3236                         isc_stdtime_get(&now);
3237                         if (now != last) {
3238                                 last = now;
3239                                 ns_client_log(client, NS_LOGCATEGORY_CLIENT,
3240                                               NS_LOGMODULE_QUERY,
3241                                               ISC_LOG_WARNING,
3242                                               "no more recursive clients: %s",
3243                                               isc_result_totext(result));
3244                         }
3245                         ns_client_killoldestquery(client);
3246                 }
3247                 if (result == ISC_R_SUCCESS && !client->mortal &&
3248                     (client->attributes & NS_CLIENTATTR_TCP) == 0) {
3249                         result = ns_client_replace(client);
3250                         if (result != ISC_R_SUCCESS) {
3251                                 ns_client_log(client, NS_LOGCATEGORY_CLIENT,
3252                                               NS_LOGMODULE_QUERY,
3253                                               ISC_LOG_WARNING,
3254                                               "ns_client_replace() failed: %s",
3255                                               isc_result_totext(result));
3256                                 isc_quota_detach(&client->recursionquota);
3257                         }
3258                 }
3259                 if (result != ISC_R_SUCCESS)
3260                         return (result);
3261                 ns_client_recursing(client);
3262         }
3263
3264         /*
3265          * Invoke the resolver.
3266          */
3267         REQUIRE(nameservers == NULL || nameservers->type == dns_rdatatype_ns);
3268         REQUIRE(client->query.fetch == NULL);
3269
3270         rdataset = query_newrdataset(client);
3271         if (rdataset == NULL)
3272                 return (ISC_R_NOMEMORY);
3273         if (WANTDNSSEC(client)) {
3274                 sigrdataset = query_newrdataset(client);
3275                 if (sigrdataset == NULL) {
3276                         query_putrdataset(client, &rdataset);
3277                         return (ISC_R_NOMEMORY);
3278                 }
3279         } else
3280                 sigrdataset = NULL;
3281
3282         if (client->query.timerset == ISC_FALSE)
3283                 ns_client_settimeout(client, 60);
3284         if ((client->attributes & NS_CLIENTATTR_TCP) == 0)
3285                 peeraddr = &client->peeraddr;
3286         else
3287                 peeraddr = NULL;
3288         result = dns_resolver_createfetch2(client->view->resolver,
3289                                            client->query.qname,
3290                                            qtype, qdomain, nameservers,
3291                                            NULL, peeraddr, client->message->id,
3292                                            client->query.fetchoptions,
3293                                            client->task,
3294                                            query_resume, client,
3295                                            rdataset, sigrdataset,
3296                                            &client->query.fetch);
3297
3298         if (result == ISC_R_SUCCESS) {
3299                 /*
3300                  * Record that we're waiting for an event.  A client which
3301                  * is shutting down will not be destroyed until all the
3302                  * events have been received.
3303                  */
3304         } else {
3305                 query_putrdataset(client, &rdataset);
3306                 if (sigrdataset != NULL)
3307                         query_putrdataset(client, &sigrdataset);
3308         }
3309
3310         return (result);
3311 }
3312
3313 #define MAX_RESTARTS 16
3314
3315 #define QUERY_ERROR(r) \
3316 do { \
3317         eresult = r; \
3318         want_restart = ISC_FALSE; \
3319         line = __LINE__; \
3320 } while (0)
3321
3322 #define RECURSE_ERROR(r) \
3323 do { \
3324         if ((r) == DNS_R_DUPLICATE || (r) == DNS_R_DROP) \
3325                 QUERY_ERROR(r); \
3326         else \
3327                 QUERY_ERROR(DNS_R_SERVFAIL); \
3328 } while (0)
3329
3330 /*
3331  * Extract a network address from the RDATA of an A or AAAA
3332  * record.
3333  *
3334  * Returns:
3335  *      ISC_R_SUCCESS
3336  *      ISC_R_NOTIMPLEMENTED    The rdata is not a known address type.
3337  */
3338 static isc_result_t
3339 rdata_tonetaddr(const dns_rdata_t *rdata, isc_netaddr_t *netaddr) {
3340         struct in_addr ina;
3341         struct in6_addr in6a;
3342
3343         switch (rdata->type) {
3344         case dns_rdatatype_a:
3345                 INSIST(rdata->length == 4);
3346                 memcpy(&ina.s_addr, rdata->data, 4);
3347                 isc_netaddr_fromin(netaddr, &ina);
3348                 return (ISC_R_SUCCESS);
3349         case dns_rdatatype_aaaa:
3350                 INSIST(rdata->length == 16);
3351                 memcpy(in6a.s6_addr, rdata->data, 16);
3352                 isc_netaddr_fromin6(netaddr, &in6a);
3353                 return (ISC_R_SUCCESS);
3354         default:
3355                 return (ISC_R_NOTIMPLEMENTED);
3356         }
3357 }
3358
3359 /*
3360  * Find the sort order of 'rdata' in the topology-like
3361  * ACL forming the second element in a 2-element top-level
3362  * sortlist statement.
3363  */
3364 static int
3365 query_sortlist_order_2element(const dns_rdata_t *rdata, const void *arg) {
3366         isc_netaddr_t netaddr;
3367
3368         if (rdata_tonetaddr(rdata, &netaddr) != ISC_R_SUCCESS)
3369                 return (INT_MAX);
3370         return (ns_sortlist_addrorder2(&netaddr, arg));
3371 }
3372
3373 /*
3374  * Find the sort order of 'rdata' in the matching element
3375  * of a 1-element top-level sortlist statement.
3376  */
3377 static int
3378 query_sortlist_order_1element(const dns_rdata_t *rdata, const void *arg) {
3379         isc_netaddr_t netaddr;
3380
3381         if (rdata_tonetaddr(rdata, &netaddr) != ISC_R_SUCCESS)
3382                 return (INT_MAX);
3383         return (ns_sortlist_addrorder1(&netaddr, arg));
3384 }
3385
3386 /*
3387  * Find the sortlist statement that applies to 'client' and set up
3388  * the sortlist info in in client->message appropriately.
3389  */
3390 static void
3391 setup_query_sortlist(ns_client_t *client) {
3392         isc_netaddr_t netaddr;
3393         dns_rdatasetorderfunc_t order = NULL;
3394         const void *order_arg = NULL;
3395
3396         isc_netaddr_fromsockaddr(&netaddr, &client->peeraddr);
3397         switch (ns_sortlist_setup(client->view->sortlist,
3398                                &netaddr, &order_arg)) {
3399         case NS_SORTLISTTYPE_1ELEMENT:
3400                 order = query_sortlist_order_1element;
3401                 break;
3402         case NS_SORTLISTTYPE_2ELEMENT:
3403                 order = query_sortlist_order_2element;
3404                 break;
3405         case NS_SORTLISTTYPE_NONE:
3406                 order = NULL;
3407                 break;
3408         default:
3409                 INSIST(0);
3410                 break;
3411         }
3412         dns_message_setsortorder(client->message, order, order_arg);
3413 }
3414
3415 static void
3416 query_addnoqnameproof(ns_client_t *client, dns_rdataset_t *rdataset) {
3417         isc_buffer_t *dbuf, b;
3418         dns_name_t *fname;
3419         dns_rdataset_t *neg, *negsig;
3420         isc_result_t result = ISC_R_NOMEMORY;
3421
3422         CTRACE("query_addnoqnameproof");
3423
3424         fname = NULL;
3425         neg = NULL;
3426         negsig = NULL;
3427
3428         dbuf = query_getnamebuf(client);
3429         if (dbuf == NULL)
3430                 goto cleanup;
3431         fname = query_newname(client, dbuf, &b);
3432         neg = query_newrdataset(client);
3433         negsig = query_newrdataset(client);
3434         if (fname == NULL || neg == NULL || negsig == NULL)
3435                 goto cleanup;
3436
3437         result = dns_rdataset_getnoqname(rdataset, fname, neg, negsig);
3438         RUNTIME_CHECK(result == ISC_R_SUCCESS);
3439
3440         query_addrrset(client, &fname, &neg, &negsig, dbuf,
3441                        DNS_SECTION_AUTHORITY);
3442
3443         if ((rdataset->attributes & DNS_RDATASETATTR_CLOSEST) == 0)
3444                 goto cleanup;
3445
3446         if (fname == NULL) {
3447                 dbuf = query_getnamebuf(client);
3448                 if (dbuf == NULL)
3449                         goto cleanup;
3450                 fname = query_newname(client, dbuf, &b);
3451         }
3452         if (neg == NULL)
3453                 neg = query_newrdataset(client);
3454         else if (dns_rdataset_isassociated(neg))
3455                 dns_rdataset_disassociate(neg);
3456         if (negsig == NULL)
3457                 negsig = query_newrdataset(client);
3458         else if (dns_rdataset_isassociated(negsig))
3459                 dns_rdataset_disassociate(negsig);
3460         if (fname == NULL || neg == NULL || negsig == NULL)
3461                 goto cleanup;
3462         result = dns_rdataset_getclosest(rdataset, fname, neg, negsig);
3463         RUNTIME_CHECK(result == ISC_R_SUCCESS);
3464
3465         query_addrrset(client, &fname, &neg, &negsig, dbuf,
3466                        DNS_SECTION_AUTHORITY);
3467
3468  cleanup:
3469         if (neg != NULL)
3470                 query_putrdataset(client, &neg);
3471         if (negsig != NULL)
3472                 query_putrdataset(client, &negsig);
3473         if (fname != NULL)
3474                 query_releasename(client, &fname);
3475 }
3476
3477 static inline void
3478 answer_in_glue(ns_client_t *client, dns_rdatatype_t qtype) {
3479         dns_name_t *name;
3480         dns_message_t *msg;
3481         dns_section_t section = DNS_SECTION_ADDITIONAL;
3482         dns_rdataset_t *rdataset = NULL;
3483
3484         msg = client->message;
3485         for (name = ISC_LIST_HEAD(msg->sections[section]);
3486              name != NULL;
3487              name = ISC_LIST_NEXT(name, link))
3488                 if (dns_name_equal(name, client->query.qname)) {
3489                         for (rdataset = ISC_LIST_HEAD(name->list);
3490                              rdataset != NULL;
3491                              rdataset = ISC_LIST_NEXT(rdataset, link))
3492                                 if (rdataset->type == qtype)
3493                                         break;
3494                         break;
3495                 }
3496         if (rdataset != NULL) {
3497                 ISC_LIST_UNLINK(msg->sections[section], name, link);
3498                 ISC_LIST_PREPEND(msg->sections[section], name, link);
3499                 ISC_LIST_UNLINK(name->list, rdataset, link);
3500                 ISC_LIST_PREPEND(name->list, rdataset, link);
3501                 rdataset->attributes |= DNS_RDATASETATTR_REQUIREDGLUE;
3502         }
3503 }
3504
3505 #define NS_NAME_INIT(A,B) \
3506          { \
3507                 DNS_NAME_MAGIC, \
3508                 A, sizeof(A), sizeof(B), \
3509                 DNS_NAMEATTR_READONLY | DNS_NAMEATTR_ABSOLUTE, \
3510                 B, NULL, { (void *)-1, (void *)-1}, \
3511                 {NULL, NULL} \
3512         }
3513
3514 static unsigned char inaddr10_offsets[] = { 0, 3, 11, 16 };
3515 static unsigned char inaddr172_offsets[] = { 0, 3, 7, 15, 20 };
3516 static unsigned char inaddr192_offsets[] = { 0, 4, 8, 16, 21 };
3517
3518 static unsigned char inaddr10[] = "\00210\007IN-ADDR\004ARPA";
3519
3520 static unsigned char inaddr16172[] = "\00216\003172\007IN-ADDR\004ARPA";
3521 static unsigned char inaddr17172[] = "\00217\003172\007IN-ADDR\004ARPA";
3522 static unsigned char inaddr18172[] = "\00218\003172\007IN-ADDR\004ARPA";
3523 static unsigned char inaddr19172[] = "\00219\003172\007IN-ADDR\004ARPA";
3524 static unsigned char inaddr20172[] = "\00220\003172\007IN-ADDR\004ARPA";
3525 static unsigned char inaddr21172[] = "\00221\003172\007IN-ADDR\004ARPA";
3526 static unsigned char inaddr22172[] = "\00222\003172\007IN-ADDR\004ARPA";
3527 static unsigned char inaddr23172[] = "\00223\003172\007IN-ADDR\004ARPA";
3528 static unsigned char inaddr24172[] = "\00224\003172\007IN-ADDR\004ARPA";
3529 static unsigned char inaddr25172[] = "\00225\003172\007IN-ADDR\004ARPA";
3530 static unsigned char inaddr26172[] = "\00226\003172\007IN-ADDR\004ARPA";
3531 static unsigned char inaddr27172[] = "\00227\003172\007IN-ADDR\004ARPA";
3532 static unsigned char inaddr28172[] = "\00228\003172\007IN-ADDR\004ARPA";
3533 static unsigned char inaddr29172[] = "\00229\003172\007IN-ADDR\004ARPA";
3534 static unsigned char inaddr30172[] = "\00230\003172\007IN-ADDR\004ARPA";
3535 static unsigned char inaddr31172[] = "\00231\003172\007IN-ADDR\004ARPA";
3536
3537 static unsigned char inaddr168192[] = "\003168\003192\007IN-ADDR\004ARPA";
3538
3539 static dns_name_t rfc1918names[] = {
3540         NS_NAME_INIT(inaddr10, inaddr10_offsets),
3541         NS_NAME_INIT(inaddr16172, inaddr172_offsets),
3542         NS_NAME_INIT(inaddr17172, inaddr172_offsets),
3543         NS_NAME_INIT(inaddr18172, inaddr172_offsets),
3544         NS_NAME_INIT(inaddr19172, inaddr172_offsets),
3545         NS_NAME_INIT(inaddr20172, inaddr172_offsets),
3546         NS_NAME_INIT(inaddr21172, inaddr172_offsets),
3547         NS_NAME_INIT(inaddr22172, inaddr172_offsets),
3548         NS_NAME_INIT(inaddr23172, inaddr172_offsets),
3549         NS_NAME_INIT(inaddr24172, inaddr172_offsets),
3550         NS_NAME_INIT(inaddr25172, inaddr172_offsets),
3551         NS_NAME_INIT(inaddr26172, inaddr172_offsets),
3552         NS_NAME_INIT(inaddr27172, inaddr172_offsets),
3553         NS_NAME_INIT(inaddr28172, inaddr172_offsets),
3554         NS_NAME_INIT(inaddr29172, inaddr172_offsets),
3555         NS_NAME_INIT(inaddr30172, inaddr172_offsets),
3556         NS_NAME_INIT(inaddr31172, inaddr172_offsets),
3557         NS_NAME_INIT(inaddr168192, inaddr192_offsets)
3558 };
3559
3560
3561 static unsigned char prisoner_data[] = "\010prisoner\004iana\003org";
3562 static unsigned char hostmaster_data[] = "\012hostmaster\014root-servers\003org";
3563
3564 static unsigned char prisoner_offsets[] = { 0, 9, 14, 18 };
3565 static unsigned char hostmaster_offsets[] = { 0, 11, 24, 28 };
3566
3567 static dns_name_t prisoner = NS_NAME_INIT(prisoner_data, prisoner_offsets);
3568 static dns_name_t hostmaster = NS_NAME_INIT(hostmaster_data, hostmaster_offsets);
3569
3570 static void
3571 warn_rfc1918(ns_client_t *client, dns_name_t *fname, dns_rdataset_t *rdataset) {
3572         unsigned int i;
3573         dns_rdata_t rdata = DNS_RDATA_INIT;
3574         dns_rdata_soa_t soa;
3575         dns_rdataset_t found;
3576         isc_result_t result;
3577
3578         for (i = 0; i < (sizeof(rfc1918names)/sizeof(*rfc1918names)); i++) {
3579                 if (dns_name_issubdomain(fname, &rfc1918names[i])) {
3580                         dns_rdataset_init(&found);
3581                         result = dns_ncache_getrdataset(rdataset,
3582                                                         &rfc1918names[i],
3583                                                         dns_rdatatype_soa,
3584                                                         &found);
3585                         if (result != ISC_R_SUCCESS)
3586                                 return;
3587
3588                         result = dns_rdataset_first(&found);
3589                         RUNTIME_CHECK(result == ISC_R_SUCCESS);
3590                         dns_rdataset_current(&found, &rdata);
3591                         result = dns_rdata_tostruct(&rdata, &soa, NULL);
3592                         RUNTIME_CHECK(result == ISC_R_SUCCESS);
3593                         if (dns_name_equal(&soa.origin, &prisoner) &&
3594                             dns_name_equal(&soa.contact, &hostmaster)) {
3595                                 char buf[DNS_NAME_FORMATSIZE];
3596                                 dns_name_format(fname, buf, sizeof(buf));
3597                                 ns_client_log(client, DNS_LOGCATEGORY_SECURITY,
3598                                               NS_LOGMODULE_QUERY,
3599                                               ISC_LOG_WARNING,
3600                                               "RFC 1918 response from "
3601                                               "Internet for %s", buf);
3602                         }
3603                         dns_rdataset_disassociate(&found);
3604                         return;
3605                 }
3606         }
3607 }
3608
3609 static void
3610 query_findclosestnsec3(dns_name_t *qname, dns_db_t *db,
3611                        dns_dbversion_t *version, ns_client_t *client,
3612                        dns_rdataset_t *rdataset, dns_rdataset_t *sigrdataset,
3613                        dns_name_t *fname, isc_boolean_t exact,
3614                        dns_name_t *found)
3615 {
3616         unsigned char salt[256];
3617         size_t salt_length;
3618         isc_uint16_t iterations;
3619         isc_result_t result;
3620         unsigned int dboptions;
3621         dns_fixedname_t fixed;
3622         dns_hash_t hash;
3623         dns_name_t name;
3624         int order;
3625         unsigned int count;
3626         dns_rdata_nsec3_t nsec3;
3627         dns_rdata_t rdata = DNS_RDATA_INIT;
3628         isc_boolean_t optout;
3629
3630         salt_length = sizeof(salt);
3631         result = dns_db_getnsec3parameters(db, version, &hash, NULL,
3632                                            &iterations, salt, &salt_length);
3633         if (result != ISC_R_SUCCESS)
3634                 return;
3635
3636         dns_name_init(&name, NULL);
3637         dns_name_clone(qname, &name);
3638
3639         /*
3640          * Map unknown algorithm to known value.
3641          */
3642         if (hash == DNS_NSEC3_UNKNOWNALG)
3643                 hash = 1;
3644
3645  again:
3646         dns_fixedname_init(&fixed);
3647         result = dns_nsec3_hashname(&fixed, NULL, NULL, &name,
3648                                     dns_db_origin(db), hash,
3649                                     iterations, salt, salt_length);
3650         if (result != ISC_R_SUCCESS)
3651                 return;
3652
3653         dboptions = client->query.dboptions | DNS_DBFIND_FORCENSEC3;
3654         result = dns_db_find(db, dns_fixedname_name(&fixed), version,
3655                              dns_rdatatype_nsec3, dboptions, client->now,
3656                              NULL, fname, rdataset, sigrdataset);
3657
3658         if (result == DNS_R_NXDOMAIN) {
3659                 if (!dns_rdataset_isassociated(rdataset)) {
3660                         return;
3661                 }
3662                 result = dns_rdataset_first(rdataset);
3663                 INSIST(result == ISC_R_SUCCESS);
3664                 dns_rdataset_current(rdataset, &rdata);
3665                 dns_rdata_tostruct(&rdata, &nsec3, NULL);
3666                 dns_rdata_reset(&rdata);
3667                 optout = ISC_TF((nsec3.flags & DNS_NSEC3FLAG_OPTOUT) != 0);
3668                 if (found != NULL && optout &&
3669                     dns_name_fullcompare(&name, dns_db_origin(db), &order,
3670                                          &count) == dns_namereln_subdomain) {
3671                         dns_rdataset_disassociate(rdataset);
3672                         if (dns_rdataset_isassociated(sigrdataset))
3673                                 dns_rdataset_disassociate(sigrdataset);
3674                         count = dns_name_countlabels(&name) - 1;
3675                         dns_name_getlabelsequence(&name, 1, count, &name);
3676                         ns_client_log(client, DNS_LOGCATEGORY_DNSSEC,
3677                                       NS_LOGMODULE_QUERY, ISC_LOG_DEBUG(3),
3678                                       "looking for closest provable encloser");
3679                         goto again;
3680                 }
3681                 if (exact)
3682                         ns_client_log(client, DNS_LOGCATEGORY_DNSSEC,
3683                                       NS_LOGMODULE_QUERY, ISC_LOG_WARNING,
3684                                       "expected a exact match NSEC3, got "
3685                                       "a covering record");
3686
3687         } else if (result != ISC_R_SUCCESS) {
3688                 return;
3689         } else if (!exact)
3690                 ns_client_log(client, DNS_LOGCATEGORY_DNSSEC,
3691                               NS_LOGMODULE_QUERY, ISC_LOG_WARNING,
3692                               "expected covering NSEC3, got an exact match");
3693         if (found != NULL)
3694                 dns_name_copy(&name, found, NULL);
3695         return;
3696 }
3697
3698 /*
3699  * Do the bulk of query processing for the current query of 'client'.
3700  * If 'event' is non-NULL, we are returning from recursion and 'qtype'
3701  * is ignored.  Otherwise, 'qtype' is the query type.
3702  */
3703 static isc_result_t
3704 query_find(ns_client_t *client, dns_fetchevent_t *event, dns_rdatatype_t qtype)
3705 {
3706         dns_db_t *db, *zdb;
3707         dns_dbnode_t *node;
3708         dns_rdatatype_t type;
3709         dns_name_t *fname, *zfname, *tname, *prefix;
3710         dns_rdataset_t *rdataset, *trdataset;
3711         dns_rdataset_t *sigrdataset, *zrdataset, *zsigrdataset;
3712         dns_rdataset_t **sigrdatasetp;
3713         dns_rdata_t rdata = DNS_RDATA_INIT;
3714         dns_rdatasetiter_t *rdsiter;
3715         isc_boolean_t want_restart, authoritative, is_zone, need_wildcardproof;
3716         unsigned int n, nlabels;
3717         dns_namereln_t namereln;
3718         int order;
3719         isc_buffer_t *dbuf;
3720         isc_buffer_t b;
3721         isc_result_t result, eresult;
3722         dns_fixedname_t fixed;
3723         dns_fixedname_t wildcardname;
3724         dns_dbversion_t *version, *zversion;
3725         dns_zone_t *zone;
3726         dns_rdata_cname_t cname;
3727         dns_rdata_dname_t dname;
3728         unsigned int options;
3729         isc_boolean_t empty_wild;
3730         dns_rdataset_t *noqname;
3731         isc_boolean_t resuming;
3732         int line = -1;
3733
3734         CTRACE("query_find");
3735
3736         /*
3737          * One-time initialization.
3738          *
3739          * It's especially important to initialize anything that the cleanup
3740          * code might cleanup.
3741          */
3742
3743         eresult = ISC_R_SUCCESS;
3744         fname = NULL;
3745         zfname = NULL;
3746         rdataset = NULL;
3747         zrdataset = NULL;
3748         sigrdataset = NULL;
3749         zsigrdataset = NULL;
3750         zversion = NULL;
3751         node = NULL;
3752         db = NULL;
3753         zdb = NULL;
3754         version = NULL;
3755         zone = NULL;
3756         need_wildcardproof = ISC_FALSE;
3757         empty_wild = ISC_FALSE;
3758         options = 0;
3759         resuming = ISC_FALSE;
3760         is_zone = ISC_FALSE;
3761
3762         if (event != NULL) {
3763                 /*
3764                  * We're returning from recursion.  Restore the query context
3765                  * and resume.
3766                  */
3767
3768                 want_restart = ISC_FALSE;
3769                 authoritative = ISC_FALSE;
3770
3771                 qtype = event->qtype;
3772                 if (qtype == dns_rdatatype_rrsig || qtype == dns_rdatatype_sig)
3773                         type = dns_rdatatype_any;
3774                 else
3775                         type = qtype;
3776                 db = event->db;
3777                 node = event->node;
3778                 rdataset = event->rdataset;
3779                 sigrdataset = event->sigrdataset;
3780
3781                 /*
3782                  * We'll need some resources...
3783                  */
3784                 dbuf = query_getnamebuf(client);
3785                 if (dbuf == NULL) {
3786                         QUERY_ERROR(DNS_R_SERVFAIL);
3787                         goto cleanup;
3788                 }
3789                 fname = query_newname(client, dbuf, &b);
3790                 if (fname == NULL) {
3791                         QUERY_ERROR(DNS_R_SERVFAIL);
3792                         goto cleanup;
3793                 }
3794                 tname = dns_fixedname_name(&event->foundname);
3795                 result = dns_name_copy(tname, fname, NULL);
3796                 if (result != ISC_R_SUCCESS) {
3797                         QUERY_ERROR(DNS_R_SERVFAIL);
3798                         goto cleanup;
3799                 }
3800
3801                 result = event->result;
3802                 resuming = ISC_TRUE;
3803
3804                 goto resume;
3805         }
3806
3807         /*
3808          * Not returning from recursion.
3809          */
3810
3811         /*
3812          * If it's a SIG query, we'll iterate the node.
3813          */
3814         if (qtype == dns_rdatatype_rrsig || qtype == dns_rdatatype_sig)
3815                 type = dns_rdatatype_any;
3816         else
3817                 type = qtype;
3818
3819  restart:
3820         CTRACE("query_find: restart");
3821         want_restart = ISC_FALSE;
3822         authoritative = ISC_FALSE;
3823         version = NULL;
3824         need_wildcardproof = ISC_FALSE;
3825
3826         if (client->view->checknames &&
3827             !dns_rdata_checkowner(client->query.qname,
3828                                   client->message->rdclass,
3829                                   qtype, ISC_FALSE)) {
3830                 char namebuf[DNS_NAME_FORMATSIZE];
3831                 char typename[DNS_RDATATYPE_FORMATSIZE];
3832                 char classname[DNS_RDATACLASS_FORMATSIZE];
3833
3834                 dns_name_format(client->query.qname, namebuf, sizeof(namebuf));
3835                 dns_rdatatype_format(qtype, typename, sizeof(typename));
3836                 dns_rdataclass_format(client->message->rdclass, classname,
3837                                       sizeof(classname));
3838                 ns_client_log(client, DNS_LOGCATEGORY_SECURITY,
3839                               NS_LOGMODULE_QUERY, ISC_LOG_ERROR,
3840                               "check-names failure %s/%s/%s", namebuf,
3841                               typename, classname);
3842                 QUERY_ERROR(DNS_R_REFUSED);
3843                 goto cleanup;
3844         }
3845
3846         /*
3847          * First we must find the right database.
3848          */
3849         options &= DNS_GETDB_NOLOG; /* Preserve DNS_GETDB_NOLOG. */
3850         if (dns_rdatatype_atparent(qtype) &&
3851             !dns_name_equal(client->query.qname, dns_rootname))
3852                 options |= DNS_GETDB_NOEXACT;
3853         result = query_getdb(client, client->query.qname, qtype, options,
3854                              &zone, &db, &version, &is_zone);
3855         if ((result != ISC_R_SUCCESS || !is_zone) && !RECURSIONOK(client) &&
3856             (options & DNS_GETDB_NOEXACT) != 0 && qtype == dns_rdatatype_ds) {
3857                 /*
3858                  * Look to see if we are authoritative for the
3859                  * child zone if the query type is DS.
3860                  */
3861                 dns_db_t *tdb = NULL;
3862                 dns_zone_t *tzone = NULL;
3863                 dns_dbversion_t *tversion = NULL;
3864                 isc_result_t tresult;
3865
3866                 tresult = query_getzonedb(client, client->query.qname, qtype,
3867                                          DNS_GETDB_PARTIAL, &tzone, &tdb,
3868                                          &tversion);
3869                 if (tresult == ISC_R_SUCCESS) {
3870                         options &= ~DNS_GETDB_NOEXACT;
3871                         query_putrdataset(client, &rdataset);
3872                         if (db != NULL)
3873                                 dns_db_detach(&db);
3874                         if (zone != NULL)
3875                                 dns_zone_detach(&zone);
3876                         version = tversion;
3877                         db = tdb;
3878                         zone = tzone;
3879                         is_zone = ISC_TRUE;
3880                         result = ISC_R_SUCCESS;
3881                 } else {
3882                         if (tdb != NULL)
3883                                 dns_db_detach(&tdb);
3884                         if (tzone != NULL)
3885                                 dns_zone_detach(&tzone);
3886                 }
3887         }
3888         if (result != ISC_R_SUCCESS) {
3889                 if (result == DNS_R_REFUSED) {
3890                         if (WANTRECURSION(client)) {
3891                                 inc_stats(client,
3892                                           dns_nsstatscounter_recurserej);
3893                         } else
3894                                 inc_stats(client, dns_nsstatscounter_authrej);
3895                         if (!PARTIALANSWER(client))
3896                                 QUERY_ERROR(DNS_R_REFUSED);
3897                 } else
3898                         QUERY_ERROR(DNS_R_SERVFAIL);
3899                 goto cleanup;
3900         }
3901
3902         if (is_zone)
3903                 authoritative = ISC_TRUE;
3904
3905         if (event == NULL && client->query.restarts == 0) {
3906                 if (is_zone) {
3907 #ifdef DLZ
3908                         if (zone != NULL) {
3909                                 /*
3910                                  * if is_zone = true, zone = NULL then this is
3911                                  * a DLZ zone.  Don't attempt to attach zone.
3912                                  */
3913 #endif
3914                                 dns_zone_attach(zone, &client->query.authzone);
3915 #ifdef DLZ
3916                         }
3917 #endif
3918                         dns_db_attach(db, &client->query.authdb);
3919                 }
3920                 client->query.authdbset = ISC_TRUE;
3921         }
3922
3923  db_find:
3924         CTRACE("query_find: db_find");
3925         /*
3926          * We'll need some resources...
3927          */
3928         dbuf = query_getnamebuf(client);
3929         if (dbuf == NULL) {
3930                 QUERY_ERROR(DNS_R_SERVFAIL);
3931                 goto cleanup;
3932         }
3933         fname = query_newname(client, dbuf, &b);
3934         rdataset = query_newrdataset(client);
3935         if (fname == NULL || rdataset == NULL) {
3936                 QUERY_ERROR(DNS_R_SERVFAIL);
3937                 goto cleanup;
3938         }
3939         if (WANTDNSSEC(client) && (!is_zone || dns_db_issecure(db))) {
3940                 sigrdataset = query_newrdataset(client);
3941                 if (sigrdataset == NULL) {
3942                         QUERY_ERROR(DNS_R_SERVFAIL);
3943                         goto cleanup;
3944                 }
3945         }
3946
3947         /*
3948          * Now look for an answer in the database.
3949          */
3950         result = dns_db_find(db, client->query.qname, version, type,
3951                              client->query.dboptions, client->now,
3952                              &node, fname, rdataset, sigrdataset);
3953
3954  resume:
3955         CTRACE("query_find: resume");
3956         switch (result) {
3957         case ISC_R_SUCCESS:
3958                 /*
3959                  * This case is handled in the main line below.
3960                  */
3961                 break;
3962         case DNS_R_GLUE:
3963         case DNS_R_ZONECUT:
3964                 /*
3965                  * These cases are handled in the main line below.
3966                  */
3967                 INSIST(is_zone);
3968                 authoritative = ISC_FALSE;
3969                 break;
3970         case ISC_R_NOTFOUND:
3971                 /*
3972                  * The cache doesn't even have the root NS.  Get them from
3973                  * the hints DB.
3974                  */
3975                 INSIST(!is_zone);
3976                 if (db != NULL)
3977                         dns_db_detach(&db);
3978
3979                 if (client->view->hints == NULL) {
3980                         /* We have no hints. */
3981                         result = ISC_R_FAILURE;
3982                 } else {
3983                         dns_db_attach(client->view->hints, &db);
3984                         result = dns_db_find(db, dns_rootname,
3985                                              NULL, dns_rdatatype_ns,
3986                                              0, client->now, &node, fname,
3987                                              rdataset, sigrdataset);
3988                 }
3989                 if (result != ISC_R_SUCCESS) {
3990                         /*
3991                          * Nonsensical root hints may require cleanup.
3992                          */
3993                         if (dns_rdataset_isassociated(rdataset))
3994                                 dns_rdataset_disassociate(rdataset);
3995                         if (sigrdataset != NULL &&
3996                             dns_rdataset_isassociated(sigrdataset))
3997                                 dns_rdataset_disassociate(sigrdataset);
3998                         if (node != NULL)
3999                                 dns_db_detachnode(db, &node);
4000
4001                         /*
4002                          * We don't have any root server hints, but
4003                          * we may have working forwarders, so try to
4004                          * recurse anyway.
4005                          */
4006                         if (RECURSIONOK(client)) {
4007                                 result = query_recurse(client, qtype,
4008                                                        NULL, NULL, resuming);
4009                                 if (result == ISC_R_SUCCESS)
4010                                         client->query.attributes |=
4011                                                 NS_QUERYATTR_RECURSING;
4012                                 else
4013                                         RECURSE_ERROR(result);
4014                                 goto cleanup;
4015                         } else {
4016                                 /* Unable to give root server referral. */
4017                                 QUERY_ERROR(DNS_R_SERVFAIL);
4018                                 goto cleanup;
4019                         }
4020                 }
4021                 /*
4022                  * XXXRTH  We should trigger root server priming here.
4023                  */
4024                 /* FALLTHROUGH */
4025         case DNS_R_DELEGATION:
4026                 authoritative = ISC_FALSE;
4027                 if (is_zone) {
4028                         /*
4029                          * Look to see if we are authoritative for the
4030                          * child zone if the query type is DS.
4031                          */
4032                         if (!RECURSIONOK(client) &&
4033                             (options & DNS_GETDB_NOEXACT) != 0 &&
4034                             qtype == dns_rdatatype_ds) {
4035                                 dns_db_t *tdb = NULL;
4036                                 dns_zone_t *tzone = NULL;
4037                                 dns_dbversion_t *tversion = NULL;
4038                                 result = query_getzonedb(client,
4039                                                          client->query.qname,
4040                                                          qtype,
4041                                                          DNS_GETDB_PARTIAL,
4042                                                          &tzone, &tdb,
4043                                                          &tversion);
4044                                 if (result == ISC_R_SUCCESS) {
4045                                         options &= ~DNS_GETDB_NOEXACT;
4046                                         query_putrdataset(client, &rdataset);
4047                                         if (sigrdataset != NULL)
4048                                                 query_putrdataset(client,
4049                                                                   &sigrdataset);
4050                                         if (fname != NULL)
4051                                                 query_releasename(client,
4052                                                                   &fname);
4053                                         if (node != NULL)
4054                                                 dns_db_detachnode(db, &node);
4055                                         if (db != NULL)
4056                                                 dns_db_detach(&db);
4057                                         if (zone != NULL)
4058                                                 dns_zone_detach(&zone);
4059                                         version = tversion;
4060                                         db = tdb;
4061                                         zone = tzone;
4062                                         authoritative = ISC_TRUE;
4063                                         goto db_find;
4064                                 }
4065                                 if (tdb != NULL)
4066                                         dns_db_detach(&tdb);
4067                                 if (tzone != NULL)
4068                                         dns_zone_detach(&tzone);
4069                         }
4070                         /*
4071                          * We're authoritative for an ancestor of QNAME.
4072                          */
4073                         if (!USECACHE(client) || !RECURSIONOK(client)) {
4074                                 dns_fixedname_t fixed;
4075
4076                                 dns_fixedname_init(&fixed);
4077                                 dns_name_copy(fname,
4078                                               dns_fixedname_name(&fixed), NULL);
4079
4080                                 /*
4081                                  * If we don't have a cache, this is the best
4082                                  * answer.
4083                                  *
4084                                  * If the client is making a nonrecursive
4085                                  * query we always give out the authoritative
4086                                  * delegation.  This way even if we get
4087                                  * junk in our cache, we won't fail in our
4088                                  * role as the delegating authority if another
4089                                  * nameserver asks us about a delegated
4090                                  * subzone.
4091                                  *
4092                                  * We enable the retrieval of glue for this
4093                                  * database by setting client->query.gluedb.
4094                                  */
4095                                 client->query.gluedb = db;
4096                                 client->query.isreferral = ISC_TRUE;
4097                                 /*
4098                                  * We must ensure NOADDITIONAL is off,
4099                                  * because the generation of
4100                                  * additional data is required in
4101                                  * delegations.
4102                                  */
4103                                 client->query.attributes &=
4104                                         ~NS_QUERYATTR_NOADDITIONAL;
4105                                 if (sigrdataset != NULL)
4106                                         sigrdatasetp = &sigrdataset;
4107                                 else
4108                                         sigrdatasetp = NULL;
4109                                 query_addrrset(client, &fname,
4110                                                &rdataset, sigrdatasetp,
4111                                                dbuf, DNS_SECTION_AUTHORITY);
4112                                 client->query.gluedb = NULL;
4113                                 if (WANTDNSSEC(client))
4114                                         query_addds(client, db, node, version,
4115                                                    dns_fixedname_name(&fixed));
4116                         } else {
4117                                 /*
4118                                  * We might have a better answer or delegation
4119                                  * in the cache.  We'll remember the current
4120                                  * values of fname, rdataset, and sigrdataset.
4121                                  * We'll then go looking for QNAME in the
4122                                  * cache.  If we find something better, we'll
4123                                  * use it instead.
4124                                  */
4125                                 query_keepname(client, fname, dbuf);
4126                                 zdb = db;
4127                                 zfname = fname;
4128                                 fname = NULL;
4129                                 zrdataset = rdataset;
4130                                 rdataset = NULL;
4131                                 zsigrdataset = sigrdataset;
4132                                 sigrdataset = NULL;
4133                                 dns_db_detachnode(db, &node);
4134                                 zversion = version;
4135                                 version = NULL;
4136                                 db = NULL;
4137                                 dns_db_attach(client->view->cachedb, &db);
4138                                 is_zone = ISC_FALSE;
4139                                 goto db_find;
4140                         }
4141                 } else {
4142                         if (zfname != NULL &&
4143                             !dns_name_issubdomain(fname, zfname)) {
4144                                 /*
4145                                  * We've already got a delegation from
4146                                  * authoritative data, and it is better
4147                                  * than what we found in the cache.  Use
4148                                  * it instead of the cache delegation.
4149                                  */
4150                                 query_releasename(client, &fname);
4151                                 fname = zfname;
4152                                 zfname = NULL;
4153                                 /*
4154                                  * We've already done query_keepname() on
4155                                  * zfname, so we must set dbuf to NULL to
4156                                  * prevent query_addrrset() from trying to
4157                                  * call query_keepname() again.
4158                                  */
4159                                 dbuf = NULL;
4160                                 query_putrdataset(client, &rdataset);
4161                                 if (sigrdataset != NULL)
4162                                         query_putrdataset(client,
4163                                                           &sigrdataset);
4164                                 rdataset = zrdataset;
4165                                 zrdataset = NULL;
4166                                 sigrdataset = zsigrdataset;
4167                                 zsigrdataset = NULL;
4168                                 version = zversion;
4169                                 zversion = NULL;
4170                                 /*
4171                                  * We don't clean up zdb here because we
4172                                  * may still need it.  It will get cleaned
4173                                  * up by the main cleanup code.
4174                                  */
4175                         }
4176
4177                         if (RECURSIONOK(client)) {
4178                                 /*
4179                                  * Recurse!
4180                                  */
4181                                 if (dns_rdatatype_atparent(type))
4182                                         result = query_recurse(client, qtype,
4183                                                                NULL, NULL,
4184                                                                resuming);
4185                                 else
4186                                         result = query_recurse(client, qtype,
4187                                                                fname, rdataset,
4188                                                                resuming);
4189                                 if (result == ISC_R_SUCCESS)
4190                                         client->query.attributes |=
4191                                                 NS_QUERYATTR_RECURSING;
4192                                 else
4193                                         RECURSE_ERROR(result);
4194                         } else {
4195                                 dns_fixedname_t fixed;
4196
4197                                 dns_fixedname_init(&fixed);
4198                                 dns_name_copy(fname,
4199                                               dns_fixedname_name(&fixed), NULL);
4200                                 /*
4201                                  * This is the best answer.
4202                                  */
4203                                 client->query.attributes |=
4204                                         NS_QUERYATTR_CACHEGLUEOK;
4205                                 client->query.gluedb = zdb;
4206                                 client->query.isreferral = ISC_TRUE;
4207                                 /*
4208                                  * We must ensure NOADDITIONAL is off,
4209                                  * because the generation of
4210                                  * additional data is required in
4211                                  * delegations.
4212                                  */
4213                                 client->query.attributes &=
4214                                         ~NS_QUERYATTR_NOADDITIONAL;
4215                                 if (sigrdataset != NULL)
4216                                         sigrdatasetp = &sigrdataset;
4217                                 else
4218                                         sigrdatasetp = NULL;
4219                                 query_addrrset(client, &fname,
4220                                                &rdataset, sigrdatasetp,
4221                                                dbuf, DNS_SECTION_AUTHORITY);
4222                                 client->query.gluedb = NULL;
4223                                 client->query.attributes &=
4224                                         ~NS_QUERYATTR_CACHEGLUEOK;
4225                                 if (WANTDNSSEC(client))
4226                                         query_addds(client, db, node, version,
4227                                                    dns_fixedname_name(&fixed));
4228                         }
4229                 }
4230                 goto cleanup;
4231         case DNS_R_EMPTYNAME:
4232                 result = DNS_R_NXRRSET;
4233                 /* FALLTHROUGH */
4234         case DNS_R_NXRRSET:
4235                 INSIST(is_zone);
4236                 /*
4237                  * Look for a NSEC3 record if we don't have a NSEC record.
4238                  */
4239                 if (!dns_rdataset_isassociated(rdataset) &&
4240                      WANTDNSSEC(client)) {
4241                         if ((fname->attributes & DNS_NAMEATTR_WILDCARD) == 0) {
4242                                 dns_name_t *found;
4243                                 dns_name_t *qname;
4244
4245                                 dns_fixedname_init(&fixed);
4246                                 found = dns_fixedname_name(&fixed);
4247                                 qname = client->query.qname;
4248
4249                                 query_findclosestnsec3(qname, db, version,
4250                                                        client, rdataset,
4251                                                        sigrdataset, fname,
4252                                                        ISC_TRUE, found);
4253                                 /*
4254                                  * Did we find the closest provable encloser
4255                                  * instead? If so add the nearest to the
4256                                  * closest provable encloser.
4257                                  */
4258                                 if (found &&
4259                                     dns_rdataset_isassociated(rdataset) &&
4260                                     !dns_name_equal(qname, found))
4261                                 {
4262                                         unsigned int count;
4263                                         unsigned int skip;
4264
4265                                         /*
4266                                          * Add the closest provable encloser.
4267                                          */
4268                                         query_addrrset(client, &fname,
4269                                                        &rdataset, &sigrdataset,
4270                                                        dbuf,
4271                                                        DNS_SECTION_AUTHORITY);
4272
4273                                         count = dns_name_countlabels(found)
4274                                                          + 1;
4275                                         skip = dns_name_countlabels(qname) -
4276                                                          count;
4277                                         dns_name_getlabelsequence(qname, skip,
4278                                                                   count,
4279                                                                   found);
4280
4281                                         fixfname(client, &fname, &dbuf, &b);
4282                                         fixrdataset(client, &rdataset);
4283                                         fixrdataset(client, &sigrdataset);
4284                                         if (fname == NULL ||
4285                                             rdataset == NULL ||
4286                                             sigrdataset == NULL) {
4287                                                 QUERY_ERROR(DNS_R_SERVFAIL);
4288                                                 goto cleanup;
4289                                         }
4290                                         /*
4291                                          * 'nearest' doesn't exist so
4292                                          * 'exist' is set to ISC_FALSE.
4293                                          */
4294                                         query_findclosestnsec3(found, db,
4295                                                                version,
4296                                                                client,
4297                                                                rdataset,
4298                                                                sigrdataset,
4299                                                                fname,
4300                                                                ISC_FALSE,
4301                                                                NULL);
4302                                 }
4303                         } else {
4304                                 query_releasename(client, &fname);
4305                                 query_addwildcardproof(client, db, version,
4306                                                        client->query.qname,
4307                                                        ISC_FALSE);
4308                         }
4309                 }
4310                 if (dns_rdataset_isassociated(rdataset)) {
4311                         /*
4312                          * If we've got a NSEC record, we need to save the
4313                          * name now because we're going call query_addsoa()
4314                          * below, and it needs to use the name buffer.
4315                          */
4316                         query_keepname(client, fname, dbuf);
4317                 } else if (fname != NULL) {
4318                         /*
4319                          * We're not going to use fname, and need to release
4320                          * our hold on the name buffer so query_addsoa()
4321                          * may use it.
4322                          */
4323                         query_releasename(client, &fname);
4324                 }
4325                 /*
4326                  * Add SOA.
4327                  */
4328                 result = query_addsoa(client, db, version, ISC_FALSE,
4329                                       dns_rdataset_isassociated(rdataset));
4330                 if (result != ISC_R_SUCCESS) {
4331                         QUERY_ERROR(result);
4332                         goto cleanup;
4333                 }
4334                 /*
4335                  * Add NSEC record if we found one.
4336                  */
4337                 if (WANTDNSSEC(client)) {
4338                         if (dns_rdataset_isassociated(rdataset))
4339                                 query_addnxrrsetnsec(client, db, version,
4340                                                      &fname, &rdataset,
4341                                                      &sigrdataset);
4342                 }
4343                 goto cleanup;
4344
4345         case DNS_R_EMPTYWILD:
4346                 empty_wild = ISC_TRUE;
4347                 /* FALLTHROUGH */
4348
4349         case DNS_R_NXDOMAIN:
4350                 INSIST(is_zone);
4351                 if (dns_rdataset_isassociated(rdataset)) {
4352                         /*
4353                          * If we've got a NSEC record, we need to save the
4354                          * name now because we're going call query_addsoa()
4355                          * below, and it needs to use the name buffer.
4356                          */
4357                         query_keepname(client, fname, dbuf);
4358                 } else if (fname != NULL) {
4359                         /*
4360                          * We're not going to use fname, and need to release
4361                          * our hold on the name buffer so query_addsoa()
4362                          * may use it.
4363                          */
4364                         query_releasename(client, &fname);
4365                 }
4366                 /*
4367                  * Add SOA.  If the query was for a SOA record force the
4368                  * ttl to zero so that it is possible for clients to find
4369                  * the containing zone of an arbitrary name with a stub
4370                  * resolver and not have it cached.
4371                  */
4372                 if (qtype == dns_rdatatype_soa &&
4373 #ifdef DLZ
4374                     zone != NULL &&
4375 #endif
4376                     dns_zone_getzeronosoattl(zone))
4377                         result = query_addsoa(client, db, version, ISC_TRUE,
4378                                           dns_rdataset_isassociated(rdataset));
4379                 else
4380                         result = query_addsoa(client, db, version, ISC_FALSE,
4381                                           dns_rdataset_isassociated(rdataset));
4382                 if (result != ISC_R_SUCCESS) {
4383                         QUERY_ERROR(result);
4384                         goto cleanup;
4385                 }
4386
4387                 if (WANTDNSSEC(client)) {
4388                         /*
4389                          * Add NSEC record if we found one.
4390                          */
4391                         if (dns_rdataset_isassociated(rdataset))
4392                                 query_addrrset(client, &fname, &rdataset,
4393                                                &sigrdataset,
4394                                                NULL, DNS_SECTION_AUTHORITY);
4395                         query_addwildcardproof(client, db, version,
4396                                                client->query.qname, ISC_FALSE);
4397                 }
4398
4399                 /*
4400                  * Set message rcode.
4401                  */
4402                 if (empty_wild)
4403                         client->message->rcode = dns_rcode_noerror;
4404                 else
4405                         client->message->rcode = dns_rcode_nxdomain;
4406                 goto cleanup;
4407
4408         case DNS_R_NCACHENXDOMAIN:
4409         case DNS_R_NCACHENXRRSET:
4410                 INSIST(!is_zone);
4411                 authoritative = ISC_FALSE;
4412                 /*
4413                  * Set message rcode, if required.
4414                  */
4415                 if (result == DNS_R_NCACHENXDOMAIN)
4416                         client->message->rcode = dns_rcode_nxdomain;
4417                 /*
4418                  * Look for RFC 1918 leakage from Internet.
4419                  */
4420                 if (result == DNS_R_NCACHENXDOMAIN &&
4421                     qtype == dns_rdatatype_ptr &&
4422                     client->message->rdclass == dns_rdataclass_in &&
4423                     dns_name_countlabels(fname) == 7)
4424                         warn_rfc1918(client, fname, rdataset);
4425                 /*
4426                  * We don't call query_addrrset() because we don't need any
4427                  * of its extra features (and things would probably break!).
4428                  */
4429                 query_keepname(client, fname, dbuf);
4430                 dns_message_addname(client->message, fname,
4431                                     DNS_SECTION_AUTHORITY);
4432                 ISC_LIST_APPEND(fname->list, rdataset, link);
4433                 fname = NULL;
4434                 rdataset = NULL;
4435                 goto cleanup;
4436
4437         case DNS_R_CNAME:
4438                 /*
4439                  * Keep a copy of the rdataset.  We have to do this because
4440                  * query_addrrset may clear 'rdataset' (to prevent the
4441                  * cleanup code from cleaning it up).
4442                  */
4443                 trdataset = rdataset;
4444                 /*
4445                  * Add the CNAME to the answer section.
4446                  */
4447                 if (sigrdataset != NULL)
4448                         sigrdatasetp = &sigrdataset;
4449                 else
4450                         sigrdatasetp = NULL;
4451                 if (WANTDNSSEC(client) &&
4452                     (fname->attributes & DNS_NAMEATTR_WILDCARD) != 0)
4453                 {
4454                         dns_fixedname_init(&wildcardname);
4455                         dns_name_copy(fname, dns_fixedname_name(&wildcardname),
4456                                       NULL);
4457                         need_wildcardproof = ISC_TRUE;
4458                 }
4459                 if (NOQNAME(rdataset) && WANTDNSSEC(client))
4460                         noqname = rdataset;
4461                 else
4462                         noqname = NULL;
4463                 query_addrrset(client, &fname, &rdataset, sigrdatasetp, dbuf,
4464                                DNS_SECTION_ANSWER);
4465                 if (noqname != NULL)
4466                         query_addnoqnameproof(client, noqname);
4467                 /*
4468                  * We set the PARTIALANSWER attribute so that if anything goes
4469                  * wrong later on, we'll return what we've got so far.
4470                  */
4471                 client->query.attributes |= NS_QUERYATTR_PARTIALANSWER;
4472                 /*
4473                  * Reset qname to be the target name of the CNAME and restart
4474                  * the query.
4475                  */
4476                 tname = NULL;
4477                 result = dns_message_gettempname(client->message, &tname);
4478                 if (result != ISC_R_SUCCESS)
4479                         goto cleanup;
4480                 result = dns_rdataset_first(trdataset);
4481                 if (result != ISC_R_SUCCESS) {
4482                         dns_message_puttempname(client->message, &tname);
4483                         goto cleanup;
4484                 }
4485                 dns_rdataset_current(trdataset, &rdata);
4486                 result = dns_rdata_tostruct(&rdata, &cname, NULL);
4487                 dns_rdata_reset(&rdata);
4488                 if (result != ISC_R_SUCCESS) {
4489                         dns_message_puttempname(client->message, &tname);
4490                         goto cleanup;
4491                 }
4492                 dns_name_init(tname, NULL);
4493                 result = dns_name_dup(&cname.cname, client->mctx, tname);
4494                 if (result != ISC_R_SUCCESS) {
4495                         dns_message_puttempname(client->message, &tname);
4496                         dns_rdata_freestruct(&cname);
4497                         goto cleanup;
4498                 }
4499                 dns_rdata_freestruct(&cname);
4500                 ns_client_qnamereplace(client, tname);
4501                 want_restart = ISC_TRUE;
4502                 if (!WANTRECURSION(client))
4503                         options |= DNS_GETDB_NOLOG;
4504                 goto addauth;
4505         case DNS_R_DNAME:
4506                 /*
4507                  * Compare the current qname to the found name.  We need
4508                  * to know how many labels and bits are in common because
4509                  * we're going to have to split qname later on.
4510                  */
4511                 namereln = dns_name_fullcompare(client->query.qname, fname,
4512                                                 &order, &nlabels);
4513                 INSIST(namereln == dns_namereln_subdomain);
4514                 /*
4515                  * Keep a copy of the rdataset.  We have to do this because
4516                  * query_addrrset may clear 'rdataset' (to prevent the
4517                  * cleanup code from cleaning it up).
4518                  */
4519                 trdataset = rdataset;
4520                 /*
4521                  * Add the DNAME to the answer section.
4522                  */
4523                 if (sigrdataset != NULL)
4524                         sigrdatasetp = &sigrdataset;
4525                 else
4526                         sigrdatasetp = NULL;
4527                 if (WANTDNSSEC(client) &&
4528                     (fname->attributes & DNS_NAMEATTR_WILDCARD) != 0)
4529                 {
4530                         dns_fixedname_init(&wildcardname);
4531                         dns_name_copy(fname, dns_fixedname_name(&wildcardname),
4532                                       NULL);
4533                         need_wildcardproof = ISC_TRUE;
4534                 }
4535                 query_addrrset(client, &fname, &rdataset, sigrdatasetp, dbuf,
4536                                DNS_SECTION_ANSWER);
4537                 /*
4538                  * We set the PARTIALANSWER attribute so that if anything goes
4539                  * wrong later on, we'll return what we've got so far.
4540                  */
4541                 client->query.attributes |= NS_QUERYATTR_PARTIALANSWER;
4542                 /*
4543                  * Get the target name of the DNAME.
4544                  */
4545                 tname = NULL;
4546                 result = dns_message_gettempname(client->message, &tname);
4547                 if (result != ISC_R_SUCCESS)
4548                         goto cleanup;
4549                 result = dns_rdataset_first(trdataset);
4550                 if (result != ISC_R_SUCCESS) {
4551                         dns_message_puttempname(client->message, &tname);
4552                         goto cleanup;
4553                 }
4554                 dns_rdataset_current(trdataset, &rdata);
4555                 result = dns_rdata_tostruct(&rdata, &dname, NULL);
4556                 dns_rdata_reset(&rdata);
4557                 if (result != ISC_R_SUCCESS) {
4558                         dns_message_puttempname(client->message, &tname);
4559                         goto cleanup;
4560                 }
4561                 dns_name_init(tname, NULL);
4562                 dns_name_clone(&dname.dname, tname);
4563                 dns_rdata_freestruct(&dname);
4564                 /*
4565                  * Construct the new qname.
4566                  */
4567                 dns_fixedname_init(&fixed);
4568                 prefix = dns_fixedname_name(&fixed);
4569                 dns_name_split(client->query.qname, nlabels, prefix, NULL);
4570                 INSIST(fname == NULL);
4571                 dbuf = query_getnamebuf(client);
4572                 if (dbuf == NULL) {
4573                         dns_message_puttempname(client->message, &tname);
4574                         goto cleanup;
4575                 }
4576                 fname = query_newname(client, dbuf, &b);
4577                 if (fname == NULL) {
4578                         dns_message_puttempname(client->message, &tname);
4579                         goto cleanup;
4580                 }
4581                 result = dns_name_concatenate(prefix, tname, fname, NULL);
4582                 if (result != ISC_R_SUCCESS) {
4583                         dns_message_puttempname(client->message, &tname);
4584                         if (result == ISC_R_NOSPACE) {
4585                                 /*
4586                                  * RFC2672, section 4.1, subsection 3c says
4587                                  * we should return YXDOMAIN if the constructed
4588                                  * name would be too long.
4589                                  */
4590                                 client->message->rcode = dns_rcode_yxdomain;
4591                         }
4592                         goto cleanup;
4593                 }
4594                 query_keepname(client, fname, dbuf);
4595                 /*
4596                  * Synthesize a CNAME for this DNAME.
4597                  *
4598                  * We want to synthesize a CNAME since if we don't
4599                  * then older software that doesn't understand DNAME
4600                  * will not chain like it should.
4601                  *
4602                  * We do not try to synthesize a signature because we hope
4603                  * that security aware servers will understand DNAME.  Also,
4604                  * even if we had an online key, making a signature
4605                  * on-the-fly is costly, and not really legitimate anyway
4606                  * since the synthesized CNAME is NOT in the zone.
4607                  */
4608                 dns_name_init(tname, NULL);
4609                 (void)query_addcnamelike(client, client->query.qname, fname,
4610                                          trdataset, &tname,
4611                                          dns_rdatatype_cname);
4612                 if (tname != NULL)
4613                         dns_message_puttempname(client->message, &tname);
4614                 /*
4615                  * Switch to the new qname and restart.
4616                  */
4617                 ns_client_qnamereplace(client, fname);
4618                 fname = NULL;
4619                 want_restart = ISC_TRUE;
4620                 if (!WANTRECURSION(client))
4621                         options |= DNS_GETDB_NOLOG;
4622                 goto addauth;
4623         default:
4624                 /*
4625                  * Something has gone wrong.
4626                  */
4627                 QUERY_ERROR(DNS_R_SERVFAIL);
4628                 goto cleanup;
4629         }
4630
4631         if (WANTDNSSEC(client) &&
4632             (fname->attributes & DNS_NAMEATTR_WILDCARD) != 0)
4633         {
4634                 dns_fixedname_init(&wildcardname);
4635                 dns_name_copy(fname, dns_fixedname_name(&wildcardname), NULL);
4636                 need_wildcardproof = ISC_TRUE;
4637         }
4638
4639         if (type == dns_rdatatype_any) {
4640                 /*
4641                  * XXXRTH  Need to handle zonecuts with special case
4642                  * code.
4643                  */
4644                 n = 0;
4645                 rdsiter = NULL;
4646                 result = dns_db_allrdatasets(db, node, version, 0, &rdsiter);
4647                 if (result != ISC_R_SUCCESS) {
4648                         QUERY_ERROR(DNS_R_SERVFAIL);
4649                         goto cleanup;
4650                 }
4651                 /*
4652                  * Calling query_addrrset() with a non-NULL dbuf is going
4653                  * to either keep or release the name.  We don't want it to
4654                  * release fname, since we may have to call query_addrrset()
4655                  * more than once.  That means we have to call query_keepname()
4656                  * now, and pass a NULL dbuf to query_addrrset().
4657                  *
4658                  * If we do a query_addrrset() below, we must set fname to
4659                  * NULL before leaving this block, otherwise we might try to
4660                  * cleanup fname even though we're using it!
4661                  */
4662                 query_keepname(client, fname, dbuf);
4663                 tname = fname;
4664                 result = dns_rdatasetiter_first(rdsiter);
4665                 while (result == ISC_R_SUCCESS) {
4666                         dns_rdatasetiter_current(rdsiter, rdataset);
4667                         if (is_zone && qtype == dns_rdatatype_any &&
4668                             !dns_db_issecure(db) &&
4669                             dns_rdatatype_isdnssec(rdataset->type)) {
4670                                 /*
4671                                  * The zone is transitioning from insecure
4672                                  * to secure. Hide the dnssec records from
4673                                  * ANY queries.
4674                                  */
4675                                 dns_rdataset_disassociate(rdataset);
4676                         } else if ((qtype == dns_rdatatype_any ||
4677                              rdataset->type == qtype) && rdataset->type != 0) {
4678                                 if (NOQNAME(rdataset) && WANTDNSSEC(client))
4679                                         noqname = rdataset;
4680                                 else
4681                                         noqname = NULL;
4682                                 query_addrrset(client,
4683                                                fname != NULL ? &fname : &tname,
4684                                                &rdataset, NULL,
4685                                                NULL, DNS_SECTION_ANSWER);
4686                                 if (noqname != NULL)
4687                                         query_addnoqnameproof(client, noqname);
4688                                 n++;
4689                                 INSIST(tname != NULL);
4690                                 /*
4691                                  * rdataset is non-NULL only in certain
4692                                  * pathological cases involving DNAMEs.
4693                                  */
4694                                 if (rdataset != NULL)
4695                                         query_putrdataset(client, &rdataset);
4696                                 rdataset = query_newrdataset(client);
4697                                 if (rdataset == NULL)
4698                                         break;
4699                         } else {
4700                                 /*
4701                                  * We're not interested in this rdataset.
4702                                  */
4703                                 dns_rdataset_disassociate(rdataset);
4704                         }
4705                         result = dns_rdatasetiter_next(rdsiter);
4706                 }
4707
4708                 if (fname != NULL)
4709                         dns_message_puttempname(client->message, &fname);
4710
4711                 if (n == 0 && is_zone) {
4712                         /*
4713                          * We didn't match any rdatasets.
4714                          */
4715                         if (qtype == dns_rdatatype_rrsig &&
4716                             result == ISC_R_NOMORE) {
4717                                 /*
4718                                  * XXXRTH  If this is a secure zone and we
4719                                  * didn't find any SIGs, we should generate
4720                                  * an error unless we were searching for
4721                                  * glue.  Ugh.
4722                                  */
4723                                 if (!is_zone) {
4724                                         authoritative = ISC_FALSE;
4725                                         dns_rdatasetiter_destroy(&rdsiter);
4726                                         if (RECURSIONOK(client)) {
4727                                                 result = query_recurse(client,
4728                                                                        qtype,
4729                                                                        NULL,
4730                                                                        NULL,
4731                                                                        resuming);
4732                                                 if (result == ISC_R_SUCCESS)
4733                                                     client->query.attributes |=
4734                                                         NS_QUERYATTR_RECURSING;
4735                                                 else
4736                                                     RECURSE_ERROR(result);
4737                                         }
4738                                         goto addauth;
4739                                 }
4740                                 /*
4741                                  * We were searching for SIG records in
4742                                  * a nonsecure zone.  Send a "no error,
4743                                  * no data" response.
4744                                  */
4745                                 /*
4746                                  * Add SOA.
4747                                  */
4748                                 result = query_addsoa(client, db, version,
4749                                                       ISC_FALSE, ISC_FALSE);
4750                                 if (result == ISC_R_SUCCESS)
4751                                         result = ISC_R_NOMORE;
4752                         } else {
4753                                 /*
4754                                  * Something went wrong.
4755                                  */
4756                                 result = DNS_R_SERVFAIL;
4757                         }
4758                 }
4759                 dns_rdatasetiter_destroy(&rdsiter);
4760                 if (result != ISC_R_NOMORE) {
4761                         QUERY_ERROR(DNS_R_SERVFAIL);
4762                         goto cleanup;
4763                 }
4764         } else {
4765                 /*
4766                  * This is the "normal" case -- an ordinary question to which
4767                  * we know the answer.
4768                  */
4769                 if (sigrdataset != NULL)
4770                         sigrdatasetp = &sigrdataset;
4771                 else
4772                         sigrdatasetp = NULL;
4773                 if (NOQNAME(rdataset) && WANTDNSSEC(client))
4774                         noqname = rdataset;
4775                 else
4776                         noqname = NULL;
4777                 /*
4778                  * BIND 8 priming queries need the additional section.
4779                  */
4780                 if (is_zone && qtype == dns_rdatatype_ns &&
4781                     dns_name_equal(client->query.qname, dns_rootname))
4782                         client->query.attributes &= ~NS_QUERYATTR_NOADDITIONAL;
4783
4784                 query_addrrset(client, &fname, &rdataset, sigrdatasetp, dbuf,
4785                                DNS_SECTION_ANSWER);
4786                 if (noqname != NULL)
4787                         query_addnoqnameproof(client, noqname);
4788                 /*
4789                  * We shouldn't ever fail to add 'rdataset'
4790                  * because it's already in the answer.
4791                  */
4792                 INSIST(rdataset == NULL);
4793         }
4794
4795  addauth:
4796         CTRACE("query_find: addauth");
4797         /*
4798          * Add NS records to the authority section (if we haven't already
4799          * added them to the answer section).
4800          */
4801         if (!want_restart && !NOAUTHORITY(client)) {
4802                 if (is_zone) {
4803                         if (!((qtype == dns_rdatatype_ns ||
4804                                qtype == dns_rdatatype_any) &&
4805                               dns_name_equal(client->query.qname,
4806                                              dns_db_origin(db))))
4807                                 (void)query_addns(client, db, version);
4808                 } else if (qtype != dns_rdatatype_ns) {
4809                         if (fname != NULL)
4810                                 query_releasename(client, &fname);
4811                         query_addbestns(client);
4812                 }
4813         }
4814
4815         /*
4816          * Add NSEC records to the authority section if they're needed for
4817          * DNSSEC wildcard proofs.
4818          */
4819         if (need_wildcardproof && dns_db_issecure(db))
4820                 query_addwildcardproof(client, db, version,
4821                                        dns_fixedname_name(&wildcardname),
4822                                        ISC_TRUE);
4823  cleanup:
4824         CTRACE("query_find: cleanup");
4825         /*
4826          * General cleanup.
4827          */
4828         if (rdataset != NULL)
4829                 query_putrdataset(client, &rdataset);
4830         if (sigrdataset != NULL)
4831                 query_putrdataset(client, &sigrdataset);
4832         if (fname != NULL)
4833                 query_releasename(client, &fname);
4834         if (node != NULL)
4835                 dns_db_detachnode(db, &node);
4836         if (db != NULL)
4837                 dns_db_detach(&db);
4838         if (zone != NULL)
4839                 dns_zone_detach(&zone);
4840         if (zdb != NULL) {
4841                 query_putrdataset(client, &zrdataset);
4842                 if (zsigrdataset != NULL)
4843                         query_putrdataset(client, &zsigrdataset);
4844                 if (zfname != NULL)
4845                         query_releasename(client, &zfname);
4846                 dns_db_detach(&zdb);
4847         }
4848         if (event != NULL)
4849                 isc_event_free(ISC_EVENT_PTR(&event));
4850
4851         /*
4852          * AA bit.
4853          */
4854         if (client->query.restarts == 0 && !authoritative) {
4855                 /*
4856                  * We're not authoritative, so we must ensure the AA bit
4857                  * isn't set.
4858                  */
4859                 client->message->flags &= ~DNS_MESSAGEFLAG_AA;
4860         }
4861
4862         /*
4863          * Restart the query?
4864          */
4865         if (want_restart && client->query.restarts < MAX_RESTARTS) {
4866                 client->query.restarts++;
4867                 goto restart;
4868         }
4869
4870         if (eresult != ISC_R_SUCCESS &&
4871             (!PARTIALANSWER(client) || WANTRECURSION(client))) {
4872                 if (eresult == DNS_R_DUPLICATE || eresult == DNS_R_DROP) {
4873                         /*
4874                          * This was a duplicate query that we are
4875                          * recursing on.  Don't send a response now.
4876                          * The original query will still cause a response.
4877                          */
4878                         query_next(client, eresult);
4879                 } else {
4880                         /*
4881                          * If we don't have any answer to give the client,
4882                          * or if the client requested recursion and thus wanted
4883                          * the complete answer, send an error response.
4884                          */
4885                         INSIST(line >= 0);
4886                         query_error(client, eresult, line);
4887                 }
4888                 ns_client_detach(&client);
4889         } else if (!RECURSING(client)) {
4890                 /*
4891                  * We are done.  Set up sortlist data for the message
4892                  * rendering code, make a final tweak to the AA bit if the
4893                  * auth-nxdomain config option says so, then render and
4894                  * send the response.
4895                  */
4896                 setup_query_sortlist(client);
4897
4898                 /*
4899                  * If this is a referral and the answer to the question
4900                  * is in the glue sort it to the start of the additional
4901                  * section.
4902                  */
4903                 if (ISC_LIST_EMPTY(client->message->sections[DNS_SECTION_ANSWER]) &&
4904                     client->message->rcode == dns_rcode_noerror &&
4905                     (qtype == dns_rdatatype_a || qtype == dns_rdatatype_aaaa))
4906                         answer_in_glue(client, qtype);
4907
4908                 if (client->message->rcode == dns_rcode_nxdomain &&
4909                     client->view->auth_nxdomain == ISC_TRUE)
4910                         client->message->flags |= DNS_MESSAGEFLAG_AA;
4911
4912                 /*
4913                  * If the response is somehow unexpected for the client and this
4914                  * is a result of recursion, return an error to the caller
4915                  * to indicate it may need to be logged.
4916                  */
4917                 if (resuming &&
4918                     (ISC_LIST_EMPTY(client->message->sections[DNS_SECTION_ANSWER]) ||
4919                      client->message->rcode != dns_rcode_noerror))
4920                         eresult = ISC_R_FAILURE;
4921
4922                 query_send(client);
4923                 ns_client_detach(&client);
4924         }
4925         CTRACE("query_find: done");
4926
4927         return (eresult);
4928 }
4929
4930 static inline void
4931 log_query(ns_client_t *client, unsigned int flags, unsigned int extflags) {
4932         char namebuf[DNS_NAME_FORMATSIZE];
4933         char typename[DNS_RDATATYPE_FORMATSIZE];
4934         char classname[DNS_RDATACLASS_FORMATSIZE];
4935         dns_rdataset_t *rdataset;
4936         int level = ISC_LOG_INFO;
4937
4938         if (! isc_log_wouldlog(ns_g_lctx, level))
4939                 return;
4940
4941         rdataset = ISC_LIST_HEAD(client->query.qname->list);
4942         INSIST(rdataset != NULL);
4943         dns_name_format(client->query.qname, namebuf, sizeof(namebuf));
4944         dns_rdataclass_format(rdataset->rdclass, classname, sizeof(classname));
4945         dns_rdatatype_format(rdataset->type, typename, sizeof(typename));
4946
4947         ns_client_log(client, NS_LOGCATEGORY_QUERIES, NS_LOGMODULE_QUERY,
4948                       level, "query: %s %s %s %s%s%s%s%s", namebuf, classname,
4949                       typename, WANTRECURSION(client) ? "+" : "-",
4950                       (client->signer != NULL) ? "S": "",
4951                       (client->opt != NULL) ? "E" : "",
4952                       ((extflags & DNS_MESSAGEEXTFLAG_DO) != 0) ? "D" : "",
4953                       ((flags & DNS_MESSAGEFLAG_CD) != 0) ? "C" : "");
4954 }
4955
4956 static inline void
4957 log_queryerror(ns_client_t *client, isc_result_t result, int line, int level) {
4958         char namebuf[DNS_NAME_FORMATSIZE];
4959         char typename[DNS_RDATATYPE_FORMATSIZE];
4960         char classname[DNS_RDATACLASS_FORMATSIZE];
4961         const char *namep, *typep, *classp, *sep1, *sep2;
4962         dns_rdataset_t *rdataset;
4963
4964         if (!isc_log_wouldlog(ns_g_lctx, level))
4965                 return;
4966
4967         namep = typep = classp = sep1 = sep2 = "";
4968
4969         /*
4970          * Query errors can happen for various reasons.  In some cases we cannot
4971          * even assume the query contains a valid question section, so we should
4972          * expect exceptional cases.
4973          */
4974         if (client->query.origqname != NULL) {
4975                 dns_name_format(client->query.origqname, namebuf,
4976                                 sizeof(namebuf));
4977                 namep = namebuf;
4978                 sep1 = " for ";
4979
4980                 rdataset = ISC_LIST_HEAD(client->query.origqname->list);
4981                 if (rdataset != NULL) {
4982                         dns_rdataclass_format(rdataset->rdclass, classname,
4983                                               sizeof(classname));
4984                         classp = classname;
4985                         dns_rdatatype_format(rdataset->type, typename,
4986                                              sizeof(typename));
4987                         typep = typename;
4988                         sep2 = "/";
4989                 }
4990         }
4991
4992         ns_client_log(client, NS_LOGCATEGORY_QUERY_EERRORS, NS_LOGMODULE_QUERY,
4993                       level, "query failed (%s)%s%s%s%s%s%s at %s:%d",
4994                       isc_result_totext(result), sep1, namep, sep2,
4995                       classp, sep2, typep, __FILE__, line);
4996 }
4997
4998 void
4999 ns_query_start(ns_client_t *client) {
5000         isc_result_t result;
5001         dns_message_t *message = client->message;
5002         dns_rdataset_t *rdataset;
5003         ns_client_t *qclient;
5004         dns_rdatatype_t qtype;
5005         unsigned int saved_extflags = client->extflags;
5006         unsigned int saved_flags = client->message->flags;
5007         isc_boolean_t want_ad;
5008
5009         CTRACE("ns_query_start");
5010
5011         /*
5012          * Test only.
5013          */
5014         if (ns_g_clienttest && (client->attributes & NS_CLIENTATTR_TCP) == 0)
5015                 RUNTIME_CHECK(ns_client_replace(client) == ISC_R_SUCCESS);
5016
5017         /*
5018          * Ensure that appropriate cleanups occur.
5019          */
5020         client->next = query_next_callback;
5021
5022         /*
5023          * Behave as if we don't support DNSSEC if not enabled.
5024          */
5025         if (!client->view->enablednssec) {
5026                 message->flags &= ~DNS_MESSAGEFLAG_CD;
5027                 client->extflags &= ~DNS_MESSAGEEXTFLAG_DO;
5028                 if (client->opt != NULL)
5029                         client->opt->ttl &= ~DNS_MESSAGEEXTFLAG_DO;
5030         }
5031
5032         if ((message->flags & DNS_MESSAGEFLAG_RD) != 0)
5033                 client->query.attributes |= NS_QUERYATTR_WANTRECURSION;
5034
5035         if ((client->extflags & DNS_MESSAGEEXTFLAG_DO) != 0)
5036                 client->attributes |= NS_CLIENTATTR_WANTDNSSEC;
5037
5038         if (client->view->minimalresponses)
5039                 client->query.attributes |= (NS_QUERYATTR_NOAUTHORITY |
5040                                              NS_QUERYATTR_NOADDITIONAL);
5041
5042         if ((client->view->cachedb == NULL)
5043             || (!client->view->additionalfromcache)) {
5044                 /*
5045                  * We don't have a cache.  Turn off cache support and
5046                  * recursion.
5047                  */
5048                 client->query.attributes &=
5049                         ~(NS_QUERYATTR_RECURSIONOK|NS_QUERYATTR_CACHEOK);
5050         } else if ((client->attributes & NS_CLIENTATTR_RA) == 0 ||
5051                    (message->flags & DNS_MESSAGEFLAG_RD) == 0) {
5052                 /*
5053                  * If the client isn't allowed to recurse (due to
5054                  * "recursion no", the allow-recursion ACL, or the
5055                  * lack of a resolver in this view), or if it
5056                  * doesn't want recursion, turn recursion off.
5057                  */
5058                 client->query.attributes &= ~NS_QUERYATTR_RECURSIONOK;
5059         }
5060
5061         /*
5062          * Get the question name.
5063          */
5064         result = dns_message_firstname(message, DNS_SECTION_QUESTION);
5065         if (result != ISC_R_SUCCESS) {
5066                 query_error(client, result, __LINE__);
5067                 return;
5068         }
5069         dns_message_currentname(message, DNS_SECTION_QUESTION,
5070                                 &client->query.qname);
5071         client->query.origqname = client->query.qname;
5072         result = dns_message_nextname(message, DNS_SECTION_QUESTION);
5073         if (result != ISC_R_NOMORE) {
5074                 if (result == ISC_R_SUCCESS) {
5075                         /*
5076                          * There's more than one QNAME in the question
5077                          * section.
5078                          */
5079                         query_error(client, DNS_R_FORMERR, __LINE__);
5080                 } else
5081                         query_error(client, result, __LINE__);
5082                 return;
5083         }
5084
5085         if (ns_g_server->log_queries)
5086                 log_query(client, saved_flags, saved_extflags);
5087
5088         /*
5089          * Check for multiple question queries, since edns1 is dead.
5090          */
5091         if (message->counts[DNS_SECTION_QUESTION] > 1) {
5092                 query_error(client, DNS_R_FORMERR, __LINE__);
5093                 return;
5094         }
5095
5096         /*
5097          * Check for meta-queries like IXFR and AXFR.
5098          */
5099         rdataset = ISC_LIST_HEAD(client->query.qname->list);
5100         INSIST(rdataset != NULL);
5101         qtype = rdataset->type;
5102         dns_rdatatypestats_increment(ns_g_server->rcvquerystats, qtype);
5103         if (dns_rdatatype_ismeta(qtype)) {
5104                 switch (qtype) {
5105                 case dns_rdatatype_any:
5106                         break; /* Let query_find handle it. */
5107                 case dns_rdatatype_ixfr:
5108                 case dns_rdatatype_axfr:
5109                         ns_xfr_start(client, rdataset->type);
5110                         return;
5111                 case dns_rdatatype_maila:
5112                 case dns_rdatatype_mailb:
5113                         query_error(client, DNS_R_NOTIMP, __LINE__);
5114                         return;
5115                 case dns_rdatatype_tkey:
5116                         result = dns_tkey_processquery(client->message,
5117                                                 ns_g_server->tkeyctx,
5118                                                 client->view->dynamickeys);
5119                         if (result == ISC_R_SUCCESS)
5120                                 query_send(client);
5121                         else
5122                                 query_error(client, result, __LINE__);
5123                         return;
5124                 default: /* TSIG, etc. */
5125                         query_error(client, DNS_R_FORMERR, __LINE__);
5126                         return;
5127                 }
5128         }
5129
5130         /*
5131          * Turn on minimal response for DNSKEY and DS queries.
5132          */
5133         if (qtype == dns_rdatatype_dnskey || qtype == dns_rdatatype_ds)
5134                 client->query.attributes |= (NS_QUERYATTR_NOAUTHORITY |
5135                                              NS_QUERYATTR_NOADDITIONAL);
5136
5137         /*
5138          * Turn on minimal responses for EDNS/UDP bufsize 512 queries.
5139          */
5140         if (client->opt != NULL && client->udpsize <= 512U &&
5141             (client->attributes & NS_CLIENTATTR_TCP) == 0)
5142                 client->query.attributes |= (NS_QUERYATTR_NOAUTHORITY |
5143                                              NS_QUERYATTR_NOADDITIONAL);
5144
5145         /*
5146          * If the client has requested that DNSSEC checking be disabled,
5147          * allow lookups to return pending data and instruct the resolver
5148          * to return data before validation has completed.
5149          *
5150          * We don't need to set DNS_DBFIND_PENDINGOK when validation is
5151          * disabled as there will be no pending data.
5152          */
5153         if (message->flags & DNS_MESSAGEFLAG_CD ||
5154             qtype == dns_rdatatype_rrsig)
5155         {
5156                 client->query.dboptions |= DNS_DBFIND_PENDINGOK;
5157                 client->query.fetchoptions |= DNS_FETCHOPT_NOVALIDATE;
5158         } else if (!client->view->enablevalidation)
5159                 client->query.fetchoptions |= DNS_FETCHOPT_NOVALIDATE;
5160
5161         /*
5162          * Allow glue NS records to be added to the authority section
5163          * if the answer is secure.
5164          */
5165         if (message->flags & DNS_MESSAGEFLAG_CD)
5166                 client->query.attributes &= ~NS_QUERYATTR_SECURE;
5167
5168         /*
5169          * Set 'want_ad' if the client has set AD in the query.
5170          * This allows AD to be returned on queries without DO set.
5171          */
5172         if ((message->flags & DNS_MESSAGEFLAG_AD) != 0)
5173                 want_ad = ISC_TRUE;
5174         else
5175                 want_ad = ISC_FALSE;
5176
5177         /*
5178          * This is an ordinary query.
5179          */
5180         result = dns_message_reply(message, ISC_TRUE);
5181         if (result != ISC_R_SUCCESS) {
5182                 query_next(client, result);
5183                 return;
5184         }
5185
5186         /*
5187          * Assume authoritative response until it is known to be
5188          * otherwise.
5189          */
5190         message->flags |= DNS_MESSAGEFLAG_AA;
5191
5192         /*
5193          * Set AD.  We must clear it if we add non-validated data to a
5194          * response.
5195          */
5196         if (WANTDNSSEC(client) || want_ad)
5197                 message->flags |= DNS_MESSAGEFLAG_AD;
5198
5199         qclient = NULL;
5200         ns_client_attach(client, &qclient);
5201         (void)query_find(qclient, NULL, qtype);
5202 }