Topology.hpp 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325
  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 CollectPeersThatNeedFirewallOpener
  172. {
  173. public:
  174. CollectPeersThatNeedFirewallOpener(std::vector< SharedPtr<Peer> > &v) :
  175. _now(Utils::now()),
  176. _v(v)
  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. _v.push_back(p);
  183. }
  184. private:
  185. uint64_t _now;
  186. std::vector< SharedPtr<Peer> > &_v;
  187. };
  188. /**
  189. * Function object to collect peers that need a ping sent
  190. */
  191. class CollectPeersThatNeedPing
  192. {
  193. public:
  194. CollectPeersThatNeedPing(std::vector< SharedPtr<Peer> > &v) :
  195. _now(Utils::now()),
  196. _v(v)
  197. {
  198. }
  199. inline void operator()(Topology &t,const SharedPtr<Peer> &p)
  200. {
  201. if ( ((t.isSupernode(p->address()))&&((_now - p->lastDirectReceive()) >= ZT_PEER_DIRECT_PING_DELAY)) || ((p->hasActiveDirectPath(_now))&&((_now - p->lastDirectSend()) >= ZT_PEER_DIRECT_PING_DELAY)) )
  202. _v.push_back(p);
  203. }
  204. private:
  205. uint64_t _now;
  206. std::vector< SharedPtr<Peer> > &_v;
  207. };
  208. /**
  209. * Function object to collect peers with active links (and supernodes)
  210. */
  211. class CollectPeersWithActiveDirectPath
  212. {
  213. public:
  214. CollectPeersWithActiveDirectPath(std::vector< SharedPtr<Peer> > &v) :
  215. _now(Utils::now()),
  216. _v(v)
  217. {
  218. }
  219. inline void operator()(Topology &t,const SharedPtr<Peer> &p)
  220. {
  221. if ((p->hasActiveDirectPath(_now))||(t.isSupernode(p->address())))
  222. _v.push_back(p);
  223. }
  224. private:
  225. uint64_t _now;
  226. std::vector< SharedPtr<Peer> > &_v;
  227. };
  228. /**
  229. * Function object to collect peers with any known direct path
  230. */
  231. class CollectPeersWithDirectPath
  232. {
  233. public:
  234. CollectPeersWithDirectPath(std::vector< SharedPtr<Peer> > &v) :
  235. _v(v)
  236. {
  237. }
  238. inline void operator()(Topology &t,const SharedPtr<Peer> &p)
  239. {
  240. if (p->hasDirectPath())
  241. _v.push_back(p);
  242. }
  243. private:
  244. std::vector< SharedPtr<Peer> > &_v;
  245. };
  246. /**
  247. * Thread main method; do not call elsewhere
  248. */
  249. void threadMain()
  250. throw();
  251. private:
  252. void _reallyAddPeer(const SharedPtr<Peer> &p);
  253. // A job for the background deep verify thread (also does cache cleaning, flushing, etc.)
  254. struct _PeerDeepVerifyJob
  255. {
  256. void (*callback)(void *,const SharedPtr<Peer> &,Topology::PeerVerifyResult);
  257. void *arg;
  258. SharedPtr<Peer> candidate;
  259. enum {
  260. VERIFY_PEER,
  261. CLEAN_CACHE,
  262. EXIT_THREAD
  263. } type;
  264. };
  265. const RuntimeEnvironment *const _r;
  266. Thread<Topology> _thread;
  267. std::map< Address,SharedPtr<Peer> > _activePeers;
  268. Mutex _activePeers_m;
  269. std::list< _PeerDeepVerifyJob > _peerDeepVerifyJobs;
  270. Mutex _peerDeepVerifyJobs_m;
  271. Condition _peerDeepVerifyJobs_c;
  272. std::map< Identity,std::vector<InetAddress> > _supernodes;
  273. std::set< Address > _supernodeAddresses;
  274. std::vector< SharedPtr<Peer> > _supernodePeers;
  275. Mutex _supernodes_m;
  276. // Set to true if my identity is in _supernodes
  277. volatile bool _amSupernode;
  278. KISSDB _dbm;
  279. Mutex _dbm_m;
  280. };
  281. } // namespace ZeroTier
  282. #endif