Topology.cpp 9.3 KB

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