Utils.hpp 13 KB

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