Peer.hpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561
  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 <algorithm>
  30. #include <utility>
  31. #include <stdexcept>
  32. #include <stdint.h>
  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 "EllipticCurveKey.hpp"
  42. #include "Packet.hpp"
  43. #include "SharedPtr.hpp"
  44. #include "AtomicCounter.hpp"
  45. #include "NonCopyable.hpp"
  46. #include "Mutex.hpp"
  47. /**
  48. * Max length of serialized peer record
  49. */
  50. #define ZT_PEER_MAX_SERIALIZED_LENGTH ( \
  51. 64 + \
  52. IDENTITY_MAX_BINARY_SERIALIZED_LENGTH + \
  53. ( ( \
  54. (sizeof(uint64_t) * 4) + \
  55. sizeof(uint16_t) + \
  56. 1 + \
  57. sizeof(uint16_t) + \
  58. 16 + \
  59. 1 \
  60. ) * 2) + \
  61. sizeof(uint64_t) + \
  62. sizeof(uint64_t) \
  63. )
  64. namespace ZeroTier {
  65. /**
  66. * A peer on the network
  67. *
  68. * Threading note:
  69. *
  70. * This structure contains no locks at the moment, but also performs no
  71. * memory allocation or pointer manipulation. As a result is is technically
  72. * "safe" for threads, as in won't crash. Right now it's only changed from
  73. * the core I/O thread so this isn't an issue. If multiple I/O threads are
  74. * introduced it ought to have a lock of some kind.
  75. */
  76. class Peer : NonCopyable
  77. {
  78. friend class SharedPtr<Peer>;
  79. private:
  80. ~Peer() {}
  81. public:
  82. Peer();
  83. /**
  84. * Construct a new peer
  85. *
  86. * @param myIdentity Identity of THIS node (for key agreement)
  87. * @param peerIdentity Identity of peer
  88. * @throws std::runtime_error Key agreement with peer's identity failed
  89. */
  90. Peer(const Identity &myIdentity,const Identity &peerIdentity)
  91. throw(std::runtime_error);
  92. /**
  93. * @return This peer's ZT address (short for identity().address())
  94. */
  95. inline const Address &address() const throw() { return _id.address(); }
  96. /**
  97. * @return This peer's identity
  98. */
  99. inline const Identity &identity() const throw() { return _id; }
  100. /**
  101. * Must be called on authenticated packet receive from this peer
  102. *
  103. * This must be called only after a packet has passed authentication
  104. * checking. Packets that fail are silently discarded.
  105. *
  106. * @param _r Runtime environment
  107. * @param localPort Local port on which packet was received
  108. * @param remoteAddr Internet address of sender
  109. * @param hops ZeroTier (not IP) hops
  110. * @param verb Packet verb
  111. * @param now Current time
  112. */
  113. void onReceive(const RuntimeEnvironment *_r,Demarc::Port localPort,const InetAddress &remoteAddr,unsigned int hops,Packet::Verb verb,uint64_t now);
  114. /**
  115. * Send a packet to this peer
  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 True if packet appears to have been sent, false on local failure
  122. */
  123. bool send(const RuntimeEnvironment *_r,const void *data,unsigned int len,uint64_t now);
  124. /**
  125. * Must be called after a packet is successfully sent to this peer
  126. *
  127. * Note that 'relay' means we've sent a packet *from* this node to this
  128. * peer by relaying it, not that we have relayed a packet from somewhere
  129. * else to this peer. In the latter case this is not called.
  130. *
  131. * @param _r Runtime environment
  132. * @param relay If true, packet was sent indirectly via a relay
  133. * @param verb Packet verb
  134. * @param now Current time
  135. */
  136. void onSent(const RuntimeEnvironment *_r,bool relay,Packet::Verb verb,uint64_t now);
  137. /**
  138. * Send firewall opener to active link
  139. *
  140. * @param _r Runtime environment
  141. * @param now Current time
  142. * @return True if send appears successful for at least one address type
  143. */
  144. bool sendFirewallOpener(const RuntimeEnvironment *_r,uint64_t now);
  145. /**
  146. * Set an address to reach this peer
  147. *
  148. * @param addr Address to set
  149. * @param fixed If true, address is fixed (won't be changed on packet receipt)
  150. */
  151. void setPathAddress(const InetAddress &addr,bool fixed);
  152. /**
  153. * Clear the fixed flag for an address type
  154. *
  155. * @param t Type to clear, or TYPE_NULL to clear flag on all types
  156. */
  157. void clearFixedFlag(InetAddress::AddressType t);
  158. /**
  159. * @return Last successfully sent firewall opener
  160. */
  161. uint64_t lastFirewallOpener() const
  162. throw()
  163. {
  164. return std::max(_ipv4p.lastFirewallOpener,_ipv6p.lastFirewallOpener);
  165. }
  166. /**
  167. * @return Time of last direct packet receive
  168. */
  169. uint64_t lastDirectReceive() const
  170. throw()
  171. {
  172. return std::max(_ipv4p.lastReceive,_ipv6p.lastReceive);
  173. }
  174. /**
  175. * @return Time of last direct packet send
  176. */
  177. uint64_t lastDirectSend() const
  178. throw()
  179. {
  180. return std::max(_ipv4p.lastSend,_ipv6p.lastSend);
  181. }
  182. /**
  183. * @return Time of most recent unicast frame (actual data transferred)
  184. */
  185. uint64_t lastUnicastFrame() const
  186. throw()
  187. {
  188. return _lastUnicastFrame;
  189. }
  190. /**
  191. * @return Time of most recent multicast frame
  192. */
  193. uint64_t lastMulticastFrame() const
  194. throw()
  195. {
  196. return _lastMulticastFrame;
  197. }
  198. /**
  199. * @return Time of most recent frame of any kind (unicast or multicast)
  200. */
  201. uint64_t lastFrame() const
  202. throw()
  203. {
  204. return std::max(_lastUnicastFrame,_lastMulticastFrame);
  205. }
  206. /**
  207. * @return Lowest of measured latencies of all paths or 0 if unknown
  208. */
  209. unsigned int latency() const
  210. throw()
  211. {
  212. if (_ipv4p.latency) {
  213. if (_ipv6p.latency)
  214. return std::min(_ipv4p.latency,_ipv6p.latency);
  215. else return _ipv4p.latency;
  216. } else if (_ipv6p.latency)
  217. return _ipv6p.latency;
  218. return 0;
  219. }
  220. /**
  221. * @param addr Remote address
  222. * @param latency Latency measurment
  223. */
  224. void setLatency(const InetAddress &addr,unsigned int latency)
  225. {
  226. if (addr == _ipv4p.addr) {
  227. _ipv4p.latency = latency;
  228. _dirty = true;
  229. } else if (addr == _ipv6p.addr) {
  230. _ipv6p.latency = latency;
  231. _dirty = true;
  232. }
  233. }
  234. /**
  235. * @return True if this peer has at least one direct IP address path
  236. */
  237. inline bool hasDirectPath() const
  238. throw()
  239. {
  240. return ((_ipv4p.addr)||(_ipv6p.addr));
  241. }
  242. /**
  243. * @param now Current time
  244. * @return True if hasDirectPath() is true and at least one path is active
  245. */
  246. inline bool hasActiveDirectPath(uint64_t now) const
  247. throw()
  248. {
  249. return ((_ipv4p.isActive(now))||(_ipv6p.isActive(now)));
  250. }
  251. /**
  252. * @return IPv4 direct address or null InetAddress if none
  253. */
  254. inline InetAddress ipv4Path() const
  255. throw()
  256. {
  257. return _ipv4p.addr;
  258. }
  259. /**
  260. * @return IPv6 direct address or null InetAddress if none
  261. */
  262. inline InetAddress ipv6Path() const
  263. throw()
  264. {
  265. return _ipv4p.addr;
  266. }
  267. /**
  268. * @return IPv4 direct address or null InetAddress if none
  269. */
  270. inline InetAddress ipv4ActivePath(uint64_t now) const
  271. throw()
  272. {
  273. if (_ipv4p.isActive(now))
  274. return _ipv4p.addr;
  275. return InetAddress();
  276. }
  277. /**
  278. * @return IPv6 direct address or null InetAddress if none
  279. */
  280. inline InetAddress ipv6ActivePath(uint64_t now) const
  281. throw()
  282. {
  283. if (_ipv6p.isActive(now))
  284. return _ipv6p.addr;
  285. return InetAddress();
  286. }
  287. /**
  288. * @return 256-bit encryption key
  289. */
  290. inline const unsigned char *cryptKey() const
  291. throw()
  292. {
  293. return _keys; // crypt key is first 32-byte key
  294. }
  295. /**
  296. * @return 256-bit MAC (message authentication code) key
  297. */
  298. inline const unsigned char *macKey() const
  299. throw()
  300. {
  301. return (_keys + 32); // mac key is second 32-byte key
  302. }
  303. /**
  304. * Set the remote version of the peer (not persisted)
  305. *
  306. * @param vmaj Major version
  307. * @param vmin Minor version
  308. * @param vrev Revision
  309. */
  310. inline void setRemoteVersion(unsigned int vmaj,unsigned int vmin,unsigned int vrev)
  311. {
  312. _vMajor = vmaj;
  313. _vMinor = vmin;
  314. _vRevision = vrev;
  315. }
  316. /**
  317. * @return Remote version in string form or '?' if unknown
  318. */
  319. inline std::string remoteVersion() const
  320. {
  321. if ((_vMajor)||(_vMinor)||(_vRevision)) {
  322. char tmp[32];
  323. sprintf(tmp,"%u.%u.%u",_vMajor,_vMinor,_vRevision);
  324. return std::string(tmp);
  325. }
  326. return std::string("?");
  327. }
  328. /**
  329. * Get and reset dirty flag
  330. *
  331. * @return Previous value of dirty flag before reset
  332. */
  333. inline bool getAndResetDirty()
  334. throw()
  335. {
  336. bool d = _dirty;
  337. _dirty = false;
  338. return d;
  339. }
  340. /**
  341. * @return Current value of dirty flag
  342. */
  343. inline bool dirty() const throw() { return _dirty; }
  344. template<unsigned int C>
  345. inline void serialize(Buffer<C> &b)
  346. throw(std::out_of_range)
  347. {
  348. b.append((unsigned char)2); // version
  349. b.append(_keys,sizeof(_keys));
  350. _id.serialize(b,false);
  351. _ipv4p.serialize(b);
  352. _ipv6p.serialize(b);
  353. b.append(_lastUnicastFrame);
  354. b.append(_lastMulticastFrame);
  355. }
  356. template<unsigned int C>
  357. inline unsigned int deserialize(const Buffer<C> &b,unsigned int startAt = 0)
  358. throw(std::out_of_range,std::invalid_argument)
  359. {
  360. unsigned int p = startAt;
  361. if (b[p++] != 2)
  362. throw std::invalid_argument("Peer: deserialize(): version mismatch");
  363. memcpy(_keys,b.field(p,sizeof(_keys)),sizeof(_keys)); p += sizeof(_keys);
  364. p += _id.deserialize(b,p);
  365. p += _ipv4p.deserialize(b,p);
  366. p += _ipv6p.deserialize(b,p);
  367. _lastUnicastFrame = b.template at<uint64_t>(p); p += sizeof(uint64_t);
  368. _lastMulticastFrame = b.template at<uint64_t>(p); p += sizeof(uint64_t);
  369. _vMajor = 0;
  370. _vMinor = 0;
  371. _vRevision = 0;
  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 _keys[32 * 2]; // crypt key[32], mac key[32]
  478. Identity _id;
  479. WanPath _ipv4p;
  480. WanPath _ipv6p;
  481. uint64_t _lastUnicastFrame;
  482. uint64_t _lastMulticastFrame;
  483. // Fields below this line are not persisted with serialize()
  484. unsigned int _vMajor,_vMinor,_vRevision;
  485. bool _dirty;
  486. AtomicCounter __refCount;
  487. };
  488. } // namespace ZeroTier
  489. // Add a swap() for shared ptr's to peers to speed up peer sorts
  490. namespace std {
  491. template<>
  492. inline void swap(ZeroTier::SharedPtr<ZeroTier::Peer> &a,ZeroTier::SharedPtr<ZeroTier::Peer> &b)
  493. {
  494. a.swap(b);
  495. }
  496. }
  497. #endif