Topology.hpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386
  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. namespace ZeroTier {
  37. class RuntimeEnvironment;
  38. /**
  39. * Database of network topology
  40. */
  41. class Topology
  42. {
  43. public:
  44. Topology(const RuntimeEnvironment *renv);
  45. /**
  46. * Add a peer to database
  47. *
  48. * This will not replace existing peers. In that case the existing peer
  49. * record is returned.
  50. *
  51. * @param peer Peer to add
  52. * @return New or existing peer (should replace 'peer')
  53. */
  54. SharedPtr<Peer> addPeer(const SharedPtr<Peer> &peer);
  55. /**
  56. * Get a peer from its address
  57. *
  58. * @param zta ZeroTier address of peer
  59. * @return Peer or NULL if not found
  60. */
  61. SharedPtr<Peer> getPeer(const Address &zta);
  62. /**
  63. * Get a peer only if it is presently in memory (no disk cache)
  64. *
  65. * This also does not update the lastUsed() time for peers, which means
  66. * that it won't prevent them from falling out of RAM. This is currently
  67. * used in the Cluster code to update peer info without forcing all peers
  68. * across the entire cluster to remain in memory cache.
  69. *
  70. * @param zta ZeroTier address
  71. */
  72. inline SharedPtr<Peer> getPeerNoCache(const Address &zta)
  73. {
  74. Mutex::Lock _l(_lock);
  75. const SharedPtr<Peer> *const ap = _peers.get(zta);
  76. if (ap)
  77. return *ap;
  78. return SharedPtr<Peer>();
  79. }
  80. /**
  81. * Get a Path object for a given local and remote physical address, creating if needed
  82. *
  83. * @param l Local address or NULL for 'any' or 'wildcard'
  84. * @param r Remote address
  85. * @return Pointer to canonicalized Path object
  86. */
  87. inline SharedPtr<Path> getPath(const InetAddress &l,const InetAddress &r)
  88. {
  89. Mutex::Lock _l(_lock);
  90. SharedPtr<Path> &p = _paths[Path::HashKey(l,r)];
  91. if (!p)
  92. p.setToUnsafe(new Path(l,r));
  93. return p;
  94. }
  95. /**
  96. * Get the identity of a peer
  97. *
  98. * @param zta ZeroTier address of peer
  99. * @return Identity or NULL Identity if not found
  100. */
  101. Identity getIdentity(const Address &zta);
  102. /**
  103. * Cache an identity
  104. *
  105. * This is done automatically on addPeer(), and so is only useful for
  106. * cluster identity replication.
  107. *
  108. * @param id Identity to cache
  109. */
  110. void saveIdentity(const Identity &id);
  111. /**
  112. * Get the current best upstream peer
  113. *
  114. * @return Root server with lowest latency or NULL if none
  115. */
  116. inline SharedPtr<Peer> getUpstreamPeer() { return getUpstreamPeer((const Address *)0,0,false); }
  117. /**
  118. * Get the current best upstream peer, avoiding those in the supplied avoid list
  119. *
  120. * @param avoid Nodes to avoid
  121. * @param avoidCount Number of nodes to avoid
  122. * @param strictAvoid If false, consider avoided root servers anyway if no non-avoid root servers are available
  123. * @return Root server or NULL if none available
  124. */
  125. SharedPtr<Peer> getUpstreamPeer(const Address *avoid,unsigned int avoidCount,bool strictAvoid);
  126. /**
  127. * @param id Identity to check
  128. * @return True if this is a root server or a network preferred relay from one of our networks
  129. */
  130. bool isUpstream(const Identity &id) const;
  131. /**
  132. * @param ztaddr ZeroTier address
  133. * @return Peer role for this device
  134. */
  135. ZT_PeerRole role(const Address &ztaddr) const;
  136. /**
  137. * Check for prohibited endpoints
  138. *
  139. * Right now this returns true if the designated ZT address is a root and if
  140. * the IP (IP only, not port) does not equal any of the IPs defined in the
  141. * current World. This is an extra little security feature in case root keys
  142. * get appropriated or something.
  143. *
  144. * Otherwise it returns false.
  145. *
  146. * @param ztaddr ZeroTier address
  147. * @param ipaddr IP address
  148. * @return True if this ZT/IP pair should not be allowed to be used
  149. */
  150. bool isProhibitedEndpoint(const Address &ztaddr,const InetAddress &ipaddr) const;
  151. /**
  152. * @param eps Hash table to fill with addresses and their stable endpoints
  153. */
  154. inline void getUpstreamStableEndpoints(Hashtable< Address,std::vector<InetAddress> > &eps) const
  155. {
  156. Mutex::Lock _l(_lock);
  157. for(std::vector<World::Root>::const_iterator i(_planet.roots().begin());i!=_planet.roots().end();++i) {
  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. for(std::vector<World>::const_iterator m(_moons.begin());m!=_moons.end();++m) {
  165. for(std::vector<World::Root>::const_iterator i(m->roots().begin());i!=m->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. }
  173. }
  174. /**
  175. * @return Vector of active upstream addresses (including roots)
  176. */
  177. inline std::vector<Address> upstreamAddresses() const
  178. {
  179. Mutex::Lock _l(_lock);
  180. return _upstreamAddresses;
  181. }
  182. /**
  183. * @return Current moons
  184. */
  185. inline std::vector<World> moons() const
  186. {
  187. Mutex::Lock _l(_lock);
  188. return _moons;
  189. }
  190. /**
  191. * @return Current planet
  192. */
  193. inline World planet() const
  194. {
  195. Mutex::Lock _l(_lock);
  196. return _planet;
  197. }
  198. /**
  199. * @return Current planet's world ID
  200. */
  201. inline uint64_t planetWorldId() const
  202. {
  203. return _planet.id(); // safe to read without lock, and used from within eachPeer() so don't lock
  204. }
  205. /**
  206. * @return Current planet's world timestamp
  207. */
  208. inline uint64_t planetWorldTimestamp() const
  209. {
  210. return _planet.timestamp(); // safe to read without lock, and used from within eachPeer() so don't lock
  211. }
  212. /**
  213. * Validate new world and update if newer and signature is okay
  214. *
  215. * @param newWorld A new or updated planet or moon to learn
  216. * @param updateOnly If true only update currently known worlds
  217. * @return True if it was valid and newer than current (or totally new for moons)
  218. */
  219. bool addWorld(const World &newWorld,bool updateOnly);
  220. /**
  221. * Clean and flush database
  222. */
  223. void clean(uint64_t now);
  224. /**
  225. * @param now Current time
  226. * @return Number of peers with active direct paths
  227. */
  228. inline unsigned long countActive(uint64_t now) const
  229. {
  230. unsigned long cnt = 0;
  231. Mutex::Lock _l(_lock);
  232. Hashtable< Address,SharedPtr<Peer> >::Iterator i(const_cast<Topology *>(this)->_peers);
  233. Address *a = (Address *)0;
  234. SharedPtr<Peer> *p = (SharedPtr<Peer> *)0;
  235. while (i.next(a,p)) {
  236. cnt += (unsigned long)((*p)->hasActiveDirectPath(now));
  237. }
  238. return cnt;
  239. }
  240. /**
  241. * Apply a function or function object to all peers
  242. *
  243. * Note: explicitly template this by reference if you want the object
  244. * passed by reference instead of copied.
  245. *
  246. * Warning: be careful not to use features in these that call any other
  247. * methods of Topology that may lock _lock, otherwise a recursive lock
  248. * and deadlock or lock corruption may occur.
  249. *
  250. * @param f Function to apply
  251. * @tparam F Function or function object type
  252. */
  253. template<typename F>
  254. inline void eachPeer(F f)
  255. {
  256. Mutex::Lock _l(_lock);
  257. Hashtable< Address,SharedPtr<Peer> >::Iterator i(_peers);
  258. Address *a = (Address *)0;
  259. SharedPtr<Peer> *p = (SharedPtr<Peer> *)0;
  260. while (i.next(a,p)) {
  261. #ifdef ZT_TRACE
  262. if (!(*p)) {
  263. 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());
  264. abort();
  265. }
  266. #endif
  267. f(*this,*((const SharedPtr<Peer> *)p));
  268. }
  269. }
  270. /**
  271. * @return All currently active peers by address (unsorted)
  272. */
  273. inline std::vector< std::pair< Address,SharedPtr<Peer> > > allPeers() const
  274. {
  275. Mutex::Lock _l(_lock);
  276. return _peers.entries();
  277. }
  278. /**
  279. * @return True if I am a root server in a planet or moon
  280. */
  281. inline bool amRoot() const { return _amRoot; }
  282. /**
  283. * Get the outbound trusted path ID for a physical address, or 0 if none
  284. *
  285. * @param physicalAddress Physical address to which we are sending the packet
  286. * @return Trusted path ID or 0 if none (0 is not a valid trusted path ID)
  287. */
  288. inline uint64_t getOutboundPathTrust(const InetAddress &physicalAddress)
  289. {
  290. for(unsigned int i=0;i<_trustedPathCount;++i) {
  291. if (_trustedPathNetworks[i].containsAddress(physicalAddress))
  292. return _trustedPathIds[i];
  293. }
  294. return 0;
  295. }
  296. /**
  297. * Check whether in incoming trusted path marked packet is valid
  298. *
  299. * @param physicalAddress Originating physical address
  300. * @param trustedPathId Trusted path ID from packet (from MAC field)
  301. */
  302. inline bool shouldInboundPathBeTrusted(const InetAddress &physicalAddress,const uint64_t trustedPathId)
  303. {
  304. for(unsigned int i=0;i<_trustedPathCount;++i) {
  305. if ((_trustedPathIds[i] == trustedPathId)&&(_trustedPathNetworks[i].containsAddress(physicalAddress)))
  306. return true;
  307. }
  308. return false;
  309. }
  310. /**
  311. * Set trusted paths in this topology
  312. *
  313. * @param networks Array of networks (prefix/netmask bits)
  314. * @param ids Array of trusted path IDs
  315. * @param count Number of trusted paths (if larger than ZT_MAX_TRUSTED_PATHS overflow is ignored)
  316. */
  317. inline void setTrustedPaths(const InetAddress *networks,const uint64_t *ids,unsigned int count)
  318. {
  319. if (count > ZT_MAX_TRUSTED_PATHS)
  320. count = ZT_MAX_TRUSTED_PATHS;
  321. Mutex::Lock _l(_lock);
  322. for(unsigned int i=0;i<count;++i) {
  323. _trustedPathIds[i] = ids[i];
  324. _trustedPathNetworks[i] = networks[i];
  325. }
  326. _trustedPathCount = count;
  327. }
  328. private:
  329. Identity _getIdentity(const Address &zta);
  330. const RuntimeEnvironment *const RR;
  331. uint64_t _trustedPathIds[ZT_MAX_TRUSTED_PATHS];
  332. InetAddress _trustedPathNetworks[ZT_MAX_TRUSTED_PATHS];
  333. unsigned int _trustedPathCount;
  334. World _planet;
  335. std::vector< World > _moons;
  336. Hashtable< Address,SharedPtr<Peer> > _peers;
  337. Hashtable< Path::HashKey,SharedPtr<Path> > _paths;
  338. std::vector< Address > _upstreamAddresses; // includes root addresses of both planets and moons
  339. bool _amRoot; // am I a root in a planet or moon?
  340. Mutex _lock;
  341. };
  342. } // namespace ZeroTier
  343. #endif