memory_datasrc.cc 33 KB

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