Topology.hpp 13 KB

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