Network.cpp 53 KB

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