Utils.hpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612
  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 <time.h>
  33. #include <string>
  34. #include <stdexcept>
  35. #include <vector>
  36. #include <map>
  37. #include "Constants.hpp"
  38. #include "../ext/lz4/lz4.h"
  39. #include "../ext/lz4/lz4hc.h"
  40. #ifdef __WINDOWS__
  41. #include <WinSock2.h>
  42. #include <Windows.h>
  43. #else
  44. #include <unistd.h>
  45. #include <sys/time.h>
  46. #include <arpa/inet.h>
  47. #endif
  48. /**
  49. * Maximum compression/decompression block size (do not change)
  50. */
  51. #define ZT_COMPRESSION_BLOCK_SIZE 16777216
  52. namespace ZeroTier {
  53. /**
  54. * Miscellaneous utility functions and global constants
  55. */
  56. class Utils
  57. {
  58. public:
  59. /**
  60. * Delete a file
  61. *
  62. * @param path Path to delete
  63. * @return True if delete was successful
  64. */
  65. static inline bool rm(const char *path)
  66. throw()
  67. {
  68. #ifdef __WINDOWS__
  69. return (DeleteFileA(path) != FALSE);
  70. #else
  71. return (unlink(path) == 0);
  72. #endif
  73. }
  74. static inline bool rm(const std::string &path)
  75. throw()
  76. {
  77. return rm(path.c_str());
  78. }
  79. /**
  80. * List a directory's contents
  81. *
  82. * @param path Path to list
  83. * @param files Set to fill with files
  84. * @param directories Set to fill with directories
  85. * @return Map of entries and whether or not they are also directories (empty on failure)
  86. */
  87. static std::map<std::string,bool> listDirectory(const char *path);
  88. /**
  89. * @param data Data to convert to hex
  90. * @param len Length of data
  91. * @return Hexadecimal string
  92. */
  93. static std::string hex(const void *data,unsigned int len);
  94. static inline std::string hex(const std::string &data) { return hex(data.data(),data.length()); }
  95. /**
  96. * @param hex Hexadecimal ASCII code (non-hex chars are ignored)
  97. * @return Binary data
  98. */
  99. static std::string unhex(const char *hex);
  100. static inline std::string unhex(const std::string &hex) { return unhex(hex.c_str()); }
  101. /**
  102. * @param hex Hexadecimal ASCII
  103. * @param buf Buffer to fill
  104. * @param len Length of buffer
  105. * @return Number of characters actually written
  106. */
  107. static unsigned int unhex(const char *hex,void *buf,unsigned int len);
  108. /**
  109. * @param buf Buffer to fill
  110. * @param bytes Number of random bytes to generate
  111. */
  112. static void getSecureRandom(void *buf,unsigned int bytes);
  113. /**
  114. * Set modes on a file to something secure
  115. *
  116. * This locks a file so that only the owner can access it. What it actually
  117. * does varies by platform.
  118. *
  119. * @param path Path to lock
  120. * @param isDir True if this is a directory
  121. */
  122. static void lockDownFile(const char *path,bool isDir);
  123. /**
  124. * Get file last modification time
  125. *
  126. * Resolution is often only second, not millisecond, but the return is
  127. * always in ms for comparison against now().
  128. *
  129. * @param path Path to file to get time
  130. * @return Last modification time in ms since epoch or 0 if not found
  131. */
  132. static uint64_t getLastModified(const char *path);
  133. /**
  134. * @param path Path to check
  135. * @return True if file or directory exists at path location
  136. */
  137. static inline bool fileExists(const char *path)
  138. {
  139. return (getLastModified(path) != 0);
  140. }
  141. /**
  142. * @param t64 Time in ms since epoch
  143. * @return RFC1123 date string
  144. */
  145. static std::string toRfc1123(uint64_t t64);
  146. /**
  147. * @param tstr Time in RFC1123 string format
  148. * @return Time in ms since epoch
  149. */
  150. static uint64_t fromRfc1123(const char *tstr);
  151. static inline uint64_t fromRfc1123(const std::string &tstr) { return fromRfc1123(tstr.c_str()); }
  152. /**
  153. * String append output function object for use with compress/decompress
  154. */
  155. class StringAppendOutput
  156. {
  157. public:
  158. StringAppendOutput(std::string &s) : _s(s) {}
  159. inline void operator()(const void *data,unsigned int len) { _s.append((const char *)data,len); }
  160. private:
  161. std::string &_s;
  162. };
  163. /**
  164. * STDIO FILE append output function object for compress/decompress
  165. *
  166. * Throws std::runtime_error on write error.
  167. */
  168. class FILEAppendOutput
  169. {
  170. public:
  171. FILEAppendOutput(FILE *f) : _f(f) {}
  172. inline void operator()(const void *data,unsigned int len)
  173. throw(std::runtime_error)
  174. {
  175. if ((int)fwrite(data,1,len,_f) != (int)len)
  176. throw std::runtime_error("write failed");
  177. }
  178. private:
  179. FILE *_f;
  180. };
  181. /**
  182. * Compress data
  183. *
  184. * O must be a function or function object that takes the following
  185. * arguments: (const void *data,unsigned int len)
  186. *
  187. * @param in Input iterator that reads bytes (char, uint8_t, etc.)
  188. * @param out Output iterator that writes bytes
  189. */
  190. template<typename I,typename O>
  191. static inline void compress(I begin,I end,O out)
  192. {
  193. unsigned int bufLen = LZ4_compressBound(ZT_COMPRESSION_BLOCK_SIZE);
  194. char *buf = new char[bufLen * 2];
  195. char *buf2 = buf + bufLen;
  196. try {
  197. I inp(begin);
  198. for(;;) {
  199. unsigned int readLen = 0;
  200. while ((readLen < ZT_COMPRESSION_BLOCK_SIZE)&&(inp != end)) {
  201. buf[readLen++] = (char)*inp;
  202. ++inp;
  203. }
  204. if (!readLen)
  205. break;
  206. uint32_t l = hton((uint32_t)readLen);
  207. out((const void *)&l,4); // original size
  208. if (readLen < 32) { // don't bother compressing itty bitty blocks
  209. l = 0; // stored
  210. out((const void *)&l,4);
  211. out((const void *)buf,readLen);
  212. continue;
  213. }
  214. int lz4CompressedLen = LZ4_compressHC(buf,buf2,(int)readLen);
  215. if ((lz4CompressedLen <= 0)||(lz4CompressedLen >= (int)readLen)) {
  216. l = 0; // stored
  217. out((const void *)&l,4);
  218. out((const void *)buf,readLen);
  219. continue;
  220. }
  221. l = hton((uint32_t)lz4CompressedLen); // lz4 only
  222. out((const void *)&l,4);
  223. out((const void *)buf2,(unsigned int)lz4CompressedLen);
  224. }
  225. delete [] buf;
  226. } catch ( ... ) {
  227. delete [] buf;
  228. throw;
  229. }
  230. }
  231. /**
  232. * Decompress data
  233. *
  234. * O must be a function or function object that takes the following
  235. * arguments: (const void *data,unsigned int len)
  236. *
  237. * @param in Input iterator that reads bytes (char, uint8_t, etc.)
  238. * @param out Output iterator that writes bytes
  239. * @return False on decompression error
  240. */
  241. template<typename I,typename O>
  242. static inline bool decompress(I begin,I end,O out)
  243. {
  244. volatile char i32c[4];
  245. void *const i32cp = (void *)i32c;
  246. unsigned int bufLen = LZ4_compressBound(ZT_COMPRESSION_BLOCK_SIZE);
  247. char *buf = new char[bufLen * 2];
  248. char *buf2 = buf + bufLen;
  249. try {
  250. I inp(begin);
  251. while (inp != end) {
  252. i32c[0] = (char)*inp; if (++inp == end) { delete [] buf; return false; }
  253. i32c[1] = (char)*inp; if (++inp == end) { delete [] buf; return false; }
  254. i32c[2] = (char)*inp; if (++inp == end) { delete [] buf; return false; }
  255. i32c[3] = (char)*inp; if (++inp == end) { delete [] buf; return false; }
  256. unsigned int originalSize = ntoh(*((const uint32_t *)i32cp));
  257. i32c[0] = (char)*inp; if (++inp == end) { delete [] buf; return false; }
  258. i32c[1] = (char)*inp; if (++inp == end) { delete [] buf; return false; }
  259. i32c[2] = (char)*inp; if (++inp == end) { delete [] buf; return false; }
  260. i32c[3] = (char)*inp; if (++inp == end) { delete [] buf; return false; }
  261. uint32_t _compressedSize = ntoh(*((const uint32_t *)i32cp));
  262. unsigned int compressedSize = _compressedSize & 0x7fffffff;
  263. if (compressedSize) {
  264. if (compressedSize > bufLen) {
  265. delete [] buf;
  266. return false;
  267. }
  268. unsigned int readLen = 0;
  269. while ((readLen < compressedSize)&&(inp != end)) {
  270. buf[readLen++] = (char)*inp;
  271. ++inp;
  272. }
  273. if (readLen != compressedSize) {
  274. delete [] buf;
  275. return false;
  276. }
  277. if (LZ4_uncompress_unknownOutputSize(buf,buf2,compressedSize,bufLen) != (int)originalSize) {
  278. delete [] buf;
  279. return false;
  280. } else out((const void *)buf2,(unsigned int)originalSize);
  281. } else { // stored
  282. if (originalSize > bufLen) {
  283. delete [] buf;
  284. return false;
  285. }
  286. unsigned int readLen = 0;
  287. while ((readLen < originalSize)&&(inp != end)) {
  288. buf[readLen++] = (char)*inp;
  289. ++inp;
  290. }
  291. if (readLen != originalSize) {
  292. delete [] buf;
  293. return false;
  294. }
  295. out((const void *)buf,(unsigned int)originalSize);
  296. }
  297. }
  298. delete [] buf;
  299. return true;
  300. } catch ( ... ) {
  301. delete [] buf;
  302. throw;
  303. }
  304. }
  305. /**
  306. * @return Current time in milliseconds since epoch
  307. */
  308. static inline uint64_t now()
  309. throw()
  310. {
  311. #ifdef __WINDOWS__
  312. FILETIME ft;
  313. SYSTEMTIME st;
  314. ULARGE_INTEGER tmp;
  315. GetSystemTime(&st);
  316. SystemTimeToFileTime(&st,&ft);
  317. tmp.LowPart = ft.dwLowDateTime;
  318. tmp.HighPart = ft.dwHighDateTime;
  319. return ( ((tmp.QuadPart - 116444736000000000ULL) / 10000L) + st.wMilliseconds );
  320. #else
  321. struct timeval tv;
  322. gettimeofday(&tv,(struct timezone *)0);
  323. return ( (1000ULL * (uint64_t)tv.tv_sec) + (uint64_t)(tv.tv_usec / 1000) );
  324. #endif
  325. };
  326. /**
  327. * @return Current time in seconds since epoch, to the highest available resolution
  328. */
  329. static inline double nowf()
  330. throw()
  331. {
  332. #ifdef __WINDOWS__
  333. FILETIME ft;
  334. SYSTEMTIME st;
  335. ULARGE_INTEGER tmp;
  336. GetSystemTime(&st);
  337. SystemTimeToFileTime(&st,&ft);
  338. tmp.LowPart = ft.dwLowDateTime;
  339. tmp.HighPart = ft.dwHighDateTime;
  340. return (((double)(tmp.QuadPart - 116444736000000000ULL)) / 10000000.0);
  341. #else
  342. struct timeval tv;
  343. gettimeofday(&tv,(struct timezone *)0);
  344. return ( ((double)tv.tv_sec) + (((double)tv.tv_usec) / 1000000.0) );
  345. #endif
  346. }
  347. /**
  348. * Read the full contents of a file into a string buffer
  349. *
  350. * The buffer isn't cleared, so if it already contains data the file's data will
  351. * be appended.
  352. *
  353. * @param path Path of file to read
  354. * @param buf Buffer to fill
  355. * @return True if open and read successful
  356. */
  357. static bool readFile(const char *path,std::string &buf);
  358. /**
  359. * Write a block of data to disk, replacing any current file contents
  360. *
  361. * @param path Path to write
  362. * @param buf Buffer containing data
  363. * @param len Length of buffer
  364. * @return True if entire file was successfully written
  365. */
  366. static bool writeFile(const char *path,const void *buf,unsigned int len);
  367. /**
  368. * Write a block of data to disk, replacing any current file contents
  369. *
  370. * @param path Path to write
  371. * @param s Data to write
  372. * @return True if entire file was successfully written
  373. */
  374. static inline bool writeFile(const char *path,const std::string &s)
  375. {
  376. return writeFile(path,s.data(),s.length());
  377. }
  378. /**
  379. * @param data Binary data to encode
  380. * @param len Length of data
  381. * @return Base64-encoded string
  382. */
  383. static std::string base64Encode(const void *data,unsigned int len);
  384. inline static std::string base64Encode(const std::string &data) { return base64Encode(data.data(),data.length()); }
  385. /**
  386. * @param data Base64-encoded string
  387. * @param len Length of encoded string
  388. * @return Decoded binary date
  389. */
  390. static std::string base64Decode(const char *data,unsigned int len);
  391. inline static std::string base64Decode(const std::string &data) { return base64Decode(data.data(),data.length()); }
  392. /**
  393. * Split a string by delimiter, with optional escape and quote characters
  394. *
  395. * @param s String to split
  396. * @param sep One or more separators
  397. * @param esc Zero or more escape characters
  398. * @param quot Zero or more quote characters
  399. * @return Vector of tokens
  400. */
  401. static std::vector<std::string> split(const char *s,const char *const sep,const char *esc,const char *quot);
  402. /**
  403. * Trim whitespace from the start and end of a string
  404. *
  405. * @param s String to trim
  406. * @return Trimmed string
  407. */
  408. static std::string trim(const std::string &s);
  409. /**
  410. * Like sprintf, but appends to std::string
  411. *
  412. * @param s String to append to
  413. * @param fmt Printf format string
  414. * @param ... Format arguments
  415. * @throws std::bad_alloc Memory allocation failure
  416. * @throws std::length_error Format + args exceeds internal buffer maximum
  417. */
  418. static void stdsprintf(std::string &s,const char *fmt,...)
  419. throw(std::bad_alloc,std::length_error);
  420. /**
  421. * Count the number of bits set in an integer
  422. *
  423. * @param v 32-bit integer
  424. * @return Number of bits set in this integer (0-32)
  425. */
  426. static inline uint32_t countBits(uint32_t v)
  427. throw()
  428. {
  429. v = v - ((v >> 1) & (uint32_t)0x55555555);
  430. v = (v & (uint32_t)0x33333333) + ((v >> 2) & (uint32_t)0x33333333);
  431. return ((((v + (v >> 4)) & (uint32_t)0xF0F0F0F) * (uint32_t)0x1010101) >> 24);
  432. }
  433. /**
  434. * Check if a memory buffer is all-zero
  435. *
  436. * @param p Memory to scan
  437. * @param len Length of memory
  438. * @return True if memory is all zero
  439. */
  440. static inline bool isZero(const void *p,unsigned int len)
  441. throw()
  442. {
  443. for(unsigned int i=0;i<len;++i) {
  444. if (((const unsigned char *)p)[i])
  445. return false;
  446. }
  447. return true;
  448. }
  449. /**
  450. * Match two strings with bits masked netmask-style
  451. *
  452. * @param a First string
  453. * @param abits Number of bits in first string
  454. * @param b Second string
  455. * @param bbits Number of bits in second string
  456. * @return True if min(abits,bbits) match between a and b
  457. */
  458. static inline bool matchNetmask(const void *a,unsigned int abits,const void *b,unsigned int bbits)
  459. throw()
  460. {
  461. const unsigned char *aptr = (const unsigned char *)a;
  462. const unsigned char *bptr = (const unsigned char *)b;
  463. while ((abits >= 8)&&(bbits >= 8)) {
  464. if (*aptr++ != *bptr++)
  465. return false;
  466. abits -= 8;
  467. bbits -= 8;
  468. }
  469. unsigned char mask = 0xff << (8 - ((abits > bbits) ? bbits : abits));
  470. return ((*aptr & mask) == (*aptr & mask));
  471. }
  472. /**
  473. * Compute CRC64
  474. *
  475. * @param crc Previous CRC (0 to start)
  476. * @param s String to add to crc
  477. * @param l Length of string in bytes
  478. * @return New CRC
  479. */
  480. static inline uint64_t crc64(uint64_t crc,const void *s,unsigned int l)
  481. throw()
  482. {
  483. for(unsigned int i=0;i<l;++i)
  484. crc = crc64Table[(uint8_t)crc ^ ((const uint8_t *)s)[i]] ^ (crc >> 8);
  485. return crc;
  486. }
  487. static inline uint8_t hton(uint8_t n) throw() { return n; }
  488. static inline int8_t hton(int8_t n) throw() { return n; }
  489. static inline uint16_t hton(uint16_t n) throw() { return htons(n); }
  490. static inline int16_t hton(int16_t n) throw() { return (int16_t)htons((uint16_t)n); }
  491. static inline uint32_t hton(uint32_t n) throw() { return htonl(n); }
  492. static inline int32_t hton(int32_t n) throw() { return (int32_t)htonl((uint32_t)n); }
  493. static inline uint64_t hton(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 hton(int64_t n) throw() { return (int64_t)hton((uint64_t)n); }
  516. static inline uint8_t ntoh(uint8_t n) throw() { return n; }
  517. static inline int8_t ntoh(int8_t n) throw() { return n; }
  518. static inline uint16_t ntoh(uint16_t n) throw() { return ntohs(n); }
  519. static inline int16_t ntoh(int16_t n) throw() { return (int16_t)ntohs((uint16_t)n); }
  520. static inline uint32_t ntoh(uint32_t n) throw() { return ntohl(n); }
  521. static inline int32_t ntoh(int32_t n) throw() { return (int32_t)ntohl((uint32_t)n); }
  522. static inline uint64_t ntoh(uint64_t n)
  523. throw()
  524. {
  525. #if __BYTE_ORDER == __LITTLE_ENDIAN
  526. #ifdef __GNUC__
  527. return __builtin_bswap64(n);
  528. #else
  529. return (
  530. ((n & 0x00000000000000FFULL) << 56) |
  531. ((n & 0x000000000000FF00ULL) << 40) |
  532. ((n & 0x0000000000FF0000ULL) << 24) |
  533. ((n & 0x00000000FF000000ULL) << 8) |
  534. ((n & 0x000000FF00000000ULL) >> 8) |
  535. ((n & 0x0000FF0000000000ULL) >> 24) |
  536. ((n & 0x00FF000000000000ULL) >> 40) |
  537. ((n & 0xFF00000000000000ULL) >> 56)
  538. );
  539. #endif
  540. #else
  541. return n;
  542. #endif
  543. }
  544. static inline int64_t ntoh(int64_t n) throw() { return (int64_t)ntoh((uint64_t)n); }
  545. /**
  546. * Hexadecimal characters 0-f
  547. */
  548. static const char HEXCHARS[16];
  549. private:
  550. static const uint64_t crc64Table[256];
  551. static const char base64EncMap[64];
  552. static const char base64DecMap[128];
  553. };
  554. } // namespace ZeroTier
  555. #endif