Utils.hpp 13 KB

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