Topology.cpp 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299
  1. /*
  2. * ZeroTier One - Global Peer to Peer Ethernet
  3. * Copyright (C) 2011-2014 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. #include <algorithm>
  28. #include "Constants.hpp"
  29. #include "Defaults.hpp"
  30. #include "Topology.hpp"
  31. #include "NodeConfig.hpp"
  32. #include "CMWC4096.hpp"
  33. #include "Dictionary.hpp"
  34. #define ZT_PEER_WRITE_BUF_SIZE 131072
  35. namespace ZeroTier {
  36. Topology::Topology(const RuntimeEnvironment *renv) :
  37. RR(renv),
  38. _idCacheBase(renv->homePath + ZT_PATH_SEPARATOR_S + "iddb.d"),
  39. _amSupernode(false)
  40. {
  41. }
  42. Topology::~Topology()
  43. {
  44. }
  45. void Topology::setSupernodes(const std::map< Identity,std::vector< std::pair<InetAddress,bool> > > &sn)
  46. {
  47. Mutex::Lock _l(_supernodes_m);
  48. if (_supernodes == sn)
  49. return; // no change
  50. _supernodes = sn;
  51. _supernodeAddresses.clear();
  52. _supernodePeers.clear();
  53. uint64_t now = Utils::now();
  54. for(std::map< Identity,std::vector< std::pair<InetAddress,bool> > >::const_iterator i(sn.begin());i!=sn.end();++i) {
  55. if (i->first != RR->identity) {
  56. SharedPtr<Peer> p(getPeer(i->first.address()));
  57. if (!p)
  58. p = addPeer(SharedPtr<Peer>(new Peer(RR->identity,i->first)));
  59. for(std::vector< std::pair<InetAddress,bool> >::const_iterator j(i->second.begin());j!=i->second.end();++j)
  60. p->addPath(Path(j->first,(j->second) ? Path::PATH_TYPE_TCP_OUT : Path::PATH_TYPE_UDP,true));
  61. p->use(now);
  62. _supernodePeers.push_back(p);
  63. }
  64. _supernodeAddresses.insert(i->first.address());
  65. }
  66. _amSupernode = (_supernodes.find(RR->identity) != _supernodes.end());
  67. }
  68. void Topology::setSupernodes(const Dictionary &sn)
  69. {
  70. std::map< Identity,std::vector< std::pair<InetAddress,bool> > > m;
  71. for(Dictionary::const_iterator d(sn.begin());d!=sn.end();++d) {
  72. if ((d->first.length() == ZT_ADDRESS_LENGTH_HEX)&&(d->second.length() > 0)) {
  73. try {
  74. Dictionary snspec(d->second);
  75. std::vector< std::pair<InetAddress,bool> > &a = m[Identity(snspec.get("id"))];
  76. std::string udp(snspec.get("udp",std::string()));
  77. if (udp.length() > 0)
  78. a.push_back(std::pair<InetAddress,bool>(InetAddress(udp),false));
  79. std::string tcp(snspec.get("tcp",std::string()));
  80. a.push_back(std::pair<InetAddress,bool>(InetAddress(tcp),true));
  81. } catch ( ... ) {
  82. LOG("supernode list contained invalid entry for: %s",d->first.c_str());
  83. }
  84. }
  85. }
  86. this->setSupernodes(m);
  87. }
  88. SharedPtr<Peer> Topology::addPeer(const SharedPtr<Peer> &peer)
  89. {
  90. if (peer->address() == RR->identity.address()) {
  91. TRACE("BUG: addNewPeer() caught and ignored attempt to add peer for self");
  92. throw std::logic_error("cannot add peer for self");
  93. }
  94. uint64_t now = Utils::now();
  95. Mutex::Lock _l(_activePeers_m);
  96. SharedPtr<Peer> p(_activePeers.insert(std::pair< Address,SharedPtr<Peer> >(peer->address(),peer)).first->second);
  97. p->use(now);
  98. _saveIdentity(p->identity());
  99. return p;
  100. }
  101. SharedPtr<Peer> Topology::getPeer(const Address &zta)
  102. {
  103. if (zta == RR->identity.address()) {
  104. TRACE("BUG: ignored attempt to getPeer() for self, returned NULL");
  105. return SharedPtr<Peer>();
  106. }
  107. uint64_t now = Utils::now();
  108. Mutex::Lock _l(_activePeers_m);
  109. SharedPtr<Peer> &ap = _activePeers[zta];
  110. if (ap) {
  111. ap->use(now);
  112. return ap;
  113. }
  114. Identity id(_getIdentity(zta));
  115. if (id) {
  116. try {
  117. ap = SharedPtr<Peer>(new Peer(RR->identity,id));
  118. ap->use(now);
  119. return ap;
  120. } catch ( ... ) {} // invalid identity?
  121. }
  122. _activePeers.erase(zta);
  123. return SharedPtr<Peer>();
  124. }
  125. SharedPtr<Peer> Topology::getBestSupernode(const Address *avoid,unsigned int avoidCount,bool strictAvoid)
  126. {
  127. SharedPtr<Peer> bestSupernode;
  128. uint64_t now = Utils::now();
  129. Mutex::Lock _l(_supernodes_m);
  130. if (_amSupernode) {
  131. /* If I am a supernode, the "best" supernode is the one whose address
  132. * is numerically greater than mine (with wrap at top of list). This
  133. * causes packets searching for a route to pretty much literally
  134. * circumnavigate the globe rather than bouncing between just two. */
  135. if (_supernodeAddresses.size() > 1) { // gotta be one other than me for this to work
  136. std::set<Address>::const_iterator sna(_supernodeAddresses.find(RR->identity.address()));
  137. if (sna != _supernodeAddresses.end()) { // sanity check -- _amSupernode should've been false in this case
  138. for(;;) {
  139. if (++sna == _supernodeAddresses.end())
  140. sna = _supernodeAddresses.begin(); // wrap around at end
  141. if (*sna != RR->identity.address()) { // pick one other than us -- starting from me+1 in sorted set order
  142. SharedPtr<Peer> p(getPeer(*sna));
  143. if ((p)&&(p->hasActiveDirectPath(now))) {
  144. bestSupernode = p;
  145. break;
  146. }
  147. }
  148. }
  149. }
  150. }
  151. } else {
  152. /* If I am not a supernode, the best supernode is the active one with
  153. * the lowest latency. */
  154. unsigned int l,bestSupernodeLatency = 65536;
  155. uint64_t lds,ldr;
  156. // First look for a best supernode by comparing latencies, but exclude
  157. // supernodes that have not responded to direct messages in order to
  158. // try to exclude any that are dead or unreachable.
  159. for(std::vector< SharedPtr<Peer> >::const_iterator sn(_supernodePeers.begin());sn!=_supernodePeers.end();) {
  160. // Skip explicitly avoided relays
  161. for(unsigned int i=0;i<avoidCount;++i) {
  162. if (avoid[i] == (*sn)->address())
  163. goto keep_searching_for_supernodes;
  164. }
  165. // Skip possibly comatose or unreachable relays
  166. lds = (*sn)->lastDirectSend();
  167. ldr = (*sn)->lastDirectReceive();
  168. if ((lds)&&(lds > ldr)&&((lds - ldr) > ZT_PEER_RELAY_CONVERSATION_LATENCY_THRESHOLD))
  169. goto keep_searching_for_supernodes;
  170. if ((*sn)->hasActiveDirectPath(now)) {
  171. l = (*sn)->latency();
  172. if (bestSupernode) {
  173. if ((l)&&(l < bestSupernodeLatency)) {
  174. bestSupernodeLatency = l;
  175. bestSupernode = *sn;
  176. }
  177. } else {
  178. if (l)
  179. bestSupernodeLatency = l;
  180. bestSupernode = *sn;
  181. }
  182. }
  183. keep_searching_for_supernodes:
  184. ++sn;
  185. }
  186. if (bestSupernode) {
  187. bestSupernode->use(now);
  188. return bestSupernode;
  189. } else if (strictAvoid)
  190. return SharedPtr<Peer>();
  191. // If we have nothing from above, just pick one without avoidance criteria.
  192. for(std::vector< SharedPtr<Peer> >::const_iterator sn=_supernodePeers.begin();sn!=_supernodePeers.end();++sn) {
  193. if ((*sn)->hasActiveDirectPath(now)) {
  194. unsigned int l = (*sn)->latency();
  195. if (bestSupernode) {
  196. if ((l)&&(l < bestSupernodeLatency)) {
  197. bestSupernodeLatency = l;
  198. bestSupernode = *sn;
  199. }
  200. } else {
  201. if (l)
  202. bestSupernodeLatency = l;
  203. bestSupernode = *sn;
  204. }
  205. }
  206. }
  207. }
  208. if (bestSupernode)
  209. bestSupernode->use(now);
  210. return bestSupernode;
  211. }
  212. void Topology::clean(uint64_t now)
  213. {
  214. Mutex::Lock _l(_activePeers_m);
  215. Mutex::Lock _l2(_supernodes_m);
  216. for(std::map< Address,SharedPtr<Peer> >::iterator p(_activePeers.begin());p!=_activePeers.end();) {
  217. if (((now - p->second->lastUsed()) >= ZT_PEER_IN_MEMORY_EXPIRATION)&&(!_supernodeAddresses.count(p->second->address()))) {
  218. _activePeers.erase(p++);
  219. } else {
  220. p->second->clean(now);
  221. ++p;
  222. }
  223. }
  224. }
  225. bool Topology::authenticateRootTopology(const Dictionary &rt)
  226. {
  227. try {
  228. std::string signer(rt.signingIdentity());
  229. if (!signer.length())
  230. return false;
  231. Identity signerId(signer);
  232. std::map< Address,Identity >::const_iterator authority(ZT_DEFAULTS.rootTopologyAuthorities.find(signerId.address()));
  233. if (authority == ZT_DEFAULTS.rootTopologyAuthorities.end())
  234. return false;
  235. if (signerId != authority->second)
  236. return false;
  237. return rt.verify(authority->second);
  238. } catch ( ... ) {
  239. return false;
  240. }
  241. }
  242. Identity Topology::_getIdentity(const Address &zta)
  243. {
  244. std::string idcPath(_idCacheBase + ZT_PATH_SEPARATOR_S + zta.toString());
  245. std::string ids;
  246. if (Utils::readFile(idcPath.c_str(),ids)) {
  247. try {
  248. return Identity(ids);
  249. } catch ( ... ) {} // ignore invalid IDs
  250. }
  251. return Identity();
  252. }
  253. void Topology::_saveIdentity(const Identity &id)
  254. {
  255. if (id) {
  256. std::string idcPath(_idCacheBase + ZT_PATH_SEPARATOR_S + id.address().toString());
  257. Utils::writeFile(idcPath.c_str(),id.toString(false));
  258. }
  259. }
  260. } // namespace ZeroTier