domaintree.h 82 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177
  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. #ifndef _DOMAINTREE_H
  15. #define _DOMAINTREE_H 1
  16. //! \file datasrc/memory/domaintree.h
  17. ///
  18. /// \note The purpose of the DomainTree is to provide a generic map with
  19. /// domain names as the key that can be used by various BIND 10
  20. /// modules or even by other applications. However, because of some
  21. /// unresolved design issue, the design and interface are not fixed,
  22. /// and DomainTree isn't ready to be used as a base data structure
  23. /// by other modules.
  24. #include <exceptions/exceptions.h>
  25. #include <util/memory_segment.h>
  26. #include <dns/name.h>
  27. #include <dns/labelsequence.h>
  28. #include <boost/utility.hpp>
  29. #include <boost/shared_ptr.hpp>
  30. #include <boost/interprocess/offset_ptr.hpp>
  31. #include <boost/static_assert.hpp>
  32. #include <ostream>
  33. #include <algorithm>
  34. #include <cassert>
  35. namespace isc {
  36. namespace datasrc {
  37. namespace memory {
  38. /// Forward declare DomainTree class here is convinent for following
  39. /// friend class declare inside DomainTreeNode and DomainTreeNodeChain
  40. template <typename T>
  41. class DomainTree;
  42. /// \brief \c DomainTreeNode is used by DomainTree to store any data
  43. /// related to one domain name.
  44. ///
  45. /// This is meant to be used only from DomainTree. It is meaningless to
  46. /// inherit it or create instances of it from elsewhere. For that
  47. /// reason, the constructor (and the allocator, see below) is private.
  48. ///
  49. /// It serves three roles. One is to keep structure of the \c DomainTree
  50. /// as a red-black tree. For that purpose, it has left, right and parent
  51. /// pointers and color member. These are private and accessed only from
  52. /// within the tree.
  53. ///
  54. /// The second one is to store data for one domain name. The data
  55. /// related functions can be used to access and set the data.
  56. ///
  57. /// The third role is to keep the hierarchy of domains. The down pointer
  58. /// points to a subtree of subdomains. The parent pointer of a subtree's
  59. /// root node points to the parent leaf of the upper tree.
  60. ///
  61. /// One special kind of node is non-terminal node. It has subdomains
  62. /// with RRsets, but doesn't have any RRsets itself.
  63. ///
  64. /// In order to keep memory footprint as small as possible, the node
  65. /// data are heavily packed. Specifically, some internal node
  66. /// properties (such as the node color) are encoded as part of "flags",
  67. /// some of the flag bits can also be set by the user application. Each
  68. /// node is associated with a sequence of domain name labels, which is
  69. /// essentially the search/insert key for the node (see also the
  70. /// description of DomainTree). This is encoded as opaque binary
  71. /// immediately following the main node object. The size of the
  72. /// allocated space for the labels data is encoded by borrowing some
  73. /// bits of the "flags" field.
  74. template <typename T>
  75. class DomainTreeNode : public boost::noncopyable {
  76. private:
  77. /// The DomainTreeNode is meant for use from within DomainTree, so
  78. /// it has access to it.
  79. friend class DomainTree<T>;
  80. /// \brief Just a type alias
  81. ///
  82. /// We are going to use a lot of these offset pointers here and they
  83. /// have a long name.
  84. typedef boost::interprocess::offset_ptr<DomainTreeNode<T> >
  85. DomainTreeNodePtr;
  86. /// \name Constructors
  87. ///
  88. /// \note The existence of a DomainTreeNode without a DomainTree is
  89. /// meaningless. Therefore the constructors are private.
  90. //@{
  91. /// \brief Constructor from normal nodes.
  92. DomainTreeNode(size_t labels_capacity);
  93. /// \brief Destructor
  94. ~DomainTreeNode();
  95. //@}
  96. /// \brief Accessor to the memory region for node labels.
  97. ///
  98. /// The only valid usage of the returned pointer is to pass it to
  99. /// the corresponding constructor of \c dns::LabelSequence.
  100. const void* getLabelsData() const { return (this + 1); }
  101. /// \brief Accessor to the memory region for node labels, mutable version.
  102. ///
  103. /// The only valid usage of the returned pointer is to pass it to
  104. /// \c LabelSequence::serialize() with the node's labels_capacity_ member
  105. /// (which should be sufficiently large for the \c LabelSequence in that
  106. /// context).
  107. void* getLabelsData() { return (this + 1); }
  108. /// \brief Allocate and construct \c DomainTreeNode
  109. ///
  110. /// This static method allocates memory for a new \c DomainTreeNode
  111. /// object from the given memory segment, constructs the object, and
  112. /// returns a pointer to it.
  113. ///
  114. /// \throw std::bad_alloc Memory allocation fails.
  115. ///
  116. /// \param mem_sgmt A \c MemorySegment from which memory for the new
  117. /// \c DomainTreeNode is allocated.
  118. static DomainTreeNode<T>* create(util::MemorySegment& mem_sgmt,
  119. const dns::LabelSequence& labels)
  120. {
  121. const size_t labels_len = labels.getSerializedLength();
  122. void* p = mem_sgmt.allocate(sizeof(DomainTreeNode<T>) + labels_len);
  123. DomainTreeNode<T>* node = new(p) DomainTreeNode<T>(labels_len);
  124. labels.serialize(node->getLabelsData(), labels_len);
  125. return (node);
  126. }
  127. /// \brief Destruct and deallocate \c DomainTreeNode
  128. ///
  129. /// \throw none
  130. ///
  131. /// \param mem_sgmt The \c MemorySegment that allocated memory for
  132. /// \c node.
  133. /// \param node A non NULL pointer to a valid \c DomainTreeNode object
  134. /// that was originally created by the \c create() method (the behavior
  135. /// is undefined if this condition isn't met).
  136. static void destroy(util::MemorySegment& mem_sgmt,
  137. DomainTreeNode<T>* node)
  138. {
  139. const size_t labels_capacity = node->labels_capacity_;
  140. node->~DomainTreeNode<T>();
  141. mem_sgmt.deallocate(node,
  142. sizeof(DomainTreeNode<T>) + labels_capacity);
  143. }
  144. /// \brief Reset node's label sequence to a new one.
  145. ///
  146. /// The new labels must be a sub sequence of the current label sequence;
  147. /// otherwise the serialize() method will throw an exception.
  148. void resetLabels(const dns::LabelSequence& labels) {
  149. labels.serialize(getLabelsData(), labels_capacity_);
  150. }
  151. public:
  152. /// Node flags.
  153. ///
  154. /// Each flag value defines a non default property for a specific node.
  155. /// These are defined as bitmask type values for the convenience of
  156. /// internal implementation, but applications are expected to use
  157. /// each flag separately via the enum definitions.
  158. ///
  159. /// All (settable) flags are off by default; they must be explicitly
  160. /// set to on by the \c setFlag() method.
  161. enum Flags {
  162. FLAG_CALLBACK = 1, ///< Callback enabled. See \ref callback
  163. FLAG_RED = 2, ///< Node color; 1 if node is red, 0 if node is black.
  164. FLAG_SUBTREE_ROOT = 4, ///< Set if the node is the root of a subtree
  165. FLAG_USER1 = 0x400000U, ///< Application specific flag
  166. FLAG_USER2 = 0x200000U, ///< Application specific flag
  167. FLAG_USER3 = 0x100000U, ///< Application specific flag
  168. FLAG_MAX = 0x400000U // for integrity check
  169. };
  170. private:
  171. // Some flag values are expected to be used for internal purposes
  172. // (e.g., representing the node color) in future versions, so we
  173. // limit the settable flags via the \c setFlag() method to those
  174. // explicitly defined in \c Flags. This constant represents all
  175. // such flags.
  176. static const uint32_t SETTABLE_FLAGS = (FLAG_CALLBACK | FLAG_USER1 |
  177. FLAG_USER2 | FLAG_USER3);
  178. public:
  179. /// \name Getter functions.
  180. //@{
  181. /// \brief Return the name of current node.
  182. ///
  183. /// It's relative to its containing node.
  184. ///
  185. /// To get the absolute name of one node, the node path from the top node
  186. /// to current node has to be recorded.
  187. ///
  188. /// \note We should eventually deprecate this method and revise all its
  189. /// usage with \c getLabels(). At this point the only user of this method
  190. /// is getAbsoluteName()::getAbsoluteName(), which would have to be revised
  191. /// using \c LabelSequence. Until then we keep this interface as a
  192. /// simplest form of wrapper; it's not efficient, but should be replaced
  193. /// before we need to worry about that.
  194. const isc::dns::Name getName() const {
  195. return (dns::Name(dns::LabelSequence(getLabelsData()).toText()));
  196. }
  197. /// \brief Return the label sequence of the node.
  198. ///
  199. /// This method returns the label sequence corresponding to this node
  200. /// in the form of \c dns::LabelSequence object. Any modification to
  201. /// the tree can invalidate the returned \c LabelSequence object or copy
  202. /// of it; in general, it's expected to be used in a very limited scope.
  203. dns::LabelSequence getLabels() const {
  204. return (dns::LabelSequence(getLabelsData()));
  205. }
  206. /// \brief Return the absolute label sequence of the node.
  207. ///
  208. /// This method returns the label sequence corresponding to the full
  209. /// name of the node; i.e. the entire name as it appears in the zone.
  210. ///
  211. /// It takes the (partial) name of the node itself, and extends it
  212. /// with all upper nodes.
  213. ///
  214. /// \note Care must be taken with the buffer that is used here; this
  215. /// method overwrites its data, so it should not be associated with
  216. /// any other LabelSequence during the lifetime of the LabelSequence
  217. /// returned by this method. See LabelSequence::extend(), which is used
  218. /// by this method.
  219. ///
  220. /// \param buf A data buffer where the label sequence will be built.
  221. /// The data in this buffer will be overwritten by this call.
  222. /// \return A LabelSequence with the absolute name of this node.
  223. isc::dns::LabelSequence getAbsoluteLabels(
  224. uint8_t buf[isc::dns::LabelSequence::MAX_SERIALIZED_LENGTH]) const;
  225. /// \brief Return the data stored in this node.
  226. ///
  227. /// You should not delete the data, it is deleted when the tree is
  228. /// destroyed.
  229. T* getData() { return (data_.get()); }
  230. /// \brief Return the data stored in this node (const).
  231. const T* getData() const { return (data_.get()); }
  232. /// \brief return whether the node has related data.
  233. ///
  234. /// There can be empty nodes inside the DomainTree. They are usually the
  235. /// non-terminal domains, but it is possible (yet probably meaningless)
  236. /// empty nodes anywhere.
  237. bool isEmpty() const { return (!data_); }
  238. //@}
  239. /// \name Setter functions.
  240. //@{
  241. /// \brief Set the data stored in the node.
  242. ///
  243. /// If there is old data, a pointer to the data will be returned;
  244. /// otherwise NULL will be returned. The caller is responsible for
  245. /// releasing any resource for the old data if it's not needed any more.
  246. /// See also the note about data ownership in the \c DomainTree
  247. /// description.
  248. ///
  249. /// \c data can be NULL, in which case it effectively clears any existing
  250. /// old data.
  251. ///
  252. /// \param data The new data to set. It can be NULL.
  253. /// \return A pointer to the old data or NULL if the node doesn't have
  254. /// data.
  255. T* setData(T* data) {
  256. T* olddata = data_.get();
  257. data_ = data;
  258. return (olddata);
  259. }
  260. //@}
  261. /// \name Node flag manipulation methods
  262. //@{
  263. /// Get the status of a node flag.
  264. ///
  265. /// This method returns whether the given node flag is set (enabled)
  266. /// on the node. The \c flag parameter is expected to be one of the
  267. /// defined \c Flags constants. For simplicity, the method interface
  268. /// does not prohibit passing an undefined flag or combined flags, but
  269. /// the return value in such a case will be meaningless for the caller
  270. /// (an application would have to use an ugly cast for such an unintended
  271. /// form of call, which will hopefully avoid accidental misuse).
  272. ///
  273. /// \exception None
  274. /// \param flag The flag to be tested.
  275. /// \return \c true if the \c flag is set; \c false otherwise.
  276. bool getFlag(Flags flag) const {
  277. return ((flags_ & flag) != 0);
  278. }
  279. /// Set or clear a node flag.
  280. ///
  281. /// This method changes the status of the specified node flag to either
  282. /// "on" (enabled) or "off" (disabled). The new status is specified by
  283. /// the \c on parameter.
  284. /// Like the \c getFlag() method, \c flag is expected to be one of the
  285. /// defined \c Flags constants. If an undefined or unsettable flag is
  286. /// specified, \c isc::InvalidParameter exception will be thrown.
  287. ///
  288. /// \exception isc::InvalidParameter Unsettable flag is specified
  289. /// \exception None otherwise
  290. /// \param flag The node flag to be changed.
  291. /// \param on If \c true, set the flag to on; otherwise set it to off.
  292. void setFlag(Flags flag, bool on = true) {
  293. if ((flag & ~SETTABLE_FLAGS) != 0) {
  294. isc_throw(isc::InvalidParameter,
  295. "Unsettable DomainTree flag is being set");
  296. }
  297. if (on) {
  298. flags_ |= flag;
  299. } else {
  300. flags_ &= ~flag;
  301. }
  302. }
  303. //@}
  304. private:
  305. /// \name Callback related methods
  306. ///
  307. /// See the description of \c DomainTree<T>::find() at \ref callback
  308. /// about callbacks.
  309. ///
  310. /// These methods never throw an exception.
  311. //@{
  312. /// Return if callback is enabled at the node.
  313. //@}
  314. /// \brief Define node color
  315. enum DomainTreeNodeColor {BLACK, RED};
  316. /// \brief Returns the color of this node
  317. DomainTreeNodeColor getColor() const {
  318. if ((flags_ & FLAG_RED) != 0) {
  319. return (RED);
  320. } else {
  321. return (BLACK);
  322. }
  323. }
  324. /// \brief Sets the color of this node
  325. void setColor(const DomainTreeNodeColor color) {
  326. if (color == RED) {
  327. flags_ |= FLAG_RED;
  328. } else {
  329. flags_ &= ~FLAG_RED;
  330. }
  331. }
  332. void setSubTreeRoot(bool root) {
  333. if (root) {
  334. flags_ |= FLAG_SUBTREE_ROOT;
  335. } else {
  336. flags_ &= ~FLAG_SUBTREE_ROOT;
  337. }
  338. }
  339. /// \brief returns if the node is a subtree's root node
  340. ///
  341. /// This method takes a node and returns \c true if it is the root
  342. /// node of the subtree it belongs to.
  343. ///
  344. /// This method never throws an exception.
  345. bool isSubTreeRoot() const {
  346. return ((flags_ & FLAG_SUBTREE_ROOT) != 0);
  347. }
  348. /// \brief returns the root of its subtree
  349. ///
  350. /// This method takes a node and returns the root of its subtree.
  351. ///
  352. /// This method never throws an exception.
  353. const DomainTreeNode<T>* getSubTreeRoot() const;
  354. public:
  355. /// \brief returns the parent of the root of its subtree
  356. ///
  357. /// This method takes a node and returns the parent of the root of
  358. /// its subtree (i.e, it returns the node's immediate ancestor in
  359. /// the tree-of-tree hierarchy). If the node is at the top level
  360. /// (which should be absolute), it will return \c NULL.
  361. ///
  362. /// This method never throws an exception.
  363. const DomainTreeNode<T>* getUpperNode() const;
  364. /// \brief return the next node which is bigger than current node
  365. /// in the same subtree
  366. ///
  367. /// The next successor for this node is the next bigger node in terms of
  368. /// the DNSSEC order relation within the same single subtree.
  369. /// Note that it may NOT be the next bigger node in the entire DomainTree;
  370. /// DomainTree is a tree in tree, and the real next node may reside in
  371. /// an upper or lower subtree of the subtree where this node belongs.
  372. /// For example, if this node has a sub domain, the real next node is
  373. /// the smallest node in the sub domain tree.
  374. ///
  375. /// If this node is the biggest node within the subtree, this method
  376. /// returns \c NULL.
  377. ///
  378. /// This method never throws an exception.
  379. const DomainTreeNode<T>* successor() const;
  380. /// \brief return the next node which is smaller than current node
  381. /// in the same subtree
  382. ///
  383. /// The predecessor for this node is the next smaller node in terms of
  384. /// the DNSSEC order relation within the same single subtree.
  385. /// Note that it may NOT be the next smaller node in the entire DomainTree;
  386. /// DomainTree is a tree in tree, and the real next node may reside in
  387. /// an upper or lower subtree of the subtree where this node belongs.
  388. /// For example, if the predecessor node has a sub domain, the real next
  389. /// node is the largest node in the sub domain tree.
  390. ///
  391. /// If this node is the smallest node within the subtree, this method
  392. /// returns \c NULL.
  393. ///
  394. /// This method never throws an exception.
  395. const DomainTreeNode<T>* predecessor() const;
  396. private:
  397. /// \brief private shared implementation of successor and predecessor
  398. ///
  399. /// As the two mentioned functions are merely mirror images of each other,
  400. /// it makes little sense to keep both versions. So this is the body of the
  401. /// functions and we call it with the correct pointers.
  402. ///
  403. /// Not to be called directly, not even by friends.
  404. ///
  405. /// The overhead of the member pointers should be optimised out, as this
  406. /// will probably get completely inlined into predecessor and successor
  407. /// methods.
  408. const DomainTreeNode<T>*
  409. abstractSuccessor(typename DomainTreeNode<T>::DomainTreeNodePtr
  410. DomainTreeNode<T>::*left,
  411. typename DomainTreeNode<T>::DomainTreeNodePtr
  412. DomainTreeNode<T>::*right)
  413. const;
  414. /// \name Data to maintain the rbtree structure.
  415. ///
  416. /// We keep them as offset pointers. This is part of a future plan, when we
  417. /// want to share the image of the tree between multiple processes.
  418. /// However, whenever we have a chance, we switch to bare pointers during
  419. /// the processing. The pointers on stack are never shared and the offset
  420. /// pointers have non-trivial performance impact.
  421. //@{
  422. DomainTreeNodePtr parent_;
  423. /// \brief Access the parent_ as bare pointer.
  424. DomainTreeNode<T>* getParent() {
  425. return (parent_.get());
  426. }
  427. /// \brief Access the parent_ as bare pointer, const.
  428. const DomainTreeNode<T>* getParent() const {
  429. return (parent_.get());
  430. }
  431. DomainTreeNodePtr left_;
  432. /// \brief Access the left_ as bare pointer.
  433. DomainTreeNode<T>* getLeft() {
  434. return (left_.get());
  435. }
  436. /// \brief Access the left_ as bare pointer, const.
  437. const DomainTreeNode<T>* getLeft() const {
  438. return (left_.get());
  439. }
  440. DomainTreeNodePtr right_;
  441. /// \brief Access the right_ as bare pointer.
  442. DomainTreeNode<T>* getRight() {
  443. return (right_.get());
  444. }
  445. /// \brief Access the right_ as bare pointer, const.
  446. const DomainTreeNode<T>* getRight() const {
  447. return (right_.get());
  448. }
  449. //@}
  450. /// \brief The subdomain tree.
  451. ///
  452. /// This points to the root node of trees of subdomains of this domain.
  453. ///
  454. /// \par Adding down pointer to \c DomainTreeNode has two purposes:
  455. /// \li Accelerate the search process, with sub domain tree, it splits the
  456. /// big flat tree into several hierarchy trees.
  457. /// \li It saves memory usage as it allows storing only relative names,
  458. /// avoiding storage of the same domain labels multiple times.
  459. DomainTreeNodePtr down_;
  460. /// \brief Access the down_ as bare pointer.
  461. DomainTreeNode<T>* getDown() {
  462. return (down_.get());
  463. }
  464. /// \brief Access the down_ as bare pointer, const.
  465. const DomainTreeNode<T>* getDown() const {
  466. return (down_.get());
  467. }
  468. /// \brief Data stored here.
  469. boost::interprocess::offset_ptr<T> data_;
  470. /// \brief Internal or user-configurable flags of node's properties.
  471. ///
  472. /// See the \c Flags enum for available flags.
  473. ///
  474. /// For memory efficiency reasons, we only use a subset of the 32-bit
  475. /// space, and use the rest to store the allocated size for the node's
  476. /// label sequence data.
  477. uint32_t flags_ : 23; // largest flag being 0x400000
  478. BOOST_STATIC_ASSERT((1 << 23) > FLAG_MAX); // assumption check
  479. const uint32_t labels_capacity_ : 9; // size for labelseq; range is 0..511
  480. // Make sure the reserved space for labels_capacity_ is sufficiently
  481. // large. In effect, we use the knowledge of the implementation of the
  482. // serialization, but we still only use its public interface, and the
  483. // public interface of this class doesn't rely on this assumption.
  484. // So we can change this implementation without affecting its users if
  485. // a future change to LabelSequence breaks this assumption.
  486. BOOST_STATIC_ASSERT((1 << 9) > dns::LabelSequence::MAX_SERIALIZED_LENGTH);
  487. };
  488. template <typename T>
  489. DomainTreeNode<T>::DomainTreeNode(size_t labels_capacity) :
  490. parent_(NULL),
  491. left_(NULL),
  492. right_(NULL),
  493. down_(NULL),
  494. data_(NULL),
  495. flags_(FLAG_RED | FLAG_SUBTREE_ROOT),
  496. labels_capacity_(labels_capacity)
  497. {
  498. }
  499. template <typename T>
  500. DomainTreeNode<T>::~DomainTreeNode() {
  501. }
  502. template <typename T>
  503. const DomainTreeNode<T>*
  504. DomainTreeNode<T>::getSubTreeRoot() const {
  505. const DomainTreeNode<T>* current = this;
  506. // current would never be equal to NULL here (in a correct tree
  507. // implementation)
  508. while (!current->isSubTreeRoot()) {
  509. current = current->getParent();
  510. }
  511. return (current);
  512. }
  513. template <typename T>
  514. const DomainTreeNode<T>*
  515. DomainTreeNode<T>::getUpperNode() const {
  516. return (getSubTreeRoot()->getParent());
  517. }
  518. template <typename T>
  519. isc::dns::LabelSequence
  520. DomainTreeNode<T>::getAbsoluteLabels(
  521. uint8_t buf[isc::dns::LabelSequence::MAX_SERIALIZED_LENGTH]) const
  522. {
  523. isc::dns::LabelSequence result(getLabels(), buf);
  524. const DomainTreeNode<T>* upper = getUpperNode();
  525. while (upper != NULL) {
  526. result.extend(upper->getLabels(), buf);
  527. upper = upper->getUpperNode();
  528. }
  529. return (result);
  530. }
  531. template <typename T>
  532. const DomainTreeNode<T>*
  533. DomainTreeNode<T>::abstractSuccessor(
  534. typename DomainTreeNode<T>::DomainTreeNodePtr DomainTreeNode<T>::*left,
  535. typename DomainTreeNode<T>::DomainTreeNodePtr DomainTreeNode<T>::*right)
  536. const
  537. {
  538. // This function is written as a successor. It becomes predecessor if
  539. // the left and right pointers are swapped. So in case of predecessor,
  540. // the left pointer points to right and vice versa. Don't get confused
  541. // by the idea, just imagine the pointers look into a mirror.
  542. const DomainTreeNode<T>* current = this;
  543. // If it has right node, the successor is the left-most node of the right
  544. // subtree.
  545. if ((current->*right).get() != NULL) {
  546. current = (current->*right).get();
  547. const DomainTreeNode<T>* left_n;
  548. while ((left_n = (current->*left).get()) != NULL) {
  549. current = left_n;
  550. }
  551. return (current);
  552. }
  553. // Otherwise go up until we find the first left branch on our path to
  554. // root. If found, the parent of the branch is the successor.
  555. // Otherwise, we return the null node
  556. const DomainTreeNode<T>* parent = current->getParent();
  557. while ((!current->isSubTreeRoot()) &&
  558. (current == (parent->*right).get())) {
  559. current = parent;
  560. parent = parent->getParent();
  561. }
  562. if (!current->isSubTreeRoot()) {
  563. return (parent);
  564. } else {
  565. return (NULL);
  566. }
  567. }
  568. template <typename T>
  569. const DomainTreeNode<T>*
  570. DomainTreeNode<T>::successor() const {
  571. return (abstractSuccessor(&DomainTreeNode<T>::left_,
  572. &DomainTreeNode<T>::right_));
  573. }
  574. template <typename T>
  575. const DomainTreeNode<T>*
  576. DomainTreeNode<T>::predecessor() const {
  577. // Swap the left and right pointers for the abstractSuccessor
  578. return (abstractSuccessor(&DomainTreeNode<T>::right_,
  579. &DomainTreeNode<T>::left_));
  580. }
  581. /// \brief DomainTreeNodeChain stores detailed information of \c
  582. /// DomainTree::find() result.
  583. ///
  584. /// - The \c DomainTreeNode that was last compared with the search name, and
  585. /// the comparison result at that point in the form of
  586. /// \c isc::dns::NameComparisonResult.
  587. /// - A sequence of nodes that forms a path to the found node.
  588. ///
  589. /// The comparison result can be used to handle some rare cases such as
  590. /// empty node processing.
  591. /// The node sequence keeps track of the nodes to reach any given node from
  592. /// the root of DomainTree.
  593. ///
  594. /// Currently, DomainTreeNode does not have "up" pointers in them (i.e.,
  595. /// back pointers from the root of one level of tree of trees to the
  596. /// node in the parent tree whose down pointer points to that root node)
  597. /// for memory usage reasons, so there is no other way to find the path
  598. /// back to the root from any given DomainTreeNode.
  599. ///
  600. /// \note This design may change in future versions. In particular, it's
  601. /// quite likely we want to have that pointer if we want to optimize name
  602. /// compression by exploiting the structure of the zone. If and when that
  603. /// happens we should also revisit the need for the chaining.
  604. /// Also, the class name may not be appropriate now that it contains other
  605. /// information than a node "chain", and the chain itself may even be
  606. /// deprecated. Something like "DomainTreeFindContext" may be a better name.
  607. /// This point should be revisited later.
  608. ///
  609. /// DomainTreeNodeChain is constructed and manipulated only inside the
  610. /// \c DomainTree class.
  611. /// \c DomainTree uses it as an inner data structure to iterate over the whole
  612. /// DomainTree.
  613. /// This is the reason why manipulation methods such as \c push() and \c pop()
  614. /// are private (and not shown in the doxygen document).
  615. template <typename T>
  616. class DomainTreeNodeChain {
  617. /// DomainTreeNodeChain is initialized by DomainTree, only DomainTree has
  618. /// knowledge to manipulate it.
  619. friend class DomainTree<T>;
  620. public:
  621. /// \name Constructors and Assignment Operator.
  622. ///
  623. /// \note The copy constructor and the assignment operator are
  624. /// intentionally defined as private, making this class non copyable.
  625. /// This may have to be changed in a future version with newer need.
  626. /// For now we explicitly disable copy to avoid accidental copy happens
  627. /// unintentionally.
  628. //{@
  629. /// The default constructor.
  630. ///
  631. /// \exception None
  632. DomainTreeNodeChain() : level_count_(0), last_compared_(NULL),
  633. // XXX: meaningless initial values:
  634. last_comparison_(0, 0,
  635. isc::dns::NameComparisonResult::EQUAL)
  636. {}
  637. /// \brief Copy constructor.
  638. ///
  639. /// \exception None
  640. DomainTreeNodeChain(const DomainTreeNodeChain<T>& other) :
  641. level_count_(other.level_count_),
  642. last_compared_(other.last_compared_),
  643. last_comparison_(other.last_comparison_)
  644. {
  645. for (size_t i = 0; i < level_count_; i++) {
  646. nodes_[i] = other.nodes_[i];
  647. }
  648. }
  649. private:
  650. DomainTreeNodeChain<T>& operator=(const DomainTreeNodeChain<T>&);
  651. //@}
  652. public:
  653. /// Clear the state of the chain.
  654. ///
  655. /// This method re-initializes the internal state of the chain so that
  656. /// it can be reused for subsequent operations.
  657. ///
  658. /// \exception None
  659. void clear() {
  660. level_count_ = 0;
  661. last_compared_ = NULL;
  662. }
  663. /// Return the \c DomainTreeNode that was last compared in \c
  664. /// DomainTree::find().
  665. ///
  666. /// If this chain has been passed to \c DomainTree::find() and there
  667. /// has been name comparison against the search name, the last
  668. /// compared \c DomainTreeNode is recorded within the chain. This
  669. /// method returns that node.
  670. ///
  671. /// If \c DomainTree::find() hasn't been called with this chain or
  672. /// name comparison hasn't taken place (which is possible if the
  673. /// tree is empty), this method returns \c NULL.
  674. ///
  675. /// \exception None
  676. const DomainTreeNode<T>* getLastComparedNode() const {
  677. return (last_compared_);
  678. }
  679. /// Return the result of last name comparison in \c DomainTree::find().
  680. ///
  681. /// Like \c getLastComparedNode(), \c DomainTree::find() records the result
  682. /// of the last name comparison in the chain. This method returns the
  683. /// result.
  684. /// The return value of this method is only meaningful when comparison
  685. /// has taken place, i.e, when \c getLastComparedNode() would return a
  686. /// non \c NULL value.
  687. ///
  688. /// \exception None
  689. const isc::dns::NameComparisonResult& getLastComparisonResult() const {
  690. return (last_comparison_);
  691. }
  692. /// \brief Return the number of levels stored in the chain.
  693. ///
  694. /// It's equal to the number of nodes in the chain; for an empty
  695. /// chain, 0 will be returned.
  696. ///
  697. /// \exception None
  698. size_t getLevelCount() const { return (level_count_); }
  699. /// \brief return the absolute name for the node which this
  700. /// \c DomainTreeNodeChain currently refers to.
  701. ///
  702. /// The chain must not be empty.
  703. ///
  704. /// \exception isc::BadValue the chain is empty.
  705. /// \exception std::bad_alloc memory allocation for the new name fails.
  706. isc::dns::Name getAbsoluteName() const {
  707. if (isEmpty()) {
  708. isc_throw(isc::BadValue,
  709. "DomainTreeNodeChain::getAbsoluteName is "
  710. "called on an empty chain");
  711. }
  712. const DomainTreeNode<T>* top_node = top();
  713. isc::dns::Name absolute_name = top_node->getName();
  714. size_t level = level_count_ - 1;
  715. while (level > 0) {
  716. top_node = nodes_[level - 1];
  717. absolute_name = absolute_name.concatenate(top_node->getName());
  718. --level;
  719. }
  720. return (absolute_name);
  721. }
  722. private:
  723. // the following private functions check invariants about the internal
  724. // state using assert() instead of exception. The state of a chain
  725. // can only be modified by operations within this file, so if any of the
  726. // assumptions fails it means an internal bug.
  727. /// \brief return whether node chain has node in it.
  728. ///
  729. /// \exception None
  730. bool isEmpty() const { return (level_count_ == 0); }
  731. /// \brief return the top node for the node chain
  732. ///
  733. /// DomainTreeNodeChain store all the nodes along top node to
  734. /// root node of DomainTree
  735. ///
  736. /// \exception None
  737. const DomainTreeNode<T>* top() const {
  738. assert(!isEmpty());
  739. return (nodes_[level_count_ - 1]);
  740. }
  741. /// \brief pop the top node from the node chain
  742. ///
  743. /// After pop, up/super node of original top node will be
  744. /// the top node
  745. ///
  746. /// \exception None
  747. void pop() {
  748. assert(!isEmpty());
  749. --level_count_;
  750. }
  751. /// \brief add the node into the node chain
  752. ///
  753. /// If the node chain isn't empty, the node should be
  754. /// the sub domain of the original top node in node chain
  755. /// otherwise the node should be the root node of DomainTree.
  756. ///
  757. /// \exception None
  758. void push(const DomainTreeNode<T>* node) {
  759. assert(level_count_ < RBT_MAX_LEVEL);
  760. nodes_[level_count_++] = node;
  761. }
  762. private:
  763. // The max label count for one domain name is Name::MAX_LABELS
  764. // (128). Since each node in domaintree stores at least one label,
  765. // it's also equal to the possible maximum level.
  766. const static int RBT_MAX_LEVEL = isc::dns::Name::MAX_LABELS;
  767. size_t level_count_;
  768. const DomainTreeNode<T>* nodes_[RBT_MAX_LEVEL];
  769. const DomainTreeNode<T>* last_compared_;
  770. isc::dns::NameComparisonResult last_comparison_;
  771. };
  772. // note: the following class description is documented using multiline comments
  773. // because the verbatim diagram contain a backslash, which could be interpreted
  774. // as escape of newline in singleline comment.
  775. /**
  776. * \brief \c DomainTree class represents all the domains with the same suffix.
  777. * It can be used to store the domains in one zone, for example.
  778. *
  779. * DomainTree is a generic map from domain names to any kind of
  780. * data. Internally, it uses a red-black tree. However, it isn't one
  781. * tree containing everything. Subdomains are trees, so this structure
  782. * is recursive - trees inside trees. But, from the interface point of
  783. * view, it is opaque data structure.
  784. *
  785. * The data of DomainTree are set by the application via the
  786. * DomainTreeNode::setData() method. The ownership of the data isn't
  787. * transferred to the DomainTree; if the application replaces existing
  788. * data for a specific name in DomainTree by setData(), the application is
  789. * responsible for releasing any resource for the old data. When the
  790. * application destroys the entire DomainTree by the \c destroy() method,
  791. * it needs to pass a deleter object for any remained data in the DomainTree.
  792. * The DomainTree will call that object with all the data in the tree so that
  793. * the application complete the cleanup about the remaining data.
  794. *
  795. * \c DomainTree splits the domain space into hierarchy red black trees; nodes
  796. * in one tree has the same base name. The benefit of this struct is that:
  797. * - Enhances the query performance compared with one big flat red black tree.
  798. * - Decreases the memory footprint, as it doesn't store the suffix labels
  799. * multiple times.
  800. *
  801. * Depending on different usage, domaintree will support different
  802. * search policies. Whether to return an empty node to end user is one
  803. * policy among them. The default policy is to NOT return an empty node
  804. * to end user; to change the behavior, specify \c true for the
  805. * constructor parameter \c returnEmptyNode.
  806. * \note The search policy only affects the \c find() behavior of DomainTree.
  807. * When inserting one name into DomainTree, if the node with the name already
  808. * exists in the DomainTree and it's an empty node which doesn't have any data,
  809. * the \c insert() method will still return \c ALREADYEXISTS regardless of
  810. * the search policy.
  811. *
  812. * The template parameter taken by \c DomainTree is \c T (the type of
  813. * data which is stored by the tree).
  814. *
  815. * \anchor diagram
  816. *
  817. * with the following names:
  818. * - a
  819. * - b
  820. * - c
  821. * - x.d.e.f
  822. * - z.d.e.f
  823. * - g.h
  824. * - o.w.y.d.e.f
  825. * - p.w.y.d.e.f
  826. * - q.w.y.d.e.f
  827. *
  828. * the tree will look like:
  829. * \verbatim
  830. .
  831. |
  832. b
  833. / \
  834. a d.e.f
  835. /|\
  836. c | g.h
  837. |
  838. w.y
  839. /|\
  840. x | z
  841. |
  842. p
  843. / \
  844. o q
  845. \endverbatim
  846. * \todo
  847. * - add remove interface
  848. */
  849. template <typename T>
  850. class DomainTree : public boost::noncopyable {
  851. friend class DomainTreeNode<T>;
  852. public:
  853. /// \brief The return value for the \c find() and insert() methods
  854. enum Result {
  855. SUCCESS, ///< Insert was successful
  856. /// \brief The node returned from find mathes exactly the name given
  857. EXACTMATCH,
  858. PARTIALMATCH, ///< A superdomain node was found
  859. NOTFOUND, ///< Not even any superdomain was found
  860. /// \brief Returned by insert() if a node of the name already exists
  861. ALREADYEXISTS,
  862. };
  863. /// \brief Allocate and construct \c DomainTree
  864. ///
  865. /// This static method allocates memory for a new \c DomainTree object
  866. /// from the given memory segment, constructs the object, and returns
  867. /// a pointer to it.
  868. ///
  869. /// \throw std::bad_alloc Memory allocation fails.
  870. ///
  871. /// \param mem_sgmt A \c MemorySegment from which memory for the new
  872. /// \c DomainTree is allocated.
  873. static DomainTree* create(util::MemorySegment& mem_sgmt,
  874. bool return_empty_node = false)
  875. {
  876. void* p = mem_sgmt.allocate(sizeof(DomainTree<T>));
  877. return (new(p) DomainTree<T>(return_empty_node));
  878. }
  879. /// \brief Destruct and deallocate \c DomainTree
  880. ///
  881. /// This method also destroys and deallocates all nodes inserted to the
  882. /// tree.
  883. ///
  884. /// The template parameter, \c DataDeleter, is a type whose instance is
  885. /// used to destroy data stored in the tree nodes. It must have a
  886. /// <code>operator()</code> method, which is called on a \c DataDeleter
  887. /// instance and passed a pointer to the data (<code>T*</code>) to be
  888. /// destroyed. This method should be written to accept a \c NULL argument.
  889. ///
  890. /// \note The memory segment (\c mem_sgmt) must be the same one that
  891. /// was originally used to allocate memory for the tree (and for all
  892. /// nodes inserted to the tree, due to the requirement of \c insert()),
  893. /// since the tree itself doesn't maintain a reference to the segment.
  894. /// This is not a robust interface, but since we plan to share the tree
  895. /// structure by multiple processes via shared memory or possibly allow
  896. /// the memory image to be dumped to a file for later reload, there
  897. /// doesn't seem to be an easy way to store such reference in the data
  898. /// itself. We should probably consider a wrapper interface that
  899. /// encapsulates the corresponding segment and always use it for any
  900. /// allocation/deallocation of tree related data (the tree itself, their
  901. /// nodes, and node data) to keep the usage as safe as possible.
  902. ///
  903. /// \throw none
  904. ///
  905. /// \param mem_sgmt The \c MemorySegment that allocated memory for
  906. /// \c tree and for all nodes inserted to the tree.
  907. /// \param tree A non NULL pointer to a valid \c DomainTree object
  908. /// that was originally created by the \c create() method (the behavior
  909. /// is undefined if this condition isn't met).
  910. /// \param deleter A deleter functor or function to delete node data.
  911. template <typename DataDeleter>
  912. static void destroy(util::MemorySegment& mem_sgmt,
  913. DomainTree<T>* tree,
  914. DataDeleter deleter)
  915. {
  916. tree->deleteAllNodes(mem_sgmt, deleter);
  917. tree->~DomainTree<T>();
  918. mem_sgmt.deallocate(tree, sizeof(DomainTree<T>));
  919. }
  920. private:
  921. /// \name Constructor and Destructor
  922. //@{
  923. /// \brief The constructor.
  924. ///
  925. /// An object of this class is always expected to be created by the
  926. /// allocator (\c create()), so the constructor is hidden as private.
  927. ///
  928. /// It never throws an exception.
  929. explicit DomainTree(bool returnEmptyNode = false);
  930. /// \brief The destructor.
  931. ///
  932. /// An object of this class is always expected to be destroyed explicitly
  933. /// by \c destroy(), so the destructor is hidden as private.
  934. ///
  935. /// \note DomainTree is not intended to be inherited so the destructor
  936. /// is not virtual
  937. ~DomainTree();
  938. //@}
  939. public:
  940. /// \name Find methods
  941. ///
  942. /// \brief Find the node that gives a longest match against the given name.
  943. ///
  944. /// \anchor find
  945. ///
  946. /// These methods search the DomainTree for a node whose name is
  947. /// longest against name. The found node, if any, is returned via
  948. /// the node pointer.
  949. ///
  950. /// By default, nodes that don't have data (see
  951. /// DomainTreeNode::isEmpty) are ignored and the result can be
  952. /// NOTFOUND even if there's a node whose name matches. If the \c
  953. /// DomainTree is constructed with its \c returnEmptyNode parameter
  954. /// being \c true, empty nodes will also be match candidates.
  955. ///
  956. /// \note Even when \c returnEmptyNode is \c true, not all empty
  957. /// nodes in terms of the DNS protocol may necessarily be found by
  958. /// this method. For example, in the \ref diagram shown in the
  959. /// class description, the name y.d.e.f is logically contained in
  960. /// the tree as part of the node w.y, but the \c find() variants
  961. /// cannot find the former for the search key of y.d.e.f, no matter
  962. /// how the \c DomainTree is constructed. The caller of this method
  963. /// must use a different way to identify the hidden match when
  964. /// necessary.
  965. ///
  966. /// These methods involve operations on names that can throw an
  967. /// exception. If that happens the exception will be propagated to
  968. /// the caller. The callback function should generally not throw an
  969. /// exception, but if it throws, the exception will be propagated to
  970. /// the caller.
  971. ///
  972. /// The \c name parameter says what should be found. The node parameter
  973. /// is output-only, and in case of EXACTMATCH or PARTIALMATCH, it is set
  974. /// to a pointer to the found node.
  975. ///
  976. /// They return:
  977. /// - EXACTMATCH when a node with the same name as requested exists.
  978. /// - PARTIALMATCH when a node with the same name does not exist (or is
  979. /// empty), but there's a (nonempty) superdomain of the requested one.
  980. /// The superdomain with longest name is returned through the node
  981. /// parameter. Beware that if you store a zone in the tree, you may get
  982. /// PARTIALMATCH with zone apex when the given domain name is not there.
  983. /// You should not try to delegate into another zone in that case.
  984. /// - NOTFOUND if there's no node with the same name nor any superdomain
  985. /// of it. In that case, node parameter is left intact.
  986. //@{
  987. /// \brief Simple find.
  988. ///
  989. /// Acts as described in the \ref find section.
  990. Result find(const isc::dns::Name& name,
  991. DomainTreeNode<T>** node) const {
  992. DomainTreeNodeChain<T> node_path;
  993. const isc::dns::LabelSequence ls(name);
  994. return (find<void*>(ls, node, node_path, NULL, NULL));
  995. }
  996. /// \brief Simple find returning immutable node.
  997. ///
  998. /// Acts as described in the \ref find section, but returns immutable node
  999. /// pointer.
  1000. Result find(const isc::dns::Name& name,
  1001. const DomainTreeNode<T>** node) const {
  1002. DomainTreeNodeChain<T> node_path;
  1003. DomainTreeNode<T> *target_node = NULL;
  1004. const isc::dns::LabelSequence ls(name);
  1005. Result ret = (find<void*>(ls, &target_node, node_path, NULL, NULL));
  1006. if (ret != NOTFOUND) {
  1007. *node = target_node;
  1008. }
  1009. return (ret);
  1010. }
  1011. /// \brief Simple find, with node_path tracking
  1012. ///
  1013. /// Acts as described in the \ref find section.
  1014. Result find(const isc::dns::Name& name, DomainTreeNode<T>** node,
  1015. DomainTreeNodeChain<T>& node_path) const
  1016. {
  1017. const isc::dns::LabelSequence ls(name);
  1018. return (find<void*>(ls, node, node_path, NULL, NULL));
  1019. }
  1020. /// \brief Simple find returning immutable node, with node_path tracking
  1021. ///
  1022. /// Acts as described in the \ref find section, but returns immutable node
  1023. /// pointer.
  1024. Result find(const isc::dns::Name& name, const DomainTreeNode<T>** node,
  1025. DomainTreeNodeChain<T>& node_path) const
  1026. {
  1027. DomainTreeNode<T> *target_node = NULL;
  1028. const isc::dns::LabelSequence ls(name);
  1029. Result ret = (find<void*>(ls, &target_node, node_path, NULL, NULL));
  1030. if (ret != NOTFOUND) {
  1031. *node = target_node;
  1032. }
  1033. return (ret);
  1034. }
  1035. /// \brief Simple find returning immutable node.
  1036. ///
  1037. /// Acts as described in the \ref find section, but returns immutable
  1038. /// node pointer.
  1039. template <typename CBARG>
  1040. Result find(const isc::dns::Name& name,
  1041. const DomainTreeNode<T>** node,
  1042. DomainTreeNodeChain<T>& node_path,
  1043. bool (*callback)(const DomainTreeNode<T>&, CBARG),
  1044. CBARG callback_arg) const
  1045. {
  1046. DomainTreeNode<T>* target_node = NULL;
  1047. const isc::dns::LabelSequence ls(name);
  1048. Result ret = find(ls, &target_node, node_path, callback,
  1049. callback_arg);
  1050. if (ret != NOTFOUND) {
  1051. *node = target_node;
  1052. }
  1053. return (ret);
  1054. }
  1055. /// \brief Find with callback and node chain
  1056. /// \anchor callback
  1057. ///
  1058. /// This version of \c find() is specifically designed for the backend
  1059. /// of the \c InMemoryZoneFinder class, and implements all necessary
  1060. /// features for that purpose. Other applications shouldn't need these
  1061. /// additional features, and should normally use the simpler versions.
  1062. ///
  1063. /// This version of \c find() calls the callback whenever traversing (on
  1064. /// the way from root down the tree) a marked node on the way down through
  1065. /// the domain namespace (see \c DomainTreeNode::FLAG_CALLBACK).
  1066. ///
  1067. /// Also, this version takes a \c LabelSequence object, not a \c Name
  1068. /// object to be as efficient as possible; operations on the former
  1069. /// needed for the search are generally much more efficient than those
  1070. /// for the latter. Since \c Name objects are more commonly used
  1071. /// in other parts of the implementation, other versions take a \c Name
  1072. /// and convert it to \c LabelSequence. This conversion is cheap,
  1073. /// while the other direction isn't, and since there would be cases
  1074. /// where an implementation primarily handles \c LabelSequence objects
  1075. /// as an efficient representation of names, it would make most sense
  1076. /// to provide the interface that takes \c LabelSequence.
  1077. ///
  1078. /// If you return true from the callback, the search is stopped and a
  1079. /// PARTIALMATCH is returned with the given node. Note that this node
  1080. /// doesn't really need to be the one with longest possible match.
  1081. ///
  1082. /// The callback is not called for the node which matches exactly
  1083. /// (EXACTMATCH is returned). This is typically the last node in the
  1084. /// traversal during a successful search.
  1085. ///
  1086. /// This callback mechanism was designed with zone cut (delegation)
  1087. /// processing in mind. The marked nodes would be the ones at delegation
  1088. /// points. It is not expected that any other applications would need
  1089. /// callbacks; they should use the versions of find without callbacks.
  1090. /// The callbacks are not general functors for the same reason - we don't
  1091. /// expect it to be needed.
  1092. ///
  1093. /// Another special feature of this version is the ability to record
  1094. /// more detailed information regarding the search result.
  1095. ///
  1096. /// This information will be returned via the \c node_path
  1097. /// parameter, which is an object of class \c DomainTreeNodeChain.
  1098. /// The passed parameter must be empty if the label sequence is
  1099. /// absolute. If the label sequence is not absolute, then find()
  1100. /// will begin from the top of the node chain.
  1101. ///
  1102. /// On success, the node sequence stored in \c node_path will contain all
  1103. /// the ancestor nodes from the found node towards the root.
  1104. /// For example, if we look for o.w.y.d.e.f in the example \ref diagram,
  1105. /// \c node_path will contain w.y and d.e.f; the \c top() node of the
  1106. /// chain will be o, w.y and d.e.f will be stored below it.
  1107. ///
  1108. /// This feature can be used to get the absolute name for a node; to
  1109. /// do so, we need to travel upside from the node toward the root,
  1110. /// concatenating all ancestor labels. A node chain can also be
  1111. /// used to find the next and previous nodes of a given node in the
  1112. /// entire DomainTree; the \c nextNode() and \c previousNode()
  1113. /// methods take a node chain as a parameter.
  1114. ///
  1115. /// \exception isc::BadValue node_path is not empty.
  1116. ///
  1117. /// \param target_labels_orig Target to be found
  1118. /// \param node On success (either \c EXACTMATCH or \c PARTIALMATCH)
  1119. /// it will store a pointer to the matching node
  1120. /// \param node_path Other search details will be stored (see the
  1121. /// description)
  1122. /// \param callback If non- \c NULL, a call back function to be called
  1123. /// at marked nodes (see the description).
  1124. /// \param callback_arg A caller supplied argument to be passed to
  1125. /// \c callback.
  1126. ///
  1127. /// \return As in the description, but in case of callback returning
  1128. /// \c true, it returns immediately with the current node.
  1129. template <typename CBARG>
  1130. Result find(const isc::dns::LabelSequence& target_labels_orig,
  1131. DomainTreeNode<T>** node,
  1132. DomainTreeNodeChain<T>& node_path,
  1133. bool (*callback)(const DomainTreeNode<T>&, CBARG),
  1134. CBARG callback_arg) const;
  1135. /// \brief Simple find returning immutable node.
  1136. ///
  1137. /// Acts as described in the \ref find section, but returns immutable
  1138. /// node pointer.
  1139. template <typename CBARG>
  1140. Result find(const isc::dns::LabelSequence& target_labels,
  1141. const DomainTreeNode<T>** node,
  1142. DomainTreeNodeChain<T>& node_path,
  1143. bool (*callback)(const DomainTreeNode<T>&, CBARG),
  1144. CBARG callback_arg) const
  1145. {
  1146. DomainTreeNode<T>* target_node = NULL;
  1147. Result ret = find(target_labels, &target_node, node_path,
  1148. callback, callback_arg);
  1149. if (ret != NOTFOUND) {
  1150. *node = target_node;
  1151. }
  1152. return (ret);
  1153. }
  1154. //@}
  1155. /// \brief return the next bigger node in DNSSEC order from a given node
  1156. /// chain.
  1157. ///
  1158. /// This method identifies the next bigger node of the node currently
  1159. /// referenced in \c node_path and returns it.
  1160. /// This method also updates the passed \c node_path so that it will store
  1161. /// the path for the returned next node.
  1162. /// It will be convenient when we want to iterate over the all nodes
  1163. /// of \c DomainTree; we can do this by calling this method repeatedly
  1164. /// starting from the root node.
  1165. ///
  1166. /// \note \c nextNode() will iterate over all the nodes in
  1167. /// DomainTree including empty nodes. If empty node isn't desired,
  1168. /// it's easy to add logic to check return node and keep invoking \c
  1169. /// nextNode() until the non-empty node is retrieved.
  1170. ///
  1171. /// \exception isc::BadValue node_path is empty.
  1172. ///
  1173. /// \param node_path A node chain that stores all the nodes along
  1174. /// the path from root to node.
  1175. ///
  1176. /// \return An \c DomainTreeNode that is next bigger than \c node;
  1177. /// if \c node is the largest, \c NULL will be returned.
  1178. const DomainTreeNode<T>*
  1179. nextNode(DomainTreeNodeChain<T>& node_path) const;
  1180. /// \brief return the next smaller node in DNSSEC order from a node
  1181. /// searched by DomainTree::find().
  1182. ///
  1183. /// This acts similarly to \c nextNode(), but it walks in the other
  1184. /// direction. But unlike \c nextNode(), this can start even if the
  1185. /// node requested by \c find() was not found. In that case, it will
  1186. /// identify the node that is previous to the queried name.
  1187. ///
  1188. /// \note \c previousNode() will iterate over all the nodes in DomainTree
  1189. /// including empty nodes. If empty node isn't desired, it's easy to add
  1190. /// logic to check return node and keep invoking \c previousNode() until the
  1191. /// non-empty node is retrieved.
  1192. ///
  1193. /// \exception isc::BadValue node_path is empty.
  1194. ///
  1195. /// \param node_path A node chain that stores all the nodes along the path
  1196. /// from root to node and the result of \c find(). This will get modified.
  1197. /// You should not use the node_path again except for repetitive calls
  1198. /// of this method.
  1199. ///
  1200. /// \return An \c DomainTreeNode that is next smaller than \c node;
  1201. /// if \c node is the smallest, \c NULL will be returned.
  1202. const DomainTreeNode<T>*
  1203. previousNode(DomainTreeNodeChain<T>& node_path) const;
  1204. /// \brief return the largest node in the tree of trees.
  1205. ///
  1206. /// \throw none
  1207. ///
  1208. /// \return A \c DomainTreeNode that is the largest node in the
  1209. /// tree. If there are no nodes, then \c NULL is returned.
  1210. const DomainTreeNode<T>* largestNode() const;
  1211. /// \brief Get the total number of nodes in the tree
  1212. ///
  1213. /// It includes nodes internally created as a result of adding a domain
  1214. /// name that is a subdomain of an existing node of the tree.
  1215. /// This function is mainly intended to be used for debugging.
  1216. uint32_t getNodeCount() const { return (node_count_); }
  1217. /// \name Debug function
  1218. //@{
  1219. /// \brief Print the nodes in the trees.
  1220. ///
  1221. /// \param os A \c std::ostream object to which the tree is printed.
  1222. /// \param depth A factor of the initial indentation. Each line
  1223. /// will begin with space character repeating <code>5 * depth</code>
  1224. /// times.
  1225. void dumpTree(std::ostream& os, unsigned int depth = 0) const;
  1226. /// \brief Print the nodes in the trees for processing with
  1227. /// Graphviz's dot.
  1228. ///
  1229. /// \param os A \c std::ostream object to which the tree is printed.
  1230. /// \param show_pointers Show node and parent pointers in the node
  1231. void dumpDot(std::ostream& os, bool show_pointers = false) const;
  1232. //@}
  1233. /// \name Modify functions
  1234. //@{
  1235. /// \brief Insert the domain name into the tree.
  1236. ///
  1237. /// It either finds an already existing node of the given name, or
  1238. /// inserts a new one if none exists yet. In any case, the \c
  1239. /// inserted_node parameter is set to point to that node. You can
  1240. /// fill data into it or modify it. So, if you don't know if a node
  1241. /// exists or not and you need to modify it, just call insert and
  1242. /// act by the result.
  1243. ///
  1244. /// Please note that the tree can add some empty nodes by itself, so
  1245. /// don't assume that if you didn't insert a node of that name it
  1246. /// doesn't exist.
  1247. ///
  1248. /// This method normally involves resource allocation. If it fails
  1249. /// the corresponding standard exception will be thrown.
  1250. ///
  1251. /// This method does not provide the strong exception guarantee in its
  1252. /// strict sense; if an exception is thrown in the middle of this
  1253. /// method, the internal structure may change. However, it should
  1254. /// still retain the same property as a mapping container before this
  1255. /// method is called. For example, the result of \c find() should be
  1256. /// the same. This method provides the weak exception guarantee in its
  1257. /// normal sense.
  1258. ///
  1259. /// \param mem_sgmt A \c MemorySegment object for allocating memory of
  1260. /// a new node to be inserted. Must be the same segment as that used
  1261. /// for creating the tree itself.
  1262. /// \param name The name to be inserted into the tree.
  1263. /// \param inserted_node This is an output parameter and is set to the
  1264. /// node.
  1265. ///
  1266. /// \return
  1267. /// - SUCCESS The node was added.
  1268. /// - ALREADYEXISTS There was already a node of that name, so it was not
  1269. /// added.
  1270. Result insert(util::MemorySegment& mem_sgmt, const isc::dns::Name& name,
  1271. DomainTreeNode<T>** inserted_node);
  1272. /// \brief Delete all tree nodes.
  1273. ///
  1274. /// \throw none.
  1275. ///
  1276. /// \param mem_sgmt The \c MemorySegment object used to insert the nodes
  1277. /// (which was also used for creating the tree due to the requirement of
  1278. /// \c inert()).
  1279. template <typename DataDeleter>
  1280. void deleteAllNodes(util::MemorySegment& mem_sgmt, DataDeleter deleter);
  1281. /// \brief Swaps two tree's contents.
  1282. ///
  1283. /// This and \c other trees must have been created with the same
  1284. /// memory segment (see the discussion in \c create()); otherwise the
  1285. /// behavior is undefined.
  1286. ///
  1287. /// This acts the same as many std::*.swap functions, exchanges the
  1288. /// contents. This doesn't throw anything.
  1289. void swap(DomainTree<T>& other) {
  1290. std::swap(root_, other.root_);
  1291. std::swap(node_count_, other.node_count_);
  1292. }
  1293. //@}
  1294. private:
  1295. /// \name DomainTree balance functions
  1296. //@{
  1297. void
  1298. insertRebalance(typename DomainTreeNode<T>::DomainTreeNodePtr* root,
  1299. DomainTreeNode<T>* node);
  1300. DomainTreeNode<T>*
  1301. rightRotate(typename DomainTreeNode<T>::DomainTreeNodePtr* root,
  1302. DomainTreeNode<T>* node);
  1303. DomainTreeNode<T>*
  1304. leftRotate(typename DomainTreeNode<T>::DomainTreeNodePtr* root,
  1305. DomainTreeNode<T>* node);
  1306. //@}
  1307. /// \name Helper functions
  1308. //@{
  1309. /// \brief delete tree whose root is equal to node
  1310. template <typename DataDeleter>
  1311. void deleteHelper(util::MemorySegment& mem_sgmt,
  1312. DomainTreeNode<T> *node,
  1313. const DataDeleter& deleter);
  1314. /// \brief Print the information of given DomainTreeNode.
  1315. void dumpTreeHelper(std::ostream& os, const DomainTreeNode<T>* node,
  1316. unsigned int depth) const;
  1317. /// \brief Print the information of given DomainTreeNode for dot.
  1318. int dumpDotHelper(std::ostream& os, const DomainTreeNode<T>* node,
  1319. int* nodecount, bool show_pointers) const;
  1320. /// \brief Indentation helper function for dumpTree
  1321. static void indent(std::ostream& os, unsigned int depth);
  1322. /// Split one node into two nodes for "prefix" and "suffix" parts of
  1323. /// the labels of the original node, respectively. The given node
  1324. /// will hold the prefix, while a newly created node will hold the prefix.
  1325. /// Note that the original node still represents the same domain name in
  1326. /// the entire tree. This ensures that a pointer to a node keeps its
  1327. /// semantics even if the tree structure is changed (as long as the node
  1328. /// itself remains valid).
  1329. void nodeFission(util::MemorySegment& mem_sgmt, DomainTreeNode<T>& node,
  1330. const isc::dns::LabelSequence& new_prefix,
  1331. const isc::dns::LabelSequence& new_suffix);
  1332. //@}
  1333. typename DomainTreeNode<T>::DomainTreeNodePtr root_;
  1334. /// the node count of current tree.
  1335. ///
  1336. /// Note: uint32_t may look awkward, but we intentionally choose it so
  1337. /// that needsReturnEmptyNode_ below won't make cause extra padding
  1338. /// in 64-bit machines (and we can minimize the total size of this class).
  1339. /// 2^32 - 1 should be a reasonable max of possible number of nodes.
  1340. uint32_t node_count_;
  1341. /// search policy for domaintree
  1342. const bool needsReturnEmptyNode_;
  1343. };
  1344. template <typename T>
  1345. DomainTree<T>::DomainTree(bool returnEmptyNode) :
  1346. root_(NULL),
  1347. node_count_(0),
  1348. needsReturnEmptyNode_(returnEmptyNode)
  1349. {
  1350. }
  1351. template <typename T>
  1352. DomainTree<T>::~DomainTree() {
  1353. assert(node_count_ == 0);
  1354. }
  1355. template <typename T>
  1356. template <typename DataDeleter>
  1357. void
  1358. DomainTree<T>::deleteHelper(util::MemorySegment& mem_sgmt,
  1359. DomainTreeNode<T>* root,
  1360. const DataDeleter& deleter)
  1361. {
  1362. while (root != NULL) {
  1363. // If there is a left, right or down node, walk into it and
  1364. // iterate.
  1365. if (root->getLeft() != NULL) {
  1366. DomainTreeNode<T>* node = root;
  1367. root = root->getLeft();
  1368. node->left_ = NULL;
  1369. } else if (root->getRight() != NULL) {
  1370. DomainTreeNode<T>* node = root;
  1371. root = root->getRight();
  1372. node->right_ = NULL;
  1373. } else if (root->getDown() != NULL) {
  1374. DomainTreeNode<T>* node = root;
  1375. root = root->getDown();
  1376. node->down_ = NULL;
  1377. } else {
  1378. // There are no left, right or down nodes, so we can
  1379. // free this one and go back to its parent.
  1380. DomainTreeNode<T>* node = root;
  1381. root = root->getParent();
  1382. deleter(node->data_.get());
  1383. DomainTreeNode<T>::destroy(mem_sgmt, node);
  1384. --node_count_;
  1385. }
  1386. }
  1387. }
  1388. template <typename T>
  1389. template <typename CBARG>
  1390. typename DomainTree<T>::Result
  1391. DomainTree<T>::find(const isc::dns::LabelSequence& target_labels_orig,
  1392. DomainTreeNode<T>** target,
  1393. DomainTreeNodeChain<T>& node_path,
  1394. bool (*callback)(const DomainTreeNode<T>&, CBARG),
  1395. CBARG callback_arg) const
  1396. {
  1397. if (node_path.isEmpty() ^ target_labels_orig.isAbsolute()) {
  1398. isc_throw(isc::BadValue,
  1399. "DomainTree::find() is given mismatched node chain"
  1400. " and label sequence");
  1401. }
  1402. DomainTreeNode<T>* node;
  1403. if (!node_path.isEmpty()) {
  1404. // Get the top node in the node chain
  1405. node = const_cast<DomainTreeNode<T>*>(node_path.top());
  1406. // Start searching from its down pointer
  1407. node = node->getDown();
  1408. } else {
  1409. node = root_.get();
  1410. }
  1411. Result ret = NOTFOUND;
  1412. dns::LabelSequence target_labels(target_labels_orig);
  1413. while (node != NULL) {
  1414. node_path.last_compared_ = node;
  1415. node_path.last_comparison_ = target_labels.compare(node->getLabels());
  1416. const isc::dns::NameComparisonResult::NameRelation relation =
  1417. node_path.last_comparison_.getRelation();
  1418. if (relation == isc::dns::NameComparisonResult::EQUAL) {
  1419. if (needsReturnEmptyNode_ || !node->isEmpty()) {
  1420. node_path.push(node);
  1421. *target = node;
  1422. ret = EXACTMATCH;
  1423. }
  1424. break;
  1425. } else if (relation == isc::dns::NameComparisonResult::NONE) {
  1426. // If the two labels have no hierarchical relationship in terms
  1427. // of matching, we should continue the binary search.
  1428. node = (node_path.last_comparison_.getOrder() < 0) ?
  1429. node->getLeft() : node->getRight();
  1430. } else {
  1431. if (relation == isc::dns::NameComparisonResult::SUBDOMAIN) {
  1432. if (needsReturnEmptyNode_ || !node->isEmpty()) {
  1433. ret = PARTIALMATCH;
  1434. *target = node;
  1435. if (callback != NULL &&
  1436. node->getFlag(DomainTreeNode<T>::FLAG_CALLBACK)) {
  1437. if ((callback)(*node, callback_arg)) {
  1438. break;
  1439. }
  1440. }
  1441. }
  1442. node_path.push(node);
  1443. target_labels.stripRight(
  1444. node_path.last_comparison_.getCommonLabels());
  1445. node = node->getDown();
  1446. } else {
  1447. break;
  1448. }
  1449. }
  1450. }
  1451. return (ret);
  1452. }
  1453. template <typename T>
  1454. const DomainTreeNode<T>*
  1455. DomainTree<T>::nextNode(DomainTreeNodeChain<T>& node_path) const {
  1456. if (node_path.isEmpty()) {
  1457. isc_throw(isc::BadValue,
  1458. "DomainTree::nextNode is given an empty chain");
  1459. }
  1460. const DomainTreeNode<T>* node = node_path.top();
  1461. // if node has sub domain, the next domain is the smallest
  1462. // domain in sub domain tree
  1463. const DomainTreeNode<T>* down = node->getDown();
  1464. if (down != NULL) {
  1465. const DomainTreeNode<T>* left_most = down;
  1466. while (left_most->getLeft() != NULL) {
  1467. left_most = left_most->getLeft();
  1468. }
  1469. node_path.push(left_most);
  1470. return (left_most);
  1471. }
  1472. // try to find a successor.
  1473. // if no successor found move to up level, the next successor
  1474. // is the successor of up node in the up level tree, if
  1475. // up node doesn't have successor we gonna keep moving to up
  1476. // level
  1477. while (!node_path.isEmpty()) {
  1478. const DomainTreeNode<T>* up_node_successor =
  1479. node_path.top()->successor();
  1480. node_path.pop();
  1481. if (up_node_successor != NULL) {
  1482. node_path.push(up_node_successor);
  1483. return (up_node_successor);
  1484. }
  1485. }
  1486. return (NULL);
  1487. }
  1488. template <typename T>
  1489. const DomainTreeNode<T>*
  1490. DomainTree<T>::previousNode(DomainTreeNodeChain<T>& node_path) const {
  1491. if (getNodeCount() == 0) {
  1492. // Special case for empty trees. It would look every time like
  1493. // we didn't search, because the last compared is empty. This is
  1494. // a slight hack and not perfect, but this is better than throwing
  1495. // on empty tree. And we probably won't meet an empty tree in practice
  1496. // anyway.
  1497. return (NULL);
  1498. }
  1499. if (node_path.last_compared_ == NULL) {
  1500. isc_throw(isc::BadValue,
  1501. "DomainTree::previousNode() called before find()");
  1502. }
  1503. // If the relation isn't EQUAL, it means the find was called previously
  1504. // and didn't find the exact node. Therefore we need to locate the place
  1505. // to start iterating the chain of domains.
  1506. //
  1507. // The logic here is not too complex, we just need to take care to handle
  1508. // all the cases and decide where to go from there.
  1509. switch (node_path.last_comparison_.getRelation()) {
  1510. case dns::NameComparisonResult::COMMONANCESTOR:
  1511. case dns::NameComparisonResult::NONE:
  1512. // We compared with a leaf in the tree and wanted to go to one of
  1513. // the children. But the child was not there. It now depends on the
  1514. // direction in which we wanted to go.
  1515. if (node_path.last_comparison_.getOrder() < 0) {
  1516. // We wanted to go left. So the one we compared with is
  1517. // the one higher than we wanted. If we just put it into
  1518. // the node_path, then the following algorithm below will find
  1519. // the smaller one.
  1520. //
  1521. // This is exactly the same as with superdomain below.
  1522. // Therefore, we just fall through to the next case.
  1523. } else {
  1524. // We wanted to go right. That means we want to output the
  1525. // one which is the largest in the tree defined by the
  1526. // compared one (it is either the compared one, or some
  1527. // subdomain of it). There probably is not an easy trick
  1528. // for this, so we just find the correct place.
  1529. const DomainTreeNode<T>* current(node_path.last_compared_);
  1530. while (current != NULL) {
  1531. node_path.push(current);
  1532. // Go a level down and as much right there as possible
  1533. current = current->getDown();
  1534. if (current != NULL) {
  1535. const DomainTreeNode<T>* right;
  1536. while ((right = current->getRight()) != NULL) {
  1537. current = right;
  1538. }
  1539. }
  1540. }
  1541. // Now, the one on top of the path is the one we want. We
  1542. // return it now and leave it there, so we can search for
  1543. // previous of it the next time we'are called.
  1544. node_path.last_comparison_ =
  1545. dns::NameComparisonResult(0, 0,
  1546. dns::NameComparisonResult::EQUAL);
  1547. return (node_path.top());
  1548. }
  1549. // No break; here - we want to fall through. See above.
  1550. case dns::NameComparisonResult::SUPERDOMAIN:
  1551. // This is the case there's a "compressed" node and we looked for
  1552. // only part of it. The node itself is larger than we wanted, but
  1553. // if we put it to the node_path and then go one step left from it,
  1554. // we get the correct result.
  1555. node_path.push(node_path.last_compared_);
  1556. // Correct the comparison result, so we won't trigger this case
  1557. // next time previousNode is called. We already located the correct
  1558. // place to start. The value is partly nonsense, but that doesn't
  1559. // matter any more.
  1560. node_path.last_comparison_ =
  1561. dns::NameComparisonResult(0, 0,
  1562. dns::NameComparisonResult::EQUAL);
  1563. break;
  1564. case dns::NameComparisonResult::SUBDOMAIN:
  1565. // A subdomain means we returned the one above the searched one
  1566. // already and it is on top of the stack. This is was smaller
  1567. // than the one already, but we want to return yet smaller one.
  1568. // So we act as if it was EQUAL.
  1569. break;
  1570. case dns::NameComparisonResult::EQUAL:
  1571. // The find gave us an exact match or the previousNode was called
  1572. // already, which located the exact node. The rest of the function
  1573. // goes one domain left and returns it for us.
  1574. break;
  1575. }
  1576. // So, the node_path now contains the path to a node we want previous for.
  1577. // We just need to go one step left.
  1578. if (node_path.isEmpty()) {
  1579. // We got past the first one. So, we're returning NULL from
  1580. // now on.
  1581. return (NULL);
  1582. }
  1583. const DomainTreeNode<T>* node(node_path.top());
  1584. // Try going left in this tree
  1585. node = node->predecessor();
  1586. if (node == NULL) {
  1587. // We are the smallest ones in this tree. We go one level
  1588. // up. That one is the smaller one than us.
  1589. node_path.pop();
  1590. if (node_path.isEmpty()) {
  1591. // We're past the first one
  1592. return (NULL);
  1593. } else {
  1594. return (node_path.top());
  1595. }
  1596. }
  1597. // Exchange the node at the top of the path, as we move horizontaly
  1598. // through the domain tree
  1599. node_path.pop();
  1600. node_path.push(node);
  1601. // Try going as deep as possible, keeping on the right side of the trees
  1602. const DomainTreeNode<T>* down;
  1603. while ((down = node->getDown()) != NULL) {
  1604. // Move to the tree below
  1605. node = down;
  1606. if (node != NULL) {
  1607. // And get as much to the right of the tree as possible
  1608. const DomainTreeNode<T>* right;
  1609. while ((right = node->getRight()) != NULL) {
  1610. node = right;
  1611. }
  1612. }
  1613. // Now, we found the right-most node in the sub-tree, we need to
  1614. // include it in the path
  1615. node_path.push(node);
  1616. }
  1617. // Now, if the current node has no down_ pointer any more, it's the
  1618. // correct one.
  1619. return (node);
  1620. }
  1621. template <typename T>
  1622. const DomainTreeNode<T>*
  1623. DomainTree<T>::largestNode() const {
  1624. const DomainTreeNode<T>* node = root_.get();
  1625. while (node != NULL) {
  1626. // We go right first, then down.
  1627. if (node->getRight() != NULL) {
  1628. node = node->getRight();
  1629. } else if (node->getDown() != NULL) {
  1630. node = node->getDown();
  1631. } else {
  1632. break;
  1633. }
  1634. }
  1635. return (node);
  1636. }
  1637. template <typename T>
  1638. typename DomainTree<T>::Result
  1639. DomainTree<T>::insert(util::MemorySegment& mem_sgmt,
  1640. const isc::dns::Name& target_name,
  1641. DomainTreeNode<T>** new_node)
  1642. {
  1643. DomainTreeNode<T>* parent = NULL;
  1644. DomainTreeNode<T>* current = root_.get();
  1645. DomainTreeNode<T>* up_node = NULL;
  1646. isc::dns::LabelSequence target_labels(target_name);
  1647. int order = -1;
  1648. // For possible LabelSequence serialization we always store labels data
  1649. // in the separate local buffer.
  1650. uint8_t labels_buf[dns::LabelSequence::MAX_SERIALIZED_LENGTH];
  1651. while (current != NULL) {
  1652. const dns::LabelSequence current_labels(
  1653. dns::LabelSequence(current->getLabels(), labels_buf));
  1654. const isc::dns::NameComparisonResult compare_result =
  1655. target_labels.compare(current_labels);
  1656. const isc::dns::NameComparisonResult::NameRelation relation =
  1657. compare_result.getRelation();
  1658. if (relation == isc::dns::NameComparisonResult::EQUAL) {
  1659. if (new_node != NULL) {
  1660. *new_node = current;
  1661. }
  1662. return (ALREADYEXISTS);
  1663. } else if (relation == isc::dns::NameComparisonResult::NONE) {
  1664. parent = current;
  1665. order = compare_result.getOrder();
  1666. current = order < 0 ? current->getLeft() : current->getRight();
  1667. } else if (relation == isc::dns::NameComparisonResult::SUBDOMAIN) {
  1668. // insert sub domain to sub tree
  1669. parent = NULL;
  1670. up_node = current;
  1671. target_labels.stripRight(compare_result.getCommonLabels());
  1672. current = current->getDown();
  1673. } else {
  1674. // The number of labels in common is fewer than the number of
  1675. // labels at the current node, so the current node must be
  1676. // adjusted to have just the common suffix, and a down pointer
  1677. // made to a new tree.
  1678. dns::LabelSequence common_ancestor = target_labels;
  1679. common_ancestor.stripLeft(target_labels.getLabelCount() -
  1680. compare_result.getCommonLabels());
  1681. dns::LabelSequence new_prefix = current_labels;
  1682. new_prefix.stripRight(compare_result.getCommonLabels());
  1683. nodeFission(mem_sgmt, *current, new_prefix, common_ancestor);
  1684. current = current->getParent();
  1685. }
  1686. }
  1687. typename DomainTreeNode<T>::DomainTreeNodePtr* current_root =
  1688. (up_node != NULL) ? &(up_node->down_) : &root_;
  1689. // Once a new node is created, no exception will be thrown until the end
  1690. // of the function, so we can simply create and hold a new node pointer.
  1691. DomainTreeNode<T>* node = DomainTreeNode<T>::create(mem_sgmt,
  1692. target_labels);
  1693. node->parent_ = parent;
  1694. if (parent == NULL) {
  1695. *current_root = node;
  1696. // node is the new root of sub tree, so its init color is BLACK
  1697. node->setColor(DomainTreeNode<T>::BLACK);
  1698. node->setSubTreeRoot(true);
  1699. node->parent_ = up_node;
  1700. } else if (order < 0) {
  1701. node->setSubTreeRoot(false);
  1702. parent->left_ = node;
  1703. } else {
  1704. node->setSubTreeRoot(false);
  1705. parent->right_ = node;
  1706. }
  1707. insertRebalance(current_root, node);
  1708. if (new_node != NULL) {
  1709. *new_node = node;
  1710. }
  1711. ++node_count_;
  1712. return (SUCCESS);
  1713. }
  1714. template <typename T>
  1715. template <typename DataDeleter>
  1716. void
  1717. DomainTree<T>::deleteAllNodes(util::MemorySegment& mem_sgmt,
  1718. DataDeleter deleter)
  1719. {
  1720. deleteHelper(mem_sgmt, root_.get(), deleter);
  1721. root_ = NULL;
  1722. }
  1723. template <typename T>
  1724. void
  1725. DomainTree<T>::nodeFission(util::MemorySegment& mem_sgmt,
  1726. DomainTreeNode<T>& node,
  1727. const isc::dns::LabelSequence& new_prefix,
  1728. const isc::dns::LabelSequence& new_suffix)
  1729. {
  1730. // Create and reset the labels.
  1731. // Once a new node is created, no exception will be thrown until
  1732. // the end of the function, and it will keep consistent behavior
  1733. // (i.e., a weak form of strong exception guarantee) even if code
  1734. // after the call to this function throws an exception.
  1735. DomainTreeNode<T>* up_node = DomainTreeNode<T>::create(mem_sgmt,
  1736. new_suffix);
  1737. node.resetLabels(new_prefix);
  1738. up_node->parent_ = node.getParent();
  1739. if (node.getParent() != NULL) {
  1740. if (node.getParent()->getLeft() == &node) {
  1741. node.getParent()->left_ = up_node;
  1742. } else if (node.getParent()->getRight() == &node) {
  1743. node.getParent()->right_ = up_node;
  1744. } else {
  1745. node.getParent()->down_ = up_node;
  1746. }
  1747. } else {
  1748. this->root_ = up_node;
  1749. }
  1750. up_node->down_ = &node;
  1751. node.parent_ = up_node;
  1752. // inherit the left/right pointers from the original node, and set
  1753. // the original node's left/right pointers to NULL.
  1754. up_node->left_ = node.getLeft();
  1755. if (node.getLeft() != NULL) {
  1756. node.getLeft()->parent_ = up_node;
  1757. }
  1758. up_node->right_ = node.getRight();
  1759. if (node.getRight() != NULL) {
  1760. node.getRight()->parent_ = up_node;
  1761. }
  1762. node.left_ = NULL;
  1763. node.right_ = NULL;
  1764. // set color of both nodes; the initial subtree node color is BLACK
  1765. up_node->setColor(node.getColor());
  1766. node.setColor(DomainTreeNode<T>::BLACK);
  1767. // set the subtree root flag of both nodes
  1768. up_node->setSubTreeRoot(node.isSubTreeRoot());
  1769. node.setSubTreeRoot(true);
  1770. ++node_count_;
  1771. }
  1772. template <typename T>
  1773. void
  1774. DomainTree<T>::insertRebalance
  1775. (typename DomainTreeNode<T>::DomainTreeNodePtr* root,
  1776. DomainTreeNode<T>* node)
  1777. {
  1778. DomainTreeNode<T>* uncle;
  1779. DomainTreeNode<T>* parent;
  1780. while (node != (*root).get() &&
  1781. ((parent = node->getParent())->getColor()) ==
  1782. DomainTreeNode<T>::RED) {
  1783. // Here, node->parent_ is not NULL and it is also red, so
  1784. // node->parent_->parent_ is also not NULL.
  1785. if (parent == parent->getParent()->getLeft()) {
  1786. uncle = parent->getParent()->getRight();
  1787. if (uncle != NULL && uncle->getColor() ==
  1788. DomainTreeNode<T>::RED) {
  1789. parent->setColor(DomainTreeNode<T>::BLACK);
  1790. uncle->setColor(DomainTreeNode<T>::BLACK);
  1791. parent->getParent()->setColor(DomainTreeNode<T>::RED);
  1792. node = parent->getParent();
  1793. } else {
  1794. if (node == parent->getRight()) {
  1795. node = parent;
  1796. leftRotate(root, node);
  1797. parent = node->getParent();
  1798. }
  1799. parent->setColor(DomainTreeNode<T>::BLACK);
  1800. parent->getParent()->setColor(DomainTreeNode<T>::RED);
  1801. rightRotate(root, parent->getParent());
  1802. }
  1803. } else {
  1804. uncle = parent->getParent()->getLeft();
  1805. if (uncle != NULL && uncle->getColor() ==
  1806. DomainTreeNode<T>::RED) {
  1807. parent->setColor(DomainTreeNode<T>::BLACK);
  1808. uncle->setColor(DomainTreeNode<T>::BLACK);
  1809. parent->getParent()->setColor(DomainTreeNode<T>::RED);
  1810. node = parent->getParent();
  1811. } else {
  1812. if (node == parent->getLeft()) {
  1813. node = parent;
  1814. rightRotate(root, node);
  1815. parent = node->getParent();
  1816. }
  1817. parent->setColor(DomainTreeNode<T>::BLACK);
  1818. parent->getParent()->setColor(DomainTreeNode<T>::RED);
  1819. leftRotate(root, parent->getParent());
  1820. }
  1821. }
  1822. }
  1823. (*root)->setColor(DomainTreeNode<T>::BLACK);
  1824. }
  1825. template <typename T>
  1826. DomainTreeNode<T>*
  1827. DomainTree<T>::leftRotate
  1828. (typename DomainTreeNode<T>::DomainTreeNodePtr* root,
  1829. DomainTreeNode<T>* node)
  1830. {
  1831. DomainTreeNode<T>* const right = node->getRight();
  1832. DomainTreeNode<T>* const rleft = right->getLeft();
  1833. node->right_ = rleft;
  1834. if (rleft != NULL) {
  1835. rleft->parent_ = node;
  1836. }
  1837. DomainTreeNode<T>* const parent = node->getParent();
  1838. right->parent_ = parent;
  1839. if (!node->isSubTreeRoot()) {
  1840. right->setSubTreeRoot(false);
  1841. if (node == parent->getLeft()) {
  1842. parent->left_ = right;
  1843. } else {
  1844. parent->right_ = right;
  1845. }
  1846. } else {
  1847. right->setSubTreeRoot(true);
  1848. *root = right;
  1849. }
  1850. right->left_ = node;
  1851. node->parent_ = right;
  1852. node->setSubTreeRoot(false);
  1853. return (node);
  1854. }
  1855. template <typename T>
  1856. DomainTreeNode<T>*
  1857. DomainTree<T>::rightRotate
  1858. (typename DomainTreeNode<T>::DomainTreeNodePtr* root,
  1859. DomainTreeNode<T>* node)
  1860. {
  1861. DomainTreeNode<T>* const left = node->getLeft();
  1862. DomainTreeNode<T>* const lright = left->getRight();
  1863. node->left_ = lright;
  1864. if (lright != NULL) {
  1865. lright->parent_ = node;
  1866. }
  1867. DomainTreeNode<T>* const parent = node->getParent();
  1868. left->parent_ = parent;
  1869. if (!node->isSubTreeRoot()) {
  1870. left->setSubTreeRoot(false);
  1871. if (node == parent->getRight()) {
  1872. parent->right_ = left;
  1873. } else {
  1874. parent->left_ = left;
  1875. }
  1876. } else {
  1877. left->setSubTreeRoot(true);
  1878. *root = left;
  1879. }
  1880. left->right_ = node;
  1881. node->parent_ = left;
  1882. node->setSubTreeRoot(false);
  1883. return (node);
  1884. }
  1885. template <typename T>
  1886. void
  1887. DomainTree<T>::dumpTree(std::ostream& os, unsigned int depth) const {
  1888. indent(os, depth);
  1889. os << "tree has " << node_count_ << " node(s)\n";
  1890. dumpTreeHelper(os, root_.get(), depth);
  1891. }
  1892. template <typename T>
  1893. void
  1894. DomainTree<T>::dumpTreeHelper(std::ostream& os,
  1895. const DomainTreeNode<T>* node,
  1896. unsigned int depth) const
  1897. {
  1898. if (node == NULL) {
  1899. indent(os, depth);
  1900. os << "NULL\n";
  1901. return;
  1902. }
  1903. indent(os, depth);
  1904. os << node->getLabels() << " ("
  1905. << ((node->getColor() == DomainTreeNode<T>::BLACK) ? "black" : "red")
  1906. << ")";
  1907. if (node->isEmpty()) {
  1908. os << " [invisible]";
  1909. }
  1910. if (node->isSubTreeRoot()) {
  1911. os << " [subtreeroot]";
  1912. }
  1913. os << "\n";
  1914. const DomainTreeNode<T>* down = node->getDown();
  1915. if (down != NULL) {
  1916. indent(os, depth + 1);
  1917. os << "begin down from " << node->getLabels() << "\n";
  1918. dumpTreeHelper(os, down, depth + 1);
  1919. indent(os, depth + 1);
  1920. os << "end down from " << node->getLabels() << "\n";
  1921. }
  1922. dumpTreeHelper(os, node->getLeft(), depth + 1);
  1923. dumpTreeHelper(os, node->getRight(), depth + 1);
  1924. }
  1925. template <typename T>
  1926. void
  1927. DomainTree<T>::indent(std::ostream& os, unsigned int depth) {
  1928. static const unsigned int INDENT_FOR_EACH_DEPTH = 5;
  1929. os << std::string(depth * INDENT_FOR_EACH_DEPTH, ' ');
  1930. }
  1931. template <typename T>
  1932. void
  1933. DomainTree<T>::dumpDot(std::ostream& os, bool show_pointers) const {
  1934. int nodecount = 0;
  1935. os << "digraph g {\n";
  1936. os << "node [shape = record,height=.1];\n";
  1937. dumpDotHelper(os, root_.get(), &nodecount, show_pointers);
  1938. os << "}\n";
  1939. }
  1940. template <typename T>
  1941. int
  1942. DomainTree<T>::dumpDotHelper(std::ostream& os,
  1943. const DomainTreeNode<T>* node,
  1944. int* nodecount, bool show_pointers) const
  1945. {
  1946. if (node == NULL) {
  1947. return 0;
  1948. }
  1949. int l = dumpDotHelper(os, node->getLeft(), nodecount, show_pointers);
  1950. int r = dumpDotHelper(os, node->getRight(), nodecount, show_pointers);
  1951. int d = dumpDotHelper(os, node->getDown(), nodecount, show_pointers);
  1952. *nodecount += 1;
  1953. os << "node" << *nodecount <<
  1954. "[label = \"<f0> |<f1> " << node->getLabels() <<
  1955. "|<f2>";
  1956. if (show_pointers) {
  1957. os << "|<f3> n=" << node << "|<f4> p=" << node->getParent();
  1958. }
  1959. os << "\"] [";
  1960. if (node->getColor() == DomainTreeNode<T>::RED) {
  1961. os << "color=red";
  1962. } else {
  1963. os << "color=black";
  1964. }
  1965. if (node->isSubTreeRoot()) {
  1966. os << ",penwidth=3";
  1967. }
  1968. if (node->isEmpty()) {
  1969. os << ",style=filled,fillcolor=lightgrey";
  1970. }
  1971. os << "];\n";
  1972. if (node->getLeft() != NULL) {
  1973. os << "\"node" << *nodecount << "\":f0 -> \"node" << l << "\":f1;\n";
  1974. }
  1975. if (node->getDown() != NULL) {
  1976. os << "\"node" << *nodecount << "\":f1 -> \"node" << d <<
  1977. "\":f1 [penwidth=5];\n";
  1978. }
  1979. if (node->getRight() != NULL) {
  1980. os << "\"node" << *nodecount << "\":f2 -> \"node" << r << "\":f1;\n";
  1981. }
  1982. return (*nodecount);
  1983. }
  1984. } // namespace memory
  1985. } // namespace datasrc
  1986. } // namespace isc
  1987. #endif // _DOMAINTREE_H
  1988. // Local Variables:
  1989. // mode: c++
  1990. // End: