messagerenderer.cc 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390
  1. // Copyright (C) 2009 Internet Systems Consortium, Inc. ("ISC")
  2. //
  3. // Permission to use, copy, modify, and/or distribute this software for any
  4. // purpose with or without fee is hereby granted, provided that the above
  5. // copyright notice and this permission notice appear in all copies.
  6. //
  7. // THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES WITH
  8. // REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
  9. // AND FITNESS. IN NO EVENT SHALL ISC BE LIABLE FOR ANY SPECIAL, DIRECT,
  10. // INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
  11. // LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE
  12. // OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
  13. // PERFORMANCE OF THIS SOFTWARE.
  14. #include <exceptions/exceptions.h>
  15. #include <util/buffer.h>
  16. #include <dns/name.h>
  17. #include <dns/name_internal.h>
  18. #include <dns/labelsequence.h>
  19. #include <dns/messagerenderer.h>
  20. #include <boost/static_assert.hpp>
  21. #include <limits>
  22. #include <cassert>
  23. #include <vector>
  24. using namespace std;
  25. using namespace isc::util;
  26. using isc::dns::name::internal::maptolower;
  27. namespace isc {
  28. namespace dns {
  29. namespace { // hide internal-only names from the public namespaces
  30. ///
  31. /// \brief The \c OffsetItem class represents a pointer to a name
  32. /// rendered in the internal buffer for the \c MessageRendererImpl object.
  33. ///
  34. /// A \c MessageRendererImpl object maintains a set of \c OffsetItem
  35. /// objects in a hash table, and searches the table for the position of the
  36. /// longest match (ancestor) name against each new name to be rendered into
  37. /// the buffer.
  38. struct OffsetItem {
  39. OffsetItem(size_t hash, size_t pos, size_t len) :
  40. hash_(hash), pos_(pos), len_(len)
  41. {}
  42. /// The hash value for the stored name calculated by LabelSequence.getHash.
  43. /// This will help make name comparison in \c NameCompare more efficient.
  44. size_t hash_;
  45. /// The position (offset from the beginning) in the buffer where the
  46. /// name starts.
  47. uint16_t pos_;
  48. /// The length of the corresponding sequence (which is a domain name).
  49. uint16_t len_;
  50. };
  51. /// \brief The \c NameCompare class is a functor that checks equality
  52. /// between the name corresponding to an \c OffsetItem object and the name
  53. /// consists of labels represented by a \c LabelSequence object.
  54. ///
  55. /// Template parameter CASE_SENSITIVE determines whether to ignore the case
  56. /// of the names. This policy doesn't change throughout the lifetime of
  57. /// this object, so we separate these using template to avoid unnecessary
  58. /// condition check.
  59. template <bool CASE_SENSITIVE>
  60. struct NameCompare {
  61. /// \brief Constructor
  62. ///
  63. /// \param buffer The buffer for rendering used in the caller renderer
  64. /// \param name_buf An input buffer storing the wire-format data of the
  65. /// name to be newly rendered (and only that data).
  66. /// \param hash The hash value for the name.
  67. NameCompare(const OutputBuffer& buffer, InputBuffer& name_buf,
  68. size_t hash) :
  69. buffer_(&buffer), name_buf_(&name_buf), hash_(hash)
  70. {}
  71. bool operator()(const OffsetItem& item) const {
  72. // Trivial inequality check. If either the hash or the total length
  73. // doesn't match, the names are obviously different.
  74. if (item.hash_ != hash_ || item.len_ != name_buf_->getLength()) {
  75. return (false);
  76. }
  77. // Compare the name data, character-by-character.
  78. // item_pos keeps track of the position in the buffer corresponding to
  79. // the character to compare. item_label_len is the number of
  80. // characters in the labels where the character pointed by item_pos
  81. // belongs. When it reaches zero, nextPosition() identifies the
  82. // position for the subsequent label, taking into account name
  83. // compression, and resets item_label_len to the length of the new
  84. // label.
  85. name_buf_->setPosition(0); // buffer can be reused, so reset position
  86. uint16_t item_pos = item.pos_;
  87. uint16_t item_label_len = 0;
  88. for (size_t i = 0; i < item.len_; ++i, ++item_pos) {
  89. item_pos = nextPosition(*buffer_, item_pos, item_label_len);
  90. const unsigned char ch1 = (*buffer_)[item_pos];
  91. const unsigned char ch2 = name_buf_->readUint8();
  92. if (CASE_SENSITIVE) {
  93. if (ch1 != ch2) {
  94. return (false);
  95. }
  96. } else {
  97. if (maptolower[ch1] != maptolower[ch2]) {
  98. return (false);
  99. }
  100. }
  101. }
  102. return (true);
  103. }
  104. private:
  105. uint16_t nextPosition(const OutputBuffer& buffer,
  106. uint16_t pos, uint16_t& llen) const
  107. {
  108. if (llen == 0) {
  109. size_t i = 0;
  110. while ((buffer[pos] & Name::COMPRESS_POINTER_MARK8) ==
  111. Name::COMPRESS_POINTER_MARK8) {
  112. pos = (buffer[pos] & ~Name::COMPRESS_POINTER_MARK8) *
  113. 256 + buffer[pos + 1];
  114. // This loop should stop as long as the buffer has been
  115. // constructed validly and the search/insert argument is based
  116. // on a valid name, which is an assumption for this class.
  117. // But we'll abort if a bug could cause an infinite loop.
  118. i += 2;
  119. assert(i < Name::MAX_WIRE);
  120. }
  121. llen = buffer[pos];
  122. } else {
  123. --llen;
  124. }
  125. return (pos);
  126. }
  127. const OutputBuffer* buffer_;
  128. InputBuffer* name_buf_;
  129. const size_t hash_;
  130. };
  131. }
  132. ///
  133. /// \brief The \c MessageRendererImpl class is the actual implementation of
  134. /// \c MessageRenderer.
  135. ///
  136. /// The implementation is hidden from applications. We can refer to specific
  137. /// members of this class only within the implementation source file.
  138. ///
  139. /// It internally holds a hash table for OffsetItem objects corresponding
  140. /// to portions of names rendered in this renderer. The offset information
  141. /// is used to compress subsequent names to be rendered.
  142. struct MessageRenderer::MessageRendererImpl {
  143. // The size of hash buckets and number of hash entries per bucket for
  144. // which space is preallocated and kept reserved for subsequent rendering
  145. // to provide better performance. These values are derived from the
  146. // BIND 9 implementation that uses a similar hash table.
  147. static const size_t BUCKETS = 64;
  148. static const size_t RESERVED_ITEMS = 16;
  149. static const uint16_t NO_OFFSET = 65535; // used as a marker of 'not found'
  150. /// \brief Constructor
  151. MessageRendererImpl() :
  152. msglength_limit_(512), truncated_(false),
  153. compress_mode_(MessageRenderer::CASE_INSENSITIVE)
  154. {
  155. // Reserve some spaces for hash table items.
  156. for (size_t i = 0; i < BUCKETS; ++i) {
  157. table_[i].reserve(RESERVED_ITEMS);
  158. }
  159. }
  160. uint16_t findOffset(const OutputBuffer& buffer, InputBuffer& name_buf,
  161. size_t hash, bool case_sensitive)
  162. {
  163. // Find a matching entry, if any. We use some heuristics here: often
  164. // the same name appers consecutively (like repeating the same owner
  165. // name for a single RRset), so in case there's a collision in the
  166. // bucket it will be more likely to find it in the tail side of the
  167. // bucket.
  168. const size_t bucket_id = hash % BUCKETS;
  169. vector<OffsetItem>::const_reverse_iterator found;
  170. if (case_sensitive) {
  171. found = find_if(table_[bucket_id].rbegin(),
  172. table_[bucket_id].rend(),
  173. NameCompare<true>(buffer, name_buf, hash));
  174. } else {
  175. found = find_if(table_[bucket_id].rbegin(),
  176. table_[bucket_id].rend(),
  177. NameCompare<false>(buffer, name_buf, hash));
  178. }
  179. if (found != table_[bucket_id].rend()) {
  180. return (found->pos_);
  181. }
  182. return (NO_OFFSET);
  183. }
  184. void addOffset(size_t hash, size_t offset, size_t len) {
  185. table_[hash % BUCKETS].push_back(OffsetItem(hash, offset, len));
  186. }
  187. // The hash table for the (offset + position in the buffer) entries
  188. vector<OffsetItem> table_[BUCKETS];
  189. /// The maximum length of rendered data that can fit without
  190. /// truncation.
  191. uint16_t msglength_limit_;
  192. /// A boolean flag that indicates truncation has occurred while rendering
  193. /// the data.
  194. bool truncated_;
  195. /// The name compression mode.
  196. CompressMode compress_mode_;
  197. };
  198. MessageRenderer::MessageRenderer() :
  199. AbstractMessageRenderer(),
  200. impl_(new MessageRendererImpl)
  201. {}
  202. MessageRenderer::~MessageRenderer() {
  203. delete impl_;
  204. }
  205. void
  206. MessageRenderer::clear() {
  207. AbstractMessageRenderer::clear();
  208. impl_->msglength_limit_ = 512;
  209. impl_->truncated_ = false;
  210. impl_->compress_mode_ = CASE_INSENSITIVE;
  211. // Clear the hash table and name placeholders. We reserve the minimum
  212. // space for possible subsequent use of the renderer.
  213. for (size_t i = 0; i < MessageRendererImpl::BUCKETS; ++i) {
  214. if (impl_->table_[i].size() > MessageRendererImpl::RESERVED_ITEMS) {
  215. // Trim excessive capacity: reserve() invalidates the excessive
  216. // items, and swap ensures the new capacity is only reasonably
  217. // large for the reserved space.
  218. impl_->table_[i].reserve(MessageRendererImpl::RESERVED_ITEMS);
  219. vector<OffsetItem>(impl_->table_[i].begin(),
  220. impl_->table_[i].end()).swap(impl_->table_[i]);
  221. }
  222. impl_->table_[i].clear();
  223. }
  224. }
  225. size_t
  226. MessageRenderer::getLengthLimit() const {
  227. return (impl_->msglength_limit_);
  228. }
  229. void
  230. MessageRenderer::setLengthLimit(const size_t len) {
  231. impl_->msglength_limit_ = len;
  232. }
  233. bool
  234. MessageRenderer::isTruncated() const {
  235. return (impl_->truncated_);
  236. }
  237. void
  238. MessageRenderer::setTruncated() {
  239. impl_->truncated_ = true;
  240. }
  241. MessageRenderer::CompressMode
  242. MessageRenderer::getCompressMode() const {
  243. return (impl_->compress_mode_);
  244. }
  245. void
  246. MessageRenderer::setCompressMode(const CompressMode mode) {
  247. if (getLength() != 0) {
  248. isc_throw(isc::InvalidParameter,
  249. "compress mode cannot be changed during rendering");
  250. }
  251. impl_->compress_mode_ = mode;
  252. }
  253. void
  254. MessageRenderer::writeName(const Name& name, const bool compress) {
  255. LabelSequence sequence(name);
  256. const size_t nlabels = sequence.getLabelCount();
  257. size_t data_len;
  258. const char* data;
  259. // We'll store hash for label sequences derived from the name in order to
  260. // avoid calculating the hash twice.
  261. size_t seq_hashes[Name::MAX_LABELS];
  262. // Find the offset in the offset table whose name gives the longest
  263. // match against the name to be rendered.
  264. size_t nlabels_uncomp;
  265. uint16_t ptr_offset = MessageRendererImpl::NO_OFFSET;
  266. const bool case_sensitive = (impl_->compress_mode_ ==
  267. MessageRenderer::CASE_SENSITIVE);
  268. for (nlabels_uncomp = 0; nlabels_uncomp < nlabels; ++nlabels_uncomp) {
  269. data = sequence.getData(&data_len);
  270. if (data_len == 1) { // trailing dot.
  271. ++nlabels_uncomp;
  272. break;
  273. }
  274. seq_hashes[nlabels_uncomp] = sequence.getHash(impl_->compress_mode_);
  275. InputBuffer name_buf(data, data_len);
  276. ptr_offset = impl_->findOffset(getBuffer(), name_buf,
  277. seq_hashes[nlabels_uncomp],
  278. case_sensitive);
  279. if (ptr_offset != MessageRendererImpl::NO_OFFSET) {
  280. break;
  281. }
  282. sequence.stripLeft(1);
  283. }
  284. // Record the current offset before updating the offset table
  285. size_t offset = getLength();
  286. // Write uncompress part:
  287. if (nlabels_uncomp > 0 || !compress) {
  288. LabelSequence uncomp_sequence(name);
  289. if (compress && nlabels > nlabels_uncomp) {
  290. // If there's compressed part, strip off that part.
  291. uncomp_sequence.stripRight(nlabels - nlabels_uncomp);
  292. }
  293. data = uncomp_sequence.getData(&data_len);
  294. writeData(data, data_len);
  295. }
  296. // And write compression pointer if available:
  297. if (compress && ptr_offset != MessageRendererImpl::NO_OFFSET) {
  298. ptr_offset |= Name::COMPRESS_POINTER_MARK16;
  299. writeUint16(ptr_offset);
  300. }
  301. // Finally, record the offset and length for each uncompressed sequence
  302. // in the hash table. The renderer's buffer has just stored the
  303. // corresponding data, so we use the rendered data to get the length
  304. // of each label of the names.
  305. size_t seqlen = name.getLength();
  306. for (size_t i = 0; i < nlabels_uncomp; ++i) {
  307. const uint8_t label_len = getBuffer()[offset];
  308. if (label_len == 0) { // offset for root doesn't need to be stored.
  309. break;
  310. }
  311. if (offset > Name::MAX_COMPRESS_POINTER) {
  312. break;
  313. }
  314. // Store the tuple of <hash, offset, len> to the table. Note that we
  315. // already know the hash value for each name.
  316. impl_->addOffset(seq_hashes[i], offset, seqlen);
  317. offset += (label_len + 1);
  318. seqlen -= (label_len + 1);
  319. }
  320. }
  321. AbstractMessageRenderer::AbstractMessageRenderer() :
  322. local_buffer_(0), buffer_(&local_buffer_)
  323. {
  324. }
  325. void
  326. AbstractMessageRenderer::setBuffer(OutputBuffer* buffer) {
  327. if (buffer != NULL && buffer_->getLength() != 0) {
  328. isc_throw(isc::InvalidParameter,
  329. "MessageRenderer buffer cannot be set when in use");
  330. } if (buffer == NULL && buffer_ == &local_buffer_) {
  331. isc_throw(isc::InvalidParameter,
  332. "Default MessageRenderer buffer cannot be reset");
  333. }
  334. if (buffer == NULL) {
  335. // Reset to the default buffer, then clear other internal resources.
  336. // The order is important; we need to keep the used buffer intact.
  337. buffer_ = &local_buffer_;
  338. clear();
  339. } else {
  340. buffer_ = buffer;
  341. }
  342. }
  343. void
  344. AbstractMessageRenderer::clear() {
  345. buffer_->clear();
  346. }
  347. }
  348. }