Network.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484
  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. if (_id == ZT_TEST_NETWORK_ID) {
  48. applyConfiguration(NetworkConfig::createTestNetworkConfig(RR->identity.address()));
  49. // Save a one-byte CR to persist membership in the test network
  50. RR->node->dataStorePut(confn,"\n",1,false);
  51. } else {
  52. bool gotConf = false;
  53. try {
  54. std::string conf(RR->node->dataStoreGet(confn));
  55. if (conf.length()) {
  56. Dictionary<ZT_NETWORKCONFIG_DICT_CAPACITY> dconf(conf.c_str());
  57. NetworkConfig nconf;
  58. if (nconf.fromDictionary(dconf)) {
  59. this->setConfiguration(nconf,false);
  60. _lastConfigUpdate = 0; // we still want to re-request a new config from the network
  61. gotConf = true;
  62. }
  63. }
  64. } catch ( ... ) {} // ignore invalids, we'll re-request
  65. if (!gotConf) {
  66. // Save a one-byte CR to persist membership while we request a real netconf
  67. RR->node->dataStorePut(confn,"\n",1,false);
  68. }
  69. }
  70. if (!_portInitialized) {
  71. ZT_VirtualNetworkConfig ctmp;
  72. _externalConfig(&ctmp);
  73. _portError = RR->node->configureVirtualNetworkPort(_id,&_uPtr,ZT_VIRTUAL_NETWORK_CONFIG_OPERATION_UP,&ctmp);
  74. _portInitialized = true;
  75. }
  76. }
  77. Network::~Network()
  78. {
  79. ZT_VirtualNetworkConfig ctmp;
  80. _externalConfig(&ctmp);
  81. char n[128];
  82. if (_destroyed) {
  83. RR->node->configureVirtualNetworkPort(_id,&_uPtr,ZT_VIRTUAL_NETWORK_CONFIG_OPERATION_DESTROY,&ctmp);
  84. Utils::snprintf(n,sizeof(n),"networks.d/%.16llx.conf",_id);
  85. RR->node->dataStoreDelete(n);
  86. } else {
  87. RR->node->configureVirtualNetworkPort(_id,&_uPtr,ZT_VIRTUAL_NETWORK_CONFIG_OPERATION_DOWN,&ctmp);
  88. }
  89. }
  90. bool Network::subscribedToMulticastGroup(const MulticastGroup &mg,bool includeBridgedGroups) const
  91. {
  92. Mutex::Lock _l(_lock);
  93. if (std::binary_search(_myMulticastGroups.begin(),_myMulticastGroups.end(),mg))
  94. return true;
  95. else if (includeBridgedGroups)
  96. return _multicastGroupsBehindMe.contains(mg);
  97. else return false;
  98. }
  99. void Network::multicastSubscribe(const MulticastGroup &mg)
  100. {
  101. {
  102. Mutex::Lock _l(_lock);
  103. if (std::binary_search(_myMulticastGroups.begin(),_myMulticastGroups.end(),mg))
  104. return;
  105. _myMulticastGroups.push_back(mg);
  106. std::sort(_myMulticastGroups.begin(),_myMulticastGroups.end());
  107. }
  108. _announceMulticastGroups();
  109. }
  110. void Network::multicastUnsubscribe(const MulticastGroup &mg)
  111. {
  112. Mutex::Lock _l(_lock);
  113. std::vector<MulticastGroup> nmg;
  114. for(std::vector<MulticastGroup>::const_iterator i(_myMulticastGroups.begin());i!=_myMulticastGroups.end();++i) {
  115. if (*i != mg)
  116. nmg.push_back(*i);
  117. }
  118. if (nmg.size() != _myMulticastGroups.size())
  119. _myMulticastGroups.swap(nmg);
  120. }
  121. bool Network::tryAnnounceMulticastGroupsTo(const SharedPtr<Peer> &peer)
  122. {
  123. Mutex::Lock _l(_lock);
  124. if (
  125. (_isAllowed(peer)) ||
  126. (peer->address() == this->controller()) ||
  127. (RR->topology->isUpstream(peer->identity()))
  128. ) {
  129. _announceMulticastGroupsTo(peer,_allMulticastGroups());
  130. return true;
  131. }
  132. return false;
  133. }
  134. bool Network::applyConfiguration(const NetworkConfig &conf)
  135. {
  136. if (_destroyed) // sanity check
  137. return false;
  138. try {
  139. if ((conf.networkId == _id)&&(conf.issuedTo == RR->identity.address())) {
  140. ZT_VirtualNetworkConfig ctmp;
  141. bool portInitialized;
  142. {
  143. Mutex::Lock _l(_lock);
  144. _config = conf;
  145. _lastConfigUpdate = RR->node->now();
  146. _netconfFailure = NETCONF_FAILURE_NONE;
  147. _externalConfig(&ctmp);
  148. portInitialized = _portInitialized;
  149. _portInitialized = true;
  150. }
  151. _portError = RR->node->configureVirtualNetworkPort(_id,&_uPtr,(portInitialized) ? ZT_VIRTUAL_NETWORK_CONFIG_OPERATION_CONFIG_UPDATE : ZT_VIRTUAL_NETWORK_CONFIG_OPERATION_UP,&ctmp);
  152. return true;
  153. } else {
  154. TRACE("ignored invalid configuration for network %.16llx (configuration contains mismatched network ID or issued-to address)",(unsigned long long)_id);
  155. }
  156. } catch (std::exception &exc) {
  157. TRACE("ignored invalid configuration for network %.16llx (%s)",(unsigned long long)_id,exc.what());
  158. } catch ( ... ) {
  159. TRACE("ignored invalid configuration for network %.16llx (unknown exception)",(unsigned long long)_id);
  160. }
  161. return false;
  162. }
  163. int Network::setConfiguration(const NetworkConfig &nconf,bool saveToDisk)
  164. {
  165. try {
  166. {
  167. Mutex::Lock _l(_lock);
  168. if (_config == nconf)
  169. return 1; // OK config, but duplicate of what we already have
  170. }
  171. if (applyConfiguration(nconf)) {
  172. if (saveToDisk) {
  173. char n[64];
  174. Utils::snprintf(n,sizeof(n),"networks.d/%.16llx.conf",_id);
  175. Dictionary<ZT_NETWORKCONFIG_DICT_CAPACITY> d;
  176. if (nconf.toDictionary(d,false))
  177. RR->node->dataStorePut(n,(const void *)d.data(),d.sizeBytes(),true);
  178. }
  179. return 2; // OK and configuration has changed
  180. }
  181. } catch ( ... ) {
  182. TRACE("ignored invalid configuration for network %.16llx",(unsigned long long)_id);
  183. }
  184. return 0;
  185. }
  186. void Network::requestConfiguration()
  187. {
  188. if (_id == ZT_TEST_NETWORK_ID) // pseudo-network-ID, uses locally generated static config
  189. return;
  190. Dictionary<ZT_NETWORKCONFIG_DICT_CAPACITY> rmd;
  191. rmd.add(ZT_NETWORKCONFIG_REQUEST_METADATA_KEY_VERSION,(uint64_t)ZT_NETWORKCONFIG_VERSION);
  192. rmd.add(ZT_NETWORKCONFIG_REQUEST_METADATA_KEY_PROTOCOL_VERSION,(uint64_t)ZT_PROTO_VERSION);
  193. rmd.add(ZT_NETWORKCONFIG_REQUEST_METADATA_KEY_NODE_MAJOR_VERSION,(uint64_t)ZEROTIER_ONE_VERSION_MAJOR);
  194. rmd.add(ZT_NETWORKCONFIG_REQUEST_METADATA_KEY_NODE_MINOR_VERSION,(uint64_t)ZEROTIER_ONE_VERSION_MINOR);
  195. rmd.add(ZT_NETWORKCONFIG_REQUEST_METADATA_KEY_NODE_REVISION,(uint64_t)ZEROTIER_ONE_VERSION_REVISION);
  196. rmd.add(ZT_NETWORKCONFIG_REQUEST_METADATA_KEY_MAX_NETWORK_RULES,(uint64_t)ZT_MAX_NETWORK_RULES);
  197. rmd.add(ZT_NETWORKCONFIG_REQUEST_METADATA_KEY_MAX_CAPABILITY_RULES,(uint64_t)ZT_MAX_CAPABILITY_RULES);
  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. if (_config.isPublic()) {
  348. return true;
  349. } else {
  350. LockingPtr<Membership> m(peer->membership(_id,false));
  351. if (m) {
  352. return _config.com.agreesWith(m->com());
  353. }
  354. }
  355. }
  356. } catch ( ... ) {
  357. TRACE("isAllowed() check failed for peer %s: unexpected exception: unexpected exception",peer->address().toString().c_str());
  358. }
  359. return false;
  360. }
  361. class _MulticastAnnounceAll
  362. {
  363. public:
  364. _MulticastAnnounceAll(const RuntimeEnvironment *renv,Network *nw) :
  365. _now(renv->node->now()),
  366. _controller(nw->controller()),
  367. _network(nw),
  368. _anchors(nw->config().anchors()),
  369. _upstreamAddresses(renv->topology->upstreamAddresses())
  370. {}
  371. inline void operator()(Topology &t,const SharedPtr<Peer> &p)
  372. {
  373. if ( (_network->_isAllowed(p)) || // FIXME: this causes multicast LIKEs for public networks to get spammed, which isn't terrible but is a bit stupid
  374. (p->address() == _controller) ||
  375. (std::find(_upstreamAddresses.begin(),_upstreamAddresses.end(),p->address()) != _upstreamAddresses.end()) ||
  376. (std::find(_anchors.begin(),_anchors.end(),p->address()) != _anchors.end()) ) {
  377. peers.push_back(p);
  378. }
  379. }
  380. std::vector< SharedPtr<Peer> > peers;
  381. private:
  382. const uint64_t _now;
  383. const Address _controller;
  384. Network *const _network;
  385. const std::vector<Address> _anchors;
  386. const std::vector<Address> _upstreamAddresses;
  387. };
  388. void Network::_announceMulticastGroups()
  389. {
  390. // Assumes _lock is locked
  391. std::vector<MulticastGroup> allMulticastGroups(_allMulticastGroups());
  392. _MulticastAnnounceAll gpfunc(RR,this);
  393. RR->topology->eachPeer<_MulticastAnnounceAll &>(gpfunc);
  394. for(std::vector< SharedPtr<Peer> >::const_iterator i(gpfunc.peers.begin());i!=gpfunc.peers.end();++i)
  395. _announceMulticastGroupsTo(*i,allMulticastGroups);
  396. }
  397. void Network::_announceMulticastGroupsTo(const SharedPtr<Peer> &peer,const std::vector<MulticastGroup> &allMulticastGroups) const
  398. {
  399. // Assumes _lock is locked
  400. // Anyone we announce multicast groups to will need our COM to authenticate GATHER requests.
  401. {
  402. LockingPtr<Membership> m(peer->membership(_id,false));
  403. if (m) m->sendCredentialsIfNeeded(RR,RR->node->now(),*peer,_config);
  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() + 24) >= ZT_PROTO_MAX_PACKET_LENGTH) {
  408. outp.compress();
  409. RR->sw->send(outp,true,0);
  410. outp.reset(peer->address(),RR->identity.address(),Packet::VERB_MULTICAST_LIKE);
  411. }
  412. // network ID, MAC, ADI
  413. outp.append((uint64_t)_id);
  414. mg->mac().appendTo(outp);
  415. outp.append((uint32_t)mg->adi());
  416. }
  417. if (outp.size() > ZT_PROTO_MIN_PACKET_LENGTH) {
  418. outp.compress();
  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