Network.cpp 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878
  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 "../version.h"
  24. #include "Network.hpp"
  25. #include "RuntimeEnvironment.hpp"
  26. #include "MAC.hpp"
  27. #include "Address.hpp"
  28. #include "InetAddress.hpp"
  29. #include "Switch.hpp"
  30. #include "Buffer.hpp"
  31. #include "Packet.hpp"
  32. #include "NetworkController.hpp"
  33. #include "Node.hpp"
  34. #include "Peer.hpp"
  35. namespace ZeroTier {
  36. // Returns true if packet appears valid; pos and proto will be set
  37. static bool _ipv6GetPayload(const uint8_t *frameData,unsigned int frameLen,unsigned int &pos,unsigned int &proto)
  38. {
  39. if (frameLen < 40)
  40. return false;
  41. pos = 40;
  42. proto = frameData[6];
  43. while (pos <= frameLen) {
  44. switch(proto) {
  45. case 0: // hop-by-hop options
  46. case 43: // routing
  47. case 60: // destination options
  48. case 135: // mobility options
  49. if ((pos + 8) > frameLen)
  50. return false; // invalid!
  51. proto = frameData[pos];
  52. pos += ((unsigned int)frameData[pos + 1] * 8) + 8;
  53. break;
  54. //case 44: // fragment -- we currently can't parse these and they are deprecated in IPv6 anyway
  55. //case 50:
  56. //case 51: // IPSec ESP and AH -- we have to stop here since this is encrypted stuff
  57. default:
  58. return true;
  59. }
  60. }
  61. return false; // overflow == invalid
  62. }
  63. static bool _doZtFilter(
  64. const RuntimeEnvironment *RR,
  65. const uint64_t nwid,
  66. const bool inbound,
  67. const Address &ztSource,
  68. const Address &ztDest,
  69. const MAC &macSource,
  70. const MAC &macDest,
  71. const uint8_t *frameData,
  72. const unsigned int frameLen,
  73. const unsigned int etherType,
  74. const unsigned int vlanId,
  75. const ZT_VirtualNetworkRule *rules,
  76. const unsigned int ruleCount,
  77. const Tag *localTags,
  78. const unsigned int localTagCount,
  79. const uint32_t *remoteTagIds,
  80. const uint32_t *remoteTagValues,
  81. const unsigned int remoteTagCount,
  82. const Tag **relevantLocalTags, // pointer array must be at least [localTagCount] in size
  83. unsigned int &relevantLocalTagCount)
  84. {
  85. // For each set of rules we start by assuming that they match (since no constraints
  86. // yields a 'match all' rule).
  87. uint8_t thisSetMatches = 1;
  88. for(unsigned int rn=0;rn<ruleCount;++rn) {
  89. const ZT_VirtualNetworkRuleType rt = (ZT_VirtualNetworkRuleType)(rules[rn].t & 0x7f);
  90. uint8_t thisRuleMatches = 0;
  91. switch(rt) {
  92. // Actions -------------------------------------------------------------
  93. case ZT_NETWORK_RULE_ACTION_DROP:
  94. if (thisSetMatches) {
  95. return false;
  96. } else {
  97. thisSetMatches = 1; // continue parsing next set of rules
  98. }
  99. break;
  100. case ZT_NETWORK_RULE_ACTION_ACCEPT:
  101. if (thisSetMatches) {
  102. return true;
  103. } else {
  104. thisSetMatches = 1; // continue parsing next set of rules
  105. }
  106. break;
  107. case ZT_NETWORK_RULE_ACTION_TEE:
  108. case ZT_NETWORK_RULE_ACTION_REDIRECT: {
  109. Packet outp(Address(rules[rn].v.zt),RR->identity.address(),Packet::VERB_EXT_FRAME);
  110. outp.append(nwid);
  111. outp.append((uint8_t)((rt == ZT_NETWORK_RULE_ACTION_REDIRECT) ? 0x04 : 0x02));
  112. macDest.appendTo(outp);
  113. macSource.appendTo(outp);
  114. outp.append((uint16_t)etherType);
  115. outp.append(frameData,frameLen);
  116. outp.compress();
  117. RR->sw->send(outp,true,nwid);
  118. if (rt == ZT_NETWORK_RULE_ACTION_REDIRECT) {
  119. return false;
  120. } else {
  121. thisSetMatches = 1; // TEE does not terminate parsing
  122. }
  123. } break;
  124. // Rules ---------------------------------------------------------------
  125. case ZT_NETWORK_RULE_MATCH_SOURCE_ZEROTIER_ADDRESS:
  126. thisRuleMatches = (uint8_t)(rules[rn].v.zt == ztSource.toInt());
  127. break;
  128. case ZT_NETWORK_RULE_MATCH_DEST_ZEROTIER_ADDRESS:
  129. thisRuleMatches = (uint8_t)(rules[rn].v.zt == ztDest.toInt());
  130. break;
  131. case ZT_NETWORK_RULE_MATCH_VLAN_ID:
  132. thisRuleMatches = (uint8_t)(rules[rn].v.vlanId == (uint16_t)vlanId);
  133. break;
  134. case ZT_NETWORK_RULE_MATCH_VLAN_PCP:
  135. // NOT SUPPORTED YET
  136. thisRuleMatches = (uint8_t)(rules[rn].v.vlanPcp == 0);
  137. break;
  138. case ZT_NETWORK_RULE_MATCH_VLAN_DEI:
  139. // NOT SUPPORTED YET
  140. thisRuleMatches = (uint8_t)(rules[rn].v.vlanDei == 0);
  141. break;
  142. case ZT_NETWORK_RULE_MATCH_ETHERTYPE:
  143. thisRuleMatches = (uint8_t)(rules[rn].v.etherType == (uint16_t)etherType);
  144. break;
  145. case ZT_NETWORK_RULE_MATCH_MAC_SOURCE:
  146. thisRuleMatches = (uint8_t)(MAC(rules[rn].v.mac,6) == macSource);
  147. break;
  148. case ZT_NETWORK_RULE_MATCH_MAC_DEST:
  149. thisRuleMatches = (uint8_t)(MAC(rules[rn].v.mac,6) == macDest);
  150. break;
  151. case ZT_NETWORK_RULE_MATCH_IPV4_SOURCE:
  152. if ((etherType == ZT_ETHERTYPE_IPV4)&&(frameLen >= 20)) {
  153. thisRuleMatches = (uint8_t)(InetAddress((const void *)&(rules[rn].v.ipv4.ip),4,rules[rn].v.ipv4.mask).containsAddress(InetAddress((const void *)(frameData + 12),4,0)));
  154. } else {
  155. thisRuleMatches = 0;
  156. }
  157. break;
  158. case ZT_NETWORK_RULE_MATCH_IPV4_DEST:
  159. if ((etherType == ZT_ETHERTYPE_IPV4)&&(frameLen >= 20)) {
  160. thisRuleMatches = (uint8_t)(InetAddress((const void *)&(rules[rn].v.ipv4.ip),4,rules[rn].v.ipv4.mask).containsAddress(InetAddress((const void *)(frameData + 16),4,0)));
  161. } else {
  162. thisRuleMatches = 0;
  163. }
  164. break;
  165. case ZT_NETWORK_RULE_MATCH_IPV6_SOURCE:
  166. if ((etherType == ZT_ETHERTYPE_IPV6)&&(frameLen >= 40)) {
  167. thisRuleMatches = (uint8_t)(InetAddress((const void *)rules[rn].v.ipv6.ip,16,rules[rn].v.ipv6.mask).containsAddress(InetAddress((const void *)(frameData + 8),16,0)));
  168. } else {
  169. thisRuleMatches = 0;
  170. }
  171. break;
  172. case ZT_NETWORK_RULE_MATCH_IPV6_DEST:
  173. if ((etherType == ZT_ETHERTYPE_IPV6)&&(frameLen >= 40)) {
  174. thisRuleMatches = (uint8_t)(InetAddress((const void *)rules[rn].v.ipv6.ip,16,rules[rn].v.ipv6.mask).containsAddress(InetAddress((const void *)(frameData + 24),16,0)));
  175. } else {
  176. thisRuleMatches = 0;
  177. }
  178. break;
  179. case ZT_NETWORK_RULE_MATCH_IP_TOS:
  180. if ((etherType == ZT_ETHERTYPE_IPV4)&&(frameLen >= 20)) {
  181. thisRuleMatches = (uint8_t)(rules[rn].v.ipTos == ((frameData[1] & 0xfc) >> 2));
  182. } else if ((etherType == ZT_ETHERTYPE_IPV6)&&(frameLen >= 40)) {
  183. const uint8_t trafficClass = ((frameData[0] << 4) & 0xf0) | ((frameData[1] >> 4) & 0x0f);
  184. thisRuleMatches = (uint8_t)(rules[rn].v.ipTos == ((trafficClass & 0xfc) >> 2));
  185. } else {
  186. thisRuleMatches = 0;
  187. }
  188. break;
  189. case ZT_NETWORK_RULE_MATCH_IP_PROTOCOL:
  190. if ((etherType == ZT_ETHERTYPE_IPV4)&&(frameLen >= 20)) {
  191. thisRuleMatches = (uint8_t)(rules[rn].v.ipProtocol == frameData[9]);
  192. } else if (etherType == ZT_ETHERTYPE_IPV6) {
  193. unsigned int pos = 0,proto = 0;
  194. if (_ipv6GetPayload(frameData,frameLen,pos,proto)) {
  195. thisRuleMatches = (uint8_t)(rules[rn].v.ipProtocol == (uint8_t)proto);
  196. } else {
  197. thisRuleMatches = 0;
  198. }
  199. } else {
  200. thisRuleMatches = 0;
  201. }
  202. break;
  203. case ZT_NETWORK_RULE_MATCH_IP_SOURCE_PORT_RANGE:
  204. case ZT_NETWORK_RULE_MATCH_IP_DEST_PORT_RANGE:
  205. if ((etherType == ZT_ETHERTYPE_IPV4)&&(frameLen >= 20)) {
  206. const unsigned int headerLen = 4 * (frameData[0] & 0xf);
  207. int p = -1;
  208. switch(frameData[9]) { // IP protocol number
  209. // All these start with 16-bit source and destination port in that order
  210. case 0x06: // TCP
  211. case 0x11: // UDP
  212. case 0x84: // SCTP
  213. case 0x88: // UDPLite
  214. if (frameLen > (headerLen + 4)) {
  215. unsigned int pos = headerLen + ((rt == ZT_NETWORK_RULE_MATCH_IP_DEST_PORT_RANGE) ? 2 : 0);
  216. p = (int)frameData[pos++] << 8;
  217. p |= (int)frameData[pos];
  218. }
  219. break;
  220. }
  221. thisRuleMatches = (p > 0) ? (uint8_t)((p >= (int)rules[rn].v.port[0])&&(p <= (int)rules[rn].v.port[1])) : (uint8_t)0;
  222. } else if (etherType == ZT_ETHERTYPE_IPV6) {
  223. unsigned int pos = 0,proto = 0;
  224. if (_ipv6GetPayload(frameData,frameLen,pos,proto)) {
  225. int p = -1;
  226. switch(proto) { // IP protocol number
  227. // All these start with 16-bit source and destination port in that order
  228. case 0x06: // TCP
  229. case 0x11: // UDP
  230. case 0x84: // SCTP
  231. case 0x88: // UDPLite
  232. if (frameLen > (pos + 4)) {
  233. if (rt == ZT_NETWORK_RULE_MATCH_IP_DEST_PORT_RANGE) pos += 2;
  234. p = (int)frameData[pos++] << 8;
  235. p |= (int)frameData[pos];
  236. }
  237. break;
  238. }
  239. thisRuleMatches = (p > 0) ? (uint8_t)((p >= (int)rules[rn].v.port[0])&&(p <= (int)rules[rn].v.port[1])) : (uint8_t)0;
  240. } else {
  241. thisRuleMatches = 0;
  242. }
  243. } else {
  244. thisRuleMatches = 0;
  245. }
  246. break;
  247. case ZT_NETWORK_RULE_MATCH_CHARACTERISTICS: {
  248. uint64_t cf = (inbound) ? ZT_RULE_PACKET_CHARACTERISTICS_INBOUND : 0ULL;
  249. if ((etherType == ZT_ETHERTYPE_IPV4)&&(frameLen >= 20)&&(frameData[9] == 0x06)) {
  250. const unsigned int headerLen = 4 * (frameData[0] & 0xf);
  251. cf |= (uint64_t)frameData[headerLen + 13];
  252. cf |= (((uint64_t)(frameData[headerLen + 12] & 0x0f)) << 8);
  253. } else if (etherType == ZT_ETHERTYPE_IPV6) {
  254. unsigned int pos = 0,proto = 0;
  255. if (_ipv6GetPayload(frameData,frameLen,pos,proto)) {
  256. if ((proto == 0x06)&&(frameLen > (pos + 14))) {
  257. cf |= (uint64_t)frameData[pos + 13];
  258. cf |= (((uint64_t)(frameData[pos + 12] & 0x0f)) << 8);
  259. }
  260. }
  261. }
  262. thisRuleMatches = (uint8_t)((cf & rules[rn].v.characteristics[0]) == rules[rn].v.characteristics[1]);
  263. } break;
  264. case ZT_NETWORK_RULE_MATCH_FRAME_SIZE_RANGE:
  265. thisRuleMatches = (uint8_t)((frameLen >= (unsigned int)rules[rn].v.frameSize[0])&&(frameLen <= (unsigned int)rules[rn].v.frameSize[1]));
  266. break;
  267. case ZT_NETWORK_RULE_MATCH_TAGS_SAMENESS:
  268. case ZT_NETWORK_RULE_MATCH_TAGS_BITWISE_AND:
  269. case ZT_NETWORK_RULE_MATCH_TAGS_BITWISE_OR:
  270. case ZT_NETWORK_RULE_MATCH_TAGS_BITWISE_XOR: {
  271. const Tag *lt = (const Tag *)0;
  272. for(unsigned int i=0;i<localTagCount;++i) {
  273. if (rules[rn].v.tag.id == localTags[i].id()) {
  274. lt = &(localTags[i]);
  275. break;
  276. }
  277. }
  278. if (!lt) {
  279. thisRuleMatches = 0;
  280. } else {
  281. const uint32_t *rtv = (const uint32_t *)0;
  282. for(unsigned int i=0;i<remoteTagCount;++i) {
  283. if (rules[rn].v.tag.id == remoteTagIds[i]) {
  284. rtv = &(remoteTagValues[i]);
  285. break;
  286. }
  287. }
  288. if (!rtv) {
  289. thisRuleMatches = 0;
  290. } else {
  291. if (rt == ZT_NETWORK_RULE_MATCH_TAGS_SAMENESS) {
  292. const uint32_t sameness = (lt->value() > *rtv) ? (lt->value() - *rtv) : (*rtv - lt->value());
  293. thisRuleMatches = (uint8_t)(sameness <= rules[rn].v.tag.value);
  294. } else if (rt == ZT_NETWORK_RULE_MATCH_TAGS_BITWISE_AND) {
  295. thisRuleMatches = (uint8_t)((lt->value() & *rtv) <= rules[rn].v.tag.value);
  296. } else if (rt == ZT_NETWORK_RULE_MATCH_TAGS_BITWISE_OR) {
  297. thisRuleMatches = (uint8_t)((lt->value() | *rtv) <= rules[rn].v.tag.value);
  298. } else if (rt == ZT_NETWORK_RULE_MATCH_TAGS_BITWISE_XOR) {
  299. thisRuleMatches = (uint8_t)((lt->value() ^ *rtv) <= rules[rn].v.tag.value);
  300. } else { // sanity check, can't really happen
  301. thisRuleMatches = 0;
  302. }
  303. if (thisRuleMatches) {
  304. relevantLocalTags[relevantLocalTagCount++] = lt;
  305. }
  306. }
  307. }
  308. } break;
  309. }
  310. // thisSetMatches remains true if the current rule matched... or does NOT match if not bit (0x80) is 1
  311. thisSetMatches &= (thisRuleMatches ^ ((rules[rn].t & 0x80) >> 7));
  312. //TRACE("[%u] %u result==%u set==%u",rn,(unsigned int)rt,(unsigned int)thisRuleMatches,(unsigned int)thisSetMatches);
  313. }
  314. return false;
  315. }
  316. const ZeroTier::MulticastGroup Network::BROADCAST(ZeroTier::MAC(0xffffffffffffULL),0);
  317. Network::Network(const RuntimeEnvironment *renv,uint64_t nwid,void *uptr) :
  318. RR(renv),
  319. _uPtr(uptr),
  320. _id(nwid),
  321. _mac(renv->identity.address(),nwid),
  322. _portInitialized(false),
  323. _lastConfigUpdate(0),
  324. _destroyed(false),
  325. _netconfFailure(NETCONF_FAILURE_NONE),
  326. _portError(0)
  327. {
  328. char confn[128],mcdbn[128];
  329. Utils::snprintf(confn,sizeof(confn),"networks.d/%.16llx.conf",_id);
  330. if (_id == ZT_TEST_NETWORK_ID) {
  331. applyConfiguration(NetworkConfig::createTestNetworkConfig(RR->identity.address()));
  332. // Save a one-byte CR to persist membership in the test network
  333. RR->node->dataStorePut(confn,"\n",1,false);
  334. } else {
  335. bool gotConf = false;
  336. try {
  337. std::string conf(RR->node->dataStoreGet(confn));
  338. if (conf.length()) {
  339. Dictionary<ZT_NETWORKCONFIG_DICT_CAPACITY> dconf(conf.c_str());
  340. NetworkConfig nconf;
  341. if (nconf.fromDictionary(dconf)) {
  342. this->setConfiguration(nconf,false);
  343. _lastConfigUpdate = 0; // we still want to re-request a new config from the network
  344. gotConf = true;
  345. }
  346. }
  347. } catch ( ... ) {} // ignore invalids, we'll re-request
  348. if (!gotConf) {
  349. // Save a one-byte CR to persist membership while we request a real netconf
  350. RR->node->dataStorePut(confn,"\n",1,false);
  351. }
  352. }
  353. if (!_portInitialized) {
  354. ZT_VirtualNetworkConfig ctmp;
  355. _externalConfig(&ctmp);
  356. _portError = RR->node->configureVirtualNetworkPort(_id,&_uPtr,ZT_VIRTUAL_NETWORK_CONFIG_OPERATION_UP,&ctmp);
  357. _portInitialized = true;
  358. }
  359. }
  360. Network::~Network()
  361. {
  362. ZT_VirtualNetworkConfig ctmp;
  363. _externalConfig(&ctmp);
  364. char n[128];
  365. if (_destroyed) {
  366. RR->node->configureVirtualNetworkPort(_id,&_uPtr,ZT_VIRTUAL_NETWORK_CONFIG_OPERATION_DESTROY,&ctmp);
  367. Utils::snprintf(n,sizeof(n),"networks.d/%.16llx.conf",_id);
  368. RR->node->dataStoreDelete(n);
  369. } else {
  370. RR->node->configureVirtualNetworkPort(_id,&_uPtr,ZT_VIRTUAL_NETWORK_CONFIG_OPERATION_DOWN,&ctmp);
  371. }
  372. }
  373. bool Network::filterOutgoingPacket(
  374. const Address &ztSource,
  375. const Address &ztDest,
  376. const MAC &macSource,
  377. const MAC &macDest,
  378. const uint8_t *frameData,
  379. const unsigned int frameLen,
  380. const unsigned int etherType,
  381. const unsigned int vlanId)
  382. {
  383. uint32_t remoteTagIds[ZT_MAX_NETWORK_TAGS];
  384. uint32_t remoteTagValues[ZT_MAX_NETWORK_TAGS];
  385. const Tag *relevantLocalTags[ZT_MAX_NETWORK_TAGS];
  386. unsigned int relevantLocalTagCount = 0;
  387. Mutex::Lock _l(_lock);
  388. Membership &m = _memberships[ztDest];
  389. const unsigned int remoteTagCount = m.getAllTags(_config,remoteTagIds,remoteTagValues,ZT_MAX_NETWORK_TAGS);
  390. if (_doZtFilter(
  391. RR,
  392. _id,
  393. false,
  394. ztSource,
  395. ztDest,
  396. macSource,
  397. macDest,
  398. frameData,
  399. frameLen,
  400. etherType,
  401. vlanId,
  402. _config.rules,
  403. _config.ruleCount,
  404. _config.tags,
  405. _config.tagCount,
  406. remoteTagIds,
  407. remoteTagValues,
  408. remoteTagCount,
  409. relevantLocalTags,
  410. relevantLocalTagCount
  411. )) {
  412. m.sendCredentialsIfNeeded(RR,RR->node->now(),ztDest,_config.com,(const Capability *)0,relevantLocalTags,relevantLocalTagCount);
  413. return true;
  414. }
  415. for(unsigned int c=0;c<_config.capabilityCount;++c) {
  416. relevantLocalTagCount = 0;
  417. if (_doZtFilter(
  418. RR,
  419. _id,
  420. false,
  421. ztSource,
  422. ztDest,
  423. macSource,
  424. macDest,
  425. frameData,
  426. frameLen,
  427. etherType,
  428. vlanId,
  429. _config.capabilities[c].rules(),
  430. _config.capabilities[c].ruleCount(),
  431. _config.tags,
  432. _config.tagCount,
  433. remoteTagIds,
  434. remoteTagValues,
  435. remoteTagCount,
  436. relevantLocalTags,
  437. relevantLocalTagCount
  438. )) {
  439. m.sendCredentialsIfNeeded(RR,RR->node->now(),ztDest,_config.com,&(_config.capabilities[c]),relevantLocalTags,relevantLocalTagCount);
  440. return true;
  441. }
  442. }
  443. return false;
  444. }
  445. bool Network::filterIncomingPacket(
  446. const SharedPtr<Peer> &sourcePeer,
  447. const Address &ztDest,
  448. const MAC &macSource,
  449. const MAC &macDest,
  450. const uint8_t *frameData,
  451. const unsigned int frameLen,
  452. const unsigned int etherType,
  453. const unsigned int vlanId)
  454. {
  455. }
  456. bool Network::subscribedToMulticastGroup(const MulticastGroup &mg,bool includeBridgedGroups) const
  457. {
  458. Mutex::Lock _l(_lock);
  459. if (std::binary_search(_myMulticastGroups.begin(),_myMulticastGroups.end(),mg))
  460. return true;
  461. else if (includeBridgedGroups)
  462. return _multicastGroupsBehindMe.contains(mg);
  463. else return false;
  464. }
  465. void Network::multicastSubscribe(const MulticastGroup &mg)
  466. {
  467. {
  468. Mutex::Lock _l(_lock);
  469. if (std::binary_search(_myMulticastGroups.begin(),_myMulticastGroups.end(),mg))
  470. return;
  471. _myMulticastGroups.push_back(mg);
  472. std::sort(_myMulticastGroups.begin(),_myMulticastGroups.end());
  473. }
  474. _announceMulticastGroups();
  475. }
  476. void Network::multicastUnsubscribe(const MulticastGroup &mg)
  477. {
  478. Mutex::Lock _l(_lock);
  479. std::vector<MulticastGroup> nmg;
  480. for(std::vector<MulticastGroup>::const_iterator i(_myMulticastGroups.begin());i!=_myMulticastGroups.end();++i) {
  481. if (*i != mg)
  482. nmg.push_back(*i);
  483. }
  484. if (nmg.size() != _myMulticastGroups.size())
  485. _myMulticastGroups.swap(nmg);
  486. }
  487. bool Network::tryAnnounceMulticastGroupsTo(const SharedPtr<Peer> &peer)
  488. {
  489. Mutex::Lock _l(_lock);
  490. if (
  491. (_isAllowed(peer)) ||
  492. (peer->address() == this->controller()) ||
  493. (RR->topology->isUpstream(peer->identity()))
  494. ) {
  495. _announceMulticastGroupsTo(peer,_allMulticastGroups());
  496. return true;
  497. }
  498. return false;
  499. }
  500. bool Network::applyConfiguration(const NetworkConfig &conf)
  501. {
  502. if (_destroyed) // sanity check
  503. return false;
  504. try {
  505. if ((conf.networkId == _id)&&(conf.issuedTo == RR->identity.address())) {
  506. ZT_VirtualNetworkConfig ctmp;
  507. bool portInitialized;
  508. {
  509. Mutex::Lock _l(_lock);
  510. _config = conf;
  511. _lastConfigUpdate = RR->node->now();
  512. _netconfFailure = NETCONF_FAILURE_NONE;
  513. _externalConfig(&ctmp);
  514. portInitialized = _portInitialized;
  515. _portInitialized = true;
  516. }
  517. _portError = RR->node->configureVirtualNetworkPort(_id,&_uPtr,(portInitialized) ? ZT_VIRTUAL_NETWORK_CONFIG_OPERATION_CONFIG_UPDATE : ZT_VIRTUAL_NETWORK_CONFIG_OPERATION_UP,&ctmp);
  518. return true;
  519. } else {
  520. TRACE("ignored invalid configuration for network %.16llx (configuration contains mismatched network ID or issued-to address)",(unsigned long long)_id);
  521. }
  522. } catch (std::exception &exc) {
  523. TRACE("ignored invalid configuration for network %.16llx (%s)",(unsigned long long)_id,exc.what());
  524. } catch ( ... ) {
  525. TRACE("ignored invalid configuration for network %.16llx (unknown exception)",(unsigned long long)_id);
  526. }
  527. return false;
  528. }
  529. int Network::setConfiguration(const NetworkConfig &nconf,bool saveToDisk)
  530. {
  531. try {
  532. {
  533. Mutex::Lock _l(_lock);
  534. if (_config == nconf)
  535. return 1; // OK config, but duplicate of what we already have
  536. }
  537. if (applyConfiguration(nconf)) {
  538. if (saveToDisk) {
  539. char n[64];
  540. Utils::snprintf(n,sizeof(n),"networks.d/%.16llx.conf",_id);
  541. Dictionary<ZT_NETWORKCONFIG_DICT_CAPACITY> d;
  542. if (nconf.toDictionary(d,false))
  543. RR->node->dataStorePut(n,(const void *)d.data(),d.sizeBytes(),true);
  544. }
  545. return 2; // OK and configuration has changed
  546. }
  547. } catch ( ... ) {
  548. TRACE("ignored invalid configuration for network %.16llx",(unsigned long long)_id);
  549. }
  550. return 0;
  551. }
  552. void Network::requestConfiguration()
  553. {
  554. if (_id == ZT_TEST_NETWORK_ID) // pseudo-network-ID, uses locally generated static config
  555. return;
  556. Dictionary<ZT_NETWORKCONFIG_DICT_CAPACITY> rmd;
  557. rmd.add(ZT_NETWORKCONFIG_REQUEST_METADATA_KEY_VERSION,(uint64_t)ZT_NETWORKCONFIG_VERSION);
  558. rmd.add(ZT_NETWORKCONFIG_REQUEST_METADATA_KEY_PROTOCOL_VERSION,(uint64_t)ZT_PROTO_VERSION);
  559. rmd.add(ZT_NETWORKCONFIG_REQUEST_METADATA_KEY_NODE_MAJOR_VERSION,(uint64_t)ZEROTIER_ONE_VERSION_MAJOR);
  560. rmd.add(ZT_NETWORKCONFIG_REQUEST_METADATA_KEY_NODE_MINOR_VERSION,(uint64_t)ZEROTIER_ONE_VERSION_MINOR);
  561. rmd.add(ZT_NETWORKCONFIG_REQUEST_METADATA_KEY_NODE_REVISION,(uint64_t)ZEROTIER_ONE_VERSION_REVISION);
  562. rmd.add(ZT_NETWORKCONFIG_REQUEST_METADATA_KEY_MAX_NETWORK_RULES,(uint64_t)ZT_MAX_NETWORK_RULES);
  563. rmd.add(ZT_NETWORKCONFIG_REQUEST_METADATA_KEY_MAX_CAPABILITY_RULES,(uint64_t)ZT_MAX_CAPABILITY_RULES);
  564. if (controller() == RR->identity.address()) {
  565. if (RR->localNetworkController) {
  566. NetworkConfig nconf;
  567. switch(RR->localNetworkController->doNetworkConfigRequest(InetAddress(),RR->identity,RR->identity,_id,rmd,nconf)) {
  568. case NetworkController::NETCONF_QUERY_OK:
  569. this->setConfiguration(nconf,true);
  570. return;
  571. case NetworkController::NETCONF_QUERY_OBJECT_NOT_FOUND:
  572. this->setNotFound();
  573. return;
  574. case NetworkController::NETCONF_QUERY_ACCESS_DENIED:
  575. this->setAccessDenied();
  576. return;
  577. default:
  578. return;
  579. }
  580. } else {
  581. this->setNotFound();
  582. return;
  583. }
  584. }
  585. TRACE("requesting netconf for network %.16llx from controller %s",(unsigned long long)_id,controller().toString().c_str());
  586. Packet outp(controller(),RR->identity.address(),Packet::VERB_NETWORK_CONFIG_REQUEST);
  587. outp.append((uint64_t)_id);
  588. const unsigned int rmdSize = rmd.sizeBytes();
  589. outp.append((uint16_t)rmdSize);
  590. outp.append((const void *)rmd.data(),rmdSize);
  591. outp.append((_config) ? (uint64_t)_config.revision : (uint64_t)0);
  592. outp.compress();
  593. RR->sw->send(outp,true,0);
  594. }
  595. void Network::clean()
  596. {
  597. const uint64_t now = RR->node->now();
  598. Mutex::Lock _l(_lock);
  599. if (_destroyed)
  600. return;
  601. {
  602. Hashtable< MulticastGroup,uint64_t >::Iterator i(_multicastGroupsBehindMe);
  603. MulticastGroup *mg = (MulticastGroup *)0;
  604. uint64_t *ts = (uint64_t *)0;
  605. while (i.next(mg,ts)) {
  606. if ((now - *ts) > (ZT_MULTICAST_LIKE_EXPIRE * 2))
  607. _multicastGroupsBehindMe.erase(*mg);
  608. }
  609. }
  610. {
  611. Address *a = (Address *)0;
  612. Membership *m = (Membership *)0;
  613. Hashtable<Address,Membership>::Iterator i(_memberships);
  614. while (i.next(a,m)) {
  615. if ((now - m->clean(now)) > ZT_MEMBERSHIP_EXPIRATION_TIME)
  616. _memberships.erase(*a);
  617. }
  618. }
  619. }
  620. void Network::learnBridgeRoute(const MAC &mac,const Address &addr)
  621. {
  622. Mutex::Lock _l(_lock);
  623. _remoteBridgeRoutes[mac] = addr;
  624. // Anti-DOS circuit breaker to prevent nodes from spamming us with absurd numbers of bridge routes
  625. while (_remoteBridgeRoutes.size() > ZT_MAX_BRIDGE_ROUTES) {
  626. Hashtable< Address,unsigned long > counts;
  627. Address maxAddr;
  628. unsigned long maxCount = 0;
  629. MAC *m = (MAC *)0;
  630. Address *a = (Address *)0;
  631. // Find the address responsible for the most entries
  632. {
  633. Hashtable<MAC,Address>::Iterator i(_remoteBridgeRoutes);
  634. while (i.next(m,a)) {
  635. const unsigned long c = ++counts[*a];
  636. if (c > maxCount) {
  637. maxCount = c;
  638. maxAddr = *a;
  639. }
  640. }
  641. }
  642. // Kill this address from our table, since it's most likely spamming us
  643. {
  644. Hashtable<MAC,Address>::Iterator i(_remoteBridgeRoutes);
  645. while (i.next(m,a)) {
  646. if (*a == maxAddr)
  647. _remoteBridgeRoutes.erase(*m);
  648. }
  649. }
  650. }
  651. }
  652. void Network::learnBridgedMulticastGroup(const MulticastGroup &mg,uint64_t now)
  653. {
  654. Mutex::Lock _l(_lock);
  655. const unsigned long tmp = (unsigned long)_multicastGroupsBehindMe.size();
  656. _multicastGroupsBehindMe.set(mg,now);
  657. if (tmp != _multicastGroupsBehindMe.size())
  658. _announceMulticastGroups();
  659. }
  660. void Network::destroy()
  661. {
  662. Mutex::Lock _l(_lock);
  663. _destroyed = true;
  664. }
  665. ZT_VirtualNetworkStatus Network::_status() const
  666. {
  667. // assumes _lock is locked
  668. if (_portError)
  669. return ZT_NETWORK_STATUS_PORT_ERROR;
  670. switch(_netconfFailure) {
  671. case NETCONF_FAILURE_ACCESS_DENIED:
  672. return ZT_NETWORK_STATUS_ACCESS_DENIED;
  673. case NETCONF_FAILURE_NOT_FOUND:
  674. return ZT_NETWORK_STATUS_NOT_FOUND;
  675. case NETCONF_FAILURE_NONE:
  676. return ((_config) ? ZT_NETWORK_STATUS_OK : ZT_NETWORK_STATUS_REQUESTING_CONFIGURATION);
  677. default:
  678. return ZT_NETWORK_STATUS_PORT_ERROR;
  679. }
  680. }
  681. void Network::_externalConfig(ZT_VirtualNetworkConfig *ec) const
  682. {
  683. // assumes _lock is locked
  684. ec->nwid = _id;
  685. ec->mac = _mac.toInt();
  686. if (_config)
  687. Utils::scopy(ec->name,sizeof(ec->name),_config.name);
  688. else ec->name[0] = (char)0;
  689. ec->status = _status();
  690. ec->type = (_config) ? (_config.isPrivate() ? ZT_NETWORK_TYPE_PRIVATE : ZT_NETWORK_TYPE_PUBLIC) : ZT_NETWORK_TYPE_PRIVATE;
  691. ec->mtu = ZT_IF_MTU;
  692. ec->dhcp = 0;
  693. std::vector<Address> ab(_config.activeBridges());
  694. ec->bridge = ((_config.allowPassiveBridging())||(std::find(ab.begin(),ab.end(),RR->identity.address()) != ab.end())) ? 1 : 0;
  695. ec->broadcastEnabled = (_config) ? (_config.enableBroadcast() ? 1 : 0) : 0;
  696. ec->portError = _portError;
  697. ec->netconfRevision = (_config) ? (unsigned long)_config.revision : 0;
  698. ec->assignedAddressCount = 0;
  699. for(unsigned int i=0;i<ZT_MAX_ZT_ASSIGNED_ADDRESSES;++i) {
  700. if (i < _config.staticIpCount) {
  701. memcpy(&(ec->assignedAddresses[i]),&(_config.staticIps[i]),sizeof(struct sockaddr_storage));
  702. ++ec->assignedAddressCount;
  703. } else {
  704. memset(&(ec->assignedAddresses[i]),0,sizeof(struct sockaddr_storage));
  705. }
  706. }
  707. ec->routeCount = 0;
  708. for(unsigned int i=0;i<ZT_MAX_NETWORK_ROUTES;++i) {
  709. if (i < _config.routeCount) {
  710. memcpy(&(ec->routes[i]),&(_config.routes[i]),sizeof(ZT_VirtualNetworkRoute));
  711. ++ec->routeCount;
  712. } else {
  713. memset(&(ec->routes[i]),0,sizeof(ZT_VirtualNetworkRoute));
  714. }
  715. }
  716. }
  717. bool Network::_isAllowed(const SharedPtr<Peer> &peer) const
  718. {
  719. // Assumes _lock is locked
  720. try {
  721. if (_config) {
  722. if (_config.isPublic()) {
  723. return true;
  724. } else {
  725. LockingPtr<Membership> m(peer->membership(_id,false));
  726. if (m) {
  727. return _config.com.agreesWith(m->com());
  728. }
  729. }
  730. }
  731. } catch ( ... ) {
  732. TRACE("isAllowed() check failed for peer %s: unexpected exception: unexpected exception",peer->address().toString().c_str());
  733. }
  734. return false;
  735. }
  736. class _MulticastAnnounceAll
  737. {
  738. public:
  739. _MulticastAnnounceAll(const RuntimeEnvironment *renv,Network *nw) :
  740. _now(renv->node->now()),
  741. _controller(nw->controller()),
  742. _network(nw),
  743. _anchors(nw->config().anchors()),
  744. _upstreamAddresses(renv->topology->upstreamAddresses())
  745. {}
  746. inline void operator()(Topology &t,const SharedPtr<Peer> &p)
  747. {
  748. if ( (_network->_isAllowed(p)) || // FIXME: this causes multicast LIKEs for public networks to get spammed, which isn't terrible but is a bit stupid
  749. (p->address() == _controller) ||
  750. (std::find(_upstreamAddresses.begin(),_upstreamAddresses.end(),p->address()) != _upstreamAddresses.end()) ||
  751. (std::find(_anchors.begin(),_anchors.end(),p->address()) != _anchors.end()) ) {
  752. peers.push_back(p);
  753. }
  754. }
  755. std::vector< SharedPtr<Peer> > peers;
  756. private:
  757. const uint64_t _now;
  758. const Address _controller;
  759. Network *const _network;
  760. const std::vector<Address> _anchors;
  761. const std::vector<Address> _upstreamAddresses;
  762. };
  763. void Network::_announceMulticastGroups()
  764. {
  765. // Assumes _lock is locked
  766. std::vector<MulticastGroup> allMulticastGroups(_allMulticastGroups());
  767. _MulticastAnnounceAll gpfunc(RR,this);
  768. RR->topology->eachPeer<_MulticastAnnounceAll &>(gpfunc);
  769. for(std::vector< SharedPtr<Peer> >::const_iterator i(gpfunc.peers.begin());i!=gpfunc.peers.end();++i)
  770. _announceMulticastGroupsTo(*i,allMulticastGroups);
  771. }
  772. void Network::_announceMulticastGroupsTo(const SharedPtr<Peer> &peer,const std::vector<MulticastGroup> &allMulticastGroups) const
  773. {
  774. // Assumes _lock is locked
  775. // Anyone we announce multicast groups to will need our COM to authenticate GATHER requests.
  776. {
  777. LockingPtr<Membership> m(peer->membership(_id,false));
  778. if (m) m->sendCredentialsIfNeeded(RR,RR->node->now(),*peer,_config);
  779. }
  780. Packet outp(peer->address(),RR->identity.address(),Packet::VERB_MULTICAST_LIKE);
  781. for(std::vector<MulticastGroup>::const_iterator mg(allMulticastGroups.begin());mg!=allMulticastGroups.end();++mg) {
  782. if ((outp.size() + 24) >= ZT_PROTO_MAX_PACKET_LENGTH) {
  783. outp.compress();
  784. RR->sw->send(outp,true,0);
  785. outp.reset(peer->address(),RR->identity.address(),Packet::VERB_MULTICAST_LIKE);
  786. }
  787. // network ID, MAC, ADI
  788. outp.append((uint64_t)_id);
  789. mg->mac().appendTo(outp);
  790. outp.append((uint32_t)mg->adi());
  791. }
  792. if (outp.size() > ZT_PROTO_MIN_PACKET_LENGTH) {
  793. outp.compress();
  794. RR->sw->send(outp,true,0);
  795. }
  796. }
  797. std::vector<MulticastGroup> Network::_allMulticastGroups() const
  798. {
  799. // Assumes _lock is locked
  800. std::vector<MulticastGroup> mgs;
  801. mgs.reserve(_myMulticastGroups.size() + _multicastGroupsBehindMe.size() + 1);
  802. mgs.insert(mgs.end(),_myMulticastGroups.begin(),_myMulticastGroups.end());
  803. _multicastGroupsBehindMe.appendKeys(mgs);
  804. if ((_config)&&(_config.enableBroadcast()))
  805. mgs.push_back(Network::BROADCAST);
  806. std::sort(mgs.begin(),mgs.end());
  807. mgs.erase(std::unique(mgs.begin(),mgs.end()),mgs.end());
  808. return mgs;
  809. }
  810. } // namespace ZeroTier