Peer.hpp 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405
  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 "AtomicCounter.hpp"
  45. #include "NonCopyable.hpp"
  46. #include "Mutex.hpp"
  47. // Increment if serialization has changed
  48. #define ZT_PEER_SERIALIZATION_VERSION 7
  49. namespace ZeroTier {
  50. /**
  51. * Peer on P2P Network
  52. */
  53. class Peer : NonCopyable
  54. {
  55. friend class SharedPtr<Peer>;
  56. private:
  57. ~Peer() {}
  58. public:
  59. Peer();
  60. /**
  61. * Construct a new peer
  62. *
  63. * @param myIdentity Identity of THIS node (for key agreement)
  64. * @param peerIdentity Identity of peer
  65. * @throws std::runtime_error Key agreement with peer's identity failed
  66. */
  67. Peer(const Identity &myIdentity,const Identity &peerIdentity)
  68. throw(std::runtime_error);
  69. /**
  70. * @return Time peer record was last used in any way
  71. */
  72. inline uint64_t lastUsed() const throw() { return _lastUsed; }
  73. /**
  74. * @param now New time of last use
  75. */
  76. inline void setLastUsed(uint64_t now) throw() { _lastUsed = now; }
  77. /**
  78. * @return This peer's ZT address (short for identity().address())
  79. */
  80. inline const Address &address() const throw() { return _id.address(); }
  81. /**
  82. * @return This peer's identity
  83. */
  84. inline const Identity &identity() const throw() { return _id; }
  85. /**
  86. * Must be called on authenticated packet receive from this peer
  87. *
  88. * @param _r Runtime environment
  89. * @param localPort Local port on which packet was received
  90. * @param remoteAddr Internet address of sender
  91. * @param hops ZeroTier (not IP) hops
  92. * @param packetId Packet ID
  93. * @param verb Packet verb
  94. * @param inRePacketId Packet ID in reply to (for OK/ERROR, 0 otherwise)
  95. * @param inReVerb Verb in reply to (for OK/ERROR, VERB_NOP otherwise)
  96. * @param now Current time
  97. */
  98. void onReceive(
  99. const RuntimeEnvironment *_r,
  100. const InetAddress &remoteAddr,
  101. unsigned int hops,
  102. uint64_t packetId,
  103. Packet::Verb verb,
  104. uint64_t inRePacketId,
  105. Packet::Verb inReVerb,
  106. uint64_t now);
  107. /**
  108. * Send a packet to this peer using the most recently active direct path
  109. *
  110. * This does not relay. It returns false if there are no available active
  111. * paths.
  112. *
  113. * @param _r Runtime environment
  114. * @param data Data to send
  115. * @param len Length of packet
  116. * @param now Current time
  117. * @return True if packet appears to have been sent, false if no path or other error
  118. */
  119. bool send(const RuntimeEnvironment *_r,const void *data,unsigned int len,uint64_t now);
  120. /**
  121. * Send firewall opener to active link
  122. *
  123. * @param _r Runtime environment
  124. * @param now Current time
  125. * @return True if send appears successful for at least one address type
  126. */
  127. bool sendFirewallOpener(const RuntimeEnvironment *_r,uint64_t now);
  128. /**
  129. * Send HELLO to a peer via all active direct paths available
  130. *
  131. * This begins attempting to use TCP paths if no ping response has been
  132. * received from any UDP path in more than ZT_TCP_FALLBACK_AFTER.
  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. * @return Last successfully sent firewall opener
  141. */
  142. inline uint64_t lastFirewallOpener() const
  143. throw()
  144. {
  145. }
  146. /**
  147. * @return Time of last direct packet receive
  148. */
  149. inline uint64_t lastDirectReceive() const
  150. throw()
  151. {
  152. }
  153. /**
  154. * @return Time of last direct packet send
  155. */
  156. inline uint64_t lastDirectSend() const
  157. throw()
  158. {
  159. }
  160. /**
  161. * @return Time of most recent unicast frame received
  162. */
  163. inline uint64_t lastUnicastFrame() const
  164. throw()
  165. {
  166. return _lastUnicastFrame;
  167. }
  168. /**
  169. * @return Time of most recent multicast frame received
  170. */
  171. inline uint64_t lastMulticastFrame() const
  172. throw()
  173. {
  174. return _lastMulticastFrame;
  175. }
  176. /**
  177. * @return Time of most recent frame of any kind (unicast or multicast)
  178. */
  179. inline uint64_t lastFrame() const
  180. throw()
  181. {
  182. return std::max(_lastUnicastFrame,_lastMulticastFrame);
  183. }
  184. /**
  185. * @return Time we last announced state TO this peer, such as multicast LIKEs
  186. */
  187. inline uint64_t lastAnnouncedTo() const
  188. throw()
  189. {
  190. return _lastAnnouncedTo;
  191. }
  192. /**
  193. * @return Current latency or 0 if unknown (max: 65535)
  194. */
  195. inline unsigned int latency() const
  196. throw()
  197. {
  198. unsigned int l = _latency;
  199. return std::min(l,(unsigned int)65535);
  200. }
  201. /**
  202. * Update latency with a new direct measurment
  203. *
  204. * @param l Direct latency measurment in ms
  205. */
  206. inline void addDirectLatencyMeasurment(unsigned int l)
  207. throw()
  208. {
  209. if (l > 65535) l = 65535;
  210. unsigned int ol = _latency;
  211. if ((ol > 0)&&(ol < 10000))
  212. _latency = (ol + l) / 2;
  213. else _latency = l;
  214. }
  215. /**
  216. * @return True if this peer has at least one direct IP address path
  217. */
  218. inline bool hasDirectPath() const
  219. throw()
  220. {
  221. }
  222. /**
  223. * @param now Current time
  224. * @return True if this peer has at least one active or fixed direct path
  225. */
  226. inline bool hasActiveDirectPath(uint64_t now) const
  227. throw()
  228. {
  229. }
  230. /**
  231. * Add a path (if we don't already have it)
  232. *
  233. * @param p New path to add
  234. */
  235. inline void addPath(const Path &p)
  236. {
  237. }
  238. /**
  239. * Clear paths
  240. *
  241. * @param fixedToo If true, clear fixed paths as well as learned ones
  242. */
  243. inline void clearPaths(bool fixedToo)
  244. {
  245. }
  246. /**
  247. * @return 256-bit secret symmetric encryption key
  248. */
  249. inline const unsigned char *key() const throw() { return _key; }
  250. /**
  251. * Set the currently known remote version of this peer's client
  252. *
  253. * @param vmaj Major version
  254. * @param vmin Minor version
  255. * @param vrev Revision
  256. */
  257. inline void setRemoteVersion(unsigned int vmaj,unsigned int vmin,unsigned int vrev)
  258. {
  259. _vMajor = vmaj;
  260. _vMinor = vmin;
  261. _vRevision = vrev;
  262. }
  263. /**
  264. * @return Remote version in string form or '?' if unknown
  265. */
  266. inline std::string remoteVersion() const
  267. {
  268. if ((_vMajor)||(_vMinor)||(_vRevision)) {
  269. char tmp[32];
  270. Utils::snprintf(tmp,sizeof(tmp),"%u.%u.%u",_vMajor,_vMinor,_vRevision);
  271. return std::string(tmp);
  272. }
  273. return std::string("?");
  274. }
  275. /**
  276. * @return True if this Peer is initialized with something
  277. */
  278. inline operator bool() const throw() { return (_id); }
  279. /**
  280. * Find a common set of addresses by which two peers can link, if any
  281. *
  282. * @param a Peer A
  283. * @param b Peer B
  284. * @param now Current time
  285. * @return Pair: B's address to send to A, A's address to send to B
  286. */
  287. static inline std::pair<InetAddress,InetAddress> findCommonGround(const Peer &a,const Peer &b,uint64_t now)
  288. throw()
  289. {
  290. if ((a._ipv6p.isActive(now))&&(b._ipv6p.isActive(now)))
  291. return std::pair<InetAddress,InetAddress>(b._ipv6p.addr,a._ipv6p.addr);
  292. else if ((a._ipv4p.isActive(now))&&(b._ipv4p.isActive(now)))
  293. return std::pair<InetAddress,InetAddress>(b._ipv4p.addr,a._ipv4p.addr);
  294. else if ((a._ipv6p.addr)&&(b._ipv6p.addr))
  295. return std::pair<InetAddress,InetAddress>(b._ipv6p.addr,a._ipv6p.addr);
  296. else if ((a._ipv4p.addr)&&(b._ipv4p.addr))
  297. return std::pair<InetAddress,InetAddress>(b._ipv4p.addr,a._ipv4p.addr);
  298. return std::pair<InetAddress,InetAddress>();
  299. }
  300. template<unsigned int C>
  301. inline void serialize(Buffer<C> &b)
  302. {
  303. b.append((unsigned char)ZT_PEER_SERIALIZATION_VERSION);
  304. b.append(_key,sizeof(_key));
  305. _id.serialize(b,false);
  306. _ipv4p.serialize(b);
  307. _ipv6p.serialize(b);
  308. b.append(_lastUsed);
  309. b.append(_lastUnicastFrame);
  310. b.append(_lastMulticastFrame);
  311. b.append(_lastAnnouncedTo);
  312. b.append((uint16_t)_vMajor);
  313. b.append((uint16_t)_vMinor);
  314. b.append((uint16_t)_vRevision);
  315. b.append((uint16_t)_latency);
  316. }
  317. template<unsigned int C>
  318. inline unsigned int deserialize(const Buffer<C> &b,unsigned int startAt = 0)
  319. {
  320. unsigned int p = startAt;
  321. if (b[p++] != ZT_PEER_SERIALIZATION_VERSION)
  322. throw std::invalid_argument("Peer: deserialize(): version mismatch");
  323. memcpy(_key,b.field(p,sizeof(_key)),sizeof(_key)); p += sizeof(_key);
  324. p += _id.deserialize(b,p);
  325. p += _ipv4p.deserialize(b,p);
  326. p += _ipv6p.deserialize(b,p);
  327. _lastUsed = b.template at<uint64_t>(p); p += sizeof(uint64_t);
  328. _lastUnicastFrame = b.template at<uint64_t>(p); p += sizeof(uint64_t);
  329. _lastMulticastFrame = b.template at<uint64_t>(p); p += sizeof(uint64_t);
  330. _lastAnnouncedTo = b.template at<uint64_t>(p); p += sizeof(uint64_t);
  331. _vMajor = b.template at<uint16_t>(p); p += sizeof(uint16_t);
  332. _vMinor = b.template at<uint16_t>(p); p += sizeof(uint16_t);
  333. _vRevision = b.template at<uint16_t>(p); p += sizeof(uint16_t);
  334. _latency = b.template at<uint16_t>(p); p += sizeof(uint16_t);
  335. return (p - startAt);
  336. }
  337. private:
  338. unsigned char _key[ZT_PEER_SECRET_KEY_LENGTH];
  339. Identity _id;
  340. std::vector<Path> _paths;
  341. volatile uint64_t _lastUsed;
  342. volatile uint64_t _lastUnicastFrame;
  343. volatile uint64_t _lastMulticastFrame;
  344. volatile uint64_t _lastAnnouncedTo;
  345. volatile unsigned int _vMajor,_vMinor,_vRevision;
  346. volatile unsigned int _latency;
  347. AtomicCounter __refCount;
  348. };
  349. } // namespace ZeroTier
  350. // Add a swap() for shared ptr's to peers to speed up peer sorts
  351. namespace std {
  352. template<>
  353. inline void swap(ZeroTier::SharedPtr<ZeroTier::Peer> &a,ZeroTier::SharedPtr<ZeroTier::Peer> &b)
  354. {
  355. a.swap(b);
  356. }
  357. }
  358. #endif