Utils.hpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440
  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. #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, int64_t bigMin, int64_t bigMax, int32_t targetMin, int32_t targetMax)
  192. {
  193. int64_t bigSpan = bigMax - bigMin;
  194. int64_t smallSpan = targetMax - targetMin;
  195. float valueScaled = (value - (float)bigMin) / (float)bigSpan;
  196. return (float)targetMin + valueScaled * (float)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 unsigned long long strToU64(const char *s)
  228. {
  229. #ifdef __WINDOWS__
  230. return (unsigned long long)_strtoui64(s,(char **)0,10);
  231. #else
  232. return strtoull(s,(char **)0,10);
  233. #endif
  234. }
  235. static inline long long strTo64(const char *s)
  236. {
  237. #ifdef __WINDOWS__
  238. return (long long)_strtoi64(s,(char **)0,10);
  239. #else
  240. return strtoll(s,(char **)0,10);
  241. #endif
  242. }
  243. static inline unsigned int hexStrToUInt(const char *s) { return (unsigned int)strtoul(s,(char **)0,16); }
  244. static inline int hexStrToInt(const char *s) { return (int)strtol(s,(char **)0,16); }
  245. static inline unsigned long hexStrToULong(const char *s) { return strtoul(s,(char **)0,16); }
  246. static inline long hexStrToLong(const char *s) { return strtol(s,(char **)0,16); }
  247. static inline unsigned long long hexStrToU64(const char *s)
  248. {
  249. #ifdef __WINDOWS__
  250. return (unsigned long long)_strtoui64(s,(char **)0,16);
  251. #else
  252. return strtoull(s,(char **)0,16);
  253. #endif
  254. }
  255. static inline long long hexStrTo64(const char *s)
  256. {
  257. #ifdef __WINDOWS__
  258. return (long long)_strtoi64(s,(char **)0,16);
  259. #else
  260. return strtoll(s,(char **)0,16);
  261. #endif
  262. }
  263. /**
  264. * Perform a safe C string copy, ALWAYS null-terminating the result
  265. *
  266. * This will never ever EVER result in dest[] not being null-terminated
  267. * regardless of any input parameter (other than len==0 which is invalid).
  268. *
  269. * @param dest Destination buffer (must not be NULL)
  270. * @param len Length of dest[] (if zero, false is returned and nothing happens)
  271. * @param src Source string (if NULL, dest will receive a zero-length string and true is returned)
  272. * @return True on success, false on overflow (buffer will still be 0-terminated)
  273. */
  274. static inline bool scopy(char *dest,unsigned int len,const char *src)
  275. {
  276. if (!len)
  277. return false; // sanity check
  278. if (!src) {
  279. *dest = (char)0;
  280. return true;
  281. }
  282. char *end = dest + len;
  283. while ((*dest++ = *src++)) {
  284. if (dest == end) {
  285. *(--dest) = (char)0;
  286. return false;
  287. }
  288. }
  289. return true;
  290. }
  291. /**
  292. * Count the number of bits set in an integer
  293. *
  294. * @param v 32-bit integer
  295. * @return Number of bits set in this integer (0-32)
  296. */
  297. static inline uint32_t countBits(uint32_t v)
  298. {
  299. v = v - ((v >> 1) & (uint32_t)0x55555555);
  300. v = (v & (uint32_t)0x33333333) + ((v >> 2) & (uint32_t)0x33333333);
  301. return ((((v + (v >> 4)) & (uint32_t)0xF0F0F0F) * (uint32_t)0x1010101) >> 24);
  302. }
  303. /**
  304. * Count the number of bits set in an integer
  305. *
  306. * @param v 64-bit integer
  307. * @return Number of bits set in this integer (0-64)
  308. */
  309. static inline uint64_t countBits(uint64_t v)
  310. {
  311. v = v - ((v >> 1) & (uint64_t)~(uint64_t)0/3);
  312. v = (v & (uint64_t)~(uint64_t)0/15*3) + ((v >> 2) & (uint64_t)~(uint64_t)0/15*3);
  313. v = (v + (v >> 4)) & (uint64_t)~(uint64_t)0/255*15;
  314. return (uint64_t)(v * ((uint64_t)~(uint64_t)0/255)) >> 56;
  315. }
  316. /**
  317. * Check if a memory buffer is all-zero
  318. *
  319. * @param p Memory to scan
  320. * @param len Length of memory
  321. * @return True if memory is all zero
  322. */
  323. static inline bool isZero(const void *p,unsigned int len)
  324. {
  325. for(unsigned int i=0;i<len;++i) {
  326. if (((const unsigned char *)p)[i])
  327. return false;
  328. }
  329. return true;
  330. }
  331. // Byte swappers for big/little endian conversion
  332. static inline uint8_t hton(uint8_t n) { return n; }
  333. static inline int8_t hton(int8_t n) { return n; }
  334. static inline uint16_t hton(uint16_t n) { return htons(n); }
  335. static inline int16_t hton(int16_t n) { return (int16_t)htons((uint16_t)n); }
  336. static inline uint32_t hton(uint32_t n) { return htonl(n); }
  337. static inline int32_t hton(int32_t n) { return (int32_t)htonl((uint32_t)n); }
  338. static inline uint64_t hton(uint64_t n)
  339. {
  340. #if __BYTE_ORDER == __LITTLE_ENDIAN
  341. #if defined(__GNUC__)
  342. #if defined(__FreeBSD__)
  343. return bswap64(n);
  344. #elif (!defined(__OpenBSD__))
  345. return __builtin_bswap64(n);
  346. #endif
  347. #else
  348. return (
  349. ((n & 0x00000000000000FFULL) << 56) |
  350. ((n & 0x000000000000FF00ULL) << 40) |
  351. ((n & 0x0000000000FF0000ULL) << 24) |
  352. ((n & 0x00000000FF000000ULL) << 8) |
  353. ((n & 0x000000FF00000000ULL) >> 8) |
  354. ((n & 0x0000FF0000000000ULL) >> 24) |
  355. ((n & 0x00FF000000000000ULL) >> 40) |
  356. ((n & 0xFF00000000000000ULL) >> 56)
  357. );
  358. #endif
  359. #else
  360. return n;
  361. #endif
  362. }
  363. static inline int64_t hton(int64_t n) { return (int64_t)hton((uint64_t)n); }
  364. static inline uint8_t ntoh(uint8_t n) { return n; }
  365. static inline int8_t ntoh(int8_t n) { return n; }
  366. static inline uint16_t ntoh(uint16_t n) { return ntohs(n); }
  367. static inline int16_t ntoh(int16_t n) { return (int16_t)ntohs((uint16_t)n); }
  368. static inline uint32_t ntoh(uint32_t n) { return ntohl(n); }
  369. static inline int32_t ntoh(int32_t n) { return (int32_t)ntohl((uint32_t)n); }
  370. static inline uint64_t ntoh(uint64_t n)
  371. {
  372. #if __BYTE_ORDER == __LITTLE_ENDIAN
  373. #if defined(__GNUC__)
  374. #if defined(__FreeBSD__)
  375. return bswap64(n);
  376. #elif (!defined(__OpenBSD__))
  377. return __builtin_bswap64(n);
  378. #endif
  379. #else
  380. return (
  381. ((n & 0x00000000000000FFULL) << 56) |
  382. ((n & 0x000000000000FF00ULL) << 40) |
  383. ((n & 0x0000000000FF0000ULL) << 24) |
  384. ((n & 0x00000000FF000000ULL) << 8) |
  385. ((n & 0x000000FF00000000ULL) >> 8) |
  386. ((n & 0x0000FF0000000000ULL) >> 24) |
  387. ((n & 0x00FF000000000000ULL) >> 40) |
  388. ((n & 0xFF00000000000000ULL) >> 56)
  389. );
  390. #endif
  391. #else
  392. return n;
  393. #endif
  394. }
  395. static inline int64_t ntoh(int64_t n) { return (int64_t)ntoh((uint64_t)n); }
  396. /**
  397. * Hexadecimal characters 0-f
  398. */
  399. static const char HEXCHARS[16];
  400. };
  401. } // namespace ZeroTier
  402. #endif