Peer.hpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565
  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 using one or both active link types
  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. uint64_t now = Utils::now();
  217. uint64_t latestOutstandingReq = 0;
  218. for(unsigned int p=0;p<ZT_PEER_REQUEST_HISTORY_LENGTH;++p)
  219. latestOutstandingReq = std::max(latestOutstandingReq,_requestHistory[p].timestamp);
  220. if (latestOutstandingReq)
  221. return std::min(std::max((unsigned int)(now - latestOutstandingReq),(unsigned int)_latency),(unsigned int)0xffff);
  222. else return _latency;
  223. }
  224. /**
  225. * @return True if this peer has at least one direct IP address path
  226. */
  227. inline bool hasDirectPath() const throw() { return ((_ipv4p.addr)||(_ipv6p.addr)); }
  228. /**
  229. * @param now Current time
  230. * @return True if this peer has at least one active or fixed direct path
  231. */
  232. inline bool hasActiveDirectPath(uint64_t now) const throw() { return ((_ipv4p.isActive(now))||(_ipv6p.isActive(now))); }
  233. /**
  234. * @return IPv4 direct address or null InetAddress if none
  235. */
  236. inline InetAddress ipv4Path() const throw() { return _ipv4p.addr; }
  237. /**
  238. * @return IPv6 direct address or null InetAddress if none
  239. */
  240. inline InetAddress ipv6Path() const throw() { return _ipv4p.addr; }
  241. /**
  242. * @return IPv4 direct address or null InetAddress if none
  243. */
  244. inline InetAddress ipv4ActivePath(uint64_t now) const
  245. throw()
  246. {
  247. if (_ipv4p.isActive(now))
  248. return _ipv4p.addr;
  249. return InetAddress();
  250. }
  251. /**
  252. * @return IPv6 direct address or null InetAddress if none
  253. */
  254. inline InetAddress ipv6ActivePath(uint64_t now) const
  255. throw()
  256. {
  257. if (_ipv6p.isActive(now))
  258. return _ipv6p.addr;
  259. return InetAddress();
  260. }
  261. /**
  262. * Forget direct paths
  263. *
  264. * @param fixedToo If true, also forget 'fixed' paths.
  265. */
  266. inline void forgetDirectPaths(bool fixedToo)
  267. throw()
  268. {
  269. if ((fixedToo)||(!_ipv4p.fixed))
  270. _ipv4p.addr.zero();
  271. if ((fixedToo)||(!_ipv6p.fixed))
  272. _ipv6p.addr.zero();
  273. }
  274. /**
  275. * @return 256-bit secret symmetric encryption key
  276. */
  277. inline const unsigned char *key() const throw() { return _key; }
  278. /**
  279. * Set the remote version of the peer (not persisted)
  280. *
  281. * @param vmaj Major version
  282. * @param vmin Minor version
  283. * @param vrev Revision
  284. */
  285. inline void setRemoteVersion(unsigned int vmaj,unsigned int vmin,unsigned int vrev)
  286. {
  287. _vMajor = vmaj;
  288. _vMinor = vmin;
  289. _vRevision = vrev;
  290. }
  291. /**
  292. * @return Remote version in string form or '?' if unknown
  293. */
  294. inline std::string remoteVersion() const
  295. {
  296. if ((_vMajor)||(_vMinor)||(_vRevision)) {
  297. char tmp[32];
  298. Utils::snprintf(tmp,sizeof(tmp),"%u.%u.%u",_vMajor,_vMinor,_vRevision);
  299. return std::string(tmp);
  300. }
  301. return std::string("?");
  302. }
  303. /**
  304. * Called when certain packet types are sent that expect OK responses
  305. *
  306. * @param packetId ID of sent packet
  307. * @param verb Verb of sent packet
  308. * @param sentFromLocalPort Outgoing local port
  309. * @param now Current time
  310. */
  311. inline void expectResponseTo(uint64_t packetId,Packet::Verb verb,Demarc::Port sentFromLocalPort,uint64_t now)
  312. throw()
  313. {
  314. unsigned int p = _requestHistoryPtr++ % ZT_PEER_REQUEST_HISTORY_LENGTH;
  315. _requestHistory[p].timestamp = now;
  316. _requestHistory[p].packetId = packetId;
  317. _requestHistory[p].localPort = sentFromLocalPort;
  318. _requestHistory[p].verb = verb;
  319. }
  320. /**
  321. * @return True if this Peer is initialized with something
  322. */
  323. inline operator bool() const throw() { return (_id); }
  324. /**
  325. * Find a common set of addresses by which two peers can link, if any
  326. *
  327. * @param a Peer A
  328. * @param b Peer B
  329. * @param now Current time
  330. * @return Pair: B's address to send to A, A's address to send to B
  331. */
  332. static inline std::pair<InetAddress,InetAddress> findCommonGround(const Peer &a,const Peer &b,uint64_t now)
  333. throw()
  334. {
  335. if ((a._ipv6p.isActive(now))&&(b._ipv6p.isActive(now)))
  336. return std::pair<InetAddress,InetAddress>(b._ipv6p.addr,a._ipv6p.addr);
  337. else if ((a._ipv4p.isActive(now))&&(b._ipv4p.isActive(now)))
  338. return std::pair<InetAddress,InetAddress>(b._ipv4p.addr,a._ipv4p.addr);
  339. else if ((a._ipv6p.addr)&&(b._ipv6p.addr))
  340. return std::pair<InetAddress,InetAddress>(b._ipv6p.addr,a._ipv6p.addr);
  341. else if ((a._ipv4p.addr)&&(b._ipv4p.addr))
  342. return std::pair<InetAddress,InetAddress>(b._ipv4p.addr,a._ipv4p.addr);
  343. return std::pair<InetAddress,InetAddress>();
  344. }
  345. template<unsigned int C>
  346. inline void serialize(Buffer<C> &b)
  347. {
  348. b.append((unsigned char)ZT_PEER_SERIALIZATION_VERSION);
  349. b.append(_key,sizeof(_key));
  350. _id.serialize(b,false);
  351. _ipv4p.serialize(b);
  352. _ipv6p.serialize(b);
  353. b.append(_lastUsed);
  354. b.append(_lastUnicastFrame);
  355. b.append(_lastMulticastFrame);
  356. b.append(_lastAnnouncedTo);
  357. b.append((uint16_t)_vMajor);
  358. b.append((uint16_t)_vMinor);
  359. b.append((uint16_t)_vRevision);
  360. b.append((uint16_t)_latency);
  361. }
  362. template<unsigned int C>
  363. inline unsigned int deserialize(const Buffer<C> &b,unsigned int startAt = 0)
  364. {
  365. unsigned int p = startAt;
  366. if (b[p++] != ZT_PEER_SERIALIZATION_VERSION)
  367. throw std::invalid_argument("Peer: deserialize(): version mismatch");
  368. memcpy(_key,b.field(p,sizeof(_key)),sizeof(_key)); p += sizeof(_key);
  369. p += _id.deserialize(b,p);
  370. p += _ipv4p.deserialize(b,p);
  371. p += _ipv6p.deserialize(b,p);
  372. _lastUsed = b.template at<uint64_t>(p); p += sizeof(uint64_t);
  373. _lastUnicastFrame = b.template at<uint64_t>(p); p += sizeof(uint64_t);
  374. _lastMulticastFrame = b.template at<uint64_t>(p); p += sizeof(uint64_t);
  375. _lastAnnouncedTo = b.template at<uint64_t>(p); p += sizeof(uint64_t);
  376. _vMajor = b.template at<uint16_t>(p); p += sizeof(uint16_t);
  377. _vMinor = b.template at<uint16_t>(p); p += sizeof(uint16_t);
  378. _vRevision = b.template at<uint16_t>(p); p += sizeof(uint16_t);
  379. _latency = b.template at<uint16_t>(p); p += sizeof(uint16_t);
  380. return (p - startAt);
  381. }
  382. private:
  383. /**
  384. * A direct IP path to a peer
  385. */
  386. class WanPath
  387. {
  388. public:
  389. WanPath() :
  390. lastSend(0),
  391. lastReceive(0),
  392. lastFirewallOpener(0),
  393. localPort(Demarc::ANY_PORT),
  394. addr(),
  395. fixed(false)
  396. {
  397. }
  398. inline bool isActive(const uint64_t now) const
  399. throw()
  400. {
  401. return ((addr)&&((fixed)||((now - lastReceive) < ZT_PEER_LINK_ACTIVITY_TIMEOUT)));
  402. }
  403. template<unsigned int C>
  404. inline void serialize(Buffer<C> &b)
  405. throw(std::out_of_range)
  406. {
  407. b.append(lastSend);
  408. b.append(lastReceive);
  409. b.append(lastFirewallOpener);
  410. b.append(Demarc::portToInt(localPort));
  411. b.append((unsigned char)addr.type());
  412. switch(addr.type()) {
  413. case InetAddress::TYPE_NULL:
  414. break;
  415. case InetAddress::TYPE_IPV4:
  416. b.append(addr.rawIpData(),4);
  417. b.append((uint16_t)addr.port());
  418. break;
  419. case InetAddress::TYPE_IPV6:
  420. b.append(addr.rawIpData(),16);
  421. b.append((uint16_t)addr.port());
  422. break;
  423. }
  424. b.append(fixed ? (unsigned char)1 : (unsigned char)0);
  425. }
  426. template<unsigned int C>
  427. inline unsigned int deserialize(const Buffer<C> &b,unsigned int startAt = 0)
  428. throw(std::out_of_range,std::invalid_argument)
  429. {
  430. unsigned int p = startAt;
  431. lastSend = b.template at<uint64_t>(p); p += sizeof(uint64_t);
  432. lastReceive = b.template at<uint64_t>(p); p += sizeof(uint64_t);
  433. lastFirewallOpener = b.template at<uint64_t>(p); p += sizeof(uint64_t);
  434. localPort = Demarc::intToPort(b.template at<uint64_t>(p)); p += sizeof(uint64_t);
  435. switch ((InetAddress::AddressType)b[p++]) {
  436. case InetAddress::TYPE_NULL:
  437. addr.zero();
  438. break;
  439. case InetAddress::TYPE_IPV4:
  440. addr.set(b.field(p,4),4,b.template at<uint16_t>(p + 4));
  441. p += 4 + sizeof(uint16_t);
  442. break;
  443. case InetAddress::TYPE_IPV6:
  444. addr.set(b.field(p,16),16,b.template at<uint16_t>(p + 16));
  445. p += 16 + sizeof(uint16_t);
  446. break;
  447. }
  448. fixed = (b[p++] != 0);
  449. return (p - startAt);
  450. }
  451. uint64_t lastSend;
  452. uint64_t lastReceive;
  453. uint64_t lastFirewallOpener;
  454. Demarc::Port localPort; // ANY_PORT if not defined (size: uint64_t)
  455. InetAddress addr; // null InetAddress if path is undefined
  456. bool fixed; // do not learn address from received packets
  457. };
  458. /**
  459. * A history of a packet sent to a peer expecing a response (e.g. HELLO)
  460. */
  461. class RequestHistoryItem
  462. {
  463. public:
  464. RequestHistoryItem() :
  465. timestamp(0),
  466. packetId(0),
  467. verb(Packet::VERB_NOP)
  468. {
  469. }
  470. uint64_t timestamp;
  471. uint64_t packetId;
  472. Demarc::Port localPort;
  473. Packet::Verb verb;
  474. };
  475. unsigned char _key[ZT_PEER_SECRET_KEY_LENGTH];
  476. Identity _id;
  477. WanPath _ipv4p;
  478. WanPath _ipv6p;
  479. volatile uint64_t _lastUsed;
  480. volatile uint64_t _lastUnicastFrame;
  481. volatile uint64_t _lastMulticastFrame;
  482. volatile uint64_t _lastAnnouncedTo;
  483. unsigned int _vMajor,_vMinor,_vRevision;
  484. volatile unsigned int _latency;
  485. // not persisted
  486. RequestHistoryItem _requestHistory[ZT_PEER_REQUEST_HISTORY_LENGTH];
  487. volatile unsigned int _requestHistoryPtr;
  488. AtomicCounter __refCount;
  489. };
  490. } // namespace ZeroTier
  491. // Add a swap() for shared ptr's to peers to speed up peer sorts
  492. namespace std {
  493. template<>
  494. inline void swap(ZeroTier::SharedPtr<ZeroTier::Peer> &a,ZeroTier::SharedPtr<ZeroTier::Peer> &b)
  495. {
  496. a.swap(b);
  497. }
  498. }
  499. #endif