memory_datasrc.cc 80 KB

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