Topology.cpp 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292
  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. namespace ZeroTier {
  34. Topology::Topology(const RuntimeEnvironment *renv) :
  35. RR(renv),
  36. _amRootserver(false)
  37. {
  38. }
  39. Topology::~Topology()
  40. {
  41. }
  42. void Topology::setRootservers(const std::map< Identity,std::vector<InetAddress> > &sn)
  43. {
  44. Mutex::Lock _l(_lock);
  45. if (_rootservers == sn)
  46. return; // no change
  47. _rootservers = sn;
  48. _rootserverAddresses.clear();
  49. _rootserverPeers.clear();
  50. const uint64_t now = RR->node->now();
  51. for(std::map< Identity,std::vector<InetAddress> >::const_iterator i(sn.begin());i!=sn.end();++i) {
  52. if (i->first != RR->identity) { // do not add self as a peer
  53. SharedPtr<Peer> &p = _activePeers[i->first.address()];
  54. if (!p)
  55. p = SharedPtr<Peer>(new Peer(RR->identity,i->first));
  56. for(std::vector<InetAddress>::const_iterator j(i->second.begin());j!=i->second.end();++j)
  57. p->addPath(Path(*j,true));
  58. p->use(now);
  59. _rootserverPeers.push_back(p);
  60. }
  61. _rootserverAddresses.push_back(i->first.address());
  62. }
  63. std::sort(_rootserverAddresses.begin(),_rootserverAddresses.end());
  64. _amRootserver = (_rootservers.find(RR->identity) != _rootservers.end());
  65. }
  66. void Topology::setRootservers(const Dictionary &sn)
  67. {
  68. std::map< Identity,std::vector<InetAddress> > m;
  69. for(Dictionary::const_iterator d(sn.begin());d!=sn.end();++d) {
  70. if ((d->first.length() == ZT_ADDRESS_LENGTH_HEX)&&(d->second.length() > 0)) {
  71. try {
  72. Dictionary snspec(d->second);
  73. std::vector<InetAddress> &a = m[Identity(snspec.get("id"))];
  74. std::string udp(snspec.get("udp",std::string()));
  75. if (udp.length() > 0)
  76. a.push_back(InetAddress(udp));
  77. } catch ( ... ) {
  78. TRACE("rootserver list contained invalid entry for: %s",d->first.c_str());
  79. }
  80. }
  81. }
  82. this->setRootservers(m);
  83. }
  84. SharedPtr<Peer> Topology::addPeer(const SharedPtr<Peer> &peer)
  85. {
  86. if (peer->address() == RR->identity.address()) {
  87. TRACE("BUG: addNewPeer() caught and ignored attempt to add peer for self");
  88. throw std::logic_error("cannot add peer for self");
  89. }
  90. const uint64_t now = RR->node->now();
  91. Mutex::Lock _l(_lock);
  92. SharedPtr<Peer> p(_activePeers.insert(std::pair< Address,SharedPtr<Peer> >(peer->address(),peer)).first->second);
  93. p->use(now);
  94. _saveIdentity(p->identity());
  95. return p;
  96. }
  97. SharedPtr<Peer> Topology::getPeer(const Address &zta)
  98. {
  99. if (zta == RR->identity.address()) {
  100. TRACE("BUG: ignored attempt to getPeer() for self, returned NULL");
  101. return SharedPtr<Peer>();
  102. }
  103. const uint64_t now = RR->node->now();
  104. Mutex::Lock _l(_lock);
  105. SharedPtr<Peer> &ap = _activePeers[zta];
  106. if (ap) {
  107. ap->use(now);
  108. return ap;
  109. }
  110. Identity id(_getIdentity(zta));
  111. if (id) {
  112. try {
  113. ap = SharedPtr<Peer>(new Peer(RR->identity,id));
  114. ap->use(now);
  115. return ap;
  116. } catch ( ... ) {} // invalid identity?
  117. }
  118. _activePeers.erase(zta);
  119. return SharedPtr<Peer>();
  120. }
  121. SharedPtr<Peer> Topology::getBestRootserver(const Address *avoid,unsigned int avoidCount,bool strictAvoid)
  122. {
  123. SharedPtr<Peer> bestRootserver;
  124. const uint64_t now = RR->node->now();
  125. Mutex::Lock _l(_lock);
  126. if (_amRootserver) {
  127. /* If I am a rootserver, the "best" rootserver is the one whose address
  128. * is numerically greater than mine (with wrap at top of list). This
  129. * causes packets searching for a route to pretty much literally
  130. * circumnavigate the globe rather than bouncing between just two. */
  131. if (_rootserverAddresses.size() > 1) { // gotta be one other than me for this to work
  132. std::vector<Address>::const_iterator sna(std::find(_rootserverAddresses.begin(),_rootserverAddresses.end(),RR->identity.address()));
  133. if (sna != _rootserverAddresses.end()) { // sanity check -- _amRootserver should've been false in this case
  134. for(;;) {
  135. if (++sna == _rootserverAddresses.end())
  136. sna = _rootserverAddresses.begin(); // wrap around at end
  137. if (*sna != RR->identity.address()) { // pick one other than us -- starting from me+1 in sorted set order
  138. std::map< Address,SharedPtr<Peer> >::const_iterator p(_activePeers.find(*sna));
  139. if ((p != _activePeers.end())&&(p->second->hasActiveDirectPath(now))) {
  140. bestRootserver = p->second;
  141. break;
  142. }
  143. }
  144. }
  145. }
  146. }
  147. } else {
  148. /* If I am not a rootserver, the best rootserver is the active one with
  149. * the lowest latency. */
  150. unsigned int l,bestRootserverLatency = 65536;
  151. uint64_t lds,ldr;
  152. // First look for a best rootserver by comparing latencies, but exclude
  153. // rootservers that have not responded to direct messages in order to
  154. // try to exclude any that are dead or unreachable.
  155. for(std::vector< SharedPtr<Peer> >::const_iterator sn(_rootserverPeers.begin());sn!=_rootserverPeers.end();) {
  156. // Skip explicitly avoided relays
  157. for(unsigned int i=0;i<avoidCount;++i) {
  158. if (avoid[i] == (*sn)->address())
  159. goto keep_searching_for_rootservers;
  160. }
  161. // Skip possibly comatose or unreachable relays
  162. lds = (*sn)->lastDirectSend();
  163. ldr = (*sn)->lastDirectReceive();
  164. if ((lds)&&(lds > ldr)&&((lds - ldr) > ZT_PEER_RELAY_CONVERSATION_LATENCY_THRESHOLD))
  165. goto keep_searching_for_rootservers;
  166. if ((*sn)->hasActiveDirectPath(now)) {
  167. l = (*sn)->latency();
  168. if (bestRootserver) {
  169. if ((l)&&(l < bestRootserverLatency)) {
  170. bestRootserverLatency = l;
  171. bestRootserver = *sn;
  172. }
  173. } else {
  174. if (l)
  175. bestRootserverLatency = l;
  176. bestRootserver = *sn;
  177. }
  178. }
  179. keep_searching_for_rootservers:
  180. ++sn;
  181. }
  182. if (bestRootserver) {
  183. bestRootserver->use(now);
  184. return bestRootserver;
  185. } else if (strictAvoid)
  186. return SharedPtr<Peer>();
  187. // If we have nothing from above, just pick one without avoidance criteria.
  188. for(std::vector< SharedPtr<Peer> >::const_iterator sn=_rootserverPeers.begin();sn!=_rootserverPeers.end();++sn) {
  189. if ((*sn)->hasActiveDirectPath(now)) {
  190. unsigned int l = (*sn)->latency();
  191. if (bestRootserver) {
  192. if ((l)&&(l < bestRootserverLatency)) {
  193. bestRootserverLatency = l;
  194. bestRootserver = *sn;
  195. }
  196. } else {
  197. if (l)
  198. bestRootserverLatency = l;
  199. bestRootserver = *sn;
  200. }
  201. }
  202. }
  203. }
  204. if (bestRootserver)
  205. bestRootserver->use(now);
  206. return bestRootserver;
  207. }
  208. void Topology::clean(uint64_t now)
  209. {
  210. Mutex::Lock _l(_lock);
  211. for(std::map< Address,SharedPtr<Peer> >::iterator p(_activePeers.begin());p!=_activePeers.end();) {
  212. if (((now - p->second->lastUsed()) >= ZT_PEER_IN_MEMORY_EXPIRATION)&&(std::find(_rootserverAddresses.begin(),_rootserverAddresses.end(),p->first) == _rootserverAddresses.end())) {
  213. _activePeers.erase(p++);
  214. } else ++p;
  215. }
  216. }
  217. bool Topology::authenticateRootTopology(const Dictionary &rt)
  218. {
  219. try {
  220. std::string signer(rt.signingIdentity());
  221. if (!signer.length())
  222. return false;
  223. Identity signerId(signer);
  224. std::map< Address,Identity >::const_iterator authority(ZT_DEFAULTS.rootTopologyAuthorities.find(signerId.address()));
  225. if (authority == ZT_DEFAULTS.rootTopologyAuthorities.end())
  226. return false;
  227. if (signerId != authority->second)
  228. return false;
  229. return rt.verify(authority->second);
  230. } catch ( ... ) {
  231. return false;
  232. }
  233. }
  234. Identity Topology::_getIdentity(const Address &zta)
  235. {
  236. char p[128];
  237. Utils::snprintf(p,sizeof(p),"iddb.d/%.10llx",(unsigned long long)zta.toInt());
  238. std::string ids(RR->node->dataStoreGet(p));
  239. if (ids.length() > 0) {
  240. try {
  241. return Identity(ids);
  242. } catch ( ... ) {} // ignore invalid IDs
  243. }
  244. return Identity();
  245. }
  246. void Topology::_saveIdentity(const Identity &id)
  247. {
  248. if (id) {
  249. char p[128];
  250. Utils::snprintf(p,sizeof(p),"iddb.d/%.10llx",(unsigned long long)id.address().toInt());
  251. RR->node->dataStorePut(p,id.toString(false),false);
  252. }
  253. }
  254. } // namespace ZeroTier