Multicaster.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421
  1. /*
  2. * ZeroTier One - Global Peer to Peer Ethernet
  3. * Copyright (C) 2011-2014 ZeroTier Networks LLC
  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 "CMWC4096.hpp"
  37. #include "C25519.hpp"
  38. #include "NodeConfig.hpp"
  39. #include "CertificateOfMembership.hpp"
  40. #include "Logger.hpp"
  41. namespace ZeroTier {
  42. Multicaster::Multicaster(const RuntimeEnvironment *renv) :
  43. RR(renv)
  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[std::pair<uint64_t,MulticastGroup>(nwid,mg)];
  55. while (p != e) {
  56. _add(now,nwid,mg,gs,Address(p,5));
  57. p += 5;
  58. }
  59. }
  60. unsigned int Multicaster::gather(const Address &queryingPeer,uint64_t nwid,const MulticastGroup &mg,Packet &appendTo,unsigned int limit) const
  61. {
  62. unsigned char *p;
  63. unsigned int added = 0,i,k,rptr,totalKnown = 0;
  64. uint64_t a,picked[(ZT_PROTO_MAX_PACKET_LENGTH / 5) + 2];
  65. if (!limit)
  66. return 0;
  67. else if (limit > 0xffff)
  68. limit = 0xffff;
  69. const unsigned int totalAt = appendTo.size();
  70. appendTo.addSize(4); // sizeof(uint32_t)
  71. const unsigned int addedAt = appendTo.size();
  72. appendTo.addSize(2); // sizeof(uint16_t)
  73. { // Return myself if I am a member of this group
  74. SharedPtr<Network> network(RR->nc->network(nwid));
  75. if ((network)&&(network->subscribedToMulticastGroup(mg))) {
  76. RR->identity.address().appendTo(appendTo);
  77. ++totalKnown;
  78. ++added;
  79. }
  80. }
  81. Mutex::Lock _l(_groups_m);
  82. std::map< std::pair<uint64_t,MulticastGroup>,MulticastGroupStatus >::const_iterator gs(_groups.find(std::pair<uint64_t,MulticastGroup>(nwid,mg)));
  83. if ((gs != _groups.end())&&(!gs->second.members.empty())) {
  84. totalKnown += (unsigned int)gs->second.members.size();
  85. // Members are returned in random order so that repeated gather queries
  86. // will return different subsets of a large multicast group.
  87. k = 0;
  88. while ((added < limit)&&(k < gs->second.members.size())&&((appendTo.size() + ZT_ADDRESS_LENGTH) <= ZT_UDP_DEFAULT_PAYLOAD_MTU)) {
  89. rptr = (unsigned int)RR->prng->next32();
  90. restart_member_scan:
  91. a = gs->second.members[rptr % (unsigned int)gs->second.members.size()].address.toInt();
  92. for(i=0;i<k;++i) {
  93. if (picked[i] == a) {
  94. ++rptr;
  95. goto restart_member_scan;
  96. }
  97. }
  98. picked[k++] = a;
  99. if (queryingPeer.toInt() != a) { // do not return the peer that is making the request as a result
  100. p = (unsigned char *)appendTo.appendField(ZT_ADDRESS_LENGTH);
  101. *(p++) = (unsigned char)((a >> 32) & 0xff);
  102. *(p++) = (unsigned char)((a >> 24) & 0xff);
  103. *(p++) = (unsigned char)((a >> 16) & 0xff);
  104. *(p++) = (unsigned char)((a >> 8) & 0xff);
  105. *p = (unsigned char)(a & 0xff);
  106. ++added;
  107. }
  108. }
  109. }
  110. appendTo.setAt(totalAt,(uint32_t)totalKnown);
  111. appendTo.setAt(addedAt,(uint16_t)added);
  112. //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());
  113. return added;
  114. }
  115. std::vector<Address> Multicaster::getMembers(uint64_t nwid,const MulticastGroup &mg,unsigned int limit) const
  116. {
  117. std::vector<Address> ls;
  118. Mutex::Lock _l(_groups_m);
  119. std::map< std::pair<uint64_t,MulticastGroup>,MulticastGroupStatus >::const_iterator gs(_groups.find(std::pair<uint64_t,MulticastGroup>(nwid,mg)));
  120. if (gs == _groups.end())
  121. return ls;
  122. for(std::vector<MulticastGroupMember>::const_reverse_iterator m(gs->second.members.rbegin());m!=gs->second.members.rend();++m) {
  123. ls.push_back(m->address);
  124. if (ls.size() >= limit)
  125. break;
  126. }
  127. return ls;
  128. }
  129. void Multicaster::send(
  130. const CertificateOfMembership *com,
  131. unsigned int limit,
  132. uint64_t now,
  133. uint64_t nwid,
  134. const std::vector<Address> &alwaysSendTo,
  135. const MulticastGroup &mg,
  136. const MAC &src,
  137. unsigned int etherType,
  138. const void *data,
  139. unsigned int len)
  140. {
  141. unsigned long idxbuf[8194];
  142. unsigned long *indexes = idxbuf;
  143. Mutex::Lock _l(_groups_m);
  144. MulticastGroupStatus &gs = _groups[std::pair<uint64_t,MulticastGroup>(nwid,mg)];
  145. if (!gs.members.empty()) {
  146. // Use a stack-allocated buffer unless this multicast group is ridiculously huge
  147. if (gs.members.size() > 8194)
  148. indexes = new unsigned long[gs.members.size()];
  149. // Generate a random permutation of member indexes
  150. for(unsigned long i=0;i<gs.members.size();++i)
  151. indexes[i] = i;
  152. for(unsigned long i=gs.members.size()-1;i>0;--i) {
  153. unsigned long j = RR->prng->next32() % (i + 1);
  154. unsigned long tmp = indexes[j];
  155. indexes[j] = indexes[i];
  156. indexes[i] = tmp;
  157. }
  158. }
  159. if (gs.members.size() >= limit) {
  160. // If we already have enough members, just send and we're done. We can
  161. // skip the TX queue and skip the overhead of maintaining a send log by
  162. // using sendOnly().
  163. OutboundMulticast out;
  164. out.init(
  165. RR,
  166. now,
  167. nwid,
  168. com,
  169. limit,
  170. 1, // we'll still gather a little from peers to keep multicast list fresh
  171. src,
  172. mg,
  173. etherType,
  174. data,
  175. len);
  176. unsigned int count = 0;
  177. for(std::vector<Address>::const_iterator ast(alwaysSendTo.begin());ast!=alwaysSendTo.end();++ast) {
  178. { // TODO / LEGACY: don't send new multicast frame to old peers (if we know their version)
  179. SharedPtr<Peer> p(RR->topology->getPeer(*ast));
  180. if ((p)&&(p->remoteVersionKnown())&&(p->remoteVersionMajor() < 1))
  181. continue;
  182. }
  183. out.sendOnly(RR,*ast);
  184. if (++count >= limit)
  185. break;
  186. }
  187. unsigned long idx = 0;
  188. while (count < limit) { // limit <= gs.members.size() so idx will never overflow here
  189. const MulticastGroupMember &m = gs.members[indexes[idx++]];
  190. { // TODO / LEGACY: don't send new multicast frame to old peers (if we know their version)
  191. SharedPtr<Peer> p(RR->topology->getPeer(m.address));
  192. if ((p)&&(p->remoteVersionKnown())&&(p->remoteVersionMajor() < 1))
  193. continue;
  194. }
  195. if (std::find(alwaysSendTo.begin(),alwaysSendTo.end(),m.address) == alwaysSendTo.end()) {
  196. out.sendOnly(RR,m.address);
  197. ++count;
  198. }
  199. }
  200. } else {
  201. unsigned int gatherLimit = (limit - (unsigned int)gs.members.size()) + 1;
  202. if ((now - gs.lastExplicitGather) >= ZT_MULTICAST_EXPLICIT_GATHER_DELAY) {
  203. gs.lastExplicitGather = now;
  204. SharedPtr<Peer> sn(RR->topology->getBestSupernode());
  205. if (sn) {
  206. TRACE(">>MC GATHER up to %u in %.16llx/%s",gatherLimit,nwid,mg.toString().c_str());
  207. Packet outp(sn->address(),RR->identity.address(),Packet::VERB_MULTICAST_GATHER);
  208. outp.append(nwid);
  209. outp.append((uint8_t)0);
  210. mg.mac().appendTo(outp);
  211. outp.append((uint32_t)mg.adi());
  212. outp.append((uint32_t)gatherLimit); // +1 just means we'll have an extra in the queue if available
  213. outp.armor(sn->key(),true);
  214. sn->send(RR,outp.data(),outp.size(),now);
  215. }
  216. gatherLimit = 1; // we still gather a bit from peers as well
  217. }
  218. gs.txQueue.push_back(OutboundMulticast());
  219. OutboundMulticast &out = gs.txQueue.back();
  220. out.init(
  221. RR,
  222. now,
  223. nwid,
  224. com,
  225. limit,
  226. gatherLimit,
  227. src,
  228. mg,
  229. etherType,
  230. data,
  231. len);
  232. unsigned int count = 0;
  233. for(std::vector<Address>::const_iterator ast(alwaysSendTo.begin());ast!=alwaysSendTo.end();++ast) {
  234. { // TODO / LEGACY: don't send new multicast frame to old peers (if we know their version)
  235. SharedPtr<Peer> p(RR->topology->getPeer(*ast));
  236. if ((p)&&(p->remoteVersionKnown())&&(p->remoteVersionMajor() < 1))
  237. continue;
  238. }
  239. out.sendAndLog(RR,*ast);
  240. if (++count >= limit)
  241. break;
  242. }
  243. unsigned long idx = 0;
  244. while ((count < limit)&&(idx < gs.members.size())) {
  245. const MulticastGroupMember &m = gs.members[indexes[idx++]];
  246. { // TODO / LEGACY: don't send new multicast frame to old peers (if we know their version)
  247. SharedPtr<Peer> p(RR->topology->getPeer(m.address));
  248. if ((p)&&(p->remoteVersionKnown())&&(p->remoteVersionMajor() < 1))
  249. continue;
  250. }
  251. if (std::find(alwaysSendTo.begin(),alwaysSendTo.end(),m.address) == alwaysSendTo.end()) {
  252. out.sendAndLog(RR,m.address);
  253. ++count;
  254. }
  255. }
  256. }
  257. if (indexes != idxbuf)
  258. delete [] indexes;
  259. // DEPRECATED / LEGACY / TODO:
  260. // Currently we also always send a legacy P5_MULTICAST_FRAME packet to our
  261. // supernode. Our supernode then takes care of relaying it down to <1.0.0
  262. // nodes. This code can go away (along with support for P5_MULTICAST_FRAME)
  263. // once there are no more such nodes on the network.
  264. {
  265. SharedPtr<Peer> sn(RR->topology->getBestSupernode());
  266. if (sn) {
  267. uint32_t rn = RR->prng->next32();
  268. Packet outp(sn->address(),RR->identity.address(),Packet::VERB_P5_MULTICAST_FRAME);
  269. outp.append((uint16_t)0xffff); // do not forward
  270. outp.append((unsigned char)0,320 + 1024); // empty queue and bloom filter
  271. outp.append((unsigned char)((com) ? ZT_PROTO_VERB_P5_MULTICAST_FRAME_FLAGS_HAS_MEMBERSHIP_CERTIFICATE : 0));
  272. outp.append((uint64_t)nwid);
  273. outp.append((uint16_t)0);
  274. outp.append((unsigned char)0);
  275. outp.append((unsigned char)0);
  276. RR->identity.address().appendTo(outp);
  277. outp.append((const void *)&rn,3); // random multicast ID
  278. if (src)
  279. src.appendTo(outp);
  280. else MAC(RR->identity.address(),nwid).appendTo(outp);
  281. mg.mac().appendTo(outp);
  282. outp.append((uint32_t)mg.adi());
  283. outp.append((uint16_t)etherType);
  284. outp.append((uint16_t)len);
  285. outp.append(data,len);
  286. unsigned int signedPortionLen = outp.size() - ZT_PROTO_VERB_P5_MULTICAST_FRAME_IDX__START_OF_SIGNED_PORTION;
  287. C25519::Signature sig(RR->identity.sign(outp.field(ZT_PROTO_VERB_P5_MULTICAST_FRAME_IDX__START_OF_SIGNED_PORTION,signedPortionLen),signedPortionLen));
  288. outp.append((uint16_t)sig.size());
  289. outp.append(sig.data,(unsigned int)sig.size());
  290. if (com) com->serialize(outp);
  291. outp.compress();
  292. outp.armor(sn->key(),true);
  293. sn->send(RR,outp.data(),outp.size(),now);
  294. }
  295. }
  296. }
  297. void Multicaster::clean(uint64_t now)
  298. {
  299. Mutex::Lock _l(_groups_m);
  300. for(std::map< std::pair<uint64_t,MulticastGroup>,MulticastGroupStatus >::iterator mm(_groups.begin());mm!=_groups.end();) {
  301. // Remove expired outgoing multicasts from multicast TX queue
  302. for(std::list<OutboundMulticast>::iterator tx(mm->second.txQueue.begin());tx!=mm->second.txQueue.end();) {
  303. if ((tx->expired(now))||(tx->atLimit()))
  304. mm->second.txQueue.erase(tx++);
  305. else ++tx;
  306. }
  307. // Remove expired members from membership list, and update rank
  308. // so that remaining members can be sorted in ascending order of
  309. // transmit priority.
  310. std::vector<MulticastGroupMember>::iterator reader(mm->second.members.begin());
  311. std::vector<MulticastGroupMember>::iterator writer(reader);
  312. unsigned int count = 0;
  313. while (reader != mm->second.members.end()) {
  314. if ((now - reader->timestamp) < ZT_MULTICAST_LIKE_EXPIRE) {
  315. *writer = *reader;
  316. ++writer;
  317. ++count;
  318. }
  319. ++reader;
  320. }
  321. if (count) {
  322. mm->second.members.resize(count);
  323. ++mm;
  324. } else if (mm->second.txQueue.empty()) {
  325. _groups.erase(mm++);
  326. } else {
  327. mm->second.members.clear();
  328. ++mm;
  329. }
  330. }
  331. }
  332. void Multicaster::_add(uint64_t now,uint64_t nwid,const MulticastGroup &mg,MulticastGroupStatus &gs,const Address &member)
  333. {
  334. // assumes _groups_m is locked
  335. // Do not add self -- even if someone else returns it
  336. if (member == RR->identity.address())
  337. return;
  338. for(std::vector<MulticastGroupMember>::iterator m(gs.members.begin());m!=gs.members.end();++m) {
  339. if (m->address == member) {
  340. m->timestamp = now;
  341. return;
  342. }
  343. }
  344. gs.members.push_back(MulticastGroupMember(member,now));
  345. //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)"));
  346. // Try to send to any outgoing multicasts that are waiting for more recipients
  347. // TODO / LEGACY: don't send new multicast frame to old peers (if we know their version)
  348. SharedPtr<Peer> p(RR->topology->getPeer(member));
  349. if ((!p)||(!p->remoteVersionKnown())||(p->remoteVersionMajor() >= 1)) {
  350. for(std::list<OutboundMulticast>::iterator tx(gs.txQueue.begin());tx!=gs.txQueue.end();) {
  351. if (tx->atLimit()) {
  352. gs.txQueue.erase(tx++);
  353. } else {
  354. tx->sendIfNew(RR,member);
  355. if (tx->atLimit())
  356. gs.txQueue.erase(tx++);
  357. else ++tx;
  358. }
  359. }
  360. }
  361. }
  362. } // namespace ZeroTier