Multicaster.cpp 13 KB

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