Multicaster.cpp 14 KB

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