Topology.hpp 8.8 KB

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