Network.cpp 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574
  1. /*
  2. * ZeroTier One - Network Virtualization Everywhere
  3. * Copyright (C) 2011-2015 ZeroTier, Inc.
  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 <stdio.h>
  28. #include <string.h>
  29. #include <stdlib.h>
  30. #include <math.h>
  31. #include "Constants.hpp"
  32. #include "Network.hpp"
  33. #include "RuntimeEnvironment.hpp"
  34. #include "Switch.hpp"
  35. #include "Packet.hpp"
  36. #include "Buffer.hpp"
  37. #include "NetworkController.hpp"
  38. #include "../version.h"
  39. namespace ZeroTier {
  40. const ZeroTier::MulticastGroup Network::BROADCAST(ZeroTier::MAC(0xffffffffffffULL),0);
  41. Network::Network(const RuntimeEnvironment *renv,uint64_t nwid) :
  42. RR(renv),
  43. _id(nwid),
  44. _mac(renv->identity.address(),nwid),
  45. _enabled(true),
  46. _portInitialized(false),
  47. _lastConfigUpdate(0),
  48. _destroyed(false),
  49. _netconfFailure(NETCONF_FAILURE_NONE),
  50. _portError(0)
  51. {
  52. char confn[128],mcdbn[128];
  53. Utils::snprintf(confn,sizeof(confn),"networks.d/%.16llx.conf",_id);
  54. Utils::snprintf(mcdbn,sizeof(mcdbn),"networks.d/%.16llx.mcerts",_id);
  55. if (_id == ZT_TEST_NETWORK_ID) {
  56. applyConfiguration(NetworkConfig::createTestNetworkConfig(RR->identity.address()));
  57. // Save a one-byte CR to persist membership in the test network
  58. RR->node->dataStorePut(confn,"\n",1,false);
  59. } else {
  60. bool gotConf = false;
  61. try {
  62. std::string conf(RR->node->dataStoreGet(confn));
  63. if (conf.length()) {
  64. setConfiguration(Dictionary(conf),false);
  65. _lastConfigUpdate = 0; // we still want to re-request a new config from the network
  66. gotConf = true;
  67. }
  68. } catch ( ... ) {} // ignore invalids, we'll re-request
  69. if (!gotConf) {
  70. // Save a one-byte CR to persist membership while we request a real netconf
  71. RR->node->dataStorePut(confn,"\n",1,false);
  72. }
  73. try {
  74. std::string mcdb(RR->node->dataStoreGet(mcdbn));
  75. if (mcdb.length() > 6) {
  76. const char *p = mcdb.data();
  77. const char *e = p + mcdb.length();
  78. if (!memcmp("ZTMCD0",p,6)) {
  79. p += 6;
  80. while (p != e) {
  81. CertificateOfMembership com;
  82. com.deserialize2(p,e);
  83. if (!com)
  84. break;
  85. _membershipCertificates.insert(std::pair< Address,CertificateOfMembership >(com.issuedTo(),com));
  86. }
  87. }
  88. }
  89. } catch ( ... ) {} // ignore invalid MCDB, we'll re-learn from peers
  90. }
  91. if (!_portInitialized) {
  92. ZT1_VirtualNetworkConfig ctmp;
  93. _externalConfig(&ctmp);
  94. _portError = RR->node->configureVirtualNetworkPort(_id,ZT1_VIRTUAL_NETWORK_CONFIG_OPERATION_UP,&ctmp);
  95. _portInitialized = true;
  96. }
  97. }
  98. Network::~Network()
  99. {
  100. ZT1_VirtualNetworkConfig ctmp;
  101. _externalConfig(&ctmp);
  102. char n[128];
  103. if (_destroyed) {
  104. RR->node->configureVirtualNetworkPort(_id,ZT1_VIRTUAL_NETWORK_CONFIG_OPERATION_DESTROY,&ctmp);
  105. Utils::snprintf(n,sizeof(n),"networks.d/%.16llx.conf",_id);
  106. RR->node->dataStoreDelete(n);
  107. Utils::snprintf(n,sizeof(n),"networks.d/%.16llx.mcerts",_id);
  108. RR->node->dataStoreDelete(n);
  109. } else {
  110. RR->node->configureVirtualNetworkPort(_id,ZT1_VIRTUAL_NETWORK_CONFIG_OPERATION_DOWN,&ctmp);
  111. clean();
  112. std::string buf("ZTMCD0");
  113. Utils::snprintf(n,sizeof(n),"networks.d/%.16llx.mcerts",_id);
  114. Mutex::Lock _l(_lock);
  115. if ((!_config)||(_config->isPublic())||(_membershipCertificates.size() == 0)) {
  116. RR->node->dataStoreDelete(n);
  117. return;
  118. }
  119. for(std::map<Address,CertificateOfMembership>::iterator c(_membershipCertificates.begin());c!=_membershipCertificates.end();++c)
  120. c->second.serialize2(buf);
  121. RR->node->dataStorePut(n,buf,true);
  122. }
  123. }
  124. bool Network::subscribedToMulticastGroup(const MulticastGroup &mg,bool includeBridgedGroups) const
  125. {
  126. Mutex::Lock _l(_lock);
  127. if (std::binary_search(_myMulticastGroups.begin(),_myMulticastGroups.end(),mg))
  128. return true;
  129. else if (includeBridgedGroups)
  130. return (_multicastGroupsBehindMe.find(mg) != _multicastGroupsBehindMe.end());
  131. else return false;
  132. }
  133. void Network::multicastSubscribe(const MulticastGroup &mg)
  134. {
  135. {
  136. Mutex::Lock _l(_lock);
  137. if (std::binary_search(_myMulticastGroups.begin(),_myMulticastGroups.end(),mg))
  138. return;
  139. _myMulticastGroups.push_back(mg);
  140. std::sort(_myMulticastGroups.begin(),_myMulticastGroups.end());
  141. }
  142. _announceMulticastGroups();
  143. }
  144. void Network::multicastUnsubscribe(const MulticastGroup &mg)
  145. {
  146. Mutex::Lock _l(_lock);
  147. std::vector<MulticastGroup> nmg;
  148. for(std::vector<MulticastGroup>::const_iterator i(_myMulticastGroups.begin());i!=_myMulticastGroups.end();++i) {
  149. if (*i != mg)
  150. nmg.push_back(*i);
  151. }
  152. if (nmg.size() != _myMulticastGroups.size())
  153. _myMulticastGroups.swap(nmg);
  154. }
  155. bool Network::applyConfiguration(const SharedPtr<NetworkConfig> &conf)
  156. {
  157. if (_destroyed) // sanity check
  158. return false;
  159. try {
  160. if ((conf->networkId() == _id)&&(conf->issuedTo() == RR->identity.address())) {
  161. ZT1_VirtualNetworkConfig ctmp;
  162. bool portInitialized;
  163. {
  164. Mutex::Lock _l(_lock);
  165. _config = conf;
  166. _lastConfigUpdate = RR->node->now();
  167. _netconfFailure = NETCONF_FAILURE_NONE;
  168. _externalConfig(&ctmp);
  169. portInitialized = _portInitialized;
  170. _portInitialized = true;
  171. }
  172. _portError = RR->node->configureVirtualNetworkPort(_id,(portInitialized) ? ZT1_VIRTUAL_NETWORK_CONFIG_OPERATION_CONFIG_UPDATE : ZT1_VIRTUAL_NETWORK_CONFIG_OPERATION_UP,&ctmp);
  173. return true;
  174. } else {
  175. TRACE("ignored invalid configuration for network %.16llx (configuration contains mismatched network ID or issued-to address)",(unsigned long long)_id);
  176. }
  177. } catch (std::exception &exc) {
  178. TRACE("ignored invalid configuration for network %.16llx (%s)",(unsigned long long)_id,exc.what());
  179. } catch ( ... ) {
  180. TRACE("ignored invalid configuration for network %.16llx (unknown exception)",(unsigned long long)_id);
  181. }
  182. return false;
  183. }
  184. int Network::setConfiguration(const Dictionary &conf,bool saveToDisk)
  185. {
  186. try {
  187. const SharedPtr<NetworkConfig> newConfig(new NetworkConfig(conf)); // throws if invalid
  188. {
  189. Mutex::Lock _l(_lock);
  190. if ((_config)&&(*_config == *newConfig))
  191. return 1; // OK config, but duplicate of what we already have
  192. }
  193. if (applyConfiguration(newConfig)) {
  194. if (saveToDisk) {
  195. char n[128];
  196. Utils::snprintf(n,sizeof(n),"networks.d/%.16llx.conf",_id);
  197. RR->node->dataStorePut(n,conf.toString(),true);
  198. }
  199. return 2; // OK and configuration has changed
  200. }
  201. } catch ( ... ) {
  202. TRACE("ignored invalid configuration for network %.16llx (dictionary decode failed)",(unsigned long long)_id);
  203. }
  204. return 0;
  205. }
  206. void Network::requestConfiguration()
  207. {
  208. if (_id == ZT_TEST_NETWORK_ID) // pseudo-network-ID, uses locally generated static config
  209. return;
  210. if (controller() == RR->identity.address()) {
  211. if (RR->localNetworkController) {
  212. SharedPtr<NetworkConfig> nconf(config2());
  213. Dictionary newconf;
  214. switch(RR->localNetworkController->doNetworkConfigRequest(InetAddress(),RR->identity,RR->identity,_id,Dictionary(),(nconf) ? nconf->revision() : (uint64_t)0,newconf)) {
  215. case NetworkController::NETCONF_QUERY_OK:
  216. this->setConfiguration(newconf,true);
  217. return;
  218. case NetworkController::NETCONF_QUERY_OBJECT_NOT_FOUND:
  219. this->setNotFound();
  220. return;
  221. case NetworkController::NETCONF_QUERY_ACCESS_DENIED:
  222. this->setAccessDenied();
  223. return;
  224. default:
  225. return;
  226. }
  227. } else {
  228. this->setNotFound();
  229. return;
  230. }
  231. }
  232. TRACE("requesting netconf for network %.16llx from controller %s",(unsigned long long)_id,controller().toString().c_str());
  233. // TODO: in the future we will include things like join tokens here, etc.
  234. Dictionary metaData;
  235. metaData.setHex(ZT_NETWORKCONFIG_REQUEST_METADATA_KEY_NODE_MAJOR_VERSION,ZEROTIER_ONE_VERSION_MAJOR);
  236. metaData.setHex(ZT_NETWORKCONFIG_REQUEST_METADATA_KEY_NODE_MINOR_VERSION,ZEROTIER_ONE_VERSION_MINOR);
  237. metaData.setHex(ZT_NETWORKCONFIG_REQUEST_METADATA_KEY_NODE_REVISION,ZEROTIER_ONE_VERSION_REVISION);
  238. std::string mds(metaData.toString());
  239. Packet outp(controller(),RR->identity.address(),Packet::VERB_NETWORK_CONFIG_REQUEST);
  240. outp.append((uint64_t)_id);
  241. outp.append((uint16_t)mds.length());
  242. outp.append((const void *)mds.data(),(unsigned int)mds.length());
  243. {
  244. Mutex::Lock _l(_lock);
  245. if (_config)
  246. outp.append((uint64_t)_config->revision());
  247. else outp.append((uint64_t)0);
  248. }
  249. RR->sw->send(outp,true,0);
  250. }
  251. bool Network::validateAndAddMembershipCertificate(const CertificateOfMembership &cert)
  252. {
  253. if (!cert) // sanity check
  254. return false;
  255. Mutex::Lock _l(_lock);
  256. CertificateOfMembership &old = _membershipCertificates[cert.issuedTo()];
  257. // Nothing to do if the cert hasn't changed -- we get duplicates due to zealous cert pushing
  258. if (old == cert)
  259. return true; // but if it's a duplicate of one we already accepted, return is 'true'
  260. // Check signature, log and return if cert is invalid
  261. if (cert.signedBy() != controller()) {
  262. TRACE("rejected network membership certificate for %.16llx signed by %s: signer not a controller of this network",(unsigned long long)_id,cert.signedBy().toString().c_str());
  263. return false; // invalid signer
  264. }
  265. if (cert.signedBy() == RR->identity.address()) {
  266. // We are the controller: RR->identity.address() == controller() == cert.signedBy()
  267. // So, verify that we signed th cert ourself
  268. if (!cert.verify(RR->identity)) {
  269. TRACE("rejected network membership certificate for %.16llx self signed by %s: signature check failed",(unsigned long long)_id,cert.signedBy().toString().c_str());
  270. return false; // invalid signature
  271. }
  272. } else {
  273. SharedPtr<Peer> signer(RR->topology->getPeer(cert.signedBy()));
  274. if (!signer) {
  275. // This would be rather odd, since this is our controller... could happen
  276. // if we get packets before we've gotten config.
  277. RR->sw->requestWhois(cert.signedBy());
  278. return false; // signer unknown
  279. }
  280. if (!cert.verify(signer->identity())) {
  281. TRACE("rejected network membership certificate for %.16llx signed by %s: signature check failed",(unsigned long long)_id,cert.signedBy().toString().c_str());
  282. return false; // invalid signature
  283. }
  284. }
  285. // If we made it past authentication, update cert
  286. if (cert.revision() != old.revision())
  287. old = cert;
  288. return true;
  289. }
  290. bool Network::peerNeedsOurMembershipCertificate(const Address &to,uint64_t now)
  291. {
  292. Mutex::Lock _l(_lock);
  293. if ((_config)&&(!_config->isPublic())&&(_config->com())) {
  294. uint64_t &lastPushed = _lastPushedMembershipCertificate[to];
  295. if ((now - lastPushed) > (ZT_NETWORK_AUTOCONF_DELAY / 2)) {
  296. lastPushed = now;
  297. return true;
  298. }
  299. }
  300. return false;
  301. }
  302. void Network::clean()
  303. {
  304. const uint64_t now = RR->node->now();
  305. Mutex::Lock _l(_lock);
  306. if (_destroyed)
  307. return;
  308. if ((_config)&&(_config->isPublic())) {
  309. // Open (public) networks do not track certs or cert pushes at all.
  310. _membershipCertificates.clear();
  311. _lastPushedMembershipCertificate.clear();
  312. } else if (_config) {
  313. // Clean certificates that are no longer valid from the cache.
  314. for(std::map<Address,CertificateOfMembership>::iterator c=(_membershipCertificates.begin());c!=_membershipCertificates.end();) {
  315. if (_config->com().agreesWith(c->second))
  316. ++c;
  317. else _membershipCertificates.erase(c++);
  318. }
  319. // Clean entries from the last pushed tracking map if they're so old as
  320. // to be no longer relevant.
  321. uint64_t forgetIfBefore = now - (ZT_PEER_ACTIVITY_TIMEOUT * 16); // arbitrary reasonable cutoff
  322. for(std::map<Address,uint64_t>::iterator lp(_lastPushedMembershipCertificate.begin());lp!=_lastPushedMembershipCertificate.end();) {
  323. if (lp->second < forgetIfBefore)
  324. _lastPushedMembershipCertificate.erase(lp++);
  325. else ++lp;
  326. }
  327. }
  328. // Clean learned multicast groups if we haven't heard from them in a while
  329. for(std::map<MulticastGroup,uint64_t>::iterator mg(_multicastGroupsBehindMe.begin());mg!=_multicastGroupsBehindMe.end();) {
  330. if ((now - mg->second) > (ZT_MULTICAST_LIKE_EXPIRE * 2))
  331. _multicastGroupsBehindMe.erase(mg++);
  332. else ++mg;
  333. }
  334. }
  335. void Network::learnBridgeRoute(const MAC &mac,const Address &addr)
  336. {
  337. Mutex::Lock _l(_lock);
  338. _remoteBridgeRoutes[mac] = addr;
  339. // If _remoteBridgeRoutes exceeds sanity limit, trim worst offenders until below -- denial of service circuit breaker
  340. while (_remoteBridgeRoutes.size() > ZT_MAX_BRIDGE_ROUTES) {
  341. std::map<Address,unsigned long> counts;
  342. Address maxAddr;
  343. unsigned long maxCount = 0;
  344. for(std::map<MAC,Address>::iterator br(_remoteBridgeRoutes.begin());br!=_remoteBridgeRoutes.end();++br) {
  345. unsigned long c = ++counts[br->second];
  346. if (c > maxCount) {
  347. maxCount = c;
  348. maxAddr = br->second;
  349. }
  350. }
  351. for(std::map<MAC,Address>::iterator br(_remoteBridgeRoutes.begin());br!=_remoteBridgeRoutes.end();) {
  352. if (br->second == maxAddr)
  353. _remoteBridgeRoutes.erase(br++);
  354. else ++br;
  355. }
  356. }
  357. }
  358. void Network::learnBridgedMulticastGroup(const MulticastGroup &mg,uint64_t now)
  359. {
  360. Mutex::Lock _l(_lock);
  361. unsigned long tmp = (unsigned long)_multicastGroupsBehindMe.size();
  362. _multicastGroupsBehindMe[mg] = now;
  363. if (tmp != _multicastGroupsBehindMe.size())
  364. _announceMulticastGroups();
  365. }
  366. void Network::setEnabled(bool enabled)
  367. {
  368. Mutex::Lock _l(_lock);
  369. if (_enabled != enabled) {
  370. _enabled = enabled;
  371. ZT1_VirtualNetworkConfig ctmp;
  372. _externalConfig(&ctmp);
  373. _portError = RR->node->configureVirtualNetworkPort(_id,ZT1_VIRTUAL_NETWORK_CONFIG_OPERATION_CONFIG_UPDATE,&ctmp);
  374. }
  375. }
  376. void Network::destroy()
  377. {
  378. Mutex::Lock _l(_lock);
  379. _enabled = false;
  380. _destroyed = true;
  381. }
  382. ZT1_VirtualNetworkStatus Network::_status() const
  383. {
  384. // assumes _lock is locked
  385. if (_portError)
  386. return ZT1_NETWORK_STATUS_PORT_ERROR;
  387. switch(_netconfFailure) {
  388. case NETCONF_FAILURE_ACCESS_DENIED:
  389. return ZT1_NETWORK_STATUS_ACCESS_DENIED;
  390. case NETCONF_FAILURE_NOT_FOUND:
  391. return ZT1_NETWORK_STATUS_NOT_FOUND;
  392. case NETCONF_FAILURE_NONE:
  393. return ((_config) ? ZT1_NETWORK_STATUS_OK : ZT1_NETWORK_STATUS_REQUESTING_CONFIGURATION);
  394. default:
  395. return ZT1_NETWORK_STATUS_PORT_ERROR;
  396. }
  397. }
  398. void Network::_externalConfig(ZT1_VirtualNetworkConfig *ec) const
  399. {
  400. // assumes _lock is locked
  401. ec->nwid = _id;
  402. ec->mac = _mac.toInt();
  403. if (_config)
  404. Utils::scopy(ec->name,sizeof(ec->name),_config->name().c_str());
  405. else ec->name[0] = (char)0;
  406. ec->status = _status();
  407. ec->type = (_config) ? (_config->isPrivate() ? ZT1_NETWORK_TYPE_PRIVATE : ZT1_NETWORK_TYPE_PUBLIC) : ZT1_NETWORK_TYPE_PRIVATE;
  408. ec->mtu = ZT_IF_MTU;
  409. ec->dhcp = 0;
  410. ec->bridge = (_config) ? ((_config->allowPassiveBridging() || (std::find(_config->activeBridges().begin(),_config->activeBridges().end(),RR->identity.address()) != _config->activeBridges().end())) ? 1 : 0) : 0;
  411. ec->broadcastEnabled = (_config) ? (_config->enableBroadcast() ? 1 : 0) : 0;
  412. ec->portError = _portError;
  413. ec->enabled = (_enabled) ? 1 : 0;
  414. ec->netconfRevision = (_config) ? (unsigned long)_config->revision() : 0;
  415. ec->multicastSubscriptionCount = std::min((unsigned int)_myMulticastGroups.size(),(unsigned int)ZT1_MAX_NETWORK_MULTICAST_SUBSCRIPTIONS);
  416. for(unsigned int i=0;i<ec->multicastSubscriptionCount;++i) {
  417. ec->multicastSubscriptions[i].mac = _myMulticastGroups[i].mac().toInt();
  418. ec->multicastSubscriptions[i].adi = _myMulticastGroups[i].adi();
  419. }
  420. if (_config) {
  421. ec->assignedAddressCount = (unsigned int)_config->staticIps().size();
  422. for(unsigned long i=0;i<ZT1_MAX_ZT_ASSIGNED_ADDRESSES;++i) {
  423. if (i < _config->staticIps().size())
  424. memcpy(&(ec->assignedAddresses[i]),&(_config->staticIps()[i]),sizeof(struct sockaddr_storage));
  425. }
  426. } else ec->assignedAddressCount = 0;
  427. }
  428. bool Network::_isAllowed(const Address &peer) const
  429. {
  430. // Assumes _lock is locked
  431. try {
  432. if (!_config)
  433. return false;
  434. if (_config->isPublic())
  435. return true;
  436. std::map<Address,CertificateOfMembership>::const_iterator pc(_membershipCertificates.find(peer));
  437. if (pc == _membershipCertificates.end())
  438. return false; // no certificate on file
  439. return _config->com().agreesWith(pc->second); // is other cert valid against ours?
  440. } catch (std::exception &exc) {
  441. TRACE("isAllowed() check failed for peer %s: unexpected exception: %s",peer.toString().c_str(),exc.what());
  442. } catch ( ... ) {
  443. TRACE("isAllowed() check failed for peer %s: unexpected exception: unknown exception",peer.toString().c_str());
  444. }
  445. return false; // default position on any failure
  446. }
  447. std::vector<MulticastGroup> Network::_allMulticastGroups() const
  448. {
  449. // Assumes _lock is locked
  450. std::vector<MulticastGroup> mgs;
  451. mgs.reserve(_myMulticastGroups.size() + _multicastGroupsBehindMe.size() + 1);
  452. mgs.insert(mgs.end(),_myMulticastGroups.begin(),_myMulticastGroups.end());
  453. for(std::map< MulticastGroup,uint64_t >::const_iterator i(_multicastGroupsBehindMe.begin());i!=_multicastGroupsBehindMe.end();++i)
  454. mgs.push_back(i->first);
  455. if ((_config)&&(_config->enableBroadcast()))
  456. mgs.push_back(Network::BROADCAST);
  457. std::sort(mgs.begin(),mgs.end());
  458. mgs.erase(std::unique(mgs.begin(),mgs.end()),mgs.end());
  459. return mgs;
  460. }
  461. // Used in Network::_announceMulticastGroups()
  462. class _AnnounceMulticastGroupsToPeersWithActiveDirectPaths
  463. {
  464. public:
  465. _AnnounceMulticastGroupsToPeersWithActiveDirectPaths(const RuntimeEnvironment *renv,Network *nw) :
  466. RR(renv),
  467. _now(renv->node->now()),
  468. _network(nw),
  469. _rootAddresses(renv->topology->rootAddresses()),
  470. _allMulticastGroups(nw->_allMulticastGroups())
  471. {}
  472. inline void operator()(Topology &t,const SharedPtr<Peer> &p)
  473. {
  474. if ( ( (p->hasActiveDirectPath(_now)) && (_network->_isAllowed(p->address())) ) || (std::find(_rootAddresses.begin(),_rootAddresses.end(),p->address()) != _rootAddresses.end()) ) {
  475. Packet outp(p->address(),RR->identity.address(),Packet::VERB_MULTICAST_LIKE);
  476. for(std::vector<MulticastGroup>::iterator mg(_allMulticastGroups.begin());mg!=_allMulticastGroups.end();++mg) {
  477. if ((outp.size() + 18) >= ZT_UDP_DEFAULT_PAYLOAD_MTU) {
  478. outp.armor(p->key(),true);
  479. p->send(RR,outp.data(),outp.size(),_now);
  480. outp.reset(p->address(),RR->identity.address(),Packet::VERB_MULTICAST_LIKE);
  481. }
  482. // network ID, MAC, ADI
  483. outp.append((uint64_t)_network->id());
  484. mg->mac().appendTo(outp);
  485. outp.append((uint32_t)mg->adi());
  486. }
  487. if (outp.size() > ZT_PROTO_MIN_PACKET_LENGTH) {
  488. outp.armor(p->key(),true);
  489. p->send(RR,outp.data(),outp.size(),_now);
  490. }
  491. }
  492. }
  493. private:
  494. const RuntimeEnvironment *RR;
  495. uint64_t _now;
  496. Network *_network;
  497. std::vector<Address> _rootAddresses;
  498. std::vector<MulticastGroup> _allMulticastGroups;
  499. };
  500. void Network::_announceMulticastGroups()
  501. {
  502. // Assumes _lock is locked
  503. _AnnounceMulticastGroupsToPeersWithActiveDirectPaths afunc(RR,this);
  504. RR->topology->eachPeer<_AnnounceMulticastGroupsToPeersWithActiveDirectPaths &>(afunc);
  505. }
  506. } // namespace ZeroTier