Multicaster.cpp 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354
  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 "C25519.hpp"
  37. #include "CertificateOfMembership.hpp"
  38. namespace ZeroTier {
  39. Multicaster::Multicaster(const RuntimeEnvironment *renv) :
  40. RR(renv)
  41. {
  42. }
  43. Multicaster::~Multicaster()
  44. {
  45. }
  46. void Multicaster::addMultiple(uint64_t now,uint64_t nwid,const MulticastGroup &mg,const void *addresses,unsigned int count,unsigned int totalKnown)
  47. {
  48. const unsigned char *p = (const unsigned char *)addresses;
  49. const unsigned char *e = p + (5 * count);
  50. Mutex::Lock _l(_groups_m);
  51. MulticastGroupStatus &gs = _groups[std::pair<uint64_t,MulticastGroup>(nwid,mg)];
  52. while (p != e) {
  53. _add(now,nwid,mg,gs,Address(p,5));
  54. p += 5;
  55. }
  56. }
  57. void Multicaster::remove(uint64_t nwid,const MulticastGroup &mg,const Address &member)
  58. {
  59. Mutex::Lock _l(_groups_m);
  60. std::map< std::pair<uint64_t,MulticastGroup>,MulticastGroupStatus >::iterator g(_groups.find(std::pair<uint64_t,MulticastGroup>(nwid,mg)));
  61. if (g != _groups.end()) {
  62. for(std::vector<MulticastGroupMember>::iterator m(g->second.members.begin());m!=g->second.members.end();++m) {
  63. if (m->address == member) {
  64. g->second.members.erase(m);
  65. break;
  66. }
  67. }
  68. }
  69. }
  70. unsigned int Multicaster::gather(const Address &queryingPeer,uint64_t nwid,const MulticastGroup &mg,Packet &appendTo,unsigned int limit) const
  71. {
  72. unsigned char *p;
  73. unsigned int added = 0,i,k,rptr,totalKnown = 0;
  74. uint64_t a,picked[(ZT_PROTO_MAX_PACKET_LENGTH / 5) + 2];
  75. if (!limit)
  76. return 0;
  77. else if (limit > 0xffff)
  78. limit = 0xffff;
  79. const unsigned int totalAt = appendTo.size();
  80. appendTo.addSize(4); // sizeof(uint32_t)
  81. const unsigned int addedAt = appendTo.size();
  82. appendTo.addSize(2); // sizeof(uint16_t)
  83. { // Return myself if I am a member of this group
  84. SharedPtr<Network> network(RR->node->network(nwid));
  85. if ((network)&&(network->subscribedToMulticastGroup(mg,true))) {
  86. RR->identity.address().appendTo(appendTo);
  87. ++totalKnown;
  88. ++added;
  89. }
  90. }
  91. Mutex::Lock _l(_groups_m);
  92. std::map< std::pair<uint64_t,MulticastGroup>,MulticastGroupStatus >::const_iterator gs(_groups.find(std::pair<uint64_t,MulticastGroup>(nwid,mg)));
  93. if ((gs != _groups.end())&&(!gs->second.members.empty())) {
  94. totalKnown += (unsigned int)gs->second.members.size();
  95. // Members are returned in random order so that repeated gather queries
  96. // will return different subsets of a large multicast group.
  97. k = 0;
  98. while ((added < limit)&&(k < gs->second.members.size())&&((appendTo.size() + ZT_ADDRESS_LENGTH) <= ZT_UDP_DEFAULT_PAYLOAD_MTU)) {
  99. rptr = (unsigned int)RR->node->prng();
  100. restart_member_scan:
  101. a = gs->second.members[rptr % (unsigned int)gs->second.members.size()].address.toInt();
  102. for(i=0;i<k;++i) {
  103. if (picked[i] == a) {
  104. ++rptr;
  105. goto restart_member_scan;
  106. }
  107. }
  108. picked[k++] = a;
  109. if (queryingPeer.toInt() != a) { // do not return the peer that is making the request as a result
  110. p = (unsigned char *)appendTo.appendField(ZT_ADDRESS_LENGTH);
  111. *(p++) = (unsigned char)((a >> 32) & 0xff);
  112. *(p++) = (unsigned char)((a >> 24) & 0xff);
  113. *(p++) = (unsigned char)((a >> 16) & 0xff);
  114. *(p++) = (unsigned char)((a >> 8) & 0xff);
  115. *p = (unsigned char)(a & 0xff);
  116. ++added;
  117. }
  118. }
  119. }
  120. appendTo.setAt(totalAt,(uint32_t)totalKnown);
  121. appendTo.setAt(addedAt,(uint16_t)added);
  122. //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());
  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. std::map< std::pair<uint64_t,MulticastGroup>,MulticastGroupStatus >::const_iterator gs(_groups.find(std::pair<uint64_t,MulticastGroup>(nwid,mg)));
  130. if (gs == _groups.end())
  131. return ls;
  132. for(std::vector<MulticastGroupMember>::const_reverse_iterator m(gs->second.members.rbegin());m!=gs->second.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. const CertificateOfMembership *com,
  141. unsigned int limit,
  142. uint64_t now,
  143. uint64_t nwid,
  144. const std::vector<Address> &alwaysSendTo,
  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[8194];
  152. unsigned long *indexes = idxbuf;
  153. Mutex::Lock _l(_groups_m);
  154. MulticastGroupStatus &gs = _groups[std::pair<uint64_t,MulticastGroup>(nwid,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. if (gs.members.size() >= limit) {
  170. // Skip queue if we already have enough members to complete the send operation
  171. OutboundMulticast out;
  172. out.init(
  173. RR,
  174. now,
  175. nwid,
  176. com,
  177. limit,
  178. 1, // we'll still gather a little from peers to keep multicast list fresh
  179. src,
  180. mg,
  181. etherType,
  182. data,
  183. len);
  184. unsigned int count = 0;
  185. for(std::vector<Address>::const_iterator ast(alwaysSendTo.begin());ast!=alwaysSendTo.end();++ast) {
  186. out.sendOnly(RR,*ast);
  187. if (++count >= limit)
  188. break;
  189. }
  190. unsigned long idx = 0;
  191. while ((count < limit)&&(idx < gs.members.size())) {
  192. Address ma(gs.members[indexes[idx++]].address);
  193. if (std::find(alwaysSendTo.begin(),alwaysSendTo.end(),ma) == alwaysSendTo.end()) {
  194. out.sendOnly(RR,ma);
  195. ++count;
  196. }
  197. }
  198. } else {
  199. unsigned int gatherLimit = (limit - (unsigned int)gs.members.size()) + 1;
  200. if ((now - gs.lastExplicitGather) >= ZT_MULTICAST_EXPLICIT_GATHER_DELAY) {
  201. gs.lastExplicitGather = now;
  202. SharedPtr<Peer> sn(RR->topology->getBestRoot());
  203. if (sn) {
  204. TRACE(">>MC upstream GATHER up to %u for group %.16llx/%s",gatherLimit,nwid,mg.toString().c_str());
  205. Packet outp(sn->address(),RR->identity.address(),Packet::VERB_MULTICAST_GATHER);
  206. outp.append(nwid);
  207. outp.append((uint8_t)0);
  208. mg.mac().appendTo(outp);
  209. outp.append((uint32_t)mg.adi());
  210. outp.append((uint32_t)gatherLimit);
  211. outp.armor(sn->key(),true);
  212. sn->send(RR,outp.data(),outp.size(),now);
  213. }
  214. gatherLimit = 0;
  215. }
  216. gs.txQueue.push_back(OutboundMulticast());
  217. OutboundMulticast &out = gs.txQueue.back();
  218. out.init(
  219. RR,
  220. now,
  221. nwid,
  222. com,
  223. limit,
  224. gatherLimit,
  225. src,
  226. mg,
  227. etherType,
  228. data,
  229. len);
  230. unsigned int count = 0;
  231. for(std::vector<Address>::const_iterator ast(alwaysSendTo.begin());ast!=alwaysSendTo.end();++ast) {
  232. out.sendAndLog(RR,*ast);
  233. if (++count >= limit)
  234. break;
  235. }
  236. unsigned long idx = 0;
  237. while ((count < limit)&&(idx < gs.members.size())) {
  238. Address ma(gs.members[indexes[idx++]].address);
  239. if (std::find(alwaysSendTo.begin(),alwaysSendTo.end(),ma) == alwaysSendTo.end()) {
  240. out.sendAndLog(RR,ma);
  241. ++count;
  242. }
  243. }
  244. }
  245. // Free allocated memory buffer if any
  246. if (indexes != idxbuf)
  247. delete [] indexes;
  248. }
  249. void Multicaster::clean(uint64_t now)
  250. {
  251. Mutex::Lock _l(_groups_m);
  252. for(std::map< std::pair<uint64_t,MulticastGroup>,MulticastGroupStatus >::iterator mm(_groups.begin());mm!=_groups.end();) {
  253. for(std::list<OutboundMulticast>::iterator tx(mm->second.txQueue.begin());tx!=mm->second.txQueue.end();) {
  254. if ((tx->expired(now))||(tx->atLimit()))
  255. mm->second.txQueue.erase(tx++);
  256. else ++tx;
  257. }
  258. unsigned long count = 0;
  259. {
  260. std::vector<MulticastGroupMember>::iterator reader(mm->second.members.begin());
  261. std::vector<MulticastGroupMember>::iterator writer(reader);
  262. while (reader != mm->second.members.end()) {
  263. if ((now - reader->timestamp) < ZT_MULTICAST_LIKE_EXPIRE) {
  264. *writer = *reader;
  265. ++writer;
  266. ++count;
  267. }
  268. ++reader;
  269. }
  270. }
  271. if (count) {
  272. mm->second.members.resize(count);
  273. ++mm;
  274. } else if (mm->second.txQueue.empty()) {
  275. _groups.erase(mm++);
  276. } else {
  277. mm->second.members.clear();
  278. ++mm;
  279. }
  280. }
  281. }
  282. void Multicaster::_add(uint64_t now,uint64_t nwid,const MulticastGroup &mg,MulticastGroupStatus &gs,const Address &member)
  283. {
  284. // assumes _groups_m is locked
  285. // Do not add self -- even if someone else returns it
  286. if (member == RR->identity.address())
  287. return;
  288. for(std::vector<MulticastGroupMember>::iterator m(gs.members.begin());m!=gs.members.end();++m) {
  289. if (m->address == member) {
  290. m->timestamp = now;
  291. return;
  292. }
  293. }
  294. gs.members.push_back(MulticastGroupMember(member,now));
  295. //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)"));
  296. for(std::list<OutboundMulticast>::iterator tx(gs.txQueue.begin());tx!=gs.txQueue.end();) {
  297. if (tx->atLimit())
  298. gs.txQueue.erase(tx++);
  299. else {
  300. tx->sendIfNew(RR,member);
  301. if (tx->atLimit())
  302. gs.txQueue.erase(tx++);
  303. else ++tx;
  304. }
  305. }
  306. }
  307. } // namespace ZeroTier