Multicaster.cpp 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317
  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,const Address &queryingPeer,uint64_t nwid,MulticastGroup &mg,Packet &appendTo,unsigned int limit) const
  47. {
  48. unsigned char *p;
  49. unsigned int n = 0,i,rptr,skipped = 0;
  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 > ((ZT_PROTO_MAX_PACKET_LENGTH / 5) + 1))
  61. limit = (ZT_PROTO_MAX_PACKET_LENGTH / 5) + 1;
  62. unsigned int totalAt = appendTo.size();
  63. appendTo.addSize(4); // sizeof(uint32_t)
  64. unsigned int nAt = appendTo.size();
  65. appendTo.addSize(2); // sizeof(uint16_t)
  66. while ((n < limit)&&((appendTo.size() + ZT_ADDRESS_LENGTH) <= ZT_PROTO_MAX_PACKET_LENGTH)) {
  67. // Pick a member at random -- if we've already picked it,
  68. // keep circling the buffer until we find one we haven't.
  69. // This won't loop forever since limit <= members.size().
  70. rptr = (unsigned int)RR->prng->next32();
  71. restart_member_scan:
  72. a = gs->second.members[rptr % (unsigned int)gs->second.members.size()].address.toInt();
  73. for(i=0;i<n;++i) {
  74. if (done[i] == a) {
  75. ++rptr;
  76. goto restart_member_scan;
  77. }
  78. }
  79. // Log that we've picked this one
  80. done[n++] = a;
  81. if (queryingPeer.toInt() == a) {
  82. ++skipped;
  83. } else {
  84. // Append to packet
  85. p = (unsigned char *)appendTo.appendField(ZT_ADDRESS_LENGTH);
  86. *(p++) = (unsigned char)((a >> 32) & 0xff);
  87. *(p++) = (unsigned char)((a >> 24) & 0xff);
  88. *(p++) = (unsigned char)((a >> 16) & 0xff);
  89. *(p++) = (unsigned char)((a >> 8) & 0xff);
  90. *p = (unsigned char)(a & 0xff);
  91. }
  92. }
  93. appendTo.setAt(totalAt,(uint32_t)(gs->second.members.size() - skipped));
  94. appendTo.setAt(nAt,(uint16_t)(n - skipped));
  95. return n;
  96. }
  97. void Multicaster::send(
  98. const CertificateOfMembership *com,
  99. unsigned int limit,
  100. uint64_t now,
  101. uint64_t nwid,
  102. const MulticastGroup &mg,
  103. const MAC &src,
  104. unsigned int etherType,
  105. const void *data,
  106. unsigned int len)
  107. {
  108. Mutex::Lock _l(_groups_m);
  109. MulticastGroupStatus &gs = _groups[std::pair<uint64_t,MulticastGroup>(nwid,mg)];
  110. // TODO / DEPRECATED:
  111. // Right now we also send all multicasts to at least one supernode.
  112. // This supernode then relays them via the old multicast message
  113. // type to pre 1.0.0 peers. We'll keep doing this until there aren't
  114. // any of these on the network. Costs a bit of bandwidth, but maintains
  115. // backward compability while people upgrade. Then this code can die.
  116. bool gotASupernode = false;
  117. if (gs.members.size() >= limit) {
  118. // If we already have enough members, just send and we're done -- no need for TX queue
  119. OutboundMulticast out;
  120. out.init(
  121. now,
  122. RR->identity.address(),
  123. nwid,
  124. com,
  125. limit,
  126. 0,
  127. src,
  128. mg,
  129. etherType,
  130. data,
  131. len);
  132. unsigned int count = 0;
  133. for(std::vector<MulticastGroupMember>::const_reverse_iterator m(gs.members.rbegin());m!=gs.members.rend();++m) {
  134. out.sendOnly(*(RR->sw),m->address); // sendOnly() avoids overhead of creating sent log since we're going to discard this immediately
  135. if (RR->topology->isSupernode(m->address))
  136. gotASupernode = true;
  137. if (++count >= limit)
  138. break;
  139. }
  140. if (!gotASupernode) {
  141. SharedPtr<Peer> sn(RR->topology->getBestSupernode());
  142. if (sn)
  143. out.sendOnly(*(RR->sw),sn->address());
  144. }
  145. } else {
  146. unsigned int gatherLimit = (limit - (unsigned int)gs.members.size()) + 1;
  147. if ((now - gs.lastExplicitGather) >= ZT_MULTICAST_EXPLICIT_GATHER_DELAY) {
  148. gs.lastExplicitGather = now;
  149. // TODO / INPROGRESS: right now supernodes track multicast LIKEs, a relic
  150. // from the old algorithm. The next step will be to devolve this duty
  151. // somewhere else, such as node(s) nominated by netconf masters. But
  152. // we'll keep announcing LIKEs to supernodes for the near future to
  153. // gradually migrate from old multicast to new without losing old nodes.
  154. SharedPtr<Peer> sn(RR->topology->getBestSupernode());
  155. if (sn) {
  156. Packet outp(sn->address(),RR->identity.address(),Packet::VERB_MULTICAST_GATHER);
  157. outp.append(nwid);
  158. outp.append((uint8_t)0);
  159. mg.mac().appendTo(outp);
  160. outp.append((uint32_t)mg.adi());
  161. outp.append((uint32_t)gatherLimit); // +1 just means we'll have an extra in the queue if available
  162. outp.armor(sn->key(),true);
  163. sn->send(RR,outp.data(),outp.size(),now);
  164. }
  165. gatherLimit = 0; // once we've done this we don't need to do it implicitly
  166. }
  167. if ((gatherLimit > 0)&&((now - gs.lastImplicitGather) > ZT_MULTICAST_IMPLICIT_GATHER_DELAY))
  168. gs.lastImplicitGather = now;
  169. else gatherLimit = 0;
  170. gs.txQueue.push_back(OutboundMulticast());
  171. OutboundMulticast &out = gs.txQueue.back();
  172. out.init(
  173. now,
  174. RR->identity.address(),
  175. nwid,
  176. com,
  177. limit,
  178. gatherLimit,
  179. src,
  180. mg,
  181. etherType,
  182. data,
  183. len);
  184. for(std::vector<MulticastGroupMember>::const_reverse_iterator m(gs.members.rbegin());m!=gs.members.rend();++m) {
  185. out.sendAndLog(*(RR->sw),m->address);
  186. if (RR->topology->isSupernode(m->address))
  187. gotASupernode = true;
  188. }
  189. if (!gotASupernode) {
  190. SharedPtr<Peer> sn(RR->topology->getBestSupernode());
  191. if (sn)
  192. out.sendAndLog(*(RR->sw),sn->address());
  193. }
  194. }
  195. }
  196. void Multicaster::clean(uint64_t now)
  197. {
  198. Mutex::Lock _l(_groups_m);
  199. for(std::map< std::pair<uint64_t,MulticastGroup>,MulticastGroupStatus >::iterator mm(_groups.begin());mm!=_groups.end();) {
  200. // Remove expired outgoing multicasts from multicast TX queue
  201. for(std::list<OutboundMulticast>::iterator tx(mm->second.txQueue.begin());tx!=mm->second.txQueue.end();) {
  202. if ((tx->expired(now))||(tx->atLimit()))
  203. mm->second.txQueue.erase(tx++);
  204. else ++tx;
  205. }
  206. // Remove expired members from membership list, and update rank
  207. // so that remaining members can be sorted in ascending order of
  208. // transmit priority.
  209. std::vector<MulticastGroupMember>::iterator reader(mm->second.members.begin());
  210. std::vector<MulticastGroupMember>::iterator writer(mm->second.members.begin());
  211. unsigned int count = 0;
  212. while (reader != mm->second.members.end()) {
  213. if ((now - reader->timestamp) < ZT_MULTICAST_LIKE_EXPIRE) {
  214. *writer = *reader;
  215. /* We rank in ascending order of most recent relevant activity. For peers we've learned
  216. * about by direct LIKEs, we do this in order of their own activity. For indirectly
  217. * acquired peers we do this minus a constant to place these categorically below directly
  218. * learned peers. For peers with no active Peer record, we use the time we last learned
  219. * about them minus one day (a large constant) to put these at the bottom of the list.
  220. * List is sorted in ascending order of rank and multicasts are sent last-to-first. */
  221. if (writer->learnedFrom) {
  222. SharedPtr<Peer> p(RR->topology->getPeer(writer->learnedFrom));
  223. if (p)
  224. writer->rank = p->lastUnicastFrame() - ZT_MULTICAST_LIKE_EXPIRE;
  225. else writer->rank = writer->timestamp - (86400000 + ZT_MULTICAST_LIKE_EXPIRE);
  226. } else {
  227. SharedPtr<Peer> p(RR->topology->getPeer(writer->address));
  228. if (p)
  229. writer->rank = p->lastUnicastFrame();
  230. else writer->rank = writer->timestamp - 86400000;
  231. }
  232. ++writer;
  233. ++count;
  234. }
  235. ++reader;
  236. }
  237. if (count) {
  238. // There are remaining members, so re-sort them by rank and resize the vector
  239. std::sort(mm->second.members.begin(),writer); // sorts in ascending order of rank
  240. mm->second.members.resize(count); // trim off the ones we cut, after writer
  241. ++mm;
  242. } else if (mm->second.txQueue.empty()) {
  243. // There are no remaining members and no pending multicasts, so erase the entry
  244. _groups.erase(mm++);
  245. } else ++mm;
  246. }
  247. }
  248. void Multicaster::_add(uint64_t now,uint64_t nwid,MulticastGroupStatus &gs,const Address &learnedFrom,const Address &member)
  249. {
  250. // assumes _groups_m is locked
  251. // Do not add self -- even if someone else returns it
  252. if (member == RR->identity.address())
  253. return;
  254. // Update timestamp and learnedFrom if existing
  255. for(std::vector<MulticastGroupMember>::iterator m(gs.members.begin());m!=gs.members.end();++m) {
  256. if (m->address == member) {
  257. // learnedFrom is NULL (zero) if we've learned this directly via MULTICAST_LIKE, at which
  258. // point this becomes a first-order connection.
  259. if (m->learnedFrom)
  260. m->learnedFrom = learnedFrom;
  261. m->timestamp = now;
  262. return;
  263. }
  264. }
  265. // If not existing, add to end of list (highest priority) -- these will
  266. // be resorted on next clean(). In the future we might want to insert
  267. // this somewhere else but we'll try this for now.
  268. gs.members.push_back(MulticastGroupMember(member,learnedFrom,now));
  269. // Try to send to any outgoing multicasts that are waiting for more recipients
  270. for(std::list<OutboundMulticast>::iterator tx(gs.txQueue.begin());tx!=gs.txQueue.end();) {
  271. tx->sendIfNew(*(RR->sw),member);
  272. if (tx->atLimit())
  273. gs.txQueue.erase(tx++);
  274. else ++tx;
  275. }
  276. }
  277. } // namespace ZeroTier