Utils.hpp 16 KB

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