Network.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483
  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. Dictionary dconf(conf.c_str());
  59. NetworkConfig nconf;
  60. if (nconf.fromDictionary(dconf)) {
  61. this->setConfiguration(nconf,false);
  62. _lastConfigUpdate = 0; // we still want to re-request a new config from the network
  63. gotConf = true;
  64. }
  65. }
  66. } catch ( ... ) {} // ignore invalids, we'll re-request
  67. if (!gotConf) {
  68. // Save a one-byte CR to persist membership while we request a real netconf
  69. RR->node->dataStorePut(confn,"\n",1,false);
  70. }
  71. }
  72. if (!_portInitialized) {
  73. ZT_VirtualNetworkConfig ctmp;
  74. _externalConfig(&ctmp);
  75. _portError = RR->node->configureVirtualNetworkPort(_id,&_uPtr,ZT_VIRTUAL_NETWORK_CONFIG_OPERATION_UP,&ctmp);
  76. _portInitialized = true;
  77. }
  78. }
  79. Network::~Network()
  80. {
  81. ZT_VirtualNetworkConfig ctmp;
  82. _externalConfig(&ctmp);
  83. char n[128];
  84. if (_destroyed) {
  85. RR->node->configureVirtualNetworkPort(_id,&_uPtr,ZT_VIRTUAL_NETWORK_CONFIG_OPERATION_DESTROY,&ctmp);
  86. Utils::snprintf(n,sizeof(n),"networks.d/%.16llx.conf",_id);
  87. RR->node->dataStoreDelete(n);
  88. } else {
  89. RR->node->configureVirtualNetworkPort(_id,&_uPtr,ZT_VIRTUAL_NETWORK_CONFIG_OPERATION_DOWN,&ctmp);
  90. }
  91. }
  92. bool Network::subscribedToMulticastGroup(const MulticastGroup &mg,bool includeBridgedGroups) const
  93. {
  94. Mutex::Lock _l(_lock);
  95. if (std::binary_search(_myMulticastGroups.begin(),_myMulticastGroups.end(),mg))
  96. return true;
  97. else if (includeBridgedGroups)
  98. return _multicastGroupsBehindMe.contains(mg);
  99. else return false;
  100. }
  101. void Network::multicastSubscribe(const MulticastGroup &mg)
  102. {
  103. {
  104. Mutex::Lock _l(_lock);
  105. if (std::binary_search(_myMulticastGroups.begin(),_myMulticastGroups.end(),mg))
  106. return;
  107. _myMulticastGroups.push_back(mg);
  108. std::sort(_myMulticastGroups.begin(),_myMulticastGroups.end());
  109. }
  110. _announceMulticastGroups();
  111. }
  112. void Network::multicastUnsubscribe(const MulticastGroup &mg)
  113. {
  114. Mutex::Lock _l(_lock);
  115. std::vector<MulticastGroup> nmg;
  116. for(std::vector<MulticastGroup>::const_iterator i(_myMulticastGroups.begin());i!=_myMulticastGroups.end();++i) {
  117. if (*i != mg)
  118. nmg.push_back(*i);
  119. }
  120. if (nmg.size() != _myMulticastGroups.size())
  121. _myMulticastGroups.swap(nmg);
  122. }
  123. bool Network::tryAnnounceMulticastGroupsTo(const SharedPtr<Peer> &peer)
  124. {
  125. Mutex::Lock _l(_lock);
  126. if (
  127. (_isAllowed(peer)) ||
  128. (peer->address() == this->controller()) ||
  129. (RR->topology->isRoot(peer->identity()))
  130. ) {
  131. _announceMulticastGroupsTo(peer,_allMulticastGroups());
  132. return true;
  133. }
  134. return false;
  135. }
  136. bool Network::applyConfiguration(const NetworkConfig &conf)
  137. {
  138. if (_destroyed) // sanity check
  139. return false;
  140. try {
  141. if ((conf.networkId == _id)&&(conf.issuedTo == RR->identity.address())) {
  142. ZT_VirtualNetworkConfig ctmp;
  143. bool portInitialized;
  144. {
  145. Mutex::Lock _l(_lock);
  146. _config = conf;
  147. _lastConfigUpdate = RR->node->now();
  148. _netconfFailure = NETCONF_FAILURE_NONE;
  149. _externalConfig(&ctmp);
  150. portInitialized = _portInitialized;
  151. _portInitialized = true;
  152. }
  153. _portError = RR->node->configureVirtualNetworkPort(_id,&_uPtr,(portInitialized) ? ZT_VIRTUAL_NETWORK_CONFIG_OPERATION_CONFIG_UPDATE : ZT_VIRTUAL_NETWORK_CONFIG_OPERATION_UP,&ctmp);
  154. return true;
  155. } else {
  156. TRACE("ignored invalid configuration for network %.16llx (configuration contains mismatched network ID or issued-to address)",(unsigned long long)_id);
  157. }
  158. } catch (std::exception &exc) {
  159. TRACE("ignored invalid configuration for network %.16llx (%s)",(unsigned long long)_id,exc.what());
  160. } catch ( ... ) {
  161. TRACE("ignored invalid configuration for network %.16llx (unknown exception)",(unsigned long long)_id);
  162. }
  163. return false;
  164. }
  165. int Network::setConfiguration(const NetworkConfig &nconf,bool saveToDisk)
  166. {
  167. try {
  168. {
  169. Mutex::Lock _l(_lock);
  170. if (_config == nconf)
  171. return 1; // OK config, but duplicate of what we already have
  172. }
  173. if (applyConfiguration(nconf)) {
  174. if (saveToDisk) {
  175. char n[64];
  176. Utils::snprintf(n,sizeof(n),"networks.d/%.16llx.conf",_id);
  177. Dictionary d;
  178. if (nconf.toDictionary(d,false))
  179. RR->node->dataStorePut(n,(const void *)d.data(),d.sizeBytes(),true);
  180. }
  181. return 2; // OK and configuration has changed
  182. }
  183. } catch ( ... ) {
  184. TRACE("ignored invalid configuration for network %.16llx",(unsigned long long)_id);
  185. }
  186. return 0;
  187. }
  188. void Network::requestConfiguration()
  189. {
  190. if (_id == ZT_TEST_NETWORK_ID) // pseudo-network-ID, uses locally generated static config
  191. return;
  192. Dictionary rmd;
  193. rmd.add(ZT_NETWORKCONFIG_REQUEST_METADATA_KEY_VERSION,(uint64_t)ZT_NETWORKCONFIG_VERSION);
  194. rmd.add(ZT_NETWORKCONFIG_REQUEST_METADATA_KEY_PROTOCOL_VERSION,(uint64_t)ZT_PROTO_VERSION);
  195. rmd.add(ZT_NETWORKCONFIG_REQUEST_METADATA_KEY_NODE_MAJOR_VERSION,(uint64_t)ZEROTIER_ONE_VERSION_MAJOR);
  196. rmd.add(ZT_NETWORKCONFIG_REQUEST_METADATA_KEY_NODE_MINOR_VERSION,(uint64_t)ZEROTIER_ONE_VERSION_MINOR);
  197. rmd.add(ZT_NETWORKCONFIG_REQUEST_METADATA_KEY_NODE_REVISION,(uint64_t)ZEROTIER_ONE_VERSION_REVISION);
  198. if (controller() == RR->identity.address()) {
  199. if (RR->localNetworkController) {
  200. NetworkConfig nconf;
  201. switch(RR->localNetworkController->doNetworkConfigRequest(InetAddress(),RR->identity,RR->identity,_id,rmd,nconf)) {
  202. case NetworkController::NETCONF_QUERY_OK:
  203. this->setConfiguration(nconf,true);
  204. return;
  205. case NetworkController::NETCONF_QUERY_OBJECT_NOT_FOUND:
  206. this->setNotFound();
  207. return;
  208. case NetworkController::NETCONF_QUERY_ACCESS_DENIED:
  209. this->setAccessDenied();
  210. return;
  211. default:
  212. return;
  213. }
  214. } else {
  215. this->setNotFound();
  216. return;
  217. }
  218. }
  219. TRACE("requesting netconf for network %.16llx from controller %s",(unsigned long long)_id,controller().toString().c_str());
  220. Packet outp(controller(),RR->identity.address(),Packet::VERB_NETWORK_CONFIG_REQUEST);
  221. outp.append((uint64_t)_id);
  222. const unsigned int rmdSize = rmd.sizeBytes();
  223. outp.append((uint16_t)rmdSize);
  224. outp.append((const void *)rmd.data(),rmdSize);
  225. outp.append((_config) ? (uint64_t)_config.revision : (uint64_t)0);
  226. outp.compress();
  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::destroy()
  286. {
  287. Mutex::Lock _l(_lock);
  288. _destroyed = true;
  289. }
  290. ZT_VirtualNetworkStatus Network::_status() const
  291. {
  292. // assumes _lock is locked
  293. if (_portError)
  294. return ZT_NETWORK_STATUS_PORT_ERROR;
  295. switch(_netconfFailure) {
  296. case NETCONF_FAILURE_ACCESS_DENIED:
  297. return ZT_NETWORK_STATUS_ACCESS_DENIED;
  298. case NETCONF_FAILURE_NOT_FOUND:
  299. return ZT_NETWORK_STATUS_NOT_FOUND;
  300. case NETCONF_FAILURE_NONE:
  301. return ((_config) ? ZT_NETWORK_STATUS_OK : ZT_NETWORK_STATUS_REQUESTING_CONFIGURATION);
  302. default:
  303. return ZT_NETWORK_STATUS_PORT_ERROR;
  304. }
  305. }
  306. void Network::_externalConfig(ZT_VirtualNetworkConfig *ec) const
  307. {
  308. // assumes _lock is locked
  309. ec->nwid = _id;
  310. ec->mac = _mac.toInt();
  311. if (_config)
  312. Utils::scopy(ec->name,sizeof(ec->name),_config.name);
  313. else ec->name[0] = (char)0;
  314. ec->status = _status();
  315. ec->type = (_config) ? (_config.isPrivate() ? ZT_NETWORK_TYPE_PRIVATE : ZT_NETWORK_TYPE_PUBLIC) : ZT_NETWORK_TYPE_PRIVATE;
  316. ec->mtu = ZT_IF_MTU;
  317. ec->dhcp = 0;
  318. std::vector<Address> ab(_config.activeBridges());
  319. ec->bridge = ((_config.allowPassiveBridging())||(std::find(ab.begin(),ab.end(),RR->identity.address()) != ab.end())) ? 1 : 0;
  320. ec->broadcastEnabled = (_config) ? (_config.enableBroadcast() ? 1 : 0) : 0;
  321. ec->portError = _portError;
  322. ec->netconfRevision = (_config) ? (unsigned long)_config.revision : 0;
  323. ec->assignedAddressCount = 0;
  324. for(unsigned int i=0;i<ZT_MAX_ZT_ASSIGNED_ADDRESSES;++i) {
  325. if (i < _config.staticIpCount) {
  326. memcpy(&(ec->assignedAddresses[i]),&(_config.staticIps[i]),sizeof(struct sockaddr_storage));
  327. ++ec->assignedAddressCount;
  328. } else {
  329. memset(&(ec->assignedAddresses[i]),0,sizeof(struct sockaddr_storage));
  330. }
  331. }
  332. ec->routeCount = 0;
  333. for(unsigned int i=0;i<ZT_MAX_NETWORK_ROUTES;++i) {
  334. if (i < _config.routeCount) {
  335. memcpy(&(ec->routes[i]),&(_config.routes[i]),sizeof(ZT_VirtualNetworkRoute));
  336. ++ec->routeCount;
  337. } else {
  338. memset(&(ec->routes[i]),0,sizeof(ZT_VirtualNetworkRoute));
  339. }
  340. }
  341. }
  342. bool Network::_isAllowed(const SharedPtr<Peer> &peer) const
  343. {
  344. // Assumes _lock is locked
  345. try {
  346. if (!_config)
  347. return false;
  348. if (_config.isPublic())
  349. return true;
  350. return ((_config.com)&&(peer->networkMembershipCertificatesAgree(_id,_config.com)));
  351. } catch (std::exception &exc) {
  352. TRACE("isAllowed() check failed for peer %s: unexpected exception: %s",peer->address().toString().c_str(),exc.what());
  353. } catch ( ... ) {
  354. TRACE("isAllowed() check failed for peer %s: unexpected exception: unknown exception",peer->address().toString().c_str());
  355. }
  356. return false; // default position on any failure
  357. }
  358. class _MulticastAnnounceAll
  359. {
  360. public:
  361. _MulticastAnnounceAll(const RuntimeEnvironment *renv,Network *nw) :
  362. _now(renv->node->now()),
  363. _controller(nw->controller()),
  364. _network(nw),
  365. _anchors(nw->config().anchors()),
  366. _rootAddresses(renv->topology->rootAddresses())
  367. {}
  368. inline void operator()(Topology &t,const SharedPtr<Peer> &p)
  369. {
  370. if ( (_network->_isAllowed(p)) || // FIXME: this causes multicast LIKEs for public networks to get spammed
  371. (p->address() == _controller) ||
  372. (std::find(_rootAddresses.begin(),_rootAddresses.end(),p->address()) != _rootAddresses.end()) ||
  373. (std::find(_anchors.begin(),_anchors.end(),p->address()) != _anchors.end()) ) {
  374. peers.push_back(p);
  375. }
  376. }
  377. std::vector< SharedPtr<Peer> > peers;
  378. private:
  379. const uint64_t _now;
  380. const Address _controller;
  381. Network *const _network;
  382. const std::vector<Address> _anchors;
  383. const std::vector<Address> _rootAddresses;
  384. };
  385. void Network::_announceMulticastGroups()
  386. {
  387. // Assumes _lock is locked
  388. std::vector<MulticastGroup> allMulticastGroups(_allMulticastGroups());
  389. _MulticastAnnounceAll gpfunc(RR,this);
  390. RR->topology->eachPeer<_MulticastAnnounceAll &>(gpfunc);
  391. for(std::vector< SharedPtr<Peer> >::const_iterator i(gpfunc.peers.begin());i!=gpfunc.peers.end();++i)
  392. _announceMulticastGroupsTo(*i,allMulticastGroups);
  393. }
  394. void Network::_announceMulticastGroupsTo(const SharedPtr<Peer> &peer,const std::vector<MulticastGroup> &allMulticastGroups) const
  395. {
  396. // Assumes _lock is locked
  397. // We push COMs ahead of MULTICAST_LIKE since they're used for access control -- a COM is a public
  398. // credential so "over-sharing" isn't really an issue (and we only do so with roots).
  399. if ((_config)&&(_config.com)&&(!_config.isPublic())&&(peer->needsOurNetworkMembershipCertificate(_id,RR->node->now(),true))) {
  400. Packet outp(peer->address(),RR->identity.address(),Packet::VERB_NETWORK_MEMBERSHIP_CERTIFICATE);
  401. _config.com.serialize(outp);
  402. RR->sw->send(outp,true,0);
  403. }
  404. {
  405. Packet outp(peer->address(),RR->identity.address(),Packet::VERB_MULTICAST_LIKE);
  406. for(std::vector<MulticastGroup>::const_iterator mg(allMulticastGroups.begin());mg!=allMulticastGroups.end();++mg) {
  407. if ((outp.size() + 18) >= ZT_UDP_DEFAULT_PAYLOAD_MTU) {
  408. RR->sw->send(outp,true,0);
  409. outp.reset(peer->address(),RR->identity.address(),Packet::VERB_MULTICAST_LIKE);
  410. }
  411. // network ID, MAC, ADI
  412. outp.append((uint64_t)_id);
  413. mg->mac().appendTo(outp);
  414. outp.append((uint32_t)mg->adi());
  415. }
  416. if (outp.size() > ZT_PROTO_MIN_PACKET_LENGTH)
  417. RR->sw->send(outp,true,0);
  418. }
  419. }
  420. std::vector<MulticastGroup> Network::_allMulticastGroups() const
  421. {
  422. // Assumes _lock is locked
  423. std::vector<MulticastGroup> mgs;
  424. mgs.reserve(_myMulticastGroups.size() + _multicastGroupsBehindMe.size() + 1);
  425. mgs.insert(mgs.end(),_myMulticastGroups.begin(),_myMulticastGroups.end());
  426. _multicastGroupsBehindMe.appendKeys(mgs);
  427. if ((_config)&&(_config.enableBroadcast()))
  428. mgs.push_back(Network::BROADCAST);
  429. std::sort(mgs.begin(),mgs.end());
  430. mgs.erase(std::unique(mgs.begin(),mgs.end()),mgs.end());
  431. return mgs;
  432. }
  433. } // namespace ZeroTier