Topology.cpp 8.1 KB

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