memory_datasrc.cc 52 KB

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