Multicaster.cpp 14 KB

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