Network.cpp 15 KB

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