Topology.hpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369
  1. /*
  2. * ZeroTier One - Network Virtualization Everywhere
  3. * Copyright (C) 2011-2015 ZeroTier, Inc.
  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. * ZeroTier may be used and distributed under the terms of the GPLv3, which
  21. * are available at: http://www.gnu.org/licenses/gpl-3.0.html
  22. *
  23. * If you would like to embed ZeroTier into a commercial application or
  24. * redistribute it in a modified binary form, please contact ZeroTier Networks
  25. * LLC. Start here: http://www.zerotier.com/
  26. */
  27. #ifndef ZT_TOPOLOGY_HPP
  28. #define ZT_TOPOLOGY_HPP
  29. #include <stdio.h>
  30. #include <string.h>
  31. #include <map>
  32. #include <vector>
  33. #include <stdexcept>
  34. #include <algorithm>
  35. #include "Constants.hpp"
  36. #include "Address.hpp"
  37. #include "Identity.hpp"
  38. #include "Peer.hpp"
  39. #include "Mutex.hpp"
  40. #include "InetAddress.hpp"
  41. #include "Utils.hpp"
  42. #include "Dictionary.hpp"
  43. #include "ExternalSurface.hpp"
  44. namespace ZeroTier {
  45. class RuntimeEnvironment;
  46. /**
  47. * Database of network topology
  48. */
  49. class Topology
  50. {
  51. public:
  52. Topology(const RuntimeEnvironment *renv);
  53. ~Topology();
  54. /**
  55. * Set up supernodes for this network
  56. *
  57. * @param sn Supernodes for this network
  58. */
  59. void setSupernodes(const std::map< Identity,std::vector< std::pair<InetAddress,bool> > > &sn);
  60. /**
  61. * Set up supernodes for this network
  62. *
  63. * This performs no signature verification of any kind. The caller must
  64. * check the signature of the root topology dictionary first.
  65. *
  66. * @param sn Supernodes dictionary from root-topology
  67. */
  68. void setSupernodes(const Dictionary &sn);
  69. /**
  70. * Add a peer to database
  71. *
  72. * This will not replace existing peers. In that case the existing peer
  73. * record is returned.
  74. *
  75. * @param peer Peer to add
  76. * @return New or existing peer (should replace 'peer')
  77. */
  78. SharedPtr<Peer> addPeer(const SharedPtr<Peer> &peer);
  79. /**
  80. * Get a peer from its address
  81. *
  82. * @param zta ZeroTier address of peer
  83. * @return Peer or NULL if not found
  84. */
  85. SharedPtr<Peer> getPeer(const Address &zta);
  86. /**
  87. * @return Vector of peers that are supernodes
  88. */
  89. inline std::vector< SharedPtr<Peer> > supernodePeers() const
  90. {
  91. Mutex::Lock _l(_lock);
  92. return _supernodePeers;
  93. }
  94. /**
  95. * @return Number of supernodes
  96. */
  97. inline unsigned int numSupernodes() const
  98. {
  99. Mutex::Lock _l(_lock);
  100. return (unsigned int)_supernodePeers.size();
  101. }
  102. /**
  103. * Get the current favorite supernode
  104. *
  105. * @return Supernode with lowest latency or NULL if none
  106. */
  107. inline SharedPtr<Peer> getBestSupernode()
  108. {
  109. return getBestSupernode((const Address *)0,0,false);
  110. }
  111. /**
  112. * Get the best supernode, avoiding supernodes listed in an array
  113. *
  114. * This will get the best supernode (lowest latency, etc.) but will
  115. * try to avoid the listed supernodes, only using them if no others
  116. * are available.
  117. *
  118. * @param avoid Nodes to avoid
  119. * @param avoidCount Number of nodes to avoid
  120. * @param strictAvoid If false, consider avoided supernodes anyway if no non-avoid supernodes are available
  121. * @return Supernode or NULL if none
  122. */
  123. SharedPtr<Peer> getBestSupernode(const Address *avoid,unsigned int avoidCount,bool strictAvoid);
  124. /**
  125. * @param zta ZeroTier address
  126. * @return True if this is a designated supernode
  127. */
  128. inline bool isSupernode(const Address &zta) const
  129. throw()
  130. {
  131. Mutex::Lock _l(_lock);
  132. return (std::find(_supernodeAddresses.begin(),_supernodeAddresses.end(),zta) != _supernodeAddresses.end());
  133. }
  134. /**
  135. * @return Vector of supernode addresses
  136. */
  137. inline std::vector<Address> supernodeAddresses() const
  138. {
  139. Mutex::Lock _l(_lock);
  140. return _supernodeAddresses;
  141. }
  142. /**
  143. * @return True if this node's identity is in the supernode set
  144. */
  145. inline bool amSupernode() const { return _amSupernode; }
  146. /**
  147. * Clean and flush database
  148. */
  149. void clean(uint64_t now);
  150. /**
  151. * Apply a function or function object to all peers
  152. *
  153. * Note: explicitly template this by reference if you want the object
  154. * passed by reference instead of copied.
  155. *
  156. * Warning: be careful not to use features in these that call any other
  157. * methods of Topology that may lock _lock, otherwise a recursive lock
  158. * and deadlock or lock corruption may occur.
  159. *
  160. * @param f Function to apply
  161. * @tparam F Function or function object type
  162. */
  163. template<typename F>
  164. inline void eachPeer(F f)
  165. {
  166. Mutex::Lock _l(_lock);
  167. for(std::map< Address,SharedPtr<Peer> >::const_iterator p(_activePeers.begin());p!=_activePeers.end();++p)
  168. f(*this,p->second);
  169. }
  170. #if 0
  171. /**
  172. * Apply a function or function object to all supernode peers
  173. *
  174. * Note: explicitly template this by reference if you want the object
  175. * passed by reference instead of copied.
  176. *
  177. * Warning: be careful not to use features in these that call any other
  178. * methods of Topology that may lock _lock, otherwise a recursive lock
  179. * and deadlock or lock corruption may occur.
  180. *
  181. * @param f Function to apply
  182. * @tparam F Function or function object type
  183. */
  184. template<typename F>
  185. inline void eachSupernodePeer(F f)
  186. {
  187. Mutex::Lock _l(_lock);
  188. for(std::vector< SharedPtr<Peer> >::const_iterator p(_supernodePeers.begin());p!=_supernodePeers.end();++p)
  189. f(*this,*p);
  190. }
  191. /**
  192. * Pings all peers that need a ping sent, excluding supernodes
  193. *
  194. * Ordinary peers are pinged if we haven't heard from them recently. Receive
  195. * time rather than send time as OK is returned on success and we want to
  196. * keep trying if a packet is lost. Ordinary peers are subject to a frame
  197. * inactivity timeout. We give up if we haven't actually transferred any
  198. * data to them recently, and eventually Topology purges them from memory.
  199. */
  200. class PingPeersThatNeedPing
  201. {
  202. public:
  203. PingPeersThatNeedPing(const RuntimeEnvironment *renv,uint64_t now) throw() :
  204. _now(now),
  205. _supernodeAddresses(renv->topology->supernodeAddresses()),
  206. RR(renv) {}
  207. inline void operator()(Topology &t,const SharedPtr<Peer> &p)
  208. {
  209. /* For ordinary nodes we ping if they've sent us a frame recently,
  210. * otherwise they are stale and we let the link die.
  211. *
  212. * Note that we measure ping time from time of last receive rather
  213. * than time of last send in order to only count full round trips. */
  214. if ( (std::find(_supernodeAddresses.begin(),_supernodeAddresses.end(),p->address()) == _supernodeAddresses.end()) &&
  215. ((_now - p->lastFrame()) < ZT_PEER_PATH_ACTIVITY_TIMEOUT) &&
  216. ((_now - p->lastDirectReceive()) >= ZT_PEER_DIRECT_PING_DELAY) ) {
  217. p->sendPing(RR,_now);
  218. }
  219. }
  220. private:
  221. uint64_t _now;
  222. std::vector<Address> _supernodeAddresses;
  223. const RuntimeEnvironment *RR;
  224. };
  225. /**
  226. * Ping peers that need ping according to supernode rules
  227. *
  228. * Supernodes ping aggressively if a ping is unanswered and they are not
  229. * subject to the activity timeout. In other words: we assume they are
  230. * always there and always try to reach them.
  231. *
  232. * The ultimate rate limit for this is controlled up in the Node main loop.
  233. */
  234. class PingSupernodesThatNeedPing
  235. {
  236. public:
  237. PingSupernodesThatNeedPing(const RuntimeEnvironment *renv,uint64_t now) throw() :
  238. _now(now),
  239. RR(renv) {}
  240. inline void operator()(Topology &t,const SharedPtr<Peer> &p)
  241. {
  242. /* For supernodes we always ping even if no frames have been seen, and
  243. * we ping aggressively if pings are unanswered. The limit to this
  244. * frequency is set in the main loop to no more than ZT_STARTUP_AGGRO. */
  245. uint64_t lp = 0;
  246. uint64_t lr = 0;
  247. p->lastPingAndDirectReceive(lp,lr);
  248. if ( ((lr < lp)&&((lp - lr) >= ZT_PING_UNANSWERED_AFTER)) || ((_now - lr) >= ZT_PEER_DIRECT_PING_DELAY) )
  249. p->sendPing(RR,_now);
  250. }
  251. private:
  252. uint64_t _now;
  253. const RuntimeEnvironment *RR;
  254. };
  255. /**
  256. * Function object to forget direct links to active peers and then ping them indirectly
  257. */
  258. class ResetActivePeers
  259. {
  260. public:
  261. ResetActivePeers(const RuntimeEnvironment *renv,uint64_t now) throw() :
  262. _now(now),
  263. _supernode(renv->topology->getBestSupernode()),
  264. _supernodeAddresses(renv->topology->supernodeAddresses()),
  265. RR(renv) {}
  266. inline void operator()(Topology &t,const SharedPtr<Peer> &p)
  267. {
  268. p->clearPaths(false); // false means don't forget 'fixed' paths e.g. supernodes
  269. Packet outp(p->address(),RR->identity.address(),Packet::VERB_NOP);
  270. outp.armor(p->key(),false); // no need to encrypt a NOP
  271. if (std::find(_supernodeAddresses.begin(),_supernodeAddresses.end(),p->address()) != _supernodeAddresses.end()) {
  272. // Send NOP directly to supernodes
  273. p->send(RR,outp.data(),outp.size(),_now);
  274. } else {
  275. // Send NOP indirectly to regular peers if still active, triggering a new RENDEZVOUS
  276. if (((_now - p->lastFrame()) < ZT_PEER_PATH_ACTIVITY_TIMEOUT)&&(_supernode)) {
  277. TRACE("sending reset NOP to %s",p->address().toString().c_str());
  278. _supernode->send(RR,outp.data(),outp.size(),_now);
  279. }
  280. }
  281. }
  282. private:
  283. uint64_t _now;
  284. SharedPtr<Peer> _supernode;
  285. std::vector<Address> _supernodeAddresses;
  286. const RuntimeEnvironment *RR;
  287. };
  288. #endif
  289. /**
  290. * Update our knowledge of exterior network addresses
  291. *
  292. * If the remote peer in question is trusted, this will update our internal
  293. * instance of ExternalSurface. If our surface has changed, this triggers a
  294. * partial or total reset of ephemeral peer addresses and a renegotiation of
  295. * new ones using supernodes / relays.
  296. *
  297. * @param remotePeer Remote peer address
  298. * @param mirroredAddress Real-world network address the remote peer told us we have
  299. * @param now Current time
  300. */
  301. bool updateSurface(const SharedPtr<Peer> &remotePeer,const InetAddress &mirroredAddress,uint64_t now);
  302. /**
  303. * Validate a root topology dictionary against the identities specified in Defaults
  304. *
  305. * @param rt Root topology dictionary
  306. * @return True if dictionary signature is valid
  307. */
  308. static bool authenticateRootTopology(const Dictionary &rt);
  309. private:
  310. Identity _getIdentity(const Address &zta);
  311. void _saveIdentity(const Identity &id);
  312. const RuntimeEnvironment *RR;
  313. std::string _idCacheBase;
  314. std::map< Address,SharedPtr<Peer> > _activePeers;
  315. std::map< Identity,std::vector< std::pair<InetAddress,bool> > > _supernodes;
  316. std::vector< Address > _supernodeAddresses;
  317. std::vector< SharedPtr<Peer> > _supernodePeers;
  318. ExternalSurface _surface;
  319. Mutex _lock;
  320. // Set to true if my identity is in _supernodes
  321. bool _amSupernode;
  322. };
  323. } // namespace ZeroTier
  324. #endif