Topology.hpp 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325
  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 Current World (copy)
  139. */
  140. inline World world() const
  141. {
  142. Mutex::Lock _l(_lock);
  143. return _world;
  144. }
  145. /**
  146. * @return Current world ID
  147. */
  148. inline uint64_t worldId() const
  149. {
  150. return _world.id(); // safe to read without lock, and used from within eachPeer() so don't lock
  151. }
  152. /**
  153. * @return Current world timestamp
  154. */
  155. inline uint64_t worldTimestamp() const
  156. {
  157. return _world.timestamp(); // safe to read without lock, and used from within eachPeer() so don't lock
  158. }
  159. /**
  160. * Validate new world and update if newer and signature is okay
  161. *
  162. * @param newWorld Potential new world definition revision
  163. * @return True if an update actually occurred
  164. */
  165. bool worldUpdateIfValid(const World &newWorld);
  166. /**
  167. * Clean and flush database
  168. */
  169. void clean(uint64_t now);
  170. /**
  171. * @param now Current time
  172. * @return Number of peers with active direct paths
  173. */
  174. inline unsigned long countActive(uint64_t now) const
  175. {
  176. unsigned long cnt = 0;
  177. Mutex::Lock _l(_lock);
  178. Hashtable< Address,SharedPtr<Peer> >::Iterator i(const_cast<Topology *>(this)->_peers);
  179. Address *a = (Address *)0;
  180. SharedPtr<Peer> *p = (SharedPtr<Peer> *)0;
  181. while (i.next(a,p)) {
  182. cnt += (unsigned long)((*p)->hasActiveDirectPath(now));
  183. }
  184. return cnt;
  185. }
  186. /**
  187. * Apply a function or function object to all peers
  188. *
  189. * Note: explicitly template this by reference if you want the object
  190. * passed by reference instead of copied.
  191. *
  192. * Warning: be careful not to use features in these that call any other
  193. * methods of Topology that may lock _lock, otherwise a recursive lock
  194. * and deadlock or lock corruption may occur.
  195. *
  196. * @param f Function to apply
  197. * @tparam F Function or function object type
  198. */
  199. template<typename F>
  200. inline void eachPeer(F f)
  201. {
  202. Mutex::Lock _l(_lock);
  203. Hashtable< Address,SharedPtr<Peer> >::Iterator i(_peers);
  204. Address *a = (Address *)0;
  205. SharedPtr<Peer> *p = (SharedPtr<Peer> *)0;
  206. while (i.next(a,p)) {
  207. #ifdef ZT_TRACE
  208. if (!(*p)) {
  209. 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());
  210. abort();
  211. }
  212. #endif
  213. f(*this,*((const SharedPtr<Peer> *)p));
  214. }
  215. }
  216. /**
  217. * @return All currently active peers by address (unsorted)
  218. */
  219. inline std::vector< std::pair< Address,SharedPtr<Peer> > > allPeers() const
  220. {
  221. Mutex::Lock _l(_lock);
  222. return _peers.entries();
  223. }
  224. /**
  225. * @return True if I am a root server in the current World
  226. */
  227. inline bool amRoot() const throw() { return _amRoot; }
  228. /**
  229. * Get the outbound trusted path ID for a physical address, or 0 if none
  230. *
  231. * @param physicalAddress Physical address to which we are sending the packet
  232. * @return Trusted path ID or 0 if none (0 is not a valid trusted path ID)
  233. */
  234. inline uint64_t getOutboundPathTrust(const InetAddress &physicalAddress)
  235. {
  236. for(unsigned int i=0;i<_trustedPathCount;++i) {
  237. if (_trustedPathNetworks[i].containsAddress(physicalAddress))
  238. return _trustedPathIds[i];
  239. }
  240. return 0;
  241. }
  242. /**
  243. * Check whether in incoming trusted path marked packet is valid
  244. *
  245. * @param physicalAddress Originating physical address
  246. * @param trustedPathId Trusted path ID from packet (from MAC field)
  247. */
  248. inline bool shouldInboundPathBeTrusted(const InetAddress &physicalAddress,const uint64_t trustedPathId)
  249. {
  250. for(unsigned int i=0;i<_trustedPathCount;++i) {
  251. if ((_trustedPathIds[i] == trustedPathId)&&(_trustedPathNetworks[i].containsAddress(physicalAddress)))
  252. return true;
  253. }
  254. return false;
  255. }
  256. /**
  257. * Set trusted paths in this topology
  258. *
  259. * @param networks Array of networks (prefix/netmask bits)
  260. * @param ids Array of trusted path IDs
  261. * @param count Number of trusted paths (if larger than ZT_MAX_TRUSTED_PATHS overflow is ignored)
  262. */
  263. inline void setTrustedPaths(const InetAddress *networks,const uint64_t *ids,unsigned int count)
  264. {
  265. if (count > ZT_MAX_TRUSTED_PATHS)
  266. count = ZT_MAX_TRUSTED_PATHS;
  267. Mutex::Lock _l(_lock);
  268. for(unsigned int i=0;i<count;++i) {
  269. _trustedPathIds[i] = ids[i];
  270. _trustedPathNetworks[i] = networks[i];
  271. }
  272. _trustedPathCount = count;
  273. }
  274. private:
  275. Identity _getIdentity(const Address &zta);
  276. void _setWorld(const World &newWorld);
  277. const RuntimeEnvironment *const RR;
  278. uint64_t _trustedPathIds[ZT_MAX_TRUSTED_PATHS];
  279. InetAddress _trustedPathNetworks[ZT_MAX_TRUSTED_PATHS];
  280. unsigned int _trustedPathCount;
  281. World _world;
  282. Hashtable< Address,SharedPtr<Peer> > _peers;
  283. std::vector< Address > _rootAddresses;
  284. std::vector< SharedPtr<Peer> > _rootPeers;
  285. bool _amRoot;
  286. Mutex _lock;
  287. };
  288. } // namespace ZeroTier
  289. #endif