memory_datasrc.cc 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547
  1. // Copyright (C) 2010 Internet Systems Consortium, Inc. ("ISC")
  2. //
  3. // Permission to use, copy, modify, and/or distribute this software for any
  4. // purpose with or without fee is hereby granted, provided that the above
  5. // copyright notice and this permission notice appear in all copies.
  6. //
  7. // THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES WITH
  8. // REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
  9. // AND FITNESS. IN NO EVENT SHALL ISC BE LIABLE FOR ANY SPECIAL, DIRECT,
  10. // INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
  11. // LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE
  12. // OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
  13. // PERFORMANCE OF THIS SOFTWARE.
  14. #include <map>
  15. #include <cassert>
  16. #include <boost/shared_ptr.hpp>
  17. #include <boost/bind.hpp>
  18. #include <dns/name.h>
  19. #include <dns/rrclass.h>
  20. #include <dns/rrsetlist.h>
  21. #include <dns/masterload.h>
  22. #include <datasrc/memory_datasrc.h>
  23. #include <datasrc/rbtree.h>
  24. using namespace std;
  25. using namespace isc::dns;
  26. namespace isc {
  27. namespace datasrc {
  28. // Private data and hidden methods of MemoryZone
  29. struct MemoryZone::MemoryZoneImpl {
  30. // Constructor
  31. MemoryZoneImpl(const RRClass& zone_class, const Name& origin) :
  32. zone_class_(zone_class), origin_(origin), origin_data_(NULL)
  33. {
  34. // We create the node for origin (it needs to exist anyway in future)
  35. domains_.insert(origin, &origin_data_);
  36. DomainPtr origin_domain(new Domain);
  37. origin_data_->setData(origin_domain);
  38. }
  39. // Some type aliases
  40. /*
  41. * Each domain consists of some RRsets. They will be looked up by the
  42. * RRType.
  43. *
  44. * The use of map is questionable with regard to performance - there'll
  45. * be usually only few RRsets in the domain, so the log n benefit isn't
  46. * much and a vector/array might be faster due to its simplicity and
  47. * continuous memory location. But this is unlikely to be a performance
  48. * critical place and map has better interface for the lookups, so we use
  49. * that.
  50. */
  51. typedef map<RRType, ConstRRsetPtr> Domain;
  52. typedef Domain::value_type DomainPair;
  53. typedef boost::shared_ptr<Domain> DomainPtr;
  54. // The tree stores domains
  55. typedef RBTree<Domain, true> DomainTree;
  56. typedef RBNode<Domain> DomainNode;
  57. static const DomainNode::Flags DOMAINFLAG_WILD = DomainNode::FLAG_USER1;
  58. // Information about the zone
  59. RRClass zone_class_;
  60. Name origin_;
  61. DomainNode* origin_data_;
  62. string file_name_;
  63. // The actual zone data
  64. DomainTree domains_;
  65. // Add the necessary magic for any wildcard contained in 'name'
  66. // (including itself) to be found in the zone.
  67. //
  68. // In order for wildcard matching to work correctly in find(),
  69. // we must ensure that a node for the wildcarding level exists in the
  70. // backend RBTree.
  71. // E.g. if the wildcard name is "*.sub.example." then we must ensure
  72. // that "sub.example." exists and is marked as a wildcard level.
  73. // Note: the "wildcarding level" is for the parent name of the wildcard
  74. // name (such as "sub.example.").
  75. //
  76. // We also perform the same trick for empty wild card names possibly
  77. // contained in 'name' (e.g., '*.foo.example' in 'bar.*.foo.example').
  78. void addWildcards(DomainTree& domains, const Name& name) {
  79. Name wname(name);
  80. const unsigned int labels(wname.getLabelCount());
  81. const unsigned int origin_labels(origin_.getLabelCount());
  82. for (unsigned int l = labels;
  83. l > origin_labels;
  84. --l, wname = wname.split(1)) {
  85. if (wname.isWildcard()) {
  86. DomainNode* node;
  87. DomainTree::Result result;
  88. // Ensure a separate level exists for the wildcard name.
  89. // Note: for 'name' itself we do this later anyway, but the
  90. // overhead should be marginal because wildcard names should
  91. // be rare.
  92. result = domains.insert(wname.split(1), &node);
  93. assert(result == DomainTree::SUCCESS ||
  94. result == DomainTree::ALREADYEXISTS);
  95. // Ensure a separate level exists for the "wildcarding" name,
  96. // and mark the node as "wild".
  97. result = domains.insert(wname, &node);
  98. assert(result == DomainTree::SUCCESS ||
  99. result == DomainTree::ALREADYEXISTS);
  100. node->setFlag(DOMAINFLAG_WILD);
  101. }
  102. }
  103. }
  104. /*
  105. * Does some checks in context of the data that are already in the zone.
  106. * Currently checks for forbidden combinations of RRsets in the same
  107. * domain (CNAME+anything, DNAME+NS).
  108. *
  109. * If such condition is found, it throws AddError.
  110. */
  111. void contextCheck(const ConstRRsetPtr& rrset,
  112. const DomainPtr& domain) const {
  113. // Ensure CNAME and other type of RR don't coexist for the same
  114. // owner name.
  115. if (rrset->getType() == RRType::CNAME()) {
  116. // XXX: this check will become incorrect when we support DNSSEC
  117. // (depending on how we support DNSSEC). We should revisit it
  118. // at that point.
  119. if (!domain->empty()) {
  120. isc_throw(AddError, "CNAME can't be added with other data for "
  121. << rrset->getName());
  122. }
  123. } else if (domain->find(RRType::CNAME()) != domain->end()) {
  124. isc_throw(AddError, "CNAME and " << rrset->getType() <<
  125. " can't coexist for " << rrset->getName());
  126. }
  127. /*
  128. * Similar with DNAME, but it must not coexist only with NS and only in
  129. * non-apex domains.
  130. * RFC 2672 section 3 mentions that it is implied from it and RFC 2181
  131. */
  132. if (rrset->getName() != origin_ &&
  133. // Adding DNAME, NS already there
  134. ((rrset->getType() == RRType::DNAME() &&
  135. domain->find(RRType::NS()) != domain->end()) ||
  136. // Adding NS, DNAME already there
  137. (rrset->getType() == RRType::NS() &&
  138. domain->find(RRType::DNAME()) != domain->end())))
  139. {
  140. isc_throw(AddError, "DNAME can't coexist with NS in non-apex "
  141. "domain " << rrset->getName());
  142. }
  143. }
  144. // Validate rrset before adding it to the zone. If something is wrong
  145. // it throws an exception. It doesn't modify the zone, and provides
  146. // the strong exception guarantee.
  147. void addValidation(const ConstRRsetPtr rrset) {
  148. if (!rrset) {
  149. isc_throw(NullRRset, "The rrset provided is NULL");
  150. }
  151. // Check for singleton RRs. It should probably handled at a different
  152. // in future.
  153. if ((rrset->getType() == RRType::CNAME() ||
  154. rrset->getType() == RRType::DNAME()) &&
  155. rrset->getRdataCount() > 1)
  156. {
  157. // XXX: this is not only for CNAME or DNAME. We should generalize
  158. // this code for all other "singleton RR types" (such as SOA) in a
  159. // separate task.
  160. isc_throw(AddError, "multiple RRs of singleton type for "
  161. << rrset->getName());
  162. }
  163. NameComparisonResult compare(origin_.compare(rrset->getName()));
  164. if (compare.getRelation() != NameComparisonResult::SUPERDOMAIN &&
  165. compare.getRelation() != NameComparisonResult::EQUAL)
  166. {
  167. isc_throw(OutOfZone, "The name " << rrset->getName() <<
  168. " is not contained in zone " << origin_);
  169. }
  170. // Some RR types do not really work well with a wildcard.
  171. // Even though the protocol specifically doesn't completely ban such
  172. // usage, we refuse to load a zone containing such RR in order to
  173. // keep the lookup logic simpler and more predictable.
  174. // See RFC4592 and (for DNAME) draft-ietf-dnsext-rfc2672bis-dname
  175. // for more technical background. Note also that BIND 9 refuses
  176. // NS at a wildcard, so in that sense we simply provide compatible
  177. // behavior.
  178. if (rrset->getName().isWildcard()) {
  179. if (rrset->getType() == RRType::NS()) {
  180. isc_throw(AddError, "Invalid NS owner name (wildcard): " <<
  181. rrset->getName());
  182. }
  183. if (rrset->getType() == RRType::DNAME()) {
  184. isc_throw(AddError, "Invalid DNAME owner name (wildcard): " <<
  185. rrset->getName());
  186. }
  187. }
  188. }
  189. /*
  190. * Implementation of longer methods. We put them here, because the
  191. * access is without the impl_-> and it will get inlined anyway.
  192. */
  193. // Implementation of MemoryZone::add
  194. result::Result add(const ConstRRsetPtr& rrset, DomainTree* domains) {
  195. // Sanitize input
  196. addValidation(rrset);
  197. // Add wildcards possibly contained in the owner name to the domain
  198. // tree.
  199. // Note: this can throw an exception, breaking strong exception
  200. // guarantee. (see also the note for contextCheck() below).
  201. addWildcards(*domains, rrset->getName());
  202. // Get the node
  203. DomainNode* node;
  204. DomainTree::Result result = domains->insert(rrset->getName(), &node);
  205. // Just check it returns reasonable results
  206. assert((result == DomainTree::SUCCESS ||
  207. result == DomainTree::ALREADYEXISTS) && node!= NULL);
  208. // Now get the domain
  209. DomainPtr domain;
  210. // It didn't exist yet, create it
  211. if (node->isEmpty()) {
  212. domain.reset(new Domain);
  213. node->setData(domain);
  214. } else { // Get existing one
  215. domain = node->getData();
  216. }
  217. // Checks related to the surrounding data.
  218. // Note: when the check fails and the exception is thrown, it may
  219. // break strong exception guarantee. At the moment we prefer
  220. // code simplicity and don't bother to introduce complicated
  221. // recovery code.
  222. contextCheck(rrset, domain);
  223. // Try inserting the rrset there
  224. if (domain->insert(DomainPair(rrset->getType(), rrset)).second) {
  225. // Ok, we just put it in
  226. // If this RRset creates a zone cut at this node, mark the node
  227. // indicating the need for callback in find().
  228. if (rrset->getType() == RRType::NS() &&
  229. rrset->getName() != origin_) {
  230. node->setFlag(DomainNode::FLAG_CALLBACK);
  231. // If it is DNAME, we have a callback as well here
  232. } else if (rrset->getType() == RRType::DNAME()) {
  233. node->setFlag(DomainNode::FLAG_CALLBACK);
  234. }
  235. return (result::SUCCESS);
  236. } else {
  237. // The RRSet of given type was already there
  238. return (result::EXIST);
  239. }
  240. }
  241. /*
  242. * Same as above, but it checks the return value and if it already exists,
  243. * it throws.
  244. */
  245. void addFromLoad(const ConstRRsetPtr& set, DomainTree* domains) {
  246. switch (add(set, domains)) {
  247. case result::EXIST:
  248. isc_throw(dns::MasterLoadError, "Duplicate rrset: " <<
  249. set->toText());
  250. case result::SUCCESS:
  251. return;
  252. default:
  253. assert(0);
  254. }
  255. }
  256. // Maintain intermediate data specific to the search context used in
  257. /// \c find().
  258. ///
  259. /// It will be passed to \c zonecutCallback() and record a possible
  260. /// zone cut node and related RRset (normally NS or DNAME).
  261. struct FindState {
  262. FindState(FindOptions options) :
  263. zonecut_node_(NULL),
  264. dname_node_(NULL),
  265. options_(options)
  266. {}
  267. const DomainNode* zonecut_node_;
  268. const DomainNode* dname_node_;
  269. ConstRRsetPtr rrset_;
  270. const FindOptions options_;
  271. };
  272. // A callback called from possible zone cut nodes and nodes with DNAME.
  273. // This will be passed from the \c find() method to \c RBTree::find().
  274. static bool cutCallback(const DomainNode& node, FindState* state) {
  275. // We need to look for DNAME first, there's allowed case where
  276. // DNAME and NS coexist in the apex. DNAME is the one to notice,
  277. // the NS is authoritative, not delegation (corner case explicitly
  278. // allowed by section 3 of 2672)
  279. const Domain::const_iterator foundDNAME(node.getData()->find(
  280. RRType::DNAME()));
  281. if (foundDNAME != node.getData()->end()) {
  282. state->dname_node_ = &node;
  283. state->rrset_ = foundDNAME->second;
  284. // No more processing below the DNAME (RFC 2672, section 3
  285. // forbids anything to exist below it, so there's no need
  286. // to actually search for it). This is strictly speaking
  287. // a different way than described in 4.1 of that RFC,
  288. // but because of the assumption in section 3, it has the
  289. // same behaviour.
  290. return (true);
  291. }
  292. // Look for NS
  293. const Domain::const_iterator foundNS(node.getData()->find(
  294. RRType::NS()));
  295. if (foundNS != node.getData()->end()) {
  296. // We perform callback check only for the highest zone cut in the
  297. // rare case of nested zone cuts.
  298. if (state->zonecut_node_ != NULL) {
  299. return (false);
  300. }
  301. // BIND 9 checks if this node is not the origin. That's probably
  302. // because it can support multiple versions for dynamic updates
  303. // and IXFR, and it's possible that the callback is called at
  304. // the apex and the DNAME doesn't exist for a particular version.
  305. // It cannot happen for us (at least for now), so we don't do
  306. // that check.
  307. state->zonecut_node_ = &node;
  308. state->rrset_ = foundNS->second;
  309. // Unless glue is allowed the search stops here, so we return
  310. // false; otherwise return true to continue the search.
  311. return ((state->options_ & FIND_GLUE_OK) == 0);
  312. }
  313. // This case should not happen because we enable callback only
  314. // when we add an RR searched for above.
  315. assert(0);
  316. // This is here to avoid warning (therefore compilation error)
  317. // in case assert is turned off. Otherwise we could get "Control
  318. // reached end of non-void function".
  319. return (false);
  320. }
  321. // Implementation of MemoryZone::find
  322. FindResult find(const Name& name, RRType type,
  323. RRsetList* target, const FindOptions options) const
  324. {
  325. // Get the node
  326. DomainNode* node(NULL);
  327. FindState state(options);
  328. switch (domains_.find(name, &node, cutCallback, &state)) {
  329. case DomainTree::PARTIALMATCH:
  330. /*
  331. * In fact, we could use a single variable instead of
  332. * dname_node_ and zonecut_node_. But then we would need
  333. * to distinquish these two cases by something else and
  334. * it seemed little more confusing to me when I wrote it.
  335. *
  336. * Usually at most one of them will be something else than
  337. * NULL (it might happen both are NULL, in which case we
  338. * consider it NOT FOUND). There's one corner case when
  339. * both might be something else than NULL and it is in case
  340. * there's a DNAME under a zone cut and we search in
  341. * glue OK mode ‒ in that case we don't stop on the domain
  342. * with NS and ignore it for the answer, but it gets set
  343. * anyway. Then we find the DNAME and we need to act by it,
  344. * therefore we first check for DNAME and then for NS. In
  345. * all other cases it doesn't matter, as at least one of them
  346. * is NULL.
  347. */
  348. if (state.dname_node_ != NULL) {
  349. // We were traversing a DNAME node (and wanted to go
  350. // lower below it), so return the DNAME
  351. return (FindResult(DNAME, state.rrset_));
  352. }
  353. if (state.zonecut_node_ != NULL) {
  354. return (FindResult(DELEGATION, state.rrset_));
  355. }
  356. // TODO: we should also cover empty non-terminal cases, which
  357. // will require non trivial code and is deferred for later
  358. // development. For now, we regard any partial match that
  359. // didn't hit a zone cut as "not found".
  360. case DomainTree::NOTFOUND:
  361. return (FindResult(NXDOMAIN, ConstRRsetPtr()));
  362. case DomainTree::EXACTMATCH: // This one is OK, handle it
  363. break;
  364. default:
  365. assert(0);
  366. }
  367. assert(node);
  368. // If there is an exact match but the node is empty, it's equivalent
  369. // to NXRRSET.
  370. if (node->isEmpty()) {
  371. return (FindResult(NXRRSET, ConstRRsetPtr()));
  372. }
  373. Domain::const_iterator found;
  374. // If the node callback is enabled, this may be a zone cut. If it
  375. // has a NS RR, we should return a delegation, but not in the apex.
  376. if (node->getFlag(DomainNode::FLAG_CALLBACK) && node != origin_data_) {
  377. found = node->getData()->find(RRType::NS());
  378. if (found != node->getData()->end()) {
  379. return (FindResult(DELEGATION, found->second));
  380. }
  381. }
  382. // handle type any query
  383. if (target != NULL && !node->getData()->empty()) {
  384. // Empty domain will be handled as NXRRSET by normal processing
  385. for (found = node->getData()->begin();
  386. found != node->getData()->end(); found++)
  387. {
  388. target->addRRset(
  389. boost::const_pointer_cast<RRset>(found->second));
  390. }
  391. return (FindResult(SUCCESS, ConstRRsetPtr()));
  392. }
  393. found = node->getData()->find(type);
  394. if (found != node->getData()->end()) {
  395. // Good, it is here
  396. return (FindResult(SUCCESS, found->second));
  397. } else {
  398. // Next, try CNAME.
  399. found = node->getData()->find(RRType::CNAME());
  400. if (found != node->getData()->end()) {
  401. return (FindResult(CNAME, found->second));
  402. }
  403. }
  404. // No exact match or CNAME. Return NXRRSET.
  405. return (FindResult(NXRRSET, ConstRRsetPtr()));
  406. }
  407. };
  408. MemoryZone::MemoryZone(const RRClass& zone_class, const Name& origin) :
  409. impl_(new MemoryZoneImpl(zone_class, origin))
  410. {
  411. }
  412. MemoryZone::~MemoryZone() {
  413. delete impl_;
  414. }
  415. const Name&
  416. MemoryZone::getOrigin() const {
  417. return (impl_->origin_);
  418. }
  419. const RRClass&
  420. MemoryZone::getClass() const {
  421. return (impl_->zone_class_);
  422. }
  423. Zone::FindResult
  424. MemoryZone::find(const Name& name, const RRType& type,
  425. RRsetList* target, const FindOptions options) const
  426. {
  427. return (impl_->find(name, type, target, options));
  428. }
  429. result::Result
  430. MemoryZone::add(const ConstRRsetPtr& rrset) {
  431. return (impl_->add(rrset, &impl_->domains_));
  432. }
  433. void
  434. MemoryZone::load(const string& filename) {
  435. // Load it into a temporary tree
  436. MemoryZoneImpl::DomainTree tmp;
  437. masterLoad(filename.c_str(), getOrigin(), getClass(),
  438. boost::bind(&MemoryZoneImpl::addFromLoad, impl_, _1, &tmp));
  439. // If it went well, put it inside
  440. impl_->file_name_ = filename;
  441. tmp.swap(impl_->domains_);
  442. // And let the old data die with tmp
  443. }
  444. void
  445. MemoryZone::swap(MemoryZone& zone) {
  446. std::swap(impl_, zone.impl_);
  447. }
  448. const string
  449. MemoryZone::getFileName() const {
  450. return (impl_->file_name_);
  451. }
  452. /// Implementation details for \c MemoryDataSrc hidden from the public
  453. /// interface.
  454. ///
  455. /// For now, \c MemoryDataSrc only contains a \c ZoneTable object, which
  456. /// consists of (pointers to) \c MemoryZone objects, we may add more
  457. /// member variables later for new features.
  458. class MemoryDataSrc::MemoryDataSrcImpl {
  459. public:
  460. MemoryDataSrcImpl() : zone_count(0) {}
  461. unsigned int zone_count;
  462. ZoneTable zone_table;
  463. };
  464. MemoryDataSrc::MemoryDataSrc() : impl_(new MemoryDataSrcImpl)
  465. {}
  466. MemoryDataSrc::~MemoryDataSrc() {
  467. delete impl_;
  468. }
  469. unsigned int
  470. MemoryDataSrc::getZoneCount() const {
  471. return (impl_->zone_count);
  472. }
  473. result::Result
  474. MemoryDataSrc::addZone(ZonePtr zone) {
  475. if (!zone) {
  476. isc_throw(InvalidParameter,
  477. "Null pointer is passed to MemoryDataSrc::addZone()");
  478. }
  479. const result::Result result = impl_->zone_table.addZone(zone);
  480. if (result == result::SUCCESS) {
  481. ++impl_->zone_count;
  482. }
  483. return (result);
  484. }
  485. MemoryDataSrc::FindResult
  486. MemoryDataSrc::findZone(const isc::dns::Name& name) const {
  487. return (FindResult(impl_->zone_table.findZone(name).code,
  488. impl_->zone_table.findZone(name).zone));
  489. }
  490. } // end of namespace datasrc
  491. } // end of namespace dns