Topology.hpp 9.7 KB

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