Topology.cpp 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327
  1. /*
  2. * ZeroTier One - Global Peer to Peer Ethernet
  3. * Copyright (C) 2011-2015 ZeroTier Networks
  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 "Defaults.hpp"
  29. #include "Topology.hpp"
  30. #include "NodeConfig.hpp"
  31. #include "CMWC4096.hpp"
  32. #include "Dictionary.hpp"
  33. #define ZT_PEER_WRITE_BUF_SIZE 131072
  34. namespace ZeroTier {
  35. Topology::Topology(const RuntimeEnvironment *renv) :
  36. RR(renv),
  37. _idCacheBase(renv->homePath + ZT_PATH_SEPARATOR_S + "iddb.d"),
  38. _amSupernode(false)
  39. {
  40. }
  41. Topology::~Topology()
  42. {
  43. }
  44. void Topology::setSupernodes(const std::map< Identity,std::vector< std::pair<InetAddress,bool> > > &sn)
  45. {
  46. Mutex::Lock _l(_lock);
  47. if (_supernodes == sn)
  48. return; // no change
  49. _supernodes = sn;
  50. _supernodeAddresses.clear();
  51. _supernodePeers.clear();
  52. uint64_t now = Utils::now();
  53. for(std::map< Identity,std::vector< std::pair<InetAddress,bool> > >::const_iterator i(sn.begin());i!=sn.end();++i) {
  54. if (i->first != RR->identity) { // do not add self as a peer
  55. SharedPtr<Peer> &p = _activePeers[i->first.address()];
  56. if (!p)
  57. p = SharedPtr<Peer>(new Peer(RR->identity,i->first));
  58. for(std::vector< std::pair<InetAddress,bool> >::const_iterator j(i->second.begin());j!=i->second.end();++j)
  59. p->addPath(Path(j->first,(j->second) ? Path::PATH_TYPE_TCP_OUT : Path::PATH_TYPE_UDP,true));
  60. p->use(now);
  61. _supernodePeers.push_back(p);
  62. }
  63. _supernodeAddresses.push_back(i->first.address());
  64. }
  65. std::sort(_supernodeAddresses.begin(),_supernodeAddresses.end());
  66. _amSupernode = (_supernodes.find(RR->identity) != _supernodes.end());
  67. }
  68. void Topology::setSupernodes(const Dictionary &sn)
  69. {
  70. std::map< Identity,std::vector< std::pair<InetAddress,bool> > > m;
  71. for(Dictionary::const_iterator d(sn.begin());d!=sn.end();++d) {
  72. if ((d->first.length() == ZT_ADDRESS_LENGTH_HEX)&&(d->second.length() > 0)) {
  73. try {
  74. Dictionary snspec(d->second);
  75. std::vector< std::pair<InetAddress,bool> > &a = m[Identity(snspec.get("id"))];
  76. std::string udp(snspec.get("udp",std::string()));
  77. if (udp.length() > 0)
  78. a.push_back(std::pair<InetAddress,bool>(InetAddress(udp),false));
  79. std::string tcp(snspec.get("tcp",std::string()));
  80. if (tcp.length() > 0)
  81. a.push_back(std::pair<InetAddress,bool>(InetAddress(tcp),true));
  82. } catch ( ... ) {
  83. LOG("supernode list contained invalid entry for: %s",d->first.c_str());
  84. }
  85. }
  86. }
  87. this->setSupernodes(m);
  88. }
  89. SharedPtr<Peer> Topology::addPeer(const SharedPtr<Peer> &peer)
  90. {
  91. if (peer->address() == RR->identity.address()) {
  92. TRACE("BUG: addNewPeer() caught and ignored attempt to add peer for self");
  93. throw std::logic_error("cannot add peer for self");
  94. }
  95. uint64_t now = Utils::now();
  96. Mutex::Lock _l(_lock);
  97. SharedPtr<Peer> p(_activePeers.insert(std::pair< Address,SharedPtr<Peer> >(peer->address(),peer)).first->second);
  98. p->use(now);
  99. _saveIdentity(p->identity());
  100. return p;
  101. }
  102. SharedPtr<Peer> Topology::getPeer(const Address &zta)
  103. {
  104. if (zta == RR->identity.address()) {
  105. TRACE("BUG: ignored attempt to getPeer() for self, returned NULL");
  106. return SharedPtr<Peer>();
  107. }
  108. uint64_t now = Utils::now();
  109. Mutex::Lock _l(_lock);
  110. SharedPtr<Peer> &ap = _activePeers[zta];
  111. if (ap) {
  112. ap->use(now);
  113. return ap;
  114. }
  115. Identity id(_getIdentity(zta));
  116. if (id) {
  117. try {
  118. ap = SharedPtr<Peer>(new Peer(RR->identity,id));
  119. ap->use(now);
  120. return ap;
  121. } catch ( ... ) {} // invalid identity?
  122. }
  123. _activePeers.erase(zta);
  124. return SharedPtr<Peer>();
  125. }
  126. SharedPtr<Peer> Topology::getBestSupernode(const Address *avoid,unsigned int avoidCount,bool strictAvoid)
  127. {
  128. SharedPtr<Peer> bestSupernode;
  129. uint64_t now = Utils::now();
  130. Mutex::Lock _l(_lock);
  131. if (_amSupernode) {
  132. /* If I am a supernode, the "best" supernode is the one whose address
  133. * is numerically greater than mine (with wrap at top of list). This
  134. * causes packets searching for a route to pretty much literally
  135. * circumnavigate the globe rather than bouncing between just two. */
  136. if (_supernodeAddresses.size() > 1) { // gotta be one other than me for this to work
  137. std::vector<Address>::const_iterator sna(std::find(_supernodeAddresses.begin(),_supernodeAddresses.end(),RR->identity.address()));
  138. if (sna != _supernodeAddresses.end()) { // sanity check -- _amSupernode should've been false in this case
  139. for(;;) {
  140. if (++sna == _supernodeAddresses.end())
  141. sna = _supernodeAddresses.begin(); // wrap around at end
  142. if (*sna != RR->identity.address()) { // pick one other than us -- starting from me+1 in sorted set order
  143. std::map< Address,SharedPtr<Peer> >::const_iterator p(_activePeers.find(*sna));
  144. if ((p != _activePeers.end())&&(p->second->hasActiveDirectPath(now))) {
  145. bestSupernode = p->second;
  146. break;
  147. }
  148. }
  149. }
  150. }
  151. }
  152. } else {
  153. /* If I am not a supernode, the best supernode is the active one with
  154. * the lowest latency. */
  155. unsigned int l,bestSupernodeLatency = 65536;
  156. uint64_t lds,ldr;
  157. // First look for a best supernode by comparing latencies, but exclude
  158. // supernodes that have not responded to direct messages in order to
  159. // try to exclude any that are dead or unreachable.
  160. for(std::vector< SharedPtr<Peer> >::const_iterator sn(_supernodePeers.begin());sn!=_supernodePeers.end();) {
  161. // Skip explicitly avoided relays
  162. for(unsigned int i=0;i<avoidCount;++i) {
  163. if (avoid[i] == (*sn)->address())
  164. goto keep_searching_for_supernodes;
  165. }
  166. // Skip possibly comatose or unreachable relays
  167. lds = (*sn)->lastDirectSend();
  168. ldr = (*sn)->lastDirectReceive();
  169. if ((lds)&&(lds > ldr)&&((lds - ldr) > ZT_PEER_RELAY_CONVERSATION_LATENCY_THRESHOLD))
  170. goto keep_searching_for_supernodes;
  171. if ((*sn)->hasActiveDirectPath(now)) {
  172. l = (*sn)->latency();
  173. if (bestSupernode) {
  174. if ((l)&&(l < bestSupernodeLatency)) {
  175. bestSupernodeLatency = l;
  176. bestSupernode = *sn;
  177. }
  178. } else {
  179. if (l)
  180. bestSupernodeLatency = l;
  181. bestSupernode = *sn;
  182. }
  183. }
  184. keep_searching_for_supernodes:
  185. ++sn;
  186. }
  187. if (bestSupernode) {
  188. bestSupernode->use(now);
  189. return bestSupernode;
  190. } else if (strictAvoid)
  191. return SharedPtr<Peer>();
  192. // If we have nothing from above, just pick one without avoidance criteria.
  193. for(std::vector< SharedPtr<Peer> >::const_iterator sn=_supernodePeers.begin();sn!=_supernodePeers.end();++sn) {
  194. if ((*sn)->hasActiveDirectPath(now)) {
  195. unsigned int l = (*sn)->latency();
  196. if (bestSupernode) {
  197. if ((l)&&(l < bestSupernodeLatency)) {
  198. bestSupernodeLatency = l;
  199. bestSupernode = *sn;
  200. }
  201. } else {
  202. if (l)
  203. bestSupernodeLatency = l;
  204. bestSupernode = *sn;
  205. }
  206. }
  207. }
  208. }
  209. if (bestSupernode)
  210. bestSupernode->use(now);
  211. return bestSupernode;
  212. }
  213. void Topology::clean(uint64_t now)
  214. {
  215. Mutex::Lock _l(_lock);
  216. for(std::map< Address,SharedPtr<Peer> >::iterator p(_activePeers.begin());p!=_activePeers.end();) {
  217. if (((now - p->second->lastUsed()) >= ZT_PEER_IN_MEMORY_EXPIRATION)&&(std::find(_supernodeAddresses.begin(),_supernodeAddresses.end(),p->first) == _supernodeAddresses.end())) {
  218. _activePeers.erase(p++);
  219. } else {
  220. p->second->clean(now);
  221. ++p;
  222. }
  223. }
  224. }
  225. bool Topology::updateSurface(const SharedPtr<Peer> &remotePeer,const InetAddress &mirroredAddress,uint64_t now)
  226. {
  227. Mutex::Lock _l(_lock);
  228. if (std::find(_supernodeAddresses.begin(),_supernodeAddresses.end(),remotePeer->address()) == _supernodeAddresses.end())
  229. return false;
  230. if (_surface.update(mirroredAddress)) {
  231. // Clear non-fixed paths for all peers -- will force reconnect on next activity
  232. for(std::map< Address,SharedPtr<Peer> >::const_iterator ap(_activePeers.begin());ap!=_activePeers.end();++ap)
  233. ap->second->clearPaths(false);
  234. // Reset TCP tunneling if our global addressing has changed
  235. if (!mirroredAddress.isLinkLocal())
  236. (const_cast <RuntimeEnvironment *>(RR))->tcpTunnelingEnabled = false;
  237. // Ping supernodes now (other than the one we might have just heard from)
  238. for(std::vector< SharedPtr<Peer> >::const_iterator sn(_supernodePeers.begin());sn!=_supernodePeers.end();++sn) {
  239. if (remotePeer != *sn)
  240. (*sn)->sendPing(RR,now);
  241. }
  242. return true;
  243. }
  244. return false;
  245. }
  246. bool Topology::authenticateRootTopology(const Dictionary &rt)
  247. {
  248. try {
  249. std::string signer(rt.signingIdentity());
  250. if (!signer.length())
  251. return false;
  252. Identity signerId(signer);
  253. std::map< Address,Identity >::const_iterator authority(ZT_DEFAULTS.rootTopologyAuthorities.find(signerId.address()));
  254. if (authority == ZT_DEFAULTS.rootTopologyAuthorities.end())
  255. return false;
  256. if (signerId != authority->second)
  257. return false;
  258. return rt.verify(authority->second);
  259. } catch ( ... ) {
  260. return false;
  261. }
  262. }
  263. Identity Topology::_getIdentity(const Address &zta)
  264. {
  265. std::string idcPath(_idCacheBase + ZT_PATH_SEPARATOR_S + zta.toString());
  266. std::string ids;
  267. if (Utils::readFile(idcPath.c_str(),ids)) {
  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. std::string idcPath(_idCacheBase + ZT_PATH_SEPARATOR_S + id.address().toString());
  278. Utils::writeFile(idcPath.c_str(),id.toString(false));
  279. }
  280. }
  281. } // namespace ZeroTier