Path.hpp 8.1 KB

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