Multicaster.cpp 9.8 KB

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