Utils.hpp 20 KB

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