Peer.hpp 13 KB

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