Topology.hpp 13 KB

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