memory_datasrc.cc 55 KB

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