memory_datasrc.cc 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017
  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. std::vector<ConstRRsetPtr> *target,
  389. const FindOptions options) const
  390. {
  391. LOG_DEBUG(logger, DBG_TRACE_BASIC, DATASRC_MEM_FIND).arg(name).
  392. arg(type);
  393. // Get the node
  394. DomainNode* node(NULL);
  395. FindState state(options);
  396. RBTreeNodeChain<Domain> node_path;
  397. bool rename(false);
  398. switch (domains_.find(name, &node, node_path, cutCallback, &state)) {
  399. case DomainTree::PARTIALMATCH:
  400. /*
  401. * In fact, we could use a single variable instead of
  402. * dname_node_ and zonecut_node_. But then we would need
  403. * to distinquish these two cases by something else and
  404. * it seemed little more confusing to me when I wrote it.
  405. *
  406. * Usually at most one of them will be something else than
  407. * NULL (it might happen both are NULL, in which case we
  408. * consider it NOT FOUND). There's one corner case when
  409. * both might be something else than NULL and it is in case
  410. * there's a DNAME under a zone cut and we search in
  411. * glue OK mode ‒ in that case we don't stop on the domain
  412. * with NS and ignore it for the answer, but it gets set
  413. * anyway. Then we find the DNAME and we need to act by it,
  414. * therefore we first check for DNAME and then for NS. In
  415. * all other cases it doesn't matter, as at least one of them
  416. * is NULL.
  417. */
  418. if (state.dname_node_ != NULL) {
  419. LOG_DEBUG(logger, DBG_TRACE_DATA, DATASRC_MEM_DNAME_FOUND).
  420. arg(state.rrset_->getName());
  421. // We were traversing a DNAME node (and wanted to go
  422. // lower below it), so return the DNAME
  423. return (FindResult(DNAME, prepareRRset(name, state.rrset_,
  424. rename)));
  425. }
  426. if (state.zonecut_node_ != NULL) {
  427. LOG_DEBUG(logger, DBG_TRACE_DATA, DATASRC_MEM_DELEG_FOUND).
  428. arg(state.rrset_->getName());
  429. return (FindResult(DELEGATION, prepareRRset(name,
  430. state.rrset_, rename)));
  431. }
  432. // If the RBTree search stopped at a node for a super domain
  433. // of the search name, it means the search name exists in
  434. // the zone but is empty. Treat it as NXRRSET.
  435. if (node_path.getLastComparisonResult().getRelation() ==
  436. NameComparisonResult::SUPERDOMAIN) {
  437. LOG_DEBUG(logger, DBG_TRACE_DATA, DATASRC_MEM_SUPER_STOP).
  438. arg(node_path.getAbsoluteName()).arg(name);
  439. return (FindResult(NXRRSET, ConstRRsetPtr()));
  440. }
  441. /*
  442. * No redirection anywhere. Let's try if it is a wildcard.
  443. *
  444. * The wildcard is checked after the empty non-terminal domain
  445. * case above, because if that one triggers, it means we should
  446. * not match according to 4.3.3 of RFC 1034 (the query name
  447. * is known to exist).
  448. */
  449. if (node->getFlag(DOMAINFLAG_WILD)) {
  450. /* Should we cancel this match?
  451. *
  452. * If we compare with some node and get a common ancestor,
  453. * it might mean we are comparing with a non-wildcard node.
  454. * In that case, we check which part is common. If we have
  455. * something in common that lives below the node we got
  456. * (the one above *), then we should cancel the match
  457. * according to section 4.3.3 of RFC 1034 (as the name
  458. * between the wildcard domain and the query name is known
  459. * to exist).
  460. *
  461. * Because the way the tree stores relative names, we will
  462. * have exactly one common label (the ".") in case we have
  463. * nothing common under the node we got and we will get
  464. * more common labels otherwise (yes, this relies on the
  465. * internal RBTree structure, which leaks out through this
  466. * little bit).
  467. *
  468. * If the empty non-terminal node actually exists in the
  469. * tree, then this cancellation is not needed, because we
  470. * will not get here at all.
  471. */
  472. if (node_path.getLastComparisonResult().getRelation() ==
  473. NameComparisonResult::COMMONANCESTOR && node_path.
  474. getLastComparisonResult().getCommonLabels() > 1) {
  475. LOG_DEBUG(logger, DBG_TRACE_DATA,
  476. DATASRC_MEM_WILDCARD_CANCEL).arg(name);
  477. return (FindResult(NXDOMAIN, ConstRRsetPtr()));
  478. }
  479. Name wildcard(Name("*").concatenate(
  480. node_path.getAbsoluteName()));
  481. DomainTree::Result result(domains_.find(wildcard, &node));
  482. /*
  483. * Otherwise, why would the DOMAINFLAG_WILD be there if
  484. * there was no wildcard under it?
  485. */
  486. assert(result == DomainTree::EXACTMATCH);
  487. /*
  488. * We have the wildcard node now. Jump below the switch,
  489. * where handling of the common (exact-match) case is.
  490. *
  491. * However, rename it to the searched name.
  492. */
  493. rename = true;
  494. break;
  495. }
  496. // fall through
  497. case DomainTree::NOTFOUND:
  498. LOG_DEBUG(logger, DBG_TRACE_DATA, DATASRC_MEM_NOT_FOUND).
  499. arg(name);
  500. return (FindResult(NXDOMAIN, ConstRRsetPtr()));
  501. case DomainTree::EXACTMATCH: // This one is OK, handle it
  502. break;
  503. default:
  504. assert(0);
  505. }
  506. assert(node != NULL);
  507. // If there is an exact match but the node is empty, it's equivalent
  508. // to NXRRSET.
  509. if (node->isEmpty()) {
  510. LOG_DEBUG(logger, DBG_TRACE_DATA, DATASRC_MEM_DOMAIN_EMPTY).
  511. arg(name);
  512. return (FindResult(NXRRSET, ConstRRsetPtr()));
  513. }
  514. Domain::const_iterator found;
  515. // If the node callback is enabled, this may be a zone cut. If it
  516. // has a NS RR, we should return a delegation, but not in the apex.
  517. if (node->getFlag(DomainNode::FLAG_CALLBACK) && node != origin_data_) {
  518. found = node->getData()->find(RRType::NS());
  519. if (found != node->getData()->end()) {
  520. LOG_DEBUG(logger, DBG_TRACE_DATA,
  521. DATASRC_MEM_EXACT_DELEGATION).arg(name);
  522. return (FindResult(DELEGATION, prepareRRset(name,
  523. found->second, rename)));
  524. }
  525. }
  526. // handle type any query
  527. if (target != NULL && !node->getData()->empty()) {
  528. // Empty domain will be handled as NXRRSET by normal processing
  529. for (found = node->getData()->begin();
  530. found != node->getData()->end(); ++found)
  531. {
  532. target->push_back(prepareRRset(name, 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. const FindOptions options)
  582. {
  583. return (impl_->find(name, type, NULL, options));
  584. }
  585. ZoneFinder::FindResult
  586. InMemoryZoneFinder::findAll(const Name& name,
  587. std::vector<ConstRRsetPtr>& target,
  588. const FindOptions options)
  589. {
  590. return (impl_->find(name, RRType::ANY(), &target, options));
  591. }
  592. ZoneFinder::FindNSEC3Result
  593. InMemoryZoneFinder::findNSEC3(const Name&, bool, ConstRRsetPtr) {
  594. isc_throw(NotImplemented, "findNSEC3 is not yet implemented for in memory "
  595. "data source");
  596. }
  597. result::Result
  598. InMemoryZoneFinder::add(const ConstRRsetPtr& rrset) {
  599. return (impl_->add(rrset, &impl_->domains_));
  600. }
  601. void
  602. InMemoryZoneFinder::load(const string& filename) {
  603. LOG_DEBUG(logger, DBG_TRACE_BASIC, DATASRC_MEM_LOAD).arg(getOrigin()).
  604. arg(filename);
  605. // Load it into a temporary tree
  606. DomainTree tmp;
  607. masterLoad(filename.c_str(), getOrigin(), getClass(),
  608. boost::bind(&InMemoryZoneFinderImpl::addFromLoad, impl_, _1, &tmp));
  609. // If it went well, put it inside
  610. impl_->file_name_ = filename;
  611. tmp.swap(impl_->domains_);
  612. // And let the old data die with tmp
  613. }
  614. void
  615. InMemoryZoneFinder::swap(InMemoryZoneFinder& zone_finder) {
  616. LOG_DEBUG(logger, DBG_TRACE_BASIC, DATASRC_MEM_SWAP).arg(getOrigin()).
  617. arg(zone_finder.getOrigin());
  618. std::swap(impl_, zone_finder.impl_);
  619. }
  620. const string
  621. InMemoryZoneFinder::getFileName() const {
  622. return (impl_->file_name_);
  623. }
  624. isc::dns::Name
  625. InMemoryZoneFinder::findPreviousName(const isc::dns::Name&) const {
  626. isc_throw(NotImplemented, "InMemory data source doesn't support DNSSEC "
  627. "yet, can't find previous name");
  628. }
  629. /// Implementation details for \c InMemoryClient hidden from the public
  630. /// interface.
  631. ///
  632. /// For now, \c InMemoryClient only contains a \c ZoneTable object, which
  633. /// consists of (pointers to) \c InMemoryZoneFinder objects, we may add more
  634. /// member variables later for new features.
  635. class InMemoryClient::InMemoryClientImpl {
  636. public:
  637. InMemoryClientImpl() : zone_count(0) {}
  638. unsigned int zone_count;
  639. ZoneTable zone_table;
  640. };
  641. InMemoryClient::InMemoryClient() : impl_(new InMemoryClientImpl)
  642. {}
  643. InMemoryClient::~InMemoryClient() {
  644. delete impl_;
  645. }
  646. unsigned int
  647. InMemoryClient::getZoneCount() const {
  648. return (impl_->zone_count);
  649. }
  650. result::Result
  651. InMemoryClient::addZone(ZoneFinderPtr zone_finder) {
  652. if (!zone_finder) {
  653. isc_throw(InvalidParameter,
  654. "Null pointer is passed to InMemoryClient::addZone()");
  655. }
  656. LOG_DEBUG(logger, DBG_TRACE_BASIC, DATASRC_MEM_ADD_ZONE).
  657. arg(zone_finder->getOrigin()).arg(zone_finder->getClass().toText());
  658. const result::Result result = impl_->zone_table.addZone(zone_finder);
  659. if (result == result::SUCCESS) {
  660. ++impl_->zone_count;
  661. }
  662. return (result);
  663. }
  664. InMemoryClient::FindResult
  665. InMemoryClient::findZone(const isc::dns::Name& name) const {
  666. LOG_DEBUG(logger, DBG_TRACE_DATA, DATASRC_MEM_FIND_ZONE).arg(name);
  667. ZoneTable::FindResult result(impl_->zone_table.findZone(name));
  668. return (FindResult(result.code, result.zone));
  669. }
  670. namespace {
  671. class MemoryIterator : public ZoneIterator {
  672. private:
  673. RBTreeNodeChain<Domain> chain_;
  674. Domain::const_iterator dom_iterator_;
  675. const DomainTree& tree_;
  676. const DomainNode* node_;
  677. // Only used when separate_rrs_ is true
  678. RdataIteratorPtr rdata_iterator_;
  679. bool separate_rrs_;
  680. bool ready_;
  681. public:
  682. MemoryIterator(const DomainTree& tree, const Name& origin, bool separate_rrs) :
  683. tree_(tree),
  684. separate_rrs_(separate_rrs),
  685. ready_(true)
  686. {
  687. // Find the first node (origin) and preserve the node chain for future
  688. // searches
  689. DomainTree::Result result(tree_.find<void*>(origin, &node_, chain_,
  690. NULL, NULL));
  691. // It can't happen that the origin is not in there
  692. if (result != DomainTree::EXACTMATCH) {
  693. isc_throw(Unexpected,
  694. "In-memory zone corrupted, missing origin node");
  695. }
  696. // Initialize the iterator if there's somewhere to point to
  697. if (node_ != NULL && node_->getData() != DomainPtr()) {
  698. dom_iterator_ = node_->getData()->begin();
  699. if (separate_rrs_ && dom_iterator_ != node_->getData()->end()) {
  700. rdata_iterator_ = dom_iterator_->second->getRdataIterator();
  701. }
  702. }
  703. }
  704. virtual ConstRRsetPtr getNextRRset() {
  705. if (!ready_) {
  706. isc_throw(Unexpected, "Iterating past the zone end");
  707. }
  708. /*
  709. * This cycle finds the first nonempty node with yet unused RRset.
  710. * If it is NULL, we run out of nodes. If it is empty, it doesn't
  711. * contain any RRsets. If we are at the end, just get to next one.
  712. */
  713. while (node_ != NULL && (node_->getData() == DomainPtr() ||
  714. dom_iterator_ == node_->getData()->end())) {
  715. node_ = tree_.nextNode(chain_);
  716. // If there's a node, initialize the iterator and check next time
  717. // if the map is empty or not
  718. if (node_ != NULL && node_->getData() != NULL) {
  719. dom_iterator_ = node_->getData()->begin();
  720. // New RRset, so get a new rdata iterator
  721. if (separate_rrs_) {
  722. rdata_iterator_ = dom_iterator_->second->getRdataIterator();
  723. }
  724. }
  725. }
  726. if (node_ == NULL) {
  727. // That's all, folks
  728. ready_ = false;
  729. return (ConstRRsetPtr());
  730. }
  731. if (separate_rrs_) {
  732. // For separate rrs, reconstruct a new RRset with just the
  733. // 'current' rdata
  734. RRsetPtr result(new RRset(dom_iterator_->second->getName(),
  735. dom_iterator_->second->getClass(),
  736. dom_iterator_->second->getType(),
  737. dom_iterator_->second->getTTL()));
  738. result->addRdata(rdata_iterator_->getCurrent());
  739. rdata_iterator_->next();
  740. if (rdata_iterator_->isLast()) {
  741. // all used up, next.
  742. ++dom_iterator_;
  743. // New RRset, so get a new rdata iterator, but only if this
  744. // was not the final RRset in the chain
  745. if (dom_iterator_ != node_->getData()->end()) {
  746. rdata_iterator_ = dom_iterator_->second->getRdataIterator();
  747. }
  748. }
  749. return (result);
  750. } else {
  751. // The iterator points to the next yet unused RRset now
  752. ConstRRsetPtr result(dom_iterator_->second);
  753. // This one is used, move it to the next time for next call
  754. ++dom_iterator_;
  755. return (result);
  756. }
  757. }
  758. virtual ConstRRsetPtr getSOA() const {
  759. isc_throw(NotImplemented, "Not imelemented");
  760. }
  761. };
  762. } // End of anonymous namespace
  763. ZoneIteratorPtr
  764. InMemoryClient::getIterator(const Name& name, bool separate_rrs) const {
  765. ZoneTable::FindResult result(impl_->zone_table.findZone(name));
  766. if (result.code != result::SUCCESS) {
  767. isc_throw(DataSourceError, "No such zone: " + name.toText());
  768. }
  769. const InMemoryZoneFinder*
  770. zone(dynamic_cast<const InMemoryZoneFinder*>(result.zone.get()));
  771. if (zone == NULL) {
  772. /*
  773. * TODO: This can happen only during some of the tests and only as
  774. * a temporary solution. This should be fixed by #1159 and then
  775. * this cast and check shouldn't be necessary. We don't have
  776. * test for handling a "can not happen" condition.
  777. */
  778. isc_throw(Unexpected, "The zone at " + name.toText() +
  779. " is not InMemoryZoneFinder");
  780. }
  781. return (ZoneIteratorPtr(new MemoryIterator(zone->impl_->domains_, name,
  782. separate_rrs)));
  783. }
  784. ZoneUpdaterPtr
  785. InMemoryClient::getUpdater(const isc::dns::Name&, bool, bool) const {
  786. isc_throw(isc::NotImplemented, "Update attempt on in memory data source");
  787. }
  788. pair<ZoneJournalReader::Result, ZoneJournalReaderPtr>
  789. InMemoryClient::getJournalReader(const isc::dns::Name&, uint32_t,
  790. uint32_t) const
  791. {
  792. isc_throw(isc::NotImplemented, "Journaling isn't supported for "
  793. "in memory data source");
  794. }
  795. namespace {
  796. // convencience function to add an error message to a list of those
  797. // (TODO: move functions like these to some util lib?)
  798. void
  799. addError(ElementPtr errors, const std::string& error) {
  800. if (errors != ElementPtr() && errors->getType() == Element::list) {
  801. errors->add(Element::create(error));
  802. }
  803. }
  804. /// Check if the given element exists in the map, and if it is a string
  805. bool
  806. checkConfigElementString(ConstElementPtr config, const std::string& name,
  807. ElementPtr errors)
  808. {
  809. if (!config->contains(name)) {
  810. addError(errors,
  811. "Config for memory backend does not contain a '"
  812. +name+
  813. "' value");
  814. return false;
  815. } else if (!config->get(name) ||
  816. config->get(name)->getType() != Element::string) {
  817. addError(errors, "value of " + name +
  818. " in memory backend config is not a string");
  819. return false;
  820. } else {
  821. return true;
  822. }
  823. }
  824. bool
  825. checkZoneConfig(ConstElementPtr config, ElementPtr errors) {
  826. bool result = true;
  827. if (!config || config->getType() != Element::map) {
  828. addError(errors, "Elements in memory backend's zone list must be maps");
  829. result = false;
  830. } else {
  831. if (!checkConfigElementString(config, "origin", errors)) {
  832. result = false;
  833. }
  834. if (!checkConfigElementString(config, "file", errors)) {
  835. result = false;
  836. }
  837. // we could add some existence/readabilty/parsability checks here
  838. // if we want
  839. }
  840. return result;
  841. }
  842. bool
  843. checkConfig(ConstElementPtr config, ElementPtr errors) {
  844. /* Specific configuration is under discussion, right now this accepts
  845. * the 'old' configuration, see [TODO]
  846. * So for memory datasource, we get a structure like this:
  847. * { "type": string ("memory"),
  848. * "class": string ("IN"/"CH"/etc),
  849. * "zones": list
  850. * }
  851. * Zones list is a list of maps:
  852. * { "origin": string,
  853. * "file": string
  854. * }
  855. *
  856. * At this moment we cannot be completely sure of the contents of the
  857. * structure, so we have to do some more extensive tests than should
  858. * strictly be necessary (e.g. existence and type of elements)
  859. */
  860. bool result = true;
  861. if (!config || config->getType() != Element::map) {
  862. addError(errors, "Base config for memory backend must be a map");
  863. result = false;
  864. } else {
  865. if (!checkConfigElementString(config, "type", errors)) {
  866. result = false;
  867. } else {
  868. if (config->get("type")->stringValue() != "memory") {
  869. addError(errors,
  870. "Config for memory backend is not of type \"memory\"");
  871. result = false;
  872. }
  873. }
  874. if (!checkConfigElementString(config, "class", errors)) {
  875. result = false;
  876. } else {
  877. try {
  878. RRClass rrc(config->get("class")->stringValue());
  879. } catch (const isc::Exception& rrce) {
  880. addError(errors,
  881. "Error parsing class config for memory backend: " +
  882. std::string(rrce.what()));
  883. result = false;
  884. }
  885. }
  886. if (!config->contains("zones")) {
  887. addError(errors, "No 'zones' element in memory backend config");
  888. result = false;
  889. } else if (!config->get("zones") ||
  890. config->get("zones")->getType() != Element::list) {
  891. addError(errors, "'zones' element in memory backend config is not a list");
  892. result = false;
  893. } else {
  894. BOOST_FOREACH(ConstElementPtr zone_config,
  895. config->get("zones")->listValue()) {
  896. if (!checkZoneConfig(zone_config, errors)) {
  897. result = false;
  898. }
  899. }
  900. }
  901. }
  902. return (result);
  903. return true;
  904. }
  905. } // end anonymous namespace
  906. DataSourceClient *
  907. createInstance(isc::data::ConstElementPtr config, std::string& error) {
  908. ElementPtr errors(Element::createList());
  909. if (!checkConfig(config, errors)) {
  910. error = "Configuration error: " + errors->str();
  911. return (NULL);
  912. }
  913. try {
  914. return (new InMemoryClient());
  915. } catch (const std::exception& exc) {
  916. error = std::string("Error creating memory datasource: ") + exc.what();
  917. return (NULL);
  918. } catch (...) {
  919. error = std::string("Error creating memory datasource, "
  920. "unknown exception");
  921. return (NULL);
  922. }
  923. }
  924. void destroyInstance(DataSourceClient* instance) {
  925. delete instance;
  926. }
  927. } // end of namespace datasrc
  928. } // end of namespace isc