Network.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513
  1. /*
  2. * ZeroTier One - Network Virtualization Everywhere
  3. * Copyright (C) 2011-2016 ZeroTier, Inc. https://www.zerotier.com/
  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. #include <stdio.h>
  19. #include <string.h>
  20. #include <stdlib.h>
  21. #include <math.h>
  22. #include "Constants.hpp"
  23. #include "Network.hpp"
  24. #include "RuntimeEnvironment.hpp"
  25. #include "Switch.hpp"
  26. #include "Packet.hpp"
  27. #include "Buffer.hpp"
  28. #include "NetworkController.hpp"
  29. #include "Node.hpp"
  30. #include "../version.h"
  31. namespace ZeroTier {
  32. const ZeroTier::MulticastGroup Network::BROADCAST(ZeroTier::MAC(0xffffffffffffULL),0);
  33. Network::Network(const RuntimeEnvironment *renv,uint64_t nwid,void *uptr) :
  34. RR(renv),
  35. _uPtr(uptr),
  36. _id(nwid),
  37. _mac(renv->identity.address(),nwid),
  38. _enabled(true),
  39. _portInitialized(false),
  40. _lastConfigUpdate(0),
  41. _destroyed(false),
  42. _netconfFailure(NETCONF_FAILURE_NONE),
  43. _portError(0)
  44. {
  45. char confn[128],mcdbn[128];
  46. Utils::snprintf(confn,sizeof(confn),"networks.d/%.16llx.conf",_id);
  47. Utils::snprintf(mcdbn,sizeof(mcdbn),"networks.d/%.16llx.mcerts",_id);
  48. // These files are no longer used, so clean them.
  49. RR->node->dataStoreDelete(mcdbn);
  50. if (_id == ZT_TEST_NETWORK_ID) {
  51. applyConfiguration(NetworkConfig::createTestNetworkConfig(RR->identity.address()));
  52. // Save a one-byte CR to persist membership in the test network
  53. RR->node->dataStorePut(confn,"\n",1,false);
  54. } else {
  55. bool gotConf = false;
  56. try {
  57. std::string conf(RR->node->dataStoreGet(confn));
  58. if (conf.length()) {
  59. this->setConfiguration((const void *)conf.data(),(unsigned int)conf.length(),false);
  60. _lastConfigUpdate = 0; // we still want to re-request a new config from the network
  61. gotConf = true;
  62. }
  63. } catch ( ... ) {} // ignore invalids, we'll re-request
  64. if (!gotConf) {
  65. // Save a one-byte CR to persist membership while we request a real netconf
  66. RR->node->dataStorePut(confn,"\n",1,false);
  67. }
  68. }
  69. if (!_portInitialized) {
  70. ZT_VirtualNetworkConfig ctmp;
  71. _externalConfig(&ctmp);
  72. _portError = RR->node->configureVirtualNetworkPort(_id,&_uPtr,ZT_VIRTUAL_NETWORK_CONFIG_OPERATION_UP,&ctmp);
  73. _portInitialized = true;
  74. }
  75. }
  76. Network::~Network()
  77. {
  78. ZT_VirtualNetworkConfig ctmp;
  79. _externalConfig(&ctmp);
  80. char n[128];
  81. if (_destroyed) {
  82. RR->node->configureVirtualNetworkPort(_id,&_uPtr,ZT_VIRTUAL_NETWORK_CONFIG_OPERATION_DESTROY,&ctmp);
  83. Utils::snprintf(n,sizeof(n),"networks.d/%.16llx.conf",_id);
  84. RR->node->dataStoreDelete(n);
  85. } else {
  86. RR->node->configureVirtualNetworkPort(_id,&_uPtr,ZT_VIRTUAL_NETWORK_CONFIG_OPERATION_DOWN,&ctmp);
  87. }
  88. }
  89. bool Network::subscribedToMulticastGroup(const MulticastGroup &mg,bool includeBridgedGroups) const
  90. {
  91. Mutex::Lock _l(_lock);
  92. if (std::binary_search(_myMulticastGroups.begin(),_myMulticastGroups.end(),mg))
  93. return true;
  94. else if (includeBridgedGroups)
  95. return _multicastGroupsBehindMe.contains(mg);
  96. else return false;
  97. }
  98. void Network::multicastSubscribe(const MulticastGroup &mg)
  99. {
  100. {
  101. Mutex::Lock _l(_lock);
  102. if (std::binary_search(_myMulticastGroups.begin(),_myMulticastGroups.end(),mg))
  103. return;
  104. _myMulticastGroups.push_back(mg);
  105. std::sort(_myMulticastGroups.begin(),_myMulticastGroups.end());
  106. }
  107. _announceMulticastGroups();
  108. }
  109. void Network::multicastUnsubscribe(const MulticastGroup &mg)
  110. {
  111. Mutex::Lock _l(_lock);
  112. std::vector<MulticastGroup> nmg;
  113. for(std::vector<MulticastGroup>::const_iterator i(_myMulticastGroups.begin());i!=_myMulticastGroups.end();++i) {
  114. if (*i != mg)
  115. nmg.push_back(*i);
  116. }
  117. if (nmg.size() != _myMulticastGroups.size())
  118. _myMulticastGroups.swap(nmg);
  119. }
  120. bool Network::tryAnnounceMulticastGroupsTo(const SharedPtr<Peer> &peer)
  121. {
  122. Mutex::Lock _l(_lock);
  123. if (
  124. (_isAllowed(peer)) ||
  125. (peer->address() == this->controller()) ||
  126. (RR->topology->isRoot(peer->identity()))
  127. ) {
  128. _announceMulticastGroupsTo(peer,_allMulticastGroups());
  129. return true;
  130. }
  131. return false;
  132. }
  133. bool Network::applyConfiguration(const NetworkConfig &conf)
  134. {
  135. if (_destroyed) // sanity check
  136. return false;
  137. try {
  138. if ((conf.networkId == _id)&&(conf.issuedTo == RR->identity.address())) {
  139. ZT_VirtualNetworkConfig ctmp;
  140. bool portInitialized;
  141. {
  142. Mutex::Lock _l(_lock);
  143. _config = conf;
  144. _lastConfigUpdate = RR->node->now();
  145. _netconfFailure = NETCONF_FAILURE_NONE;
  146. _externalConfig(&ctmp);
  147. portInitialized = _portInitialized;
  148. _portInitialized = true;
  149. }
  150. _portError = RR->node->configureVirtualNetworkPort(_id,&_uPtr,(portInitialized) ? ZT_VIRTUAL_NETWORK_CONFIG_OPERATION_CONFIG_UPDATE : ZT_VIRTUAL_NETWORK_CONFIG_OPERATION_UP,&ctmp);
  151. return true;
  152. } else {
  153. TRACE("ignored invalid configuration for network %.16llx (configuration contains mismatched network ID or issued-to address)",(unsigned long long)_id);
  154. }
  155. } catch (std::exception &exc) {
  156. TRACE("ignored invalid configuration for network %.16llx (%s)",(unsigned long long)_id,exc.what());
  157. } catch ( ... ) {
  158. TRACE("ignored invalid configuration for network %.16llx (unknown exception)",(unsigned long long)_id);
  159. }
  160. return false;
  161. }
  162. int Network::setConfiguration(const void *confBytes,unsigned int confLen,bool saveToDisk)
  163. {
  164. try {
  165. if (confLen <= 1)
  166. return 0;
  167. NetworkConfig newConfig;
  168. // Find the length of any string-serialized old-style Dictionary,
  169. // including its terminating NULL (if any). If this is before
  170. // the end of the config, that tells us there is a new-style
  171. // binary config which is preferred.
  172. unsigned int dictLen = 0;
  173. while (dictLen < confLen) {
  174. if (!(reinterpret_cast<const uint8_t *>(confBytes)[dictLen++]))
  175. break;
  176. }
  177. if (dictLen < (confLen - 2)) {
  178. Buffer<8194> tmp(reinterpret_cast<const uint8_t *>(confBytes) + dictLen,confLen - dictLen);
  179. newConfig.deserialize(tmp,0);
  180. } else {
  181. #ifdef ZT_SUPPORT_OLD_STYLE_NETCONF
  182. newConfig.fromDictionary(reinterpret_cast<const char *>(confBytes),confLen); // throws if invalid
  183. #else
  184. return 0;
  185. #endif
  186. }
  187. if (!newConfig)
  188. return 0;
  189. {
  190. Mutex::Lock _l(_lock);
  191. if (_config == newConfig)
  192. return 1; // OK config, but duplicate of what we already have
  193. }
  194. if (applyConfiguration(newConfig)) {
  195. if (saveToDisk) {
  196. char n[128];
  197. Utils::snprintf(n,sizeof(n),"networks.d/%.16llx.conf",_id);
  198. RR->node->dataStorePut(n,confBytes,confLen,true);
  199. }
  200. return 2; // OK and configuration has changed
  201. }
  202. } catch ( ... ) {
  203. TRACE("ignored invalid configuration for network %.16llx",(unsigned long long)_id);
  204. }
  205. return 0;
  206. }
  207. void Network::requestConfiguration()
  208. {
  209. if (_id == ZT_TEST_NETWORK_ID) // pseudo-network-ID, uses locally generated static config
  210. return;
  211. if (controller() == RR->identity.address()) {
  212. if (RR->localNetworkController) {
  213. Buffer<8194> tmp;
  214. switch(RR->localNetworkController->doNetworkConfigRequest(InetAddress(),RR->identity,RR->identity,_id,NetworkConfigRequestMetaData(),tmp)) {
  215. case NetworkController::NETCONF_QUERY_OK:
  216. this->setConfiguration(tmp.data(),tmp.size(),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. NetworkConfigRequestMetaData metaData;
  234. metaData.initWithDefaults();
  235. Buffer<4096> mds;
  236. metaData.serialize(mds); // this always includes legacy fields to support old controllers
  237. Packet outp(controller(),RR->identity.address(),Packet::VERB_NETWORK_CONFIG_REQUEST);
  238. outp.append((uint64_t)_id);
  239. outp.append((uint16_t)mds.size());
  240. outp.append(mds.data(),mds.size());
  241. outp.append((_config) ? (uint64_t)_config.revision : (uint64_t)0);
  242. RR->sw->send(outp,true,0);
  243. }
  244. void Network::clean()
  245. {
  246. const uint64_t now = RR->node->now();
  247. Mutex::Lock _l(_lock);
  248. if (_destroyed)
  249. return;
  250. {
  251. Hashtable< MulticastGroup,uint64_t >::Iterator i(_multicastGroupsBehindMe);
  252. MulticastGroup *mg = (MulticastGroup *)0;
  253. uint64_t *ts = (uint64_t *)0;
  254. while (i.next(mg,ts)) {
  255. if ((now - *ts) > (ZT_MULTICAST_LIKE_EXPIRE * 2))
  256. _multicastGroupsBehindMe.erase(*mg);
  257. }
  258. }
  259. }
  260. void Network::learnBridgeRoute(const MAC &mac,const Address &addr)
  261. {
  262. Mutex::Lock _l(_lock);
  263. _remoteBridgeRoutes[mac] = addr;
  264. // Anti-DOS circuit breaker to prevent nodes from spamming us with absurd numbers of bridge routes
  265. while (_remoteBridgeRoutes.size() > ZT_MAX_BRIDGE_ROUTES) {
  266. Hashtable< Address,unsigned long > counts;
  267. Address maxAddr;
  268. unsigned long maxCount = 0;
  269. MAC *m = (MAC *)0;
  270. Address *a = (Address *)0;
  271. // Find the address responsible for the most entries
  272. {
  273. Hashtable<MAC,Address>::Iterator i(_remoteBridgeRoutes);
  274. while (i.next(m,a)) {
  275. const unsigned long c = ++counts[*a];
  276. if (c > maxCount) {
  277. maxCount = c;
  278. maxAddr = *a;
  279. }
  280. }
  281. }
  282. // Kill this address from our table, since it's most likely spamming us
  283. {
  284. Hashtable<MAC,Address>::Iterator i(_remoteBridgeRoutes);
  285. while (i.next(m,a)) {
  286. if (*a == maxAddr)
  287. _remoteBridgeRoutes.erase(*m);
  288. }
  289. }
  290. }
  291. }
  292. void Network::learnBridgedMulticastGroup(const MulticastGroup &mg,uint64_t now)
  293. {
  294. Mutex::Lock _l(_lock);
  295. const unsigned long tmp = (unsigned long)_multicastGroupsBehindMe.size();
  296. _multicastGroupsBehindMe.set(mg,now);
  297. if (tmp != _multicastGroupsBehindMe.size())
  298. _announceMulticastGroups();
  299. }
  300. void Network::setEnabled(bool enabled)
  301. {
  302. Mutex::Lock _l(_lock);
  303. if (_enabled != enabled) {
  304. _enabled = enabled;
  305. ZT_VirtualNetworkConfig ctmp;
  306. _externalConfig(&ctmp);
  307. _portError = RR->node->configureVirtualNetworkPort(_id,&_uPtr,ZT_VIRTUAL_NETWORK_CONFIG_OPERATION_CONFIG_UPDATE,&ctmp);
  308. }
  309. }
  310. void Network::destroy()
  311. {
  312. Mutex::Lock _l(_lock);
  313. _enabled = false;
  314. _destroyed = true;
  315. }
  316. ZT_VirtualNetworkStatus Network::_status() const
  317. {
  318. // assumes _lock is locked
  319. if (_portError)
  320. return ZT_NETWORK_STATUS_PORT_ERROR;
  321. switch(_netconfFailure) {
  322. case NETCONF_FAILURE_ACCESS_DENIED:
  323. return ZT_NETWORK_STATUS_ACCESS_DENIED;
  324. case NETCONF_FAILURE_NOT_FOUND:
  325. return ZT_NETWORK_STATUS_NOT_FOUND;
  326. case NETCONF_FAILURE_NONE:
  327. return ((_config) ? ZT_NETWORK_STATUS_OK : ZT_NETWORK_STATUS_REQUESTING_CONFIGURATION);
  328. default:
  329. return ZT_NETWORK_STATUS_PORT_ERROR;
  330. }
  331. }
  332. void Network::_externalConfig(ZT_VirtualNetworkConfig *ec) const
  333. {
  334. // assumes _lock is locked
  335. ec->nwid = _id;
  336. ec->mac = _mac.toInt();
  337. if (_config)
  338. Utils::scopy(ec->name,sizeof(ec->name),_config.name);
  339. else ec->name[0] = (char)0;
  340. ec->status = _status();
  341. ec->type = (_config) ? (_config.isPrivate() ? ZT_NETWORK_TYPE_PRIVATE : ZT_NETWORK_TYPE_PUBLIC) : ZT_NETWORK_TYPE_PRIVATE;
  342. ec->mtu = ZT_IF_MTU;
  343. ec->dhcp = 0;
  344. std::vector<Address> ab(_config.activeBridges());
  345. ec->bridge = ((_config.allowPassiveBridging())||(std::find(ab.begin(),ab.end(),RR->identity.address()) != ab.end())) ? 1 : 0;
  346. ec->broadcastEnabled = (_config) ? (_config.enableBroadcast() ? 1 : 0) : 0;
  347. ec->portError = _portError;
  348. ec->enabled = (_enabled) ? 1 : 0;
  349. ec->netconfRevision = (_config) ? (unsigned long)_config.revision : 0;
  350. ec->multicastSubscriptionCount = std::min((unsigned int)_myMulticastGroups.size(),(unsigned int)ZT_MAX_NETWORK_MULTICAST_SUBSCRIPTIONS);
  351. for(unsigned int i=0;i<ec->multicastSubscriptionCount;++i) {
  352. ec->multicastSubscriptions[i].mac = _myMulticastGroups[i].mac().toInt();
  353. ec->multicastSubscriptions[i].adi = _myMulticastGroups[i].adi();
  354. }
  355. ec->assignedAddressCount = 0;
  356. for(unsigned int i=0;i<ZT_MAX_ZT_ASSIGNED_ADDRESSES;++i) {
  357. if (i < _config.staticIpCount) {
  358. memcpy(&(ec->assignedAddresses[i]),&(_config.staticIps[i]),sizeof(struct sockaddr_storage));
  359. ++ec->assignedAddressCount;
  360. } else {
  361. memset(&(ec->assignedAddresses[i]),0,sizeof(struct sockaddr_storage));
  362. }
  363. }
  364. }
  365. bool Network::_isAllowed(const SharedPtr<Peer> &peer) const
  366. {
  367. // Assumes _lock is locked
  368. try {
  369. if (!_config)
  370. return false;
  371. if (_config.isPublic())
  372. return true;
  373. return ((_config.com)&&(peer->networkMembershipCertificatesAgree(_id,_config.com)));
  374. } catch (std::exception &exc) {
  375. TRACE("isAllowed() check failed for peer %s: unexpected exception: %s",peer->address().toString().c_str(),exc.what());
  376. } catch ( ... ) {
  377. TRACE("isAllowed() check failed for peer %s: unexpected exception: unknown exception",peer->address().toString().c_str());
  378. }
  379. return false; // default position on any failure
  380. }
  381. class _MulticastAnnounceAll
  382. {
  383. public:
  384. _MulticastAnnounceAll(const RuntimeEnvironment *renv,Network *nw) :
  385. _now(renv->node->now()),
  386. _controller(nw->controller()),
  387. _network(nw),
  388. _anchors(nw->config().anchors()),
  389. _rootAddresses(renv->topology->rootAddresses())
  390. {}
  391. inline void operator()(Topology &t,const SharedPtr<Peer> &p)
  392. {
  393. if ( (_network->_isAllowed(p)) || // FIXME: this causes multicast LIKEs for public networks to get spammed
  394. (p->address() == _controller) ||
  395. (std::find(_rootAddresses.begin(),_rootAddresses.end(),p->address()) != _rootAddresses.end()) ||
  396. (std::find(_anchors.begin(),_anchors.end(),p->address()) != _anchors.end()) ) {
  397. peers.push_back(p);
  398. }
  399. }
  400. std::vector< SharedPtr<Peer> > peers;
  401. private:
  402. const uint64_t _now;
  403. const Address _controller;
  404. Network *const _network;
  405. const std::vector<Address> _anchors;
  406. const std::vector<Address> _rootAddresses;
  407. };
  408. void Network::_announceMulticastGroups()
  409. {
  410. // Assumes _lock is locked
  411. std::vector<MulticastGroup> allMulticastGroups(_allMulticastGroups());
  412. _MulticastAnnounceAll gpfunc(RR,this);
  413. RR->topology->eachPeer<_MulticastAnnounceAll &>(gpfunc);
  414. for(std::vector< SharedPtr<Peer> >::const_iterator i(gpfunc.peers.begin());i!=gpfunc.peers.end();++i)
  415. _announceMulticastGroupsTo(*i,allMulticastGroups);
  416. }
  417. void Network::_announceMulticastGroupsTo(const SharedPtr<Peer> &peer,const std::vector<MulticastGroup> &allMulticastGroups) const
  418. {
  419. // Assumes _lock is locked
  420. // We push COMs ahead of MULTICAST_LIKE since they're used for access control -- a COM is a public
  421. // credential so "over-sharing" isn't really an issue (and we only do so with roots).
  422. if ((_config)&&(_config.com)&&(!_config.isPublic())&&(peer->needsOurNetworkMembershipCertificate(_id,RR->node->now(),true))) {
  423. Packet outp(peer->address(),RR->identity.address(),Packet::VERB_NETWORK_MEMBERSHIP_CERTIFICATE);
  424. _config.com.serialize(outp);
  425. RR->sw->send(outp,true,0);
  426. }
  427. {
  428. Packet outp(peer->address(),RR->identity.address(),Packet::VERB_MULTICAST_LIKE);
  429. for(std::vector<MulticastGroup>::const_iterator mg(allMulticastGroups.begin());mg!=allMulticastGroups.end();++mg) {
  430. if ((outp.size() + 18) >= ZT_UDP_DEFAULT_PAYLOAD_MTU) {
  431. RR->sw->send(outp,true,0);
  432. outp.reset(peer->address(),RR->identity.address(),Packet::VERB_MULTICAST_LIKE);
  433. }
  434. // network ID, MAC, ADI
  435. outp.append((uint64_t)_id);
  436. mg->mac().appendTo(outp);
  437. outp.append((uint32_t)mg->adi());
  438. }
  439. if (outp.size() > ZT_PROTO_MIN_PACKET_LENGTH)
  440. RR->sw->send(outp,true,0);
  441. }
  442. }
  443. std::vector<MulticastGroup> Network::_allMulticastGroups() const
  444. {
  445. // Assumes _lock is locked
  446. std::vector<MulticastGroup> mgs;
  447. mgs.reserve(_myMulticastGroups.size() + _multicastGroupsBehindMe.size() + 1);
  448. mgs.insert(mgs.end(),_myMulticastGroups.begin(),_myMulticastGroups.end());
  449. _multicastGroupsBehindMe.appendKeys(mgs);
  450. if ((_config)&&(_config.enableBroadcast()))
  451. mgs.push_back(Network::BROADCAST);
  452. std::sort(mgs.begin(),mgs.end());
  453. mgs.erase(std::unique(mgs.begin(),mgs.end()),mgs.end());
  454. return mgs;
  455. }
  456. } // namespace ZeroTier