Utils.hpp 17 KB

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