Network.cpp 51 KB

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