Peer.hpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536
  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
  74. throw()
  75. {
  76. return _lastUsed;
  77. }
  78. /**
  79. * @param now New time of last use
  80. */
  81. inline void use(uint64_t now)
  82. throw()
  83. {
  84. _lastUsed = now;
  85. }
  86. /**
  87. * @return This peer's ZT address (short for identity().address())
  88. */
  89. inline const Address &address() const throw() { return _id.address(); }
  90. /**
  91. * @return This peer's identity
  92. */
  93. inline const Identity &identity() const throw() { return _id; }
  94. /**
  95. * Must be called on authenticated packet receive from this peer
  96. *
  97. * @param _r Runtime environment
  98. * @param fromSock Socket from which packet was received
  99. * @param remoteAddr Internet address of sender
  100. * @param hops ZeroTier (not IP) hops
  101. * @param packetId Packet ID
  102. * @param verb Packet verb
  103. * @param inRePacketId Packet ID in reply to (for OK/ERROR, 0 otherwise)
  104. * @param inReVerb Verb in reply to (for OK/ERROR, VERB_NOP otherwise)
  105. * @param now Current time
  106. */
  107. void receive(
  108. const RuntimeEnvironment *_r,
  109. const SharedPtr<Socket> &fromSock,
  110. const InetAddress &remoteAddr,
  111. unsigned int hops,
  112. uint64_t packetId,
  113. Packet::Verb verb,
  114. uint64_t inRePacketId,
  115. Packet::Verb inReVerb,
  116. uint64_t now);
  117. /**
  118. * Send a packet to this peer using the most recently active direct path
  119. *
  120. * This does not relay. It returns false if there are no available active
  121. * paths.
  122. *
  123. * @param _r Runtime environment
  124. * @param data Data to send
  125. * @param len Length of packet
  126. * @param now Current time
  127. * @return True if packet appears to have been sent, false if no path or other error
  128. */
  129. bool send(const RuntimeEnvironment *_r,const void *data,unsigned int len,uint64_t now);
  130. /**
  131. * Send firewall opener to all UDP paths
  132. *
  133. * @param _r Runtime environment
  134. * @param now Current time
  135. * @return True if send appears successful for at least one address type
  136. */
  137. bool sendFirewallOpener(const RuntimeEnvironment *_r,uint64_t now);
  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. * @return Last successfully sent firewall opener for any path
  163. */
  164. inline uint64_t lastFirewallOpener() const
  165. throw()
  166. {
  167. uint64_t x = 0;
  168. Mutex::Lock _l(_lock);
  169. for(std::vector<Path>::const_iterator p(_paths.begin());p!=_paths.end();++p) {
  170. uint64_t l = p->lastFirewallOpener();
  171. if (l > x)
  172. x = l;
  173. }
  174. return x;
  175. }
  176. /**
  177. * @return Time of last direct packet receive for any path
  178. */
  179. inline uint64_t lastDirectReceive() const
  180. throw()
  181. {
  182. uint64_t x = 0;
  183. Mutex::Lock _l(_lock);
  184. for(std::vector<Path>::const_iterator p(_paths.begin());p!=_paths.end();++p) {
  185. uint64_t l = p->lastReceived();
  186. if (l > x)
  187. x = l;
  188. }
  189. return x;
  190. }
  191. /**
  192. * @return Time of last direct packet send for any path
  193. */
  194. inline uint64_t lastDirectSend() const
  195. throw()
  196. {
  197. uint64_t x = 0;
  198. Mutex::Lock _l(_lock);
  199. for(std::vector<Path>::const_iterator p(_paths.begin());p!=_paths.end();++p) {
  200. uint64_t l = p->lastSend();
  201. if (l > x)
  202. x = l;
  203. }
  204. return x;
  205. }
  206. /**
  207. * @param _r Runtime environment
  208. * @param now Current time
  209. * @return True if the last ping is unanswered
  210. */
  211. inline bool pingUnanswered(const RuntimeEnvironment *_r,uint64_t now)
  212. throw()
  213. {
  214. uint64_t lp = 0;
  215. uint64_t lr = 0;
  216. {
  217. Mutex::Lock _l(_lock);
  218. for(std::vector<Path>::const_iterator p(_paths.begin());p!=_paths.end();++p) {
  219. lp = std::max(p->lastPing(),lp);
  220. lr = std::max(p->lastReceived(),lr);
  221. }
  222. }
  223. return ( (lp > _r->timeOfLastResynchronize) && ((lr < lp)&&((lp - lr) >= ZT_PING_UNANSWERED_AFTER)) );
  224. }
  225. /**
  226. * @return Time of most recent unicast frame received
  227. */
  228. inline uint64_t lastUnicastFrame() const
  229. throw()
  230. {
  231. return _lastUnicastFrame;
  232. }
  233. /**
  234. * @return Time of most recent multicast frame received
  235. */
  236. inline uint64_t lastMulticastFrame() const
  237. throw()
  238. {
  239. return _lastMulticastFrame;
  240. }
  241. /**
  242. * @return Time of most recent frame of any kind (unicast or multicast)
  243. */
  244. inline uint64_t lastFrame() const
  245. throw()
  246. {
  247. return std::max(_lastUnicastFrame,_lastMulticastFrame);
  248. }
  249. /**
  250. * @return Time we last announced state TO this peer, such as multicast LIKEs
  251. */
  252. inline uint64_t lastAnnouncedTo() const
  253. throw()
  254. {
  255. return _lastAnnouncedTo;
  256. }
  257. /**
  258. * @return Current latency or 0 if unknown (max: 65535)
  259. */
  260. inline unsigned int latency() const
  261. throw()
  262. {
  263. unsigned int l = _latency;
  264. return std::min(l,(unsigned int)65535);
  265. }
  266. /**
  267. * Update latency with a new direct measurment
  268. *
  269. * @param l Direct latency measurment in ms
  270. */
  271. inline void addDirectLatencyMeasurment(unsigned int l)
  272. throw()
  273. {
  274. if (l > 65535) l = 65535;
  275. unsigned int ol = _latency;
  276. if ((ol > 0)&&(ol < 10000))
  277. _latency = (ol + l) / 2;
  278. else _latency = l;
  279. }
  280. /**
  281. * @return True if this peer has at least one direct IP address path
  282. */
  283. inline bool hasDirectPath() const
  284. throw()
  285. {
  286. Mutex::Lock _l(_lock);
  287. return (!_paths.empty());
  288. }
  289. /**
  290. * @param now Current time
  291. * @return True if this peer has at least one active or fixed direct path
  292. */
  293. inline bool hasActiveDirectPath(uint64_t now) const
  294. throw()
  295. {
  296. Mutex::Lock _l(_lock);
  297. for(std::vector<Path>::const_iterator p(_paths.begin());p!=_paths.end();++p) {
  298. if (p->active(now))
  299. return true;
  300. }
  301. return false;
  302. }
  303. /**
  304. * Add a path (if we don't already have it)
  305. *
  306. * @param p New path to add
  307. */
  308. inline void addPath(const Path &newp)
  309. {
  310. Mutex::Lock _l(_lock);
  311. for(std::vector<Path>::iterator p(_paths.begin());p!=_paths.end();++p) {
  312. if (*p == newp) {
  313. p->setFixed(newp.fixed());
  314. return;
  315. }
  316. }
  317. _paths.push_back(newp);
  318. }
  319. /**
  320. * Clear paths
  321. *
  322. * @param fixedToo If true, clear fixed paths as well as learned ones
  323. */
  324. inline void clearPaths(bool fixedToo)
  325. {
  326. std::vector<Path> npv;
  327. Mutex::Lock _l(_lock);
  328. if (!fixedToo) {
  329. for(std::vector<Path>::const_iterator p(_paths.begin());p!=_paths.end();++p) {
  330. if (p->fixed())
  331. npv.push_back(*p);
  332. }
  333. }
  334. _paths = npv;
  335. }
  336. /**
  337. * @return 256-bit secret symmetric encryption key
  338. */
  339. inline const unsigned char *key() const throw() { return _key; }
  340. /**
  341. * Set the currently known remote version of this peer's client
  342. *
  343. * @param vmaj Major version
  344. * @param vmin Minor version
  345. * @param vrev Revision
  346. */
  347. inline void setRemoteVersion(unsigned int vmaj,unsigned int vmin,unsigned int vrev)
  348. {
  349. _vMajor = vmaj;
  350. _vMinor = vmin;
  351. _vRevision = vrev;
  352. }
  353. /**
  354. * @return Remote version in string form or '?' if unknown
  355. */
  356. inline std::string remoteVersion() const
  357. {
  358. if ((_vMajor)||(_vMinor)||(_vRevision)) {
  359. char tmp[32];
  360. Utils::snprintf(tmp,sizeof(tmp),"%u.%u.%u",_vMajor,_vMinor,_vRevision);
  361. return std::string(tmp);
  362. }
  363. return std::string("?");
  364. }
  365. /**
  366. * @return True if this Peer is initialized with something
  367. */
  368. inline operator bool() const throw() { return (_id); }
  369. /**
  370. * @param now Current time
  371. * @param v4 Result parameter to receive active IPv4 address, if any
  372. * @param v6 Result parameter to receive active IPv6 address, if any
  373. */
  374. inline void getActiveUdpPathAddresses(uint64_t now,InetAddress &v4,InetAddress &v6) const
  375. {
  376. bool gotV4 = false,gotV6 = false;
  377. Mutex::Lock _l(_lock);
  378. for(std::vector<Path>::const_iterator p(_paths.begin());p!=_paths.end();++p) {
  379. if (!gotV4) {
  380. if ((!p->tcp())&&(p->address().isV4())&&(p->active(now))) {
  381. gotV4 = true;
  382. v4 = p->address();
  383. }
  384. } else if (!gotV6) {
  385. if ((!p->tcp())&&(p->address().isV6())&&(p->active(now))) {
  386. gotV6 = true;
  387. v6 = p->address();
  388. }
  389. } else break;
  390. }
  391. }
  392. /**
  393. * Find a common set of addresses by which two peers can link, if any
  394. *
  395. * @param a Peer A
  396. * @param b Peer B
  397. * @param now Current time
  398. * @return Pair: B's address (to send to A), A's address (to send to B)
  399. */
  400. static inline std::pair<InetAddress,InetAddress> findCommonGround(const Peer &a,const Peer &b,uint64_t now)
  401. throw()
  402. {
  403. std::pair<InetAddress,InetAddress> v4,v6;
  404. b.getActiveUdpPathAddresses(now,v4.first,v6.first);
  405. a.getActiveUdpPathAddresses(now,v4.second,v6.second);
  406. if ((v6.first)&&(v6.second))
  407. return v6;
  408. if ((v4.first)&&(v4.second))
  409. return v4;
  410. return std::pair<InetAddress,InetAddress>();
  411. }
  412. template<unsigned int C>
  413. inline void serialize(Buffer<C> &b) const
  414. {
  415. Mutex::Lock _l(_lock);
  416. b.append((unsigned char)ZT_PEER_SERIALIZATION_VERSION);
  417. _id.serialize(b,false);
  418. b.append(_key,sizeof(_key));
  419. b.append(_lastUsed);
  420. b.append(_lastUnicastFrame);
  421. b.append(_lastMulticastFrame);
  422. b.append(_lastAnnouncedTo);
  423. b.append((uint16_t)_vMajor);
  424. b.append((uint16_t)_vMinor);
  425. b.append((uint16_t)_vRevision);
  426. b.append((uint16_t)_latency);
  427. b.append((uint16_t)_paths.size());
  428. for(std::vector<Path>::const_iterator p(_paths.begin());p!=_paths.end();++p)
  429. p->serialize(b);
  430. }
  431. template<unsigned int C>
  432. inline unsigned int deserialize(const Buffer<C> &b,unsigned int startAt = 0)
  433. {
  434. unsigned int p = startAt;
  435. if (b[p++] != ZT_PEER_SERIALIZATION_VERSION)
  436. throw std::invalid_argument("Peer: deserialize(): version mismatch");
  437. Mutex::Lock _l(_lock);
  438. p += _id.deserialize(b,p);
  439. memcpy(_key,b.field(p,sizeof(_key)),sizeof(_key)); p += sizeof(_key);
  440. _lastUsed = b.template at<uint64_t>(p); p += sizeof(uint64_t);
  441. _lastUnicastFrame = b.template at<uint64_t>(p); p += sizeof(uint64_t);
  442. _lastMulticastFrame = b.template at<uint64_t>(p); p += sizeof(uint64_t);
  443. _lastAnnouncedTo = b.template at<uint64_t>(p); p += sizeof(uint64_t);
  444. _vMajor = b.template at<uint16_t>(p); p += sizeof(uint16_t);
  445. _vMinor = b.template at<uint16_t>(p); p += sizeof(uint16_t);
  446. _vRevision = b.template at<uint16_t>(p); p += sizeof(uint16_t);
  447. _latency = b.template at<uint16_t>(p); p += sizeof(uint16_t);
  448. unsigned int npaths = (unsigned int)b.template at<uint16_t>(p); p += sizeof(uint16_t);
  449. _paths.clear();
  450. for(unsigned int i=0;i<npaths;++i) {
  451. _paths.push_back(Path());
  452. p += _paths.back().deserialize(b,p);
  453. }
  454. return (p - startAt);
  455. }
  456. private:
  457. bool _isTcpFailoverTime(const RuntimeEnvironment *_r,uint64_t now) const
  458. throw();
  459. unsigned char _key[ZT_PEER_SECRET_KEY_LENGTH];
  460. Identity _id;
  461. std::vector<Path> _paths;
  462. volatile uint64_t _lastUsed;
  463. volatile uint64_t _lastUnicastFrame;
  464. volatile uint64_t _lastMulticastFrame;
  465. volatile uint64_t _lastAnnouncedTo;
  466. volatile unsigned int _vMajor;
  467. volatile unsigned int _vMinor;
  468. volatile unsigned int _vRevision;
  469. volatile unsigned int _latency;
  470. Mutex _lock;
  471. AtomicCounter __refCount;
  472. };
  473. } // namespace ZeroTier
  474. // Add a swap() for shared ptr's to peers to speed up peer sorts
  475. namespace std {
  476. template<>
  477. inline void swap(ZeroTier::SharedPtr<ZeroTier::Peer> &a,ZeroTier::SharedPtr<ZeroTier::Peer> &b)
  478. {
  479. a.swap(b);
  480. }
  481. }
  482. #endif