Utils.hpp 11 KB

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