Topology.hpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397
  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(uint64_t now);
  168. /**
  169. * Apply a function or function object to all peers
  170. *
  171. * Note: explicitly template this by reference if you want the object
  172. * passed by reference instead of copied.
  173. *
  174. * @param f Function to apply
  175. * @tparam F Function or function object type
  176. */
  177. template<typename F>
  178. inline void eachPeer(F f)
  179. {
  180. Mutex::Lock _l(_activePeers_m);
  181. for(std::map< Address,SharedPtr<Peer> >::const_iterator p(_activePeers.begin());p!=_activePeers.end();++p)
  182. f(*this,p->second);
  183. }
  184. /**
  185. * Apply a function or function object to all supernode peers
  186. *
  187. * Note: explicitly template this by reference if you want the object
  188. * passed by reference instead of copied.
  189. *
  190. * @param f Function to apply
  191. * @tparam F Function or function object type
  192. */
  193. template<typename F>
  194. inline void eachSupernodePeer(F f)
  195. {
  196. Mutex::Lock _l(_supernodes_m);
  197. for(std::vector< SharedPtr<Peer> >::const_iterator p(_supernodePeers.begin());p!=_supernodePeers.end();++p)
  198. f(*this,*p);
  199. }
  200. /**
  201. * Pings all peers that need a ping sent, excluding supernodes
  202. *
  203. * Ordinary peers are pinged if we haven't heard from them recently. Receive
  204. * time rather than send time as OK is returned on success and we want to
  205. * keep trying if a packet is lost. Ordinary peers are subject to a frame
  206. * inactivity timeout. We give up if we haven't actually transferred any
  207. * data to them recently, and eventually Topology purges them from memory.
  208. */
  209. class PingPeersThatNeedPing
  210. {
  211. public:
  212. PingPeersThatNeedPing(const RuntimeEnvironment *renv,uint64_t now) throw() :
  213. _now(now),
  214. _supernodeAddresses(renv->topology->supernodeAddresses()),
  215. RR(renv) {}
  216. inline void operator()(Topology &t,const SharedPtr<Peer> &p)
  217. {
  218. /* For ordinary nodes we ping if they've sent us a frame recently,
  219. * otherwise they are stale and we let the link die.
  220. *
  221. * Note that we measure ping time from time of last receive rather
  222. * than time of last send in order to only count full round trips. */
  223. if ( (!_supernodeAddresses.count(p->address())) &&
  224. ((_now - p->lastFrame()) < ZT_PEER_PATH_ACTIVITY_TIMEOUT) &&
  225. ((_now - p->lastDirectReceive()) >= ZT_PEER_DIRECT_PING_DELAY) ) {
  226. p->sendPing(RR,_now);
  227. }
  228. }
  229. private:
  230. uint64_t _now;
  231. std::set<Address> _supernodeAddresses;
  232. const RuntimeEnvironment *RR;
  233. };
  234. /**
  235. * Ping peers that need ping according to supernode rules
  236. *
  237. * Supernodes ping aggressively if a ping is unanswered and they are not
  238. * subject to the activity timeout. In other words: we assume they are
  239. * always there and always try to reach them.
  240. *
  241. * The ultimate rate limit for this is controlled up in the Node main loop.
  242. */
  243. class PingSupernodesThatNeedPing
  244. {
  245. public:
  246. PingSupernodesThatNeedPing(const RuntimeEnvironment *renv,uint64_t now) throw() :
  247. _now(now),
  248. RR(renv) {}
  249. inline void operator()(Topology &t,const SharedPtr<Peer> &p)
  250. {
  251. /* For supernodes we always ping even if no frames have been seen, and
  252. * we ping aggressively if pings are unanswered. The limit to this
  253. * frequency is set in the main loop to no more than ZT_STARTUP_AGGRO. */
  254. uint64_t lp = 0;
  255. uint64_t lr = 0;
  256. p->lastPingAndDirectReceive(lp,lr);
  257. if ( (lr < RR->timeOfLastResynchronize) || ((lr < lp)&&((lp - lr) >= ZT_PING_UNANSWERED_AFTER)) || ((_now - lr) >= ZT_PEER_DIRECT_PING_DELAY) )
  258. p->sendPing(RR,_now);
  259. }
  260. private:
  261. uint64_t _now;
  262. const RuntimeEnvironment *RR;
  263. };
  264. /**
  265. * Computes most recent timestamp of direct packet receive over a list of peers
  266. */
  267. class FindMostRecentDirectReceiveTimestamp
  268. {
  269. public:
  270. FindMostRecentDirectReceiveTimestamp(uint64_t &ts) throw() : _ts(ts) {}
  271. inline void operator()(Topology &t,const SharedPtr<Peer> &p) throw() { _ts = std::max(p->lastDirectReceive(),_ts); }
  272. private:
  273. uint64_t &_ts;
  274. };
  275. /**
  276. * Function object to forget direct links to active peers and then ping them indirectly
  277. */
  278. class ResetActivePeers
  279. {
  280. public:
  281. ResetActivePeers(const RuntimeEnvironment *renv,uint64_t now) throw() :
  282. _now(now),
  283. _supernode(renv->topology->getBestSupernode()),
  284. _supernodeAddresses(renv->topology->supernodeAddresses()),
  285. RR(renv) {}
  286. inline void operator()(Topology &t,const SharedPtr<Peer> &p)
  287. {
  288. p->clearPaths(false); // false means don't forget 'fixed' paths e.g. supernodes
  289. Packet outp(p->address(),RR->identity.address(),Packet::VERB_NOP);
  290. outp.armor(p->key(),false); // no need to encrypt a NOP
  291. if (_supernodeAddresses.count(p->address())) {
  292. // Send NOP directly to supernodes
  293. p->send(RR,outp.data(),outp.size(),_now);
  294. } else {
  295. // Send NOP indirectly to regular peers if still active, triggering a new RENDEZVOUS
  296. if (((_now - p->lastFrame()) < ZT_PEER_PATH_ACTIVITY_TIMEOUT)&&(_supernode)) {
  297. TRACE("sending reset NOP to %s",p->address().toString().c_str());
  298. _supernode->send(RR,outp.data(),outp.size(),_now);
  299. }
  300. }
  301. }
  302. private:
  303. uint64_t _now;
  304. SharedPtr<Peer> _supernode;
  305. std::set<Address> _supernodeAddresses;
  306. const RuntimeEnvironment *RR;
  307. };
  308. /**
  309. * Function object to collect peers with any known direct path
  310. */
  311. class CollectPeersWithActiveDirectPath
  312. {
  313. public:
  314. CollectPeersWithActiveDirectPath(std::vector< SharedPtr<Peer> > &v,uint64_t now) throw() :
  315. _now(now),
  316. _v(v) {}
  317. inline void operator()(Topology &t,const SharedPtr<Peer> &p)
  318. {
  319. if (p->hasActiveDirectPath(_now))
  320. _v.push_back(p);
  321. }
  322. private:
  323. uint64_t _now;
  324. std::vector< SharedPtr<Peer> > &_v;
  325. };
  326. /**
  327. * Validate a root topology dictionary against the identities specified in Defaults
  328. *
  329. * @param rt Root topology dictionary
  330. * @return True if dictionary signature is valid
  331. */
  332. static bool authenticateRootTopology(const Dictionary &rt);
  333. private:
  334. const RuntimeEnvironment *RR;
  335. void _dumpPeers();
  336. void _loadPeers();
  337. std::string _idCacheBase; // empty if identity caching disabled
  338. std::map< Address,SharedPtr<Peer> > _activePeers;
  339. Mutex _activePeers_m;
  340. std::map< Identity,std::vector< std::pair<InetAddress,bool> > > _supernodes;
  341. std::set< Address > _supernodeAddresses;
  342. std::vector< SharedPtr<Peer> > _supernodePeers;
  343. Mutex _supernodes_m;
  344. // Set to true if my identity is in _supernodes
  345. volatile bool _amSupernode;
  346. };
  347. } // namespace ZeroTier
  348. #endif