Peer.hpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435
  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_PEER_HPP
  28. #define ZT_PEER_HPP
  29. #include <stdint.h>
  30. #include "Constants.hpp"
  31. #include <algorithm>
  32. #include <utility>
  33. #include <vector>
  34. #include <stdexcept>
  35. #include "../include/ZeroTierOne.h"
  36. #include "RuntimeEnvironment.hpp"
  37. #include "CertificateOfMembership.hpp"
  38. #include "RemotePath.hpp"
  39. #include "Address.hpp"
  40. #include "Utils.hpp"
  41. #include "Identity.hpp"
  42. #include "InetAddress.hpp"
  43. #include "Packet.hpp"
  44. #include "SharedPtr.hpp"
  45. #include "AtomicCounter.hpp"
  46. #include "NonCopyable.hpp"
  47. namespace ZeroTier {
  48. /**
  49. * Peer on P2P Network (virtual layer 1)
  50. */
  51. class Peer : NonCopyable
  52. {
  53. friend class SharedPtr<Peer>;
  54. private:
  55. Peer() {} // disabled to prevent bugs -- should not be constructed uninitialized
  56. public:
  57. ~Peer() { Utils::burn(_key,sizeof(_key)); }
  58. /**
  59. * Construct a new peer
  60. *
  61. * @param myIdentity Identity of THIS node (for key agreement)
  62. * @param peerIdentity Identity of peer
  63. * @throws std::runtime_error Key agreement with peer's identity failed
  64. */
  65. Peer(const Identity &myIdentity,const Identity &peerIdentity)
  66. throw(std::runtime_error);
  67. /**
  68. * @return Time peer record was last used in any way
  69. */
  70. inline uint64_t lastUsed() const throw() { return _lastUsed; }
  71. /**
  72. * Log a use of this peer record (done by Topology when peers are looked up)
  73. *
  74. * @param now New time of last use
  75. */
  76. inline void use(uint64_t now) throw() { _lastUsed = now; }
  77. /**
  78. * @return This peer's ZT address (short for identity().address())
  79. */
  80. inline const Address &address() const throw() { return _id.address(); }
  81. /**
  82. * @return This peer's identity
  83. */
  84. inline const Identity &identity() const throw() { return _id; }
  85. /**
  86. * Log receipt of an authenticated packet
  87. *
  88. * This is called by the decode pipe when a packet is proven to be authentic
  89. * and appears to be valid.
  90. *
  91. * @param RR Runtime environment
  92. * @param remoteAddr Internet address of sender
  93. * @param hops ZeroTier (not IP) hops
  94. * @param packetId Packet ID
  95. * @param verb Packet verb
  96. * @param inRePacketId Packet ID in reply to (default: none)
  97. * @param inReVerb Verb in reply to (for OK/ERROR, default: VERB_NOP)
  98. */
  99. void received(
  100. const RuntimeEnvironment *RR,
  101. const InetAddress &remoteAddr,
  102. unsigned int hops,
  103. uint64_t packetId,
  104. Packet::Verb verb,
  105. uint64_t inRePacketId = 0,
  106. Packet::Verb inReVerb = Packet::VERB_NOP);
  107. /**
  108. * Get the best direct path to this peer
  109. *
  110. * @param now Current time
  111. * @return Best path or NULL if there are no active (or fixed) direct paths
  112. */
  113. RemotePath *getBestPath(uint64_t now);
  114. /**
  115. * Send via best path
  116. *
  117. * @param RR Runtime environment
  118. * @param data Packet data
  119. * @param len Packet length
  120. * @param now Current time
  121. * @return Path used on success or NULL on failure
  122. */
  123. inline RemotePath *send(const RuntimeEnvironment *RR,const void *data,unsigned int len,uint64_t now)
  124. {
  125. RemotePath *bestPath = getBestPath(now);
  126. if (bestPath) {
  127. if (bestPath->send(RR,data,len,now))
  128. return bestPath;
  129. }
  130. return (RemotePath *)0;
  131. }
  132. /**
  133. * Send a HELLO to this peer at a specified physical address
  134. *
  135. * This does not update any statistics. It's used to send initial HELLOs
  136. * for NAT traversal and path verification.
  137. *
  138. * @param RR Runtime environment
  139. * @param atAddress Destination address
  140. * @param now Current time
  141. */
  142. void attemptToContactAt(const RuntimeEnvironment *RR,const InetAddress &atAddress,uint64_t now);
  143. /**
  144. * Send pings or keepalives depending on configured timeouts
  145. *
  146. * @param RR Runtime environment
  147. * @param now Current time
  148. */
  149. void doPingAndKeepalive(const RuntimeEnvironment *RR,uint64_t now);
  150. /**
  151. * Push direct paths if we haven't done so in [rate limit] milliseconds
  152. *
  153. * @param RR Runtime environment
  154. * @param path Remote path to use to send the push
  155. * @param now Current time
  156. * @param force If true, push regardless of rate limit
  157. */
  158. void pushDirectPaths(const RuntimeEnvironment *RR,RemotePath *path,uint64_t now,bool force);
  159. /**
  160. * @return All known direct paths to this peer
  161. */
  162. inline std::vector<RemotePath> paths() const
  163. {
  164. std::vector<RemotePath> pp;
  165. for(unsigned int p=0,np=_numPaths;p<np;++p)
  166. pp.push_back(_paths[p]);
  167. return pp;
  168. }
  169. /**
  170. * @return Time of last direct packet receive for any path
  171. */
  172. inline uint64_t lastDirectReceive() const
  173. throw()
  174. {
  175. uint64_t x = 0;
  176. for(unsigned int p=0,np=_numPaths;p<np;++p)
  177. x = std::max(x,_paths[p].lastReceived());
  178. return x;
  179. }
  180. /**
  181. * @return Time of last direct packet send for any path
  182. */
  183. inline uint64_t lastDirectSend() const
  184. throw()
  185. {
  186. uint64_t x = 0;
  187. for(unsigned int p=0,np=_numPaths;p<np;++p)
  188. x = std::max(x,_paths[p].lastSend());
  189. return x;
  190. }
  191. /**
  192. * @return Time of last receive of anything, whether direct or relayed
  193. */
  194. inline uint64_t lastReceive() const throw() { return _lastReceive; }
  195. /**
  196. * @return Time of most recent unicast frame received
  197. */
  198. inline uint64_t lastUnicastFrame() const throw() { return _lastUnicastFrame; }
  199. /**
  200. * @return Time of most recent multicast frame received
  201. */
  202. inline uint64_t lastMulticastFrame() const throw() { return _lastMulticastFrame; }
  203. /**
  204. * @return Time of most recent frame of any kind (unicast or multicast)
  205. */
  206. inline uint64_t lastFrame() const throw() { return std::max(_lastUnicastFrame,_lastMulticastFrame); }
  207. /**
  208. * @return Time we last announced state TO this peer, such as multicast LIKEs
  209. */
  210. inline uint64_t lastAnnouncedTo() const throw() { return _lastAnnouncedTo; }
  211. /**
  212. * @return True if peer has received an actual data frame within ZT_PEER_ACTIVITY_TIMEOUT milliseconds
  213. */
  214. inline uint64_t alive(uint64_t now) const throw() { return ((now - lastFrame()) < ZT_PEER_ACTIVITY_TIMEOUT); }
  215. /**
  216. * @return Current latency or 0 if unknown (max: 65535)
  217. */
  218. inline unsigned int latency() const
  219. throw()
  220. {
  221. unsigned int l = _latency;
  222. return std::min(l,(unsigned int)65535);
  223. }
  224. /**
  225. * Update latency with a new direct measurment
  226. *
  227. * @param l Direct latency measurment in ms
  228. */
  229. inline void addDirectLatencyMeasurment(unsigned int l)
  230. throw()
  231. {
  232. unsigned int ol = _latency;
  233. if ((ol > 0)&&(ol < 10000))
  234. _latency = (ol + std::min(l,(unsigned int)65535)) / 2;
  235. else _latency = std::min(l,(unsigned int)65535);
  236. }
  237. /**
  238. * @return True if this peer has at least one direct IP address path
  239. */
  240. inline bool hasDirectPath() const throw() { return (_numPaths != 0); }
  241. /**
  242. * @param now Current time
  243. * @return True if this peer has at least one active or fixed direct path
  244. */
  245. inline bool hasActiveDirectPath(uint64_t now) const
  246. throw()
  247. {
  248. for(unsigned int p=0,np=_numPaths;p<np;++p) {
  249. if (_paths[p].active(now))
  250. return true;
  251. }
  252. return false;
  253. }
  254. /**
  255. * Add a path (if we don't already have it)
  256. *
  257. * @param p New path to add
  258. */
  259. void addPath(const RemotePath &newp);
  260. /**
  261. * Clear paths
  262. *
  263. * @param fixedToo If true, clear fixed paths as well as learned ones
  264. */
  265. void clearPaths(bool fixedToo);
  266. /**
  267. * Reset paths within a given scope
  268. *
  269. * For fixed paths in this scope, a packet is sent. Non-fixed paths in this
  270. * scope are forgotten.
  271. *
  272. * @param RR Runtime environment
  273. * @param scope IP scope of paths to reset
  274. * @param now Current time
  275. * @return True if at least one path was forgotten
  276. */
  277. bool resetWithinScope(const RuntimeEnvironment *RR,InetAddress::IpScope scope,uint64_t now);
  278. /**
  279. * @return 256-bit secret symmetric encryption key
  280. */
  281. inline const unsigned char *key() const throw() { return _key; }
  282. /**
  283. * Set the currently known remote version of this peer's client
  284. *
  285. * @param vproto Protocol version
  286. * @param vmaj Major version
  287. * @param vmin Minor version
  288. * @param vrev Revision
  289. */
  290. inline void setRemoteVersion(unsigned int vproto,unsigned int vmaj,unsigned int vmin,unsigned int vrev)
  291. {
  292. _vProto = (uint16_t)vproto;
  293. _vMajor = (uint16_t)vmaj;
  294. _vMinor = (uint16_t)vmin;
  295. _vRevision = (uint16_t)vrev;
  296. }
  297. inline unsigned int remoteVersionProtocol() const throw() { return _vProto; }
  298. inline unsigned int remoteVersionMajor() const throw() { return _vMajor; }
  299. inline unsigned int remoteVersionMinor() const throw() { return _vMinor; }
  300. inline unsigned int remoteVersionRevision() const throw() { return _vRevision; }
  301. inline bool remoteVersionKnown() const throw() { return ((_vMajor > 0)||(_vMinor > 0)||(_vRevision > 0)); }
  302. /**
  303. * Check whether this peer's version is both known and is at least what is specified
  304. *
  305. * @param major Major version to check against
  306. * @param minor Minor version
  307. * @param rev Revision
  308. * @return True if peer's version is at least supplied tuple
  309. */
  310. inline bool atLeastVersion(unsigned int major,unsigned int minor,unsigned int rev)
  311. throw()
  312. {
  313. if ((_vMajor > 0)||(_vMinor > 0)||(_vRevision > 0)) {
  314. if (_vMajor > major)
  315. return true;
  316. else if (_vMajor == major) {
  317. if (_vMinor > minor)
  318. return true;
  319. else if (_vMinor == minor) {
  320. if (_vRevision >= rev)
  321. return true;
  322. }
  323. }
  324. }
  325. return false;
  326. }
  327. /**
  328. * Get most recently active path addresses for IPv4 and/or IPv6
  329. *
  330. * Note that v4 and v6 are not modified if they are not found, so
  331. * initialize these to a NULL address to be able to check.
  332. *
  333. * @param now Current time
  334. * @param v4 Result parameter to receive active IPv4 address, if any
  335. * @param v6 Result parameter to receive active IPv6 address, if any
  336. */
  337. void getBestActiveAddresses(uint64_t now,InetAddress &v4,InetAddress &v6) const;
  338. /**
  339. * Find a common set of addresses by which two peers can link, if any
  340. *
  341. * @param a Peer A
  342. * @param b Peer B
  343. * @param now Current time
  344. * @return Pair: B's address (to send to A), A's address (to send to B)
  345. */
  346. static inline std::pair<InetAddress,InetAddress> findCommonGround(const Peer &a,const Peer &b,uint64_t now)
  347. {
  348. std::pair<InetAddress,InetAddress> v4,v6;
  349. b.getBestActiveAddresses(now,v4.first,v6.first);
  350. a.getBestActiveAddresses(now,v4.second,v6.second);
  351. if ((v6.first)&&(v6.second)) // prefer IPv6 if both have it since NAT-t is (almost) unnecessary
  352. return v6;
  353. else if ((v4.first)&&(v4.second))
  354. return v4;
  355. else return std::pair<InetAddress,InetAddress>();
  356. }
  357. private:
  358. void _announceMulticastGroups(const RuntimeEnvironment *RR,uint64_t now);
  359. unsigned char _key[ZT_PEER_SECRET_KEY_LENGTH];
  360. uint64_t _lastUsed;
  361. uint64_t _lastReceive; // direct or indirect
  362. uint64_t _lastUnicastFrame;
  363. uint64_t _lastMulticastFrame;
  364. uint64_t _lastAnnouncedTo;
  365. uint64_t _lastPathConfirmationSent;
  366. uint64_t _lastDirectPathPush;
  367. uint16_t _vProto;
  368. uint16_t _vMajor;
  369. uint16_t _vMinor;
  370. uint16_t _vRevision;
  371. Identity _id;
  372. RemotePath _paths[ZT1_MAX_PEER_NETWORK_PATHS];
  373. unsigned int _numPaths;
  374. unsigned int _latency;
  375. AtomicCounter __refCount;
  376. };
  377. } // namespace ZeroTier
  378. // Add a swap() for shared ptr's to peers to speed up peer sorts
  379. namespace std {
  380. template<>
  381. inline void swap(ZeroTier::SharedPtr<ZeroTier::Peer> &a,ZeroTier::SharedPtr<ZeroTier::Peer> &b)
  382. {
  383. a.swap(b);
  384. }
  385. }
  386. #endif