Utils.hpp 11 KB

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