Network.cpp 16 KB

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