Buf.hpp 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741
  1. /*
  2. * Copyright (c)2013-2020 ZeroTier, Inc.
  3. *
  4. * Use of this software is governed by the Business Source License included
  5. * in the LICENSE.TXT file in the project's root directory.
  6. *
  7. * Change Date: 2024-01-01
  8. *
  9. * On the date above, in accordance with the Business Source License, use
  10. * of this software will be governed by version 2.0 of the Apache License.
  11. */
  12. /****/
  13. #ifndef ZT_BUF_HPP
  14. #define ZT_BUF_HPP
  15. #include "Constants.hpp"
  16. #include "Utils.hpp"
  17. #include "SharedPtr.hpp"
  18. #include "Mutex.hpp"
  19. #include "TriviallyCopyable.hpp"
  20. #include "FCV.hpp"
  21. #include <cstdint>
  22. #include <cstring>
  23. #include <cstdlib>
  24. #include <stdexcept>
  25. #include <utility>
  26. #include <algorithm>
  27. #include <new>
  28. // Buffers are 16384 bytes in size because this is the smallest size that can hold any packet
  29. // and is a power of two. It needs to be a power of two because masking is significantly faster
  30. // than integer division modulus.
  31. #define ZT_BUF_MEM_SIZE 0x00004000
  32. #define ZT_BUF_MEM_MASK 0x00003fffU
  33. // Sanity limit on maximum buffer pool size
  34. #define ZT_BUF_MAX_POOL_SIZE 1024
  35. namespace ZeroTier {
  36. /**
  37. * Buffer and methods for branch-free bounds-checked data assembly and parsing
  38. *
  39. * This implements an extremely fast buffer for packet assembly and parsing that avoids
  40. * branching whenever possible. To be safe it must be used correctly!
  41. *
  42. * The read methods are prefixed by 'r', and write methods with 'w'. All methods take
  43. * an iterator, which is just an int that should be initialized to 0 (or whatever starting
  44. * position is desired). All read methods will advance the iterator regardless of outcome.
  45. *
  46. * Read and write methods fail silently in the event of overflow. They do not corrupt or
  47. * access memory outside the bounds of Buf, but will otherwise produce undefined results.
  48. *
  49. * IT IS THE RESPONSIBILITY OF THE USER of this class to use the readOverflow() and
  50. * writeOverflow() static methods to check the iterator for overflow after each series
  51. * of reads and writes and BEFORE ANY PARSING or other decisions are made on the basis
  52. * of the data obtained from a buffer. Failure to do so can result in bugs due
  53. * to parsing and branching on undefined or corrupt data.
  54. *
  55. * ^^ THIS IS VERY IMPORTANT ^^
  56. *
  57. * A typical packet assembly consists of repeated calls to the write methods followed by
  58. * a check to writeOverflow() before final packet armoring and transport. A typical packet
  59. * disassembly and parsing consists of a series of read calls to obtain the packet's
  60. * fields followed by a call to readOverflow() to check that these fields are valid. The
  61. * packet is discarded if readOverflow() returns true. Some packet parsers may make
  62. * additional reads and in this case readOverflow() must be checked after each set of
  63. * reads to ensure that overflow did not occur.
  64. *
  65. * Buf uses a lock-free pool for extremely fast allocation and deallocation.
  66. *
  67. * Buf can optionally take a template parameter that will be placed in the 'data'
  68. * union as 'fields.' This must be a basic plain data type and must be no larger than
  69. * ZT_BUF_MEM_SIZE. It's typically a packed struct.
  70. *
  71. * Buf instances with different template parameters can freely be cast to one another
  72. * as there is no actual difference in size or layout.
  73. *
  74. * @tparam U Type to overlap with data bytes in data union (can't be larger than ZT_BUF_MEM_SIZE)
  75. */
  76. class Buf
  77. {
  78. friend class SharedPtr<Buf>;
  79. public:
  80. // New and delete operators that allocate Buf instances from a shared lock-free memory pool.
  81. static void *operator new(std::size_t sz);
  82. static void operator delete(void *ptr);
  83. /**
  84. * Free all instances of Buf in shared pool.
  85. *
  86. * New buffers will be created and the pool repopulated if get() is called
  87. * and outstanding buffers will still be returned to the pool. This just
  88. * frees buffers currently held in reserve.
  89. */
  90. static void freePool() noexcept;
  91. /**
  92. * @return Number of Buf objects currently allocated via pool mechanism
  93. */
  94. static long poolAllocated() noexcept;
  95. /**
  96. * Slice is almost exactly like the built-in slice data structure in Go
  97. */
  98. struct Slice : TriviallyCopyable
  99. {
  100. ZT_INLINE Slice(const SharedPtr<Buf> &b_,const unsigned int s_,const unsigned int e_) noexcept : b(b_),s(s_),e(e_) {}
  101. ZT_INLINE Slice() noexcept : b(),s(0),e(0) {}
  102. ZT_INLINE operator bool() const noexcept { return (b); } // NOLINT(google-explicit-constructor,hicpp-explicit-conversions)
  103. ZT_INLINE unsigned int size() const noexcept { return (e - s); }
  104. ZT_INLINE void zero() noexcept { b.zero(); s = 0; e = 0; }
  105. /**
  106. * Buffer holding slice data
  107. */
  108. SharedPtr<Buf> b;
  109. /**
  110. * Index of start of data in slice
  111. */
  112. unsigned int s;
  113. /**
  114. * Index of end of data in slice (make sure it's greater than or equal to 's'!)
  115. */
  116. unsigned int e;
  117. };
  118. /**
  119. * Assemble all slices in a vector into a single slice starting at position 0
  120. *
  121. * The returned slice will start at 0 and contain the entire vector unless the
  122. * vector is too large to fit in a single buffer. If that or any other error
  123. * occurs the returned slice will be empty and contain a NULL Buf.
  124. *
  125. * The vector may be modified by this function and should be considered
  126. * undefined after it is called.
  127. *
  128. * @tparam FCVC Capacity of FCV (generally inferred automatically)
  129. * @param fcv FCV containing one or more slices
  130. * @return Single slice containing fully assembled buffer (empty on error)
  131. */
  132. template<unsigned int FCVC>
  133. static ZT_INLINE Buf::Slice assembleSliceVector(FCV<Buf::Slice,FCVC> &fcv) noexcept
  134. {
  135. Buf::Slice r;
  136. typename FCV<Buf::Slice,FCVC>::iterator s(fcv.begin());
  137. unsigned int l = s->e - s->s;
  138. if (l <= ZT_BUF_MEM_SIZE) {
  139. r.b.move(s->b);
  140. if (s->s > 0)
  141. memmove(r.b->unsafeData,r.b->unsafeData + s->s,l);
  142. r.e = l;
  143. while (++s != fcv.end()) {
  144. l = s->e - s->s;
  145. if (l > (ZT_BUF_MEM_SIZE - r.e)) {
  146. r.b.zero();
  147. r.e = 0;
  148. break;
  149. }
  150. Utils::copy(r.b->unsafeData + r.e,s->b->unsafeData + s->s,l);
  151. s->b.zero(); // let go of buffer in vector as soon as possible
  152. r.e += l;
  153. }
  154. }
  155. return r;
  156. }
  157. /**
  158. * Create a new uninitialized buffer with undefined contents (use clear() to zero if needed)
  159. */
  160. ZT_INLINE Buf() noexcept : __nextInPool(0),__refCount(0) {} // NOLINT(cppcoreguidelines-pro-type-member-init,hicpp-member-init)
  161. /**
  162. * Create a new buffer and copy data into it
  163. */
  164. ZT_INLINE Buf(const void *const data,const unsigned int len) noexcept : // NOLINT(cppcoreguidelines-pro-type-member-init,hicpp-member-init)
  165. __nextInPool(0),
  166. __refCount(0)
  167. {
  168. Utils::copy(unsafeData,data,len);
  169. }
  170. ZT_INLINE Buf(const Buf &b2) noexcept : // NOLINT(cppcoreguidelines-pro-type-member-init,hicpp-member-init)
  171. __nextInPool(0),
  172. __refCount(0)
  173. {
  174. Utils::copy<ZT_BUF_MEM_SIZE>(unsafeData,b2.unsafeData);
  175. }
  176. ZT_INLINE Buf &operator=(const Buf &b2) noexcept
  177. {
  178. if (this != &b2)
  179. Utils::copy<ZT_BUF_MEM_SIZE>(unsafeData,b2.unsafeData);
  180. return *this;
  181. }
  182. /**
  183. * Check for overflow beyond the size of the buffer
  184. *
  185. * This is used to check for overflow when writing. It returns true if the iterator
  186. * has passed beyond the capacity of the buffer.
  187. *
  188. * @param ii Iterator to check
  189. * @return True if iterator has read past the size of the buffer
  190. */
  191. static ZT_INLINE bool writeOverflow(const int &ii) noexcept { return ((ii - ZT_BUF_MEM_SIZE) > 0); }
  192. /**
  193. * Check for overflow beyond the size of the data that should be in the buffer
  194. *
  195. * This is used to check for overflow when reading, with the second argument being the
  196. * size of the meaningful data actually present in the buffer.
  197. *
  198. * @param ii Iterator to check
  199. * @param size Size of data that should be in buffer
  200. * @return True if iterator has read past the size of the data
  201. */
  202. static ZT_INLINE bool readOverflow(const int &ii,const unsigned int size) noexcept { return ((ii - (int)size) > 0); }
  203. /**
  204. * Set all memory to zero
  205. */
  206. ZT_INLINE void clear() noexcept
  207. {
  208. Utils::zero<ZT_BUF_MEM_SIZE>(unsafeData);
  209. }
  210. /**
  211. * Read a byte
  212. *
  213. * @param ii Index value-result parameter (incremented by 1)
  214. * @return Byte (undefined on overflow)
  215. */
  216. ZT_INLINE uint8_t rI8(int &ii) const noexcept
  217. {
  218. const int s = ii++;
  219. return unsafeData[(unsigned int)s & ZT_BUF_MEM_MASK];
  220. }
  221. /**
  222. * Read a 16-bit integer
  223. *
  224. * @param ii Index value-result parameter (incremented by 2)
  225. * @return Integer (undefined on overflow)
  226. */
  227. ZT_INLINE uint16_t rI16(int &ii) const noexcept
  228. {
  229. const unsigned int s = (unsigned int)ii & ZT_BUF_MEM_MASK;
  230. ii += 2;
  231. #ifdef ZT_NO_UNALIGNED_ACCESS
  232. return (
  233. ((uint16_t)unsafeData[s] << 8U) |
  234. (uint16_t)unsafeData[s + 1]);
  235. #else
  236. return Utils::ntoh(*reinterpret_cast<const uint16_t *>(unsafeData + s));
  237. #endif
  238. }
  239. /**
  240. * Read a 32-bit integer
  241. *
  242. * @param ii Index value-result parameter (incremented by 4)
  243. * @return Integer (undefined on overflow)
  244. */
  245. ZT_INLINE uint32_t rI32(int &ii) const noexcept
  246. {
  247. const unsigned int s = (unsigned int)ii & ZT_BUF_MEM_MASK;
  248. ii += 4;
  249. #ifdef ZT_NO_UNALIGNED_ACCESS
  250. return (
  251. ((uint32_t)unsafeData[s] << 24U) |
  252. ((uint32_t)unsafeData[s + 1] << 16U) |
  253. ((uint32_t)unsafeData[s + 2] << 8U) |
  254. (uint32_t)unsafeData[s + 3]);
  255. #else
  256. return Utils::ntoh(*reinterpret_cast<const uint32_t *>(unsafeData + s));
  257. #endif
  258. }
  259. /**
  260. * Read a 64-bit integer
  261. *
  262. * @param ii Index value-result parameter (incremented by 8)
  263. * @return Integer (undefined on overflow)
  264. */
  265. ZT_INLINE uint64_t rI64(int &ii) const noexcept
  266. {
  267. const unsigned int s = (unsigned int)ii & ZT_BUF_MEM_MASK;
  268. ii += 8;
  269. #ifdef ZT_NO_UNALIGNED_ACCESS
  270. return (
  271. ((uint64_t)unsafeData[s] << 56U) |
  272. ((uint64_t)unsafeData[s + 1] << 48U) |
  273. ((uint64_t)unsafeData[s + 2] << 40U) |
  274. ((uint64_t)unsafeData[s + 3] << 32U) |
  275. ((uint64_t)unsafeData[s + 4] << 24U) |
  276. ((uint64_t)unsafeData[s + 5] << 16U) |
  277. ((uint64_t)unsafeData[s + 6] << 8U) |
  278. (uint64_t)unsafeData[s + 7]);
  279. #else
  280. return Utils::ntoh(*reinterpret_cast<const uint64_t *>(unsafeData + s));
  281. #endif
  282. }
  283. /**
  284. * Read an object supporting the marshal/unmarshal interface
  285. *
  286. * If the return value is negative the object's state is undefined. A return value of
  287. * zero typically also indicates a problem, though this may depend on the object type.
  288. *
  289. * Since objects may be invalid even if there is no overflow, it's important to check
  290. * the return value of this function in all cases and discard invalid packets as it
  291. * indicates.
  292. *
  293. * @tparam T Object type
  294. * @param ii Index value-result parameter (incremented by object's size in bytes)
  295. * @param obj Object to read
  296. * @return Bytes read or a negative value on unmarshal error (passed from object) or overflow
  297. */
  298. template<typename T>
  299. ZT_INLINE int rO(int &ii,T &obj) const noexcept
  300. {
  301. if (likely(ii < ZT_BUF_MEM_SIZE)) {
  302. int ms = obj.unmarshal(unsafeData + ii,ZT_BUF_MEM_SIZE - ii);
  303. if (ms > 0)
  304. ii += ms;
  305. return ms;
  306. }
  307. return -1;
  308. }
  309. /**
  310. * Read a C-style string from the buffer, making a copy and advancing the iterator
  311. *
  312. * Use this if the buffer's memory may get changed between reading and processing
  313. * what is read.
  314. *
  315. * @param ii Index value-result parameter (incremented by length of string)
  316. * @param buf Buffer to receive string
  317. * @param bufSize Capacity of buffer in bytes
  318. * @return Pointer to buf or NULL on overflow or error
  319. */
  320. ZT_INLINE char *rS(int &ii,char *const buf,const unsigned int bufSize) const noexcept
  321. {
  322. const char *const s = (const char *)(unsafeData + ii);
  323. const int sii = ii;
  324. while (likely(ii < ZT_BUF_MEM_SIZE)) {
  325. if (unsafeData[ii++] == 0) {
  326. Utils::copy(buf,s,ii - sii);
  327. return buf;
  328. }
  329. }
  330. return nullptr;
  331. }
  332. /**
  333. * Obtain a pointer to a C-style string in the buffer without copying and advance the iterator
  334. *
  335. * The iterator is advanced even if this fails and returns NULL so that readOverflow()
  336. * will indicate that an overflow occurred. As with other reads the string's contents are
  337. * undefined if readOverflow() returns true.
  338. *
  339. * This version avoids a copy and so is faster if the buffer won't be modified between
  340. * reading and processing.
  341. *
  342. * @param ii Index value-result parameter (incremented by length of string)
  343. * @return Pointer to null-terminated C-style string or NULL on overflow or error
  344. */
  345. ZT_INLINE const char *rSnc(int &ii) const noexcept
  346. {
  347. const char *const s = (const char *)(unsafeData + ii);
  348. while (ii < ZT_BUF_MEM_SIZE) {
  349. if (unsafeData[ii++] == 0)
  350. return s;
  351. }
  352. return nullptr;
  353. }
  354. /**
  355. * Read a byte array from the buffer, making a copy and advancing the iterator
  356. *
  357. * Use this if the buffer's memory may get changed between reading and processing
  358. * what is read.
  359. *
  360. * @param ii Index value-result parameter (incremented by len)
  361. * @param bytes Buffer to contain data to read
  362. * @param len Length of buffer
  363. * @return Pointer to data or NULL on overflow or error
  364. */
  365. ZT_INLINE uint8_t *rB(int &ii,void *const bytes,const unsigned int len) const noexcept
  366. {
  367. if (likely(((ii += (int)len) <= ZT_BUF_MEM_SIZE))) {
  368. Utils::copy(bytes,unsafeData + ii,len);
  369. return reinterpret_cast<uint8_t *>(bytes);
  370. }
  371. return nullptr;
  372. }
  373. /**
  374. * Obtain a pointer to a field in the buffer without copying and advance the iterator
  375. *
  376. * The iterator is advanced even if this fails and returns NULL so that readOverflow()
  377. * will indicate that an overflow occurred.
  378. *
  379. * This version avoids a copy and so is faster if the buffer won't be modified between
  380. * reading and processing.
  381. *
  382. * @param ii Index value-result parameter (incremented by len)
  383. * @param len Length of data field to obtain a pointer to
  384. * @return Pointer to field or NULL on overflow
  385. */
  386. ZT_INLINE const uint8_t *rBnc(int &ii,unsigned int len) const noexcept
  387. {
  388. const uint8_t *const b = unsafeData + ii;
  389. return ((ii += (int)len) <= ZT_BUF_MEM_SIZE) ? b : nullptr;
  390. }
  391. /**
  392. * Load a value at an index without advancing the index
  393. *
  394. * Note that unlike the rI??() methods this does not increment ii and therefore
  395. * will not necessarily result in a 'true' return from readOverflow(). It does
  396. * however subject 'ii' to soft bounds masking like the gI??() methods.
  397. */
  398. ZT_INLINE uint8_t lI8(const int ii) const noexcept
  399. {
  400. return unsafeData[(unsigned int)ii & ZT_BUF_MEM_MASK];
  401. }
  402. /**
  403. * Load a value at an index without advancing the index
  404. *
  405. * Note that unlike the rI??() methods this does not increment ii and therefore
  406. * will not necessarily result in a 'true' return from readOverflow(). It does
  407. * however subject 'ii' to soft bounds masking like the gI??() methods.
  408. */
  409. ZT_INLINE uint16_t lI16(const int ii) const noexcept
  410. {
  411. const unsigned int s = (unsigned int)ii & ZT_BUF_MEM_MASK;
  412. #ifdef ZT_NO_UNALIGNED_ACCESS
  413. return (
  414. ((uint16_t)unsafeData[s] << 8U) |
  415. (uint16_t)unsafeData[s + 1]);
  416. #else
  417. return Utils::ntoh(*reinterpret_cast<const uint16_t *>(unsafeData + s));
  418. #endif
  419. }
  420. /**
  421. * Load a value at an index without advancing the index
  422. *
  423. * Note that unlike the rI??() methods this does not increment ii and therefore
  424. * will not necessarily result in a 'true' return from readOverflow(). It does
  425. * however subject 'ii' to soft bounds masking like the gI??() methods.
  426. */
  427. ZT_INLINE uint32_t lI32(const int ii) const noexcept
  428. {
  429. const unsigned int s = (unsigned int)ii & ZT_BUF_MEM_MASK;
  430. #ifdef ZT_NO_UNALIGNED_ACCESS
  431. return (
  432. ((uint32_t)unsafeData[s] << 24U) |
  433. ((uint32_t)unsafeData[s + 1] << 16U) |
  434. ((uint32_t)unsafeData[s + 2] << 8U) |
  435. (uint32_t)unsafeData[s + 3]);
  436. #else
  437. return Utils::ntoh(*reinterpret_cast<const uint32_t *>(unsafeData + s));
  438. #endif
  439. }
  440. /**
  441. * Load a value at an index without advancing the index
  442. *
  443. * Note that unlike the rI??() methods this does not increment ii and therefore
  444. * will not necessarily result in a 'true' return from readOverflow(). It does
  445. * however subject 'ii' to soft bounds masking like the gI??() methods.
  446. */
  447. ZT_INLINE uint8_t lI64(const int ii) const noexcept
  448. {
  449. const unsigned int s = (unsigned int)ii & ZT_BUF_MEM_MASK;
  450. #ifdef ZT_NO_UNALIGNED_ACCESS
  451. return (
  452. ((uint64_t)unsafeData[s] << 56U) |
  453. ((uint64_t)unsafeData[s + 1] << 48U) |
  454. ((uint64_t)unsafeData[s + 2] << 40U) |
  455. ((uint64_t)unsafeData[s + 3] << 32U) |
  456. ((uint64_t)unsafeData[s + 4] << 24U) |
  457. ((uint64_t)unsafeData[s + 5] << 16U) |
  458. ((uint64_t)unsafeData[s + 6] << 8U) |
  459. (uint64_t)unsafeData[s + 7]);
  460. #else
  461. return Utils::ntoh(*reinterpret_cast<const uint64_t *>(unsafeData + s));
  462. #endif
  463. }
  464. /**
  465. * Write a byte
  466. *
  467. * @param ii Index value-result parameter (incremented by 1)
  468. * @param n Byte
  469. */
  470. ZT_INLINE void wI8(int &ii,const uint8_t n) noexcept
  471. {
  472. const int s = ii++;
  473. unsafeData[(unsigned int)s & ZT_BUF_MEM_MASK] = n;
  474. }
  475. /**
  476. * Write a 16-bit integer in big-endian byte order
  477. *
  478. * @param ii Index value-result parameter (incremented by 2)
  479. * @param n Integer
  480. */
  481. ZT_INLINE void wI16(int &ii,const uint16_t n) noexcept
  482. {
  483. const unsigned int s = ((unsigned int)ii) & ZT_BUF_MEM_MASK;
  484. ii += 2;
  485. #ifdef ZT_NO_UNALIGNED_ACCESS
  486. unsafeData[s] = (uint8_t)(n >> 8U);
  487. unsafeData[s + 1] = (uint8_t)n;
  488. #else
  489. *reinterpret_cast<uint16_t *>(unsafeData + s) = Utils::hton(n);
  490. #endif
  491. }
  492. /**
  493. * Write a 32-bit integer in big-endian byte order
  494. *
  495. * @param ii Index value-result parameter (incremented by 4)
  496. * @param n Integer
  497. */
  498. ZT_INLINE void wI32(int &ii,const uint32_t n) noexcept
  499. {
  500. const unsigned int s = ((unsigned int)ii) & ZT_BUF_MEM_MASK;
  501. ii += 4;
  502. #ifdef ZT_NO_UNALIGNED_ACCESS
  503. unsafeData[s] = (uint8_t)(n >> 24U);
  504. unsafeData[s + 1] = (uint8_t)(n >> 16U);
  505. unsafeData[s + 2] = (uint8_t)(n >> 8U);
  506. unsafeData[s + 3] = (uint8_t)n;
  507. #else
  508. *reinterpret_cast<uint32_t *>(unsafeData + s) = Utils::hton(n);
  509. #endif
  510. }
  511. /**
  512. * Write a 64-bit integer in big-endian byte order
  513. *
  514. * @param ii Index value-result parameter (incremented by 8)
  515. * @param n Integer
  516. */
  517. ZT_INLINE void wI64(int &ii,const uint64_t n) noexcept
  518. {
  519. const unsigned int s = ((unsigned int)ii) & ZT_BUF_MEM_MASK;
  520. ii += 8;
  521. #ifdef ZT_NO_UNALIGNED_ACCESS
  522. unsafeData[s] = (uint8_t)(n >> 56U);
  523. unsafeData[s + 1] = (uint8_t)(n >> 48U);
  524. unsafeData[s + 2] = (uint8_t)(n >> 40U);
  525. unsafeData[s + 3] = (uint8_t)(n >> 32U);
  526. unsafeData[s + 4] = (uint8_t)(n >> 24U);
  527. unsafeData[s + 5] = (uint8_t)(n >> 16U);
  528. unsafeData[s + 6] = (uint8_t)(n >> 8U);
  529. unsafeData[s + 7] = (uint8_t)n;
  530. #else
  531. *reinterpret_cast<uint64_t *>(unsafeData + s) = Utils::hton(n);
  532. #endif
  533. }
  534. /**
  535. * Write an object implementing the marshal interface
  536. *
  537. * @tparam T Object type
  538. * @param ii Index value-result parameter (incremented by size of object)
  539. * @param t Object to write
  540. */
  541. template<typename T>
  542. ZT_INLINE void wO(int &ii,T &t) noexcept
  543. {
  544. const int s = ii;
  545. if (likely((s + T::marshalSizeMax()) <= ZT_BUF_MEM_SIZE)) {
  546. int ms = t.marshal(unsafeData + s);
  547. if (ms > 0)
  548. ii += ms;
  549. } else {
  550. ii += T::marshalSizeMax(); // mark as overflowed even if we didn't do anything
  551. }
  552. }
  553. /**
  554. * Write a C-style null-terminated string (including the trailing zero)
  555. *
  556. * @param ii Index value-result parameter (incremented by length of string)
  557. * @param s String to write (writes an empty string if this is NULL)
  558. */
  559. ZT_INLINE void wS(int &ii,const char *s) noexcept
  560. {
  561. if (s) {
  562. char c;
  563. do {
  564. c = *(s++);
  565. wI8(ii,(uint8_t)c);
  566. } while (c);
  567. } else {
  568. wI8(ii,0);
  569. }
  570. }
  571. /**
  572. * Write a byte array
  573. *
  574. * @param ii Index value-result parameter (incremented by len)
  575. * @param bytes Bytes to write
  576. * @param len Size of data in bytes
  577. */
  578. ZT_INLINE void wB(int &ii,const void *const bytes,const unsigned int len) noexcept
  579. {
  580. const int s = ii;
  581. if (likely((ii += (int)len) <= ZT_BUF_MEM_SIZE))
  582. Utils::copy(unsafeData + s,bytes,len);
  583. }
  584. /**
  585. * Store a byte without advancing the index
  586. */
  587. ZT_INLINE void sI8(const int ii,const uint8_t n) noexcept
  588. {
  589. unsafeData[(unsigned int)ii & ZT_BUF_MEM_MASK] = n;
  590. }
  591. /**
  592. * Store an integer without advancing the index
  593. */
  594. ZT_INLINE void sI16(const int ii,const uint16_t n) noexcept
  595. {
  596. const unsigned int s = ((unsigned int)ii) & ZT_BUF_MEM_MASK;
  597. #ifdef ZT_NO_UNALIGNED_ACCESS
  598. unsafeData[s] = (uint8_t)(n >> 8U);
  599. unsafeData[s + 1] = (uint8_t)n;
  600. #else
  601. *reinterpret_cast<uint16_t *>(unsafeData + s) = Utils::hton(n);
  602. #endif
  603. }
  604. /**
  605. * Store an integer without advancing the index
  606. */
  607. ZT_INLINE void sI32(const int ii,const uint32_t n) noexcept
  608. {
  609. const unsigned int s = ((unsigned int)ii) & ZT_BUF_MEM_MASK;
  610. #ifdef ZT_NO_UNALIGNED_ACCESS
  611. unsafeData[s] = (uint8_t)(n >> 24U);
  612. unsafeData[s + 1] = (uint8_t)(n >> 16U);
  613. unsafeData[s + 2] = (uint8_t)(n >> 8U);
  614. unsafeData[s + 3] = (uint8_t)n;
  615. #else
  616. *reinterpret_cast<uint32_t *>(unsafeData + s) = Utils::hton(n);
  617. #endif
  618. }
  619. /**
  620. * Store an integer without advancing the index
  621. */
  622. ZT_INLINE void sI64(const int ii,const uint64_t n) noexcept
  623. {
  624. const unsigned int s = ((unsigned int)ii) & ZT_BUF_MEM_MASK;
  625. #ifdef ZT_NO_UNALIGNED_ACCESS
  626. unsafeData[s] = (uint8_t)(n >> 56U);
  627. unsafeData[s + 1] = (uint8_t)(n >> 48U);
  628. unsafeData[s + 2] = (uint8_t)(n >> 40U);
  629. unsafeData[s + 3] = (uint8_t)(n >> 32U);
  630. unsafeData[s + 4] = (uint8_t)(n >> 24U);
  631. unsafeData[s + 5] = (uint8_t)(n >> 16U);
  632. unsafeData[s + 6] = (uint8_t)(n >> 8U);
  633. unsafeData[s + 7] = (uint8_t)n;
  634. #else
  635. *reinterpret_cast<uint64_t *>(unsafeData + s) = Utils::hton(n);
  636. #endif
  637. }
  638. /**
  639. * @return Capacity of this buffer (usable size of data.bytes)
  640. */
  641. static constexpr unsigned int capacity() noexcept { return ZT_BUF_MEM_SIZE; }
  642. /**
  643. * Cast data in 'b' to a (usually packed) structure type
  644. *
  645. * Warning: this does no bounds checking. It should only be used with packed
  646. * struct types designed for use in packet decoding such as those in
  647. * Protocol.hpp, and if 'i' is non-zero the caller must check bounds.
  648. *
  649. * @tparam T Structure type to cast 'b' to
  650. * @param i Index of start of structure (default: 0)
  651. * @return Reference to 'b' cast to type T
  652. */
  653. template<typename T>
  654. ZT_INLINE T &as(const unsigned int i = 0) noexcept { return *reinterpret_cast<T *>(unsafeData + i); }
  655. /**
  656. * Cast data in 'b' to a (usually packed) structure type (const)
  657. *
  658. * Warning: this does no bounds checking. It should only be used with packed
  659. * struct types designed for use in packet decoding such as those in
  660. * Protocol.hpp, and if 'i' is non-zero the caller must check bounds.
  661. *
  662. * @tparam T Structure type to cast 'b' to
  663. * @param i Index of start of structure (default: 0)
  664. * @return Reference to 'b' cast to type T
  665. */
  666. template<typename T>
  667. ZT_INLINE const T &as(const unsigned int i = 0) const noexcept { return *reinterpret_cast<const T *>(unsafeData + i); }
  668. /**
  669. * Raw data held in buffer
  670. *
  671. * The additional eight bytes should not be used and should be considered undefined.
  672. * They exist to allow reads and writes of integer types to silently overflow if a
  673. * read or write is performed at the end of the buffer.
  674. */
  675. uint8_t unsafeData[ZT_BUF_MEM_SIZE + 8];
  676. private:
  677. // Next item in free buffer pool linked list if Buf is placed in pool, undefined and unused otherwise
  678. std::atomic<uintptr_t> __nextInPool;
  679. // Reference counter for SharedPtr<>
  680. std::atomic<int> __refCount;
  681. };
  682. } // namespace ZeroTier
  683. #endif