Path.hpp 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285
  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: 2025-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. _localSocket(-1),
  73. _latency(0xffff),
  74. _addr(),
  75. _ipScope(InetAddress::IP_SCOPE_NONE)
  76. {}
  77. Path(const int64_t localSocket,const InetAddress &addr) :
  78. _lastOut(0),
  79. _lastIn(0),
  80. _lastTrustEstablishedPacketReceived(0),
  81. _localSocket(localSocket),
  82. _latency(0xffff),
  83. _addr(addr),
  84. _ipScope(addr.ipScope())
  85. {}
  86. /**
  87. * Called when a packet is received from this remote path, regardless of content
  88. *
  89. * @param t Time of receive
  90. */
  91. inline void received(const uint64_t t)
  92. {
  93. _lastIn = t;
  94. }
  95. /**
  96. * Set time last trusted packet was received (done in Peer::received())
  97. */
  98. inline void trustedPacketReceived(const uint64_t t) { _lastTrustEstablishedPacketReceived = t; }
  99. /**
  100. * Send a packet via this path (last out time is also updated)
  101. *
  102. * @param RR Runtime environment
  103. * @param tPtr Thread pointer to be handed through to any callbacks called as a result of this call
  104. * @param data Packet data
  105. * @param len Packet length
  106. * @param now Current time
  107. * @return True if transport reported success
  108. */
  109. bool send(const RuntimeEnvironment *RR,void *tPtr,const void *data,unsigned int len,int64_t now);
  110. /**
  111. * Manually update last sent time
  112. *
  113. * @param t Time of send
  114. */
  115. inline void sent(const int64_t t) { _lastOut = t; }
  116. /**
  117. * Update path latency with a new measurement
  118. *
  119. * @param l Measured latency
  120. */
  121. inline void updateLatency(const unsigned int l, int64_t now)
  122. {
  123. unsigned int pl = _latency;
  124. if (pl < 0xffff) {
  125. _latency = (pl + l) / 2;
  126. }
  127. else {
  128. _latency = l;
  129. }
  130. }
  131. /**
  132. * @return Local socket as specified by external code
  133. */
  134. inline int64_t localSocket() const { return _localSocket; }
  135. /**
  136. * @return Physical address
  137. */
  138. inline const InetAddress &address() const { return _addr; }
  139. /**
  140. * @return IP scope -- faster shortcut for address().ipScope()
  141. */
  142. inline InetAddress::IpScope ipScope() const { return _ipScope; }
  143. /**
  144. * @return True if path has received a trust established packet (e.g. common network membership) in the past ZT_TRUST_EXPIRATION ms
  145. */
  146. inline bool trustEstablished(const int64_t now) const { return ((now - _lastTrustEstablishedPacketReceived) < ZT_TRUST_EXPIRATION); }
  147. /**
  148. * @return Preference rank, higher == better
  149. */
  150. inline unsigned int preferenceRank() const
  151. {
  152. // This causes us to rank paths in order of IP scope rank (see InetAdddress.hpp) but
  153. // within each IP scope class to prefer IPv6 over IPv4.
  154. return ( ((unsigned int)_ipScope << 1) | (unsigned int)(_addr.ss_family == AF_INET6) );
  155. }
  156. /**
  157. * Check whether this address is valid for a ZeroTier path
  158. *
  159. * This checks the address type and scope against address types and scopes
  160. * that we currently support for ZeroTier communication.
  161. *
  162. * @param a Address to check
  163. * @return True if address is good for ZeroTier path use
  164. */
  165. static inline bool isAddressValidForPath(const InetAddress &a)
  166. {
  167. if ((a.ss_family == AF_INET)||(a.ss_family == AF_INET6)) {
  168. switch(a.ipScope()) {
  169. /* Note: we don't do link-local at the moment. Unfortunately these
  170. * cause several issues. The first is that they usually require a
  171. * device qualifier, which we don't handle yet and can't portably
  172. * push in PUSH_DIRECT_PATHS. The second is that some OSes assign
  173. * these very ephemerally or otherwise strangely. So we'll use
  174. * private, pseudo-private, shared (e.g. carrier grade NAT), or
  175. * global IP addresses. */
  176. case InetAddress::IP_SCOPE_PRIVATE:
  177. case InetAddress::IP_SCOPE_PSEUDOPRIVATE:
  178. case InetAddress::IP_SCOPE_SHARED:
  179. case InetAddress::IP_SCOPE_GLOBAL:
  180. if (a.ss_family == AF_INET6) {
  181. // TEMPORARY HACK: for now, we are going to blacklist he.net IPv6
  182. // tunnels due to very spotty performance and low MTU issues over
  183. // these IPv6 tunnel links.
  184. const uint8_t *ipd = reinterpret_cast<const uint8_t *>(reinterpret_cast<const struct sockaddr_in6 *>(&a)->sin6_addr.s6_addr);
  185. if ((ipd[0] == 0x20)&&(ipd[1] == 0x01)&&(ipd[2] == 0x04)&&(ipd[3] == 0x70))
  186. return false;
  187. }
  188. return true;
  189. default:
  190. return false;
  191. }
  192. }
  193. return false;
  194. }
  195. /**
  196. * @return Latency or 0xffff if unknown
  197. */
  198. inline unsigned int latency() const { return _latency; }
  199. /**
  200. * @return Path quality -- lower is better
  201. */
  202. inline long quality(const int64_t now) const
  203. {
  204. const int l = (long)_latency;
  205. const int age = (long)std::min((now - _lastIn),(int64_t)(ZT_PATH_HEARTBEAT_PERIOD * 10)); // set an upper sanity limit to avoid overflow
  206. return (((age < (ZT_PATH_HEARTBEAT_PERIOD + 5000)) ? l : (l + 0xffff + age)) * (long)((ZT_INETADDRESS_MAX_SCOPE - _ipScope) + 1));
  207. }
  208. /**
  209. * @return True if this path is alive (receiving heartbeats)
  210. */
  211. inline bool alive(const int64_t now) const {
  212. return (now - _lastIn) < (ZT_PATH_HEARTBEAT_PERIOD + 5000);
  213. }
  214. /**
  215. * @return True if this path needs a heartbeat
  216. */
  217. inline bool needsHeartbeat(const int64_t now) const { return ((now - _lastOut) >= ZT_PATH_HEARTBEAT_PERIOD); }
  218. /**
  219. * @return Last time we sent something
  220. */
  221. inline int64_t lastOut() const { return _lastOut; }
  222. /**
  223. * @return Last time we received anything
  224. */
  225. inline int64_t lastIn() const { return _lastIn; }
  226. /**
  227. * @return the age of the path in terms of receiving packets
  228. */
  229. inline int64_t age(int64_t now) { return (now - _lastIn); }
  230. /**
  231. * @return Time last trust-established packet was received
  232. */
  233. inline int64_t lastTrustEstablishedPacketReceived() const { return _lastTrustEstablishedPacketReceived; }
  234. void *_bondingMetricPtr;
  235. private:
  236. volatile int64_t _lastOut;
  237. volatile int64_t _lastIn;
  238. volatile int64_t _lastTrustEstablishedPacketReceived;
  239. int64_t _localSocket;
  240. volatile unsigned int _latency;
  241. InetAddress _addr;
  242. InetAddress::IpScope _ipScope; // memoize this since it's a computed value checked often
  243. AtomicCounter __refCount;
  244. };
  245. } // namespace ZeroTier
  246. #endif