Multicaster.cpp 12 KB

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