memory_datasrc.cc 52 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293
  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 RRset& rrset, const Domain& domain) const {
  160. // Ensure CNAME and other type of RR don't coexist for the same
  161. // owner name except with NSEC, which is the only RR that can coexist
  162. // with CNAME (and also RRSIG, which is handled separately)
  163. if (rrset.getType() == RRType::CNAME()) {
  164. if (!domain.empty() &&
  165. (domain.size() > 1 ||
  166. (domain.begin()->second->getType() != RRType::NSEC()))) {
  167. LOG_ERROR(logger, DATASRC_MEM_CNAME_TO_NONEMPTY).
  168. arg(rrset.getName());
  169. isc_throw(AddError, "CNAME can't be added with other data for "
  170. << rrset.getName());
  171. }
  172. } else if (rrset.getType() != RRType::NSEC() &&
  173. 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. // Implementation of InMemoryZoneFinder::find
  572. FindResult find(const Name& name, RRType type,
  573. std::vector<ConstRRsetPtr> *target,
  574. const FindOptions options) const
  575. {
  576. LOG_DEBUG(logger, DBG_TRACE_BASIC, DATASRC_MEM_FIND).arg(name).
  577. arg(type);
  578. // Get the node
  579. DomainNode* node(NULL);
  580. FindState state(options);
  581. RBTreeNodeChain<Domain> node_path;
  582. bool rename(false);
  583. switch (zone_data_->domains_.find(name, &node, node_path, cutCallback,
  584. &state)) {
  585. case DomainTree::PARTIALMATCH:
  586. /*
  587. * In fact, we could use a single variable instead of
  588. * dname_node_ and zonecut_node_. But then we would need
  589. * to distinquish these two cases by something else and
  590. * it seemed little more confusing to me when I wrote it.
  591. *
  592. * Usually at most one of them will be something else than
  593. * NULL (it might happen both are NULL, in which case we
  594. * consider it NOT FOUND). There's one corner case when
  595. * both might be something else than NULL and it is in case
  596. * there's a DNAME under a zone cut and we search in
  597. * glue OK mode ‒ in that case we don't stop on the domain
  598. * with NS and ignore it for the answer, but it gets set
  599. * anyway. Then we find the DNAME and we need to act by it,
  600. * therefore we first check for DNAME and then for NS. In
  601. * all other cases it doesn't matter, as at least one of them
  602. * is NULL.
  603. */
  604. if (state.dname_node_ != NULL) {
  605. LOG_DEBUG(logger, DBG_TRACE_DATA, DATASRC_MEM_DNAME_FOUND).
  606. arg(state.rrset_->getName());
  607. // We were traversing a DNAME node (and wanted to go
  608. // lower below it), so return the DNAME
  609. return (FindResult(DNAME, prepareRRset(name, state.rrset_,
  610. rename)));
  611. }
  612. if (state.zonecut_node_ != NULL) {
  613. LOG_DEBUG(logger, DBG_TRACE_DATA, DATASRC_MEM_DELEG_FOUND).
  614. arg(state.rrset_->getName());
  615. return (FindResult(DELEGATION, prepareRRset(name,
  616. state.rrset_, rename)));
  617. }
  618. // If the RBTree search stopped at a node for a super domain
  619. // of the search name, it means the search name exists in
  620. // the zone but is empty. Treat it as NXRRSET.
  621. if (node_path.getLastComparisonResult().getRelation() ==
  622. NameComparisonResult::SUPERDOMAIN) {
  623. LOG_DEBUG(logger, DBG_TRACE_DATA, DATASRC_MEM_SUPER_STOP).
  624. arg(node_path.getAbsoluteName()).arg(name);
  625. return (FindResult(NXRRSET, ConstRRsetPtr()));
  626. }
  627. /*
  628. * No redirection anywhere. Let's try if it is a wildcard.
  629. *
  630. * The wildcard is checked after the empty non-terminal domain
  631. * case above, because if that one triggers, it means we should
  632. * not match according to 4.3.3 of RFC 1034 (the query name
  633. * is known to exist).
  634. */
  635. if (node->getFlag(DOMAINFLAG_WILD)) {
  636. /* Should we cancel this match?
  637. *
  638. * If we compare with some node and get a common ancestor,
  639. * it might mean we are comparing with a non-wildcard node.
  640. * In that case, we check which part is common. If we have
  641. * something in common that lives below the node we got
  642. * (the one above *), then we should cancel the match
  643. * according to section 4.3.3 of RFC 1034 (as the name
  644. * between the wildcard domain and the query name is known
  645. * to exist).
  646. *
  647. * Because the way the tree stores relative names, we will
  648. * have exactly one common label (the ".") in case we have
  649. * nothing common under the node we got and we will get
  650. * more common labels otherwise (yes, this relies on the
  651. * internal RBTree structure, which leaks out through this
  652. * little bit).
  653. *
  654. * If the empty non-terminal node actually exists in the
  655. * tree, then this cancellation is not needed, because we
  656. * will not get here at all.
  657. */
  658. if (node_path.getLastComparisonResult().getRelation() ==
  659. NameComparisonResult::COMMONANCESTOR && node_path.
  660. getLastComparisonResult().getCommonLabels() > 1) {
  661. LOG_DEBUG(logger, DBG_TRACE_DATA,
  662. DATASRC_MEM_WILDCARD_CANCEL).arg(name);
  663. return (FindResult(NXDOMAIN, ConstRRsetPtr()));
  664. }
  665. Name wildcard(Name("*").concatenate(
  666. node_path.getAbsoluteName()));
  667. DomainTree::Result result =
  668. zone_data_->domains_.find(wildcard, &node);
  669. /*
  670. * Otherwise, why would the DOMAINFLAG_WILD be there if
  671. * there was no wildcard under it?
  672. */
  673. assert(result == DomainTree::EXACTMATCH);
  674. /*
  675. * We have the wildcard node now. Jump below the switch,
  676. * where handling of the common (exact-match) case is.
  677. *
  678. * However, rename it to the searched name.
  679. */
  680. rename = true;
  681. break;
  682. }
  683. // fall through
  684. case DomainTree::NOTFOUND:
  685. LOG_DEBUG(logger, DBG_TRACE_DATA, DATASRC_MEM_NOT_FOUND).
  686. arg(name);
  687. return (FindResult(NXDOMAIN, ConstRRsetPtr()));
  688. case DomainTree::EXACTMATCH: // This one is OK, handle it
  689. break;
  690. default:
  691. assert(0);
  692. }
  693. assert(node != NULL);
  694. // If there is an exact match but the node is empty, it's equivalent
  695. // to NXRRSET.
  696. if (node->isEmpty()) {
  697. LOG_DEBUG(logger, DBG_TRACE_DATA, DATASRC_MEM_DOMAIN_EMPTY).
  698. arg(name);
  699. return (FindResult(NXRRSET, ConstRRsetPtr()));
  700. }
  701. Domain::const_iterator found;
  702. // If the node callback is enabled, this may be a zone cut. If it
  703. // has a NS RR, we should return a delegation, but not in the apex.
  704. // There is one exception: the case for DS query, which should always
  705. // be considered in-zone lookup.
  706. if (node->getFlag(DomainNode::FLAG_CALLBACK) &&
  707. node != zone_data_->origin_data_ && type != RRType::DS()) {
  708. found = node->getData()->find(RRType::NS());
  709. if (found != node->getData()->end()) {
  710. LOG_DEBUG(logger, DBG_TRACE_DATA,
  711. DATASRC_MEM_EXACT_DELEGATION).arg(name);
  712. return (FindResult(DELEGATION, prepareRRset(name,
  713. found->second, rename)));
  714. }
  715. }
  716. // handle type any query
  717. if (target != NULL && !node->getData()->empty()) {
  718. // Empty domain will be handled as NXRRSET by normal processing
  719. for (found = node->getData()->begin();
  720. found != node->getData()->end(); ++found)
  721. {
  722. target->push_back(prepareRRset(name, found->second, rename));
  723. }
  724. LOG_DEBUG(logger, DBG_TRACE_DATA, DATASRC_MEM_ANY_SUCCESS).
  725. arg(name);
  726. return (FindResult(SUCCESS, ConstRRsetPtr()));
  727. }
  728. found = node->getData()->find(type);
  729. if (found != node->getData()->end()) {
  730. // Good, it is here
  731. LOG_DEBUG(logger, DBG_TRACE_DATA, DATASRC_MEM_SUCCESS).arg(name).
  732. arg(type);
  733. return (FindResult(SUCCESS, prepareRRset(name, found->second,
  734. rename)));
  735. } else {
  736. // Next, try CNAME.
  737. found = node->getData()->find(RRType::CNAME());
  738. if (found != node->getData()->end()) {
  739. LOG_DEBUG(logger, DBG_TRACE_DATA, DATASRC_MEM_CNAME).arg(name);
  740. return (FindResult(CNAME, prepareRRset(name, found->second,
  741. rename)));
  742. }
  743. }
  744. // No exact match or CNAME. Return NXRRSET.
  745. LOG_DEBUG(logger, DBG_TRACE_DATA, DATASRC_MEM_NXRRSET).arg(type).
  746. arg(name);
  747. return (FindResult(NXRRSET, ConstRRsetPtr()));
  748. }
  749. };
  750. InMemoryZoneFinder::InMemoryZoneFinder(const RRClass& zone_class, const Name& origin) :
  751. impl_(new InMemoryZoneFinderImpl(zone_class, origin))
  752. {
  753. LOG_DEBUG(logger, DBG_TRACE_BASIC, DATASRC_MEM_CREATE).arg(origin).
  754. arg(zone_class);
  755. }
  756. InMemoryZoneFinder::~InMemoryZoneFinder() {
  757. LOG_DEBUG(logger, DBG_TRACE_BASIC, DATASRC_MEM_DESTROY).arg(getOrigin()).
  758. arg(getClass());
  759. delete impl_;
  760. }
  761. Name
  762. InMemoryZoneFinder::getOrigin() const {
  763. return (impl_->origin_);
  764. }
  765. RRClass
  766. InMemoryZoneFinder::getClass() const {
  767. return (impl_->zone_class_);
  768. }
  769. ZoneFinder::FindResult
  770. InMemoryZoneFinder::find(const Name& name, const RRType& type,
  771. const FindOptions options)
  772. {
  773. return (impl_->find(name, type, NULL, options));
  774. }
  775. ZoneFinder::FindResult
  776. InMemoryZoneFinder::findAll(const Name& name,
  777. std::vector<ConstRRsetPtr>& target,
  778. const FindOptions options)
  779. {
  780. return (impl_->find(name, RRType::ANY(), &target, options));
  781. }
  782. ZoneFinder::FindNSEC3Result
  783. InMemoryZoneFinder::findNSEC3(const Name&, bool) {
  784. isc_throw(NotImplemented, "findNSEC3 is not yet implemented for in memory "
  785. "data source");
  786. }
  787. ZoneFinder::FindNSEC3Result
  788. InMemoryZoneFinder::findNSEC3Tmp(const Name& name, bool recursive) {
  789. if (!impl_->zone_data_->nsec3_data_) {
  790. isc_throw(Unexpected, "findNSEC3 is called for non NSEC3 zone");
  791. }
  792. if (recursive) {
  793. isc_throw(Unexpected, "recursive mode isn't expected in tests");
  794. }
  795. // A temporary workaround for testing: convert the original name to
  796. // NSEC3-hashed name using hardcoded mapping.
  797. string hname_text;
  798. if (name == Name("example.org")) {
  799. hname_text = "0P9MHAVEQVM6T7VBL5LOP2U3T2RP3TOM";
  800. } else if (name == Name("www.example.org")) {
  801. hname_text = "2S9MHAVEQVM6T7VBL5LOP2U3T2RP3TOM";
  802. } else if (name == Name("xxx.example.org")) {
  803. hname_text = "Q09MHAVEQVM6T7VBL5LOP2U3T2RP3TOM";
  804. } else if (name == Name("yyy.example.org")) {
  805. hname_text = "0A9MHAVEQVM6T7VBL5LOP2U3T2RP3TOM";
  806. } else {
  807. isc_throw(Unexpected, "unexpected name for NSEC3 test: " << name);
  808. }
  809. // Below we assume the map is not empty for simplicity.
  810. NSEC3Map::const_iterator found =
  811. impl_->zone_data_->nsec3_data_->map_.lower_bound(hname_text);
  812. if (found != impl_->zone_data_->nsec3_data_->map_.end() &&
  813. found->first == hname_text) {
  814. // exact match
  815. return (FindNSEC3Result(true, 2, found->second, ConstRRsetPtr()));
  816. } else if (found == impl_->zone_data_->nsec3_data_->map_.end() ||
  817. found == impl_->zone_data_->nsec3_data_->map_.begin()) {
  818. // the search key is "smaller" than the smallest or "larger" than
  819. // largest. In either case "previous" is the largest one.
  820. return (FindNSEC3Result(false, 2,
  821. impl_->zone_data_->nsec3_data_->map_.
  822. rbegin()->second, ConstRRsetPtr()));
  823. } else {
  824. // Otherwise, H(found_domain-1) < given_hash < H(found_domain)
  825. // The covering proof is the first one.
  826. return (FindNSEC3Result(false, 2, (--found)->second, ConstRRsetPtr()));
  827. }
  828. // We should have covered all cases.
  829. isc_throw(Unexpected, "Impossible NSEC3 search result for " << name);
  830. }
  831. result::Result
  832. InMemoryZoneFinder::add(const ConstRRsetPtr& rrset) {
  833. return (impl_->add(rrset, *impl_->zone_data_));
  834. }
  835. void
  836. InMemoryZoneFinder::load(const string& filename) {
  837. LOG_DEBUG(logger, DBG_TRACE_BASIC, DATASRC_MEM_LOAD).arg(getOrigin()).
  838. arg(filename);
  839. // Load it into temporary zone data
  840. scoped_ptr<ZoneData> tmp(new ZoneData(getOrigin()));
  841. masterLoad(filename.c_str(), getOrigin(), getClass(),
  842. boost::bind(&InMemoryZoneFinderImpl::addFromLoad, impl_,
  843. _1, tmp.get()));
  844. // If the zone is NSEC3-signed, check if it has NSEC3PARAM
  845. if (tmp->nsec3_data_) {
  846. // Note: origin_data_ is set on creation of ZoneData, and the load
  847. // process only adds new nodes (and their data), so this assertion
  848. // should hold.
  849. assert(tmp->origin_data_ != NULL && !tmp->origin_data_->isEmpty());
  850. if (tmp->origin_data_->getData()->find(RRType::NSEC3PARAM()) ==
  851. tmp->origin_data_->getData()->end()) {
  852. LOG_WARN(logger, DATASRC_MEM_NO_NSEC3PARAM).
  853. arg(getOrigin()).arg(getClass());
  854. }
  855. }
  856. // If it went well, put it inside
  857. impl_->file_name_ = filename;
  858. tmp.swap(impl_->zone_data_);
  859. // And let the old data die with tmp
  860. }
  861. void
  862. InMemoryZoneFinder::swap(InMemoryZoneFinder& zone_finder) {
  863. LOG_DEBUG(logger, DBG_TRACE_BASIC, DATASRC_MEM_SWAP).arg(getOrigin()).
  864. arg(zone_finder.getOrigin());
  865. std::swap(impl_, zone_finder.impl_);
  866. }
  867. const string
  868. InMemoryZoneFinder::getFileName() const {
  869. return (impl_->file_name_);
  870. }
  871. isc::dns::Name
  872. InMemoryZoneFinder::findPreviousName(const isc::dns::Name&) const {
  873. isc_throw(NotImplemented, "InMemory data source doesn't support DNSSEC "
  874. "yet, can't find previous name");
  875. }
  876. /// Implementation details for \c InMemoryClient hidden from the public
  877. /// interface.
  878. ///
  879. /// For now, \c InMemoryClient only contains a \c ZoneTable object, which
  880. /// consists of (pointers to) \c InMemoryZoneFinder objects, we may add more
  881. /// member variables later for new features.
  882. class InMemoryClient::InMemoryClientImpl {
  883. public:
  884. InMemoryClientImpl() : zone_count(0) {}
  885. unsigned int zone_count;
  886. ZoneTable zone_table;
  887. };
  888. InMemoryClient::InMemoryClient() : impl_(new InMemoryClientImpl)
  889. {}
  890. InMemoryClient::~InMemoryClient() {
  891. delete impl_;
  892. }
  893. unsigned int
  894. InMemoryClient::getZoneCount() const {
  895. return (impl_->zone_count);
  896. }
  897. result::Result
  898. InMemoryClient::addZone(ZoneFinderPtr zone_finder) {
  899. if (!zone_finder) {
  900. isc_throw(InvalidParameter,
  901. "Null pointer is passed to InMemoryClient::addZone()");
  902. }
  903. LOG_DEBUG(logger, DBG_TRACE_BASIC, DATASRC_MEM_ADD_ZONE).
  904. arg(zone_finder->getOrigin()).arg(zone_finder->getClass().toText());
  905. const result::Result result = impl_->zone_table.addZone(zone_finder);
  906. if (result == result::SUCCESS) {
  907. ++impl_->zone_count;
  908. }
  909. return (result);
  910. }
  911. InMemoryClient::FindResult
  912. InMemoryClient::findZone(const isc::dns::Name& name) const {
  913. LOG_DEBUG(logger, DBG_TRACE_DATA, DATASRC_MEM_FIND_ZONE).arg(name);
  914. ZoneTable::FindResult result(impl_->zone_table.findZone(name));
  915. return (FindResult(result.code, result.zone));
  916. }
  917. namespace {
  918. class MemoryIterator : public ZoneIterator {
  919. private:
  920. RBTreeNodeChain<Domain> chain_;
  921. Domain::const_iterator dom_iterator_;
  922. const DomainTree& tree_;
  923. const DomainNode* node_;
  924. // Only used when separate_rrs_ is true
  925. RdataIteratorPtr rdata_iterator_;
  926. bool separate_rrs_;
  927. bool ready_;
  928. public:
  929. MemoryIterator(const DomainTree& tree, const Name& origin, bool separate_rrs) :
  930. tree_(tree),
  931. separate_rrs_(separate_rrs),
  932. ready_(true)
  933. {
  934. // Find the first node (origin) and preserve the node chain for future
  935. // searches
  936. DomainTree::Result result(tree_.find<void*>(origin, &node_, chain_,
  937. NULL, NULL));
  938. // It can't happen that the origin is not in there
  939. if (result != DomainTree::EXACTMATCH) {
  940. isc_throw(Unexpected,
  941. "In-memory zone corrupted, missing origin node");
  942. }
  943. // Initialize the iterator if there's somewhere to point to
  944. if (node_ != NULL && node_->getData() != DomainPtr()) {
  945. dom_iterator_ = node_->getData()->begin();
  946. if (separate_rrs_ && dom_iterator_ != node_->getData()->end()) {
  947. rdata_iterator_ = dom_iterator_->second->getRdataIterator();
  948. }
  949. }
  950. }
  951. virtual ConstRRsetPtr getNextRRset() {
  952. if (!ready_) {
  953. isc_throw(Unexpected, "Iterating past the zone end");
  954. }
  955. /*
  956. * This cycle finds the first nonempty node with yet unused RRset.
  957. * If it is NULL, we run out of nodes. If it is empty, it doesn't
  958. * contain any RRsets. If we are at the end, just get to next one.
  959. */
  960. while (node_ != NULL && (node_->getData() == DomainPtr() ||
  961. dom_iterator_ == node_->getData()->end())) {
  962. node_ = tree_.nextNode(chain_);
  963. // If there's a node, initialize the iterator and check next time
  964. // if the map is empty or not
  965. if (node_ != NULL && node_->getData() != NULL) {
  966. dom_iterator_ = node_->getData()->begin();
  967. // New RRset, so get a new rdata iterator
  968. if (separate_rrs_) {
  969. rdata_iterator_ = dom_iterator_->second->getRdataIterator();
  970. }
  971. }
  972. }
  973. if (node_ == NULL) {
  974. // That's all, folks
  975. ready_ = false;
  976. return (ConstRRsetPtr());
  977. }
  978. if (separate_rrs_) {
  979. // For separate rrs, reconstruct a new RRset with just the
  980. // 'current' rdata
  981. RRsetPtr result(new RRset(dom_iterator_->second->getName(),
  982. dom_iterator_->second->getClass(),
  983. dom_iterator_->second->getType(),
  984. dom_iterator_->second->getTTL()));
  985. result->addRdata(rdata_iterator_->getCurrent());
  986. rdata_iterator_->next();
  987. if (rdata_iterator_->isLast()) {
  988. // all used up, next.
  989. ++dom_iterator_;
  990. // New RRset, so get a new rdata iterator, but only if this
  991. // was not the final RRset in the chain
  992. if (dom_iterator_ != node_->getData()->end()) {
  993. rdata_iterator_ = dom_iterator_->second->getRdataIterator();
  994. }
  995. }
  996. return (result);
  997. } else {
  998. // The iterator points to the next yet unused RRset now
  999. ConstRRsetPtr result(dom_iterator_->second);
  1000. // This one is used, move it to the next time for next call
  1001. ++dom_iterator_;
  1002. return (result);
  1003. }
  1004. }
  1005. virtual ConstRRsetPtr getSOA() const {
  1006. isc_throw(NotImplemented, "Not imelemented");
  1007. }
  1008. };
  1009. } // End of anonymous namespace
  1010. ZoneIteratorPtr
  1011. InMemoryClient::getIterator(const Name& name, bool separate_rrs) const {
  1012. ZoneTable::FindResult result(impl_->zone_table.findZone(name));
  1013. if (result.code != result::SUCCESS) {
  1014. isc_throw(DataSourceError, "No such zone: " + name.toText());
  1015. }
  1016. const InMemoryZoneFinder*
  1017. zone(dynamic_cast<const InMemoryZoneFinder*>(result.zone.get()));
  1018. if (zone == NULL) {
  1019. /*
  1020. * TODO: This can happen only during some of the tests and only as
  1021. * a temporary solution. This should be fixed by #1159 and then
  1022. * this cast and check shouldn't be necessary. We don't have
  1023. * test for handling a "can not happen" condition.
  1024. */
  1025. isc_throw(Unexpected, "The zone at " + name.toText() +
  1026. " is not InMemoryZoneFinder");
  1027. }
  1028. return (ZoneIteratorPtr(new MemoryIterator(
  1029. zone->impl_->zone_data_->domains_, name,
  1030. separate_rrs)));
  1031. }
  1032. ZoneUpdaterPtr
  1033. InMemoryClient::getUpdater(const isc::dns::Name&, bool, bool) const {
  1034. isc_throw(isc::NotImplemented, "Update attempt on in memory data source");
  1035. }
  1036. pair<ZoneJournalReader::Result, ZoneJournalReaderPtr>
  1037. InMemoryClient::getJournalReader(const isc::dns::Name&, uint32_t,
  1038. uint32_t) const
  1039. {
  1040. isc_throw(isc::NotImplemented, "Journaling isn't supported for "
  1041. "in memory data source");
  1042. }
  1043. namespace {
  1044. // convencience function to add an error message to a list of those
  1045. // (TODO: move functions like these to some util lib?)
  1046. void
  1047. addError(ElementPtr errors, const std::string& error) {
  1048. if (errors != ElementPtr() && errors->getType() == Element::list) {
  1049. errors->add(Element::create(error));
  1050. }
  1051. }
  1052. /// Check if the given element exists in the map, and if it is a string
  1053. bool
  1054. checkConfigElementString(ConstElementPtr config, const std::string& name,
  1055. ElementPtr errors)
  1056. {
  1057. if (!config->contains(name)) {
  1058. addError(errors,
  1059. "Config for memory backend does not contain a '"
  1060. +name+
  1061. "' value");
  1062. return false;
  1063. } else if (!config->get(name) ||
  1064. config->get(name)->getType() != Element::string) {
  1065. addError(errors, "value of " + name +
  1066. " in memory backend config is not a string");
  1067. return false;
  1068. } else {
  1069. return true;
  1070. }
  1071. }
  1072. bool
  1073. checkZoneConfig(ConstElementPtr config, ElementPtr errors) {
  1074. bool result = true;
  1075. if (!config || config->getType() != Element::map) {
  1076. addError(errors, "Elements in memory backend's zone list must be maps");
  1077. result = false;
  1078. } else {
  1079. if (!checkConfigElementString(config, "origin", errors)) {
  1080. result = false;
  1081. }
  1082. if (!checkConfigElementString(config, "file", errors)) {
  1083. result = false;
  1084. }
  1085. // we could add some existence/readabilty/parsability checks here
  1086. // if we want
  1087. }
  1088. return result;
  1089. }
  1090. bool
  1091. checkConfig(ConstElementPtr config, ElementPtr errors) {
  1092. /* Specific configuration is under discussion, right now this accepts
  1093. * the 'old' configuration, see [TODO]
  1094. * So for memory datasource, we get a structure like this:
  1095. * { "type": string ("memory"),
  1096. * "class": string ("IN"/"CH"/etc),
  1097. * "zones": list
  1098. * }
  1099. * Zones list is a list of maps:
  1100. * { "origin": string,
  1101. * "file": string
  1102. * }
  1103. *
  1104. * At this moment we cannot be completely sure of the contents of the
  1105. * structure, so we have to do some more extensive tests than should
  1106. * strictly be necessary (e.g. existence and type of elements)
  1107. */
  1108. bool result = true;
  1109. if (!config || config->getType() != Element::map) {
  1110. addError(errors, "Base config for memory backend must be a map");
  1111. result = false;
  1112. } else {
  1113. if (!checkConfigElementString(config, "type", errors)) {
  1114. result = false;
  1115. } else {
  1116. if (config->get("type")->stringValue() != "memory") {
  1117. addError(errors,
  1118. "Config for memory backend is not of type \"memory\"");
  1119. result = false;
  1120. }
  1121. }
  1122. if (!checkConfigElementString(config, "class", errors)) {
  1123. result = false;
  1124. } else {
  1125. try {
  1126. RRClass rrc(config->get("class")->stringValue());
  1127. } catch (const isc::Exception& rrce) {
  1128. addError(errors,
  1129. "Error parsing class config for memory backend: " +
  1130. std::string(rrce.what()));
  1131. result = false;
  1132. }
  1133. }
  1134. if (!config->contains("zones")) {
  1135. addError(errors, "No 'zones' element in memory backend config");
  1136. result = false;
  1137. } else if (!config->get("zones") ||
  1138. config->get("zones")->getType() != Element::list) {
  1139. addError(errors, "'zones' element in memory backend config is not a list");
  1140. result = false;
  1141. } else {
  1142. BOOST_FOREACH(ConstElementPtr zone_config,
  1143. config->get("zones")->listValue()) {
  1144. if (!checkZoneConfig(zone_config, errors)) {
  1145. result = false;
  1146. }
  1147. }
  1148. }
  1149. }
  1150. return (result);
  1151. return true;
  1152. }
  1153. } // end anonymous namespace
  1154. DataSourceClient *
  1155. createInstance(isc::data::ConstElementPtr config, std::string& error) {
  1156. ElementPtr errors(Element::createList());
  1157. if (!checkConfig(config, errors)) {
  1158. error = "Configuration error: " + errors->str();
  1159. return (NULL);
  1160. }
  1161. try {
  1162. return (new InMemoryClient());
  1163. } catch (const std::exception& exc) {
  1164. error = std::string("Error creating memory datasource: ") + exc.what();
  1165. return (NULL);
  1166. } catch (...) {
  1167. error = std::string("Error creating memory datasource, "
  1168. "unknown exception");
  1169. return (NULL);
  1170. }
  1171. }
  1172. void destroyInstance(DataSourceClient* instance) {
  1173. delete instance;
  1174. }
  1175. } // end of namespace datasrc
  1176. } // end of namespace isc