Topology.hpp 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359
  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. #include "Root.hpp"
  44. namespace ZeroTier {
  45. class RuntimeEnvironment;
  46. /**
  47. * Database of network topology
  48. */
  49. class Topology
  50. {
  51. public:
  52. inline Topology(const RuntimeEnvironment *renv,const Identity &myId) :
  53. RR(renv),
  54. _myIdentity(myId),
  55. _numConfiguredPhysicalPaths(0) {}
  56. inline ~Topology() {}
  57. /**
  58. * Add a peer to database
  59. *
  60. * This will not replace existing peers. In that case the existing peer
  61. * record is returned.
  62. *
  63. * @param tPtr Thread pointer to be handed through to any callbacks called as a result of this call
  64. * @param peer Peer to add
  65. * @return New or existing peer (should replace 'peer')
  66. */
  67. inline SharedPtr<Peer> add(const SharedPtr<Peer> &peer)
  68. {
  69. SharedPtr<Peer> np;
  70. {
  71. Mutex::Lock _l(_peers_m);
  72. SharedPtr<Peer> &hp = _peers[peer->address()];
  73. if (!hp)
  74. hp = peer;
  75. np = hp;
  76. }
  77. return np;
  78. }
  79. /**
  80. * Get a peer from its address
  81. *
  82. * @param tPtr Thread pointer to be handed through to any callbacks called as a result of this call
  83. * @param zta ZeroTier address of peer
  84. * @return Peer or NULL if not found
  85. */
  86. inline SharedPtr<Peer> get(const Address &zta)
  87. {
  88. if (zta == _myIdentity.address())
  89. return SharedPtr<Peer>();
  90. Mutex::Lock l1(_peers_m);
  91. const SharedPtr<Peer> *const ap = _peers.get(zta);
  92. if (ap)
  93. return *ap;
  94. Mutex::Lock l2(_roots_m);
  95. for(std::vector<Root>::const_iterator r(_roots.begin());r!=_roots.end();++r) {
  96. if (r->address() == zta) {
  97. try {
  98. SharedPtr<Peer> rp(new Peer(RR,_myIdentity,r->id()));
  99. _peers[zta] = rp;
  100. return rp;
  101. } catch ( ... ) {}
  102. }
  103. }
  104. return SharedPtr<Peer>();
  105. }
  106. /**
  107. * @param tPtr Thread pointer to be handed through to any callbacks called as a result of this call
  108. * @param zta ZeroTier address of peer
  109. * @return Identity or NULL identity if not found
  110. */
  111. inline Identity getIdentity(void *tPtr,const Address &zta)
  112. {
  113. if (zta == _myIdentity.address()) {
  114. return _myIdentity;
  115. } else {
  116. Mutex::Lock _l(_peers_m);
  117. const SharedPtr<Peer> *const ap = _peers.get(zta);
  118. if (ap)
  119. return (*ap)->identity();
  120. }
  121. return Identity();
  122. }
  123. /**
  124. * Get a Path object for a given local and remote physical address, creating if needed
  125. *
  126. * @param l Local socket
  127. * @param r Remote address
  128. * @return Pointer to canonicalized Path object
  129. */
  130. inline SharedPtr<Path> getPath(const int64_t l,const InetAddress &r)
  131. {
  132. Mutex::Lock _l(_paths_m);
  133. SharedPtr<Path> &p = _paths[Path::HashKey(l,r)];
  134. if (!p)
  135. p.set(new Path(l,r));
  136. return p;
  137. }
  138. /**
  139. * @param id Identity to check
  140. * @return True if this identity corresponds to a root
  141. */
  142. inline bool isRoot(const Identity &id) const
  143. {
  144. Mutex::Lock l(_roots_m);
  145. for(std::vector<Root>::const_iterator r(_roots.begin());r!=_roots.end();++r) {
  146. if (r->is(id))
  147. return true;
  148. }
  149. return false;
  150. }
  151. /**
  152. * Do periodic tasks such as database cleanup
  153. */
  154. inline void doPeriodicTasks(int64_t now)
  155. {
  156. {
  157. Mutex::Lock _l1(_peers_m);
  158. Hashtable< Address,SharedPtr<Peer> >::Iterator i(_peers);
  159. Address *a = (Address *)0;
  160. SharedPtr<Peer> *p = (SharedPtr<Peer> *)0;
  161. while (i.next(a,p)) {
  162. if (!(*p)->isAlive(now)) {
  163. _peers.erase(*a);
  164. }
  165. }
  166. }
  167. {
  168. Mutex::Lock _l(_paths_m);
  169. Hashtable< Path::HashKey,SharedPtr<Path> >::Iterator i(_paths);
  170. Path::HashKey *k = (Path::HashKey *)0;
  171. SharedPtr<Path> *p = (SharedPtr<Path> *)0;
  172. while (i.next(k,p)) {
  173. if (p->references() <= 1)
  174. _paths.erase(*k);
  175. }
  176. }
  177. }
  178. /**
  179. * @param now Current time
  180. * @return Number of peers with active direct paths
  181. */
  182. inline unsigned long countActive(int64_t now) const
  183. {
  184. unsigned long cnt = 0;
  185. Mutex::Lock _l(_peers_m);
  186. Hashtable< Address,SharedPtr<Peer> >::Iterator i(const_cast<Topology *>(this)->_peers);
  187. Address *a = (Address *)0;
  188. SharedPtr<Peer> *p = (SharedPtr<Peer> *)0;
  189. while (i.next(a,p)) {
  190. const SharedPtr<Path> pp((*p)->getAppropriatePath(now,false));
  191. if (pp)
  192. ++cnt;
  193. }
  194. return cnt;
  195. }
  196. /**
  197. * Apply a function or function object to all peers
  198. *
  199. * @param f Function to apply
  200. * @tparam F Function or function object type
  201. */
  202. template<typename F>
  203. inline void eachPeer(F f)
  204. {
  205. Mutex::Lock _l(_peers_m);
  206. Hashtable< Address,SharedPtr<Peer> >::Iterator i(_peers);
  207. Address *a = (Address *)0;
  208. SharedPtr<Peer> *p = (SharedPtr<Peer> *)0;
  209. while (i.next(a,p)) {
  210. f(*this,*((const SharedPtr<Peer> *)p));
  211. }
  212. }
  213. /**
  214. * @return All peers by address (unsorted)
  215. */
  216. inline std::vector< std::pair< Address,SharedPtr<Peer> > > allPeers() const
  217. {
  218. Mutex::Lock _l(_peers_m);
  219. return _peers.entries();
  220. }
  221. /**
  222. * Get info about a path
  223. *
  224. * The supplied result variables are not modified if no special config info is found.
  225. *
  226. * @param physicalAddress Physical endpoint address
  227. * @param mtu Variable set to MTU
  228. * @param trustedPathId Variable set to trusted path ID
  229. */
  230. inline void getOutboundPathInfo(const InetAddress &physicalAddress,unsigned int &mtu,uint64_t &trustedPathId)
  231. {
  232. for(unsigned int i=0,j=_numConfiguredPhysicalPaths;i<j;++i) {
  233. if (_physicalPathConfig[i].first.containsAddress(physicalAddress)) {
  234. trustedPathId = _physicalPathConfig[i].second.trustedPathId;
  235. mtu = _physicalPathConfig[i].second.mtu;
  236. return;
  237. }
  238. }
  239. }
  240. /**
  241. * Get the payload MTU for an outbound physical path (returns default if not configured)
  242. *
  243. * @param physicalAddress Physical endpoint address
  244. * @return MTU
  245. */
  246. inline unsigned int getOutboundPathMtu(const InetAddress &physicalAddress)
  247. {
  248. for(unsigned int i=0,j=_numConfiguredPhysicalPaths;i<j;++i) {
  249. if (_physicalPathConfig[i].first.containsAddress(physicalAddress))
  250. return _physicalPathConfig[i].second.mtu;
  251. }
  252. return ZT_DEFAULT_PHYSMTU;
  253. }
  254. /**
  255. * Get the outbound trusted path ID for a physical address, or 0 if none
  256. *
  257. * @param physicalAddress Physical address to which we are sending the packet
  258. * @return Trusted path ID or 0 if none (0 is not a valid trusted path ID)
  259. */
  260. inline uint64_t getOutboundPathTrust(const InetAddress &physicalAddress)
  261. {
  262. for(unsigned int i=0,j=_numConfiguredPhysicalPaths;i<j;++i) {
  263. if (_physicalPathConfig[i].first.containsAddress(physicalAddress))
  264. return _physicalPathConfig[i].second.trustedPathId;
  265. }
  266. return 0;
  267. }
  268. /**
  269. * Check whether in incoming trusted path marked packet is valid
  270. *
  271. * @param physicalAddress Originating physical address
  272. * @param trustedPathId Trusted path ID from packet (from MAC field)
  273. */
  274. inline bool shouldInboundPathBeTrusted(const InetAddress &physicalAddress,const uint64_t trustedPathId)
  275. {
  276. for(unsigned int i=0,j=_numConfiguredPhysicalPaths;i<j;++i) {
  277. if ((_physicalPathConfig[i].second.trustedPathId == trustedPathId)&&(_physicalPathConfig[i].first.containsAddress(physicalAddress)))
  278. return true;
  279. }
  280. return false;
  281. }
  282. /**
  283. * Set or clear physical path configuration (called via Node::setPhysicalPathConfiguration)
  284. */
  285. inline void setPhysicalPathConfiguration(const struct sockaddr_storage *pathNetwork,const ZT_PhysicalPathConfiguration *pathConfig)
  286. {
  287. if (!pathNetwork) {
  288. _numConfiguredPhysicalPaths = 0;
  289. } else {
  290. std::map<InetAddress,ZT_PhysicalPathConfiguration> cpaths;
  291. for(unsigned int i=0,j=_numConfiguredPhysicalPaths;i<j;++i)
  292. cpaths[_physicalPathConfig[i].first] = _physicalPathConfig[i].second;
  293. if (pathConfig) {
  294. ZT_PhysicalPathConfiguration pc(*pathConfig);
  295. if (pc.mtu <= 0)
  296. pc.mtu = ZT_DEFAULT_PHYSMTU;
  297. else if (pc.mtu < ZT_MIN_PHYSMTU)
  298. pc.mtu = ZT_MIN_PHYSMTU;
  299. else if (pc.mtu > ZT_MAX_PHYSMTU)
  300. pc.mtu = ZT_MAX_PHYSMTU;
  301. cpaths[*(reinterpret_cast<const InetAddress *>(pathNetwork))] = pc;
  302. } else {
  303. cpaths.erase(*(reinterpret_cast<const InetAddress *>(pathNetwork)));
  304. }
  305. unsigned int cnt = 0;
  306. for(std::map<InetAddress,ZT_PhysicalPathConfiguration>::const_iterator i(cpaths.begin());((i!=cpaths.end())&&(cnt<ZT_MAX_CONFIGURABLE_PATHS));++i) {
  307. _physicalPathConfig[cnt].first = i->first;
  308. _physicalPathConfig[cnt].second = i->second;
  309. ++cnt;
  310. }
  311. _numConfiguredPhysicalPaths = cnt;
  312. }
  313. }
  314. private:
  315. const RuntimeEnvironment *const RR;
  316. const Identity _myIdentity;
  317. std::pair<InetAddress,ZT_PhysicalPathConfiguration> _physicalPathConfig[ZT_MAX_CONFIGURABLE_PATHS];
  318. unsigned int _numConfiguredPhysicalPaths;
  319. std::vector<Root> _roots;
  320. Hashtable< Address,SharedPtr<Peer> > _peers;
  321. Hashtable< Path::HashKey,SharedPtr<Path> > _paths;
  322. Mutex _roots_m;
  323. Mutex _peers_m;
  324. Mutex _paths_m;
  325. };
  326. } // namespace ZeroTier
  327. #endif