Utils.hpp 12 KB

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