Network.cpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583
  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. _certInfo[com.issuedTo()].com = com;
  86. }
  87. }
  88. }
  89. } catch ( ... ) {} // ignore invalid MCDB, we'll re-learn from peers
  90. }
  91. if (!_portInitialized) {
  92. ZT_VirtualNetworkConfig ctmp;
  93. _externalConfig(&ctmp);
  94. _portError = RR->node->configureVirtualNetworkPort(_id,ZT_VIRTUAL_NETWORK_CONFIG_OPERATION_UP,&ctmp);
  95. _portInitialized = true;
  96. }
  97. }
  98. Network::~Network()
  99. {
  100. ZT_VirtualNetworkConfig ctmp;
  101. _externalConfig(&ctmp);
  102. char n[128];
  103. if (_destroyed) {
  104. RR->node->configureVirtualNetworkPort(_id,ZT_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,ZT_VIRTUAL_NETWORK_CONFIG_OPERATION_DOWN,&ctmp);
  111. clean();
  112. Utils::snprintf(n,sizeof(n),"networks.d/%.16llx.mcerts",_id);
  113. Mutex::Lock _l(_lock);
  114. if ((!_config)||(_config->isPublic())||(_certInfo.empty())) {
  115. RR->node->dataStoreDelete(n);
  116. } else {
  117. std::string buf("ZTMCD0");
  118. Hashtable< Address,_RemoteMemberCertificateInfo >::Iterator i(_certInfo);
  119. Address *a = (Address *)0;
  120. _RemoteMemberCertificateInfo *ci = (_RemoteMemberCertificateInfo *)0;
  121. while (i.next(a,ci)) {
  122. if (ci->com)
  123. ci->com.serialize2(buf);
  124. }
  125. RR->node->dataStorePut(n,buf,true);
  126. }
  127. }
  128. }
  129. bool Network::subscribedToMulticastGroup(const MulticastGroup &mg,bool includeBridgedGroups) const
  130. {
  131. Mutex::Lock _l(_lock);
  132. if (std::binary_search(_myMulticastGroups.begin(),_myMulticastGroups.end(),mg))
  133. return true;
  134. else if (includeBridgedGroups)
  135. return _multicastGroupsBehindMe.contains(mg);
  136. else return false;
  137. }
  138. void Network::multicastSubscribe(const MulticastGroup &mg)
  139. {
  140. {
  141. Mutex::Lock _l(_lock);
  142. if (std::binary_search(_myMulticastGroups.begin(),_myMulticastGroups.end(),mg))
  143. return;
  144. _myMulticastGroups.push_back(mg);
  145. std::sort(_myMulticastGroups.begin(),_myMulticastGroups.end());
  146. }
  147. _announceMulticastGroups();
  148. }
  149. void Network::multicastUnsubscribe(const MulticastGroup &mg)
  150. {
  151. Mutex::Lock _l(_lock);
  152. std::vector<MulticastGroup> nmg;
  153. for(std::vector<MulticastGroup>::const_iterator i(_myMulticastGroups.begin());i!=_myMulticastGroups.end();++i) {
  154. if (*i != mg)
  155. nmg.push_back(*i);
  156. }
  157. if (nmg.size() != _myMulticastGroups.size())
  158. _myMulticastGroups.swap(nmg);
  159. }
  160. bool Network::applyConfiguration(const SharedPtr<NetworkConfig> &conf)
  161. {
  162. if (_destroyed) // sanity check
  163. return false;
  164. try {
  165. if ((conf->networkId() == _id)&&(conf->issuedTo() == RR->identity.address())) {
  166. ZT_VirtualNetworkConfig ctmp;
  167. bool portInitialized;
  168. {
  169. Mutex::Lock _l(_lock);
  170. _config = conf;
  171. _lastConfigUpdate = RR->node->now();
  172. _netconfFailure = NETCONF_FAILURE_NONE;
  173. _externalConfig(&ctmp);
  174. portInitialized = _portInitialized;
  175. _portInitialized = true;
  176. }
  177. _portError = RR->node->configureVirtualNetworkPort(_id,(portInitialized) ? ZT_VIRTUAL_NETWORK_CONFIG_OPERATION_CONFIG_UPDATE : ZT_VIRTUAL_NETWORK_CONFIG_OPERATION_UP,&ctmp);
  178. return true;
  179. } else {
  180. TRACE("ignored invalid configuration for network %.16llx (configuration contains mismatched network ID or issued-to address)",(unsigned long long)_id);
  181. }
  182. } catch (std::exception &exc) {
  183. TRACE("ignored invalid configuration for network %.16llx (%s)",(unsigned long long)_id,exc.what());
  184. } catch ( ... ) {
  185. TRACE("ignored invalid configuration for network %.16llx (unknown exception)",(unsigned long long)_id);
  186. }
  187. return false;
  188. }
  189. int Network::setConfiguration(const Dictionary &conf,bool saveToDisk)
  190. {
  191. try {
  192. const SharedPtr<NetworkConfig> newConfig(new NetworkConfig(conf)); // throws if invalid
  193. {
  194. Mutex::Lock _l(_lock);
  195. if ((_config)&&(*_config == *newConfig))
  196. return 1; // OK config, but duplicate of what we already have
  197. }
  198. if (applyConfiguration(newConfig)) {
  199. if (saveToDisk) {
  200. char n[128];
  201. Utils::snprintf(n,sizeof(n),"networks.d/%.16llx.conf",_id);
  202. RR->node->dataStorePut(n,conf.toString(),true);
  203. }
  204. return 2; // OK and configuration has changed
  205. }
  206. } catch ( ... ) {
  207. TRACE("ignored invalid configuration for network %.16llx (dictionary decode failed)",(unsigned long long)_id);
  208. }
  209. return 0;
  210. }
  211. void Network::requestConfiguration()
  212. {
  213. if (_id == ZT_TEST_NETWORK_ID) // pseudo-network-ID, uses locally generated static config
  214. return;
  215. if (controller() == RR->identity.address()) {
  216. if (RR->localNetworkController) {
  217. SharedPtr<NetworkConfig> nconf(config2());
  218. Dictionary newconf;
  219. switch(RR->localNetworkController->doNetworkConfigRequest(InetAddress(),RR->identity,RR->identity,_id,Dictionary(),newconf)) {
  220. case NetworkController::NETCONF_QUERY_OK:
  221. this->setConfiguration(newconf,true);
  222. return;
  223. case NetworkController::NETCONF_QUERY_OBJECT_NOT_FOUND:
  224. this->setNotFound();
  225. return;
  226. case NetworkController::NETCONF_QUERY_ACCESS_DENIED:
  227. this->setAccessDenied();
  228. return;
  229. default:
  230. return;
  231. }
  232. } else {
  233. this->setNotFound();
  234. return;
  235. }
  236. }
  237. TRACE("requesting netconf for network %.16llx from controller %s",(unsigned long long)_id,controller().toString().c_str());
  238. // TODO: in the future we will include things like join tokens here, etc.
  239. Dictionary metaData;
  240. metaData.setHex(ZT_NETWORKCONFIG_REQUEST_METADATA_KEY_NODE_MAJOR_VERSION,ZEROTIER_ONE_VERSION_MAJOR);
  241. metaData.setHex(ZT_NETWORKCONFIG_REQUEST_METADATA_KEY_NODE_MINOR_VERSION,ZEROTIER_ONE_VERSION_MINOR);
  242. metaData.setHex(ZT_NETWORKCONFIG_REQUEST_METADATA_KEY_NODE_REVISION,ZEROTIER_ONE_VERSION_REVISION);
  243. std::string mds(metaData.toString());
  244. Packet outp(controller(),RR->identity.address(),Packet::VERB_NETWORK_CONFIG_REQUEST);
  245. outp.append((uint64_t)_id);
  246. outp.append((uint16_t)mds.length());
  247. outp.append((const void *)mds.data(),(unsigned int)mds.length());
  248. {
  249. Mutex::Lock _l(_lock);
  250. if (_config)
  251. outp.append((uint64_t)_config->revision());
  252. else outp.append((uint64_t)0);
  253. }
  254. RR->sw->send(outp,true,0);
  255. }
  256. bool Network::validateAndAddMembershipCertificate(const CertificateOfMembership &cert)
  257. {
  258. if (!cert) // sanity check
  259. return false;
  260. Mutex::Lock _l(_lock);
  261. {
  262. const _RemoteMemberCertificateInfo *ci = _certInfo.get(cert.issuedTo());
  263. if ((ci)&&(ci->com == cert))
  264. return true; // we already have it
  265. }
  266. // Check signature, log and return if cert is invalid
  267. if (cert.signedBy() != controller()) {
  268. 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());
  269. return false; // invalid signer
  270. }
  271. if (cert.signedBy() == RR->identity.address()) {
  272. // We are the controller: RR->identity.address() == controller() == cert.signedBy()
  273. // So, verify that we signed th cert ourself
  274. if (!cert.verify(RR->identity)) {
  275. TRACE("rejected network membership certificate for %.16llx self signed by %s: signature check failed",(unsigned long long)_id,cert.signedBy().toString().c_str());
  276. return false; // invalid signature
  277. }
  278. } else {
  279. SharedPtr<Peer> signer(RR->topology->getPeer(cert.signedBy()));
  280. if (!signer) {
  281. // This would be rather odd, since this is our controller... could happen
  282. // if we get packets before we've gotten config.
  283. RR->sw->requestWhois(cert.signedBy());
  284. return false; // signer unknown
  285. }
  286. if (!cert.verify(signer->identity())) {
  287. TRACE("rejected network membership certificate for %.16llx signed by %s: signature check failed",(unsigned long long)_id,cert.signedBy().toString().c_str());
  288. return false; // invalid signature
  289. }
  290. }
  291. // If we made it past authentication, add or update cert in our cert info store
  292. _certInfo[cert.issuedTo()].com = cert;
  293. return true;
  294. }
  295. bool Network::peerNeedsOurMembershipCertificate(const Address &to,uint64_t now)
  296. {
  297. Mutex::Lock _l(_lock);
  298. if ((_config)&&(!_config->isPublic())&&(_config->com())) {
  299. _RemoteMemberCertificateInfo &ci = _certInfo[to];
  300. if ((now - ci.lastPushed) > (ZT_NETWORK_AUTOCONF_DELAY / 2)) {
  301. ci.lastPushed = now;
  302. return true;
  303. }
  304. }
  305. return false;
  306. }
  307. void Network::clean()
  308. {
  309. const uint64_t now = RR->node->now();
  310. Mutex::Lock _l(_lock);
  311. if (_destroyed)
  312. return;
  313. if ((_config)&&(_config->isPublic())) {
  314. // Open (public) networks do not track certs or cert pushes at all.
  315. _certInfo.clear();
  316. } else if (_config) {
  317. // Clean obsolete entries from private network cert info table
  318. Hashtable< Address,_RemoteMemberCertificateInfo >::Iterator i(_certInfo);
  319. Address *a = (Address *)0;
  320. _RemoteMemberCertificateInfo *ci = (_RemoteMemberCertificateInfo *)0;
  321. const uint64_t forgetIfBefore = now - (ZT_PEER_ACTIVITY_TIMEOUT * 16); // arbitrary reasonable cutoff
  322. while (i.next(a,ci)) {
  323. if ((ci->lastPushed < forgetIfBefore)&&(!ci->com.agreesWith(_config->com())))
  324. _certInfo.erase(*a);
  325. }
  326. }
  327. // Clean learned multicast groups if we haven't heard from them in a while
  328. {
  329. Hashtable< MulticastGroup,uint64_t >::Iterator i(_multicastGroupsBehindMe);
  330. MulticastGroup *mg = (MulticastGroup *)0;
  331. uint64_t *ts = (uint64_t *)0;
  332. while (i.next(mg,ts)) {
  333. if ((now - *ts) > (ZT_MULTICAST_LIKE_EXPIRE * 2))
  334. _multicastGroupsBehindMe.erase(*mg);
  335. }
  336. }
  337. }
  338. void Network::learnBridgeRoute(const MAC &mac,const Address &addr)
  339. {
  340. Mutex::Lock _l(_lock);
  341. _remoteBridgeRoutes[mac] = addr;
  342. // Anti-DOS circuit breaker to prevent nodes from spamming us with absurd numbers of bridge routes
  343. while (_remoteBridgeRoutes.size() > ZT_MAX_BRIDGE_ROUTES) {
  344. Hashtable< Address,unsigned long > counts;
  345. Address maxAddr;
  346. unsigned long maxCount = 0;
  347. MAC *m = (MAC *)0;
  348. Address *a = (Address *)0;
  349. // Find the address responsible for the most entries
  350. {
  351. Hashtable<MAC,Address>::Iterator i(_remoteBridgeRoutes);
  352. while (i.next(m,a)) {
  353. const unsigned long c = ++counts[*a];
  354. if (c > maxCount) {
  355. maxCount = c;
  356. maxAddr = *a;
  357. }
  358. }
  359. }
  360. // Kill this address from our table, since it's most likely spamming us
  361. {
  362. Hashtable<MAC,Address>::Iterator i(_remoteBridgeRoutes);
  363. while (i.next(m,a)) {
  364. if (*a == maxAddr)
  365. _remoteBridgeRoutes.erase(*m);
  366. }
  367. }
  368. }
  369. }
  370. void Network::learnBridgedMulticastGroup(const MulticastGroup &mg,uint64_t now)
  371. {
  372. Mutex::Lock _l(_lock);
  373. const unsigned long tmp = (unsigned long)_multicastGroupsBehindMe.size();
  374. _multicastGroupsBehindMe.set(mg,now);
  375. if (tmp != _multicastGroupsBehindMe.size())
  376. _announceMulticastGroups();
  377. }
  378. void Network::setEnabled(bool enabled)
  379. {
  380. Mutex::Lock _l(_lock);
  381. if (_enabled != enabled) {
  382. _enabled = enabled;
  383. ZT_VirtualNetworkConfig ctmp;
  384. _externalConfig(&ctmp);
  385. _portError = RR->node->configureVirtualNetworkPort(_id,ZT_VIRTUAL_NETWORK_CONFIG_OPERATION_CONFIG_UPDATE,&ctmp);
  386. }
  387. }
  388. void Network::destroy()
  389. {
  390. Mutex::Lock _l(_lock);
  391. _enabled = false;
  392. _destroyed = true;
  393. }
  394. ZT_VirtualNetworkStatus Network::_status() const
  395. {
  396. // assumes _lock is locked
  397. if (_portError)
  398. return ZT_NETWORK_STATUS_PORT_ERROR;
  399. switch(_netconfFailure) {
  400. case NETCONF_FAILURE_ACCESS_DENIED:
  401. return ZT_NETWORK_STATUS_ACCESS_DENIED;
  402. case NETCONF_FAILURE_NOT_FOUND:
  403. return ZT_NETWORK_STATUS_NOT_FOUND;
  404. case NETCONF_FAILURE_NONE:
  405. return ((_config) ? ZT_NETWORK_STATUS_OK : ZT_NETWORK_STATUS_REQUESTING_CONFIGURATION);
  406. default:
  407. return ZT_NETWORK_STATUS_PORT_ERROR;
  408. }
  409. }
  410. void Network::_externalConfig(ZT_VirtualNetworkConfig *ec) const
  411. {
  412. // assumes _lock is locked
  413. ec->nwid = _id;
  414. ec->mac = _mac.toInt();
  415. if (_config)
  416. Utils::scopy(ec->name,sizeof(ec->name),_config->name().c_str());
  417. else ec->name[0] = (char)0;
  418. ec->status = _status();
  419. ec->type = (_config) ? (_config->isPrivate() ? ZT_NETWORK_TYPE_PRIVATE : ZT_NETWORK_TYPE_PUBLIC) : ZT_NETWORK_TYPE_PRIVATE;
  420. ec->mtu = ZT_IF_MTU;
  421. ec->dhcp = 0;
  422. ec->bridge = (_config) ? ((_config->allowPassiveBridging() || (std::find(_config->activeBridges().begin(),_config->activeBridges().end(),RR->identity.address()) != _config->activeBridges().end())) ? 1 : 0) : 0;
  423. ec->broadcastEnabled = (_config) ? (_config->enableBroadcast() ? 1 : 0) : 0;
  424. ec->portError = _portError;
  425. ec->enabled = (_enabled) ? 1 : 0;
  426. ec->netconfRevision = (_config) ? (unsigned long)_config->revision() : 0;
  427. ec->multicastSubscriptionCount = std::min((unsigned int)_myMulticastGroups.size(),(unsigned int)ZT_MAX_NETWORK_MULTICAST_SUBSCRIPTIONS);
  428. for(unsigned int i=0;i<ec->multicastSubscriptionCount;++i) {
  429. ec->multicastSubscriptions[i].mac = _myMulticastGroups[i].mac().toInt();
  430. ec->multicastSubscriptions[i].adi = _myMulticastGroups[i].adi();
  431. }
  432. if (_config) {
  433. ec->assignedAddressCount = (unsigned int)_config->staticIps().size();
  434. for(unsigned long i=0;i<ZT_MAX_ZT_ASSIGNED_ADDRESSES;++i) {
  435. if (i < _config->staticIps().size())
  436. memcpy(&(ec->assignedAddresses[i]),&(_config->staticIps()[i]),sizeof(struct sockaddr_storage));
  437. }
  438. } else ec->assignedAddressCount = 0;
  439. }
  440. bool Network::_isAllowed(const Address &peer) const
  441. {
  442. // Assumes _lock is locked
  443. try {
  444. if (!_config)
  445. return false;
  446. if (_config->isPublic())
  447. return true;
  448. const _RemoteMemberCertificateInfo *ci = _certInfo.get(peer);
  449. if (!ci)
  450. return false;
  451. return _config->com().agreesWith(ci->com);
  452. } catch (std::exception &exc) {
  453. TRACE("isAllowed() check failed for peer %s: unexpected exception: %s",peer.toString().c_str(),exc.what());
  454. } catch ( ... ) {
  455. TRACE("isAllowed() check failed for peer %s: unexpected exception: unknown exception",peer.toString().c_str());
  456. }
  457. return false; // default position on any failure
  458. }
  459. std::vector<MulticastGroup> Network::_allMulticastGroups() const
  460. {
  461. // Assumes _lock is locked
  462. std::vector<MulticastGroup> mgs;
  463. mgs.reserve(_myMulticastGroups.size() + _multicastGroupsBehindMe.size() + 1);
  464. mgs.insert(mgs.end(),_myMulticastGroups.begin(),_myMulticastGroups.end());
  465. _multicastGroupsBehindMe.appendKeys(mgs);
  466. if ((_config)&&(_config->enableBroadcast()))
  467. mgs.push_back(Network::BROADCAST);
  468. std::sort(mgs.begin(),mgs.end());
  469. mgs.erase(std::unique(mgs.begin(),mgs.end()),mgs.end());
  470. return mgs;
  471. }
  472. // Used in Network::_announceMulticastGroups()
  473. class _AnnounceMulticastGroupsToPeersWithActiveDirectPaths
  474. {
  475. public:
  476. _AnnounceMulticastGroupsToPeersWithActiveDirectPaths(const RuntimeEnvironment *renv,Network *nw) :
  477. RR(renv),
  478. _now(renv->node->now()),
  479. _network(nw),
  480. _rootAddresses(renv->topology->rootAddresses()),
  481. _allMulticastGroups(nw->_allMulticastGroups())
  482. {}
  483. inline void operator()(Topology &t,const SharedPtr<Peer> &p)
  484. {
  485. if ( ( (p->hasActiveDirectPath(_now)) && ( (_network->_isAllowed(p->address())) || (p->address() == _network->controller()) ) ) || (std::find(_rootAddresses.begin(),_rootAddresses.end(),p->address()) != _rootAddresses.end()) ) {
  486. Packet outp(p->address(),RR->identity.address(),Packet::VERB_MULTICAST_LIKE);
  487. for(std::vector<MulticastGroup>::iterator mg(_allMulticastGroups.begin());mg!=_allMulticastGroups.end();++mg) {
  488. if ((outp.size() + 18) >= ZT_UDP_DEFAULT_PAYLOAD_MTU) {
  489. outp.armor(p->key(),true);
  490. p->send(RR,outp.data(),outp.size(),_now);
  491. outp.reset(p->address(),RR->identity.address(),Packet::VERB_MULTICAST_LIKE);
  492. }
  493. // network ID, MAC, ADI
  494. outp.append((uint64_t)_network->id());
  495. mg->mac().appendTo(outp);
  496. outp.append((uint32_t)mg->adi());
  497. }
  498. if (outp.size() > ZT_PROTO_MIN_PACKET_LENGTH) {
  499. outp.armor(p->key(),true);
  500. p->send(RR,outp.data(),outp.size(),_now);
  501. }
  502. }
  503. }
  504. private:
  505. const RuntimeEnvironment *RR;
  506. uint64_t _now;
  507. Network *_network;
  508. std::vector<Address> _rootAddresses;
  509. std::vector<MulticastGroup> _allMulticastGroups;
  510. };
  511. void Network::_announceMulticastGroups()
  512. {
  513. // Assumes _lock is locked
  514. _AnnounceMulticastGroupsToPeersWithActiveDirectPaths afunc(RR,this);
  515. RR->topology->eachPeer<_AnnounceMulticastGroupsToPeersWithActiveDirectPaths &>(afunc);
  516. }
  517. } // namespace ZeroTier