buffer.h 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546
  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. #ifndef __BUFFER_H
  15. #define __BUFFER_H 1
  16. #include <stdlib.h>
  17. #include <cstring>
  18. #include <vector>
  19. #include <string.h>
  20. #include <stdint.h>
  21. #include <exceptions/exceptions.h>
  22. #include <boost/shared_ptr.hpp>
  23. namespace isc {
  24. namespace util {
  25. ///
  26. /// \brief A standard DNS module exception that is thrown if an out-of-range
  27. /// buffer operation is being performed.
  28. ///
  29. class InvalidBufferPosition : public Exception {
  30. public:
  31. InvalidBufferPosition(const char* file, size_t line, const char* what) :
  32. isc::Exception(file, line, what) {}
  33. };
  34. ///\brief The \c InputBuffer class is a buffer abstraction for manipulating
  35. /// read-only data.
  36. ///
  37. /// The main purpose of this class is to provide a safe placeholder for
  38. /// examining wire-format data received from a network.
  39. ///
  40. /// Applications normally use this class only in a limited situation: as an
  41. /// interface between legacy I/O operation (such as receiving data from a BSD
  42. /// socket) and the rest of the BIND10 DNS library. One common usage of this
  43. /// class for an application would therefore be something like this:
  44. ///
  45. /// \code unsigned char buf[1024];
  46. /// struct sockaddr addr;
  47. /// socklen_t addrlen = sizeof(addr);
  48. /// int cc = recvfrom(s, buf, sizeof(buf), 0, &addr, &addrlen);
  49. /// InputBuffer buffer(buf, cc);
  50. /// // pass the buffer to a DNS message object to parse the message \endcode
  51. ///
  52. /// Other BIND10 DNS classes will then use methods of this class to get access
  53. /// to the data, but the application normally doesn't have to care about the
  54. /// details.
  55. ///
  56. /// An \c InputBuffer object internally holds a reference to the given data,
  57. /// rather than make a local copy of the data. Also, it does not have an
  58. /// ownership of the given data. It is application's responsibility to ensure
  59. /// the data remains valid throughout the lifetime of the \c InputBuffer
  60. /// object. Likewise, this object generally assumes the data isn't modified
  61. /// throughout its lifetime; if the application modifies the data while this
  62. /// object retains a reference to it, the result is undefined. The application
  63. /// will also be responsible for releasing the data when it's not needed if it
  64. /// was dynamically acquired.
  65. ///
  66. /// This is a deliberate design choice: although it's safer to make a local
  67. /// copy of the given data on construction, it would cause unacceptable
  68. /// performance overhead, especially considering that a DNS message can be
  69. /// as large as a few KB. Alternatively, we could allow the object to allocate
  70. /// memory internally and expose it to the application to store network data
  71. /// in it. This is also a bad design, however, in that we would effectively
  72. /// break the abstraction employed in the class, and do so by publishing
  73. /// "read-only" stuff as a writable memory region. Since there doesn't seem to
  74. /// be a perfect solution, we have adopted what we thought a "least bad" one.
  75. ///
  76. /// Methods for reading data from the buffer generally work like an input
  77. /// stream: it begins with the head of the data, and once some length of data
  78. /// is read from the buffer, the next read operation will take place from the
  79. /// head of the unread data. An object of this class internally holds (a
  80. /// notion of) where the next read operation should start. We call it the
  81. /// <em>read position</em> in this document.
  82. class InputBuffer {
  83. public:
  84. ///
  85. /// \name Constructors and Destructor
  86. //@{
  87. /// \brief Constructor from variable length of data.
  88. ///
  89. /// It is caller's responsibility to ensure that the data is valid as long
  90. /// as the buffer exists.
  91. /// \param data A pointer to the data stored in the buffer.
  92. /// \param len The length of the data in bytes.
  93. InputBuffer(const void* data, size_t len) :
  94. position_(0), data_(static_cast<const uint8_t*>(data)), len_(len) {}
  95. //@}
  96. ///
  97. /// \name Getter Methods
  98. //@{
  99. /// \brief Return the length of the data stored in the buffer.
  100. size_t getLength() const { return (len_); }
  101. /// \brief Return the current read position.
  102. size_t getPosition() const { return (position_); }
  103. //@}
  104. ///
  105. /// \name Setter Methods
  106. ///
  107. //@{
  108. /// \brief Set the read position of the buffer to the given value.
  109. ///
  110. /// The new position must be in the valid range of the buffer; otherwise
  111. /// an exception of class \c isc::dns::InvalidBufferPosition will be thrown.
  112. /// \param position The new position (offset from the beginning of the
  113. /// buffer).
  114. void setPosition(size_t position) {
  115. if (position > len_) {
  116. throwError("position is too large");
  117. }
  118. position_ = position;
  119. }
  120. //@}
  121. ///
  122. /// \name Methods for reading data from the buffer.
  123. //@{
  124. /// \brief Read an unsigned 8-bit integer from the buffer and return it.
  125. ///
  126. /// If the remaining length of the buffer is smaller than 8-bit, an
  127. /// exception of class \c isc::dns::InvalidBufferPosition will be thrown.
  128. uint8_t readUint8() {
  129. if (position_ + sizeof(uint8_t) > len_) {
  130. throwError("read beyond end of buffer");
  131. }
  132. return (data_[position_++]);
  133. }
  134. /// \brief Read an unsigned 16-bit integer in network byte order from the
  135. /// buffer, convert it to host byte order, and return it.
  136. ///
  137. /// If the remaining length of the buffer is smaller than 16-bit, an
  138. /// exception of class \c isc::dns::InvalidBufferPosition will be thrown.
  139. uint16_t readUint16() {
  140. uint16_t data;
  141. const uint8_t* cp;
  142. if (position_ + sizeof(data) > len_) {
  143. throwError("read beyond end of buffer");
  144. }
  145. cp = &data_[position_];
  146. data = ((unsigned int)(cp[0])) << 8;
  147. data |= ((unsigned int)(cp[1]));
  148. position_ += sizeof(data);
  149. return (data);
  150. }
  151. /// \brief Read an unsigned 32-bit integer in network byte order from the
  152. /// buffer, convert it to host byte order, and return it.
  153. ///
  154. /// If the remaining length of the buffer is smaller than 32-bit, an
  155. /// exception of class \c isc::dns::InvalidBufferPosition will be thrown.
  156. uint32_t readUint32() {
  157. uint32_t data;
  158. const uint8_t* cp;
  159. if (position_ + sizeof(data) > len_) {
  160. throwError("read beyond end of buffer");
  161. }
  162. cp = &data_[position_];
  163. data = ((unsigned int)(cp[0])) << 24;
  164. data |= ((unsigned int)(cp[1])) << 16;
  165. data |= ((unsigned int)(cp[2])) << 8;
  166. data |= ((unsigned int)(cp[3]));
  167. position_ += sizeof(data);
  168. return (data);
  169. }
  170. /// \brief Read data of the specified length from the buffer and copy it to
  171. /// the caller supplied buffer.
  172. ///
  173. /// The data is copied as stored in the buffer; no conversion is performed.
  174. /// If the remaining length of the buffer is smaller than the specified
  175. /// length, an exception of class \c isc::dns::InvalidBufferPosition will
  176. /// be thrown.
  177. void readData(void* data, size_t len) {
  178. if (position_ + len > len_) {
  179. throwError("read beyond end of buffer");
  180. }
  181. memcpy(data, &data_[position_], len);
  182. position_ += len;
  183. }
  184. //@}
  185. /// @brief Read specified number of bytes as a vector.
  186. ///
  187. /// If specified buffer is too short, it will be expanded
  188. /// using vector::resize() method.
  189. ///
  190. /// @param Reference to a buffer (data will be stored there).
  191. /// @param Size specified number of bytes to read in a vector.
  192. ///
  193. void readVector(std::vector<uint8_t>& data, size_t len) {
  194. if (position_ + len > len_) {
  195. throwError("read beyond end of buffer");
  196. }
  197. data.resize(len);
  198. readData(&data[0], len);
  199. }
  200. private:
  201. /// \brief A common helper to throw an exception on invalid operation.
  202. ///
  203. /// Experiments showed that throwing from each method makes the buffer
  204. /// operation slower, so we consolidate it here, and let the methods
  205. /// call this.
  206. static void throwError(const char* msg) {
  207. isc_throw(InvalidBufferPosition, msg);
  208. }
  209. size_t position_;
  210. // XXX: The following must be private, but for a short term workaround with
  211. // Boost.Python binding, we changed it to protected. We should soon
  212. // revisit it.
  213. protected:
  214. const uint8_t* data_;
  215. size_t len_;
  216. };
  217. ///
  218. ///\brief The \c OutputBuffer class is a buffer abstraction for manipulating
  219. /// mutable data.
  220. ///
  221. /// The main purpose of this class is to provide a safe workplace for
  222. /// constructing wire-format data to be sent out to a network. Here,
  223. /// <em>safe</em> means that it automatically allocates necessary memory and
  224. /// avoid buffer overrun.
  225. ///
  226. /// Like for the \c InputBuffer class, applications normally use this class only
  227. /// in a limited situation. One common usage of this class for an application
  228. /// would be something like this:
  229. ///
  230. /// \code OutputBuffer buffer(4096); // give a sufficiently large initial size
  231. /// // pass the buffer to a DNS message object to construct a wire-format
  232. /// // DNS message.
  233. /// struct sockaddr to;
  234. /// sendto(s, buffer.getData(), buffer.getLength(), 0, &to, sizeof(to));
  235. /// \endcode
  236. ///
  237. /// where the \c getData() method gives a reference to the internal memory
  238. /// region stored in the \c buffer object. This is a suboptimal design in that
  239. /// it exposes an encapsulated "handle" of an object to its user.
  240. /// Unfortunately, there is no easy way to avoid this without involving
  241. /// expensive data copy if we want to use this object with a legacy API such as
  242. /// a BSD socket interface. And, indeed, this is one major purpose for this
  243. /// object. Applications should use this method only under such a special
  244. /// circumstance. It should also be noted that the memory region returned by
  245. /// \c getData() may be invalidated after a subsequent write operation.
  246. ///
  247. /// An \c OutputBuffer class object automatically extends its memory region when
  248. /// data is written beyond the end of the current buffer. However, it will
  249. /// involve performance overhead such as reallocating more memory and copying
  250. /// data. It is therefore recommended to construct the buffer object with a
  251. /// sufficiently large initial size.
  252. /// The \c getCapacity() method provides the current maximum size of data
  253. /// (including the portion already written) that can be written into the buffer
  254. /// without causing memory reallocation.
  255. ///
  256. /// Methods for writing data into the buffer generally work like an output
  257. /// stream: it begins with the head of the buffer, and once some length of data
  258. /// is written into the buffer, the next write operation will take place from
  259. /// the end of the buffer. Other methods to emulate "random access" are also
  260. /// provided (e.g., \c writeUint16At()). The normal write operations are
  261. /// normally exception-free as this class automatically extends the buffer
  262. /// when necessary. However, in extreme cases such as an attempt of writing
  263. /// multi-GB data, a separate exception (e.g., \c std::bad_alloc) may be thrown
  264. /// by the system. This also applies to the constructor with a very large
  265. /// initial size.
  266. ///
  267. /// Note to developers: it may make more sense to introduce an abstract base
  268. /// class for the \c OutputBuffer and define the simple implementation as a
  269. /// a concrete derived class. That way we can provide flexibility for future
  270. /// extension such as more efficient buffer implementation or allowing users
  271. /// to have their own customized version without modifying the source code.
  272. /// We in fact considered that option, but at the moment chose the simpler
  273. /// approach with a single concrete class because it may make the
  274. /// implementation unnecessarily complicated while we were still not certain
  275. /// if we really want that flexibility. We may revisit the class design as
  276. /// we see more applications of the class. The same considerations apply to
  277. /// the \c InputBuffer and \c MessageRenderer classes.
  278. class OutputBuffer {
  279. public:
  280. ///
  281. /// \name Constructors and Destructor
  282. ///
  283. //@{
  284. /// \brief Constructor from the initial size of the buffer.
  285. ///
  286. /// \param len The initial length of the buffer in bytes.
  287. OutputBuffer(size_t len) :
  288. buffer_(NULL),
  289. size_(0),
  290. allocated_(len)
  291. {
  292. // We use malloc and free instead of C++ new[] and delete[].
  293. // This way we can use realloc, which may in fact do it without a copy.
  294. buffer_ = static_cast<uint8_t*>(malloc(allocated_));
  295. if (buffer_ == NULL && len != 0) {
  296. throw std::bad_alloc();
  297. }
  298. }
  299. /// \brief Copy constructor
  300. OutputBuffer(const OutputBuffer& other) :
  301. buffer_(NULL),
  302. size_(other.size_),
  303. allocated_(other.allocated_)
  304. {
  305. buffer_ = static_cast<uint8_t*>(malloc(allocated_));
  306. if (buffer_ == NULL && allocated_ != 0) {
  307. throw std::bad_alloc();
  308. }
  309. memcpy(buffer_, other.buffer_, size_);
  310. }
  311. /// \brief Destructor
  312. ~ OutputBuffer() {
  313. free(buffer_);
  314. }
  315. //@}
  316. /// \brief Assignment operator
  317. OutputBuffer& operator =(const OutputBuffer& other) {
  318. uint8_t* newbuff(static_cast<uint8_t*>(malloc(other.allocated_)));
  319. if (newbuff == NULL && other.allocated_ != 0) {
  320. throw std::bad_alloc();
  321. }
  322. free(buffer_);
  323. buffer_ = newbuff;
  324. size_ = other.size_;
  325. allocated_ = other.allocated_;
  326. memcpy(buffer_, other.buffer_, size_);
  327. return (*this);
  328. }
  329. ///
  330. /// \name Getter Methods
  331. ///
  332. //@{
  333. /// \brief Return the current capacity of the buffer.
  334. size_t getCapacity() const { return (allocated_); }
  335. /// \brief Return a pointer to the head of the data stored in the buffer.
  336. ///
  337. /// The caller can assume that the subsequent \c getLength() bytes are
  338. /// identical to the stored data of the buffer.
  339. ///
  340. /// Note: The pointer returned by this method may be invalidated after a
  341. /// subsequent write operation.
  342. const void* getData() const { return (buffer_); }
  343. /// \brief Return the length of data written in the buffer.
  344. size_t getLength() const { return (size_); }
  345. /// \brief Return the value of the buffer at the specified position.
  346. ///
  347. /// \c pos must specify the valid position of the buffer; otherwise an
  348. /// exception class of \c InvalidBufferPosition will be thrown.
  349. ///
  350. /// \param pos The position in the buffer to be returned.
  351. uint8_t operator[](size_t pos) const
  352. {
  353. if (pos >= size_) {
  354. isc_throw(InvalidBufferPosition, "read at invalid position");
  355. }
  356. return (buffer_[pos]);
  357. }
  358. //@}
  359. ///
  360. /// \name Methods for writing data into the buffer.
  361. ///
  362. //@{
  363. /// \brief Insert a specified length of gap at the end of the buffer.
  364. ///
  365. /// The caller should not assume any particular value to be inserted.
  366. /// This method is provided as a shortcut to make a hole in the buffer
  367. /// that is to be filled in later, e.g, by \ref writeUint16At().
  368. /// \param len The length of the gap to be inserted in bytes.
  369. void skip(size_t len) {
  370. ensureAllocated(size_ + len);
  371. size_ += len;
  372. }
  373. /// \brief Trim the specified length of data from the end of the buffer.
  374. ///
  375. /// The specified length must not exceed the current data size of the
  376. /// buffer; otherwise an exception of class \c isc::OutOfRange will
  377. /// be thrown.
  378. ///
  379. /// \param len The length of data that should be trimmed.
  380. void trim(size_t len)
  381. {
  382. if (len > size_) {
  383. isc_throw(OutOfRange, "trimming too large from output buffer");
  384. }
  385. size_ -= len;
  386. }
  387. /// \brief Clear buffer content.
  388. ///
  389. /// This method can be used to re-initialize and reuse the buffer without
  390. /// constructing a new one.
  391. void clear() { size_ = 0; }
  392. /// \brief Write an unsigned 8-bit integer into the buffer.
  393. ///
  394. /// \param data The 8-bit integer to be written into the buffer.
  395. void writeUint8(uint8_t data) {
  396. ensureAllocated(size_ + 1);
  397. buffer_[size_ ++] = data;
  398. }
  399. /// \brief Write an unsigned 8-bit integer into the buffer.
  400. ///
  401. /// The position must be lower than the size of the buffer,
  402. /// otherwise an exception of class \c isc::dns::InvalidBufferPosition
  403. /// will be thrown.
  404. ///
  405. /// \param data The 8-bit integer to be written into the buffer.
  406. /// \param pos The position in the buffer to write the data.
  407. void writeUint8At(uint8_t data, size_t pos) {
  408. if (pos + sizeof(data) > size_) {
  409. isc_throw(InvalidBufferPosition, "write at invalid position");
  410. }
  411. buffer_[pos] = data;
  412. }
  413. /// \brief Write an unsigned 16-bit integer in host byte order into the
  414. /// buffer in network byte order.
  415. ///
  416. /// \param data The 16-bit integer to be written into the buffer.
  417. void writeUint16(uint16_t data)
  418. {
  419. ensureAllocated(size_ + sizeof(data));
  420. buffer_[size_ ++] = static_cast<uint8_t>((data & 0xff00U) >> 8);
  421. buffer_[size_ ++] = static_cast<uint8_t>(data & 0x00ffU);
  422. }
  423. /// \brief Write an unsigned 16-bit integer in host byte order at the
  424. /// specified position of the buffer in network byte order.
  425. ///
  426. /// The buffer must have a sufficient room to store the given data at the
  427. /// given position, that is, <code>pos + 2 < getLength()</code>;
  428. /// otherwise an exception of class \c isc::dns::InvalidBufferPosition will
  429. /// be thrown.
  430. /// Note also that this method never extends the buffer.
  431. ///
  432. /// \param data The 16-bit integer to be written into the buffer.
  433. /// \param pos The beginning position in the buffer to write the data.
  434. void writeUint16At(uint16_t data, size_t pos)
  435. {
  436. if (pos + sizeof(data) > size_) {
  437. isc_throw(InvalidBufferPosition, "write at invalid position");
  438. }
  439. buffer_[pos] = static_cast<uint8_t>((data & 0xff00U) >> 8);
  440. buffer_[pos + 1] = static_cast<uint8_t>(data & 0x00ffU);
  441. }
  442. /// \brief Write an unsigned 32-bit integer in host byte order
  443. /// into the buffer in network byte order.
  444. ///
  445. /// \param data The 32-bit integer to be written into the buffer.
  446. void writeUint32(uint32_t data)
  447. {
  448. ensureAllocated(size_ + sizeof(data));
  449. buffer_[size_ ++] = static_cast<uint8_t>((data & 0xff000000) >> 24);
  450. buffer_[size_ ++] = static_cast<uint8_t>((data & 0x00ff0000) >> 16);
  451. buffer_[size_ ++] = static_cast<uint8_t>((data & 0x0000ff00) >> 8);
  452. buffer_[size_ ++] = static_cast<uint8_t>(data & 0x000000ff);
  453. }
  454. /// \brief Copy an arbitrary length of data into the buffer.
  455. ///
  456. /// No conversion on the copied data is performed.
  457. ///
  458. /// \param data A pointer to the data to be copied into the buffer.
  459. /// \param len The length of the data in bytes.
  460. void writeData(const void *data, size_t len)
  461. {
  462. ensureAllocated(size_ + len);
  463. memcpy(buffer_ + size_, data, len);
  464. size_ += len;
  465. }
  466. //@}
  467. private:
  468. // The actual data
  469. uint8_t* buffer_;
  470. // How many bytes are used
  471. size_t size_;
  472. // How many bytes do we have preallocated (eg. the capacity)
  473. size_t allocated_;
  474. // Make sure at last needed_size bytes are allocated in the buffer
  475. void ensureAllocated(size_t needed_size) {
  476. if (allocated_ < needed_size) {
  477. // Guess some bigger size
  478. size_t new_size = (allocated_ == 0) ? 1024 : allocated_;
  479. while (new_size < needed_size) {
  480. new_size *= 2;
  481. }
  482. // Allocate bigger space
  483. uint8_t* new_buffer_(static_cast<uint8_t*>(realloc(buffer_,
  484. new_size)));
  485. if (new_buffer_ == NULL) {
  486. // If it fails, the original block is left intact by it
  487. throw std::bad_alloc();
  488. }
  489. buffer_ = new_buffer_;
  490. allocated_ = new_size;
  491. }
  492. }
  493. };
  494. /// \brief Pointer-like types pointing to \c InputBuffer or \c OutputBuffer
  495. ///
  496. /// These types are expected to be used as an argument in asynchronous
  497. /// callback functions. The internal reference-counting will ensure that
  498. /// that ongoing state information will not be lost if the object
  499. /// that originated the asynchronous call falls out of scope.
  500. typedef boost::shared_ptr<InputBuffer> InputBufferPtr;
  501. typedef boost::shared_ptr<OutputBuffer> OutputBufferPtr;
  502. } // namespace util
  503. } // namespace isc
  504. #endif // __BUFFER_H
  505. // Local Variables:
  506. // mode: c++
  507. // End: