Topology.cpp 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358
  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,bool enablePermanentIdCaching) :
  37. _r(renv),
  38. _amSupernode(false)
  39. {
  40. if (enablePermanentIdCaching)
  41. _idCacheBase = (_r->homePath + ZT_PATH_SEPARATOR_S + "iddb.d");
  42. _loadPeers();
  43. }
  44. Topology::~Topology()
  45. {
  46. clean();
  47. _dumpPeers();
  48. }
  49. void Topology::setSupernodes(const std::map< Identity,std::vector< std::pair<InetAddress,bool> > > &sn)
  50. {
  51. Mutex::Lock _l(_supernodes_m);
  52. if (_supernodes == sn)
  53. return; // no change
  54. _supernodes = sn;
  55. _supernodeAddresses.clear();
  56. _supernodePeers.clear();
  57. uint64_t now = Utils::now();
  58. for(std::map< Identity,std::vector< std::pair<InetAddress,bool> > >::const_iterator i(sn.begin());i!=sn.end();++i) {
  59. if (i->first != _r->identity) {
  60. SharedPtr<Peer> p(getPeer(i->first.address()));
  61. if (!p)
  62. p = addPeer(SharedPtr<Peer>(new Peer(_r->identity,i->first)));
  63. for(std::vector< std::pair<InetAddress,bool> >::const_iterator j(i->second.begin());j!=i->second.end();++j)
  64. p->addPath(Path(j->first,(j->second) ? Path::PATH_TYPE_TCP_OUT : Path::PATH_TYPE_UDP,true));
  65. p->use(now);
  66. _supernodePeers.push_back(p);
  67. }
  68. _supernodeAddresses.insert(i->first.address());
  69. }
  70. _amSupernode = (_supernodes.find(_r->identity) != _supernodes.end());
  71. }
  72. void Topology::setSupernodes(const Dictionary &sn)
  73. {
  74. std::map< Identity,std::vector< std::pair<InetAddress,bool> > > m;
  75. for(Dictionary::const_iterator d(sn.begin());d!=sn.end();++d) {
  76. if ((d->first.length() == ZT_ADDRESS_LENGTH_HEX)&&(d->second.length() > 0)) {
  77. try {
  78. Dictionary snspec(d->second);
  79. std::vector< std::pair<InetAddress,bool> > &a = m[Identity(snspec.get("id"))];
  80. std::string udp(snspec.get("udp",std::string()));
  81. if (udp.length() > 0)
  82. a.push_back(std::pair<InetAddress,bool>(InetAddress(udp),false));
  83. std::string tcp(snspec.get("tcp",std::string()));
  84. a.push_back(std::pair<InetAddress,bool>(InetAddress(tcp),true));
  85. } catch ( ... ) {
  86. LOG("supernode list contained invalid entry for: %s",d->first.c_str());
  87. }
  88. }
  89. }
  90. this->setSupernodes(m);
  91. }
  92. SharedPtr<Peer> Topology::addPeer(const SharedPtr<Peer> &peer)
  93. {
  94. if (peer->address() == _r->identity.address()) {
  95. TRACE("BUG: addNewPeer() caught and ignored attempt to add peer for self");
  96. throw std::logic_error("cannot add peer for self");
  97. }
  98. uint64_t now = Utils::now();
  99. Mutex::Lock _l(_activePeers_m);
  100. SharedPtr<Peer> p(_activePeers.insert(std::pair< Address,SharedPtr<Peer> >(peer->address(),peer)).first->second);
  101. p->use(now);
  102. saveIdentity(p->identity());
  103. return p;
  104. }
  105. SharedPtr<Peer> Topology::getPeer(const Address &zta) const
  106. {
  107. if (zta == _r->identity.address()) {
  108. TRACE("BUG: ignored attempt to getPeer() for self, returned NULL");
  109. return SharedPtr<Peer>();
  110. }
  111. uint64_t now = Utils::now();
  112. Mutex::Lock _l(_activePeers_m);
  113. std::map< Address,SharedPtr<Peer> >::const_iterator ap(_activePeers.find(zta));
  114. if ((ap != _activePeers.end())&&(ap->second)) {
  115. ap->second->use(now);
  116. return ap->second;
  117. }
  118. return SharedPtr<Peer>();
  119. }
  120. Identity Topology::getIdentity(const Address &zta)
  121. {
  122. SharedPtr<Peer> p(getPeer(zta));
  123. if (p)
  124. return p->identity();
  125. if (_idCacheBase.length()) {
  126. std::string idcPath(_idCacheBase + ZT_PATH_SEPARATOR_S + zta.toString());
  127. std::string ids;
  128. if (Utils::readFile(idcPath.c_str(),ids)) {
  129. try {
  130. return Identity(ids);
  131. } catch ( ... ) {} // ignore invalid IDs
  132. }
  133. }
  134. return Identity();
  135. }
  136. void Topology::saveIdentity(const Identity &id)
  137. {
  138. if ((id)&&(_idCacheBase.length())) {
  139. std::string idcPath(_idCacheBase + ZT_PATH_SEPARATOR_S + id.address().toString());
  140. if (!Utils::fileExists(idcPath.c_str()))
  141. Utils::writeFile(idcPath.c_str(),id.toString(false));
  142. }
  143. }
  144. SharedPtr<Peer> Topology::getBestSupernode(const Address *avoid,unsigned int avoidCount,bool strictAvoid) const
  145. {
  146. SharedPtr<Peer> bestSupernode;
  147. unsigned int l,bestSupernodeLatency = 65536;
  148. uint64_t now = Utils::now();
  149. uint64_t lds,ldr;
  150. Mutex::Lock _l(_supernodes_m);
  151. // First look for a best supernode by comparing latencies, but exclude
  152. // supernodes that have not responded to direct messages in order to
  153. // try to exclude any that are dead or unreachable.
  154. for(std::vector< SharedPtr<Peer> >::const_iterator sn(_supernodePeers.begin());sn!=_supernodePeers.end();) {
  155. // Skip explicitly avoided relays
  156. for(unsigned int i=0;i<avoidCount;++i) {
  157. if (avoid[i] == (*sn)->address())
  158. goto keep_searching_for_supernodes;
  159. }
  160. // Skip possibly comatose or unreachable relays
  161. lds = (*sn)->lastDirectSend();
  162. ldr = (*sn)->lastDirectReceive();
  163. if ((lds)&&(lds > ldr)&&((lds - ldr) > ZT_PEER_RELAY_CONVERSATION_LATENCY_THRESHOLD))
  164. goto keep_searching_for_supernodes;
  165. if ((*sn)->hasActiveDirectPath(now)) {
  166. l = (*sn)->latency();
  167. if (bestSupernode) {
  168. if ((l)&&(l < bestSupernodeLatency)) {
  169. bestSupernodeLatency = l;
  170. bestSupernode = *sn;
  171. }
  172. } else {
  173. if (l)
  174. bestSupernodeLatency = l;
  175. bestSupernode = *sn;
  176. }
  177. }
  178. keep_searching_for_supernodes:
  179. ++sn;
  180. }
  181. if (bestSupernode) {
  182. bestSupernode->use(now);
  183. return bestSupernode;
  184. } else if (strictAvoid)
  185. return SharedPtr<Peer>();
  186. // If we have nothing from above, just pick one without avoidance criteria.
  187. for(std::vector< SharedPtr<Peer> >::const_iterator sn=_supernodePeers.begin();sn!=_supernodePeers.end();++sn) {
  188. if ((*sn)->hasActiveDirectPath(now)) {
  189. unsigned int l = (*sn)->latency();
  190. if (bestSupernode) {
  191. if ((l)&&(l < bestSupernodeLatency)) {
  192. bestSupernodeLatency = l;
  193. bestSupernode = *sn;
  194. }
  195. } else {
  196. if (l)
  197. bestSupernodeLatency = l;
  198. bestSupernode = *sn;
  199. }
  200. }
  201. }
  202. if (bestSupernode)
  203. bestSupernode->use(now);
  204. return bestSupernode;
  205. }
  206. void Topology::clean()
  207. {
  208. uint64_t now = Utils::now();
  209. Mutex::Lock _l(_activePeers_m);
  210. Mutex::Lock _l2(_supernodes_m);
  211. for(std::map< Address,SharedPtr<Peer> >::iterator p(_activePeers.begin());p!=_activePeers.end();) {
  212. if (((now - p->second->lastUsed()) >= ZT_PEER_IN_MEMORY_EXPIRATION)&&(!_supernodeAddresses.count(p->second->address())))
  213. _activePeers.erase(p++);
  214. else {
  215. p->second->clean(now);
  216. ++p;
  217. }
  218. }
  219. }
  220. bool Topology::authenticateRootTopology(const Dictionary &rt)
  221. {
  222. try {
  223. std::string signer(rt.signingIdentity());
  224. if (!signer.length())
  225. return false;
  226. Identity signerId(signer);
  227. std::map< Address,Identity >::const_iterator authority(ZT_DEFAULTS.rootTopologyAuthorities.find(signerId.address()));
  228. if (authority == ZT_DEFAULTS.rootTopologyAuthorities.end())
  229. return false;
  230. if (signerId != authority->second)
  231. return false;
  232. return rt.verify(authority->second);
  233. } catch ( ... ) {
  234. return false;
  235. }
  236. }
  237. void Topology::_dumpPeers()
  238. {
  239. Buffer<ZT_PEER_WRITE_BUF_SIZE> buf;
  240. std::string pdpath(_r->homePath + ZT_PATH_SEPARATOR_S + "peers.persist");
  241. Mutex::Lock _l(_activePeers_m);
  242. FILE *pd = fopen(pdpath.c_str(),"wb");
  243. if (!pd)
  244. return;
  245. if (fwrite("ZTPD0",5,1,pd) != 1) {
  246. fclose(pd);
  247. Utils::rm(pdpath);
  248. return;
  249. }
  250. for(std::map< Address,SharedPtr<Peer> >::iterator p(_activePeers.begin());p!=_activePeers.end();++p) {
  251. try {
  252. p->second->serialize(buf);
  253. if (buf.size() >= (ZT_PEER_WRITE_BUF_SIZE / 2)) {
  254. if (fwrite(buf.data(),buf.size(),1,pd) != 1) {
  255. fclose(pd);
  256. Utils::rm(pdpath);
  257. buf.burn();
  258. return;
  259. }
  260. buf.clear();
  261. buf.burn();
  262. }
  263. } catch ( ... ) {
  264. fclose(pd);
  265. Utils::rm(pdpath);
  266. buf.burn();
  267. return;
  268. }
  269. }
  270. if (buf.size()) {
  271. if (fwrite(buf.data(),buf.size(),1,pd) != 1) {
  272. fclose(pd);
  273. Utils::rm(pdpath);
  274. buf.burn();
  275. return;
  276. }
  277. buf.burn();
  278. }
  279. fclose(pd);
  280. Utils::lockDownFile(pdpath.c_str(),false);
  281. buf.burn();
  282. }
  283. void Topology::_loadPeers()
  284. {
  285. Buffer<ZT_PEER_WRITE_BUF_SIZE> buf;
  286. std::string pdpath(_r->homePath + ZT_PATH_SEPARATOR_S + "peers.persist");
  287. Mutex::Lock _l(_activePeers_m);
  288. _activePeers.clear();
  289. FILE *pd = fopen(pdpath.c_str(),"rb");
  290. if (!pd)
  291. return;
  292. try {
  293. char magic[5];
  294. if ((fread(magic,5,1,pd) == 1)&&(!memcmp("ZTPD0",magic,5))) {
  295. long rlen = 0;
  296. do {
  297. long rlen = (long)fread(buf.data() + buf.size(),1,ZT_PEER_WRITE_BUF_SIZE - buf.size(),pd);
  298. if (rlen < 0) rlen = 0;
  299. buf.setSize(buf.size() + (unsigned int)rlen);
  300. unsigned int ptr = 0;
  301. while ((ptr < (ZT_PEER_WRITE_BUF_SIZE / 2))&&(ptr < buf.size())) {
  302. SharedPtr<Peer> p(new Peer());
  303. ptr += p->deserialize(buf,ptr);
  304. _activePeers[p->address()] = p;
  305. saveIdentity(p->identity());
  306. }
  307. if (ptr) {
  308. memmove(buf.data(),buf.data() + ptr,buf.size() - ptr);
  309. buf.setSize(buf.size() - ptr);
  310. }
  311. } while (rlen > 0);
  312. }
  313. } catch ( ... ) {
  314. _activePeers.clear();
  315. }
  316. fclose(pd);
  317. Utils::rm(pdpath);
  318. buf.burn();
  319. }
  320. } // namespace ZeroTier