Peer.hpp 13 KB

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