Topology.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354
  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 131072
  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. _thread = Thread::start(this);
  51. }
  52. Topology::~Topology()
  53. {
  54. {
  55. Mutex::Lock _l(_peerDeepVerifyJobs_m);
  56. _peerDeepVerifyJobs.push_back(_PeerDeepVerifyJob());
  57. _peerDeepVerifyJobs.back().type = _PeerDeepVerifyJob::CLEAN_CACHE;
  58. _peerDeepVerifyJobs.push_back(_PeerDeepVerifyJob());
  59. _peerDeepVerifyJobs.back().type = _PeerDeepVerifyJob::EXIT_THREAD;
  60. }
  61. _peerDeepVerifyJobs_c.signal();
  62. Thread::join(_thread);
  63. KISSDB_close(&_dbm);
  64. }
  65. void Topology::setSupernodes(const std::map< Identity,std::vector<InetAddress> > &sn)
  66. {
  67. Mutex::Lock _l(_supernodes_m);
  68. _supernodes = sn;
  69. _supernodeAddresses.clear();
  70. _supernodePeers.clear();
  71. for(std::map< Identity,std::vector<InetAddress> >::const_iterator i(sn.begin());i!=sn.end();++i) {
  72. if (i->first != _r->identity) {
  73. SharedPtr<Peer> p(getPeer(i->first.address()));
  74. if ((!p)||(p->identity() != i->first)) {
  75. p = SharedPtr<Peer>(new Peer(_r->identity,i->first));
  76. _reallyAddPeer(p);
  77. }
  78. for(std::vector<InetAddress>::const_iterator j(i->second.begin());j!=i->second.end();++j)
  79. p->setPathAddress(*j,true);
  80. _supernodePeers.push_back(p);
  81. }
  82. _supernodeAddresses.insert(i->first.address());
  83. }
  84. _amSupernode = (_supernodes.find(_r->identity) != _supernodes.end());
  85. }
  86. void Topology::addPeer(const SharedPtr<Peer> &candidate,void (*callback)(void *,const SharedPtr<Peer> &,Topology::PeerVerifyResult),void *arg)
  87. {
  88. if (candidate->address() != _r->identity.address()) {
  89. Mutex::Lock _l(_peerDeepVerifyJobs_m);
  90. _peerDeepVerifyJobs.push_back(_PeerDeepVerifyJob());
  91. _PeerDeepVerifyJob &job = _peerDeepVerifyJobs.back();
  92. job.callback = callback;
  93. job.arg = arg;
  94. job.candidate = candidate;
  95. job.type = _PeerDeepVerifyJob::VERIFY_PEER;
  96. _peerDeepVerifyJobs_c.signal();
  97. } else {
  98. TRACE("BUG: addPeer() caught and ignored attempt to add peer for self");
  99. if (callback)
  100. callback(arg,candidate,PEER_VERIFY_REJECTED_DUPLICATE_TRIAGED);
  101. }
  102. }
  103. SharedPtr<Peer> Topology::getPeer(const Address &zta)
  104. {
  105. if (zta == _r->identity.address()) {
  106. TRACE("BUG: ignored attempt to getPeer() for self, returned NULL");
  107. return SharedPtr<Peer>();
  108. }
  109. {
  110. Mutex::Lock _l(_activePeers_m);
  111. std::map< Address,SharedPtr<Peer> >::const_iterator ap(_activePeers.find(zta));
  112. if ((ap != _activePeers.end())&&(ap->second))
  113. return ap->second;
  114. }
  115. unsigned char ztatmp[ZT_ADDRESS_LENGTH];
  116. zta.copyTo(ztatmp,ZT_ADDRESS_LENGTH);
  117. Buffer<ZT_KISSDB_VALUE_SIZE> b(ZT_KISSDB_VALUE_SIZE);
  118. _dbm_m.lock();
  119. if (!KISSDB_get(&_dbm,ztatmp,b.data())) {
  120. _dbm_m.unlock();
  121. SharedPtr<Peer> p(new Peer());
  122. try {
  123. p->deserialize(b,0);
  124. Mutex::Lock _l(_activePeers_m);
  125. _activePeers[zta] = p;
  126. return p;
  127. } catch ( ... ) {
  128. TRACE("unexpected exception deserializing peer %s from peerdb",zta.toString().c_str());
  129. return SharedPtr<Peer>();
  130. }
  131. } else _dbm_m.unlock();
  132. return SharedPtr<Peer>();
  133. }
  134. SharedPtr<Peer> Topology::getBestSupernode(const Address *avoid,unsigned int avoidCount,bool strictAvoid) const
  135. {
  136. SharedPtr<Peer> bestSupernode;
  137. unsigned int bestSupernodeLatency = 0xffff;
  138. uint64_t now = Utils::now();
  139. Mutex::Lock _l(_supernodes_m);
  140. if (_supernodePeers.empty())
  141. return bestSupernode;
  142. for(std::vector< SharedPtr<Peer> >::const_iterator sn=_supernodePeers.begin();sn!=_supernodePeers.end();) {
  143. for(unsigned int i=0;i<avoidCount;++i) {
  144. if (avoid[i] == (*sn)->address())
  145. goto skip_and_try_next_supernode;
  146. }
  147. if ((*sn)->hasActiveDirectPath(now)) {
  148. unsigned int l = (*sn)->latency();
  149. if (bestSupernode) {
  150. if ((l)&&(l < bestSupernodeLatency)) {
  151. bestSupernodeLatency = l;
  152. bestSupernode = *sn;
  153. }
  154. } else {
  155. if (l)
  156. bestSupernodeLatency = l;
  157. bestSupernode = *sn;
  158. }
  159. }
  160. skip_and_try_next_supernode:
  161. ++sn;
  162. }
  163. if ((bestSupernode)||(strictAvoid))
  164. return bestSupernode;
  165. for(std::vector< SharedPtr<Peer> >::const_iterator sn=_supernodePeers.begin();sn!=_supernodePeers.end();++sn) {
  166. if ((*sn)->hasActiveDirectPath(now)) {
  167. unsigned int l = (*sn)->latency();
  168. if (bestSupernode) {
  169. if ((l)&&(l < bestSupernodeLatency)) {
  170. bestSupernodeLatency = l;
  171. bestSupernode = *sn;
  172. }
  173. } else {
  174. if (l)
  175. bestSupernodeLatency = l;
  176. bestSupernode = *sn;
  177. }
  178. }
  179. }
  180. if (bestSupernode)
  181. return bestSupernode;
  182. return _supernodePeers[_r->prng->next32() % _supernodePeers.size()];
  183. }
  184. void Topology::clean()
  185. {
  186. {
  187. Mutex::Lock _l(_peerDeepVerifyJobs_m);
  188. _peerDeepVerifyJobs.push_back(_PeerDeepVerifyJob());
  189. _peerDeepVerifyJobs.back().type = _PeerDeepVerifyJob::CLEAN_CACHE;
  190. }
  191. _peerDeepVerifyJobs_c.signal();
  192. }
  193. void Topology::threadMain()
  194. throw()
  195. {
  196. for(;;) {
  197. _peerDeepVerifyJobs_m.lock();
  198. if (_peerDeepVerifyJobs.empty()) {
  199. _peerDeepVerifyJobs_m.unlock();
  200. _peerDeepVerifyJobs_c.wait();
  201. continue;
  202. }
  203. _PeerDeepVerifyJob job(_peerDeepVerifyJobs.front());
  204. _peerDeepVerifyJobs.pop_front();
  205. unsigned long queueRemaining = (unsigned long)_peerDeepVerifyJobs.size();
  206. _peerDeepVerifyJobs_m.unlock();
  207. switch(job.type) {
  208. case _PeerDeepVerifyJob::VERIFY_PEER:
  209. /* TODO: We should really verify peers every time completely if this
  210. * is a supernode, perhaps deferring the expensive part for new
  211. * addresses. An attempt at claim jumping should also trigger a
  212. * short duration ban of the originating IP address in most cases,
  213. * since this means either malicious intent or broken software. */
  214. TRACE("verifying peer: %s",job.candidate->identity().address().toString().c_str());
  215. if ((job.candidate->identity())&&(!job.candidate->identity().address().isReserved())&&(job.candidate->identity().locallyValidate(false))) {
  216. // Peer passes sniff test, so check to see if we've already got
  217. // one with the same address.
  218. SharedPtr<Peer> existingPeer(getPeer(job.candidate->identity().address()));
  219. if (existingPeer) {
  220. if (existingPeer->identity() == job.candidate->identity()) {
  221. // It's an *exact* duplicate, so return the existing peer
  222. if (job.callback)
  223. job.callback(job.arg,existingPeer,PEER_VERIFY_ACCEPTED_ALREADY_HAVE);
  224. } else if (queueRemaining > 3) {
  225. /* Prevents a CPU hog DOS attack, while allowing a very unlikely kind of
  226. * DOS attack where someone knows someone else's address prior to their
  227. * registering it and claim-jumps them and then floods with bad identities
  228. * to hold their claim. Of the two, the latter would be infeasable
  229. * without already having cracked the target's machine in which case
  230. * the attacker has their private key anyway and can really steal their
  231. * identity. So why bother.*/
  232. TRACE("%s is duplicate, load too high, old won",job.candidate->identity().address().toString().c_str());
  233. if (job.callback)
  234. job.callback(job.arg,job.candidate,PEER_VERIFY_REJECTED_DUPLICATE_TRIAGED);
  235. } else {
  236. // It's different so deeply validate it first, then the
  237. // existing claimant, and toss the imposter. If both verify, the
  238. // one we already have wins.
  239. if (!job.candidate->identity().locallyValidate(true)) {
  240. LOG("Topology: IMPOSTER %s rejected",job.candidate->identity().address().toString().c_str());
  241. if (job.callback)
  242. job.callback(job.arg,job.candidate,PEER_VERIFY_REJECTED_INVALID_IDENTITY);
  243. } else if (!existingPeer->identity().locallyValidate(true)) {
  244. LOG("Topology: previous IMPOSTER %s displaced by valid identity!",job.candidate->identity().address().toString().c_str());
  245. _reallyAddPeer(job.candidate);
  246. if (job.callback)
  247. job.callback(job.arg,job.candidate,PEER_VERIFY_ACCEPTED_DISPLACED_INVALID_ADDRESS);
  248. } else {
  249. LOG("Topology: tie between apparently valid claims on %s, oldest won",job.candidate->identity().address().toString().c_str());
  250. if (job.callback)
  251. job.callback(job.arg,job.candidate,PEER_VERIFY_REJECTED_DUPLICATE);
  252. }
  253. }
  254. } else {
  255. TRACE("%s accepted as new",job.candidate->identity().address().toString().c_str());
  256. _reallyAddPeer(job.candidate);
  257. if (job.callback)
  258. job.callback(job.arg,job.candidate,PEER_VERIFY_ACCEPTED_NEW);
  259. }
  260. } else {
  261. TRACE("%s rejected, identity failed initial checks",job.candidate->identity().address().toString().c_str());
  262. if (job.callback)
  263. job.callback(job.arg,job.candidate,PEER_VERIFY_REJECTED_INVALID_IDENTITY);
  264. }
  265. break;
  266. case _PeerDeepVerifyJob::CLEAN_CACHE:
  267. TRACE("cleaning caches and flushing modified peers to disk...");
  268. {
  269. Mutex::Lock _l(_activePeers_m);
  270. for(std::map< Address,SharedPtr<Peer> >::iterator p(_activePeers.begin());p!=_activePeers.end();++p) {
  271. if (p->second->getAndResetDirty()) {
  272. try {
  273. uint64_t atmp[ZT_ADDRESS_LENGTH];
  274. p->second->identity().address().copyTo(atmp,ZT_ADDRESS_LENGTH);
  275. Buffer<ZT_PEER_MAX_SERIALIZED_LENGTH> b;
  276. p->second->serialize(b);
  277. b.zeroUnused();
  278. _dbm_m.lock();
  279. if (KISSDB_put(&_dbm,atmp,b.data())) {
  280. TRACE("error writing %s to peer.db",p->second->identity().address().toString().c_str());
  281. }
  282. _dbm_m.unlock();
  283. } catch ( ... ) {
  284. TRACE("unexpected exception flushing %s to peer.db",p->second->identity().address().toString().c_str());
  285. }
  286. }
  287. }
  288. }
  289. break;
  290. case _PeerDeepVerifyJob::EXIT_THREAD:
  291. TRACE("thread terminating...");
  292. return;
  293. }
  294. }
  295. }
  296. void Topology::_reallyAddPeer(const SharedPtr<Peer> &p)
  297. {
  298. {
  299. Mutex::Lock _l(_activePeers_m);
  300. _activePeers[p->identity().address()] = p;
  301. }
  302. try {
  303. uint64_t atmp[ZT_ADDRESS_LENGTH];
  304. p->address().copyTo(atmp,ZT_ADDRESS_LENGTH);
  305. Buffer<ZT_PEER_MAX_SERIALIZED_LENGTH> b;
  306. p->serialize(b);
  307. b.zeroUnused();
  308. _dbm_m.lock();
  309. if (KISSDB_put(&_dbm,atmp,b.data())) {
  310. TRACE("error writing %s to peerdb",p->address().toString().c_str());
  311. } else p->getAndResetDirty();
  312. _dbm_m.unlock();
  313. } catch ( ... ) {
  314. TRACE("unexpected exception flushing to peerdb");
  315. }
  316. }
  317. } // namespace ZeroTier