domaintree.h 80 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133
  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. const DomainTreeNode<T>** node) const {
  1001. DomainTreeNodeChain<T> node_path;
  1002. const isc::dns::LabelSequence ls(name);
  1003. Result ret = (find<void*>(ls, node, node_path, NULL, NULL));
  1004. return (ret);
  1005. }
  1006. /// \brief Simple find, with node_path tracking
  1007. ///
  1008. /// Acts as described in the \ref find section.
  1009. Result find(const isc::dns::Name& name, const DomainTreeNode<T>** node,
  1010. DomainTreeNodeChain<T>& node_path) const
  1011. {
  1012. const isc::dns::LabelSequence ls(name);
  1013. Result ret = (find<void*>(ls, node, node_path, NULL, NULL));
  1014. return (ret);
  1015. }
  1016. /// \brief Simple find returning immutable node.
  1017. ///
  1018. /// Acts as described in the \ref find section, but returns immutable
  1019. /// node pointer.
  1020. template <typename CBARG>
  1021. Result find(const isc::dns::Name& name,
  1022. const DomainTreeNode<T>** node,
  1023. DomainTreeNodeChain<T>& node_path,
  1024. bool (*callback)(const DomainTreeNode<T>&, CBARG),
  1025. CBARG callback_arg) const
  1026. {
  1027. const isc::dns::LabelSequence ls(name);
  1028. Result ret = find(ls, node, node_path, callback,
  1029. callback_arg);
  1030. return (ret);
  1031. }
  1032. /// \brief Find with callback and node chain
  1033. /// \anchor callback
  1034. ///
  1035. /// This version of \c find() is specifically designed for the backend
  1036. /// of the \c InMemoryZoneFinder class, and implements all necessary
  1037. /// features for that purpose. Other applications shouldn't need these
  1038. /// additional features, and should normally use the simpler versions.
  1039. ///
  1040. /// This version of \c find() calls the callback whenever traversing (on
  1041. /// the way from root down the tree) a marked node on the way down through
  1042. /// the domain namespace (see \c DomainTreeNode::FLAG_CALLBACK).
  1043. ///
  1044. /// Also, this version takes a \c LabelSequence object, not a \c Name
  1045. /// object to be as efficient as possible; operations on the former
  1046. /// needed for the search are generally much more efficient than those
  1047. /// for the latter. Since \c Name objects are more commonly used
  1048. /// in other parts of the implementation, other versions take a \c Name
  1049. /// and convert it to \c LabelSequence. This conversion is cheap,
  1050. /// while the other direction isn't, and since there would be cases
  1051. /// where an implementation primarily handles \c LabelSequence objects
  1052. /// as an efficient representation of names, it would make most sense
  1053. /// to provide the interface that takes \c LabelSequence.
  1054. ///
  1055. /// If you return true from the callback, the search is stopped and a
  1056. /// PARTIALMATCH is returned with the given node. Note that this node
  1057. /// doesn't really need to be the one with longest possible match.
  1058. ///
  1059. /// The callback is not called for the node which matches exactly
  1060. /// (EXACTMATCH is returned). This is typically the last node in the
  1061. /// traversal during a successful search.
  1062. ///
  1063. /// This callback mechanism was designed with zone cut (delegation)
  1064. /// processing in mind. The marked nodes would be the ones at delegation
  1065. /// points. It is not expected that any other applications would need
  1066. /// callbacks; they should use the versions of find without callbacks.
  1067. /// The callbacks are not general functors for the same reason - we don't
  1068. /// expect it to be needed.
  1069. ///
  1070. /// Another special feature of this version is the ability to record
  1071. /// more detailed information regarding the search result.
  1072. ///
  1073. /// This information will be returned via the \c node_path
  1074. /// parameter, which is an object of class \c DomainTreeNodeChain.
  1075. /// The passed parameter must be empty if the label sequence is
  1076. /// absolute. If the label sequence is not absolute, then find()
  1077. /// will begin from the top of the node chain.
  1078. ///
  1079. /// On success, the node sequence stored in \c node_path will contain all
  1080. /// the ancestor nodes from the found node towards the root.
  1081. /// For example, if we look for o.w.y.d.e.f in the example \ref diagram,
  1082. /// \c node_path will contain w.y and d.e.f; the \c top() node of the
  1083. /// chain will be o, w.y and d.e.f will be stored below it.
  1084. ///
  1085. /// This feature can be used to get the absolute name for a node; to
  1086. /// do so, we need to travel upside from the node toward the root,
  1087. /// concatenating all ancestor labels. A node chain can also be
  1088. /// used to find the next and previous nodes of a given node in the
  1089. /// entire DomainTree; the \c nextNode() and \c previousNode()
  1090. /// methods take a node chain as a parameter.
  1091. ///
  1092. /// \exception isc::BadValue node_path is not empty.
  1093. ///
  1094. /// \param target_labels_orig Target to be found
  1095. /// \param node On success (either \c EXACTMATCH or \c PARTIALMATCH)
  1096. /// it will store a pointer to the matching node
  1097. /// \param node_path Other search details will be stored (see the
  1098. /// description)
  1099. /// \param callback If non- \c NULL, a call back function to be called
  1100. /// at marked nodes (see the description).
  1101. /// \param callback_arg A caller supplied argument to be passed to
  1102. /// \c callback.
  1103. ///
  1104. /// \return As in the description, but in case of callback returning
  1105. /// \c true, it returns immediately with the current node.
  1106. template <typename CBARG>
  1107. Result find(const isc::dns::LabelSequence& target_labels_orig,
  1108. const DomainTreeNode<T>** node,
  1109. DomainTreeNodeChain<T>& node_path,
  1110. bool (*callback)(const DomainTreeNode<T>&, CBARG),
  1111. CBARG callback_arg) const;
  1112. //@}
  1113. /// \brief return the next bigger node in DNSSEC order from a given node
  1114. /// chain.
  1115. ///
  1116. /// This method identifies the next bigger node of the node currently
  1117. /// referenced in \c node_path and returns it.
  1118. /// This method also updates the passed \c node_path so that it will store
  1119. /// the path for the returned next node.
  1120. /// It will be convenient when we want to iterate over the all nodes
  1121. /// of \c DomainTree; we can do this by calling this method repeatedly
  1122. /// starting from the root node.
  1123. ///
  1124. /// \note \c nextNode() will iterate over all the nodes in
  1125. /// DomainTree including empty nodes. If empty node isn't desired,
  1126. /// it's easy to add logic to check return node and keep invoking \c
  1127. /// nextNode() until the non-empty node is retrieved.
  1128. ///
  1129. /// \exception isc::BadValue node_path is empty.
  1130. ///
  1131. /// \param node_path A node chain that stores all the nodes along
  1132. /// the path from root to node.
  1133. ///
  1134. /// \return An \c DomainTreeNode that is next bigger than \c node;
  1135. /// if \c node is the largest, \c NULL will be returned.
  1136. const DomainTreeNode<T>*
  1137. nextNode(DomainTreeNodeChain<T>& node_path) const;
  1138. /// \brief return the next smaller node in DNSSEC order from a node
  1139. /// searched by DomainTree::find().
  1140. ///
  1141. /// This acts similarly to \c nextNode(), but it walks in the other
  1142. /// direction. But unlike \c nextNode(), this can start even if the
  1143. /// node requested by \c find() was not found. In that case, it will
  1144. /// identify the node that is previous to the queried name.
  1145. ///
  1146. /// \note \c previousNode() will iterate over all the nodes in DomainTree
  1147. /// including empty nodes. If empty node isn't desired, it's easy to add
  1148. /// logic to check return node and keep invoking \c previousNode() until the
  1149. /// non-empty node is retrieved.
  1150. ///
  1151. /// \exception isc::BadValue node_path is empty.
  1152. ///
  1153. /// \param node_path A node chain that stores all the nodes along the path
  1154. /// from root to node and the result of \c find(). This will get modified.
  1155. /// You should not use the node_path again except for repetitive calls
  1156. /// of this method.
  1157. ///
  1158. /// \return An \c DomainTreeNode that is next smaller than \c node;
  1159. /// if \c node is the smallest, \c NULL will be returned.
  1160. const DomainTreeNode<T>*
  1161. previousNode(DomainTreeNodeChain<T>& node_path) const;
  1162. /// \brief return the largest node in the tree of trees.
  1163. ///
  1164. /// \throw none
  1165. ///
  1166. /// \return A \c DomainTreeNode that is the largest node in the
  1167. /// tree. If there are no nodes, then \c NULL is returned.
  1168. const DomainTreeNode<T>* largestNode() const;
  1169. /// \brief Get the total number of nodes in the tree
  1170. ///
  1171. /// It includes nodes internally created as a result of adding a domain
  1172. /// name that is a subdomain of an existing node of the tree.
  1173. /// This function is mainly intended to be used for debugging.
  1174. uint32_t getNodeCount() const { return (node_count_); }
  1175. /// \name Debug function
  1176. //@{
  1177. /// \brief Print the nodes in the trees.
  1178. ///
  1179. /// \param os A \c std::ostream object to which the tree is printed.
  1180. /// \param depth A factor of the initial indentation. Each line
  1181. /// will begin with space character repeating <code>5 * depth</code>
  1182. /// times.
  1183. void dumpTree(std::ostream& os, unsigned int depth = 0) const;
  1184. /// \brief Print the nodes in the trees for processing with
  1185. /// Graphviz's dot.
  1186. ///
  1187. /// \param os A \c std::ostream object to which the tree is printed.
  1188. /// \param show_pointers Show node and parent pointers in the node
  1189. void dumpDot(std::ostream& os, bool show_pointers = false) const;
  1190. //@}
  1191. /// \name Modify functions
  1192. //@{
  1193. /// \brief Insert the domain name into the tree.
  1194. ///
  1195. /// It either finds an already existing node of the given name, or
  1196. /// inserts a new one if none exists yet. In any case, the \c
  1197. /// inserted_node parameter is set to point to that node. You can
  1198. /// fill data into it or modify it. So, if you don't know if a node
  1199. /// exists or not and you need to modify it, just call insert and
  1200. /// act by the result.
  1201. ///
  1202. /// Please note that the tree can add some empty nodes by itself, so
  1203. /// don't assume that if you didn't insert a node of that name it
  1204. /// doesn't exist.
  1205. ///
  1206. /// This method normally involves resource allocation. If it fails
  1207. /// the corresponding standard exception will be thrown.
  1208. ///
  1209. /// This method does not provide the strong exception guarantee in its
  1210. /// strict sense; if an exception is thrown in the middle of this
  1211. /// method, the internal structure may change. However, it should
  1212. /// still retain the same property as a mapping container before this
  1213. /// method is called. For example, the result of \c find() should be
  1214. /// the same. This method provides the weak exception guarantee in its
  1215. /// normal sense.
  1216. ///
  1217. /// \param mem_sgmt A \c MemorySegment object for allocating memory of
  1218. /// a new node to be inserted. Must be the same segment as that used
  1219. /// for creating the tree itself.
  1220. /// \param name The name to be inserted into the tree.
  1221. /// \param inserted_node This is an output parameter and is set to the
  1222. /// node.
  1223. ///
  1224. /// \return
  1225. /// - SUCCESS The node was added.
  1226. /// - ALREADYEXISTS There was already a node of that name, so it was not
  1227. /// added.
  1228. Result insert(util::MemorySegment& mem_sgmt, const isc::dns::Name& name,
  1229. DomainTreeNode<T>** inserted_node);
  1230. /// \brief Delete all tree nodes.
  1231. ///
  1232. /// \throw none.
  1233. ///
  1234. /// \param mem_sgmt The \c MemorySegment object used to insert the nodes
  1235. /// (which was also used for creating the tree due to the requirement of
  1236. /// \c inert()).
  1237. template <typename DataDeleter>
  1238. void deleteAllNodes(util::MemorySegment& mem_sgmt, DataDeleter deleter);
  1239. /// \brief Swaps two tree's contents.
  1240. ///
  1241. /// This and \c other trees must have been created with the same
  1242. /// memory segment (see the discussion in \c create()); otherwise the
  1243. /// behavior is undefined.
  1244. ///
  1245. /// This acts the same as many std::*.swap functions, exchanges the
  1246. /// contents. This doesn't throw anything.
  1247. void swap(DomainTree<T>& other) {
  1248. std::swap(root_, other.root_);
  1249. std::swap(node_count_, other.node_count_);
  1250. }
  1251. //@}
  1252. private:
  1253. /// \name DomainTree balance functions
  1254. //@{
  1255. void
  1256. insertRebalance(typename DomainTreeNode<T>::DomainTreeNodePtr* root,
  1257. DomainTreeNode<T>* node);
  1258. DomainTreeNode<T>*
  1259. rightRotate(typename DomainTreeNode<T>::DomainTreeNodePtr* root,
  1260. DomainTreeNode<T>* node);
  1261. DomainTreeNode<T>*
  1262. leftRotate(typename DomainTreeNode<T>::DomainTreeNodePtr* root,
  1263. DomainTreeNode<T>* node);
  1264. //@}
  1265. /// \name Helper functions
  1266. //@{
  1267. /// \brief delete tree whose root is equal to node
  1268. template <typename DataDeleter>
  1269. void deleteHelper(util::MemorySegment& mem_sgmt,
  1270. DomainTreeNode<T> *node,
  1271. const DataDeleter& deleter);
  1272. /// \brief Print the information of given DomainTreeNode.
  1273. void dumpTreeHelper(std::ostream& os, const DomainTreeNode<T>* node,
  1274. unsigned int depth) const;
  1275. /// \brief Print the information of given DomainTreeNode for dot.
  1276. int dumpDotHelper(std::ostream& os, const DomainTreeNode<T>* node,
  1277. int* nodecount, bool show_pointers) const;
  1278. /// \brief Indentation helper function for dumpTree
  1279. static void indent(std::ostream& os, unsigned int depth);
  1280. /// Split one node into two nodes for "prefix" and "suffix" parts of
  1281. /// the labels of the original node, respectively. The given node
  1282. /// will hold the prefix, while a newly created node will hold the prefix.
  1283. /// Note that the original node still represents the same domain name in
  1284. /// the entire tree. This ensures that a pointer to a node keeps its
  1285. /// semantics even if the tree structure is changed (as long as the node
  1286. /// itself remains valid).
  1287. void nodeFission(util::MemorySegment& mem_sgmt, DomainTreeNode<T>& node,
  1288. const isc::dns::LabelSequence& new_prefix,
  1289. const isc::dns::LabelSequence& new_suffix);
  1290. //@}
  1291. typename DomainTreeNode<T>::DomainTreeNodePtr root_;
  1292. /// the node count of current tree.
  1293. ///
  1294. /// Note: uint32_t may look awkward, but we intentionally choose it so
  1295. /// that needsReturnEmptyNode_ below won't make cause extra padding
  1296. /// in 64-bit machines (and we can minimize the total size of this class).
  1297. /// 2^32 - 1 should be a reasonable max of possible number of nodes.
  1298. uint32_t node_count_;
  1299. /// search policy for domaintree
  1300. const bool needsReturnEmptyNode_;
  1301. };
  1302. template <typename T>
  1303. DomainTree<T>::DomainTree(bool returnEmptyNode) :
  1304. root_(NULL),
  1305. node_count_(0),
  1306. needsReturnEmptyNode_(returnEmptyNode)
  1307. {
  1308. }
  1309. template <typename T>
  1310. DomainTree<T>::~DomainTree() {
  1311. assert(node_count_ == 0);
  1312. }
  1313. template <typename T>
  1314. template <typename DataDeleter>
  1315. void
  1316. DomainTree<T>::deleteHelper(util::MemorySegment& mem_sgmt,
  1317. DomainTreeNode<T>* root,
  1318. const DataDeleter& deleter)
  1319. {
  1320. while (root != NULL) {
  1321. // If there is a left, right or down node, walk into it and
  1322. // iterate.
  1323. if (root->getLeft() != NULL) {
  1324. DomainTreeNode<T>* node = root;
  1325. root = root->getLeft();
  1326. node->left_ = NULL;
  1327. } else if (root->getRight() != NULL) {
  1328. DomainTreeNode<T>* node = root;
  1329. root = root->getRight();
  1330. node->right_ = NULL;
  1331. } else if (root->getDown() != NULL) {
  1332. DomainTreeNode<T>* node = root;
  1333. root = root->getDown();
  1334. node->down_ = NULL;
  1335. } else {
  1336. // There are no left, right or down nodes, so we can
  1337. // free this one and go back to its parent.
  1338. DomainTreeNode<T>* node = root;
  1339. root = root->getParent();
  1340. deleter(node->data_.get());
  1341. DomainTreeNode<T>::destroy(mem_sgmt, node);
  1342. --node_count_;
  1343. }
  1344. }
  1345. }
  1346. template <typename T>
  1347. template <typename CBARG>
  1348. typename DomainTree<T>::Result
  1349. DomainTree<T>::find(const isc::dns::LabelSequence& target_labels_orig,
  1350. const DomainTreeNode<T>** target,
  1351. DomainTreeNodeChain<T>& node_path,
  1352. bool (*callback)(const DomainTreeNode<T>&, CBARG),
  1353. CBARG callback_arg) const
  1354. {
  1355. if (node_path.isEmpty() ^ target_labels_orig.isAbsolute()) {
  1356. isc_throw(isc::BadValue,
  1357. "DomainTree::find() is given mismatched node chain"
  1358. " and label sequence");
  1359. }
  1360. const DomainTreeNode<T>* node;
  1361. if (!node_path.isEmpty()) {
  1362. // Get the top node in the node chain
  1363. node = node_path.top();
  1364. // Start searching from its down pointer
  1365. node = node->getDown();
  1366. } else {
  1367. node = root_.get();
  1368. }
  1369. Result ret = NOTFOUND;
  1370. dns::LabelSequence target_labels(target_labels_orig);
  1371. while (node != NULL) {
  1372. node_path.last_compared_ = node;
  1373. node_path.last_comparison_ = target_labels.compare(node->getLabels());
  1374. const isc::dns::NameComparisonResult::NameRelation relation =
  1375. node_path.last_comparison_.getRelation();
  1376. if (relation == isc::dns::NameComparisonResult::EQUAL) {
  1377. if (needsReturnEmptyNode_ || !node->isEmpty()) {
  1378. node_path.push(node);
  1379. *target = node;
  1380. ret = EXACTMATCH;
  1381. }
  1382. break;
  1383. } else if (relation == isc::dns::NameComparisonResult::NONE) {
  1384. // If the two labels have no hierarchical relationship in terms
  1385. // of matching, we should continue the binary search.
  1386. node = (node_path.last_comparison_.getOrder() < 0) ?
  1387. node->getLeft() : node->getRight();
  1388. } else {
  1389. if (relation == isc::dns::NameComparisonResult::SUBDOMAIN) {
  1390. if (needsReturnEmptyNode_ || !node->isEmpty()) {
  1391. ret = PARTIALMATCH;
  1392. *target = node;
  1393. if (callback != NULL &&
  1394. node->getFlag(DomainTreeNode<T>::FLAG_CALLBACK)) {
  1395. if ((callback)(*node, callback_arg)) {
  1396. break;
  1397. }
  1398. }
  1399. }
  1400. node_path.push(node);
  1401. target_labels.stripRight(
  1402. node_path.last_comparison_.getCommonLabels());
  1403. node = node->getDown();
  1404. } else {
  1405. break;
  1406. }
  1407. }
  1408. }
  1409. return (ret);
  1410. }
  1411. template <typename T>
  1412. const DomainTreeNode<T>*
  1413. DomainTree<T>::nextNode(DomainTreeNodeChain<T>& node_path) const {
  1414. if (node_path.isEmpty()) {
  1415. isc_throw(isc::BadValue,
  1416. "DomainTree::nextNode is given an empty chain");
  1417. }
  1418. const DomainTreeNode<T>* node = node_path.top();
  1419. // if node has sub domain, the next domain is the smallest
  1420. // domain in sub domain tree
  1421. const DomainTreeNode<T>* down = node->getDown();
  1422. if (down != NULL) {
  1423. const DomainTreeNode<T>* left_most = down;
  1424. while (left_most->getLeft() != NULL) {
  1425. left_most = left_most->getLeft();
  1426. }
  1427. node_path.push(left_most);
  1428. return (left_most);
  1429. }
  1430. // try to find a successor.
  1431. // if no successor found move to up level, the next successor
  1432. // is the successor of up node in the up level tree, if
  1433. // up node doesn't have successor we gonna keep moving to up
  1434. // level
  1435. while (!node_path.isEmpty()) {
  1436. const DomainTreeNode<T>* up_node_successor =
  1437. node_path.top()->successor();
  1438. node_path.pop();
  1439. if (up_node_successor != NULL) {
  1440. node_path.push(up_node_successor);
  1441. return (up_node_successor);
  1442. }
  1443. }
  1444. return (NULL);
  1445. }
  1446. template <typename T>
  1447. const DomainTreeNode<T>*
  1448. DomainTree<T>::previousNode(DomainTreeNodeChain<T>& node_path) const {
  1449. if (getNodeCount() == 0) {
  1450. // Special case for empty trees. It would look every time like
  1451. // we didn't search, because the last compared is empty. This is
  1452. // a slight hack and not perfect, but this is better than throwing
  1453. // on empty tree. And we probably won't meet an empty tree in practice
  1454. // anyway.
  1455. return (NULL);
  1456. }
  1457. if (node_path.last_compared_ == NULL) {
  1458. isc_throw(isc::BadValue,
  1459. "DomainTree::previousNode() called before find()");
  1460. }
  1461. // If the relation isn't EQUAL, it means the find was called previously
  1462. // and didn't find the exact node. Therefore we need to locate the place
  1463. // to start iterating the chain of domains.
  1464. //
  1465. // The logic here is not too complex, we just need to take care to handle
  1466. // all the cases and decide where to go from there.
  1467. switch (node_path.last_comparison_.getRelation()) {
  1468. case dns::NameComparisonResult::COMMONANCESTOR:
  1469. case dns::NameComparisonResult::NONE:
  1470. // We compared with a leaf in the tree and wanted to go to one of
  1471. // the children. But the child was not there. It now depends on the
  1472. // direction in which we wanted to go.
  1473. if (node_path.last_comparison_.getOrder() < 0) {
  1474. // We wanted to go left. So the one we compared with is
  1475. // the one higher than we wanted. If we just put it into
  1476. // the node_path, then the following algorithm below will find
  1477. // the smaller one.
  1478. //
  1479. // This is exactly the same as with superdomain below.
  1480. // Therefore, we just fall through to the next case.
  1481. } else {
  1482. // We wanted to go right. That means we want to output the
  1483. // one which is the largest in the tree defined by the
  1484. // compared one (it is either the compared one, or some
  1485. // subdomain of it). There probably is not an easy trick
  1486. // for this, so we just find the correct place.
  1487. const DomainTreeNode<T>* current(node_path.last_compared_);
  1488. while (current != NULL) {
  1489. node_path.push(current);
  1490. // Go a level down and as much right there as possible
  1491. current = current->getDown();
  1492. if (current != NULL) {
  1493. const DomainTreeNode<T>* right;
  1494. while ((right = current->getRight()) != NULL) {
  1495. current = right;
  1496. }
  1497. }
  1498. }
  1499. // Now, the one on top of the path is the one we want. We
  1500. // return it now and leave it there, so we can search for
  1501. // previous of it the next time we'are called.
  1502. node_path.last_comparison_ =
  1503. dns::NameComparisonResult(0, 0,
  1504. dns::NameComparisonResult::EQUAL);
  1505. return (node_path.top());
  1506. }
  1507. // No break; here - we want to fall through. See above.
  1508. case dns::NameComparisonResult::SUPERDOMAIN:
  1509. // This is the case there's a "compressed" node and we looked for
  1510. // only part of it. The node itself is larger than we wanted, but
  1511. // if we put it to the node_path and then go one step left from it,
  1512. // we get the correct result.
  1513. node_path.push(node_path.last_compared_);
  1514. // Correct the comparison result, so we won't trigger this case
  1515. // next time previousNode is called. We already located the correct
  1516. // place to start. The value is partly nonsense, but that doesn't
  1517. // matter any more.
  1518. node_path.last_comparison_ =
  1519. dns::NameComparisonResult(0, 0,
  1520. dns::NameComparisonResult::EQUAL);
  1521. break;
  1522. case dns::NameComparisonResult::SUBDOMAIN:
  1523. // A subdomain means we returned the one above the searched one
  1524. // already and it is on top of the stack. This is was smaller
  1525. // than the one already, but we want to return yet smaller one.
  1526. // So we act as if it was EQUAL.
  1527. break;
  1528. case dns::NameComparisonResult::EQUAL:
  1529. // The find gave us an exact match or the previousNode was called
  1530. // already, which located the exact node. The rest of the function
  1531. // goes one domain left and returns it for us.
  1532. break;
  1533. }
  1534. // So, the node_path now contains the path to a node we want previous for.
  1535. // We just need to go one step left.
  1536. if (node_path.isEmpty()) {
  1537. // We got past the first one. So, we're returning NULL from
  1538. // now on.
  1539. return (NULL);
  1540. }
  1541. const DomainTreeNode<T>* node(node_path.top());
  1542. // Try going left in this tree
  1543. node = node->predecessor();
  1544. if (node == NULL) {
  1545. // We are the smallest ones in this tree. We go one level
  1546. // up. That one is the smaller one than us.
  1547. node_path.pop();
  1548. if (node_path.isEmpty()) {
  1549. // We're past the first one
  1550. return (NULL);
  1551. } else {
  1552. return (node_path.top());
  1553. }
  1554. }
  1555. // Exchange the node at the top of the path, as we move horizontaly
  1556. // through the domain tree
  1557. node_path.pop();
  1558. node_path.push(node);
  1559. // Try going as deep as possible, keeping on the right side of the trees
  1560. const DomainTreeNode<T>* down;
  1561. while ((down = node->getDown()) != NULL) {
  1562. // Move to the tree below
  1563. node = down;
  1564. if (node != NULL) {
  1565. // And get as much to the right of the tree as possible
  1566. const DomainTreeNode<T>* right;
  1567. while ((right = node->getRight()) != NULL) {
  1568. node = right;
  1569. }
  1570. }
  1571. // Now, we found the right-most node in the sub-tree, we need to
  1572. // include it in the path
  1573. node_path.push(node);
  1574. }
  1575. // Now, if the current node has no down_ pointer any more, it's the
  1576. // correct one.
  1577. return (node);
  1578. }
  1579. template <typename T>
  1580. const DomainTreeNode<T>*
  1581. DomainTree<T>::largestNode() const {
  1582. const DomainTreeNode<T>* node = root_.get();
  1583. while (node != NULL) {
  1584. // We go right first, then down.
  1585. if (node->getRight() != NULL) {
  1586. node = node->getRight();
  1587. } else if (node->getDown() != NULL) {
  1588. node = node->getDown();
  1589. } else {
  1590. break;
  1591. }
  1592. }
  1593. return (node);
  1594. }
  1595. template <typename T>
  1596. typename DomainTree<T>::Result
  1597. DomainTree<T>::insert(util::MemorySegment& mem_sgmt,
  1598. const isc::dns::Name& target_name,
  1599. DomainTreeNode<T>** new_node)
  1600. {
  1601. DomainTreeNode<T>* parent = NULL;
  1602. DomainTreeNode<T>* current = root_.get();
  1603. DomainTreeNode<T>* up_node = NULL;
  1604. isc::dns::LabelSequence target_labels(target_name);
  1605. int order = -1;
  1606. // For possible LabelSequence serialization we always store labels data
  1607. // in the separate local buffer.
  1608. uint8_t labels_buf[dns::LabelSequence::MAX_SERIALIZED_LENGTH];
  1609. while (current != NULL) {
  1610. const dns::LabelSequence current_labels(
  1611. dns::LabelSequence(current->getLabels(), labels_buf));
  1612. const isc::dns::NameComparisonResult compare_result =
  1613. target_labels.compare(current_labels);
  1614. const isc::dns::NameComparisonResult::NameRelation relation =
  1615. compare_result.getRelation();
  1616. if (relation == isc::dns::NameComparisonResult::EQUAL) {
  1617. if (new_node != NULL) {
  1618. *new_node = current;
  1619. }
  1620. return (ALREADYEXISTS);
  1621. } else if (relation == isc::dns::NameComparisonResult::NONE) {
  1622. parent = current;
  1623. order = compare_result.getOrder();
  1624. current = order < 0 ? current->getLeft() : current->getRight();
  1625. } else if (relation == isc::dns::NameComparisonResult::SUBDOMAIN) {
  1626. // insert sub domain to sub tree
  1627. parent = NULL;
  1628. up_node = current;
  1629. target_labels.stripRight(compare_result.getCommonLabels());
  1630. current = current->getDown();
  1631. } else {
  1632. // The number of labels in common is fewer than the number of
  1633. // labels at the current node, so the current node must be
  1634. // adjusted to have just the common suffix, and a down pointer
  1635. // made to a new tree.
  1636. dns::LabelSequence common_ancestor = target_labels;
  1637. common_ancestor.stripLeft(target_labels.getLabelCount() -
  1638. compare_result.getCommonLabels());
  1639. dns::LabelSequence new_prefix = current_labels;
  1640. new_prefix.stripRight(compare_result.getCommonLabels());
  1641. nodeFission(mem_sgmt, *current, new_prefix, common_ancestor);
  1642. current = current->getParent();
  1643. }
  1644. }
  1645. typename DomainTreeNode<T>::DomainTreeNodePtr* current_root =
  1646. (up_node != NULL) ? &(up_node->down_) : &root_;
  1647. // Once a new node is created, no exception will be thrown until the end
  1648. // of the function, so we can simply create and hold a new node pointer.
  1649. DomainTreeNode<T>* node = DomainTreeNode<T>::create(mem_sgmt,
  1650. target_labels);
  1651. node->parent_ = parent;
  1652. if (parent == NULL) {
  1653. *current_root = node;
  1654. // node is the new root of sub tree, so its init color is BLACK
  1655. node->setColor(DomainTreeNode<T>::BLACK);
  1656. node->setSubTreeRoot(true);
  1657. node->parent_ = up_node;
  1658. } else if (order < 0) {
  1659. node->setSubTreeRoot(false);
  1660. parent->left_ = node;
  1661. } else {
  1662. node->setSubTreeRoot(false);
  1663. parent->right_ = node;
  1664. }
  1665. insertRebalance(current_root, node);
  1666. if (new_node != NULL) {
  1667. *new_node = node;
  1668. }
  1669. ++node_count_;
  1670. return (SUCCESS);
  1671. }
  1672. template <typename T>
  1673. template <typename DataDeleter>
  1674. void
  1675. DomainTree<T>::deleteAllNodes(util::MemorySegment& mem_sgmt,
  1676. DataDeleter deleter)
  1677. {
  1678. deleteHelper(mem_sgmt, root_.get(), deleter);
  1679. root_ = NULL;
  1680. }
  1681. template <typename T>
  1682. void
  1683. DomainTree<T>::nodeFission(util::MemorySegment& mem_sgmt,
  1684. DomainTreeNode<T>& node,
  1685. const isc::dns::LabelSequence& new_prefix,
  1686. const isc::dns::LabelSequence& new_suffix)
  1687. {
  1688. // Create and reset the labels.
  1689. // Once a new node is created, no exception will be thrown until
  1690. // the end of the function, and it will keep consistent behavior
  1691. // (i.e., a weak form of strong exception guarantee) even if code
  1692. // after the call to this function throws an exception.
  1693. DomainTreeNode<T>* up_node = DomainTreeNode<T>::create(mem_sgmt,
  1694. new_suffix);
  1695. node.resetLabels(new_prefix);
  1696. up_node->parent_ = node.getParent();
  1697. if (node.getParent() != NULL) {
  1698. if (node.getParent()->getLeft() == &node) {
  1699. node.getParent()->left_ = up_node;
  1700. } else if (node.getParent()->getRight() == &node) {
  1701. node.getParent()->right_ = up_node;
  1702. } else {
  1703. node.getParent()->down_ = up_node;
  1704. }
  1705. } else {
  1706. root_ = up_node;
  1707. }
  1708. up_node->down_ = &node;
  1709. node.parent_ = up_node;
  1710. // inherit the left/right pointers from the original node, and set
  1711. // the original node's left/right pointers to NULL.
  1712. up_node->left_ = node.getLeft();
  1713. if (node.getLeft() != NULL) {
  1714. node.getLeft()->parent_ = up_node;
  1715. }
  1716. up_node->right_ = node.getRight();
  1717. if (node.getRight() != NULL) {
  1718. node.getRight()->parent_ = up_node;
  1719. }
  1720. node.left_ = NULL;
  1721. node.right_ = NULL;
  1722. // set color of both nodes; the initial subtree node color is BLACK
  1723. up_node->setColor(node.getColor());
  1724. node.setColor(DomainTreeNode<T>::BLACK);
  1725. // set the subtree root flag of both nodes
  1726. up_node->setSubTreeRoot(node.isSubTreeRoot());
  1727. node.setSubTreeRoot(true);
  1728. ++node_count_;
  1729. }
  1730. template <typename T>
  1731. void
  1732. DomainTree<T>::insertRebalance
  1733. (typename DomainTreeNode<T>::DomainTreeNodePtr* root,
  1734. DomainTreeNode<T>* node)
  1735. {
  1736. DomainTreeNode<T>* uncle;
  1737. DomainTreeNode<T>* parent;
  1738. while (node != (*root).get() &&
  1739. ((parent = node->getParent())->getColor()) ==
  1740. DomainTreeNode<T>::RED) {
  1741. // Here, node->parent_ is not NULL and it is also red, so
  1742. // node->parent_->parent_ is also not NULL.
  1743. if (parent == parent->getParent()->getLeft()) {
  1744. uncle = parent->getParent()->getRight();
  1745. if (uncle != NULL && uncle->getColor() ==
  1746. DomainTreeNode<T>::RED) {
  1747. parent->setColor(DomainTreeNode<T>::BLACK);
  1748. uncle->setColor(DomainTreeNode<T>::BLACK);
  1749. parent->getParent()->setColor(DomainTreeNode<T>::RED);
  1750. node = parent->getParent();
  1751. } else {
  1752. if (node == parent->getRight()) {
  1753. node = parent;
  1754. leftRotate(root, node);
  1755. parent = node->getParent();
  1756. }
  1757. parent->setColor(DomainTreeNode<T>::BLACK);
  1758. parent->getParent()->setColor(DomainTreeNode<T>::RED);
  1759. rightRotate(root, parent->getParent());
  1760. }
  1761. } else {
  1762. uncle = parent->getParent()->getLeft();
  1763. if (uncle != NULL && uncle->getColor() ==
  1764. DomainTreeNode<T>::RED) {
  1765. parent->setColor(DomainTreeNode<T>::BLACK);
  1766. uncle->setColor(DomainTreeNode<T>::BLACK);
  1767. parent->getParent()->setColor(DomainTreeNode<T>::RED);
  1768. node = parent->getParent();
  1769. } else {
  1770. if (node == parent->getLeft()) {
  1771. node = parent;
  1772. rightRotate(root, node);
  1773. parent = node->getParent();
  1774. }
  1775. parent->setColor(DomainTreeNode<T>::BLACK);
  1776. parent->getParent()->setColor(DomainTreeNode<T>::RED);
  1777. leftRotate(root, parent->getParent());
  1778. }
  1779. }
  1780. }
  1781. (*root)->setColor(DomainTreeNode<T>::BLACK);
  1782. }
  1783. template <typename T>
  1784. DomainTreeNode<T>*
  1785. DomainTree<T>::leftRotate
  1786. (typename DomainTreeNode<T>::DomainTreeNodePtr* root,
  1787. DomainTreeNode<T>* node)
  1788. {
  1789. DomainTreeNode<T>* const right = node->getRight();
  1790. DomainTreeNode<T>* const rleft = right->getLeft();
  1791. node->right_ = rleft;
  1792. if (rleft != NULL) {
  1793. rleft->parent_ = node;
  1794. }
  1795. DomainTreeNode<T>* const parent = node->getParent();
  1796. right->parent_ = parent;
  1797. if (!node->isSubTreeRoot()) {
  1798. right->setSubTreeRoot(false);
  1799. if (node == parent->getLeft()) {
  1800. parent->left_ = right;
  1801. } else {
  1802. parent->right_ = right;
  1803. }
  1804. } else {
  1805. right->setSubTreeRoot(true);
  1806. *root = right;
  1807. }
  1808. right->left_ = node;
  1809. node->parent_ = right;
  1810. node->setSubTreeRoot(false);
  1811. return (node);
  1812. }
  1813. template <typename T>
  1814. DomainTreeNode<T>*
  1815. DomainTree<T>::rightRotate
  1816. (typename DomainTreeNode<T>::DomainTreeNodePtr* root,
  1817. DomainTreeNode<T>* node)
  1818. {
  1819. DomainTreeNode<T>* const left = node->getLeft();
  1820. DomainTreeNode<T>* const lright = left->getRight();
  1821. node->left_ = lright;
  1822. if (lright != NULL) {
  1823. lright->parent_ = node;
  1824. }
  1825. DomainTreeNode<T>* const parent = node->getParent();
  1826. left->parent_ = parent;
  1827. if (!node->isSubTreeRoot()) {
  1828. left->setSubTreeRoot(false);
  1829. if (node == parent->getRight()) {
  1830. parent->right_ = left;
  1831. } else {
  1832. parent->left_ = left;
  1833. }
  1834. } else {
  1835. left->setSubTreeRoot(true);
  1836. *root = left;
  1837. }
  1838. left->right_ = node;
  1839. node->parent_ = left;
  1840. node->setSubTreeRoot(false);
  1841. return (node);
  1842. }
  1843. template <typename T>
  1844. void
  1845. DomainTree<T>::dumpTree(std::ostream& os, unsigned int depth) const {
  1846. indent(os, depth);
  1847. os << "tree has " << node_count_ << " node(s)\n";
  1848. dumpTreeHelper(os, root_.get(), depth);
  1849. }
  1850. template <typename T>
  1851. void
  1852. DomainTree<T>::dumpTreeHelper(std::ostream& os,
  1853. const DomainTreeNode<T>* node,
  1854. unsigned int depth) const
  1855. {
  1856. if (node == NULL) {
  1857. indent(os, depth);
  1858. os << "NULL\n";
  1859. return;
  1860. }
  1861. indent(os, depth);
  1862. os << node->getLabels() << " ("
  1863. << ((node->getColor() == DomainTreeNode<T>::BLACK) ? "black" : "red")
  1864. << ")";
  1865. if (node->isEmpty()) {
  1866. os << " [invisible]";
  1867. }
  1868. if (node->isSubTreeRoot()) {
  1869. os << " [subtreeroot]";
  1870. }
  1871. os << "\n";
  1872. const DomainTreeNode<T>* down = node->getDown();
  1873. if (down != NULL) {
  1874. indent(os, depth + 1);
  1875. os << "begin down from " << node->getLabels() << "\n";
  1876. dumpTreeHelper(os, down, depth + 1);
  1877. indent(os, depth + 1);
  1878. os << "end down from " << node->getLabels() << "\n";
  1879. }
  1880. dumpTreeHelper(os, node->getLeft(), depth + 1);
  1881. dumpTreeHelper(os, node->getRight(), depth + 1);
  1882. }
  1883. template <typename T>
  1884. void
  1885. DomainTree<T>::indent(std::ostream& os, unsigned int depth) {
  1886. static const unsigned int INDENT_FOR_EACH_DEPTH = 5;
  1887. os << std::string(depth * INDENT_FOR_EACH_DEPTH, ' ');
  1888. }
  1889. template <typename T>
  1890. void
  1891. DomainTree<T>::dumpDot(std::ostream& os, bool show_pointers) const {
  1892. int nodecount = 0;
  1893. os << "digraph g {\n";
  1894. os << "node [shape = record,height=.1];\n";
  1895. dumpDotHelper(os, root_.get(), &nodecount, show_pointers);
  1896. os << "}\n";
  1897. }
  1898. template <typename T>
  1899. int
  1900. DomainTree<T>::dumpDotHelper(std::ostream& os,
  1901. const DomainTreeNode<T>* node,
  1902. int* nodecount, bool show_pointers) const
  1903. {
  1904. if (node == NULL) {
  1905. return 0;
  1906. }
  1907. int l = dumpDotHelper(os, node->getLeft(), nodecount, show_pointers);
  1908. int r = dumpDotHelper(os, node->getRight(), nodecount, show_pointers);
  1909. int d = dumpDotHelper(os, node->getDown(), nodecount, show_pointers);
  1910. *nodecount += 1;
  1911. os << "node" << *nodecount <<
  1912. "[label = \"<f0> |<f1> " << node->getLabels() <<
  1913. "|<f2>";
  1914. if (show_pointers) {
  1915. os << "|<f3> n=" << node << "|<f4> p=" << node->getParent();
  1916. }
  1917. os << "\"] [";
  1918. if (node->getColor() == DomainTreeNode<T>::RED) {
  1919. os << "color=red";
  1920. } else {
  1921. os << "color=black";
  1922. }
  1923. if (node->isSubTreeRoot()) {
  1924. os << ",penwidth=3";
  1925. }
  1926. if (node->isEmpty()) {
  1927. os << ",style=filled,fillcolor=lightgrey";
  1928. }
  1929. os << "];\n";
  1930. if (node->getLeft() != NULL) {
  1931. os << "\"node" << *nodecount << "\":f0 -> \"node" << l << "\":f1;\n";
  1932. }
  1933. if (node->getDown() != NULL) {
  1934. os << "\"node" << *nodecount << "\":f1 -> \"node" << d <<
  1935. "\":f1 [penwidth=5];\n";
  1936. }
  1937. if (node->getRight() != NULL) {
  1938. os << "\"node" << *nodecount << "\":f2 -> \"node" << r << "\":f1;\n";
  1939. }
  1940. return (*nodecount);
  1941. }
  1942. } // namespace memory
  1943. } // namespace datasrc
  1944. } // namespace isc
  1945. #endif // _DOMAINTREE_H
  1946. // Local Variables:
  1947. // mode: c++
  1948. // End: