Utils.hpp 14 KB

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