Cluster.cpp 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742
  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. #ifdef ZT_ENABLE_CLUSTER
  28. #include <stdint.h>
  29. #include <stdio.h>
  30. #include <stdlib.h>
  31. #include <string.h>
  32. #include <math.h>
  33. #include <algorithm>
  34. #include <utility>
  35. #include "../version.h"
  36. #include "Cluster.hpp"
  37. #include "RuntimeEnvironment.hpp"
  38. #include "MulticastGroup.hpp"
  39. #include "CertificateOfMembership.hpp"
  40. #include "Salsa20.hpp"
  41. #include "Poly1305.hpp"
  42. #include "Identity.hpp"
  43. #include "Topology.hpp"
  44. #include "Packet.hpp"
  45. #include "Switch.hpp"
  46. #include "Node.hpp"
  47. namespace ZeroTier {
  48. static inline double _dist3d(int x1,int y1,int z1,int x2,int y2,int z2)
  49. throw()
  50. {
  51. double dx = ((double)x2 - (double)x1);
  52. double dy = ((double)y2 - (double)y1);
  53. double dz = ((double)z2 - (double)z1);
  54. return sqrt((dx * dx) + (dy * dy) + (dz * dz));
  55. }
  56. Cluster::Cluster(
  57. const RuntimeEnvironment *renv,
  58. uint16_t id,
  59. const std::vector<InetAddress> &zeroTierPhysicalEndpoints,
  60. int32_t x,
  61. int32_t y,
  62. int32_t z,
  63. void (*sendFunction)(void *,unsigned int,const void *,unsigned int),
  64. void *sendFunctionArg,
  65. int (*addressToLocationFunction)(void *,const struct sockaddr_storage *,int *,int *,int *),
  66. void *addressToLocationFunctionArg) :
  67. RR(renv),
  68. _sendFunction(sendFunction),
  69. _sendFunctionArg(sendFunctionArg),
  70. _addressToLocationFunction(addressToLocationFunction),
  71. _addressToLocationFunctionArg(addressToLocationFunctionArg),
  72. _x(x),
  73. _y(y),
  74. _z(z),
  75. _id(id),
  76. _zeroTierPhysicalEndpoints(zeroTierPhysicalEndpoints),
  77. _members(new _Member[ZT_CLUSTER_MAX_MEMBERS]),
  78. _peerAffinities(65536),
  79. _lastCleanedPeerAffinities(0),
  80. _lastCheckedPeersForAnnounce(0),
  81. _lastFlushed(0),
  82. _lastCleanedRemotePeers(0)
  83. {
  84. uint16_t stmp[ZT_SHA512_DIGEST_LEN / sizeof(uint16_t)];
  85. // Generate master secret by hashing the secret from our Identity key pair
  86. RR->identity.sha512PrivateKey(_masterSecret);
  87. // Generate our inbound message key, which is the master secret XORed with our ID and hashed twice
  88. memcpy(stmp,_masterSecret,sizeof(stmp));
  89. stmp[0] ^= Utils::hton(id);
  90. SHA512::hash(stmp,stmp,sizeof(stmp));
  91. SHA512::hash(stmp,stmp,sizeof(stmp));
  92. memcpy(_key,stmp,sizeof(_key));
  93. Utils::burn(stmp,sizeof(stmp));
  94. }
  95. Cluster::~Cluster()
  96. {
  97. Utils::burn(_masterSecret,sizeof(_masterSecret));
  98. Utils::burn(_key,sizeof(_key));
  99. delete [] _members;
  100. for(std::multimap<Address,_SQE *>::iterator qi(_sendViaClusterQueue.begin());qi!=_sendViaClusterQueue.end();)
  101. delete qi->second;
  102. }
  103. void Cluster::handleIncomingStateMessage(const void *msg,unsigned int len)
  104. {
  105. Buffer<ZT_CLUSTER_MAX_MESSAGE_LENGTH> dmsg;
  106. {
  107. // FORMAT: <[16] iv><[8] MAC><... data>
  108. if ((len < 24)||(len > ZT_CLUSTER_MAX_MESSAGE_LENGTH))
  109. return;
  110. // 16-byte IV: first 8 bytes XORed with key, last 8 bytes used as Salsa20 64-bit IV
  111. char keytmp[32];
  112. memcpy(keytmp,_key,32);
  113. for(int i=0;i<8;++i)
  114. keytmp[i] ^= reinterpret_cast<const char *>(msg)[i];
  115. Salsa20 s20(keytmp,256,reinterpret_cast<const char *>(msg) + 8);
  116. Utils::burn(keytmp,sizeof(keytmp));
  117. // One-time-use Poly1305 key from first 32 bytes of Salsa20 keystream (as per DJB/NaCl "standard")
  118. char polykey[ZT_POLY1305_KEY_LEN];
  119. memset(polykey,0,sizeof(polykey));
  120. s20.encrypt12(polykey,polykey,sizeof(polykey));
  121. // Compute 16-byte MAC
  122. char mac[ZT_POLY1305_MAC_LEN];
  123. Poly1305::compute(mac,reinterpret_cast<const char *>(msg) + 24,len - 24,polykey);
  124. // Check first 8 bytes of MAC against 64-bit MAC in stream
  125. if (!Utils::secureEq(mac,reinterpret_cast<const char *>(msg) + 16,8))
  126. return;
  127. // Decrypt!
  128. dmsg.setSize(len - 24);
  129. s20.decrypt12(reinterpret_cast<const char *>(msg) + 24,const_cast<void *>(dmsg.data()),dmsg.size());
  130. }
  131. if (dmsg.size() < 4)
  132. return;
  133. const uint16_t fromMemberId = dmsg.at<uint16_t>(0);
  134. unsigned int ptr = 2;
  135. if (fromMemberId == _id) // sanity check: we don't talk to ourselves
  136. return;
  137. const uint16_t toMemberId = dmsg.at<uint16_t>(ptr);
  138. ptr += 2;
  139. if (toMemberId != _id) // sanity check: message not for us?
  140. return;
  141. { // make sure sender is actually considered a member
  142. Mutex::Lock _l3(_memberIds_m);
  143. if (std::find(_memberIds.begin(),_memberIds.end(),fromMemberId) == _memberIds.end())
  144. return;
  145. }
  146. _Member &m = _members[fromMemberId];
  147. try {
  148. while (ptr < dmsg.size()) {
  149. const unsigned int mlen = dmsg.at<uint16_t>(ptr); ptr += 2;
  150. const unsigned int nextPtr = ptr + mlen;
  151. if (nextPtr > dmsg.size())
  152. break;
  153. int mtype = -1;
  154. try {
  155. switch((StateMessageType)(mtype = (int)dmsg[ptr++])) {
  156. default:
  157. break;
  158. case CLUSTER_MESSAGE_ALIVE: {
  159. Mutex::Lock mlck(m.lock);
  160. ptr += 7; // skip version stuff, not used yet
  161. m.x = dmsg.at<int32_t>(ptr); ptr += 4;
  162. m.y = dmsg.at<int32_t>(ptr); ptr += 4;
  163. m.z = dmsg.at<int32_t>(ptr); ptr += 4;
  164. ptr += 8; // skip local clock, not used
  165. m.load = dmsg.at<uint64_t>(ptr); ptr += 8;
  166. m.peers = dmsg.at<uint64_t>(ptr); ptr += 8;
  167. ptr += 8; // skip flags, unused
  168. #ifdef ZT_TRACE
  169. std::string addrs;
  170. #endif
  171. unsigned int physicalAddressCount = dmsg[ptr++];
  172. m.zeroTierPhysicalEndpoints.clear();
  173. for(unsigned int i=0;i<physicalAddressCount;++i) {
  174. m.zeroTierPhysicalEndpoints.push_back(InetAddress());
  175. ptr += m.zeroTierPhysicalEndpoints.back().deserialize(dmsg,ptr);
  176. if (!(m.zeroTierPhysicalEndpoints.back())) {
  177. m.zeroTierPhysicalEndpoints.pop_back();
  178. }
  179. #ifdef ZT_TRACE
  180. else {
  181. if (addrs.length() > 0)
  182. addrs.push_back(',');
  183. addrs.append(m.zeroTierPhysicalEndpoints.back().toString());
  184. }
  185. #endif
  186. }
  187. #ifdef ZT_TRACE
  188. if ((RR->node->now() - m.lastReceivedAliveAnnouncement) >= ZT_CLUSTER_TIMEOUT) {
  189. TRACE("[%u] I'm alive! peers close to %d,%d,%d can be redirected to: %s",(unsigned int)fromMemberId,m.x,m.y,m.z,addrs.c_str());
  190. }
  191. #endif
  192. m.lastReceivedAliveAnnouncement = RR->node->now();
  193. } break;
  194. case CLUSTER_MESSAGE_HAVE_PEER: {
  195. Identity id;
  196. ptr += id.deserialize(dmsg,ptr);
  197. if (id) {
  198. RR->topology->saveIdentity(id);
  199. {
  200. Mutex::Lock _l(_remotePeers_m);
  201. _remotePeers[std::pair<Address,unsigned int>(id.address(),(unsigned int)fromMemberId)] = RR->node->now();
  202. }
  203. std::pair<Address,_SQE *> q[ZT_CLUSTER_MAX_QUEUE_PER_SENDER];
  204. unsigned int qc = 0;
  205. {
  206. Mutex::Lock _l(_sendViaClusterQueue_m);
  207. std::pair< std::multimap<Address,_SQE *>::iterator,std::multimap<Address,_SQE>::iterator > er(_sendViaClusterQueue.equal_range(id.address()));
  208. for(std::multimap<Address,_SQE *>::iterator qi(er.first);qi!=er.second;) {
  209. if (qc >= ZT_CLUSTER_MAX_QUEUE_PER_SENDER) // sanity check
  210. break;
  211. q[qc++] = *qi;
  212. _sendViaClusterQueue.erase(qi++);
  213. }
  214. }
  215. for(unsigned int i=0;i<qc;++i) {
  216. this->sendViaCluster(q[i].first,q[i].second->toPeerAddress,q[i].second->data,q[i].second->len,q[i].second->unite);
  217. delete q[i].second;
  218. }
  219. TRACE("[%u] has %s",(unsigned int)fromMemberId,id.address().toString().c_str());
  220. }
  221. } break;
  222. case CLUSTER_MESSAGE_WANT_PEER: {
  223. const Address zeroTierAddress(dmsg.field(ptr,ZT_ADDRESS_LENGTH),ZT_ADDRESS_LENGTH); ptr += ZT_ADDRESS_LENGTH;
  224. SharedPtr<Peer> peer(RR->topology->getPeerNoCache(zeroTierAddress));
  225. if ( (peer) && (peer->hasActiveDirectPath(RR->node->now())) ) {
  226. Buffer<1024> buf;
  227. peer->identity().serialize(buf);
  228. Mutex::Lock _l2(_members[fromMemberId].lock);
  229. _send(fromMemberId,CLUSTER_MESSAGE_HAVE_PEER,buf.data(),buf.size());
  230. _flush(fromMemberId); // lookups are latency sensitive
  231. }
  232. }
  233. } break;
  234. case CLUSTER_MESSAGE_REMOTE_PACKET: {
  235. const unsigned int plen = dmsg.at<uint16_t>(ptr); ptr += 2;
  236. if (plen) {
  237. Packet remotep(dmsg.field(ptr,plen),plen); ptr += plen;
  238. TRACE("remote %s from %s via %u (%u bytes)",Packet::verbString(remotep.verb()),remotep.source().toString().c_str(),fromMemberId,plen);
  239. switch(remotep.verb()) {
  240. case Packet::VERB_WHOIS: _doREMOTE_WHOIS(fromMemberId,remotep); break;
  241. case Packet::VERB_MULTICAST_GATHER: _doREMOTE_MULTICAST_GATHER(fromMemberId,remotep); break;
  242. default: break; // ignore things we don't care about across cluster
  243. }
  244. }
  245. } break;
  246. case CLUSTER_MESSAGE_PROXY_UNITE: {
  247. const Address localPeerAddress(dmsg.field(ptr,ZT_ADDRESS_LENGTH),ZT_ADDRESS_LENGTH); ptr += ZT_ADDRESS_LENGTH;
  248. const Address remotePeerAddress(dmsg.field(ptr,ZT_ADDRESS_LENGTH),ZT_ADDRESS_LENGTH); ptr += ZT_ADDRESS_LENGTH;
  249. const unsigned int numRemotePeerPaths = dmsg[ptr++];
  250. InetAddress remotePeerPaths[256]; // size is 8-bit, so 256 is max
  251. for(unsigned int i=0;i<numRemotePeerPaths;++i)
  252. ptr += remotePeerPaths[i].deserialize(dmsg,ptr);
  253. TRACE("[%u] requested that we unite local %s with remote %s",(unsigned int)fromMemberId,localPeerAddress.toString().c_str(),remotePeerAddress.toString().c_str());
  254. const uint64_t now = RR->node->now();
  255. SharedPtr<Peer> localPeer(RR->topology->getPeerNoCache(localPeerAddress));
  256. if ((localPeer)&&(numRemotePeerPaths > 0)) {
  257. InetAddress bestLocalV4,bestLocalV6;
  258. localPeer->getBestActiveAddresses(now,bestLocalV4,bestLocalV6);
  259. InetAddress bestRemoteV4,bestRemoteV6;
  260. for(unsigned int i=0;i<numRemotePeerPaths;++i) {
  261. if ((bestRemoteV4)&&(bestRemoteV6))
  262. break;
  263. switch(remotePeerPaths[i].ss_family) {
  264. case AF_INET:
  265. if (!bestRemoteV4)
  266. bestRemoteV4 = remotePeerPaths[i];
  267. break;
  268. case AF_INET6:
  269. if (!bestRemoteV6)
  270. bestRemoteV6 = remotePeerPaths[i];
  271. break;
  272. }
  273. }
  274. Packet rendezvousForLocal(localPeerAddress,RR->identity.address(),Packet::VERB_RENDEZVOUS);
  275. rendezvousForLocal.append((uint8_t)0);
  276. remotePeerAddress.appendTo(rendezvousForLocal);
  277. Buffer<2048> rendezvousForRemote;
  278. remotePeerAddress.appendTo(rendezvousForRemote);
  279. rendezvousForRemote.append((uint8_t)Packet::VERB_RENDEZVOUS);
  280. const unsigned int rendezvousForOtherEndPayloadSizePtr = rendezvousForRemote.size();
  281. rendezvousForRemote.addSize(2); // space for actual packet payload length
  282. rendezvousForRemote.append((uint8_t)0); // flags == 0
  283. localPeerAddress.appendTo(rendezvousForRemote);
  284. bool haveMatch = false;
  285. if ((bestLocalV6)&&(bestRemoteV6)) {
  286. haveMatch = true;
  287. rendezvousForLocal.append((uint16_t)bestRemoteV6.port());
  288. rendezvousForLocal.append((uint8_t)16);
  289. rendezvousForLocal.append(bestRemoteV6.rawIpData(),16);
  290. rendezvousForRemote.append((uint16_t)bestLocalV6.port());
  291. rendezvousForRemote.append((uint8_t)16);
  292. rendezvousForRemote.append(bestLocalV6.rawIpData(),16);
  293. rendezvousForRemote.setAt<uint16_t>(rendezvousForOtherEndPayloadSizePtr,(uint16_t)(9 + 16));
  294. } else if ((bestLocalV4)&&(bestRemoteV4)) {
  295. haveMatch = true;
  296. rendezvousForLocal.append((uint16_t)bestRemoteV4.port());
  297. rendezvousForLocal.append((uint8_t)4);
  298. rendezvousForLocal.append(bestRemoteV4.rawIpData(),4);
  299. rendezvousForRemote.append((uint16_t)bestLocalV4.port());
  300. rendezvousForRemote.append((uint8_t)4);
  301. rendezvousForRemote.append(bestLocalV4.rawIpData(),4);
  302. rendezvousForRemote.setAt<uint16_t>(rendezvousForOtherEndPayloadSizePtr,(uint16_t)(9 + 4));
  303. }
  304. if (haveMatch) {
  305. _send(fromMemberId,CLUSTER_MESSAGE_PROXY_SEND,rendezvousForRemote.data(),rendezvousForRemote.size());
  306. _flush(fromMemberId);
  307. RR->sw->send(rendezvousForLocal,true,0);
  308. }
  309. }
  310. } break;
  311. case CLUSTER_MESSAGE_PROXY_SEND: {
  312. const Address rcpt(dmsg.field(ptr,ZT_ADDRESS_LENGTH),ZT_ADDRESS_LENGTH); ptr += ZT_ADDRESS_LENGTH;
  313. const Packet::Verb verb = (Packet::Verb)dmsg[ptr++];
  314. const unsigned int len = dmsg.at<uint16_t>(ptr); ptr += 2;
  315. Packet outp(rcpt,RR->identity.address(),verb);
  316. outp.append(dmsg.field(ptr,len),len); ptr += len;
  317. RR->sw->send(outp,true,0);
  318. //TRACE("[%u] proxy send %s to %s length %u",(unsigned int)fromMemberId,Packet::verbString(verb),rcpt.toString().c_str(),len);
  319. } break;
  320. }
  321. } catch ( ... ) {
  322. TRACE("invalid message of size %u type %d (inner decode), discarding",mlen,mtype);
  323. // drop invalids
  324. }
  325. ptr = nextPtr;
  326. }
  327. } catch ( ... ) {
  328. TRACE("invalid message (outer loop), discarding");
  329. // drop invalids
  330. }
  331. }
  332. bool Cluster::sendViaCluster(const Address &fromPeerAddress,const Address &toPeerAddress,const void *data,unsigned int len,bool unite)
  333. {
  334. if (len > ZT_PROTO_MAX_PACKET_LENGTH) // sanity check
  335. return false;
  336. const uint64_t now = RR->node->now();
  337. unsigned int canHasPeer = 0;
  338. uint64_t mostRecentTs = 0;
  339. unsigned int mostRecentMemberId = 0xffffffff;
  340. {
  341. Mutex::Lock _l2(_remotePeers_m);
  342. std::map< std::pair<Address,unsigned int>,uint64_t >::const_iterator rpe(_remotePeers.lower_bound(std::pair<Address,unsigned int>(fromPeerAddress,0)));
  343. for(;;) {
  344. if ((rpe == _remotePeers.end())||(rpe->first.first != fromPeerAddress))
  345. break;
  346. else if (rpe->second > mostRecentTs) {
  347. mostRecentTs = rpe->second;
  348. mostRecentMemberId = rpe->first.second;
  349. }
  350. }
  351. }
  352. const uint64_t age = now - mostRecentTs;
  353. if (age >= (ZT_PEER_ACTIVITY_TIMEOUT / 3)) {
  354. // Poll everyone with WANT_PEER if the age of our most recent entry is
  355. // approaching expiration (or has expired, or does not exist).
  356. char tmp[ZT_ADDRESS_LENGTH];
  357. toPeerAddress.copyTo(tmp,ZT_ADDRESS_LENGTH);
  358. {
  359. Mutex::Lock _l(_memberIds_m);
  360. for(std::vector<uint16_t>::const_iterator mid(_memberIds.begin());mid!=_memberIds.end();++mid) {
  361. Mutex::Lock _l2(_members[*mid].lock);
  362. _send(*mid,CLUSTER_MESSAGE_WANT_PEER,tmp,ZT_ADDRESS_LENGTH);
  363. if (mostRecentMemberId > 0xffff)
  364. _flush(*mid); // latency sensitive if we don't have one
  365. }
  366. }
  367. // If there isn't a good place to send via, then enqueue this for retrying
  368. // later and return after having broadcasted a WANT_PEER.
  369. if ((age >= ZT_PEER_ACTIVITY_TIMEOUT)||(mostRecentMemberId > 0xffff)) {
  370. Mutex::Lock _l(_sendViaClusterQueue_m);
  371. if (_sendViaClusterQueue.count(fromPeerAddress) < ZT_CLUSTER_MAX_QUEUE_PER_SENDER)
  372. _sendViaClusterQueue.insert(std::pair<Address,_SQE *>(fromPeerAddress,new _SQE(now,toPeerAddress,data,len,unite)));
  373. return true;
  374. }
  375. }
  376. Buffer<1024> buf;
  377. if (unite) {
  378. InetAddress v4,v6;
  379. if (fromPeerAddress) {
  380. SharedPtr<Peer> fromPeer(RR->topology->getPeerNoCache(fromPeerAddress));
  381. if (fromPeer)
  382. fromPeer->getBestActiveAddresses(now,v4,v6);
  383. }
  384. uint8_t addrCount = 0;
  385. if (v4)
  386. ++addrCount;
  387. if (v6)
  388. ++addrCount;
  389. if (addrCount) {
  390. toPeerAddress.appendTo(buf);
  391. fromPeerAddress.appendTo(buf);
  392. buf.append(addrCount);
  393. if (v4)
  394. v4.serialize(buf);
  395. if (v6)
  396. v6.serialize(buf);
  397. }
  398. }
  399. {
  400. Mutex::Lock _l2(_members[mostRecentMemberId].lock);
  401. if (buf.size() > 0) {
  402. _send(canHasPeer,CLUSTER_MESSAGE_PROXY_UNITE,buf.data(),buf.size());
  403. _flush(canHasPeer); // latency sensitive
  404. }
  405. if (_members[mostRecentMemberId].zeroTierPhysicalEndpoints.size() > 0)
  406. RR->node->putPacket(InetAddress(),_members[canHasPeer].zeroTierPhysicalEndpoints.front(),data,len);
  407. }
  408. TRACE("sendViaCluster(): relaying %u bytes from %s to %s by way of %u",len,fromPeerAddress.toString().c_str(),toPeerAddress.toString().c_str(),(unsigned int)canHasPeer);
  409. return true;
  410. }
  411. void Cluster::sendDistributedQuery(const Packet &pkt)
  412. {
  413. Buffer<4096> buf;
  414. buf.append((uint16_t)pkt.size());
  415. buf.append(pkt.data(),pkt.size());
  416. Mutex::Lock _l(_memberIds_m);
  417. for(std::vector<uint16_t>::const_iterator mid(_memberIds.begin());mid!=_memberIds.end();++mid) {
  418. Mutex::Lock _l2(_members[*mid].lock);
  419. _send(*mid,CLUSTER_MESSAGE_REMOTE_PACKET,buf.data(),buf.size());
  420. _flush(*mid); // these tend to be latency-sensitive
  421. }
  422. }
  423. void Cluster::doPeriodicTasks()
  424. {
  425. const uint64_t now = RR->node->now();
  426. if ((now - _lastFlushed) >= ZT_CLUSTER_FLUSH_PERIOD) {
  427. _lastFlushed = now;
  428. {
  429. Mutex::Lock _l2(_sendViaClusterQueue_m);
  430. for(std::multimap<Address,_SQE *>::iterator qi(_sendViaClusterQueue.begin());qi!=_sendViaClusterQueue.end();) {
  431. if ((now - qi->second->timestamp) >= ZT_CLUSTER_QUEUE_EXPIRATION) {
  432. delete qi->second;
  433. _sendViaClusterQueue.erase(qi++);
  434. } else ++qi;
  435. }
  436. }
  437. Mutex::Lock _l(_memberIds_m);
  438. for(std::vector<uint16_t>::const_iterator mid(_memberIds.begin());mid!=_memberIds.end();++mid) {
  439. Mutex::Lock _l2(_members[*mid].lock);
  440. if ((now - _members[*mid].lastAnnouncedAliveTo) >= ((ZT_CLUSTER_TIMEOUT / 2) - 1000)) {
  441. _members[*mid].lastAnnouncedAliveTo = now;
  442. Buffer<2048> alive;
  443. alive.append((uint16_t)ZEROTIER_ONE_VERSION_MAJOR);
  444. alive.append((uint16_t)ZEROTIER_ONE_VERSION_MINOR);
  445. alive.append((uint16_t)ZEROTIER_ONE_VERSION_REVISION);
  446. alive.append((uint8_t)ZT_PROTO_VERSION);
  447. if (_addressToLocationFunction) {
  448. alive.append((int32_t)_x);
  449. alive.append((int32_t)_y);
  450. alive.append((int32_t)_z);
  451. } else {
  452. alive.append((int32_t)0);
  453. alive.append((int32_t)0);
  454. alive.append((int32_t)0);
  455. }
  456. alive.append((uint64_t)now);
  457. alive.append((uint64_t)0); // TODO: compute and send load average
  458. alive.append((uint64_t)RR->topology->countActive());
  459. alive.append((uint64_t)0); // unused/reserved flags
  460. alive.append((uint8_t)_zeroTierPhysicalEndpoints.size());
  461. for(std::vector<InetAddress>::const_iterator pe(_zeroTierPhysicalEndpoints.begin());pe!=_zeroTierPhysicalEndpoints.end();++pe)
  462. pe->serialize(alive);
  463. _send(*mid,CLUSTER_MESSAGE_ALIVE,alive.data(),alive.size());
  464. }
  465. _flush(*mid); // does nothing if nothing to flush
  466. }
  467. }
  468. if ((now - _lastCleanedRemotePeers) >= (ZT_PEER_ACTIVITY_TIMEOUT * 2)) {
  469. _lastCleanedRemotePeers = now;
  470. Mutex::Lock _l(_remotePeers_m);
  471. for(std::map< std::pair<Address,unsigned int>,uint64_t >::iterator rp(_remotePeers.begin());rp!=_remotePeers.end();) {
  472. if ((now - rp->second) >= ZT_PEER_ACTIVITY_TIMEOUT)
  473. _remotePeers.erase(rp++);
  474. else ++rp;
  475. }
  476. }
  477. }
  478. void Cluster::addMember(uint16_t memberId)
  479. {
  480. if ((memberId >= ZT_CLUSTER_MAX_MEMBERS)||(memberId == _id))
  481. return;
  482. Mutex::Lock _l2(_members[memberId].lock);
  483. {
  484. Mutex::Lock _l(_memberIds_m);
  485. if (std::find(_memberIds.begin(),_memberIds.end(),memberId) != _memberIds.end())
  486. return;
  487. _memberIds.push_back(memberId);
  488. std::sort(_memberIds.begin(),_memberIds.end());
  489. }
  490. _members[memberId].clear();
  491. // Generate this member's message key from the master and its ID
  492. uint16_t stmp[ZT_SHA512_DIGEST_LEN / sizeof(uint16_t)];
  493. memcpy(stmp,_masterSecret,sizeof(stmp));
  494. stmp[0] ^= Utils::hton(memberId);
  495. SHA512::hash(stmp,stmp,sizeof(stmp));
  496. SHA512::hash(stmp,stmp,sizeof(stmp));
  497. memcpy(_members[memberId].key,stmp,sizeof(_members[memberId].key));
  498. Utils::burn(stmp,sizeof(stmp));
  499. // Prepare q
  500. _members[memberId].q.clear();
  501. char iv[16];
  502. Utils::getSecureRandom(iv,16);
  503. _members[memberId].q.append(iv,16);
  504. _members[memberId].q.addSize(8); // room for MAC
  505. _members[memberId].q.append((uint16_t)_id);
  506. _members[memberId].q.append((uint16_t)memberId);
  507. }
  508. void Cluster::removeMember(uint16_t memberId)
  509. {
  510. Mutex::Lock _l(_memberIds_m);
  511. std::vector<uint16_t> newMemberIds;
  512. for(std::vector<uint16_t>::const_iterator mid(_memberIds.begin());mid!=_memberIds.end();++mid) {
  513. if (*mid != memberId)
  514. newMemberIds.push_back(*mid);
  515. }
  516. _memberIds = newMemberIds;
  517. }
  518. bool Cluster::findBetterEndpoint(InetAddress &redirectTo,const Address &peerAddress,const InetAddress &peerPhysicalAddress,bool offload)
  519. {
  520. if (_addressToLocationFunction) {
  521. // Pick based on location if it can be determined
  522. int px = 0,py = 0,pz = 0;
  523. if (_addressToLocationFunction(_addressToLocationFunctionArg,reinterpret_cast<const struct sockaddr_storage *>(&peerPhysicalAddress),&px,&py,&pz) == 0) {
  524. TRACE("no geolocation data for %s (geo-lookup is lazy/async so it may work next time)",peerPhysicalAddress.toIpString().c_str());
  525. return false;
  526. }
  527. // Find member closest to this peer
  528. const uint64_t now = RR->node->now();
  529. std::vector<InetAddress> best;
  530. const double currentDistance = _dist3d(_x,_y,_z,px,py,pz);
  531. double bestDistance = (offload ? 2147483648.0 : currentDistance);
  532. unsigned int bestMember = _id;
  533. {
  534. Mutex::Lock _l(_memberIds_m);
  535. for(std::vector<uint16_t>::const_iterator mid(_memberIds.begin());mid!=_memberIds.end();++mid) {
  536. _Member &m = _members[*mid];
  537. Mutex::Lock _ml(m.lock);
  538. // Consider member if it's alive and has sent us a location and one or more physical endpoints to send peers to
  539. if ( ((now - m.lastReceivedAliveAnnouncement) < ZT_CLUSTER_TIMEOUT) && ((m.x != 0)||(m.y != 0)||(m.z != 0)) && (m.zeroTierPhysicalEndpoints.size() > 0) ) {
  540. const double mdist = _dist3d(m.x,m.y,m.z,px,py,pz);
  541. if (mdist < bestDistance) {
  542. bestDistance = mdist;
  543. bestMember = *mid;
  544. best = m.zeroTierPhysicalEndpoints;
  545. }
  546. }
  547. }
  548. }
  549. // Redirect to a closer member if it has a ZeroTier endpoint address in the same ss_family
  550. for(std::vector<InetAddress>::const_iterator a(best.begin());a!=best.end();++a) {
  551. if (a->ss_family == peerPhysicalAddress.ss_family) {
  552. TRACE("%s at [%d,%d,%d] is %f from us but %f from %u, can redirect to %s",peerAddress.toString().c_str(),px,py,pz,currentDistance,bestDistance,bestMember,a->toString().c_str());
  553. redirectTo = *a;
  554. return true;
  555. }
  556. }
  557. TRACE("%s at [%d,%d,%d] is %f from us, no better endpoints found",peerAddress.toString().c_str(),px,py,pz,currentDistance);
  558. return false;
  559. } else {
  560. // TODO: pick based on load if no location info?
  561. return false;
  562. }
  563. }
  564. void Cluster::status(ZT_ClusterStatus &status) const
  565. {
  566. const uint64_t now = RR->node->now();
  567. memset(&status,0,sizeof(ZT_ClusterStatus));
  568. status.myId = _id;
  569. ms[_id] = &(status.members[status.clusterSize++]);
  570. ms[_id]->id = _id;
  571. ms[_id]->alive = 1;
  572. ms[_id]->x = _x;
  573. ms[_id]->y = _y;
  574. ms[_id]->z = _z;
  575. ms[_id]->load = 0; // TODO
  576. ms[_id]->peers = RR->topology->countActive();
  577. for(std::vector<InetAddress>::const_iterator ep(_zeroTierPhysicalEndpoints.begin());ep!=_zeroTierPhysicalEndpoints.end();++ep) {
  578. if (ms[_id]->numZeroTierPhysicalEndpoints >= ZT_CLUSTER_MAX_ZT_PHYSICAL_ADDRESSES) // sanity check
  579. break;
  580. memcpy(&(ms[_id]->zeroTierPhysicalEndpoints[ms[_id]->numZeroTierPhysicalEndpoints++]),&(*ep),sizeof(struct sockaddr_storage));
  581. }
  582. {
  583. Mutex::Lock _l1(_memberIds_m);
  584. for(std::vector<uint16_t>::const_iterator mid(_memberIds.begin());mid!=_memberIds.end();++mid) {
  585. if (status.clusterSize >= ZT_CLUSTER_MAX_MEMBERS) // sanity check
  586. break;
  587. _Member &m = _members[*mid];
  588. Mutex::Lock ml(m.lock);
  589. ZT_ClusterMemberStatus *const s = &(status.members[status.clusterSize++]);
  590. s->id = *mid;
  591. s->msSinceLastHeartbeat = (unsigned int)std::min((uint64_t)(~((unsigned int)0)),(now - m.lastReceivedAliveAnnouncement));
  592. s->alive = (s->msSinceLastHeartbeat < ZT_CLUSTER_TIMEOUT) ? 1 : 0;
  593. s->x = m.x;
  594. s->y = m.y;
  595. s->z = m.z;
  596. s->load = m.load;
  597. s->peers = m.peers;
  598. for(std::vector<InetAddress>::const_iterator ep(m.zeroTierPhysicalEndpoints.begin());ep!=m.zeroTierPhysicalEndpoints.end();++ep) {
  599. if (s->numZeroTierPhysicalEndpoints >= ZT_CLUSTER_MAX_ZT_PHYSICAL_ADDRESSES) // sanity check
  600. break;
  601. memcpy(&(s->zeroTierPhysicalEndpoints[s->numZeroTierPhysicalEndpoints++]),&(*ep),sizeof(struct sockaddr_storage));
  602. }
  603. }
  604. }
  605. }
  606. void Cluster::_send(uint16_t memberId,StateMessageType type,const void *msg,unsigned int len)
  607. {
  608. if ((len + 3) > (ZT_CLUSTER_MAX_MESSAGE_LENGTH - (24 + 2 + 2))) // sanity check
  609. return;
  610. _Member &m = _members[memberId];
  611. // assumes m.lock is locked!
  612. if ((m.q.size() + len + 3) > ZT_CLUSTER_MAX_MESSAGE_LENGTH)
  613. _flush(memberId);
  614. m.q.append((uint16_t)(len + 1));
  615. m.q.append((uint8_t)type);
  616. m.q.append(msg,len);
  617. }
  618. void Cluster::_flush(uint16_t memberId)
  619. {
  620. _Member &m = _members[memberId];
  621. // assumes m.lock is locked!
  622. if (m.q.size() > (24 + 2 + 2)) { // 16-byte IV + 8-byte MAC + 2 byte from-member-ID + 2 byte to-member-ID
  623. // Create key from member's key and IV
  624. char keytmp[32];
  625. memcpy(keytmp,m.key,32);
  626. for(int i=0;i<8;++i)
  627. keytmp[i] ^= m.q[i];
  628. Salsa20 s20(keytmp,256,m.q.field(8,8));
  629. Utils::burn(keytmp,sizeof(keytmp));
  630. // One-time-use Poly1305 key from first 32 bytes of Salsa20 keystream (as per DJB/NaCl "standard")
  631. char polykey[ZT_POLY1305_KEY_LEN];
  632. memset(polykey,0,sizeof(polykey));
  633. s20.encrypt12(polykey,polykey,sizeof(polykey));
  634. // Encrypt m.q in place
  635. s20.encrypt12(reinterpret_cast<const char *>(m.q.data()) + 24,const_cast<char *>(reinterpret_cast<const char *>(m.q.data())) + 24,m.q.size() - 24);
  636. // Add MAC for authentication (encrypt-then-MAC)
  637. char mac[ZT_POLY1305_MAC_LEN];
  638. Poly1305::compute(mac,reinterpret_cast<const char *>(m.q.data()) + 24,m.q.size() - 24,polykey);
  639. memcpy(m.q.field(16,8),mac,8);
  640. // Send!
  641. _sendFunction(_sendFunctionArg,memberId,m.q.data(),m.q.size());
  642. // Prepare for more
  643. m.q.clear();
  644. char iv[16];
  645. Utils::getSecureRandom(iv,16);
  646. m.q.append(iv,16);
  647. m.q.addSize(8); // room for MAC
  648. m.q.append((uint16_t)_id); // from member ID
  649. m.q.append((uint16_t)memberId); // to member ID
  650. }
  651. }
  652. } // namespace ZeroTier
  653. #endif // ZT_ENABLE_CLUSTER