Topology.hpp 12 KB

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