Network.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502
  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. this->setConfiguration((const void *)conf.data(),(unsigned int)conf.length(),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 void *confBytes,unsigned int confLen,bool saveToDisk)
  163. {
  164. try {
  165. if (!confLen)
  166. return 0;
  167. NetworkConfig newConfig;
  168. if (reinterpret_cast<const uint8_t *>(confBytes)[0] == ZT_NETWORKCONFIG_V2_MARKER_BYTE) {
  169. Buffer<8194> tmp(confBytes,confLen);
  170. newConfig.deserialize(tmp,0);
  171. } else {
  172. #ifdef ZT_SUPPORT_OLD_STYLE_NETCONF
  173. newConfig.fromDictionary(reinterpret_cast<const char *>(confBytes),confLen); // throws if invalid
  174. #else
  175. return 0;
  176. #endif
  177. }
  178. {
  179. Mutex::Lock _l(_lock);
  180. if (_config == newConfig)
  181. return 1; // OK config, but duplicate of what we already have
  182. }
  183. if (applyConfiguration(newConfig)) {
  184. if (saveToDisk) {
  185. char n[128];
  186. Utils::snprintf(n,sizeof(n),"networks.d/%.16llx.conf",_id);
  187. RR->node->dataStorePut(n,confBytes,confLen,true);
  188. }
  189. return 2; // OK and configuration has changed
  190. }
  191. } catch ( ... ) {
  192. TRACE("ignored invalid configuration for network %.16llx",(unsigned long long)_id);
  193. }
  194. return 0;
  195. }
  196. void Network::requestConfiguration()
  197. {
  198. if (_id == ZT_TEST_NETWORK_ID) // pseudo-network-ID, uses locally generated static config
  199. return;
  200. if (controller() == RR->identity.address()) {
  201. if (RR->localNetworkController) {
  202. Dictionary newconf;
  203. switch(RR->localNetworkController->doNetworkConfigRequest(InetAddress(),RR->identity,RR->identity,_id,Dictionary(),newconf)) {
  204. case NetworkController::NETCONF_QUERY_OK: {
  205. std::string tmp(newconf.toString());
  206. this->setConfiguration((const void *)tmp.data(),(unsigned int)tmp.length(),true);
  207. } return;
  208. case NetworkController::NETCONF_QUERY_OBJECT_NOT_FOUND:
  209. this->setNotFound();
  210. return;
  211. case NetworkController::NETCONF_QUERY_ACCESS_DENIED:
  212. this->setAccessDenied();
  213. return;
  214. default:
  215. return;
  216. }
  217. } else {
  218. this->setNotFound();
  219. return;
  220. }
  221. }
  222. TRACE("requesting netconf for network %.16llx from controller %s",(unsigned long long)_id,controller().toString().c_str());
  223. // TODO: in the future we will include things like join tokens here, etc.
  224. Dictionary metaData;
  225. metaData.setHex(ZT_NETWORKCONFIG_REQUEST_METADATA_KEY_NODE_MAJOR_VERSION,ZEROTIER_ONE_VERSION_MAJOR);
  226. metaData.setHex(ZT_NETWORKCONFIG_REQUEST_METADATA_KEY_NODE_MINOR_VERSION,ZEROTIER_ONE_VERSION_MINOR);
  227. metaData.setHex(ZT_NETWORKCONFIG_REQUEST_METADATA_KEY_NODE_REVISION,ZEROTIER_ONE_VERSION_REVISION);
  228. std::string mds(metaData.toString());
  229. Packet outp(controller(),RR->identity.address(),Packet::VERB_NETWORK_CONFIG_REQUEST);
  230. outp.append((uint64_t)_id);
  231. outp.append((uint16_t)mds.length());
  232. outp.append((const void *)mds.data(),(unsigned int)mds.length());
  233. if (_config)
  234. outp.append((uint64_t)_config.revision());
  235. else outp.append((uint64_t)0);
  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());
  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. std::vector<Address> ab(_config.activeBridges());
  339. ec->bridge = ((_config.allowPassiveBridging())||(std::find(ab.begin(),ab.end(),RR->identity.address()) != ab.end())) ? 1 : 0;
  340. ec->broadcastEnabled = (_config) ? (_config.enableBroadcast() ? 1 : 0) : 0;
  341. ec->portError = _portError;
  342. ec->enabled = (_enabled) ? 1 : 0;
  343. ec->netconfRevision = (_config) ? (unsigned long)_config.revision() : 0;
  344. ec->multicastSubscriptionCount = std::min((unsigned int)_myMulticastGroups.size(),(unsigned int)ZT_MAX_NETWORK_MULTICAST_SUBSCRIPTIONS);
  345. for(unsigned int i=0;i<ec->multicastSubscriptionCount;++i) {
  346. ec->multicastSubscriptions[i].mac = _myMulticastGroups[i].mac().toInt();
  347. ec->multicastSubscriptions[i].adi = _myMulticastGroups[i].adi();
  348. }
  349. std::vector<InetAddress> sips(_config.staticIps());
  350. ec->assignedAddressCount = 0;
  351. for(unsigned long i=0;i<ZT_MAX_ZT_ASSIGNED_ADDRESSES;++i) {
  352. if (i < sips.size()) {
  353. memcpy(&(ec->assignedAddresses[i]),&(sips[i]),sizeof(struct sockaddr_storage));
  354. ++ec->assignedAddressCount;
  355. } else memset(&(ec->assignedAddresses[i]),0,sizeof(struct sockaddr_storage));
  356. }
  357. }
  358. bool Network::_isAllowed(const SharedPtr<Peer> &peer) const
  359. {
  360. // Assumes _lock is locked
  361. try {
  362. if (!_config)
  363. return false;
  364. if (_config.isPublic())
  365. return true;
  366. return ((_config.com())&&(peer->networkMembershipCertificatesAgree(_id,_config.com())));
  367. } catch (std::exception &exc) {
  368. TRACE("isAllowed() check failed for peer %s: unexpected exception: %s",peer->address().toString().c_str(),exc.what());
  369. } catch ( ... ) {
  370. TRACE("isAllowed() check failed for peer %s: unexpected exception: unknown exception",peer->address().toString().c_str());
  371. }
  372. return false; // default position on any failure
  373. }
  374. class _MulticastAnnounceAll
  375. {
  376. public:
  377. _MulticastAnnounceAll(const RuntimeEnvironment *renv,Network *nw) :
  378. _now(renv->node->now()),
  379. _controller(nw->controller()),
  380. _network(nw),
  381. _rootAddresses(renv->topology->rootAddresses())
  382. {}
  383. inline void operator()(Topology &t,const SharedPtr<Peer> &p)
  384. {
  385. if (
  386. (_network->_isAllowed(p)) ||
  387. (p->address() == _controller) ||
  388. (std::find(_rootAddresses.begin(),_rootAddresses.end(),p->address()) != _rootAddresses.end())
  389. ) {
  390. peers.push_back(p);
  391. }
  392. }
  393. std::vector< SharedPtr<Peer> > peers;
  394. private:
  395. const uint64_t _now;
  396. const Address _controller;
  397. Network *const _network;
  398. const std::vector<Address> _rootAddresses;
  399. };
  400. void Network::_announceMulticastGroups()
  401. {
  402. // Assumes _lock is locked
  403. _MulticastAnnounceAll gpfunc(RR,this);
  404. RR->topology->eachPeer<_MulticastAnnounceAll &>(gpfunc);
  405. std::vector<MulticastGroup> allMulticastGroups(_allMulticastGroups());
  406. for(std::vector< SharedPtr<Peer> >::const_iterator i(gpfunc.peers.begin());i!=gpfunc.peers.end();++i)
  407. _announceMulticastGroupsTo(*i,allMulticastGroups);
  408. }
  409. void Network::_announceMulticastGroupsTo(const SharedPtr<Peer> &peer,const std::vector<MulticastGroup> &allMulticastGroups) const
  410. {
  411. // Assumes _lock is locked
  412. // We push COMs ahead of MULTICAST_LIKE since they're used for access control -- a COM is a public
  413. // credential so "over-sharing" isn't really an issue (and we only do so with roots).
  414. if ((_config)&&(_config.com())&&(!_config.isPublic())&&(peer->needsOurNetworkMembershipCertificate(_id,RR->node->now(),true))) {
  415. Packet outp(peer->address(),RR->identity.address(),Packet::VERB_NETWORK_MEMBERSHIP_CERTIFICATE);
  416. _config.com().serialize(outp);
  417. RR->sw->send(outp,true,0);
  418. }
  419. {
  420. Packet outp(peer->address(),RR->identity.address(),Packet::VERB_MULTICAST_LIKE);
  421. for(std::vector<MulticastGroup>::const_iterator mg(allMulticastGroups.begin());mg!=allMulticastGroups.end();++mg) {
  422. if ((outp.size() + 18) >= ZT_UDP_DEFAULT_PAYLOAD_MTU) {
  423. RR->sw->send(outp,true,0);
  424. outp.reset(peer->address(),RR->identity.address(),Packet::VERB_MULTICAST_LIKE);
  425. }
  426. // network ID, MAC, ADI
  427. outp.append((uint64_t)_id);
  428. mg->mac().appendTo(outp);
  429. outp.append((uint32_t)mg->adi());
  430. }
  431. if (outp.size() > ZT_PROTO_MIN_PACKET_LENGTH)
  432. RR->sw->send(outp,true,0);
  433. }
  434. }
  435. std::vector<MulticastGroup> Network::_allMulticastGroups() const
  436. {
  437. // Assumes _lock is locked
  438. std::vector<MulticastGroup> mgs;
  439. mgs.reserve(_myMulticastGroups.size() + _multicastGroupsBehindMe.size() + 1);
  440. mgs.insert(mgs.end(),_myMulticastGroups.begin(),_myMulticastGroups.end());
  441. _multicastGroupsBehindMe.appendKeys(mgs);
  442. if ((_config)&&(_config.enableBroadcast()))
  443. mgs.push_back(Network::BROADCAST);
  444. std::sort(mgs.begin(),mgs.end());
  445. mgs.erase(std::unique(mgs.begin(),mgs.end()),mgs.end());
  446. return mgs;
  447. }
  448. } // namespace ZeroTier