Utils.hpp 11 KB

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