1
0

Peer.hpp 14 KB

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