Network.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488
  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 "Peer.hpp"
  31. #include "../version.h"
  32. namespace ZeroTier {
  33. const ZeroTier::MulticastGroup Network::BROADCAST(ZeroTier::MAC(0xffffffffffffULL),0);
  34. Network::Network(const RuntimeEnvironment *renv,uint64_t nwid,void *uptr) :
  35. RR(renv),
  36. _uPtr(uptr),
  37. _id(nwid),
  38. _mac(renv->identity.address(),nwid),
  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. Dictionary<ZT_NETWORKCONFIG_DICT_CAPACITY> dconf(conf.c_str());
  60. NetworkConfig nconf;
  61. if (nconf.fromDictionary(dconf)) {
  62. this->setConfiguration(nconf,false);
  63. _lastConfigUpdate = 0; // we still want to re-request a new config from the network
  64. gotConf = true;
  65. }
  66. }
  67. } catch ( ... ) {} // ignore invalids, we'll re-request
  68. if (!gotConf) {
  69. // Save a one-byte CR to persist membership while we request a real netconf
  70. RR->node->dataStorePut(confn,"\n",1,false);
  71. }
  72. }
  73. if (!_portInitialized) {
  74. ZT_VirtualNetworkConfig ctmp;
  75. _externalConfig(&ctmp);
  76. _portError = RR->node->configureVirtualNetworkPort(_id,&_uPtr,ZT_VIRTUAL_NETWORK_CONFIG_OPERATION_UP,&ctmp);
  77. _portInitialized = true;
  78. }
  79. }
  80. Network::~Network()
  81. {
  82. ZT_VirtualNetworkConfig ctmp;
  83. _externalConfig(&ctmp);
  84. char n[128];
  85. if (_destroyed) {
  86. RR->node->configureVirtualNetworkPort(_id,&_uPtr,ZT_VIRTUAL_NETWORK_CONFIG_OPERATION_DESTROY,&ctmp);
  87. Utils::snprintf(n,sizeof(n),"networks.d/%.16llx.conf",_id);
  88. RR->node->dataStoreDelete(n);
  89. } else {
  90. RR->node->configureVirtualNetworkPort(_id,&_uPtr,ZT_VIRTUAL_NETWORK_CONFIG_OPERATION_DOWN,&ctmp);
  91. }
  92. }
  93. bool Network::subscribedToMulticastGroup(const MulticastGroup &mg,bool includeBridgedGroups) const
  94. {
  95. Mutex::Lock _l(_lock);
  96. if (std::binary_search(_myMulticastGroups.begin(),_myMulticastGroups.end(),mg))
  97. return true;
  98. else if (includeBridgedGroups)
  99. return _multicastGroupsBehindMe.contains(mg);
  100. else return false;
  101. }
  102. void Network::multicastSubscribe(const MulticastGroup &mg)
  103. {
  104. {
  105. Mutex::Lock _l(_lock);
  106. if (std::binary_search(_myMulticastGroups.begin(),_myMulticastGroups.end(),mg))
  107. return;
  108. _myMulticastGroups.push_back(mg);
  109. std::sort(_myMulticastGroups.begin(),_myMulticastGroups.end());
  110. }
  111. _announceMulticastGroups();
  112. }
  113. void Network::multicastUnsubscribe(const MulticastGroup &mg)
  114. {
  115. Mutex::Lock _l(_lock);
  116. std::vector<MulticastGroup> nmg;
  117. for(std::vector<MulticastGroup>::const_iterator i(_myMulticastGroups.begin());i!=_myMulticastGroups.end();++i) {
  118. if (*i != mg)
  119. nmg.push_back(*i);
  120. }
  121. if (nmg.size() != _myMulticastGroups.size())
  122. _myMulticastGroups.swap(nmg);
  123. }
  124. bool Network::tryAnnounceMulticastGroupsTo(const SharedPtr<Peer> &peer)
  125. {
  126. Mutex::Lock _l(_lock);
  127. if (
  128. (_isAllowed(peer)) ||
  129. (peer->address() == this->controller()) ||
  130. (RR->topology->isRoot(peer->identity()))
  131. ) {
  132. _announceMulticastGroupsTo(peer,_allMulticastGroups());
  133. return true;
  134. }
  135. return false;
  136. }
  137. bool Network::applyConfiguration(const NetworkConfig &conf)
  138. {
  139. if (_destroyed) // sanity check
  140. return false;
  141. try {
  142. if ((conf.networkId == _id)&&(conf.issuedTo == RR->identity.address())) {
  143. ZT_VirtualNetworkConfig ctmp;
  144. bool portInitialized;
  145. {
  146. Mutex::Lock _l(_lock);
  147. _config = conf;
  148. _lastConfigUpdate = RR->node->now();
  149. _netconfFailure = NETCONF_FAILURE_NONE;
  150. _externalConfig(&ctmp);
  151. portInitialized = _portInitialized;
  152. _portInitialized = true;
  153. }
  154. _portError = RR->node->configureVirtualNetworkPort(_id,&_uPtr,(portInitialized) ? ZT_VIRTUAL_NETWORK_CONFIG_OPERATION_CONFIG_UPDATE : ZT_VIRTUAL_NETWORK_CONFIG_OPERATION_UP,&ctmp);
  155. return true;
  156. } else {
  157. TRACE("ignored invalid configuration for network %.16llx (configuration contains mismatched network ID or issued-to address)",(unsigned long long)_id);
  158. }
  159. } catch (std::exception &exc) {
  160. TRACE("ignored invalid configuration for network %.16llx (%s)",(unsigned long long)_id,exc.what());
  161. } catch ( ... ) {
  162. TRACE("ignored invalid configuration for network %.16llx (unknown exception)",(unsigned long long)_id);
  163. }
  164. return false;
  165. }
  166. int Network::setConfiguration(const NetworkConfig &nconf,bool saveToDisk)
  167. {
  168. try {
  169. {
  170. Mutex::Lock _l(_lock);
  171. if (_config == nconf)
  172. return 1; // OK config, but duplicate of what we already have
  173. }
  174. if (applyConfiguration(nconf)) {
  175. if (saveToDisk) {
  176. char n[64];
  177. Utils::snprintf(n,sizeof(n),"networks.d/%.16llx.conf",_id);
  178. Dictionary<ZT_NETWORKCONFIG_DICT_CAPACITY> d;
  179. if (nconf.toDictionary(d,false))
  180. RR->node->dataStorePut(n,(const void *)d.data(),d.sizeBytes(),true);
  181. }
  182. return 2; // OK and configuration has changed
  183. }
  184. } catch ( ... ) {
  185. TRACE("ignored invalid configuration for network %.16llx",(unsigned long long)_id);
  186. }
  187. return 0;
  188. }
  189. void Network::requestConfiguration()
  190. {
  191. if (_id == ZT_TEST_NETWORK_ID) // pseudo-network-ID, uses locally generated static config
  192. return;
  193. Dictionary<ZT_NETWORKCONFIG_DICT_CAPACITY> rmd;
  194. rmd.add(ZT_NETWORKCONFIG_REQUEST_METADATA_KEY_VERSION,(uint64_t)ZT_NETWORKCONFIG_VERSION);
  195. rmd.add(ZT_NETWORKCONFIG_REQUEST_METADATA_KEY_PROTOCOL_VERSION,(uint64_t)ZT_PROTO_VERSION);
  196. rmd.add(ZT_NETWORKCONFIG_REQUEST_METADATA_KEY_NODE_MAJOR_VERSION,(uint64_t)ZEROTIER_ONE_VERSION_MAJOR);
  197. rmd.add(ZT_NETWORKCONFIG_REQUEST_METADATA_KEY_NODE_MINOR_VERSION,(uint64_t)ZEROTIER_ONE_VERSION_MINOR);
  198. rmd.add(ZT_NETWORKCONFIG_REQUEST_METADATA_KEY_NODE_REVISION,(uint64_t)ZEROTIER_ONE_VERSION_REVISION);
  199. rmd.add(ZT_NETWORKCONFIG_REQUEST_METADATA_KEY_MAX_NETWORK_RULES,(uint64_t)ZT_MAX_NETWORK_RULES);
  200. rmd.add(ZT_NETWORKCONFIG_REQUEST_METADATA_KEY_MAX_CAPABILITY_RULES,(uint64_t)ZT_MAX_CAPABILITY_RULES);
  201. if (controller() == RR->identity.address()) {
  202. if (RR->localNetworkController) {
  203. NetworkConfig nconf;
  204. switch(RR->localNetworkController->doNetworkConfigRequest(InetAddress(),RR->identity,RR->identity,_id,rmd,nconf)) {
  205. case NetworkController::NETCONF_QUERY_OK:
  206. this->setConfiguration(nconf,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. Packet outp(controller(),RR->identity.address(),Packet::VERB_NETWORK_CONFIG_REQUEST);
  224. outp.append((uint64_t)_id);
  225. const unsigned int rmdSize = rmd.sizeBytes();
  226. outp.append((uint16_t)rmdSize);
  227. outp.append((const void *)rmd.data(),rmdSize);
  228. outp.append((_config) ? (uint64_t)_config.revision : (uint64_t)0);
  229. outp.compress();
  230. RR->sw->send(outp,true,0);
  231. }
  232. void Network::clean()
  233. {
  234. const uint64_t now = RR->node->now();
  235. Mutex::Lock _l(_lock);
  236. if (_destroyed)
  237. return;
  238. {
  239. Hashtable< MulticastGroup,uint64_t >::Iterator i(_multicastGroupsBehindMe);
  240. MulticastGroup *mg = (MulticastGroup *)0;
  241. uint64_t *ts = (uint64_t *)0;
  242. while (i.next(mg,ts)) {
  243. if ((now - *ts) > (ZT_MULTICAST_LIKE_EXPIRE * 2))
  244. _multicastGroupsBehindMe.erase(*mg);
  245. }
  246. }
  247. }
  248. void Network::learnBridgeRoute(const MAC &mac,const Address &addr)
  249. {
  250. Mutex::Lock _l(_lock);
  251. _remoteBridgeRoutes[mac] = addr;
  252. // Anti-DOS circuit breaker to prevent nodes from spamming us with absurd numbers of bridge routes
  253. while (_remoteBridgeRoutes.size() > ZT_MAX_BRIDGE_ROUTES) {
  254. Hashtable< Address,unsigned long > counts;
  255. Address maxAddr;
  256. unsigned long maxCount = 0;
  257. MAC *m = (MAC *)0;
  258. Address *a = (Address *)0;
  259. // Find the address responsible for the most entries
  260. {
  261. Hashtable<MAC,Address>::Iterator i(_remoteBridgeRoutes);
  262. while (i.next(m,a)) {
  263. const unsigned long c = ++counts[*a];
  264. if (c > maxCount) {
  265. maxCount = c;
  266. maxAddr = *a;
  267. }
  268. }
  269. }
  270. // Kill this address from our table, since it's most likely spamming us
  271. {
  272. Hashtable<MAC,Address>::Iterator i(_remoteBridgeRoutes);
  273. while (i.next(m,a)) {
  274. if (*a == maxAddr)
  275. _remoteBridgeRoutes.erase(*m);
  276. }
  277. }
  278. }
  279. }
  280. void Network::learnBridgedMulticastGroup(const MulticastGroup &mg,uint64_t now)
  281. {
  282. Mutex::Lock _l(_lock);
  283. const unsigned long tmp = (unsigned long)_multicastGroupsBehindMe.size();
  284. _multicastGroupsBehindMe.set(mg,now);
  285. if (tmp != _multicastGroupsBehindMe.size())
  286. _announceMulticastGroups();
  287. }
  288. void Network::destroy()
  289. {
  290. Mutex::Lock _l(_lock);
  291. _destroyed = true;
  292. }
  293. ZT_VirtualNetworkStatus Network::_status() const
  294. {
  295. // assumes _lock is locked
  296. if (_portError)
  297. return ZT_NETWORK_STATUS_PORT_ERROR;
  298. switch(_netconfFailure) {
  299. case NETCONF_FAILURE_ACCESS_DENIED:
  300. return ZT_NETWORK_STATUS_ACCESS_DENIED;
  301. case NETCONF_FAILURE_NOT_FOUND:
  302. return ZT_NETWORK_STATUS_NOT_FOUND;
  303. case NETCONF_FAILURE_NONE:
  304. return ((_config) ? ZT_NETWORK_STATUS_OK : ZT_NETWORK_STATUS_REQUESTING_CONFIGURATION);
  305. default:
  306. return ZT_NETWORK_STATUS_PORT_ERROR;
  307. }
  308. }
  309. void Network::_externalConfig(ZT_VirtualNetworkConfig *ec) const
  310. {
  311. // assumes _lock is locked
  312. ec->nwid = _id;
  313. ec->mac = _mac.toInt();
  314. if (_config)
  315. Utils::scopy(ec->name,sizeof(ec->name),_config.name);
  316. else ec->name[0] = (char)0;
  317. ec->status = _status();
  318. ec->type = (_config) ? (_config.isPrivate() ? ZT_NETWORK_TYPE_PRIVATE : ZT_NETWORK_TYPE_PUBLIC) : ZT_NETWORK_TYPE_PRIVATE;
  319. ec->mtu = ZT_IF_MTU;
  320. ec->dhcp = 0;
  321. std::vector<Address> ab(_config.activeBridges());
  322. ec->bridge = ((_config.allowPassiveBridging())||(std::find(ab.begin(),ab.end(),RR->identity.address()) != ab.end())) ? 1 : 0;
  323. ec->broadcastEnabled = (_config) ? (_config.enableBroadcast() ? 1 : 0) : 0;
  324. ec->portError = _portError;
  325. ec->netconfRevision = (_config) ? (unsigned long)_config.revision : 0;
  326. ec->assignedAddressCount = 0;
  327. for(unsigned int i=0;i<ZT_MAX_ZT_ASSIGNED_ADDRESSES;++i) {
  328. if (i < _config.staticIpCount) {
  329. memcpy(&(ec->assignedAddresses[i]),&(_config.staticIps[i]),sizeof(struct sockaddr_storage));
  330. ++ec->assignedAddressCount;
  331. } else {
  332. memset(&(ec->assignedAddresses[i]),0,sizeof(struct sockaddr_storage));
  333. }
  334. }
  335. ec->routeCount = 0;
  336. for(unsigned int i=0;i<ZT_MAX_NETWORK_ROUTES;++i) {
  337. if (i < _config.routeCount) {
  338. memcpy(&(ec->routes[i]),&(_config.routes[i]),sizeof(ZT_VirtualNetworkRoute));
  339. ++ec->routeCount;
  340. } else {
  341. memset(&(ec->routes[i]),0,sizeof(ZT_VirtualNetworkRoute));
  342. }
  343. }
  344. }
  345. bool Network::_isAllowed(const SharedPtr<Peer> &peer) const
  346. {
  347. // Assumes _lock is locked
  348. try {
  349. if (_config) {
  350. if (_config.isPublic()) {
  351. return true;
  352. } else {
  353. LockingPtr<Membership> m(peer->membership(_id,false));
  354. if (m) {
  355. return _config.com.agreesWith(m->com());
  356. }
  357. }
  358. }
  359. } catch ( ... ) {
  360. TRACE("isAllowed() check failed for peer %s: unexpected exception: unexpected exception",peer->address().toString().c_str());
  361. }
  362. return false;
  363. }
  364. class _MulticastAnnounceAll
  365. {
  366. public:
  367. _MulticastAnnounceAll(const RuntimeEnvironment *renv,Network *nw) :
  368. _now(renv->node->now()),
  369. _controller(nw->controller()),
  370. _network(nw),
  371. _anchors(nw->config().anchors()),
  372. _upstreamAddresses(renv->topology->upstreamAddresses())
  373. {}
  374. inline void operator()(Topology &t,const SharedPtr<Peer> &p)
  375. {
  376. if ( (_network->_isAllowed(p)) || // FIXME: this causes multicast LIKEs for public networks to get spammed, which isn't terrible but is a bit stupid
  377. (p->address() == _controller) ||
  378. (std::find(_upstreamAddresses.begin(),_upstreamAddresses.end(),p->address()) != _upstreamAddresses.end()) ||
  379. (std::find(_anchors.begin(),_anchors.end(),p->address()) != _anchors.end()) ) {
  380. peers.push_back(p);
  381. }
  382. }
  383. std::vector< SharedPtr<Peer> > peers;
  384. private:
  385. const uint64_t _now;
  386. const Address _controller;
  387. Network *const _network;
  388. const std::vector<Address> _anchors;
  389. const std::vector<Address> _upstreamAddresses;
  390. };
  391. void Network::_announceMulticastGroups()
  392. {
  393. // Assumes _lock is locked
  394. std::vector<MulticastGroup> allMulticastGroups(_allMulticastGroups());
  395. _MulticastAnnounceAll gpfunc(RR,this);
  396. RR->topology->eachPeer<_MulticastAnnounceAll &>(gpfunc);
  397. for(std::vector< SharedPtr<Peer> >::const_iterator i(gpfunc.peers.begin());i!=gpfunc.peers.end();++i)
  398. _announceMulticastGroupsTo(*i,allMulticastGroups);
  399. }
  400. void Network::_announceMulticastGroupsTo(const SharedPtr<Peer> &peer,const std::vector<MulticastGroup> &allMulticastGroups) const
  401. {
  402. // Assumes _lock is locked
  403. // Anyone we announce multicast groups to will need our COM to authenticate GATHER requests.
  404. {
  405. LockingPtr<Membership> m(peer->membership(_id,false));
  406. if (m) m->sendCredentialsIfNeeded(RR,RR->node->now(),*peer,_config);
  407. }
  408. Packet outp(peer->address(),RR->identity.address(),Packet::VERB_MULTICAST_LIKE);
  409. for(std::vector<MulticastGroup>::const_iterator mg(allMulticastGroups.begin());mg!=allMulticastGroups.end();++mg) {
  410. if ((outp.size() + 24) >= ZT_PROTO_MAX_PACKET_LENGTH) {
  411. outp.compress();
  412. RR->sw->send(outp,true,0);
  413. outp.reset(peer->address(),RR->identity.address(),Packet::VERB_MULTICAST_LIKE);
  414. }
  415. // network ID, MAC, ADI
  416. outp.append((uint64_t)_id);
  417. mg->mac().appendTo(outp);
  418. outp.append((uint32_t)mg->adi());
  419. }
  420. if (outp.size() > ZT_PROTO_MIN_PACKET_LENGTH) {
  421. outp.compress();
  422. RR->sw->send(outp,true,0);
  423. }
  424. }
  425. std::vector<MulticastGroup> Network::_allMulticastGroups() const
  426. {
  427. // Assumes _lock is locked
  428. std::vector<MulticastGroup> mgs;
  429. mgs.reserve(_myMulticastGroups.size() + _multicastGroupsBehindMe.size() + 1);
  430. mgs.insert(mgs.end(),_myMulticastGroups.begin(),_myMulticastGroups.end());
  431. _multicastGroupsBehindMe.appendKeys(mgs);
  432. if ((_config)&&(_config.enableBroadcast()))
  433. mgs.push_back(Network::BROADCAST);
  434. std::sort(mgs.begin(),mgs.end());
  435. mgs.erase(std::unique(mgs.begin(),mgs.end()),mgs.end());
  436. return mgs;
  437. }
  438. } // namespace ZeroTier