Topology.hpp 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354
  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. ~Topology();
  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(_lock);
  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(_lock);
  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 favorite root server
  114. *
  115. * @return Root server with lowest latency or NULL if none
  116. */
  117. inline SharedPtr<Peer> getBestRoot() { return getBestRoot((const Address *)0,0,false); }
  118. /**
  119. * Get the best root server, avoiding root servers listed in an array
  120. *
  121. * This will get the best root server (lowest latency, etc.) but will
  122. * try to avoid the listed root servers, only using them if no others
  123. * are available.
  124. *
  125. * @param avoid Nodes to avoid
  126. * @param avoidCount Number of nodes to avoid
  127. * @param strictAvoid If false, consider avoided root servers anyway if no non-avoid root servers are available
  128. * @return Root server or NULL if none available
  129. */
  130. SharedPtr<Peer> getBestRoot(const Address *avoid,unsigned int avoidCount,bool strictAvoid);
  131. /**
  132. * @param id Identity to check
  133. * @return True if this is a designated root server in this world
  134. */
  135. inline bool isRoot(const Identity &id) const
  136. {
  137. Mutex::Lock _l(_lock);
  138. return (std::find(_rootAddresses.begin(),_rootAddresses.end(),id.address()) != _rootAddresses.end());
  139. }
  140. /**
  141. * @param id Identity to check
  142. * @return True if this is a root server or a network preferred relay from one of our networks
  143. */
  144. bool isUpstream(const Identity &id) const;
  145. /**
  146. * @return Vector of root server addresses
  147. */
  148. inline std::vector<Address> rootAddresses() const
  149. {
  150. Mutex::Lock _l(_lock);
  151. return _rootAddresses;
  152. }
  153. /**
  154. * @return Vector of active upstream addresses (including roots)
  155. */
  156. inline std::vector<Address> upstreamAddresses() const
  157. {
  158. return rootAddresses();
  159. }
  160. /**
  161. * @return Current World (copy)
  162. */
  163. inline World world() const
  164. {
  165. Mutex::Lock _l(_lock);
  166. return _world;
  167. }
  168. /**
  169. * @return Current world ID
  170. */
  171. inline uint64_t worldId() const
  172. {
  173. return _world.id(); // safe to read without lock, and used from within eachPeer() so don't lock
  174. }
  175. /**
  176. * @return Current world timestamp
  177. */
  178. inline uint64_t worldTimestamp() const
  179. {
  180. return _world.timestamp(); // safe to read without lock, and used from within eachPeer() so don't lock
  181. }
  182. /**
  183. * Validate new world and update if newer and signature is okay
  184. *
  185. * @param newWorld Potential new world definition revision
  186. * @return True if an update actually occurred
  187. */
  188. bool worldUpdateIfValid(const World &newWorld);
  189. /**
  190. * Clean and flush database
  191. */
  192. void clean(uint64_t now);
  193. /**
  194. * @param now Current time
  195. * @return Number of peers with active direct paths
  196. */
  197. inline unsigned long countActive(uint64_t now) const
  198. {
  199. unsigned long cnt = 0;
  200. Mutex::Lock _l(_lock);
  201. Hashtable< Address,SharedPtr<Peer> >::Iterator i(const_cast<Topology *>(this)->_peers);
  202. Address *a = (Address *)0;
  203. SharedPtr<Peer> *p = (SharedPtr<Peer> *)0;
  204. while (i.next(a,p)) {
  205. cnt += (unsigned long)((*p)->hasActiveDirectPath(now));
  206. }
  207. return cnt;
  208. }
  209. /**
  210. * Apply a function or function object to all peers
  211. *
  212. * Note: explicitly template this by reference if you want the object
  213. * passed by reference instead of copied.
  214. *
  215. * Warning: be careful not to use features in these that call any other
  216. * methods of Topology that may lock _lock, otherwise a recursive lock
  217. * and deadlock or lock corruption may occur.
  218. *
  219. * @param f Function to apply
  220. * @tparam F Function or function object type
  221. */
  222. template<typename F>
  223. inline void eachPeer(F f)
  224. {
  225. Mutex::Lock _l(_lock);
  226. Hashtable< Address,SharedPtr<Peer> >::Iterator i(_peers);
  227. Address *a = (Address *)0;
  228. SharedPtr<Peer> *p = (SharedPtr<Peer> *)0;
  229. while (i.next(a,p)) {
  230. #ifdef ZT_TRACE
  231. if (!(*p)) {
  232. 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());
  233. abort();
  234. }
  235. #endif
  236. f(*this,*((const SharedPtr<Peer> *)p));
  237. }
  238. }
  239. /**
  240. * @return All currently active peers by address (unsorted)
  241. */
  242. inline std::vector< std::pair< Address,SharedPtr<Peer> > > allPeers() const
  243. {
  244. Mutex::Lock _l(_lock);
  245. return _peers.entries();
  246. }
  247. /**
  248. * @return True if I am a root server in the current World
  249. */
  250. inline bool amRoot() const throw() { return _amRoot; }
  251. /**
  252. * Get the outbound trusted path ID for a physical address, or 0 if none
  253. *
  254. * @param physicalAddress Physical address to which we are sending the packet
  255. * @return Trusted path ID or 0 if none (0 is not a valid trusted path ID)
  256. */
  257. inline uint64_t getOutboundPathTrust(const InetAddress &physicalAddress)
  258. {
  259. for(unsigned int i=0;i<_trustedPathCount;++i) {
  260. if (_trustedPathNetworks[i].containsAddress(physicalAddress))
  261. return _trustedPathIds[i];
  262. }
  263. return 0;
  264. }
  265. /**
  266. * Check whether in incoming trusted path marked packet is valid
  267. *
  268. * @param physicalAddress Originating physical address
  269. * @param trustedPathId Trusted path ID from packet (from MAC field)
  270. */
  271. inline bool shouldInboundPathBeTrusted(const InetAddress &physicalAddress,const uint64_t trustedPathId)
  272. {
  273. for(unsigned int i=0;i<_trustedPathCount;++i) {
  274. if ((_trustedPathIds[i] == trustedPathId)&&(_trustedPathNetworks[i].containsAddress(physicalAddress)))
  275. return true;
  276. }
  277. return false;
  278. }
  279. /**
  280. * Set trusted paths in this topology
  281. *
  282. * @param networks Array of networks (prefix/netmask bits)
  283. * @param ids Array of trusted path IDs
  284. * @param count Number of trusted paths (if larger than ZT_MAX_TRUSTED_PATHS overflow is ignored)
  285. */
  286. inline void setTrustedPaths(const InetAddress *networks,const uint64_t *ids,unsigned int count)
  287. {
  288. if (count > ZT_MAX_TRUSTED_PATHS)
  289. count = ZT_MAX_TRUSTED_PATHS;
  290. Mutex::Lock _l(_lock);
  291. for(unsigned int i=0;i<count;++i) {
  292. _trustedPathIds[i] = ids[i];
  293. _trustedPathNetworks[i] = networks[i];
  294. }
  295. _trustedPathCount = count;
  296. }
  297. private:
  298. Identity _getIdentity(const Address &zta);
  299. void _setWorld(const World &newWorld);
  300. const RuntimeEnvironment *const RR;
  301. uint64_t _trustedPathIds[ZT_MAX_TRUSTED_PATHS];
  302. InetAddress _trustedPathNetworks[ZT_MAX_TRUSTED_PATHS];
  303. unsigned int _trustedPathCount;
  304. World _world;
  305. Hashtable< Address,SharedPtr<Peer> > _peers;
  306. Hashtable< Path::HashKey,SharedPtr<Path> > _paths;
  307. std::vector< Address > _rootAddresses;
  308. std::vector< SharedPtr<Peer> > _rootPeers;
  309. bool _amRoot;
  310. Mutex _lock;
  311. };
  312. } // namespace ZeroTier
  313. #endif