Utils.hpp 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870
  1. /*
  2. * Copyright (c)2019 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: 2026-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_UTILS_HPP
  14. #define ZT_UTILS_HPP
  15. #include <stdio.h>
  16. #include <stdlib.h>
  17. #include <stdint.h>
  18. #include <string.h>
  19. #include <time.h>
  20. #include <string>
  21. #include <stdexcept>
  22. #include <vector>
  23. #include <map>
  24. #include <algorithm>
  25. #if defined(__FreeBSD__)
  26. #include <sys/endian.h>
  27. #endif
  28. #include "Constants.hpp"
  29. #if __BYTE_ORDER == __LITTLE_ENDIAN
  30. #define ZT_CONST_TO_BE_UINT16(x) ((uint16_t)((uint16_t)((uint16_t)(x) << 8U) | (uint16_t)((uint16_t)(x) >> 8U)))
  31. #define ZT_CONST_TO_BE_UINT64(x) ( \
  32. (((uint64_t)(x) & 0x00000000000000ffULL) << 56U) | \
  33. (((uint64_t)(x) & 0x000000000000ff00ULL) << 40U) | \
  34. (((uint64_t)(x) & 0x0000000000ff0000ULL) << 24U) | \
  35. (((uint64_t)(x) & 0x00000000ff000000ULL) << 8U) | \
  36. (((uint64_t)(x) & 0x000000ff00000000ULL) >> 8U) | \
  37. (((uint64_t)(x) & 0x0000ff0000000000ULL) >> 24U) | \
  38. (((uint64_t)(x) & 0x00ff000000000000ULL) >> 40U) | \
  39. (((uint64_t)(x) & 0xff00000000000000ULL) >> 56U))
  40. #else
  41. #define ZT_CONST_TO_BE_UINT16(x) ((uint16_t)(x))
  42. #define ZT_CONST_TO_BE_UINT64(x) ((uint64_t)(x))
  43. #endif
  44. #define ZT_ROR64(x, r) (((x) >> (r)) | ((x) << (64 - (r))))
  45. #define ZT_ROL64(x, r) (((x) << (r)) | ((x) >> (64 - (r))))
  46. #define ZT_ROR32(x, r) (((x) >> (r)) | ((x) << (32 - (r))))
  47. #define ZT_ROL32(x, r) (((x) << (r)) | ((x) >> (32 - (r))))
  48. namespace ZeroTier {
  49. /**
  50. * Miscellaneous utility functions and global constants
  51. */
  52. class Utils
  53. {
  54. public:
  55. static const uint64_t ZERO256[4];
  56. #ifdef ZT_ARCH_ARM_HAS_NEON
  57. struct ARMCapabilities
  58. {
  59. ARMCapabilities() noexcept;
  60. bool aes;
  61. bool crc32;
  62. bool pmull;
  63. bool sha1;
  64. bool sha2;
  65. };
  66. static const ARMCapabilities ARMCAP;
  67. #endif
  68. #ifdef ZT_ARCH_X64
  69. struct CPUIDRegisters
  70. {
  71. CPUIDRegisters() noexcept;
  72. bool rdrand;
  73. bool aes;
  74. bool avx;
  75. bool vaes; // implies AVX
  76. bool vpclmulqdq; // implies AVX
  77. bool avx2;
  78. bool avx512f;
  79. bool sha;
  80. bool fsrm;
  81. };
  82. static const CPUIDRegisters CPUID;
  83. #endif
  84. /**
  85. * Compute the log2 (most significant bit set) of a 32-bit integer
  86. *
  87. * @param v Integer to compute
  88. * @return log2 or 0 if v is 0
  89. */
  90. static inline unsigned int log2(uint32_t v)
  91. {
  92. uint32_t r = (v > 0xffff) << 4;
  93. v >>= r;
  94. uint32_t shift = (v > 0xff) << 3;
  95. v >>= shift;
  96. r |= shift;
  97. shift = (v > 0xf) << 2;
  98. v >>= shift;
  99. r |= shift;
  100. shift = (v > 0x3) << 1;
  101. v >>= shift;
  102. r |= shift;
  103. r |= (v >> 1);
  104. return (unsigned int)r;
  105. }
  106. /**
  107. * Perform a time-invariant binary comparison
  108. *
  109. * @param a First binary string
  110. * @param b Second binary string
  111. * @param len Length of strings
  112. * @return True if strings are equal
  113. */
  114. static inline bool secureEq(const void *a,const void *b,unsigned int len)
  115. {
  116. uint8_t diff = 0;
  117. for(unsigned int i=0;i<len;++i) {
  118. diff |= ( (reinterpret_cast<const uint8_t *>(a))[i] ^ (reinterpret_cast<const uint8_t *>(b))[i] );
  119. }
  120. return (diff == 0);
  121. }
  122. /**
  123. * Securely zero memory, avoiding compiler optimizations and such
  124. */
  125. static void burn(void *ptr,unsigned int len);
  126. /**
  127. * @param n Number to convert
  128. * @param s Buffer, at least 24 bytes in size
  129. * @return String containing 'n' in base 10 form
  130. */
  131. static char *decimal(unsigned long n,char s[24]);
  132. static inline char *hex(uint64_t i,char s[17])
  133. {
  134. s[0] = HEXCHARS[(i >> 60) & 0xf];
  135. s[1] = HEXCHARS[(i >> 56) & 0xf];
  136. s[2] = HEXCHARS[(i >> 52) & 0xf];
  137. s[3] = HEXCHARS[(i >> 48) & 0xf];
  138. s[4] = HEXCHARS[(i >> 44) & 0xf];
  139. s[5] = HEXCHARS[(i >> 40) & 0xf];
  140. s[6] = HEXCHARS[(i >> 36) & 0xf];
  141. s[7] = HEXCHARS[(i >> 32) & 0xf];
  142. s[8] = HEXCHARS[(i >> 28) & 0xf];
  143. s[9] = HEXCHARS[(i >> 24) & 0xf];
  144. s[10] = HEXCHARS[(i >> 20) & 0xf];
  145. s[11] = HEXCHARS[(i >> 16) & 0xf];
  146. s[12] = HEXCHARS[(i >> 12) & 0xf];
  147. s[13] = HEXCHARS[(i >> 8) & 0xf];
  148. s[14] = HEXCHARS[(i >> 4) & 0xf];
  149. s[15] = HEXCHARS[i & 0xf];
  150. s[16] = (char)0;
  151. return s;
  152. }
  153. static inline char *hex10(uint64_t i,char s[11])
  154. {
  155. s[0] = HEXCHARS[(i >> 36) & 0xf];
  156. s[1] = HEXCHARS[(i >> 32) & 0xf];
  157. s[2] = HEXCHARS[(i >> 28) & 0xf];
  158. s[3] = HEXCHARS[(i >> 24) & 0xf];
  159. s[4] = HEXCHARS[(i >> 20) & 0xf];
  160. s[5] = HEXCHARS[(i >> 16) & 0xf];
  161. s[6] = HEXCHARS[(i >> 12) & 0xf];
  162. s[7] = HEXCHARS[(i >> 8) & 0xf];
  163. s[8] = HEXCHARS[(i >> 4) & 0xf];
  164. s[9] = HEXCHARS[i & 0xf];
  165. s[10] = (char)0;
  166. return s;
  167. }
  168. static inline char *hex(uint32_t i,char s[9])
  169. {
  170. s[0] = HEXCHARS[(i >> 28) & 0xf];
  171. s[1] = HEXCHARS[(i >> 24) & 0xf];
  172. s[2] = HEXCHARS[(i >> 20) & 0xf];
  173. s[3] = HEXCHARS[(i >> 16) & 0xf];
  174. s[4] = HEXCHARS[(i >> 12) & 0xf];
  175. s[5] = HEXCHARS[(i >> 8) & 0xf];
  176. s[6] = HEXCHARS[(i >> 4) & 0xf];
  177. s[7] = HEXCHARS[i & 0xf];
  178. s[8] = (char)0;
  179. return s;
  180. }
  181. static inline char *hex(uint16_t i,char s[5])
  182. {
  183. s[0] = HEXCHARS[(i >> 12) & 0xf];
  184. s[1] = HEXCHARS[(i >> 8) & 0xf];
  185. s[2] = HEXCHARS[(i >> 4) & 0xf];
  186. s[3] = HEXCHARS[i & 0xf];
  187. s[4] = (char)0;
  188. return s;
  189. }
  190. static inline char *hex(uint8_t i,char s[3])
  191. {
  192. s[0] = HEXCHARS[(i >> 4) & 0xf];
  193. s[1] = HEXCHARS[i & 0xf];
  194. s[2] = (char)0;
  195. return s;
  196. }
  197. static inline char *hex(const void *d,unsigned int l,char *s)
  198. {
  199. char *const save = s;
  200. for(unsigned int i=0;i<l;++i) {
  201. const unsigned int b = reinterpret_cast<const uint8_t *>(d)[i];
  202. *(s++) = HEXCHARS[b >> 4];
  203. *(s++) = HEXCHARS[b & 0xf];
  204. }
  205. *s = (char)0;
  206. return save;
  207. }
  208. static inline unsigned int unhex(const char *h,void *buf,unsigned int buflen)
  209. {
  210. unsigned int l = 0;
  211. while (l < buflen) {
  212. uint8_t hc = *(reinterpret_cast<const uint8_t *>(h++));
  213. if (!hc) {
  214. break;
  215. }
  216. uint8_t c = 0;
  217. if ((hc >= 48)&&(hc <= 57)) { // 0..9
  218. c = hc - 48;
  219. } else if ((hc >= 97)&&(hc <= 102)) { // a..f
  220. c = hc - 87;
  221. } else if ((hc >= 65)&&(hc <= 70)) { // A..F
  222. c = hc - 55;
  223. }
  224. hc = *(reinterpret_cast<const uint8_t *>(h++));
  225. if (!hc) {
  226. break;
  227. }
  228. c <<= 4;
  229. if ((hc >= 48)&&(hc <= 57)) {
  230. c |= hc - 48;
  231. } else if ((hc >= 97)&&(hc <= 102)) {
  232. c |= hc - 87;
  233. } else if ((hc >= 65)&&(hc <= 70)) {
  234. c |= hc - 55;
  235. }
  236. reinterpret_cast<uint8_t *>(buf)[l++] = c;
  237. }
  238. return l;
  239. }
  240. static inline unsigned int unhex(const char *h,unsigned int hlen,void *buf,unsigned int buflen)
  241. {
  242. unsigned int l = 0;
  243. const char *hend = h + hlen;
  244. while (l < buflen) {
  245. if (h == hend) {
  246. break;
  247. }
  248. uint8_t hc = *(reinterpret_cast<const uint8_t *>(h++));
  249. if (!hc) {
  250. break;
  251. }
  252. uint8_t c = 0;
  253. if ((hc >= 48)&&(hc <= 57)) {
  254. c = hc - 48;
  255. } else if ((hc >= 97)&&(hc <= 102)) {
  256. c = hc - 87;
  257. } else if ((hc >= 65)&&(hc <= 70)) {
  258. c = hc - 55;
  259. }
  260. if (h == hend) {
  261. break;
  262. }
  263. hc = *(reinterpret_cast<const uint8_t *>(h++));
  264. if (!hc) {
  265. break;
  266. }
  267. c <<= 4;
  268. if ((hc >= 48)&&(hc <= 57)) {
  269. c |= hc - 48;
  270. } else if ((hc >= 97)&&(hc <= 102)) {
  271. c |= hc - 87;
  272. } else if ((hc >= 65)&&(hc <= 70)) {
  273. c |= hc - 55;
  274. }
  275. reinterpret_cast<uint8_t *>(buf)[l++] = c;
  276. }
  277. return l;
  278. }
  279. static inline float normalize(float value, float bigMin, float bigMax, float targetMin, float targetMax)
  280. {
  281. float bigSpan = bigMax - bigMin;
  282. float smallSpan = targetMax - targetMin;
  283. float valueScaled = (value - bigMin) / bigSpan;
  284. return targetMin + valueScaled * smallSpan;
  285. }
  286. /**
  287. * Generate secure random bytes
  288. *
  289. * This will try to use whatever OS sources of entropy are available. It's
  290. * guarded by an internal mutex so it's thread-safe.
  291. *
  292. * @param buf Buffer to fill
  293. * @param bytes Number of random bytes to generate
  294. */
  295. static void getSecureRandom(void *buf,unsigned int bytes);
  296. /**
  297. * Tokenize a string (alias for strtok_r or strtok_s depending on platform)
  298. *
  299. * @param str String to split
  300. * @param delim Delimiters
  301. * @param saveptr Pointer to a char * for temporary reentrant storage
  302. */
  303. static inline char *stok(char *str,const char *delim,char **saveptr)
  304. {
  305. #ifdef __WINDOWS__
  306. return strtok_s(str,delim,saveptr);
  307. #else
  308. return strtok_r(str,delim,saveptr);
  309. #endif
  310. }
  311. static inline unsigned int strToUInt(const char *s) { return (unsigned int)strtoul(s,(char **)0,10); }
  312. static inline int strToInt(const char *s) { return (int)strtol(s,(char **)0,10); }
  313. static inline unsigned long strToULong(const char *s) { return strtoul(s,(char **)0,10); }
  314. static inline long strToLong(const char *s) { return strtol(s,(char **)0,10); }
  315. static inline double strToDouble(const char *s) { return strtod(s,NULL); }
  316. static inline unsigned long long strToU64(const char *s)
  317. {
  318. #ifdef __WINDOWS__
  319. return (unsigned long long)_strtoui64(s,(char **)0,10);
  320. #else
  321. return strtoull(s,(char **)0,10);
  322. #endif
  323. }
  324. static inline long long strTo64(const char *s)
  325. {
  326. #ifdef __WINDOWS__
  327. return (long long)_strtoi64(s,(char **)0,10);
  328. #else
  329. return strtoll(s,(char **)0,10);
  330. #endif
  331. }
  332. static inline unsigned int hexStrToUInt(const char *s) { return (unsigned int)strtoul(s,(char **)0,16); }
  333. static inline int hexStrToInt(const char *s) { return (int)strtol(s,(char **)0,16); }
  334. static inline unsigned long hexStrToULong(const char *s) { return strtoul(s,(char **)0,16); }
  335. static inline long hexStrToLong(const char *s) { return strtol(s,(char **)0,16); }
  336. static inline unsigned long long hexStrToU64(const char *s)
  337. {
  338. #ifdef __WINDOWS__
  339. return (unsigned long long)_strtoui64(s,(char **)0,16);
  340. #else
  341. return strtoull(s,(char **)0,16);
  342. #endif
  343. }
  344. static inline long long hexStrTo64(const char *s)
  345. {
  346. #ifdef __WINDOWS__
  347. return (long long)_strtoi64(s,(char **)0,16);
  348. #else
  349. return strtoll(s,(char **)0,16);
  350. #endif
  351. }
  352. /**
  353. * Perform a safe C string copy, ALWAYS null-terminating the result
  354. *
  355. * This will never ever EVER result in dest[] not being null-terminated
  356. * regardless of any input parameter (other than len==0 which is invalid).
  357. *
  358. * @param dest Destination buffer (must not be NULL)
  359. * @param len Length of dest[] (if zero, false is returned and nothing happens)
  360. * @param src Source string (if NULL, dest will receive a zero-length string and true is returned)
  361. * @return True on success, false on overflow (buffer will still be 0-terminated)
  362. */
  363. static inline bool scopy(char *dest,unsigned int len,const char *src)
  364. {
  365. if (!len) {
  366. return false; // sanity check
  367. }
  368. if (!src) {
  369. *dest = (char)0;
  370. return true;
  371. }
  372. char *end = dest + len;
  373. while ((*dest++ = *src++)) {
  374. if (dest == end) {
  375. *(--dest) = (char)0;
  376. return false;
  377. }
  378. }
  379. return true;
  380. }
  381. /**
  382. * Count the number of bits set in an integer
  383. *
  384. * @param v 32-bit integer
  385. * @return Number of bits set in this integer (0-32)
  386. */
  387. static inline uint32_t countBits(uint32_t v)
  388. {
  389. v = v - ((v >> 1) & (uint32_t)0x55555555);
  390. v = (v & (uint32_t)0x33333333) + ((v >> 2) & (uint32_t)0x33333333);
  391. return ((((v + (v >> 4)) & (uint32_t)0xF0F0F0F) * (uint32_t)0x1010101) >> 24);
  392. }
  393. /**
  394. * Count the number of bits set in an integer
  395. *
  396. * @param v 64-bit integer
  397. * @return Number of bits set in this integer (0-64)
  398. */
  399. static inline uint64_t countBits(uint64_t v)
  400. {
  401. v = v - ((v >> 1) & (uint64_t)~(uint64_t)0/3);
  402. v = (v & (uint64_t)~(uint64_t)0/15*3) + ((v >> 2) & (uint64_t)~(uint64_t)0/15*3);
  403. v = (v + (v >> 4)) & (uint64_t)~(uint64_t)0/255*15;
  404. return (uint64_t)(v * ((uint64_t)~(uint64_t)0/255)) >> 56;
  405. }
  406. /**
  407. * Check if a memory buffer is all-zero
  408. *
  409. * @param p Memory to scan
  410. * @param len Length of memory
  411. * @return True if memory is all zero
  412. */
  413. static inline bool isZero(const void *p,unsigned int len)
  414. {
  415. for(unsigned int i=0;i<len;++i) {
  416. if (((const unsigned char *)p)[i]) {
  417. return false;
  418. }
  419. }
  420. return true;
  421. }
  422. /**
  423. * Unconditionally swap bytes regardless of host byte order
  424. *
  425. * @param n Integer to swap
  426. * @return Integer with bytes reversed
  427. */
  428. static ZT_INLINE uint64_t swapBytes(const uint64_t n) noexcept
  429. {
  430. #ifdef __GNUC__
  431. return __builtin_bswap64(n);
  432. #else
  433. #ifdef _MSC_VER
  434. return (uint64_t)_byteswap_uint64((unsigned __int64)n);
  435. #else
  436. return (
  437. ((n & 0x00000000000000ffULL) << 56) |
  438. ((n & 0x000000000000ff00ULL) << 40) |
  439. ((n & 0x0000000000ff0000ULL) << 24) |
  440. ((n & 0x00000000ff000000ULL) << 8) |
  441. ((n & 0x000000ff00000000ULL) >> 8) |
  442. ((n & 0x0000ff0000000000ULL) >> 24) |
  443. ((n & 0x00ff000000000000ULL) >> 40) |
  444. ((n & 0xff00000000000000ULL) >> 56)
  445. );
  446. #endif
  447. #endif
  448. }
  449. /**
  450. * Unconditionally swap bytes regardless of host byte order
  451. *
  452. * @param n Integer to swap
  453. * @return Integer with bytes reversed
  454. */
  455. static ZT_INLINE uint32_t swapBytes(const uint32_t n) noexcept
  456. {
  457. #if defined(__GNUC__)
  458. return __builtin_bswap32(n);
  459. #else
  460. #ifdef _MSC_VER
  461. return (uint32_t)_byteswap_ulong((unsigned long)n);
  462. #else
  463. return htonl(n);
  464. #endif
  465. #endif
  466. }
  467. /**
  468. * Unconditionally swap bytes regardless of host byte order
  469. *
  470. * @param n Integer to swap
  471. * @return Integer with bytes reversed
  472. */
  473. static ZT_INLINE uint16_t swapBytes(const uint16_t n) noexcept
  474. {
  475. #if defined(__GNUC__)
  476. return __builtin_bswap16(n);
  477. #else
  478. #ifdef _MSC_VER
  479. return (uint16_t)_byteswap_ushort((unsigned short)n);
  480. #else
  481. return htons(n);
  482. #endif
  483. #endif
  484. }
  485. // These are helper adapters to load and swap integer types special cased by size
  486. // to work with all typedef'd variants, signed/unsigned, etc.
  487. template< typename I, unsigned int S >
  488. class _swap_bytes_bysize;
  489. template< typename I >
  490. class _swap_bytes_bysize< I, 1 >
  491. {
  492. public:
  493. static ZT_INLINE I s(const I n) noexcept
  494. { return n; }
  495. };
  496. template< typename I >
  497. class _swap_bytes_bysize< I, 2 >
  498. {
  499. public:
  500. static ZT_INLINE I s(const I n) noexcept
  501. { return (I)swapBytes((uint16_t)n); }
  502. };
  503. template< typename I >
  504. class _swap_bytes_bysize< I, 4 >
  505. {
  506. public:
  507. static ZT_INLINE I s(const I n) noexcept
  508. { return (I)swapBytes((uint32_t)n); }
  509. };
  510. template< typename I >
  511. class _swap_bytes_bysize< I, 8 >
  512. {
  513. public:
  514. static ZT_INLINE I s(const I n) noexcept
  515. { return (I)swapBytes((uint64_t)n); }
  516. };
  517. template< typename I, unsigned int S >
  518. class _load_be_bysize;
  519. template< typename I >
  520. class _load_be_bysize< I, 1 >
  521. {
  522. public:
  523. static ZT_INLINE I l(const uint8_t *const p) noexcept
  524. { return p[0]; }
  525. };
  526. template< typename I >
  527. class _load_be_bysize< I, 2 >
  528. {
  529. public:
  530. static ZT_INLINE I l(const uint8_t *const p) noexcept
  531. { return (I)(((unsigned int)p[0] << 8U) | (unsigned int)p[1]); }
  532. };
  533. template< typename I >
  534. class _load_be_bysize< I, 4 >
  535. {
  536. public:
  537. static ZT_INLINE I l(const uint8_t *const p) noexcept
  538. { return (I)(((uint32_t)p[0] << 24U) | ((uint32_t)p[1] << 16U) | ((uint32_t)p[2] << 8U) | (uint32_t)p[3]); }
  539. };
  540. template< typename I >
  541. class _load_be_bysize< I, 8 >
  542. {
  543. public:
  544. static ZT_INLINE I l(const uint8_t *const p) noexcept
  545. { return (I)(((uint64_t)p[0] << 56U) | ((uint64_t)p[1] << 48U) | ((uint64_t)p[2] << 40U) | ((uint64_t)p[3] << 32U) | ((uint64_t)p[4] << 24U) | ((uint64_t)p[5] << 16U) | ((uint64_t)p[6] << 8U) | (uint64_t)p[7]); }
  546. };
  547. template< typename I, unsigned int S >
  548. class _load_le_bysize;
  549. template< typename I >
  550. class _load_le_bysize< I, 1 >
  551. {
  552. public:
  553. static ZT_INLINE I l(const uint8_t *const p) noexcept
  554. { return p[0]; }
  555. };
  556. template< typename I >
  557. class _load_le_bysize< I, 2 >
  558. {
  559. public:
  560. static ZT_INLINE I l(const uint8_t *const p) noexcept
  561. { return (I)((unsigned int)p[0] | ((unsigned int)p[1] << 8U)); }
  562. };
  563. template< typename I >
  564. class _load_le_bysize< I, 4 >
  565. {
  566. public:
  567. static ZT_INLINE I l(const uint8_t *const p) noexcept
  568. { return (I)((uint32_t)p[0] | ((uint32_t)p[1] << 8U) | ((uint32_t)p[2] << 16U) | ((uint32_t)p[3] << 24U)); }
  569. };
  570. template< typename I >
  571. class _load_le_bysize< I, 8 >
  572. {
  573. public:
  574. static ZT_INLINE I l(const uint8_t *const p) noexcept
  575. { return (I)((uint64_t)p[0] | ((uint64_t)p[1] << 8U) | ((uint64_t)p[2] << 16U) | ((uint64_t)p[3] << 24U) | ((uint64_t)p[4] << 32U) | ((uint64_t)p[5] << 40U) | ((uint64_t)p[6] << 48U) | ((uint64_t)p[7]) << 56U); }
  576. };
  577. /**
  578. * Convert any signed or unsigned integer type to big-endian ("network") byte order
  579. *
  580. * @tparam I Integer type (usually inferred)
  581. * @param n Value to convert
  582. * @return Value in big-endian order
  583. */
  584. template< typename I >
  585. static ZT_INLINE I hton(const I n) noexcept
  586. {
  587. #if __BYTE_ORDER == __LITTLE_ENDIAN
  588. return _swap_bytes_bysize< I, sizeof(I) >::s(n);
  589. #else
  590. return n;
  591. #endif
  592. }
  593. /**
  594. * Convert any signed or unsigned integer type to host byte order from big-endian ("network") byte order
  595. *
  596. * @tparam I Integer type (usually inferred)
  597. * @param n Value to convert
  598. * @return Value in host byte order
  599. */
  600. template< typename I >
  601. static ZT_INLINE I ntoh(const I n) noexcept
  602. {
  603. #if __BYTE_ORDER == __LITTLE_ENDIAN
  604. return _swap_bytes_bysize< I, sizeof(I) >::s(n);
  605. #else
  606. return n;
  607. #endif
  608. }
  609. /**
  610. * Copy bits from memory into an integer type without modifying their order
  611. *
  612. * @tparam I Type to load
  613. * @param p Byte stream, must be at least sizeof(I) in size
  614. * @return Loaded raw integer
  615. */
  616. template< typename I >
  617. static ZT_INLINE I loadMachineEndian(const void *const p) noexcept
  618. {
  619. #ifdef ZT_NO_UNALIGNED_ACCESS
  620. I tmp;
  621. for(int i=0;i<(int)sizeof(I);++i) {
  622. reinterpret_cast<uint8_t *>(&tmp)[i] = reinterpret_cast<const uint8_t *>(p)[i];
  623. }
  624. return tmp;
  625. #else
  626. return *reinterpret_cast<const I *>(p);
  627. #endif
  628. }
  629. /**
  630. * Copy bits from memory into an integer type without modifying their order
  631. *
  632. * @tparam I Type to store
  633. * @param p Byte array (must be at least sizeof(I))
  634. * @param i Integer to store
  635. */
  636. template< typename I >
  637. static ZT_INLINE void storeMachineEndian(void *const p, const I i) noexcept
  638. {
  639. #ifdef ZT_NO_UNALIGNED_ACCESS
  640. for(unsigned int k=0;k<sizeof(I);++k) {
  641. reinterpret_cast<uint8_t *>(p)[k] = reinterpret_cast<const uint8_t *>(&i)[k];
  642. }
  643. #else
  644. *reinterpret_cast<I *>(p) = i;
  645. #endif
  646. }
  647. /**
  648. * Decode a big-endian value from a byte stream
  649. *
  650. * @tparam I Type to decode (should be unsigned e.g. uint32_t or uint64_t)
  651. * @param p Byte stream, must be at least sizeof(I) in size
  652. * @return Decoded integer
  653. */
  654. template< typename I >
  655. static ZT_INLINE I loadBigEndian(const void *const p) noexcept
  656. {
  657. #ifdef ZT_NO_UNALIGNED_ACCESS
  658. return _load_be_bysize<I,sizeof(I)>::l(reinterpret_cast<const uint8_t *>(p));
  659. #else
  660. return ntoh(*reinterpret_cast<const I *>(p));
  661. #endif
  662. }
  663. /**
  664. * Save an integer in big-endian format
  665. *
  666. * @tparam I Integer type to store (usually inferred)
  667. * @param p Byte stream to write (must be at least sizeof(I))
  668. * #param i Integer to write
  669. */
  670. template< typename I >
  671. static ZT_INLINE void storeBigEndian(void *const p, I i) noexcept
  672. {
  673. #ifdef ZT_NO_UNALIGNED_ACCESS
  674. storeMachineEndian(p,hton(i));
  675. #else
  676. *reinterpret_cast<I *>(p) = hton(i);
  677. #endif
  678. }
  679. /**
  680. * Decode a little-endian value from a byte stream
  681. *
  682. * @tparam I Type to decode
  683. * @param p Byte stream, must be at least sizeof(I) in size
  684. * @return Decoded integer
  685. */
  686. template< typename I >
  687. static ZT_INLINE I loadLittleEndian(const void *const p) noexcept
  688. {
  689. #if __BYTE_ORDER == __BIG_ENDIAN || defined(ZT_NO_UNALIGNED_ACCESS)
  690. return _load_le_bysize<I,sizeof(I)>::l(reinterpret_cast<const uint8_t *>(p));
  691. #else
  692. return *reinterpret_cast<const I *>(p);
  693. #endif
  694. }
  695. /**
  696. * Save an integer in little-endian format
  697. *
  698. * @tparam I Integer type to store (usually inferred)
  699. * @param p Byte stream to write (must be at least sizeof(I))
  700. * #param i Integer to write
  701. */
  702. template< typename I >
  703. static ZT_INLINE void storeLittleEndian(void *const p, const I i) noexcept
  704. {
  705. #if __BYTE_ORDER == __BIG_ENDIAN
  706. storeMachineEndian(p,_swap_bytes_bysize<I,sizeof(I)>::s(i));
  707. #else
  708. #ifdef ZT_NO_UNALIGNED_ACCESS
  709. storeMachineEndian(p,i);
  710. #else
  711. *reinterpret_cast<I *>(p) = i;
  712. #endif
  713. #endif
  714. }
  715. /**
  716. * Copy memory block whose size is known at compile time.
  717. *
  718. * @tparam L Size of memory
  719. * @param dest Destination memory
  720. * @param src Source memory
  721. */
  722. template< unsigned long L >
  723. static ZT_INLINE void copy(void *dest, const void *src) noexcept
  724. {
  725. #if defined(ZT_ARCH_X64) && defined(__GNUC__)
  726. uintptr_t l = L;
  727. __asm__ __volatile__ ("cld ; rep movsb" : "+c"(l), "+S"(src), "+D"(dest) :: "memory");
  728. #else
  729. memcpy(dest, src, L);
  730. #endif
  731. }
  732. /**
  733. * Copy memory block whose size is known at run time
  734. *
  735. * @param dest Destination memory
  736. * @param src Source memory
  737. * @param len Bytes to copy
  738. */
  739. static ZT_INLINE void copy(void *dest, const void *src, unsigned long len) noexcept
  740. {
  741. #if defined(ZT_ARCH_X64) && defined(__GNUC__)
  742. __asm__ __volatile__ ("cld ; rep movsb" : "+c"(len), "+S"(src), "+D"(dest) :: "memory");
  743. #else
  744. memcpy(dest, src, len);
  745. #endif
  746. }
  747. /**
  748. * Zero memory block whose size is known at compile time
  749. *
  750. * @tparam L Size in bytes
  751. * @param dest Memory to zero
  752. */
  753. template< unsigned long L >
  754. static ZT_INLINE void zero(void *dest) noexcept
  755. {
  756. #if defined(ZT_ARCH_X64) && defined(__GNUC__)
  757. uintptr_t l = L;
  758. __asm__ __volatile__ ("cld ; rep stosb" :"+c" (l), "+D" (dest) : "a" (0) : "memory");
  759. #else
  760. memset(dest, 0, L);
  761. #endif
  762. }
  763. /**
  764. * Zero memory block whose size is known at run time
  765. *
  766. * @param dest Memory to zero
  767. * @param len Size in bytes
  768. */
  769. static ZT_INLINE void zero(void *dest, unsigned long len) noexcept
  770. {
  771. #if defined(ZT_ARCH_X64) && defined(__GNUC__)
  772. __asm__ __volatile__ ("cld ; rep stosb" :"+c" (len), "+D" (dest) : "a" (0) : "memory");
  773. #else
  774. memset(dest, 0, len);
  775. #endif
  776. }
  777. /**
  778. * Hexadecimal characters 0-f
  779. */
  780. static const char HEXCHARS[16];
  781. /*
  782. * Remove `-` and `:` from a MAC address (in-place).
  783. *
  784. * @param mac The MAC address
  785. */
  786. static inline void cleanMac(std::string& mac)
  787. {
  788. auto start = mac.begin();
  789. auto end = mac.end();
  790. auto new_end = std::remove_if(start, end, [](char c) { return c == 45 || c == 58; });
  791. mac.erase(new_end, end);
  792. }
  793. };
  794. } // namespace ZeroTier
  795. #endif