Topology.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349
  1. /*
  2. * ZeroTier One - Network Virtualization Everywhere
  3. * Copyright (C) 2011-2015 ZeroTier, Inc.
  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 "Constants.hpp"
  28. #include "Topology.hpp"
  29. #include "RuntimeEnvironment.hpp"
  30. #include "Node.hpp"
  31. #include "Buffer.hpp"
  32. namespace ZeroTier {
  33. // Default World
  34. #define ZT_DEFAULT_WORLD_LENGTH 494
  35. static const unsigned char ZT_DEFAULT_WORLD[ZT_DEFAULT_WORLD_LENGTH] = {0x01,0x00,0x00,0x00,0x00,0x08,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,0x6c,0xd1,0xd9,0x42,0xa9,0x0d,0x1b,0xd1,0xd2,0xdc,0xa3,0xea,0x84,0xef,0x7d,0x85,0xaf,0xe6,0x61,0x1f,0xb4,0x3f,0xf0,0xb7,0x41,0x26,0xd9,0x0a,0x6e,0x00,0x01,0x04,0x80,0xc7,0xc5,0xd9,0x27,0x09};
  36. Topology::Topology(const RuntimeEnvironment *renv) :
  37. RR(renv),
  38. _amRoot(false)
  39. {
  40. std::string alls(RR->node->dataStoreGet("peers.save"));
  41. const uint8_t *all = reinterpret_cast<const uint8_t *>(alls.data());
  42. RR->node->dataStoreDelete("peers.save");
  43. unsigned int ptr = 0;
  44. while ((ptr + 4) < alls.size()) {
  45. try {
  46. const unsigned int reclen = ( // each Peer serialized record is prefixed by a record length
  47. ((((unsigned int)all[ptr]) & 0xff) << 24) |
  48. ((((unsigned int)all[ptr + 1]) & 0xff) << 16) |
  49. ((((unsigned int)all[ptr + 2]) & 0xff) << 8) |
  50. (((unsigned int)all[ptr + 3]) & 0xff)
  51. );
  52. unsigned int pos = 0;
  53. SharedPtr<Peer> p(Peer::deserializeNew(RR->identity,Buffer<ZT_PEER_SUGGESTED_SERIALIZATION_BUFFER_SIZE>(all + ptr,reclen + 4),pos));
  54. ptr += pos;
  55. if (!p)
  56. break; // stop if invalid records
  57. if (p->address() != RR->identity.address())
  58. _peers[p->address()] = p;
  59. } catch ( ... ) {
  60. break; // stop if invalid records
  61. }
  62. }
  63. clean(RR->node->now());
  64. std::string dsWorld(RR->node->dataStoreGet("world"));
  65. World cachedWorld;
  66. try {
  67. Buffer<ZT_WORLD_MAX_SERIALIZED_LENGTH> dswtmp(dsWorld.data(),dsWorld.length());
  68. cachedWorld.deserialize(dswtmp,0);
  69. } catch ( ... ) {
  70. cachedWorld = World(); // clear if cached world is invalid
  71. }
  72. World defaultWorld;
  73. {
  74. Buffer<ZT_DEFAULT_WORLD_LENGTH> wtmp(ZT_DEFAULT_WORLD,ZT_DEFAULT_WORLD_LENGTH);
  75. defaultWorld.deserialize(wtmp,0); // throws on error, which would indicate a bad static variable up top
  76. }
  77. if (cachedWorld.shouldBeReplacedBy(defaultWorld,false)) {
  78. _setWorld(defaultWorld);
  79. if (dsWorld.length() > 0)
  80. RR->node->dataStoreDelete("world");
  81. } else _setWorld(cachedWorld);
  82. }
  83. Topology::~Topology()
  84. {
  85. Buffer<ZT_PEER_SUGGESTED_SERIALIZATION_BUFFER_SIZE> pbuf;
  86. std::string all;
  87. Address *a = (Address *)0;
  88. SharedPtr<Peer> *p = (SharedPtr<Peer> *)0;
  89. Hashtable< Address,SharedPtr<Peer> >::Iterator i(_peers);
  90. while (i.next(a,p)) {
  91. if (std::find(_rootAddresses.begin(),_rootAddresses.end(),*a) == _rootAddresses.end()) {
  92. pbuf.clear();
  93. try {
  94. (*p)->serialize(pbuf);
  95. try {
  96. all.append((const char *)pbuf.data(),pbuf.size());
  97. } catch ( ... ) {
  98. return; // out of memory? just skip
  99. }
  100. } catch ( ... ) {} // peer too big? shouldn't happen, but it so skip
  101. }
  102. }
  103. RR->node->dataStorePut("peers.save",all,true);
  104. }
  105. SharedPtr<Peer> Topology::addPeer(const SharedPtr<Peer> &peer)
  106. {
  107. if (peer->address() == RR->identity.address()) {
  108. TRACE("BUG: addNewPeer() caught and ignored attempt to add peer for self");
  109. throw std::logic_error("cannot add peer for self");
  110. }
  111. const uint64_t now = RR->node->now();
  112. Mutex::Lock _l(_lock);
  113. SharedPtr<Peer> &p = _peers.set(peer->address(),peer);
  114. p->use(now);
  115. saveIdentity(p->identity());
  116. return p;
  117. }
  118. SharedPtr<Peer> Topology::getPeer(const Address &zta)
  119. {
  120. if (zta == RR->identity.address()) {
  121. TRACE("BUG: ignored attempt to getPeer() for self, returned NULL");
  122. return SharedPtr<Peer>();
  123. }
  124. const uint64_t now = RR->node->now();
  125. Mutex::Lock _l(_lock);
  126. SharedPtr<Peer> &ap = _peers[zta];
  127. if (ap) {
  128. ap->use(now);
  129. return ap;
  130. }
  131. Identity id(_getIdentity(zta));
  132. if (id) {
  133. try {
  134. ap = SharedPtr<Peer>(new Peer(RR->identity,id));
  135. ap->use(now);
  136. return ap;
  137. } catch ( ... ) {} // invalid identity?
  138. }
  139. _peers.erase(zta);
  140. return SharedPtr<Peer>();
  141. }
  142. Identity Topology::getIdentity(const Address &zta)
  143. {
  144. {
  145. Mutex::Lock _l(_lock);
  146. SharedPtr<Peer> &ap = _peers[zta];
  147. if (ap)
  148. return ap->identity();
  149. }
  150. return _getIdentity(zta);
  151. }
  152. void Topology::saveIdentity(const Identity &id)
  153. {
  154. if (id) {
  155. char p[128];
  156. Utils::snprintf(p,sizeof(p),"iddb.d/%.10llx",(unsigned long long)id.address().toInt());
  157. RR->node->dataStorePut(p,id.toString(false),false);
  158. }
  159. }
  160. SharedPtr<Peer> Topology::getBestRoot(const Address *avoid,unsigned int avoidCount,bool strictAvoid)
  161. {
  162. SharedPtr<Peer> bestRoot;
  163. const uint64_t now = RR->node->now();
  164. Mutex::Lock _l(_lock);
  165. if (_amRoot) {
  166. /* If I am a root server, the "best" root server is the one whose address
  167. * is numerically greater than mine (with wrap at top of list). This
  168. * causes packets searching for a route to pretty much literally
  169. * circumnavigate the globe rather than bouncing between just two. */
  170. if (_rootAddresses.size() > 1) { // gotta be one other than me for this to work
  171. std::vector<Address>::const_iterator sna(std::find(_rootAddresses.begin(),_rootAddresses.end(),RR->identity.address()));
  172. if (sna != _rootAddresses.end()) { // sanity check -- _amRoot should've been false in this case
  173. for(;;) {
  174. if (++sna == _rootAddresses.end())
  175. sna = _rootAddresses.begin(); // wrap around at end
  176. if (*sna != RR->identity.address()) { // pick one other than us -- starting from me+1 in sorted set order
  177. SharedPtr<Peer> *p = _peers.get(*sna);
  178. if ((p)&&((*p)->hasActiveDirectPath(now))) {
  179. bestRoot = *p;
  180. break;
  181. }
  182. }
  183. }
  184. }
  185. }
  186. } else {
  187. /* If I am not a root server, the best root server is the active one with
  188. * the lowest latency. */
  189. unsigned int l,bestLatency = 65536;
  190. uint64_t lds,ldr;
  191. // First look for a best root by comparing latencies, but exclude
  192. // root servers that have not responded to direct messages in order to
  193. // try to exclude any that are dead or unreachable.
  194. for(std::vector< SharedPtr<Peer> >::const_iterator sn(_rootPeers.begin());sn!=_rootPeers.end();) {
  195. // Skip explicitly avoided relays
  196. for(unsigned int i=0;i<avoidCount;++i) {
  197. if (avoid[i] == (*sn)->address())
  198. goto keep_searching_for_roots;
  199. }
  200. // Skip possibly comatose or unreachable relays
  201. lds = (*sn)->lastDirectSend();
  202. ldr = (*sn)->lastDirectReceive();
  203. if ((lds)&&(lds > ldr)&&((lds - ldr) > ZT_PEER_RELAY_CONVERSATION_LATENCY_THRESHOLD))
  204. goto keep_searching_for_roots;
  205. if ((*sn)->hasActiveDirectPath(now)) {
  206. l = (*sn)->latency();
  207. if (bestRoot) {
  208. if ((l)&&(l < bestLatency)) {
  209. bestLatency = l;
  210. bestRoot = *sn;
  211. }
  212. } else {
  213. if (l)
  214. bestLatency = l;
  215. bestRoot = *sn;
  216. }
  217. }
  218. keep_searching_for_roots:
  219. ++sn;
  220. }
  221. if (bestRoot) {
  222. bestRoot->use(now);
  223. return bestRoot;
  224. } else if (strictAvoid)
  225. return SharedPtr<Peer>();
  226. // If we have nothing from above, just pick one without avoidance criteria.
  227. for(std::vector< SharedPtr<Peer> >::const_iterator sn=_rootPeers.begin();sn!=_rootPeers.end();++sn) {
  228. if ((*sn)->hasActiveDirectPath(now)) {
  229. unsigned int l = (*sn)->latency();
  230. if (bestRoot) {
  231. if ((l)&&(l < bestLatency)) {
  232. bestLatency = l;
  233. bestRoot = *sn;
  234. }
  235. } else {
  236. if (l)
  237. bestLatency = l;
  238. bestRoot = *sn;
  239. }
  240. }
  241. }
  242. }
  243. if (bestRoot)
  244. bestRoot->use(now);
  245. return bestRoot;
  246. }
  247. bool Topology::worldUpdateIfValid(const World &newWorld)
  248. {
  249. Mutex::Lock _l(_lock);
  250. if (_world.shouldBeReplacedBy(newWorld,true)) {
  251. _setWorld(newWorld);
  252. try {
  253. Buffer<ZT_WORLD_MAX_SERIALIZED_LENGTH> dswtmp;
  254. newWorld.serialize(dswtmp,false);
  255. RR->node->dataStorePut("world",dswtmp.data(),dswtmp.size(),false);
  256. } catch ( ... ) {
  257. RR->node->dataStoreDelete("world");
  258. }
  259. return true;
  260. }
  261. return false;
  262. }
  263. void Topology::clean(uint64_t now)
  264. {
  265. Mutex::Lock _l(_lock);
  266. Hashtable< Address,SharedPtr<Peer> >::Iterator i(_peers);
  267. Address *a = (Address *)0;
  268. SharedPtr<Peer> *p = (SharedPtr<Peer> *)0;
  269. while (i.next(a,p)) {
  270. if (((now - (*p)->lastUsed()) >= ZT_PEER_IN_MEMORY_EXPIRATION)&&(std::find(_rootAddresses.begin(),_rootAddresses.end(),*a) == _rootAddresses.end())) {
  271. _peers.erase(*a);
  272. } else {
  273. (*p)->clean(RR,now);
  274. }
  275. }
  276. }
  277. Identity Topology::_getIdentity(const Address &zta)
  278. {
  279. char p[128];
  280. Utils::snprintf(p,sizeof(p),"iddb.d/%.10llx",(unsigned long long)zta.toInt());
  281. std::string ids(RR->node->dataStoreGet(p));
  282. if (ids.length() > 0) {
  283. try {
  284. return Identity(ids);
  285. } catch ( ... ) {} // ignore invalid IDs
  286. }
  287. return Identity();
  288. }
  289. void Topology::_setWorld(const World &newWorld)
  290. {
  291. // assumed _lock is locked (or in constructor)
  292. _world = newWorld;
  293. _amRoot = false;
  294. _rootAddresses.clear();
  295. _rootPeers.clear();
  296. for(std::vector<World::Root>::const_iterator r(_world.roots().begin());r!=_world.roots().end();++r) {
  297. if (r->identity == RR->identity)
  298. _amRoot = true;
  299. _rootAddresses.push_back(r->identity.address());
  300. SharedPtr<Peer> *rp = _peers.get(r->identity.address());
  301. if (rp) {
  302. _rootPeers.push_back(*rp);
  303. } else if (r->identity.address() != RR->identity.address()) {
  304. SharedPtr<Peer> newrp(new Peer(RR->identity,r->identity));
  305. _peers.set(r->identity.address(),newrp);
  306. _rootPeers.push_back(newrp);
  307. }
  308. }
  309. }
  310. } // namespace ZeroTier