Topology.cpp 12 KB

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