Utils.hpp 14 KB

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