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