Utils.hpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491
  1. /*
  2. * ZeroTier One - Network Virtualization Everywhere
  3. * Copyright (C) 2011-2018 ZeroTier, Inc. https://www.zerotier.com/
  4. *
  5. * This program is free software: you can redistribute it and/or modify
  6. * it under the terms of the GNU General Public License as published by
  7. * the Free Software Foundation, either version 3 of the License, or
  8. * (at your option) any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU General Public License
  16. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  17. *
  18. * --
  19. *
  20. * You can be released from the requirements of the license by purchasing
  21. * a commercial license. Buying such a license is mandatory as soon as you
  22. * develop commercial closed-source software that incorporates or links
  23. * directly against ZeroTier software without disclosing the source code
  24. * of your own application.
  25. */
  26. #ifndef ZT_UTILS_HPP
  27. #define ZT_UTILS_HPP
  28. #include <stdio.h>
  29. #include <stdlib.h>
  30. #include <stdint.h>
  31. #include <string.h>
  32. #include <time.h>
  33. #include <string>
  34. #include <stdexcept>
  35. #include <vector>
  36. #include <map>
  37. #if defined(__FreeBSD__)
  38. #include <sys/endian.h>
  39. #endif
  40. #include "Constants.hpp"
  41. #ifdef __LINUX__
  42. //#if (defined(_MSC_VER) || defined(__GNUC__)) && (defined(__amd64) || defined(__amd64__) || defined(__x86_64) || defined(__x86_64__) || defined(__AMD64) || defined(__AMD64__) || defined(_M_X64))
  43. #if 0
  44. #include <emmintrin.h>
  45. static inline void ZT_FAST_MEMCPY(void *a,const void *b,unsigned long k)
  46. {
  47. char *aa = reinterpret_cast<char *>(a);
  48. const char *bb = reinterpret_cast<const char *>(b);
  49. while (k >= 64) {
  50. __m128 t1 = _mm_loadu_ps(reinterpret_cast<const float *>(bb));
  51. __m128 t2 = _mm_loadu_ps(reinterpret_cast<const float *>(bb + 16));
  52. __m128 t3 = _mm_loadu_ps(reinterpret_cast<const float *>(bb + 32));
  53. __m128 t4 = _mm_loadu_ps(reinterpret_cast<const float *>(bb + 48));
  54. _mm_storeu_ps(reinterpret_cast<float *>(aa),t1);
  55. _mm_storeu_ps(reinterpret_cast<float *>(aa + 16),t2);
  56. _mm_storeu_ps(reinterpret_cast<float *>(aa + 32),t3);
  57. _mm_storeu_ps(reinterpret_cast<float *>(aa + 48),t4);
  58. bb += 64;
  59. aa += 64;
  60. k -= 64;
  61. }
  62. while (k >= 16) {
  63. __m128 t1 = _mm_loadu_ps(reinterpret_cast<const float *>(bb));
  64. _mm_storeu_ps(reinterpret_cast<float *>(aa),t1);
  65. bb += 16;
  66. aa += 16;
  67. k -= 16;
  68. }
  69. for(unsigned long i=0;i<k;++i)
  70. aa[i] = bb[i];
  71. }
  72. #else
  73. #define ZT_FAST_MEMCPY(a,b,c) memcpy(a,b,c)
  74. #endif
  75. #else
  76. #define ZT_FAST_MEMCPY(a,b,c) memcpy(a,b,c)
  77. #endif
  78. namespace ZeroTier {
  79. /**
  80. * Miscellaneous utility functions and global constants
  81. */
  82. class Utils
  83. {
  84. public:
  85. /**
  86. * Perform a time-invariant binary comparison
  87. *
  88. * @param a First binary string
  89. * @param b Second binary string
  90. * @param len Length of strings
  91. * @return True if strings are equal
  92. */
  93. static inline bool secureEq(const void *a,const void *b,unsigned int len)
  94. {
  95. uint8_t diff = 0;
  96. for(unsigned int i=0;i<len;++i)
  97. diff |= ( (reinterpret_cast<const uint8_t *>(a))[i] ^ (reinterpret_cast<const uint8_t *>(b))[i] );
  98. return (diff == 0);
  99. }
  100. /**
  101. * Securely zero memory, avoiding compiler optimizations and such
  102. */
  103. static void burn(void *ptr,unsigned int len);
  104. /**
  105. * @param n Number to convert
  106. * @param s Buffer, at least 24 bytes in size
  107. * @return String containing 'n' in base 10 form
  108. */
  109. static char *decimal(unsigned long n,char s[24]);
  110. static inline char *hex(uint64_t i,char s[17])
  111. {
  112. s[0] = HEXCHARS[(i >> 60) & 0xf];
  113. s[1] = HEXCHARS[(i >> 56) & 0xf];
  114. s[2] = HEXCHARS[(i >> 52) & 0xf];
  115. s[3] = HEXCHARS[(i >> 48) & 0xf];
  116. s[4] = HEXCHARS[(i >> 44) & 0xf];
  117. s[5] = HEXCHARS[(i >> 40) & 0xf];
  118. s[6] = HEXCHARS[(i >> 36) & 0xf];
  119. s[7] = HEXCHARS[(i >> 32) & 0xf];
  120. s[8] = HEXCHARS[(i >> 28) & 0xf];
  121. s[9] = HEXCHARS[(i >> 24) & 0xf];
  122. s[10] = HEXCHARS[(i >> 20) & 0xf];
  123. s[11] = HEXCHARS[(i >> 16) & 0xf];
  124. s[12] = HEXCHARS[(i >> 12) & 0xf];
  125. s[13] = HEXCHARS[(i >> 8) & 0xf];
  126. s[14] = HEXCHARS[(i >> 4) & 0xf];
  127. s[15] = HEXCHARS[i & 0xf];
  128. s[16] = (char)0;
  129. return s;
  130. }
  131. static inline char *hex10(uint64_t i,char s[11])
  132. {
  133. s[0] = HEXCHARS[(i >> 36) & 0xf];
  134. s[1] = HEXCHARS[(i >> 32) & 0xf];
  135. s[2] = HEXCHARS[(i >> 28) & 0xf];
  136. s[3] = HEXCHARS[(i >> 24) & 0xf];
  137. s[4] = HEXCHARS[(i >> 20) & 0xf];
  138. s[5] = HEXCHARS[(i >> 16) & 0xf];
  139. s[6] = HEXCHARS[(i >> 12) & 0xf];
  140. s[7] = HEXCHARS[(i >> 8) & 0xf];
  141. s[8] = HEXCHARS[(i >> 4) & 0xf];
  142. s[9] = HEXCHARS[i & 0xf];
  143. s[10] = (char)0;
  144. return s;
  145. }
  146. static inline char *hex(uint32_t i,char s[9])
  147. {
  148. s[0] = HEXCHARS[(i >> 28) & 0xf];
  149. s[1] = HEXCHARS[(i >> 24) & 0xf];
  150. s[2] = HEXCHARS[(i >> 20) & 0xf];
  151. s[3] = HEXCHARS[(i >> 16) & 0xf];
  152. s[4] = HEXCHARS[(i >> 12) & 0xf];
  153. s[5] = HEXCHARS[(i >> 8) & 0xf];
  154. s[6] = HEXCHARS[(i >> 4) & 0xf];
  155. s[7] = HEXCHARS[i & 0xf];
  156. s[8] = (char)0;
  157. return s;
  158. }
  159. static inline char *hex(uint16_t i,char s[5])
  160. {
  161. s[0] = HEXCHARS[(i >> 12) & 0xf];
  162. s[1] = HEXCHARS[(i >> 8) & 0xf];
  163. s[2] = HEXCHARS[(i >> 4) & 0xf];
  164. s[3] = HEXCHARS[i & 0xf];
  165. s[4] = (char)0;
  166. return s;
  167. }
  168. static inline char *hex(uint8_t i,char s[3])
  169. {
  170. s[0] = HEXCHARS[(i >> 4) & 0xf];
  171. s[1] = HEXCHARS[i & 0xf];
  172. s[2] = (char)0;
  173. return s;
  174. }
  175. static inline char *hex(const void *d,unsigned int l,char *s)
  176. {
  177. char *const save = s;
  178. for(unsigned int i=0;i<l;++i) {
  179. const unsigned int b = reinterpret_cast<const uint8_t *>(d)[i];
  180. *(s++) = HEXCHARS[b >> 4];
  181. *(s++) = HEXCHARS[b & 0xf];
  182. }
  183. *s = (char)0;
  184. return save;
  185. }
  186. static inline unsigned int unhex(const char *h,void *buf,unsigned int buflen)
  187. {
  188. unsigned int l = 0;
  189. while (l < buflen) {
  190. uint8_t hc = *(reinterpret_cast<const uint8_t *>(h++));
  191. if (!hc) break;
  192. uint8_t c = 0;
  193. if ((hc >= 48)&&(hc <= 57)) // 0..9
  194. c = hc - 48;
  195. else if ((hc >= 97)&&(hc <= 102)) // a..f
  196. c = hc - 87;
  197. else if ((hc >= 65)&&(hc <= 70)) // A..F
  198. c = hc - 55;
  199. hc = *(reinterpret_cast<const uint8_t *>(h++));
  200. if (!hc) break;
  201. c <<= 4;
  202. if ((hc >= 48)&&(hc <= 57))
  203. c |= hc - 48;
  204. else if ((hc >= 97)&&(hc <= 102))
  205. c |= hc - 87;
  206. else if ((hc >= 65)&&(hc <= 70))
  207. c |= hc - 55;
  208. reinterpret_cast<uint8_t *>(buf)[l++] = c;
  209. }
  210. return l;
  211. }
  212. static inline unsigned int unhex(const char *h,unsigned int hlen,void *buf,unsigned int buflen)
  213. {
  214. unsigned int l = 0;
  215. const char *hend = h + hlen;
  216. while (l < buflen) {
  217. if (h == hend) break;
  218. uint8_t hc = *(reinterpret_cast<const uint8_t *>(h++));
  219. if (!hc) break;
  220. uint8_t c = 0;
  221. if ((hc >= 48)&&(hc <= 57))
  222. c = hc - 48;
  223. else if ((hc >= 97)&&(hc <= 102))
  224. c = hc - 87;
  225. else if ((hc >= 65)&&(hc <= 70))
  226. c = hc - 55;
  227. if (h == hend) break;
  228. hc = *(reinterpret_cast<const uint8_t *>(h++));
  229. if (!hc) break;
  230. c <<= 4;
  231. if ((hc >= 48)&&(hc <= 57))
  232. c |= hc - 48;
  233. else if ((hc >= 97)&&(hc <= 102))
  234. c |= hc - 87;
  235. else if ((hc >= 65)&&(hc <= 70))
  236. c |= hc - 55;
  237. reinterpret_cast<uint8_t *>(buf)[l++] = c;
  238. }
  239. return l;
  240. }
  241. static inline float normalize(float value, int64_t bigMin, int64_t bigMax, int32_t targetMin, int32_t targetMax)
  242. {
  243. int64_t bigSpan = bigMax - bigMin;
  244. int64_t smallSpan = targetMax - targetMin;
  245. float valueScaled = (value - (float)bigMin) / (float)bigSpan;
  246. return (float)targetMin + valueScaled * (float)smallSpan;
  247. }
  248. /**
  249. * Generate secure random bytes
  250. *
  251. * This will try to use whatever OS sources of entropy are available. It's
  252. * guarded by an internal mutex so it's thread-safe.
  253. *
  254. * @param buf Buffer to fill
  255. * @param bytes Number of random bytes to generate
  256. */
  257. static void getSecureRandom(void *buf,unsigned int bytes);
  258. /**
  259. * Tokenize a string (alias for strtok_r or strtok_s depending on platform)
  260. *
  261. * @param str String to split
  262. * @param delim Delimiters
  263. * @param saveptr Pointer to a char * for temporary reentrant storage
  264. */
  265. static inline char *stok(char *str,const char *delim,char **saveptr)
  266. {
  267. #ifdef __WINDOWS__
  268. return strtok_s(str,delim,saveptr);
  269. #else
  270. return strtok_r(str,delim,saveptr);
  271. #endif
  272. }
  273. static inline unsigned int strToUInt(const char *s) { return (unsigned int)strtoul(s,(char **)0,10); }
  274. static inline int strToInt(const char *s) { return (int)strtol(s,(char **)0,10); }
  275. static inline unsigned long strToULong(const char *s) { return strtoul(s,(char **)0,10); }
  276. static inline long strToLong(const char *s) { return strtol(s,(char **)0,10); }
  277. static inline unsigned long long strToU64(const char *s)
  278. {
  279. #ifdef __WINDOWS__
  280. return (unsigned long long)_strtoui64(s,(char **)0,10);
  281. #else
  282. return strtoull(s,(char **)0,10);
  283. #endif
  284. }
  285. static inline long long strTo64(const char *s)
  286. {
  287. #ifdef __WINDOWS__
  288. return (long long)_strtoi64(s,(char **)0,10);
  289. #else
  290. return strtoll(s,(char **)0,10);
  291. #endif
  292. }
  293. static inline unsigned int hexStrToUInt(const char *s) { return (unsigned int)strtoul(s,(char **)0,16); }
  294. static inline int hexStrToInt(const char *s) { return (int)strtol(s,(char **)0,16); }
  295. static inline unsigned long hexStrToULong(const char *s) { return strtoul(s,(char **)0,16); }
  296. static inline long hexStrToLong(const char *s) { return strtol(s,(char **)0,16); }
  297. static inline unsigned long long hexStrToU64(const char *s)
  298. {
  299. #ifdef __WINDOWS__
  300. return (unsigned long long)_strtoui64(s,(char **)0,16);
  301. #else
  302. return strtoull(s,(char **)0,16);
  303. #endif
  304. }
  305. static inline long long hexStrTo64(const char *s)
  306. {
  307. #ifdef __WINDOWS__
  308. return (long long)_strtoi64(s,(char **)0,16);
  309. #else
  310. return strtoll(s,(char **)0,16);
  311. #endif
  312. }
  313. /**
  314. * Perform a safe C string copy, ALWAYS null-terminating the result
  315. *
  316. * This will never ever EVER result in dest[] not being null-terminated
  317. * regardless of any input parameter (other than len==0 which is invalid).
  318. *
  319. * @param dest Destination buffer (must not be NULL)
  320. * @param len Length of dest[] (if zero, false is returned and nothing happens)
  321. * @param src Source string (if NULL, dest will receive a zero-length string and true is returned)
  322. * @return True on success, false on overflow (buffer will still be 0-terminated)
  323. */
  324. static inline bool scopy(char *dest,unsigned int len,const char *src)
  325. {
  326. if (!len)
  327. return false; // sanity check
  328. if (!src) {
  329. *dest = (char)0;
  330. return true;
  331. }
  332. char *end = dest + len;
  333. while ((*dest++ = *src++)) {
  334. if (dest == end) {
  335. *(--dest) = (char)0;
  336. return false;
  337. }
  338. }
  339. return true;
  340. }
  341. /**
  342. * Count the number of bits set in an integer
  343. *
  344. * @param v 32-bit integer
  345. * @return Number of bits set in this integer (0-32)
  346. */
  347. static inline uint32_t countBits(uint32_t v)
  348. {
  349. v = v - ((v >> 1) & (uint32_t)0x55555555);
  350. v = (v & (uint32_t)0x33333333) + ((v >> 2) & (uint32_t)0x33333333);
  351. return ((((v + (v >> 4)) & (uint32_t)0xF0F0F0F) * (uint32_t)0x1010101) >> 24);
  352. }
  353. /**
  354. * Count the number of bits set in an integer
  355. *
  356. * @param v 64-bit integer
  357. * @return Number of bits set in this integer (0-64)
  358. */
  359. static inline uint64_t countBits(uint64_t v)
  360. {
  361. v = v - ((v >> 1) & (uint64_t)~(uint64_t)0/3);
  362. v = (v & (uint64_t)~(uint64_t)0/15*3) + ((v >> 2) & (uint64_t)~(uint64_t)0/15*3);
  363. v = (v + (v >> 4)) & (uint64_t)~(uint64_t)0/255*15;
  364. return (uint64_t)(v * ((uint64_t)~(uint64_t)0/255)) >> 56;
  365. }
  366. /**
  367. * Check if a memory buffer is all-zero
  368. *
  369. * @param p Memory to scan
  370. * @param len Length of memory
  371. * @return True if memory is all zero
  372. */
  373. static inline bool isZero(const void *p,unsigned int len)
  374. {
  375. for(unsigned int i=0;i<len;++i) {
  376. if (((const unsigned char *)p)[i])
  377. return false;
  378. }
  379. return true;
  380. }
  381. // Byte swappers for big/little endian conversion
  382. static inline uint8_t hton(uint8_t n) { return n; }
  383. static inline int8_t hton(int8_t n) { return n; }
  384. static inline uint16_t hton(uint16_t n) { return htons(n); }
  385. static inline int16_t hton(int16_t n) { return (int16_t)htons((uint16_t)n); }
  386. static inline uint32_t hton(uint32_t n) { return htonl(n); }
  387. static inline int32_t hton(int32_t n) { return (int32_t)htonl((uint32_t)n); }
  388. static inline uint64_t hton(uint64_t n)
  389. {
  390. #if __BYTE_ORDER == __LITTLE_ENDIAN
  391. #if defined(__GNUC__)
  392. #if defined(__FreeBSD__)
  393. return bswap64(n);
  394. #elif (!defined(__OpenBSD__))
  395. return __builtin_bswap64(n);
  396. #endif
  397. #else
  398. return (
  399. ((n & 0x00000000000000FFULL) << 56) |
  400. ((n & 0x000000000000FF00ULL) << 40) |
  401. ((n & 0x0000000000FF0000ULL) << 24) |
  402. ((n & 0x00000000FF000000ULL) << 8) |
  403. ((n & 0x000000FF00000000ULL) >> 8) |
  404. ((n & 0x0000FF0000000000ULL) >> 24) |
  405. ((n & 0x00FF000000000000ULL) >> 40) |
  406. ((n & 0xFF00000000000000ULL) >> 56)
  407. );
  408. #endif
  409. #else
  410. return n;
  411. #endif
  412. }
  413. static inline int64_t hton(int64_t n) { return (int64_t)hton((uint64_t)n); }
  414. static inline uint8_t ntoh(uint8_t n) { return n; }
  415. static inline int8_t ntoh(int8_t n) { return n; }
  416. static inline uint16_t ntoh(uint16_t n) { return ntohs(n); }
  417. static inline int16_t ntoh(int16_t n) { return (int16_t)ntohs((uint16_t)n); }
  418. static inline uint32_t ntoh(uint32_t n) { return ntohl(n); }
  419. static inline int32_t ntoh(int32_t n) { return (int32_t)ntohl((uint32_t)n); }
  420. static inline uint64_t ntoh(uint64_t n)
  421. {
  422. #if __BYTE_ORDER == __LITTLE_ENDIAN
  423. #if defined(__GNUC__)
  424. #if defined(__FreeBSD__)
  425. return bswap64(n);
  426. #elif (!defined(__OpenBSD__))
  427. return __builtin_bswap64(n);
  428. #endif
  429. #else
  430. return (
  431. ((n & 0x00000000000000FFULL) << 56) |
  432. ((n & 0x000000000000FF00ULL) << 40) |
  433. ((n & 0x0000000000FF0000ULL) << 24) |
  434. ((n & 0x00000000FF000000ULL) << 8) |
  435. ((n & 0x000000FF00000000ULL) >> 8) |
  436. ((n & 0x0000FF0000000000ULL) >> 24) |
  437. ((n & 0x00FF000000000000ULL) >> 40) |
  438. ((n & 0xFF00000000000000ULL) >> 56)
  439. );
  440. #endif
  441. #else
  442. return n;
  443. #endif
  444. }
  445. static inline int64_t ntoh(int64_t n) { return (int64_t)ntoh((uint64_t)n); }
  446. /**
  447. * Hexadecimal characters 0-f
  448. */
  449. static const char HEXCHARS[16];
  450. };
  451. } // namespace ZeroTier
  452. #endif