Topology.cpp 10 KB

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