Network.cpp 52 KB

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