Topology.cpp 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297
  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. #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->setPathAddress(*j,true);
  60. p->setLastUsed(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->setLastUsed(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->setLastUsed(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 bestSupernodeLatency = 0xffff;
  123. uint64_t now = Utils::now();
  124. Mutex::Lock _l(_supernodes_m);
  125. if (_supernodePeers.empty())
  126. return bestSupernode;
  127. for(std::vector< SharedPtr<Peer> >::const_iterator sn=_supernodePeers.begin();sn!=_supernodePeers.end();) {
  128. for(unsigned int i=0;i<avoidCount;++i) {
  129. if (avoid[i] == (*sn)->address())
  130. goto skip_and_try_next_supernode;
  131. }
  132. if ((*sn)->hasActiveDirectPath(now)) {
  133. unsigned int l = (*sn)->latency();
  134. if (bestSupernode) {
  135. if ((l)&&(l < bestSupernodeLatency)) {
  136. bestSupernodeLatency = l;
  137. bestSupernode = *sn;
  138. }
  139. } else {
  140. if (l)
  141. bestSupernodeLatency = l;
  142. bestSupernode = *sn;
  143. }
  144. }
  145. skip_and_try_next_supernode:
  146. ++sn;
  147. }
  148. if (bestSupernode) {
  149. bestSupernode->setLastUsed(now);
  150. return bestSupernode;
  151. } else if (strictAvoid)
  152. return SharedPtr<Peer>();
  153. for(std::vector< SharedPtr<Peer> >::const_iterator sn=_supernodePeers.begin();sn!=_supernodePeers.end();++sn) {
  154. if ((*sn)->hasActiveDirectPath(now)) {
  155. unsigned int l = (*sn)->latency();
  156. if (bestSupernode) {
  157. if ((l)&&(l < bestSupernodeLatency)) {
  158. bestSupernodeLatency = l;
  159. bestSupernode = *sn;
  160. }
  161. } else {
  162. if (l)
  163. bestSupernodeLatency = l;
  164. bestSupernode = *sn;
  165. }
  166. }
  167. }
  168. if (bestSupernode)
  169. bestSupernode->setLastUsed(now);
  170. return bestSupernode;
  171. }
  172. void Topology::clean()
  173. {
  174. uint64_t now = Utils::now();
  175. Mutex::Lock _l(_activePeers_m);
  176. Mutex::Lock _l2(_supernodes_m);
  177. for(std::map< Address,SharedPtr<Peer> >::iterator p(_activePeers.begin());p!=_activePeers.end();) {
  178. if (((now - p->second->lastUsed()) >= ZT_PEER_IN_MEMORY_EXPIRATION)&&(!_supernodeAddresses.count(p->second->address())))
  179. _activePeers.erase(p++);
  180. else ++p;
  181. }
  182. }
  183. void Topology::_dumpPeers()
  184. {
  185. Buffer<ZT_PEER_WRITE_BUF_SIZE> buf;
  186. std::string pdpath(_r->homePath + ZT_PATH_SEPARATOR_S + "peers.persist");
  187. Mutex::Lock _l(_activePeers_m);
  188. FILE *pd = fopen(pdpath.c_str(),"wb");
  189. if (!pd)
  190. return;
  191. if (fwrite("ZTPD0",5,1,pd) != 1) {
  192. fclose(pd);
  193. Utils::rm(pdpath);
  194. return;
  195. }
  196. for(std::map< Address,SharedPtr<Peer> >::iterator p(_activePeers.begin());p!=_activePeers.end();++p) {
  197. try {
  198. p->second->serialize(buf);
  199. if (buf.size() >= (ZT_PEER_WRITE_BUF_SIZE / 2)) {
  200. if (fwrite(buf.data(),buf.size(),1,pd) != 1) {
  201. fclose(pd);
  202. Utils::rm(pdpath);
  203. return;
  204. }
  205. buf.clear();
  206. }
  207. } catch ( ... ) {
  208. fclose(pd);
  209. Utils::rm(pdpath);
  210. return;
  211. }
  212. }
  213. if (buf.size()) {
  214. if (fwrite(buf.data(),buf.size(),1,pd) != 1) {
  215. fclose(pd);
  216. Utils::rm(pdpath);
  217. return;
  218. }
  219. }
  220. fclose(pd);
  221. Utils::lockDownFile(pdpath.c_str(),false);
  222. }
  223. void Topology::_loadPeers()
  224. {
  225. Buffer<ZT_PEER_WRITE_BUF_SIZE> buf;
  226. std::string pdpath(_r->homePath + ZT_PATH_SEPARATOR_S + "peers.persist");
  227. Mutex::Lock _l(_activePeers_m);
  228. _activePeers.clear();
  229. FILE *pd = fopen(pdpath.c_str(),"rb");
  230. if (!pd)
  231. return;
  232. try {
  233. char magic[5];
  234. if ((fread(magic,5,1,pd) == 1)&&(!memcmp("ZTPD0",magic,5))) {
  235. long rlen = 0;
  236. do {
  237. long rlen = (long)fread(buf.data() + buf.size(),1,ZT_PEER_WRITE_BUF_SIZE - buf.size(),pd);
  238. if (rlen < 0) rlen = 0;
  239. buf.setSize(buf.size() + (unsigned int)rlen);
  240. unsigned int ptr = 0;
  241. while ((ptr < (ZT_PEER_WRITE_BUF_SIZE / 2))&&(ptr < buf.size())) {
  242. SharedPtr<Peer> p(new Peer());
  243. ptr += p->deserialize(buf,ptr);
  244. _activePeers[p->address()] = p;
  245. saveIdentity(p->identity());
  246. }
  247. if (ptr) {
  248. memmove(buf.data(),buf.data() + ptr,buf.size() - ptr);
  249. buf.setSize(buf.size() - ptr);
  250. }
  251. } while (rlen > 0);
  252. fclose(pd);
  253. } else {
  254. fclose(pd);
  255. Utils::rm(pdpath);
  256. }
  257. } catch ( ... ) {
  258. // Membership cert dump file invalid. We'll re-learn them off the net.
  259. _activePeers.clear();
  260. fclose(pd);
  261. Utils::rm(pdpath);
  262. }
  263. }
  264. } // namespace ZeroTier