memory_datasrc.cc 65 KB

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