Utils.hpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392
  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 <stdio.h>
  16. #include <stdlib.h>
  17. #include <stdint.h>
  18. #include <string.h>
  19. #include <time.h>
  20. #include <string>
  21. #include <stdexcept>
  22. #include <vector>
  23. #include <map>
  24. #include "Constants.hpp"
  25. namespace ZeroTier {
  26. /**
  27. * Miscellaneous utility functions and global constants
  28. */
  29. class Utils
  30. {
  31. public:
  32. /**
  33. * Hexadecimal characters 0-f
  34. */
  35. static const char HEXCHARS[16];
  36. /**
  37. * Perform a time-invariant binary comparison
  38. *
  39. * @param a First binary string
  40. * @param b Second binary string
  41. * @param len Length of strings
  42. * @return True if strings are equal
  43. */
  44. static ZT_ALWAYS_INLINE bool secureEq(const void *a,const void *b,unsigned int len)
  45. {
  46. uint8_t diff = 0;
  47. for(unsigned int i=0;i<len;++i)
  48. diff |= ( (reinterpret_cast<const uint8_t *>(a))[i] ^ (reinterpret_cast<const uint8_t *>(b))[i] );
  49. return (diff == 0);
  50. }
  51. /**
  52. * Zero memory, ensuring to avoid any compiler optimizations or other things that may stop this.
  53. */
  54. static void burn(void *ptr,unsigned int len);
  55. /**
  56. * @param n Number to convert
  57. * @param s Buffer, at least 24 bytes in size
  58. * @return String containing 'n' in base 10 form
  59. */
  60. static char *decimal(unsigned long n,char s[24]);
  61. static inline char *hex(uint64_t i,char s[17])
  62. {
  63. s[0] = HEXCHARS[(i >> 60) & 0xf];
  64. s[1] = HEXCHARS[(i >> 56) & 0xf];
  65. s[2] = HEXCHARS[(i >> 52) & 0xf];
  66. s[3] = HEXCHARS[(i >> 48) & 0xf];
  67. s[4] = HEXCHARS[(i >> 44) & 0xf];
  68. s[5] = HEXCHARS[(i >> 40) & 0xf];
  69. s[6] = HEXCHARS[(i >> 36) & 0xf];
  70. s[7] = HEXCHARS[(i >> 32) & 0xf];
  71. s[8] = HEXCHARS[(i >> 28) & 0xf];
  72. s[9] = HEXCHARS[(i >> 24) & 0xf];
  73. s[10] = HEXCHARS[(i >> 20) & 0xf];
  74. s[11] = HEXCHARS[(i >> 16) & 0xf];
  75. s[12] = HEXCHARS[(i >> 12) & 0xf];
  76. s[13] = HEXCHARS[(i >> 8) & 0xf];
  77. s[14] = HEXCHARS[(i >> 4) & 0xf];
  78. s[15] = HEXCHARS[i & 0xf];
  79. s[16] = (char)0;
  80. return s;
  81. }
  82. static inline char *hex10(uint64_t i,char s[11])
  83. {
  84. s[0] = HEXCHARS[(i >> 36) & 0xf];
  85. s[1] = HEXCHARS[(i >> 32) & 0xf];
  86. s[2] = HEXCHARS[(i >> 28) & 0xf];
  87. s[3] = HEXCHARS[(i >> 24) & 0xf];
  88. s[4] = HEXCHARS[(i >> 20) & 0xf];
  89. s[5] = HEXCHARS[(i >> 16) & 0xf];
  90. s[6] = HEXCHARS[(i >> 12) & 0xf];
  91. s[7] = HEXCHARS[(i >> 8) & 0xf];
  92. s[8] = HEXCHARS[(i >> 4) & 0xf];
  93. s[9] = HEXCHARS[i & 0xf];
  94. s[10] = (char)0;
  95. return s;
  96. }
  97. static inline char *hex(uint32_t i,char s[9])
  98. {
  99. s[0] = HEXCHARS[(i >> 28) & 0xf];
  100. s[1] = HEXCHARS[(i >> 24) & 0xf];
  101. s[2] = HEXCHARS[(i >> 20) & 0xf];
  102. s[3] = HEXCHARS[(i >> 16) & 0xf];
  103. s[4] = HEXCHARS[(i >> 12) & 0xf];
  104. s[5] = HEXCHARS[(i >> 8) & 0xf];
  105. s[6] = HEXCHARS[(i >> 4) & 0xf];
  106. s[7] = HEXCHARS[i & 0xf];
  107. s[8] = (char)0;
  108. return s;
  109. }
  110. static inline char *hex(uint16_t i,char s[5])
  111. {
  112. s[0] = HEXCHARS[(i >> 12) & 0xf];
  113. s[1] = HEXCHARS[(i >> 8) & 0xf];
  114. s[2] = HEXCHARS[(i >> 4) & 0xf];
  115. s[3] = HEXCHARS[i & 0xf];
  116. s[4] = (char)0;
  117. return s;
  118. }
  119. static inline char *hex(uint8_t i,char s[3])
  120. {
  121. s[0] = HEXCHARS[(i >> 4) & 0xf];
  122. s[1] = HEXCHARS[i & 0xf];
  123. s[2] = (char)0;
  124. return s;
  125. }
  126. static inline char *hex(const void *d,unsigned int l,char *s)
  127. {
  128. char *const save = s;
  129. for(unsigned int i=0;i<l;++i) {
  130. const unsigned int b = reinterpret_cast<const uint8_t *>(d)[i];
  131. *(s++) = HEXCHARS[b >> 4];
  132. *(s++) = HEXCHARS[b & 0xf];
  133. }
  134. *s = (char)0;
  135. return save;
  136. }
  137. static unsigned int unhex(const char *h,void *buf,unsigned int buflen);
  138. static unsigned int unhex(const char *h,unsigned int hlen,void *buf,unsigned int buflen);
  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. static void getSecureRandom(void *buf,unsigned int bytes);
  149. /**
  150. * Get a 64-bit unsigned secure random number
  151. */
  152. static ZT_ALWAYS_INLINE uint64_t getSecureRandom64()
  153. {
  154. uint64_t x;
  155. getSecureRandom(&x,sizeof(x));
  156. return x;
  157. }
  158. static int b32e(const uint8_t *data,int length,char *result,int bufSize);
  159. static int b32d(const char *encoded, uint8_t *result, int bufSize);
  160. static ZT_ALWAYS_INLINE unsigned int b64MaxEncodedSize(const unsigned int s) { return ((((s + 2) / 3) * 4) + 1); }
  161. static unsigned int b64e(const uint8_t *in,unsigned int inlen,char *out,unsigned int outlen);
  162. static unsigned int b64d(const char *in,uint8_t *out,unsigned int outlen);
  163. /**
  164. * Get a non-cryptographic random integer
  165. */
  166. static uint64_t random();
  167. static ZT_ALWAYS_INLINE float normalize(float value, int64_t bigMin, int64_t bigMax, int32_t targetMin, int32_t targetMax)
  168. {
  169. int64_t bigSpan = bigMax - bigMin;
  170. int64_t smallSpan = targetMax - targetMin;
  171. float valueScaled = (value - (float)bigMin) / (float)bigSpan;
  172. return (float)targetMin + valueScaled * (float)smallSpan;
  173. }
  174. /**
  175. * Tokenize a string (alias for strtok_r or strtok_s depending on platform)
  176. *
  177. * @param str String to split
  178. * @param delim Delimiters
  179. * @param saveptr Pointer to a char * for temporary reentrant storage
  180. */
  181. static ZT_ALWAYS_INLINE char *stok(char *str,const char *delim,char **saveptr)
  182. {
  183. #ifdef __WINDOWS__
  184. return strtok_s(str,delim,saveptr);
  185. #else
  186. return strtok_r(str,delim,saveptr);
  187. #endif
  188. }
  189. static ZT_ALWAYS_INLINE unsigned int strToUInt(const char *s) { return (unsigned int)strtoul(s,(char **)0,10); }
  190. static ZT_ALWAYS_INLINE int strToInt(const char *s) { return (int)strtol(s,(char **)0,10); }
  191. static ZT_ALWAYS_INLINE unsigned long strToULong(const char *s) { return strtoul(s,(char **)0,10); }
  192. static ZT_ALWAYS_INLINE long strToLong(const char *s) { return strtol(s,(char **)0,10); }
  193. static ZT_ALWAYS_INLINE unsigned long long strToU64(const char *s)
  194. {
  195. #ifdef __WINDOWS__
  196. return (unsigned long long)_strtoui64(s,(char **)0,10);
  197. #else
  198. return strtoull(s,(char **)0,10);
  199. #endif
  200. }
  201. static ZT_ALWAYS_INLINE long long strTo64(const char *s)
  202. {
  203. #ifdef __WINDOWS__
  204. return (long long)_strtoi64(s,(char **)0,10);
  205. #else
  206. return strtoll(s,(char **)0,10);
  207. #endif
  208. }
  209. static ZT_ALWAYS_INLINE unsigned int hexStrToUInt(const char *s) { return (unsigned int)strtoul(s,(char **)0,16); }
  210. static ZT_ALWAYS_INLINE int hexStrToInt(const char *s) { return (int)strtol(s,(char **)0,16); }
  211. static ZT_ALWAYS_INLINE unsigned long hexStrToULong(const char *s) { return strtoul(s,(char **)0,16); }
  212. static ZT_ALWAYS_INLINE long hexStrToLong(const char *s) { return strtol(s,(char **)0,16); }
  213. static ZT_ALWAYS_INLINE unsigned long long hexStrToU64(const char *s)
  214. {
  215. #ifdef __WINDOWS__
  216. return (unsigned long long)_strtoui64(s,(char **)0,16);
  217. #else
  218. return strtoull(s,(char **)0,16);
  219. #endif
  220. }
  221. static ZT_ALWAYS_INLINE long long hexStrTo64(const char *s)
  222. {
  223. #ifdef __WINDOWS__
  224. return (long long)_strtoi64(s,(char **)0,16);
  225. #else
  226. return strtoll(s,(char **)0,16);
  227. #endif
  228. }
  229. /**
  230. * Perform a safe C string copy, ALWAYS null-terminating the result
  231. *
  232. * This will never ever EVER result in dest[] not being null-terminated
  233. * regardless of any input parameter (other than len==0 which is invalid).
  234. *
  235. * @param dest Destination buffer (must not be NULL)
  236. * @param len Length of dest[] (if zero, false is returned and nothing happens)
  237. * @param src Source string (if NULL, dest will receive a zero-length string and true is returned)
  238. * @return True on success, false on overflow (buffer will still be 0-terminated)
  239. */
  240. static ZT_ALWAYS_INLINE bool scopy(char *dest,unsigned int len,const char *src)
  241. {
  242. if (!len)
  243. return false; // sanity check
  244. if (!src) {
  245. *dest = (char)0;
  246. return true;
  247. }
  248. char *end = dest + len;
  249. while ((*dest++ = *src++)) {
  250. if (dest == end) {
  251. *(--dest) = (char)0;
  252. return false;
  253. }
  254. }
  255. return true;
  256. }
  257. /**
  258. * Count the number of bits set in an integer
  259. *
  260. * @param v Unsigned integer
  261. * @return Number of bits set in this integer (0-bits in integer)
  262. */
  263. template<typename T>
  264. static ZT_ALWAYS_INLINE uint64_t countBits(T v)
  265. {
  266. v = v - ((v >> 1) & (T)~(T)0/3);
  267. v = (v & (T)~(T)0/15*3) + ((v >> 2) & (T)~(T)0/15*3);
  268. v = (v + (v >> 4)) & (T)~(T)0/255*15;
  269. return (T)(v * ((~((T)0))/((T)255))) >> ((sizeof(T) - 1) * 8);
  270. }
  271. // Byte swappers for big/little endian conversion
  272. #if __BYTE_ORDER == __LITTLE_ENDIAN
  273. static ZT_ALWAYS_INLINE uint8_t hton(uint8_t n) { return n; }
  274. static ZT_ALWAYS_INLINE int8_t hton(int8_t n) { return n; }
  275. static ZT_ALWAYS_INLINE uint16_t hton(uint16_t n) { return htons(n); }
  276. static ZT_ALWAYS_INLINE int16_t hton(int16_t n) { return (int16_t)Utils::hton((uint16_t)n); }
  277. static ZT_ALWAYS_INLINE uint32_t hton(uint32_t n)
  278. {
  279. #if defined(__GNUC__)
  280. #if defined(__FreeBSD__)
  281. return htonl(n);
  282. #elif (!defined(__OpenBSD__))
  283. return __builtin_bswap32(n);
  284. #endif
  285. #else
  286. return htonl(n);
  287. #endif
  288. }
  289. static ZT_ALWAYS_INLINE int32_t hton(int32_t n) { return (int32_t)Utils::hton((uint32_t)n); }
  290. static ZT_ALWAYS_INLINE uint64_t hton(uint64_t n)
  291. {
  292. #if defined(__GNUC__)
  293. #if defined(__FreeBSD__)
  294. return bswap64(n);
  295. #elif (!defined(__OpenBSD__))
  296. return __builtin_bswap64(n);
  297. #endif
  298. #else
  299. return (
  300. ((n & 0x00000000000000FFULL) << 56) |
  301. ((n & 0x000000000000FF00ULL) << 40) |
  302. ((n & 0x0000000000FF0000ULL) << 24) |
  303. ((n & 0x00000000FF000000ULL) << 8) |
  304. ((n & 0x000000FF00000000ULL) >> 8) |
  305. ((n & 0x0000FF0000000000ULL) >> 24) |
  306. ((n & 0x00FF000000000000ULL) >> 40) |
  307. ((n & 0xFF00000000000000ULL) >> 56)
  308. );
  309. #endif
  310. }
  311. static ZT_ALWAYS_INLINE int64_t hton(int64_t n) { return (int64_t)hton((uint64_t)n); }
  312. #else
  313. template<typename T>
  314. static ZT_ALWAYS_INLINE T hton(T n) { return n; }
  315. #endif
  316. #if __BYTE_ORDER == __LITTLE_ENDIAN
  317. static ZT_ALWAYS_INLINE uint8_t ntoh(uint8_t n) { return n; }
  318. static ZT_ALWAYS_INLINE int8_t ntoh(int8_t n) { return n; }
  319. static ZT_ALWAYS_INLINE uint16_t ntoh(uint16_t n) { return ntohs(n); }
  320. static ZT_ALWAYS_INLINE int16_t ntoh(int16_t n) { return (int16_t)Utils::ntoh((uint16_t)n); }
  321. static ZT_ALWAYS_INLINE uint32_t ntoh(uint32_t n)
  322. {
  323. #if defined(__GNUC__)
  324. #if defined(__FreeBSD__)
  325. return ntohl(n);
  326. #elif (!defined(__OpenBSD__))
  327. return __builtin_bswap32(n);
  328. #endif
  329. #else
  330. return ntohl(n);
  331. #endif
  332. }
  333. static ZT_ALWAYS_INLINE int32_t ntoh(int32_t n) { return (int32_t)Utils::ntoh((uint32_t)n); }
  334. static ZT_ALWAYS_INLINE uint64_t ntoh(uint64_t n)
  335. {
  336. #if defined(__GNUC__)
  337. #if defined(__FreeBSD__)
  338. return bswap64(n);
  339. #elif (!defined(__OpenBSD__))
  340. return __builtin_bswap64(n);
  341. #endif
  342. #else
  343. return (
  344. ((n & 0x00000000000000FFULL) << 56) |
  345. ((n & 0x000000000000FF00ULL) << 40) |
  346. ((n & 0x0000000000FF0000ULL) << 24) |
  347. ((n & 0x00000000FF000000ULL) << 8) |
  348. ((n & 0x000000FF00000000ULL) >> 8) |
  349. ((n & 0x0000FF0000000000ULL) >> 24) |
  350. ((n & 0x00FF000000000000ULL) >> 40) |
  351. ((n & 0xFF00000000000000ULL) >> 56)
  352. );
  353. #endif
  354. }
  355. static ZT_ALWAYS_INLINE int64_t ntoh(int64_t n) { return (int64_t)ntoh((uint64_t)n); }
  356. #else
  357. template<typename T>
  358. static ZT_ALWAYS_INLINE T ntoh(T n) { return n; }
  359. #endif
  360. };
  361. } // namespace ZeroTier
  362. #endif