Peer.hpp 14 KB

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