Topology.hpp 13 KB

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