Multicaster.cpp 14 KB

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