Path.hpp 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326
  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. /**
  27. * Flag indicating that this path is suboptimal
  28. *
  29. * This is used in cluster mode to indicate that the peer has been directed
  30. * to a better path. This path can continue to be used but shouldn't be kept
  31. * or advertised to other cluster members. Not used if clustering is not
  32. * built and enabled.
  33. */
  34. #define ZT_PATH_FLAG_CLUSTER_SUBOPTIMAL 0x0001
  35. /**
  36. * Maximum return value of preferenceRank()
  37. */
  38. #define ZT_PATH_MAX_PREFERENCE_RANK ((ZT_INETADDRESS_MAX_SCOPE << 1) | 1)
  39. namespace ZeroTier {
  40. class RuntimeEnvironment;
  41. /**
  42. * Base class for paths
  43. *
  44. * The base Path class is an immutable value.
  45. */
  46. class Path
  47. {
  48. public:
  49. Path() :
  50. _lastSend(0),
  51. _lastPing(0),
  52. _lastKeepalive(0),
  53. _lastReceived(0),
  54. _addr(),
  55. _localAddress(),
  56. _flags(0),
  57. _ipScope(InetAddress::IP_SCOPE_NONE)
  58. {
  59. }
  60. Path(const InetAddress &localAddress,const InetAddress &addr) :
  61. _lastSend(0),
  62. _lastPing(0),
  63. _lastKeepalive(0),
  64. _lastReceived(0),
  65. _addr(addr),
  66. _localAddress(localAddress),
  67. _flags(0),
  68. _ipScope(addr.ipScope())
  69. {
  70. }
  71. inline Path &operator=(const Path &p)
  72. {
  73. if (this != &p)
  74. memcpy(this,&p,sizeof(Path));
  75. return *this;
  76. }
  77. /**
  78. * Called when a packet is sent to this remote path
  79. *
  80. * This is called automatically by Path::send().
  81. *
  82. * @param t Time of send
  83. */
  84. inline void sent(uint64_t t) { _lastSend = t; }
  85. /**
  86. * Called when we've sent a ping or echo
  87. *
  88. * @param t Time of send
  89. */
  90. inline void pinged(uint64_t t) { _lastPing = t; }
  91. /**
  92. * Called when we send a NAT keepalive
  93. *
  94. * @param t Time of send
  95. */
  96. inline void sentKeepalive(uint64_t t) { _lastKeepalive = t; }
  97. /**
  98. * Called when a packet is received from this remote path
  99. *
  100. * @param t Time of receive
  101. */
  102. inline void received(uint64_t t)
  103. {
  104. _lastReceived = t;
  105. _probation = 0;
  106. }
  107. /**
  108. * @param now Current time
  109. * @return True if this path appears active
  110. */
  111. inline bool active(uint64_t now) const
  112. throw()
  113. {
  114. return (((now - _lastReceived) < ZT_PEER_ACTIVITY_TIMEOUT)&&(_probation < ZT_PEER_DEAD_PATH_DETECTION_MAX_PROBATION));
  115. }
  116. /**
  117. * Send a packet via this path
  118. *
  119. * @param RR Runtime environment
  120. * @param data Packet data
  121. * @param len Packet length
  122. * @param now Current time
  123. * @return True if transport reported success
  124. */
  125. bool send(const RuntimeEnvironment *RR,const void *data,unsigned int len,uint64_t now);
  126. /**
  127. * @return Address of local side of this path or NULL if unspecified
  128. */
  129. inline const InetAddress &localAddress() const throw() { return _localAddress; }
  130. /**
  131. * @return Time of last send to this path
  132. */
  133. inline uint64_t lastSend() const throw() { return _lastSend; }
  134. /**
  135. * @return Time we last pinged or dead path checked this link
  136. */
  137. inline uint64_t lastPing() const throw() { return _lastPing; }
  138. /**
  139. * @return Time of last keepalive
  140. */
  141. inline uint64_t lastKeepalive() const throw() { return _lastKeepalive; }
  142. /**
  143. * @return Time of last receive from this path
  144. */
  145. inline uint64_t lastReceived() const throw() { return _lastReceived; }
  146. /**
  147. * @return Physical address
  148. */
  149. inline const InetAddress &address() const throw() { return _addr; }
  150. /**
  151. * @return IP scope -- faster shortcut for address().ipScope()
  152. */
  153. inline InetAddress::IpScope ipScope() const throw() { return _ipScope; }
  154. /**
  155. * @return Preference rank, higher == better (will be less than 255)
  156. */
  157. inline unsigned int preferenceRank() const throw()
  158. {
  159. // First, since the scope enum values in InetAddress.hpp are in order of
  160. // use preference rank, we take that. Then we multiple by two, yielding
  161. // a sequence like 0, 2, 4, 6, etc. Then if it's IPv6 we add one. This
  162. // makes IPv6 addresses of a given scope outrank IPv4 addresses of the
  163. // same scope -- e.g. 1 outranks 0. This makes us prefer IPv6, but not
  164. // if the address scope/class is of a fundamentally lower rank.
  165. return ( ((unsigned int)_ipScope << 1) | (unsigned int)(_addr.ss_family == AF_INET6) );
  166. }
  167. /**
  168. * @return This path's overall score (higher == better)
  169. */
  170. inline uint64_t score() const throw()
  171. {
  172. /* We compute the score based on the "freshness" of the path (when we last
  173. * received something) scaled/corrected by the preference rank within the
  174. * ping keepalive window. That way higher ranking paths are preferred but
  175. * not to the point of overriding timeouts and choosing potentially dead
  176. * paths. */
  177. return (_lastReceived + (preferenceRank() * (ZT_PEER_DIRECT_PING_DELAY / ZT_PATH_MAX_PREFERENCE_RANK)));
  178. }
  179. /**
  180. * @return True if path is considered reliable (no NAT keepalives etc. are needed)
  181. */
  182. inline bool reliable() const throw()
  183. {
  184. if (_addr.ss_family == AF_INET)
  185. return ((_ipScope != InetAddress::IP_SCOPE_GLOBAL)&&(_ipScope != InetAddress::IP_SCOPE_PSEUDOPRIVATE));
  186. return true;
  187. }
  188. /**
  189. * @return True if address is non-NULL
  190. */
  191. inline operator bool() const throw() { return (_addr); }
  192. /**
  193. * Check whether this address is valid for a ZeroTier path
  194. *
  195. * This checks the address type and scope against address types and scopes
  196. * that we currently support for ZeroTier communication.
  197. *
  198. * @param a Address to check
  199. * @return True if address is good for ZeroTier path use
  200. */
  201. static inline bool isAddressValidForPath(const InetAddress &a)
  202. throw()
  203. {
  204. if ((a.ss_family == AF_INET)||(a.ss_family == AF_INET6)) {
  205. switch(a.ipScope()) {
  206. /* Note: we don't do link-local at the moment. Unfortunately these
  207. * cause several issues. The first is that they usually require a
  208. * device qualifier, which we don't handle yet and can't portably
  209. * push in PUSH_DIRECT_PATHS. The second is that some OSes assign
  210. * these very ephemerally or otherwise strangely. So we'll use
  211. * private, pseudo-private, shared (e.g. carrier grade NAT), or
  212. * global IP addresses. */
  213. case InetAddress::IP_SCOPE_PRIVATE:
  214. case InetAddress::IP_SCOPE_PSEUDOPRIVATE:
  215. case InetAddress::IP_SCOPE_SHARED:
  216. case InetAddress::IP_SCOPE_GLOBAL:
  217. return true;
  218. default:
  219. return false;
  220. }
  221. }
  222. return false;
  223. }
  224. #ifdef ZT_ENABLE_CLUSTER
  225. /**
  226. * @param f New value of ZT_PATH_FLAG_CLUSTER_SUBOPTIMAL
  227. */
  228. inline void setClusterSuboptimal(bool f) { _flags = ((f) ? (_flags | ZT_PATH_FLAG_CLUSTER_SUBOPTIMAL) : (_flags & (~ZT_PATH_FLAG_CLUSTER_SUBOPTIMAL))); }
  229. /**
  230. * @return True if ZT_PATH_FLAG_CLUSTER_SUBOPTIMAL is set
  231. */
  232. inline bool isClusterSuboptimal() const { return ((_flags & ZT_PATH_FLAG_CLUSTER_SUBOPTIMAL) != 0); }
  233. #endif
  234. /**
  235. * @return Current path probation count (for dead path detect)
  236. */
  237. inline unsigned int probation() const { return _probation; }
  238. /**
  239. * Increase this path's probation violation count (for dead path detect)
  240. */
  241. inline void increaseProbation() { ++_probation; }
  242. template<unsigned int C>
  243. inline void serialize(Buffer<C> &b) const
  244. {
  245. b.append((uint8_t)2); // version
  246. b.append((uint64_t)_lastSend);
  247. b.append((uint64_t)_lastPing);
  248. b.append((uint64_t)_lastKeepalive);
  249. b.append((uint64_t)_lastReceived);
  250. _addr.serialize(b);
  251. _localAddress.serialize(b);
  252. b.append((uint16_t)_flags);
  253. b.append((uint16_t)_probation);
  254. }
  255. template<unsigned int C>
  256. inline unsigned int deserialize(const Buffer<C> &b,unsigned int startAt = 0)
  257. {
  258. unsigned int p = startAt;
  259. if (b[p++] != 2)
  260. throw std::invalid_argument("invalid serialized Path");
  261. _lastSend = b.template at<uint64_t>(p); p += 8;
  262. _lastPing = b.template at<uint64_t>(p); p += 8;
  263. _lastKeepalive = b.template at<uint64_t>(p); p += 8;
  264. _lastReceived = b.template at<uint64_t>(p); p += 8;
  265. p += _addr.deserialize(b,p);
  266. p += _localAddress.deserialize(b,p);
  267. _flags = b.template at<uint16_t>(p); p += 2;
  268. _probation = b.template at<uint16_t>(p); p += 2;
  269. _ipScope = _addr.ipScope();
  270. return (p - startAt);
  271. }
  272. inline bool operator==(const Path &p) const { return ((p._addr == _addr)&&(p._localAddress == _localAddress)); }
  273. inline bool operator!=(const Path &p) const { return ((p._addr != _addr)||(p._localAddress != _localAddress)); }
  274. private:
  275. uint64_t _lastSend;
  276. uint64_t _lastPing;
  277. uint64_t _lastKeepalive;
  278. uint64_t _lastReceived;
  279. InetAddress _addr;
  280. InetAddress _localAddress;
  281. unsigned int _flags;
  282. unsigned int _probation;
  283. InetAddress::IpScope _ipScope; // memoize this since it's a computed value checked often
  284. };
  285. } // namespace ZeroTier
  286. #endif