Multicaster.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388
  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 "NodeConfig.hpp"
  39. #include "CertificateOfMembership.hpp"
  40. #include "Logger.hpp"
  41. namespace ZeroTier {
  42. Multicaster::Multicaster(const RuntimeEnvironment *renv) :
  43. RR(renv)
  44. {
  45. }
  46. Multicaster::~Multicaster()
  47. {
  48. }
  49. void Multicaster::addMultiple(uint64_t now,uint64_t nwid,const MulticastGroup &mg,const void *addresses,unsigned int count,unsigned int totalKnown)
  50. {
  51. const unsigned char *p = (const unsigned char *)addresses;
  52. const unsigned char *e = p + (5 * count);
  53. Mutex::Lock _l(_groups_m);
  54. MulticastGroupStatus &gs = _groups[std::pair<uint64_t,MulticastGroup>(nwid,mg)];
  55. while (p != e) {
  56. _add(now,nwid,mg,gs,Address(p,5));
  57. p += 5;
  58. }
  59. }
  60. unsigned int Multicaster::gather(const Address &queryingPeer,uint64_t nwid,const MulticastGroup &mg,Packet &appendTo,unsigned int limit) const
  61. {
  62. unsigned char *p;
  63. unsigned int added = 0,i,k,rptr,totalKnown = 0;
  64. uint64_t a,picked[(ZT_PROTO_MAX_PACKET_LENGTH / 5) + 2];
  65. if (!limit)
  66. return 0;
  67. else if (limit > 0xffff)
  68. limit = 0xffff;
  69. const unsigned int totalAt = appendTo.size();
  70. appendTo.addSize(4); // sizeof(uint32_t)
  71. const unsigned int addedAt = appendTo.size();
  72. appendTo.addSize(2); // sizeof(uint16_t)
  73. { // Return myself if I am a member of this group
  74. SharedPtr<Network> network(RR->nc->network(nwid));
  75. if ((network)&&(network->subscribedToMulticastGroup(mg))) {
  76. RR->identity.address().appendTo(appendTo);
  77. ++totalKnown;
  78. ++added;
  79. }
  80. }
  81. Mutex::Lock _l(_groups_m);
  82. std::map< std::pair<uint64_t,MulticastGroup>,MulticastGroupStatus >::const_iterator gs(_groups.find(std::pair<uint64_t,MulticastGroup>(nwid,mg)));
  83. if ((gs != _groups.end())&&(!gs->second.members.empty())) {
  84. totalKnown += (unsigned int)gs->second.members.size();
  85. // Members are returned in random order so that repeated gather queries
  86. // will return different subsets of a large multicast group.
  87. k = 0;
  88. while ((added < limit)&&(k < gs->second.members.size())&&((appendTo.size() + ZT_ADDRESS_LENGTH) <= ZT_UDP_DEFAULT_PAYLOAD_MTU)) {
  89. rptr = (unsigned int)RR->prng->next32();
  90. restart_member_scan:
  91. a = gs->second.members[rptr % (unsigned int)gs->second.members.size()].address.toInt();
  92. for(i=0;i<k;++i) {
  93. if (picked[i] == a) {
  94. ++rptr;
  95. goto restart_member_scan;
  96. }
  97. }
  98. picked[k++] = a;
  99. if (queryingPeer.toInt() != a) { // do not return the peer that is making the request as a result
  100. p = (unsigned char *)appendTo.appendField(ZT_ADDRESS_LENGTH);
  101. *(p++) = (unsigned char)((a >> 32) & 0xff);
  102. *(p++) = (unsigned char)((a >> 24) & 0xff);
  103. *(p++) = (unsigned char)((a >> 16) & 0xff);
  104. *(p++) = (unsigned char)((a >> 8) & 0xff);
  105. *p = (unsigned char)(a & 0xff);
  106. ++added;
  107. }
  108. }
  109. }
  110. appendTo.setAt(totalAt,(uint32_t)totalKnown);
  111. appendTo.setAt(addedAt,(uint16_t)added);
  112. //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());
  113. return added;
  114. }
  115. std::vector<Address> Multicaster::getMembers(uint64_t nwid,const MulticastGroup &mg,unsigned int limit) const
  116. {
  117. std::vector<Address> ls;
  118. Mutex::Lock _l(_groups_m);
  119. std::map< std::pair<uint64_t,MulticastGroup>,MulticastGroupStatus >::const_iterator gs(_groups.find(std::pair<uint64_t,MulticastGroup>(nwid,mg)));
  120. if (gs == _groups.end())
  121. return ls;
  122. for(std::vector<MulticastGroupMember>::const_reverse_iterator m(gs->second.members.rbegin());m!=gs->second.members.rend();++m) {
  123. ls.push_back(m->address);
  124. if (ls.size() >= limit)
  125. break;
  126. }
  127. return ls;
  128. }
  129. void Multicaster::send(
  130. const CertificateOfMembership *com,
  131. unsigned int limit,
  132. uint64_t now,
  133. uint64_t nwid,
  134. const std::vector<Address> &alwaysSendTo,
  135. const MulticastGroup &mg,
  136. const MAC &src,
  137. unsigned int etherType,
  138. const void *data,
  139. unsigned int len)
  140. {
  141. unsigned long idxbuf[8194];
  142. unsigned long *indexes = idxbuf;
  143. Mutex::Lock _l(_groups_m);
  144. MulticastGroupStatus &gs = _groups[std::pair<uint64_t,MulticastGroup>(nwid,mg)];
  145. if (!gs.members.empty()) {
  146. // Allocate a memory buffer if group is monstrous
  147. if (gs.members.size() > (sizeof(idxbuf) / sizeof(unsigned long)))
  148. indexes = new unsigned long[gs.members.size()];
  149. // Generate a random permutation of member indexes
  150. for(unsigned long i=0;i<gs.members.size();++i)
  151. indexes[i] = i;
  152. for(unsigned long i=(unsigned long)gs.members.size()-1;i>0;--i) {
  153. unsigned long j = RR->prng->next32() % (i + 1);
  154. unsigned long tmp = indexes[j];
  155. indexes[j] = indexes[i];
  156. indexes[i] = tmp;
  157. }
  158. }
  159. if (gs.members.size() >= limit) {
  160. // Skip queue if we already have enough members to complete the send operation
  161. OutboundMulticast out;
  162. out.init(
  163. RR,
  164. now,
  165. nwid,
  166. com,
  167. limit,
  168. 1, // we'll still gather a little from peers to keep multicast list fresh
  169. src,
  170. mg,
  171. etherType,
  172. data,
  173. len);
  174. unsigned int count = 0;
  175. for(std::vector<Address>::const_iterator ast(alwaysSendTo.begin());ast!=alwaysSendTo.end();++ast) {
  176. out.sendOnly(RR,*ast);
  177. if (++count >= limit)
  178. break;
  179. }
  180. unsigned long idx = 0;
  181. while ((count < limit)&&(idx < gs.members.size())) {
  182. Address ma(gs.members[indexes[idx++]].address);
  183. if (std::find(alwaysSendTo.begin(),alwaysSendTo.end(),ma) == alwaysSendTo.end()) {
  184. out.sendOnly(RR,ma);
  185. ++count;
  186. }
  187. }
  188. } else {
  189. unsigned int gatherLimit = (limit - (unsigned int)gs.members.size()) + 1;
  190. if ((now - gs.lastExplicitGather) >= ZT_MULTICAST_EXPLICIT_GATHER_DELAY) {
  191. gs.lastExplicitGather = now;
  192. SharedPtr<Peer> sn(RR->topology->getBestSupernode());
  193. if (sn) {
  194. TRACE(">>MC upstream GATHER up to %u for group %.16llx/%s",gatherLimit,nwid,mg.toString().c_str());
  195. Packet outp(sn->address(),RR->identity.address(),Packet::VERB_MULTICAST_GATHER);
  196. outp.append(nwid);
  197. outp.append((uint8_t)0);
  198. mg.mac().appendTo(outp);
  199. outp.append((uint32_t)mg.adi());
  200. outp.append((uint32_t)gatherLimit);
  201. outp.armor(sn->key(),true);
  202. sn->send(RR,outp.data(),outp.size(),now);
  203. }
  204. gatherLimit = 0;
  205. }
  206. gs.txQueue.push_back(OutboundMulticast());
  207. OutboundMulticast &out = gs.txQueue.back();
  208. out.init(
  209. RR,
  210. now,
  211. nwid,
  212. com,
  213. limit,
  214. gatherLimit,
  215. src,
  216. mg,
  217. etherType,
  218. data,
  219. len);
  220. unsigned int count = 0;
  221. for(std::vector<Address>::const_iterator ast(alwaysSendTo.begin());ast!=alwaysSendTo.end();++ast) {
  222. out.sendAndLog(RR,*ast);
  223. if (++count >= limit)
  224. break;
  225. }
  226. unsigned long idx = 0;
  227. while ((count < limit)&&(idx < gs.members.size())) {
  228. Address ma(gs.members[indexes[idx++]].address);
  229. if (std::find(alwaysSendTo.begin(),alwaysSendTo.end(),ma) == alwaysSendTo.end()) {
  230. out.sendAndLog(RR,ma);
  231. ++count;
  232. }
  233. }
  234. }
  235. // Free allocated memory buffer if any
  236. if (indexes != idxbuf)
  237. delete [] indexes;
  238. #ifdef ZT_SUPPORT_LEGACY_MULTICAST
  239. // This sends a P5 multicast up to our supernode, who then
  240. // redistributes it manually down to all <1.0.0 peers for
  241. // legacy support. These peers don't support the new multicast
  242. // frame type, so even if they receive it they will ignore it.
  243. {
  244. SharedPtr<Peer> sn(RR->topology->getBestSupernode());
  245. if (sn) {
  246. uint32_t rn = RR->prng->next32();
  247. Packet outp(sn->address(),RR->identity.address(),Packet::VERB_P5_MULTICAST_FRAME);
  248. outp.append((uint16_t)0xffff); // do not forward
  249. outp.append((unsigned char)0,320 + 1024); // empty queue and bloom filter
  250. outp.append((unsigned char)((com) ? ZT_PROTO_VERB_P5_MULTICAST_FRAME_FLAGS_HAS_MEMBERSHIP_CERTIFICATE : 0));
  251. outp.append((uint64_t)nwid);
  252. outp.append((uint16_t)0);
  253. outp.append((unsigned char)0);
  254. outp.append((unsigned char)0);
  255. RR->identity.address().appendTo(outp);
  256. outp.append((const void *)&rn,3); // random multicast ID
  257. if (src)
  258. src.appendTo(outp);
  259. else MAC(RR->identity.address(),nwid).appendTo(outp);
  260. mg.mac().appendTo(outp);
  261. outp.append((uint32_t)mg.adi());
  262. outp.append((uint16_t)etherType);
  263. outp.append((uint16_t)len);
  264. outp.append(data,len);
  265. unsigned int signedPortionLen = outp.size() - ZT_PROTO_VERB_P5_MULTICAST_FRAME_IDX__START_OF_SIGNED_PORTION;
  266. C25519::Signature sig(RR->identity.sign(outp.field(ZT_PROTO_VERB_P5_MULTICAST_FRAME_IDX__START_OF_SIGNED_PORTION,signedPortionLen),signedPortionLen));
  267. outp.append((uint16_t)sig.size());
  268. outp.append(sig.data,(unsigned int)sig.size());
  269. if (com) com->serialize(outp);
  270. outp.compress();
  271. outp.armor(sn->key(),true);
  272. sn->send(RR,outp.data(),outp.size(),now);
  273. }
  274. }
  275. #endif // ZT_SUPPORT_LEGACY_MULTICAST
  276. }
  277. void Multicaster::clean(uint64_t now)
  278. {
  279. Mutex::Lock _l(_groups_m);
  280. for(std::map< std::pair<uint64_t,MulticastGroup>,MulticastGroupStatus >::iterator mm(_groups.begin());mm!=_groups.end();) {
  281. for(std::list<OutboundMulticast>::iterator tx(mm->second.txQueue.begin());tx!=mm->second.txQueue.end();) {
  282. if ((tx->expired(now))||(tx->atLimit()))
  283. mm->second.txQueue.erase(tx++);
  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::list<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. gs.txQueue.erase(tx++);
  331. else ++tx;
  332. }
  333. }
  334. }
  335. } // namespace ZeroTier