Multicaster.cpp 10.0 KB

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