memory_datasrc.cc 32 KB

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