Utils.hpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402
  1. /*
  2. * ZeroTier One - Network Virtualization Everywhere
  3. * Copyright (C) 2011-2015 ZeroTier, Inc.
  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. * ZeroTier may be used and distributed under the terms of the GPLv3, which
  21. * are available at: http://www.gnu.org/licenses/gpl-3.0.html
  22. *
  23. * If you would like to embed ZeroTier into a commercial application or
  24. * redistribute it in a modified binary form, please contact ZeroTier Networks
  25. * LLC. Start here: http://www.zerotier.com/
  26. */
  27. #ifndef ZT_UTILS_HPP
  28. #define ZT_UTILS_HPP
  29. #include <stdio.h>
  30. #include <stdlib.h>
  31. #include <stdint.h>
  32. #include <string.h>
  33. #include <time.h>
  34. #include <string>
  35. #include <stdexcept>
  36. #include <vector>
  37. #include <map>
  38. #include "Constants.hpp"
  39. namespace ZeroTier {
  40. /**
  41. * Miscellaneous utility functions and global constants
  42. */
  43. class Utils
  44. {
  45. public:
  46. /**
  47. * Perform a time-invariant binary comparison
  48. *
  49. * @param a First binary string
  50. * @param b Second binary string
  51. * @param len Length of strings
  52. * @return True if strings are equal
  53. */
  54. static inline bool secureEq(const void *a,const void *b,unsigned int len)
  55. throw()
  56. {
  57. char diff = 0;
  58. for(unsigned int i=0;i<len;++i)
  59. diff |= ( (reinterpret_cast<const char *>(a))[i] ^ (reinterpret_cast<const char *>(b))[i] );
  60. return (diff == 0);
  61. }
  62. /**
  63. * Securely zero memory, avoiding compiler optimizations and such
  64. */
  65. static void burn(void *ptr,unsigned int len)
  66. throw();
  67. /**
  68. * Convert binary data to hexadecimal
  69. *
  70. * @param data Data to convert to hex
  71. * @param len Length of data
  72. * @return Hexadecimal string
  73. */
  74. static std::string hex(const void *data,unsigned int len);
  75. static inline std::string hex(const std::string &data) { return hex(data.data(),(unsigned int)data.length()); }
  76. /**
  77. * Convert hexadecimal to binary data
  78. *
  79. * This ignores all non-hex characters, just stepping over them and
  80. * continuing. Upper and lower case are supported for letters a-f.
  81. *
  82. * @param hex Hexadecimal ASCII code (non-hex chars are ignored, stops at zero or maxlen)
  83. * @param maxlen Maximum length of hex string buffer
  84. * @return Binary data
  85. */
  86. static std::string unhex(const char *hex,unsigned int maxlen);
  87. static inline std::string unhex(const std::string &hex) { return unhex(hex.c_str(),(unsigned int)hex.length()); }
  88. /**
  89. * Convert hexadecimal to binary data
  90. *
  91. * This ignores all non-hex characters, just stepping over them and
  92. * continuing. Upper and lower case are supported for letters a-f.
  93. *
  94. * @param hex Hexadecimal ASCII
  95. * @param maxlen Maximum length of hex string buffer
  96. * @param buf Buffer to fill
  97. * @param len Length of buffer
  98. * @return Number of characters actually written
  99. */
  100. static unsigned int unhex(const char *hex,unsigned int maxlen,void *buf,unsigned int len);
  101. 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); }
  102. /**
  103. * Generate secure random bytes
  104. *
  105. * This will try to use whatever OS sources of entropy are available. It's
  106. * guarded by an internal mutex so it's thread-safe.
  107. *
  108. * @param buf Buffer to fill
  109. * @param bytes Number of random bytes to generate
  110. */
  111. static void getSecureRandom(void *buf,unsigned int bytes);
  112. /**
  113. * Split a string by delimiter, with optional escape and quote characters
  114. *
  115. * @param s String to split
  116. * @param sep One or more separators
  117. * @param esc Zero or more escape characters
  118. * @param quot Zero or more quote characters
  119. * @return Vector of tokens
  120. */
  121. static std::vector<std::string> split(const char *s,const char *const sep,const char *esc,const char *quot);
  122. /**
  123. * Tokenize a string (alias for strtok_r or strtok_s depending on platform)
  124. *
  125. * @param str String to split
  126. * @param delim Delimiters
  127. * @param saveptr Pointer to a char * for temporary reentrant storage
  128. */
  129. static inline char *stok(char *str,const char *delim,char **saveptr)
  130. throw()
  131. {
  132. #ifdef __WINDOWS__
  133. return strtok_s(str,delim,saveptr);
  134. #else
  135. return strtok_r(str,delim,saveptr);
  136. #endif
  137. }
  138. // String to number converters -- defined here to permit portability
  139. // ifdefs for platforms that lack some of the strtoXX functions.
  140. static inline unsigned int strToUInt(const char *s)
  141. throw()
  142. {
  143. return (unsigned int)strtoul(s,(char **)0,10);
  144. }
  145. static inline int strToInt(const char *s)
  146. throw()
  147. {
  148. return (int)strtol(s,(char **)0,10);
  149. }
  150. static inline unsigned long strToULong(const char *s)
  151. throw()
  152. {
  153. return strtoul(s,(char **)0,10);
  154. }
  155. static inline long strToLong(const char *s)
  156. throw()
  157. {
  158. return strtol(s,(char **)0,10);
  159. }
  160. static inline unsigned long long strToU64(const char *s)
  161. throw()
  162. {
  163. #ifdef __WINDOWS__
  164. return (unsigned long long)_strtoui64(s,(char **)0,10);
  165. #else
  166. return strtoull(s,(char **)0,10);
  167. #endif
  168. }
  169. static inline long long strTo64(const char *s)
  170. throw()
  171. {
  172. #ifdef __WINDOWS__
  173. return (long long)_strtoi64(s,(char **)0,10);
  174. #else
  175. return strtoll(s,(char **)0,10);
  176. #endif
  177. }
  178. static inline unsigned int hexStrToUInt(const char *s)
  179. throw()
  180. {
  181. return (unsigned int)strtoul(s,(char **)0,16);
  182. }
  183. static inline int hexStrToInt(const char *s)
  184. throw()
  185. {
  186. return (int)strtol(s,(char **)0,16);
  187. }
  188. static inline unsigned long hexStrToULong(const char *s)
  189. throw()
  190. {
  191. return strtoul(s,(char **)0,16);
  192. }
  193. static inline long hexStrToLong(const char *s)
  194. throw()
  195. {
  196. return strtol(s,(char **)0,16);
  197. }
  198. static inline unsigned long long hexStrToU64(const char *s)
  199. throw()
  200. {
  201. #ifdef __WINDOWS__
  202. return (unsigned long long)_strtoui64(s,(char **)0,16);
  203. #else
  204. return strtoull(s,(char **)0,16);
  205. #endif
  206. }
  207. static inline long long hexStrTo64(const char *s)
  208. throw()
  209. {
  210. #ifdef __WINDOWS__
  211. return (long long)_strtoi64(s,(char **)0,16);
  212. #else
  213. return strtoll(s,(char **)0,16);
  214. #endif
  215. }
  216. static inline double strToDouble(const char *s)
  217. throw()
  218. {
  219. return strtod(s,(char **)0);
  220. }
  221. /**
  222. * Perform a safe C string copy
  223. *
  224. * @param dest Destination buffer
  225. * @param len Length of buffer
  226. * @param src Source string
  227. * @return True on success, false on overflow (buffer will still be 0-terminated)
  228. */
  229. static inline bool scopy(char *dest,unsigned int len,const char *src)
  230. throw()
  231. {
  232. if (!len)
  233. return false; // sanity check
  234. char *end = dest + len;
  235. while ((*dest++ = *src++)) {
  236. if (dest == end) {
  237. *(--dest) = (char)0;
  238. return false;
  239. }
  240. }
  241. return true;
  242. }
  243. /**
  244. * Variant of snprintf that is portable and throws an exception
  245. *
  246. * This just wraps the local implementation whatever it's called, while
  247. * performing a few other checks and adding exceptions for overflow.
  248. *
  249. * @param buf Buffer to write to
  250. * @param len Length of buffer in bytes
  251. * @param fmt Format string
  252. * @param ... Format arguments
  253. * @throws std::length_error buf[] too short (buf[] will still be left null-terminated)
  254. */
  255. static unsigned int snprintf(char *buf,unsigned int len,const char *fmt,...)
  256. throw(std::length_error);
  257. /**
  258. * Count the number of bits set in an integer
  259. *
  260. * @param v 32-bit integer
  261. * @return Number of bits set in this integer (0-32)
  262. */
  263. static inline uint32_t countBits(uint32_t v)
  264. throw()
  265. {
  266. v = v - ((v >> 1) & (uint32_t)0x55555555);
  267. v = (v & (uint32_t)0x33333333) + ((v >> 2) & (uint32_t)0x33333333);
  268. return ((((v + (v >> 4)) & (uint32_t)0xF0F0F0F) * (uint32_t)0x1010101) >> 24);
  269. }
  270. /**
  271. * Check if a memory buffer is all-zero
  272. *
  273. * @param p Memory to scan
  274. * @param len Length of memory
  275. * @return True if memory is all zero
  276. */
  277. static inline bool isZero(const void *p,unsigned int len)
  278. throw()
  279. {
  280. for(unsigned int i=0;i<len;++i) {
  281. if (((const unsigned char *)p)[i])
  282. return false;
  283. }
  284. return true;
  285. }
  286. // Byte swappers for big/little endian conversion
  287. static inline uint8_t hton(uint8_t n) throw() { return n; }
  288. static inline int8_t hton(int8_t n) throw() { return n; }
  289. static inline uint16_t hton(uint16_t n) throw() { return htons(n); }
  290. static inline int16_t hton(int16_t n) throw() { return (int16_t)htons((uint16_t)n); }
  291. static inline uint32_t hton(uint32_t n) throw() { return htonl(n); }
  292. static inline int32_t hton(int32_t n) throw() { return (int32_t)htonl((uint32_t)n); }
  293. static inline uint64_t hton(uint64_t n)
  294. throw()
  295. {
  296. #if __BYTE_ORDER == __LITTLE_ENDIAN
  297. #if defined(__GNUC__) && (!defined(__OpenBSD__))
  298. return __builtin_bswap64(n);
  299. #else
  300. return (
  301. ((n & 0x00000000000000FFULL) << 56) |
  302. ((n & 0x000000000000FF00ULL) << 40) |
  303. ((n & 0x0000000000FF0000ULL) << 24) |
  304. ((n & 0x00000000FF000000ULL) << 8) |
  305. ((n & 0x000000FF00000000ULL) >> 8) |
  306. ((n & 0x0000FF0000000000ULL) >> 24) |
  307. ((n & 0x00FF000000000000ULL) >> 40) |
  308. ((n & 0xFF00000000000000ULL) >> 56)
  309. );
  310. #endif
  311. #else
  312. return n;
  313. #endif
  314. }
  315. static inline int64_t hton(int64_t n) throw() { return (int64_t)hton((uint64_t)n); }
  316. static inline uint8_t ntoh(uint8_t n) throw() { return n; }
  317. static inline int8_t ntoh(int8_t n) throw() { return n; }
  318. static inline uint16_t ntoh(uint16_t n) throw() { return ntohs(n); }
  319. static inline int16_t ntoh(int16_t n) throw() { return (int16_t)ntohs((uint16_t)n); }
  320. static inline uint32_t ntoh(uint32_t n) throw() { return ntohl(n); }
  321. static inline int32_t ntoh(int32_t n) throw() { return (int32_t)ntohl((uint32_t)n); }
  322. static inline uint64_t ntoh(uint64_t n)
  323. throw()
  324. {
  325. #if __BYTE_ORDER == __LITTLE_ENDIAN
  326. #if defined(__GNUC__) && !defined(__OpenBSD__)
  327. return __builtin_bswap64(n);
  328. #else
  329. return (
  330. ((n & 0x00000000000000FFULL) << 56) |
  331. ((n & 0x000000000000FF00ULL) << 40) |
  332. ((n & 0x0000000000FF0000ULL) << 24) |
  333. ((n & 0x00000000FF000000ULL) << 8) |
  334. ((n & 0x000000FF00000000ULL) >> 8) |
  335. ((n & 0x0000FF0000000000ULL) >> 24) |
  336. ((n & 0x00FF000000000000ULL) >> 40) |
  337. ((n & 0xFF00000000000000ULL) >> 56)
  338. );
  339. #endif
  340. #else
  341. return n;
  342. #endif
  343. }
  344. static inline int64_t ntoh(int64_t n) throw() { return (int64_t)ntoh((uint64_t)n); }
  345. /**
  346. * Compare Peer version tuples
  347. *
  348. * @return -1, 0, or 1 based on whether first tuple is less than, equal to, or greater than second
  349. */
  350. static inline int compareVersion(unsigned int maj1,unsigned int min1,unsigned int rev1,unsigned int maj2,unsigned int min2,unsigned int rev2)
  351. throw()
  352. {
  353. if (maj1 > maj2)
  354. return 1;
  355. else if (maj1 < maj2)
  356. return -1;
  357. else {
  358. if (min1 > min2)
  359. return 1;
  360. else if (min1 < min2)
  361. return -1;
  362. else {
  363. if (rev1 > rev2)
  364. return 1;
  365. else if (rev1 < rev2)
  366. return -1;
  367. else return 0;
  368. }
  369. }
  370. }
  371. /**
  372. * Hexadecimal characters 0-f
  373. */
  374. static const char HEXCHARS[16];
  375. };
  376. } // namespace ZeroTier
  377. #endif