domaintree.h 81 KB

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