memory_datasrc.cc 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797
  1. // Copyright (C) 2010 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 <map>
  15. #include <cassert>
  16. #include <boost/shared_ptr.hpp>
  17. #include <boost/bind.hpp>
  18. #include <dns/name.h>
  19. #include <dns/rrclass.h>
  20. #include <dns/rrsetlist.h>
  21. #include <dns/masterload.h>
  22. #include <datasrc/memory_datasrc.h>
  23. #include <datasrc/rbtree.h>
  24. #include <datasrc/logger.h>
  25. #include <datasrc/iterator.h>
  26. #include <datasrc/data_source.h>
  27. using namespace std;
  28. using namespace isc::dns;
  29. namespace isc {
  30. namespace datasrc {
  31. namespace {
  32. // Some type aliases
  33. /*
  34. * Each domain consists of some RRsets. They will be looked up by the
  35. * RRType.
  36. *
  37. * The use of map is questionable with regard to performance - there'll
  38. * be usually only few RRsets in the domain, so the log n benefit isn't
  39. * much and a vector/array might be faster due to its simplicity and
  40. * continuous memory location. But this is unlikely to be a performance
  41. * critical place and map has better interface for the lookups, so we use
  42. * that.
  43. */
  44. typedef map<RRType, ConstRRsetPtr> Domain;
  45. typedef Domain::value_type DomainPair;
  46. typedef boost::shared_ptr<Domain> DomainPtr;
  47. // The tree stores domains
  48. typedef RBTree<Domain> DomainTree;
  49. typedef RBNode<Domain> DomainNode;
  50. }
  51. // Private data and hidden methods of InMemoryZoneFinder
  52. struct InMemoryZoneFinder::InMemoryZoneFinderImpl {
  53. // Constructor
  54. InMemoryZoneFinderImpl(const RRClass& zone_class, const Name& origin) :
  55. zone_class_(zone_class), origin_(origin), origin_data_(NULL),
  56. domains_(true)
  57. {
  58. // We create the node for origin (it needs to exist anyway in future)
  59. domains_.insert(origin, &origin_data_);
  60. DomainPtr origin_domain(new Domain);
  61. origin_data_->setData(origin_domain);
  62. }
  63. static const DomainNode::Flags DOMAINFLAG_WILD = DomainNode::FLAG_USER1;
  64. // Information about the zone
  65. RRClass zone_class_;
  66. Name origin_;
  67. DomainNode* origin_data_;
  68. string file_name_;
  69. // The actual zone data
  70. DomainTree domains_;
  71. // Add the necessary magic for any wildcard contained in 'name'
  72. // (including itself) to be found in the zone.
  73. //
  74. // In order for wildcard matching to work correctly in find(),
  75. // we must ensure that a node for the wildcarding level exists in the
  76. // backend RBTree.
  77. // E.g. if the wildcard name is "*.sub.example." then we must ensure
  78. // that "sub.example." exists and is marked as a wildcard level.
  79. // Note: the "wildcarding level" is for the parent name of the wildcard
  80. // name (such as "sub.example.").
  81. //
  82. // We also perform the same trick for empty wild card names possibly
  83. // contained in 'name' (e.g., '*.foo.example' in 'bar.*.foo.example').
  84. void addWildcards(DomainTree& domains, const Name& name) {
  85. Name wname(name);
  86. const unsigned int labels(wname.getLabelCount());
  87. const unsigned int origin_labels(origin_.getLabelCount());
  88. for (unsigned int l = labels;
  89. l > origin_labels;
  90. --l, wname = wname.split(1)) {
  91. if (wname.isWildcard()) {
  92. LOG_DEBUG(logger, DBG_TRACE_DATA, DATASRC_MEM_ADD_WILDCARD).
  93. arg(name);
  94. // Ensure a separate level exists for the "wildcarding" name,
  95. // and mark the node as "wild".
  96. DomainNode* node;
  97. DomainTree::Result result(domains.insert(wname.split(1),
  98. &node));
  99. assert(result == DomainTree::SUCCESS ||
  100. result == DomainTree::ALREADYEXISTS);
  101. node->setFlag(DOMAINFLAG_WILD);
  102. // Ensure a separate level exists for the wildcard name.
  103. // Note: for 'name' itself we do this later anyway, but the
  104. // overhead should be marginal because wildcard names should
  105. // be rare.
  106. result = domains.insert(wname, &node);
  107. assert(result == DomainTree::SUCCESS ||
  108. result == DomainTree::ALREADYEXISTS);
  109. }
  110. }
  111. }
  112. /*
  113. * Does some checks in context of the data that are already in the zone.
  114. * Currently checks for forbidden combinations of RRsets in the same
  115. * domain (CNAME+anything, DNAME+NS).
  116. *
  117. * If such condition is found, it throws AddError.
  118. */
  119. void contextCheck(const ConstRRsetPtr& rrset,
  120. const DomainPtr& domain) const {
  121. // Ensure CNAME and other type of RR don't coexist for the same
  122. // owner name.
  123. if (rrset->getType() == RRType::CNAME()) {
  124. // TODO: this check will become incorrect when we support DNSSEC
  125. // (depending on how we support DNSSEC). We should revisit it
  126. // at that point.
  127. if (!domain->empty()) {
  128. LOG_ERROR(logger, DATASRC_MEM_CNAME_TO_NONEMPTY).
  129. arg(rrset->getName());
  130. isc_throw(AddError, "CNAME can't be added with other data for "
  131. << rrset->getName());
  132. }
  133. } else if (domain->find(RRType::CNAME()) != domain->end()) {
  134. LOG_ERROR(logger, DATASRC_MEM_CNAME_COEXIST).arg(rrset->getName());
  135. isc_throw(AddError, "CNAME and " << rrset->getType() <<
  136. " can't coexist for " << rrset->getName());
  137. }
  138. /*
  139. * Similar with DNAME, but it must not coexist only with NS and only in
  140. * non-apex domains.
  141. * RFC 2672 section 3 mentions that it is implied from it and RFC 2181
  142. */
  143. if (rrset->getName() != origin_ &&
  144. // Adding DNAME, NS already there
  145. ((rrset->getType() == RRType::DNAME() &&
  146. domain->find(RRType::NS()) != domain->end()) ||
  147. // Adding NS, DNAME already there
  148. (rrset->getType() == RRType::NS() &&
  149. domain->find(RRType::DNAME()) != domain->end())))
  150. {
  151. LOG_ERROR(logger, DATASRC_MEM_DNAME_NS).arg(rrset->getName());
  152. isc_throw(AddError, "DNAME can't coexist with NS in non-apex "
  153. "domain " << rrset->getName());
  154. }
  155. }
  156. // Validate rrset before adding it to the zone. If something is wrong
  157. // it throws an exception. It doesn't modify the zone, and provides
  158. // the strong exception guarantee.
  159. void addValidation(const ConstRRsetPtr rrset) {
  160. if (!rrset) {
  161. isc_throw(NullRRset, "The rrset provided is NULL");
  162. }
  163. // Check for singleton RRs. It should probably handled at a different
  164. // in future.
  165. if ((rrset->getType() == RRType::CNAME() ||
  166. rrset->getType() == RRType::DNAME()) &&
  167. rrset->getRdataCount() > 1)
  168. {
  169. // XXX: this is not only for CNAME or DNAME. We should generalize
  170. // this code for all other "singleton RR types" (such as SOA) in a
  171. // separate task.
  172. LOG_ERROR(logger, DATASRC_MEM_SINGLETON).arg(rrset->getName()).
  173. arg(rrset->getType());
  174. isc_throw(AddError, "multiple RRs of singleton type for "
  175. << rrset->getName());
  176. }
  177. NameComparisonResult compare(origin_.compare(rrset->getName()));
  178. if (compare.getRelation() != NameComparisonResult::SUPERDOMAIN &&
  179. compare.getRelation() != NameComparisonResult::EQUAL)
  180. {
  181. LOG_ERROR(logger, DATASRC_MEM_OUT_OF_ZONE).arg(rrset->getName()).
  182. arg(origin_);
  183. isc_throw(OutOfZone, "The name " << rrset->getName() <<
  184. " is not contained in zone " << origin_);
  185. }
  186. // Some RR types do not really work well with a wildcard.
  187. // Even though the protocol specifically doesn't completely ban such
  188. // usage, we refuse to load a zone containing such RR in order to
  189. // keep the lookup logic simpler and more predictable.
  190. // See RFC4592 and (for DNAME) draft-ietf-dnsext-rfc2672bis-dname
  191. // for more technical background. Note also that BIND 9 refuses
  192. // NS at a wildcard, so in that sense we simply provide compatible
  193. // behavior.
  194. if (rrset->getName().isWildcard()) {
  195. if (rrset->getType() == RRType::NS()) {
  196. LOG_ERROR(logger, DATASRC_MEM_WILDCARD_NS).
  197. arg(rrset->getName());
  198. isc_throw(AddError, "Invalid NS owner name (wildcard): " <<
  199. rrset->getName());
  200. }
  201. if (rrset->getType() == RRType::DNAME()) {
  202. LOG_ERROR(logger, DATASRC_MEM_WILDCARD_DNAME).
  203. arg(rrset->getName());
  204. isc_throw(AddError, "Invalid DNAME owner name (wildcard): " <<
  205. rrset->getName());
  206. }
  207. }
  208. }
  209. /*
  210. * Implementation of longer methods. We put them here, because the
  211. * access is without the impl_-> and it will get inlined anyway.
  212. */
  213. // Implementation of InMemoryZoneFinder::add
  214. result::Result add(const ConstRRsetPtr& rrset, DomainTree* domains) {
  215. // Sanitize input. This will cause an exception to be thrown
  216. // if the input RRset is empty.
  217. addValidation(rrset);
  218. // OK, can add the RRset.
  219. LOG_DEBUG(logger, DBG_TRACE_DATA, DATASRC_MEM_ADD_RRSET).
  220. arg(rrset->getName()).arg(rrset->getType()).arg(origin_);
  221. // Add wildcards possibly contained in the owner name to the domain
  222. // tree.
  223. // Note: this can throw an exception, breaking strong exception
  224. // guarantee. (see also the note for contextCheck() below).
  225. addWildcards(*domains, rrset->getName());
  226. // Get the node
  227. DomainNode* node;
  228. DomainTree::Result result = domains->insert(rrset->getName(), &node);
  229. // Just check it returns reasonable results
  230. assert((result == DomainTree::SUCCESS ||
  231. result == DomainTree::ALREADYEXISTS) && node!= NULL);
  232. // Now get the domain
  233. DomainPtr domain;
  234. // It didn't exist yet, create it
  235. if (node->isEmpty()) {
  236. domain.reset(new Domain);
  237. node->setData(domain);
  238. } else { // Get existing one
  239. domain = node->getData();
  240. }
  241. // Checks related to the surrounding data.
  242. // Note: when the check fails and the exception is thrown, it may
  243. // break strong exception guarantee. At the moment we prefer
  244. // code simplicity and don't bother to introduce complicated
  245. // recovery code.
  246. contextCheck(rrset, domain);
  247. // Try inserting the rrset there
  248. if (domain->insert(DomainPair(rrset->getType(), rrset)).second) {
  249. // Ok, we just put it in
  250. // If this RRset creates a zone cut at this node, mark the node
  251. // indicating the need for callback in find().
  252. if (rrset->getType() == RRType::NS() &&
  253. rrset->getName() != origin_) {
  254. node->setFlag(DomainNode::FLAG_CALLBACK);
  255. // If it is DNAME, we have a callback as well here
  256. } else if (rrset->getType() == RRType::DNAME()) {
  257. node->setFlag(DomainNode::FLAG_CALLBACK);
  258. }
  259. return (result::SUCCESS);
  260. } else {
  261. // The RRSet of given type was already there
  262. return (result::EXIST);
  263. }
  264. }
  265. /*
  266. * Same as above, but it checks the return value and if it already exists,
  267. * it throws.
  268. */
  269. void addFromLoad(const ConstRRsetPtr& set, DomainTree* domains) {
  270. switch (add(set, domains)) {
  271. case result::EXIST:
  272. LOG_ERROR(logger, DATASRC_MEM_DUP_RRSET).
  273. arg(set->getName()).arg(set->getType());
  274. isc_throw(dns::MasterLoadError, "Duplicate rrset: " <<
  275. set->toText());
  276. case result::SUCCESS:
  277. return;
  278. default:
  279. assert(0);
  280. }
  281. }
  282. // Maintain intermediate data specific to the search context used in
  283. /// \c find().
  284. ///
  285. /// It will be passed to \c zonecutCallback() and record a possible
  286. /// zone cut node and related RRset (normally NS or DNAME).
  287. struct FindState {
  288. FindState(FindOptions options) :
  289. zonecut_node_(NULL),
  290. dname_node_(NULL),
  291. options_(options)
  292. {}
  293. const DomainNode* zonecut_node_;
  294. const DomainNode* dname_node_;
  295. ConstRRsetPtr rrset_;
  296. const FindOptions options_;
  297. };
  298. // A callback called from possible zone cut nodes and nodes with DNAME.
  299. // This will be passed from the \c find() method to \c RBTree::find().
  300. static bool cutCallback(const DomainNode& node, FindState* state) {
  301. // We need to look for DNAME first, there's allowed case where
  302. // DNAME and NS coexist in the apex. DNAME is the one to notice,
  303. // the NS is authoritative, not delegation (corner case explicitly
  304. // allowed by section 3 of 2672)
  305. const Domain::const_iterator foundDNAME(node.getData()->find(
  306. RRType::DNAME()));
  307. if (foundDNAME != node.getData()->end()) {
  308. LOG_DEBUG(logger, DBG_TRACE_DETAILED,
  309. DATASRC_MEM_DNAME_ENCOUNTERED);
  310. state->dname_node_ = &node;
  311. state->rrset_ = foundDNAME->second;
  312. // No more processing below the DNAME (RFC 2672, section 3
  313. // forbids anything to exist below it, so there's no need
  314. // to actually search for it). This is strictly speaking
  315. // a different way than described in 4.1 of that RFC,
  316. // but because of the assumption in section 3, it has the
  317. // same behaviour.
  318. return (true);
  319. }
  320. // Look for NS
  321. const Domain::const_iterator foundNS(node.getData()->find(
  322. RRType::NS()));
  323. if (foundNS != node.getData()->end()) {
  324. // We perform callback check only for the highest zone cut in the
  325. // rare case of nested zone cuts.
  326. if (state->zonecut_node_ != NULL) {
  327. return (false);
  328. }
  329. LOG_DEBUG(logger, DBG_TRACE_DETAILED, DATASRC_MEM_NS_ENCOUNTERED);
  330. // BIND 9 checks if this node is not the origin. That's probably
  331. // because it can support multiple versions for dynamic updates
  332. // and IXFR, and it's possible that the callback is called at
  333. // the apex and the DNAME doesn't exist for a particular version.
  334. // It cannot happen for us (at least for now), so we don't do
  335. // that check.
  336. state->zonecut_node_ = &node;
  337. state->rrset_ = foundNS->second;
  338. // Unless glue is allowed the search stops here, so we return
  339. // false; otherwise return true to continue the search.
  340. return ((state->options_ & FIND_GLUE_OK) == 0);
  341. }
  342. // This case should not happen because we enable callback only
  343. // when we add an RR searched for above.
  344. assert(0);
  345. // This is here to avoid warning (therefore compilation error)
  346. // in case assert is turned off. Otherwise we could get "Control
  347. // reached end of non-void function".
  348. return (false);
  349. }
  350. /*
  351. * Prepares a rrset to be return as a result.
  352. *
  353. * If rename is false, it returns the one provided. If it is true, it
  354. * creates a new rrset with the same data but with provided name.
  355. * It is designed for wildcard case, where we create the rrsets
  356. * dynamically.
  357. */
  358. static ConstRRsetPtr prepareRRset(const Name& name, const ConstRRsetPtr&
  359. rrset, bool rename)
  360. {
  361. if (rename) {
  362. LOG_DEBUG(logger, DBG_TRACE_DETAILED, DATASRC_MEM_RENAME).
  363. arg(rrset->getName()).arg(name);
  364. /*
  365. * We lose a signature here. But it would be wrong anyway, because
  366. * the name changed. This might turn out to be unimportant in
  367. * future, because wildcards will probably be handled somehow
  368. * by DNSSEC.
  369. */
  370. RRsetPtr result(new RRset(name, rrset->getClass(),
  371. rrset->getType(), rrset->getTTL()));
  372. for (RdataIteratorPtr i(rrset->getRdataIterator()); !i->isLast();
  373. i->next()) {
  374. result->addRdata(i->getCurrent());
  375. }
  376. return (result);
  377. } else {
  378. return (rrset);
  379. }
  380. }
  381. // Implementation of InMemoryZoneFinder::find
  382. FindResult find(const Name& name, RRType type,
  383. RRsetList* target, const FindOptions options) const
  384. {
  385. LOG_DEBUG(logger, DBG_TRACE_BASIC, DATASRC_MEM_FIND).arg(name).
  386. arg(type);
  387. // Get the node
  388. DomainNode* node(NULL);
  389. FindState state(options);
  390. RBTreeNodeChain<Domain> node_path;
  391. bool rename(false);
  392. switch (domains_.find(name, &node, node_path, cutCallback, &state)) {
  393. case DomainTree::PARTIALMATCH:
  394. /*
  395. * In fact, we could use a single variable instead of
  396. * dname_node_ and zonecut_node_. But then we would need
  397. * to distinquish these two cases by something else and
  398. * it seemed little more confusing to me when I wrote it.
  399. *
  400. * Usually at most one of them will be something else than
  401. * NULL (it might happen both are NULL, in which case we
  402. * consider it NOT FOUND). There's one corner case when
  403. * both might be something else than NULL and it is in case
  404. * there's a DNAME under a zone cut and we search in
  405. * glue OK mode ‒ in that case we don't stop on the domain
  406. * with NS and ignore it for the answer, but it gets set
  407. * anyway. Then we find the DNAME and we need to act by it,
  408. * therefore we first check for DNAME and then for NS. In
  409. * all other cases it doesn't matter, as at least one of them
  410. * is NULL.
  411. */
  412. if (state.dname_node_ != NULL) {
  413. LOG_DEBUG(logger, DBG_TRACE_DATA, DATASRC_MEM_DNAME_FOUND).
  414. arg(state.rrset_->getName());
  415. // We were traversing a DNAME node (and wanted to go
  416. // lower below it), so return the DNAME
  417. return (FindResult(DNAME, prepareRRset(name, state.rrset_,
  418. rename)));
  419. }
  420. if (state.zonecut_node_ != NULL) {
  421. LOG_DEBUG(logger, DBG_TRACE_DATA, DATASRC_MEM_DELEG_FOUND).
  422. arg(state.rrset_->getName());
  423. return (FindResult(DELEGATION, prepareRRset(name,
  424. state.rrset_, rename)));
  425. }
  426. // If the RBTree search stopped at a node for a super domain
  427. // of the search name, it means the search name exists in
  428. // the zone but is empty. Treat it as NXRRSET.
  429. if (node_path.getLastComparisonResult().getRelation() ==
  430. NameComparisonResult::SUPERDOMAIN) {
  431. LOG_DEBUG(logger, DBG_TRACE_DATA, DATASRC_MEM_SUPER_STOP).
  432. arg(node_path.getAbsoluteName()).arg(name);
  433. return (FindResult(NXRRSET, ConstRRsetPtr()));
  434. }
  435. /*
  436. * No redirection anywhere. Let's try if it is a wildcard.
  437. *
  438. * The wildcard is checked after the empty non-terminal domain
  439. * case above, because if that one triggers, it means we should
  440. * not match according to 4.3.3 of RFC 1034 (the query name
  441. * is known to exist).
  442. */
  443. if (node->getFlag(DOMAINFLAG_WILD)) {
  444. /* Should we cancel this match?
  445. *
  446. * If we compare with some node and get a common ancestor,
  447. * it might mean we are comparing with a non-wildcard node.
  448. * In that case, we check which part is common. If we have
  449. * something in common that lives below the node we got
  450. * (the one above *), then we should cancel the match
  451. * according to section 4.3.3 of RFC 1034 (as the name
  452. * between the wildcard domain and the query name is known
  453. * to exist).
  454. *
  455. * Because the way the tree stores relative names, we will
  456. * have exactly one common label (the ".") in case we have
  457. * nothing common under the node we got and we will get
  458. * more common labels otherwise (yes, this relies on the
  459. * internal RBTree structure, which leaks out through this
  460. * little bit).
  461. *
  462. * If the empty non-terminal node actually exists in the
  463. * tree, then this cancellation is not needed, because we
  464. * will not get here at all.
  465. */
  466. if (node_path.getLastComparisonResult().getRelation() ==
  467. NameComparisonResult::COMMONANCESTOR && node_path.
  468. getLastComparisonResult().getCommonLabels() > 1) {
  469. LOG_DEBUG(logger, DBG_TRACE_DATA,
  470. DATASRC_MEM_WILDCARD_CANCEL).arg(name);
  471. return (FindResult(NXDOMAIN, ConstRRsetPtr()));
  472. }
  473. Name wildcard(Name("*").concatenate(
  474. node_path.getAbsoluteName()));
  475. DomainTree::Result result(domains_.find(wildcard, &node));
  476. /*
  477. * Otherwise, why would the DOMAINFLAG_WILD be there if
  478. * there was no wildcard under it?
  479. */
  480. assert(result == DomainTree::EXACTMATCH);
  481. /*
  482. * We have the wildcard node now. Jump below the switch,
  483. * where handling of the common (exact-match) case is.
  484. *
  485. * However, rename it to the searched name.
  486. */
  487. rename = true;
  488. break;
  489. }
  490. // fall through
  491. case DomainTree::NOTFOUND:
  492. LOG_DEBUG(logger, DBG_TRACE_DATA, DATASRC_MEM_NOT_FOUND).
  493. arg(name);
  494. return (FindResult(NXDOMAIN, ConstRRsetPtr()));
  495. case DomainTree::EXACTMATCH: // This one is OK, handle it
  496. break;
  497. default:
  498. assert(0);
  499. }
  500. assert(node != NULL);
  501. // If there is an exact match but the node is empty, it's equivalent
  502. // to NXRRSET.
  503. if (node->isEmpty()) {
  504. LOG_DEBUG(logger, DBG_TRACE_DATA, DATASRC_MEM_DOMAIN_EMPTY).
  505. arg(name);
  506. return (FindResult(NXRRSET, ConstRRsetPtr()));
  507. }
  508. Domain::const_iterator found;
  509. // If the node callback is enabled, this may be a zone cut. If it
  510. // has a NS RR, we should return a delegation, but not in the apex.
  511. if (node->getFlag(DomainNode::FLAG_CALLBACK) && node != origin_data_) {
  512. found = node->getData()->find(RRType::NS());
  513. if (found != node->getData()->end()) {
  514. LOG_DEBUG(logger, DBG_TRACE_DATA,
  515. DATASRC_MEM_EXACT_DELEGATION).arg(name);
  516. return (FindResult(DELEGATION, prepareRRset(name,
  517. found->second, rename)));
  518. }
  519. }
  520. // handle type any query
  521. if (target != NULL && !node->getData()->empty()) {
  522. // Empty domain will be handled as NXRRSET by normal processing
  523. for (found = node->getData()->begin();
  524. found != node->getData()->end(); ++found)
  525. {
  526. target->addRRset(
  527. boost::const_pointer_cast<RRset>(prepareRRset(name,
  528. found->second, rename)));
  529. }
  530. LOG_DEBUG(logger, DBG_TRACE_DATA, DATASRC_MEM_ANY_SUCCESS).
  531. arg(name);
  532. return (FindResult(SUCCESS, ConstRRsetPtr()));
  533. }
  534. found = node->getData()->find(type);
  535. if (found != node->getData()->end()) {
  536. // Good, it is here
  537. LOG_DEBUG(logger, DBG_TRACE_DATA, DATASRC_MEM_SUCCESS).arg(name).
  538. arg(type);
  539. return (FindResult(SUCCESS, prepareRRset(name, found->second,
  540. rename)));
  541. } else {
  542. // Next, try CNAME.
  543. found = node->getData()->find(RRType::CNAME());
  544. if (found != node->getData()->end()) {
  545. LOG_DEBUG(logger, DBG_TRACE_DATA, DATASRC_MEM_CNAME).arg(name);
  546. return (FindResult(CNAME, prepareRRset(name, found->second,
  547. rename)));
  548. }
  549. }
  550. // No exact match or CNAME. Return NXRRSET.
  551. LOG_DEBUG(logger, DBG_TRACE_DATA, DATASRC_MEM_NXRRSET).arg(type).
  552. arg(name);
  553. return (FindResult(NXRRSET, ConstRRsetPtr()));
  554. }
  555. };
  556. InMemoryZoneFinder::InMemoryZoneFinder(const RRClass& zone_class, const Name& origin) :
  557. impl_(new InMemoryZoneFinderImpl(zone_class, origin))
  558. {
  559. LOG_DEBUG(logger, DBG_TRACE_BASIC, DATASRC_MEM_CREATE).arg(origin).
  560. arg(zone_class);
  561. }
  562. InMemoryZoneFinder::~InMemoryZoneFinder() {
  563. LOG_DEBUG(logger, DBG_TRACE_BASIC, DATASRC_MEM_DESTROY).arg(getOrigin()).
  564. arg(getClass());
  565. delete impl_;
  566. }
  567. Name
  568. InMemoryZoneFinder::getOrigin() const {
  569. return (impl_->origin_);
  570. }
  571. RRClass
  572. InMemoryZoneFinder::getClass() const {
  573. return (impl_->zone_class_);
  574. }
  575. ZoneFinder::FindResult
  576. InMemoryZoneFinder::find(const Name& name, const RRType& type,
  577. RRsetList* target, const FindOptions options)
  578. {
  579. return (impl_->find(name, type, target, options));
  580. }
  581. result::Result
  582. InMemoryZoneFinder::add(const ConstRRsetPtr& rrset) {
  583. return (impl_->add(rrset, &impl_->domains_));
  584. }
  585. void
  586. InMemoryZoneFinder::load(const string& filename) {
  587. LOG_DEBUG(logger, DBG_TRACE_BASIC, DATASRC_MEM_LOAD).arg(getOrigin()).
  588. arg(filename);
  589. // Load it into a temporary tree
  590. DomainTree tmp;
  591. masterLoad(filename.c_str(), getOrigin(), getClass(),
  592. boost::bind(&InMemoryZoneFinderImpl::addFromLoad, impl_, _1, &tmp));
  593. // If it went well, put it inside
  594. impl_->file_name_ = filename;
  595. tmp.swap(impl_->domains_);
  596. // And let the old data die with tmp
  597. }
  598. void
  599. InMemoryZoneFinder::swap(InMemoryZoneFinder& zone_finder) {
  600. LOG_DEBUG(logger, DBG_TRACE_BASIC, DATASRC_MEM_SWAP).arg(getOrigin()).
  601. arg(zone_finder.getOrigin());
  602. std::swap(impl_, zone_finder.impl_);
  603. }
  604. const string
  605. InMemoryZoneFinder::getFileName() const {
  606. return (impl_->file_name_);
  607. }
  608. /// Implementation details for \c InMemoryClient hidden from the public
  609. /// interface.
  610. ///
  611. /// For now, \c InMemoryClient only contains a \c ZoneTable object, which
  612. /// consists of (pointers to) \c InMemoryZoneFinder objects, we may add more
  613. /// member variables later for new features.
  614. class InMemoryClient::InMemoryClientImpl {
  615. public:
  616. InMemoryClientImpl() : zone_count(0) {}
  617. unsigned int zone_count;
  618. ZoneTable zone_table;
  619. };
  620. InMemoryClient::InMemoryClient() : impl_(new InMemoryClientImpl)
  621. {}
  622. InMemoryClient::~InMemoryClient() {
  623. delete impl_;
  624. }
  625. unsigned int
  626. InMemoryClient::getZoneCount() const {
  627. return (impl_->zone_count);
  628. }
  629. result::Result
  630. InMemoryClient::addZone(ZoneFinderPtr zone_finder) {
  631. if (!zone_finder) {
  632. isc_throw(InvalidParameter,
  633. "Null pointer is passed to InMemoryClient::addZone()");
  634. }
  635. LOG_DEBUG(logger, DBG_TRACE_BASIC, DATASRC_MEM_ADD_ZONE).
  636. arg(zone_finder->getOrigin()).arg(zone_finder->getClass().toText());
  637. const result::Result result = impl_->zone_table.addZone(zone_finder);
  638. if (result == result::SUCCESS) {
  639. ++impl_->zone_count;
  640. }
  641. return (result);
  642. }
  643. InMemoryClient::FindResult
  644. InMemoryClient::findZone(const isc::dns::Name& name) const {
  645. LOG_DEBUG(logger, DBG_TRACE_DATA, DATASRC_MEM_FIND_ZONE).arg(name);
  646. ZoneTable::FindResult result(impl_->zone_table.findZone(name));
  647. return (FindResult(result.code, result.zone));
  648. }
  649. namespace {
  650. class MemoryIterator : public ZoneIterator {
  651. private:
  652. RBTreeNodeChain<Domain> chain_;
  653. Domain::const_iterator dom_iterator_;
  654. const DomainTree& tree_;
  655. const DomainNode* node_;
  656. bool ready_;
  657. public:
  658. MemoryIterator(const DomainTree& tree, const Name& origin) :
  659. tree_(tree),
  660. ready_(true)
  661. {
  662. // Find the first node (origin) and preserve the node chain for future
  663. // searches
  664. DomainTree::Result result(tree_.find<void*>(origin, &node_, chain_,
  665. NULL, NULL));
  666. // It can't happen that the origin is not in there
  667. if (result != DomainTree::EXACTMATCH) {
  668. isc_throw(Unexpected,
  669. "In-memory zone corrupted, missing origin node");
  670. }
  671. // Initialize the iterator if there's somewhere to point to
  672. if (node_ != NULL && node_->getData() != DomainPtr()) {
  673. dom_iterator_ = node_->getData()->begin();
  674. }
  675. }
  676. virtual ConstRRsetPtr getNextRRset() {
  677. if (!ready_) {
  678. isc_throw(Unexpected, "Iterating past the zone end");
  679. }
  680. /*
  681. * This cycle finds the first nonempty node with yet unused RRset.
  682. * If it is NULL, we run out of nodes. If it is empty, it doesn't
  683. * contain any RRsets. If we are at the end, just get to next one.
  684. */
  685. while (node_ != NULL && (node_->getData() == DomainPtr() ||
  686. dom_iterator_ == node_->getData()->end())) {
  687. node_ = tree_.nextNode(chain_);
  688. // If there's a node, initialize the iterator and check next time
  689. // if the map is empty or not
  690. if (node_ != NULL && node_->getData() != NULL) {
  691. dom_iterator_ = node_->getData()->begin();
  692. }
  693. }
  694. if (node_ == NULL) {
  695. // That's all, folks
  696. ready_ = false;
  697. return (ConstRRsetPtr());
  698. }
  699. // The iterator points to the next yet unused RRset now
  700. ConstRRsetPtr result(dom_iterator_->second);
  701. // This one is used, move it to the next time for next call
  702. ++dom_iterator_;
  703. return (result);
  704. }
  705. };
  706. } // End of anonymous namespace
  707. ZoneIteratorPtr
  708. InMemoryClient::getIterator(const Name& name) const {
  709. ZoneTable::FindResult result(impl_->zone_table.findZone(name));
  710. if (result.code != result::SUCCESS) {
  711. isc_throw(DataSourceError, "No such zone: " + name.toText());
  712. }
  713. const InMemoryZoneFinder*
  714. zone(dynamic_cast<const InMemoryZoneFinder*>(result.zone.get()));
  715. if (zone == NULL) {
  716. /*
  717. * TODO: This can happen only during some of the tests and only as
  718. * a temporary solution. This should be fixed by #1159 and then
  719. * this cast and check shouldn't be necessary. We don't have
  720. * test for handling a "can not happen" condition.
  721. */
  722. isc_throw(Unexpected, "The zone at " + name.toText() +
  723. " is not InMemoryZoneFinder");
  724. }
  725. return (ZoneIteratorPtr(new MemoryIterator(zone->impl_->domains_, name)));
  726. }
  727. } // end of namespace datasrc
  728. } // end of namespace dns