Buffer.hpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496
  1. /*
  2. * ZeroTier One - Network Virtualization Everywhere
  3. * Copyright (C) 2011-2016 ZeroTier, Inc. https://www.zerotier.com/
  4. *
  5. * This program is free software: you can redistribute it and/or modify
  6. * it under the terms of the GNU General Public License as published by
  7. * the Free Software Foundation, either version 3 of the License, or
  8. * (at your option) any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU General Public License
  16. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  17. */
  18. #ifndef ZT_BUFFER_HPP
  19. #define ZT_BUFFER_HPP
  20. #include <string.h>
  21. #include <stdint.h>
  22. #include <stdexcept>
  23. #include <string>
  24. #include <algorithm>
  25. #include <utility>
  26. #include "Constants.hpp"
  27. #include "Utils.hpp"
  28. #if defined(__GNUC__) && (!defined(ZT_NO_TYPE_PUNNING))
  29. #define ZT_VAR_MAY_ALIAS __attribute__((__may_alias__))
  30. #else
  31. #define ZT_VAR_MAY_ALIAS
  32. #endif
  33. namespace ZeroTier {
  34. /**
  35. * A variable length but statically allocated buffer
  36. *
  37. * Bounds-checking is done everywhere, since this is used in security
  38. * critical code. This supports construction and assignment from buffers
  39. * of differing capacities, provided the data actually in them fits.
  40. * It throws std::out_of_range on any boundary violation.
  41. *
  42. * The at(), append(), etc. methods encode integers larger than 8-bit in
  43. * big-endian (network) byte order.
  44. *
  45. * @tparam C Total capacity
  46. */
  47. template<unsigned int C>
  48. class Buffer
  49. {
  50. // I love me!
  51. template <unsigned int C2> friend class Buffer;
  52. public:
  53. // STL container idioms
  54. typedef unsigned char value_type;
  55. typedef unsigned char * pointer;
  56. typedef const char * const_pointer;
  57. typedef char & reference;
  58. typedef const char & const_reference;
  59. typedef char * iterator;
  60. typedef const char * const_iterator;
  61. typedef unsigned int size_type;
  62. typedef int difference_type;
  63. typedef std::reverse_iterator<iterator> reverse_iterator;
  64. typedef std::reverse_iterator<const_iterator> const_reverse_iterator;
  65. inline iterator begin() { return _b; }
  66. inline iterator end() { return (_b + _l); }
  67. inline const_iterator begin() const { return _b; }
  68. inline const_iterator end() const { return (_b + _l); }
  69. inline reverse_iterator rbegin() { return reverse_iterator(begin()); }
  70. inline reverse_iterator rend() { return reverse_iterator(end()); }
  71. inline const_reverse_iterator rbegin() const { return const_reverse_iterator(begin()); }
  72. inline const_reverse_iterator rend() const { return const_reverse_iterator(end()); }
  73. Buffer() :
  74. _l(0)
  75. {
  76. }
  77. Buffer(unsigned int l)
  78. throw(std::out_of_range)
  79. {
  80. if (l > C)
  81. throw std::out_of_range("Buffer: construct with size larger than capacity");
  82. _l = l;
  83. }
  84. template<unsigned int C2>
  85. Buffer(const Buffer<C2> &b)
  86. throw(std::out_of_range)
  87. {
  88. *this = b;
  89. }
  90. Buffer(const void *b,unsigned int l)
  91. throw(std::out_of_range)
  92. {
  93. copyFrom(b,l);
  94. }
  95. Buffer(const std::string &s)
  96. throw(std::out_of_range)
  97. {
  98. copyFrom(s.data(),s.length());
  99. }
  100. template<unsigned int C2>
  101. inline Buffer &operator=(const Buffer<C2> &b)
  102. throw(std::out_of_range)
  103. {
  104. if (b._l > C)
  105. throw std::out_of_range("Buffer: assignment from buffer larger than capacity");
  106. memcpy(_b,b._b,_l = b._l);
  107. return *this;
  108. }
  109. inline Buffer &operator=(const std::string &s)
  110. throw(std::out_of_range)
  111. {
  112. copyFrom(s.data(),s.length());
  113. return *this;
  114. }
  115. inline void copyFrom(const void *b,unsigned int l)
  116. throw(std::out_of_range)
  117. {
  118. if (l > C)
  119. throw std::out_of_range("Buffer: set from C array larger than capacity");
  120. _l = l;
  121. memcpy(_b,b,l);
  122. }
  123. unsigned char operator[](const unsigned int i) const
  124. throw(std::out_of_range)
  125. {
  126. if (i >= _l)
  127. throw std::out_of_range("Buffer: [] beyond end of data");
  128. return (unsigned char)_b[i];
  129. }
  130. unsigned char &operator[](const unsigned int i)
  131. throw(std::out_of_range)
  132. {
  133. if (i >= _l)
  134. throw std::out_of_range("Buffer: [] beyond end of data");
  135. return ((unsigned char *)_b)[i];
  136. }
  137. /**
  138. * Get a raw pointer to a field with bounds checking
  139. *
  140. * This isn't perfectly safe in that the caller could still overflow
  141. * the pointer, but its use provides both a sanity check and
  142. * documentation / reminder to the calling code to treat the returned
  143. * pointer as being of size [l].
  144. *
  145. * @param i Index of field in buffer
  146. * @param l Length of field in bytes
  147. * @return Pointer to field data
  148. * @throws std::out_of_range Field extends beyond data size
  149. */
  150. unsigned char *field(unsigned int i,unsigned int l)
  151. throw(std::out_of_range)
  152. {
  153. if ((i + l) > _l)
  154. throw std::out_of_range("Buffer: field() beyond end of data");
  155. return (unsigned char *)(_b + i);
  156. }
  157. const unsigned char *field(unsigned int i,unsigned int l) const
  158. throw(std::out_of_range)
  159. {
  160. if ((i + l) > _l)
  161. throw std::out_of_range("Buffer: field() beyond end of data");
  162. return (const unsigned char *)(_b + i);
  163. }
  164. /**
  165. * Place a primitive integer value at a given position
  166. *
  167. * @param i Index to place value
  168. * @param v Value
  169. * @tparam T Integer type (e.g. uint16_t, int64_t)
  170. */
  171. template<typename T>
  172. inline void setAt(unsigned int i,const T v)
  173. throw(std::out_of_range)
  174. {
  175. if ((i + sizeof(T)) > _l)
  176. throw std::out_of_range("Buffer: setAt() beyond end of data");
  177. #ifdef ZT_NO_TYPE_PUNNING
  178. uint8_t *p = reinterpret_cast<uint8_t *>(_b + i);
  179. for(unsigned int x=1;x<=sizeof(T);++x)
  180. *(p++) = (uint8_t)(v >> (8 * (sizeof(T) - x)));
  181. #else
  182. T *const ZT_VAR_MAY_ALIAS p = reinterpret_cast<T *>(_b + i);
  183. *p = Utils::hton(v);
  184. #endif
  185. }
  186. /**
  187. * Get a primitive integer value at a given position
  188. *
  189. * @param i Index to get integer
  190. * @tparam T Integer type (e.g. uint16_t, int64_t)
  191. * @return Integer value
  192. */
  193. template<typename T>
  194. inline T at(unsigned int i) const
  195. throw(std::out_of_range)
  196. {
  197. if ((i + sizeof(T)) > _l)
  198. throw std::out_of_range("Buffer: at() beyond end of data");
  199. #ifdef ZT_NO_TYPE_PUNNING
  200. T v = 0;
  201. const uint8_t *p = reinterpret_cast<const uint8_t *>(_b + i);
  202. for(unsigned int x=0;x<sizeof(T);++x) {
  203. v <<= 8;
  204. v |= (T)*(p++);
  205. }
  206. return v;
  207. #else
  208. const T *const ZT_VAR_MAY_ALIAS p = reinterpret_cast<const T *>(_b + i);
  209. return Utils::ntoh(*p);
  210. #endif
  211. }
  212. /**
  213. * Append an integer type to this buffer
  214. *
  215. * @param v Value to append
  216. * @tparam T Integer type (e.g. uint16_t, int64_t)
  217. * @throws std::out_of_range Attempt to append beyond capacity
  218. */
  219. template<typename T>
  220. inline void append(const T v)
  221. throw(std::out_of_range)
  222. {
  223. if ((_l + sizeof(T)) > C)
  224. throw std::out_of_range("Buffer: append beyond capacity");
  225. #ifdef ZT_NO_TYPE_PUNNING
  226. uint8_t *p = reinterpret_cast<uint8_t *>(_b + _l);
  227. for(unsigned int x=1;x<=sizeof(T);++x)
  228. *(p++) = (uint8_t)(v >> (8 * (sizeof(T) - x)));
  229. #else
  230. T *const ZT_VAR_MAY_ALIAS p = reinterpret_cast<T *>(_b + _l);
  231. *p = Utils::hton(v);
  232. #endif
  233. _l += sizeof(T);
  234. }
  235. /**
  236. * Append a run of bytes
  237. *
  238. * @param c Character value to append
  239. * @param n Number of times to append
  240. * @throws std::out_of_range Attempt to append beyond capacity
  241. */
  242. inline void append(unsigned char c,unsigned int n)
  243. throw(std::out_of_range)
  244. {
  245. if ((_l + n) > C)
  246. throw std::out_of_range("Buffer: append beyond capacity");
  247. for(unsigned int i=0;i<n;++i)
  248. _b[_l++] = (char)c;
  249. }
  250. /**
  251. * Append a C-array of bytes
  252. *
  253. * @param b Data
  254. * @param l Length
  255. * @throws std::out_of_range Attempt to append beyond capacity
  256. */
  257. inline void append(const void *b,unsigned int l)
  258. throw(std::out_of_range)
  259. {
  260. if ((_l + l) > C)
  261. throw std::out_of_range("Buffer: append beyond capacity");
  262. memcpy(_b + _l,b,l);
  263. _l += l;
  264. }
  265. /**
  266. * Append a string
  267. *
  268. * @param s String to append
  269. * @throws std::out_of_range Attempt to append beyond capacity
  270. */
  271. inline void append(const std::string &s)
  272. throw(std::out_of_range)
  273. {
  274. append(s.data(),(unsigned int)s.length());
  275. }
  276. /**
  277. * Append a C string including null termination byte
  278. *
  279. * @param s C string
  280. * @throws std::out_of_range Attempt to append beyond capacity
  281. */
  282. inline void appendCString(const char *s)
  283. throw(std::out_of_range)
  284. {
  285. for(;;) {
  286. if (_l >= C)
  287. throw std::out_of_range("Buffer: append beyond capacity");
  288. if (!(_b[_l++] = *(s++)))
  289. break;
  290. }
  291. }
  292. /**
  293. * Append a buffer
  294. *
  295. * @param b Buffer to append
  296. * @tparam C2 Capacity of second buffer (typically inferred)
  297. * @throws std::out_of_range Attempt to append beyond capacity
  298. */
  299. template<unsigned int C2>
  300. inline void append(const Buffer<C2> &b)
  301. throw(std::out_of_range)
  302. {
  303. append(b._b,b._l);
  304. }
  305. /**
  306. * Increment size and return pointer to field of specified size
  307. *
  308. * Nothing is actually written to the memory. This is a shortcut
  309. * for addSize() followed by field() to reference the previous
  310. * position and the new size.
  311. *
  312. * @param l Length of field to append
  313. * @return Pointer to beginning of appended field of length 'l'
  314. */
  315. inline char *appendField(unsigned int l)
  316. throw(std::out_of_range)
  317. {
  318. if ((_l + l) > C)
  319. throw std::out_of_range("Buffer: append beyond capacity");
  320. char *r = _b + _l;
  321. _l += l;
  322. return r;
  323. }
  324. /**
  325. * Increment size by a given number of bytes
  326. *
  327. * The contents of new space are undefined.
  328. *
  329. * @param i Bytes to increment
  330. * @throws std::out_of_range Capacity exceeded
  331. */
  332. inline void addSize(unsigned int i)
  333. throw(std::out_of_range)
  334. {
  335. if ((i + _l) > C)
  336. throw std::out_of_range("Buffer: setSize to larger than capacity");
  337. _l += i;
  338. }
  339. /**
  340. * Set size of data in buffer
  341. *
  342. * The contents of new space are undefined.
  343. *
  344. * @param i New size
  345. * @throws std::out_of_range Size larger than capacity
  346. */
  347. inline void setSize(const unsigned int i)
  348. throw(std::out_of_range)
  349. {
  350. if (i > C)
  351. throw std::out_of_range("Buffer: setSize to larger than capacity");
  352. _l = i;
  353. }
  354. /**
  355. * Move everything after 'at' to the buffer's front and truncate
  356. *
  357. * @param at Truncate before this position
  358. * @throw std::out_of_range Position is beyond size of buffer
  359. */
  360. inline void behead(const unsigned int at)
  361. throw(std::out_of_range)
  362. {
  363. if (!at)
  364. return;
  365. if (at > _l)
  366. throw std::out_of_range("Buffer: behead() beyond capacity");
  367. ::memmove(_b,_b + at,_l -= at);
  368. }
  369. /**
  370. * Erase something from the middle of the buffer
  371. *
  372. * @param start Starting position
  373. * @param length Length of block to erase
  374. * @throw std::out_of_range Position plus length is beyond size of buffer
  375. */
  376. inline void erase(const unsigned int at,const unsigned int length)
  377. throw(std::out_of_range)
  378. {
  379. const unsigned int endr = at + length;
  380. if (endr > _l)
  381. throw std::out_of_range("Buffer: erase() range beyond end of buffer");
  382. ::memmove(_b + at,_b + endr,_l - endr);
  383. _l -= length;
  384. }
  385. /**
  386. * Set buffer data length to zero
  387. */
  388. inline void clear() { _l = 0; }
  389. /**
  390. * Zero buffer up to size()
  391. */
  392. inline void zero() { memset(_b,0,_l); }
  393. /**
  394. * Zero unused capacity area
  395. */
  396. inline void zeroUnused() { memset(_b + _l,0,C - _l); }
  397. /**
  398. * Unconditionally and securely zero buffer's underlying memory
  399. */
  400. inline void burn() { Utils::burn(_b,sizeof(_b)); }
  401. /**
  402. * @return Constant pointer to data in buffer
  403. */
  404. inline const void *data() const { return _b; }
  405. /**
  406. * @return Non-constant pointer to data in buffer
  407. */
  408. inline void *unsafeData() { return _b; }
  409. /**
  410. * @return Size of data in buffer
  411. */
  412. inline unsigned int size() const { return _l; }
  413. /**
  414. * @return Capacity of buffer
  415. */
  416. inline unsigned int capacity() const { return C; }
  417. template<unsigned int C2>
  418. inline bool operator==(const Buffer<C2> &b) const
  419. {
  420. return ((_l == b._l)&&(!memcmp(_b,b._b,_l)));
  421. }
  422. template<unsigned int C2>
  423. inline bool operator!=(const Buffer<C2> &b) const
  424. {
  425. return ((_l != b._l)||(memcmp(_b,b._b,_l)));
  426. }
  427. template<unsigned int C2>
  428. inline bool operator<(const Buffer<C2> &b) const
  429. {
  430. return (memcmp(_b,b._b,std::min(_l,b._l)) < 0);
  431. }
  432. template<unsigned int C2>
  433. inline bool operator>(const Buffer<C2> &b) const
  434. {
  435. return (b < *this);
  436. }
  437. template<unsigned int C2>
  438. inline bool operator<=(const Buffer<C2> &b) const
  439. {
  440. return !(b < *this);
  441. }
  442. template<unsigned int C2>
  443. inline bool operator>=(const Buffer<C2> &b) const
  444. {
  445. return !(*this < b);
  446. }
  447. private:
  448. unsigned int _l;
  449. char ZT_VAR_MAY_ALIAS _b[C];
  450. };
  451. } // namespace ZeroTier
  452. #endif