Network.cpp 15 KB

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