Network.cpp 15 KB

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