Utils.hpp 18 KB

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