Peer.hpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517
  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 9
  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 _r 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 *_r,
  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 _r 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 *_r,const void *data,unsigned int len,uint64_t now);
  128. /**
  129. * Send firewall opener to all UDP paths
  130. *
  131. * @param _r Runtime environment
  132. * @param now Current time
  133. * @return True if send appears successful for at least one address type
  134. */
  135. bool sendFirewallOpener(const RuntimeEnvironment *_r,uint64_t now);
  136. /**
  137. * Send HELLO to a peer via all direct paths available
  138. *
  139. * This begins attempting to use TCP paths if no ping response has been
  140. * received from any UDP path in more than ZT_TCP_FALLBACK_AFTER.
  141. *
  142. * @param _r Runtime environment
  143. * @param now Current time
  144. * @return True if send appears successful for at least one address type
  145. */
  146. bool sendPing(const RuntimeEnvironment *_r,uint64_t now);
  147. /**
  148. * Called periodically by Topology::clean() to remove stale paths and do other cleanup
  149. */
  150. void clean(uint64_t now);
  151. /**
  152. * @return All known direct paths to this peer
  153. */
  154. std::vector<Path> paths() const
  155. {
  156. Mutex::Lock _l(_lock);
  157. return _paths;
  158. }
  159. /**
  160. * @param addr IP:port
  161. * @return True if we have a UDP path to this address
  162. */
  163. inline bool haveUdpPath(const InetAddress &addr) const
  164. {
  165. Mutex::Lock _l(_lock);
  166. for(std::vector<Path>::const_iterator p(_paths.begin());p!=_paths.end();++p) {
  167. if ((p->type() == Path::PATH_TYPE_UDP)&&(p->address() == addr))
  168. return true;
  169. }
  170. return false;
  171. }
  172. /**
  173. * @return Last successfully sent firewall opener for any path
  174. */
  175. inline uint64_t lastFirewallOpener() const
  176. throw()
  177. {
  178. uint64_t x = 0;
  179. Mutex::Lock _l(_lock);
  180. for(std::vector<Path>::const_iterator p(_paths.begin());p!=_paths.end();++p)
  181. x = std::max(x,p->lastFirewallOpener());
  182. return x;
  183. }
  184. /**
  185. * @return Time of last direct packet receive for any path
  186. */
  187. inline uint64_t lastDirectReceive() const
  188. throw()
  189. {
  190. uint64_t x = 0;
  191. Mutex::Lock _l(_lock);
  192. for(std::vector<Path>::const_iterator p(_paths.begin());p!=_paths.end();++p)
  193. x = std::max(x,p->lastReceived());
  194. return x;
  195. }
  196. /**
  197. * @return Time of last direct packet send for any path
  198. */
  199. inline uint64_t lastDirectSend() const
  200. throw()
  201. {
  202. uint64_t x = 0;
  203. Mutex::Lock _l(_lock);
  204. for(std::vector<Path>::const_iterator p(_paths.begin());p!=_paths.end();++p)
  205. x = std::max(x,p->lastSend());
  206. return x;
  207. }
  208. /**
  209. * Get max timestamp of last ping and max timestamp of last receive in a single pass
  210. *
  211. * @param lp Last ping result parameter (init to 0 before calling)
  212. * @param lr Last receive result parameter (init to 0 before calling)
  213. */
  214. inline void lastPingAndDirectReceive(uint64_t &lp,uint64_t &lr)
  215. throw()
  216. {
  217. Mutex::Lock _l(_lock);
  218. for(std::vector<Path>::const_iterator p(_paths.begin());p!=_paths.end();++p) {
  219. lp = std::max(lp,p->lastPing());
  220. lr = std::max(lr,p->lastReceived());
  221. }
  222. }
  223. /**
  224. * @return Time of last receive of anything, whether direct or relayed
  225. */
  226. inline uint64_t lastReceive() const throw() { return _lastReceive; }
  227. /**
  228. * @return Time of most recent unicast frame received
  229. */
  230. inline uint64_t lastUnicastFrame() const throw() { return _lastUnicastFrame; }
  231. /**
  232. * @return Time of most recent multicast frame received
  233. */
  234. inline uint64_t lastMulticastFrame() const throw() { return _lastMulticastFrame; }
  235. /**
  236. * @return Time of most recent frame of any kind (unicast or multicast)
  237. */
  238. inline uint64_t lastFrame() const throw() { return std::max(_lastUnicastFrame,_lastMulticastFrame); }
  239. /**
  240. * @return Time we last announced state TO this peer, such as multicast LIKEs
  241. */
  242. inline uint64_t lastAnnouncedTo() const throw() { return _lastAnnouncedTo; }
  243. /**
  244. * @param now Current time
  245. * @return True if peer has received something within ZT_PEER_ACTIVITY_TIMEOUT ms
  246. */
  247. inline bool alive(uint64_t now) const
  248. throw()
  249. {
  250. return ((now - _lastReceive) < ZT_PEER_ACTIVITY_TIMEOUT);
  251. }
  252. /**
  253. * @return Current latency or 0 if unknown (max: 65535)
  254. */
  255. inline unsigned int latency() const
  256. throw()
  257. {
  258. unsigned int l = _latency;
  259. return std::min(l,(unsigned int)65535);
  260. }
  261. /**
  262. * Update latency with a new direct measurment
  263. *
  264. * @param l Direct latency measurment in ms
  265. */
  266. inline void addDirectLatencyMeasurment(unsigned int l)
  267. throw()
  268. {
  269. unsigned int ol = _latency;
  270. if ((ol > 0)&&(ol < 10000))
  271. _latency = (ol + std::min(l,(unsigned int)65535)) / 2;
  272. else _latency = std::min(l,(unsigned int)65535);
  273. }
  274. /**
  275. * @return True if this peer has at least one direct IP address path
  276. */
  277. inline bool hasDirectPath() const
  278. throw()
  279. {
  280. Mutex::Lock _l(_lock);
  281. return (!_paths.empty());
  282. }
  283. /**
  284. * @param now Current time
  285. * @return True if this peer has at least one active or fixed direct path
  286. */
  287. inline bool hasActiveDirectPath(uint64_t now) const
  288. throw()
  289. {
  290. Mutex::Lock _l(_lock);
  291. for(std::vector<Path>::const_iterator p(_paths.begin());p!=_paths.end();++p) {
  292. if (p->active(now))
  293. return true;
  294. }
  295. return false;
  296. }
  297. /**
  298. * Add a path (if we don't already have it)
  299. *
  300. * @param p New path to add
  301. */
  302. inline void addPath(const Path &newp)
  303. {
  304. Mutex::Lock _l(_lock);
  305. for(std::vector<Path>::iterator p(_paths.begin());p!=_paths.end();++p) {
  306. if (*p == newp) {
  307. p->setFixed(newp.fixed());
  308. return;
  309. }
  310. }
  311. _paths.push_back(newp);
  312. }
  313. /**
  314. * Clear paths
  315. *
  316. * @param fixedToo If true, clear fixed paths as well as learned ones
  317. */
  318. inline void clearPaths(bool fixedToo)
  319. {
  320. std::vector<Path> npv;
  321. Mutex::Lock _l(_lock);
  322. if (!fixedToo) {
  323. for(std::vector<Path>::const_iterator p(_paths.begin());p!=_paths.end();++p) {
  324. if (p->fixed())
  325. npv.push_back(*p);
  326. }
  327. }
  328. _paths = npv;
  329. }
  330. /**
  331. * @return 256-bit secret symmetric encryption key
  332. */
  333. inline const unsigned char *key() const throw() { return _key; }
  334. /**
  335. * Set the currently known remote version of this peer's client
  336. *
  337. * @param vmaj Major version
  338. * @param vmin Minor version
  339. * @param vrev Revision
  340. */
  341. inline void setRemoteVersion(unsigned int vmaj,unsigned int vmin,unsigned int vrev)
  342. throw()
  343. {
  344. _vMajor = vmaj;
  345. _vMinor = vmin;
  346. _vRevision = vrev;
  347. }
  348. /**
  349. * @return Remote version in string form or '?' if unknown
  350. */
  351. inline std::string remoteVersion() const
  352. {
  353. if ((_vMajor > 0)||(_vMinor > 0)||(_vRevision > 0)) {
  354. char tmp[32];
  355. Utils::snprintf(tmp,sizeof(tmp),"%u.%u.%u",_vMajor,_vMinor,_vRevision);
  356. return std::string(tmp);
  357. }
  358. return std::string("?.?.?");
  359. }
  360. /**
  361. * Get most recently active UDP path addresses for IPv4 and/or IPv6
  362. *
  363. * Note that v4 and v6 are not modified if they are not found, so
  364. * initialize these to a NULL address to be able to check.
  365. *
  366. * @param now Current time
  367. * @param v4 Result parameter to receive active IPv4 address, if any
  368. * @param v6 Result parameter to receive active IPv6 address, if any
  369. */
  370. void getBestActiveUdpPathAddresses(uint64_t now,InetAddress &v4,InetAddress &v6) const;
  371. /**
  372. * Find a common set of addresses by which two peers can link, if any
  373. *
  374. * @param a Peer A
  375. * @param b Peer B
  376. * @param now Current time
  377. * @return Pair: B's address (to send to A), A's address (to send to B)
  378. */
  379. static inline std::pair<InetAddress,InetAddress> findCommonGround(const Peer &a,const Peer &b,uint64_t now)
  380. {
  381. std::pair<InetAddress,InetAddress> v4,v6;
  382. b.getBestActiveUdpPathAddresses(now,v4.first,v6.first);
  383. a.getBestActiveUdpPathAddresses(now,v4.second,v6.second);
  384. if ((v6.first)&&(v6.second)) // prefer IPv6 if both have it since NAT-t is (almost) unnecessary
  385. return v6;
  386. else if ((v4.first)&&(v4.second))
  387. return v4;
  388. else return std::pair<InetAddress,InetAddress>();
  389. }
  390. template<unsigned int C>
  391. inline void serialize(Buffer<C> &b) const
  392. {
  393. Mutex::Lock _l(_lock);
  394. b.append((unsigned char)ZT_PEER_SERIALIZATION_VERSION);
  395. _id.serialize(b,false);
  396. b.append(_key,sizeof(_key));
  397. b.append(_lastUsed);
  398. b.append(_lastReceive);
  399. b.append(_lastUnicastFrame);
  400. b.append(_lastMulticastFrame);
  401. b.append(_lastAnnouncedTo);
  402. b.append((uint16_t)_vMajor);
  403. b.append((uint16_t)_vMinor);
  404. b.append((uint16_t)_vRevision);
  405. b.append((uint16_t)_latency);
  406. b.append((uint16_t)_paths.size());
  407. for(std::vector<Path>::const_iterator p(_paths.begin());p!=_paths.end();++p)
  408. p->serialize(b);
  409. }
  410. template<unsigned int C>
  411. inline unsigned int deserialize(const Buffer<C> &b,unsigned int startAt = 0)
  412. {
  413. unsigned int p = startAt;
  414. if (b[p++] != ZT_PEER_SERIALIZATION_VERSION)
  415. throw std::invalid_argument("Peer: deserialize(): version mismatch");
  416. Mutex::Lock _l(_lock);
  417. p += _id.deserialize(b,p);
  418. memcpy(_key,b.field(p,sizeof(_key)),sizeof(_key)); p += sizeof(_key);
  419. _lastUsed = b.template at<uint64_t>(p); p += sizeof(uint64_t);
  420. _lastReceive = b.template at<uint64_t>(p); p += sizeof(uint64_t);
  421. _lastUnicastFrame = b.template at<uint64_t>(p); p += sizeof(uint64_t);
  422. _lastMulticastFrame = b.template at<uint64_t>(p); p += sizeof(uint64_t);
  423. _lastAnnouncedTo = b.template at<uint64_t>(p); p += sizeof(uint64_t);
  424. _vMajor = b.template at<uint16_t>(p); p += sizeof(uint16_t);
  425. _vMinor = b.template at<uint16_t>(p); p += sizeof(uint16_t);
  426. _vRevision = b.template at<uint16_t>(p); p += sizeof(uint16_t);
  427. _latency = b.template at<uint16_t>(p); p += sizeof(uint16_t);
  428. unsigned int npaths = (unsigned int)b.template at<uint16_t>(p); p += sizeof(uint16_t);
  429. _paths.clear();
  430. for(unsigned int i=0;i<npaths;++i) {
  431. _paths.push_back(Path());
  432. p += _paths.back().deserialize(b,p);
  433. }
  434. return (p - startAt);
  435. }
  436. private:
  437. unsigned char _key[ZT_PEER_SECRET_KEY_LENGTH];
  438. Identity _id;
  439. std::vector<Path> _paths;
  440. volatile uint64_t _lastUsed;
  441. volatile uint64_t _lastReceive; // direct or indirect
  442. volatile uint64_t _lastUnicastFrame;
  443. volatile uint64_t _lastMulticastFrame;
  444. volatile uint64_t _lastAnnouncedTo;
  445. volatile unsigned int _vMajor;
  446. volatile unsigned int _vMinor;
  447. volatile unsigned int _vRevision;
  448. volatile unsigned int _latency;
  449. Mutex _lock;
  450. AtomicCounter __refCount;
  451. };
  452. } // namespace ZeroTier
  453. // Add a swap() for shared ptr's to peers to speed up peer sorts
  454. namespace std {
  455. template<>
  456. inline void swap(ZeroTier::SharedPtr<ZeroTier::Peer> &a,ZeroTier::SharedPtr<ZeroTier::Peer> &b)
  457. {
  458. a.swap(b);
  459. }
  460. }
  461. #endif