zone_finder.cc 40 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958
  1. // Copyright (C) 2012 Internet Systems Consortium, Inc. ("ISC")
  2. //
  3. // Permission to use, copy, modify, and/or distribute this software for any
  4. // purpose with or without fee is hereby granted, provided that the above
  5. // copyright notice and this permission notice appear in all copies.
  6. //
  7. // THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES WITH
  8. // REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
  9. // AND FITNESS. IN NO EVENT SHALL ISC BE LIABLE FOR ANY SPECIAL, DIRECT,
  10. // INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
  11. // LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE
  12. // OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
  13. // PERFORMANCE OF THIS SOFTWARE.
  14. #include <datasrc/memory/zone_finder.h>
  15. #include <datasrc/memory/domaintree.h>
  16. #include <datasrc/memory/treenode_rrset.h>
  17. #include <datasrc/memory/rdata_serialization.h>
  18. #include <datasrc/zone.h>
  19. #include <datasrc/data_source.h>
  20. #include <dns/labelsequence.h>
  21. #include <dns/name.h>
  22. #include <dns/rrset.h>
  23. #include <dns/rrtype.h>
  24. #include <dns/nsec3hash.h>
  25. #include <datasrc/logger.h>
  26. #include <boost/scoped_ptr.hpp>
  27. #include <boost/bind.hpp>
  28. #include <algorithm>
  29. #include <vector>
  30. using namespace isc::dns;
  31. using namespace isc::datasrc::memory;
  32. using namespace isc::datasrc;
  33. namespace isc {
  34. namespace datasrc {
  35. namespace memory {
  36. namespace internal {
  37. // Specialized version of ZoneFinder::ResultContext, which holds objects
  38. // related to find() results using internal representations of the in-memory
  39. // data source implementation.
  40. class ZoneFinderResultContext {
  41. public:
  42. /// \brief Constructor
  43. ///
  44. /// The first three parameters correspond to those of
  45. /// ZoneFinder::ResultContext. If node is non NULL, it specifies the
  46. /// found ZoneNode in the search.
  47. ZoneFinderResultContext(ZoneFinder::Result code_param,
  48. TreeNodeRRsetPtr rrset_param,
  49. ZoneFinder::FindResultFlags flags_param,
  50. const ZoneData& zone_data_param,
  51. const ZoneNode* node, const RdataSet* rdset) :
  52. code(code_param), rrset(rrset_param), flags(flags_param),
  53. zone_data(&zone_data_param), found_node(node), found_rdset(rdset)
  54. {}
  55. const ZoneFinder::Result code;
  56. const TreeNodeRRsetPtr rrset;
  57. const ZoneFinder::FindResultFlags flags;
  58. const ZoneData* const zone_data;
  59. const ZoneNode* const found_node;
  60. const RdataSet* const found_rdset;
  61. };
  62. }
  63. using internal::ZoneFinderResultContext;
  64. namespace {
  65. /// Creates a TreeNodeRRsetPtr for the given RdataSet at the given Node, for
  66. /// the given RRClass
  67. ///
  68. /// We should probably have some pool so these do not need to be allocated
  69. /// dynamically.
  70. ///
  71. /// \param node The ZoneNode found by the find() calls
  72. /// \param rdataset The RdataSet to create the RRsetPtr for
  73. /// \param rrclass The RRClass as passed by the client
  74. /// \param realname If given, the TreeNodeRRset is created with this name
  75. /// (e.g. for wildcard substitution)
  76. ///
  77. /// Returns an empty TreeNodeRRsetPtr if node is NULL or if rdataset is NULL.
  78. TreeNodeRRsetPtr
  79. createTreeNodeRRset(const ZoneNode* node,
  80. const RdataSet* rdataset,
  81. const RRClass& rrclass,
  82. ZoneFinder::FindOptions options,
  83. const Name* realname = NULL)
  84. {
  85. const bool dnssec = ((options & ZoneFinder::FIND_DNSSEC) != 0);
  86. if (node != NULL && rdataset != NULL) {
  87. if (realname != NULL) {
  88. return (TreeNodeRRsetPtr(new TreeNodeRRset(*realname, rrclass,
  89. node, rdataset,
  90. dnssec)));
  91. } else {
  92. return (TreeNodeRRsetPtr(new TreeNodeRRset(rrclass, node, rdataset,
  93. dnssec)));
  94. }
  95. } else {
  96. return (TreeNodeRRsetPtr());
  97. }
  98. }
  99. /// Maintain intermediate data specific to the search context used in
  100. /// \c find().
  101. ///
  102. /// It will be passed to \c cutCallback() (see below) and record a possible
  103. /// zone cut node and related RRset (normally NS or DNAME).
  104. struct FindState {
  105. FindState(bool glue_ok) :
  106. zonecut_node_(NULL),
  107. dname_node_(NULL),
  108. rrset_(NULL),
  109. glue_ok_(glue_ok)
  110. {}
  111. // These will be set to a domain node of the highest delegation point,
  112. // if any. In fact, we could use a single variable instead of both.
  113. // But then we would need to distinquish these two cases by something
  114. // else and it seemed little more confusing when this was written.
  115. const ZoneNode* zonecut_node_;
  116. const ZoneNode* dname_node_;
  117. // Delegation RRset (NS or DNAME), if found.
  118. const RdataSet* rrset_;
  119. // Whether to continue search below a delegation point.
  120. // Set at construction time.
  121. const bool glue_ok_;
  122. };
  123. // A callback called from possible zone cut nodes and nodes with DNAME.
  124. // This will be passed from findNode() to \c RBTree::find().
  125. bool cutCallback(const ZoneNode& node, FindState* state) {
  126. // We need to look for DNAME first, there's allowed case where
  127. // DNAME and NS coexist in the apex. DNAME is the one to notice,
  128. // the NS is authoritative, not delegation (corner case explicitly
  129. // allowed by section 3 of 2672)
  130. const RdataSet* found_dname = RdataSet::find(node.getData(),
  131. RRType::DNAME());
  132. if (found_dname != NULL) {
  133. LOG_DEBUG(logger, DBG_TRACE_DETAILED, DATASRC_MEM_DNAME_ENCOUNTERED);
  134. state->dname_node_ = &node;
  135. state->rrset_ = found_dname;
  136. return (true);
  137. }
  138. // Look for NS
  139. const RdataSet* found_ns = RdataSet::find(node.getData(), RRType::NS());
  140. if (found_ns != NULL) {
  141. // We perform callback check only for the highest zone cut in the
  142. // rare case of nested zone cuts.
  143. if (state->zonecut_node_ != NULL) {
  144. return (false);
  145. }
  146. LOG_DEBUG(logger, DBG_TRACE_DETAILED, DATASRC_MEM_NS_ENCOUNTERED);
  147. // BIND 9 checks if this node is not the origin. That's probably
  148. // because it can support multiple versions for dynamic updates
  149. // and IXFR, and it's possible that the callback is called at
  150. // the apex and the DNAME doesn't exist for a particular version.
  151. // It cannot happen for us (at least for now), so we don't do
  152. // that check.
  153. state->zonecut_node_ = &node;
  154. state->rrset_ = found_ns;
  155. // Unless glue is allowed the search stops here, so we return
  156. // false; otherwise return true to continue the search.
  157. return (!state->glue_ok_);
  158. }
  159. // This case should not happen because we enable callback only
  160. // when we add an RR searched for above.
  161. assert(0);
  162. // This is here to avoid warning (therefore compilation error)
  163. // in case assert is turned off. Otherwise we could get "Control
  164. // reached end of non-void function".
  165. return (false);
  166. }
  167. /// Creates a NSEC3 ConstRRsetPtr for the given ZoneNode inside the
  168. /// NSEC3 tree, for the given RRClass.
  169. ///
  170. /// It asserts that the node contains data (RdataSet) and is of type
  171. /// NSEC3.
  172. ///
  173. /// \param node The ZoneNode inside the NSEC3 tree
  174. /// \param rrclass The RRClass as passed by the client
  175. ConstRRsetPtr
  176. createNSEC3RRset(const ZoneNode* node, const RRClass& rrclass) {
  177. const RdataSet* rdataset = node->getData();
  178. // Only NSEC3 ZoneNodes are allowed to be passed to this method. We
  179. // assert that these have data, and also are of type NSEC3.
  180. assert(rdataset != NULL);
  181. assert(rdataset->type == RRType::NSEC3());
  182. // Create the RRset. Note the DNSSEC flag: NSEC3 implies DNSSEC.
  183. return (createTreeNodeRRset(node, rdataset, rrclass,
  184. ZoneFinder::FIND_DNSSEC));
  185. }
  186. // convenience function to fill in the final details
  187. //
  188. // Set up ZoneFinderResultContext object as a return value of find(),
  189. // taking into account wildcard matches and DNSSEC information. We set
  190. // the NSEC/NSEC3 flag when applicable regardless of the find option; the
  191. // caller would simply ignore these when they didn't request DNSSEC
  192. // related results.
  193. //
  194. // Also performs the conversion of node + RdataSet into a TreeNodeRRsetPtr
  195. //
  196. // if wild is true, the RESULT_WILDCARD flag will be set.
  197. // If qname is not NULL, this is the query name, to be used in wildcard
  198. // substitution instead of the Node's name).
  199. ZoneFinderResultContext
  200. createFindResult(const RRClass& rrclass,
  201. const ZoneData& zone_data,
  202. ZoneFinder::Result code,
  203. const RdataSet* rdset,
  204. const ZoneNode* node,
  205. ZoneFinder::FindOptions options,
  206. bool wild = false,
  207. const Name* qname = NULL)
  208. {
  209. ZoneFinder::FindResultFlags flags = ZoneFinder::RESULT_DEFAULT;
  210. const Name* rename = NULL;
  211. if (wild) {
  212. flags = flags | ZoneFinder::RESULT_WILDCARD;
  213. // only use the rename qname if wild is true
  214. rename = qname;
  215. }
  216. if (code == ZoneFinder::NXRRSET || code == ZoneFinder::NXDOMAIN || wild) {
  217. if (zone_data.isNSEC3Signed()) {
  218. flags = flags | ZoneFinder::RESULT_NSEC3_SIGNED;
  219. } else if (zone_data.isSigned()) {
  220. flags = flags | ZoneFinder::RESULT_NSEC_SIGNED;
  221. }
  222. }
  223. return (ZoneFinderResultContext(code, createTreeNodeRRset(node, rdset,
  224. rrclass, options,
  225. rename),
  226. flags, zone_data, node, rdset));
  227. }
  228. // A helper function for NSEC-signed zones. It searches the zone for
  229. // the "closest" NSEC corresponding to the search context stored in
  230. // node_path (it should contain sufficient information to identify the
  231. // previous name of the query name in the zone). In some cases the
  232. // immediate closest name may not have NSEC (when it's under a zone cut
  233. // for glue records, or even when the zone is partly broken), so this
  234. // method continues the search until it finds a name that has NSEC,
  235. // and returns the one found first. Due to the prerequisite (see below),
  236. // it should always succeed.
  237. //
  238. // node_path must store valid search context (in practice, it's expected
  239. // to be set by findNode()); otherwise the underlying RBTree implementation
  240. // throws.
  241. //
  242. // If the zone is not considered NSEC-signed or DNSSEC records were not
  243. // required in the original search context (specified in options), this
  244. // method doesn't bother to find NSEC, and simply returns NULL. So, by
  245. // definition of "NSEC-signed", when it really tries to find an NSEC it
  246. // should succeed; there should be one at least at the zone origin.
  247. const RdataSet*
  248. getClosestNSEC(const ZoneData& zone_data,
  249. ZoneChain& node_path,
  250. const ZoneNode** nsec_node,
  251. ZoneFinder::FindOptions options)
  252. {
  253. if (!zone_data.isSigned() ||
  254. (options & ZoneFinder::FIND_DNSSEC) == 0 ||
  255. zone_data.isNSEC3Signed()) {
  256. return (NULL);
  257. }
  258. const ZoneNode* prev_node;
  259. while ((prev_node = zone_data.getZoneTree().previousNode(node_path))
  260. != NULL) {
  261. if (!prev_node->isEmpty()) {
  262. const RdataSet* found =
  263. RdataSet::find(prev_node->getData(), RRType::NSEC());
  264. if (found != NULL) {
  265. *nsec_node = prev_node;
  266. return (found);
  267. }
  268. }
  269. }
  270. // This must be impossible and should be an internal bug.
  271. // See the description at the method declaration.
  272. assert(false);
  273. // Even though there is an assert here, strict compilers
  274. // will still need some return value.
  275. return (NULL);
  276. }
  277. // A helper function for the NXRRSET case in find(). If the zone is
  278. // NSEC-signed and DNSSEC records are requested, try to find NSEC
  279. // on the given node, and return it if found; return NULL for all other
  280. // cases.
  281. const RdataSet*
  282. getNSECForNXRRSET(const ZoneData& zone_data,
  283. ZoneFinder::FindOptions options,
  284. const ZoneNode* node)
  285. {
  286. if (zone_data.isSigned() &&
  287. !zone_data.isNSEC3Signed() &&
  288. (options & ZoneFinder::FIND_DNSSEC) != 0) {
  289. const RdataSet* found = RdataSet::find(node->getData(),
  290. RRType::NSEC());
  291. if (found != NULL) {
  292. return (found);
  293. }
  294. }
  295. return (NULL);
  296. }
  297. // Structure to hold result data of the findNode() call
  298. class FindNodeResult {
  299. public:
  300. // Bitwise flags to represent supplemental information of the
  301. // search result:
  302. // Search resulted in a wildcard match.
  303. static const unsigned int FIND_WILDCARD = 1;
  304. // Search encountered a zone cut due to NS but continued to look for
  305. // a glue.
  306. static const unsigned int FIND_ZONECUT = 2;
  307. FindNodeResult(ZoneFinder::Result code_param,
  308. const ZoneNode* node_param,
  309. const RdataSet* rrset_param,
  310. unsigned int flags_param = 0) :
  311. code(code_param),
  312. node(node_param),
  313. rrset(rrset_param),
  314. flags(flags_param)
  315. {}
  316. const ZoneFinder::Result code;
  317. const ZoneNode* node;
  318. const RdataSet* rrset;
  319. const unsigned int flags;
  320. };
  321. // Implementation notes: this method identifies an ZoneNode that best matches
  322. // the give name in terms of DNS query handling. In many cases,
  323. // DomainTree::find() will result in EXACTMATCH or PARTIALMATCH (note that
  324. // the given name is generally expected to be contained in the zone, so
  325. // even if it doesn't exist, it should at least match the zone origin).
  326. // If it finds an exact match, that's obviously the best one. The partial
  327. // match case is more complicated.
  328. //
  329. // We first need to consider the case where search hits a delegation point,
  330. // either due to NS or DNAME. They are indicated as either dname_node_ or
  331. // zonecut_node_ being non NULL. Usually at most one of them will be
  332. // something else than NULL (it might happen both are NULL, in which case we
  333. // consider it NOT FOUND). There's one corner case when both might be
  334. // something else than NULL and it is in case there's a DNAME under a zone
  335. // cut and we search in glue OK mode ‒ in that case we don't stop on the
  336. // domain with NS and ignore it for the answer, but it gets set anyway. Then
  337. // we find the DNAME and we need to act by it, therefore we first check for
  338. // DNAME and then for NS. In all other cases it doesn't matter, as at least
  339. // one of them is NULL.
  340. //
  341. // Next, we need to check if the ZoneTree search stopped at a node for a
  342. // subdomain of the search name (so the comparison result that stopped the
  343. // search is "SUPERDOMAIN"), it means the stopping node is an empty
  344. // non-terminal node. In this case the search name is considered to exist
  345. // but no data should be found there.
  346. //
  347. // If none of above is the case, we then consider whether there's a matching
  348. // wildcard. DomainTree::find() records the node if it encounters a
  349. // "wildcarding" node, i.e., the immediate ancestor of a wildcard name
  350. // (e.g., wild.example.com for *.wild.example.com), and returns it if it
  351. // doesn't find any node that better matches the query name. In this case
  352. // we'll check if there's indeed a wildcard below the wildcarding node.
  353. //
  354. // Note, first, that the wildcard is checked after the empty
  355. // non-terminal domain case above, because if that one triggers, it
  356. // means we should not match according to 4.3.3 of RFC 1034 (the query
  357. // name is known to exist).
  358. //
  359. // Before we try to find a wildcard, we should check whether there's
  360. // an existing node that would cancel the wildcard match. If
  361. // DomainTree::find() stopped at a node which has a common ancestor
  362. // with the query name, it might mean we are comparing with a
  363. // non-wildcard node. In that case, we check which part is common. If
  364. // we have something in common that lives below the node we got (the
  365. // one above *), then we should cancel the match according to section
  366. // 4.3.3 of RFC 1034 (as the name between the wildcard domain and the
  367. // query name is known to exist).
  368. //
  369. // If there's no node below the wildcarding node that shares a common ancestor
  370. // of the query name, we can conclude the wildcard is the best match.
  371. // We'll then identify the wildcard node via an incremental search. Note that
  372. // there's no possibility that the query name is at an empty non terminal
  373. // node below the wildcarding node at this stage; that case should have been
  374. // caught above.
  375. //
  376. // If none of the above succeeds, we conclude the name doesn't exist in
  377. // the zone, and throw an OutOfZone exception by default. If the optional
  378. // out_of_zone_ok is true, it returns an NXDOMAIN result with NULL data so
  379. // the caller can take an action to it (technically it's not "NXDOMAIN",
  380. // but the caller is assumed not to rely on the difference.)
  381. FindNodeResult findNode(const ZoneData& zone_data,
  382. const LabelSequence& name_labels,
  383. ZoneChain& node_path,
  384. ZoneFinder::FindOptions options,
  385. bool out_of_zone_ok = false)
  386. {
  387. ZoneNode* node = NULL;
  388. FindState state((options & ZoneFinder::FIND_GLUE_OK) != 0);
  389. const ZoneTree& tree(zone_data.getZoneTree());
  390. const ZoneTree::Result result = tree.find(name_labels, &node, node_path,
  391. cutCallback, &state);
  392. const unsigned int zonecut_flag =
  393. (state.zonecut_node_ != NULL) ? FindNodeResult::FIND_ZONECUT : 0;
  394. if (result == ZoneTree::EXACTMATCH) {
  395. return (FindNodeResult(ZoneFinder::SUCCESS, node, state.rrset_,
  396. zonecut_flag));
  397. } else if (result == ZoneTree::PARTIALMATCH) {
  398. assert(node != NULL);
  399. if (state.dname_node_ != NULL) { // DNAME
  400. LOG_DEBUG(logger, DBG_TRACE_DATA, DATASRC_MEM_DNAME_FOUND).
  401. arg(state.dname_node_->getName());
  402. return (FindNodeResult(ZoneFinder::DNAME, state.dname_node_,
  403. state.rrset_));
  404. }
  405. if (state.zonecut_node_ != NULL) { // DELEGATION due to NS
  406. LOG_DEBUG(logger, DBG_TRACE_DATA, DATASRC_MEM_DELEG_FOUND).
  407. arg(state.zonecut_node_->getName());
  408. return (FindNodeResult(ZoneFinder::DELEGATION,
  409. state.zonecut_node_,
  410. state.rrset_));
  411. }
  412. if (node_path.getLastComparisonResult().getRelation() ==
  413. NameComparisonResult::SUPERDOMAIN) { // empty node, so NXRRSET
  414. LOG_DEBUG(logger, DBG_TRACE_DATA,
  415. DATASRC_MEM_SUPER_STOP).arg(name_labels);
  416. const ZoneNode* nsec_node;
  417. const RdataSet* nsec_rds = getClosestNSEC(zone_data,
  418. node_path,
  419. &nsec_node,
  420. options);
  421. return (FindNodeResult(ZoneFinder::NXRRSET, nsec_node,
  422. nsec_rds));
  423. }
  424. // Nothing really matched.
  425. // May be a wildcard, but check only if not disabled
  426. if (node->getFlag(ZoneData::WILDCARD_NODE) &&
  427. (options & ZoneFinder::NO_WILDCARD) == 0) {
  428. if (node_path.getLastComparisonResult().getRelation() ==
  429. NameComparisonResult::COMMONANCESTOR) {
  430. // This means, e.g., we have *.wild.example and
  431. // bar.foo.wild.example and are looking for
  432. // baz.foo.wild.example. The common ancestor, foo.wild.example,
  433. // should cancel wildcard. Treat it as NXDOMAIN.
  434. LOG_DEBUG(logger, DBG_TRACE_DATA,
  435. DATASRC_MEM_WILDCARD_CANCEL).arg(name_labels);
  436. const ZoneNode* nsec_node;
  437. const RdataSet* nsec_rds = getClosestNSEC(zone_data,
  438. node_path,
  439. &nsec_node,
  440. options);
  441. return (FindNodeResult(ZoneFinder::NXDOMAIN, nsec_node,
  442. nsec_rds));
  443. }
  444. uint8_t ls_buf[LabelSequence::MAX_SERIALIZED_LENGTH];
  445. // Create the wildcard name (i.e. take "*" and extend it
  446. // with all node labels down to the wildcard node
  447. LabelSequence wildcard_ls(LabelSequence::WILDCARD(), ls_buf);
  448. const ZoneNode* extend_with = node;
  449. while (extend_with != NULL) {
  450. wildcard_ls.extend(extend_with->getLabels(), ls_buf);
  451. extend_with = extend_with->getUpperNode();
  452. }
  453. // Clear the node_path so that we don't keep incorrect (NSEC)
  454. // context
  455. node_path.clear();
  456. ZoneTree::Result result = tree.find(LabelSequence(wildcard_ls),
  457. &node, node_path, cutCallback,
  458. &state);
  459. // Otherwise, why would the domain_flag::WILD be there if
  460. // there was no wildcard under it?
  461. assert(result == ZoneTree::EXACTMATCH);
  462. return (FindNodeResult(ZoneFinder::SUCCESS, node, state.rrset_,
  463. FindNodeResult::FIND_WILDCARD | zonecut_flag));
  464. }
  465. LOG_DEBUG(logger, DBG_TRACE_DATA, DATASRC_MEM_NOT_FOUND).
  466. arg(name_labels);
  467. const ZoneNode* nsec_node;
  468. const RdataSet* nsec_rds = getClosestNSEC(zone_data, node_path,
  469. &nsec_node, options);
  470. return (FindNodeResult(ZoneFinder::NXDOMAIN, nsec_node, nsec_rds));
  471. } else {
  472. // If the name is neither an exact or partial match, it is
  473. // out of bailiwick, which is considered an error, unless the caller
  474. // is willing to accept it.
  475. if (out_of_zone_ok) {
  476. return (FindNodeResult(ZoneFinder::NXDOMAIN, NULL, NULL));
  477. }
  478. isc_throw(OutOfZone, name_labels << " not in " <<
  479. zone_data.getOriginNode()->getName());
  480. }
  481. }
  482. } // end anonymous namespace
  483. /// \brief Specialization of the ZoneFinder::Context for the in-memory finder.
  484. ///
  485. /// Note that we don't have a specific constructor for the findAll() case.
  486. /// For (successful) type ANY query, found_node points to the
  487. /// corresponding zone node, which is recorded within this specialized
  488. /// context.
  489. class InMemoryZoneFinder::Context : public ZoneFinder::Context {
  490. public:
  491. Context(ZoneFinder& finder, ZoneFinder::FindOptions options,
  492. const RRClass& rrclass, const ZoneFinderResultContext& result) :
  493. ZoneFinder::Context(finder, options,
  494. ResultContext(result.code, result.rrset,
  495. result.flags)),
  496. rrclass_(rrclass), zone_data_(result.zone_data),
  497. found_node_(result.found_node),
  498. found_rdset_(result.found_rdset)
  499. {}
  500. protected:
  501. virtual void getAdditionalImpl(const std::vector<RRType>& requested_types,
  502. std::vector<ConstRRsetPtr>& result)
  503. {
  504. if (found_rdset_ != NULL) {
  505. // Normal query with successful result.
  506. getAdditionalForRdataset(found_rdset_, requested_types, result,
  507. options_);
  508. } else if (found_node_ != NULL) {
  509. // Successful type ANY query result. Call
  510. // getAdditionalForRdataset for each RdataSet of the node.
  511. for (const RdataSet* rdset = found_node_->getData();
  512. rdset != NULL;
  513. rdset = rdset->getNext())
  514. {
  515. getAdditionalForRdataset(rdset, requested_types, result,
  516. options_);
  517. }
  518. }
  519. }
  520. private:
  521. // Main subroutine of getAdditionalImpl, iterate over Rdata fields
  522. // find, create, and insert necessary additional RRsets.
  523. void
  524. getAdditionalForRdataset(const RdataSet* rdset,
  525. const std::vector<RRType>& requested_types,
  526. std::vector<ConstRRsetPtr>& result,
  527. ZoneFinder::FindOptions orig_options) const
  528. {
  529. ZoneFinder::FindOptions options = ZoneFinder::FIND_DEFAULT;
  530. if ((orig_options & ZoneFinder::FIND_DNSSEC) != 0) {
  531. options = options | ZoneFinder::FIND_DNSSEC;
  532. }
  533. if (rdset->type == RRType::NS()) {
  534. options = options | ZoneFinder::FIND_GLUE_OK;
  535. }
  536. RdataReader(rrclass_, rdset->type, rdset->getDataBuf(),
  537. rdset->getRdataCount(), rdset->getSigRdataCount(),
  538. boost::bind(&Context::findAdditional, this,
  539. &requested_types, &result, options, _1, _2),
  540. &RdataReader::emptyDataAction).iterate();
  541. }
  542. // RdataReader callback for additional section processing.
  543. void
  544. findAdditional(const std::vector<RRType>* requested_types,
  545. std::vector<ConstRRsetPtr>* result,
  546. ZoneFinder::FindOptions options,
  547. const LabelSequence& name_labels,
  548. RdataNameAttributes attr) const;
  549. // Subroutine for findAdditional() to unify the normal and wildcard match
  550. // cases.
  551. void
  552. findAdditionalHelper(const std::vector<RRType>* requested_types,
  553. std::vector<ConstRRsetPtr>* result,
  554. const ZoneNode* node,
  555. ZoneFinder::FindOptions options,
  556. const Name* real_name) const
  557. {
  558. const std::vector<RRType>::const_iterator type_beg =
  559. requested_types->begin();
  560. const std::vector<RRType>::const_iterator type_end =
  561. requested_types->end();
  562. for (const RdataSet* rdset = node->getData();
  563. rdset != NULL;
  564. rdset = rdset->getNext())
  565. {
  566. // Checking all types for all RdataSets could be suboptimal.
  567. // This can be a bit more optimized, but unless we have many
  568. // requested types the effect is probably marginal. For now we
  569. // keep it simple.
  570. if (std::find(type_beg, type_end, rdset->type) != type_end) {
  571. result->push_back(createTreeNodeRRset(node, rdset, rrclass_,
  572. options, real_name));
  573. }
  574. }
  575. }
  576. private:
  577. const RRClass rrclass_;
  578. const ZoneData* const zone_data_;
  579. const ZoneNode* const found_node_;
  580. const RdataSet* const found_rdset_;
  581. };
  582. void
  583. InMemoryZoneFinder::Context::findAdditional(
  584. const std::vector<RRType>* requested_types,
  585. std::vector<ConstRRsetPtr>* result,
  586. ZoneFinder::FindOptions options,
  587. const LabelSequence& name_labels,
  588. RdataNameAttributes attr) const
  589. {
  590. // Ignore name data that don't need additional processing.
  591. if ((attr & NAMEATTR_ADDITIONAL) == 0) {
  592. return;
  593. }
  594. // Find the zone node for the additional name. By passing true as the
  595. // last parameter of findNode() we ignore out-of-zone names.
  596. ZoneChain node_path;
  597. const FindNodeResult node_result =
  598. findNode(*zone_data_, name_labels, node_path, options, true);
  599. // we only need non-empty exact match
  600. if (node_result.code != SUCCESS) {
  601. return;
  602. }
  603. // Ignore data at a zone cut (due to subdomain delegation) unless glue is
  604. // allowed. Checking the node callback flag is a cheap way to detect
  605. // zone cuts, but it includes DNAME delegation, in which case we should
  606. // keep finding the additional records regardless of the 'GLUE_OK' flag.
  607. // The last two conditions limit the case to delegation NS, i.e, the node
  608. // has an NS and it's not the zone origin.
  609. const ZoneNode* node = node_result.node;
  610. if ((options & ZoneFinder::FIND_GLUE_OK) == 0 &&
  611. node->getFlag(ZoneNode::FLAG_CALLBACK) &&
  612. node != zone_data_->getOriginNode() &&
  613. RdataSet::find(node->getData(), RRType::NS()) != NULL) {
  614. return;
  615. }
  616. // Examine RdataSets of the node, and create and insert requested types
  617. // of RRsets as we find them.
  618. if ((node_result.flags & FindNodeResult::FIND_WILDCARD) == 0) {
  619. // normal case
  620. findAdditionalHelper(requested_types, result, node, options, NULL);
  621. } else {
  622. // if the additional name is subject to wildcard substitution, we need
  623. // to create a name object for the "real" (after substitution) name.
  624. // This is expensive, but in the additional processing this should be
  625. // very rare cases and acceptable.
  626. size_t data_len;
  627. const uint8_t* data;
  628. data = name_labels.getData(&data_len);
  629. util::InputBuffer buffer(data, data_len);
  630. const Name real_name(buffer);
  631. findAdditionalHelper(requested_types, result, node, options,
  632. &real_name);
  633. }
  634. }
  635. boost::shared_ptr<ZoneFinder::Context>
  636. InMemoryZoneFinder::find(const isc::dns::Name& name,
  637. const isc::dns::RRType& type,
  638. const FindOptions options)
  639. {
  640. return (ZoneFinderContextPtr(new Context(*this, options, rrclass_,
  641. find_internal(name, type,
  642. NULL, options))));
  643. }
  644. boost::shared_ptr<ZoneFinder::Context>
  645. InMemoryZoneFinder::findAll(const isc::dns::Name& name,
  646. std::vector<isc::dns::ConstRRsetPtr>& target,
  647. const FindOptions options)
  648. {
  649. return (ZoneFinderContextPtr(new Context(*this, options, rrclass_,
  650. find_internal(name,
  651. RRType::ANY(),
  652. &target,
  653. options))));
  654. }
  655. ZoneFinderResultContext
  656. InMemoryZoneFinder::find_internal(const isc::dns::Name& name,
  657. const isc::dns::RRType& type,
  658. std::vector<ConstRRsetPtr>* target,
  659. const FindOptions options)
  660. {
  661. // Get the node. All other cases than an exact match are handled
  662. // in findNode(). We simply construct a result structure and return.
  663. ZoneChain node_path;
  664. const FindNodeResult node_result =
  665. findNode(zone_data_, LabelSequence(name), node_path, options);
  666. if (node_result.code != SUCCESS) {
  667. return (createFindResult(rrclass_, zone_data_, node_result.code,
  668. node_result.rrset, node_result.node,
  669. options));
  670. }
  671. const ZoneNode* node = node_result.node;
  672. assert(node != NULL);
  673. // We've found an exact match, may or may not be a result of wildcard.
  674. const bool wild = ((node_result.flags &
  675. FindNodeResult::FIND_WILDCARD) != 0);
  676. // If there is an exact match but the node is empty, it's equivalent
  677. // to NXRRSET.
  678. if (node->isEmpty()) {
  679. LOG_DEBUG(logger, DBG_TRACE_DATA, DATASRC_MEM_DOMAIN_EMPTY).
  680. arg(name);
  681. const ZoneNode* nsec_node;
  682. const RdataSet* nsec_rds = getClosestNSEC(zone_data_, node_path,
  683. &nsec_node, options);
  684. return (createFindResult(rrclass_, zone_data_, NXRRSET,
  685. nsec_rds, nsec_node, options, wild));
  686. }
  687. const RdataSet* found;
  688. // If the node callback is enabled, this may be a zone cut. If it
  689. // has a NS RR, we should return a delegation, but not in the apex.
  690. // There are two exceptions:
  691. // - the case for DS query, which should always be considered in-zone
  692. // lookup.
  693. // - when we are looking for glue records (FIND_GLUE_OK)
  694. if (node->getFlag(ZoneNode::FLAG_CALLBACK) &&
  695. (options & FIND_GLUE_OK) == 0 &&
  696. node != zone_data_.getOriginNode() && type != RRType::DS()) {
  697. found = RdataSet::find(node->getData(), RRType::NS());
  698. if (found != NULL) {
  699. LOG_DEBUG(logger, DBG_TRACE_DATA,
  700. DATASRC_MEM_EXACT_DELEGATION).arg(name);
  701. return (createFindResult(rrclass_, zone_data_, DELEGATION,
  702. found, node, options, wild, &name));
  703. }
  704. }
  705. // Handle type any query
  706. if (target != NULL && node->getData() != NULL) {
  707. // Empty domain will be handled as NXRRSET by normal processing
  708. const RdataSet* cur_rds = node->getData();
  709. while (cur_rds != NULL) {
  710. target->push_back(createTreeNodeRRset(node, cur_rds, rrclass_,
  711. options, &name));
  712. cur_rds = cur_rds->getNext();
  713. }
  714. LOG_DEBUG(logger, DBG_TRACE_DATA, DATASRC_MEM_ANY_SUCCESS).
  715. arg(name);
  716. return (createFindResult(rrclass_, zone_data_, SUCCESS, NULL, node,
  717. options, wild, &name));
  718. }
  719. found = RdataSet::find(node->getData(), type);
  720. if (found != NULL) {
  721. // Good, it is here
  722. LOG_DEBUG(logger, DBG_TRACE_DATA, DATASRC_MEM_SUCCESS).arg(name).
  723. arg(type);
  724. return (createFindResult(rrclass_, zone_data_, SUCCESS, found, node,
  725. options, wild, &name));
  726. } else {
  727. // Next, try CNAME.
  728. found = RdataSet::find(node->getData(), RRType::CNAME());
  729. if (found != NULL) {
  730. LOG_DEBUG(logger, DBG_TRACE_DATA, DATASRC_MEM_CNAME).arg(name);
  731. return (createFindResult(rrclass_, zone_data_, CNAME, found, node,
  732. options, wild, &name));
  733. }
  734. }
  735. // No exact match or CNAME. Get NSEC if necessary and return NXRRSET.
  736. return (createFindResult(rrclass_, zone_data_, NXRRSET,
  737. getNSECForNXRRSET(zone_data_, options, node),
  738. node, options, wild, &name));
  739. }
  740. isc::datasrc::ZoneFinder::FindNSEC3Result
  741. InMemoryZoneFinder::findNSEC3(const isc::dns::Name& name, bool recursive) {
  742. LOG_DEBUG(logger, DBG_TRACE_BASIC, DATASRC_MEM_FINDNSEC3).arg(name).
  743. arg(recursive ? "recursive" : "non-recursive");
  744. uint8_t labels_buf[LabelSequence::MAX_SERIALIZED_LENGTH];
  745. const LabelSequence origin_ls(zone_data_.getOriginNode()->
  746. getAbsoluteLabels(labels_buf));
  747. const LabelSequence name_ls(name);
  748. if (!zone_data_.isNSEC3Signed()) {
  749. isc_throw(DataSourceError,
  750. "findNSEC3 attempt for non NSEC3 signed zone: " <<
  751. origin_ls << "/" << getClass());
  752. }
  753. const NSEC3Data* nsec3_data = zone_data_.getNSEC3Data();
  754. // This would be a programming mistake, as ZoneData::isNSEC3Signed()
  755. // should check this.
  756. assert(nsec3_data != NULL);
  757. const ZoneTree& tree = nsec3_data->getNSEC3Tree();
  758. if (tree.getNodeCount() == 0) {
  759. isc_throw(DataSourceError,
  760. "findNSEC3 attempt but zone has no NSEC3 RRs: " <<
  761. origin_ls << "/" << getClass());
  762. }
  763. const NameComparisonResult cmp_result = name_ls.compare(origin_ls);
  764. if (cmp_result.getRelation() != NameComparisonResult::EQUAL &&
  765. cmp_result.getRelation() != NameComparisonResult::SUBDOMAIN) {
  766. isc_throw(OutOfZone, "findNSEC3 attempt for out-of-zone name: "
  767. << name_ls << ", zone: " << origin_ls << "/"
  768. << getClass());
  769. }
  770. // Convenient shortcuts
  771. const unsigned int olabels = origin_ls.getLabelCount();
  772. const unsigned int qlabels = name.getLabelCount();
  773. // placeholder of the next closer proof
  774. const ZoneNode* covering_node(NULL);
  775. // Now we'll first look up the origin node and initialize orig_chain
  776. // with it.
  777. ZoneChain orig_chain;
  778. const ZoneNode* node(NULL);
  779. ZoneTree::Result result =
  780. tree.find<void*>(origin_ls, &node, orig_chain, NULL, NULL);
  781. if (result != ZoneTree::EXACTMATCH) {
  782. // If the origin node doesn't exist, simply fail.
  783. isc_throw(DataSourceError,
  784. "findNSEC3 attempt but zone has no NSEC3 RRs: " <<
  785. origin_ls << "/" << getClass());
  786. }
  787. const boost::scoped_ptr<NSEC3Hash> hash
  788. (NSEC3Hash::create(nsec3_data->hashalg,
  789. nsec3_data->iterations,
  790. nsec3_data->getSaltData(),
  791. nsec3_data->getSaltLen()));
  792. // Examine all names from the query name to the origin name, stripping
  793. // the deepest label one by one, until we find a name that has a matching
  794. // NSEC3 hash.
  795. for (unsigned int labels = qlabels; labels >= olabels; --labels) {
  796. const Name& hname = (labels == qlabels ?
  797. name : name.split(qlabels - labels, labels));
  798. const std::string hlabel = hash->calculate(hname);
  799. LOG_DEBUG(logger, DBG_TRACE_BASIC, DATASRC_MEM_FINDNSEC3_TRYHASH).
  800. arg(name).arg(labels).arg(hlabel);
  801. node = NULL;
  802. ZoneChain chain(orig_chain);
  803. // Now, make a label sequence relative to the origin.
  804. const Name hlabel_name(hlabel);
  805. LabelSequence hlabel_ls(hlabel_name);
  806. // Remove trailing '.' making it relative
  807. hlabel_ls.stripRight(1);
  808. // Find hlabel relative to the orig_chain.
  809. result = tree.find<void*>(hlabel_ls, &node, chain, NULL, NULL);
  810. if (result == ZoneTree::EXACTMATCH) {
  811. // We found an exact match.
  812. ConstRRsetPtr closest = createNSEC3RRset(node, getClass());
  813. ConstRRsetPtr next;
  814. if (covering_node != NULL) {
  815. next = createNSEC3RRset(covering_node, getClass());
  816. }
  817. LOG_DEBUG(logger, DBG_TRACE_BASIC,
  818. DATASRC_MEM_FINDNSEC3_MATCH).arg(name).arg(labels).
  819. arg(*closest);
  820. return (FindNSEC3Result(true, labels, closest, next));
  821. } else {
  822. while ((covering_node = tree.previousNode(chain)) != NULL &&
  823. covering_node->isEmpty()) {
  824. ;
  825. }
  826. if (covering_node == NULL) {
  827. covering_node = tree.largestNode();
  828. }
  829. if (!recursive) { // in non recursive mode, we are done.
  830. ConstRRsetPtr closest;
  831. if (covering_node != NULL) {
  832. closest = createNSEC3RRset(covering_node, getClass());
  833. LOG_DEBUG(logger, DBG_TRACE_BASIC,
  834. DATASRC_MEM_FINDNSEC3_COVER).
  835. arg(name).arg(*closest);
  836. }
  837. return (FindNSEC3Result(false, labels,
  838. closest, ConstRRsetPtr()));
  839. }
  840. }
  841. }
  842. isc_throw(DataSourceError, "recursive findNSEC3 mode didn't stop, likely "
  843. "a broken NSEC3 zone: " << getOrigin() << "/"
  844. << getClass());
  845. }
  846. Name
  847. InMemoryZoneFinder::getOrigin() const {
  848. size_t data_len;
  849. const uint8_t* data;
  850. // Normally the label sequence of the origin node should be absolute,
  851. // in which case we can simply generate the origin name from the labels.
  852. const LabelSequence node_labels = zone_data_.getOriginNode()->getLabels();
  853. if (node_labels.isAbsolute()) {
  854. data = node_labels.getData(&data_len);
  855. } else {
  856. // In future we may allow adding out-of-zone names in the zone tree.
  857. // For example, to hold out-of-zone NS names so we can establish a
  858. // shortcut link to them as an optimization. If and when that happens
  859. // the origin node may not have an absolute label (consider the zone
  860. // is example.org and we add ns.noexample.org). In that case
  861. // we first need to construct the absolute label sequence and then
  862. // construct the name.
  863. uint8_t labels_buf[LabelSequence::MAX_SERIALIZED_LENGTH];
  864. const LabelSequence name_labels =
  865. zone_data_.getOriginNode()->getAbsoluteLabels(labels_buf);
  866. data = name_labels.getData(&data_len);
  867. }
  868. util::InputBuffer buffer(data, data_len);
  869. return (Name(buffer));
  870. }
  871. } // namespace memory
  872. } // namespace datasrc
  873. } // namespace isc