Utils.hpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571
  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_UTILS_HPP
  14. #define ZT_UTILS_HPP
  15. #include "Constants.hpp"
  16. #include <cstdlib>
  17. #include <cstring>
  18. namespace ZeroTier {
  19. namespace Utils {
  20. #ifdef ZT_ARCH_X64
  21. struct CPUIDRegisters
  22. {
  23. uint32_t eax,ebx,ecx,edx;
  24. bool rdrand;
  25. bool aes;
  26. CPUIDRegisters();
  27. };
  28. extern const CPUIDRegisters CPUID;
  29. #endif
  30. /**
  31. * 256 zero bits / 32 zero bytes
  32. */
  33. extern const uint64_t ZERO256[4];
  34. /**
  35. * Hexadecimal characters 0-f
  36. */
  37. extern const char HEXCHARS[16];
  38. /**
  39. * Perform a time-invariant binary comparison
  40. *
  41. * @param a First binary string
  42. * @param b Second binary string
  43. * @param len Length of strings
  44. * @return True if strings are equal
  45. */
  46. bool secureEq(const void *a,const void *b,unsigned int len) noexcept;
  47. /**
  48. * Be absolutely sure to zero memory
  49. *
  50. * This uses some hacks to be totally sure the compiler does not optimize it out.
  51. *
  52. * @param ptr Memory to zero
  53. * @param len Length of memory in bytes
  54. */
  55. void burn(void *ptr,unsigned int len);
  56. /**
  57. * @param n Number to convert
  58. * @param s Buffer, at least 24 bytes in size
  59. * @return String containing 'n' in base 10 form
  60. */
  61. char *decimal(unsigned long n,char s[24]) noexcept;
  62. /**
  63. * Convert an unsigned integer into hex
  64. *
  65. * @param i Any unsigned integer
  66. * @param s Buffer to receive hex, must be at least (2*sizeof(i))+1 in size or overflow will occur.
  67. * @return Pointer to s containing hex string with trailing zero byte
  68. */
  69. char *hex(uint8_t i,char s[3]) noexcept;
  70. /**
  71. * Convert an unsigned integer into hex
  72. *
  73. * @param i Any unsigned integer
  74. * @param s Buffer to receive hex, must be at least (2*sizeof(i))+1 in size or overflow will occur.
  75. * @return Pointer to s containing hex string with trailing zero byte
  76. */
  77. char *hex(uint16_t i,char s[5]) noexcept;
  78. /**
  79. * Convert an unsigned integer into hex
  80. *
  81. * @param i Any unsigned integer
  82. * @param s Buffer to receive hex, must be at least (2*sizeof(i))+1 in size or overflow will occur.
  83. * @return Pointer to s containing hex string with trailing zero byte
  84. */
  85. char *hex(uint32_t i,char s[9]) noexcept;
  86. /**
  87. * Convert an unsigned integer into hex
  88. *
  89. * @param i Any unsigned integer
  90. * @param s Buffer to receive hex, must be at least (2*sizeof(i))+1 in size or overflow will occur.
  91. * @return Pointer to s containing hex string with trailing zero byte
  92. */
  93. char *hex(uint64_t i,char s[17]) noexcept;
  94. /**
  95. * Decode an unsigned integer in hex format
  96. *
  97. * @param s String to decode, non-hex chars are ignored
  98. * @return Unsigned integer
  99. */
  100. uint64_t unhex(const char *s) noexcept;
  101. /**
  102. * Convert the least significant 40 bits of a uint64_t to hex
  103. *
  104. * @param i Unsigned 64-bit int
  105. * @param s Buffer of size [11] to receive 10 hex characters
  106. * @return Pointer to buffer
  107. */
  108. char *hex10(uint64_t i,char s[11]) noexcept;
  109. /**
  110. * Convert a byte array into hex
  111. *
  112. * @param d Bytes
  113. * @param l Length of bytes
  114. * @param s String buffer, must be at least (l*2)+1 in size or overflow will occur
  115. * @return Pointer to filled string buffer
  116. */
  117. char *hex(const void *d,unsigned int l,char *s) noexcept;
  118. /**
  119. * Decode a hex string
  120. *
  121. * @param h Hex C-string (non hex chars are ignored)
  122. * @param hlen Maximum length of string (will stop at terminating zero)
  123. * @param buf Output buffer
  124. * @param buflen Length of output buffer
  125. * @return Number of written bytes
  126. */
  127. unsigned int unhex(const char *h,unsigned int hlen,void *buf,unsigned int buflen) noexcept;
  128. /**
  129. * Generate secure random bytes
  130. *
  131. * This will try to use whatever OS sources of entropy are available. It's
  132. * guarded by an internal mutex so it's thread-safe.
  133. *
  134. * @param buf Buffer to fill
  135. * @param bytes Number of random bytes to generate
  136. */
  137. void getSecureRandom(void *buf,unsigned int bytes) noexcept;
  138. /**
  139. * @return Secure random 64-bit integer
  140. */
  141. uint64_t getSecureRandomU64() noexcept;
  142. /**
  143. * Encode string to base32
  144. *
  145. * @param data Binary data to encode
  146. * @param length Length of data in bytes
  147. * @param result Result buffer
  148. * @param bufSize Size of result buffer
  149. * @return Number of bytes written
  150. */
  151. int b32e(const uint8_t *data,int length,char *result,int bufSize) noexcept;
  152. /**
  153. * Decode base32 string
  154. *
  155. * @param encoded C-string in base32 format (non-base32 characters are ignored)
  156. * @param result Result buffer
  157. * @param bufSize Size of result buffer
  158. * @return Number of bytes written or -1 on error
  159. */
  160. int b32d(const char *encoded, uint8_t *result, int bufSize) noexcept;
  161. /**
  162. * Get a non-cryptographic random integer
  163. */
  164. uint64_t random() noexcept;
  165. /**
  166. * Perform a safe C string copy, ALWAYS null-terminating the result
  167. *
  168. * This will never ever EVER result in dest[] not being null-terminated
  169. * regardless of any input parameter (other than len==0 which is invalid).
  170. *
  171. * @param dest Destination buffer (must not be NULL)
  172. * @param len Length of dest[] (if zero, false is returned and nothing happens)
  173. * @param src Source string (if NULL, dest will receive a zero-length string and true is returned)
  174. * @return True on success, false on overflow (buffer will still be 0-terminated)
  175. */
  176. bool scopy(char *dest,unsigned int len,const char *src) noexcept;
  177. /**
  178. * Mix bits in a 64-bit integer
  179. *
  180. * https://nullprogram.com/blog/2018/07/31/
  181. *
  182. * @param x Integer to mix
  183. * @return Hashed value
  184. */
  185. static ZT_ALWAYS_INLINE uint64_t hash64(uint64_t x) noexcept
  186. {
  187. x ^= x >> 30U;
  188. x *= 0xbf58476d1ce4e5b9ULL;
  189. x ^= x >> 27U;
  190. x *= 0x94d049bb133111ebULL;
  191. x ^= x >> 31U;
  192. return x;
  193. }
  194. /**
  195. * @param b Buffer to check
  196. * @param l Length of buffer
  197. * @return True if buffer is all zero
  198. */
  199. static ZT_ALWAYS_INLINE bool allZero(const void *const b,const unsigned int l) noexcept
  200. {
  201. const uint8_t *x = reinterpret_cast<const uint8_t *>(b);
  202. const uint8_t *const y = x + l;
  203. while (x != y) {
  204. if (*x != 0)
  205. return false;
  206. ++x;
  207. }
  208. return true;
  209. }
  210. /**
  211. * Wrapper around reentrant strtok functions, which differ in name by platform
  212. *
  213. * @param str String to tokenize or NULL for subsequent calls
  214. * @param delim Delimiter
  215. * @param saveptr Pointer to pointer where function can save state
  216. * @return Next token or NULL if none
  217. */
  218. static ZT_ALWAYS_INLINE char *stok(char *str,const char *delim,char **saveptr) noexcept
  219. {
  220. #ifdef __WINDOWS__
  221. return strtok_s(str,delim,saveptr);
  222. #else
  223. return strtok_r(str,delim,saveptr);
  224. #endif
  225. }
  226. static ZT_ALWAYS_INLINE unsigned int strToUInt(const char *s) noexcept
  227. {
  228. return (unsigned int)strtoul(s,nullptr,10);
  229. }
  230. static ZT_ALWAYS_INLINE unsigned long long hexStrToU64(const char *s) noexcept
  231. {
  232. #ifdef __WINDOWS__
  233. return (unsigned long long)_strtoui64(s,nullptr,16);
  234. #else
  235. return strtoull(s,nullptr,16);
  236. #endif
  237. }
  238. /**
  239. * Calculate a non-cryptographic hash of a byte string
  240. *
  241. * @param key Key to hash
  242. * @param len Length in bytes
  243. * @return Non-cryptographic hash suitable for use in a hash table
  244. */
  245. static ZT_ALWAYS_INLINE unsigned long hashString(const void *restrict key,const unsigned int len) noexcept
  246. {
  247. const uint8_t *p = reinterpret_cast<const uint8_t *>(key);
  248. unsigned long h = 0;
  249. for (unsigned int i=0;i<len;++i) {
  250. h += p[i];
  251. h += (h << 10U);
  252. h ^= (h >> 6U);
  253. }
  254. h += (h << 3U);
  255. h ^= (h >> 11U);
  256. h += (h << 15U);
  257. return h;
  258. }
  259. #ifdef __GNUC__
  260. static ZT_ALWAYS_INLINE unsigned int countBits(const uint8_t v) noexcept { return (unsigned int)__builtin_popcount((unsigned int)v); }
  261. static ZT_ALWAYS_INLINE unsigned int countBits(const uint16_t v) noexcept { return (unsigned int)__builtin_popcount((unsigned int)v); }
  262. static ZT_ALWAYS_INLINE unsigned int countBits(const uint32_t v) noexcept { return (unsigned int)__builtin_popcountl((unsigned long)v); }
  263. static ZT_ALWAYS_INLINE unsigned int countBits(const uint64_t v) noexcept{ return (unsigned int)__builtin_popcountll((unsigned long long)v); }
  264. #else
  265. template<typename T>
  266. static ZT_ALWAYS_INLINE unsigned int countBits(T v) noexcept
  267. {
  268. v = v - ((v >> 1) & (T)~(T)0/3);
  269. v = (v & (T)~(T)0/15*3) + ((v >> 2) & (T)~(T)0/15*3);
  270. v = (v + (v >> 4)) & (T)~(T)0/255*15;
  271. return (unsigned int)((v * ((~((T)0))/((T)255))) >> ((sizeof(T) - 1) * 8));
  272. }
  273. #endif
  274. #if __BYTE_ORDER == __LITTLE_ENDIAN
  275. static ZT_ALWAYS_INLINE uint8_t hton(uint8_t n) noexcept { return n; }
  276. static ZT_ALWAYS_INLINE int8_t hton(int8_t n) noexcept { return n; }
  277. static ZT_ALWAYS_INLINE uint16_t hton(uint16_t n) noexcept
  278. {
  279. #if defined(__GNUC__)
  280. #if defined(__FreeBSD__)
  281. return htons(n);
  282. #elif (!defined(__OpenBSD__))
  283. return __builtin_bswap16(n);
  284. #endif
  285. #else
  286. return htons(n);
  287. #endif
  288. }
  289. static ZT_ALWAYS_INLINE int16_t hton(int16_t n) noexcept { return (int16_t)Utils::hton((uint16_t)n); }
  290. static ZT_ALWAYS_INLINE uint32_t hton(uint32_t n) noexcept
  291. {
  292. #if defined(__GNUC__)
  293. #if defined(__FreeBSD__)
  294. return htonl(n);
  295. #elif (!defined(__OpenBSD__))
  296. return __builtin_bswap32(n);
  297. #endif
  298. #else
  299. return htonl(n);
  300. #endif
  301. }
  302. static ZT_ALWAYS_INLINE int32_t hton(int32_t n) noexcept { return (int32_t)Utils::hton((uint32_t)n); }
  303. static ZT_ALWAYS_INLINE uint64_t hton(uint64_t n) noexcept
  304. {
  305. #if defined(__GNUC__)
  306. #if defined(__FreeBSD__)
  307. return bswap64(n);
  308. #elif (!defined(__OpenBSD__))
  309. return __builtin_bswap64(n);
  310. #endif
  311. #else
  312. return (
  313. ((n & 0x00000000000000FFULL) << 56) |
  314. ((n & 0x000000000000FF00ULL) << 40) |
  315. ((n & 0x0000000000FF0000ULL) << 24) |
  316. ((n & 0x00000000FF000000ULL) << 8) |
  317. ((n & 0x000000FF00000000ULL) >> 8) |
  318. ((n & 0x0000FF0000000000ULL) >> 24) |
  319. ((n & 0x00FF000000000000ULL) >> 40) |
  320. ((n & 0xFF00000000000000ULL) >> 56)
  321. );
  322. #endif
  323. }
  324. static ZT_ALWAYS_INLINE int64_t hton(int64_t n) noexcept { return (int64_t)hton((uint64_t)n); }
  325. #else
  326. template<typename T>
  327. static ZT_ALWAYS_INLINE T hton(T n) noexcept { return n; }
  328. #endif
  329. #if __BYTE_ORDER == __LITTLE_ENDIAN
  330. static ZT_ALWAYS_INLINE uint8_t ntoh(uint8_t n) noexcept { return n; }
  331. static ZT_ALWAYS_INLINE int8_t ntoh(int8_t n) noexcept { return n; }
  332. static ZT_ALWAYS_INLINE uint16_t ntoh(uint16_t n) noexcept
  333. {
  334. #if defined(__GNUC__)
  335. #if defined(__FreeBSD__)
  336. return htons(n);
  337. #elif (!defined(__OpenBSD__))
  338. return __builtin_bswap16(n);
  339. #endif
  340. #else
  341. return htons(n);
  342. #endif
  343. }
  344. static ZT_ALWAYS_INLINE int16_t ntoh(int16_t n) noexcept { return (int16_t)Utils::ntoh((uint16_t)n); }
  345. static ZT_ALWAYS_INLINE uint32_t ntoh(uint32_t n) noexcept
  346. {
  347. #if defined(__GNUC__)
  348. #if defined(__FreeBSD__)
  349. return ntohl(n);
  350. #elif (!defined(__OpenBSD__))
  351. return __builtin_bswap32(n);
  352. #endif
  353. #else
  354. return ntohl(n);
  355. #endif
  356. }
  357. static ZT_ALWAYS_INLINE int32_t ntoh(int32_t n) noexcept { return (int32_t)Utils::ntoh((uint32_t)n); }
  358. static ZT_ALWAYS_INLINE uint64_t ntoh(uint64_t n) noexcept
  359. {
  360. #if defined(__GNUC__)
  361. #if defined(__FreeBSD__)
  362. return bswap64(n);
  363. #elif (!defined(__OpenBSD__))
  364. return __builtin_bswap64(n);
  365. #endif
  366. #else
  367. return (
  368. ((n & 0x00000000000000FFULL) << 56) |
  369. ((n & 0x000000000000FF00ULL) << 40) |
  370. ((n & 0x0000000000FF0000ULL) << 24) |
  371. ((n & 0x00000000FF000000ULL) << 8) |
  372. ((n & 0x000000FF00000000ULL) >> 8) |
  373. ((n & 0x0000FF0000000000ULL) >> 24) |
  374. ((n & 0x00FF000000000000ULL) >> 40) |
  375. ((n & 0xFF00000000000000ULL) >> 56)
  376. );
  377. #endif
  378. }
  379. static ZT_ALWAYS_INLINE int64_t ntoh(int64_t n) noexcept { return (int64_t)ntoh((uint64_t)n); }
  380. #else
  381. template<typename T>
  382. static ZT_ALWAYS_INLINE T ntoh(T n) noexcept { return n; }
  383. #endif
  384. /**
  385. * Decode a big-endian value from a byte stream
  386. *
  387. * @tparam I Type to decode (should be unsigned e.g. uint32_t or uint64_t)
  388. * @param p Byte stream, must be at least sizeof(I) in size
  389. * @return Decoded integer
  390. */
  391. template<typename I>
  392. static ZT_ALWAYS_INLINE I loadBigEndian(const void *const p) noexcept
  393. {
  394. #ifdef ZT_NO_UNALIGNED_ACCESS
  395. I x = (I)0;
  396. for(unsigned int k=0;k<sizeof(I);++k) {
  397. #if __BYTE_ORDER == __LITTLE_ENDIAN
  398. reinterpret_cast<uint8_t *>(&x)[k] = reinterpret_cast<const uint8_t *>(p)[(sizeof(I)-1)-k];
  399. #else
  400. reinterpret_cast<uint8_t *>(&x)[k] = reinterpret_cast<const uint8_t *>(p)[k];
  401. #endif
  402. }
  403. return x;
  404. #else
  405. return ntoh(*reinterpret_cast<const I *>(p));
  406. #endif
  407. }
  408. /**
  409. * Save an integer in big-endian format
  410. *
  411. * @tparam I Integer type to store (usually inferred)
  412. * @param p Byte stream to write (must be at least sizeof(I))
  413. * #param i Integer to write
  414. */
  415. template<typename I>
  416. static ZT_ALWAYS_INLINE void storeBigEndian(void *const p,const I i) noexcept
  417. {
  418. #ifdef ZT_NO_UNALIGNED_ACCESS
  419. for(unsigned int k=0;k<sizeof(I);++k) {
  420. #if __BYTE_ORDER == __LITTLE_ENDIAN
  421. reinterpret_cast<uint8_t *>(p)[k] = reinterpret_cast<const uint8_t *>(&i)[(sizeof(I)-1)-k];
  422. #else
  423. reinterpret_cast<uint8_t *>(p)[k] = reinterpret_cast<const uint8_t *>(&i)[k];
  424. #endif
  425. }
  426. #else
  427. *reinterpret_cast<I *>(p) = hton(i);
  428. #endif
  429. }
  430. /**
  431. * Decode a little-endian value from a byte stream
  432. *
  433. * @tparam I Type to decode (should be unsigned e.g. uint32_t or uint64_t)
  434. * @param p Byte stream, must be at least sizeof(I) in size
  435. * @return Decoded integer
  436. */
  437. template<typename I>
  438. static ZT_ALWAYS_INLINE I loadLittleEndian(const void *const p) noexcept
  439. {
  440. #ifdef ZT_NO_UNALIGNED_ACCESS
  441. I x = (I)0;
  442. for(unsigned int k=0;k<sizeof(I);++k) {
  443. #if __BYTE_ORDER == __LITTLE_ENDIAN
  444. reinterpret_cast<uint8_t *>(&x)[k] = reinterpret_cast<const uint8_t *>(p)[k];
  445. #else
  446. reinterpret_cast<uint8_t *>(&x)[k] = reinterpret_cast<const uint8_t *>(p)[(sizeof(I)-1)-k];
  447. #endif
  448. }
  449. return x;
  450. #else
  451. #if __BYTE_ORDER == __LITTLE_ENDIAN
  452. return *reinterpret_cast<const I *>(p);
  453. #else
  454. I x = (I)0;
  455. for(unsigned int k=0;k<sizeof(I);++k) {
  456. reinterpret_cast<uint8_t *>(&x)[k] = reinterpret_cast<const uint8_t *>(p)[(sizeof(I)-1)-k];
  457. }
  458. return x;
  459. #endif
  460. #endif
  461. }
  462. /**
  463. * Save an integer in little-endian format
  464. *
  465. * @tparam I Integer type to store (usually inferred)
  466. * @param p Byte stream to write (must be at least sizeof(I))
  467. * #param i Integer to write
  468. */
  469. template<typename I>
  470. static ZT_ALWAYS_INLINE void storeLittleEndian(void *const p,const I i) noexcept
  471. {
  472. #ifdef ZT_NO_UNALIGNED_ACCESS
  473. for(unsigned int k=0;k<sizeof(I);++k) {
  474. #if __BYTE_ORDER == __LITTLE_ENDIAN
  475. reinterpret_cast<uint8_t *>(p)[k] = reinterpret_cast<const uint8_t *>(&i)[k];
  476. #else
  477. reinterpret_cast<uint8_t *>(p)[k] = reinterpret_cast<const uint8_t *>(&i)[(sizeof(I)-1)-k];
  478. #endif
  479. }
  480. #else
  481. #if __BYTE_ORDER == __LITTLE_ENDIAN
  482. *reinterpret_cast<I *>(p) = i;
  483. #else
  484. for(unsigned int k=0;k<sizeof(I);++k) {
  485. reinterpret_cast<uint8_t *>(p)[k] = reinterpret_cast<const uint8_t *>(&i)[(sizeof(I)-1)-k];
  486. }
  487. #endif
  488. #endif
  489. }
  490. /**
  491. * Copy bits from memory into an integer type without modifying their order
  492. *
  493. * @tparam I Type to load
  494. * @param p Byte stream, must be at least sizeof(I) in size
  495. * @return Loaded raw integer
  496. */
  497. template<typename I>
  498. static ZT_ALWAYS_INLINE I loadAsIsEndian(const void *const p) noexcept
  499. {
  500. #ifdef ZT_NO_UNALIGNED_ACCESS
  501. I x = (I)0;
  502. for(unsigned int k=0;k<sizeof(I);++k)
  503. reinterpret_cast<uint8_t *>(&x)[k] = reinterpret_cast<const uint8_t *>(p)[k];
  504. return x;
  505. #else
  506. return *reinterpret_cast<const I *>(p);
  507. #endif
  508. }
  509. /**
  510. * Copy bits from memory into an integer type without modifying their order
  511. *
  512. * @tparam I Type to store
  513. * @param p Byte array (must be at least sizeof(I))
  514. * @param i Integer to store
  515. */
  516. template<typename I>
  517. static ZT_ALWAYS_INLINE void storeAsIsEndian(void *const p,const I i) noexcept
  518. {
  519. #ifdef ZT_NO_UNALIGNED_ACCESS
  520. for(unsigned int k=0;k<sizeof(I);++k)
  521. reinterpret_cast<uint8_t *>(p)[k] = reinterpret_cast<const uint8_t *>(&i)[k];
  522. #else
  523. *reinterpret_cast<I *>(p) = i;
  524. #endif
  525. }
  526. } // namespace Utils
  527. } // namespace ZeroTier
  528. #endif