domaintree.h 82 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187
  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. // If the current node already has absolute labels, just return it.
  524. // This should normally be the case for the origin node if this tree
  525. // is used to represent a single DNS zone.
  526. const isc::dns::LabelSequence cur_labels(getLabels());
  527. if (cur_labels.isAbsolute()) {
  528. return (cur_labels);
  529. }
  530. // Otherwise, build the absolute sequence traversing the tree of tree
  531. // toward the top root.
  532. isc::dns::LabelSequence result(cur_labels, buf);
  533. const DomainTreeNode<T>* upper = getUpperNode();
  534. while (upper != NULL) {
  535. result.extend(upper->getLabels(), buf);
  536. upper = upper->getUpperNode();
  537. }
  538. return (result);
  539. }
  540. template <typename T>
  541. const DomainTreeNode<T>*
  542. DomainTreeNode<T>::abstractSuccessor(
  543. typename DomainTreeNode<T>::DomainTreeNodePtr DomainTreeNode<T>::*left,
  544. typename DomainTreeNode<T>::DomainTreeNodePtr DomainTreeNode<T>::*right)
  545. const
  546. {
  547. // This function is written as a successor. It becomes predecessor if
  548. // the left and right pointers are swapped. So in case of predecessor,
  549. // the left pointer points to right and vice versa. Don't get confused
  550. // by the idea, just imagine the pointers look into a mirror.
  551. const DomainTreeNode<T>* current = this;
  552. // If it has right node, the successor is the left-most node of the right
  553. // subtree.
  554. if ((current->*right).get() != NULL) {
  555. current = (current->*right).get();
  556. const DomainTreeNode<T>* left_n;
  557. while ((left_n = (current->*left).get()) != NULL) {
  558. current = left_n;
  559. }
  560. return (current);
  561. }
  562. // Otherwise go up until we find the first left branch on our path to
  563. // root. If found, the parent of the branch is the successor.
  564. // Otherwise, we return the null node
  565. const DomainTreeNode<T>* parent = current->getParent();
  566. while ((!current->isSubTreeRoot()) &&
  567. (current == (parent->*right).get())) {
  568. current = parent;
  569. parent = parent->getParent();
  570. }
  571. if (!current->isSubTreeRoot()) {
  572. return (parent);
  573. } else {
  574. return (NULL);
  575. }
  576. }
  577. template <typename T>
  578. const DomainTreeNode<T>*
  579. DomainTreeNode<T>::successor() const {
  580. return (abstractSuccessor(&DomainTreeNode<T>::left_,
  581. &DomainTreeNode<T>::right_));
  582. }
  583. template <typename T>
  584. const DomainTreeNode<T>*
  585. DomainTreeNode<T>::predecessor() const {
  586. // Swap the left and right pointers for the abstractSuccessor
  587. return (abstractSuccessor(&DomainTreeNode<T>::right_,
  588. &DomainTreeNode<T>::left_));
  589. }
  590. /// \brief DomainTreeNodeChain stores detailed information of \c
  591. /// DomainTree::find() result.
  592. ///
  593. /// - The \c DomainTreeNode that was last compared with the search name, and
  594. /// the comparison result at that point in the form of
  595. /// \c isc::dns::NameComparisonResult.
  596. /// - A sequence of nodes that forms a path to the found node.
  597. ///
  598. /// The comparison result can be used to handle some rare cases such as
  599. /// empty node processing.
  600. /// The node sequence keeps track of the nodes to reach any given node from
  601. /// the root of DomainTree.
  602. ///
  603. /// Currently, DomainTreeNode does not have "up" pointers in them (i.e.,
  604. /// back pointers from the root of one level of tree of trees to the
  605. /// node in the parent tree whose down pointer points to that root node)
  606. /// for memory usage reasons, so there is no other way to find the path
  607. /// back to the root from any given DomainTreeNode.
  608. ///
  609. /// \note This design may change in future versions. In particular, it's
  610. /// quite likely we want to have that pointer if we want to optimize name
  611. /// compression by exploiting the structure of the zone. If and when that
  612. /// happens we should also revisit the need for the chaining.
  613. /// Also, the class name may not be appropriate now that it contains other
  614. /// information than a node "chain", and the chain itself may even be
  615. /// deprecated. Something like "DomainTreeFindContext" may be a better name.
  616. /// This point should be revisited later.
  617. ///
  618. /// DomainTreeNodeChain is constructed and manipulated only inside the
  619. /// \c DomainTree class.
  620. /// \c DomainTree uses it as an inner data structure to iterate over the whole
  621. /// DomainTree.
  622. /// This is the reason why manipulation methods such as \c push() and \c pop()
  623. /// are private (and not shown in the doxygen document).
  624. template <typename T>
  625. class DomainTreeNodeChain {
  626. /// DomainTreeNodeChain is initialized by DomainTree, only DomainTree has
  627. /// knowledge to manipulate it.
  628. friend class DomainTree<T>;
  629. public:
  630. /// \name Constructors and Assignment Operator.
  631. ///
  632. /// \note The copy constructor and the assignment operator are
  633. /// intentionally defined as private, making this class non copyable.
  634. /// This may have to be changed in a future version with newer need.
  635. /// For now we explicitly disable copy to avoid accidental copy happens
  636. /// unintentionally.
  637. //{@
  638. /// The default constructor.
  639. ///
  640. /// \exception None
  641. DomainTreeNodeChain() : level_count_(0), last_compared_(NULL),
  642. // XXX: meaningless initial values:
  643. last_comparison_(0, 0,
  644. isc::dns::NameComparisonResult::EQUAL)
  645. {}
  646. /// \brief Copy constructor.
  647. ///
  648. /// \exception None
  649. DomainTreeNodeChain(const DomainTreeNodeChain<T>& other) :
  650. level_count_(other.level_count_),
  651. last_compared_(other.last_compared_),
  652. last_comparison_(other.last_comparison_)
  653. {
  654. for (size_t i = 0; i < level_count_; i++) {
  655. nodes_[i] = other.nodes_[i];
  656. }
  657. }
  658. private:
  659. DomainTreeNodeChain<T>& operator=(const DomainTreeNodeChain<T>&);
  660. //@}
  661. public:
  662. /// Clear the state of the chain.
  663. ///
  664. /// This method re-initializes the internal state of the chain so that
  665. /// it can be reused for subsequent operations.
  666. ///
  667. /// \exception None
  668. void clear() {
  669. level_count_ = 0;
  670. last_compared_ = NULL;
  671. }
  672. /// Return the \c DomainTreeNode that was last compared in \c
  673. /// DomainTree::find().
  674. ///
  675. /// If this chain has been passed to \c DomainTree::find() and there
  676. /// has been name comparison against the search name, the last
  677. /// compared \c DomainTreeNode is recorded within the chain. This
  678. /// method returns that node.
  679. ///
  680. /// If \c DomainTree::find() hasn't been called with this chain or
  681. /// name comparison hasn't taken place (which is possible if the
  682. /// tree is empty), this method returns \c NULL.
  683. ///
  684. /// \exception None
  685. const DomainTreeNode<T>* getLastComparedNode() const {
  686. return (last_compared_);
  687. }
  688. /// Return the result of last name comparison in \c DomainTree::find().
  689. ///
  690. /// Like \c getLastComparedNode(), \c DomainTree::find() records the result
  691. /// of the last name comparison in the chain. This method returns the
  692. /// result.
  693. /// The return value of this method is only meaningful when comparison
  694. /// has taken place, i.e, when \c getLastComparedNode() would return a
  695. /// non \c NULL value.
  696. ///
  697. /// \exception None
  698. const isc::dns::NameComparisonResult& getLastComparisonResult() const {
  699. return (last_comparison_);
  700. }
  701. /// \brief Return the number of levels stored in the chain.
  702. ///
  703. /// It's equal to the number of nodes in the chain; for an empty
  704. /// chain, 0 will be returned.
  705. ///
  706. /// \exception None
  707. size_t getLevelCount() const { return (level_count_); }
  708. /// \brief return the absolute name for the node which this
  709. /// \c DomainTreeNodeChain currently refers to.
  710. ///
  711. /// The chain must not be empty.
  712. ///
  713. /// \exception isc::BadValue the chain is empty.
  714. /// \exception std::bad_alloc memory allocation for the new name fails.
  715. isc::dns::Name getAbsoluteName() const {
  716. if (isEmpty()) {
  717. isc_throw(isc::BadValue,
  718. "DomainTreeNodeChain::getAbsoluteName is "
  719. "called on an empty chain");
  720. }
  721. const DomainTreeNode<T>* top_node = top();
  722. isc::dns::Name absolute_name = top_node->getName();
  723. size_t level = level_count_ - 1;
  724. while (level > 0) {
  725. top_node = nodes_[level - 1];
  726. absolute_name = absolute_name.concatenate(top_node->getName());
  727. --level;
  728. }
  729. return (absolute_name);
  730. }
  731. private:
  732. // the following private functions check invariants about the internal
  733. // state using assert() instead of exception. The state of a chain
  734. // can only be modified by operations within this file, so if any of the
  735. // assumptions fails it means an internal bug.
  736. /// \brief return whether node chain has node in it.
  737. ///
  738. /// \exception None
  739. bool isEmpty() const { return (level_count_ == 0); }
  740. /// \brief return the top node for the node chain
  741. ///
  742. /// DomainTreeNodeChain store all the nodes along top node to
  743. /// root node of DomainTree
  744. ///
  745. /// \exception None
  746. const DomainTreeNode<T>* top() const {
  747. assert(!isEmpty());
  748. return (nodes_[level_count_ - 1]);
  749. }
  750. /// \brief pop the top node from the node chain
  751. ///
  752. /// After pop, up/super node of original top node will be
  753. /// the top node
  754. ///
  755. /// \exception None
  756. void pop() {
  757. assert(!isEmpty());
  758. --level_count_;
  759. }
  760. /// \brief add the node into the node chain
  761. ///
  762. /// If the node chain isn't empty, the node should be
  763. /// the sub domain of the original top node in node chain
  764. /// otherwise the node should be the root node of DomainTree.
  765. ///
  766. /// \exception None
  767. void push(const DomainTreeNode<T>* node) {
  768. assert(level_count_ < RBT_MAX_LEVEL);
  769. nodes_[level_count_++] = node;
  770. }
  771. private:
  772. // The max label count for one domain name is Name::MAX_LABELS
  773. // (128). Since each node in domaintree stores at least one label,
  774. // it's also equal to the possible maximum level.
  775. const static int RBT_MAX_LEVEL = isc::dns::Name::MAX_LABELS;
  776. size_t level_count_;
  777. const DomainTreeNode<T>* nodes_[RBT_MAX_LEVEL];
  778. const DomainTreeNode<T>* last_compared_;
  779. isc::dns::NameComparisonResult last_comparison_;
  780. };
  781. // note: the following class description is documented using multiline comments
  782. // because the verbatim diagram contain a backslash, which could be interpreted
  783. // as escape of newline in singleline comment.
  784. /**
  785. * \brief \c DomainTree class represents all the domains with the same suffix.
  786. * It can be used to store the domains in one zone, for example.
  787. *
  788. * DomainTree is a generic map from domain names to any kind of
  789. * data. Internally, it uses a red-black tree. However, it isn't one
  790. * tree containing everything. Subdomains are trees, so this structure
  791. * is recursive - trees inside trees. But, from the interface point of
  792. * view, it is opaque data structure.
  793. *
  794. * The data of DomainTree are set by the application via the
  795. * DomainTreeNode::setData() method. The ownership of the data isn't
  796. * transferred to the DomainTree; if the application replaces existing
  797. * data for a specific name in DomainTree by setData(), the application is
  798. * responsible for releasing any resource for the old data. When the
  799. * application destroys the entire DomainTree by the \c destroy() method,
  800. * it needs to pass a deleter object for any remained data in the DomainTree.
  801. * The DomainTree will call that object with all the data in the tree so that
  802. * the application complete the cleanup about the remaining data.
  803. *
  804. * \c DomainTree splits the domain space into hierarchy red black trees; nodes
  805. * in one tree has the same base name. The benefit of this struct is that:
  806. * - Enhances the query performance compared with one big flat red black tree.
  807. * - Decreases the memory footprint, as it doesn't store the suffix labels
  808. * multiple times.
  809. *
  810. * Depending on different usage, domaintree will support different
  811. * search policies. Whether to return an empty node to end user is one
  812. * policy among them. The default policy is to NOT return an empty node
  813. * to end user; to change the behavior, specify \c true for the
  814. * constructor parameter \c returnEmptyNode.
  815. * \note The search policy only affects the \c find() behavior of DomainTree.
  816. * When inserting one name into DomainTree, if the node with the name already
  817. * exists in the DomainTree and it's an empty node which doesn't have any data,
  818. * the \c insert() method will still return \c ALREADYEXISTS regardless of
  819. * the search policy.
  820. *
  821. * The template parameter taken by \c DomainTree is \c T (the type of
  822. * data which is stored by the tree).
  823. *
  824. * \anchor diagram
  825. *
  826. * with the following names:
  827. * - a
  828. * - b
  829. * - c
  830. * - x.d.e.f
  831. * - z.d.e.f
  832. * - g.h
  833. * - o.w.y.d.e.f
  834. * - p.w.y.d.e.f
  835. * - q.w.y.d.e.f
  836. *
  837. * the tree will look like:
  838. * \verbatim
  839. .
  840. |
  841. b
  842. / \
  843. a d.e.f
  844. /|\
  845. c | g.h
  846. |
  847. w.y
  848. /|\
  849. x | z
  850. |
  851. p
  852. / \
  853. o q
  854. \endverbatim
  855. * \todo
  856. * - add remove interface
  857. */
  858. template <typename T>
  859. class DomainTree : public boost::noncopyable {
  860. friend class DomainTreeNode<T>;
  861. public:
  862. /// \brief The return value for the \c find() and insert() methods
  863. enum Result {
  864. SUCCESS, ///< Insert was successful
  865. /// \brief The node returned from find mathes exactly the name given
  866. EXACTMATCH,
  867. PARTIALMATCH, ///< A superdomain node was found
  868. NOTFOUND, ///< Not even any superdomain was found
  869. /// \brief Returned by insert() if a node of the name already exists
  870. ALREADYEXISTS,
  871. };
  872. /// \brief Allocate and construct \c DomainTree
  873. ///
  874. /// This static method allocates memory for a new \c DomainTree object
  875. /// from the given memory segment, constructs the object, and returns
  876. /// a pointer to it.
  877. ///
  878. /// \throw std::bad_alloc Memory allocation fails.
  879. ///
  880. /// \param mem_sgmt A \c MemorySegment from which memory for the new
  881. /// \c DomainTree is allocated.
  882. static DomainTree* create(util::MemorySegment& mem_sgmt,
  883. bool return_empty_node = false)
  884. {
  885. void* p = mem_sgmt.allocate(sizeof(DomainTree<T>));
  886. return (new(p) DomainTree<T>(return_empty_node));
  887. }
  888. /// \brief Destruct and deallocate \c DomainTree
  889. ///
  890. /// This method also destroys and deallocates all nodes inserted to the
  891. /// tree.
  892. ///
  893. /// The template parameter, \c DataDeleter, is a type whose instance is
  894. /// used to destroy data stored in the tree nodes. It must have a
  895. /// <code>operator()</code> method, which is called on a \c DataDeleter
  896. /// instance and passed a pointer to the data (<code>T*</code>) to be
  897. /// destroyed. This method should be written to accept a \c NULL argument.
  898. ///
  899. /// \note The memory segment (\c mem_sgmt) must be the same one that
  900. /// was originally used to allocate memory for the tree (and for all
  901. /// nodes inserted to the tree, due to the requirement of \c insert()),
  902. /// since the tree itself doesn't maintain a reference to the segment.
  903. /// This is not a robust interface, but since we plan to share the tree
  904. /// structure by multiple processes via shared memory or possibly allow
  905. /// the memory image to be dumped to a file for later reload, there
  906. /// doesn't seem to be an easy way to store such reference in the data
  907. /// itself. We should probably consider a wrapper interface that
  908. /// encapsulates the corresponding segment and always use it for any
  909. /// allocation/deallocation of tree related data (the tree itself, their
  910. /// nodes, and node data) to keep the usage as safe as possible.
  911. ///
  912. /// \throw none
  913. ///
  914. /// \param mem_sgmt The \c MemorySegment that allocated memory for
  915. /// \c tree and for all nodes inserted to the tree.
  916. /// \param tree A non NULL pointer to a valid \c DomainTree object
  917. /// that was originally created by the \c create() method (the behavior
  918. /// is undefined if this condition isn't met).
  919. /// \param deleter A deleter functor or function to delete node data.
  920. template <typename DataDeleter>
  921. static void destroy(util::MemorySegment& mem_sgmt,
  922. DomainTree<T>* tree,
  923. DataDeleter deleter)
  924. {
  925. tree->deleteAllNodes(mem_sgmt, deleter);
  926. tree->~DomainTree<T>();
  927. mem_sgmt.deallocate(tree, sizeof(DomainTree<T>));
  928. }
  929. private:
  930. /// \name Constructor and Destructor
  931. //@{
  932. /// \brief The constructor.
  933. ///
  934. /// An object of this class is always expected to be created by the
  935. /// allocator (\c create()), so the constructor is hidden as private.
  936. ///
  937. /// It never throws an exception.
  938. explicit DomainTree(bool returnEmptyNode = false);
  939. /// \brief The destructor.
  940. ///
  941. /// An object of this class is always expected to be destroyed explicitly
  942. /// by \c destroy(), so the destructor is hidden as private.
  943. ///
  944. /// \note DomainTree is not intended to be inherited so the destructor
  945. /// is not virtual
  946. ~DomainTree();
  947. //@}
  948. public:
  949. /// \name Find methods
  950. ///
  951. /// \brief Find the node that gives a longest match against the given name.
  952. ///
  953. /// \anchor find
  954. ///
  955. /// These methods search the DomainTree for a node whose name is
  956. /// longest against name. The found node, if any, is returned via
  957. /// the node pointer.
  958. ///
  959. /// By default, nodes that don't have data (see
  960. /// DomainTreeNode::isEmpty) are ignored and the result can be
  961. /// NOTFOUND even if there's a node whose name matches. If the \c
  962. /// DomainTree is constructed with its \c returnEmptyNode parameter
  963. /// being \c true, empty nodes will also be match candidates.
  964. ///
  965. /// \note Even when \c returnEmptyNode is \c true, not all empty
  966. /// nodes in terms of the DNS protocol may necessarily be found by
  967. /// this method. For example, in the \ref diagram shown in the
  968. /// class description, the name y.d.e.f is logically contained in
  969. /// the tree as part of the node w.y, but the \c find() variants
  970. /// cannot find the former for the search key of y.d.e.f, no matter
  971. /// how the \c DomainTree is constructed. The caller of this method
  972. /// must use a different way to identify the hidden match when
  973. /// necessary.
  974. ///
  975. /// These methods involve operations on names that can throw an
  976. /// exception. If that happens the exception will be propagated to
  977. /// the caller. The callback function should generally not throw an
  978. /// exception, but if it throws, the exception will be propagated to
  979. /// the caller.
  980. ///
  981. /// The \c name parameter says what should be found. The node parameter
  982. /// is output-only, and in case of EXACTMATCH or PARTIALMATCH, it is set
  983. /// to a pointer to the found node.
  984. ///
  985. /// They return:
  986. /// - EXACTMATCH when a node with the same name as requested exists.
  987. /// - PARTIALMATCH when a node with the same name does not exist (or is
  988. /// empty), but there's a (nonempty) superdomain of the requested one.
  989. /// The superdomain with longest name is returned through the node
  990. /// parameter. Beware that if you store a zone in the tree, you may get
  991. /// PARTIALMATCH with zone apex when the given domain name is not there.
  992. /// You should not try to delegate into another zone in that case.
  993. /// - NOTFOUND if there's no node with the same name nor any superdomain
  994. /// of it. In that case, node parameter is left intact.
  995. //@{
  996. /// \brief Simple find.
  997. ///
  998. /// Acts as described in the \ref find section.
  999. Result find(const isc::dns::Name& name,
  1000. DomainTreeNode<T>** node) const {
  1001. DomainTreeNodeChain<T> node_path;
  1002. const isc::dns::LabelSequence ls(name);
  1003. return (find<void*>(ls, node, node_path, NULL, NULL));
  1004. }
  1005. /// \brief Simple find returning immutable node.
  1006. ///
  1007. /// Acts as described in the \ref find section, but returns immutable node
  1008. /// pointer.
  1009. Result find(const isc::dns::Name& name,
  1010. const DomainTreeNode<T>** node) const {
  1011. DomainTreeNodeChain<T> node_path;
  1012. DomainTreeNode<T> *target_node = NULL;
  1013. const isc::dns::LabelSequence ls(name);
  1014. Result ret = (find<void*>(ls, &target_node, node_path, NULL, NULL));
  1015. if (ret != NOTFOUND) {
  1016. *node = target_node;
  1017. }
  1018. return (ret);
  1019. }
  1020. /// \brief Simple find, with node_path tracking
  1021. ///
  1022. /// Acts as described in the \ref find section.
  1023. Result find(const isc::dns::Name& name, DomainTreeNode<T>** node,
  1024. DomainTreeNodeChain<T>& node_path) const
  1025. {
  1026. const isc::dns::LabelSequence ls(name);
  1027. return (find<void*>(ls, node, node_path, NULL, NULL));
  1028. }
  1029. /// \brief Simple find returning immutable node, with node_path tracking
  1030. ///
  1031. /// Acts as described in the \ref find section, but returns immutable node
  1032. /// pointer.
  1033. Result find(const isc::dns::Name& name, const DomainTreeNode<T>** node,
  1034. DomainTreeNodeChain<T>& node_path) const
  1035. {
  1036. DomainTreeNode<T> *target_node = NULL;
  1037. const isc::dns::LabelSequence ls(name);
  1038. Result ret = (find<void*>(ls, &target_node, node_path, NULL, NULL));
  1039. if (ret != NOTFOUND) {
  1040. *node = target_node;
  1041. }
  1042. return (ret);
  1043. }
  1044. /// \brief Simple find returning immutable node.
  1045. ///
  1046. /// Acts as described in the \ref find section, but returns immutable
  1047. /// node pointer.
  1048. template <typename CBARG>
  1049. Result find(const isc::dns::Name& name,
  1050. const DomainTreeNode<T>** node,
  1051. DomainTreeNodeChain<T>& node_path,
  1052. bool (*callback)(const DomainTreeNode<T>&, CBARG),
  1053. CBARG callback_arg) const
  1054. {
  1055. DomainTreeNode<T>* target_node = NULL;
  1056. const isc::dns::LabelSequence ls(name);
  1057. Result ret = find(ls, &target_node, node_path, callback,
  1058. callback_arg);
  1059. if (ret != NOTFOUND) {
  1060. *node = target_node;
  1061. }
  1062. return (ret);
  1063. }
  1064. /// \brief Find with callback and node chain
  1065. /// \anchor callback
  1066. ///
  1067. /// This version of \c find() is specifically designed for the backend
  1068. /// of the \c InMemoryZoneFinder class, and implements all necessary
  1069. /// features for that purpose. Other applications shouldn't need these
  1070. /// additional features, and should normally use the simpler versions.
  1071. ///
  1072. /// This version of \c find() calls the callback whenever traversing (on
  1073. /// the way from root down the tree) a marked node on the way down through
  1074. /// the domain namespace (see \c DomainTreeNode::FLAG_CALLBACK).
  1075. ///
  1076. /// Also, this version takes a \c LabelSequence object, not a \c Name
  1077. /// object to be as efficient as possible; operations on the former
  1078. /// needed for the search are generally much more efficient than those
  1079. /// for the latter. Since \c Name objects are more commonly used
  1080. /// in other parts of the implementation, other versions take a \c Name
  1081. /// and convert it to \c LabelSequence. This conversion is cheap,
  1082. /// while the other direction isn't, and since there would be cases
  1083. /// where an implementation primarily handles \c LabelSequence objects
  1084. /// as an efficient representation of names, it would make most sense
  1085. /// to provide the interface that takes \c LabelSequence.
  1086. ///
  1087. /// If you return true from the callback, the search is stopped and a
  1088. /// PARTIALMATCH is returned with the given node. Note that this node
  1089. /// doesn't really need to be the one with longest possible match.
  1090. ///
  1091. /// The callback is not called for the node which matches exactly
  1092. /// (EXACTMATCH is returned). This is typically the last node in the
  1093. /// traversal during a successful search.
  1094. ///
  1095. /// This callback mechanism was designed with zone cut (delegation)
  1096. /// processing in mind. The marked nodes would be the ones at delegation
  1097. /// points. It is not expected that any other applications would need
  1098. /// callbacks; they should use the versions of find without callbacks.
  1099. /// The callbacks are not general functors for the same reason - we don't
  1100. /// expect it to be needed.
  1101. ///
  1102. /// Another special feature of this version is the ability to record
  1103. /// more detailed information regarding the search result.
  1104. ///
  1105. /// This information will be returned via the \c node_path
  1106. /// parameter, which is an object of class \c DomainTreeNodeChain.
  1107. /// The passed parameter must be empty if the label sequence is
  1108. /// absolute. If the label sequence is not absolute, then find()
  1109. /// will begin from the top of the node chain.
  1110. ///
  1111. /// On success, the node sequence stored in \c node_path will contain all
  1112. /// the ancestor nodes from the found node towards the root.
  1113. /// For example, if we look for o.w.y.d.e.f in the example \ref diagram,
  1114. /// \c node_path will contain w.y and d.e.f; the \c top() node of the
  1115. /// chain will be o, w.y and d.e.f will be stored below it.
  1116. ///
  1117. /// This feature can be used to get the absolute name for a node; to
  1118. /// do so, we need to travel upside from the node toward the root,
  1119. /// concatenating all ancestor labels. A node chain can also be
  1120. /// used to find the next and previous nodes of a given node in the
  1121. /// entire DomainTree; the \c nextNode() and \c previousNode()
  1122. /// methods take a node chain as a parameter.
  1123. ///
  1124. /// \exception isc::BadValue node_path is not empty.
  1125. ///
  1126. /// \param target_labels_orig Target to be found
  1127. /// \param node On success (either \c EXACTMATCH or \c PARTIALMATCH)
  1128. /// it will store a pointer to the matching node
  1129. /// \param node_path Other search details will be stored (see the
  1130. /// description)
  1131. /// \param callback If non- \c NULL, a call back function to be called
  1132. /// at marked nodes (see the description).
  1133. /// \param callback_arg A caller supplied argument to be passed to
  1134. /// \c callback.
  1135. ///
  1136. /// \return As in the description, but in case of callback returning
  1137. /// \c true, it returns immediately with the current node.
  1138. template <typename CBARG>
  1139. Result find(const isc::dns::LabelSequence& target_labels_orig,
  1140. DomainTreeNode<T>** node,
  1141. DomainTreeNodeChain<T>& node_path,
  1142. bool (*callback)(const DomainTreeNode<T>&, CBARG),
  1143. CBARG callback_arg) const;
  1144. /// \brief Simple find returning immutable node.
  1145. ///
  1146. /// Acts as described in the \ref find section, but returns immutable
  1147. /// node pointer.
  1148. template <typename CBARG>
  1149. Result find(const isc::dns::LabelSequence& target_labels,
  1150. const DomainTreeNode<T>** node,
  1151. DomainTreeNodeChain<T>& node_path,
  1152. bool (*callback)(const DomainTreeNode<T>&, CBARG),
  1153. CBARG callback_arg) const
  1154. {
  1155. DomainTreeNode<T>* target_node = NULL;
  1156. Result ret = find(target_labels, &target_node, node_path,
  1157. callback, callback_arg);
  1158. if (ret != NOTFOUND) {
  1159. *node = target_node;
  1160. }
  1161. return (ret);
  1162. }
  1163. //@}
  1164. /// \brief return the next bigger node in DNSSEC order from a given node
  1165. /// chain.
  1166. ///
  1167. /// This method identifies the next bigger node of the node currently
  1168. /// referenced in \c node_path and returns it.
  1169. /// This method also updates the passed \c node_path so that it will store
  1170. /// the path for the returned next node.
  1171. /// It will be convenient when we want to iterate over the all nodes
  1172. /// of \c DomainTree; we can do this by calling this method repeatedly
  1173. /// starting from the root node.
  1174. ///
  1175. /// \note \c nextNode() will iterate over all the nodes in
  1176. /// DomainTree including empty nodes. If empty node isn't desired,
  1177. /// it's easy to add logic to check return node and keep invoking \c
  1178. /// nextNode() until the non-empty node is retrieved.
  1179. ///
  1180. /// \exception isc::BadValue node_path is empty.
  1181. ///
  1182. /// \param node_path A node chain that stores all the nodes along
  1183. /// the path from root to node.
  1184. ///
  1185. /// \return An \c DomainTreeNode that is next bigger than \c node;
  1186. /// if \c node is the largest, \c NULL will be returned.
  1187. const DomainTreeNode<T>*
  1188. nextNode(DomainTreeNodeChain<T>& node_path) const;
  1189. /// \brief return the next smaller node in DNSSEC order from a node
  1190. /// searched by DomainTree::find().
  1191. ///
  1192. /// This acts similarly to \c nextNode(), but it walks in the other
  1193. /// direction. But unlike \c nextNode(), this can start even if the
  1194. /// node requested by \c find() was not found. In that case, it will
  1195. /// identify the node that is previous to the queried name.
  1196. ///
  1197. /// \note \c previousNode() will iterate over all the nodes in DomainTree
  1198. /// including empty nodes. If empty node isn't desired, it's easy to add
  1199. /// logic to check return node and keep invoking \c previousNode() until the
  1200. /// non-empty node is retrieved.
  1201. ///
  1202. /// \exception isc::BadValue node_path is empty.
  1203. ///
  1204. /// \param node_path A node chain that stores all the nodes along the path
  1205. /// from root to node and the result of \c find(). This will get modified.
  1206. /// You should not use the node_path again except for repetitive calls
  1207. /// of this method.
  1208. ///
  1209. /// \return An \c DomainTreeNode that is next smaller than \c node;
  1210. /// if \c node is the smallest, \c NULL will be returned.
  1211. const DomainTreeNode<T>*
  1212. previousNode(DomainTreeNodeChain<T>& node_path) const;
  1213. /// \brief return the largest node in the tree of trees.
  1214. ///
  1215. /// \throw none
  1216. ///
  1217. /// \return A \c DomainTreeNode that is the largest node in the
  1218. /// tree. If there are no nodes, then \c NULL is returned.
  1219. const DomainTreeNode<T>* largestNode() const;
  1220. /// \brief Get the total number of nodes in the tree
  1221. ///
  1222. /// It includes nodes internally created as a result of adding a domain
  1223. /// name that is a subdomain of an existing node of the tree.
  1224. /// This function is mainly intended to be used for debugging.
  1225. uint32_t getNodeCount() const { return (node_count_); }
  1226. /// \name Debug function
  1227. //@{
  1228. /// \brief Print the nodes in the trees.
  1229. ///
  1230. /// \param os A \c std::ostream object to which the tree is printed.
  1231. /// \param depth A factor of the initial indentation. Each line
  1232. /// will begin with space character repeating <code>5 * depth</code>
  1233. /// times.
  1234. void dumpTree(std::ostream& os, unsigned int depth = 0) const;
  1235. /// \brief Print the nodes in the trees for processing with
  1236. /// Graphviz's dot.
  1237. ///
  1238. /// \param os A \c std::ostream object to which the tree is printed.
  1239. /// \param show_pointers Show node and parent pointers in the node
  1240. void dumpDot(std::ostream& os, bool show_pointers = false) const;
  1241. //@}
  1242. /// \name Modify functions
  1243. //@{
  1244. /// \brief Insert the domain name into the tree.
  1245. ///
  1246. /// It either finds an already existing node of the given name, or
  1247. /// inserts a new one if none exists yet. In any case, the \c
  1248. /// inserted_node parameter is set to point to that node. You can
  1249. /// fill data into it or modify it. So, if you don't know if a node
  1250. /// exists or not and you need to modify it, just call insert and
  1251. /// act by the result.
  1252. ///
  1253. /// Please note that the tree can add some empty nodes by itself, so
  1254. /// don't assume that if you didn't insert a node of that name it
  1255. /// doesn't exist.
  1256. ///
  1257. /// This method normally involves resource allocation. If it fails
  1258. /// the corresponding standard exception will be thrown.
  1259. ///
  1260. /// This method does not provide the strong exception guarantee in its
  1261. /// strict sense; if an exception is thrown in the middle of this
  1262. /// method, the internal structure may change. However, it should
  1263. /// still retain the same property as a mapping container before this
  1264. /// method is called. For example, the result of \c find() should be
  1265. /// the same. This method provides the weak exception guarantee in its
  1266. /// normal sense.
  1267. ///
  1268. /// \param mem_sgmt A \c MemorySegment object for allocating memory of
  1269. /// a new node to be inserted. Must be the same segment as that used
  1270. /// for creating the tree itself.
  1271. /// \param name The name to be inserted into the tree.
  1272. /// \param inserted_node This is an output parameter and is set to the
  1273. /// node.
  1274. ///
  1275. /// \return
  1276. /// - SUCCESS The node was added.
  1277. /// - ALREADYEXISTS There was already a node of that name, so it was not
  1278. /// added.
  1279. Result insert(util::MemorySegment& mem_sgmt, const isc::dns::Name& name,
  1280. DomainTreeNode<T>** inserted_node);
  1281. /// \brief Delete all tree nodes.
  1282. ///
  1283. /// \throw none.
  1284. ///
  1285. /// \param mem_sgmt The \c MemorySegment object used to insert the nodes
  1286. /// (which was also used for creating the tree due to the requirement of
  1287. /// \c inert()).
  1288. template <typename DataDeleter>
  1289. void deleteAllNodes(util::MemorySegment& mem_sgmt, DataDeleter deleter);
  1290. /// \brief Swaps two tree's contents.
  1291. ///
  1292. /// This and \c other trees must have been created with the same
  1293. /// memory segment (see the discussion in \c create()); otherwise the
  1294. /// behavior is undefined.
  1295. ///
  1296. /// This acts the same as many std::*.swap functions, exchanges the
  1297. /// contents. This doesn't throw anything.
  1298. void swap(DomainTree<T>& other) {
  1299. std::swap(root_, other.root_);
  1300. std::swap(node_count_, other.node_count_);
  1301. }
  1302. //@}
  1303. private:
  1304. /// \name DomainTree balance functions
  1305. //@{
  1306. void
  1307. insertRebalance(typename DomainTreeNode<T>::DomainTreeNodePtr* root,
  1308. DomainTreeNode<T>* node);
  1309. DomainTreeNode<T>*
  1310. rightRotate(typename DomainTreeNode<T>::DomainTreeNodePtr* root,
  1311. DomainTreeNode<T>* node);
  1312. DomainTreeNode<T>*
  1313. leftRotate(typename DomainTreeNode<T>::DomainTreeNodePtr* root,
  1314. DomainTreeNode<T>* node);
  1315. //@}
  1316. /// \name Helper functions
  1317. //@{
  1318. /// \brief delete tree whose root is equal to node
  1319. template <typename DataDeleter>
  1320. void deleteHelper(util::MemorySegment& mem_sgmt,
  1321. DomainTreeNode<T> *node,
  1322. const DataDeleter& deleter);
  1323. /// \brief Print the information of given DomainTreeNode.
  1324. void dumpTreeHelper(std::ostream& os, const DomainTreeNode<T>* node,
  1325. unsigned int depth) const;
  1326. /// \brief Print the information of given DomainTreeNode for dot.
  1327. int dumpDotHelper(std::ostream& os, const DomainTreeNode<T>* node,
  1328. int* nodecount, bool show_pointers) const;
  1329. /// \brief Indentation helper function for dumpTree
  1330. static void indent(std::ostream& os, unsigned int depth);
  1331. /// Split one node into two nodes for "prefix" and "suffix" parts of
  1332. /// the labels of the original node, respectively. The given node
  1333. /// will hold the prefix, while a newly created node will hold the prefix.
  1334. /// Note that the original node still represents the same domain name in
  1335. /// the entire tree. This ensures that a pointer to a node keeps its
  1336. /// semantics even if the tree structure is changed (as long as the node
  1337. /// itself remains valid).
  1338. void nodeFission(util::MemorySegment& mem_sgmt, DomainTreeNode<T>& node,
  1339. const isc::dns::LabelSequence& new_prefix,
  1340. const isc::dns::LabelSequence& new_suffix);
  1341. //@}
  1342. typename DomainTreeNode<T>::DomainTreeNodePtr root_;
  1343. /// the node count of current tree.
  1344. ///
  1345. /// Note: uint32_t may look awkward, but we intentionally choose it so
  1346. /// that needsReturnEmptyNode_ below won't make cause extra padding
  1347. /// in 64-bit machines (and we can minimize the total size of this class).
  1348. /// 2^32 - 1 should be a reasonable max of possible number of nodes.
  1349. uint32_t node_count_;
  1350. /// search policy for domaintree
  1351. const bool needsReturnEmptyNode_;
  1352. };
  1353. template <typename T>
  1354. DomainTree<T>::DomainTree(bool returnEmptyNode) :
  1355. root_(NULL),
  1356. node_count_(0),
  1357. needsReturnEmptyNode_(returnEmptyNode)
  1358. {
  1359. }
  1360. template <typename T>
  1361. DomainTree<T>::~DomainTree() {
  1362. assert(node_count_ == 0);
  1363. }
  1364. template <typename T>
  1365. template <typename DataDeleter>
  1366. void
  1367. DomainTree<T>::deleteHelper(util::MemorySegment& mem_sgmt,
  1368. DomainTreeNode<T>* root,
  1369. const DataDeleter& deleter)
  1370. {
  1371. while (root != NULL) {
  1372. // If there is a left, right or down node, walk into it and
  1373. // iterate.
  1374. if (root->getLeft() != NULL) {
  1375. DomainTreeNode<T>* node = root;
  1376. root = root->getLeft();
  1377. node->left_ = NULL;
  1378. } else if (root->getRight() != NULL) {
  1379. DomainTreeNode<T>* node = root;
  1380. root = root->getRight();
  1381. node->right_ = NULL;
  1382. } else if (root->getDown() != NULL) {
  1383. DomainTreeNode<T>* node = root;
  1384. root = root->getDown();
  1385. node->down_ = NULL;
  1386. } else {
  1387. // There are no left, right or down nodes, so we can
  1388. // free this one and go back to its parent.
  1389. DomainTreeNode<T>* node = root;
  1390. root = root->getParent();
  1391. deleter(node->data_.get());
  1392. DomainTreeNode<T>::destroy(mem_sgmt, node);
  1393. --node_count_;
  1394. }
  1395. }
  1396. }
  1397. template <typename T>
  1398. template <typename CBARG>
  1399. typename DomainTree<T>::Result
  1400. DomainTree<T>::find(const isc::dns::LabelSequence& target_labels_orig,
  1401. DomainTreeNode<T>** target,
  1402. DomainTreeNodeChain<T>& node_path,
  1403. bool (*callback)(const DomainTreeNode<T>&, CBARG),
  1404. CBARG callback_arg) const
  1405. {
  1406. if (node_path.isEmpty() ^ target_labels_orig.isAbsolute()) {
  1407. isc_throw(isc::BadValue,
  1408. "DomainTree::find() is given mismatched node chain"
  1409. " and label sequence");
  1410. }
  1411. DomainTreeNode<T>* node;
  1412. if (!node_path.isEmpty()) {
  1413. // Get the top node in the node chain
  1414. node = const_cast<DomainTreeNode<T>*>(node_path.top());
  1415. // Start searching from its down pointer
  1416. node = node->getDown();
  1417. } else {
  1418. node = root_.get();
  1419. }
  1420. Result ret = NOTFOUND;
  1421. dns::LabelSequence target_labels(target_labels_orig);
  1422. while (node != NULL) {
  1423. node_path.last_compared_ = node;
  1424. node_path.last_comparison_ = target_labels.compare(node->getLabels());
  1425. const isc::dns::NameComparisonResult::NameRelation relation =
  1426. node_path.last_comparison_.getRelation();
  1427. if (relation == isc::dns::NameComparisonResult::EQUAL) {
  1428. if (needsReturnEmptyNode_ || !node->isEmpty()) {
  1429. node_path.push(node);
  1430. *target = node;
  1431. ret = EXACTMATCH;
  1432. }
  1433. break;
  1434. } else if (relation == isc::dns::NameComparisonResult::NONE) {
  1435. // If the two labels have no hierarchical relationship in terms
  1436. // of matching, we should continue the binary search.
  1437. node = (node_path.last_comparison_.getOrder() < 0) ?
  1438. node->getLeft() : node->getRight();
  1439. } else {
  1440. if (relation == isc::dns::NameComparisonResult::SUBDOMAIN) {
  1441. if (needsReturnEmptyNode_ || !node->isEmpty()) {
  1442. ret = PARTIALMATCH;
  1443. *target = node;
  1444. if (callback != NULL &&
  1445. node->getFlag(DomainTreeNode<T>::FLAG_CALLBACK)) {
  1446. if ((callback)(*node, callback_arg)) {
  1447. break;
  1448. }
  1449. }
  1450. }
  1451. node_path.push(node);
  1452. target_labels.stripRight(
  1453. node_path.last_comparison_.getCommonLabels());
  1454. node = node->getDown();
  1455. } else {
  1456. break;
  1457. }
  1458. }
  1459. }
  1460. return (ret);
  1461. }
  1462. template <typename T>
  1463. const DomainTreeNode<T>*
  1464. DomainTree<T>::nextNode(DomainTreeNodeChain<T>& node_path) const {
  1465. if (node_path.isEmpty()) {
  1466. isc_throw(isc::BadValue,
  1467. "DomainTree::nextNode is given an empty chain");
  1468. }
  1469. const DomainTreeNode<T>* node = node_path.top();
  1470. // if node has sub domain, the next domain is the smallest
  1471. // domain in sub domain tree
  1472. const DomainTreeNode<T>* down = node->getDown();
  1473. if (down != NULL) {
  1474. const DomainTreeNode<T>* left_most = down;
  1475. while (left_most->getLeft() != NULL) {
  1476. left_most = left_most->getLeft();
  1477. }
  1478. node_path.push(left_most);
  1479. return (left_most);
  1480. }
  1481. // try to find a successor.
  1482. // if no successor found move to up level, the next successor
  1483. // is the successor of up node in the up level tree, if
  1484. // up node doesn't have successor we gonna keep moving to up
  1485. // level
  1486. while (!node_path.isEmpty()) {
  1487. const DomainTreeNode<T>* up_node_successor =
  1488. node_path.top()->successor();
  1489. node_path.pop();
  1490. if (up_node_successor != NULL) {
  1491. node_path.push(up_node_successor);
  1492. return (up_node_successor);
  1493. }
  1494. }
  1495. return (NULL);
  1496. }
  1497. template <typename T>
  1498. const DomainTreeNode<T>*
  1499. DomainTree<T>::previousNode(DomainTreeNodeChain<T>& node_path) const {
  1500. if (getNodeCount() == 0) {
  1501. // Special case for empty trees. It would look every time like
  1502. // we didn't search, because the last compared is empty. This is
  1503. // a slight hack and not perfect, but this is better than throwing
  1504. // on empty tree. And we probably won't meet an empty tree in practice
  1505. // anyway.
  1506. return (NULL);
  1507. }
  1508. if (node_path.last_compared_ == NULL) {
  1509. isc_throw(isc::BadValue,
  1510. "DomainTree::previousNode() called before find()");
  1511. }
  1512. // If the relation isn't EQUAL, it means the find was called previously
  1513. // and didn't find the exact node. Therefore we need to locate the place
  1514. // to start iterating the chain of domains.
  1515. //
  1516. // The logic here is not too complex, we just need to take care to handle
  1517. // all the cases and decide where to go from there.
  1518. switch (node_path.last_comparison_.getRelation()) {
  1519. case dns::NameComparisonResult::COMMONANCESTOR:
  1520. case dns::NameComparisonResult::NONE:
  1521. // We compared with a leaf in the tree and wanted to go to one of
  1522. // the children. But the child was not there. It now depends on the
  1523. // direction in which we wanted to go.
  1524. if (node_path.last_comparison_.getOrder() < 0) {
  1525. // We wanted to go left. So the one we compared with is
  1526. // the one higher than we wanted. If we just put it into
  1527. // the node_path, then the following algorithm below will find
  1528. // the smaller one.
  1529. //
  1530. // This is exactly the same as with superdomain below.
  1531. // Therefore, we just fall through to the next case.
  1532. } else {
  1533. // We wanted to go right. That means we want to output the
  1534. // one which is the largest in the tree defined by the
  1535. // compared one (it is either the compared one, or some
  1536. // subdomain of it). There probably is not an easy trick
  1537. // for this, so we just find the correct place.
  1538. const DomainTreeNode<T>* current(node_path.last_compared_);
  1539. while (current != NULL) {
  1540. node_path.push(current);
  1541. // Go a level down and as much right there as possible
  1542. current = current->getDown();
  1543. if (current != NULL) {
  1544. const DomainTreeNode<T>* right;
  1545. while ((right = current->getRight()) != NULL) {
  1546. current = right;
  1547. }
  1548. }
  1549. }
  1550. // Now, the one on top of the path is the one we want. We
  1551. // return it now and leave it there, so we can search for
  1552. // previous of it the next time we'are called.
  1553. node_path.last_comparison_ =
  1554. dns::NameComparisonResult(0, 0,
  1555. dns::NameComparisonResult::EQUAL);
  1556. return (node_path.top());
  1557. }
  1558. // No break; here - we want to fall through. See above.
  1559. case dns::NameComparisonResult::SUPERDOMAIN:
  1560. // This is the case there's a "compressed" node and we looked for
  1561. // only part of it. The node itself is larger than we wanted, but
  1562. // if we put it to the node_path and then go one step left from it,
  1563. // we get the correct result.
  1564. node_path.push(node_path.last_compared_);
  1565. // Correct the comparison result, so we won't trigger this case
  1566. // next time previousNode is called. We already located the correct
  1567. // place to start. The value is partly nonsense, but that doesn't
  1568. // matter any more.
  1569. node_path.last_comparison_ =
  1570. dns::NameComparisonResult(0, 0,
  1571. dns::NameComparisonResult::EQUAL);
  1572. break;
  1573. case dns::NameComparisonResult::SUBDOMAIN:
  1574. // A subdomain means we returned the one above the searched one
  1575. // already and it is on top of the stack. This is was smaller
  1576. // than the one already, but we want to return yet smaller one.
  1577. // So we act as if it was EQUAL.
  1578. break;
  1579. case dns::NameComparisonResult::EQUAL:
  1580. // The find gave us an exact match or the previousNode was called
  1581. // already, which located the exact node. The rest of the function
  1582. // goes one domain left and returns it for us.
  1583. break;
  1584. }
  1585. // So, the node_path now contains the path to a node we want previous for.
  1586. // We just need to go one step left.
  1587. if (node_path.isEmpty()) {
  1588. // We got past the first one. So, we're returning NULL from
  1589. // now on.
  1590. return (NULL);
  1591. }
  1592. const DomainTreeNode<T>* node(node_path.top());
  1593. // Try going left in this tree
  1594. node = node->predecessor();
  1595. if (node == NULL) {
  1596. // We are the smallest ones in this tree. We go one level
  1597. // up. That one is the smaller one than us.
  1598. node_path.pop();
  1599. if (node_path.isEmpty()) {
  1600. // We're past the first one
  1601. return (NULL);
  1602. } else {
  1603. return (node_path.top());
  1604. }
  1605. }
  1606. // Exchange the node at the top of the path, as we move horizontaly
  1607. // through the domain tree
  1608. node_path.pop();
  1609. node_path.push(node);
  1610. // Try going as deep as possible, keeping on the right side of the trees
  1611. const DomainTreeNode<T>* down;
  1612. while ((down = node->getDown()) != NULL) {
  1613. // Move to the tree below
  1614. node = down;
  1615. if (node != NULL) {
  1616. // And get as much to the right of the tree as possible
  1617. const DomainTreeNode<T>* right;
  1618. while ((right = node->getRight()) != NULL) {
  1619. node = right;
  1620. }
  1621. }
  1622. // Now, we found the right-most node in the sub-tree, we need to
  1623. // include it in the path
  1624. node_path.push(node);
  1625. }
  1626. // Now, if the current node has no down_ pointer any more, it's the
  1627. // correct one.
  1628. return (node);
  1629. }
  1630. template <typename T>
  1631. const DomainTreeNode<T>*
  1632. DomainTree<T>::largestNode() const {
  1633. const DomainTreeNode<T>* node = root_.get();
  1634. while (node != NULL) {
  1635. // We go right first, then down.
  1636. if (node->getRight() != NULL) {
  1637. node = node->getRight();
  1638. } else if (node->getDown() != NULL) {
  1639. node = node->getDown();
  1640. } else {
  1641. break;
  1642. }
  1643. }
  1644. return (node);
  1645. }
  1646. template <typename T>
  1647. typename DomainTree<T>::Result
  1648. DomainTree<T>::insert(util::MemorySegment& mem_sgmt,
  1649. const isc::dns::Name& target_name,
  1650. DomainTreeNode<T>** new_node)
  1651. {
  1652. DomainTreeNode<T>* parent = NULL;
  1653. DomainTreeNode<T>* current = root_.get();
  1654. DomainTreeNode<T>* up_node = NULL;
  1655. isc::dns::LabelSequence target_labels(target_name);
  1656. int order = -1;
  1657. // For possible LabelSequence serialization we always store labels data
  1658. // in the separate local buffer.
  1659. uint8_t labels_buf[dns::LabelSequence::MAX_SERIALIZED_LENGTH];
  1660. while (current != NULL) {
  1661. const dns::LabelSequence current_labels(
  1662. dns::LabelSequence(current->getLabels(), labels_buf));
  1663. const isc::dns::NameComparisonResult compare_result =
  1664. target_labels.compare(current_labels);
  1665. const isc::dns::NameComparisonResult::NameRelation relation =
  1666. compare_result.getRelation();
  1667. if (relation == isc::dns::NameComparisonResult::EQUAL) {
  1668. if (new_node != NULL) {
  1669. *new_node = current;
  1670. }
  1671. return (ALREADYEXISTS);
  1672. } else if (relation == isc::dns::NameComparisonResult::NONE) {
  1673. parent = current;
  1674. order = compare_result.getOrder();
  1675. current = order < 0 ? current->getLeft() : current->getRight();
  1676. } else if (relation == isc::dns::NameComparisonResult::SUBDOMAIN) {
  1677. // insert sub domain to sub tree
  1678. parent = NULL;
  1679. up_node = current;
  1680. target_labels.stripRight(compare_result.getCommonLabels());
  1681. current = current->getDown();
  1682. } else {
  1683. // The number of labels in common is fewer than the number of
  1684. // labels at the current node, so the current node must be
  1685. // adjusted to have just the common suffix, and a down pointer
  1686. // made to a new tree.
  1687. dns::LabelSequence common_ancestor = target_labels;
  1688. common_ancestor.stripLeft(target_labels.getLabelCount() -
  1689. compare_result.getCommonLabels());
  1690. dns::LabelSequence new_prefix = current_labels;
  1691. new_prefix.stripRight(compare_result.getCommonLabels());
  1692. nodeFission(mem_sgmt, *current, new_prefix, common_ancestor);
  1693. current = current->getParent();
  1694. }
  1695. }
  1696. typename DomainTreeNode<T>::DomainTreeNodePtr* current_root =
  1697. (up_node != NULL) ? &(up_node->down_) : &root_;
  1698. // Once a new node is created, no exception will be thrown until the end
  1699. // of the function, so we can simply create and hold a new node pointer.
  1700. DomainTreeNode<T>* node = DomainTreeNode<T>::create(mem_sgmt,
  1701. target_labels);
  1702. node->parent_ = parent;
  1703. if (parent == NULL) {
  1704. *current_root = node;
  1705. // node is the new root of sub tree, so its init color is BLACK
  1706. node->setColor(DomainTreeNode<T>::BLACK);
  1707. node->setSubTreeRoot(true);
  1708. node->parent_ = up_node;
  1709. } else if (order < 0) {
  1710. node->setSubTreeRoot(false);
  1711. parent->left_ = node;
  1712. } else {
  1713. node->setSubTreeRoot(false);
  1714. parent->right_ = node;
  1715. }
  1716. insertRebalance(current_root, node);
  1717. if (new_node != NULL) {
  1718. *new_node = node;
  1719. }
  1720. ++node_count_;
  1721. return (SUCCESS);
  1722. }
  1723. template <typename T>
  1724. template <typename DataDeleter>
  1725. void
  1726. DomainTree<T>::deleteAllNodes(util::MemorySegment& mem_sgmt,
  1727. DataDeleter deleter)
  1728. {
  1729. deleteHelper(mem_sgmt, root_.get(), deleter);
  1730. root_ = NULL;
  1731. }
  1732. template <typename T>
  1733. void
  1734. DomainTree<T>::nodeFission(util::MemorySegment& mem_sgmt,
  1735. DomainTreeNode<T>& node,
  1736. const isc::dns::LabelSequence& new_prefix,
  1737. const isc::dns::LabelSequence& new_suffix)
  1738. {
  1739. // Create and reset the labels.
  1740. // Once a new node is created, no exception will be thrown until
  1741. // the end of the function, and it will keep consistent behavior
  1742. // (i.e., a weak form of strong exception guarantee) even if code
  1743. // after the call to this function throws an exception.
  1744. DomainTreeNode<T>* up_node = DomainTreeNode<T>::create(mem_sgmt,
  1745. new_suffix);
  1746. node.resetLabels(new_prefix);
  1747. up_node->parent_ = node.getParent();
  1748. if (node.getParent() != NULL) {
  1749. if (node.getParent()->getLeft() == &node) {
  1750. node.getParent()->left_ = up_node;
  1751. } else if (node.getParent()->getRight() == &node) {
  1752. node.getParent()->right_ = up_node;
  1753. } else {
  1754. node.getParent()->down_ = up_node;
  1755. }
  1756. } else {
  1757. this->root_ = up_node;
  1758. }
  1759. up_node->down_ = &node;
  1760. node.parent_ = up_node;
  1761. // inherit the left/right pointers from the original node, and set
  1762. // the original node's left/right pointers to NULL.
  1763. up_node->left_ = node.getLeft();
  1764. if (node.getLeft() != NULL) {
  1765. node.getLeft()->parent_ = up_node;
  1766. }
  1767. up_node->right_ = node.getRight();
  1768. if (node.getRight() != NULL) {
  1769. node.getRight()->parent_ = up_node;
  1770. }
  1771. node.left_ = NULL;
  1772. node.right_ = NULL;
  1773. // set color of both nodes; the initial subtree node color is BLACK
  1774. up_node->setColor(node.getColor());
  1775. node.setColor(DomainTreeNode<T>::BLACK);
  1776. // set the subtree root flag of both nodes
  1777. up_node->setSubTreeRoot(node.isSubTreeRoot());
  1778. node.setSubTreeRoot(true);
  1779. ++node_count_;
  1780. }
  1781. template <typename T>
  1782. void
  1783. DomainTree<T>::insertRebalance
  1784. (typename DomainTreeNode<T>::DomainTreeNodePtr* root,
  1785. DomainTreeNode<T>* node)
  1786. {
  1787. DomainTreeNode<T>* uncle;
  1788. DomainTreeNode<T>* parent;
  1789. while (node != (*root).get() &&
  1790. ((parent = node->getParent())->getColor()) ==
  1791. DomainTreeNode<T>::RED) {
  1792. // Here, node->parent_ is not NULL and it is also red, so
  1793. // node->parent_->parent_ is also not NULL.
  1794. if (parent == parent->getParent()->getLeft()) {
  1795. uncle = parent->getParent()->getRight();
  1796. if (uncle != NULL && uncle->getColor() ==
  1797. DomainTreeNode<T>::RED) {
  1798. parent->setColor(DomainTreeNode<T>::BLACK);
  1799. uncle->setColor(DomainTreeNode<T>::BLACK);
  1800. parent->getParent()->setColor(DomainTreeNode<T>::RED);
  1801. node = parent->getParent();
  1802. } else {
  1803. if (node == parent->getRight()) {
  1804. node = parent;
  1805. leftRotate(root, node);
  1806. parent = node->getParent();
  1807. }
  1808. parent->setColor(DomainTreeNode<T>::BLACK);
  1809. parent->getParent()->setColor(DomainTreeNode<T>::RED);
  1810. rightRotate(root, parent->getParent());
  1811. }
  1812. } else {
  1813. uncle = parent->getParent()->getLeft();
  1814. if (uncle != NULL && uncle->getColor() ==
  1815. DomainTreeNode<T>::RED) {
  1816. parent->setColor(DomainTreeNode<T>::BLACK);
  1817. uncle->setColor(DomainTreeNode<T>::BLACK);
  1818. parent->getParent()->setColor(DomainTreeNode<T>::RED);
  1819. node = parent->getParent();
  1820. } else {
  1821. if (node == parent->getLeft()) {
  1822. node = parent;
  1823. rightRotate(root, node);
  1824. parent = node->getParent();
  1825. }
  1826. parent->setColor(DomainTreeNode<T>::BLACK);
  1827. parent->getParent()->setColor(DomainTreeNode<T>::RED);
  1828. leftRotate(root, parent->getParent());
  1829. }
  1830. }
  1831. }
  1832. (*root)->setColor(DomainTreeNode<T>::BLACK);
  1833. }
  1834. template <typename T>
  1835. DomainTreeNode<T>*
  1836. DomainTree<T>::leftRotate
  1837. (typename DomainTreeNode<T>::DomainTreeNodePtr* root,
  1838. DomainTreeNode<T>* node)
  1839. {
  1840. DomainTreeNode<T>* const right = node->getRight();
  1841. DomainTreeNode<T>* const rleft = right->getLeft();
  1842. node->right_ = rleft;
  1843. if (rleft != NULL) {
  1844. rleft->parent_ = node;
  1845. }
  1846. DomainTreeNode<T>* const parent = node->getParent();
  1847. right->parent_ = parent;
  1848. if (!node->isSubTreeRoot()) {
  1849. right->setSubTreeRoot(false);
  1850. if (node == parent->getLeft()) {
  1851. parent->left_ = right;
  1852. } else {
  1853. parent->right_ = right;
  1854. }
  1855. } else {
  1856. right->setSubTreeRoot(true);
  1857. *root = right;
  1858. }
  1859. right->left_ = node;
  1860. node->parent_ = right;
  1861. node->setSubTreeRoot(false);
  1862. return (node);
  1863. }
  1864. template <typename T>
  1865. DomainTreeNode<T>*
  1866. DomainTree<T>::rightRotate
  1867. (typename DomainTreeNode<T>::DomainTreeNodePtr* root,
  1868. DomainTreeNode<T>* node)
  1869. {
  1870. DomainTreeNode<T>* const left = node->getLeft();
  1871. DomainTreeNode<T>* const lright = left->getRight();
  1872. node->left_ = lright;
  1873. if (lright != NULL) {
  1874. lright->parent_ = node;
  1875. }
  1876. DomainTreeNode<T>* const parent = node->getParent();
  1877. left->parent_ = parent;
  1878. if (!node->isSubTreeRoot()) {
  1879. left->setSubTreeRoot(false);
  1880. if (node == parent->getRight()) {
  1881. parent->right_ = left;
  1882. } else {
  1883. parent->left_ = left;
  1884. }
  1885. } else {
  1886. left->setSubTreeRoot(true);
  1887. *root = left;
  1888. }
  1889. left->right_ = node;
  1890. node->parent_ = left;
  1891. node->setSubTreeRoot(false);
  1892. return (node);
  1893. }
  1894. template <typename T>
  1895. void
  1896. DomainTree<T>::dumpTree(std::ostream& os, unsigned int depth) const {
  1897. indent(os, depth);
  1898. os << "tree has " << node_count_ << " node(s)\n";
  1899. dumpTreeHelper(os, root_.get(), depth);
  1900. }
  1901. template <typename T>
  1902. void
  1903. DomainTree<T>::dumpTreeHelper(std::ostream& os,
  1904. const DomainTreeNode<T>* node,
  1905. unsigned int depth) const
  1906. {
  1907. if (node == NULL) {
  1908. indent(os, depth);
  1909. os << "NULL\n";
  1910. return;
  1911. }
  1912. indent(os, depth);
  1913. os << node->getLabels() << " ("
  1914. << ((node->getColor() == DomainTreeNode<T>::BLACK) ? "black" : "red")
  1915. << ")";
  1916. if (node->isEmpty()) {
  1917. os << " [invisible]";
  1918. }
  1919. if (node->isSubTreeRoot()) {
  1920. os << " [subtreeroot]";
  1921. }
  1922. os << "\n";
  1923. const DomainTreeNode<T>* down = node->getDown();
  1924. if (down != NULL) {
  1925. indent(os, depth + 1);
  1926. os << "begin down from " << node->getLabels() << "\n";
  1927. dumpTreeHelper(os, down, depth + 1);
  1928. indent(os, depth + 1);
  1929. os << "end down from " << node->getLabels() << "\n";
  1930. }
  1931. dumpTreeHelper(os, node->getLeft(), depth + 1);
  1932. dumpTreeHelper(os, node->getRight(), depth + 1);
  1933. }
  1934. template <typename T>
  1935. void
  1936. DomainTree<T>::indent(std::ostream& os, unsigned int depth) {
  1937. static const unsigned int INDENT_FOR_EACH_DEPTH = 5;
  1938. os << std::string(depth * INDENT_FOR_EACH_DEPTH, ' ');
  1939. }
  1940. template <typename T>
  1941. void
  1942. DomainTree<T>::dumpDot(std::ostream& os, bool show_pointers) const {
  1943. int nodecount = 0;
  1944. os << "digraph g {\n";
  1945. os << "node [shape = record,height=.1];\n";
  1946. dumpDotHelper(os, root_.get(), &nodecount, show_pointers);
  1947. os << "}\n";
  1948. }
  1949. template <typename T>
  1950. int
  1951. DomainTree<T>::dumpDotHelper(std::ostream& os,
  1952. const DomainTreeNode<T>* node,
  1953. int* nodecount, bool show_pointers) const
  1954. {
  1955. if (node == NULL) {
  1956. return 0;
  1957. }
  1958. int l = dumpDotHelper(os, node->getLeft(), nodecount, show_pointers);
  1959. int r = dumpDotHelper(os, node->getRight(), nodecount, show_pointers);
  1960. int d = dumpDotHelper(os, node->getDown(), nodecount, show_pointers);
  1961. *nodecount += 1;
  1962. os << "node" << *nodecount <<
  1963. "[label = \"<f0> |<f1> " << node->getLabels() <<
  1964. "|<f2>";
  1965. if (show_pointers) {
  1966. os << "|<f3> n=" << node << "|<f4> p=" << node->getParent();
  1967. }
  1968. os << "\"] [";
  1969. if (node->getColor() == DomainTreeNode<T>::RED) {
  1970. os << "color=red";
  1971. } else {
  1972. os << "color=black";
  1973. }
  1974. if (node->isSubTreeRoot()) {
  1975. os << ",penwidth=3";
  1976. }
  1977. if (node->isEmpty()) {
  1978. os << ",style=filled,fillcolor=lightgrey";
  1979. }
  1980. os << "];\n";
  1981. if (node->getLeft() != NULL) {
  1982. os << "\"node" << *nodecount << "\":f0 -> \"node" << l << "\":f1;\n";
  1983. }
  1984. if (node->getDown() != NULL) {
  1985. os << "\"node" << *nodecount << "\":f1 -> \"node" << d <<
  1986. "\":f1 [penwidth=5];\n";
  1987. }
  1988. if (node->getRight() != NULL) {
  1989. os << "\"node" << *nodecount << "\":f2 -> \"node" << r << "\":f1;\n";
  1990. }
  1991. return (*nodecount);
  1992. }
  1993. } // namespace memory
  1994. } // namespace datasrc
  1995. } // namespace isc
  1996. #endif // _DOMAINTREE_H
  1997. // Local Variables:
  1998. // mode: c++
  1999. // End: