Peer.hpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534
  1. /*
  2. * ZeroTier One - Global Peer to Peer Ethernet
  3. * Copyright (C) 2012-2013 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 <algorithm>
  31. #include <utility>
  32. #include <stdexcept>
  33. #include "Constants.hpp"
  34. #include "Address.hpp"
  35. #include "Utils.hpp"
  36. #include "Identity.hpp"
  37. #include "Logger.hpp"
  38. #include "Demarc.hpp"
  39. #include "RuntimeEnvironment.hpp"
  40. #include "InetAddress.hpp"
  41. #include "Packet.hpp"
  42. #include "SharedPtr.hpp"
  43. #include "AtomicCounter.hpp"
  44. #include "NonCopyable.hpp"
  45. #include "Mutex.hpp"
  46. // Increment if serialization has changed
  47. #define ZT_PEER_SERIALIZATION_VERSION 6
  48. namespace ZeroTier {
  49. /**
  50. * A peer on the network
  51. *
  52. * Threading note:
  53. *
  54. * This structure contains no locks at the moment, but also performs no
  55. * memory allocation or pointer manipulation. As a result is is technically
  56. * "safe" for threads, as in won't crash. Right now it's only changed from
  57. * the core I/O thread so this isn't an issue. If multiple I/O threads are
  58. * introduced it ought to have a lock of some kind.
  59. */
  60. class Peer : NonCopyable
  61. {
  62. friend class SharedPtr<Peer>;
  63. private:
  64. ~Peer() {}
  65. public:
  66. Peer();
  67. /**
  68. * Construct a new peer
  69. *
  70. * @param myIdentity Identity of THIS node (for key agreement)
  71. * @param peerIdentity Identity of peer
  72. * @throws std::runtime_error Key agreement with peer's identity failed
  73. */
  74. Peer(const Identity &myIdentity,const Identity &peerIdentity)
  75. throw(std::runtime_error);
  76. /**
  77. * @return Time peer record was last used in any way
  78. */
  79. inline uint64_t lastUsed() const throw() { return _lastUsed; }
  80. /**
  81. * @param now New time of last use
  82. */
  83. inline void setLastUsed(uint64_t now) throw() { _lastUsed = now; }
  84. /**
  85. * @return This peer's ZT address (short for identity().address())
  86. */
  87. inline const Address &address() const throw() { return _id.address(); }
  88. /**
  89. * @return This peer's identity
  90. */
  91. inline const Identity &identity() const throw() { return _id; }
  92. /**
  93. * Must be called on authenticated packet receive from this peer
  94. *
  95. * @param _r Runtime environment
  96. * @param localPort Local port on 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 onReceive(
  106. const RuntimeEnvironment *_r,
  107. Demarc::Port localPort,
  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 UDP packet to this peer directly (not via relaying)
  117. *
  118. * @param _r Runtime environment
  119. * @param data Data to send
  120. * @param len Length of packet
  121. * @param now Current time
  122. * @return NULL_PORT or port packet was sent from
  123. */
  124. Demarc::Port send(const RuntimeEnvironment *_r,const void *data,unsigned int len,uint64_t now);
  125. /**
  126. * Send firewall opener to active link
  127. *
  128. * @param _r Runtime environment
  129. * @param now Current time
  130. * @return True if send appears successful for at least one address type
  131. */
  132. bool sendFirewallOpener(const RuntimeEnvironment *_r,uint64_t now);
  133. /**
  134. * Send HELLO to a peer via all active direct paths available
  135. *
  136. * @param _r Runtime environment
  137. * @param now Current time
  138. * @return True if send appears successful for at least one address type
  139. */
  140. bool sendPing(const RuntimeEnvironment *_r,uint64_t now);
  141. /**
  142. * Set an address to reach this peer
  143. *
  144. * @param addr Address to set
  145. * @param fixed If true, address is fixed (won't be changed on packet receipt)
  146. */
  147. void setPathAddress(const InetAddress &addr,bool fixed);
  148. /**
  149. * Clear the fixed flag for an address type
  150. *
  151. * @param t Type to clear, or TYPE_NULL to clear flag on all types
  152. */
  153. void clearFixedFlag(InetAddress::AddressType t);
  154. /**
  155. * @return Last successfully sent firewall opener
  156. */
  157. inline uint64_t lastFirewallOpener() const
  158. throw()
  159. {
  160. return std::max(_ipv4p.lastFirewallOpener,_ipv6p.lastFirewallOpener);
  161. }
  162. /**
  163. * @return Time of last direct packet receive
  164. */
  165. inline uint64_t lastDirectReceive() const
  166. throw()
  167. {
  168. return std::max(_ipv4p.lastReceive,_ipv6p.lastReceive);
  169. }
  170. /**
  171. * @return Time of last direct packet send
  172. */
  173. inline uint64_t lastDirectSend() const
  174. throw()
  175. {
  176. return std::max(_ipv4p.lastSend,_ipv6p.lastSend);
  177. }
  178. /**
  179. * @return Time of most recent unicast frame received
  180. */
  181. inline uint64_t lastUnicastFrame() const
  182. throw()
  183. {
  184. return _lastUnicastFrame;
  185. }
  186. /**
  187. * @return Time of most recent multicast frame received
  188. */
  189. inline uint64_t lastMulticastFrame() const
  190. throw()
  191. {
  192. return _lastMulticastFrame;
  193. }
  194. /**
  195. * @return Time of most recent frame of any kind (unicast or multicast)
  196. */
  197. inline uint64_t lastFrame() const
  198. throw()
  199. {
  200. return std::max(_lastUnicastFrame,_lastMulticastFrame);
  201. }
  202. /**
  203. * @return Time we last announced state TO this peer, such as multicast LIKEs
  204. */
  205. inline uint64_t lastAnnouncedTo() const
  206. throw()
  207. {
  208. return _lastAnnouncedTo;
  209. }
  210. /**
  211. * @return Current latency or 0 if unknown (max: 65535)
  212. */
  213. inline unsigned int latency() const
  214. throw()
  215. {
  216. unsigned int l = _latency;
  217. return std::min(l,(unsigned int)65535);
  218. }
  219. /**
  220. * Update latency with a new direct measurment
  221. *
  222. * @param l Direct latency measurment in ms
  223. */
  224. inline void addDirectLatencyMeasurment(unsigned int l)
  225. throw()
  226. {
  227. if (l > 65535) l = 65535;
  228. unsigned int ol = _latency;
  229. if ((ol > 0)&&(ol < 10000))
  230. _latency = (ol + l) / 2;
  231. else _latency = l;
  232. }
  233. /**
  234. * @return True if this peer has at least one direct IP address path
  235. */
  236. inline bool hasDirectPath() const throw() { return ((_ipv4p.addr)||(_ipv6p.addr)); }
  237. /**
  238. * @param now Current time
  239. * @return True if this peer has at least one active or fixed direct path
  240. */
  241. inline bool hasActiveDirectPath(uint64_t now) const throw() { return ((_ipv4p.isActive(now))||(_ipv6p.isActive(now))); }
  242. /**
  243. * @return IPv4 direct address or null InetAddress if none
  244. */
  245. inline InetAddress ipv4Path() const throw() { return _ipv4p.addr; }
  246. /**
  247. * @return IPv6 direct address or null InetAddress if none
  248. */
  249. inline InetAddress ipv6Path() const throw() { return _ipv4p.addr; }
  250. /**
  251. * @return IPv4 direct address or null InetAddress if none
  252. */
  253. inline InetAddress ipv4ActivePath(uint64_t now) const
  254. throw()
  255. {
  256. if (_ipv4p.isActive(now))
  257. return _ipv4p.addr;
  258. return InetAddress();
  259. }
  260. /**
  261. * @return IPv6 direct address or null InetAddress if none
  262. */
  263. inline InetAddress ipv6ActivePath(uint64_t now) const
  264. throw()
  265. {
  266. if (_ipv6p.isActive(now))
  267. return _ipv6p.addr;
  268. return InetAddress();
  269. }
  270. /**
  271. * Forget direct paths
  272. *
  273. * @param fixedToo If true, also forget 'fixed' paths.
  274. */
  275. inline void forgetDirectPaths(bool fixedToo)
  276. throw()
  277. {
  278. if ((fixedToo)||(!_ipv4p.fixed))
  279. _ipv4p.addr.zero();
  280. if ((fixedToo)||(!_ipv6p.fixed))
  281. _ipv6p.addr.zero();
  282. }
  283. /**
  284. * @return 256-bit secret symmetric encryption key
  285. */
  286. inline const unsigned char *key() const throw() { return _key; }
  287. /**
  288. * Set the currently known remote version of this peer's client
  289. *
  290. * @param vmaj Major version
  291. * @param vmin Minor version
  292. * @param vrev Revision
  293. */
  294. inline void setRemoteVersion(unsigned int vmaj,unsigned int vmin,unsigned int vrev)
  295. {
  296. _vMajor = vmaj;
  297. _vMinor = vmin;
  298. _vRevision = vrev;
  299. }
  300. /**
  301. * @return Remote version in string form or '?' if unknown
  302. */
  303. inline std::string remoteVersion() const
  304. {
  305. if ((_vMajor)||(_vMinor)||(_vRevision)) {
  306. char tmp[32];
  307. Utils::snprintf(tmp,sizeof(tmp),"%u.%u.%u",_vMajor,_vMinor,_vRevision);
  308. return std::string(tmp);
  309. }
  310. return std::string("?");
  311. }
  312. /**
  313. * @return True if this Peer is initialized with something
  314. */
  315. inline operator bool() const throw() { return (_id); }
  316. /**
  317. * Find a common set of addresses by which two peers can link, if any
  318. *
  319. * @param a Peer A
  320. * @param b Peer B
  321. * @param now Current time
  322. * @return Pair: B's address to send to A, A's address to send to B
  323. */
  324. static inline std::pair<InetAddress,InetAddress> findCommonGround(const Peer &a,const Peer &b,uint64_t now)
  325. throw()
  326. {
  327. if ((a._ipv6p.isActive(now))&&(b._ipv6p.isActive(now)))
  328. return std::pair<InetAddress,InetAddress>(b._ipv6p.addr,a._ipv6p.addr);
  329. else if ((a._ipv4p.isActive(now))&&(b._ipv4p.isActive(now)))
  330. return std::pair<InetAddress,InetAddress>(b._ipv4p.addr,a._ipv4p.addr);
  331. else if ((a._ipv6p.addr)&&(b._ipv6p.addr))
  332. return std::pair<InetAddress,InetAddress>(b._ipv6p.addr,a._ipv6p.addr);
  333. else if ((a._ipv4p.addr)&&(b._ipv4p.addr))
  334. return std::pair<InetAddress,InetAddress>(b._ipv4p.addr,a._ipv4p.addr);
  335. return std::pair<InetAddress,InetAddress>();
  336. }
  337. template<unsigned int C>
  338. inline void serialize(Buffer<C> &b)
  339. {
  340. b.append((unsigned char)ZT_PEER_SERIALIZATION_VERSION);
  341. b.append(_key,sizeof(_key));
  342. _id.serialize(b,false);
  343. _ipv4p.serialize(b);
  344. _ipv6p.serialize(b);
  345. b.append(_lastUsed);
  346. b.append(_lastUnicastFrame);
  347. b.append(_lastMulticastFrame);
  348. b.append(_lastAnnouncedTo);
  349. b.append((uint16_t)_vMajor);
  350. b.append((uint16_t)_vMinor);
  351. b.append((uint16_t)_vRevision);
  352. b.append((uint16_t)_latency);
  353. }
  354. template<unsigned int C>
  355. inline unsigned int deserialize(const Buffer<C> &b,unsigned int startAt = 0)
  356. {
  357. unsigned int p = startAt;
  358. if (b[p++] != ZT_PEER_SERIALIZATION_VERSION)
  359. throw std::invalid_argument("Peer: deserialize(): version mismatch");
  360. memcpy(_key,b.field(p,sizeof(_key)),sizeof(_key)); p += sizeof(_key);
  361. p += _id.deserialize(b,p);
  362. p += _ipv4p.deserialize(b,p);
  363. p += _ipv6p.deserialize(b,p);
  364. _lastUsed = b.template at<uint64_t>(p); p += sizeof(uint64_t);
  365. _lastUnicastFrame = b.template at<uint64_t>(p); p += sizeof(uint64_t);
  366. _lastMulticastFrame = b.template at<uint64_t>(p); p += sizeof(uint64_t);
  367. _lastAnnouncedTo = b.template at<uint64_t>(p); p += sizeof(uint64_t);
  368. _vMajor = b.template at<uint16_t>(p); p += sizeof(uint16_t);
  369. _vMinor = b.template at<uint16_t>(p); p += sizeof(uint16_t);
  370. _vRevision = b.template at<uint16_t>(p); p += sizeof(uint16_t);
  371. _latency = b.template at<uint16_t>(p); p += sizeof(uint16_t);
  372. return (p - startAt);
  373. }
  374. private:
  375. /**
  376. * A direct IP path to a peer
  377. */
  378. class WanPath
  379. {
  380. public:
  381. WanPath() :
  382. lastSend(0),
  383. lastReceive(0),
  384. lastFirewallOpener(0),
  385. localPort(Demarc::ANY_PORT),
  386. addr(),
  387. fixed(false)
  388. {
  389. }
  390. inline bool isActive(const uint64_t now) const
  391. throw()
  392. {
  393. return ((addr)&&((fixed)||((now - lastReceive) < ZT_PEER_LINK_ACTIVITY_TIMEOUT)));
  394. }
  395. template<unsigned int C>
  396. inline void serialize(Buffer<C> &b)
  397. throw(std::out_of_range)
  398. {
  399. b.append(lastSend);
  400. b.append(lastReceive);
  401. b.append(lastFirewallOpener);
  402. b.append(Demarc::portToInt(localPort));
  403. b.append((unsigned char)addr.type());
  404. switch(addr.type()) {
  405. case InetAddress::TYPE_NULL:
  406. break;
  407. case InetAddress::TYPE_IPV4:
  408. b.append(addr.rawIpData(),4);
  409. b.append((uint16_t)addr.port());
  410. break;
  411. case InetAddress::TYPE_IPV6:
  412. b.append(addr.rawIpData(),16);
  413. b.append((uint16_t)addr.port());
  414. break;
  415. }
  416. b.append(fixed ? (unsigned char)1 : (unsigned char)0);
  417. }
  418. template<unsigned int C>
  419. inline unsigned int deserialize(const Buffer<C> &b,unsigned int startAt = 0)
  420. throw(std::out_of_range,std::invalid_argument)
  421. {
  422. unsigned int p = startAt;
  423. lastSend = b.template at<uint64_t>(p); p += sizeof(uint64_t);
  424. lastReceive = b.template at<uint64_t>(p); p += sizeof(uint64_t);
  425. lastFirewallOpener = b.template at<uint64_t>(p); p += sizeof(uint64_t);
  426. localPort = Demarc::intToPort(b.template at<uint64_t>(p)); p += sizeof(uint64_t);
  427. switch ((InetAddress::AddressType)b[p++]) {
  428. case InetAddress::TYPE_NULL:
  429. addr.zero();
  430. break;
  431. case InetAddress::TYPE_IPV4:
  432. addr.set(b.field(p,4),4,b.template at<uint16_t>(p + 4));
  433. p += 4 + sizeof(uint16_t);
  434. break;
  435. case InetAddress::TYPE_IPV6:
  436. addr.set(b.field(p,16),16,b.template at<uint16_t>(p + 16));
  437. p += 16 + sizeof(uint16_t);
  438. break;
  439. }
  440. fixed = (b[p++] != 0);
  441. return (p - startAt);
  442. }
  443. uint64_t lastSend;
  444. uint64_t lastReceive;
  445. uint64_t lastFirewallOpener;
  446. Demarc::Port localPort; // ANY_PORT if not defined (size: uint64_t)
  447. InetAddress addr; // null InetAddress if path is undefined
  448. bool fixed; // do not learn address from received packets
  449. };
  450. unsigned char _key[ZT_PEER_SECRET_KEY_LENGTH];
  451. Identity _id;
  452. WanPath _ipv4p;
  453. WanPath _ipv6p;
  454. volatile uint64_t _lastUsed;
  455. volatile uint64_t _lastUnicastFrame;
  456. volatile uint64_t _lastMulticastFrame;
  457. volatile uint64_t _lastAnnouncedTo;
  458. volatile unsigned int _vMajor,_vMinor,_vRevision;
  459. volatile unsigned int _latency;
  460. AtomicCounter __refCount;
  461. };
  462. } // namespace ZeroTier
  463. // Add a swap() for shared ptr's to peers to speed up peer sorts
  464. namespace std {
  465. template<>
  466. inline void swap(ZeroTier::SharedPtr<ZeroTier::Peer> &a,ZeroTier::SharedPtr<ZeroTier::Peer> &b)
  467. {
  468. a.swap(b);
  469. }
  470. }
  471. #endif