Topology.cpp 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301
  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. _amRoot(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 (_roots == sn)
  46. return; // no change
  47. _roots = sn;
  48. _rootAddresses.clear();
  49. _rootPeers.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(RemotePath(InetAddress(),*j,true));
  58. p->use(now);
  59. _rootPeers.push_back(p);
  60. }
  61. _rootAddresses.push_back(i->first.address());
  62. }
  63. std::sort(_rootAddresses.begin(),_rootAddresses.end());
  64. _amRoot = (_roots.find(RR->identity) != _roots.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("root server 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.set(peer->address(),peer);
  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::getBestRoot(const Address *avoid,unsigned int avoidCount,bool strictAvoid)
  122. {
  123. SharedPtr<Peer> bestRoot;
  124. const uint64_t now = RR->node->now();
  125. Mutex::Lock _l(_lock);
  126. if (_amRoot) {
  127. /* If I am a root server, the "best" root server 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 (_rootAddresses.size() > 1) { // gotta be one other than me for this to work
  132. std::vector<Address>::const_iterator sna(std::find(_rootAddresses.begin(),_rootAddresses.end(),RR->identity.address()));
  133. if (sna != _rootAddresses.end()) { // sanity check -- _amRoot should've been false in this case
  134. for(;;) {
  135. if (++sna == _rootAddresses.end())
  136. sna = _rootAddresses.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. SharedPtr<Peer> *p = _activePeers.get(*sna);
  139. if ((p)&&((*p)->hasActiveDirectPath(now))) {
  140. bestRoot = *p;
  141. break;
  142. }
  143. }
  144. }
  145. }
  146. }
  147. } else {
  148. /* If I am not a root server, the best root server is the active one with
  149. * the lowest latency. */
  150. unsigned int l,bestLatency = 65536;
  151. uint64_t lds,ldr;
  152. // First look for a best root by comparing latencies, but exclude
  153. // root servers 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(_rootPeers.begin());sn!=_rootPeers.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_roots;
  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_roots;
  166. if ((*sn)->hasActiveDirectPath(now)) {
  167. l = (*sn)->latency();
  168. if (bestRoot) {
  169. if ((l)&&(l < bestLatency)) {
  170. bestLatency = l;
  171. bestRoot = *sn;
  172. }
  173. } else {
  174. if (l)
  175. bestLatency = l;
  176. bestRoot = *sn;
  177. }
  178. }
  179. keep_searching_for_roots:
  180. ++sn;
  181. }
  182. if (bestRoot) {
  183. bestRoot->use(now);
  184. return bestRoot;
  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=_rootPeers.begin();sn!=_rootPeers.end();++sn) {
  189. if ((*sn)->hasActiveDirectPath(now)) {
  190. unsigned int l = (*sn)->latency();
  191. if (bestRoot) {
  192. if ((l)&&(l < bestLatency)) {
  193. bestLatency = l;
  194. bestRoot = *sn;
  195. }
  196. } else {
  197. if (l)
  198. bestLatency = l;
  199. bestRoot = *sn;
  200. }
  201. }
  202. }
  203. }
  204. if (bestRoot)
  205. bestRoot->use(now);
  206. return bestRoot;
  207. }
  208. bool Topology::isRoot(const Identity &id) const
  209. throw()
  210. {
  211. Mutex::Lock _l(_lock);
  212. return (_roots.count(id) != 0);
  213. }
  214. void Topology::clean(uint64_t now)
  215. {
  216. Mutex::Lock _l(_lock);
  217. Hashtable< Address,SharedPtr<Peer> >::Iterator i(_activePeers);
  218. Address *a = (Address *)0;
  219. SharedPtr<Peer> *p = (SharedPtr<Peer> *)0;
  220. while (i.next(a,p))
  221. if (((now - (*p)->lastUsed()) >= ZT_PEER_IN_MEMORY_EXPIRATION)&&(std::find(_rootAddresses.begin(),_rootAddresses.end(),*a) == _rootAddresses.end())) {
  222. _activePeers.erase(*a);
  223. }
  224. }
  225. bool Topology::authenticateRootTopology(const Dictionary &rt)
  226. {
  227. try {
  228. std::string signer(rt.signingIdentity());
  229. if (!signer.length())
  230. return false;
  231. Identity signerId(signer);
  232. std::map< Address,Identity >::const_iterator authority(ZT_DEFAULTS.rootTopologyAuthorities.find(signerId.address()));
  233. if (authority == ZT_DEFAULTS.rootTopologyAuthorities.end())
  234. return false;
  235. if (signerId != authority->second)
  236. return false;
  237. return rt.verify(authority->second);
  238. } catch ( ... ) {
  239. return false;
  240. }
  241. }
  242. Identity Topology::_getIdentity(const Address &zta)
  243. {
  244. char p[128];
  245. Utils::snprintf(p,sizeof(p),"iddb.d/%.10llx",(unsigned long long)zta.toInt());
  246. std::string ids(RR->node->dataStoreGet(p));
  247. if (ids.length() > 0) {
  248. try {
  249. return Identity(ids);
  250. } catch ( ... ) {} // ignore invalid IDs
  251. }
  252. return Identity();
  253. }
  254. void Topology::_saveIdentity(const Identity &id)
  255. {
  256. if (id) {
  257. char p[128];
  258. Utils::snprintf(p,sizeof(p),"iddb.d/%.10llx",(unsigned long long)id.address().toInt());
  259. RR->node->dataStorePut(p,id.toString(false),false);
  260. }
  261. }
  262. } // namespace ZeroTier