Network.cpp 52 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497
  1. /*
  2. * Copyright (c)2013-2020 ZeroTier, Inc.
  3. *
  4. * Use of this software is governed by the Business Source License included
  5. * in the LICENSE.TXT file in the project's root directory.
  6. *
  7. * Change Date: 2024-01-01
  8. *
  9. * On the date above, in accordance with the Business Source License, use
  10. * of this software will be governed by version 2.0 of the Apache License.
  11. */
  12. /****/
  13. #include <cstring>
  14. #include <cstdlib>
  15. #include "Constants.hpp"
  16. #include "Network.hpp"
  17. #include "RuntimeEnvironment.hpp"
  18. #include "MAC.hpp"
  19. #include "Address.hpp"
  20. #include "InetAddress.hpp"
  21. #include "Switch.hpp"
  22. #include "NetworkController.hpp"
  23. #include "Peer.hpp"
  24. #include "Trace.hpp"
  25. #include "ScopedPtr.hpp"
  26. #include "Buf.hpp"
  27. #include <set>
  28. namespace ZeroTier {
  29. namespace {
  30. // Returns true if packet appears valid; pos and proto will be set
  31. bool _ipv6GetPayload(const uint8_t *frameData,unsigned int frameLen,unsigned int &pos,unsigned int &proto)
  32. {
  33. if (frameLen < 40)
  34. return false;
  35. pos = 40;
  36. proto = frameData[6];
  37. while (pos <= frameLen) {
  38. switch(proto) {
  39. case 0: // hop-by-hop options
  40. case 43: // routing
  41. case 60: // destination options
  42. case 135: // mobility options
  43. if ((pos + 8) > frameLen)
  44. return false; // invalid!
  45. proto = frameData[pos];
  46. pos += ((unsigned int)frameData[pos + 1] * 8) + 8;
  47. break;
  48. //case 44: // fragment -- we currently can't parse these and they are deprecated in IPv6 anyway
  49. //case 50:
  50. //case 51: // IPSec ESP and AH -- we have to stop here since this is encrypted stuff
  51. default:
  52. return true;
  53. }
  54. }
  55. return false; // overflow == invalid
  56. }
  57. enum _doZtFilterResult
  58. {
  59. DOZTFILTER_NO_MATCH,
  60. DOZTFILTER_DROP,
  61. DOZTFILTER_REDIRECT,
  62. DOZTFILTER_ACCEPT,
  63. DOZTFILTER_SUPER_ACCEPT
  64. };
  65. _doZtFilterResult _doZtFilter(
  66. const RuntimeEnvironment *RR,
  67. Trace::RuleResultLog &rrl,
  68. const NetworkConfig &nconf,
  69. const Membership *membership, // can be NULL
  70. const bool inbound,
  71. const Address &ztSource,
  72. Address &ztDest, // MUTABLE -- is changed on REDIRECT actions
  73. const MAC &macSource,
  74. const MAC &macDest,
  75. const uint8_t *const frameData,
  76. const unsigned int frameLen,
  77. const unsigned int etherType,
  78. const unsigned int vlanId,
  79. const ZT_VirtualNetworkRule *rules, // cannot be NULL
  80. const unsigned int ruleCount,
  81. Address &cc, // MUTABLE -- set to TEE destination if TEE action is taken or left alone otherwise
  82. unsigned int &ccLength, // MUTABLE -- set to length of packet payload to TEE
  83. bool &ccWatch, // MUTABLE -- set to true for WATCH target as opposed to normal TEE
  84. uint8_t &qosBucket) // MUTABLE -- set to the value of the argument provided to PRIORITY
  85. {
  86. // Set to true if we are a TEE/REDIRECT/WATCH target
  87. bool superAccept = false;
  88. // The default match state for each set of entries starts as 'true' since an
  89. // ACTION with no MATCH entries preceding it is always taken.
  90. uint8_t thisSetMatches = 1;
  91. rrl.clear();
  92. for(unsigned int rn=0;rn<ruleCount;++rn) {
  93. const ZT_VirtualNetworkRuleType rt = (ZT_VirtualNetworkRuleType)(rules[rn].t & 0x3fU);
  94. // First check if this is an ACTION
  95. if ((unsigned int)rt <= (unsigned int)ZT_NETWORK_RULE_ACTION__MAX_ID) {
  96. if (thisSetMatches) {
  97. switch(rt) {
  98. case ZT_NETWORK_RULE_ACTION_PRIORITY:
  99. qosBucket = (rules[rn].v.qosBucket >= 0 && rules[rn].v.qosBucket <= 8) ? rules[rn].v.qosBucket : 4; // 4 = default bucket (no priority)
  100. return DOZTFILTER_ACCEPT;
  101. case ZT_NETWORK_RULE_ACTION_DROP:
  102. return DOZTFILTER_DROP;
  103. case ZT_NETWORK_RULE_ACTION_ACCEPT:
  104. return (superAccept ? DOZTFILTER_SUPER_ACCEPT : DOZTFILTER_ACCEPT); // match, accept packet
  105. // These are initially handled together since preliminary logic is common
  106. case ZT_NETWORK_RULE_ACTION_TEE:
  107. case ZT_NETWORK_RULE_ACTION_WATCH:
  108. case ZT_NETWORK_RULE_ACTION_REDIRECT: {
  109. const Address fwdAddr(rules[rn].v.fwd.address);
  110. if (fwdAddr == ztSource) {
  111. // Skip as no-op since source is target
  112. } else if (fwdAddr == RR->identity.address()) {
  113. if (inbound) {
  114. return DOZTFILTER_SUPER_ACCEPT;
  115. } else {
  116. }
  117. } else if (fwdAddr == ztDest) {
  118. } else {
  119. if (rt == ZT_NETWORK_RULE_ACTION_REDIRECT) {
  120. ztDest = fwdAddr;
  121. return DOZTFILTER_REDIRECT;
  122. } else {
  123. cc = fwdAddr;
  124. ccLength = (rules[rn].v.fwd.length != 0) ? ((frameLen < (unsigned int)rules[rn].v.fwd.length) ? frameLen : (unsigned int)rules[rn].v.fwd.length) : frameLen;
  125. ccWatch = (rt == ZT_NETWORK_RULE_ACTION_WATCH);
  126. }
  127. }
  128. } continue;
  129. case ZT_NETWORK_RULE_ACTION_BREAK:
  130. return DOZTFILTER_NO_MATCH;
  131. // Unrecognized ACTIONs are ignored as no-ops
  132. default:
  133. continue;
  134. }
  135. } else {
  136. // If this is an incoming packet and we are a TEE or REDIRECT target, we should
  137. // super-accept if we accept at all. This will cause us to accept redirected or
  138. // tee'd packets in spite of MAC and ZT addressing checks.
  139. if (inbound) {
  140. switch(rt) {
  141. case ZT_NETWORK_RULE_ACTION_TEE:
  142. case ZT_NETWORK_RULE_ACTION_WATCH:
  143. case ZT_NETWORK_RULE_ACTION_REDIRECT:
  144. if (RR->identity.address() == rules[rn].v.fwd.address)
  145. superAccept = true;
  146. break;
  147. default:
  148. break;
  149. }
  150. }
  151. thisSetMatches = 1; // reset to default true for next batch of entries
  152. continue;
  153. }
  154. }
  155. // Circuit breaker: no need to evaluate an AND if the set's match state
  156. // is currently false since anything AND false is false.
  157. if ((!thisSetMatches)&&(!(rules[rn].t & 0x40U))) {
  158. rrl.logSkipped(rn,thisSetMatches);
  159. continue;
  160. }
  161. // If this was not an ACTION evaluate next MATCH and update thisSetMatches with (AND [result])
  162. uint8_t thisRuleMatches = 0;
  163. uint64_t ownershipVerificationMask = 1; // this magic value means it hasn't been computed yet -- this is done lazily the first time it's needed
  164. switch(rt) {
  165. case ZT_NETWORK_RULE_MATCH_SOURCE_ZEROTIER_ADDRESS:
  166. thisRuleMatches = (uint8_t)(rules[rn].v.zt == ztSource.toInt());
  167. break;
  168. case ZT_NETWORK_RULE_MATCH_DEST_ZEROTIER_ADDRESS:
  169. thisRuleMatches = (uint8_t)(rules[rn].v.zt == ztDest.toInt());
  170. break;
  171. case ZT_NETWORK_RULE_MATCH_VLAN_ID:
  172. thisRuleMatches = (uint8_t)(rules[rn].v.vlanId == (uint16_t)vlanId);
  173. break;
  174. case ZT_NETWORK_RULE_MATCH_VLAN_PCP:
  175. // NOT SUPPORTED YET
  176. thisRuleMatches = (uint8_t)(rules[rn].v.vlanPcp == 0);
  177. break;
  178. case ZT_NETWORK_RULE_MATCH_VLAN_DEI:
  179. // NOT SUPPORTED YET
  180. thisRuleMatches = (uint8_t)(rules[rn].v.vlanDei == 0);
  181. break;
  182. case ZT_NETWORK_RULE_MATCH_MAC_SOURCE:
  183. thisRuleMatches = (uint8_t)(MAC(rules[rn].v.mac) == macSource);
  184. break;
  185. case ZT_NETWORK_RULE_MATCH_MAC_DEST:
  186. thisRuleMatches = (uint8_t)(MAC(rules[rn].v.mac) == macDest);
  187. break;
  188. case ZT_NETWORK_RULE_MATCH_IPV4_SOURCE:
  189. if ((etherType == ZT_ETHERTYPE_IPV4)&&(frameLen >= 20)) {
  190. 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)));
  191. } else {
  192. thisRuleMatches = 0;
  193. }
  194. break;
  195. case ZT_NETWORK_RULE_MATCH_IPV4_DEST:
  196. if ((etherType == ZT_ETHERTYPE_IPV4)&&(frameLen >= 20)) {
  197. 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)));
  198. } else {
  199. thisRuleMatches = 0;
  200. }
  201. break;
  202. case ZT_NETWORK_RULE_MATCH_IPV6_SOURCE:
  203. if ((etherType == ZT_ETHERTYPE_IPV6)&&(frameLen >= 40)) {
  204. 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)));
  205. } else {
  206. thisRuleMatches = 0;
  207. }
  208. break;
  209. case ZT_NETWORK_RULE_MATCH_IPV6_DEST:
  210. if ((etherType == ZT_ETHERTYPE_IPV6)&&(frameLen >= 40)) {
  211. 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)));
  212. } else {
  213. thisRuleMatches = 0;
  214. }
  215. break;
  216. case ZT_NETWORK_RULE_MATCH_IP_TOS:
  217. if ((etherType == ZT_ETHERTYPE_IPV4)&&(frameLen >= 20)) {
  218. const uint8_t tosMasked = frameData[1] & rules[rn].v.ipTos.mask;
  219. thisRuleMatches = (uint8_t)((tosMasked >= rules[rn].v.ipTos.value[0])&&(tosMasked <= rules[rn].v.ipTos.value[1]));
  220. } else if ((etherType == ZT_ETHERTYPE_IPV6)&&(frameLen >= 40)) {
  221. const uint8_t tosMasked = (((frameData[0] << 4U) & 0xf0U) | ((frameData[1] >> 4U) & 0x0fU)) & rules[rn].v.ipTos.mask;
  222. thisRuleMatches = (uint8_t)((tosMasked >= rules[rn].v.ipTos.value[0])&&(tosMasked <= rules[rn].v.ipTos.value[1]));
  223. } else {
  224. thisRuleMatches = 0;
  225. }
  226. break;
  227. case ZT_NETWORK_RULE_MATCH_IP_PROTOCOL:
  228. if ((etherType == ZT_ETHERTYPE_IPV4)&&(frameLen >= 20)) {
  229. thisRuleMatches = (uint8_t)(rules[rn].v.ipProtocol == frameData[9]);
  230. } else if (etherType == ZT_ETHERTYPE_IPV6) {
  231. unsigned int pos = 0,proto = 0;
  232. if (_ipv6GetPayload(frameData,frameLen,pos,proto)) {
  233. thisRuleMatches = (uint8_t)(rules[rn].v.ipProtocol == (uint8_t)proto);
  234. } else {
  235. thisRuleMatches = 0;
  236. }
  237. } else {
  238. thisRuleMatches = 0;
  239. }
  240. break;
  241. case ZT_NETWORK_RULE_MATCH_ETHERTYPE:
  242. thisRuleMatches = (uint8_t)(rules[rn].v.etherType == (uint16_t)etherType);
  243. break;
  244. case ZT_NETWORK_RULE_MATCH_ICMP:
  245. if ((etherType == ZT_ETHERTYPE_IPV4)&&(frameLen >= 20)) {
  246. if (frameData[9] == 0x01) { // IP protocol == ICMP
  247. const unsigned int ihl = (frameData[0] & 0xfU) * 4;
  248. if (frameLen >= (ihl + 2)) {
  249. if (rules[rn].v.icmp.type == frameData[ihl]) {
  250. if ((rules[rn].v.icmp.flags & 0x01) != 0) {
  251. thisRuleMatches = (uint8_t)(frameData[ihl+1] == rules[rn].v.icmp.code);
  252. } else {
  253. thisRuleMatches = 1;
  254. }
  255. } else {
  256. thisRuleMatches = 0;
  257. }
  258. } else {
  259. thisRuleMatches = 0;
  260. }
  261. } else {
  262. thisRuleMatches = 0;
  263. }
  264. } else if (etherType == ZT_ETHERTYPE_IPV6) {
  265. unsigned int pos = 0,proto = 0;
  266. if (_ipv6GetPayload(frameData,frameLen,pos,proto)) {
  267. if ((proto == 0x3a)&&(frameLen >= (pos+2))) {
  268. if (rules[rn].v.icmp.type == frameData[pos]) {
  269. if ((rules[rn].v.icmp.flags & 0x01) != 0) {
  270. thisRuleMatches = (uint8_t)(frameData[pos+1] == rules[rn].v.icmp.code);
  271. } else {
  272. thisRuleMatches = 1;
  273. }
  274. } else {
  275. thisRuleMatches = 0;
  276. }
  277. } else {
  278. thisRuleMatches = 0;
  279. }
  280. } else {
  281. thisRuleMatches = 0;
  282. }
  283. } else {
  284. thisRuleMatches = 0;
  285. }
  286. break;
  287. case ZT_NETWORK_RULE_MATCH_IP_SOURCE_PORT_RANGE:
  288. case ZT_NETWORK_RULE_MATCH_IP_DEST_PORT_RANGE:
  289. if ((etherType == ZT_ETHERTYPE_IPV4)&&(frameLen >= 20)) {
  290. const unsigned int headerLen = 4 * (frameData[0] & 0xfU);
  291. int p = -1;
  292. switch(frameData[9]) { // IP protocol number
  293. // All these start with 16-bit source and destination port in that order
  294. case 0x06: // TCP
  295. case 0x11: // UDP
  296. case 0x84: // SCTP
  297. case 0x88: // UDPLite
  298. if (frameLen > (headerLen + 4)) {
  299. unsigned int pos = headerLen + ((rt == ZT_NETWORK_RULE_MATCH_IP_DEST_PORT_RANGE) ? 2 : 0);
  300. p = (int)(frameData[pos++] << 8U);
  301. p |= (int)frameData[pos];
  302. }
  303. break;
  304. }
  305. thisRuleMatches = (p >= 0) ? (uint8_t)((p >= (int)rules[rn].v.port[0])&&(p <= (int)rules[rn].v.port[1])) : (uint8_t)0;
  306. } else if (etherType == ZT_ETHERTYPE_IPV6) {
  307. unsigned int pos = 0,proto = 0;
  308. if (_ipv6GetPayload(frameData,frameLen,pos,proto)) {
  309. int p = -1;
  310. switch(proto) { // IP protocol number
  311. // All these start with 16-bit source and destination port in that order
  312. case 0x06: // TCP
  313. case 0x11: // UDP
  314. case 0x84: // SCTP
  315. case 0x88: // UDPLite
  316. if (frameLen > (pos + 4)) {
  317. if (rt == ZT_NETWORK_RULE_MATCH_IP_DEST_PORT_RANGE) pos += 2;
  318. p = (int)(frameData[pos++] << 8U);
  319. p |= (int)frameData[pos];
  320. }
  321. break;
  322. }
  323. thisRuleMatches = (p > 0) ? (uint8_t)((p >= (int)rules[rn].v.port[0])&&(p <= (int)rules[rn].v.port[1])) : (uint8_t)0;
  324. } else {
  325. thisRuleMatches = 0;
  326. }
  327. } else {
  328. thisRuleMatches = 0;
  329. }
  330. break;
  331. case ZT_NETWORK_RULE_MATCH_CHARACTERISTICS: {
  332. uint64_t cf = (inbound) ? ZT_RULE_PACKET_CHARACTERISTICS_INBOUND : 0ULL;
  333. if (macDest.isMulticast()) cf |= ZT_RULE_PACKET_CHARACTERISTICS_MULTICAST;
  334. if (macDest.isBroadcast()) cf |= ZT_RULE_PACKET_CHARACTERISTICS_BROADCAST;
  335. if (ownershipVerificationMask == 1) {
  336. ownershipVerificationMask = 0;
  337. InetAddress src;
  338. if ((etherType == ZT_ETHERTYPE_IPV4)&&(frameLen >= 20)) {
  339. src.set((const void *)(frameData + 12),4,0);
  340. } else if ((etherType == ZT_ETHERTYPE_IPV6)&&(frameLen >= 40)) {
  341. // IPv6 NDP requires special handling, since the src and dest IPs in the packet are empty or link-local.
  342. if ( (frameLen >= (40 + 8 + 16)) && (frameData[6] == 0x3a) && ((frameData[40] == 0x87)||(frameData[40] == 0x88)) ) {
  343. if (frameData[40] == 0x87) {
  344. // Neighbor solicitations contain no reliable source address, so we implement a small
  345. // hack by considering them authenticated. Otherwise you would pretty much have to do
  346. // this manually in the rule set for IPv6 to work at all.
  347. ownershipVerificationMask |= ZT_RULE_PACKET_CHARACTERISTICS_SENDER_IP_AUTHENTICATED;
  348. } else {
  349. // Neighbor advertisements on the other hand can absolutely be authenticated.
  350. src.set((const void *)(frameData + 40 + 8),16,0);
  351. }
  352. } else {
  353. // Other IPv6 packets can be handled normally
  354. src.set((const void *)(frameData + 8),16,0);
  355. }
  356. } else if ((etherType == ZT_ETHERTYPE_ARP)&&(frameLen >= 28)) {
  357. src.set((const void *)(frameData + 14),4,0);
  358. }
  359. if (inbound) {
  360. if (membership) {
  361. if ((src)&&(membership->peerOwnsAddress<InetAddress>(nconf,src)))
  362. ownershipVerificationMask |= ZT_RULE_PACKET_CHARACTERISTICS_SENDER_IP_AUTHENTICATED;
  363. if (membership->peerOwnsAddress<MAC>(nconf,macSource))
  364. ownershipVerificationMask |= ZT_RULE_PACKET_CHARACTERISTICS_SENDER_MAC_AUTHENTICATED;
  365. }
  366. } else {
  367. for(unsigned int i=0;i<nconf.certificateOfOwnershipCount;++i) {
  368. if ((src)&&(nconf.certificatesOfOwnership[i].owns(src)))
  369. ownershipVerificationMask |= ZT_RULE_PACKET_CHARACTERISTICS_SENDER_IP_AUTHENTICATED;
  370. if (nconf.certificatesOfOwnership[i].owns(macSource))
  371. ownershipVerificationMask |= ZT_RULE_PACKET_CHARACTERISTICS_SENDER_MAC_AUTHENTICATED;
  372. }
  373. }
  374. }
  375. cf |= ownershipVerificationMask;
  376. if ((etherType == ZT_ETHERTYPE_IPV4)&&(frameLen >= 20)&&(frameData[9] == 0x06)) {
  377. const unsigned int headerLen = 4 * (frameData[0] & 0xfU);
  378. cf |= (uint64_t)frameData[headerLen + 13];
  379. cf |= (((uint64_t)(frameData[headerLen + 12] & 0x0fU)) << 8U);
  380. } else if (etherType == ZT_ETHERTYPE_IPV6) {
  381. unsigned int pos = 0,proto = 0;
  382. if (_ipv6GetPayload(frameData,frameLen,pos,proto)) {
  383. if ((proto == 0x06)&&(frameLen > (pos + 14))) {
  384. cf |= (uint64_t)frameData[pos + 13];
  385. cf |= (((uint64_t)(frameData[pos + 12] & 0x0fU)) << 8U);
  386. }
  387. }
  388. }
  389. thisRuleMatches = (uint8_t)((cf & rules[rn].v.characteristics) != 0);
  390. } break;
  391. case ZT_NETWORK_RULE_MATCH_FRAME_SIZE_RANGE:
  392. thisRuleMatches = (uint8_t)((frameLen >= (unsigned int)rules[rn].v.frameSize[0])&&(frameLen <= (unsigned int)rules[rn].v.frameSize[1]));
  393. break;
  394. case ZT_NETWORK_RULE_MATCH_RANDOM:
  395. thisRuleMatches = (uint8_t)((uint32_t)(Utils::random() & 0xffffffffULL) <= rules[rn].v.randomProbability);
  396. break;
  397. case ZT_NETWORK_RULE_MATCH_TAGS_DIFFERENCE:
  398. case ZT_NETWORK_RULE_MATCH_TAGS_BITWISE_AND:
  399. case ZT_NETWORK_RULE_MATCH_TAGS_BITWISE_OR:
  400. case ZT_NETWORK_RULE_MATCH_TAGS_BITWISE_XOR:
  401. case ZT_NETWORK_RULE_MATCH_TAGS_EQUAL: {
  402. const Tag *const localTag = std::lower_bound(&(nconf.tags[0]),&(nconf.tags[nconf.tagCount]),rules[rn].v.tag.id,Tag::IdComparePredicate());
  403. if ((localTag != &(nconf.tags[nconf.tagCount]))&&(localTag->id() == rules[rn].v.tag.id)) {
  404. const Tag *const remoteTag = ((membership) ? membership->getTag(nconf,rules[rn].v.tag.id) : (const Tag *)0);
  405. if (remoteTag) {
  406. const uint32_t ltv = localTag->value();
  407. const uint32_t rtv = remoteTag->value();
  408. if (rt == ZT_NETWORK_RULE_MATCH_TAGS_DIFFERENCE) {
  409. const uint32_t diff = (ltv > rtv) ? (ltv - rtv) : (rtv - ltv);
  410. thisRuleMatches = (uint8_t)(diff <= rules[rn].v.tag.value);
  411. } else if (rt == ZT_NETWORK_RULE_MATCH_TAGS_BITWISE_AND) {
  412. thisRuleMatches = (uint8_t)((ltv & rtv) == rules[rn].v.tag.value);
  413. } else if (rt == ZT_NETWORK_RULE_MATCH_TAGS_BITWISE_OR) {
  414. thisRuleMatches = (uint8_t)((ltv | rtv) == rules[rn].v.tag.value);
  415. } else if (rt == ZT_NETWORK_RULE_MATCH_TAGS_BITWISE_XOR) {
  416. thisRuleMatches = (uint8_t)((ltv ^ rtv) == rules[rn].v.tag.value);
  417. } else if (rt == ZT_NETWORK_RULE_MATCH_TAGS_EQUAL) {
  418. thisRuleMatches = (uint8_t)((ltv == rules[rn].v.tag.value)&&(rtv == rules[rn].v.tag.value));
  419. } else { // sanity check, can't really happen
  420. thisRuleMatches = 0;
  421. }
  422. } else {
  423. if ((inbound)&&(!superAccept)) {
  424. thisRuleMatches = 0;
  425. } else {
  426. // Outbound side is not strict since if we have to match both tags and
  427. // we are sending a first packet to a recipient, we probably do not know
  428. // about their tags yet. They will filter on inbound and we will filter
  429. // once we get their tag. If we are a tee/redirect target we are also
  430. // not strict since we likely do not have these tags.
  431. thisRuleMatches = 1;
  432. }
  433. }
  434. } else {
  435. thisRuleMatches = 0;
  436. }
  437. } break;
  438. case ZT_NETWORK_RULE_MATCH_TAG_SENDER:
  439. case ZT_NETWORK_RULE_MATCH_TAG_RECEIVER: {
  440. if (superAccept) {
  441. thisRuleMatches = 1;
  442. } else if ( ((rt == ZT_NETWORK_RULE_MATCH_TAG_SENDER)&&(inbound)) || ((rt == ZT_NETWORK_RULE_MATCH_TAG_RECEIVER)&&(!inbound)) ) {
  443. const Tag *const remoteTag = ((membership) ? membership->getTag(nconf,rules[rn].v.tag.id) : (const Tag *)0);
  444. if (remoteTag) {
  445. thisRuleMatches = (uint8_t)(remoteTag->value() == rules[rn].v.tag.value);
  446. } else {
  447. if (rt == ZT_NETWORK_RULE_MATCH_TAG_RECEIVER) {
  448. // If we are checking the receiver and this is an outbound packet, we
  449. // can't be strict since we may not yet know the receiver's tag.
  450. thisRuleMatches = 1;
  451. } else {
  452. thisRuleMatches = 0;
  453. }
  454. }
  455. } else { // sender and outbound or receiver and inbound
  456. const Tag *const localTag = std::lower_bound(&(nconf.tags[0]),&(nconf.tags[nconf.tagCount]),rules[rn].v.tag.id,Tag::IdComparePredicate());
  457. if ((localTag != &(nconf.tags[nconf.tagCount]))&&(localTag->id() == rules[rn].v.tag.id)) {
  458. thisRuleMatches = (uint8_t)(localTag->value() == rules[rn].v.tag.value);
  459. } else {
  460. thisRuleMatches = 0;
  461. }
  462. }
  463. } break;
  464. case ZT_NETWORK_RULE_MATCH_INTEGER_RANGE: {
  465. uint64_t integer = 0;
  466. const unsigned int bits = (rules[rn].v.intRange.format & 63U) + 1;
  467. const unsigned int bytes = ((bits + 8 - 1) / 8); // integer ceiling of division by 8
  468. if ((rules[rn].v.intRange.format & 0x80U) == 0) {
  469. // Big-endian
  470. unsigned int idx = rules[rn].v.intRange.idx + (8 - bytes);
  471. const unsigned int eof = idx + bytes;
  472. if (eof <= frameLen) {
  473. while (idx < eof) {
  474. integer <<= 8U;
  475. integer |= frameData[idx++];
  476. }
  477. }
  478. integer &= 0xffffffffffffffffULL >> (64 - bits);
  479. } else {
  480. // Little-endian
  481. unsigned int idx = rules[rn].v.intRange.idx;
  482. const unsigned int eof = idx + bytes;
  483. if (eof <= frameLen) {
  484. while (idx < eof) {
  485. integer >>= 8U;
  486. integer |= ((uint64_t)frameData[idx++]) << 56U;
  487. }
  488. }
  489. integer >>= (64 - bits);
  490. }
  491. thisRuleMatches = (uint8_t)((integer >= rules[rn].v.intRange.start)&&(integer <= (rules[rn].v.intRange.start + (uint64_t)rules[rn].v.intRange.end)));
  492. } break;
  493. // The result of an unsupported MATCH is configurable at the network
  494. // level via a flag.
  495. default:
  496. thisRuleMatches = (uint8_t)((nconf.flags & ZT_NETWORKCONFIG_FLAG_RULES_RESULT_OF_UNSUPPORTED_MATCH) != 0);
  497. break;
  498. }
  499. rrl.log(rn,thisRuleMatches,thisSetMatches);
  500. if ((rules[rn].t & 0x40U))
  501. thisSetMatches |= (thisRuleMatches ^ ((rules[rn].t >> 7U) & 1U));
  502. else thisSetMatches &= (thisRuleMatches ^ ((rules[rn].t >> 7U) & 1U));
  503. }
  504. return DOZTFILTER_NO_MATCH;
  505. }
  506. } // anonymous namespace
  507. const ZeroTier::MulticastGroup Network::BROADCAST(ZeroTier::MAC(0xffffffffffffULL),0);
  508. Network::Network(const RuntimeEnvironment *renv,void *tPtr,uint64_t nwid,void *uptr,const NetworkConfig *nconf) :
  509. RR(renv),
  510. _uPtr(uptr),
  511. _id(nwid),
  512. _mac(renv->identity.address(),nwid),
  513. _portInitialized(false),
  514. _lastConfigUpdate(0),
  515. _destroyed(false),
  516. _netconfFailure(NETCONF_FAILURE_NONE)
  517. {
  518. if (nconf) {
  519. this->setConfiguration(tPtr,*nconf,false);
  520. _lastConfigUpdate = 0; // still want to re-request since it's likely outdated
  521. } else {
  522. uint64_t tmp[2];
  523. tmp[0] = nwid; tmp[1] = 0;
  524. bool got = false;
  525. try {
  526. Dictionary dict;
  527. std::vector<uint8_t> nconfData(RR->node->stateObjectGet(tPtr,ZT_STATE_OBJECT_NETWORK_CONFIG,tmp));
  528. if (nconfData.size() > 2) {
  529. nconfData.push_back(0);
  530. if (dict.decode(nconfData.data(),(unsigned int)nconfData.size())) {
  531. try {
  532. ScopedPtr<NetworkConfig> nconf2(new NetworkConfig());
  533. if (nconf2->fromDictionary(dict)) {
  534. this->setConfiguration(tPtr,*nconf2,false);
  535. _lastConfigUpdate = 0; // still want to re-request an update since it's likely outdated
  536. got = true;
  537. }
  538. } catch (...) {}
  539. }
  540. }
  541. } catch ( ... ) {}
  542. if (!got)
  543. RR->node->stateObjectPut(tPtr,ZT_STATE_OBJECT_NETWORK_CONFIG,tmp,"\n",1);
  544. }
  545. if (!_portInitialized) {
  546. ZT_VirtualNetworkConfig ctmp;
  547. _externalConfig(&ctmp);
  548. RR->node->configureVirtualNetworkPort(tPtr,_id,&_uPtr,ZT_VIRTUAL_NETWORK_CONFIG_OPERATION_UP,&ctmp);
  549. _portInitialized = true;
  550. }
  551. }
  552. Network::~Network()
  553. {
  554. _memberships_l.lock();
  555. _config_l.lock();
  556. _config_l.unlock();
  557. _memberships_l.unlock();
  558. ZT_VirtualNetworkConfig ctmp;
  559. _externalConfig(&ctmp);
  560. if (_destroyed) {
  561. // This is done in Node::leave() so we can pass tPtr properly
  562. //RR->node->configureVirtualNetworkPort((void *)0,_id,&_uPtr,ZT_VIRTUAL_NETWORK_CONFIG_OPERATION_DESTROY,&ctmp);
  563. } else {
  564. RR->node->configureVirtualNetworkPort((void *)0,_id,&_uPtr,ZT_VIRTUAL_NETWORK_CONFIG_OPERATION_DOWN,&ctmp);
  565. }
  566. }
  567. bool Network::filterOutgoingPacket(
  568. void *tPtr,
  569. const bool noTee,
  570. const Address &ztSource,
  571. const Address &ztDest,
  572. const MAC &macSource,
  573. const MAC &macDest,
  574. const uint8_t *frameData,
  575. const unsigned int frameLen,
  576. const unsigned int etherType,
  577. const unsigned int vlanId,
  578. uint8_t &qosBucket)
  579. {
  580. Trace::RuleResultLog rrl,crrl;
  581. Address ztFinalDest(ztDest);
  582. int localCapabilityIndex = -1;
  583. int accept = 0;
  584. Address cc;
  585. unsigned int ccLength = 0;
  586. bool ccWatch = false;
  587. Mutex::Lock l1(_memberships_l);
  588. Mutex::Lock l2(_config_l);
  589. Membership *const membership = (ztDest) ? _memberships.get(ztDest) : (Membership *)0;
  590. switch(_doZtFilter(RR,rrl,_config,membership,false,ztSource,ztFinalDest,macSource,macDest,frameData,frameLen,etherType,vlanId,_config.rules,_config.ruleCount,cc,ccLength,ccWatch,qosBucket)) {
  591. case DOZTFILTER_NO_MATCH: {
  592. for(unsigned int c=0;c<_config.capabilityCount;++c) {
  593. ztFinalDest = ztDest; // sanity check, shouldn't be possible if there was no match
  594. Address cc2;
  595. unsigned int ccLength2 = 0;
  596. bool ccWatch2 = false;
  597. switch (_doZtFilter(RR,crrl,_config,membership,false,ztSource,ztFinalDest,macSource,macDest,frameData,frameLen,etherType,vlanId,_config.capabilities[c].rules(),_config.capabilities[c].ruleCount(),cc2,ccLength2,ccWatch2,qosBucket)) {
  598. case DOZTFILTER_NO_MATCH:
  599. case DOZTFILTER_DROP: // explicit DROP in a capability just terminates its evaluation and is an anti-pattern
  600. break;
  601. case DOZTFILTER_REDIRECT: // interpreted as ACCEPT but ztFinalDest will have been changed in _doZtFilter()
  602. case DOZTFILTER_ACCEPT:
  603. case DOZTFILTER_SUPER_ACCEPT: // no difference in behavior on outbound side in capabilities
  604. localCapabilityIndex = (int)c;
  605. accept = 1;
  606. if ((!noTee)&&(cc2)) {
  607. Packet outp(cc2,RR->identity.address(),Packet::VERB_EXT_FRAME);
  608. outp.append(_id);
  609. outp.append((uint8_t)(ccWatch2 ? 0x16 : 0x02));
  610. macDest.appendTo(outp);
  611. macSource.appendTo(outp);
  612. outp.append((uint16_t)etherType);
  613. outp.append(frameData,ccLength2);
  614. outp.compress();
  615. RR->sw->send(tPtr,outp,true);
  616. }
  617. break;
  618. }
  619. if (accept)
  620. break;
  621. }
  622. } break;
  623. case DOZTFILTER_DROP:
  624. RR->t->networkFilter(tPtr,_id,rrl.l,nullptr,0,0,ztSource,ztDest,macSource,macDest,(uint16_t)frameLen,frameData,(uint16_t)etherType,(uint16_t)vlanId,noTee,false,0);
  625. return false;
  626. case DOZTFILTER_REDIRECT: // interpreted as ACCEPT but ztFinalDest will have been changed in _doZtFilter()
  627. case DOZTFILTER_ACCEPT:
  628. accept = 1;
  629. break;
  630. case DOZTFILTER_SUPER_ACCEPT:
  631. accept = 2;
  632. break;
  633. }
  634. if (accept != 0) {
  635. if ((!noTee)&&(cc)) {
  636. Packet outp(cc,RR->identity.address(),Packet::VERB_EXT_FRAME);
  637. outp.append(_id);
  638. outp.append((uint8_t)(ccWatch ? 0x16 : 0x02));
  639. macDest.appendTo(outp);
  640. macSource.appendTo(outp);
  641. outp.append((uint16_t)etherType);
  642. outp.append(frameData,ccLength);
  643. outp.compress();
  644. RR->sw->send(tPtr,outp,true);
  645. }
  646. if ((ztDest != ztFinalDest)&&(ztFinalDest)) {
  647. Packet outp(ztFinalDest,RR->identity.address(),Packet::VERB_EXT_FRAME);
  648. outp.append(_id);
  649. outp.append((uint8_t)0x04);
  650. macDest.appendTo(outp);
  651. macSource.appendTo(outp);
  652. outp.append((uint16_t)etherType);
  653. outp.append(frameData,frameLen);
  654. outp.compress();
  655. RR->sw->send(tPtr,outp,true);
  656. // DROP locally since we redirected
  657. accept = 0;
  658. }
  659. }
  660. if (localCapabilityIndex >= 0) {
  661. const Capability &cap = _config.capabilities[localCapabilityIndex];
  662. RR->t->networkFilter(tPtr,_id,rrl.l,crrl.l,cap.id(),cap.timestamp(),ztSource,ztDest,macSource,macDest,(uint16_t)frameLen,frameData,(uint16_t)etherType,(uint16_t)vlanId,noTee,false,accept);
  663. } else {
  664. RR->t->networkFilter(tPtr,_id,rrl.l,nullptr,0,0,ztSource,ztDest,macSource,macDest,(uint16_t)frameLen,frameData,(uint16_t)etherType,(uint16_t)vlanId,noTee,false,accept);
  665. }
  666. return (accept != 0);
  667. }
  668. int Network::filterIncomingPacket(
  669. void *tPtr,
  670. const SharedPtr<Peer> &sourcePeer,
  671. const Address &ztDest,
  672. const MAC &macSource,
  673. const MAC &macDest,
  674. const uint8_t *frameData,
  675. const unsigned int frameLen,
  676. const unsigned int etherType,
  677. const unsigned int vlanId)
  678. {
  679. Address ztFinalDest(ztDest);
  680. Trace::RuleResultLog rrl,crrl;
  681. int accept = 0;
  682. Address cc;
  683. unsigned int ccLength = 0;
  684. bool ccWatch = false;
  685. const Capability *c = (Capability *)0;
  686. uint8_t qosBucket = 255; // For incoming packets this is a dummy value
  687. Mutex::Lock l1(_memberships_l);
  688. Mutex::Lock l2(_config_l);
  689. Membership &membership = _memberships[sourcePeer->address()];
  690. switch (_doZtFilter(RR,rrl,_config,&membership,true,sourcePeer->address(),ztFinalDest,macSource,macDest,frameData,frameLen,etherType,vlanId,_config.rules,_config.ruleCount,cc,ccLength,ccWatch,qosBucket)) {
  691. case DOZTFILTER_NO_MATCH: {
  692. Membership::CapabilityIterator mci(membership,_config);
  693. while ((c = mci.next())) {
  694. ztFinalDest = ztDest; // sanity check, should be unmodified if there was no match
  695. Address cc2;
  696. unsigned int ccLength2 = 0;
  697. bool ccWatch2 = false;
  698. switch(_doZtFilter(RR,crrl,_config,&membership,true,sourcePeer->address(),ztFinalDest,macSource,macDest,frameData,frameLen,etherType,vlanId,c->rules(),c->ruleCount(),cc2,ccLength2,ccWatch2,qosBucket)) {
  699. case DOZTFILTER_NO_MATCH:
  700. case DOZTFILTER_DROP: // explicit DROP in a capability just terminates its evaluation and is an anti-pattern
  701. break;
  702. case DOZTFILTER_REDIRECT: // interpreted as ACCEPT but ztDest will have been changed in _doZtFilter()
  703. case DOZTFILTER_ACCEPT:
  704. accept = 1; // ACCEPT
  705. break;
  706. case DOZTFILTER_SUPER_ACCEPT:
  707. accept = 2; // super-ACCEPT
  708. break;
  709. }
  710. if (accept) {
  711. if (cc2) {
  712. Packet outp(cc2,RR->identity.address(),Packet::VERB_EXT_FRAME);
  713. outp.append(_id);
  714. outp.append((uint8_t)(ccWatch2 ? 0x1c : 0x08));
  715. macDest.appendTo(outp);
  716. macSource.appendTo(outp);
  717. outp.append((uint16_t)etherType);
  718. outp.append(frameData,ccLength2);
  719. outp.compress();
  720. RR->sw->send(tPtr,outp,true);
  721. }
  722. break;
  723. }
  724. }
  725. } break;
  726. case DOZTFILTER_DROP:
  727. //if (_config.remoteTraceTarget)
  728. // RR->t->networkFilter(tPtr,*this,rrl,(Trace::RuleResultLog *)0,(Capability *)0,sourcePeer->address(),ztDest,macSource,macDest,frameData,frameLen,etherType,vlanId,false,true,0);
  729. return 0; // DROP
  730. case DOZTFILTER_REDIRECT: // interpreted as ACCEPT but ztFinalDest will have been changed in _doZtFilter()
  731. case DOZTFILTER_ACCEPT:
  732. accept = 1; // ACCEPT
  733. break;
  734. case DOZTFILTER_SUPER_ACCEPT:
  735. accept = 2; // super-ACCEPT
  736. break;
  737. }
  738. if (accept) {
  739. if (cc) {
  740. Packet outp(cc,RR->identity.address(),Packet::VERB_EXT_FRAME);
  741. outp.append(_id);
  742. outp.append((uint8_t)(ccWatch ? 0x1c : 0x08));
  743. macDest.appendTo(outp);
  744. macSource.appendTo(outp);
  745. outp.append((uint16_t)etherType);
  746. outp.append(frameData,ccLength);
  747. outp.compress();
  748. RR->sw->send(tPtr,outp,true);
  749. }
  750. if ((ztDest != ztFinalDest)&&(ztFinalDest)) {
  751. Packet outp(ztFinalDest,RR->identity.address(),Packet::VERB_EXT_FRAME);
  752. outp.append(_id);
  753. outp.append((uint8_t)0x0a);
  754. macDest.appendTo(outp);
  755. macSource.appendTo(outp);
  756. outp.append((uint16_t)etherType);
  757. outp.append(frameData,frameLen);
  758. outp.compress();
  759. RR->sw->send(tPtr,outp,true);
  760. //if (_config.remoteTraceTarget)
  761. // RR->t->networkFilter(tPtr,*this,rrl,(c) ? &crrl : (Trace::RuleResultLog *)0,c,sourcePeer->address(),ztDest,macSource,macDest,frameData,frameLen,etherType,vlanId,false,true,0);
  762. return 0; // DROP locally, since we redirected
  763. }
  764. }
  765. //if (_config.remoteTraceTarget)
  766. // RR->t->networkFilter(tPtr,*this,rrl,(c) ? &crrl : (Trace::RuleResultLog *)0,c,sourcePeer->address(),ztDest,macSource,macDest,frameData,frameLen,etherType,vlanId,false,true,accept);
  767. return accept;
  768. }
  769. void Network::multicastSubscribe(void *tPtr,const MulticastGroup &mg)
  770. {
  771. Mutex::Lock l(_myMulticastGroups_l);
  772. if (!std::binary_search(_myMulticastGroups.begin(),_myMulticastGroups.end(),mg)) {
  773. _myMulticastGroups.insert(std::upper_bound(_myMulticastGroups.begin(),_myMulticastGroups.end(),mg),mg);
  774. Mutex::Lock l2(_memberships_l);
  775. _announceMulticastGroups(tPtr,true);
  776. }
  777. }
  778. void Network::multicastUnsubscribe(const MulticastGroup &mg)
  779. {
  780. Mutex::Lock l(_myMulticastGroups_l);
  781. std::vector<MulticastGroup>::iterator i(std::lower_bound(_myMulticastGroups.begin(),_myMulticastGroups.end(),mg));
  782. if ( (i != _myMulticastGroups.end()) && (*i == mg) )
  783. _myMulticastGroups.erase(i);
  784. }
  785. uint64_t Network::handleConfigChunk(void *tPtr,uint64_t packetId,const Address &source,const Buf<> &chunk,int ptr,int size)
  786. {
  787. if (_destroyed)
  788. return 0;
  789. const unsigned int chunkPayloadStart = ptr;
  790. ptr += 8; // skip network ID, which is already obviously known
  791. const unsigned int chunkLen = chunk.rI16(ptr);
  792. const uint8_t *chunkData = chunk.rBnc(ptr,chunkLen);
  793. if (Buf<>::readOverflow(ptr,size))
  794. return 0;
  795. Mutex::Lock l1(_config_l);
  796. _IncomingConfigChunk *c = nullptr;
  797. uint64_t configUpdateId;
  798. int totalLength = 0,chunkIndex = 0;
  799. if (ptr < size) {
  800. // If there is more data after the chunk / dictionary, it means this is a new controller
  801. // that sends signed chunks. We still support really old controllers, but probably not forever.
  802. const bool fastPropagate = ((chunk.rI8(ptr) & Protocol::NETWORK_CONFIG_FLAG_FAST_PROPAGATE) != 0);
  803. configUpdateId = chunk.rI64(ptr);
  804. totalLength = chunk.rI32(ptr);
  805. chunkIndex = chunk.rI32(ptr);
  806. ++ptr; // skip unused signature type field
  807. const unsigned int signatureSize = chunk.rI16(ptr);
  808. const uint8_t *signature = chunk.rBnc(ptr,signatureSize);
  809. if ((Buf<>::readOverflow(ptr,size))||((chunkIndex + chunkLen) > totalLength)||(totalLength >= ZT_MAX_NETWORK_CONFIG_BYTES)||(signatureSize > ZT_SIGNATURE_BUFFER_SIZE)||(!signature))
  810. return 0;
  811. const unsigned int chunkPayloadSize = (unsigned int)ptr - chunkPayloadStart;
  812. // Find existing or new slot for this update and its chunk(s).
  813. for(int i=0;i<ZT_NETWORK_MAX_INCOMING_UPDATES;++i) {
  814. if (_incomingConfigChunks[i].updateId == configUpdateId) {
  815. c = &(_incomingConfigChunks[i]);
  816. if (c->chunks.find(chunkIndex) != c->chunks.end())
  817. return 0; // we already have this chunk!
  818. break;
  819. } else if ((!c)||(_incomingConfigChunks[i].touchCtr < c->touchCtr)) {
  820. c = &(_incomingConfigChunks[i]);
  821. }
  822. }
  823. if (!c) // sanity check; should not be possible
  824. return 0;
  825. // Verify this chunk's signature
  826. const SharedPtr<Peer> controllerPeer(RR->topology->get(tPtr,controller()));
  827. if ((!controllerPeer)||(!controllerPeer->identity().verify(chunk.data.bytes + chunkPayloadStart,chunkPayloadSize,signature,signatureSize)))
  828. return 0;
  829. // New properly verified chunks can be flooded "virally" through the network via an aggressive
  830. // exponential rumor mill algorithm.
  831. if (fastPropagate) {
  832. Mutex::Lock l2(_memberships_l);
  833. Address *a = nullptr;
  834. Membership *m = nullptr;
  835. Hashtable<Address,Membership>::Iterator i(_memberships);
  836. while (i.next(a,m)) {
  837. if ((*a != source)&&(*a != controller())) {
  838. ZT_GET_NEW_BUF(outp,Protocol::Header);
  839. outp->data.fields.packetId = Protocol::getPacketId();
  840. a->copyTo(outp->data.fields.destination);
  841. RR->identity.address().copyTo(outp->data.fields.source);
  842. outp->data.fields.flags = 0;
  843. outp->data.fields.verb = Protocol::VERB_NETWORK_CONFIG;
  844. int outl = sizeof(Protocol::Header);
  845. outp->wB(outl,chunk.data.bytes + chunkPayloadStart,chunkPayloadSize);
  846. if (Buf<>::writeOverflow(outl)) // sanity check... it fit before!
  847. break;
  848. RR->sw->send(tPtr,outp,true);
  849. }
  850. }
  851. }
  852. } else if ((source == controller())||(!source)) {
  853. // Legacy support for OK(NETWORK_CONFIG_REQUEST) from older controllers that don't sign chunks and don't
  854. // support multiple chunks. Since old controllers don't sign chunks we only accept the message if it comes
  855. // directly from the controller.
  856. configUpdateId = packetId;
  857. totalLength = (int)chunkLen;
  858. if (totalLength > ZT_MAX_NETWORK_CONFIG_BYTES)
  859. return 0;
  860. for(int i=0;i<ZT_NETWORK_MAX_INCOMING_UPDATES;++i) {
  861. if ((!c)||(_incomingConfigChunks[i].touchCtr < c->touchCtr))
  862. c = &(_incomingConfigChunks[i]);
  863. }
  864. } else {
  865. // Not signed, not from controller -> reject.
  866. return 0;
  867. }
  868. try {
  869. ++c->touchCtr;
  870. if (c->updateId != configUpdateId) {
  871. c->updateId = configUpdateId;
  872. c->chunks.clear();
  873. }
  874. c->chunks[chunkIndex].assign(chunkData,chunkData + chunkLen);
  875. int haveLength = 0;
  876. for(std::map< int,std::vector<uint8_t> >::const_iterator ch(c->chunks.begin());ch!=c->chunks.end();++ch)
  877. haveLength += (int)ch->second.size();
  878. if (haveLength > ZT_MAX_NETWORK_CONFIG_BYTES) {
  879. c->touchCtr = 0;
  880. c->updateId = 0;
  881. c->chunks.clear();
  882. return 0;
  883. }
  884. if (haveLength == totalLength) {
  885. std::vector<uint8_t> assembledConfig;
  886. for(std::map< int,std::vector<uint8_t> >::const_iterator ch(c->chunks.begin());ch!=c->chunks.end();++ch)
  887. assembledConfig.insert(assembledConfig.end(),ch->second.begin(),ch->second.end());
  888. Dictionary dict;
  889. if (dict.decode(assembledConfig.data(),(unsigned int)assembledConfig.size())) {
  890. ScopedPtr<NetworkConfig> nc(new NetworkConfig());
  891. if (nc->fromDictionary(dict)) {
  892. this->setConfiguration(tPtr,*nc,true);
  893. return configUpdateId;
  894. }
  895. }
  896. }
  897. } catch (...) {}
  898. return 0;
  899. }
  900. int Network::setConfiguration(void *tPtr,const NetworkConfig &nconf,bool saveToDisk)
  901. {
  902. if (_destroyed)
  903. return 0;
  904. // _lock is NOT locked when this is called
  905. try {
  906. if ((nconf.issuedTo != RR->identity.address())||(nconf.networkId != _id))
  907. return 0; // invalid config that is not for us or not for this network
  908. if (_config == nconf)
  909. return 1; // OK config, but duplicate of what we already have
  910. ZT_VirtualNetworkConfig ctmp;
  911. bool oldPortInitialized;
  912. { // do things that require lock here, but unlock before calling callbacks
  913. Mutex::Lock l1(_config_l);
  914. _config = nconf;
  915. _lastConfigUpdate = RR->node->now();
  916. _netconfFailure = NETCONF_FAILURE_NONE;
  917. oldPortInitialized = _portInitialized;
  918. _portInitialized = true;
  919. _externalConfig(&ctmp);
  920. }
  921. RR->node->configureVirtualNetworkPort(tPtr,_id,&_uPtr,(oldPortInitialized) ? ZT_VIRTUAL_NETWORK_CONFIG_OPERATION_CONFIG_UPDATE : ZT_VIRTUAL_NETWORK_CONFIG_OPERATION_UP,&ctmp);
  922. if (saveToDisk) {
  923. try {
  924. Dictionary d;
  925. if (nconf.toDictionary(d,false)) {
  926. uint64_t tmp[2];
  927. tmp[0] = _id; tmp[1] = 0;
  928. std::vector<uint8_t> d2;
  929. d.encode(d2);
  930. RR->node->stateObjectPut(tPtr,ZT_STATE_OBJECT_NETWORK_CONFIG,tmp,d2.data(),(unsigned int)d2.size());
  931. }
  932. } catch ( ... ) {}
  933. }
  934. return 2; // OK and configuration has changed
  935. } catch ( ... ) {} // ignore invalid configs
  936. return 0;
  937. }
  938. bool Network::gate(void *tPtr,const SharedPtr<Peer> &peer)
  939. {
  940. Mutex::Lock l(_memberships_l);
  941. try {
  942. if (_config) {
  943. Membership *m = _memberships.get(peer->address());
  944. if ( (_config.isPublic()) || ((m)&&(m->isAllowedOnNetwork(_config))) ) {
  945. if (!m)
  946. m = &(_memberships[peer->address()]);
  947. return true;
  948. }
  949. }
  950. } catch ( ... ) {}
  951. return false;
  952. }
  953. void Network::doPeriodicTasks(void *tPtr,const int64_t now)
  954. {
  955. if (_destroyed)
  956. return;
  957. if ((now - _lastConfigUpdate) >= ZT_NETWORK_AUTOCONF_DELAY)
  958. _requestConfiguration(tPtr);
  959. {
  960. Mutex::Lock l1(_memberships_l);
  961. {
  962. Address *a = nullptr;
  963. Membership *m = nullptr;
  964. Hashtable<Address,Membership>::Iterator i(_memberships);
  965. while (i.next(a,m))
  966. m->clean(now,_config);
  967. }
  968. {
  969. Mutex::Lock l2(_myMulticastGroups_l);
  970. // TODO
  971. /*
  972. Hashtable< MulticastGroup,uint64_t >::Iterator i(_multicastGroupsBehindMe);
  973. MulticastGroup *mg = (MulticastGroup *)0;
  974. uint64_t *ts = (uint64_t *)0;
  975. while (i.next(mg,ts)) {
  976. if ((now - *ts) > (ZT_MULTICAST_LIKE_EXPIRE * 2))
  977. _multicastGroupsBehindMe.erase(*mg);
  978. }
  979. _announceMulticastGroups(tPtr,false);
  980. */
  981. }
  982. }
  983. }
  984. void Network::learnBridgeRoute(const MAC &mac,const Address &addr)
  985. {
  986. Mutex::Lock _l(_remoteBridgeRoutes_l);
  987. _remoteBridgeRoutes[mac] = addr;
  988. // Anti-DOS circuit breaker to prevent nodes from spamming us with absurd numbers of bridge routes
  989. while (_remoteBridgeRoutes.size() > ZT_MAX_BRIDGE_ROUTES) {
  990. Hashtable< Address,unsigned long > counts;
  991. Address maxAddr;
  992. unsigned long maxCount = 0;
  993. MAC *m = nullptr;
  994. Address *a = nullptr;
  995. // Find the address responsible for the most entries
  996. {
  997. Hashtable<MAC,Address>::Iterator i(_remoteBridgeRoutes);
  998. while (i.next(m,a)) {
  999. const unsigned long c = ++counts[*a];
  1000. if (c > maxCount) {
  1001. maxCount = c;
  1002. maxAddr = *a;
  1003. }
  1004. }
  1005. }
  1006. // Kill this address from our table, since it's most likely spamming us
  1007. {
  1008. Hashtable<MAC,Address>::Iterator i(_remoteBridgeRoutes);
  1009. while (i.next(m,a)) {
  1010. if (*a == maxAddr)
  1011. _remoteBridgeRoutes.erase(*m);
  1012. }
  1013. }
  1014. }
  1015. }
  1016. Membership::AddCredentialResult Network::addCredential(void *tPtr,const Identity &sourcePeerIdentity,const CertificateOfMembership &com)
  1017. {
  1018. if (com.networkId() != _id)
  1019. return Membership::ADD_REJECTED;
  1020. Mutex::Lock _l(_memberships_l);
  1021. return _memberships[com.issuedTo()].addCredential(RR,tPtr,sourcePeerIdentity,_config,com);
  1022. }
  1023. Membership::AddCredentialResult Network::addCredential(void *tPtr,const Identity &sourcePeerIdentity,const Capability &cap)
  1024. {
  1025. if (cap.networkId() != _id)
  1026. return Membership::ADD_REJECTED;
  1027. Mutex::Lock _l(_memberships_l);
  1028. return _memberships[cap.issuedTo()].addCredential(RR,tPtr,sourcePeerIdentity,_config,cap);
  1029. }
  1030. Membership::AddCredentialResult Network::addCredential(void *tPtr,const Identity &sourcePeerIdentity,const Tag &tag)
  1031. {
  1032. if (tag.networkId() != _id)
  1033. return Membership::ADD_REJECTED;
  1034. Mutex::Lock _l(_memberships_l);
  1035. return _memberships[tag.issuedTo()].addCredential(RR,tPtr,sourcePeerIdentity,_config,tag);
  1036. }
  1037. Membership::AddCredentialResult Network::addCredential(void *tPtr,const Identity &sourcePeerIdentity,const Revocation &rev)
  1038. {
  1039. if (rev.networkId() != _id)
  1040. return Membership::ADD_REJECTED;
  1041. Mutex::Lock l1(_memberships_l);
  1042. Membership &m = _memberships[rev.target()];
  1043. const Membership::AddCredentialResult result = m.addCredential(RR,tPtr,sourcePeerIdentity,_config,rev);
  1044. if ((result == Membership::ADD_ACCEPTED_NEW)&&(rev.fastPropagate())) {
  1045. Address *a = nullptr;
  1046. Membership *m = nullptr;
  1047. Hashtable<Address,Membership>::Iterator i(_memberships);
  1048. while (i.next(a,m)) {
  1049. if ((*a != sourcePeerIdentity.address())&&(*a != rev.signer())) {
  1050. Packet outp(*a,RR->identity.address(),Packet::VERB_NETWORK_CREDENTIALS);
  1051. outp.append((uint8_t)0x00); // no COM
  1052. outp.append((uint16_t)0); // no capabilities
  1053. outp.append((uint16_t)0); // no tags
  1054. outp.append((uint16_t)1); // one revocation!
  1055. rev.serialize(outp);
  1056. outp.append((uint16_t)0); // no certificates of ownership
  1057. RR->sw->send(tPtr,outp,true);
  1058. }
  1059. }
  1060. }
  1061. return result;
  1062. }
  1063. Membership::AddCredentialResult Network::addCredential(void *tPtr,const Identity &sourcePeerIdentity,const CertificateOfOwnership &coo)
  1064. {
  1065. if (coo.networkId() != _id)
  1066. return Membership::ADD_REJECTED;
  1067. Mutex::Lock _l(_memberships_l);
  1068. return _memberships[coo.issuedTo()].addCredential(RR,tPtr,sourcePeerIdentity,_config,coo);
  1069. }
  1070. void Network::pushCredentialsNow(void *tPtr,const Address &to,const int64_t now)
  1071. {
  1072. Mutex::Lock _l(_memberships_l);
  1073. _memberships[to].pushCredentials(RR,tPtr,now,to,_config);
  1074. }
  1075. void Network::destroy()
  1076. {
  1077. _memberships_l.lock();
  1078. _config_l.lock();
  1079. _destroyed = true;
  1080. _config_l.unlock();
  1081. _memberships_l.unlock();
  1082. }
  1083. void Network::externalConfig(ZT_VirtualNetworkConfig *ec) const
  1084. {
  1085. Mutex::Lock _l(_config_l);
  1086. _externalConfig(ec);
  1087. }
  1088. void Network::_requestConfiguration(void *tPtr)
  1089. {
  1090. if (_destroyed)
  1091. return;
  1092. if ((_id >> 56U) == 0xff) {
  1093. if ((_id & 0xffffffU) == 0) {
  1094. const uint16_t startPortRange = (uint16_t)((_id >> 40U) & 0xffff);
  1095. const uint16_t endPortRange = (uint16_t)((_id >> 24U) & 0xffff);
  1096. if (endPortRange >= startPortRange) {
  1097. ScopedPtr<NetworkConfig> nconf(new NetworkConfig());
  1098. nconf->networkId = _id;
  1099. nconf->timestamp = RR->node->now();
  1100. nconf->credentialTimeMaxDelta = ZT_NETWORKCONFIG_DEFAULT_CREDENTIAL_TIME_MAX_MAX_DELTA;
  1101. nconf->revision = 1;
  1102. nconf->issuedTo = RR->identity.address();
  1103. nconf->flags = ZT_NETWORKCONFIG_FLAG_ENABLE_IPV6_NDP_EMULATION;
  1104. nconf->mtu = ZT_DEFAULT_MTU;
  1105. nconf->multicastLimit = 0;
  1106. nconf->staticIpCount = 1;
  1107. nconf->ruleCount = 14;
  1108. nconf->staticIps[0] = InetAddress::makeIpv66plane(_id,RR->identity.address().toInt());
  1109. // Drop everything but IPv6
  1110. nconf->rules[0].t = (uint8_t)ZT_NETWORK_RULE_MATCH_ETHERTYPE | 0x80U; // NOT
  1111. nconf->rules[0].v.etherType = 0x86dd; // IPv6
  1112. nconf->rules[1].t = (uint8_t)ZT_NETWORK_RULE_ACTION_DROP;
  1113. // Allow ICMPv6
  1114. nconf->rules[2].t = (uint8_t)ZT_NETWORK_RULE_MATCH_IP_PROTOCOL;
  1115. nconf->rules[2].v.ipProtocol = 0x3a; // ICMPv6
  1116. nconf->rules[3].t = (uint8_t)ZT_NETWORK_RULE_ACTION_ACCEPT;
  1117. // Allow destination ports within range
  1118. nconf->rules[4].t = (uint8_t)ZT_NETWORK_RULE_MATCH_IP_PROTOCOL;
  1119. nconf->rules[4].v.ipProtocol = 0x11; // UDP
  1120. nconf->rules[5].t = (uint8_t)ZT_NETWORK_RULE_MATCH_IP_PROTOCOL | 0x40U; // OR
  1121. nconf->rules[5].v.ipProtocol = 0x06; // TCP
  1122. nconf->rules[6].t = (uint8_t)ZT_NETWORK_RULE_MATCH_IP_DEST_PORT_RANGE;
  1123. nconf->rules[6].v.port[0] = startPortRange;
  1124. nconf->rules[6].v.port[1] = endPortRange;
  1125. nconf->rules[7].t = (uint8_t)ZT_NETWORK_RULE_ACTION_ACCEPT;
  1126. // Allow non-SYN TCP packets to permit non-connection-initiating traffic
  1127. nconf->rules[8].t = (uint8_t)ZT_NETWORK_RULE_MATCH_CHARACTERISTICS | 0x80U; // NOT
  1128. nconf->rules[8].v.characteristics = ZT_RULE_PACKET_CHARACTERISTICS_TCP_SYN;
  1129. nconf->rules[9].t = (uint8_t)ZT_NETWORK_RULE_ACTION_ACCEPT;
  1130. // Also allow SYN+ACK which are replies to SYN
  1131. nconf->rules[10].t = (uint8_t)ZT_NETWORK_RULE_MATCH_CHARACTERISTICS;
  1132. nconf->rules[10].v.characteristics = ZT_RULE_PACKET_CHARACTERISTICS_TCP_SYN;
  1133. nconf->rules[11].t = (uint8_t)ZT_NETWORK_RULE_MATCH_CHARACTERISTICS;
  1134. nconf->rules[11].v.characteristics = ZT_RULE_PACKET_CHARACTERISTICS_TCP_ACK;
  1135. nconf->rules[12].t = (uint8_t)ZT_NETWORK_RULE_ACTION_ACCEPT;
  1136. nconf->rules[13].t = (uint8_t)ZT_NETWORK_RULE_ACTION_DROP;
  1137. nconf->type = ZT_NETWORK_TYPE_PUBLIC;
  1138. nconf->name[0] = 'a';
  1139. nconf->name[1] = 'd';
  1140. nconf->name[2] = 'h';
  1141. nconf->name[3] = 'o';
  1142. nconf->name[4] = 'c';
  1143. nconf->name[5] = '-';
  1144. Utils::hex((uint16_t)startPortRange,nconf->name + 6);
  1145. nconf->name[10] = '-';
  1146. Utils::hex((uint16_t)endPortRange,nconf->name + 11);
  1147. nconf->name[15] = (char)0;
  1148. this->setConfiguration(tPtr,*nconf,false);
  1149. } else {
  1150. this->setNotFound();
  1151. }
  1152. } else if ((_id & 0xffU) == 0x01) {
  1153. // ffAAaaaaaaaaaa01 -- where AA is the IPv4 /8 to use and aaaaaaaaaa is the anchor node for multicast gather and replication
  1154. const uint64_t myAddress = RR->identity.address().toInt();
  1155. const uint64_t networkHub = (_id >> 8U) & 0xffffffffffULL;
  1156. uint8_t ipv4[4];
  1157. ipv4[0] = (uint8_t)(_id >> 48U);
  1158. ipv4[1] = (uint8_t)(myAddress >> 16U);
  1159. ipv4[2] = (uint8_t)(myAddress >> 8U);
  1160. ipv4[3] = (uint8_t)myAddress;
  1161. char v4ascii[24];
  1162. Utils::decimal(ipv4[0],v4ascii);
  1163. ScopedPtr<NetworkConfig> nconf(new NetworkConfig());
  1164. nconf->networkId = _id;
  1165. nconf->timestamp = RR->node->now();
  1166. nconf->credentialTimeMaxDelta = ZT_NETWORKCONFIG_DEFAULT_CREDENTIAL_TIME_MAX_MAX_DELTA;
  1167. nconf->revision = 1;
  1168. nconf->issuedTo = RR->identity.address();
  1169. nconf->flags = ZT_NETWORKCONFIG_FLAG_ENABLE_IPV6_NDP_EMULATION;
  1170. nconf->mtu = ZT_DEFAULT_MTU;
  1171. nconf->multicastLimit = 1024;
  1172. nconf->specialistCount = (networkHub == 0) ? 0 : 1;
  1173. nconf->staticIpCount = 2;
  1174. nconf->ruleCount = 1;
  1175. if (networkHub != 0)
  1176. nconf->specialists[0] = networkHub;
  1177. nconf->staticIps[0] = InetAddress::makeIpv66plane(_id,myAddress);
  1178. nconf->staticIps[1].set(ipv4,4,8);
  1179. nconf->rules[0].t = (uint8_t)ZT_NETWORK_RULE_ACTION_ACCEPT;
  1180. nconf->type = ZT_NETWORK_TYPE_PUBLIC;
  1181. nconf->name[0] = 'a';
  1182. nconf->name[1] = 'd';
  1183. nconf->name[2] = 'h';
  1184. nconf->name[3] = 'o';
  1185. nconf->name[4] = 'c';
  1186. nconf->name[5] = '-';
  1187. unsigned long nn = 6;
  1188. while ((nconf->name[nn] = v4ascii[nn - 6])) ++nn;
  1189. nconf->name[nn++] = '.';
  1190. nconf->name[nn++] = '0';
  1191. nconf->name[nn++] = '.';
  1192. nconf->name[nn++] = '0';
  1193. nconf->name[nn++] = '.';
  1194. nconf->name[nn++] = '0';
  1195. nconf->name[nn] = (char)0;
  1196. this->setConfiguration(tPtr,*nconf,false);
  1197. }
  1198. return;
  1199. }
  1200. const Address ctrl(controller());
  1201. Dictionary rmd;
  1202. rmd.add(ZT_NETWORKCONFIG_REQUEST_METADATA_KEY_NODE_VENDOR,(uint64_t)1); // 1 == ZeroTier, no other vendors at the moment
  1203. rmd.add(ZT_NETWORKCONFIG_REQUEST_METADATA_KEY_PROTOCOL_VERSION,(uint64_t)ZT_PROTO_VERSION);
  1204. rmd.add(ZT_NETWORKCONFIG_REQUEST_METADATA_KEY_NODE_MAJOR_VERSION,(uint64_t)ZEROTIER_ONE_VERSION_MAJOR);
  1205. rmd.add(ZT_NETWORKCONFIG_REQUEST_METADATA_KEY_NODE_MINOR_VERSION,(uint64_t)ZEROTIER_ONE_VERSION_MINOR);
  1206. rmd.add(ZT_NETWORKCONFIG_REQUEST_METADATA_KEY_NODE_REVISION,(uint64_t)ZEROTIER_ONE_VERSION_REVISION);
  1207. rmd.add(ZT_NETWORKCONFIG_REQUEST_METADATA_KEY_MAX_NETWORK_RULES,(uint64_t)ZT_MAX_NETWORK_RULES);
  1208. rmd.add(ZT_NETWORKCONFIG_REQUEST_METADATA_KEY_MAX_NETWORK_CAPABILITIES,(uint64_t)ZT_MAX_NETWORK_CAPABILITIES);
  1209. rmd.add(ZT_NETWORKCONFIG_REQUEST_METADATA_KEY_MAX_CAPABILITY_RULES,(uint64_t)ZT_MAX_CAPABILITY_RULES);
  1210. rmd.add(ZT_NETWORKCONFIG_REQUEST_METADATA_KEY_MAX_NETWORK_TAGS,(uint64_t)ZT_MAX_NETWORK_TAGS);
  1211. rmd.add(ZT_NETWORKCONFIG_REQUEST_METADATA_KEY_FLAGS,(uint64_t)0);
  1212. rmd.add(ZT_NETWORKCONFIG_REQUEST_METADATA_KEY_RULES_ENGINE_REV,(uint64_t)ZT_RULES_ENGINE_REVISION);
  1213. RR->t->networkConfigRequestSent(tPtr,_id);
  1214. if (ctrl == RR->identity.address()) {
  1215. if (RR->localNetworkController) {
  1216. RR->localNetworkController->request(_id,InetAddress(),0xffffffffffffffffULL,RR->identity,rmd);
  1217. } else {
  1218. this->setNotFound();
  1219. }
  1220. return;
  1221. }
  1222. Packet outp(ctrl,RR->identity.address(),Packet::VERB_NETWORK_CONFIG_REQUEST);
  1223. outp.append((uint64_t)_id);
  1224. const unsigned int rmdSize = rmd->sizeBytes();
  1225. outp.append((uint16_t)rmdSize);
  1226. outp.append((const void *)rmd->data(),rmdSize);
  1227. if (_config) {
  1228. outp.append((uint64_t)_config.revision);
  1229. outp.append((uint64_t)_config.timestamp);
  1230. } else {
  1231. outp.append((unsigned char)0,16);
  1232. }
  1233. outp.compress();
  1234. RR->node->expectReplyTo(outp.packetId());
  1235. RR->sw->send(tPtr,outp,true);
  1236. }
  1237. ZT_VirtualNetworkStatus Network::_status() const
  1238. {
  1239. switch(_netconfFailure) {
  1240. case NETCONF_FAILURE_ACCESS_DENIED:
  1241. return ZT_NETWORK_STATUS_ACCESS_DENIED;
  1242. case NETCONF_FAILURE_NOT_FOUND:
  1243. return ZT_NETWORK_STATUS_NOT_FOUND;
  1244. case NETCONF_FAILURE_NONE:
  1245. return ((_config) ? ZT_NETWORK_STATUS_OK : ZT_NETWORK_STATUS_REQUESTING_CONFIGURATION);
  1246. default:
  1247. return ZT_NETWORK_STATUS_REQUESTING_CONFIGURATION;
  1248. }
  1249. }
  1250. void Network::_externalConfig(ZT_VirtualNetworkConfig *ec) const
  1251. {
  1252. // assumes _config_l is locked
  1253. ec->nwid = _id;
  1254. ec->mac = _mac.toInt();
  1255. if (_config)
  1256. Utils::scopy(ec->name,sizeof(ec->name),_config.name);
  1257. else ec->name[0] = (char)0;
  1258. ec->status = _status();
  1259. ec->type = (_config) ? (_config.isPrivate() ? ZT_NETWORK_TYPE_PRIVATE : ZT_NETWORK_TYPE_PUBLIC) : ZT_NETWORK_TYPE_PRIVATE;
  1260. ec->mtu = (_config) ? _config.mtu : ZT_DEFAULT_MTU;
  1261. std::vector<Address> ab;
  1262. for(unsigned int i=0;i<_config.specialistCount;++i) {
  1263. if ((_config.specialists[i] & ZT_NETWORKCONFIG_SPECIALIST_TYPE_ACTIVE_BRIDGE) != 0)
  1264. ab.push_back(Address(_config.specialists[i]));
  1265. }
  1266. ec->bridge = (std::find(ab.begin(),ab.end(),RR->identity.address()) != ab.end()) ? 1 : 0;
  1267. ec->broadcastEnabled = (_config) ? (_config.enableBroadcast() ? 1 : 0) : 0;
  1268. ec->netconfRevision = (_config) ? (unsigned long)_config.revision : 0;
  1269. ec->assignedAddressCount = 0;
  1270. for(unsigned int i=0;i<ZT_MAX_ZT_ASSIGNED_ADDRESSES;++i) {
  1271. if (i < _config.staticIpCount) {
  1272. memcpy(&(ec->assignedAddresses[i]),&(_config.staticIps[i]),sizeof(struct sockaddr_storage));
  1273. ++ec->assignedAddressCount;
  1274. } else {
  1275. memset(&(ec->assignedAddresses[i]),0,sizeof(struct sockaddr_storage));
  1276. }
  1277. }
  1278. ec->routeCount = 0;
  1279. for(unsigned int i=0;i<ZT_MAX_NETWORK_ROUTES;++i) {
  1280. if (i < _config.routeCount) {
  1281. memcpy(&(ec->routes[i]),&(_config.routes[i]),sizeof(ZT_VirtualNetworkRoute));
  1282. ++ec->routeCount;
  1283. } else {
  1284. memset(&(ec->routes[i]),0,sizeof(ZT_VirtualNetworkRoute));
  1285. }
  1286. }
  1287. }
  1288. void Network::_announceMulticastGroups(void *tPtr,bool force)
  1289. {
  1290. // Assumes _myMulticastGroups_l and _memberships_l are locked
  1291. const std::vector<MulticastGroup> groups(_allMulticastGroups());
  1292. _announceMulticastGroupsTo(tPtr,controller(),groups);
  1293. {
  1294. Address *a = nullptr;
  1295. Membership *m = nullptr;
  1296. Hashtable<Address,Membership>::Iterator i(_memberships);
  1297. while (i.next(a,m)) {
  1298. // TODO
  1299. /*
  1300. bool announce = m->multicastLikeGate(now); // force this to be called even if 'force' is true since it updates last push time
  1301. if ((!announce)&&(force))
  1302. announce = true;
  1303. if ((announce)&&(m->isAllowedOnNetwork(_config)))
  1304. _announceMulticastGroupsTo(tPtr,*a,groups);
  1305. */
  1306. }
  1307. }
  1308. }
  1309. void Network::_announceMulticastGroupsTo(void *tPtr,const Address &peer,const std::vector<MulticastGroup> &allMulticastGroups)
  1310. {
  1311. // Assumes _myMulticastGroups_l and _memberships_l are locked
  1312. ScopedPtr<Packet> outp(new Packet(peer,RR->identity.address(),Packet::VERB_MULTICAST_LIKE));
  1313. for(std::vector<MulticastGroup>::const_iterator mg(allMulticastGroups.begin());mg!=allMulticastGroups.end();++mg) {
  1314. if ((outp->size() + 24) >= ZT_PROTO_MAX_PACKET_LENGTH) {
  1315. outp->compress();
  1316. RR->sw->send(tPtr,*outp,true);
  1317. outp->reset(peer,RR->identity.address(),Packet::VERB_MULTICAST_LIKE);
  1318. }
  1319. // network ID, MAC, ADI
  1320. outp->append((uint64_t)_id);
  1321. mg->mac().appendTo(*outp);
  1322. outp->append((uint32_t)mg->adi());
  1323. }
  1324. if (outp->size() > ZT_PROTO_MIN_PACKET_LENGTH) {
  1325. outp->compress();
  1326. RR->sw->send(tPtr,*outp,true);
  1327. }
  1328. }
  1329. std::vector<MulticastGroup> Network::_allMulticastGroups() const
  1330. {
  1331. // Assumes _myMulticastGroups_l is locked
  1332. std::vector<MulticastGroup> mgs;
  1333. mgs.reserve(_myMulticastGroups.size() + _multicastGroupsBehindMe.size() + 1);
  1334. mgs.insert(mgs.end(),_myMulticastGroups.begin(),_myMulticastGroups.end());
  1335. _multicastGroupsBehindMe.appendKeys(mgs);
  1336. if ((_config)&&(_config.enableBroadcast()))
  1337. mgs.push_back(Network::BROADCAST);
  1338. std::sort(mgs.begin(),mgs.end());
  1339. mgs.erase(std::unique(mgs.begin(),mgs.end()),mgs.end());
  1340. return mgs;
  1341. }
  1342. } // namespace ZeroTier