Peer.hpp 12 KB

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