Peer.hpp 14 KB

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