Multicaster.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390
  1. /*
  2. * ZeroTier One - Network Virtualization Everywhere
  3. * Copyright (C) 2011-2015 ZeroTier, Inc.
  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. * ZeroTier may be used and distributed under the terms of the GPLv3, which
  21. * are available at: http://www.gnu.org/licenses/gpl-3.0.html
  22. *
  23. * If you would like to embed ZeroTier into a commercial application or
  24. * redistribute it in a modified binary form, please contact ZeroTier Networks
  25. * LLC. Start here: http://www.zerotier.com/
  26. */
  27. #include <algorithm>
  28. #include "Constants.hpp"
  29. #include "RuntimeEnvironment.hpp"
  30. #include "SharedPtr.hpp"
  31. #include "Multicaster.hpp"
  32. #include "Topology.hpp"
  33. #include "Switch.hpp"
  34. #include "Packet.hpp"
  35. #include "Peer.hpp"
  36. #include "CMWC4096.hpp"
  37. #include "C25519.hpp"
  38. #include "CertificateOfMembership.hpp"
  39. namespace ZeroTier {
  40. Multicaster::Multicaster(const RuntimeEnvironment *renv) :
  41. RR(renv)
  42. {
  43. }
  44. Multicaster::~Multicaster()
  45. {
  46. }
  47. void Multicaster::addMultiple(uint64_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[std::pair<uint64_t,MulticastGroup>(nwid,mg)];
  53. while (p != e) {
  54. _add(now,nwid,mg,gs,Address(p,5));
  55. p += 5;
  56. }
  57. }
  58. unsigned int Multicaster::gather(const Address &queryingPeer,uint64_t nwid,const MulticastGroup &mg,Packet &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. std::map< std::pair<uint64_t,MulticastGroup>,MulticastGroupStatus >::const_iterator gs(_groups.find(std::pair<uint64_t,MulticastGroup>(nwid,mg)));
  81. if ((gs != _groups.end())&&(!gs->second.members.empty())) {
  82. totalKnown += (unsigned int)gs->second.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 < gs->second.members.size())&&((appendTo.size() + ZT_ADDRESS_LENGTH) <= ZT_UDP_DEFAULT_PAYLOAD_MTU)) {
  87. rptr = (unsigned int)RR->prng->next32();
  88. restart_member_scan:
  89. a = gs->second.members[rptr % (unsigned int)gs->second.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. //TRACE("..MC Multicaster::gather() attached %u of %u peers for %.16llx/%s (2)",n,(unsigned int)(gs->second.members.size() - skipped),nwid,mg.toString().c_str());
  111. return added;
  112. }
  113. std::vector<Address> Multicaster::getMembers(uint64_t nwid,const MulticastGroup &mg,unsigned int limit) const
  114. {
  115. std::vector<Address> ls;
  116. Mutex::Lock _l(_groups_m);
  117. std::map< std::pair<uint64_t,MulticastGroup>,MulticastGroupStatus >::const_iterator gs(_groups.find(std::pair<uint64_t,MulticastGroup>(nwid,mg)));
  118. if (gs == _groups.end())
  119. return ls;
  120. for(std::vector<MulticastGroupMember>::const_reverse_iterator m(gs->second.members.rbegin());m!=gs->second.members.rend();++m) {
  121. ls.push_back(m->address);
  122. if (ls.size() >= limit)
  123. break;
  124. }
  125. return ls;
  126. }
  127. void Multicaster::send(
  128. const CertificateOfMembership *com,
  129. unsigned int limit,
  130. uint64_t now,
  131. uint64_t nwid,
  132. const std::vector<Address> &alwaysSendTo,
  133. const MulticastGroup &mg,
  134. const MAC &src,
  135. unsigned int etherType,
  136. const void *data,
  137. unsigned int len)
  138. {
  139. unsigned long idxbuf[8194];
  140. unsigned long *indexes = idxbuf;
  141. Mutex::Lock _l(_groups_m);
  142. MulticastGroupStatus &gs = _groups[std::pair<uint64_t,MulticastGroup>(nwid,mg)];
  143. if (!gs.members.empty()) {
  144. // Allocate a memory buffer if group is monstrous
  145. if (gs.members.size() > (sizeof(idxbuf) / sizeof(unsigned long)))
  146. indexes = new unsigned long[gs.members.size()];
  147. // Generate a random permutation of member indexes
  148. for(unsigned long i=0;i<gs.members.size();++i)
  149. indexes[i] = i;
  150. for(unsigned long i=(unsigned long)gs.members.size()-1;i>0;--i) {
  151. unsigned long j = RR->prng->next32() % (i + 1);
  152. unsigned long tmp = indexes[j];
  153. indexes[j] = indexes[i];
  154. indexes[i] = tmp;
  155. }
  156. }
  157. if (gs.members.size() >= limit) {
  158. // Skip queue if we already have enough members to complete the send operation
  159. OutboundMulticast out;
  160. out.init(
  161. RR,
  162. now,
  163. nwid,
  164. com,
  165. limit,
  166. 1, // we'll still gather a little from peers to keep multicast list fresh
  167. src,
  168. mg,
  169. etherType,
  170. data,
  171. len);
  172. unsigned int count = 0;
  173. for(std::vector<Address>::const_iterator ast(alwaysSendTo.begin());ast!=alwaysSendTo.end();++ast) {
  174. out.sendOnly(RR,*ast);
  175. if (++count >= limit)
  176. break;
  177. }
  178. unsigned long idx = 0;
  179. while ((count < limit)&&(idx < gs.members.size())) {
  180. Address ma(gs.members[indexes[idx++]].address);
  181. if (std::find(alwaysSendTo.begin(),alwaysSendTo.end(),ma) == alwaysSendTo.end()) {
  182. out.sendOnly(RR,ma);
  183. ++count;
  184. }
  185. }
  186. } else {
  187. unsigned int gatherLimit = (limit - (unsigned int)gs.members.size()) + 1;
  188. if ((now - gs.lastExplicitGather) >= ZT_MULTICAST_EXPLICIT_GATHER_DELAY) {
  189. gs.lastExplicitGather = now;
  190. SharedPtr<Peer> sn(RR->topology->getBestSupernode());
  191. if (sn) {
  192. TRACE(">>MC upstream GATHER up to %u for group %.16llx/%s",gatherLimit,nwid,mg.toString().c_str());
  193. Packet outp(sn->address(),RR->identity.address(),Packet::VERB_MULTICAST_GATHER);
  194. outp.append(nwid);
  195. outp.append((uint8_t)0);
  196. mg.mac().appendTo(outp);
  197. outp.append((uint32_t)mg.adi());
  198. outp.append((uint32_t)gatherLimit);
  199. outp.armor(sn->key(),true);
  200. sn->send(RR,outp.data(),outp.size(),now);
  201. }
  202. gatherLimit = 0;
  203. }
  204. gs.txQueue.push_back(OutboundMulticast());
  205. OutboundMulticast &out = gs.txQueue.back();
  206. out.init(
  207. RR,
  208. now,
  209. nwid,
  210. com,
  211. limit,
  212. gatherLimit,
  213. src,
  214. mg,
  215. etherType,
  216. data,
  217. len);
  218. unsigned int count = 0;
  219. for(std::vector<Address>::const_iterator ast(alwaysSendTo.begin());ast!=alwaysSendTo.end();++ast) {
  220. out.sendAndLog(RR,*ast);
  221. if (++count >= limit)
  222. break;
  223. }
  224. unsigned long idx = 0;
  225. while ((count < limit)&&(idx < gs.members.size())) {
  226. Address ma(gs.members[indexes[idx++]].address);
  227. if (std::find(alwaysSendTo.begin(),alwaysSendTo.end(),ma) == alwaysSendTo.end()) {
  228. out.sendAndLog(RR,ma);
  229. ++count;
  230. }
  231. }
  232. }
  233. // Free allocated memory buffer if any
  234. if (indexes != idxbuf)
  235. delete [] indexes;
  236. #ifdef ZT_SUPPORT_LEGACY_MULTICAST
  237. // This sends a P5 multicast up to our supernode, who then
  238. // redistributes it manually down to all <1.0.0 peers for
  239. // legacy support. These peers don't support the new multicast
  240. // frame type, so even if they receive it they will ignore it.
  241. {
  242. SharedPtr<Peer> sn(RR->topology->getBestSupernode());
  243. if (sn) {
  244. uint32_t rn = RR->prng->next32();
  245. Packet outp(sn->address(),RR->identity.address(),Packet::VERB_P5_MULTICAST_FRAME);
  246. outp.append((uint16_t)0xffff); // do not forward
  247. outp.append((unsigned char)0,320 + 1024); // empty queue and bloom filter
  248. outp.append((unsigned char)((com) ? ZT_PROTO_VERB_P5_MULTICAST_FRAME_FLAGS_HAS_MEMBERSHIP_CERTIFICATE : 0));
  249. outp.append((uint64_t)nwid);
  250. outp.append((uint16_t)0);
  251. outp.append((unsigned char)0);
  252. outp.append((unsigned char)0);
  253. RR->identity.address().appendTo(outp);
  254. outp.append((const void *)&rn,3); // random multicast ID
  255. if (src)
  256. src.appendTo(outp);
  257. else MAC(RR->identity.address(),nwid).appendTo(outp);
  258. mg.mac().appendTo(outp);
  259. outp.append((uint32_t)mg.adi());
  260. outp.append((uint16_t)etherType);
  261. outp.append((uint16_t)len);
  262. outp.append(data,len);
  263. unsigned int signedPortionLen = outp.size() - ZT_PROTO_VERB_P5_MULTICAST_FRAME_IDX__START_OF_SIGNED_PORTION;
  264. C25519::Signature sig(RR->identity.sign(outp.field(ZT_PROTO_VERB_P5_MULTICAST_FRAME_IDX__START_OF_SIGNED_PORTION,signedPortionLen),signedPortionLen));
  265. outp.append((uint16_t)sig.size());
  266. outp.append(sig.data,(unsigned int)sig.size());
  267. if (com) com->serialize(outp);
  268. outp.compress();
  269. outp.armor(sn->key(),true);
  270. sn->send(RR,outp.data(),outp.size(),now);
  271. }
  272. }
  273. #endif // ZT_SUPPORT_LEGACY_MULTICAST
  274. }
  275. void Multicaster::clean(uint64_t now)
  276. {
  277. Mutex::Lock _l(_groups_m);
  278. for(std::map< std::pair<uint64_t,MulticastGroup>,MulticastGroupStatus >::iterator mm(_groups.begin());mm!=_groups.end();) {
  279. for(std::vector<OutboundMulticast>::iterator tx(mm->second.txQueue.begin());tx!=mm->second.txQueue.end();) {
  280. if ((tx->expired(now))||(tx->atLimit())) {
  281. // erase element (replace by last)
  282. *tx = mm->second.txQueue.back();
  283. mm->second.txQueue.pop_back();
  284. } else ++tx;
  285. }
  286. unsigned long count = 0;
  287. {
  288. std::vector<MulticastGroupMember>::iterator reader(mm->second.members.begin());
  289. std::vector<MulticastGroupMember>::iterator writer(reader);
  290. while (reader != mm->second.members.end()) {
  291. if ((now - reader->timestamp) < ZT_MULTICAST_LIKE_EXPIRE) {
  292. *writer = *reader;
  293. ++writer;
  294. ++count;
  295. }
  296. ++reader;
  297. }
  298. }
  299. if (count) {
  300. mm->second.members.resize(count);
  301. ++mm;
  302. } else if (mm->second.txQueue.empty()) {
  303. _groups.erase(mm++);
  304. } else {
  305. mm->second.members.clear();
  306. ++mm;
  307. }
  308. }
  309. }
  310. void Multicaster::_add(uint64_t now,uint64_t nwid,const MulticastGroup &mg,MulticastGroupStatus &gs,const Address &member)
  311. {
  312. // assumes _groups_m is locked
  313. // Do not add self -- even if someone else returns it
  314. if (member == RR->identity.address())
  315. return;
  316. for(std::vector<MulticastGroupMember>::iterator m(gs.members.begin());m!=gs.members.end();++m) {
  317. if (m->address == member) {
  318. m->timestamp = now;
  319. return;
  320. }
  321. }
  322. gs.members.push_back(MulticastGroupMember(member,now));
  323. //TRACE("..MC %s joined multicast group %.16llx/%s via %s",member.toString().c_str(),nwid,mg.toString().c_str(),((learnedFrom) ? learnedFrom.toString().c_str() : "(direct)"));
  324. for(std::vector<OutboundMulticast>::iterator tx(gs.txQueue.begin());tx!=gs.txQueue.end();) {
  325. if (tx->atLimit()) {
  326. gs.txQueue.erase(tx++);
  327. } else {
  328. tx->sendIfNew(RR,member);
  329. if (tx->atLimit()) {
  330. // erase element (replace by last)
  331. *tx = gs.txQueue.back();
  332. gs.txQueue.pop_back();
  333. } else ++tx;
  334. }
  335. }
  336. }
  337. } // namespace ZeroTier