Topology.hpp 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273
  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 "Address.hpp"
  28. #include "Identity.hpp"
  29. #include "Peer.hpp"
  30. #include "Mutex.hpp"
  31. #include "InetAddress.hpp"
  32. #include "Hashtable.hpp"
  33. #include "World.hpp"
  34. namespace ZeroTier {
  35. class RuntimeEnvironment;
  36. /**
  37. * Database of network topology
  38. */
  39. class Topology
  40. {
  41. public:
  42. Topology(const RuntimeEnvironment *renv);
  43. ~Topology();
  44. /**
  45. * Add a peer to database
  46. *
  47. * This will not replace existing peers. In that case the existing peer
  48. * record is returned.
  49. *
  50. * @param peer Peer to add
  51. * @return New or existing peer (should replace 'peer')
  52. */
  53. SharedPtr<Peer> addPeer(const SharedPtr<Peer> &peer);
  54. /**
  55. * Get a peer from its address
  56. *
  57. * @param zta ZeroTier address of peer
  58. * @return Peer or NULL if not found
  59. */
  60. SharedPtr<Peer> getPeer(const Address &zta);
  61. /**
  62. * Get a peer only if it is presently in memory (no disk cache)
  63. *
  64. * This also does not update the lastUsed() time for peers, which means
  65. * that it won't prevent them from falling out of RAM. This is currently
  66. * used in the Cluster code to update peer info without forcing all peers
  67. * across the entire cluster to remain in memory cache.
  68. *
  69. * @param zta ZeroTier address
  70. */
  71. inline SharedPtr<Peer> getPeerNoCache(const Address &zta)
  72. {
  73. Mutex::Lock _l(_lock);
  74. const SharedPtr<Peer> *const ap = _peers.get(zta);
  75. if (ap)
  76. return *ap;
  77. return SharedPtr<Peer>();
  78. }
  79. /**
  80. * Get the identity of a peer
  81. *
  82. * @param zta ZeroTier address of peer
  83. * @return Identity or NULL Identity if not found
  84. */
  85. Identity getIdentity(const Address &zta);
  86. /**
  87. * Cache an identity
  88. *
  89. * This is done automatically on addPeer(), and so is only useful for
  90. * cluster identity replication.
  91. *
  92. * @param id Identity to cache
  93. */
  94. void saveIdentity(const Identity &id);
  95. /**
  96. * Get the current favorite root server
  97. *
  98. * @return Root server with lowest latency or NULL if none
  99. */
  100. inline SharedPtr<Peer> getBestRoot() { return getBestRoot((const Address *)0,0,false); }
  101. /**
  102. * Get the best root server, avoiding root servers listed in an array
  103. *
  104. * This will get the best root server (lowest latency, etc.) but will
  105. * try to avoid the listed root servers, only using them if no others
  106. * are available.
  107. *
  108. * @param avoid Nodes to avoid
  109. * @param avoidCount Number of nodes to avoid
  110. * @param strictAvoid If false, consider avoided root servers anyway if no non-avoid root servers are available
  111. * @return Root server or NULL if none available
  112. */
  113. SharedPtr<Peer> getBestRoot(const Address *avoid,unsigned int avoidCount,bool strictAvoid);
  114. /**
  115. * @param id Identity to check
  116. * @return True if this is a designated root server in this world
  117. */
  118. inline bool isRoot(const Identity &id) const
  119. {
  120. Mutex::Lock _l(_lock);
  121. return (std::find(_rootAddresses.begin(),_rootAddresses.end(),id.address()) != _rootAddresses.end());
  122. }
  123. /**
  124. * @param id Identity to check
  125. * @return True if this is a root server or a network preferred relay from one of our networks
  126. */
  127. bool isUpstream(const Identity &id) const;
  128. /**
  129. * @return Vector of root server addresses
  130. */
  131. inline std::vector<Address> rootAddresses() const
  132. {
  133. Mutex::Lock _l(_lock);
  134. return _rootAddresses;
  135. }
  136. /**
  137. * @return Current World (copy)
  138. */
  139. inline World world() const
  140. {
  141. Mutex::Lock _l(_lock);
  142. return _world;
  143. }
  144. /**
  145. * @return Current world ID
  146. */
  147. inline uint64_t worldId() const
  148. {
  149. return _world.id(); // safe to read without lock, and used from within eachPeer() so don't lock
  150. }
  151. /**
  152. * @return Current world timestamp
  153. */
  154. inline uint64_t worldTimestamp() const
  155. {
  156. return _world.timestamp(); // safe to read without lock, and used from within eachPeer() so don't lock
  157. }
  158. /**
  159. * Validate new world and update if newer and signature is okay
  160. *
  161. * @param newWorld Potential new world definition revision
  162. * @return True if an update actually occurred
  163. */
  164. bool worldUpdateIfValid(const World &newWorld);
  165. /**
  166. * Clean and flush database
  167. */
  168. void clean(uint64_t now);
  169. /**
  170. * @param now Current time
  171. * @return Number of peers with active direct paths
  172. */
  173. inline unsigned long countActive(uint64_t now) const
  174. {
  175. unsigned long cnt = 0;
  176. Mutex::Lock _l(_lock);
  177. Hashtable< Address,SharedPtr<Peer> >::Iterator i(const_cast<Topology *>(this)->_peers);
  178. Address *a = (Address *)0;
  179. SharedPtr<Peer> *p = (SharedPtr<Peer> *)0;
  180. while (i.next(a,p)) {
  181. cnt += (unsigned long)((*p)->hasActiveDirectPath(now));
  182. }
  183. return cnt;
  184. }
  185. /**
  186. * Apply a function or function object to all peers
  187. *
  188. * Note: explicitly template this by reference if you want the object
  189. * passed by reference instead of copied.
  190. *
  191. * Warning: be careful not to use features in these that call any other
  192. * methods of Topology that may lock _lock, otherwise a recursive lock
  193. * and deadlock or lock corruption may occur.
  194. *
  195. * @param f Function to apply
  196. * @tparam F Function or function object type
  197. */
  198. template<typename F>
  199. inline void eachPeer(F f)
  200. {
  201. Mutex::Lock _l(_lock);
  202. Hashtable< Address,SharedPtr<Peer> >::Iterator i(_peers);
  203. Address *a = (Address *)0;
  204. SharedPtr<Peer> *p = (SharedPtr<Peer> *)0;
  205. while (i.next(a,p)) {
  206. #ifdef ZT_TRACE
  207. if (!(*p)) {
  208. 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());
  209. abort();
  210. }
  211. #endif
  212. f(*this,*((const SharedPtr<Peer> *)p));
  213. }
  214. }
  215. /**
  216. * @return All currently active peers by address (unsorted)
  217. */
  218. inline std::vector< std::pair< Address,SharedPtr<Peer> > > allPeers() const
  219. {
  220. Mutex::Lock _l(_lock);
  221. return _peers.entries();
  222. }
  223. /**
  224. * @return True if I am a root server in the current World
  225. */
  226. inline bool amRoot() const throw() { return _amRoot; }
  227. private:
  228. Identity _getIdentity(const Address &zta);
  229. void _setWorld(const World &newWorld);
  230. const RuntimeEnvironment *const RR;
  231. World _world;
  232. Hashtable< Address,SharedPtr<Peer> > _peers;
  233. std::vector< Address > _rootAddresses;
  234. std::vector< SharedPtr<Peer> > _rootPeers;
  235. bool _amRoot;
  236. Mutex _lock;
  237. };
  238. } // namespace ZeroTier
  239. #endif