Topology.hpp 14 KB

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