Multicaster.cpp 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241
  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 "SharedPtr.hpp"
  30. #include "Multicaster.hpp"
  31. #include "Topology.hpp"
  32. #include "Switch.hpp"
  33. #include "Packet.hpp"
  34. #include "Peer.hpp"
  35. #include "CMWC4096.hpp"
  36. #include "CertificateOfMembership.hpp"
  37. #include "RuntimeEnvironment.hpp"
  38. namespace ZeroTier {
  39. Multicaster::Multicaster()
  40. {
  41. }
  42. Multicaster::~Multicaster()
  43. {
  44. }
  45. unsigned int Multicaster::gather(const RuntimeEnvironment *RR,uint64_t nwid,MulticastGroup &mg,Packet &appendTo,unsigned int limit) const
  46. {
  47. unsigned char *p;
  48. unsigned int n = 0,i,rptr;
  49. uint64_t a,done[(ZT_PROTO_MAX_PACKET_LENGTH / 5) + 1];
  50. Mutex::Lock _l(_groups_m);
  51. std::map< std::pair<uint64_t,MulticastGroup>,MulticastGroupStatus >::const_iterator gs(_groups.find(std::pair<uint64_t,MulticastGroup>(nwid,mg)));
  52. if ((gs == _groups.end())||(gs->second.members.empty())) {
  53. appendTo.append((uint32_t)0);
  54. appendTo.append((uint16_t)0);
  55. return 0;
  56. }
  57. if (limit > gs->second.members.size())
  58. limit = (unsigned int)gs->second.members.size();
  59. if (limit > 0xffff) // sanity check -- this won't fit in a packet anyway
  60. limit = 0xffff;
  61. appendTo.append((uint32_t)gs->second.members.size());
  62. unsigned int nAt = appendTo.size();
  63. appendTo.append((uint16_t)0); // set to n later
  64. while ((n < limit)&&((appendTo.size() + ZT_ADDRESS_LENGTH) <= ZT_PROTO_MAX_PACKET_LENGTH)) {
  65. // Pick a member at random -- if we've already picked it,
  66. // keep circling the buffer until we find one we haven't.
  67. // This won't loop forever since limit <= members.size().
  68. rptr = (unsigned int)RR->prng->next32();
  69. restart_member_scan:
  70. a = gs->second.members[rptr % (unsigned int)gs->second.members.size()].address.toInt();
  71. for(i=0;i<n;++i) {
  72. if (done[i] == a) {
  73. ++rptr;
  74. goto restart_member_scan;
  75. }
  76. }
  77. // Log that we've picked this one
  78. done[n++] = a;
  79. // Append to packet
  80. p = (unsigned char *)appendTo.appendField(ZT_ADDRESS_LENGTH);
  81. *(p++) = (unsigned char)((a >> 32) & 0xff);
  82. *(p++) = (unsigned char)((a >> 24) & 0xff);
  83. *(p++) = (unsigned char)((a >> 16) & 0xff);
  84. *(p++) = (unsigned char)((a >> 8) & 0xff);
  85. *p = (unsigned char)(a & 0xff);
  86. }
  87. appendTo.setAt(nAt,(uint16_t)n);
  88. return n;
  89. }
  90. void Multicaster::send(
  91. const RuntimeEnvironment *RR,
  92. const CertificateOfMembership *com,
  93. unsigned int limit,
  94. uint64_t now,
  95. uint64_t nwid,
  96. const MulticastGroup &mg,
  97. const MAC &src,
  98. unsigned int etherType,
  99. const void *data,
  100. unsigned int len)
  101. {
  102. Mutex::Lock _l(_groups_m);
  103. MulticastGroupStatus &gs = _groups[std::pair<uint64_t,MulticastGroup>(nwid,mg)];
  104. if (gs.members.size() >= limit) {
  105. // If we already have enough members, just send and we're done -- no need for TX queue
  106. OutboundMulticast out;
  107. out.init(now,RR->identity.address(),nwid,com,ZT_MULTICAST_DEFAULT_IMPLICIT_GATHER,src,mg,etherType,data,len);
  108. unsigned int count = 0;
  109. for(std::vector<MulticastGroupMember>::const_reverse_iterator m(gs.members.rbegin());m!=gs.members.rend();++m) {
  110. out.sendOnly(*(RR->sw),m->address); // sendOnly() avoids overhead of creating sent log since we're going to discard this immediately
  111. if (++count >= limit)
  112. break;
  113. }
  114. } else {
  115. // If we don't already have enough members, send to the ones we have and then gather (if allowed within gather rate limit delay)
  116. gs.txQueue.push_back(OutboundMulticast());
  117. OutboundMulticast &out = gs.txQueue.back();
  118. out.init(now,RR->identity.address(),nwid,com,ZT_MULTICAST_DEFAULT_IMPLICIT_GATHER,src,mg,etherType,data,len);
  119. for(std::vector<MulticastGroupMember>::const_reverse_iterator m(gs.members.rbegin());m!=gs.members.rend();++m)
  120. out.sendAndLog(*(RR->sw),m->address);
  121. if ((now - gs.lastExplicitGather) >= ZT_MULTICAST_GATHER_DELAY) {
  122. gs.lastExplicitGather = now;
  123. // TODO / INPROGRESS: right now supernodes track multicast LIKEs, a relic
  124. // from the old algorithm. The next step will be to devolve this duty
  125. // somewhere else, such as node(s) nominated by netconf masters. But
  126. // we'll keep announcing LIKEs to supernodes for the near future to
  127. // gradually migrate from old multicast to new without losing old nodes.
  128. SharedPtr<Peer> sn(RR->topology->getBestSupernode());
  129. if (sn) {
  130. Packet outp(sn->address(),RR->identity.address(),Packet::VERB_MULTICAST_GATHER);
  131. outp.append(nwid);
  132. outp.append((uint8_t)0);
  133. mg.mac().appendTo(outp);
  134. outp.append((uint32_t)mg.adi());
  135. outp.append((uint32_t)((limit - (unsigned int)gs.members.size()) + 1)); // +1 just means we'll have an extra in the queue if available
  136. outp.armor(sn->key(),true);
  137. sn->send(RR,outp.data(),outp.size(),now);
  138. }
  139. }
  140. }
  141. }
  142. void Multicaster::clean(const RuntimeEnvironment *RR,uint64_t now)
  143. {
  144. Mutex::Lock _l(_groups_m);
  145. for(std::map< std::pair<uint64_t,MulticastGroup>,MulticastGroupStatus >::iterator mm(_groups.begin());mm!=_groups.end();) {
  146. // Remove expired outgoing multicasts from multicast TX queue
  147. for(std::list<OutboundMulticast>::iterator tx(mm->second.txQueue.begin());tx!=mm->second.txQueue.end();) {
  148. if (tx->expired(now))
  149. mm->second.txQueue.erase(tx++);
  150. else ++tx;
  151. }
  152. // Remove expired members from membership list, and update rank
  153. // so that remaining members can be sorted in ascending order of
  154. // transmit priority.
  155. std::vector<MulticastGroupMember>::iterator reader(mm->second.members.begin());
  156. std::vector<MulticastGroupMember>::iterator writer(mm->second.members.begin());
  157. unsigned int count = 0;
  158. while (reader != mm->second.members.end()) {
  159. if ((now - reader->timestamp) < ZT_MULTICAST_LIKE_EXPIRE) {
  160. *writer = *reader;
  161. /* We rank in ascending order of most recent relevant activity. For peers we've learned
  162. * about by direct LIKEs, we do this in order of their own activity. For indirectly
  163. * acquired peers we do this minus a constant to place these categorically below directly
  164. * learned peers. For peers with no active Peer record, we use the time we last learned
  165. * about them minus one day (a large constant) to put these at the bottom of the list.
  166. * List is sorted in ascending order of rank and multicasts are sent last-to-first. */
  167. if (writer->learnedFrom) {
  168. SharedPtr<Peer> p(RR->topology->getPeer(writer->learnedFrom));
  169. if (p)
  170. writer->rank = p->lastUnicastFrame() - ZT_MULTICAST_LIKE_EXPIRE;
  171. else writer->rank = writer->timestamp - (86400000 + ZT_MULTICAST_LIKE_EXPIRE);
  172. } else {
  173. SharedPtr<Peer> p(RR->topology->getPeer(writer->address));
  174. if (p)
  175. writer->rank = p->lastUnicastFrame();
  176. else writer->rank = writer->timestamp - 86400000;
  177. }
  178. ++writer;
  179. ++count;
  180. }
  181. ++reader;
  182. }
  183. if (count) {
  184. // There are remaining members, so re-sort them by rank and resize the vector
  185. std::sort(mm->second.members.begin(),writer); // sorts in ascending order of rank
  186. mm->second.members.resize(count); // trim off the ones we cut, after writer
  187. ++mm;
  188. } else if (mm->second.txQueue.empty()) {
  189. // There are no remaining members and no pending multicasts, so erase the entry
  190. _groups.erase(mm++);
  191. } else ++mm;
  192. }
  193. }
  194. void Multicaster::_add(uint64_t now,MulticastGroupStatus &gs,const Address &learnedFrom,const Address &member)
  195. {
  196. // assumes _groups_m is locked
  197. // Update timestamp and learnedFrom if existing
  198. for(std::vector<MulticastGroupMember>::iterator m(gs.members.begin());m!=gs.members.end();++m) {
  199. if (m->address == member) {
  200. if (m->learnedFrom)
  201. m->learnedFrom = learnedFrom; // only update with indirect learnedFrom if we've never directly learned from this peer
  202. m->timestamp = now;
  203. return;
  204. }
  205. }
  206. // If not existing, add to end of list (highest priority) -- these will
  207. // be resorted on next clean(). In the future we might want to insert
  208. // this somewhere else but we'll try this for now.
  209. gs.members.push_back(MulticastGroupMember(member,learnedFrom,now));
  210. }
  211. } // namespace ZeroTier