Peer.hpp 13 KB

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