memory_datasrc.cc 56 KB

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