Path.hpp 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334
  1. /*
  2. * ZeroTier One - Network Virtualization Everywhere
  3. * Copyright (C) 2011-2015 ZeroTier, Inc.
  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. * ZeroTier may be used and distributed under the terms of the GPLv3, which
  21. * are available at: http://www.gnu.org/licenses/gpl-3.0.html
  22. *
  23. * If you would like to embed ZeroTier into a commercial application or
  24. * redistribute it in a modified binary form, please contact ZeroTier Networks
  25. * LLC. Start here: http://www.zerotier.com/
  26. */
  27. #ifndef ZT_PATH_HPP
  28. #define ZT_PATH_HPP
  29. #include <stdint.h>
  30. #include <string.h>
  31. #include <stdexcept>
  32. #include <algorithm>
  33. #include "Constants.hpp"
  34. #include "InetAddress.hpp"
  35. /**
  36. * Flag indicating that this path is suboptimal
  37. *
  38. * This is used in cluster mode to indicate that the peer has been directed
  39. * to a better path. This path can continue to be used but shouldn't be kept
  40. * or advertised to other cluster members. Not used if clustering is not
  41. * built and enabled.
  42. */
  43. #define ZT_PATH_FLAG_CLUSTER_SUBOPTIMAL 0x0001
  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. throw()
  122. {
  123. return (((now - _lastReceived) < ZT_PEER_ACTIVITY_TIMEOUT)&&(_probation < ZT_PEER_DEAD_PATH_DETECTION_MAX_PROBATION));
  124. }
  125. /**
  126. * Send a packet via this path
  127. *
  128. * @param RR Runtime environment
  129. * @param data Packet data
  130. * @param len Packet length
  131. * @param now Current time
  132. * @return True if transport reported success
  133. */
  134. bool send(const RuntimeEnvironment *RR,const void *data,unsigned int len,uint64_t now);
  135. /**
  136. * @return Address of local side of this path or NULL if unspecified
  137. */
  138. inline const InetAddress &localAddress() const throw() { return _localAddress; }
  139. /**
  140. * @return Time of last send to this path
  141. */
  142. inline uint64_t lastSend() const throw() { return _lastSend; }
  143. /**
  144. * @return Time we last pinged or dead path checked this link
  145. */
  146. inline uint64_t lastPing() const throw() { return _lastPing; }
  147. /**
  148. * @return Time of last keepalive
  149. */
  150. inline uint64_t lastKeepalive() const throw() { return _lastKeepalive; }
  151. /**
  152. * @return Time of last receive from this path
  153. */
  154. inline uint64_t lastReceived() const throw() { return _lastReceived; }
  155. /**
  156. * @return Physical address
  157. */
  158. inline const InetAddress &address() const throw() { return _addr; }
  159. /**
  160. * @return IP scope -- faster shortcut for address().ipScope()
  161. */
  162. inline InetAddress::IpScope ipScope() const throw() { return _ipScope; }
  163. /**
  164. * @return Preference rank, higher == better (will be less than 255)
  165. */
  166. inline unsigned int preferenceRank() const throw()
  167. {
  168. // First, since the scope enum values in InetAddress.hpp are in order of
  169. // use preference rank, we take that. Then we multiple by two, yielding
  170. // a sequence like 0, 2, 4, 6, etc. Then if it's IPv6 we add one. This
  171. // makes IPv6 addresses of a given scope outrank IPv4 addresses of the
  172. // same scope -- e.g. 1 outranks 0. This makes us prefer IPv6, but not
  173. // if the address scope/class is of a fundamentally lower rank.
  174. return ( ((unsigned int)_ipScope << 1) | (unsigned int)(_addr.ss_family == AF_INET6) );
  175. }
  176. /**
  177. * @return This path's overall score (higher == better)
  178. */
  179. inline uint64_t score() const throw()
  180. {
  181. /* We compute the score based on the "freshness" of the path (when we last
  182. * received something) scaled/corrected by the preference rank within the
  183. * ping keepalive window. That way higher ranking paths are preferred but
  184. * not to the point of overriding timeouts and choosing potentially dead
  185. * paths. */
  186. return (_lastReceived + (preferenceRank() * (ZT_PEER_DIRECT_PING_DELAY / ZT_PATH_MAX_PREFERENCE_RANK)));
  187. }
  188. /**
  189. * @return True if path is considered reliable (no NAT keepalives etc. are needed)
  190. */
  191. inline bool reliable() const throw()
  192. {
  193. if (_addr.ss_family == AF_INET)
  194. return ((_ipScope != InetAddress::IP_SCOPE_GLOBAL)&&(_ipScope != InetAddress::IP_SCOPE_PSEUDOPRIVATE));
  195. return true;
  196. }
  197. /**
  198. * @return True if address is non-NULL
  199. */
  200. inline operator bool() const throw() { return (_addr); }
  201. /**
  202. * Check whether this address is valid for a ZeroTier path
  203. *
  204. * This checks the address type and scope against address types and scopes
  205. * that we currently support for ZeroTier communication.
  206. *
  207. * @param a Address to check
  208. * @return True if address is good for ZeroTier path use
  209. */
  210. static inline bool isAddressValidForPath(const InetAddress &a)
  211. throw()
  212. {
  213. if ((a.ss_family == AF_INET)||(a.ss_family == AF_INET6)) {
  214. switch(a.ipScope()) {
  215. /* Note: we don't do link-local at the moment. Unfortunately these
  216. * cause several issues. The first is that they usually require a
  217. * device qualifier, which we don't handle yet and can't portably
  218. * push in PUSH_DIRECT_PATHS. The second is that some OSes assign
  219. * these very ephemerally or otherwise strangely. So we'll use
  220. * private, pseudo-private, shared (e.g. carrier grade NAT), or
  221. * global IP addresses. */
  222. case InetAddress::IP_SCOPE_PRIVATE:
  223. case InetAddress::IP_SCOPE_PSEUDOPRIVATE:
  224. case InetAddress::IP_SCOPE_SHARED:
  225. case InetAddress::IP_SCOPE_GLOBAL:
  226. return true;
  227. default:
  228. return false;
  229. }
  230. }
  231. return false;
  232. }
  233. #ifdef ZT_ENABLE_CLUSTER
  234. /**
  235. * @param f New value of ZT_PATH_FLAG_CLUSTER_SUBOPTIMAL
  236. */
  237. inline void setClusterSuboptimal(bool f) { _flags = ((f) ? (_flags | ZT_PATH_FLAG_CLUSTER_SUBOPTIMAL) : (_flags & (~ZT_PATH_FLAG_CLUSTER_SUBOPTIMAL))); }
  238. /**
  239. * @return True if ZT_PATH_FLAG_CLUSTER_SUBOPTIMAL is set
  240. */
  241. inline bool isClusterSuboptimal() const { return ((_flags & ZT_PATH_FLAG_CLUSTER_SUBOPTIMAL) != 0); }
  242. #endif
  243. /**
  244. * @return Current path probation count (for dead path detect)
  245. */
  246. inline unsigned int probation() const { return _probation; }
  247. /**
  248. * Increase this path's probation violation count (for dead path detect)
  249. */
  250. inline void increaseProbation() { ++_probation; }
  251. template<unsigned int C>
  252. inline void serialize(Buffer<C> &b) const
  253. {
  254. b.append((uint8_t)2); // version
  255. b.append((uint64_t)_lastSend);
  256. b.append((uint64_t)_lastPing);
  257. b.append((uint64_t)_lastKeepalive);
  258. b.append((uint64_t)_lastReceived);
  259. _addr.serialize(b);
  260. _localAddress.serialize(b);
  261. b.append((uint16_t)_flags);
  262. b.append((uint16_t)_probation);
  263. }
  264. template<unsigned int C>
  265. inline unsigned int deserialize(const Buffer<C> &b,unsigned int startAt = 0)
  266. {
  267. unsigned int p = startAt;
  268. if (b[p++] != 2)
  269. throw std::invalid_argument("invalid serialized Path");
  270. _lastSend = b.template at<uint64_t>(p); p += 8;
  271. _lastPing = b.template at<uint64_t>(p); p += 8;
  272. _lastKeepalive = b.template at<uint64_t>(p); p += 8;
  273. _lastReceived = b.template at<uint64_t>(p); p += 8;
  274. p += _addr.deserialize(b,p);
  275. p += _localAddress.deserialize(b,p);
  276. _flags = b.template at<uint16_t>(p); p += 2;
  277. _probation = b.template at<uint16_t>(p); p += 2;
  278. _ipScope = _addr.ipScope();
  279. return (p - startAt);
  280. }
  281. inline bool operator==(const Path &p) const { return ((p._addr == _addr)&&(p._localAddress == _localAddress)); }
  282. inline bool operator!=(const Path &p) const { return ((p._addr != _addr)||(p._localAddress != _localAddress)); }
  283. private:
  284. uint64_t _lastSend;
  285. uint64_t _lastPing;
  286. uint64_t _lastKeepalive;
  287. uint64_t _lastReceived;
  288. InetAddress _addr;
  289. InetAddress _localAddress;
  290. unsigned int _flags;
  291. unsigned int _probation;
  292. InetAddress::IpScope _ipScope; // memoize this since it's a computed value checked often
  293. };
  294. } // namespace ZeroTier
  295. #endif