Topology.cpp 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239
  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. namespace ZeroTier {
  32. #define ZT_KISSDB_HASH_TABLE_SIZE 32768
  33. #define ZT_KISSDB_KEY_SIZE ZT_ADDRESS_LENGTH
  34. #define ZT_KISSDB_VALUE_SIZE ZT_PEER_MAX_SERIALIZED_LENGTH
  35. Topology::Topology(const RuntimeEnvironment *renv,const char *dbpath)
  36. throw(std::runtime_error) :
  37. _r(renv),
  38. _amSupernode(false)
  39. {
  40. if (KISSDB_open(&_dbm,dbpath,KISSDB_OPEN_MODE_RWCREAT,ZT_KISSDB_HASH_TABLE_SIZE,ZT_KISSDB_KEY_SIZE,ZT_KISSDB_VALUE_SIZE)) {
  41. if (KISSDB_open(&_dbm,dbpath,KISSDB_OPEN_MODE_RWREPLACE,ZT_KISSDB_HASH_TABLE_SIZE,ZT_KISSDB_KEY_SIZE,ZT_KISSDB_VALUE_SIZE))
  42. throw std::runtime_error("unable to open peer database (rw/create)");
  43. }
  44. if ((_dbm.key_size != ZT_KISSDB_KEY_SIZE)||(_dbm.value_size != ZT_KISSDB_VALUE_SIZE)||(_dbm.hash_table_size != ZT_KISSDB_HASH_TABLE_SIZE)) {
  45. KISSDB_close(&_dbm);
  46. if (KISSDB_open(&_dbm,dbpath,KISSDB_OPEN_MODE_RWREPLACE,ZT_KISSDB_HASH_TABLE_SIZE,ZT_KISSDB_KEY_SIZE,ZT_KISSDB_VALUE_SIZE))
  47. throw std::runtime_error("unable to open peer database (recreate)");
  48. }
  49. Utils::lockDownFile(dbpath,false); // node.db caches secrets
  50. }
  51. Topology::~Topology()
  52. {
  53. // Flush last changes to disk
  54. clean();
  55. }
  56. void Topology::setSupernodes(const std::map< Identity,std::vector<InetAddress> > &sn)
  57. {
  58. Mutex::Lock _l(_supernodes_m);
  59. _supernodes = sn;
  60. _supernodeAddresses.clear();
  61. _supernodePeers.clear();
  62. for(std::map< Identity,std::vector<InetAddress> >::const_iterator i(sn.begin());i!=sn.end();++i) {
  63. if (i->first != _r->identity) {
  64. SharedPtr<Peer> p(getPeer(i->first.address()));
  65. if (!p)
  66. p = addPeer(SharedPtr<Peer>(new Peer(_r->identity,i->first)));
  67. for(std::vector<InetAddress>::const_iterator j(i->second.begin());j!=i->second.end();++j)
  68. p->setPathAddress(*j,true);
  69. _supernodePeers.push_back(p);
  70. }
  71. _supernodeAddresses.insert(i->first.address());
  72. }
  73. _amSupernode = (_supernodes.find(_r->identity) != _supernodes.end());
  74. }
  75. SharedPtr<Peer> Topology::addPeer(const SharedPtr<Peer> &peer)
  76. {
  77. if (peer->address() == _r->identity.address()) {
  78. TRACE("BUG: addNewPeer() caught and ignored attempt to add peer for self");
  79. throw std::logic_error("cannot add peer for self");
  80. }
  81. SharedPtr<Peer> actualPeer;
  82. {
  83. Mutex::Lock _l(_activePeers_m);
  84. actualPeer = _activePeers.insert(std::pair< Address,SharedPtr<Peer> >(peer->address(),peer)).first->second;
  85. }
  86. uint64_t atmp[ZT_ADDRESS_LENGTH];
  87. actualPeer->address().copyTo(atmp,ZT_ADDRESS_LENGTH);
  88. Buffer<ZT_PEER_MAX_SERIALIZED_LENGTH> b;
  89. actualPeer->serialize(b);
  90. b.zeroUnused();
  91. _dbm_m.lock();
  92. if (KISSDB_put(&_dbm,atmp,b.data())) {
  93. TRACE("error writing %s to peerdb",actualPeer->address().toString().c_str());
  94. } else actualPeer->getAndResetDirty();
  95. _dbm_m.unlock();
  96. return actualPeer;
  97. }
  98. SharedPtr<Peer> Topology::getPeer(const Address &zta)
  99. {
  100. if (zta == _r->identity.address()) {
  101. TRACE("BUG: ignored attempt to getPeer() for self, returned NULL");
  102. return SharedPtr<Peer>();
  103. }
  104. {
  105. Mutex::Lock _l(_activePeers_m);
  106. std::map< Address,SharedPtr<Peer> >::const_iterator ap(_activePeers.find(zta));
  107. if ((ap != _activePeers.end())&&(ap->second))
  108. return ap->second;
  109. }
  110. unsigned char ztatmp[ZT_ADDRESS_LENGTH];
  111. zta.copyTo(ztatmp,ZT_ADDRESS_LENGTH);
  112. Buffer<ZT_KISSDB_VALUE_SIZE> b(ZT_KISSDB_VALUE_SIZE);
  113. _dbm_m.lock();
  114. if (!KISSDB_get(&_dbm,ztatmp,b.data())) {
  115. _dbm_m.unlock();
  116. SharedPtr<Peer> p(new Peer());
  117. try {
  118. p->deserialize(b,0);
  119. Mutex::Lock _l(_activePeers_m);
  120. _activePeers[zta] = p;
  121. return p;
  122. } catch ( ... ) {
  123. TRACE("unexpected exception deserializing peer %s from peerdb",zta.toString().c_str());
  124. return SharedPtr<Peer>();
  125. }
  126. } else _dbm_m.unlock();
  127. return SharedPtr<Peer>();
  128. }
  129. SharedPtr<Peer> Topology::getBestSupernode(const Address *avoid,unsigned int avoidCount,bool strictAvoid) const
  130. {
  131. SharedPtr<Peer> bestSupernode;
  132. unsigned int bestSupernodeLatency = 0xffff;
  133. uint64_t now = Utils::now();
  134. Mutex::Lock _l(_supernodes_m);
  135. if (_supernodePeers.empty())
  136. return bestSupernode;
  137. for(std::vector< SharedPtr<Peer> >::const_iterator sn=_supernodePeers.begin();sn!=_supernodePeers.end();) {
  138. for(unsigned int i=0;i<avoidCount;++i) {
  139. if (avoid[i] == (*sn)->address())
  140. goto skip_and_try_next_supernode;
  141. }
  142. if ((*sn)->hasActiveDirectPath(now)) {
  143. unsigned int l = (*sn)->latency();
  144. if (bestSupernode) {
  145. if ((l)&&(l < bestSupernodeLatency)) {
  146. bestSupernodeLatency = l;
  147. bestSupernode = *sn;
  148. }
  149. } else {
  150. if (l)
  151. bestSupernodeLatency = l;
  152. bestSupernode = *sn;
  153. }
  154. }
  155. skip_and_try_next_supernode:
  156. ++sn;
  157. }
  158. if ((bestSupernode)||(strictAvoid))
  159. return bestSupernode;
  160. for(std::vector< SharedPtr<Peer> >::const_iterator sn=_supernodePeers.begin();sn!=_supernodePeers.end();++sn) {
  161. if ((*sn)->hasActiveDirectPath(now)) {
  162. unsigned int l = (*sn)->latency();
  163. if (bestSupernode) {
  164. if ((l)&&(l < bestSupernodeLatency)) {
  165. bestSupernodeLatency = l;
  166. bestSupernode = *sn;
  167. }
  168. } else {
  169. if (l)
  170. bestSupernodeLatency = l;
  171. bestSupernode = *sn;
  172. }
  173. }
  174. }
  175. if (bestSupernode)
  176. return bestSupernode;
  177. return _supernodePeers[_r->prng->next32() % _supernodePeers.size()];
  178. }
  179. void Topology::clean()
  180. {
  181. TRACE("cleaning caches and flushing modified peers to disk...");
  182. Mutex::Lock _l(_activePeers_m);
  183. for(std::map< Address,SharedPtr<Peer> >::iterator p(_activePeers.begin());p!=_activePeers.end();++p) {
  184. if (p->second->getAndResetDirty()) {
  185. try {
  186. uint64_t atmp[ZT_ADDRESS_LENGTH];
  187. p->second->identity().address().copyTo(atmp,ZT_ADDRESS_LENGTH);
  188. Buffer<ZT_PEER_MAX_SERIALIZED_LENGTH> b;
  189. p->second->serialize(b);
  190. b.zeroUnused();
  191. _dbm_m.lock();
  192. if (KISSDB_put(&_dbm,atmp,b.data())) {
  193. TRACE("error writing %s to peer.db",p->second->identity().address().toString().c_str());
  194. }
  195. _dbm_m.unlock();
  196. } catch ( ... ) {
  197. TRACE("unexpected exception flushing %s to peer.db",p->second->identity().address().toString().c_str());
  198. }
  199. }
  200. }
  201. }
  202. } // namespace ZeroTier