Peer.hpp 14 KB

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