Topology.hpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391
  1. /*
  2. * ZeroTier One - Global Peer to Peer Ethernet
  3. * Copyright (C) 2011-2014 ZeroTier Networks LLC
  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 <set>
  33. #include <vector>
  34. #include <stdexcept>
  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 "Packet.hpp"
  43. #include "Logger.hpp"
  44. #include "Dictionary.hpp"
  45. namespace ZeroTier {
  46. class RuntimeEnvironment;
  47. /**
  48. * Database of network topology
  49. */
  50. class Topology
  51. {
  52. public:
  53. Topology(const RuntimeEnvironment *renv,bool enablePermanentIdCaching);
  54. ~Topology();
  55. /**
  56. * Set up supernodes for this network
  57. *
  58. * @param sn Supernodes for this network
  59. */
  60. void setSupernodes(const std::map< Identity,std::vector< std::pair<InetAddress,bool> > > &sn);
  61. /**
  62. * Set up supernodes for this network
  63. *
  64. * This performs no signature verification of any kind. The caller must
  65. * check the signature of the root topology dictionary first.
  66. *
  67. * @param sn Supernodes dictionary from root-topology
  68. */
  69. void setSupernodes(const Dictionary &sn);
  70. /**
  71. * Add a peer to database
  72. *
  73. * This will not replace existing peers. In that case the existing peer
  74. * record is returned.
  75. *
  76. * @param peer Peer to add
  77. * @return New or existing peer (should replace 'peer')
  78. */
  79. SharedPtr<Peer> addPeer(const SharedPtr<Peer> &peer);
  80. /**
  81. * Get a peer from its address
  82. *
  83. * @param zta ZeroTier address of peer
  84. * @return Peer or NULL if not found
  85. */
  86. SharedPtr<Peer> getPeer(const Address &zta) const;
  87. /**
  88. * Get an identity if cached or available in a peer record
  89. *
  90. * @param zta ZeroTier address
  91. * @return Identity or NULL-identity if not found
  92. */
  93. Identity getIdentity(const Address &zta);
  94. /**
  95. * Save identity in permanent store, or do nothing if disabled
  96. *
  97. * This is called automatically by addPeer(), so it should not need to be
  98. * called manually anywhere else. The private part of the identity, if
  99. * present, is NOT cached by this.
  100. *
  101. * @param id Identity to save
  102. */
  103. void saveIdentity(const Identity &id);
  104. /**
  105. * @return Vector of peers that are supernodes
  106. */
  107. inline std::vector< SharedPtr<Peer> > supernodePeers() const
  108. {
  109. Mutex::Lock _l(_supernodes_m);
  110. return _supernodePeers;
  111. }
  112. /**
  113. * @return Number of supernodes
  114. */
  115. inline unsigned int numSupernodes() const
  116. {
  117. Mutex::Lock _l(_supernodes_m);
  118. return _supernodePeers.size();
  119. }
  120. /**
  121. * Get the current favorite supernode
  122. *
  123. * @return Supernode with lowest latency or NULL if none
  124. */
  125. inline SharedPtr<Peer> getBestSupernode() const
  126. {
  127. return getBestSupernode((const Address *)0,0,false);
  128. }
  129. /**
  130. * Get the best supernode, avoiding supernodes listed in an array
  131. *
  132. * This will get the best supernode (lowest latency, etc.) but will
  133. * try to avoid the listed supernodes, only using them if no others
  134. * are available.
  135. *
  136. * @param avoid Nodes to avoid
  137. * @param avoidCount Number of nodes to avoid
  138. * @param strictAvoid If false, consider avoided supernodes anyway if no non-avoid supernodes are available
  139. * @return Supernode or NULL if none
  140. */
  141. SharedPtr<Peer> getBestSupernode(const Address *avoid,unsigned int avoidCount,bool strictAvoid) const;
  142. /**
  143. * @param zta ZeroTier address
  144. * @return True if this is a designated supernode
  145. */
  146. inline bool isSupernode(const Address &zta) const
  147. throw()
  148. {
  149. Mutex::Lock _l(_supernodes_m);
  150. return (_supernodeAddresses.count(zta) > 0);
  151. }
  152. /**
  153. * @return Set of supernode addresses
  154. */
  155. inline std::set<Address> supernodeAddresses() const
  156. {
  157. Mutex::Lock _l(_supernodes_m);
  158. return _supernodeAddresses;
  159. }
  160. /**
  161. * @return True if this node's identity is in the supernode set
  162. */
  163. inline bool amSupernode() const { return _amSupernode; }
  164. /**
  165. * Clean and flush database
  166. */
  167. void clean();
  168. /**
  169. * Apply a function or function object to all peers
  170. *
  171. * @param f Function to apply
  172. * @tparam F Function or function object type
  173. */
  174. template<typename F>
  175. inline void eachPeer(F f)
  176. {
  177. Mutex::Lock _l(_activePeers_m);
  178. for(std::map< Address,SharedPtr<Peer> >::const_iterator p(_activePeers.begin());p!=_activePeers.end();++p)
  179. f(*this,p->second);
  180. }
  181. /**
  182. * Apply a function or function object to all supernode peers
  183. *
  184. * @param f Function to apply
  185. * @tparam F Function or function object type
  186. */
  187. template<typename F>
  188. inline void eachSupernodePeer(F f)
  189. {
  190. Mutex::Lock _l(_supernodes_m);
  191. for(std::vector< SharedPtr<Peer> >::const_iterator p(_supernodePeers.begin());p!=_supernodePeers.end();++p)
  192. f(*this,*p);
  193. }
  194. /**
  195. * Pings all peers that need a ping sent, excluding supernodes
  196. *
  197. * Ordinary peers are pinged if we haven't heard from them recently. Receive
  198. * time rather than send time as OK is returned on success and we want to
  199. * keep trying if a packet is lost. Ordinary peers are subject to a frame
  200. * inactivity timeout. We give up if we haven't actually transferred any
  201. * data to them recently, and eventually Topology purges them from memory.
  202. */
  203. class PingPeersThatNeedPing
  204. {
  205. public:
  206. PingPeersThatNeedPing(const RuntimeEnvironment *renv,uint64_t now) throw() :
  207. _now(now),
  208. _supernodeAddresses(renv->topology->supernodeAddresses()),
  209. _r(renv) {}
  210. inline void operator()(Topology &t,const SharedPtr<Peer> &p)
  211. {
  212. /* For ordinary nodes we ping if they've sent us a frame recently,
  213. * otherwise they are stale and we let the link die.
  214. *
  215. * Note that we measure ping time from time of last receive rather
  216. * than time of last send in order to only count full round trips. */
  217. if ( (!_supernodeAddresses.count(p->address())) &&
  218. ((_now - p->lastFrame()) < ZT_PEER_PATH_ACTIVITY_TIMEOUT) &&
  219. ((_now - p->lastDirectReceive()) >= ZT_PEER_DIRECT_PING_DELAY) ) {
  220. p->sendPing(_r,_now);
  221. }
  222. }
  223. private:
  224. uint64_t _now;
  225. std::set<Address> _supernodeAddresses;
  226. const RuntimeEnvironment *_r;
  227. };
  228. /**
  229. * Ping peers that need ping according to supernode rules
  230. *
  231. * Supernodes ping aggressively if a ping is unanswered and they are not
  232. * subject to the activity timeout. In other words: we assume they are
  233. * always there and always try to reach them.
  234. *
  235. * The ultimate rate limit for this is controlled up in the Node main loop.
  236. */
  237. class PingSupernodesThatNeedPing
  238. {
  239. public:
  240. PingSupernodesThatNeedPing(const RuntimeEnvironment *renv,uint64_t now) throw() :
  241. _now(now),
  242. _r(renv) {}
  243. inline void operator()(Topology &t,const SharedPtr<Peer> &p)
  244. {
  245. /* For supernodes we always ping even if no frames have been seen, and
  246. * we ping aggressively if pings are unanswered. The limit to this
  247. * frequency is set in the main loop to no more than ZT_STARTUP_AGGRO. */
  248. uint64_t lp = 0;
  249. uint64_t lr = 0;
  250. p->lastPingAndDirectReceive(lp,lr);
  251. if ( (lr < _r->timeOfLastResynchronize) || ((lr < lp)&&((lp - lr) >= ZT_PING_UNANSWERED_AFTER)) || ((_now - lr) >= ZT_PEER_DIRECT_PING_DELAY) )
  252. p->sendPing(_r,_now);
  253. }
  254. private:
  255. uint64_t _now;
  256. const RuntimeEnvironment *_r;
  257. };
  258. /**
  259. * Computes most recent timestamp of direct packet receive over a list of peers
  260. */
  261. class FindMostRecentDirectReceiveTimestamp
  262. {
  263. public:
  264. FindMostRecentDirectReceiveTimestamp(uint64_t &ts) throw() : _ts(ts) {}
  265. inline void operator()(Topology &t,const SharedPtr<Peer> &p) throw() { _ts = std::max(p->lastDirectReceive(),_ts); }
  266. private:
  267. uint64_t &_ts;
  268. };
  269. /**
  270. * Function object to forget direct links to active peers and then ping them indirectly
  271. */
  272. class ResetActivePeers
  273. {
  274. public:
  275. ResetActivePeers(const RuntimeEnvironment *renv,uint64_t now) throw() :
  276. _now(now),
  277. _supernode(renv->topology->getBestSupernode()),
  278. _supernodeAddresses(renv->topology->supernodeAddresses()),
  279. _r(renv) {}
  280. inline void operator()(Topology &t,const SharedPtr<Peer> &p)
  281. {
  282. p->clearPaths(false); // false means don't forget 'fixed' paths e.g. supernodes
  283. Packet outp(p->address(),_r->identity.address(),Packet::VERB_NOP);
  284. outp.armor(p->key(),false); // no need to encrypt a NOP
  285. if (_supernodeAddresses.count(p->address())) {
  286. // Send NOP directly to supernodes
  287. p->send(_r,outp.data(),outp.size(),_now);
  288. } else {
  289. // Send NOP indirectly to regular peers if still active, triggering a new RENDEZVOUS
  290. if (((_now - p->lastFrame()) < ZT_PEER_PATH_ACTIVITY_TIMEOUT)&&(_supernode)) {
  291. TRACE("sending reset NOP to %s",p->address().toString().c_str());
  292. _supernode->send(_r,outp.data(),outp.size(),_now);
  293. }
  294. }
  295. }
  296. private:
  297. uint64_t _now;
  298. SharedPtr<Peer> _supernode;
  299. std::set<Address> _supernodeAddresses;
  300. const RuntimeEnvironment *_r;
  301. };
  302. /**
  303. * Function object to collect peers with any known direct path
  304. */
  305. class CollectPeersWithActiveDirectPath
  306. {
  307. public:
  308. CollectPeersWithActiveDirectPath(std::vector< SharedPtr<Peer> > &v,uint64_t now) throw() :
  309. _now(now),
  310. _v(v) {}
  311. inline void operator()(Topology &t,const SharedPtr<Peer> &p)
  312. {
  313. if (p->hasActiveDirectPath(_now))
  314. _v.push_back(p);
  315. }
  316. private:
  317. uint64_t _now;
  318. std::vector< SharedPtr<Peer> > &_v;
  319. };
  320. /**
  321. * Validate a root topology dictionary against the identities specified in Defaults
  322. *
  323. * @param rt Root topology dictionary
  324. * @return True if dictionary signature is valid
  325. */
  326. static bool authenticateRootTopology(const Dictionary &rt);
  327. private:
  328. const RuntimeEnvironment *const _r;
  329. void _dumpPeers();
  330. void _loadPeers();
  331. std::string _idCacheBase; // empty if identity caching disabled
  332. std::map< Address,SharedPtr<Peer> > _activePeers;
  333. Mutex _activePeers_m;
  334. std::map< Identity,std::vector< std::pair<InetAddress,bool> > > _supernodes;
  335. std::set< Address > _supernodeAddresses;
  336. std::vector< SharedPtr<Peer> > _supernodePeers;
  337. Mutex _supernodes_m;
  338. // Set to true if my identity is in _supernodes
  339. volatile bool _amSupernode;
  340. };
  341. } // namespace ZeroTier
  342. #endif