Peer.hpp 15 KB

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