Path.hpp 8.3 KB

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