2
0

Utils.hpp 17 KB

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