memory_datasrc.cc 54 KB

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