Peer.hpp 14 KB

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