Network.cpp 15 KB

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