Utils.hpp 16 KB

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