Utils.hpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394
  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. 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. * Convert binary data to hexadecimal
  66. *
  67. * @param data Data to convert to hex
  68. * @param len Length of data
  69. * @return Hexadecimal string
  70. */
  71. static std::string hex(const void *data,unsigned int len);
  72. static inline std::string hex(const std::string &data) { return hex(data.data(),(unsigned int)data.length()); }
  73. /**
  74. * Convert hexadecimal to binary data
  75. *
  76. * This ignores all non-hex characters, just stepping over them and
  77. * continuing. Upper and lower case are supported for letters a-f.
  78. *
  79. * @param hex Hexadecimal ASCII code (non-hex chars are ignored, stops at zero or maxlen)
  80. * @param maxlen Maximum length of hex string buffer
  81. * @return Binary data
  82. */
  83. static std::string unhex(const char *hex,unsigned int maxlen);
  84. static inline std::string unhex(const std::string &hex) { return unhex(hex.c_str(),(unsigned int)hex.length()); }
  85. /**
  86. * Convert hexadecimal to binary data
  87. *
  88. * This ignores all non-hex characters, just stepping over them and
  89. * continuing. Upper and lower case are supported for letters a-f.
  90. *
  91. * @param hex Hexadecimal ASCII
  92. * @param maxlen Maximum length of hex string buffer
  93. * @param buf Buffer to fill
  94. * @param len Length of buffer
  95. * @return Number of characters actually written
  96. */
  97. static unsigned int unhex(const char *hex,unsigned int maxlen,void *buf,unsigned int len);
  98. static inline unsigned int unhex(const std::string &hex,void *buf,unsigned int len) { return unhex(hex.c_str(),(unsigned int)hex.length(),buf,len); }
  99. /**
  100. * Generate secure random bytes
  101. *
  102. * This will try to use whatever OS sources of entropy are available. It's
  103. * guarded by an internal mutex so it's thread-safe.
  104. *
  105. * @param buf Buffer to fill
  106. * @param bytes Number of random bytes to generate
  107. */
  108. static void getSecureRandom(void *buf,unsigned int bytes);
  109. /**
  110. * Tokenize a string (alias for strtok_r or strtok_s depending on platform)
  111. *
  112. * @param str String to split
  113. * @param delim Delimiters
  114. * @param saveptr Pointer to a char * for temporary reentrant storage
  115. */
  116. static inline char *stok(char *str,const char *delim,char **saveptr)
  117. throw()
  118. {
  119. #ifdef __WINDOWS__
  120. return strtok_s(str,delim,saveptr);
  121. #else
  122. return strtok_r(str,delim,saveptr);
  123. #endif
  124. }
  125. // String to number converters -- defined here to permit portability
  126. // ifdefs for platforms that lack some of the strtoXX functions.
  127. static inline unsigned int strToUInt(const char *s)
  128. throw()
  129. {
  130. return (unsigned int)strtoul(s,(char **)0,10);
  131. }
  132. static inline int strToInt(const char *s)
  133. throw()
  134. {
  135. return (int)strtol(s,(char **)0,10);
  136. }
  137. static inline unsigned long strToULong(const char *s)
  138. throw()
  139. {
  140. return strtoul(s,(char **)0,10);
  141. }
  142. static inline long strToLong(const char *s)
  143. throw()
  144. {
  145. return strtol(s,(char **)0,10);
  146. }
  147. static inline unsigned long long strToU64(const char *s)
  148. throw()
  149. {
  150. #ifdef __WINDOWS__
  151. return (unsigned long long)_strtoui64(s,(char **)0,10);
  152. #else
  153. return strtoull(s,(char **)0,10);
  154. #endif
  155. }
  156. static inline long long strTo64(const char *s)
  157. throw()
  158. {
  159. #ifdef __WINDOWS__
  160. return (long long)_strtoi64(s,(char **)0,10);
  161. #else
  162. return strtoll(s,(char **)0,10);
  163. #endif
  164. }
  165. static inline unsigned int hexStrToUInt(const char *s)
  166. throw()
  167. {
  168. return (unsigned int)strtoul(s,(char **)0,16);
  169. }
  170. static inline int hexStrToInt(const char *s)
  171. throw()
  172. {
  173. return (int)strtol(s,(char **)0,16);
  174. }
  175. static inline unsigned long hexStrToULong(const char *s)
  176. throw()
  177. {
  178. return strtoul(s,(char **)0,16);
  179. }
  180. static inline long hexStrToLong(const char *s)
  181. throw()
  182. {
  183. return strtol(s,(char **)0,16);
  184. }
  185. static inline unsigned long long hexStrToU64(const char *s)
  186. throw()
  187. {
  188. #ifdef __WINDOWS__
  189. return (unsigned long long)_strtoui64(s,(char **)0,16);
  190. #else
  191. return strtoull(s,(char **)0,16);
  192. #endif
  193. }
  194. static inline long long hexStrTo64(const char *s)
  195. throw()
  196. {
  197. #ifdef __WINDOWS__
  198. return (long long)_strtoi64(s,(char **)0,16);
  199. #else
  200. return strtoll(s,(char **)0,16);
  201. #endif
  202. }
  203. static inline double strToDouble(const char *s)
  204. throw()
  205. {
  206. return strtod(s,(char **)0);
  207. }
  208. /**
  209. * Perform a safe C string copy, ALWAYS null-terminating the result
  210. *
  211. * This will never ever EVER result in dest[] not being null-terminated
  212. * regardless of any input parameter (other than len==0 which is invalid).
  213. *
  214. * @param dest Destination buffer (must not be NULL)
  215. * @param len Length of dest[] (if zero, false is returned and nothing happens)
  216. * @param src Source string (if NULL, dest will receive a zero-length string and true is returned)
  217. * @return True on success, false on overflow (buffer will still be 0-terminated)
  218. */
  219. static bool scopy(char *dest,unsigned int len,const char *src);
  220. /**
  221. * Variant of snprintf that is portable and throws an exception
  222. *
  223. * This just wraps the local implementation whatever it's called, while
  224. * performing a few other checks and adding exceptions for overflow.
  225. *
  226. * @param buf Buffer to write to
  227. * @param len Length of buffer in bytes
  228. * @param fmt Format string
  229. * @param ... Format arguments
  230. * @throws std::length_error buf[] too short (buf[] will still be left null-terminated)
  231. */
  232. static unsigned int snprintf(char *buf,unsigned int len,const char *fmt,...)
  233. throw(std::length_error);
  234. /**
  235. * Count the number of bits set in an integer
  236. *
  237. * @param v 32-bit integer
  238. * @return Number of bits set in this integer (0-32)
  239. */
  240. static inline uint32_t countBits(uint32_t v)
  241. {
  242. v = v - ((v >> 1) & (uint32_t)0x55555555);
  243. v = (v & (uint32_t)0x33333333) + ((v >> 2) & (uint32_t)0x33333333);
  244. return ((((v + (v >> 4)) & (uint32_t)0xF0F0F0F) * (uint32_t)0x1010101) >> 24);
  245. }
  246. /**
  247. * Count the number of bits set in an integer
  248. *
  249. * @param v 64-bit integer
  250. * @return Number of bits set in this integer (0-64)
  251. */
  252. static inline uint64_t countBits(uint64_t v)
  253. {
  254. v = v - ((v >> 1) & (uint64_t)~(uint64_t)0/3);
  255. v = (v & (uint64_t)~(uint64_t)0/15*3) + ((v >> 2) & (uint64_t)~(uint64_t)0/15*3);
  256. v = (v + (v >> 4)) & (uint64_t)~(uint64_t)0/255*15;
  257. return (uint64_t)(v * ((uint64_t)~(uint64_t)0/255)) >> 56;
  258. }
  259. /**
  260. * Check if a memory buffer is all-zero
  261. *
  262. * @param p Memory to scan
  263. * @param len Length of memory
  264. * @return True if memory is all zero
  265. */
  266. static inline bool isZero(const void *p,unsigned int len)
  267. {
  268. for(unsigned int i=0;i<len;++i) {
  269. if (((const unsigned char *)p)[i])
  270. return false;
  271. }
  272. return true;
  273. }
  274. // Byte swappers for big/little endian conversion
  275. static inline uint8_t hton(uint8_t n) throw() { return n; }
  276. static inline int8_t hton(int8_t n) throw() { return n; }
  277. static inline uint16_t hton(uint16_t n) throw() { return htons(n); }
  278. static inline int16_t hton(int16_t n) throw() { return (int16_t)htons((uint16_t)n); }
  279. static inline uint32_t hton(uint32_t n) throw() { return htonl(n); }
  280. static inline int32_t hton(int32_t n) throw() { return (int32_t)htonl((uint32_t)n); }
  281. static inline uint64_t hton(uint64_t n)
  282. throw()
  283. {
  284. #if __BYTE_ORDER == __LITTLE_ENDIAN
  285. #if defined(__GNUC__) && (!defined(__OpenBSD__))
  286. return __builtin_bswap64(n);
  287. #else
  288. return (
  289. ((n & 0x00000000000000FFULL) << 56) |
  290. ((n & 0x000000000000FF00ULL) << 40) |
  291. ((n & 0x0000000000FF0000ULL) << 24) |
  292. ((n & 0x00000000FF000000ULL) << 8) |
  293. ((n & 0x000000FF00000000ULL) >> 8) |
  294. ((n & 0x0000FF0000000000ULL) >> 24) |
  295. ((n & 0x00FF000000000000ULL) >> 40) |
  296. ((n & 0xFF00000000000000ULL) >> 56)
  297. );
  298. #endif
  299. #else
  300. return n;
  301. #endif
  302. }
  303. static inline int64_t hton(int64_t n) throw() { return (int64_t)hton((uint64_t)n); }
  304. static inline uint8_t ntoh(uint8_t n) throw() { return n; }
  305. static inline int8_t ntoh(int8_t n) throw() { return n; }
  306. static inline uint16_t ntoh(uint16_t n) throw() { return ntohs(n); }
  307. static inline int16_t ntoh(int16_t n) throw() { return (int16_t)ntohs((uint16_t)n); }
  308. static inline uint32_t ntoh(uint32_t n) throw() { return ntohl(n); }
  309. static inline int32_t ntoh(int32_t n) throw() { return (int32_t)ntohl((uint32_t)n); }
  310. static inline uint64_t ntoh(uint64_t n)
  311. throw()
  312. {
  313. #if __BYTE_ORDER == __LITTLE_ENDIAN
  314. #if defined(__GNUC__) && !defined(__OpenBSD__)
  315. return __builtin_bswap64(n);
  316. #else
  317. return (
  318. ((n & 0x00000000000000FFULL) << 56) |
  319. ((n & 0x000000000000FF00ULL) << 40) |
  320. ((n & 0x0000000000FF0000ULL) << 24) |
  321. ((n & 0x00000000FF000000ULL) << 8) |
  322. ((n & 0x000000FF00000000ULL) >> 8) |
  323. ((n & 0x0000FF0000000000ULL) >> 24) |
  324. ((n & 0x00FF000000000000ULL) >> 40) |
  325. ((n & 0xFF00000000000000ULL) >> 56)
  326. );
  327. #endif
  328. #else
  329. return n;
  330. #endif
  331. }
  332. static inline int64_t ntoh(int64_t n) throw() { return (int64_t)ntoh((uint64_t)n); }
  333. /**
  334. * Compare Peer version tuples
  335. *
  336. * @return -1, 0, or 1 based on whether first tuple is less than, equal to, or greater than second
  337. */
  338. static inline int compareVersion(unsigned int maj1,unsigned int min1,unsigned int rev1,unsigned int b1,unsigned int maj2,unsigned int min2,unsigned int rev2,unsigned int b2)
  339. {
  340. if (maj1 > maj2)
  341. return 1;
  342. else if (maj1 < maj2)
  343. return -1;
  344. else {
  345. if (min1 > min2)
  346. return 1;
  347. else if (min1 < min2)
  348. return -1;
  349. else {
  350. if (rev1 > rev2)
  351. return 1;
  352. else if (rev1 < rev2)
  353. return -1;
  354. else {
  355. if (b1 > b2)
  356. return 1;
  357. else if (b1 < b2)
  358. return -1;
  359. else return 0;
  360. }
  361. }
  362. }
  363. }
  364. /**
  365. * Hexadecimal characters 0-f
  366. */
  367. static const char HEXCHARS[16];
  368. };
  369. } // namespace ZeroTier
  370. #endif