Topology.hpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471
  1. /*
  2. * Copyright (c)2019 ZeroTier, Inc.
  3. *
  4. * Use of this software is governed by the Business Source License included
  5. * in the LICENSE.TXT file in the project's root directory.
  6. *
  7. * Change Date: 2026-01-01
  8. *
  9. * On the date above, in accordance with the Business Source License, use
  10. * of this software will be governed by version 2.0 of the Apache License.
  11. */
  12. /****/
  13. #ifndef ZT_TOPOLOGY_HPP
  14. #define ZT_TOPOLOGY_HPP
  15. #include "../include/ZeroTierOne.h"
  16. #include "Address.hpp"
  17. #include "Constants.hpp"
  18. #include "Hashtable.hpp"
  19. #include "Identity.hpp"
  20. #include "InetAddress.hpp"
  21. #include "Mutex.hpp"
  22. #include "Path.hpp"
  23. #include "Peer.hpp"
  24. #include "World.hpp"
  25. #include <algorithm>
  26. #include <stdexcept>
  27. #include <stdio.h>
  28. #include <string.h>
  29. #include <utility>
  30. #include <vector>
  31. namespace ZeroTier {
  32. class RuntimeEnvironment;
  33. /**
  34. * Database of network topology
  35. */
  36. class Topology {
  37. public:
  38. Topology(const RuntimeEnvironment* renv, void* tPtr);
  39. ~Topology();
  40. /**
  41. * Add a peer to database
  42. *
  43. * This will not replace existing peers. In that case the existing peer
  44. * record is returned.
  45. *
  46. * @param tPtr Thread pointer to be handed through to any callbacks called as a result of this call
  47. * @param peer Peer to add
  48. * @return New or existing peer (should replace 'peer')
  49. */
  50. SharedPtr<Peer> addPeer(void* tPtr, const SharedPtr<Peer>& peer);
  51. /**
  52. * Get a peer from its address
  53. *
  54. * @param tPtr Thread pointer to be handed through to any callbacks called as a result of this call
  55. * @param zta ZeroTier address of peer
  56. * @return Peer or NULL if not found
  57. */
  58. SharedPtr<Peer> getPeer(void* tPtr, const Address& zta);
  59. /**
  60. * @param tPtr Thread pointer to be handed through to any callbacks called as a result of this call
  61. * @param zta ZeroTier address of peer
  62. * @return Identity or NULL identity if not found
  63. */
  64. Identity getIdentity(void* tPtr, const Address& zta);
  65. /**
  66. * Get a peer only if it is presently in memory (no disk cache)
  67. *
  68. * This also does not update the lastUsed() time for peers, which means
  69. * that it won't prevent them from falling out of RAM. This is currently
  70. * used in the Cluster code to update peer info without forcing all peers
  71. * across the entire cluster to remain in memory cache.
  72. *
  73. * @param zta ZeroTier address
  74. */
  75. inline SharedPtr<Peer> getPeerNoCache(const Address& zta)
  76. {
  77. Mutex::Lock _l(_peers_m);
  78. const SharedPtr<Peer>* const ap = _peers.get(zta);
  79. if (ap) {
  80. return *ap;
  81. }
  82. return SharedPtr<Peer>();
  83. }
  84. /**
  85. * Get a Path object for a given local and remote physical address, creating if needed
  86. *
  87. * @param l Local socket
  88. * @param r Remote address
  89. * @return Pointer to canonicalized Path object
  90. */
  91. inline SharedPtr<Path> getPath(const int64_t l, const InetAddress& r)
  92. {
  93. Mutex::Lock _l(_paths_m);
  94. SharedPtr<Path>& p = _paths[Path::HashKey(l, r)];
  95. if (! p) {
  96. p.set(new Path(l, r));
  97. }
  98. return p;
  99. }
  100. /**
  101. * Get the current best upstream peer
  102. *
  103. * @return Upstream or NULL if none available
  104. */
  105. SharedPtr<Peer> getUpstreamPeer();
  106. /**
  107. * @param id Identity to check
  108. * @return True if this is a root server or a network preferred relay from one of our networks
  109. */
  110. bool isUpstream(const Identity& id) const;
  111. /**
  112. * @param addr Address to check
  113. * @return True if we should accept a world update from this address
  114. */
  115. bool shouldAcceptWorldUpdateFrom(const Address& addr) const;
  116. /**
  117. * @param ztaddr ZeroTier address
  118. * @return Peer role for this device
  119. */
  120. ZT_PeerRole role(const Address& ztaddr) const;
  121. /**
  122. * Check for prohibited endpoints
  123. *
  124. * Right now this returns true if the designated ZT address is a root and if
  125. * the IP (IP only, not port) does not equal any of the IPs defined in the
  126. * current World. This is an extra little security feature in case root keys
  127. * get appropriated or something.
  128. *
  129. * Otherwise it returns false.
  130. *
  131. * @param ztaddr ZeroTier address
  132. * @param ipaddr IP address
  133. * @return True if this ZT/IP pair should not be allowed to be used
  134. */
  135. bool isProhibitedEndpoint(const Address& ztaddr, const InetAddress& ipaddr) const;
  136. /**
  137. * Gets upstreams to contact and their stable endpoints (if known)
  138. *
  139. * @param eps Hash table to fill with addresses and their stable endpoints
  140. */
  141. inline void getUpstreamsToContact(Hashtable<Address, std::vector<InetAddress> >& eps) const
  142. {
  143. Mutex::Lock _l(_upstreams_m);
  144. for (std::vector<World::Root>::const_iterator i(_planet.roots().begin()); i != _planet.roots().end(); ++i) {
  145. if (i->identity != RR->identity) {
  146. std::vector<InetAddress>& ips = eps[i->identity.address()];
  147. for (std::vector<InetAddress>::const_iterator j(i->stableEndpoints.begin()); j != i->stableEndpoints.end(); ++j) {
  148. if (std::find(ips.begin(), ips.end(), *j) == ips.end()) {
  149. ips.push_back(*j);
  150. }
  151. }
  152. }
  153. }
  154. for (std::vector<World>::const_iterator m(_moons.begin()); m != _moons.end(); ++m) {
  155. for (std::vector<World::Root>::const_iterator i(m->roots().begin()); i != m->roots().end(); ++i) {
  156. if (i->identity != RR->identity) {
  157. std::vector<InetAddress>& ips = eps[i->identity.address()];
  158. for (std::vector<InetAddress>::const_iterator j(i->stableEndpoints.begin()); j != i->stableEndpoints.end(); ++j) {
  159. if (std::find(ips.begin(), ips.end(), *j) == ips.end()) {
  160. ips.push_back(*j);
  161. }
  162. }
  163. }
  164. }
  165. }
  166. for (std::vector<std::pair<uint64_t, Address> >::const_iterator m(_moonSeeds.begin()); m != _moonSeeds.end(); ++m) {
  167. eps[m->second];
  168. }
  169. }
  170. /**
  171. * @return Vector of active upstream addresses (including roots)
  172. */
  173. inline std::vector<Address> upstreamAddresses() const
  174. {
  175. Mutex::Lock _l(_upstreams_m);
  176. return _upstreamAddresses;
  177. }
  178. /**
  179. * @return Current moons
  180. */
  181. inline std::vector<World> moons() const
  182. {
  183. Mutex::Lock _l(_upstreams_m);
  184. return _moons;
  185. }
  186. /**
  187. * @return Moon IDs we are waiting for from seeds
  188. */
  189. inline std::vector<uint64_t> moonsWanted() const
  190. {
  191. Mutex::Lock _l(_upstreams_m);
  192. std::vector<uint64_t> mw;
  193. for (std::vector<std::pair<uint64_t, Address> >::const_iterator s(_moonSeeds.begin()); s != _moonSeeds.end(); ++s) {
  194. if (std::find(mw.begin(), mw.end(), s->first) == mw.end()) {
  195. mw.push_back(s->first);
  196. }
  197. }
  198. return mw;
  199. }
  200. /**
  201. * @return Current planet
  202. */
  203. inline World planet() const
  204. {
  205. Mutex::Lock _l(_upstreams_m);
  206. return _planet;
  207. }
  208. /**
  209. * @return Current planet's world ID
  210. */
  211. inline uint64_t planetWorldId() const
  212. {
  213. return _planet.id(); // safe to read without lock, and used from within eachPeer() so don't lock
  214. }
  215. /**
  216. * @return Current planet's world timestamp
  217. */
  218. inline uint64_t planetWorldTimestamp() const
  219. {
  220. return _planet.timestamp(); // safe to read without lock, and used from within eachPeer() so don't lock
  221. }
  222. /**
  223. * Validate new world and update if newer and signature is okay
  224. *
  225. * @param tPtr Thread pointer to be handed through to any callbacks called as a result of this call
  226. * @param newWorld A new or updated planet or moon to learn
  227. * @param alwaysAcceptNew If true, always accept new moons even if we're not waiting for one
  228. * @return True if it was valid and newer than current (or totally new for moons)
  229. */
  230. bool addWorld(void* tPtr, const World& newWorld, bool alwaysAcceptNew);
  231. /**
  232. * Add a moon
  233. *
  234. * This loads it from moons.d if present, and if not adds it to
  235. * a list of moons that we want to contact.
  236. *
  237. * @param id Moon ID
  238. * @param seed If non-NULL, an address of any member of the moon to contact
  239. */
  240. void addMoon(void* tPtr, const uint64_t id, const Address& seed);
  241. /**
  242. * Remove a moon
  243. *
  244. * @param tPtr Thread pointer to be handed through to any callbacks called as a result of this call
  245. * @param id Moon's world ID
  246. */
  247. void removeMoon(void* tPtr, const uint64_t id);
  248. /**
  249. * Clean and flush database
  250. */
  251. void doPeriodicTasks(void* tPtr, int64_t now);
  252. /**
  253. * @param now Current time
  254. * @return Number of peers with active direct paths
  255. */
  256. inline unsigned long countActive(int64_t now) const
  257. {
  258. unsigned long cnt = 0;
  259. Mutex::Lock _l(_peers_m);
  260. Hashtable<Address, SharedPtr<Peer> >::Iterator i(const_cast<Topology*>(this)->_peers);
  261. Address* a = (Address*)0;
  262. SharedPtr<Peer>* p = (SharedPtr<Peer>*)0;
  263. while (i.next(a, p)) {
  264. const SharedPtr<Path> pp((*p)->getAppropriatePath(now, false));
  265. if (pp) {
  266. ++cnt;
  267. }
  268. }
  269. return cnt;
  270. }
  271. /**
  272. * Apply a function or function object to all peers
  273. *
  274. * @param f Function to apply
  275. * @tparam F Function or function object type
  276. */
  277. template <typename F> inline void eachPeer(F f)
  278. {
  279. Mutex::Lock _l(_peers_m);
  280. Hashtable<Address, SharedPtr<Peer> >::Iterator i(_peers);
  281. Address* a = (Address*)0;
  282. SharedPtr<Peer>* p = (SharedPtr<Peer>*)0;
  283. while (i.next(a, p)) {
  284. f(*this, *((const SharedPtr<Peer>*)p));
  285. }
  286. }
  287. /**
  288. * @return All currently active peers by address (unsorted)
  289. */
  290. inline std::vector<std::pair<Address, SharedPtr<Peer> > > allPeers() const
  291. {
  292. Mutex::Lock _l(_peers_m);
  293. return _peers.entries();
  294. }
  295. /**
  296. * @return True if I am a root server in a planet or moon
  297. */
  298. inline bool amUpstream() const
  299. {
  300. return _amUpstream;
  301. }
  302. /**
  303. * Get info about a path
  304. *
  305. * The supplied result variables are not modified if no special config info is found.
  306. *
  307. * @param physicalAddress Physical endpoint address
  308. * @param mtu Variable set to MTU
  309. * @param trustedPathId Variable set to trusted path ID
  310. */
  311. inline void getOutboundPathInfo(const InetAddress& physicalAddress, unsigned int& mtu, uint64_t& trustedPathId)
  312. {
  313. for (unsigned int i = 0, j = _numConfiguredPhysicalPaths; i < j; ++i) {
  314. if (_physicalPathConfig[i].first.containsAddress(physicalAddress)) {
  315. trustedPathId = _physicalPathConfig[i].second.trustedPathId;
  316. mtu = _physicalPathConfig[i].second.mtu;
  317. return;
  318. }
  319. }
  320. }
  321. /**
  322. * Get the payload MTU for an outbound physical path (returns default if not configured)
  323. *
  324. * @param physicalAddress Physical endpoint address
  325. * @return MTU
  326. */
  327. inline unsigned int getOutboundPathMtu(const InetAddress& physicalAddress)
  328. {
  329. for (unsigned int i = 0, j = _numConfiguredPhysicalPaths; i < j; ++i) {
  330. if (_physicalPathConfig[i].first.containsAddress(physicalAddress)) {
  331. return _physicalPathConfig[i].second.mtu;
  332. }
  333. }
  334. return ZT_DEFAULT_PHYSMTU;
  335. }
  336. /**
  337. * Get the outbound trusted path ID for a physical address, or 0 if none
  338. *
  339. * @param physicalAddress Physical address to which we are sending the packet
  340. * @return Trusted path ID or 0 if none (0 is not a valid trusted path ID)
  341. */
  342. inline uint64_t getOutboundPathTrust(const InetAddress& physicalAddress)
  343. {
  344. for (unsigned int i = 0, j = _numConfiguredPhysicalPaths; i < j; ++i) {
  345. if (_physicalPathConfig[i].first.containsAddress(physicalAddress)) {
  346. return _physicalPathConfig[i].second.trustedPathId;
  347. }
  348. }
  349. return 0;
  350. }
  351. /**
  352. * Check whether in incoming trusted path marked packet is valid
  353. *
  354. * @param physicalAddress Originating physical address
  355. * @param trustedPathId Trusted path ID from packet (from MAC field)
  356. */
  357. inline bool shouldInboundPathBeTrusted(const InetAddress& physicalAddress, const uint64_t trustedPathId)
  358. {
  359. for (unsigned int i = 0, j = _numConfiguredPhysicalPaths; i < j; ++i) {
  360. if ((_physicalPathConfig[i].second.trustedPathId == trustedPathId) && (_physicalPathConfig[i].first.containsAddress(physicalAddress))) {
  361. return true;
  362. }
  363. }
  364. return false;
  365. }
  366. /**
  367. * Set or clear physical path configuration (called via Node::setPhysicalPathConfiguration)
  368. */
  369. inline void setPhysicalPathConfiguration(const struct sockaddr_storage* pathNetwork, const ZT_PhysicalPathConfiguration* pathConfig)
  370. {
  371. if (! pathNetwork) {
  372. _numConfiguredPhysicalPaths = 0;
  373. }
  374. else {
  375. std::map<InetAddress, ZT_PhysicalPathConfiguration> cpaths;
  376. for (unsigned int i = 0, j = _numConfiguredPhysicalPaths; i < j; ++i) {
  377. cpaths[_physicalPathConfig[i].first] = _physicalPathConfig[i].second;
  378. }
  379. if (pathConfig) {
  380. ZT_PhysicalPathConfiguration pc(*pathConfig);
  381. if (pc.mtu <= 0) {
  382. pc.mtu = ZT_DEFAULT_PHYSMTU;
  383. }
  384. else if (pc.mtu < ZT_MIN_PHYSMTU) {
  385. pc.mtu = ZT_MIN_PHYSMTU;
  386. }
  387. else if (pc.mtu > ZT_MAX_PHYSMTU) {
  388. pc.mtu = ZT_MAX_PHYSMTU;
  389. }
  390. cpaths[*(reinterpret_cast<const InetAddress*>(pathNetwork))] = pc;
  391. }
  392. else {
  393. cpaths.erase(*(reinterpret_cast<const InetAddress*>(pathNetwork)));
  394. }
  395. unsigned int cnt = 0;
  396. for (std::map<InetAddress, ZT_PhysicalPathConfiguration>::const_iterator i(cpaths.begin()); ((i != cpaths.end()) && (cnt < ZT_MAX_CONFIGURABLE_PATHS)); ++i) {
  397. _physicalPathConfig[cnt].first = i->first;
  398. _physicalPathConfig[cnt].second = i->second;
  399. ++cnt;
  400. }
  401. _numConfiguredPhysicalPaths = cnt;
  402. }
  403. }
  404. private:
  405. Identity _getIdentity(void* tPtr, const Address& zta);
  406. void _memoizeUpstreams(void* tPtr);
  407. void _savePeer(void* tPtr, const SharedPtr<Peer>& peer);
  408. const RuntimeEnvironment* const RR;
  409. std::pair<InetAddress, ZT_PhysicalPathConfiguration> _physicalPathConfig[ZT_MAX_CONFIGURABLE_PATHS];
  410. volatile unsigned int _numConfiguredPhysicalPaths;
  411. Hashtable<Address, SharedPtr<Peer> > _peers;
  412. Mutex _peers_m;
  413. Hashtable<Path::HashKey, SharedPtr<Path> > _paths;
  414. Mutex _paths_m;
  415. World _planet;
  416. std::vector<World> _moons;
  417. std::vector<std::pair<uint64_t, Address> > _moonSeeds;
  418. std::vector<Address> _upstreamAddresses;
  419. bool _amUpstream;
  420. Mutex _upstreams_m; // locks worlds, upstream info, moon info, etc.
  421. };
  422. } // namespace ZeroTier
  423. #endif