Path.hpp 11 KB

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