Utils.hpp 11 KB

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