Topology.hpp 11 KB

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