Multicaster.cpp 11 KB

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