Network.cpp 16 KB

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