Network.cpp 50 KB

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