Multicaster.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468
  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. Note that bridges do not do this since this would
  157. // break bridge route learning. This is sort of an edge case limitation of
  158. // the current protocol and could be fixed, but fixing it would add more
  159. // complexity than the fix is probably worth. Bridges are generally high
  160. // bandwidth nodes.
  161. if (!network->config().isActiveBridge(RR->identity.address())) {
  162. Address multicastReplicators[ZT_MAX_NETWORK_SPECIALISTS];
  163. const unsigned int multicastReplicatorCount = network->config().multicastReplicators(multicastReplicators);
  164. if (multicastReplicatorCount) {
  165. if (std::find(multicastReplicators,multicastReplicators + multicastReplicatorCount,RR->identity.address()) == (multicastReplicators + multicastReplicatorCount)) {
  166. SharedPtr<Peer> bestMulticastReplicator;
  167. SharedPtr<Path> bestMulticastReplicatorPath;
  168. unsigned int bestMulticastReplicatorLatency = 0xffff;
  169. for(unsigned int i=0;i<multicastReplicatorCount;++i) {
  170. const SharedPtr<Peer> p(RR->topology->getPeerNoCache(multicastReplicators[i]));
  171. if ((p)&&(p->isAlive(now))) {
  172. const SharedPtr<Path> pp(p->getBestPath(now,false));
  173. if ((pp)&&(pp->latency() < bestMulticastReplicatorLatency)) {
  174. bestMulticastReplicatorLatency = pp->latency();
  175. bestMulticastReplicatorPath = pp;
  176. bestMulticastReplicator = p;
  177. }
  178. }
  179. }
  180. if (bestMulticastReplicator) {
  181. Packet outp(bestMulticastReplicator->address(),RR->identity.address(),Packet::VERB_MULTICAST_FRAME);
  182. outp.append((uint64_t)network->id());
  183. outp.append((uint8_t)0x0c); // includes source MAC | please replicate
  184. ((src) ? src : MAC(RR->identity.address(),network->id())).appendTo(outp);
  185. mg.mac().appendTo(outp);
  186. outp.append((uint32_t)mg.adi());
  187. outp.append((uint16_t)etherType);
  188. outp.append(data,len);
  189. if (!network->config().disableCompression()) outp.compress();
  190. outp.armor(bestMulticastReplicator->key(),true);
  191. bestMulticastReplicatorPath->send(RR,tPtr,outp.data(),outp.size(),now);
  192. return;
  193. }
  194. }
  195. }
  196. }
  197. try {
  198. Mutex::Lock _l(_groups_m);
  199. MulticastGroupStatus &gs = _groups[Multicaster::Key(network->id(),mg)];
  200. if (!gs.members.empty()) {
  201. // Allocate a memory buffer if group is monstrous
  202. if (gs.members.size() > (sizeof(idxbuf) / sizeof(unsigned long)))
  203. indexes = new unsigned long[gs.members.size()];
  204. // Generate a random permutation of member indexes
  205. for(unsigned long i=0;i<gs.members.size();++i)
  206. indexes[i] = i;
  207. for(unsigned long i=(unsigned long)gs.members.size()-1;i>0;--i) {
  208. unsigned long j = (unsigned long)RR->node->prng() % (i + 1);
  209. unsigned long tmp = indexes[j];
  210. indexes[j] = indexes[i];
  211. indexes[i] = tmp;
  212. }
  213. }
  214. Address activeBridges[ZT_MAX_NETWORK_SPECIALISTS];
  215. const unsigned int activeBridgeCount = network->config().activeBridges(activeBridges);
  216. const unsigned int limit = network->config().multicastLimit;
  217. if (gs.members.size() >= limit) {
  218. // Skip queue if we already have enough members to complete the send operation
  219. OutboundMulticast out;
  220. out.init(
  221. RR,
  222. now,
  223. network->id(),
  224. network->config().disableCompression(),
  225. limit,
  226. 1, // we'll still gather a little from peers to keep multicast list fresh
  227. src,
  228. mg,
  229. etherType,
  230. data,
  231. len);
  232. unsigned int count = 0;
  233. for(unsigned int i=0;i<activeBridgeCount;++i) {
  234. if ((activeBridges[i] != RR->identity.address())&&(activeBridges[i] != origin)) {
  235. out.sendOnly(RR,tPtr,activeBridges[i]); // optimization: don't use dedup log if it's a one-pass send
  236. if (++count >= limit)
  237. break;
  238. }
  239. }
  240. unsigned long idx = 0;
  241. while ((count < limit)&&(idx < gs.members.size())) {
  242. const Address ma(gs.members[indexes[idx++]].address);
  243. if ((std::find(activeBridges,activeBridges + activeBridgeCount,ma) == (activeBridges + activeBridgeCount))&&(ma != origin)) {
  244. out.sendOnly(RR,tPtr,ma); // optimization: don't use dedup log if it's a one-pass send
  245. ++count;
  246. }
  247. }
  248. } else {
  249. const unsigned int gatherLimit = (limit - (unsigned int)gs.members.size()) + 1;
  250. if ((gs.members.empty())||((now - gs.lastExplicitGather) >= ZT_MULTICAST_EXPLICIT_GATHER_DELAY)) {
  251. gs.lastExplicitGather = now;
  252. Address explicitGatherPeers[16];
  253. unsigned int numExplicitGatherPeers = 0;
  254. SharedPtr<Peer> bestRoot(RR->topology->getUpstreamPeer());
  255. if (bestRoot)
  256. explicitGatherPeers[numExplicitGatherPeers++] = bestRoot->address();
  257. explicitGatherPeers[numExplicitGatherPeers++] = network->controller();
  258. Address ac[ZT_MAX_NETWORK_SPECIALISTS];
  259. const unsigned int accnt = network->config().alwaysContactAddresses(ac);
  260. unsigned int shuffled[ZT_MAX_NETWORK_SPECIALISTS];
  261. for(unsigned int i=0;i<accnt;++i)
  262. shuffled[i] = i;
  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. std::vector<Address> anchors(network->config().anchors());
  277. for(std::vector<Address>::const_iterator a(anchors.begin());a!=anchors.end();++a) {
  278. if (*a != RR->identity.address()) {
  279. explicitGatherPeers[numExplicitGatherPeers++] = *a;
  280. if (numExplicitGatherPeers == 16)
  281. break;
  282. }
  283. }
  284. for(unsigned int k=0;k<numExplicitGatherPeers;++k) {
  285. const CertificateOfMembership *com = (network) ? ((network->config().com) ? &(network->config().com) : (const CertificateOfMembership *)0) : (const CertificateOfMembership *)0;
  286. Packet outp(explicitGatherPeers[k],RR->identity.address(),Packet::VERB_MULTICAST_GATHER);
  287. outp.append(network->id());
  288. outp.append((uint8_t)((com) ? 0x01 : 0x00));
  289. mg.mac().appendTo(outp);
  290. outp.append((uint32_t)mg.adi());
  291. outp.append((uint32_t)gatherLimit);
  292. if (com)
  293. com->serialize(outp);
  294. RR->node->expectReplyTo(outp.packetId());
  295. RR->sw->send(tPtr,outp,true);
  296. }
  297. }
  298. gs.txQueue.push_back(OutboundMulticast());
  299. OutboundMulticast &out = gs.txQueue.back();
  300. out.init(
  301. RR,
  302. now,
  303. network->id(),
  304. network->config().disableCompression(),
  305. limit,
  306. gatherLimit,
  307. src,
  308. mg,
  309. etherType,
  310. data,
  311. len);
  312. if (origin)
  313. out.logAsSent(origin);
  314. unsigned int count = 0;
  315. for(unsigned int i=0;i<activeBridgeCount;++i) {
  316. if (activeBridges[i] != RR->identity.address()) {
  317. out.sendAndLog(RR,tPtr,activeBridges[i]);
  318. if (++count >= limit)
  319. break;
  320. }
  321. }
  322. unsigned long idx = 0;
  323. while ((count < limit)&&(idx < gs.members.size())) {
  324. Address ma(gs.members[indexes[idx++]].address);
  325. if (std::find(activeBridges,activeBridges + activeBridgeCount,ma) == (activeBridges + activeBridgeCount)) {
  326. out.sendAndLog(RR,tPtr,ma);
  327. ++count;
  328. }
  329. }
  330. }
  331. } catch ( ... ) {} // this is a sanity check to catch any failures and make sure indexes[] still gets deleted
  332. // Free allocated memory buffer if any
  333. if (indexes != idxbuf)
  334. delete [] indexes;
  335. }
  336. void Multicaster::clean(int64_t now)
  337. {
  338. {
  339. Mutex::Lock _l(_groups_m);
  340. Multicaster::Key *k = (Multicaster::Key *)0;
  341. MulticastGroupStatus *s = (MulticastGroupStatus *)0;
  342. Hashtable<Multicaster::Key,MulticastGroupStatus>::Iterator mm(_groups);
  343. while (mm.next(k,s)) {
  344. for(std::list<OutboundMulticast>::iterator tx(s->txQueue.begin());tx!=s->txQueue.end();) {
  345. if ((tx->expired(now))||(tx->atLimit()))
  346. s->txQueue.erase(tx++);
  347. else ++tx;
  348. }
  349. unsigned long count = 0;
  350. {
  351. std::vector<MulticastGroupMember>::iterator reader(s->members.begin());
  352. std::vector<MulticastGroupMember>::iterator writer(reader);
  353. while (reader != s->members.end()) {
  354. if ((now - reader->timestamp) < ZT_MULTICAST_LIKE_EXPIRE) {
  355. *writer = *reader;
  356. ++writer;
  357. ++count;
  358. }
  359. ++reader;
  360. }
  361. }
  362. if (count) {
  363. s->members.resize(count);
  364. } else if (s->txQueue.empty()) {
  365. _groups.erase(*k);
  366. } else {
  367. s->members.clear();
  368. }
  369. }
  370. }
  371. {
  372. Mutex::Lock _l(_gatherAuth_m);
  373. _GatherAuthKey *k = (_GatherAuthKey *)0;
  374. uint64_t *ts = NULL;
  375. Hashtable<_GatherAuthKey,uint64_t>::Iterator i(_gatherAuth);
  376. while (i.next(k,ts)) {
  377. if ((now - *ts) >= ZT_MULTICAST_CREDENTIAL_EXPIRATON)
  378. _gatherAuth.erase(*k);
  379. }
  380. }
  381. }
  382. void Multicaster::addCredential(void *tPtr,const CertificateOfMembership &com,bool alreadyValidated)
  383. {
  384. if ((alreadyValidated)||(com.verify(RR,tPtr) == 0)) {
  385. Mutex::Lock _l(_gatherAuth_m);
  386. _gatherAuth[_GatherAuthKey(com.networkId(),com.issuedTo())] = RR->node->now();
  387. }
  388. }
  389. void Multicaster::_add(void *tPtr,int64_t now,uint64_t nwid,const MulticastGroup &mg,MulticastGroupStatus &gs,const Address &member)
  390. {
  391. // assumes _groups_m is locked
  392. // Do not add self -- even if someone else returns it
  393. if (member == RR->identity.address())
  394. return;
  395. for(std::vector<MulticastGroupMember>::iterator m(gs.members.begin());m!=gs.members.end();++m) {
  396. if (m->address == member) {
  397. m->timestamp = now;
  398. return;
  399. }
  400. }
  401. gs.members.push_back(MulticastGroupMember(member,now));
  402. for(std::list<OutboundMulticast>::iterator tx(gs.txQueue.begin());tx!=gs.txQueue.end();) {
  403. if (tx->atLimit())
  404. gs.txQueue.erase(tx++);
  405. else {
  406. tx->sendIfNew(RR,tPtr,member);
  407. if (tx->atLimit())
  408. gs.txQueue.erase(tx++);
  409. else ++tx;
  410. }
  411. }
  412. }
  413. } // namespace ZeroTier