Topology.cpp 12 KB

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