zone_finder.cc 40 KB

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