Path.hpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408
  1. /*
  2. * Copyright (c)2013-2020 ZeroTier, Inc.
  3. *
  4. * Use of this software is governed by the Business Source License included
  5. * in the LICENSE.TXT file in the project's root directory.
  6. *
  7. * Change Date: 2026-01-01
  8. *
  9. * On the date above, in accordance with the Business Source License, use
  10. * of this software will be governed by version 2.0 of the Apache License.
  11. */
  12. /****/
  13. #ifndef ZT_PATH_HPP
  14. #define ZT_PATH_HPP
  15. #include <stdint.h>
  16. #include <string.h>
  17. #include <stdlib.h>
  18. #include <stdexcept>
  19. #include <algorithm>
  20. #include "Constants.hpp"
  21. #include "InetAddress.hpp"
  22. #include "SharedPtr.hpp"
  23. #include "AtomicCounter.hpp"
  24. #include "Utils.hpp"
  25. #include "Packet.hpp"
  26. #include "RingBuffer.hpp"
  27. /**
  28. * Maximum return value of preferenceRank()
  29. */
  30. #define ZT_PATH_MAX_PREFERENCE_RANK ((ZT_INETADDRESS_MAX_SCOPE << 1) | 1)
  31. namespace ZeroTier {
  32. class RuntimeEnvironment;
  33. /**
  34. * A path across the physical network
  35. */
  36. class Path
  37. {
  38. friend class SharedPtr<Path>;
  39. friend class Bond;
  40. public:
  41. /**
  42. * Efficient unique key for paths in a Hashtable
  43. */
  44. class HashKey
  45. {
  46. public:
  47. HashKey() {}
  48. HashKey(const int64_t l,const InetAddress &r)
  49. {
  50. if (r.ss_family == AF_INET) {
  51. _k[0] = (uint64_t)reinterpret_cast<const struct sockaddr_in *>(&r)->sin_addr.s_addr;
  52. _k[1] = (uint64_t)reinterpret_cast<const struct sockaddr_in *>(&r)->sin_port;
  53. _k[2] = (uint64_t)l;
  54. } else if (r.ss_family == AF_INET6) {
  55. memcpy(_k,reinterpret_cast<const struct sockaddr_in6 *>(&r)->sin6_addr.s6_addr,16);
  56. _k[2] = ((uint64_t)reinterpret_cast<const struct sockaddr_in6 *>(&r)->sin6_port << 32) ^ (uint64_t)l;
  57. } else {
  58. memcpy(_k,&r,std::min(sizeof(_k),sizeof(InetAddress)));
  59. _k[2] += (uint64_t)l;
  60. }
  61. }
  62. inline unsigned long hashCode() const { return (unsigned long)(_k[0] + _k[1] + _k[2]); }
  63. inline bool operator==(const HashKey &k) const { return ( (_k[0] == k._k[0]) && (_k[1] == k._k[1]) && (_k[2] == k._k[2]) ); }
  64. inline bool operator!=(const HashKey &k) const { return (!(*this == k)); }
  65. private:
  66. uint64_t _k[3];
  67. };
  68. Path() :
  69. _lastOut(0),
  70. _lastIn(0),
  71. _lastTrustEstablishedPacketReceived(0),
  72. _lastEchoRequestReceived(0),
  73. _localPort(0),
  74. _localSocket(-1),
  75. _latencyMean(0.0),
  76. _latencyVariance(0.0),
  77. _packetLossRatio(0.0),
  78. _packetErrorRatio(0.0),
  79. _assignedFlowCount(0),
  80. _valid(true),
  81. _eligible(false),
  82. _bonded(false),
  83. _mtu(0),
  84. _givenLinkSpeed(0),
  85. _relativeQuality(0),
  86. _latency(0xffff),
  87. _addr(),
  88. _ipScope(InetAddress::IP_SCOPE_NONE)
  89. {}
  90. Path(const int64_t localSocket,const InetAddress &addr) :
  91. _lastOut(0),
  92. _lastIn(0),
  93. _lastTrustEstablishedPacketReceived(0),
  94. _lastEchoRequestReceived(0),
  95. _localPort(0),
  96. _localSocket(localSocket),
  97. _latencyMean(0.0),
  98. _latencyVariance(0.0),
  99. _packetLossRatio(0.0),
  100. _packetErrorRatio(0.0),
  101. _assignedFlowCount(0),
  102. _valid(true),
  103. _eligible(false),
  104. _bonded(false),
  105. _mtu(0),
  106. _givenLinkSpeed(0),
  107. _relativeQuality(0),
  108. _latency(0xffff),
  109. _addr(addr),
  110. _ipScope(addr.ipScope())
  111. {}
  112. /**
  113. * Called when a packet is received from this remote path, regardless of content
  114. *
  115. * @param t Time of receive
  116. */
  117. inline void received(const uint64_t t)
  118. {
  119. _lastIn = t;
  120. }
  121. /**
  122. * Set time last trusted packet was received (done in Peer::received())
  123. */
  124. inline void trustedPacketReceived(const uint64_t t) { _lastTrustEstablishedPacketReceived = t; }
  125. /**
  126. * Send a packet via this path (last out time is also updated)
  127. *
  128. * @param RR Runtime environment
  129. * @param tPtr Thread pointer to be handed through to any callbacks called as a result of this call
  130. * @param data Packet data
  131. * @param len Packet length
  132. * @param now Current time
  133. * @return True if transport reported success
  134. */
  135. bool send(const RuntimeEnvironment *RR,void *tPtr,const void *data,unsigned int len,int64_t now);
  136. /**
  137. * Manually update last sent time
  138. *
  139. * @param t Time of send
  140. */
  141. inline void sent(const int64_t t) { _lastOut = t; }
  142. /**
  143. * Update path latency with a new measurement
  144. *
  145. * @param l Measured latency
  146. */
  147. inline void updateLatency(const unsigned int l, int64_t now)
  148. {
  149. unsigned int pl = _latency;
  150. if (pl < 0xffff) {
  151. _latency = (pl + l) / 2;
  152. } else {
  153. _latency = l;
  154. }
  155. }
  156. /**
  157. * @return Local socket as specified by external code
  158. */
  159. inline int64_t localSocket() const { return _localSocket; }
  160. /**
  161. * @return Local port corresponding to the localSocket
  162. */
  163. inline int64_t localPort() const { return _localPort; }
  164. /**
  165. * @return Physical address
  166. */
  167. inline const InetAddress &address() const { return _addr; }
  168. /**
  169. * @return IP scope -- faster shortcut for address().ipScope()
  170. */
  171. inline InetAddress::IpScope ipScope() const { return _ipScope; }
  172. /**
  173. * @return True if path has received a trust established packet (e.g. common network membership) in the past ZT_TRUST_EXPIRATION ms
  174. */
  175. inline bool trustEstablished(const int64_t now) const { return ((now - _lastTrustEstablishedPacketReceived) < ZT_TRUST_EXPIRATION); }
  176. /**
  177. * @return Preference rank, higher == better
  178. */
  179. inline unsigned int preferenceRank() const
  180. {
  181. // This causes us to rank paths in order of IP scope rank (see InetAddress.hpp) but
  182. // within each IP scope class to prefer IPv6 over IPv4.
  183. return ( ((unsigned int)_ipScope << 1) | (unsigned int)(_addr.ss_family == AF_INET6) );
  184. }
  185. /**
  186. * Check whether this address is valid for a ZeroTier path
  187. *
  188. * This checks the address type and scope against address types and scopes
  189. * that we currently support for ZeroTier communication.
  190. *
  191. * @param a Address to check
  192. * @return True if address is good for ZeroTier path use
  193. */
  194. static inline bool isAddressValidForPath(const InetAddress &a)
  195. {
  196. if ((a.ss_family == AF_INET)||(a.ss_family == AF_INET6)) {
  197. switch(a.ipScope()) {
  198. /* Note: we don't do link-local at the moment. Unfortunately these
  199. * cause several issues. The first is that they usually require a
  200. * device qualifier, which we don't handle yet and can't portably
  201. * push in PUSH_DIRECT_PATHS. The second is that some OSes assign
  202. * these very ephemerally or otherwise strangely. So we'll use
  203. * private, pseudo-private, shared (e.g. carrier grade NAT), or
  204. * global IP addresses. */
  205. case InetAddress::IP_SCOPE_PRIVATE:
  206. case InetAddress::IP_SCOPE_PSEUDOPRIVATE:
  207. case InetAddress::IP_SCOPE_SHARED:
  208. case InetAddress::IP_SCOPE_GLOBAL:
  209. if (a.ss_family == AF_INET6) {
  210. // TEMPORARY HACK: for now, we are going to blacklist he.net IPv6
  211. // tunnels due to very spotty performance and low MTU issues over
  212. // these IPv6 tunnel links.
  213. const uint8_t *ipd = reinterpret_cast<const uint8_t *>(reinterpret_cast<const struct sockaddr_in6 *>(&a)->sin6_addr.s6_addr);
  214. if ((ipd[0] == 0x20)&&(ipd[1] == 0x01)&&(ipd[2] == 0x04)&&(ipd[3] == 0x70)) {
  215. return false;
  216. }
  217. }
  218. return true;
  219. default:
  220. return false;
  221. }
  222. }
  223. return false;
  224. }
  225. /**
  226. * @return Latency or 0xffff if unknown
  227. */
  228. inline unsigned int latency() const { return _latency; }
  229. /**
  230. * @return Path quality -- lower is better
  231. */
  232. inline long quality(const int64_t now) const
  233. {
  234. const int l = (long)_latency;
  235. const int age = (long)std::min((now - _lastIn),(int64_t)(ZT_PATH_HEARTBEAT_PERIOD * 10)); // set an upper sanity limit to avoid overflow
  236. return (((age < (ZT_PATH_HEARTBEAT_PERIOD + 5000)) ? l : (l + 0xffff + age)) * (long)((ZT_INETADDRESS_MAX_SCOPE - _ipScope) + 1));
  237. }
  238. /**
  239. * @return True if this path is alive (receiving heartbeats)
  240. */
  241. inline bool alive(const int64_t now) const {
  242. return (now - _lastIn) < (ZT_PATH_HEARTBEAT_PERIOD + 5000);
  243. }
  244. /**
  245. * @return True if this path needs a heartbeat
  246. */
  247. inline bool needsHeartbeat(const int64_t now) const { return ((now - _lastOut) >= ZT_PATH_HEARTBEAT_PERIOD); }
  248. /**
  249. * @return Last time we sent something
  250. */
  251. inline int64_t lastOut() const { return _lastOut; }
  252. /**
  253. * @return Last time we received anything
  254. */
  255. inline int64_t lastIn() const { return _lastIn; }
  256. /**
  257. * @return the age of the path in terms of receiving packets
  258. */
  259. inline int64_t age(int64_t now) { return (now - _lastIn); }
  260. /**
  261. * @return Time last trust-established packet was received
  262. */
  263. inline int64_t lastTrustEstablishedPacketReceived() const { return _lastTrustEstablishedPacketReceived; }
  264. /**
  265. * Rate limit gate for inbound ECHO requests
  266. */
  267. inline bool rateGateEchoRequest(const int64_t now)
  268. {
  269. if ((now - _lastEchoRequestReceived) >= (ZT_PEER_GENERAL_RATE_LIMIT / 6)) {
  270. _lastEchoRequestReceived = now;
  271. return true;
  272. }
  273. return false;
  274. }
  275. /**
  276. * @return Mean latency as reported by the bonding layer
  277. */
  278. inline float latencyMean() const { return _latencyMean; }
  279. /**
  280. * @return Latency variance as reported by the bonding layer
  281. */
  282. inline float latencyVariance() const { return _latencyVariance; }
  283. /**
  284. * @return Packet Loss Ratio as reported by the bonding layer
  285. */
  286. inline float packetLossRatio() const { return _packetLossRatio; }
  287. /**
  288. * @return Packet Error Ratio as reported by the bonding layer
  289. */
  290. inline float packetErrorRatio() const { return _packetErrorRatio; }
  291. /**
  292. * @return Number of flows assigned to this path
  293. */
  294. inline unsigned int assignedFlowCount() const { return _assignedFlowCount; }
  295. /**
  296. * @return Whether this path is valid as reported by the bonding layer. The bonding layer
  297. * actually checks with Phy to see if the interface is still up
  298. */
  299. inline bool valid() const { return _valid; }
  300. /**
  301. * @return Whether this path is eligible for use in a bond as reported by the bonding layer
  302. */
  303. inline bool eligible() const { return _eligible; }
  304. /**
  305. * @return Whether this path is bonded as reported by the bonding layer
  306. */
  307. inline bool bonded() const { return _bonded; }
  308. /**
  309. * @return Whether the user-specified MTU for this path (determined by MTU for parent link)
  310. */
  311. inline uint16_t mtu() const { return _mtu; }
  312. /**
  313. * @return Given link capacity as reported by the bonding layer
  314. */
  315. inline uint32_t givenLinkSpeed() const { return _givenLinkSpeed; }
  316. /**
  317. * @return Path's quality as reported by the bonding layer
  318. */
  319. inline float relativeQuality() const { return _relativeQuality; }
  320. /**
  321. * @return Physical interface name that this path lives on
  322. */
  323. char *ifname() {
  324. return _ifname;
  325. }
  326. private:
  327. char _ifname[ZT_MAX_PHYSIFNAME] = { };
  328. volatile int64_t _lastOut;
  329. volatile int64_t _lastIn;
  330. volatile int64_t _lastTrustEstablishedPacketReceived;
  331. int64_t _lastEchoRequestReceived;
  332. uint16_t _localPort;
  333. int64_t _localSocket;
  334. volatile float _latencyMean;
  335. volatile float _latencyVariance;
  336. volatile float _packetLossRatio;
  337. volatile float _packetErrorRatio;
  338. volatile uint16_t _assignedFlowCount;
  339. volatile bool _valid;
  340. volatile bool _eligible;
  341. volatile bool _bonded;
  342. volatile uint16_t _mtu;
  343. volatile uint32_t _givenLinkSpeed;
  344. volatile float _relativeQuality;
  345. volatile unsigned int _latency;
  346. InetAddress _addr;
  347. InetAddress::IpScope _ipScope; // memoize this since it's a computed value checked often
  348. AtomicCounter __refCount;
  349. };
  350. } // namespace ZeroTier
  351. #endif