Topology.cpp 8.3 KB

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