memory_datasrc.cc 37 KB

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