Multicaster.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406
  1. /*
  2. * ZeroTier One - Network Virtualization Everywhere
  3. * Copyright (C) 2011-2019 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(32)
  42. {
  43. }
  44. Multicaster::~Multicaster()
  45. {
  46. }
  47. void Multicaster::addMultiple(void *tPtr,int64_t now,uint64_t nwid,const MulticastGroup &mg,const void *addresses,unsigned int count,unsigned int totalKnown)
  48. {
  49. const unsigned char *p = (const unsigned char *)addresses;
  50. const unsigned char *e = p + (5 * count);
  51. Mutex::Lock _l(_groups_m);
  52. MulticastGroupStatus &gs = _groups[Multicaster::Key(nwid,mg)];
  53. while (p != e) {
  54. _add(tPtr,now,nwid,mg,gs,Address(p,5));
  55. p += 5;
  56. }
  57. }
  58. void Multicaster::remove(uint64_t nwid,const MulticastGroup &mg,const Address &member)
  59. {
  60. Mutex::Lock _l(_groups_m);
  61. MulticastGroupStatus *s = _groups.get(Multicaster::Key(nwid,mg));
  62. if (s) {
  63. for(std::vector<MulticastGroupMember>::iterator m(s->members.begin());m!=s->members.end();++m) {
  64. if (m->address == member) {
  65. s->members.erase(m);
  66. break;
  67. }
  68. }
  69. }
  70. }
  71. unsigned int Multicaster::gather(const Address &queryingPeer,uint64_t nwid,const MulticastGroup &mg,Buffer<ZT_PROTO_MAX_PACKET_LENGTH> &appendTo,unsigned int limit) const
  72. {
  73. unsigned char *p;
  74. unsigned int added = 0,i,k,rptr,totalKnown = 0;
  75. uint64_t a,picked[(ZT_PROTO_MAX_PACKET_LENGTH / 5) + 2];
  76. if (!limit)
  77. return 0;
  78. else if (limit > 0xffff)
  79. limit = 0xffff;
  80. const unsigned int totalAt = appendTo.size();
  81. appendTo.addSize(4); // sizeof(uint32_t)
  82. const unsigned int addedAt = appendTo.size();
  83. appendTo.addSize(2); // sizeof(uint16_t)
  84. { // Return myself if I am a member of this group
  85. SharedPtr<Network> network(RR->node->network(nwid));
  86. if ((network)&&(network->subscribedToMulticastGroup(mg,true))) {
  87. RR->identity.address().appendTo(appendTo);
  88. ++totalKnown;
  89. ++added;
  90. }
  91. }
  92. Mutex::Lock _l(_groups_m);
  93. const MulticastGroupStatus *s = _groups.get(Multicaster::Key(nwid,mg));
  94. if ((s)&&(!s->members.empty())) {
  95. totalKnown += (unsigned int)s->members.size();
  96. // Members are returned in random order so that repeated gather queries
  97. // will return different subsets of a large multicast group.
  98. k = 0;
  99. while ((added < limit)&&(k < s->members.size())&&((appendTo.size() + ZT_ADDRESS_LENGTH) <= ZT_PROTO_MAX_PACKET_LENGTH)) {
  100. rptr = (unsigned int)RR->node->prng();
  101. restart_member_scan:
  102. a = s->members[rptr % (unsigned int)s->members.size()].address.toInt();
  103. for(i=0;i<k;++i) {
  104. if (picked[i] == a) {
  105. ++rptr;
  106. goto restart_member_scan;
  107. }
  108. }
  109. picked[k++] = a;
  110. if (queryingPeer.toInt() != a) { // do not return the peer that is making the request as a result
  111. p = (unsigned char *)appendTo.appendField(ZT_ADDRESS_LENGTH);
  112. *(p++) = (unsigned char)((a >> 32) & 0xff);
  113. *(p++) = (unsigned char)((a >> 24) & 0xff);
  114. *(p++) = (unsigned char)((a >> 16) & 0xff);
  115. *(p++) = (unsigned char)((a >> 8) & 0xff);
  116. *p = (unsigned char)(a & 0xff);
  117. ++added;
  118. }
  119. }
  120. }
  121. appendTo.setAt(totalAt,(uint32_t)totalKnown);
  122. appendTo.setAt(addedAt,(uint16_t)added);
  123. return added;
  124. }
  125. std::vector<Address> Multicaster::getMembers(uint64_t nwid,const MulticastGroup &mg,unsigned int limit) const
  126. {
  127. std::vector<Address> ls;
  128. Mutex::Lock _l(_groups_m);
  129. const MulticastGroupStatus *s = _groups.get(Multicaster::Key(nwid,mg));
  130. if (!s)
  131. return ls;
  132. for(std::vector<MulticastGroupMember>::const_reverse_iterator m(s->members.rbegin());m!=s->members.rend();++m) {
  133. ls.push_back(m->address);
  134. if (ls.size() >= limit)
  135. break;
  136. }
  137. return ls;
  138. }
  139. void Multicaster::send(
  140. void *tPtr,
  141. int64_t now,
  142. const SharedPtr<Network> &network,
  143. const Address &origin,
  144. const MulticastGroup &mg,
  145. const MAC &src,
  146. unsigned int etherType,
  147. const void *data,
  148. unsigned int len)
  149. {
  150. unsigned long idxbuf[4096];
  151. unsigned long *indexes = idxbuf;
  152. try {
  153. Mutex::Lock _l(_groups_m);
  154. MulticastGroupStatus &gs = _groups[Multicaster::Key(network->id(),mg)];
  155. if (!gs.members.empty()) {
  156. // Allocate a memory buffer if group is monstrous
  157. if (gs.members.size() > (sizeof(idxbuf) / sizeof(unsigned long)))
  158. indexes = new unsigned long[gs.members.size()];
  159. // Generate a random permutation of member indexes
  160. for(unsigned long i=0;i<gs.members.size();++i)
  161. indexes[i] = i;
  162. for(unsigned long i=(unsigned long)gs.members.size()-1;i>0;--i) {
  163. unsigned long j = (unsigned long)RR->node->prng() % (i + 1);
  164. unsigned long tmp = indexes[j];
  165. indexes[j] = indexes[i];
  166. indexes[i] = tmp;
  167. }
  168. }
  169. Address activeBridges[ZT_MAX_NETWORK_SPECIALISTS];
  170. const unsigned int activeBridgeCount = network->config().activeBridges(activeBridges);
  171. const unsigned int limit = network->config().multicastLimit;
  172. if (gs.members.size() >= limit) {
  173. // Skip queue if we already have enough members to complete the send operation
  174. OutboundMulticast out;
  175. out.init(
  176. RR,
  177. now,
  178. network->id(),
  179. network->config().disableCompression(),
  180. limit,
  181. 1, // we'll still gather a little from peers to keep multicast list fresh
  182. src,
  183. mg,
  184. etherType,
  185. data,
  186. len);
  187. unsigned int count = 0;
  188. for(unsigned int i=0;i<activeBridgeCount;++i) {
  189. if ((activeBridges[i] != RR->identity.address())&&(activeBridges[i] != origin)) {
  190. out.sendOnly(RR,tPtr,activeBridges[i]); // optimization: don't use dedup log if it's a one-pass send
  191. if (++count >= limit)
  192. break;
  193. }
  194. }
  195. unsigned long idx = 0;
  196. while ((count < limit)&&(idx < gs.members.size())) {
  197. const Address ma(gs.members[indexes[idx++]].address);
  198. if ((std::find(activeBridges,activeBridges + activeBridgeCount,ma) == (activeBridges + activeBridgeCount))&&(ma != origin)) {
  199. out.sendOnly(RR,tPtr,ma); // optimization: don't use dedup log if it's a one-pass send
  200. ++count;
  201. }
  202. }
  203. } else {
  204. if (gs.txQueue.size() >= ZT_TX_QUEUE_SIZE) {
  205. RR->t->outgoingNetworkFrameDropped(tPtr,network,src,mg.mac(),etherType,0,len,"multicast TX queue is full");
  206. return;
  207. }
  208. const unsigned int gatherLimit = (limit - (unsigned int)gs.members.size()) + 1;
  209. if ((gs.members.empty())||((now - gs.lastExplicitGather) >= ZT_MULTICAST_EXPLICIT_GATHER_DELAY)) {
  210. gs.lastExplicitGather = now;
  211. Address explicitGatherPeers[16];
  212. unsigned int numExplicitGatherPeers = 0;
  213. explicitGatherPeers[numExplicitGatherPeers++] = network->controller();
  214. Address ac[ZT_MAX_NETWORK_SPECIALISTS];
  215. const unsigned int accnt = network->config().alwaysContactAddresses(ac);
  216. unsigned int shuffled[ZT_MAX_NETWORK_SPECIALISTS];
  217. for(unsigned int i=0;i<accnt;++i)
  218. shuffled[i] = i;
  219. for(unsigned int i=0,k=accnt>>1;i<k;++i) {
  220. const uint64_t x = RR->node->prng();
  221. const unsigned int x1 = shuffled[(unsigned int)x % accnt];
  222. const unsigned int x2 = shuffled[(unsigned int)(x >> 32) % accnt];
  223. const unsigned int tmp = shuffled[x1];
  224. shuffled[x1] = shuffled[x2];
  225. shuffled[x2] = tmp;
  226. }
  227. for(unsigned int i=0;i<accnt;++i) {
  228. explicitGatherPeers[numExplicitGatherPeers++] = ac[shuffled[i]];
  229. if (numExplicitGatherPeers == 16)
  230. break;
  231. }
  232. std::vector<Address> anchors(network->config().anchors());
  233. for(std::vector<Address>::const_iterator a(anchors.begin());a!=anchors.end();++a) {
  234. if (*a != RR->identity.address()) {
  235. explicitGatherPeers[numExplicitGatherPeers++] = *a;
  236. if (numExplicitGatherPeers == 16)
  237. break;
  238. }
  239. }
  240. for(unsigned int k=0;k<numExplicitGatherPeers;++k) {
  241. const CertificateOfMembership *com = (network) ? ((network->config().com) ? &(network->config().com) : (const CertificateOfMembership *)0) : (const CertificateOfMembership *)0;
  242. Packet outp(explicitGatherPeers[k],RR->identity.address(),Packet::VERB_MULTICAST_GATHER);
  243. outp.append(network->id());
  244. outp.append((uint8_t)((com) ? 0x01 : 0x00));
  245. mg.mac().appendTo(outp);
  246. outp.append((uint32_t)mg.adi());
  247. outp.append((uint32_t)gatherLimit);
  248. if (com)
  249. com->serialize(outp);
  250. RR->node->expectReplyTo(outp.packetId());
  251. RR->sw->send(tPtr,outp,true);
  252. }
  253. }
  254. gs.txQueue.push_back(OutboundMulticast());
  255. OutboundMulticast &out = gs.txQueue.back();
  256. out.init(
  257. RR,
  258. now,
  259. network->id(),
  260. network->config().disableCompression(),
  261. limit,
  262. gatherLimit,
  263. src,
  264. mg,
  265. etherType,
  266. data,
  267. len);
  268. if (origin)
  269. out.logAsSent(origin);
  270. unsigned int count = 0;
  271. for(unsigned int i=0;i<activeBridgeCount;++i) {
  272. if (activeBridges[i] != RR->identity.address()) {
  273. out.sendAndLog(RR,tPtr,activeBridges[i]);
  274. if (++count >= limit)
  275. break;
  276. }
  277. }
  278. unsigned long idx = 0;
  279. while ((count < limit)&&(idx < gs.members.size())) {
  280. Address ma(gs.members[indexes[idx++]].address);
  281. if (std::find(activeBridges,activeBridges + activeBridgeCount,ma) == (activeBridges + activeBridgeCount)) {
  282. out.sendAndLog(RR,tPtr,ma);
  283. ++count;
  284. }
  285. }
  286. }
  287. } catch ( ... ) {} // this is a sanity check to catch any failures and make sure indexes[] still gets deleted
  288. // Free allocated memory buffer if any
  289. if (indexes != idxbuf)
  290. delete [] indexes;
  291. }
  292. void Multicaster::clean(int64_t now)
  293. {
  294. {
  295. Mutex::Lock _l(_groups_m);
  296. Multicaster::Key *k = (Multicaster::Key *)0;
  297. MulticastGroupStatus *s = (MulticastGroupStatus *)0;
  298. Hashtable<Multicaster::Key,MulticastGroupStatus>::Iterator mm(_groups);
  299. while (mm.next(k,s)) {
  300. for(std::list<OutboundMulticast>::iterator tx(s->txQueue.begin());tx!=s->txQueue.end();) {
  301. if ((tx->expired(now))||(tx->atLimit()))
  302. s->txQueue.erase(tx++);
  303. else ++tx;
  304. }
  305. unsigned long count = 0;
  306. {
  307. std::vector<MulticastGroupMember>::iterator reader(s->members.begin());
  308. std::vector<MulticastGroupMember>::iterator writer(reader);
  309. while (reader != s->members.end()) {
  310. if ((now - reader->timestamp) < ZT_MULTICAST_LIKE_EXPIRE) {
  311. *writer = *reader;
  312. ++writer;
  313. ++count;
  314. }
  315. ++reader;
  316. }
  317. }
  318. if (count) {
  319. s->members.resize(count);
  320. } else if (s->txQueue.empty()) {
  321. _groups.erase(*k);
  322. } else {
  323. s->members.clear();
  324. }
  325. }
  326. }
  327. }
  328. void Multicaster::_add(void *tPtr,int64_t now,uint64_t nwid,const MulticastGroup &mg,MulticastGroupStatus &gs,const Address &member)
  329. {
  330. // assumes _groups_m is locked
  331. // Do not add self -- even if someone else returns it
  332. if (member == RR->identity.address())
  333. return;
  334. std::vector<MulticastGroupMember>::iterator m(std::lower_bound(gs.members.begin(),gs.members.end(),member));
  335. if (m != gs.members.end()) {
  336. if (m->address == member) {
  337. m->timestamp = now;
  338. return;
  339. }
  340. gs.members.insert(m,MulticastGroupMember(member,now));
  341. } else {
  342. gs.members.push_back(MulticastGroupMember(member,now));
  343. }
  344. for(std::list<OutboundMulticast>::iterator tx(gs.txQueue.begin());tx!=gs.txQueue.end();) {
  345. if (tx->atLimit())
  346. gs.txQueue.erase(tx++);
  347. else {
  348. tx->sendIfNew(RR,tPtr,member);
  349. if (tx->atLimit())
  350. gs.txQueue.erase(tx++);
  351. else ++tx;
  352. }
  353. }
  354. }
  355. } // namespace ZeroTier