Network.cpp 15 KB

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