Utils.hpp 13 KB

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