Multicaster.cpp 14 KB

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