Topology.hpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458
  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 "Path.hpp"
  32. #include "Mutex.hpp"
  33. #include "InetAddress.hpp"
  34. #include "Hashtable.hpp"
  35. #include "World.hpp"
  36. #include "CertificateOfRepresentation.hpp"
  37. namespace ZeroTier {
  38. class RuntimeEnvironment;
  39. /**
  40. * Database of network topology
  41. */
  42. class Topology
  43. {
  44. public:
  45. Topology(const RuntimeEnvironment *renv,void *tPtr);
  46. /**
  47. * Add a peer to database
  48. *
  49. * This will not replace existing peers. In that case the existing peer
  50. * record is returned.
  51. *
  52. * @param tPtr Thread pointer to be handed through to any callbacks called as a result of this call
  53. * @param peer Peer to add
  54. * @return New or existing peer (should replace 'peer')
  55. */
  56. SharedPtr<Peer> addPeer(void *tPtr,const SharedPtr<Peer> &peer);
  57. /**
  58. * Get a peer from its address
  59. *
  60. * @param tPtr Thread pointer to be handed through to any callbacks called as a result of this call
  61. * @param zta ZeroTier address of peer
  62. * @return Peer or NULL if not found
  63. */
  64. SharedPtr<Peer> getPeer(void *tPtr,const Address &zta);
  65. /**
  66. * Get a peer only if it is presently in memory (no disk cache)
  67. *
  68. * This also does not update the lastUsed() time for peers, which means
  69. * that it won't prevent them from falling out of RAM. This is currently
  70. * used in the Cluster code to update peer info without forcing all peers
  71. * across the entire cluster to remain in memory cache.
  72. *
  73. * @param zta ZeroTier address
  74. */
  75. inline SharedPtr<Peer> getPeerNoCache(const Address &zta)
  76. {
  77. Mutex::Lock _l(_peers_m);
  78. const SharedPtr<Peer> *const ap = _peers.get(zta);
  79. if (ap)
  80. return *ap;
  81. return SharedPtr<Peer>();
  82. }
  83. /**
  84. * Get a Path object for a given local and remote physical address, creating if needed
  85. *
  86. * @param l Local address or NULL for 'any' or 'wildcard'
  87. * @param r Remote address
  88. * @return Pointer to canonicalized Path object
  89. */
  90. inline SharedPtr<Path> getPath(const InetAddress &l,const InetAddress &r)
  91. {
  92. Mutex::Lock _l(_paths_m);
  93. SharedPtr<Path> &p = _paths[Path::HashKey(l,r)];
  94. if (!p)
  95. p.setToUnsafe(new Path(l,r));
  96. return p;
  97. }
  98. /**
  99. * Get the identity of a peer
  100. *
  101. * @param tPtr Thread pointer to be handed through to any callbacks called as a result of this call
  102. * @param zta ZeroTier address of peer
  103. * @return Identity or NULL Identity if not found
  104. */
  105. Identity getIdentity(void *tPtr,const Address &zta);
  106. /**
  107. * Cache an identity
  108. *
  109. * This is done automatically on addPeer(), and so is only useful for
  110. * cluster identity replication.
  111. *
  112. * @param tPtr Thread pointer to be handed through to any callbacks called as a result of this call
  113. * @param id Identity to cache
  114. */
  115. void saveIdentity(void *tPtr,const Identity &id);
  116. /**
  117. * Get the current best upstream peer
  118. *
  119. * @return Root server with lowest latency or NULL if none
  120. */
  121. inline SharedPtr<Peer> getUpstreamPeer() { return getUpstreamPeer((const Address *)0,0,false); }
  122. /**
  123. * Get the current best upstream peer, avoiding those in the supplied avoid list
  124. *
  125. * @param avoid Nodes to avoid
  126. * @param avoidCount Number of nodes to avoid
  127. * @param strictAvoid If false, consider avoided root servers anyway if no non-avoid root servers are available
  128. * @return Root server or NULL if none available
  129. */
  130. SharedPtr<Peer> getUpstreamPeer(const Address *avoid,unsigned int avoidCount,bool strictAvoid);
  131. /**
  132. * @param id Identity to check
  133. * @return True if this is a root server or a network preferred relay from one of our networks
  134. */
  135. bool isUpstream(const Identity &id) const;
  136. /**
  137. * @param addr Address to check
  138. * @return True if we should accept a world update from this address
  139. */
  140. bool shouldAcceptWorldUpdateFrom(const Address &addr) const;
  141. /**
  142. * @param ztaddr ZeroTier address
  143. * @return Peer role for this device
  144. */
  145. ZT_PeerRole role(const Address &ztaddr) const;
  146. /**
  147. * Check for prohibited endpoints
  148. *
  149. * Right now this returns true if the designated ZT address is a root and if
  150. * the IP (IP only, not port) does not equal any of the IPs defined in the
  151. * current World. This is an extra little security feature in case root keys
  152. * get appropriated or something.
  153. *
  154. * Otherwise it returns false.
  155. *
  156. * @param ztaddr ZeroTier address
  157. * @param ipaddr IP address
  158. * @return True if this ZT/IP pair should not be allowed to be used
  159. */
  160. bool isProhibitedEndpoint(const Address &ztaddr,const InetAddress &ipaddr) const;
  161. /**
  162. * Gets upstreams to contact and their stable endpoints (if known)
  163. *
  164. * @param eps Hash table to fill with addresses and their stable endpoints
  165. */
  166. inline void getUpstreamsToContact(Hashtable< Address,std::vector<InetAddress> > &eps) const
  167. {
  168. Mutex::Lock _l(_upstreams_m);
  169. for(std::vector<World::Root>::const_iterator i(_planet.roots().begin());i!=_planet.roots().end();++i) {
  170. if (i->identity != RR->identity) {
  171. std::vector<InetAddress> &ips = eps[i->identity.address()];
  172. for(std::vector<InetAddress>::const_iterator j(i->stableEndpoints.begin());j!=i->stableEndpoints.end();++j) {
  173. if (std::find(ips.begin(),ips.end(),*j) == ips.end())
  174. ips.push_back(*j);
  175. }
  176. }
  177. }
  178. for(std::vector<World>::const_iterator m(_moons.begin());m!=_moons.end();++m) {
  179. for(std::vector<World::Root>::const_iterator i(m->roots().begin());i!=m->roots().end();++i) {
  180. if (i->identity != RR->identity) {
  181. std::vector<InetAddress> &ips = eps[i->identity.address()];
  182. for(std::vector<InetAddress>::const_iterator j(i->stableEndpoints.begin());j!=i->stableEndpoints.end();++j) {
  183. if (std::find(ips.begin(),ips.end(),*j) == ips.end())
  184. ips.push_back(*j);
  185. }
  186. }
  187. }
  188. }
  189. for(std::vector< std::pair<uint64_t,Address> >::const_iterator m(_moonSeeds.begin());m!=_moonSeeds.end();++m)
  190. eps[m->second];
  191. }
  192. /**
  193. * @return Vector of active upstream addresses (including roots)
  194. */
  195. inline std::vector<Address> upstreamAddresses() const
  196. {
  197. Mutex::Lock _l(_upstreams_m);
  198. return _upstreamAddresses;
  199. }
  200. /**
  201. * @return Current moons
  202. */
  203. inline std::vector<World> moons() const
  204. {
  205. Mutex::Lock _l(_upstreams_m);
  206. return _moons;
  207. }
  208. /**
  209. * @return Moon IDs we are waiting for from seeds
  210. */
  211. inline std::vector<uint64_t> moonsWanted() const
  212. {
  213. Mutex::Lock _l(_upstreams_m);
  214. std::vector<uint64_t> mw;
  215. for(std::vector< std::pair<uint64_t,Address> >::const_iterator s(_moonSeeds.begin());s!=_moonSeeds.end();++s) {
  216. if (std::find(mw.begin(),mw.end(),s->first) == mw.end())
  217. mw.push_back(s->first);
  218. }
  219. return mw;
  220. }
  221. /**
  222. * @return Current planet
  223. */
  224. inline World planet() const
  225. {
  226. Mutex::Lock _l(_upstreams_m);
  227. return _planet;
  228. }
  229. /**
  230. * @return Current planet's world ID
  231. */
  232. inline uint64_t planetWorldId() const
  233. {
  234. return _planet.id(); // safe to read without lock, and used from within eachPeer() so don't lock
  235. }
  236. /**
  237. * @return Current planet's world timestamp
  238. */
  239. inline uint64_t planetWorldTimestamp() const
  240. {
  241. return _planet.timestamp(); // safe to read without lock, and used from within eachPeer() so don't lock
  242. }
  243. /**
  244. * Validate new world and update if newer and signature is okay
  245. *
  246. * @param tPtr Thread pointer to be handed through to any callbacks called as a result of this call
  247. * @param newWorld A new or updated planet or moon to learn
  248. * @param alwaysAcceptNew If true, always accept new moons even if we're not waiting for one
  249. * @return True if it was valid and newer than current (or totally new for moons)
  250. */
  251. bool addWorld(void *tPtr,const World &newWorld,bool alwaysAcceptNew);
  252. /**
  253. * Add a moon
  254. *
  255. * This loads it from moons.d if present, and if not adds it to
  256. * a list of moons that we want to contact.
  257. *
  258. * @param id Moon ID
  259. * @param seed If non-NULL, an address of any member of the moon to contact
  260. */
  261. void addMoon(void *tPtr,const uint64_t id,const Address &seed);
  262. /**
  263. * Remove a moon
  264. *
  265. * @param tPtr Thread pointer to be handed through to any callbacks called as a result of this call
  266. * @param id Moon's world ID
  267. */
  268. void removeMoon(void *tPtr,const uint64_t id);
  269. /**
  270. * Clean and flush database
  271. */
  272. void clean(uint64_t now);
  273. /**
  274. * @param now Current time
  275. * @return Number of peers with active direct paths
  276. */
  277. inline unsigned long countActive(uint64_t now) const
  278. {
  279. unsigned long cnt = 0;
  280. Mutex::Lock _l(_peers_m);
  281. Hashtable< Address,SharedPtr<Peer> >::Iterator i(const_cast<Topology *>(this)->_peers);
  282. Address *a = (Address *)0;
  283. SharedPtr<Peer> *p = (SharedPtr<Peer> *)0;
  284. while (i.next(a,p)) {
  285. const SharedPtr<Path> pp((*p)->getBestPath(now,false));
  286. if ((pp)&&(pp->alive(now)))
  287. ++cnt;
  288. }
  289. return cnt;
  290. }
  291. /**
  292. * Apply a function or function object to all peers
  293. *
  294. * @param f Function to apply
  295. * @tparam F Function or function object type
  296. */
  297. template<typename F>
  298. inline void eachPeer(F f)
  299. {
  300. Mutex::Lock _l(_peers_m);
  301. Hashtable< Address,SharedPtr<Peer> >::Iterator i(_peers);
  302. Address *a = (Address *)0;
  303. SharedPtr<Peer> *p = (SharedPtr<Peer> *)0;
  304. while (i.next(a,p)) {
  305. #ifdef ZT_TRACE
  306. if (!(*p)) {
  307. 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());
  308. abort();
  309. }
  310. #endif
  311. f(*this,*((const SharedPtr<Peer> *)p));
  312. }
  313. }
  314. /**
  315. * @return All currently active peers by address (unsorted)
  316. */
  317. inline std::vector< std::pair< Address,SharedPtr<Peer> > > allPeers() const
  318. {
  319. Mutex::Lock _l(_peers_m);
  320. return _peers.entries();
  321. }
  322. /**
  323. * @return True if I am a root server in a planet or moon
  324. */
  325. inline bool amRoot() const { return _amRoot; }
  326. /**
  327. * Get the outbound trusted path ID for a physical address, or 0 if none
  328. *
  329. * @param physicalAddress Physical address to which we are sending the packet
  330. * @return Trusted path ID or 0 if none (0 is not a valid trusted path ID)
  331. */
  332. inline uint64_t getOutboundPathTrust(const InetAddress &physicalAddress)
  333. {
  334. for(unsigned int i=0;i<_trustedPathCount;++i) {
  335. if (_trustedPathNetworks[i].containsAddress(physicalAddress))
  336. return _trustedPathIds[i];
  337. }
  338. return 0;
  339. }
  340. /**
  341. * Check whether in incoming trusted path marked packet is valid
  342. *
  343. * @param physicalAddress Originating physical address
  344. * @param trustedPathId Trusted path ID from packet (from MAC field)
  345. */
  346. inline bool shouldInboundPathBeTrusted(const InetAddress &physicalAddress,const uint64_t trustedPathId)
  347. {
  348. for(unsigned int i=0;i<_trustedPathCount;++i) {
  349. if ((_trustedPathIds[i] == trustedPathId)&&(_trustedPathNetworks[i].containsAddress(physicalAddress)))
  350. return true;
  351. }
  352. return false;
  353. }
  354. /**
  355. * Set trusted paths in this topology
  356. *
  357. * @param networks Array of networks (prefix/netmask bits)
  358. * @param ids Array of trusted path IDs
  359. * @param count Number of trusted paths (if larger than ZT_MAX_TRUSTED_PATHS overflow is ignored)
  360. */
  361. inline void setTrustedPaths(const InetAddress *networks,const uint64_t *ids,unsigned int count)
  362. {
  363. if (count > ZT_MAX_TRUSTED_PATHS)
  364. count = ZT_MAX_TRUSTED_PATHS;
  365. Mutex::Lock _l(_trustedPaths_m);
  366. for(unsigned int i=0;i<count;++i) {
  367. _trustedPathIds[i] = ids[i];
  368. _trustedPathNetworks[i] = networks[i];
  369. }
  370. _trustedPathCount = count;
  371. }
  372. /**
  373. * @return Current certificate of representation (copy)
  374. */
  375. inline CertificateOfRepresentation certificateOfRepresentation() const
  376. {
  377. Mutex::Lock _l(_upstreams_m);
  378. return _cor;
  379. }
  380. /**
  381. * @param buf Buffer to receive COR
  382. */
  383. template<unsigned int C>
  384. void appendCertificateOfRepresentation(Buffer<C> &buf)
  385. {
  386. Mutex::Lock _l(_upstreams_m);
  387. _cor.serialize(buf);
  388. }
  389. private:
  390. Identity _getIdentity(void *tPtr,const Address &zta);
  391. void _memoizeUpstreams(void *tPtr);
  392. const RuntimeEnvironment *const RR;
  393. uint64_t _trustedPathIds[ZT_MAX_TRUSTED_PATHS];
  394. InetAddress _trustedPathNetworks[ZT_MAX_TRUSTED_PATHS];
  395. unsigned int _trustedPathCount;
  396. Mutex _trustedPaths_m;
  397. Hashtable< Address,SharedPtr<Peer> > _peers;
  398. Mutex _peers_m;
  399. Hashtable< Path::HashKey,SharedPtr<Path> > _paths;
  400. Mutex _paths_m;
  401. World _planet;
  402. std::vector<World> _moons;
  403. std::vector< std::pair<uint64_t,Address> > _moonSeeds;
  404. std::vector<Address> _upstreamAddresses;
  405. CertificateOfRepresentation _cor;
  406. bool _amRoot;
  407. Mutex _upstreams_m; // locks worlds, upstream info, moon info, etc.
  408. };
  409. } // namespace ZeroTier
  410. #endif