Multicaster.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461
  1. /*
  2. * ZeroTier One - Network Virtualization Everywhere
  3. * Copyright (C) 2011-2018 ZeroTier, Inc. https://www.zerotier.com/
  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. * You can be released from the requirements of the license by purchasing
  21. * a commercial license. Buying such a license is mandatory as soon as you
  22. * develop commercial closed-source software that incorporates or links
  23. * directly against ZeroTier software without disclosing the source code
  24. * of your own application.
  25. */
  26. #include <algorithm>
  27. #include "Constants.hpp"
  28. #include "RuntimeEnvironment.hpp"
  29. #include "Multicaster.hpp"
  30. #include "Topology.hpp"
  31. #include "Switch.hpp"
  32. #include "Packet.hpp"
  33. #include "Peer.hpp"
  34. #include "C25519.hpp"
  35. #include "CertificateOfMembership.hpp"
  36. #include "Node.hpp"
  37. #include "Network.hpp"
  38. namespace ZeroTier {
  39. Multicaster::Multicaster(const RuntimeEnvironment *renv) :
  40. RR(renv),
  41. _groups(256),
  42. _gatherAuth(256)
  43. {
  44. }
  45. Multicaster::~Multicaster()
  46. {
  47. }
  48. void Multicaster::addMultiple(void *tPtr,int64_t now,uint64_t nwid,const MulticastGroup &mg,const void *addresses,unsigned int count,unsigned int totalKnown)
  49. {
  50. const unsigned char *p = (const unsigned char *)addresses;
  51. const unsigned char *e = p + (5 * count);
  52. Mutex::Lock _l(_groups_m);
  53. MulticastGroupStatus &gs = _groups[Multicaster::Key(nwid,mg)];
  54. while (p != e) {
  55. _add(tPtr,now,nwid,mg,gs,Address(p,5));
  56. p += 5;
  57. }
  58. }
  59. void Multicaster::remove(uint64_t nwid,const MulticastGroup &mg,const Address &member)
  60. {
  61. Mutex::Lock _l(_groups_m);
  62. MulticastGroupStatus *s = _groups.get(Multicaster::Key(nwid,mg));
  63. if (s) {
  64. for(std::vector<MulticastGroupMember>::iterator m(s->members.begin());m!=s->members.end();++m) {
  65. if (m->address == member) {
  66. s->members.erase(m);
  67. break;
  68. }
  69. }
  70. }
  71. }
  72. unsigned int Multicaster::gather(const Address &queryingPeer,uint64_t nwid,const MulticastGroup &mg,Buffer<ZT_PROTO_MAX_PACKET_LENGTH> &appendTo,unsigned int limit) const
  73. {
  74. unsigned char *p;
  75. unsigned int added = 0,i,k,rptr,totalKnown = 0;
  76. uint64_t a,picked[(ZT_PROTO_MAX_PACKET_LENGTH / 5) + 2];
  77. if (!limit)
  78. return 0;
  79. else if (limit > 0xffff)
  80. limit = 0xffff;
  81. const unsigned int totalAt = appendTo.size();
  82. appendTo.addSize(4); // sizeof(uint32_t)
  83. const unsigned int addedAt = appendTo.size();
  84. appendTo.addSize(2); // sizeof(uint16_t)
  85. { // Return myself if I am a member of this group
  86. SharedPtr<Network> network(RR->node->network(nwid));
  87. if ((network)&&(network->subscribedToMulticastGroup(mg,true))) {
  88. RR->identity.address().appendTo(appendTo);
  89. ++totalKnown;
  90. ++added;
  91. }
  92. }
  93. Mutex::Lock _l(_groups_m);
  94. const MulticastGroupStatus *s = _groups.get(Multicaster::Key(nwid,mg));
  95. if ((s)&&(!s->members.empty())) {
  96. totalKnown += (unsigned int)s->members.size();
  97. // Members are returned in random order so that repeated gather queries
  98. // will return different subsets of a large multicast group.
  99. k = 0;
  100. while ((added < limit)&&(k < s->members.size())&&((appendTo.size() + ZT_ADDRESS_LENGTH) <= ZT_PROTO_MAX_PACKET_LENGTH)) {
  101. rptr = (unsigned int)RR->node->prng();
  102. restart_member_scan:
  103. a = s->members[rptr % (unsigned int)s->members.size()].address.toInt();
  104. for(i=0;i<k;++i) {
  105. if (picked[i] == a) {
  106. ++rptr;
  107. goto restart_member_scan;
  108. }
  109. }
  110. picked[k++] = a;
  111. if (queryingPeer.toInt() != a) { // do not return the peer that is making the request as a result
  112. p = (unsigned char *)appendTo.appendField(ZT_ADDRESS_LENGTH);
  113. *(p++) = (unsigned char)((a >> 32) & 0xff);
  114. *(p++) = (unsigned char)((a >> 24) & 0xff);
  115. *(p++) = (unsigned char)((a >> 16) & 0xff);
  116. *(p++) = (unsigned char)((a >> 8) & 0xff);
  117. *p = (unsigned char)(a & 0xff);
  118. ++added;
  119. }
  120. }
  121. }
  122. appendTo.setAt(totalAt,(uint32_t)totalKnown);
  123. appendTo.setAt(addedAt,(uint16_t)added);
  124. return added;
  125. }
  126. std::vector<Address> Multicaster::getMembers(uint64_t nwid,const MulticastGroup &mg,unsigned int limit) const
  127. {
  128. std::vector<Address> ls;
  129. Mutex::Lock _l(_groups_m);
  130. const MulticastGroupStatus *s = _groups.get(Multicaster::Key(nwid,mg));
  131. if (!s)
  132. return ls;
  133. for(std::vector<MulticastGroupMember>::const_reverse_iterator m(s->members.rbegin());m!=s->members.rend();++m) {
  134. ls.push_back(m->address);
  135. if (ls.size() >= limit)
  136. break;
  137. }
  138. return ls;
  139. }
  140. void Multicaster::send(
  141. void *tPtr,
  142. int64_t now,
  143. const SharedPtr<Network> &network,
  144. const Address &origin,
  145. const MulticastGroup &mg,
  146. const MAC &src,
  147. unsigned int etherType,
  148. const void *data,
  149. unsigned int len)
  150. {
  151. unsigned long idxbuf[4096];
  152. unsigned long *indexes = idxbuf;
  153. // If we're in hub-and-spoke designated multicast replication mode, see if we
  154. // have a multicast replicator active. If so, pick the best and send it
  155. // there. If we are a multicast replicator or if none are alive, fall back
  156. // to sender replication.
  157. {
  158. Address multicastReplicators[ZT_MAX_NETWORK_SPECIALISTS];
  159. const unsigned int multicastReplicatorCount = network->config().multicastReplicators(multicastReplicators);
  160. if (multicastReplicatorCount) {
  161. if (std::find(multicastReplicators,multicastReplicators + multicastReplicatorCount,RR->identity.address()) == (multicastReplicators + multicastReplicatorCount)) {
  162. SharedPtr<Peer> bestMulticastReplicator;
  163. SharedPtr<Path> bestMulticastReplicatorPath;
  164. unsigned int bestMulticastReplicatorLatency = 0xffff;
  165. for(unsigned int i=0;i<multicastReplicatorCount;++i) {
  166. const SharedPtr<Peer> p(RR->topology->getPeerNoCache(multicastReplicators[i]));
  167. if ((p)&&(p->isAlive(now))) {
  168. const SharedPtr<Path> pp(p->getBestPath(now,false));
  169. if ((pp)&&(pp->latency() < bestMulticastReplicatorLatency)) {
  170. bestMulticastReplicatorLatency = pp->latency();
  171. bestMulticastReplicatorPath = pp;
  172. bestMulticastReplicator = p;
  173. }
  174. }
  175. }
  176. if (bestMulticastReplicator) {
  177. Packet outp(bestMulticastReplicator->address(),RR->identity.address(),Packet::VERB_MULTICAST_FRAME);
  178. outp.append((uint64_t)network->id());
  179. outp.append((uint8_t)0x04); // includes source MAC
  180. ((src) ? src : MAC(RR->identity.address(),network->id())).appendTo(outp);
  181. mg.mac().appendTo(outp);
  182. outp.append((uint32_t)mg.adi());
  183. outp.append((uint16_t)etherType);
  184. outp.append(data,len);
  185. if (!network->config().disableCompression()) outp.compress();
  186. outp.armor(bestMulticastReplicator->key(),true);
  187. bestMulticastReplicatorPath->send(RR,tPtr,outp.data(),outp.size(),now);
  188. return;
  189. }
  190. }
  191. }
  192. }
  193. try {
  194. Mutex::Lock _l(_groups_m);
  195. MulticastGroupStatus &gs = _groups[Multicaster::Key(network->id(),mg)];
  196. if (!gs.members.empty()) {
  197. // Allocate a memory buffer if group is monstrous
  198. if (gs.members.size() > (sizeof(idxbuf) / sizeof(unsigned long)))
  199. indexes = new unsigned long[gs.members.size()];
  200. // Generate a random permutation of member indexes
  201. for(unsigned long i=0;i<gs.members.size();++i)
  202. indexes[i] = i;
  203. for(unsigned long i=(unsigned long)gs.members.size()-1;i>0;--i) {
  204. unsigned long j = (unsigned long)RR->node->prng() % (i + 1);
  205. unsigned long tmp = indexes[j];
  206. indexes[j] = indexes[i];
  207. indexes[i] = tmp;
  208. }
  209. }
  210. Address activeBridges[ZT_MAX_NETWORK_SPECIALISTS];
  211. const unsigned int activeBridgeCount = network->config().activeBridges(activeBridges);
  212. const unsigned int limit = network->config().multicastLimit;
  213. if (gs.members.size() >= limit) {
  214. // Skip queue if we already have enough members to complete the send operation
  215. OutboundMulticast out;
  216. out.init(
  217. RR,
  218. now,
  219. network->id(),
  220. network->config().disableCompression(),
  221. limit,
  222. 1, // we'll still gather a little from peers to keep multicast list fresh
  223. src,
  224. mg,
  225. etherType,
  226. data,
  227. len);
  228. unsigned int count = 0;
  229. for(unsigned int i=0;i<activeBridgeCount;++i) {
  230. if ((activeBridges[i] != RR->identity.address())&&(activeBridges[i] != origin)) {
  231. out.sendOnly(RR,tPtr,activeBridges[i]); // optimization: don't use dedup log if it's a one-pass send
  232. if (++count >= limit)
  233. break;
  234. }
  235. }
  236. unsigned long idx = 0;
  237. while ((count < limit)&&(idx < gs.members.size())) {
  238. const Address ma(gs.members[indexes[idx++]].address);
  239. if ((std::find(activeBridges,activeBridges + activeBridgeCount,ma) == (activeBridges + activeBridgeCount))&&(ma != origin)) {
  240. out.sendOnly(RR,tPtr,ma); // optimization: don't use dedup log if it's a one-pass send
  241. ++count;
  242. }
  243. }
  244. } else {
  245. const unsigned int gatherLimit = (limit - (unsigned int)gs.members.size()) + 1;
  246. if ((gs.members.empty())||((now - gs.lastExplicitGather) >= ZT_MULTICAST_EXPLICIT_GATHER_DELAY)) {
  247. gs.lastExplicitGather = now;
  248. Address explicitGatherPeers[16];
  249. unsigned int numExplicitGatherPeers = 0;
  250. SharedPtr<Peer> bestRoot(RR->topology->getUpstreamPeer());
  251. if (bestRoot)
  252. explicitGatherPeers[numExplicitGatherPeers++] = bestRoot->address();
  253. explicitGatherPeers[numExplicitGatherPeers++] = network->controller();
  254. Address ac[ZT_MAX_NETWORK_SPECIALISTS];
  255. const unsigned int accnt = network->config().alwaysContactAddresses(ac);
  256. unsigned int shuffled[ZT_MAX_NETWORK_SPECIALISTS];
  257. for(unsigned int i=0;i<accnt;++i)
  258. shuffled[i] = i;
  259. for(unsigned int i=0,k=accnt>>1;i<k;++i) {
  260. const uint64_t x = RR->node->prng();
  261. const unsigned int x1 = shuffled[(unsigned int)x % accnt];
  262. const unsigned int x2 = shuffled[(unsigned int)(x >> 32) % accnt];
  263. const unsigned int tmp = shuffled[x1];
  264. shuffled[x1] = shuffled[x2];
  265. shuffled[x2] = tmp;
  266. }
  267. for(unsigned int i=0;i<accnt;++i) {
  268. explicitGatherPeers[numExplicitGatherPeers++] = ac[shuffled[i]];
  269. if (numExplicitGatherPeers == 16)
  270. break;
  271. }
  272. std::vector<Address> anchors(network->config().anchors());
  273. for(std::vector<Address>::const_iterator a(anchors.begin());a!=anchors.end();++a) {
  274. if (*a != RR->identity.address()) {
  275. explicitGatherPeers[numExplicitGatherPeers++] = *a;
  276. if (numExplicitGatherPeers == 16)
  277. break;
  278. }
  279. }
  280. for(unsigned int k=0;k<numExplicitGatherPeers;++k) {
  281. const CertificateOfMembership *com = (network) ? ((network->config().com) ? &(network->config().com) : (const CertificateOfMembership *)0) : (const CertificateOfMembership *)0;
  282. Packet outp(explicitGatherPeers[k],RR->identity.address(),Packet::VERB_MULTICAST_GATHER);
  283. outp.append(network->id());
  284. outp.append((uint8_t)((com) ? 0x01 : 0x00));
  285. mg.mac().appendTo(outp);
  286. outp.append((uint32_t)mg.adi());
  287. outp.append((uint32_t)gatherLimit);
  288. if (com)
  289. com->serialize(outp);
  290. RR->node->expectReplyTo(outp.packetId());
  291. RR->sw->send(tPtr,outp,true);
  292. }
  293. }
  294. gs.txQueue.push_back(OutboundMulticast());
  295. OutboundMulticast &out = gs.txQueue.back();
  296. out.init(
  297. RR,
  298. now,
  299. network->id(),
  300. network->config().disableCompression(),
  301. limit,
  302. gatherLimit,
  303. src,
  304. mg,
  305. etherType,
  306. data,
  307. len);
  308. unsigned int count = 0;
  309. for(unsigned int i=0;i<activeBridgeCount;++i) {
  310. if (activeBridges[i] != RR->identity.address()) {
  311. out.sendAndLog(RR,tPtr,activeBridges[i]);
  312. if (++count >= limit)
  313. break;
  314. }
  315. }
  316. unsigned long idx = 0;
  317. while ((count < limit)&&(idx < gs.members.size())) {
  318. Address ma(gs.members[indexes[idx++]].address);
  319. if (std::find(activeBridges,activeBridges + activeBridgeCount,ma) == (activeBridges + activeBridgeCount)) {
  320. out.sendAndLog(RR,tPtr,ma);
  321. ++count;
  322. }
  323. }
  324. }
  325. } catch ( ... ) {} // this is a sanity check to catch any failures and make sure indexes[] still gets deleted
  326. // Free allocated memory buffer if any
  327. if (indexes != idxbuf)
  328. delete [] indexes;
  329. }
  330. void Multicaster::clean(int64_t now)
  331. {
  332. {
  333. Mutex::Lock _l(_groups_m);
  334. Multicaster::Key *k = (Multicaster::Key *)0;
  335. MulticastGroupStatus *s = (MulticastGroupStatus *)0;
  336. Hashtable<Multicaster::Key,MulticastGroupStatus>::Iterator mm(_groups);
  337. while (mm.next(k,s)) {
  338. for(std::list<OutboundMulticast>::iterator tx(s->txQueue.begin());tx!=s->txQueue.end();) {
  339. if ((tx->expired(now))||(tx->atLimit()))
  340. s->txQueue.erase(tx++);
  341. else ++tx;
  342. }
  343. unsigned long count = 0;
  344. {
  345. std::vector<MulticastGroupMember>::iterator reader(s->members.begin());
  346. std::vector<MulticastGroupMember>::iterator writer(reader);
  347. while (reader != s->members.end()) {
  348. if ((now - reader->timestamp) < ZT_MULTICAST_LIKE_EXPIRE) {
  349. *writer = *reader;
  350. ++writer;
  351. ++count;
  352. }
  353. ++reader;
  354. }
  355. }
  356. if (count) {
  357. s->members.resize(count);
  358. } else if (s->txQueue.empty()) {
  359. _groups.erase(*k);
  360. } else {
  361. s->members.clear();
  362. }
  363. }
  364. }
  365. {
  366. Mutex::Lock _l(_gatherAuth_m);
  367. _GatherAuthKey *k = (_GatherAuthKey *)0;
  368. uint64_t *ts = NULL;
  369. Hashtable<_GatherAuthKey,uint64_t>::Iterator i(_gatherAuth);
  370. while (i.next(k,ts)) {
  371. if ((now - *ts) >= ZT_MULTICAST_CREDENTIAL_EXPIRATON)
  372. _gatherAuth.erase(*k);
  373. }
  374. }
  375. }
  376. void Multicaster::addCredential(void *tPtr,const CertificateOfMembership &com,bool alreadyValidated)
  377. {
  378. if ((alreadyValidated)||(com.verify(RR,tPtr) == 0)) {
  379. Mutex::Lock _l(_gatherAuth_m);
  380. _gatherAuth[_GatherAuthKey(com.networkId(),com.issuedTo())] = RR->node->now();
  381. }
  382. }
  383. void Multicaster::_add(void *tPtr,int64_t now,uint64_t nwid,const MulticastGroup &mg,MulticastGroupStatus &gs,const Address &member)
  384. {
  385. // assumes _groups_m is locked
  386. // Do not add self -- even if someone else returns it
  387. if (member == RR->identity.address())
  388. return;
  389. for(std::vector<MulticastGroupMember>::iterator m(gs.members.begin());m!=gs.members.end();++m) {
  390. if (m->address == member) {
  391. m->timestamp = now;
  392. return;
  393. }
  394. }
  395. gs.members.push_back(MulticastGroupMember(member,now));
  396. for(std::list<OutboundMulticast>::iterator tx(gs.txQueue.begin());tx!=gs.txQueue.end();) {
  397. if (tx->atLimit())
  398. gs.txQueue.erase(tx++);
  399. else {
  400. tx->sendIfNew(RR,tPtr,member);
  401. if (tx->atLimit())
  402. gs.txQueue.erase(tx++);
  403. else ++tx;
  404. }
  405. }
  406. }
  407. } // namespace ZeroTier