Peer.hpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528
  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. const InetAddress &remoteAddr,
  107. unsigned int hops,
  108. uint64_t packetId,
  109. Packet::Verb verb,
  110. uint64_t inRePacketId,
  111. Packet::Verb inReVerb,
  112. uint64_t now);
  113. /**
  114. * Send a UDP packet to this peer directly (not via relaying)
  115. *
  116. * @param _r Runtime environment
  117. * @param data Data to send
  118. * @param len Length of packet
  119. * @param now Current time
  120. * @return True if packet appears to have been sent
  121. */
  122. bool send(const RuntimeEnvironment *_r,const void *data,unsigned int len,uint64_t now);
  123. /**
  124. * Send firewall opener to active link
  125. *
  126. * @param _r Runtime environment
  127. * @param now Current time
  128. * @return True if send appears successful for at least one address type
  129. */
  130. bool sendFirewallOpener(const RuntimeEnvironment *_r,uint64_t now);
  131. /**
  132. * Send HELLO to a peer via all active direct paths available
  133. *
  134. * @param _r Runtime environment
  135. * @param now Current time
  136. * @return True if send appears successful for at least one address type
  137. */
  138. bool sendPing(const RuntimeEnvironment *_r,uint64_t now);
  139. /**
  140. * Set an address to reach this peer
  141. *
  142. * @param addr Address to set
  143. * @param fixed If true, address is fixed (won't be changed on packet receipt)
  144. */
  145. void setPathAddress(const InetAddress &addr,bool fixed);
  146. /**
  147. * Clear the fixed flag for an address type
  148. *
  149. * @param t Type to clear, or TYPE_NULL to clear flag on all types
  150. */
  151. void clearFixedFlag(InetAddress::AddressType t);
  152. /**
  153. * @return Last successfully sent firewall opener
  154. */
  155. inline uint64_t lastFirewallOpener() const
  156. throw()
  157. {
  158. return std::max(_ipv4p.lastFirewallOpener,_ipv6p.lastFirewallOpener);
  159. }
  160. /**
  161. * @return Time of last direct packet receive
  162. */
  163. inline uint64_t lastDirectReceive() const
  164. throw()
  165. {
  166. return std::max(_ipv4p.lastReceive,_ipv6p.lastReceive);
  167. }
  168. /**
  169. * @return Time of last direct packet send
  170. */
  171. inline uint64_t lastDirectSend() const
  172. throw()
  173. {
  174. return std::max(_ipv4p.lastSend,_ipv6p.lastSend);
  175. }
  176. /**
  177. * @return Time of most recent unicast frame received
  178. */
  179. inline uint64_t lastUnicastFrame() const
  180. throw()
  181. {
  182. return _lastUnicastFrame;
  183. }
  184. /**
  185. * @return Time of most recent multicast frame received
  186. */
  187. inline uint64_t lastMulticastFrame() const
  188. throw()
  189. {
  190. return _lastMulticastFrame;
  191. }
  192. /**
  193. * @return Time of most recent frame of any kind (unicast or multicast)
  194. */
  195. inline uint64_t lastFrame() const
  196. throw()
  197. {
  198. return std::max(_lastUnicastFrame,_lastMulticastFrame);
  199. }
  200. /**
  201. * @return Time we last announced state TO this peer, such as multicast LIKEs
  202. */
  203. inline uint64_t lastAnnouncedTo() const
  204. throw()
  205. {
  206. return _lastAnnouncedTo;
  207. }
  208. /**
  209. * @return Current latency or 0 if unknown (max: 65535)
  210. */
  211. inline unsigned int latency() const
  212. throw()
  213. {
  214. unsigned int l = _latency;
  215. return std::min(l,(unsigned int)65535);
  216. }
  217. /**
  218. * Update latency with a new direct measurment
  219. *
  220. * @param l Direct latency measurment in ms
  221. */
  222. inline void addDirectLatencyMeasurment(unsigned int l)
  223. throw()
  224. {
  225. if (l > 65535) l = 65535;
  226. unsigned int ol = _latency;
  227. if ((ol > 0)&&(ol < 10000))
  228. _latency = (ol + l) / 2;
  229. else _latency = l;
  230. }
  231. /**
  232. * @return True if this peer has at least one direct IP address path
  233. */
  234. inline bool hasDirectPath() const throw() { return ((_ipv4p.addr)||(_ipv6p.addr)); }
  235. /**
  236. * @param now Current time
  237. * @return True if this peer has at least one active or fixed direct path
  238. */
  239. inline bool hasActiveDirectPath(uint64_t now) const throw() { return ((_ipv4p.isActive(now))||(_ipv6p.isActive(now))); }
  240. /**
  241. * @return IPv4 direct address or null InetAddress if none
  242. */
  243. inline InetAddress ipv4Path() const throw() { return _ipv4p.addr; }
  244. /**
  245. * @return IPv6 direct address or null InetAddress if none
  246. */
  247. inline InetAddress ipv6Path() const throw() { return _ipv4p.addr; }
  248. /**
  249. * @return IPv4 direct address or null InetAddress if none
  250. */
  251. inline InetAddress ipv4ActivePath(uint64_t now) const
  252. throw()
  253. {
  254. if (_ipv4p.isActive(now))
  255. return _ipv4p.addr;
  256. return InetAddress();
  257. }
  258. /**
  259. * @return IPv6 direct address or null InetAddress if none
  260. */
  261. inline InetAddress ipv6ActivePath(uint64_t now) const
  262. throw()
  263. {
  264. if (_ipv6p.isActive(now))
  265. return _ipv6p.addr;
  266. return InetAddress();
  267. }
  268. /**
  269. * Forget direct paths
  270. *
  271. * @param fixedToo If true, also forget 'fixed' paths.
  272. */
  273. inline void forgetDirectPaths(bool fixedToo)
  274. throw()
  275. {
  276. if ((fixedToo)||(!_ipv4p.fixed))
  277. _ipv4p.addr.zero();
  278. if ((fixedToo)||(!_ipv6p.fixed))
  279. _ipv6p.addr.zero();
  280. }
  281. /**
  282. * @return 256-bit secret symmetric encryption key
  283. */
  284. inline const unsigned char *key() const throw() { return _key; }
  285. /**
  286. * Set the currently known remote version of this peer's client
  287. *
  288. * @param vmaj Major version
  289. * @param vmin Minor version
  290. * @param vrev Revision
  291. */
  292. inline void setRemoteVersion(unsigned int vmaj,unsigned int vmin,unsigned int vrev)
  293. {
  294. _vMajor = vmaj;
  295. _vMinor = vmin;
  296. _vRevision = vrev;
  297. }
  298. /**
  299. * @return Remote version in string form or '?' if unknown
  300. */
  301. inline std::string remoteVersion() const
  302. {
  303. if ((_vMajor)||(_vMinor)||(_vRevision)) {
  304. char tmp[32];
  305. Utils::snprintf(tmp,sizeof(tmp),"%u.%u.%u",_vMajor,_vMinor,_vRevision);
  306. return std::string(tmp);
  307. }
  308. return std::string("?");
  309. }
  310. /**
  311. * @return True if this Peer is initialized with something
  312. */
  313. inline operator bool() const throw() { return (_id); }
  314. /**
  315. * Find a common set of addresses by which two peers can link, if any
  316. *
  317. * @param a Peer A
  318. * @param b Peer B
  319. * @param now Current time
  320. * @return Pair: B's address to send to A, A's address to send to B
  321. */
  322. static inline std::pair<InetAddress,InetAddress> findCommonGround(const Peer &a,const Peer &b,uint64_t now)
  323. throw()
  324. {
  325. if ((a._ipv6p.isActive(now))&&(b._ipv6p.isActive(now)))
  326. return std::pair<InetAddress,InetAddress>(b._ipv6p.addr,a._ipv6p.addr);
  327. else if ((a._ipv4p.isActive(now))&&(b._ipv4p.isActive(now)))
  328. return std::pair<InetAddress,InetAddress>(b._ipv4p.addr,a._ipv4p.addr);
  329. else if ((a._ipv6p.addr)&&(b._ipv6p.addr))
  330. return std::pair<InetAddress,InetAddress>(b._ipv6p.addr,a._ipv6p.addr);
  331. else if ((a._ipv4p.addr)&&(b._ipv4p.addr))
  332. return std::pair<InetAddress,InetAddress>(b._ipv4p.addr,a._ipv4p.addr);
  333. return std::pair<InetAddress,InetAddress>();
  334. }
  335. template<unsigned int C>
  336. inline void serialize(Buffer<C> &b)
  337. {
  338. b.append((unsigned char)ZT_PEER_SERIALIZATION_VERSION);
  339. b.append(_key,sizeof(_key));
  340. _id.serialize(b,false);
  341. _ipv4p.serialize(b);
  342. _ipv6p.serialize(b);
  343. b.append(_lastUsed);
  344. b.append(_lastUnicastFrame);
  345. b.append(_lastMulticastFrame);
  346. b.append(_lastAnnouncedTo);
  347. b.append((uint16_t)_vMajor);
  348. b.append((uint16_t)_vMinor);
  349. b.append((uint16_t)_vRevision);
  350. b.append((uint16_t)_latency);
  351. }
  352. template<unsigned int C>
  353. inline unsigned int deserialize(const Buffer<C> &b,unsigned int startAt = 0)
  354. {
  355. unsigned int p = startAt;
  356. if (b[p++] != ZT_PEER_SERIALIZATION_VERSION)
  357. throw std::invalid_argument("Peer: deserialize(): version mismatch");
  358. memcpy(_key,b.field(p,sizeof(_key)),sizeof(_key)); p += sizeof(_key);
  359. p += _id.deserialize(b,p);
  360. p += _ipv4p.deserialize(b,p);
  361. p += _ipv6p.deserialize(b,p);
  362. _lastUsed = b.template at<uint64_t>(p); p += sizeof(uint64_t);
  363. _lastUnicastFrame = b.template at<uint64_t>(p); p += sizeof(uint64_t);
  364. _lastMulticastFrame = b.template at<uint64_t>(p); p += sizeof(uint64_t);
  365. _lastAnnouncedTo = b.template at<uint64_t>(p); p += sizeof(uint64_t);
  366. _vMajor = b.template at<uint16_t>(p); p += sizeof(uint16_t);
  367. _vMinor = b.template at<uint16_t>(p); p += sizeof(uint16_t);
  368. _vRevision = b.template at<uint16_t>(p); p += sizeof(uint16_t);
  369. _latency = b.template at<uint16_t>(p); p += sizeof(uint16_t);
  370. return (p - startAt);
  371. }
  372. private:
  373. /**
  374. * A direct IP path to a peer
  375. */
  376. class WanPath
  377. {
  378. public:
  379. WanPath() :
  380. lastSend(0),
  381. lastReceive(0),
  382. lastFirewallOpener(0),
  383. addr(),
  384. fixed(false)
  385. {
  386. }
  387. inline bool isActive(const uint64_t now) const
  388. throw()
  389. {
  390. return ((addr)&&((fixed)||((now - lastReceive) < ZT_PEER_LINK_ACTIVITY_TIMEOUT)));
  391. }
  392. template<unsigned int C>
  393. inline void serialize(Buffer<C> &b)
  394. throw(std::out_of_range)
  395. {
  396. b.append(lastSend);
  397. b.append(lastReceive);
  398. b.append(lastFirewallOpener);
  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. switch ((InetAddress::AddressType)b[p++]) {
  423. case InetAddress::TYPE_NULL:
  424. addr.zero();
  425. break;
  426. case InetAddress::TYPE_IPV4:
  427. addr.set(b.field(p,4),4,b.template at<uint16_t>(p + 4));
  428. p += 4 + sizeof(uint16_t);
  429. break;
  430. case InetAddress::TYPE_IPV6:
  431. addr.set(b.field(p,16),16,b.template at<uint16_t>(p + 16));
  432. p += 16 + sizeof(uint16_t);
  433. break;
  434. }
  435. fixed = (b[p++] != 0);
  436. return (p - startAt);
  437. }
  438. uint64_t lastSend;
  439. uint64_t lastReceive;
  440. uint64_t lastFirewallOpener;
  441. InetAddress addr; // null InetAddress if path is undefined
  442. bool fixed; // do not learn address from received packets
  443. };
  444. unsigned char _key[ZT_PEER_SECRET_KEY_LENGTH];
  445. Identity _id;
  446. WanPath _ipv4p;
  447. WanPath _ipv6p;
  448. volatile uint64_t _lastUsed;
  449. volatile uint64_t _lastUnicastFrame;
  450. volatile uint64_t _lastMulticastFrame;
  451. volatile uint64_t _lastAnnouncedTo;
  452. volatile unsigned int _vMajor,_vMinor,_vRevision;
  453. volatile unsigned int _latency;
  454. AtomicCounter __refCount;
  455. };
  456. } // namespace ZeroTier
  457. // Add a swap() for shared ptr's to peers to speed up peer sorts
  458. namespace std {
  459. template<>
  460. inline void swap(ZeroTier::SharedPtr<ZeroTier::Peer> &a,ZeroTier::SharedPtr<ZeroTier::Peer> &b)
  461. {
  462. a.swap(b);
  463. }
  464. }
  465. #endif