Network.cpp 16 KB

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