Path.hpp 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323
  1. /*
  2. * ZeroTier One - Network Virtualization Everywhere
  3. * Copyright (C) 2011-2016 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. #ifndef ZT_PATH_HPP
  19. #define ZT_PATH_HPP
  20. #include <stdint.h>
  21. #include <string.h>
  22. #include <stdexcept>
  23. #include <algorithm>
  24. #include "Constants.hpp"
  25. #include "InetAddress.hpp"
  26. // Note: if you change these flags check the logic below. Some of it depends
  27. // on these bits being what they are.
  28. /**
  29. * Flag indicating that this path is suboptimal
  30. *
  31. * Clusters set this flag on remote paths if GeoIP or other routing decisions
  32. * indicate that a peer should be handed off to another cluster member.
  33. */
  34. #define ZT_PATH_FLAG_CLUSTER_SUBOPTIMAL 0x0001
  35. /**
  36. * Flag indicating that this path is optimal
  37. *
  38. * Peers set this flag on paths that are pushed by a cluster and indicated as
  39. * optimal. A second flag is needed since we want to prioritize cluster optimal
  40. * paths and de-prioritize sub-optimal paths and for new paths we don't know
  41. * which one they are. So we want a trinary state: optimal, suboptimal, unknown.
  42. */
  43. #define ZT_PATH_FLAG_CLUSTER_OPTIMAL 0x0002
  44. /**
  45. * Maximum return value of preferenceRank()
  46. */
  47. #define ZT_PATH_MAX_PREFERENCE_RANK ((ZT_INETADDRESS_MAX_SCOPE << 1) | 1)
  48. namespace ZeroTier {
  49. class RuntimeEnvironment;
  50. /**
  51. * Base class for paths
  52. *
  53. * The base Path class is an immutable value.
  54. */
  55. class Path
  56. {
  57. public:
  58. Path() :
  59. _lastSend(0),
  60. _lastPing(0),
  61. _lastKeepalive(0),
  62. _lastReceived(0),
  63. _addr(),
  64. _localAddress(),
  65. _flags(0),
  66. _ipScope(InetAddress::IP_SCOPE_NONE)
  67. {
  68. }
  69. Path(const InetAddress &localAddress,const InetAddress &addr) :
  70. _lastSend(0),
  71. _lastPing(0),
  72. _lastKeepalive(0),
  73. _lastReceived(0),
  74. _addr(addr),
  75. _localAddress(localAddress),
  76. _flags(0),
  77. _ipScope(addr.ipScope())
  78. {
  79. }
  80. inline Path &operator=(const Path &p)
  81. {
  82. if (this != &p)
  83. memcpy(this,&p,sizeof(Path));
  84. return *this;
  85. }
  86. /**
  87. * Called when a packet is sent to this remote path
  88. *
  89. * This is called automatically by Path::send().
  90. *
  91. * @param t Time of send
  92. */
  93. inline void sent(uint64_t t) { _lastSend = t; }
  94. /**
  95. * Called when we've sent a ping or echo
  96. *
  97. * @param t Time of send
  98. */
  99. inline void pinged(uint64_t t) { _lastPing = t; }
  100. /**
  101. * Called when we send a NAT keepalive
  102. *
  103. * @param t Time of send
  104. */
  105. inline void sentKeepalive(uint64_t t) { _lastKeepalive = t; }
  106. /**
  107. * Called when a packet is received from this remote path
  108. *
  109. * @param t Time of receive
  110. */
  111. inline void received(uint64_t t)
  112. {
  113. _lastReceived = t;
  114. _probation = 0;
  115. }
  116. /**
  117. * @param now Current time
  118. * @return True if this path appears active
  119. */
  120. inline bool active(uint64_t now) const
  121. {
  122. return ( ((now - _lastReceived) < ZT_PATH_ACTIVITY_TIMEOUT) && (_probation < ZT_PEER_DEAD_PATH_DETECTION_MAX_PROBATION) );
  123. }
  124. /**
  125. * Send a packet via this path
  126. *
  127. * @param RR Runtime environment
  128. * @param data Packet data
  129. * @param len Packet length
  130. * @param now Current time
  131. * @return True if transport reported success
  132. */
  133. bool send(const RuntimeEnvironment *RR,const void *data,unsigned int len,uint64_t now);
  134. /**
  135. * @return Address of local side of this path or NULL if unspecified
  136. */
  137. inline const InetAddress &localAddress() const throw() { return _localAddress; }
  138. /**
  139. * @return Time of last send to this path
  140. */
  141. inline uint64_t lastSend() const throw() { return _lastSend; }
  142. /**
  143. * @return Time we last pinged or dead path checked this link
  144. */
  145. inline uint64_t lastPing() const throw() { return _lastPing; }
  146. /**
  147. * @return Time of last keepalive
  148. */
  149. inline uint64_t lastKeepalive() const throw() { return _lastKeepalive; }
  150. /**
  151. * @return Time of last receive from this path
  152. */
  153. inline uint64_t lastReceived() const throw() { return _lastReceived; }
  154. /**
  155. * @return Physical address
  156. */
  157. inline const InetAddress &address() const throw() { return _addr; }
  158. /**
  159. * @return IP scope -- faster shortcut for address().ipScope()
  160. */
  161. inline InetAddress::IpScope ipScope() const throw() { return _ipScope; }
  162. /**
  163. * @param f Valuve of ZT_PATH_FLAG_CLUSTER_SUBOPTIMAL and inverse of ZT_PATH_FLAG_CLUSTER_OPTIMAL (both are changed)
  164. */
  165. inline void setClusterSuboptimal(bool f)
  166. {
  167. if (f) {
  168. _flags = (_flags | ZT_PATH_FLAG_CLUSTER_SUBOPTIMAL) & ~ZT_PATH_FLAG_CLUSTER_OPTIMAL;
  169. } else {
  170. _flags = (_flags | ZT_PATH_FLAG_CLUSTER_OPTIMAL) & ~ZT_PATH_FLAG_CLUSTER_SUBOPTIMAL;
  171. }
  172. }
  173. /**
  174. * @return True if ZT_PATH_FLAG_CLUSTER_SUBOPTIMAL is set
  175. */
  176. inline bool isClusterSuboptimal() const { return ((_flags & ZT_PATH_FLAG_CLUSTER_SUBOPTIMAL) != 0); }
  177. /**
  178. * @return True if ZT_PATH_FLAG_CLUSTER_OPTIMAL is set
  179. */
  180. inline bool isClusterOptimal() const { return ((_flags & ZT_PATH_FLAG_CLUSTER_OPTIMAL) != 0); }
  181. /**
  182. * @return Preference rank, higher == better (will be less than 255)
  183. */
  184. inline unsigned int preferenceRank() const throw()
  185. {
  186. /* First, since the scope enum values in InetAddress.hpp are in order of
  187. * use preference rank, we take that. Then we multiple by two, yielding
  188. * a sequence like 0, 2, 4, 6, etc. Then if it's IPv6 we add one. This
  189. * makes IPv6 addresses of a given scope outrank IPv4 addresses of the
  190. * same scope -- e.g. 1 outranks 0. This makes us prefer IPv6, but not
  191. * if the address scope/class is of a fundamentally lower rank. */
  192. return ( ((unsigned int)_ipScope << 1) | (unsigned int)(_addr.ss_family == AF_INET6) );
  193. }
  194. /**
  195. * @return This path's overall quality score (higher is better)
  196. */
  197. inline uint64_t score() const throw()
  198. {
  199. // This is a little bit convoluted because we try to be branch-free, using multiplication instead of branches for boolean flags
  200. // Start with the last time this path was active, and add a fudge factor to prevent integer underflow if _lastReceived is 0
  201. uint64_t score = _lastReceived + (ZT_PEER_DIRECT_PING_DELAY * (ZT_PEER_DEAD_PATH_DETECTION_MAX_PROBATION + 1));
  202. // Increase score based on path preference rank, which is based on IP scope and address family
  203. score += preferenceRank() * (ZT_PEER_DIRECT_PING_DELAY / ZT_PATH_MAX_PREFERENCE_RANK);
  204. // Increase score if this is known to be an optimal path to a cluster
  205. score += (uint64_t)(_flags & ZT_PATH_FLAG_CLUSTER_OPTIMAL) * (ZT_PEER_DIRECT_PING_DELAY / 2); // /2 because CLUSTER_OPTIMAL is flag 0x0002
  206. // Decrease score if this is known to be a sub-optimal path to a cluster
  207. score -= (uint64_t)(_flags & ZT_PATH_FLAG_CLUSTER_SUBOPTIMAL) * ZT_PEER_DIRECT_PING_DELAY;
  208. // Penalize for missed ECHO tests in dead path detection
  209. score -= (uint64_t)((ZT_PEER_DIRECT_PING_DELAY / 2) * _probation);
  210. return score;
  211. }
  212. /**
  213. * @return True if address is non-NULL
  214. */
  215. inline operator bool() const throw() { return (_addr); }
  216. /**
  217. * Check whether this address is valid for a ZeroTier path
  218. *
  219. * This checks the address type and scope against address types and scopes
  220. * that we currently support for ZeroTier communication.
  221. *
  222. * @param a Address to check
  223. * @return True if address is good for ZeroTier path use
  224. */
  225. static inline bool isAddressValidForPath(const InetAddress &a)
  226. throw()
  227. {
  228. if ((a.ss_family == AF_INET)||(a.ss_family == AF_INET6)) {
  229. switch(a.ipScope()) {
  230. /* Note: we don't do link-local at the moment. Unfortunately these
  231. * cause several issues. The first is that they usually require a
  232. * device qualifier, which we don't handle yet and can't portably
  233. * push in PUSH_DIRECT_PATHS. The second is that some OSes assign
  234. * these very ephemerally or otherwise strangely. So we'll use
  235. * private, pseudo-private, shared (e.g. carrier grade NAT), or
  236. * global IP addresses. */
  237. case InetAddress::IP_SCOPE_PRIVATE:
  238. case InetAddress::IP_SCOPE_PSEUDOPRIVATE:
  239. case InetAddress::IP_SCOPE_SHARED:
  240. case InetAddress::IP_SCOPE_GLOBAL:
  241. if (a.ss_family == AF_INET6) {
  242. // TEMPORARY HACK: for now, we are going to blacklist he.net IPv6
  243. // tunnels due to very spotty performance and low MTU issues over
  244. // these IPv6 tunnel links.
  245. const uint8_t *ipd = reinterpret_cast<const uint8_t *>(reinterpret_cast<const struct sockaddr_in6 *>(&a)->sin6_addr.s6_addr);
  246. if ((ipd[0] == 0x20)&&(ipd[1] == 0x01)&&(ipd[2] == 0x04)&&(ipd[3] == 0x70))
  247. return false;
  248. }
  249. return true;
  250. default:
  251. return false;
  252. }
  253. }
  254. return false;
  255. }
  256. /**
  257. * @return Current path probation count (for dead path detect)
  258. */
  259. inline unsigned int probation() const { return _probation; }
  260. /**
  261. * Increase this path's probation violation count (for dead path detect)
  262. */
  263. inline void increaseProbation() { ++_probation; }
  264. inline bool operator==(const Path &p) const { return ((p._addr == _addr)&&(p._localAddress == _localAddress)); }
  265. inline bool operator!=(const Path &p) const { return ((p._addr != _addr)||(p._localAddress != _localAddress)); }
  266. private:
  267. uint64_t _lastSend;
  268. uint64_t _lastPing;
  269. uint64_t _lastKeepalive;
  270. uint64_t _lastReceived;
  271. InetAddress _addr;
  272. InetAddress _localAddress;
  273. unsigned int _flags;
  274. unsigned int _probation;
  275. InetAddress::IpScope _ipScope; // memoize this since it's a computed value checked often
  276. };
  277. } // namespace ZeroTier
  278. #endif