Topology.hpp 12 KB

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