Utils.hpp 20 KB

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