Topology.hpp 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339
  1. /*
  2. * ZeroTier One - Global Peer to Peer Ethernet
  3. * Copyright (C) 2012-2013 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 <map>
  30. #include <set>
  31. #include <list>
  32. #include <vector>
  33. #include <stdexcept>
  34. #include "Address.hpp"
  35. #include "Peer.hpp"
  36. #include "Mutex.hpp"
  37. #include "Condition.hpp"
  38. #include "InetAddress.hpp"
  39. #include "Constants.hpp"
  40. #include "Thread.hpp"
  41. #include "MulticastGroup.hpp"
  42. #include "Utils.hpp"
  43. #include "../ext/kissdb/kissdb.h"
  44. namespace ZeroTier {
  45. class RuntimeEnvironment;
  46. /**
  47. * Database of network topology
  48. */
  49. class Topology : protected Thread
  50. {
  51. public:
  52. /**
  53. * Result of peer add/verify
  54. */
  55. enum PeerVerifyResult
  56. {
  57. PEER_VERIFY_ACCEPTED_NEW, /* new peer */
  58. PEER_VERIFY_ACCEPTED_ALREADY_HAVE, /* we already knew ye */
  59. PEER_VERIFY_ACCEPTED_DISPLACED_INVALID_ADDRESS, /* you booted out an impostor */
  60. PEER_VERIFY_REJECTED_INVALID_IDENTITY, /* identity is invalid or validation failed */
  61. PEER_VERIFY_REJECTED_DUPLICATE, /* someone equally valid already has your address */
  62. PEER_VERIFY_REJECTED_DUPLICATE_TRIAGED /* you look duplicate and I'm too busy to deep verify */
  63. };
  64. Topology(const RuntimeEnvironment *renv,const char *dbpath)
  65. throw(std::runtime_error);
  66. virtual ~Topology();
  67. /**
  68. * Set up supernodes for this network
  69. *
  70. * @param sn Supernodes for this network
  71. */
  72. void setSupernodes(const std::map< Identity,std::vector<InetAddress> > &sn);
  73. /**
  74. * Add a peer to this network
  75. *
  76. * Verification and adding actually occurs in the background, since in
  77. * rare cases it can be somewhat CPU-intensive. The callback will be
  78. * called (from the background thread) when add is complete.
  79. *
  80. * The peer given to the callback may not be the same object provided
  81. * as a candidate if the candidate was an exact duplicate of a peer we
  82. * already have.
  83. *
  84. * @param candidate New candidate peer to be added
  85. * @param callback Callback to call when peer verification is complete
  86. * @param arg First argument to callback
  87. * @return Verification result or PEER_VERIFY__IN_PROGRESS if occurring in background
  88. */
  89. void addPeer(const SharedPtr<Peer> &candidate,void (*callback)(void *,const SharedPtr<Peer> &,PeerVerifyResult),void *arg);
  90. /**
  91. * Get a peer from its address
  92. *
  93. * @param zta ZeroTier address of peer
  94. * @return Peer or NULL if not found
  95. */
  96. SharedPtr<Peer> getPeer(const Address &zta);
  97. /**
  98. * @return Current network supernodes
  99. */
  100. inline std::map< Identity,std::vector<InetAddress> > supernodes() const
  101. {
  102. Mutex::Lock _l(_supernodes_m);
  103. return _supernodes;
  104. }
  105. /**
  106. * @return Vector of peers that are supernodes
  107. */
  108. inline std::vector< SharedPtr<Peer> > supernodePeers() const
  109. {
  110. Mutex::Lock _l(_supernodes_m);
  111. return _supernodePeers;
  112. }
  113. /**
  114. * Get the current favorite supernode
  115. *
  116. * @return Supernode with lowest latency or NULL if none
  117. */
  118. inline SharedPtr<Peer> getBestSupernode() const
  119. {
  120. return getBestSupernode((const Address *)0,0);
  121. }
  122. /**
  123. * Get the best supernode, avoiding supernodes listed in an array
  124. *
  125. * This will get the best supernode (lowest latency, etc.) but will
  126. * try to avoid the listed supernodes, only using them if no others
  127. * are available.
  128. *
  129. * @param avoid Nodes to avoid
  130. * @param avoidCount Number of nodes to avoid
  131. * @return Supernode or NULL if none
  132. */
  133. SharedPtr<Peer> getBestSupernode(const Address *avoid,unsigned int avoidCount) const;
  134. /**
  135. * @param zta ZeroTier address
  136. * @return True if this is a designated supernode
  137. */
  138. inline bool isSupernode(const Address &zta) const
  139. throw()
  140. {
  141. Mutex::Lock _l(_supernodes_m);
  142. return (_supernodeAddresses.count(zta) > 0);
  143. }
  144. /**
  145. * Clean and flush database now (runs in the background)
  146. */
  147. void clean();
  148. /**
  149. * Pick peers for multicast propagation
  150. *
  151. * @param nwid Network ID
  152. * @param exclude Peer to exclude or zero address for none
  153. * @param propagationBloom Propgation bloom filter
  154. * @param propagationBloomSize Size of propagation bloom filter in BITS
  155. * @param count Number of peers desired (propagation breadth)
  156. * @param mg Multicast group
  157. * @param peers Array to receive peers (must be at least [count])
  158. * @return Number of peers actually picked
  159. */
  160. unsigned int pickMulticastPropagationPeers(uint64_t nwid,const Address &exclude,const void *propagationBloom,unsigned int propagationBloomSize,unsigned int count,const MulticastGroup &mg,SharedPtr<Peer> *peers);
  161. /**
  162. * Add or update last 'like' time for an address's membership in a multicast group
  163. *
  164. * @param nwid Network ID
  165. * @param mg Multicast group
  166. * @param addr ZeroTier address
  167. * @param now Current time
  168. */
  169. void likesMulticastGroup(uint64_t nwid,const MulticastGroup &mg,const Address &addr,uint64_t now);
  170. /**
  171. * Apply a function or function object to all peers
  172. *
  173. * @param f Function to apply
  174. * @tparam F Function or function object type
  175. */
  176. template<typename F>
  177. inline void eachPeer(F f)
  178. {
  179. Mutex::Lock _l(_activePeers_m);
  180. for(std::map< Address,SharedPtr<Peer> >::const_iterator p(_activePeers.begin());p!=_activePeers.end();++p)
  181. f(*this,p->second);
  182. }
  183. /**
  184. * Function object to collect peers that need a firewall opener sent
  185. */
  186. class CollectPeersThatNeedFirewallOpener
  187. {
  188. public:
  189. CollectPeersThatNeedFirewallOpener(std::vector< SharedPtr<Peer> > &v) :
  190. _now(Utils::now()),
  191. _v(v)
  192. {
  193. }
  194. inline void operator()(Topology &t,const SharedPtr<Peer> &p)
  195. {
  196. if ((p->hasDirectPath())&&((_now - p->lastFirewallOpener()) >= ZT_FIREWALL_OPENER_DELAY))
  197. _v.push_back(p);
  198. }
  199. private:
  200. uint64_t _now;
  201. std::vector< SharedPtr<Peer> > &_v;
  202. };
  203. /**
  204. * Function object to collect peers that need a ping sent
  205. */
  206. class CollectPeersThatNeedPing
  207. {
  208. public:
  209. CollectPeersThatNeedPing(std::vector< SharedPtr<Peer> > &v) :
  210. _now(Utils::now()),
  211. _v(v)
  212. {
  213. }
  214. inline void operator()(Topology &t,const SharedPtr<Peer> &p)
  215. {
  216. if (((p->hasActiveDirectPath(_now))||(t.isSupernode(p->address())))&&((_now - p->lastDirectSend()) >= ZT_PEER_DIRECT_PING_DELAY))
  217. _v.push_back(p);
  218. }
  219. private:
  220. uint64_t _now;
  221. std::vector< SharedPtr<Peer> > &_v;
  222. };
  223. /**
  224. * Function object to collect peers with active links (and supernodes)
  225. */
  226. class CollectPeersWithActiveDirectPath
  227. {
  228. public:
  229. CollectPeersWithActiveDirectPath(std::vector< SharedPtr<Peer> > &v) :
  230. _now(Utils::now()),
  231. _v(v)
  232. {
  233. }
  234. inline void operator()(Topology &t,const SharedPtr<Peer> &p)
  235. {
  236. if ((p->hasActiveDirectPath(_now))||(t.isSupernode(p->address())))
  237. _v.push_back(p);
  238. }
  239. private:
  240. uint64_t _now;
  241. std::vector< SharedPtr<Peer> > &_v;
  242. };
  243. /**
  244. * Function object to collect peers with any known direct path
  245. */
  246. class CollectPeersWithDirectPath
  247. {
  248. public:
  249. CollectPeersWithDirectPath(std::vector< SharedPtr<Peer> > &v) :
  250. _v(v)
  251. {
  252. }
  253. inline void operator()(Topology &t,const SharedPtr<Peer> &p)
  254. {
  255. if (p->hasDirectPath())
  256. _v.push_back(p);
  257. }
  258. private:
  259. std::vector< SharedPtr<Peer> > &_v;
  260. };
  261. protected:
  262. virtual void main()
  263. throw();
  264. private:
  265. void _reallyAddPeer(const SharedPtr<Peer> &p);
  266. // A job for the background deep verify thread (also does cache cleaning, flushing, etc.)
  267. struct _PeerDeepVerifyJob
  268. {
  269. void (*callback)(void *,const SharedPtr<Peer> &,Topology::PeerVerifyResult);
  270. void *arg;
  271. SharedPtr<Peer> candidate;
  272. enum {
  273. VERIFY_PEER,
  274. CLEAN_CACHE,
  275. EXIT_THREAD
  276. } type;
  277. };
  278. const RuntimeEnvironment *const _r;
  279. std::map< Address,SharedPtr<Peer> > _activePeers;
  280. Mutex _activePeers_m;
  281. std::list< _PeerDeepVerifyJob > _peerDeepVerifyJobs;
  282. Mutex _peerDeepVerifyJobs_m;
  283. Condition _peerDeepVerifyJobs_c;
  284. std::map< Identity,std::vector<InetAddress> > _supernodes;
  285. std::set< Address > _supernodeAddresses;
  286. std::vector< SharedPtr<Peer> > _supernodePeers;
  287. Mutex _supernodes_m;
  288. KISSDB _dbm;
  289. Mutex _dbm_m;
  290. // Multicast group members by network ID, then multicast group
  291. std::map< uint64_t,std::map< MulticastGroup,std::map< Address,uint64_t > > > _multicastGroupMembers;
  292. Mutex _multicastGroupMembers_m;
  293. };
  294. } // namespace ZeroTier
  295. #endif