memory_datasrc.cc 78 KB

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