Utils.hpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565
  1. /*
  2. * ZeroTier One - Global Peer to Peer Ethernet
  3. * Copyright (C) 2012-2013 ZeroTier Networks LLC
  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. #ifdef __WINDOWS__
  40. #include <WinSock2.h>
  41. #include <Windows.h>
  42. #else
  43. #include <unistd.h>
  44. #include <sys/time.h>
  45. #include <arpa/inet.h>
  46. #endif
  47. namespace ZeroTier {
  48. /**
  49. * Miscellaneous utility functions and global constants
  50. */
  51. class Utils
  52. {
  53. public:
  54. /**
  55. * Perform a time-invariant binary comparison
  56. *
  57. * @param a First binary string
  58. * @param b Second binary string
  59. * @param len Length of strings
  60. * @return True if strings are equal
  61. */
  62. static inline bool secureEq(const void *a,const void *b,unsigned int len)
  63. throw()
  64. {
  65. const char *p1 = (const char *)a;
  66. const char *p2 = (const char *)b;
  67. uint64_t diff = 0;
  68. while (len >= 8) {
  69. diff |= (*((const uint64_t *)p1) ^ *((const uint64_t *)p2));
  70. p1 += 8;
  71. p2 += 8;
  72. len -= 8;
  73. }
  74. while (len--)
  75. diff |= (uint64_t)(*p1++ ^ *p2++);
  76. return (diff == 0ULL);
  77. }
  78. /**
  79. * Delete a file
  80. *
  81. * @param path Path to delete
  82. * @return True if delete was successful
  83. */
  84. static inline bool rm(const char *path)
  85. throw()
  86. {
  87. #ifdef __WINDOWS__
  88. return (DeleteFileA(path) != FALSE);
  89. #else
  90. return (unlink(path) == 0);
  91. #endif
  92. }
  93. static inline bool rm(const std::string &path) throw() { return rm(path.c_str()); }
  94. /**
  95. * List a directory's contents
  96. *
  97. * Keys in returned map are filenames only and don't include the leading
  98. * path. Pseudo-paths like . and .. are not returned.
  99. *
  100. * @param path Path to list
  101. * @return Map of entries and whether or not they are also directories (empty on failure)
  102. */
  103. static std::map<std::string,bool> listDirectory(const char *path);
  104. /**
  105. * @param data Data to convert to hex
  106. * @param len Length of data
  107. * @return Hexadecimal string
  108. */
  109. static std::string hex(const void *data,unsigned int len);
  110. static inline std::string hex(const std::string &data) { return hex(data.data(),(unsigned int)data.length()); }
  111. /**
  112. * @param hex Hexadecimal ASCII code (non-hex chars are ignored)
  113. * @return Binary data
  114. */
  115. static std::string unhex(const char *hex);
  116. static inline std::string unhex(const std::string &hex) { return unhex(hex.c_str()); }
  117. /**
  118. * @param hex Hexadecimal ASCII
  119. * @param buf Buffer to fill
  120. * @param len Length of buffer
  121. * @return Number of characters actually written
  122. */
  123. static unsigned int unhex(const char *hex,void *buf,unsigned int len);
  124. static inline unsigned int unhex(const std::string &hex,void *buf,unsigned int len) { return unhex(hex.c_str(),buf,len); }
  125. /**
  126. * @param hex Hexadecimal ASCII
  127. * @param hexlen Length of hex ASCII
  128. * @param buf Buffer to fill
  129. * @param len Length of buffer
  130. * @return Number of bytes actually written to buffer
  131. */
  132. static unsigned int unhex(const char *hex,unsigned int hexlen,void *buf,unsigned int len)
  133. throw();
  134. /**
  135. * @param buf Buffer to fill
  136. * @param bytes Number of random bytes to generate
  137. */
  138. static void getSecureRandom(void *buf,unsigned int bytes);
  139. /**
  140. * Set modes on a file to something secure
  141. *
  142. * This locks a file so that only the owner can access it. What it actually
  143. * does varies by platform.
  144. *
  145. * @param path Path to lock
  146. * @param isDir True if this is a directory
  147. */
  148. static void lockDownFile(const char *path,bool isDir);
  149. /**
  150. * Get file last modification time
  151. *
  152. * Resolution is often only second, not millisecond, but the return is
  153. * always in ms for comparison against now().
  154. *
  155. * @param path Path to file to get time
  156. * @return Last modification time in ms since epoch or 0 if not found
  157. */
  158. static uint64_t getLastModified(const char *path);
  159. /**
  160. * @param path Path to check
  161. * @return True if file or directory exists at path location
  162. */
  163. static inline bool fileExists(const char *path)
  164. {
  165. return (getLastModified(path) != 0);
  166. }
  167. /**
  168. * @param path Path to file
  169. * @return File size or -1 if nonexistent or other failure
  170. */
  171. static int64_t getFileSize(const char *path);
  172. /**
  173. * @return Current time in milliseconds since epoch
  174. */
  175. static inline uint64_t now()
  176. throw()
  177. {
  178. #ifdef __WINDOWS__
  179. FILETIME ft;
  180. SYSTEMTIME st;
  181. ULARGE_INTEGER tmp;
  182. GetSystemTime(&st);
  183. SystemTimeToFileTime(&st,&ft);
  184. tmp.LowPart = ft.dwLowDateTime;
  185. tmp.HighPart = ft.dwHighDateTime;
  186. return ( ((tmp.QuadPart - 116444736000000000ULL) / 10000L) + st.wMilliseconds );
  187. #else
  188. struct timeval tv;
  189. gettimeofday(&tv,(struct timezone *)0);
  190. return ( (1000ULL * (uint64_t)tv.tv_sec) + (uint64_t)(tv.tv_usec / 1000) );
  191. #endif
  192. };
  193. /**
  194. * @return Current time in seconds since epoch, to the highest available resolution
  195. */
  196. static inline double nowf()
  197. throw()
  198. {
  199. #ifdef __WINDOWS__
  200. FILETIME ft;
  201. SYSTEMTIME st;
  202. ULARGE_INTEGER tmp;
  203. GetSystemTime(&st);
  204. SystemTimeToFileTime(&st,&ft);
  205. tmp.LowPart = ft.dwLowDateTime;
  206. tmp.HighPart = ft.dwHighDateTime;
  207. return (((double)(tmp.QuadPart - 116444736000000000ULL)) / 10000000.0);
  208. #else
  209. struct timeval tv;
  210. gettimeofday(&tv,(struct timezone *)0);
  211. return ( ((double)tv.tv_sec) + (((double)tv.tv_usec) / 1000000.0) );
  212. #endif
  213. }
  214. /**
  215. * Read the full contents of a file into a string buffer
  216. *
  217. * The buffer isn't cleared, so if it already contains data the file's data will
  218. * be appended.
  219. *
  220. * @param path Path of file to read
  221. * @param buf Buffer to fill
  222. * @return True if open and read successful
  223. */
  224. static bool readFile(const char *path,std::string &buf);
  225. /**
  226. * Write a block of data to disk, replacing any current file contents
  227. *
  228. * @param path Path to write
  229. * @param buf Buffer containing data
  230. * @param len Length of buffer
  231. * @return True if entire file was successfully written
  232. */
  233. static bool writeFile(const char *path,const void *buf,unsigned int len);
  234. /**
  235. * Write a block of data to disk, replacing any current file contents
  236. *
  237. * @param path Path to write
  238. * @param s Data to write
  239. * @return True if entire file was successfully written
  240. */
  241. static inline bool writeFile(const char *path,const std::string &s)
  242. {
  243. return writeFile(path,s.data(),(unsigned int)s.length());
  244. }
  245. /**
  246. * Split a string by delimiter, with optional escape and quote characters
  247. *
  248. * @param s String to split
  249. * @param sep One or more separators
  250. * @param esc Zero or more escape characters
  251. * @param quot Zero or more quote characters
  252. * @return Vector of tokens
  253. */
  254. static std::vector<std::string> split(const char *s,const char *const sep,const char *esc,const char *quot);
  255. /**
  256. * Tokenize a string (alias for strtok_r or strtok_s depending on platform)
  257. *
  258. * @param str String to split
  259. * @param delim Delimiters
  260. * @param saveptr Pointer to a char * for temporary reentrant storage
  261. */
  262. static inline char *stok(char *str,const char *delim,char **saveptr)
  263. throw()
  264. {
  265. #ifdef __WINDOWS__
  266. return strtok_s(str,delim,saveptr);
  267. #else
  268. return strtok_r(str,delim,saveptr);
  269. #endif
  270. }
  271. // String to number converters -- defined here to permit portability
  272. // ifdefs for platforms that lack some of the strtoXX functions.
  273. static inline unsigned int strToUInt(const char *s)
  274. throw()
  275. {
  276. return (unsigned int)strtoul(s,(char **)0,10);
  277. }
  278. static inline int strToInt(const char *s)
  279. throw()
  280. {
  281. return (int)strtol(s,(char **)0,10);
  282. }
  283. static inline unsigned long strToULong(const char *s)
  284. throw()
  285. {
  286. return strtoul(s,(char **)0,10);
  287. }
  288. static inline long strToLong(const char *s)
  289. throw()
  290. {
  291. return strtol(s,(char **)0,10);
  292. }
  293. static inline unsigned long long strToU64(const char *s)
  294. throw()
  295. {
  296. #ifdef __WINDOWS__
  297. return (unsigned long long)_strtoui64(s,(char **)0,10);
  298. #else
  299. return strtoull(s,(char **)0,10);
  300. #endif
  301. }
  302. static inline long long strTo64(const char *s)
  303. throw()
  304. {
  305. #ifdef __WINDOWS__
  306. return (long long)_strtoi64(s,(char **)0,10);
  307. #else
  308. return strtoll(s,(char **)0,10);
  309. #endif
  310. }
  311. static inline unsigned int hexStrToUInt(const char *s)
  312. throw()
  313. {
  314. return (unsigned int)strtoul(s,(char **)0,16);
  315. }
  316. static inline int hexStrToInt(const char *s)
  317. throw()
  318. {
  319. return (int)strtol(s,(char **)0,16);
  320. }
  321. static inline unsigned long hexStrToULong(const char *s)
  322. throw()
  323. {
  324. return strtoul(s,(char **)0,16);
  325. }
  326. static inline long hexStrToLong(const char *s)
  327. throw()
  328. {
  329. return strtol(s,(char **)0,16);
  330. }
  331. static inline unsigned long long hexStrToU64(const char *s)
  332. throw()
  333. {
  334. #ifdef __WINDOWS__
  335. return (unsigned long long)_strtoui64(s,(char **)0,16);
  336. #else
  337. return strtoull(s,(char **)0,16);
  338. #endif
  339. }
  340. static inline long long hexStrTo64(const char *s)
  341. throw()
  342. {
  343. #ifdef __WINDOWS__
  344. return (long long)_strtoi64(s,(char **)0,16);
  345. #else
  346. return strtoll(s,(char **)0,16);
  347. #endif
  348. }
  349. static inline double strToDouble(const char *s)
  350. throw()
  351. {
  352. return strtod(s,(char **)0);
  353. }
  354. /**
  355. * Perform a safe C string copy
  356. *
  357. * @param dest Destination buffer
  358. * @param len Length of buffer
  359. * @param src Source string
  360. * @return True on success, false on overflow (buffer will still be 0-terminated)
  361. */
  362. static inline bool scopy(char *dest,unsigned int len,const char *src)
  363. throw()
  364. {
  365. if (!len)
  366. return false; // sanity check
  367. char *end = dest + len;
  368. while ((*dest++ = *src++)) {
  369. if (dest == end) {
  370. *(--dest) = (char)0;
  371. return false;
  372. }
  373. }
  374. return true;
  375. }
  376. /**
  377. * Trim whitespace from the start and end of a string
  378. *
  379. * @param s String to trim
  380. * @return Trimmed string
  381. */
  382. static std::string trim(const std::string &s);
  383. /**
  384. * Like sprintf, but appends to std::string
  385. *
  386. * @param s String to append to
  387. * @param fmt Printf format string
  388. * @param ... Format arguments
  389. * @throws std::bad_alloc Memory allocation failure
  390. * @throws std::length_error Format + args exceeds internal buffer maximum
  391. */
  392. static void stdsprintf(std::string &s,const char *fmt,...)
  393. throw(std::bad_alloc,std::length_error);
  394. /**
  395. * Variant of snprintf that is portable and throws an exception
  396. *
  397. * @param buf Buffer to write to
  398. * @param len Length of buffer in bytes
  399. * @param fmt Format string
  400. * @param ... Format arguments
  401. * @throws std::length_error buf[] too short (buf[] will still be left null-terminated)
  402. */
  403. static unsigned int snprintf(char *buf,unsigned int len,const char *fmt,...)
  404. throw(std::length_error);
  405. /**
  406. * Count the number of bits set in an integer
  407. *
  408. * @param v 32-bit integer
  409. * @return Number of bits set in this integer (0-32)
  410. */
  411. static inline uint32_t countBits(uint32_t v)
  412. throw()
  413. {
  414. v = v - ((v >> 1) & (uint32_t)0x55555555);
  415. v = (v & (uint32_t)0x33333333) + ((v >> 2) & (uint32_t)0x33333333);
  416. return ((((v + (v >> 4)) & (uint32_t)0xF0F0F0F) * (uint32_t)0x1010101) >> 24);
  417. }
  418. /**
  419. * Check if a memory buffer is all-zero
  420. *
  421. * @param p Memory to scan
  422. * @param len Length of memory
  423. * @return True if memory is all zero
  424. */
  425. static inline bool isZero(const void *p,unsigned int len)
  426. throw()
  427. {
  428. for(unsigned int i=0;i<len;++i) {
  429. if (((const unsigned char *)p)[i])
  430. return false;
  431. }
  432. return true;
  433. }
  434. /**
  435. * Match two strings with bits masked netmask-style
  436. *
  437. * @param a First string
  438. * @param abits Number of bits in first string
  439. * @param b Second string
  440. * @param bbits Number of bits in second string
  441. * @return True if min(abits,bbits) match between a and b
  442. */
  443. static inline bool matchNetmask(const void *a,unsigned int abits,const void *b,unsigned int bbits)
  444. throw()
  445. {
  446. const unsigned char *aptr = (const unsigned char *)a;
  447. const unsigned char *bptr = (const unsigned char *)b;
  448. while ((abits >= 8)&&(bbits >= 8)) {
  449. if (*aptr++ != *bptr++)
  450. return false;
  451. abits -= 8;
  452. bbits -= 8;
  453. }
  454. unsigned char mask = 0xff << (8 - ((abits > bbits) ? bbits : abits));
  455. return ((*aptr & mask) == (*aptr & mask));
  456. }
  457. // Byte swappers for big/little endian conversion
  458. static inline uint8_t hton(uint8_t n) throw() { return n; }
  459. static inline int8_t hton(int8_t n) throw() { return n; }
  460. static inline uint16_t hton(uint16_t n) throw() { return htons(n); }
  461. static inline int16_t hton(int16_t n) throw() { return (int16_t)htons((uint16_t)n); }
  462. static inline uint32_t hton(uint32_t n) throw() { return htonl(n); }
  463. static inline int32_t hton(int32_t n) throw() { return (int32_t)htonl((uint32_t)n); }
  464. static inline uint64_t hton(uint64_t n)
  465. throw()
  466. {
  467. #if __BYTE_ORDER == __LITTLE_ENDIAN
  468. #ifdef __GNUC__
  469. return __builtin_bswap64(n);
  470. #else
  471. return (
  472. ((n & 0x00000000000000FFULL) << 56) |
  473. ((n & 0x000000000000FF00ULL) << 40) |
  474. ((n & 0x0000000000FF0000ULL) << 24) |
  475. ((n & 0x00000000FF000000ULL) << 8) |
  476. ((n & 0x000000FF00000000ULL) >> 8) |
  477. ((n & 0x0000FF0000000000ULL) >> 24) |
  478. ((n & 0x00FF000000000000ULL) >> 40) |
  479. ((n & 0xFF00000000000000ULL) >> 56)
  480. );
  481. #endif
  482. #else
  483. return n;
  484. #endif
  485. }
  486. static inline int64_t hton(int64_t n) throw() { return (int64_t)hton((uint64_t)n); }
  487. static inline uint8_t ntoh(uint8_t n) throw() { return n; }
  488. static inline int8_t ntoh(int8_t n) throw() { return n; }
  489. static inline uint16_t ntoh(uint16_t n) throw() { return ntohs(n); }
  490. static inline int16_t ntoh(int16_t n) throw() { return (int16_t)ntohs((uint16_t)n); }
  491. static inline uint32_t ntoh(uint32_t n) throw() { return ntohl(n); }
  492. static inline int32_t ntoh(int32_t n) throw() { return (int32_t)ntohl((uint32_t)n); }
  493. static inline uint64_t ntoh(uint64_t n)
  494. throw()
  495. {
  496. #if __BYTE_ORDER == __LITTLE_ENDIAN
  497. #ifdef __GNUC__
  498. return __builtin_bswap64(n);
  499. #else
  500. return (
  501. ((n & 0x00000000000000FFULL) << 56) |
  502. ((n & 0x000000000000FF00ULL) << 40) |
  503. ((n & 0x0000000000FF0000ULL) << 24) |
  504. ((n & 0x00000000FF000000ULL) << 8) |
  505. ((n & 0x000000FF00000000ULL) >> 8) |
  506. ((n & 0x0000FF0000000000ULL) >> 24) |
  507. ((n & 0x00FF000000000000ULL) >> 40) |
  508. ((n & 0xFF00000000000000ULL) >> 56)
  509. );
  510. #endif
  511. #else
  512. return n;
  513. #endif
  514. }
  515. static inline int64_t ntoh(int64_t n) throw() { return (int64_t)ntoh((uint64_t)n); }
  516. /**
  517. * Hexadecimal characters 0-f
  518. */
  519. static const char HEXCHARS[16];
  520. };
  521. } // namespace ZeroTier
  522. #endif