Peer.hpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509
  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 <vector>
  31. #include <algorithm>
  32. #include <utility>
  33. #include <stdexcept>
  34. #include "Constants.hpp"
  35. #include "Path.hpp"
  36. #include "Address.hpp"
  37. #include "Utils.hpp"
  38. #include "Identity.hpp"
  39. #include "Logger.hpp"
  40. #include "RuntimeEnvironment.hpp"
  41. #include "InetAddress.hpp"
  42. #include "Packet.hpp"
  43. #include "SharedPtr.hpp"
  44. #include "Socket.hpp"
  45. #include "AtomicCounter.hpp"
  46. #include "NonCopyable.hpp"
  47. #include "Mutex.hpp"
  48. #define ZT_PEER_SERIALIZATION_VERSION 8
  49. namespace ZeroTier {
  50. /**
  51. * Peer on P2P Network
  52. */
  53. class Peer : NonCopyable
  54. {
  55. friend class SharedPtr<Peer>;
  56. public:
  57. /**
  58. * Construct an uninitialized peer (used with deserialize())
  59. */
  60. Peer();
  61. /**
  62. * Construct a new peer
  63. *
  64. * @param myIdentity Identity of THIS node (for key agreement)
  65. * @param peerIdentity Identity of peer
  66. * @throws std::runtime_error Key agreement with peer's identity failed
  67. */
  68. Peer(const Identity &myIdentity,const Identity &peerIdentity)
  69. throw(std::runtime_error);
  70. /**
  71. * @return Time peer record was last used in any way
  72. */
  73. inline uint64_t lastUsed() const
  74. throw()
  75. {
  76. return _lastUsed;
  77. }
  78. /**
  79. * @param now New time of last use
  80. */
  81. inline void use(uint64_t now)
  82. throw()
  83. {
  84. _lastUsed = now;
  85. }
  86. /**
  87. * @return This peer's ZT address (short for identity().address())
  88. */
  89. inline const Address &address() const throw() { return _id.address(); }
  90. /**
  91. * @return This peer's identity
  92. */
  93. inline const Identity &identity() const throw() { return _id; }
  94. /**
  95. * Must be called on authenticated packet receive from this peer
  96. *
  97. * @param _r Runtime environment
  98. * @param fromSock Socket from which packet was received
  99. * @param remoteAddr Internet address of sender
  100. * @param hops ZeroTier (not IP) hops
  101. * @param packetId Packet ID
  102. * @param verb Packet verb
  103. * @param inRePacketId Packet ID in reply to (for OK/ERROR, 0 otherwise)
  104. * @param inReVerb Verb in reply to (for OK/ERROR, VERB_NOP otherwise)
  105. * @param now Current time
  106. */
  107. void receive(
  108. const RuntimeEnvironment *_r,
  109. const SharedPtr<Socket> &fromSock,
  110. const InetAddress &remoteAddr,
  111. unsigned int hops,
  112. uint64_t packetId,
  113. Packet::Verb verb,
  114. uint64_t inRePacketId,
  115. Packet::Verb inReVerb,
  116. uint64_t now);
  117. /**
  118. * Send a packet to this peer using the most recently active direct path
  119. *
  120. * This does not relay. It returns false if there are no available active
  121. * paths.
  122. *
  123. * @param _r Runtime environment
  124. * @param data Data to send
  125. * @param len Length of packet
  126. * @param now Current time
  127. * @return True if packet appears to have been sent, false if no path or other error
  128. */
  129. bool send(const RuntimeEnvironment *_r,const void *data,unsigned int len,uint64_t now);
  130. /**
  131. * Send firewall opener to all UDP paths
  132. *
  133. * @param _r Runtime environment
  134. * @param now Current time
  135. * @return True if send appears successful for at least one address type
  136. */
  137. bool sendFirewallOpener(const RuntimeEnvironment *_r,uint64_t now);
  138. /**
  139. * Send HELLO to a peer via all direct paths available
  140. *
  141. * This begins attempting to use TCP paths if no ping response has been
  142. * received from any UDP path in more than ZT_TCP_FALLBACK_AFTER.
  143. *
  144. * @param _r Runtime environment
  145. * @param now Current time
  146. * @param firstSinceReset If true, this is the first ping sent since a network reset
  147. * @return True if send appears successful for at least one address type
  148. */
  149. bool sendPing(const RuntimeEnvironment *_r,uint64_t now,bool firstSinceReset);
  150. /**
  151. * @return All known direct paths to this peer
  152. */
  153. std::vector<Path> paths() const
  154. {
  155. Mutex::Lock _l(_lock);
  156. return _paths;
  157. }
  158. /**
  159. * @return Last successfully sent firewall opener for any path
  160. */
  161. inline uint64_t lastFirewallOpener() const
  162. throw()
  163. {
  164. uint64_t x = 0;
  165. Mutex::Lock _l(_lock);
  166. for(std::vector<Path>::const_iterator p(_paths.begin());p!=_paths.end();++p) {
  167. uint64_t l = p->lastFirewallOpener();
  168. if (l > x)
  169. x = l;
  170. }
  171. return x;
  172. }
  173. /**
  174. * @return Time of last direct packet receive for any path
  175. */
  176. inline uint64_t lastDirectReceive() const
  177. throw()
  178. {
  179. uint64_t x = 0;
  180. Mutex::Lock _l(_lock);
  181. for(std::vector<Path>::const_iterator p(_paths.begin());p!=_paths.end();++p) {
  182. uint64_t l = p->lastReceived();
  183. if (l > x)
  184. x = l;
  185. }
  186. return x;
  187. }
  188. /**
  189. * @return Time of last direct packet send for any path
  190. */
  191. inline uint64_t lastDirectSend() const
  192. throw()
  193. {
  194. uint64_t x = 0;
  195. Mutex::Lock _l(_lock);
  196. for(std::vector<Path>::const_iterator p(_paths.begin());p!=_paths.end();++p) {
  197. uint64_t l = p->lastSend();
  198. if (l > x)
  199. x = l;
  200. }
  201. return x;
  202. }
  203. /**
  204. * @return Time of most recent unicast frame received
  205. */
  206. inline uint64_t lastUnicastFrame() const
  207. throw()
  208. {
  209. return _lastUnicastFrame;
  210. }
  211. /**
  212. * @return Time of most recent multicast frame received
  213. */
  214. inline uint64_t lastMulticastFrame() const
  215. throw()
  216. {
  217. return _lastMulticastFrame;
  218. }
  219. /**
  220. * @return Time of most recent frame of any kind (unicast or multicast)
  221. */
  222. inline uint64_t lastFrame() const
  223. throw()
  224. {
  225. return std::max(_lastUnicastFrame,_lastMulticastFrame);
  226. }
  227. /**
  228. * @return Time we last announced state TO this peer, such as multicast LIKEs
  229. */
  230. inline uint64_t lastAnnouncedTo() const
  231. throw()
  232. {
  233. return _lastAnnouncedTo;
  234. }
  235. /**
  236. * @return Current latency or 0 if unknown (max: 65535)
  237. */
  238. inline unsigned int latency() const
  239. throw()
  240. {
  241. unsigned int l = _latency;
  242. return std::min(l,(unsigned int)65535);
  243. }
  244. /**
  245. * Update latency with a new direct measurment
  246. *
  247. * @param l Direct latency measurment in ms
  248. */
  249. inline void addDirectLatencyMeasurment(unsigned int l)
  250. throw()
  251. {
  252. if (l > 65535) l = 65535;
  253. unsigned int ol = _latency;
  254. if ((ol > 0)&&(ol < 10000))
  255. _latency = (ol + l) / 2;
  256. else _latency = l;
  257. }
  258. /**
  259. * @return True if this peer has at least one direct IP address path
  260. */
  261. inline bool hasDirectPath() const
  262. throw()
  263. {
  264. Mutex::Lock _l(_lock);
  265. return (!_paths.empty());
  266. }
  267. /**
  268. * @param now Current time
  269. * @return True if this peer has at least one active or fixed direct path
  270. */
  271. inline bool hasActiveDirectPath(uint64_t now) const
  272. throw()
  273. {
  274. Mutex::Lock _l(_lock);
  275. for(std::vector<Path>::const_iterator p(_paths.begin());p!=_paths.end();++p) {
  276. if (p->active(now))
  277. return true;
  278. }
  279. return false;
  280. }
  281. /**
  282. * Add a path (if we don't already have it)
  283. *
  284. * @param p New path to add
  285. */
  286. inline void addPath(const Path &newp)
  287. {
  288. Mutex::Lock _l(_lock);
  289. for(std::vector<Path>::iterator p(_paths.begin());p!=_paths.end();++p) {
  290. if (*p == newp) {
  291. p->setFixed(newp.fixed());
  292. return;
  293. }
  294. }
  295. _paths.push_back(newp);
  296. }
  297. /**
  298. * Clear paths
  299. *
  300. * @param fixedToo If true, clear fixed paths as well as learned ones
  301. */
  302. inline void clearPaths(bool fixedToo)
  303. {
  304. std::vector<Path> npv;
  305. Mutex::Lock _l(_lock);
  306. if (!fixedToo) {
  307. for(std::vector<Path>::const_iterator p(_paths.begin());p!=_paths.end();++p) {
  308. if (p->fixed())
  309. npv.push_back(*p);
  310. }
  311. }
  312. _paths = npv;
  313. }
  314. /**
  315. * @return 256-bit secret symmetric encryption key
  316. */
  317. inline const unsigned char *key() const throw() { return _key; }
  318. /**
  319. * Set the currently known remote version of this peer's client
  320. *
  321. * @param vmaj Major version
  322. * @param vmin Minor version
  323. * @param vrev Revision
  324. */
  325. inline void setRemoteVersion(unsigned int vmaj,unsigned int vmin,unsigned int vrev)
  326. {
  327. _vMajor = vmaj;
  328. _vMinor = vmin;
  329. _vRevision = vrev;
  330. }
  331. /**
  332. * @return Remote version in string form or '?' if unknown
  333. */
  334. inline std::string remoteVersion() const
  335. {
  336. if ((_vMajor)||(_vMinor)||(_vRevision)) {
  337. char tmp[32];
  338. Utils::snprintf(tmp,sizeof(tmp),"%u.%u.%u",_vMajor,_vMinor,_vRevision);
  339. return std::string(tmp);
  340. }
  341. return std::string("?");
  342. }
  343. /**
  344. * @return True if this Peer is initialized with something
  345. */
  346. inline operator bool() const throw() { return (_id); }
  347. /**
  348. * @param now Current time
  349. * @param v4 Result parameter to receive active IPv4 address, if any
  350. * @param v6 Result parameter to receive active IPv6 address, if any
  351. */
  352. inline void getActiveUdpPathAddresses(uint64_t now,InetAddress &v4,InetAddress &v6) const
  353. {
  354. bool gotV4 = false,gotV6 = false;
  355. Mutex::Lock _l(_lock);
  356. for(std::vector<Path>::const_iterator p(_paths.begin());p!=_paths.end();++p) {
  357. if (!gotV4) {
  358. if ((!p->tcp())&&(p->address().isV4())&&(p->active(now))) {
  359. gotV4 = true;
  360. v4 = p->address();
  361. }
  362. } else if (!gotV6) {
  363. if ((!p->tcp())&&(p->address().isV6())&&(p->active(now))) {
  364. gotV6 = true;
  365. v6 = p->address();
  366. }
  367. } else break;
  368. }
  369. }
  370. /**
  371. * Find a common set of addresses by which two peers can link, if any
  372. *
  373. * @param a Peer A
  374. * @param b Peer B
  375. * @param now Current time
  376. * @return Pair: B's address (to send to A), A's address (to send to B)
  377. */
  378. static inline std::pair<InetAddress,InetAddress> findCommonGround(const Peer &a,const Peer &b,uint64_t now)
  379. throw()
  380. {
  381. std::pair<InetAddress,InetAddress> v4,v6;
  382. b.getActiveUdpPathAddresses(now,v4.first,v6.first);
  383. a.getActiveUdpPathAddresses(now,v4.second,v6.second);
  384. if ((v6.first)&&(v6.second))
  385. return v6;
  386. if ((v4.first)&&(v4.second))
  387. return v4;
  388. return std::pair<InetAddress,InetAddress>();
  389. }
  390. template<unsigned int C>
  391. inline void serialize(Buffer<C> &b) const
  392. {
  393. Mutex::Lock _l(_lock);
  394. b.append((unsigned char)ZT_PEER_SERIALIZATION_VERSION);
  395. _id.serialize(b,false);
  396. b.append(_key,sizeof(_key));
  397. b.append(_lastUsed);
  398. b.append(_lastUnicastFrame);
  399. b.append(_lastMulticastFrame);
  400. b.append(_lastAnnouncedTo);
  401. b.append((uint16_t)_vMajor);
  402. b.append((uint16_t)_vMinor);
  403. b.append((uint16_t)_vRevision);
  404. b.append((uint16_t)_latency);
  405. b.append((uint16_t)_paths.size());
  406. for(std::vector<Path>::const_iterator p(_paths.begin());p!=_paths.end();++p)
  407. p->serialize(b);
  408. }
  409. template<unsigned int C>
  410. inline unsigned int deserialize(const Buffer<C> &b,unsigned int startAt = 0)
  411. {
  412. unsigned int p = startAt;
  413. if (b[p++] != ZT_PEER_SERIALIZATION_VERSION)
  414. throw std::invalid_argument("Peer: deserialize(): version mismatch");
  415. Mutex::Lock _l(_lock);
  416. p += _id.deserialize(b,p);
  417. memcpy(_key,b.field(p,sizeof(_key)),sizeof(_key)); p += sizeof(_key);
  418. _lastUsed = b.template at<uint64_t>(p); p += sizeof(uint64_t);
  419. _lastUnicastFrame = b.template at<uint64_t>(p); p += sizeof(uint64_t);
  420. _lastMulticastFrame = b.template at<uint64_t>(p); p += sizeof(uint64_t);
  421. _lastAnnouncedTo = b.template at<uint64_t>(p); p += sizeof(uint64_t);
  422. _vMajor = b.template at<uint16_t>(p); p += sizeof(uint16_t);
  423. _vMinor = b.template at<uint16_t>(p); p += sizeof(uint16_t);
  424. _vRevision = b.template at<uint16_t>(p); p += sizeof(uint16_t);
  425. _latency = b.template at<uint16_t>(p); p += sizeof(uint16_t);
  426. unsigned int npaths = (unsigned int)b.template at<uint16_t>(p); p += sizeof(uint16_t);
  427. _paths.clear();
  428. for(unsigned int i=0;i<npaths;++i) {
  429. _paths.push_back(Path());
  430. p += _paths.back().deserialize(b,p);
  431. }
  432. return (p - startAt);
  433. }
  434. private:
  435. unsigned char _key[ZT_PEER_SECRET_KEY_LENGTH];
  436. Identity _id;
  437. std::vector<Path> _paths;
  438. volatile uint64_t _lastUsed;
  439. volatile uint64_t _lastUnicastFrame;
  440. volatile uint64_t _lastMulticastFrame;
  441. volatile uint64_t _lastAnnouncedTo;
  442. volatile unsigned int _vMajor;
  443. volatile unsigned int _vMinor;
  444. volatile unsigned int _vRevision;
  445. volatile unsigned int _latency;
  446. Mutex _lock;
  447. AtomicCounter __refCount;
  448. };
  449. } // namespace ZeroTier
  450. // Add a swap() for shared ptr's to peers to speed up peer sorts
  451. namespace std {
  452. template<>
  453. inline void swap(ZeroTier::SharedPtr<ZeroTier::Peer> &a,ZeroTier::SharedPtr<ZeroTier::Peer> &b)
  454. {
  455. a.swap(b);
  456. }
  457. }
  458. #endif