memory_datasrc.cc 51 KB

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