Topology.hpp 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349
  1. /*
  2. * ZeroTier One - Network Virtualization Everywhere
  3. * Copyright (C) 2011-2019 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. * --
  19. *
  20. * You can be released from the requirements of the license by purchasing
  21. * a commercial license. Buying such a license is mandatory as soon as you
  22. * develop commercial closed-source software that incorporates or links
  23. * directly against ZeroTier software without disclosing the source code
  24. * of your own application.
  25. */
  26. #ifndef ZT_TOPOLOGY_HPP
  27. #define ZT_TOPOLOGY_HPP
  28. #include <stdio.h>
  29. #include <string.h>
  30. #include <vector>
  31. #include <stdexcept>
  32. #include <algorithm>
  33. #include <utility>
  34. #include "Constants.hpp"
  35. #include "../include/ZeroTierOne.h"
  36. #include "Address.hpp"
  37. #include "Identity.hpp"
  38. #include "Peer.hpp"
  39. #include "Path.hpp"
  40. #include "Mutex.hpp"
  41. #include "InetAddress.hpp"
  42. #include "Hashtable.hpp"
  43. namespace ZeroTier {
  44. class RuntimeEnvironment;
  45. /**
  46. * Database of network topology
  47. */
  48. class Topology
  49. {
  50. public:
  51. Topology(const RuntimeEnvironment *renv,void *tPtr);
  52. ~Topology();
  53. /**
  54. * Add a peer to database
  55. *
  56. * This will not replace existing peers. In that case the existing peer
  57. * record is returned.
  58. *
  59. * @param tPtr Thread pointer to be handed through to any callbacks called as a result of this call
  60. * @param peer Peer to add
  61. * @return New or existing peer (should replace 'peer')
  62. */
  63. SharedPtr<Peer> addPeer(void *tPtr,const SharedPtr<Peer> &peer);
  64. /**
  65. * Get a peer from its address
  66. *
  67. * @param tPtr Thread pointer to be handed through to any callbacks called as a result of this call
  68. * @param zta ZeroTier address of peer
  69. * @return Peer or NULL if not found
  70. */
  71. SharedPtr<Peer> getPeer(void *tPtr,const Address &zta);
  72. /**
  73. * @param tPtr Thread pointer to be handed through to any callbacks called as a result of this call
  74. * @param zta ZeroTier address of peer
  75. * @return Identity or NULL identity if not found
  76. */
  77. Identity getIdentity(void *tPtr,const Address &zta);
  78. /**
  79. * Get a peer only if it is presently in memory (no disk cache)
  80. *
  81. * This also does not update the lastUsed() time for peers, which means
  82. * that it won't prevent them from falling out of RAM. This is currently
  83. * used in the Cluster code to update peer info without forcing all peers
  84. * across the entire cluster to remain in memory cache.
  85. *
  86. * @param zta ZeroTier address
  87. */
  88. inline SharedPtr<Peer> getPeerNoCache(const Address &zta)
  89. {
  90. Mutex::Lock _l(_peers_m);
  91. const SharedPtr<Peer> *const ap = _peers.get(zta);
  92. if (ap)
  93. return *ap;
  94. return SharedPtr<Peer>();
  95. }
  96. /**
  97. * Get a Path object for a given local and remote physical address, creating if needed
  98. *
  99. * @param l Local socket
  100. * @param r Remote address
  101. * @return Pointer to canonicalized Path object
  102. */
  103. inline SharedPtr<Path> getPath(const int64_t l,const InetAddress &r)
  104. {
  105. Mutex::Lock _l(_paths_m);
  106. SharedPtr<Path> &p = _paths[Path::HashKey(l,r)];
  107. if (!p)
  108. p.set(new Path(l,r));
  109. return p;
  110. }
  111. /**
  112. * Get the current best upstream peer
  113. *
  114. * @return Upstream or NULL if none available
  115. */
  116. SharedPtr<Peer> getUpstreamPeer();
  117. /**
  118. * @param id Identity to check
  119. * @return True if this is a root server or a network preferred relay from one of our networks
  120. */
  121. bool isUpstream(const Identity &id) const;
  122. /**
  123. * @param ztaddr ZeroTier address
  124. * @return Peer role for this device
  125. */
  126. ZT_PeerRole role(const Address &ztaddr) const;
  127. /**
  128. * Check for prohibited endpoints
  129. *
  130. * Right now this returns true if the designated ZT address is a root and if
  131. * the IP (IP only, not port) does not equal any of the IPs defined in the
  132. * current World. This is an extra little security feature in case root keys
  133. * get appropriated or something.
  134. *
  135. * Otherwise it returns false.
  136. *
  137. * @param ztaddr ZeroTier address
  138. * @param ipaddr IP address
  139. * @return True if this ZT/IP pair should not be allowed to be used
  140. */
  141. bool isProhibitedEndpoint(const Address &ztaddr,const InetAddress &ipaddr) const;
  142. /**
  143. * Gets upstreams to contact and their stable endpoints (if known)
  144. *
  145. * @param eps Hash table to fill with addresses and their stable endpoints
  146. */
  147. inline void getUpstreamsToContact(Hashtable< Address,std::vector<InetAddress> > &eps) const
  148. {
  149. }
  150. /**
  151. * @return Vector of active upstream addresses (including roots)
  152. */
  153. inline std::vector<Address> upstreamAddresses() const
  154. {
  155. return std::vector<Address>();
  156. }
  157. /**
  158. * Clean and flush database
  159. */
  160. void doPeriodicTasks(void *tPtr,int64_t now);
  161. /**
  162. * @param now Current time
  163. * @return Number of peers with active direct paths
  164. */
  165. inline unsigned long countActive(int64_t now) const
  166. {
  167. unsigned long cnt = 0;
  168. Mutex::Lock _l(_peers_m);
  169. Hashtable< Address,SharedPtr<Peer> >::Iterator i(const_cast<Topology *>(this)->_peers);
  170. Address *a = (Address *)0;
  171. SharedPtr<Peer> *p = (SharedPtr<Peer> *)0;
  172. while (i.next(a,p)) {
  173. const SharedPtr<Path> pp((*p)->getAppropriatePath(now,false));
  174. if (pp)
  175. ++cnt;
  176. }
  177. return cnt;
  178. }
  179. /**
  180. * Apply a function or function object to all peers
  181. *
  182. * @param f Function to apply
  183. * @tparam F Function or function object type
  184. */
  185. template<typename F>
  186. inline void eachPeer(F f)
  187. {
  188. Mutex::Lock _l(_peers_m);
  189. Hashtable< Address,SharedPtr<Peer> >::Iterator i(_peers);
  190. Address *a = (Address *)0;
  191. SharedPtr<Peer> *p = (SharedPtr<Peer> *)0;
  192. while (i.next(a,p)) {
  193. f(*this,*((const SharedPtr<Peer> *)p));
  194. }
  195. }
  196. /**
  197. * @return All currently active peers by address (unsorted)
  198. */
  199. inline std::vector< std::pair< Address,SharedPtr<Peer> > > allPeers() const
  200. {
  201. Mutex::Lock _l(_peers_m);
  202. return _peers.entries();
  203. }
  204. /**
  205. * Get info about a path
  206. *
  207. * The supplied result variables are not modified if no special config info is found.
  208. *
  209. * @param physicalAddress Physical endpoint address
  210. * @param mtu Variable set to MTU
  211. * @param trustedPathId Variable set to trusted path ID
  212. */
  213. inline void getOutboundPathInfo(const InetAddress &physicalAddress,unsigned int &mtu,uint64_t &trustedPathId)
  214. {
  215. for(unsigned int i=0,j=_numConfiguredPhysicalPaths;i<j;++i) {
  216. if (_physicalPathConfig[i].first.containsAddress(physicalAddress)) {
  217. trustedPathId = _physicalPathConfig[i].second.trustedPathId;
  218. mtu = _physicalPathConfig[i].second.mtu;
  219. return;
  220. }
  221. }
  222. }
  223. /**
  224. * Get the payload MTU for an outbound physical path (returns default if not configured)
  225. *
  226. * @param physicalAddress Physical endpoint address
  227. * @return MTU
  228. */
  229. inline unsigned int getOutboundPathMtu(const InetAddress &physicalAddress)
  230. {
  231. for(unsigned int i=0,j=_numConfiguredPhysicalPaths;i<j;++i) {
  232. if (_physicalPathConfig[i].first.containsAddress(physicalAddress))
  233. return _physicalPathConfig[i].second.mtu;
  234. }
  235. return ZT_DEFAULT_PHYSMTU;
  236. }
  237. /**
  238. * Get the outbound trusted path ID for a physical address, or 0 if none
  239. *
  240. * @param physicalAddress Physical address to which we are sending the packet
  241. * @return Trusted path ID or 0 if none (0 is not a valid trusted path ID)
  242. */
  243. inline uint64_t getOutboundPathTrust(const InetAddress &physicalAddress)
  244. {
  245. for(unsigned int i=0,j=_numConfiguredPhysicalPaths;i<j;++i) {
  246. if (_physicalPathConfig[i].first.containsAddress(physicalAddress))
  247. return _physicalPathConfig[i].second.trustedPathId;
  248. }
  249. return 0;
  250. }
  251. /**
  252. * Check whether in incoming trusted path marked packet is valid
  253. *
  254. * @param physicalAddress Originating physical address
  255. * @param trustedPathId Trusted path ID from packet (from MAC field)
  256. */
  257. inline bool shouldInboundPathBeTrusted(const InetAddress &physicalAddress,const uint64_t trustedPathId)
  258. {
  259. for(unsigned int i=0,j=_numConfiguredPhysicalPaths;i<j;++i) {
  260. if ((_physicalPathConfig[i].second.trustedPathId == trustedPathId)&&(_physicalPathConfig[i].first.containsAddress(physicalAddress)))
  261. return true;
  262. }
  263. return false;
  264. }
  265. /**
  266. * Set or clear physical path configuration (called via Node::setPhysicalPathConfiguration)
  267. */
  268. inline void setPhysicalPathConfiguration(const struct sockaddr_storage *pathNetwork,const ZT_PhysicalPathConfiguration *pathConfig)
  269. {
  270. if (!pathNetwork) {
  271. _numConfiguredPhysicalPaths = 0;
  272. } else {
  273. std::map<InetAddress,ZT_PhysicalPathConfiguration> cpaths;
  274. for(unsigned int i=0,j=_numConfiguredPhysicalPaths;i<j;++i)
  275. cpaths[_physicalPathConfig[i].first] = _physicalPathConfig[i].second;
  276. if (pathConfig) {
  277. ZT_PhysicalPathConfiguration pc(*pathConfig);
  278. if (pc.mtu <= 0)
  279. pc.mtu = ZT_DEFAULT_PHYSMTU;
  280. else if (pc.mtu < ZT_MIN_PHYSMTU)
  281. pc.mtu = ZT_MIN_PHYSMTU;
  282. else if (pc.mtu > ZT_MAX_PHYSMTU)
  283. pc.mtu = ZT_MAX_PHYSMTU;
  284. cpaths[*(reinterpret_cast<const InetAddress *>(pathNetwork))] = pc;
  285. } else {
  286. cpaths.erase(*(reinterpret_cast<const InetAddress *>(pathNetwork)));
  287. }
  288. unsigned int cnt = 0;
  289. for(std::map<InetAddress,ZT_PhysicalPathConfiguration>::const_iterator i(cpaths.begin());((i!=cpaths.end())&&(cnt<ZT_MAX_CONFIGURABLE_PATHS));++i) {
  290. _physicalPathConfig[cnt].first = i->first;
  291. _physicalPathConfig[cnt].second = i->second;
  292. ++cnt;
  293. }
  294. _numConfiguredPhysicalPaths = cnt;
  295. }
  296. }
  297. private:
  298. Identity _getIdentity(void *tPtr,const Address &zta);
  299. void _memoizeUpstreams(void *tPtr);
  300. void _savePeer(void *tPtr,const SharedPtr<Peer> &peer);
  301. const RuntimeEnvironment *const RR;
  302. std::pair<InetAddress,ZT_PhysicalPathConfiguration> _physicalPathConfig[ZT_MAX_CONFIGURABLE_PATHS];
  303. volatile unsigned int _numConfiguredPhysicalPaths;
  304. Hashtable< Address,SharedPtr<Peer> > _peers;
  305. Mutex _peers_m;
  306. Hashtable< Path::HashKey,SharedPtr<Path> > _paths;
  307. Mutex _paths_m;
  308. };
  309. } // namespace ZeroTier
  310. #endif