Utils.hpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630
  1. /*
  2. * ZeroTier One - Global Peer to Peer Ethernet
  3. * Copyright (C) 2011-2014 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 <string.h>
  33. #include <time.h>
  34. #include <string>
  35. #include <stdexcept>
  36. #include <vector>
  37. #include <map>
  38. #include "Constants.hpp"
  39. #ifdef __WINDOWS__
  40. #include <WinSock2.h>
  41. #include <Windows.h>
  42. #else
  43. #include <unistd.h>
  44. #include <sys/time.h>
  45. #include <arpa/inet.h>
  46. #endif
  47. namespace ZeroTier {
  48. /**
  49. * Miscellaneous utility functions and global constants
  50. */
  51. class Utils
  52. {
  53. public:
  54. #ifdef __UNIX_LIKE__
  55. /**
  56. * Close STDOUT_FILENO and STDERR_FILENO and replace them with output to given path
  57. *
  58. * This can be called after fork() and prior to exec() to suppress output
  59. * from a subprocess, such as auto-update.
  60. *
  61. * @param stdoutPath Path to file to use for stdout
  62. * @param stderrPath Path to file to use for stderr, or NULL for same as stdout (default)
  63. * @return True on success
  64. */
  65. static bool redirectUnixOutputs(const char *stdoutPath,const char *stderrPath = (const char *)0)
  66. throw();
  67. #endif // __UNIX_LIKE__
  68. /**
  69. * Perform a time-invariant binary comparison
  70. *
  71. * @param a First binary string
  72. * @param b Second binary string
  73. * @param len Length of strings
  74. * @return True if strings are equal
  75. */
  76. static inline bool secureEq(const void *a,const void *b,unsigned int len)
  77. throw()
  78. {
  79. const char *p1 = (const char *)a;
  80. const char *p2 = (const char *)b;
  81. uint64_t diff = 0;
  82. while (len >= 8) {
  83. diff |= (*((const uint64_t *)p1) ^ *((const uint64_t *)p2));
  84. p1 += 8;
  85. p2 += 8;
  86. len -= 8;
  87. }
  88. while (len--)
  89. diff |= (uint64_t)(*p1++ ^ *p2++);
  90. return (diff == 0ULL);
  91. }
  92. /**
  93. * Securely zero memory
  94. *
  95. * This just uses volatile to ensure that it's never optimized out.
  96. */
  97. static inline void burn(void *ptr,unsigned int len)
  98. throw()
  99. {
  100. volatile unsigned char *p = (unsigned char *)ptr;
  101. volatile unsigned char *e = p + len;
  102. while (p != e)
  103. *(p++) = (unsigned char)0;
  104. }
  105. /**
  106. * Delete a file
  107. *
  108. * @param path Path to delete
  109. * @return True if delete was successful
  110. */
  111. static inline bool rm(const char *path)
  112. throw()
  113. {
  114. #ifdef __WINDOWS__
  115. return (DeleteFileA(path) != FALSE);
  116. #else
  117. return (unlink(path) == 0);
  118. #endif
  119. }
  120. static inline bool rm(const std::string &path) throw() { return rm(path.c_str()); }
  121. /**
  122. * List a directory's contents
  123. *
  124. * Keys in returned map are filenames only and don't include the leading
  125. * path. Pseudo-paths like . and .. are not returned. Values are true if
  126. * the item is a directory, false if it's a file. More detailed attributes
  127. * aren't supported since the code that uses this doesn't need them.
  128. *
  129. * @param path Path to list
  130. * @return Map of entries and whether or not they are also directories (empty on failure)
  131. */
  132. static std::map<std::string,bool> listDirectory(const char *path);
  133. /**
  134. * Convert binary data to hexadecimal
  135. *
  136. * @param data Data to convert to hex
  137. * @param len Length of data
  138. * @return Hexadecimal string
  139. */
  140. static std::string hex(const void *data,unsigned int len);
  141. static inline std::string hex(const std::string &data) { return hex(data.data(),(unsigned int)data.length()); }
  142. /**
  143. * Convert hexadecimal to binary data
  144. *
  145. * This ignores all non-hex characters, just stepping over them and
  146. * continuing. Upper and lower case are supported for letters a-f.
  147. *
  148. * @param hex Hexadecimal ASCII code (non-hex chars are ignored, stops at zero or maxlen)
  149. * @param maxlen Maximum length of hex string buffer
  150. * @return Binary data
  151. */
  152. static std::string unhex(const char *hex,unsigned int maxlen);
  153. static inline std::string unhex(const std::string &hex) { return unhex(hex.c_str(),(unsigned int)hex.length()); }
  154. /**
  155. * Convert hexadecimal to binary data
  156. *
  157. * This ignores all non-hex characters, just stepping over them and
  158. * continuing. Upper and lower case are supported for letters a-f.
  159. *
  160. * @param hex Hexadecimal ASCII
  161. * @param maxlen Maximum length of hex string buffer
  162. * @param buf Buffer to fill
  163. * @param len Length of buffer
  164. * @return Number of characters actually written
  165. */
  166. static unsigned int unhex(const char *hex,unsigned int maxlen,void *buf,unsigned int len);
  167. static inline unsigned int unhex(const std::string &hex,void *buf,unsigned int len) { return unhex(hex.c_str(),(unsigned int)hex.length(),buf,len); }
  168. /**
  169. * Generate secure random bytes
  170. *
  171. * This will try to use whatever OS sources of entropy are available. It's
  172. * guarded by an internal mutex so it's thread-safe.
  173. *
  174. * @param buf Buffer to fill
  175. * @param bytes Number of random bytes to generate
  176. */
  177. static void getSecureRandom(void *buf,unsigned int bytes);
  178. /**
  179. * Set modes on a file to something secure
  180. *
  181. * This locks a file so that only the owner can access it. What it actually
  182. * does varies by platform.
  183. *
  184. * @param path Path to lock
  185. * @param isDir True if this is a directory
  186. */
  187. static void lockDownFile(const char *path,bool isDir);
  188. /**
  189. * Get file last modification time
  190. *
  191. * Resolution is often only second, not millisecond, but the return is
  192. * always in ms for comparison against now().
  193. *
  194. * @param path Path to file to get time
  195. * @return Last modification time in ms since epoch or 0 if not found
  196. */
  197. static uint64_t getLastModified(const char *path);
  198. /**
  199. * @param path Path to check
  200. * @param followLinks Follow links (on platforms with that concept)
  201. * @return True if file or directory exists at path location
  202. */
  203. static bool fileExists(const char *path,bool followLinks = true);
  204. /**
  205. * @param path Path to file
  206. * @return File size or -1 if nonexistent or other failure
  207. */
  208. static int64_t getFileSize(const char *path);
  209. /**
  210. * @return Current time in milliseconds since epoch
  211. */
  212. static inline uint64_t now()
  213. throw()
  214. {
  215. #ifdef __WINDOWS__
  216. FILETIME ft;
  217. SYSTEMTIME st;
  218. ULARGE_INTEGER tmp;
  219. GetSystemTime(&st);
  220. SystemTimeToFileTime(&st,&ft);
  221. tmp.LowPart = ft.dwLowDateTime;
  222. tmp.HighPart = ft.dwHighDateTime;
  223. return ( ((tmp.QuadPart - 116444736000000000ULL) / 10000L) + st.wMilliseconds );
  224. #else
  225. struct timeval tv;
  226. gettimeofday(&tv,(struct timezone *)0);
  227. return ( (1000ULL * (uint64_t)tv.tv_sec) + (uint64_t)(tv.tv_usec / 1000) );
  228. #endif
  229. };
  230. /**
  231. * @return Current time in seconds since epoch, to the highest available resolution
  232. */
  233. static inline double nowf()
  234. throw()
  235. {
  236. #ifdef __WINDOWS__
  237. FILETIME ft;
  238. SYSTEMTIME st;
  239. ULARGE_INTEGER tmp;
  240. GetSystemTime(&st);
  241. SystemTimeToFileTime(&st,&ft);
  242. tmp.LowPart = ft.dwLowDateTime;
  243. tmp.HighPart = ft.dwHighDateTime;
  244. return (((double)(tmp.QuadPart - 116444736000000000ULL)) / 10000000.0);
  245. #else
  246. struct timeval tv;
  247. gettimeofday(&tv,(struct timezone *)0);
  248. return ( ((double)tv.tv_sec) + (((double)tv.tv_usec) / 1000000.0) );
  249. #endif
  250. }
  251. /**
  252. * Read the full contents of a file into a string buffer
  253. *
  254. * The buffer isn't cleared, so if it already contains data the file's data will
  255. * be appended.
  256. *
  257. * @param path Path of file to read
  258. * @param buf Buffer to fill
  259. * @return True if open and read successful
  260. */
  261. static bool readFile(const char *path,std::string &buf);
  262. /**
  263. * Write a block of data to disk, replacing any current file contents
  264. *
  265. * @param path Path to write
  266. * @param buf Buffer containing data
  267. * @param len Length of buffer
  268. * @return True if entire file was successfully written
  269. */
  270. static bool writeFile(const char *path,const void *buf,unsigned int len);
  271. /**
  272. * Write a block of data to disk, replacing any current file contents
  273. *
  274. * @param path Path to write
  275. * @param s Data to write
  276. * @return True if entire file was successfully written
  277. */
  278. static inline bool writeFile(const char *path,const std::string &s)
  279. {
  280. return writeFile(path,s.data(),(unsigned int)s.length());
  281. }
  282. /**
  283. * Split a string by delimiter, with optional escape and quote characters
  284. *
  285. * @param s String to split
  286. * @param sep One or more separators
  287. * @param esc Zero or more escape characters
  288. * @param quot Zero or more quote characters
  289. * @return Vector of tokens
  290. */
  291. static std::vector<std::string> split(const char *s,const char *const sep,const char *esc,const char *quot);
  292. /**
  293. * Tokenize a string (alias for strtok_r or strtok_s depending on platform)
  294. *
  295. * @param str String to split
  296. * @param delim Delimiters
  297. * @param saveptr Pointer to a char * for temporary reentrant storage
  298. */
  299. static inline char *stok(char *str,const char *delim,char **saveptr)
  300. throw()
  301. {
  302. #ifdef __WINDOWS__
  303. return strtok_s(str,delim,saveptr);
  304. #else
  305. return strtok_r(str,delim,saveptr);
  306. #endif
  307. }
  308. // String to number converters -- defined here to permit portability
  309. // ifdefs for platforms that lack some of the strtoXX functions.
  310. static inline unsigned int strToUInt(const char *s)
  311. throw()
  312. {
  313. return (unsigned int)strtoul(s,(char **)0,10);
  314. }
  315. static inline int strToInt(const char *s)
  316. throw()
  317. {
  318. return (int)strtol(s,(char **)0,10);
  319. }
  320. static inline unsigned long strToULong(const char *s)
  321. throw()
  322. {
  323. return strtoul(s,(char **)0,10);
  324. }
  325. static inline long strToLong(const char *s)
  326. throw()
  327. {
  328. return strtol(s,(char **)0,10);
  329. }
  330. static inline unsigned long long strToU64(const char *s)
  331. throw()
  332. {
  333. #ifdef __WINDOWS__
  334. return (unsigned long long)_strtoui64(s,(char **)0,10);
  335. #else
  336. return strtoull(s,(char **)0,10);
  337. #endif
  338. }
  339. static inline long long strTo64(const char *s)
  340. throw()
  341. {
  342. #ifdef __WINDOWS__
  343. return (long long)_strtoi64(s,(char **)0,10);
  344. #else
  345. return strtoll(s,(char **)0,10);
  346. #endif
  347. }
  348. static inline unsigned int hexStrToUInt(const char *s)
  349. throw()
  350. {
  351. return (unsigned int)strtoul(s,(char **)0,16);
  352. }
  353. static inline int hexStrToInt(const char *s)
  354. throw()
  355. {
  356. return (int)strtol(s,(char **)0,16);
  357. }
  358. static inline unsigned long hexStrToULong(const char *s)
  359. throw()
  360. {
  361. return strtoul(s,(char **)0,16);
  362. }
  363. static inline long hexStrToLong(const char *s)
  364. throw()
  365. {
  366. return strtol(s,(char **)0,16);
  367. }
  368. static inline unsigned long long hexStrToU64(const char *s)
  369. throw()
  370. {
  371. #ifdef __WINDOWS__
  372. return (unsigned long long)_strtoui64(s,(char **)0,16);
  373. #else
  374. return strtoull(s,(char **)0,16);
  375. #endif
  376. }
  377. static inline long long hexStrTo64(const char *s)
  378. throw()
  379. {
  380. #ifdef __WINDOWS__
  381. return (long long)_strtoi64(s,(char **)0,16);
  382. #else
  383. return strtoll(s,(char **)0,16);
  384. #endif
  385. }
  386. static inline double strToDouble(const char *s)
  387. throw()
  388. {
  389. return strtod(s,(char **)0);
  390. }
  391. /**
  392. * Perform a safe C string copy
  393. *
  394. * @param dest Destination buffer
  395. * @param len Length of buffer
  396. * @param src Source string
  397. * @return True on success, false on overflow (buffer will still be 0-terminated)
  398. */
  399. static inline bool scopy(char *dest,unsigned int len,const char *src)
  400. throw()
  401. {
  402. if (!len)
  403. return false; // sanity check
  404. char *end = dest + len;
  405. while ((*dest++ = *src++)) {
  406. if (dest == end) {
  407. *(--dest) = (char)0;
  408. return false;
  409. }
  410. }
  411. return true;
  412. }
  413. /**
  414. * Trim whitespace from the start and end of a string
  415. *
  416. * @param s String to trim
  417. * @return Trimmed string
  418. */
  419. static std::string trim(const std::string &s);
  420. /**
  421. * Variant of snprintf that is portable and throws an exception
  422. *
  423. * This just wraps the local implementation whatever it's called, while
  424. * performing a few other checks and adding exceptions for overflow.
  425. *
  426. * @param buf Buffer to write to
  427. * @param len Length of buffer in bytes
  428. * @param fmt Format string
  429. * @param ... Format arguments
  430. * @throws std::length_error buf[] too short (buf[] will still be left null-terminated)
  431. */
  432. static unsigned int snprintf(char *buf,unsigned int len,const char *fmt,...)
  433. throw(std::length_error);
  434. /**
  435. * Count the number of bits set in an integer
  436. *
  437. * @param v 32-bit integer
  438. * @return Number of bits set in this integer (0-32)
  439. */
  440. static inline uint32_t countBits(uint32_t v)
  441. throw()
  442. {
  443. v = v - ((v >> 1) & (uint32_t)0x55555555);
  444. v = (v & (uint32_t)0x33333333) + ((v >> 2) & (uint32_t)0x33333333);
  445. return ((((v + (v >> 4)) & (uint32_t)0xF0F0F0F) * (uint32_t)0x1010101) >> 24);
  446. }
  447. /**
  448. * Check if a memory buffer is all-zero
  449. *
  450. * @param p Memory to scan
  451. * @param len Length of memory
  452. * @return True if memory is all zero
  453. */
  454. static inline bool isZero(const void *p,unsigned int len)
  455. throw()
  456. {
  457. for(unsigned int i=0;i<len;++i) {
  458. if (((const unsigned char *)p)[i])
  459. return false;
  460. }
  461. return true;
  462. }
  463. /**
  464. * Compute SDBM hash of a binary string
  465. *
  466. * See: http://www.cse.yorku.ca/~oz/hash.html
  467. *
  468. * @param s Data to hash
  469. * @param l Length in bytes
  470. * @param h Previous hash value (use 0 initially)
  471. * @tparam H Hash integer type -- should be unsigned
  472. * @return New hash value
  473. */
  474. template<typename H>
  475. static inline H sdbmHash(const void *s,unsigned int l,H h)
  476. throw()
  477. {
  478. for(unsigned int i=0;i<l;++i)
  479. h = ((H)(((const unsigned char *)s)[i])) + (h << 6) + (h << 16) - h;
  480. return h;
  481. }
  482. /**
  483. * Compute SDBM hash of a 0-terminated C string
  484. *
  485. * See: http://www.cse.yorku.ca/~oz/hash.html
  486. *
  487. * @param s C-string to hash
  488. * @param h Previous hash value (use 0 initially)
  489. * @tparam H Hash integer type -- should be unsigned
  490. * @return New hash value
  491. */
  492. template<typename H>
  493. static inline H sdbmHash(const char *s,H h)
  494. throw()
  495. {
  496. char c;
  497. while ((c = *(s++)))
  498. h = ((H)c) + (h << 6) + (h << 16) - h;
  499. return h;
  500. }
  501. /**
  502. * Compute SDBM hash of an integer's bytes in little-endian byte order
  503. *
  504. * See: http://www.cse.yorku.ca/~oz/hash.html
  505. *
  506. * @param n Integer to hash in LE byte order
  507. * @param h Previous hash value (use 0 initially)
  508. * @tparam I Integer type -- should be unsigned
  509. * @tparam H Hash integer type -- should be unsigned
  510. * @return New hash value
  511. */
  512. template<typename I,typename H>
  513. static inline H sdbmHash(I n,H h)
  514. throw()
  515. {
  516. for(unsigned int i=0;i<(unsigned int)sizeof(n);++i) {
  517. h = ((H)(n & 0xff)) + (h << 6) + (h << 16) - h;
  518. n >>= 8;
  519. }
  520. return h;
  521. }
  522. // Byte swappers for big/little endian conversion
  523. static inline uint8_t hton(uint8_t n) throw() { return n; }
  524. static inline int8_t hton(int8_t n) throw() { return n; }
  525. static inline uint16_t hton(uint16_t n) throw() { return htons(n); }
  526. static inline int16_t hton(int16_t n) throw() { return (int16_t)htons((uint16_t)n); }
  527. static inline uint32_t hton(uint32_t n) throw() { return htonl(n); }
  528. static inline int32_t hton(int32_t n) throw() { return (int32_t)htonl((uint32_t)n); }
  529. static inline uint64_t hton(uint64_t n)
  530. throw()
  531. {
  532. #if __BYTE_ORDER == __LITTLE_ENDIAN
  533. #ifdef __GNUC__
  534. return __builtin_bswap64(n);
  535. #else
  536. return (
  537. ((n & 0x00000000000000FFULL) << 56) |
  538. ((n & 0x000000000000FF00ULL) << 40) |
  539. ((n & 0x0000000000FF0000ULL) << 24) |
  540. ((n & 0x00000000FF000000ULL) << 8) |
  541. ((n & 0x000000FF00000000ULL) >> 8) |
  542. ((n & 0x0000FF0000000000ULL) >> 24) |
  543. ((n & 0x00FF000000000000ULL) >> 40) |
  544. ((n & 0xFF00000000000000ULL) >> 56)
  545. );
  546. #endif
  547. #else
  548. return n;
  549. #endif
  550. }
  551. static inline int64_t hton(int64_t n) throw() { return (int64_t)hton((uint64_t)n); }
  552. static inline uint8_t ntoh(uint8_t n) throw() { return n; }
  553. static inline int8_t ntoh(int8_t n) throw() { return n; }
  554. static inline uint16_t ntoh(uint16_t n) throw() { return ntohs(n); }
  555. static inline int16_t ntoh(int16_t n) throw() { return (int16_t)ntohs((uint16_t)n); }
  556. static inline uint32_t ntoh(uint32_t n) throw() { return ntohl(n); }
  557. static inline int32_t ntoh(int32_t n) throw() { return (int32_t)ntohl((uint32_t)n); }
  558. static inline uint64_t ntoh(uint64_t n)
  559. throw()
  560. {
  561. #if __BYTE_ORDER == __LITTLE_ENDIAN
  562. #ifdef __GNUC__
  563. return __builtin_bswap64(n);
  564. #else
  565. return (
  566. ((n & 0x00000000000000FFULL) << 56) |
  567. ((n & 0x000000000000FF00ULL) << 40) |
  568. ((n & 0x0000000000FF0000ULL) << 24) |
  569. ((n & 0x00000000FF000000ULL) << 8) |
  570. ((n & 0x000000FF00000000ULL) >> 8) |
  571. ((n & 0x0000FF0000000000ULL) >> 24) |
  572. ((n & 0x00FF000000000000ULL) >> 40) |
  573. ((n & 0xFF00000000000000ULL) >> 56)
  574. );
  575. #endif
  576. #else
  577. return n;
  578. #endif
  579. }
  580. static inline int64_t ntoh(int64_t n) throw() { return (int64_t)ntoh((uint64_t)n); }
  581. /**
  582. * Hexadecimal characters 0-f
  583. */
  584. static const char HEXCHARS[16];
  585. };
  586. } // namespace ZeroTier
  587. #endif