Multicaster.cpp 9.1 KB

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