Peer.hpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565
  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 "Address.hpp"
  34. #include "Utils.hpp"
  35. #include "Identity.hpp"
  36. #include "Constants.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. 32 + \
  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. * Set an address to reach this peer
  133. *
  134. * @param addr Address to set
  135. * @param fixed If true, address is fixed (won't be changed on packet receipt)
  136. */
  137. void setPathAddress(const InetAddress &addr,bool fixed);
  138. /**
  139. * Clear the fixed flag for an address type
  140. *
  141. * @param t Type to clear, or TYPE_NULL to clear flag on all types
  142. */
  143. void clearFixedFlag(InetAddress::AddressType t);
  144. /**
  145. * @return Last successfully sent firewall opener
  146. */
  147. inline uint64_t lastFirewallOpener() const
  148. throw()
  149. {
  150. return std::max(_ipv4p.lastFirewallOpener,_ipv6p.lastFirewallOpener);
  151. }
  152. /**
  153. * @return Time of last direct packet receive
  154. */
  155. inline uint64_t lastDirectReceive() const
  156. throw()
  157. {
  158. return std::max(_ipv4p.lastReceive,_ipv6p.lastReceive);
  159. }
  160. /**
  161. * @return Time of last direct packet send
  162. */
  163. inline uint64_t lastDirectSend() const
  164. throw()
  165. {
  166. return std::max(_ipv4p.lastSend,_ipv6p.lastSend);
  167. }
  168. /**
  169. * @return Time of most recent unicast frame received
  170. */
  171. inline uint64_t lastUnicastFrame() const
  172. throw()
  173. {
  174. return _lastUnicastFrame;
  175. }
  176. /**
  177. * @return Time of most recent multicast frame received
  178. */
  179. inline uint64_t lastMulticastFrame() const
  180. throw()
  181. {
  182. return _lastMulticastFrame;
  183. }
  184. /**
  185. * @return Time of most recent frame of any kind (unicast or multicast)
  186. */
  187. inline uint64_t lastFrame() const
  188. throw()
  189. {
  190. return std::max(_lastUnicastFrame,_lastMulticastFrame);
  191. }
  192. /**
  193. * @return Time we last announced state TO this peer, such as multicast LIKEs
  194. */
  195. inline uint64_t lastAnnouncedTo() const
  196. throw()
  197. {
  198. return _lastAnnouncedTo;
  199. }
  200. /**
  201. * Set the time of last announcement
  202. *
  203. * @param t Time, typically current
  204. */
  205. inline void setLastAnnouncedTo(const uint64_t t)
  206. throw()
  207. {
  208. _lastAnnouncedTo = t;
  209. _dirty = true;
  210. }
  211. /**
  212. * @return Lowest of measured latencies of all paths or 0 if unknown
  213. */
  214. inline unsigned int latency() const
  215. throw()
  216. {
  217. if (_ipv4p.latency) {
  218. if (_ipv6p.latency)
  219. return std::min(_ipv4p.latency,_ipv6p.latency);
  220. else return _ipv4p.latency;
  221. } else if (_ipv6p.latency)
  222. return _ipv6p.latency;
  223. return 0;
  224. }
  225. /**
  226. * @param addr Remote address
  227. * @param latency Latency measurment
  228. */
  229. inline void setLatency(const InetAddress &addr,unsigned int latency)
  230. {
  231. if (addr == _ipv4p.addr) {
  232. _ipv4p.latency = latency;
  233. _dirty = true;
  234. } else if (addr == _ipv6p.addr) {
  235. _ipv6p.latency = latency;
  236. _dirty = true;
  237. }
  238. }
  239. /**
  240. * @return True if this peer has at least one direct IP address path
  241. */
  242. inline bool hasDirectPath() const
  243. throw()
  244. {
  245. return ((_ipv4p.addr)||(_ipv6p.addr));
  246. }
  247. /**
  248. * @param now Current time
  249. * @return True if hasDirectPath() is true and at least one path is active
  250. */
  251. inline bool hasActiveDirectPath(uint64_t now) const
  252. throw()
  253. {
  254. return ((_ipv4p.isActive(now))||(_ipv6p.isActive(now)));
  255. }
  256. /**
  257. * @return IPv4 direct address or null InetAddress if none
  258. */
  259. inline InetAddress ipv4Path() const
  260. throw()
  261. {
  262. return _ipv4p.addr;
  263. }
  264. /**
  265. * @return IPv6 direct address or null InetAddress if none
  266. */
  267. inline InetAddress ipv6Path() const
  268. throw()
  269. {
  270. return _ipv4p.addr;
  271. }
  272. /**
  273. * @return IPv4 direct address or null InetAddress if none
  274. */
  275. inline InetAddress ipv4ActivePath(uint64_t now) const
  276. throw()
  277. {
  278. if (_ipv4p.isActive(now))
  279. return _ipv4p.addr;
  280. return InetAddress();
  281. }
  282. /**
  283. * @return IPv6 direct address or null InetAddress if none
  284. */
  285. inline InetAddress ipv6ActivePath(uint64_t now) const
  286. throw()
  287. {
  288. if (_ipv6p.isActive(now))
  289. return _ipv6p.addr;
  290. return InetAddress();
  291. }
  292. /**
  293. * @return 256-bit encryption key
  294. */
  295. inline const unsigned char *key() const
  296. throw()
  297. {
  298. return _key;
  299. }
  300. /**
  301. * Set the remote version of the peer (not persisted)
  302. *
  303. * @param vmaj Major version
  304. * @param vmin Minor version
  305. * @param vrev Revision
  306. */
  307. inline void setRemoteVersion(unsigned int vmaj,unsigned int vmin,unsigned int vrev)
  308. {
  309. _vMajor = vmaj;
  310. _vMinor = vmin;
  311. _vRevision = vrev;
  312. }
  313. /**
  314. * @return Remote version in string form or '?' if unknown
  315. */
  316. inline std::string remoteVersion() const
  317. {
  318. if ((_vMajor)||(_vMinor)||(_vRevision)) {
  319. char tmp[32];
  320. Utils::snprintf(tmp,sizeof(tmp),"%u.%u.%u",_vMajor,_vMinor,_vRevision);
  321. return std::string(tmp);
  322. }
  323. return std::string("?");
  324. }
  325. /**
  326. * Get and reset dirty flag
  327. *
  328. * @return Previous value of dirty flag before reset
  329. */
  330. inline bool getAndResetDirty()
  331. throw()
  332. {
  333. bool d = _dirty;
  334. _dirty = false;
  335. return d;
  336. }
  337. /**
  338. * @return Current value of dirty flag
  339. */
  340. inline bool dirty() const throw() { return _dirty; }
  341. template<unsigned int C>
  342. inline void serialize(Buffer<C> &b)
  343. throw(std::out_of_range)
  344. {
  345. b.append((unsigned char)3); // version
  346. b.append(_key,sizeof(_key));
  347. _id.serialize(b,false);
  348. _ipv4p.serialize(b);
  349. _ipv6p.serialize(b);
  350. b.append(_lastUnicastFrame);
  351. b.append(_lastMulticastFrame);
  352. b.append(_lastAnnouncedTo);
  353. b.append((uint16_t)_vMajor);
  354. b.append((uint16_t)_vMinor);
  355. b.append((uint16_t)_vRevision);
  356. }
  357. template<unsigned int C>
  358. inline unsigned int deserialize(const Buffer<C> &b,unsigned int startAt = 0)
  359. throw(std::out_of_range,std::invalid_argument)
  360. {
  361. unsigned int p = startAt;
  362. if (b[p++] != 3)
  363. throw std::invalid_argument("Peer: deserialize(): version mismatch");
  364. memcpy(_key,b.field(p,sizeof(_key)),sizeof(_key)); p += sizeof(_key);
  365. p += _id.deserialize(b,p);
  366. p += _ipv4p.deserialize(b,p);
  367. p += _ipv6p.deserialize(b,p);
  368. _lastUnicastFrame = b.template at<uint64_t>(p); p += sizeof(uint64_t);
  369. _lastMulticastFrame = b.template at<uint64_t>(p); p += sizeof(uint64_t);
  370. _lastAnnouncedTo = b.template at<uint64_t>(p); p += sizeof(uint64_t);
  371. _vMajor = b.template at<uint16_t>(p); p += sizeof(uint16_t);
  372. _vMinor = b.template at<uint16_t>(p); p += sizeof(uint16_t);
  373. _vRevision = b.template at<uint16_t>(p); p += sizeof(uint16_t);
  374. _dirty = false;
  375. return (p - startAt);
  376. }
  377. /**
  378. * @return True if this Peer is initialized with something
  379. */
  380. inline operator bool() const throw() { return (_id); }
  381. /**
  382. * Find a common set of addresses by which two peers can link, if any
  383. *
  384. * @param a Peer A
  385. * @param b Peer B
  386. * @param now Current time
  387. * @return Pair: B's address to send to A, A's address to send to B
  388. */
  389. static inline std::pair<InetAddress,InetAddress> findCommonGround(const Peer &a,const Peer &b,uint64_t now)
  390. throw()
  391. {
  392. if ((a._ipv6p.isActive(now))&&(b._ipv6p.isActive(now)))
  393. return std::pair<InetAddress,InetAddress>(b._ipv6p.addr,a._ipv6p.addr);
  394. else if ((a._ipv4p.isActive(now))&&(b._ipv4p.isActive(now)))
  395. return std::pair<InetAddress,InetAddress>(b._ipv4p.addr,a._ipv4p.addr);
  396. else if ((a._ipv6p.addr)&&(b._ipv6p.addr))
  397. return std::pair<InetAddress,InetAddress>(b._ipv6p.addr,a._ipv6p.addr);
  398. else if ((a._ipv4p.addr)&&(b._ipv4p.addr))
  399. return std::pair<InetAddress,InetAddress>(b._ipv4p.addr,a._ipv4p.addr);
  400. return std::pair<InetAddress,InetAddress>();
  401. }
  402. private:
  403. class WanPath
  404. {
  405. public:
  406. WanPath() :
  407. lastSend(0),
  408. lastReceive(0),
  409. lastFirewallOpener(0),
  410. localPort(Demarc::ANY_PORT),
  411. latency(0),
  412. addr(),
  413. fixed(false)
  414. {
  415. }
  416. inline bool isActive(const uint64_t now) const
  417. throw()
  418. {
  419. return ((addr)&&((now - lastReceive) < ZT_PEER_LINK_ACTIVITY_TIMEOUT));
  420. }
  421. template<unsigned int C>
  422. inline void serialize(Buffer<C> &b)
  423. throw(std::out_of_range)
  424. {
  425. b.append(lastSend);
  426. b.append(lastReceive);
  427. b.append(lastFirewallOpener);
  428. b.append(Demarc::portToInt(localPort));
  429. b.append((uint16_t)latency);
  430. b.append((unsigned char)addr.type());
  431. switch(addr.type()) {
  432. case InetAddress::TYPE_NULL:
  433. break;
  434. case InetAddress::TYPE_IPV4:
  435. b.append(addr.rawIpData(),4);
  436. b.append((uint16_t)addr.port());
  437. break;
  438. case InetAddress::TYPE_IPV6:
  439. b.append(addr.rawIpData(),16);
  440. b.append((uint16_t)addr.port());
  441. break;
  442. }
  443. b.append(fixed ? (unsigned char)1 : (unsigned char)0);
  444. }
  445. template<unsigned int C>
  446. inline unsigned int deserialize(const Buffer<C> &b,unsigned int startAt = 0)
  447. throw(std::out_of_range,std::invalid_argument)
  448. {
  449. unsigned int p = startAt;
  450. lastSend = b.template at<uint64_t>(p); p += sizeof(uint64_t);
  451. lastReceive = b.template at<uint64_t>(p); p += sizeof(uint64_t);
  452. lastFirewallOpener = b.template at<uint64_t>(p); p += sizeof(uint64_t);
  453. localPort = Demarc::intToPort(b.template at<uint64_t>(p)); p += sizeof(uint64_t);
  454. latency = b.template at<uint16_t>(p); p += sizeof(uint16_t);
  455. switch ((InetAddress::AddressType)b[p++]) {
  456. case InetAddress::TYPE_NULL:
  457. addr.zero();
  458. break;
  459. case InetAddress::TYPE_IPV4:
  460. addr.set(b.field(p,4),4,b.template at<uint16_t>(p + 4));
  461. p += 4 + sizeof(uint16_t);
  462. break;
  463. case InetAddress::TYPE_IPV6:
  464. addr.set(b.field(p,16),16,b.template at<uint16_t>(p + 16));
  465. p += 16 + sizeof(uint16_t);
  466. break;
  467. }
  468. fixed = (b[p++] != 0);
  469. return (p - startAt);
  470. }
  471. uint64_t lastSend;
  472. uint64_t lastReceive;
  473. uint64_t lastFirewallOpener;
  474. Demarc::Port localPort; // ANY_PORT if not defined (size: uint64_t)
  475. unsigned int latency; // 0 if never determined
  476. InetAddress addr; // null InetAddress if path is undefined
  477. bool fixed; // do not learn address from received packets
  478. };
  479. unsigned char _key[32]; // shared secret key agreed upon between identities
  480. Identity _id;
  481. WanPath _ipv4p;
  482. WanPath _ipv6p;
  483. uint64_t _lastUnicastFrame;
  484. uint64_t _lastMulticastFrame;
  485. uint64_t _lastAnnouncedTo;
  486. unsigned int _vMajor,_vMinor,_vRevision;
  487. // Fields below this line are not persisted with serialize() ---------------
  488. bool _dirty;
  489. AtomicCounter __refCount;
  490. };
  491. } // namespace ZeroTier
  492. // Add a swap() for shared ptr's to peers to speed up peer sorts
  493. namespace std {
  494. template<>
  495. inline void swap(ZeroTier::SharedPtr<ZeroTier::Peer> &a,ZeroTier::SharedPtr<ZeroTier::Peer> &b)
  496. {
  497. a.swap(b);
  498. }
  499. }
  500. #endif