Utils.hpp 15 KB

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