Utils.hpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423
  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: 2023-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. #if (defined(__amd64) || defined(__amd64__) || defined(__x86_64) || defined(__x86_64__) || defined(__AMD64) || defined(__AMD64__) || defined(_M_X64))
  21. #include <emmintrin.h>
  22. #include <xmmintrin.h>
  23. #include <immintrin.h>
  24. #endif
  25. #include <string>
  26. #include <stdexcept>
  27. #include <vector>
  28. #include <map>
  29. #include "Constants.hpp"
  30. namespace ZeroTier {
  31. namespace Utils {
  32. #if (defined(__amd64) || defined(__amd64__) || defined(__x86_64) || defined(__x86_64__) || defined(__AMD64) || defined(__AMD64__) || defined(_M_X64))
  33. struct CPUIDRegisters
  34. {
  35. uint32_t eax,ebx,ecx,edx;
  36. bool rdrand;
  37. bool aes;
  38. CPUIDRegisters();
  39. };
  40. extern CPUIDRegisters CPUID;
  41. #endif
  42. /**
  43. * Hexadecimal characters 0-f
  44. */
  45. extern const char HEXCHARS[16];
  46. /**
  47. * Perform a time-invariant binary comparison
  48. *
  49. * @param a First binary string
  50. * @param b Second binary string
  51. * @param len Length of strings
  52. * @return True if strings are equal
  53. */
  54. bool secureEq(const void *a,const void *b,unsigned int len);
  55. /**
  56. * Zero memory, ensuring to avoid any compiler optimizations or other things that may stop this.
  57. */
  58. void burn(void *ptr,unsigned int len);
  59. /**
  60. * @param n Number to convert
  61. * @param s Buffer, at least 24 bytes in size
  62. * @return String containing 'n' in base 10 form
  63. */
  64. char *decimal(unsigned long n,char s[24]);
  65. /**
  66. * Convert an unsigned integer into hex
  67. *
  68. * @param i Any unsigned integer
  69. * @param s Buffer to receive hex, must be at least (2*sizeof(i))+1 in size or overflow will occur.
  70. * @return Pointer to s containing hex string with trailing zero byte
  71. */
  72. template<typename I>
  73. static inline char *hex(I x,char *s)
  74. {
  75. char *const r = s;
  76. for(unsigned int i=0,b=(sizeof(x)*8);i<sizeof(x);++i) {
  77. *(s++) = HEXCHARS[(x >> (b -= 4)) & 0xf];
  78. *(s++) = HEXCHARS[(x >> (b -= 4)) & 0xf];
  79. }
  80. *s = (char)0;
  81. return r;
  82. }
  83. /**
  84. * Convert the least significant 40 bits of a uint64_t to hex
  85. *
  86. * @param i Unsigned 64-bit int
  87. * @param s Buffer of size [11] to receive 10 hex characters
  88. * @return Pointer to buffer
  89. */
  90. char *hex10(uint64_t i,char s[11]);
  91. /**
  92. * Convert a byte array into hex
  93. *
  94. * @param d Bytes
  95. * @param l Length of bytes
  96. * @param s String buffer, must be at least (l*2)+1 in size or overflow will occur
  97. * @return Pointer to filled string buffer
  98. */
  99. char *hex(const void *d,unsigned int l,char *s);
  100. /**
  101. * Decode a hex string
  102. *
  103. * @param h Hex C-string (non hex chars are ignored)
  104. * @param hlen Maximum length of string (will stop at terminating zero)
  105. * @param buf Output buffer
  106. * @param buflen Length of output buffer
  107. * @return Number of written bytes
  108. */
  109. unsigned int unhex(const char *h,unsigned int hlen,void *buf,unsigned int buflen);
  110. /**
  111. * Generate secure random bytes
  112. *
  113. * This will try to use whatever OS sources of entropy are available. It's
  114. * guarded by an internal mutex so it's thread-safe.
  115. *
  116. * @param buf Buffer to fill
  117. * @param bytes Number of random bytes to generate
  118. */
  119. void getSecureRandom(void *buf,unsigned int bytes);
  120. /**
  121. * Encode string to base32
  122. *
  123. * @param data Binary data to encode
  124. * @param length Length of data in bytes
  125. * @param result Result buffer
  126. * @param bufSize Size of result buffer
  127. * @return Number of bytes written
  128. */
  129. int b32e(const uint8_t *data,int length,char *result,int bufSize);
  130. /**
  131. * Decode base32 string
  132. *
  133. * @param encoded C-string in base32 format (non-base32 characters are ignored)
  134. * @param result Result buffer
  135. * @param bufSize Size of result buffer
  136. * @return Number of bytes written or -1 on error
  137. */
  138. int b32d(const char *encoded, uint8_t *result, int bufSize);
  139. /**
  140. * Get a non-cryptographic random integer
  141. */
  142. uint64_t random();
  143. /**
  144. * Perform a safe C string copy, ALWAYS null-terminating the result
  145. *
  146. * This will never ever EVER result in dest[] not being null-terminated
  147. * regardless of any input parameter (other than len==0 which is invalid).
  148. *
  149. * @param dest Destination buffer (must not be NULL)
  150. * @param len Length of dest[] (if zero, false is returned and nothing happens)
  151. * @param src Source string (if NULL, dest will receive a zero-length string and true is returned)
  152. * @return True on success, false on overflow (buffer will still be 0-terminated)
  153. */
  154. bool scopy(char *dest,unsigned int len,const char *src);
  155. /**
  156. * Tokenize a string (alias for strtok_r or strtok_s depending on platform)
  157. *
  158. * @param str String to split
  159. * @param delim Delimiters
  160. * @param saveptr Pointer to a char * for temporary reentrant storage
  161. */
  162. ZT_ALWAYS_INLINE char *stok(char *str,const char *delim,char **saveptr)
  163. {
  164. #ifdef __WINDOWS__
  165. return strtok_s(str,delim,saveptr);
  166. #else
  167. return strtok_r(str,delim,saveptr);
  168. #endif
  169. }
  170. ZT_ALWAYS_INLINE unsigned int strToUInt(const char *s) { return (unsigned int)strtoul(s,(char **)0,10); }
  171. ZT_ALWAYS_INLINE int strToInt(const char *s) { return (int)strtol(s,(char **)0,10); }
  172. ZT_ALWAYS_INLINE unsigned long strToULong(const char *s) { return strtoul(s,(char **)0,10); }
  173. ZT_ALWAYS_INLINE long strToLong(const char *s) { return strtol(s,(char **)0,10); }
  174. ZT_ALWAYS_INLINE unsigned long long strToU64(const char *s)
  175. {
  176. #ifdef __WINDOWS__
  177. return (unsigned long long)_strtoui64(s,(char **)0,10);
  178. #else
  179. return strtoull(s,(char **)0,10);
  180. #endif
  181. }
  182. ZT_ALWAYS_INLINE long long strTo64(const char *s)
  183. {
  184. #ifdef __WINDOWS__
  185. return (long long)_strtoi64(s,(char **)0,10);
  186. #else
  187. return strtoll(s,(char **)0,10);
  188. #endif
  189. }
  190. ZT_ALWAYS_INLINE unsigned int hexStrToUInt(const char *s) { return (unsigned int)strtoul(s,(char **)0,16); }
  191. ZT_ALWAYS_INLINE int hexStrToInt(const char *s) { return (int)strtol(s,(char **)0,16); }
  192. ZT_ALWAYS_INLINE unsigned long hexStrToULong(const char *s) { return strtoul(s,(char **)0,16); }
  193. ZT_ALWAYS_INLINE long hexStrToLong(const char *s) { return strtol(s,(char **)0,16); }
  194. ZT_ALWAYS_INLINE unsigned long long hexStrToU64(const char *s)
  195. {
  196. #ifdef __WINDOWS__
  197. return (unsigned long long)_strtoui64(s,(char **)0,16);
  198. #else
  199. return strtoull(s,(char **)0,16);
  200. #endif
  201. }
  202. ZT_ALWAYS_INLINE long long hexStrTo64(const char *s)
  203. {
  204. #ifdef __WINDOWS__
  205. return (long long)_strtoi64(s,(char **)0,16);
  206. #else
  207. return strtoll(s,(char **)0,16);
  208. #endif
  209. }
  210. /**
  211. * Calculate a non-cryptographic hash of a byte string
  212. *
  213. * @param key Key to hash
  214. * @param len Length in bytes
  215. * @return Non-cryptographic hash suitable for use in a hash table
  216. */
  217. ZT_ALWAYS_INLINE unsigned long hashString(const void *restrict key,const unsigned int len)
  218. {
  219. const uint8_t *p = reinterpret_cast<const uint8_t *>(key);
  220. unsigned long h = 0;
  221. for (unsigned int i=0;i<len;++i) {
  222. h += p[i];
  223. h += (h << 10);
  224. h ^= (h >> 6);
  225. }
  226. h += (h << 3);
  227. h ^= (h >> 11);
  228. h += (h << 15);
  229. return h;
  230. }
  231. #ifdef __GNUC__
  232. ZT_ALWAYS_INLINE unsigned int countBits(const uint8_t v) { return (unsigned int)__builtin_popcount((unsigned int)v); }
  233. ZT_ALWAYS_INLINE unsigned int countBits(const uint16_t v) { return (unsigned int)__builtin_popcount((unsigned int)v); }
  234. ZT_ALWAYS_INLINE unsigned int countBits(const uint32_t v) { return (unsigned int)__builtin_popcountl((unsigned long)v); }
  235. ZT_ALWAYS_INLINE unsigned int countBits(const uint64_t v) { return (unsigned int)__builtin_popcountll((unsigned long long)v); }
  236. #else
  237. template<typename T>
  238. ZT_ALWAYS_INLINE unsigned int countBits(T v)
  239. {
  240. v = v - ((v >> 1) & (T)~(T)0/3);
  241. v = (v & (T)~(T)0/15*3) + ((v >> 2) & (T)~(T)0/15*3);
  242. v = (v + (v >> 4)) & (T)~(T)0/255*15;
  243. return (unsigned int)((v * ((~((T)0))/((T)255))) >> ((sizeof(T) - 1) * 8));
  244. }
  245. #endif
  246. #if __BYTE_ORDER == __LITTLE_ENDIAN
  247. ZT_ALWAYS_INLINE uint8_t hton(uint8_t n) { return n; }
  248. ZT_ALWAYS_INLINE int8_t hton(int8_t n) { return n; }
  249. ZT_ALWAYS_INLINE uint16_t hton(uint16_t n)
  250. {
  251. #if defined(__GNUC__)
  252. #if defined(__FreeBSD__)
  253. return htons(n);
  254. #elif (!defined(__OpenBSD__))
  255. return __builtin_bswap16(n);
  256. #endif
  257. #else
  258. return htons(n);
  259. #endif
  260. }
  261. ZT_ALWAYS_INLINE int16_t hton(int16_t n) { return (int16_t)Utils::hton((uint16_t)n); }
  262. ZT_ALWAYS_INLINE uint32_t hton(uint32_t n)
  263. {
  264. #if defined(__GNUC__)
  265. #if defined(__FreeBSD__)
  266. return htonl(n);
  267. #elif (!defined(__OpenBSD__))
  268. return __builtin_bswap32(n);
  269. #endif
  270. #else
  271. return htonl(n);
  272. #endif
  273. }
  274. ZT_ALWAYS_INLINE int32_t hton(int32_t n) { return (int32_t)Utils::hton((uint32_t)n); }
  275. ZT_ALWAYS_INLINE uint64_t hton(uint64_t n)
  276. {
  277. #if defined(__GNUC__)
  278. #if defined(__FreeBSD__)
  279. return bswap64(n);
  280. #elif (!defined(__OpenBSD__))
  281. return __builtin_bswap64(n);
  282. #endif
  283. #else
  284. return (
  285. ((n & 0x00000000000000FFULL) << 56) |
  286. ((n & 0x000000000000FF00ULL) << 40) |
  287. ((n & 0x0000000000FF0000ULL) << 24) |
  288. ((n & 0x00000000FF000000ULL) << 8) |
  289. ((n & 0x000000FF00000000ULL) >> 8) |
  290. ((n & 0x0000FF0000000000ULL) >> 24) |
  291. ((n & 0x00FF000000000000ULL) >> 40) |
  292. ((n & 0xFF00000000000000ULL) >> 56)
  293. );
  294. #endif
  295. }
  296. ZT_ALWAYS_INLINE int64_t hton(int64_t n) { return (int64_t)hton((uint64_t)n); }
  297. #else
  298. template<typename T>
  299. static ZT_ALWAYS_INLINE T hton(T n) { return n; }
  300. #endif
  301. #if __BYTE_ORDER == __LITTLE_ENDIAN
  302. ZT_ALWAYS_INLINE uint8_t ntoh(uint8_t n) { return n; }
  303. ZT_ALWAYS_INLINE int8_t ntoh(int8_t n) { return n; }
  304. ZT_ALWAYS_INLINE uint16_t ntoh(uint16_t n)
  305. {
  306. #if defined(__GNUC__)
  307. #if defined(__FreeBSD__)
  308. return htons(n);
  309. #elif (!defined(__OpenBSD__))
  310. return __builtin_bswap16(n);
  311. #endif
  312. #else
  313. return htons(n);
  314. #endif
  315. }
  316. ZT_ALWAYS_INLINE int16_t ntoh(int16_t n) { return (int16_t)Utils::ntoh((uint16_t)n); }
  317. ZT_ALWAYS_INLINE uint32_t ntoh(uint32_t n)
  318. {
  319. #if defined(__GNUC__)
  320. #if defined(__FreeBSD__)
  321. return ntohl(n);
  322. #elif (!defined(__OpenBSD__))
  323. return __builtin_bswap32(n);
  324. #endif
  325. #else
  326. return ntohl(n);
  327. #endif
  328. }
  329. ZT_ALWAYS_INLINE int32_t ntoh(int32_t n) { return (int32_t)Utils::ntoh((uint32_t)n); }
  330. ZT_ALWAYS_INLINE uint64_t ntoh(uint64_t n)
  331. {
  332. #if defined(__GNUC__)
  333. #if defined(__FreeBSD__)
  334. return bswap64(n);
  335. #elif (!defined(__OpenBSD__))
  336. return __builtin_bswap64(n);
  337. #endif
  338. #else
  339. return (
  340. ((n & 0x00000000000000FFULL) << 56) |
  341. ((n & 0x000000000000FF00ULL) << 40) |
  342. ((n & 0x0000000000FF0000ULL) << 24) |
  343. ((n & 0x00000000FF000000ULL) << 8) |
  344. ((n & 0x000000FF00000000ULL) >> 8) |
  345. ((n & 0x0000FF0000000000ULL) >> 24) |
  346. ((n & 0x00FF000000000000ULL) >> 40) |
  347. ((n & 0xFF00000000000000ULL) >> 56)
  348. );
  349. #endif
  350. }
  351. ZT_ALWAYS_INLINE int64_t ntoh(int64_t n) { return (int64_t)ntoh((uint64_t)n); }
  352. #else
  353. template<typename T>
  354. ZT_ALWAYS_INLINE T ntoh(T n) { return n; }
  355. #endif
  356. ZT_ALWAYS_INLINE uint64_t readUInt64(const void *const p)
  357. {
  358. #ifdef ZT_NO_TYPE_PUNNING
  359. const uint8_t *const b = reinterpret_cast<const uint8_t *>(p);
  360. return (
  361. ((uint64_t)b[0] << 56) |
  362. ((uint64_t)b[1] << 48) |
  363. ((uint64_t)b[2] << 40) |
  364. ((uint64_t)b[3] << 32) |
  365. ((uint64_t)b[4] << 24) |
  366. ((uint64_t)b[5] << 16) |
  367. ((uint64_t)b[6] << 8) |
  368. (uint64_t)b[7]);
  369. #else
  370. return ntoh(*reinterpret_cast<const uint64_t *>(p));
  371. #endif
  372. }
  373. ZT_ALWAYS_INLINE void putUInt64(void *const p,const uint64_t i)
  374. {
  375. #ifdef ZT_NO_TYPE_PUNNING
  376. uint8_t *const b = reinterpret_cast<uint8_t *>(p);
  377. p[0] = (uint8_t)(i << 56);
  378. p[1] = (uint8_t)(i << 48);
  379. p[2] = (uint8_t)(i << 40);
  380. p[3] = (uint8_t)(i << 32);
  381. p[4] = (uint8_t)(i << 24);
  382. p[5] = (uint8_t)(i << 16);
  383. p[6] = (uint8_t)(i << 8);
  384. p[7] = (uint8_t)i;
  385. #else
  386. *reinterpret_cast<uint64_t *>(p) = Utils::hton(i);
  387. #endif
  388. }
  389. } // namespace Utils
  390. } // namespace ZeroTier
  391. #endif