Peer.hpp 11 KB

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