Utils.hpp 20 KB

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