Utils.hpp 15 KB

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