Topology.hpp 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345
  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
  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. ~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. * @return True if this node's identity is in the supernode set
  149. */
  150. inline bool amSupernode() const { return _amSupernode; }
  151. /**
  152. * Clean and flush database now (runs in the background)
  153. */
  154. void clean();
  155. /**
  156. * Apply a function or function object to all peers
  157. *
  158. * @param f Function to apply
  159. * @tparam F Function or function object type
  160. */
  161. template<typename F>
  162. inline void eachPeer(F f)
  163. {
  164. Mutex::Lock _l(_activePeers_m);
  165. for(std::map< Address,SharedPtr<Peer> >::const_iterator p(_activePeers.begin());p!=_activePeers.end();++p)
  166. f(*this,p->second);
  167. }
  168. /**
  169. * Function object to collect peers that need a firewall opener sent
  170. */
  171. class OpenPeersThatNeedFirewallOpener
  172. {
  173. public:
  174. OpenPeersThatNeedFirewallOpener(const RuntimeEnvironment *renv,uint64_t now) throw() :
  175. _now(now),
  176. _r(renv)
  177. {
  178. }
  179. inline void operator()(Topology &t,const SharedPtr<Peer> &p)
  180. {
  181. if ((p->hasDirectPath())&&((_now - std::max(p->lastFirewallOpener(),p->lastDirectSend())) >= ZT_FIREWALL_OPENER_DELAY))
  182. p->sendFirewallOpener(_r,_now);
  183. }
  184. private:
  185. uint64_t _now;
  186. const RuntimeEnvironment *_r;
  187. };
  188. /**
  189. * Function object to collect peers that need a ping sent
  190. */
  191. class PingPeersThatNeedPing
  192. {
  193. public:
  194. PingPeersThatNeedPing(const RuntimeEnvironment *renv,uint64_t now) throw() :
  195. _now(now),
  196. _r(renv)
  197. {
  198. }
  199. inline void operator()(Topology &t,const SharedPtr<Peer> &p)
  200. {
  201. if (
  202. ((_now - p->lastDirectReceive()) >= ZT_PEER_DIRECT_PING_DELAY) &&
  203. (
  204. (
  205. (p->hasDirectPath())&&
  206. ((_now - p->lastFrame()) < ZT_PEER_LINK_ACTIVITY_TIMEOUT)
  207. ) ||
  208. (t.isSupernode(p->address()))
  209. )
  210. ) {
  211. p->sendPing(_r,_now);
  212. }
  213. }
  214. private:
  215. uint64_t _now;
  216. const RuntimeEnvironment *_r;
  217. };
  218. /**
  219. * Function object to collect peers that we're talking to
  220. */
  221. class PingAllActivePeers
  222. {
  223. public:
  224. PingAllActivePeers(const RuntimeEnvironment *renv,uint64_t now) throw() :
  225. _now(now),
  226. _r(renv)
  227. {
  228. }
  229. inline void operator()(Topology &t,const SharedPtr<Peer> &p)
  230. {
  231. if (
  232. (
  233. (p->hasDirectPath())&&
  234. ((_now - p->lastFrame()) < ZT_PEER_LINK_ACTIVITY_TIMEOUT)
  235. ) ||
  236. (t.isSupernode(p->address()))
  237. ) {
  238. p->sendPing(_r,_now);
  239. }
  240. }
  241. private:
  242. uint64_t _now;
  243. const RuntimeEnvironment *_r;
  244. };
  245. /**
  246. * Function object to collect peers with any known direct path
  247. */
  248. class CollectPeersWithActiveDirectPath
  249. {
  250. public:
  251. CollectPeersWithActiveDirectPath(std::vector< SharedPtr<Peer> > &v,uint64_t now) throw() :
  252. _now(now),
  253. _v(v)
  254. {
  255. }
  256. inline void operator()(Topology &t,const SharedPtr<Peer> &p)
  257. {
  258. if (p->hasActiveDirectPath(_now))
  259. _v.push_back(p);
  260. }
  261. private:
  262. uint64_t _now;
  263. std::vector< SharedPtr<Peer> > &_v;
  264. };
  265. /**
  266. * Thread main method; do not call elsewhere
  267. */
  268. void threadMain()
  269. throw();
  270. private:
  271. void _reallyAddPeer(const SharedPtr<Peer> &p);
  272. // A job for the background deep verify thread (also does cache cleaning, flushing, etc.)
  273. struct _PeerDeepVerifyJob
  274. {
  275. void (*callback)(void *,const SharedPtr<Peer> &,Topology::PeerVerifyResult);
  276. void *arg;
  277. SharedPtr<Peer> candidate;
  278. enum {
  279. VERIFY_PEER,
  280. CLEAN_CACHE,
  281. EXIT_THREAD
  282. } type;
  283. };
  284. const RuntimeEnvironment *const _r;
  285. Thread _thread;
  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. // Set to true if my identity is in _supernodes
  296. volatile bool _amSupernode;
  297. KISSDB _dbm;
  298. Mutex _dbm_m;
  299. };
  300. } // namespace ZeroTier
  301. #endif