1
0

Peer.hpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492
  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) * 5) + \
  55. sizeof(uint16_t) + \
  56. 1 + \
  57. sizeof(uint16_t) + \
  58. 16 + \
  59. 1 \
  60. ) * 2) + \
  61. 64 \
  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. * @param _r Runtime environment
  103. * @param localPort Local port on which packet was received
  104. * @param fromAddr Internet address of sender
  105. * @param hops ZeroTier (not IP) hops
  106. * @param verb Packet verb
  107. * @param now Current time
  108. */
  109. void onReceive(const RuntimeEnvironment *_r,Demarc::Port localPort,const InetAddress &fromAddr,unsigned int hops,Packet::Verb verb,uint64_t now);
  110. /**
  111. * Send a UDP packet to this peer
  112. *
  113. * If the active link is timed out (no receives for ping timeout ms), then
  114. * the active link number is incremented after send. This causes sends to
  115. * cycle through links if there is no clear active link. This also happens
  116. * if the send fails for some reason.
  117. *
  118. * @param _r Runtime environment
  119. * @param data Data to send
  120. * @param len Length of packet
  121. * @param relay This is a relay on behalf of another peer (verb is ignored)
  122. * @param verb Packet verb (if not relay)
  123. * @param now Current time
  124. * @return True if packet appears to have been sent, false on local failure
  125. */
  126. bool send(const RuntimeEnvironment *_r,const void *data,unsigned int len,bool relay,Packet::Verb verb,uint64_t now);
  127. /**
  128. * Send firewall opener to active link
  129. *
  130. * @param _r Runtime environment
  131. * @param now Current time
  132. * @return True if send appears successful for at least one address type
  133. */
  134. bool sendFirewallOpener(const RuntimeEnvironment *_r,uint64_t now);
  135. /**
  136. * Set an address to reach this peer
  137. *
  138. * @param addr Address to set
  139. * @param fixed If true, address is fixed (won't be changed on packet receipt)
  140. */
  141. void setPathAddress(const InetAddress &addr,bool fixed);
  142. /**
  143. * Clear the fixed flag for an address type
  144. *
  145. * @param t Type to clear, or TYPE_NULL to clear flag on all types
  146. */
  147. void clearFixedFlag(InetAddress::AddressType t);
  148. /**
  149. * @return Last successfully sent firewall opener
  150. */
  151. uint64_t lastFirewallOpener() const
  152. throw()
  153. {
  154. return std::max(_ipv4p.lastFirewallOpener,_ipv6p.lastFirewallOpener);
  155. }
  156. /**
  157. * @return Time of last direct packet receive
  158. */
  159. uint64_t lastDirectReceive() const
  160. throw()
  161. {
  162. return std::max(_ipv4p.lastReceive,_ipv6p.lastReceive);
  163. }
  164. /**
  165. * @return Time of last direct packet send
  166. */
  167. uint64_t lastDirectSend() const
  168. throw()
  169. {
  170. return std::max(_ipv4p.lastSend,_ipv6p.lastSend);
  171. }
  172. /**
  173. * @return Time of most recent unicast frame (actual data transferred)
  174. */
  175. uint64_t lastUnicastFrame() const
  176. throw()
  177. {
  178. return std::max(_ipv4p.lastUnicastFrame,_ipv6p.lastUnicastFrame);
  179. }
  180. /**
  181. * @return Lowest of measured latencies of all paths or 0 if unknown
  182. */
  183. unsigned int latency() const
  184. throw()
  185. {
  186. if (_ipv4p.latency) {
  187. if (_ipv6p.latency)
  188. return std::min(_ipv4p.latency,_ipv6p.latency);
  189. else return _ipv4p.latency;
  190. } else if (_ipv6p.latency)
  191. return _ipv6p.latency;
  192. return 0;
  193. }
  194. /**
  195. * @param latency measurment for IPv4 path
  196. */
  197. void setV4Latency(unsigned int latency)
  198. {
  199. _ipv4p.latency = latency;
  200. _dirty = true;
  201. }
  202. /**
  203. * @param latency Latency measurment for IPv6 path
  204. */
  205. void setV6Latency(unsigned int latency)
  206. {
  207. _ipv6p.latency = latency;
  208. _dirty = true;
  209. }
  210. /**
  211. * @return True if this peer has at least one direct IP address path
  212. */
  213. inline bool hasDirectPath() const
  214. throw()
  215. {
  216. return ((_ipv4p.addr)||(_ipv6p.addr));
  217. }
  218. /**
  219. * @param now Current time
  220. * @return True if hasDirectPath() is true and at least one path is active
  221. */
  222. inline bool hasActiveDirectPath(uint64_t now) const
  223. throw()
  224. {
  225. return ((_ipv4p.isActive(now))||(_ipv6p.isActive(now)));
  226. }
  227. /**
  228. * @return IPv4 direct address or null InetAddress if none
  229. */
  230. inline InetAddress ipv4Path() const
  231. throw()
  232. {
  233. return _ipv4p.addr;
  234. }
  235. /**
  236. * @return IPv6 direct address or null InetAddress if none
  237. */
  238. inline InetAddress ipv6Path() const
  239. throw()
  240. {
  241. return _ipv4p.addr;
  242. }
  243. /**
  244. * @return IPv4 direct address or null InetAddress if none
  245. */
  246. inline InetAddress ipv4ActivePath(uint64_t now) const
  247. throw()
  248. {
  249. if (_ipv4p.isActive(now))
  250. return _ipv4p.addr;
  251. return InetAddress();
  252. }
  253. /**
  254. * @return IPv6 direct address or null InetAddress if none
  255. */
  256. inline InetAddress ipv6ActivePath(uint64_t now) const
  257. throw()
  258. {
  259. if (_ipv6p.isActive(now))
  260. return _ipv6p.addr;
  261. return InetAddress();
  262. }
  263. /**
  264. * @return 256-bit encryption key
  265. */
  266. inline const unsigned char *cryptKey() const
  267. throw()
  268. {
  269. return _keys; // crypt key is first 32-byte key
  270. }
  271. /**
  272. * @return 256-bit MAC (message authentication code) key
  273. */
  274. inline const unsigned char *macKey() const
  275. throw()
  276. {
  277. return (_keys + 32); // mac key is second 32-byte key
  278. }
  279. /**
  280. * Get and reset dirty flag
  281. *
  282. * @return Previous value of dirty flag before reset
  283. */
  284. inline bool getAndResetDirty()
  285. throw()
  286. {
  287. bool d = _dirty;
  288. _dirty = false;
  289. return d;
  290. }
  291. /**
  292. * @return Current value of dirty flag
  293. */
  294. inline bool dirty() const throw() { return _dirty; }
  295. template<unsigned int C>
  296. inline void serialize(Buffer<C> &b)
  297. throw(std::out_of_range)
  298. {
  299. b.append((unsigned char)1); // version
  300. b.append(_keys,sizeof(_keys));
  301. _id.serialize(b,false);
  302. _ipv4p.serialize(b);
  303. _ipv6p.serialize(b);
  304. }
  305. template<unsigned int C>
  306. inline unsigned int deserialize(const Buffer<C> &b,unsigned int startAt = 0)
  307. throw(std::out_of_range,std::invalid_argument)
  308. {
  309. unsigned int p = startAt;
  310. if (b[p++] != 1)
  311. throw std::invalid_argument("Peer: deserialize(): version mismatch");
  312. memcpy(_keys,b.field(p,sizeof(_keys)),sizeof(_keys)); p += sizeof(_keys);
  313. p += _id.deserialize(b,p);
  314. p += _ipv4p.deserialize(b,p);
  315. p += _ipv6p.deserialize(b,p);
  316. _dirty = false;
  317. return (p - startAt);
  318. }
  319. /**
  320. * @return True if this Peer is initialized with something
  321. */
  322. inline operator bool() const throw() { return (_id); }
  323. /**
  324. * Find a common set of addresses by which two peers can link, if any
  325. *
  326. * @param a Peer A
  327. * @param b Peer B
  328. * @param now Current time
  329. * @return Pair: B's address to send to A, A's address to send to B
  330. */
  331. static inline std::pair<InetAddress,InetAddress> findCommonGround(const Peer &a,const Peer &b,uint64_t now)
  332. throw()
  333. {
  334. if ((a._ipv6p.isActive(now))&&(b._ipv6p.isActive(now)))
  335. return std::pair<InetAddress,InetAddress>(b._ipv6p.addr,a._ipv6p.addr);
  336. else if ((a._ipv4p.isActive(now))&&(b._ipv4p.isActive(now)))
  337. return std::pair<InetAddress,InetAddress>(b._ipv4p.addr,a._ipv4p.addr);
  338. else if ((a._ipv6p.addr)&&(b._ipv6p.addr))
  339. return std::pair<InetAddress,InetAddress>(b._ipv6p.addr,a._ipv6p.addr);
  340. else if ((a._ipv4p.addr)&&(b._ipv4p.addr))
  341. return std::pair<InetAddress,InetAddress>(b._ipv4p.addr,a._ipv4p.addr);
  342. return std::pair<InetAddress,InetAddress>();
  343. }
  344. private:
  345. class WanPath
  346. {
  347. public:
  348. WanPath() :
  349. lastSend(0),
  350. lastReceive(0),
  351. lastUnicastFrame(0),
  352. lastFirewallOpener(0),
  353. localPort(Demarc::ANY_PORT),
  354. latency(0),
  355. addr(),
  356. fixed(false)
  357. {
  358. }
  359. inline bool isActive(const uint64_t now) const
  360. throw()
  361. {
  362. return ((addr)&&((now - lastReceive) < ZT_PEER_LINK_ACTIVITY_TIMEOUT));
  363. }
  364. template<unsigned int C>
  365. inline void serialize(Buffer<C> &b)
  366. throw(std::out_of_range)
  367. {
  368. b.append(lastSend);
  369. b.append(lastReceive);
  370. b.append(lastUnicastFrame);
  371. b.append(lastFirewallOpener);
  372. b.append(Demarc::portToInt(localPort));
  373. b.append((uint16_t)latency);
  374. b.append((unsigned char)addr.type());
  375. switch(addr.type()) {
  376. case InetAddress::TYPE_NULL:
  377. break;
  378. case InetAddress::TYPE_IPV4:
  379. b.append(addr.rawIpData(),4);
  380. b.append((uint16_t)addr.port());
  381. break;
  382. case InetAddress::TYPE_IPV6:
  383. b.append(addr.rawIpData(),16);
  384. b.append((uint16_t)addr.port());
  385. break;
  386. }
  387. b.append(fixed ? (unsigned char)1 : (unsigned char)0);
  388. }
  389. template<unsigned int C>
  390. inline unsigned int deserialize(const Buffer<C> &b,unsigned int startAt = 0)
  391. throw(std::out_of_range,std::invalid_argument)
  392. {
  393. unsigned int p = startAt;
  394. lastSend = b.template at<uint64_t>(p); p += sizeof(uint64_t);
  395. lastReceive = b.template at<uint64_t>(p); p += sizeof(uint64_t);
  396. lastUnicastFrame = b.template at<uint64_t>(p); p += sizeof(uint64_t);
  397. lastFirewallOpener = b.template at<uint64_t>(p); p += sizeof(uint64_t);
  398. localPort = Demarc::intToPort(b.template at<uint64_t>(p)); p += sizeof(uint64_t);
  399. latency = b.template at<uint16_t>(p); p += sizeof(uint16_t);
  400. switch ((InetAddress::AddressType)b[p++]) {
  401. case InetAddress::TYPE_NULL:
  402. addr.zero();
  403. break;
  404. case InetAddress::TYPE_IPV4:
  405. addr.set(b.field(p,4),4,b.template at<uint16_t>(p + 4));
  406. p += 4 + sizeof(uint16_t);
  407. break;
  408. case InetAddress::TYPE_IPV6:
  409. addr.set(b.field(p,16),16,b.template at<uint16_t>(p + 16));
  410. p += 16 + sizeof(uint16_t);
  411. break;
  412. }
  413. fixed = (b[p++] != 0);
  414. return (p - startAt);
  415. }
  416. uint64_t lastSend;
  417. uint64_t lastReceive;
  418. uint64_t lastUnicastFrame;
  419. uint64_t lastFirewallOpener;
  420. Demarc::Port localPort; // ANY_PORT if not defined
  421. unsigned int latency; // 0 if never determined
  422. InetAddress addr; // null InetAddress if path is undefined
  423. bool fixed; // do not learn address from received packets
  424. };
  425. unsigned char _keys[32 * 2]; // crypt key[32], mac key[32]
  426. Identity _id;
  427. WanPath _ipv4p;
  428. WanPath _ipv6p;
  429. // Fields below this line are not persisted with serialize()
  430. bool _dirty;
  431. AtomicCounter __refCount;
  432. };
  433. } // namespace ZeroTier
  434. #endif