Multicaster.cpp 14 KB

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