Utils.hpp 14 KB

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