Topology.hpp 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343
  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,false);
  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. * @param strictAvoid If false, consider avoided supernodes anyway if no non-avoid supernodes are available
  134. * @return Supernode or NULL if none
  135. */
  136. SharedPtr<Peer> getBestSupernode(const Address *avoid,unsigned int avoidCount,bool strictAvoid) const;
  137. /**
  138. * @param zta ZeroTier address
  139. * @return True if this is a designated supernode
  140. */
  141. inline bool isSupernode(const Address &zta) const
  142. throw()
  143. {
  144. Mutex::Lock _l(_supernodes_m);
  145. return (_supernodeAddresses.count(zta) > 0);
  146. }
  147. /**
  148. * Clean and flush database now (runs in the background)
  149. */
  150. void clean();
  151. /**
  152. * Apply a function or function object to all peers
  153. *
  154. * @param f Function to apply
  155. * @tparam F Function or function object type
  156. */
  157. template<typename F>
  158. inline void eachPeer(F f)
  159. {
  160. Mutex::Lock _l(_activePeers_m);
  161. for(std::map< Address,SharedPtr<Peer> >::const_iterator p(_activePeers.begin());p!=_activePeers.end();++p)
  162. f(*this,p->second);
  163. }
  164. /**
  165. * Function object to collect peers that need a firewall opener sent
  166. */
  167. class CollectPeersThatNeedFirewallOpener
  168. {
  169. public:
  170. CollectPeersThatNeedFirewallOpener(std::vector< SharedPtr<Peer> > &v) :
  171. _now(Utils::now()),
  172. _v(v)
  173. {
  174. }
  175. inline void operator()(Topology &t,const SharedPtr<Peer> &p)
  176. {
  177. if ((p->hasDirectPath())&&((_now - p->lastFirewallOpener()) >= ZT_FIREWALL_OPENER_DELAY))
  178. _v.push_back(p);
  179. }
  180. private:
  181. uint64_t _now;
  182. std::vector< SharedPtr<Peer> > &_v;
  183. };
  184. /**
  185. * Function object to collect peers that need a ping sent
  186. */
  187. class CollectPeersThatNeedPing
  188. {
  189. public:
  190. CollectPeersThatNeedPing(std::vector< SharedPtr<Peer> > &v) :
  191. _now(Utils::now()),
  192. _v(v)
  193. {
  194. }
  195. inline void operator()(Topology &t,const SharedPtr<Peer> &p)
  196. {
  197. if (((p->hasActiveDirectPath(_now))||(t.isSupernode(p->address())))&&((_now - p->lastDirectSend()) >= ZT_PEER_DIRECT_PING_DELAY))
  198. _v.push_back(p);
  199. }
  200. private:
  201. uint64_t _now;
  202. std::vector< SharedPtr<Peer> > &_v;
  203. };
  204. /**
  205. * Function object to collect peers with active links (and supernodes)
  206. */
  207. class CollectPeersWithActiveDirectPath
  208. {
  209. public:
  210. CollectPeersWithActiveDirectPath(std::vector< SharedPtr<Peer> > &v) :
  211. _now(Utils::now()),
  212. _v(v)
  213. {
  214. }
  215. inline void operator()(Topology &t,const SharedPtr<Peer> &p)
  216. {
  217. if ((p->hasActiveDirectPath(_now))||(t.isSupernode(p->address())))
  218. _v.push_back(p);
  219. }
  220. private:
  221. uint64_t _now;
  222. std::vector< SharedPtr<Peer> > &_v;
  223. };
  224. /**
  225. * Function object to collect peers with any known direct path
  226. */
  227. class CollectPeersWithDirectPath
  228. {
  229. public:
  230. CollectPeersWithDirectPath(std::vector< SharedPtr<Peer> > &v) :
  231. _v(v)
  232. {
  233. }
  234. inline void operator()(Topology &t,const SharedPtr<Peer> &p)
  235. {
  236. if (p->hasDirectPath())
  237. _v.push_back(p);
  238. }
  239. private:
  240. std::vector< SharedPtr<Peer> > &_v;
  241. };
  242. /**
  243. * Dump peer I/O statistics to an open FILE (for status reporting and debug)
  244. */
  245. class DumpPeerStatistics
  246. {
  247. public:
  248. DumpPeerStatistics(FILE *out) :
  249. _out(out),
  250. _now(Utils::now())
  251. {
  252. fprintf(_out,"Peer Direct IPv4 Direct IPv6 Latency(ms)"ZT_EOL_S);
  253. }
  254. inline void operator()(Topology &t,const SharedPtr<Peer> &p)
  255. {
  256. InetAddress v4(p->ipv4ActivePath(_now));
  257. InetAddress v6(p->ipv6ActivePath(_now));
  258. fprintf(_out,"%-10s %-21s %-51s %u"ZT_EOL_S,
  259. p->address().toString().c_str(),
  260. ((v4) ? v4.toString().c_str() : "(none)"),
  261. ((v6) ? v6.toString().c_str() : "(none)"),
  262. p->latency());
  263. }
  264. private:
  265. FILE *_out;
  266. uint64_t _now;
  267. };
  268. protected:
  269. virtual void main()
  270. throw();
  271. private:
  272. void _reallyAddPeer(const SharedPtr<Peer> &p);
  273. // A job for the background deep verify thread (also does cache cleaning, flushing, etc.)
  274. struct _PeerDeepVerifyJob
  275. {
  276. void (*callback)(void *,const SharedPtr<Peer> &,Topology::PeerVerifyResult);
  277. void *arg;
  278. SharedPtr<Peer> candidate;
  279. enum {
  280. VERIFY_PEER,
  281. CLEAN_CACHE,
  282. EXIT_THREAD
  283. } type;
  284. };
  285. const RuntimeEnvironment *const _r;
  286. std::map< Address,SharedPtr<Peer> > _activePeers;
  287. Mutex _activePeers_m;
  288. std::list< _PeerDeepVerifyJob > _peerDeepVerifyJobs;
  289. Mutex _peerDeepVerifyJobs_m;
  290. Condition _peerDeepVerifyJobs_c;
  291. std::map< Identity,std::vector<InetAddress> > _supernodes;
  292. std::set< Address > _supernodeAddresses;
  293. std::vector< SharedPtr<Peer> > _supernodePeers;
  294. Mutex _supernodes_m;
  295. KISSDB _dbm;
  296. Mutex _dbm_m;
  297. };
  298. } // namespace ZeroTier
  299. #endif