Topology.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443
  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::likesMulticastGroup(uint64_t nwid,const MulticastGroup &mg,const Address &addr,uint64_t now)
  184. {
  185. Mutex::Lock _l(_multicastGroupMembers_m);
  186. _multicastGroupMembers[nwid][mg][addr] = now;
  187. }
  188. struct _PickMulticastPropagationPeersPeerPrioritySortOrder
  189. {
  190. inline bool operator()(const SharedPtr<Peer> &p1,const SharedPtr<Peer> &p2) const
  191. {
  192. return (p1->lastUnicastFrame() >= p2->lastUnicastFrame());
  193. }
  194. };
  195. #define _MAX_PEERS_TO_CONSIDER 256
  196. unsigned int Topology::pickMulticastPropagationPeers(uint64_t nwid,const Address &exclude,const void *propagationBloom,unsigned int propagationBloomSize,unsigned int count,const MulticastGroup &mg,SharedPtr<Peer> *peers)
  197. {
  198. SharedPtr<Peer> possiblePeers[_MAX_PEERS_TO_CONSIDER];
  199. unsigned int numPossiblePeers = 0;
  200. if (count > _MAX_PEERS_TO_CONSIDER)
  201. count = _MAX_PEERS_TO_CONSIDER;
  202. Mutex::Lock _l1(_activePeers_m);
  203. Mutex::Lock _l2(_supernodes_m);
  204. // Grab known non-supernode peers in multicast group, excluding 'exclude'
  205. // Also lazily clean up the _multicastGroupMembers structure
  206. {
  207. Mutex::Lock _l3(_multicastGroupMembers_m);
  208. std::map< uint64_t,std::map< MulticastGroup,std::map< Address,uint64_t > > >::iterator mgm(_multicastGroupMembers.find(nwid));
  209. if (mgm != _multicastGroupMembers.end()) {
  210. std::map< MulticastGroup,std::map< Address,uint64_t > >::iterator g(mgm->second.find(mg));
  211. if (g != mgm->second.end()) {
  212. uint64_t now = Utils::now();
  213. for(std::map< Address,uint64_t >::iterator m(g->second.begin());m!=g->second.end();) {
  214. if ((now - m->second) < ZT_MULTICAST_LIKE_EXPIRE) {
  215. std::map< Address,SharedPtr<Peer> >::const_iterator p(_activePeers.find(m->first));
  216. if (p != _activePeers.end()) {
  217. possiblePeers[numPossiblePeers++] = p->second;
  218. if (numPossiblePeers > _MAX_PEERS_TO_CONSIDER)
  219. break;
  220. }
  221. ++m;
  222. } else g->second.erase(m++);
  223. }
  224. if (!g->second.size())
  225. mgm->second.erase(g);
  226. }
  227. }
  228. }
  229. // Sort non-supernode peers in descending order of most recent data
  230. // exchange timestamp. This sorts by implicit social relationships -- who
  231. // you are talking to are the people who get multicasts first.
  232. std::sort(&(possiblePeers[0]),&(possiblePeers[numPossiblePeers]),_PickMulticastPropagationPeersPeerPrioritySortOrder());
  233. // Tack on a supernode peer to the end if we don't have enough regular
  234. // peers, using supernodes to bridge gaps in sparse multicast groups.
  235. if (numPossiblePeers < count) {
  236. SharedPtr<Peer> bestSupernode;
  237. unsigned int bestSupernodeLatency = 0xffff;
  238. for(std::vector< SharedPtr<Peer> >::const_iterator sn(_supernodePeers.begin());sn!=_supernodePeers.end();++sn) {
  239. if (((*sn)->latency())&&((*sn)->latency() < bestSupernodeLatency)) {
  240. bestSupernodeLatency = (*sn)->latency();
  241. bestSupernode = *sn;
  242. }
  243. }
  244. if (bestSupernode)
  245. possiblePeers[numPossiblePeers++] = bestSupernode;
  246. }
  247. unsigned int num = 0;
  248. // First, try to pick peers not in the propgation bloom filter
  249. for(unsigned int i=0;i<numPossiblePeers;++i) {
  250. if (!Utils::bloomContains(propagationBloom,propagationBloomSize,possiblePeers[i]->address().sum())) {
  251. peers[num++] = possiblePeers[i];
  252. if (num >= count)
  253. return num;
  254. }
  255. }
  256. // Next, pick other peers until full (without duplicates)
  257. for(unsigned int i=0;i<numPossiblePeers;++i) {
  258. for(unsigned int j=0;j<num;++j) {
  259. if (peers[j] == possiblePeers[i])
  260. goto check_next_peer;
  261. }
  262. peers[num++] = possiblePeers[i];
  263. if (num >= count)
  264. return num;
  265. check_next_peer:
  266. continue;
  267. }
  268. return num;
  269. }
  270. void Topology::main()
  271. throw()
  272. {
  273. for(;;) {
  274. _peerDeepVerifyJobs_m.lock();
  275. if (_peerDeepVerifyJobs.empty()) {
  276. _peerDeepVerifyJobs_m.unlock();
  277. _peerDeepVerifyJobs_c.wait();
  278. continue;
  279. }
  280. _PeerDeepVerifyJob job(_peerDeepVerifyJobs.front());
  281. _peerDeepVerifyJobs.pop_front();
  282. unsigned long queueRemaining = _peerDeepVerifyJobs.size();
  283. _peerDeepVerifyJobs_m.unlock();
  284. switch(job.type) {
  285. case _PeerDeepVerifyJob::VERIFY_PEER:
  286. /* TODO: We should really verify peers every time completely if this
  287. * is a supernode, perhaps deferring the expensive part for new
  288. * addresses. An attempt at claim jumping should also trigger a
  289. * short duration ban of the originating IP address in most cases,
  290. * since this means either malicious intent or broken software. */
  291. TRACE("verifying peer: %s",job.candidate->identity().address().toString().c_str());
  292. if ((job.candidate->identity())&&(!job.candidate->identity().address().isReserved())&&(job.candidate->identity().locallyValidate(false))) {
  293. // Peer passes sniff test, so check to see if we've already got
  294. // one with the same address.
  295. SharedPtr<Peer> existingPeer(getPeer(job.candidate->identity().address()));
  296. if (existingPeer) {
  297. if (existingPeer->identity() == job.candidate->identity()) {
  298. // It's an *exact* duplicate, so return the existing peer
  299. if (job.callback)
  300. job.callback(job.arg,existingPeer,PEER_VERIFY_ACCEPTED_ALREADY_HAVE);
  301. } else if (queueRemaining > 3) {
  302. /* Prevents a CPU hog DOS attack, while allowing a very unlikely kind of
  303. * DOS attack where someone knows someone else's address prior to their
  304. * registering it and claim-jumps them and then floods with bad identities
  305. * to hold their claim. Of the two, the latter would be infeasable
  306. * without already having cracked the target's machine in which case
  307. * the attacker has their private key anyway and can really steal their
  308. * identity. So why bother.*/
  309. TRACE("%s is duplicate, load too high, old won",job.candidate->identity().address().toString().c_str());
  310. if (job.callback)
  311. job.callback(job.arg,job.candidate,PEER_VERIFY_REJECTED_DUPLICATE_TRIAGED);
  312. } else {
  313. // It's different so deeply validate it first, then the
  314. // existing claimant, and toss the imposter. If both verify, the
  315. // one we already have wins.
  316. if (!job.candidate->identity().locallyValidate(true)) {
  317. LOG("Topology: IMPOSTER %s rejected",job.candidate->identity().address().toString().c_str());
  318. if (job.callback)
  319. job.callback(job.arg,job.candidate,PEER_VERIFY_REJECTED_INVALID_IDENTITY);
  320. } else if (!existingPeer->identity().locallyValidate(true)) {
  321. LOG("Topology: previous IMPOSTER %s displaced by valid identity!",job.candidate->identity().address().toString().c_str());
  322. _reallyAddPeer(job.candidate);
  323. if (job.callback)
  324. job.callback(job.arg,job.candidate,PEER_VERIFY_ACCEPTED_DISPLACED_INVALID_ADDRESS);
  325. } else {
  326. LOG("Topology: tie between apparently valid claims on %s, oldest won",job.candidate->identity().address().toString().c_str());
  327. if (job.callback)
  328. job.callback(job.arg,job.candidate,PEER_VERIFY_REJECTED_DUPLICATE);
  329. }
  330. }
  331. } else {
  332. TRACE("%s accepted as new",job.candidate->identity().address().toString().c_str());
  333. _reallyAddPeer(job.candidate);
  334. if (job.callback)
  335. job.callback(job.arg,job.candidate,PEER_VERIFY_ACCEPTED_NEW);
  336. }
  337. } else {
  338. TRACE("%s rejected, identity failed initial checks",job.candidate->identity().address().toString().c_str());
  339. if (job.callback)
  340. job.callback(job.arg,job.candidate,PEER_VERIFY_REJECTED_INVALID_IDENTITY);
  341. }
  342. break;
  343. case _PeerDeepVerifyJob::CLEAN_CACHE:
  344. TRACE("cleaning caches and flushing modified peers to disk...");
  345. {
  346. Mutex::Lock _l(_activePeers_m);
  347. for(std::map< Address,SharedPtr<Peer> >::iterator p(_activePeers.begin());p!=_activePeers.end();++p) {
  348. if (p->second->getAndResetDirty()) {
  349. try {
  350. Buffer<ZT_PEER_MAX_SERIALIZED_LENGTH> b;
  351. p->second->serialize(b);
  352. b.zeroUnused();
  353. _dbm_m.lock();
  354. if (KISSDB_put(&_dbm,p->second->identity().address().data(),b.data())) {
  355. TRACE("error writing %s to peer.db",p->second->identity().address().toString().c_str());
  356. }
  357. _dbm_m.unlock();
  358. } catch ( ... ) {
  359. TRACE("unexpected exception flushing %s to peer.db",p->second->identity().address().toString().c_str());
  360. }
  361. }
  362. }
  363. }
  364. {
  365. Mutex::Lock _l(_multicastGroupMembers_m);
  366. for(std::map< uint64_t,std::map< MulticastGroup,std::map< Address,uint64_t > > >::iterator mgm(_multicastGroupMembers.begin());mgm!=_multicastGroupMembers.end();) {
  367. if (_r->nc->hasNetwork(mgm->first))
  368. ++mgm;
  369. else _multicastGroupMembers.erase(mgm++);
  370. }
  371. }
  372. break;
  373. case _PeerDeepVerifyJob::EXIT_THREAD:
  374. TRACE("thread terminating...");
  375. return;
  376. }
  377. }
  378. }
  379. void Topology::_reallyAddPeer(const SharedPtr<Peer> &p)
  380. {
  381. {
  382. Mutex::Lock _l(_activePeers_m);
  383. _activePeers[p->identity().address()] = p;
  384. }
  385. try {
  386. Buffer<ZT_PEER_MAX_SERIALIZED_LENGTH> b;
  387. p->serialize(b);
  388. b.zeroUnused();
  389. _dbm_m.lock();
  390. if (KISSDB_put(&_dbm,p->identity().address().data(),b.data())) {
  391. TRACE("error writing %s to peerdb",p->address().toString().c_str());
  392. } else p->getAndResetDirty();
  393. _dbm_m.unlock();
  394. } catch ( ... ) {
  395. TRACE("unexpected exception flushing to peerdb");
  396. }
  397. }
  398. } // namespace ZeroTier