Buffer.hpp 11 KB

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