memory_datasrc.cc 44 KB

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