Topology.cpp 7.0 KB

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