Utils.hpp 20 KB

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