Topology.hpp 14 KB

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