Topology.cpp 9.7 KB

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