Peer.hpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499
  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 8
  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 most recent unicast frame received
  225. */
  226. inline uint64_t lastUnicastFrame() const throw() { return _lastUnicastFrame; }
  227. /**
  228. * @return Time of most recent multicast frame received
  229. */
  230. inline uint64_t lastMulticastFrame() const throw() { return _lastMulticastFrame; }
  231. /**
  232. * @return Time of most recent frame of any kind (unicast or multicast)
  233. */
  234. inline uint64_t lastFrame() const throw() { return std::max(_lastUnicastFrame,_lastMulticastFrame); }
  235. /**
  236. * @return Time we last announced state TO this peer, such as multicast LIKEs
  237. */
  238. inline uint64_t lastAnnouncedTo() const throw() { return _lastAnnouncedTo; }
  239. /**
  240. * @return Current latency or 0 if unknown (max: 65535)
  241. */
  242. inline unsigned int latency() const
  243. throw()
  244. {
  245. unsigned int l = _latency;
  246. return std::min(l,(unsigned int)65535);
  247. }
  248. /**
  249. * Update latency with a new direct measurment
  250. *
  251. * @param l Direct latency measurment in ms
  252. */
  253. inline void addDirectLatencyMeasurment(unsigned int l)
  254. throw()
  255. {
  256. unsigned int ol = _latency;
  257. if ((ol > 0)&&(ol < 10000))
  258. _latency = (ol + std::min(l,(unsigned int)65535)) / 2;
  259. else _latency = std::min(l,(unsigned int)65535);
  260. }
  261. /**
  262. * @return True if this peer has at least one direct IP address path
  263. */
  264. inline bool hasDirectPath() const
  265. throw()
  266. {
  267. Mutex::Lock _l(_lock);
  268. return (!_paths.empty());
  269. }
  270. /**
  271. * @param now Current time
  272. * @return True if this peer has at least one active or fixed direct path
  273. */
  274. inline bool hasActiveDirectPath(uint64_t now) const
  275. throw()
  276. {
  277. Mutex::Lock _l(_lock);
  278. for(std::vector<Path>::const_iterator p(_paths.begin());p!=_paths.end();++p) {
  279. if (p->active(now))
  280. return true;
  281. }
  282. return false;
  283. }
  284. /**
  285. * Add a path (if we don't already have it)
  286. *
  287. * @param p New path to add
  288. */
  289. inline void addPath(const Path &newp)
  290. {
  291. Mutex::Lock _l(_lock);
  292. for(std::vector<Path>::iterator p(_paths.begin());p!=_paths.end();++p) {
  293. if (*p == newp) {
  294. p->setFixed(newp.fixed());
  295. return;
  296. }
  297. }
  298. _paths.push_back(newp);
  299. }
  300. /**
  301. * Clear paths
  302. *
  303. * @param fixedToo If true, clear fixed paths as well as learned ones
  304. */
  305. inline void clearPaths(bool fixedToo)
  306. {
  307. std::vector<Path> npv;
  308. Mutex::Lock _l(_lock);
  309. if (!fixedToo) {
  310. for(std::vector<Path>::const_iterator p(_paths.begin());p!=_paths.end();++p) {
  311. if (p->fixed())
  312. npv.push_back(*p);
  313. }
  314. }
  315. _paths = npv;
  316. }
  317. /**
  318. * @return 256-bit secret symmetric encryption key
  319. */
  320. inline const unsigned char *key() const throw() { return _key; }
  321. /**
  322. * Set the currently known remote version of this peer's client
  323. *
  324. * @param vmaj Major version
  325. * @param vmin Minor version
  326. * @param vrev Revision
  327. */
  328. inline void setRemoteVersion(unsigned int vmaj,unsigned int vmin,unsigned int vrev)
  329. throw()
  330. {
  331. _vMajor = vmaj;
  332. _vMinor = vmin;
  333. _vRevision = vrev;
  334. }
  335. /**
  336. * @return Remote version in string form or '?' if unknown
  337. */
  338. inline std::string remoteVersion() const
  339. {
  340. if ((_vMajor > 0)||(_vMinor > 0)||(_vRevision > 0)) {
  341. char tmp[32];
  342. Utils::snprintf(tmp,sizeof(tmp),"%u.%u.%u",_vMajor,_vMinor,_vRevision);
  343. return std::string(tmp);
  344. }
  345. return std::string("?.?.?");
  346. }
  347. /**
  348. * Get most recently active UDP path addresses for IPv4 and/or IPv6
  349. *
  350. * Note that v4 and v6 are not modified if they are not found, so
  351. * initialize these to a NULL address to be able to check.
  352. *
  353. * @param now Current time
  354. * @param v4 Result parameter to receive active IPv4 address, if any
  355. * @param v6 Result parameter to receive active IPv6 address, if any
  356. */
  357. void getBestActiveUdpPathAddresses(uint64_t now,InetAddress &v4,InetAddress &v6) const;
  358. /**
  359. * Find a common set of addresses by which two peers can link, if any
  360. *
  361. * @param a Peer A
  362. * @param b Peer B
  363. * @param now Current time
  364. * @return Pair: B's address (to send to A), A's address (to send to B)
  365. */
  366. static inline std::pair<InetAddress,InetAddress> findCommonGround(const Peer &a,const Peer &b,uint64_t now)
  367. {
  368. std::pair<InetAddress,InetAddress> v4,v6;
  369. b.getBestActiveUdpPathAddresses(now,v4.first,v6.first);
  370. a.getBestActiveUdpPathAddresses(now,v4.second,v6.second);
  371. if ((v6.first)&&(v6.second)) // prefer IPv6 if both have it since NAT-t is (almost) unnecessary
  372. return v6;
  373. else if ((v4.first)&&(v4.second))
  374. return v4;
  375. else return std::pair<InetAddress,InetAddress>();
  376. }
  377. template<unsigned int C>
  378. inline void serialize(Buffer<C> &b) const
  379. {
  380. Mutex::Lock _l(_lock);
  381. b.append((unsigned char)ZT_PEER_SERIALIZATION_VERSION);
  382. _id.serialize(b,false);
  383. b.append(_key,sizeof(_key));
  384. b.append(_lastUsed);
  385. b.append(_lastUnicastFrame);
  386. b.append(_lastMulticastFrame);
  387. b.append(_lastAnnouncedTo);
  388. b.append((uint16_t)_vMajor);
  389. b.append((uint16_t)_vMinor);
  390. b.append((uint16_t)_vRevision);
  391. b.append((uint16_t)_latency);
  392. b.append((uint16_t)_paths.size());
  393. for(std::vector<Path>::const_iterator p(_paths.begin());p!=_paths.end();++p)
  394. p->serialize(b);
  395. }
  396. template<unsigned int C>
  397. inline unsigned int deserialize(const Buffer<C> &b,unsigned int startAt = 0)
  398. {
  399. unsigned int p = startAt;
  400. if (b[p++] != ZT_PEER_SERIALIZATION_VERSION)
  401. throw std::invalid_argument("Peer: deserialize(): version mismatch");
  402. Mutex::Lock _l(_lock);
  403. p += _id.deserialize(b,p);
  404. memcpy(_key,b.field(p,sizeof(_key)),sizeof(_key)); p += sizeof(_key);
  405. _lastUsed = b.template at<uint64_t>(p); p += sizeof(uint64_t);
  406. _lastUnicastFrame = b.template at<uint64_t>(p); p += sizeof(uint64_t);
  407. _lastMulticastFrame = b.template at<uint64_t>(p); p += sizeof(uint64_t);
  408. _lastAnnouncedTo = b.template at<uint64_t>(p); p += sizeof(uint64_t);
  409. _vMajor = b.template at<uint16_t>(p); p += sizeof(uint16_t);
  410. _vMinor = b.template at<uint16_t>(p); p += sizeof(uint16_t);
  411. _vRevision = b.template at<uint16_t>(p); p += sizeof(uint16_t);
  412. _latency = b.template at<uint16_t>(p); p += sizeof(uint16_t);
  413. unsigned int npaths = (unsigned int)b.template at<uint16_t>(p); p += sizeof(uint16_t);
  414. _paths.clear();
  415. for(unsigned int i=0;i<npaths;++i) {
  416. _paths.push_back(Path());
  417. p += _paths.back().deserialize(b,p);
  418. }
  419. return (p - startAt);
  420. }
  421. private:
  422. unsigned char _key[ZT_PEER_SECRET_KEY_LENGTH];
  423. Identity _id;
  424. std::vector<Path> _paths;
  425. volatile uint64_t _lastUsed;
  426. volatile uint64_t _lastUnicastFrame;
  427. volatile uint64_t _lastMulticastFrame;
  428. volatile uint64_t _lastAnnouncedTo;
  429. volatile unsigned int _vMajor;
  430. volatile unsigned int _vMinor;
  431. volatile unsigned int _vRevision;
  432. volatile unsigned int _latency;
  433. Mutex _lock;
  434. AtomicCounter __refCount;
  435. };
  436. } // namespace ZeroTier
  437. // Add a swap() for shared ptr's to peers to speed up peer sorts
  438. namespace std {
  439. template<>
  440. inline void swap(ZeroTier::SharedPtr<ZeroTier::Peer> &a,ZeroTier::SharedPtr<ZeroTier::Peer> &b)
  441. {
  442. a.swap(b);
  443. }
  444. }
  445. #endif