Network.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485
  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<ZT_NETWORKCONFIG_DICT_CAPACITY> 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<ZT_NETWORKCONFIG_DICT_CAPACITY> 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<ZT_NETWORKCONFIG_DICT_CAPACITY> 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. rmd.add(ZT_NETWORKCONFIG_REQUEST_METADATA_KEY_MAX_NETWORK_RULES,(uint64_t)ZT_MAX_NETWORK_RULES);
  199. rmd.add(ZT_NETWORKCONFIG_REQUEST_METADATA_KEY_MAX_CAPABILITY_RULES,(uint64_t)ZT_MAX_CAPABILITY_RULES);
  200. if (controller() == RR->identity.address()) {
  201. if (RR->localNetworkController) {
  202. NetworkConfig nconf;
  203. switch(RR->localNetworkController->doNetworkConfigRequest(InetAddress(),RR->identity,RR->identity,_id,rmd,nconf)) {
  204. case NetworkController::NETCONF_QUERY_OK:
  205. this->setConfiguration(nconf,true);
  206. return;
  207. case NetworkController::NETCONF_QUERY_OBJECT_NOT_FOUND:
  208. this->setNotFound();
  209. return;
  210. case NetworkController::NETCONF_QUERY_ACCESS_DENIED:
  211. this->setAccessDenied();
  212. return;
  213. default:
  214. return;
  215. }
  216. } else {
  217. this->setNotFound();
  218. return;
  219. }
  220. }
  221. TRACE("requesting netconf for network %.16llx from controller %s",(unsigned long long)_id,controller().toString().c_str());
  222. Packet outp(controller(),RR->identity.address(),Packet::VERB_NETWORK_CONFIG_REQUEST);
  223. outp.append((uint64_t)_id);
  224. const unsigned int rmdSize = rmd.sizeBytes();
  225. outp.append((uint16_t)rmdSize);
  226. outp.append((const void *)rmd.data(),rmdSize);
  227. outp.append((_config) ? (uint64_t)_config.revision : (uint64_t)0);
  228. outp.compress();
  229. RR->sw->send(outp,true,0);
  230. }
  231. void Network::clean()
  232. {
  233. const uint64_t now = RR->node->now();
  234. Mutex::Lock _l(_lock);
  235. if (_destroyed)
  236. return;
  237. {
  238. Hashtable< MulticastGroup,uint64_t >::Iterator i(_multicastGroupsBehindMe);
  239. MulticastGroup *mg = (MulticastGroup *)0;
  240. uint64_t *ts = (uint64_t *)0;
  241. while (i.next(mg,ts)) {
  242. if ((now - *ts) > (ZT_MULTICAST_LIKE_EXPIRE * 2))
  243. _multicastGroupsBehindMe.erase(*mg);
  244. }
  245. }
  246. }
  247. void Network::learnBridgeRoute(const MAC &mac,const Address &addr)
  248. {
  249. Mutex::Lock _l(_lock);
  250. _remoteBridgeRoutes[mac] = addr;
  251. // Anti-DOS circuit breaker to prevent nodes from spamming us with absurd numbers of bridge routes
  252. while (_remoteBridgeRoutes.size() > ZT_MAX_BRIDGE_ROUTES) {
  253. Hashtable< Address,unsigned long > counts;
  254. Address maxAddr;
  255. unsigned long maxCount = 0;
  256. MAC *m = (MAC *)0;
  257. Address *a = (Address *)0;
  258. // Find the address responsible for the most entries
  259. {
  260. Hashtable<MAC,Address>::Iterator i(_remoteBridgeRoutes);
  261. while (i.next(m,a)) {
  262. const unsigned long c = ++counts[*a];
  263. if (c > maxCount) {
  264. maxCount = c;
  265. maxAddr = *a;
  266. }
  267. }
  268. }
  269. // Kill this address from our table, since it's most likely spamming us
  270. {
  271. Hashtable<MAC,Address>::Iterator i(_remoteBridgeRoutes);
  272. while (i.next(m,a)) {
  273. if (*a == maxAddr)
  274. _remoteBridgeRoutes.erase(*m);
  275. }
  276. }
  277. }
  278. }
  279. void Network::learnBridgedMulticastGroup(const MulticastGroup &mg,uint64_t now)
  280. {
  281. Mutex::Lock _l(_lock);
  282. const unsigned long tmp = (unsigned long)_multicastGroupsBehindMe.size();
  283. _multicastGroupsBehindMe.set(mg,now);
  284. if (tmp != _multicastGroupsBehindMe.size())
  285. _announceMulticastGroups();
  286. }
  287. void Network::destroy()
  288. {
  289. Mutex::Lock _l(_lock);
  290. _destroyed = true;
  291. }
  292. ZT_VirtualNetworkStatus Network::_status() const
  293. {
  294. // assumes _lock is locked
  295. if (_portError)
  296. return ZT_NETWORK_STATUS_PORT_ERROR;
  297. switch(_netconfFailure) {
  298. case NETCONF_FAILURE_ACCESS_DENIED:
  299. return ZT_NETWORK_STATUS_ACCESS_DENIED;
  300. case NETCONF_FAILURE_NOT_FOUND:
  301. return ZT_NETWORK_STATUS_NOT_FOUND;
  302. case NETCONF_FAILURE_NONE:
  303. return ((_config) ? ZT_NETWORK_STATUS_OK : ZT_NETWORK_STATUS_REQUESTING_CONFIGURATION);
  304. default:
  305. return ZT_NETWORK_STATUS_PORT_ERROR;
  306. }
  307. }
  308. void Network::_externalConfig(ZT_VirtualNetworkConfig *ec) const
  309. {
  310. // assumes _lock is locked
  311. ec->nwid = _id;
  312. ec->mac = _mac.toInt();
  313. if (_config)
  314. Utils::scopy(ec->name,sizeof(ec->name),_config.name);
  315. else ec->name[0] = (char)0;
  316. ec->status = _status();
  317. ec->type = (_config) ? (_config.isPrivate() ? ZT_NETWORK_TYPE_PRIVATE : ZT_NETWORK_TYPE_PUBLIC) : ZT_NETWORK_TYPE_PRIVATE;
  318. ec->mtu = ZT_IF_MTU;
  319. ec->dhcp = 0;
  320. std::vector<Address> ab(_config.activeBridges());
  321. ec->bridge = ((_config.allowPassiveBridging())||(std::find(ab.begin(),ab.end(),RR->identity.address()) != ab.end())) ? 1 : 0;
  322. ec->broadcastEnabled = (_config) ? (_config.enableBroadcast() ? 1 : 0) : 0;
  323. ec->portError = _portError;
  324. ec->netconfRevision = (_config) ? (unsigned long)_config.revision : 0;
  325. ec->assignedAddressCount = 0;
  326. for(unsigned int i=0;i<ZT_MAX_ZT_ASSIGNED_ADDRESSES;++i) {
  327. if (i < _config.staticIpCount) {
  328. memcpy(&(ec->assignedAddresses[i]),&(_config.staticIps[i]),sizeof(struct sockaddr_storage));
  329. ++ec->assignedAddressCount;
  330. } else {
  331. memset(&(ec->assignedAddresses[i]),0,sizeof(struct sockaddr_storage));
  332. }
  333. }
  334. ec->routeCount = 0;
  335. for(unsigned int i=0;i<ZT_MAX_NETWORK_ROUTES;++i) {
  336. if (i < _config.routeCount) {
  337. memcpy(&(ec->routes[i]),&(_config.routes[i]),sizeof(ZT_VirtualNetworkRoute));
  338. ++ec->routeCount;
  339. } else {
  340. memset(&(ec->routes[i]),0,sizeof(ZT_VirtualNetworkRoute));
  341. }
  342. }
  343. }
  344. bool Network::_isAllowed(const SharedPtr<Peer> &peer) const
  345. {
  346. // Assumes _lock is locked
  347. try {
  348. if (!_config)
  349. return false;
  350. if (_config.isPublic())
  351. return true;
  352. return ((_config.com)&&(peer->networkMembershipCertificatesAgree(_id,_config.com)));
  353. } catch (std::exception &exc) {
  354. TRACE("isAllowed() check failed for peer %s: unexpected exception: %s",peer->address().toString().c_str(),exc.what());
  355. } catch ( ... ) {
  356. TRACE("isAllowed() check failed for peer %s: unexpected exception: unknown exception",peer->address().toString().c_str());
  357. }
  358. return false; // default position on any failure
  359. }
  360. class _MulticastAnnounceAll
  361. {
  362. public:
  363. _MulticastAnnounceAll(const RuntimeEnvironment *renv,Network *nw) :
  364. _now(renv->node->now()),
  365. _controller(nw->controller()),
  366. _network(nw),
  367. _anchors(nw->config().anchors()),
  368. _rootAddresses(renv->topology->rootAddresses())
  369. {}
  370. inline void operator()(Topology &t,const SharedPtr<Peer> &p)
  371. {
  372. if ( (_network->_isAllowed(p)) || // FIXME: this causes multicast LIKEs for public networks to get spammed
  373. (p->address() == _controller) ||
  374. (std::find(_rootAddresses.begin(),_rootAddresses.end(),p->address()) != _rootAddresses.end()) ||
  375. (std::find(_anchors.begin(),_anchors.end(),p->address()) != _anchors.end()) ) {
  376. peers.push_back(p);
  377. }
  378. }
  379. std::vector< SharedPtr<Peer> > peers;
  380. private:
  381. const uint64_t _now;
  382. const Address _controller;
  383. Network *const _network;
  384. const std::vector<Address> _anchors;
  385. const std::vector<Address> _rootAddresses;
  386. };
  387. void Network::_announceMulticastGroups()
  388. {
  389. // Assumes _lock is locked
  390. std::vector<MulticastGroup> allMulticastGroups(_allMulticastGroups());
  391. _MulticastAnnounceAll gpfunc(RR,this);
  392. RR->topology->eachPeer<_MulticastAnnounceAll &>(gpfunc);
  393. for(std::vector< SharedPtr<Peer> >::const_iterator i(gpfunc.peers.begin());i!=gpfunc.peers.end();++i)
  394. _announceMulticastGroupsTo(*i,allMulticastGroups);
  395. }
  396. void Network::_announceMulticastGroupsTo(const SharedPtr<Peer> &peer,const std::vector<MulticastGroup> &allMulticastGroups) const
  397. {
  398. // Assumes _lock is locked
  399. // We push COMs ahead of MULTICAST_LIKE since they're used for access control -- a COM is a public
  400. // credential so "over-sharing" isn't really an issue (and we only do so with roots).
  401. if ((_config)&&(_config.com)&&(!_config.isPublic())&&(peer->needsOurNetworkMembershipCertificate(_id,RR->node->now(),true))) {
  402. Packet outp(peer->address(),RR->identity.address(),Packet::VERB_NETWORK_MEMBERSHIP_CERTIFICATE);
  403. _config.com.serialize(outp);
  404. RR->sw->send(outp,true,0);
  405. }
  406. {
  407. Packet outp(peer->address(),RR->identity.address(),Packet::VERB_MULTICAST_LIKE);
  408. for(std::vector<MulticastGroup>::const_iterator mg(allMulticastGroups.begin());mg!=allMulticastGroups.end();++mg) {
  409. if ((outp.size() + 18) >= ZT_UDP_DEFAULT_PAYLOAD_MTU) {
  410. RR->sw->send(outp,true,0);
  411. outp.reset(peer->address(),RR->identity.address(),Packet::VERB_MULTICAST_LIKE);
  412. }
  413. // network ID, MAC, ADI
  414. outp.append((uint64_t)_id);
  415. mg->mac().appendTo(outp);
  416. outp.append((uint32_t)mg->adi());
  417. }
  418. if (outp.size() > ZT_PROTO_MIN_PACKET_LENGTH)
  419. RR->sw->send(outp,true,0);
  420. }
  421. }
  422. std::vector<MulticastGroup> Network::_allMulticastGroups() const
  423. {
  424. // Assumes _lock is locked
  425. std::vector<MulticastGroup> mgs;
  426. mgs.reserve(_myMulticastGroups.size() + _multicastGroupsBehindMe.size() + 1);
  427. mgs.insert(mgs.end(),_myMulticastGroups.begin(),_myMulticastGroups.end());
  428. _multicastGroupsBehindMe.appendKeys(mgs);
  429. if ((_config)&&(_config.enableBroadcast()))
  430. mgs.push_back(Network::BROADCAST);
  431. std::sort(mgs.begin(),mgs.end());
  432. mgs.erase(std::unique(mgs.begin(),mgs.end()),mgs.end());
  433. return mgs;
  434. }
  435. } // namespace ZeroTier