Path.hpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337
  1. /*
  2. * ZeroTier One - Network Virtualization Everywhere
  3. * Copyright (C) 2011-2017 ZeroTier, Inc. https://www.zerotier.com/
  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. * You can be released from the requirements of the license by purchasing
  21. * a commercial license. Buying such a license is mandatory as soon as you
  22. * develop commercial closed-source software that incorporates or links
  23. * directly against ZeroTier software without disclosing the source code
  24. * of your own application.
  25. */
  26. #ifndef ZT_PATH_HPP
  27. #define ZT_PATH_HPP
  28. #include <stdint.h>
  29. #include <string.h>
  30. #include <stdlib.h>
  31. #include <stdexcept>
  32. #include <algorithm>
  33. #include "Constants.hpp"
  34. #include "InetAddress.hpp"
  35. #include "SharedPtr.hpp"
  36. #include "AtomicCounter.hpp"
  37. #include "NonCopyable.hpp"
  38. #include "Utils.hpp"
  39. /**
  40. * Maximum return value of preferenceRank()
  41. */
  42. #define ZT_PATH_MAX_PREFERENCE_RANK ((ZT_INETADDRESS_MAX_SCOPE << 1) | 1)
  43. namespace ZeroTier {
  44. class RuntimeEnvironment;
  45. /**
  46. * A path across the physical network
  47. */
  48. class Path : NonCopyable
  49. {
  50. friend class SharedPtr<Path>;
  51. public:
  52. /**
  53. * Efficient unique key for paths in a Hashtable
  54. */
  55. class HashKey
  56. {
  57. public:
  58. HashKey() {}
  59. HashKey(const int64_t l,const InetAddress &r)
  60. {
  61. if (r.ss_family == AF_INET) {
  62. _k[0] = (uint64_t)reinterpret_cast<const struct sockaddr_in *>(&r)->sin_addr.s_addr;
  63. _k[1] = (uint64_t)reinterpret_cast<const struct sockaddr_in *>(&r)->sin_port;
  64. _k[2] = (uint64_t)l;
  65. } else if (r.ss_family == AF_INET6) {
  66. memcpy(_k,reinterpret_cast<const struct sockaddr_in6 *>(&r)->sin6_addr.s6_addr,16);
  67. _k[2] = ((uint64_t)reinterpret_cast<const struct sockaddr_in6 *>(&r)->sin6_port << 32) ^ (uint64_t)l;
  68. } else {
  69. memcpy(_k,&r,std::min(sizeof(_k),sizeof(InetAddress)));
  70. _k[2] += (uint64_t)l;
  71. }
  72. }
  73. inline unsigned long hashCode() const { return (unsigned long)(_k[0] + _k[1] + _k[2]); }
  74. inline bool operator==(const HashKey &k) const { return ( (_k[0] == k._k[0]) && (_k[1] == k._k[1]) && (_k[2] == k._k[2]) ); }
  75. inline bool operator!=(const HashKey &k) const { return (!(*this == k)); }
  76. private:
  77. uint64_t _k[3];
  78. };
  79. Path() :
  80. _lastOut(0),
  81. _lastIn(0),
  82. _lastTrustEstablishedPacketReceived(0),
  83. _incomingLinkQualityFastLog(0xffffffffffffffffULL),
  84. _localSocket(-1),
  85. _incomingLinkQualitySlowLogPtr(0),
  86. _incomingLinkQualitySlowLogCounter(-64), // discard first fast log
  87. _incomingLinkQualityPreviousPacketCounter(0),
  88. _outgoingPacketCounter(0),
  89. _latency(0xffff),
  90. _addr(),
  91. _ipScope(InetAddress::IP_SCOPE_NONE)
  92. {
  93. for(int i=0;i<(int)sizeof(_incomingLinkQualitySlowLog);++i)
  94. _incomingLinkQualitySlowLog[i] = ZT_PATH_LINK_QUALITY_MAX;
  95. }
  96. Path(const int64_t localSocket,const InetAddress &addr) :
  97. _lastOut(0),
  98. _lastIn(0),
  99. _lastTrustEstablishedPacketReceived(0),
  100. _incomingLinkQualityFastLog(0xffffffffffffffffULL),
  101. _localSocket(localSocket),
  102. _incomingLinkQualitySlowLogPtr(0),
  103. _incomingLinkQualitySlowLogCounter(-64), // discard first fast log
  104. _incomingLinkQualityPreviousPacketCounter(0),
  105. _outgoingPacketCounter(0),
  106. _latency(0xffff),
  107. _addr(addr),
  108. _ipScope(addr.ipScope())
  109. {
  110. for(int i=0;i<(int)sizeof(_incomingLinkQualitySlowLog);++i)
  111. _incomingLinkQualitySlowLog[i] = ZT_PATH_LINK_QUALITY_MAX;
  112. }
  113. /**
  114. * Called when a packet is received from this remote path, regardless of content
  115. *
  116. * @param t Time of receive
  117. */
  118. inline void received(const uint64_t t) { _lastIn = t; }
  119. /**
  120. * Update link quality using a counter from an incoming packet (or packet head in fragmented case)
  121. *
  122. * @param counter Packet link quality counter (range 0 to 7, must not have other bits set)
  123. */
  124. inline void updateLinkQuality(const unsigned int counter)
  125. {
  126. const unsigned int prev = _incomingLinkQualityPreviousPacketCounter;
  127. _incomingLinkQualityPreviousPacketCounter = counter;
  128. const uint64_t fl = (_incomingLinkQualityFastLog = ((_incomingLinkQualityFastLog << 1) | (uint64_t)(prev == ((counter - 1) & 0x7))));
  129. if (++_incomingLinkQualitySlowLogCounter >= 64) {
  130. _incomingLinkQualitySlowLogCounter = 0;
  131. _incomingLinkQualitySlowLog[_incomingLinkQualitySlowLogPtr++ % sizeof(_incomingLinkQualitySlowLog)] = (uint8_t)Utils::countBits(fl);
  132. }
  133. }
  134. /**
  135. * @return Link quality from 0 (min) to 255 (max)
  136. */
  137. inline unsigned int linkQuality() const
  138. {
  139. unsigned long slsize = _incomingLinkQualitySlowLogPtr;
  140. if (slsize > (unsigned long)sizeof(_incomingLinkQualitySlowLog))
  141. slsize = (unsigned long)sizeof(_incomingLinkQualitySlowLog);
  142. else if (!slsize)
  143. return 255; // ZT_PATH_LINK_QUALITY_MAX
  144. unsigned long lq = 0;
  145. for(unsigned long i=0;i<slsize;++i)
  146. lq += (unsigned long)_incomingLinkQualitySlowLog[i] * 4;
  147. lq /= slsize;
  148. return (unsigned int)((lq >= 255) ? 255 : lq);
  149. }
  150. /**
  151. * Set time last trusted packet was received (done in Peer::received())
  152. */
  153. inline void trustedPacketReceived(const uint64_t t) { _lastTrustEstablishedPacketReceived = t; }
  154. /**
  155. * Send a packet via this path (last out time is also updated)
  156. *
  157. * @param RR Runtime environment
  158. * @param tPtr Thread pointer to be handed through to any callbacks called as a result of this call
  159. * @param data Packet data
  160. * @param len Packet length
  161. * @param now Current time
  162. * @return True if transport reported success
  163. */
  164. bool send(const RuntimeEnvironment *RR,void *tPtr,const void *data,unsigned int len,int64_t now);
  165. /**
  166. * Manually update last sent time
  167. *
  168. * @param t Time of send
  169. */
  170. inline void sent(const int64_t t) { _lastOut = t; }
  171. /**
  172. * Update path latency with a new measurement
  173. *
  174. * @param l Measured latency
  175. */
  176. inline void updateLatency(const unsigned int l)
  177. {
  178. unsigned int pl = _latency;
  179. if (pl < 0xffff)
  180. _latency = (pl + l) / 2;
  181. else _latency = l;
  182. }
  183. /**
  184. * @return Local socket as specified by external code
  185. */
  186. inline const int64_t localSocket() const { return _localSocket; }
  187. /**
  188. * @return Physical address
  189. */
  190. inline const InetAddress &address() const { return _addr; }
  191. /**
  192. * @return IP scope -- faster shortcut for address().ipScope()
  193. */
  194. inline InetAddress::IpScope ipScope() const { return _ipScope; }
  195. /**
  196. * @return True if path has received a trust established packet (e.g. common network membership) in the past ZT_TRUST_EXPIRATION ms
  197. */
  198. inline bool trustEstablished(const int64_t now) const { return ((now - _lastTrustEstablishedPacketReceived) < ZT_TRUST_EXPIRATION); }
  199. /**
  200. * @return Preference rank, higher == better
  201. */
  202. inline unsigned int preferenceRank() const
  203. {
  204. // This causes us to rank paths in order of IP scope rank (see InetAdddress.hpp) but
  205. // within each IP scope class to prefer IPv6 over IPv4.
  206. return ( ((unsigned int)_ipScope << 1) | (unsigned int)(_addr.ss_family == AF_INET6) );
  207. }
  208. /**
  209. * Check whether this address is valid for a ZeroTier path
  210. *
  211. * This checks the address type and scope against address types and scopes
  212. * that we currently support for ZeroTier communication.
  213. *
  214. * @param a Address to check
  215. * @return True if address is good for ZeroTier path use
  216. */
  217. static inline bool isAddressValidForPath(const InetAddress &a)
  218. {
  219. if ((a.ss_family == AF_INET)||(a.ss_family == AF_INET6)) {
  220. switch(a.ipScope()) {
  221. /* Note: we don't do link-local at the moment. Unfortunately these
  222. * cause several issues. The first is that they usually require a
  223. * device qualifier, which we don't handle yet and can't portably
  224. * push in PUSH_DIRECT_PATHS. The second is that some OSes assign
  225. * these very ephemerally or otherwise strangely. So we'll use
  226. * private, pseudo-private, shared (e.g. carrier grade NAT), or
  227. * global IP addresses. */
  228. case InetAddress::IP_SCOPE_PRIVATE:
  229. case InetAddress::IP_SCOPE_PSEUDOPRIVATE:
  230. case InetAddress::IP_SCOPE_SHARED:
  231. case InetAddress::IP_SCOPE_GLOBAL:
  232. if (a.ss_family == AF_INET6) {
  233. // TEMPORARY HACK: for now, we are going to blacklist he.net IPv6
  234. // tunnels due to very spotty performance and low MTU issues over
  235. // these IPv6 tunnel links.
  236. const uint8_t *ipd = reinterpret_cast<const uint8_t *>(reinterpret_cast<const struct sockaddr_in6 *>(&a)->sin6_addr.s6_addr);
  237. if ((ipd[0] == 0x20)&&(ipd[1] == 0x01)&&(ipd[2] == 0x04)&&(ipd[3] == 0x70))
  238. return false;
  239. }
  240. return true;
  241. default:
  242. return false;
  243. }
  244. }
  245. return false;
  246. }
  247. /**
  248. * @return Latency or 0xffff if unknown
  249. */
  250. inline unsigned int latency() const { return _latency; }
  251. /**
  252. * @return Path quality -- lower is better
  253. */
  254. inline int quality(const int64_t now) const
  255. {
  256. const int l = (int)_latency;
  257. const int age = (int)std::min((now - _lastIn),(int64_t)(ZT_PATH_HEARTBEAT_PERIOD * 10)); // set an upper sanity limit to avoid overflow
  258. return (((age < (ZT_PATH_HEARTBEAT_PERIOD + 5000)) ? l : (l + 0xffff + age)) * (int)((ZT_INETADDRESS_MAX_SCOPE - _ipScope) + 1));
  259. }
  260. /**
  261. * @return True if this path needs a heartbeat
  262. */
  263. inline bool needsHeartbeat(const int64_t now) const { return ((now - _lastOut) >= ZT_PATH_HEARTBEAT_PERIOD); }
  264. /**
  265. * @return Last time we sent something
  266. */
  267. inline int64_t lastOut() const { return _lastOut; }
  268. /**
  269. * @return Last time we received anything
  270. */
  271. inline int64_t lastIn() const { return _lastIn; }
  272. /**
  273. * @return Time last trust-established packet was received
  274. */
  275. inline int64_t lastTrustEstablishedPacketReceived() const { return _lastTrustEstablishedPacketReceived; }
  276. /**
  277. * Return and increment outgoing packet counter (used with Packet::armor())
  278. *
  279. * @return Next value that should be used for outgoing packet counter (only least significant 3 bits are used)
  280. */
  281. inline unsigned int nextOutgoingCounter() { return _outgoingPacketCounter++; }
  282. private:
  283. volatile int64_t _lastOut;
  284. volatile int64_t _lastIn;
  285. volatile int64_t _lastTrustEstablishedPacketReceived;
  286. volatile uint64_t _incomingLinkQualityFastLog;
  287. int64_t _localSocket;
  288. volatile unsigned long _incomingLinkQualitySlowLogPtr;
  289. volatile signed int _incomingLinkQualitySlowLogCounter;
  290. volatile unsigned int _incomingLinkQualityPreviousPacketCounter;
  291. volatile unsigned int _outgoingPacketCounter;
  292. volatile unsigned int _latency;
  293. InetAddress _addr;
  294. InetAddress::IpScope _ipScope; // memoize this since it's a computed value checked often
  295. volatile uint8_t _incomingLinkQualitySlowLog[32];
  296. AtomicCounter __refCount;
  297. };
  298. } // namespace ZeroTier
  299. #endif