1
0

Topology.cpp 12 KB

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