Multicaster.cpp 14 KB

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