Peer.hpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563
  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. /**
  47. * Max length of serialized peer record
  48. */
  49. #define ZT_PEER_MAX_SERIALIZED_LENGTH ( \
  50. ZT_PEER_SECRET_KEY_LENGTH + \
  51. ZT_IDENTITY_MAX_BINARY_SERIALIZED_LENGTH + \
  52. ( ( \
  53. (sizeof(uint64_t) * 4) + \
  54. sizeof(uint16_t) + \
  55. 1 + \
  56. sizeof(uint16_t) + \
  57. 16 + \
  58. 1 \
  59. ) * 2) + \
  60. (sizeof(uint64_t) * 3) + \
  61. (sizeof(uint16_t) * 3) \
  62. )
  63. namespace ZeroTier {
  64. /**
  65. * A peer on the network
  66. *
  67. * Threading note:
  68. *
  69. * This structure contains no locks at the moment, but also performs no
  70. * memory allocation or pointer manipulation. As a result is is technically
  71. * "safe" for threads, as in won't crash. Right now it's only changed from
  72. * the core I/O thread so this isn't an issue. If multiple I/O threads are
  73. * introduced it ought to have a lock of some kind.
  74. */
  75. class Peer : NonCopyable
  76. {
  77. friend class SharedPtr<Peer>;
  78. private:
  79. ~Peer() {}
  80. public:
  81. Peer();
  82. /**
  83. * Construct a new peer
  84. *
  85. * @param myIdentity Identity of THIS node (for key agreement)
  86. * @param peerIdentity Identity of peer
  87. * @throws std::runtime_error Key agreement with peer's identity failed
  88. */
  89. Peer(const Identity &myIdentity,const Identity &peerIdentity)
  90. throw(std::runtime_error);
  91. /**
  92. * @return This peer's ZT address (short for identity().address())
  93. */
  94. inline const Address &address() const throw() { return _id.address(); }
  95. /**
  96. * @return This peer's identity
  97. */
  98. inline const Identity &identity() const throw() { return _id; }
  99. /**
  100. * Must be called on authenticated packet receive from this peer
  101. *
  102. * This must be called only after a packet has passed authentication
  103. * checking. Packets that fail are silently discarded.
  104. *
  105. * @param _r Runtime environment
  106. * @param localPort Local port on which packet was received
  107. * @param remoteAddr Internet address of sender
  108. * @param hops ZeroTier (not IP) hops
  109. * @param verb Packet verb
  110. * @param now Current time
  111. */
  112. void onReceive(const RuntimeEnvironment *_r,Demarc::Port localPort,const InetAddress &remoteAddr,unsigned int hops,Packet::Verb verb,uint64_t now);
  113. /**
  114. * Send a packet to this peer
  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, false on local failure
  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 using one or both active link types
  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 Lowest of measured latencies of all paths or 0 if unknown
  210. */
  211. inline unsigned int latency() const
  212. throw()
  213. {
  214. if (_ipv4p.latency) {
  215. if (_ipv6p.latency)
  216. return std::min(_ipv4p.latency,_ipv6p.latency);
  217. else return _ipv4p.latency;
  218. } else if (_ipv6p.latency)
  219. return _ipv6p.latency;
  220. return 0;
  221. }
  222. /**
  223. * @param addr Remote address
  224. * @param latency Latency measurment
  225. */
  226. inline void setLatency(const InetAddress &addr,unsigned int latency)
  227. {
  228. if (addr == _ipv4p.addr) {
  229. _ipv4p.latency = latency;
  230. _dirty = true;
  231. } else if (addr == _ipv6p.addr) {
  232. _ipv6p.latency = latency;
  233. _dirty = true;
  234. }
  235. }
  236. /**
  237. * @return True if this peer has at least one direct IP address path
  238. */
  239. inline bool hasDirectPath() const
  240. throw()
  241. {
  242. return ((_ipv4p.addr)||(_ipv6p.addr));
  243. }
  244. /**
  245. * @return True if this peer has at least one direct IP address path that looks active
  246. *
  247. * @param now Current time
  248. */
  249. inline bool hasActiveDirectPath(uint64_t now) const
  250. throw()
  251. {
  252. return ((_ipv4p.isActive(now))||(_ipv6p.isActive(now)));
  253. }
  254. /**
  255. * @return IPv4 direct address or null InetAddress if none
  256. */
  257. inline InetAddress ipv4Path() const
  258. throw()
  259. {
  260. return _ipv4p.addr;
  261. }
  262. /**
  263. * @return IPv6 direct address or null InetAddress if none
  264. */
  265. inline InetAddress ipv6Path() const
  266. throw()
  267. {
  268. return _ipv4p.addr;
  269. }
  270. /**
  271. * @return IPv4 direct address or null InetAddress if none
  272. */
  273. inline InetAddress ipv4ActivePath(uint64_t now) const
  274. throw()
  275. {
  276. if (_ipv4p.isActive(now))
  277. return _ipv4p.addr;
  278. return InetAddress();
  279. }
  280. /**
  281. * @return IPv6 direct address or null InetAddress if none
  282. */
  283. inline InetAddress ipv6ActivePath(uint64_t now) const
  284. throw()
  285. {
  286. if (_ipv6p.isActive(now))
  287. return _ipv6p.addr;
  288. return InetAddress();
  289. }
  290. /**
  291. * @return 256-bit encryption key
  292. */
  293. inline const unsigned char *key() const
  294. throw()
  295. {
  296. return _key;
  297. }
  298. /**
  299. * Set the remote version of the peer (not persisted)
  300. *
  301. * @param vmaj Major version
  302. * @param vmin Minor version
  303. * @param vrev Revision
  304. */
  305. inline void setRemoteVersion(unsigned int vmaj,unsigned int vmin,unsigned int vrev)
  306. {
  307. _vMajor = vmaj;
  308. _vMinor = vmin;
  309. _vRevision = vrev;
  310. }
  311. /**
  312. * @return Remote version in string form or '?' if unknown
  313. */
  314. inline std::string remoteVersion() const
  315. {
  316. if ((_vMajor)||(_vMinor)||(_vRevision)) {
  317. char tmp[32];
  318. Utils::snprintf(tmp,sizeof(tmp),"%u.%u.%u",_vMajor,_vMinor,_vRevision);
  319. return std::string(tmp);
  320. }
  321. return std::string("?");
  322. }
  323. /**
  324. * Get and reset dirty flag
  325. *
  326. * @return Previous value of dirty flag before reset
  327. */
  328. inline bool getAndResetDirty()
  329. throw()
  330. {
  331. bool d = _dirty;
  332. _dirty = false;
  333. return d;
  334. }
  335. /**
  336. * @return Current value of dirty flag
  337. */
  338. inline bool dirty() const throw() { return _dirty; }
  339. template<unsigned int C>
  340. inline void serialize(Buffer<C> &b)
  341. throw(std::out_of_range)
  342. {
  343. b.append((unsigned char)3); // version
  344. b.append(_key,sizeof(_key));
  345. _id.serialize(b,false);
  346. _ipv4p.serialize(b);
  347. _ipv6p.serialize(b);
  348. b.append(_lastUnicastFrame);
  349. b.append(_lastMulticastFrame);
  350. b.append(_lastAnnouncedTo);
  351. b.append((uint16_t)_vMajor);
  352. b.append((uint16_t)_vMinor);
  353. b.append((uint16_t)_vRevision);
  354. }
  355. template<unsigned int C>
  356. inline unsigned int deserialize(const Buffer<C> &b,unsigned int startAt = 0)
  357. throw(std::out_of_range,std::invalid_argument)
  358. {
  359. unsigned int p = startAt;
  360. if (b[p++] != 3)
  361. throw std::invalid_argument("Peer: deserialize(): version mismatch");
  362. memcpy(_key,b.field(p,sizeof(_key)),sizeof(_key)); p += sizeof(_key);
  363. p += _id.deserialize(b,p);
  364. p += _ipv4p.deserialize(b,p);
  365. p += _ipv6p.deserialize(b,p);
  366. _lastUnicastFrame = b.template at<uint64_t>(p); p += sizeof(uint64_t);
  367. _lastMulticastFrame = b.template at<uint64_t>(p); p += sizeof(uint64_t);
  368. _lastAnnouncedTo = b.template at<uint64_t>(p); p += sizeof(uint64_t);
  369. _vMajor = b.template at<uint16_t>(p); p += sizeof(uint16_t);
  370. _vMinor = b.template at<uint16_t>(p); p += sizeof(uint16_t);
  371. _vRevision = b.template at<uint16_t>(p); p += sizeof(uint16_t);
  372. _dirty = false;
  373. return (p - startAt);
  374. }
  375. /**
  376. * @return True if this Peer is initialized with something
  377. */
  378. inline operator bool() const throw() { return (_id); }
  379. /**
  380. * Find a common set of addresses by which two peers can link, if any
  381. *
  382. * @param a Peer A
  383. * @param b Peer B
  384. * @param now Current time
  385. * @return Pair: B's address to send to A, A's address to send to B
  386. */
  387. static inline std::pair<InetAddress,InetAddress> findCommonGround(const Peer &a,const Peer &b,uint64_t now)
  388. throw()
  389. {
  390. if ((a._ipv6p.isActive(now))&&(b._ipv6p.isActive(now)))
  391. return std::pair<InetAddress,InetAddress>(b._ipv6p.addr,a._ipv6p.addr);
  392. else if ((a._ipv4p.isActive(now))&&(b._ipv4p.isActive(now)))
  393. return std::pair<InetAddress,InetAddress>(b._ipv4p.addr,a._ipv4p.addr);
  394. else if ((a._ipv6p.addr)&&(b._ipv6p.addr))
  395. return std::pair<InetAddress,InetAddress>(b._ipv6p.addr,a._ipv6p.addr);
  396. else if ((a._ipv4p.addr)&&(b._ipv4p.addr))
  397. return std::pair<InetAddress,InetAddress>(b._ipv4p.addr,a._ipv4p.addr);
  398. return std::pair<InetAddress,InetAddress>();
  399. }
  400. private:
  401. class WanPath
  402. {
  403. public:
  404. WanPath() :
  405. lastSend(0),
  406. lastReceive(0),
  407. lastFirewallOpener(0),
  408. localPort(Demarc::ANY_PORT),
  409. latency(0),
  410. addr(),
  411. fixed(false)
  412. {
  413. }
  414. inline bool isActive(const uint64_t now) const
  415. throw()
  416. {
  417. return ((addr)&&((now - lastReceive) < ZT_PEER_LINK_ACTIVITY_TIMEOUT));
  418. }
  419. template<unsigned int C>
  420. inline void serialize(Buffer<C> &b)
  421. throw(std::out_of_range)
  422. {
  423. b.append(lastSend);
  424. b.append(lastReceive);
  425. b.append(lastFirewallOpener);
  426. b.append(Demarc::portToInt(localPort));
  427. b.append((uint16_t)latency);
  428. b.append((unsigned char)addr.type());
  429. switch(addr.type()) {
  430. case InetAddress::TYPE_NULL:
  431. break;
  432. case InetAddress::TYPE_IPV4:
  433. b.append(addr.rawIpData(),4);
  434. b.append((uint16_t)addr.port());
  435. break;
  436. case InetAddress::TYPE_IPV6:
  437. b.append(addr.rawIpData(),16);
  438. b.append((uint16_t)addr.port());
  439. break;
  440. }
  441. b.append(fixed ? (unsigned char)1 : (unsigned char)0);
  442. }
  443. template<unsigned int C>
  444. inline unsigned int deserialize(const Buffer<C> &b,unsigned int startAt = 0)
  445. throw(std::out_of_range,std::invalid_argument)
  446. {
  447. unsigned int p = startAt;
  448. lastSend = b.template at<uint64_t>(p); p += sizeof(uint64_t);
  449. lastReceive = b.template at<uint64_t>(p); p += sizeof(uint64_t);
  450. lastFirewallOpener = b.template at<uint64_t>(p); p += sizeof(uint64_t);
  451. localPort = Demarc::intToPort(b.template at<uint64_t>(p)); p += sizeof(uint64_t);
  452. latency = b.template at<uint16_t>(p); p += sizeof(uint16_t);
  453. switch ((InetAddress::AddressType)b[p++]) {
  454. case InetAddress::TYPE_NULL:
  455. addr.zero();
  456. break;
  457. case InetAddress::TYPE_IPV4:
  458. addr.set(b.field(p,4),4,b.template at<uint16_t>(p + 4));
  459. p += 4 + sizeof(uint16_t);
  460. break;
  461. case InetAddress::TYPE_IPV6:
  462. addr.set(b.field(p,16),16,b.template at<uint16_t>(p + 16));
  463. p += 16 + sizeof(uint16_t);
  464. break;
  465. }
  466. fixed = (b[p++] != 0);
  467. return (p - startAt);
  468. }
  469. uint64_t lastSend;
  470. uint64_t lastReceive;
  471. uint64_t lastFirewallOpener;
  472. Demarc::Port localPort; // ANY_PORT if not defined (size: uint64_t)
  473. unsigned int latency; // 0 if never determined
  474. InetAddress addr; // null InetAddress if path is undefined
  475. bool fixed; // do not learn address from received packets
  476. };
  477. unsigned char _key[ZT_PEER_SECRET_KEY_LENGTH];
  478. Identity _id;
  479. WanPath _ipv4p;
  480. WanPath _ipv6p;
  481. uint64_t _lastUnicastFrame;
  482. uint64_t _lastMulticastFrame;
  483. uint64_t _lastAnnouncedTo;
  484. unsigned int _vMajor,_vMinor,_vRevision;
  485. // Fields below this line are not persisted with serialize() ---------------
  486. bool _dirty;
  487. AtomicCounter __refCount;
  488. };
  489. } // namespace ZeroTier
  490. // Add a swap() for shared ptr's to peers to speed up peer sorts
  491. namespace std {
  492. template<>
  493. inline void swap(ZeroTier::SharedPtr<ZeroTier::Peer> &a,ZeroTier::SharedPtr<ZeroTier::Peer> &b)
  494. {
  495. a.swap(b);
  496. }
  497. }
  498. #endif