Peer.hpp 13 KB

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