Utils.hpp 20 KB

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