2
0

Topology.hpp 12 KB

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