Peer.hpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412
  1. /*
  2. * ZeroTier One - Global Peer to Peer Ethernet
  3. * Copyright (C) 2011-2015 ZeroTier Networks
  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 "Constants.hpp"
  35. #include "Path.hpp"
  36. #include "Address.hpp"
  37. #include "Utils.hpp"
  38. #include "Identity.hpp"
  39. #include "Logger.hpp"
  40. #include "RuntimeEnvironment.hpp"
  41. #include "InetAddress.hpp"
  42. #include "Packet.hpp"
  43. #include "SharedPtr.hpp"
  44. #include "Socket.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 8
  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 fromSock Socket from which packet was received
  101. * @param remoteAddr Internet address of sender
  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 (for OK/ERROR, 0 otherwise)
  106. * @param inReVerb Verb in reply to (for OK/ERROR, VERB_NOP otherwise)
  107. * @param now Current time
  108. */
  109. void received(
  110. const RuntimeEnvironment *RR,
  111. const SharedPtr<Socket> &fromSock,
  112. const InetAddress &remoteAddr,
  113. unsigned int hops,
  114. uint64_t packetId,
  115. Packet::Verb verb,
  116. uint64_t inRePacketId,
  117. Packet::Verb inReVerb,
  118. uint64_t now);
  119. /**
  120. * Send a packet directly to this peer
  121. *
  122. * This sends only via direct paths if available and does not handle
  123. * finding of relays. That is done in the send logic in Switch.
  124. *
  125. * @param RR Runtime environment
  126. * @param data Data to send
  127. * @param len Length of packet
  128. * @param now Current time
  129. * @return Type of path used or Path::PATH_TYPE_NULL on failure
  130. */
  131. Path::Type send(const RuntimeEnvironment *RR,const void *data,unsigned int len,uint64_t now);
  132. /**
  133. * Send HELLO to a peer via all direct paths available
  134. *
  135. * This begins attempting to use TCP paths if no ping response has been
  136. * received from any UDP path in more than ZT_TCP_FALLBACK_AFTER.
  137. *
  138. * @param RR Runtime environment
  139. * @param now Current time
  140. * @return True if send appears successful for at least one address type
  141. */
  142. bool sendPing(const RuntimeEnvironment *RR,uint64_t now);
  143. /**
  144. * Called periodically by Topology::clean() to remove stale paths and do other cleanup
  145. */
  146. void clean(uint64_t now);
  147. /**
  148. * @return All known direct paths to this peer
  149. */
  150. std::vector<Path> paths() const
  151. {
  152. std::vector<Path> pp;
  153. for(unsigned int p=0,np=_numPaths;p<np;++p)
  154. pp.push_back(_paths[p]);
  155. return pp;
  156. }
  157. /**
  158. * @param addr IP:port
  159. * @return True if we have a UDP path to this address
  160. */
  161. inline bool haveUdpPath(const InetAddress &addr) const
  162. {
  163. for(unsigned int p=0,np=_numPaths;p<np;++p) {
  164. if ((_paths[p].type() == Path::PATH_TYPE_UDP)&&(_paths[p].address() == addr))
  165. return true;
  166. }
  167. return false;
  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. * Get max timestamp of last ping and max timestamp of last receive in a single pass
  193. *
  194. * @param lp Last ping result parameter (init to 0 before calling)
  195. * @param lr Last receive result parameter (init to 0 before calling)
  196. */
  197. inline void lastPingAndDirectReceive(uint64_t &lp,uint64_t &lr)
  198. throw()
  199. {
  200. for(unsigned int p=0,np=_numPaths;p<np;++p) {
  201. lp = std::max(lp,_paths[p].lastPing());
  202. lr = std::max(lr,_paths[p].lastReceived());
  203. }
  204. }
  205. /**
  206. * @return Time of last receive of anything, whether direct or relayed
  207. */
  208. inline uint64_t lastReceive() const throw() { return _lastReceive; }
  209. /**
  210. * @return Time of most recent unicast frame received
  211. */
  212. inline uint64_t lastUnicastFrame() const throw() { return _lastUnicastFrame; }
  213. /**
  214. * @return Time of most recent multicast frame received
  215. */
  216. inline uint64_t lastMulticastFrame() const throw() { return _lastMulticastFrame; }
  217. /**
  218. * @return Time of most recent frame of any kind (unicast or multicast)
  219. */
  220. inline uint64_t lastFrame() const throw() { return std::max(_lastUnicastFrame,_lastMulticastFrame); }
  221. /**
  222. * @return Time we last announced state TO this peer, such as multicast LIKEs
  223. */
  224. inline uint64_t lastAnnouncedTo() const throw() { return _lastAnnouncedTo; }
  225. /**
  226. * @param now Current time
  227. * @return True if peer has received something within ZT_PEER_ACTIVITY_TIMEOUT ms
  228. */
  229. inline bool alive(uint64_t now) const throw() { return ((now - _lastReceive) < ZT_PEER_ACTIVITY_TIMEOUT); }
  230. /**
  231. * @return Current latency or 0 if unknown (max: 65535)
  232. */
  233. inline unsigned int latency() const
  234. throw()
  235. {
  236. unsigned int l = _latency;
  237. return std::min(l,(unsigned int)65535);
  238. }
  239. /**
  240. * Update latency with a new direct measurment
  241. *
  242. * @param l Direct latency measurment in ms
  243. */
  244. inline void addDirectLatencyMeasurment(unsigned int l)
  245. throw()
  246. {
  247. unsigned int ol = _latency;
  248. if ((ol > 0)&&(ol < 10000))
  249. _latency = (ol + std::min(l,(unsigned int)65535)) / 2;
  250. else _latency = std::min(l,(unsigned int)65535);
  251. }
  252. /**
  253. * @return True if this peer has at least one direct IP address path
  254. */
  255. inline bool hasDirectPath() const throw() { return (_numPaths != 0); }
  256. /**
  257. * @param now Current time
  258. * @return True if this peer has at least one active or fixed direct path
  259. */
  260. inline bool hasActiveDirectPath(uint64_t now) const
  261. throw()
  262. {
  263. for(unsigned int p=0,np=_numPaths;p<np;++p) {
  264. if (_paths[p].active(now))
  265. return true;
  266. }
  267. return false;
  268. }
  269. /**
  270. * Add a path (if we don't already have it)
  271. *
  272. * @param p New path to add
  273. */
  274. void addPath(const Path &newp);
  275. /**
  276. * Clear paths
  277. *
  278. * @param fixedToo If true, clear fixed paths as well as learned ones
  279. */
  280. void clearPaths(bool fixedToo);
  281. /**
  282. * @return 256-bit secret symmetric encryption key
  283. */
  284. inline const unsigned char *key() const throw() { return _key; }
  285. /**
  286. * Set the currently known remote version of this peer's client
  287. *
  288. * @param vproto Protocol version
  289. * @param vmaj Major version
  290. * @param vmin Minor version
  291. * @param vrev Revision
  292. */
  293. inline void setRemoteVersion(unsigned int vproto,unsigned int vmaj,unsigned int vmin,unsigned int vrev)
  294. {
  295. _vProto = (uint16_t)vproto;
  296. _vMajor = (uint16_t)vmaj;
  297. _vMinor = (uint16_t)vmin;
  298. _vRevision = (uint16_t)vrev;
  299. }
  300. inline unsigned int remoteVersionProtocol() const throw() { return _vProto; }
  301. inline unsigned int remoteVersionMajor() const throw() { return _vMajor; }
  302. inline unsigned int remoteVersionMinor() const throw() { return _vMinor; }
  303. inline unsigned int remoteVersionRevision() const throw() { return _vRevision; }
  304. inline bool remoteVersionKnown() const throw() { return ((_vMajor > 0)||(_vMinor > 0)||(_vRevision > 0)); }
  305. /**
  306. * Get most recently active UDP path addresses for IPv4 and/or IPv6
  307. *
  308. * Note that v4 and v6 are not modified if they are not found, so
  309. * initialize these to a NULL address to be able to check.
  310. *
  311. * @param now Current time
  312. * @param v4 Result parameter to receive active IPv4 address, if any
  313. * @param v6 Result parameter to receive active IPv6 address, if any
  314. */
  315. void getBestActiveUdpPathAddresses(uint64_t now,InetAddress &v4,InetAddress &v6) const;
  316. /**
  317. * Find a common set of addresses by which two peers can link, if any
  318. *
  319. * @param a Peer A
  320. * @param b Peer B
  321. * @param now Current time
  322. * @return Pair: B's address (to send to A), A's address (to send to B)
  323. */
  324. static inline std::pair<InetAddress,InetAddress> findCommonGround(const Peer &a,const Peer &b,uint64_t now)
  325. {
  326. std::pair<InetAddress,InetAddress> v4,v6;
  327. b.getBestActiveUdpPathAddresses(now,v4.first,v6.first);
  328. a.getBestActiveUdpPathAddresses(now,v4.second,v6.second);
  329. if ((v6.first)&&(v6.second)) // prefer IPv6 if both have it since NAT-t is (almost) unnecessary
  330. return v6;
  331. else if ((v4.first)&&(v4.second))
  332. return v4;
  333. else return std::pair<InetAddress,InetAddress>();
  334. }
  335. private:
  336. void _announceMulticastGroups(const RuntimeEnvironment *RR,uint64_t now);
  337. volatile uint64_t _lastUsed;
  338. volatile uint64_t _lastReceive; // direct or indirect
  339. volatile uint64_t _lastUnicastFrame;
  340. volatile uint64_t _lastMulticastFrame;
  341. volatile uint64_t _lastAnnouncedTo;
  342. volatile uint16_t _vProto;
  343. volatile uint16_t _vMajor;
  344. volatile uint16_t _vMinor;
  345. volatile uint16_t _vRevision;
  346. Path _paths[ZT_PEER_MAX_PATHS];
  347. volatile unsigned int _numPaths;
  348. volatile unsigned int _latency;
  349. unsigned char _key[ZT_PEER_SECRET_KEY_LENGTH];
  350. Identity _id;
  351. AtomicCounter __refCount;
  352. };
  353. } // namespace ZeroTier
  354. // Add a swap() for shared ptr's to peers to speed up peer sorts
  355. namespace std {
  356. template<>
  357. inline void swap(ZeroTier::SharedPtr<ZeroTier::Peer> &a,ZeroTier::SharedPtr<ZeroTier::Peer> &b)
  358. {
  359. a.swap(b);
  360. }
  361. }
  362. #endif