Network.cpp 50 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423
  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. _mac(renv->identity.address(),nwid),
  530. _portInitialized(false),
  531. _lastConfigUpdate(0),
  532. _destroyed(false),
  533. _netconfFailure(NETCONF_FAILURE_NONE),
  534. _portError(0)
  535. {
  536. for(int i=0;i<ZT_NETWORK_MAX_INCOMING_UPDATES;++i)
  537. _incomingConfigChunks[i].ts = 0;
  538. if (nconf) {
  539. this->setConfiguration(tPtr,*nconf,false);
  540. _lastConfigUpdate = 0; // still want to re-request since it's likely outdated
  541. } else {
  542. uint64_t tmp[2];
  543. tmp[0] = nwid; tmp[1] = 0;
  544. bool got = false;
  545. Dictionary<ZT_NETWORKCONFIG_DICT_CAPACITY> *dict = new Dictionary<ZT_NETWORKCONFIG_DICT_CAPACITY>();
  546. try {
  547. int n = RR->node->stateObjectGet(tPtr,ZT_STATE_OBJECT_NETWORK_CONFIG,tmp,dict->unsafeData(),ZT_NETWORKCONFIG_DICT_CAPACITY - 1);
  548. if (n > 1) {
  549. NetworkConfig *nconf = new NetworkConfig();
  550. try {
  551. if (nconf->fromDictionary(*dict)) {
  552. this->setConfiguration(tPtr,*nconf,false);
  553. _lastConfigUpdate = 0; // still want to re-request an update since it's likely outdated
  554. got = true;
  555. }
  556. } catch ( ... ) {}
  557. delete nconf;
  558. }
  559. } catch ( ... ) {}
  560. delete dict;
  561. if (!got)
  562. RR->node->stateObjectPut(tPtr,ZT_STATE_OBJECT_NETWORK_CONFIG,tmp,"\n",1);
  563. }
  564. if (!_portInitialized) {
  565. ZT_VirtualNetworkConfig ctmp;
  566. _externalConfig(&ctmp);
  567. _portError = RR->node->configureVirtualNetworkPort(tPtr,_id,&_uPtr,ZT_VIRTUAL_NETWORK_CONFIG_OPERATION_UP,&ctmp);
  568. _portInitialized = true;
  569. }
  570. }
  571. Network::~Network()
  572. {
  573. _memberships_l.lock();
  574. _config_l.lock();
  575. _config_l.unlock();
  576. _memberships_l.unlock();
  577. ZT_VirtualNetworkConfig ctmp;
  578. _externalConfig(&ctmp);
  579. if (_destroyed) {
  580. // This is done in Node::leave() so we can pass tPtr properly
  581. //RR->node->configureVirtualNetworkPort((void *)0,_id,&_uPtr,ZT_VIRTUAL_NETWORK_CONFIG_OPERATION_DESTROY,&ctmp);
  582. } else {
  583. RR->node->configureVirtualNetworkPort((void *)0,_id,&_uPtr,ZT_VIRTUAL_NETWORK_CONFIG_OPERATION_DOWN,&ctmp);
  584. }
  585. }
  586. bool Network::filterOutgoingPacket(
  587. void *tPtr,
  588. const bool noTee,
  589. const Address &ztSource,
  590. const Address &ztDest,
  591. const MAC &macSource,
  592. const MAC &macDest,
  593. const uint8_t *frameData,
  594. const unsigned int frameLen,
  595. const unsigned int etherType,
  596. const unsigned int vlanId,
  597. uint8_t &qosBucket)
  598. {
  599. Address ztFinalDest(ztDest);
  600. int localCapabilityIndex = -1;
  601. int accept = 0;
  602. Trace::RuleResultLog rrl,crrl;
  603. Address cc;
  604. unsigned int ccLength = 0;
  605. bool ccWatch = false;
  606. Mutex::Lock l1(_memberships_l);
  607. Mutex::Lock l2(_config_l);
  608. Membership *const membership = (ztDest) ? _memberships.get(ztDest) : (Membership *)0;
  609. switch(_doZtFilter(RR,rrl,_config,membership,false,ztSource,ztFinalDest,macSource,macDest,frameData,frameLen,etherType,vlanId,_config.rules,_config.ruleCount,cc,ccLength,ccWatch,qosBucket)) {
  610. case DOZTFILTER_NO_MATCH: {
  611. for(unsigned int c=0;c<_config.capabilityCount;++c) {
  612. ztFinalDest = ztDest; // sanity check, shouldn't be possible if there was no match
  613. Address cc2;
  614. unsigned int ccLength2 = 0;
  615. bool ccWatch2 = false;
  616. 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)) {
  617. case DOZTFILTER_NO_MATCH:
  618. case DOZTFILTER_DROP: // explicit DROP in a capability just terminates its evaluation and is an anti-pattern
  619. break;
  620. case DOZTFILTER_REDIRECT: // interpreted as ACCEPT but ztFinalDest will have been changed in _doZtFilter()
  621. case DOZTFILTER_ACCEPT:
  622. case DOZTFILTER_SUPER_ACCEPT: // no difference in behavior on outbound side in capabilities
  623. localCapabilityIndex = (int)c;
  624. accept = 1;
  625. if ((!noTee)&&(cc2)) {
  626. Packet outp(cc2,RR->identity.address(),Packet::VERB_EXT_FRAME);
  627. outp.append(_id);
  628. outp.append((uint8_t)(ccWatch2 ? 0x16 : 0x02));
  629. macDest.appendTo(outp);
  630. macSource.appendTo(outp);
  631. outp.append((uint16_t)etherType);
  632. outp.append(frameData,ccLength2);
  633. outp.compress();
  634. RR->sw->send(tPtr,outp,true);
  635. }
  636. break;
  637. }
  638. if (accept)
  639. break;
  640. }
  641. } break;
  642. case DOZTFILTER_DROP:
  643. if (_config.remoteTraceTarget)
  644. RR->t->networkFilter(tPtr,*this,rrl,(Trace::RuleResultLog *)0,(Capability *)0,ztSource,ztDest,macSource,macDest,frameData,frameLen,etherType,vlanId,noTee,false,0);
  645. return false;
  646. case DOZTFILTER_REDIRECT: // interpreted as ACCEPT but ztFinalDest will have been changed in _doZtFilter()
  647. case DOZTFILTER_ACCEPT:
  648. accept = 1;
  649. break;
  650. case DOZTFILTER_SUPER_ACCEPT:
  651. accept = 2;
  652. break;
  653. }
  654. if (accept) {
  655. if (membership)
  656. membership->logSentBytes(frameLen);
  657. if ((!noTee)&&(cc)) {
  658. Packet outp(cc,RR->identity.address(),Packet::VERB_EXT_FRAME);
  659. outp.append(_id);
  660. outp.append((uint8_t)(ccWatch ? 0x16 : 0x02));
  661. macDest.appendTo(outp);
  662. macSource.appendTo(outp);
  663. outp.append((uint16_t)etherType);
  664. outp.append(frameData,ccLength);
  665. outp.compress();
  666. RR->sw->send(tPtr,outp,true);
  667. }
  668. if ((ztDest != ztFinalDest)&&(ztFinalDest)) {
  669. Packet outp(ztFinalDest,RR->identity.address(),Packet::VERB_EXT_FRAME);
  670. outp.append(_id);
  671. outp.append((uint8_t)0x04);
  672. macDest.appendTo(outp);
  673. macSource.appendTo(outp);
  674. outp.append((uint16_t)etherType);
  675. outp.append(frameData,frameLen);
  676. outp.compress();
  677. RR->sw->send(tPtr,outp,true);
  678. if (_config.remoteTraceTarget)
  679. 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);
  680. return false; // DROP locally, since we redirected
  681. } else {
  682. if (_config.remoteTraceTarget)
  683. 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);
  684. return true;
  685. }
  686. } else {
  687. if (_config.remoteTraceTarget)
  688. 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);
  689. return false;
  690. }
  691. }
  692. int Network::filterIncomingPacket(
  693. void *tPtr,
  694. const SharedPtr<Peer> &sourcePeer,
  695. const Address &ztDest,
  696. const MAC &macSource,
  697. const MAC &macDest,
  698. const uint8_t *frameData,
  699. const unsigned int frameLen,
  700. const unsigned int etherType,
  701. const unsigned int vlanId)
  702. {
  703. Address ztFinalDest(ztDest);
  704. Trace::RuleResultLog rrl,crrl;
  705. int accept = 0;
  706. Address cc;
  707. unsigned int ccLength = 0;
  708. bool ccWatch = false;
  709. const Capability *c = (Capability *)0;
  710. uint8_t qosBucket = 255; // For incoming packets this is a dummy value
  711. Mutex::Lock l1(_memberships_l);
  712. Mutex::Lock l2(_config_l);
  713. Membership &membership = _memberships[sourcePeer->address()];
  714. switch (_doZtFilter(RR,rrl,_config,&membership,true,sourcePeer->address(),ztFinalDest,macSource,macDest,frameData,frameLen,etherType,vlanId,_config.rules,_config.ruleCount,cc,ccLength,ccWatch,qosBucket)) {
  715. case DOZTFILTER_NO_MATCH: {
  716. Membership::CapabilityIterator mci(membership,_config);
  717. while ((c = mci.next())) {
  718. ztFinalDest = ztDest; // sanity check, should be unmodified if there was no match
  719. Address cc2;
  720. unsigned int ccLength2 = 0;
  721. bool ccWatch2 = false;
  722. switch(_doZtFilter(RR,crrl,_config,&membership,true,sourcePeer->address(),ztFinalDest,macSource,macDest,frameData,frameLen,etherType,vlanId,c->rules(),c->ruleCount(),cc2,ccLength2,ccWatch2,qosBucket)) {
  723. case DOZTFILTER_NO_MATCH:
  724. case DOZTFILTER_DROP: // explicit DROP in a capability just terminates its evaluation and is an anti-pattern
  725. break;
  726. case DOZTFILTER_REDIRECT: // interpreted as ACCEPT but ztDest will have been changed in _doZtFilter()
  727. case DOZTFILTER_ACCEPT:
  728. accept = 1; // ACCEPT
  729. break;
  730. case DOZTFILTER_SUPER_ACCEPT:
  731. accept = 2; // super-ACCEPT
  732. break;
  733. }
  734. if (accept) {
  735. if (cc2) {
  736. Packet outp(cc2,RR->identity.address(),Packet::VERB_EXT_FRAME);
  737. outp.append(_id);
  738. outp.append((uint8_t)(ccWatch2 ? 0x1c : 0x08));
  739. macDest.appendTo(outp);
  740. macSource.appendTo(outp);
  741. outp.append((uint16_t)etherType);
  742. outp.append(frameData,ccLength2);
  743. outp.compress();
  744. RR->sw->send(tPtr,outp,true);
  745. }
  746. break;
  747. }
  748. }
  749. } break;
  750. case DOZTFILTER_DROP:
  751. if (_config.remoteTraceTarget)
  752. RR->t->networkFilter(tPtr,*this,rrl,(Trace::RuleResultLog *)0,(Capability *)0,sourcePeer->address(),ztDest,macSource,macDest,frameData,frameLen,etherType,vlanId,false,true,0);
  753. return 0; // DROP
  754. case DOZTFILTER_REDIRECT: // interpreted as ACCEPT but ztFinalDest will have been changed in _doZtFilter()
  755. case DOZTFILTER_ACCEPT:
  756. accept = 1; // ACCEPT
  757. break;
  758. case DOZTFILTER_SUPER_ACCEPT:
  759. accept = 2; // super-ACCEPT
  760. break;
  761. }
  762. if (accept) {
  763. membership.logReceivedBytes(frameLen);
  764. if (cc) {
  765. Packet outp(cc,RR->identity.address(),Packet::VERB_EXT_FRAME);
  766. outp.append(_id);
  767. outp.append((uint8_t)(ccWatch ? 0x1c : 0x08));
  768. macDest.appendTo(outp);
  769. macSource.appendTo(outp);
  770. outp.append((uint16_t)etherType);
  771. outp.append(frameData,ccLength);
  772. outp.compress();
  773. RR->sw->send(tPtr,outp,true);
  774. }
  775. if ((ztDest != ztFinalDest)&&(ztFinalDest)) {
  776. Packet outp(ztFinalDest,RR->identity.address(),Packet::VERB_EXT_FRAME);
  777. outp.append(_id);
  778. outp.append((uint8_t)0x0a);
  779. macDest.appendTo(outp);
  780. macSource.appendTo(outp);
  781. outp.append((uint16_t)etherType);
  782. outp.append(frameData,frameLen);
  783. outp.compress();
  784. RR->sw->send(tPtr,outp,true);
  785. if (_config.remoteTraceTarget)
  786. RR->t->networkFilter(tPtr,*this,rrl,(c) ? &crrl : (Trace::RuleResultLog *)0,c,sourcePeer->address(),ztDest,macSource,macDest,frameData,frameLen,etherType,vlanId,false,true,0);
  787. return 0; // DROP locally, since we redirected
  788. }
  789. }
  790. if (_config.remoteTraceTarget)
  791. RR->t->networkFilter(tPtr,*this,rrl,(c) ? &crrl : (Trace::RuleResultLog *)0,c,sourcePeer->address(),ztDest,macSource,macDest,frameData,frameLen,etherType,vlanId,false,true,accept);
  792. return accept;
  793. }
  794. uint64_t Network::handleConfigChunk(void *tPtr,const uint64_t packetId,const Address &source,const Buffer<ZT_PROTO_MAX_PACKET_LENGTH> &chunk,unsigned int ptr)
  795. {
  796. if (_destroyed)
  797. return 0;
  798. const unsigned int start = ptr;
  799. ptr += 8; // skip network ID, which is already obviously known
  800. const unsigned int chunkLen = chunk.at<uint16_t>(ptr); ptr += 2;
  801. const void *chunkData = chunk.field(ptr,chunkLen); ptr += chunkLen;
  802. NetworkConfig *nc = (NetworkConfig *)0;
  803. uint64_t configUpdateId;
  804. {
  805. Mutex::Lock l1(_config_l);
  806. _IncomingConfigChunk *c = (_IncomingConfigChunk *)0;
  807. uint64_t chunkId = 0;
  808. unsigned long totalLength,chunkIndex;
  809. if (ptr < chunk.size()) {
  810. const bool fastPropagate = ((chunk[ptr++] & 0x01) != 0);
  811. configUpdateId = chunk.at<uint64_t>(ptr); ptr += 8;
  812. totalLength = chunk.at<uint32_t>(ptr); ptr += 4;
  813. chunkIndex = chunk.at<uint32_t>(ptr); ptr += 4;
  814. if (((chunkIndex + chunkLen) > totalLength)||(totalLength >= ZT_NETWORKCONFIG_DICT_CAPACITY)) // >= since we need room for a null at the end
  815. return 0;
  816. if ((chunk[ptr] != 1)||(chunk.at<uint16_t>(ptr + 1) != ZT_C25519_SIGNATURE_LEN))
  817. return 0;
  818. const uint8_t *sig = reinterpret_cast<const uint8_t *>(chunk.field(ptr + 3,ZT_C25519_SIGNATURE_LEN));
  819. // We can use the signature, which is unique per chunk, to get a per-chunk ID for local deduplication use
  820. for(unsigned int i=0;i<16;++i)
  821. reinterpret_cast<uint8_t *>(&chunkId)[i & 7] ^= sig[i];
  822. // Find existing or new slot for this update and check if this is a duplicate chunk
  823. for(int i=0;i<ZT_NETWORK_MAX_INCOMING_UPDATES;++i) {
  824. if (_incomingConfigChunks[i].updateId == configUpdateId) {
  825. c = &(_incomingConfigChunks[i]);
  826. for(unsigned long j=0;j<c->haveChunks;++j) {
  827. if (c->haveChunkIds[j] == chunkId)
  828. return 0;
  829. }
  830. break;
  831. } else if ((!c)||(_incomingConfigChunks[i].ts < c->ts)) {
  832. c = &(_incomingConfigChunks[i]);
  833. }
  834. }
  835. // If it's not a duplicate, check chunk signature
  836. const Identity controllerId(RR->topology->getIdentity(tPtr,controller()));
  837. if (!controllerId) // we should always have the controller identity by now, otherwise how would we have queried it the first time?
  838. return 0;
  839. if (!controllerId.verify(chunk.field(start,ptr - start),ptr - start,sig,ZT_C25519_SIGNATURE_LEN))
  840. return 0;
  841. // New properly verified chunks can be flooded "virally" through the network
  842. if (fastPropagate) {
  843. Mutex::Lock l2(_memberships_l);
  844. Address *a = (Address *)0;
  845. Membership *m = (Membership *)0;
  846. Hashtable<Address,Membership>::Iterator i(_memberships);
  847. while (i.next(a,m)) {
  848. if ((*a != source)&&(*a != controller())) {
  849. Packet outp(*a,RR->identity.address(),Packet::VERB_NETWORK_CONFIG);
  850. outp.append(reinterpret_cast<const uint8_t *>(chunk.data()) + start,chunk.size() - start);
  851. RR->sw->send(tPtr,outp,true);
  852. }
  853. }
  854. }
  855. } else if ((source == controller())||(!source)) { // since old chunks aren't signed, only accept from controller itself (or via cluster backplane)
  856. // Legacy support for OK(NETWORK_CONFIG_REQUEST) from older controllers
  857. chunkId = packetId;
  858. configUpdateId = chunkId;
  859. totalLength = chunkLen;
  860. chunkIndex = 0;
  861. if (totalLength >= ZT_NETWORKCONFIG_DICT_CAPACITY)
  862. return 0;
  863. for(int i=0;i<ZT_NETWORK_MAX_INCOMING_UPDATES;++i) {
  864. if ((!c)||(_incomingConfigChunks[i].ts < c->ts))
  865. c = &(_incomingConfigChunks[i]);
  866. }
  867. } else {
  868. // Single-chunk unsigned legacy configs are only allowed from the controller itself
  869. return 0;
  870. }
  871. ++c->ts; // newer is higher, that's all we need
  872. if (c->updateId != configUpdateId) {
  873. c->updateId = configUpdateId;
  874. c->haveChunks = 0;
  875. c->haveBytes = 0;
  876. }
  877. if (c->haveChunks >= ZT_NETWORK_MAX_UPDATE_CHUNKS)
  878. return false;
  879. c->haveChunkIds[c->haveChunks++] = chunkId;
  880. memcpy(c->data.unsafeData() + chunkIndex,chunkData,chunkLen);
  881. c->haveBytes += chunkLen;
  882. if (c->haveBytes == totalLength) {
  883. c->data.unsafeData()[c->haveBytes] = (char)0; // ensure null terminated
  884. nc = new NetworkConfig();
  885. try {
  886. if (!nc->fromDictionary(c->data)) {
  887. delete nc;
  888. nc = (NetworkConfig *)0;
  889. }
  890. } catch ( ... ) {
  891. delete nc;
  892. nc = (NetworkConfig *)0;
  893. }
  894. }
  895. }
  896. if (nc) {
  897. this->setConfiguration(tPtr,*nc,true);
  898. delete nc;
  899. return configUpdateId;
  900. } else {
  901. return 0;
  902. }
  903. return 0;
  904. }
  905. int Network::setConfiguration(void *tPtr,const NetworkConfig &nconf,bool saveToDisk)
  906. {
  907. if (_destroyed)
  908. return 0;
  909. // _lock is NOT locked when this is called
  910. try {
  911. if ((nconf.issuedTo != RR->identity.address())||(nconf.networkId != _id))
  912. return 0; // invalid config that is not for us or not for this network
  913. if (_config == nconf)
  914. return 1; // OK config, but duplicate of what we already have
  915. ZT_VirtualNetworkConfig ctmp;
  916. bool oldPortInitialized;
  917. { // do things that require lock here, but unlock before calling callbacks
  918. Mutex::Lock l1(_config_l);
  919. _config = nconf;
  920. _lastConfigUpdate = RR->node->now();
  921. _netconfFailure = NETCONF_FAILURE_NONE;
  922. oldPortInitialized = _portInitialized;
  923. _portInitialized = true;
  924. _externalConfig(&ctmp);
  925. }
  926. _portError = RR->node->configureVirtualNetworkPort(tPtr,_id,&_uPtr,(oldPortInitialized) ? ZT_VIRTUAL_NETWORK_CONFIG_OPERATION_CONFIG_UPDATE : ZT_VIRTUAL_NETWORK_CONFIG_OPERATION_UP,&ctmp);
  927. if (saveToDisk) {
  928. Dictionary<ZT_NETWORKCONFIG_DICT_CAPACITY> *const d = new Dictionary<ZT_NETWORKCONFIG_DICT_CAPACITY>();
  929. try {
  930. if (nconf.toDictionary(*d,false)) {
  931. uint64_t tmp[2];
  932. tmp[0] = _id; tmp[1] = 0;
  933. RR->node->stateObjectPut(tPtr,ZT_STATE_OBJECT_NETWORK_CONFIG,tmp,d->data(),d->sizeBytes());
  934. }
  935. } catch ( ... ) {}
  936. delete d;
  937. }
  938. return 2; // OK and configuration has changed
  939. } catch ( ... ) {} // ignore invalid configs
  940. return 0;
  941. }
  942. void Network::requestConfiguration(void *tPtr)
  943. {
  944. if (_destroyed)
  945. return;
  946. if ((_id >> 56) == 0xff) {
  947. if ((_id & 0xffffff) == 0) {
  948. const uint16_t startPortRange = (uint16_t)((_id >> 40) & 0xffff);
  949. const uint16_t endPortRange = (uint16_t)((_id >> 24) & 0xffff);
  950. if (endPortRange >= startPortRange) {
  951. NetworkConfig *const nconf = new NetworkConfig();
  952. nconf->networkId = _id;
  953. nconf->timestamp = RR->node->now();
  954. nconf->credentialTimeMaxDelta = ZT_NETWORKCONFIG_DEFAULT_CREDENTIAL_TIME_MAX_MAX_DELTA;
  955. nconf->revision = 1;
  956. nconf->issuedTo = RR->identity.address();
  957. nconf->flags = ZT_NETWORKCONFIG_FLAG_ENABLE_IPV6_NDP_EMULATION;
  958. nconf->mtu = ZT_DEFAULT_MTU;
  959. nconf->multicastLimit = 0;
  960. nconf->staticIpCount = 1;
  961. nconf->ruleCount = 14;
  962. nconf->staticIps[0] = InetAddress::makeIpv66plane(_id,RR->identity.address().toInt());
  963. // Drop everything but IPv6
  964. nconf->rules[0].t = (uint8_t)ZT_NETWORK_RULE_MATCH_ETHERTYPE | 0x80; // NOT
  965. nconf->rules[0].v.etherType = 0x86dd; // IPv6
  966. nconf->rules[1].t = (uint8_t)ZT_NETWORK_RULE_ACTION_DROP;
  967. // Allow ICMPv6
  968. nconf->rules[2].t = (uint8_t)ZT_NETWORK_RULE_MATCH_IP_PROTOCOL;
  969. nconf->rules[2].v.ipProtocol = 0x3a; // ICMPv6
  970. nconf->rules[3].t = (uint8_t)ZT_NETWORK_RULE_ACTION_ACCEPT;
  971. // Allow destination ports within range
  972. nconf->rules[4].t = (uint8_t)ZT_NETWORK_RULE_MATCH_IP_PROTOCOL;
  973. nconf->rules[4].v.ipProtocol = 0x11; // UDP
  974. nconf->rules[5].t = (uint8_t)ZT_NETWORK_RULE_MATCH_IP_PROTOCOL | 0x40; // OR
  975. nconf->rules[5].v.ipProtocol = 0x06; // TCP
  976. nconf->rules[6].t = (uint8_t)ZT_NETWORK_RULE_MATCH_IP_DEST_PORT_RANGE;
  977. nconf->rules[6].v.port[0] = startPortRange;
  978. nconf->rules[6].v.port[1] = endPortRange;
  979. nconf->rules[7].t = (uint8_t)ZT_NETWORK_RULE_ACTION_ACCEPT;
  980. // Allow non-SYN TCP packets to permit non-connection-initiating traffic
  981. nconf->rules[8].t = (uint8_t)ZT_NETWORK_RULE_MATCH_CHARACTERISTICS | 0x80; // NOT
  982. nconf->rules[8].v.characteristics = ZT_RULE_PACKET_CHARACTERISTICS_TCP_SYN;
  983. nconf->rules[9].t = (uint8_t)ZT_NETWORK_RULE_ACTION_ACCEPT;
  984. // Also allow SYN+ACK which are replies to SYN
  985. nconf->rules[10].t = (uint8_t)ZT_NETWORK_RULE_MATCH_CHARACTERISTICS;
  986. nconf->rules[10].v.characteristics = ZT_RULE_PACKET_CHARACTERISTICS_TCP_SYN;
  987. nconf->rules[11].t = (uint8_t)ZT_NETWORK_RULE_MATCH_CHARACTERISTICS;
  988. nconf->rules[11].v.characteristics = ZT_RULE_PACKET_CHARACTERISTICS_TCP_ACK;
  989. nconf->rules[12].t = (uint8_t)ZT_NETWORK_RULE_ACTION_ACCEPT;
  990. nconf->rules[13].t = (uint8_t)ZT_NETWORK_RULE_ACTION_DROP;
  991. nconf->type = ZT_NETWORK_TYPE_PUBLIC;
  992. nconf->name[0] = 'a';
  993. nconf->name[1] = 'd';
  994. nconf->name[2] = 'h';
  995. nconf->name[3] = 'o';
  996. nconf->name[4] = 'c';
  997. nconf->name[5] = '-';
  998. Utils::hex((uint16_t)startPortRange,nconf->name + 6);
  999. nconf->name[10] = '-';
  1000. Utils::hex((uint16_t)endPortRange,nconf->name + 11);
  1001. nconf->name[15] = (char)0;
  1002. this->setConfiguration(tPtr,*nconf,false);
  1003. delete nconf;
  1004. } else {
  1005. this->setNotFound();
  1006. }
  1007. } else if ((_id & 0xff) == 0x01) {
  1008. // ffAAaaaaaaaaaa01 -- where AA is the IPv4 /8 to use and aaaaaaaaaa is the anchor node for multicast gather and replication
  1009. const uint64_t myAddress = RR->identity.address().toInt();
  1010. const uint64_t networkHub = (_id >> 8) & 0xffffffffffULL;
  1011. uint8_t ipv4[4];
  1012. ipv4[0] = (uint8_t)((_id >> 48) & 0xff);
  1013. ipv4[1] = (uint8_t)((myAddress >> 16) & 0xff);
  1014. ipv4[2] = (uint8_t)((myAddress >> 8) & 0xff);
  1015. ipv4[3] = (uint8_t)(myAddress & 0xff);
  1016. char v4ascii[24];
  1017. Utils::decimal(ipv4[0],v4ascii);
  1018. NetworkConfig *const nconf = new NetworkConfig();
  1019. nconf->networkId = _id;
  1020. nconf->timestamp = RR->node->now();
  1021. nconf->credentialTimeMaxDelta = ZT_NETWORKCONFIG_DEFAULT_CREDENTIAL_TIME_MAX_MAX_DELTA;
  1022. nconf->revision = 1;
  1023. nconf->issuedTo = RR->identity.address();
  1024. nconf->flags = ZT_NETWORKCONFIG_FLAG_ENABLE_IPV6_NDP_EMULATION;
  1025. nconf->mtu = ZT_DEFAULT_MTU;
  1026. nconf->multicastLimit = 1024;
  1027. nconf->specialistCount = (networkHub == 0) ? 0 : 1;
  1028. nconf->staticIpCount = 2;
  1029. nconf->ruleCount = 1;
  1030. if (networkHub != 0)
  1031. nconf->specialists[0] = networkHub;
  1032. nconf->staticIps[0] = InetAddress::makeIpv66plane(_id,myAddress);
  1033. nconf->staticIps[1].set(ipv4,4,8);
  1034. nconf->rules[0].t = (uint8_t)ZT_NETWORK_RULE_ACTION_ACCEPT;
  1035. nconf->type = ZT_NETWORK_TYPE_PUBLIC;
  1036. nconf->name[0] = 'a';
  1037. nconf->name[1] = 'd';
  1038. nconf->name[2] = 'h';
  1039. nconf->name[3] = 'o';
  1040. nconf->name[4] = 'c';
  1041. nconf->name[5] = '-';
  1042. unsigned long nn = 6;
  1043. while ((nconf->name[nn] = v4ascii[nn - 6])) ++nn;
  1044. nconf->name[nn++] = '.';
  1045. nconf->name[nn++] = '0';
  1046. nconf->name[nn++] = '.';
  1047. nconf->name[nn++] = '0';
  1048. nconf->name[nn++] = '.';
  1049. nconf->name[nn++] = '0';
  1050. nconf->name[nn++] = (char)0;
  1051. this->setConfiguration(tPtr,*nconf,false);
  1052. delete nconf;
  1053. }
  1054. return;
  1055. }
  1056. const Address ctrl(controller());
  1057. Dictionary<ZT_NETWORKCONFIG_METADATA_DICT_CAPACITY> rmd;
  1058. rmd.add(ZT_NETWORKCONFIG_REQUEST_METADATA_KEY_VERSION,(uint64_t)ZT_NETWORKCONFIG_VERSION);
  1059. rmd.add(ZT_NETWORKCONFIG_REQUEST_METADATA_KEY_NODE_VENDOR,(uint64_t)ZT_VENDOR_ZEROTIER);
  1060. rmd.add(ZT_NETWORKCONFIG_REQUEST_METADATA_KEY_PROTOCOL_VERSION,(uint64_t)ZT_PROTO_VERSION);
  1061. rmd.add(ZT_NETWORKCONFIG_REQUEST_METADATA_KEY_NODE_MAJOR_VERSION,(uint64_t)ZEROTIER_ONE_VERSION_MAJOR);
  1062. rmd.add(ZT_NETWORKCONFIG_REQUEST_METADATA_KEY_NODE_MINOR_VERSION,(uint64_t)ZEROTIER_ONE_VERSION_MINOR);
  1063. rmd.add(ZT_NETWORKCONFIG_REQUEST_METADATA_KEY_NODE_REVISION,(uint64_t)ZEROTIER_ONE_VERSION_REVISION);
  1064. rmd.add(ZT_NETWORKCONFIG_REQUEST_METADATA_KEY_MAX_NETWORK_RULES,(uint64_t)ZT_MAX_NETWORK_RULES);
  1065. rmd.add(ZT_NETWORKCONFIG_REQUEST_METADATA_KEY_MAX_NETWORK_CAPABILITIES,(uint64_t)ZT_MAX_NETWORK_CAPABILITIES);
  1066. rmd.add(ZT_NETWORKCONFIG_REQUEST_METADATA_KEY_MAX_CAPABILITY_RULES,(uint64_t)ZT_MAX_CAPABILITY_RULES);
  1067. rmd.add(ZT_NETWORKCONFIG_REQUEST_METADATA_KEY_MAX_NETWORK_TAGS,(uint64_t)ZT_MAX_NETWORK_TAGS);
  1068. rmd.add(ZT_NETWORKCONFIG_REQUEST_METADATA_KEY_FLAGS,(uint64_t)0);
  1069. rmd.add(ZT_NETWORKCONFIG_REQUEST_METADATA_KEY_RULES_ENGINE_REV,(uint64_t)ZT_RULES_ENGINE_REVISION);
  1070. RR->t->networkConfigRequestSent(tPtr,*this,ctrl);
  1071. if (ctrl == RR->identity.address()) {
  1072. if (RR->localNetworkController) {
  1073. RR->localNetworkController->request(_id,InetAddress(),0xffffffffffffffffULL,RR->identity,rmd);
  1074. } else {
  1075. this->setNotFound();
  1076. }
  1077. return;
  1078. }
  1079. Packet outp(ctrl,RR->identity.address(),Packet::VERB_NETWORK_CONFIG_REQUEST);
  1080. outp.append((uint64_t)_id);
  1081. const unsigned int rmdSize = rmd.sizeBytes();
  1082. outp.append((uint16_t)rmdSize);
  1083. outp.append((const void *)rmd.data(),rmdSize);
  1084. if (_config) {
  1085. outp.append((uint64_t)_config.revision);
  1086. outp.append((uint64_t)_config.timestamp);
  1087. } else {
  1088. outp.append((unsigned char)0,16);
  1089. }
  1090. outp.compress();
  1091. RR->node->expectReplyTo(outp.packetId());
  1092. RR->sw->send(tPtr,outp,true);
  1093. }
  1094. bool Network::gate(void *tPtr,const SharedPtr<Peer> &peer)
  1095. {
  1096. const int64_t now = RR->node->now();
  1097. Mutex::Lock l(_memberships_l);
  1098. try {
  1099. if (_config) {
  1100. Membership *m = _memberships.get(peer->address());
  1101. if ( (_config.isPublic()) || ((m)&&(m->isAllowedOnNetwork(_config))) ) {
  1102. if (!m)
  1103. m = &(_memberships[peer->address()]);
  1104. if (m->multicastLikeGate(now)) {
  1105. Mutex::Lock l2(_myMulticastGroups_l);
  1106. _announceMulticastGroupsTo(tPtr,peer->address(),_allMulticastGroups());
  1107. }
  1108. return true;
  1109. }
  1110. }
  1111. } catch ( ... ) {}
  1112. return false;
  1113. }
  1114. void Network::doPeriodicTasks(void *tPtr)
  1115. {
  1116. const int64_t now = RR->node->now();
  1117. Mutex::Lock l1(_memberships_l);
  1118. if (_destroyed)
  1119. return;
  1120. {
  1121. Address *a = (Address *)0;
  1122. Membership *m = (Membership *)0;
  1123. Hashtable<Address,Membership>::Iterator i(_memberships);
  1124. while (i.next(a,m)) {
  1125. m->clean(now,_config);
  1126. }
  1127. }
  1128. {
  1129. Mutex::Lock l2(_myMulticastGroups_l);
  1130. Hashtable< MulticastGroup,uint64_t >::Iterator i(_multicastGroupsBehindMe);
  1131. MulticastGroup *mg = (MulticastGroup *)0;
  1132. uint64_t *ts = (uint64_t *)0;
  1133. while (i.next(mg,ts)) {
  1134. if ((now - *ts) > (ZT_MULTICAST_LIKE_EXPIRE * 2))
  1135. _multicastGroupsBehindMe.erase(*mg);
  1136. }
  1137. _announceMulticastGroups(tPtr,false);
  1138. }
  1139. }
  1140. Membership::AddCredentialResult Network::addCredential(void *tPtr,const Address &sentFrom,const Revocation &rev)
  1141. {
  1142. if (rev.networkId() != _id)
  1143. return Membership::ADD_REJECTED;
  1144. Mutex::Lock l1(_memberships_l);
  1145. Membership &m = _memberships[rev.target()];
  1146. const Membership::AddCredentialResult result = m.addCredential(RR,tPtr,_config,rev);
  1147. if ((result == Membership::ADD_ACCEPTED_NEW)&&(rev.fastPropagate())) {
  1148. Address *a = (Address *)0;
  1149. Membership *m = (Membership *)0;
  1150. Hashtable<Address,Membership>::Iterator i(_memberships);
  1151. while (i.next(a,m)) {
  1152. if ((*a != sentFrom)&&(*a != rev.signer())) {
  1153. Packet outp(*a,RR->identity.address(),Packet::VERB_NETWORK_CREDENTIALS);
  1154. outp.append((uint8_t)0x00); // no COM
  1155. outp.append((uint16_t)0); // no capabilities
  1156. outp.append((uint16_t)0); // no tags
  1157. outp.append((uint16_t)1); // one revocation!
  1158. rev.serialize(outp);
  1159. outp.append((uint16_t)0); // no certificates of ownership
  1160. RR->sw->send(tPtr,outp,true);
  1161. }
  1162. }
  1163. }
  1164. return result;
  1165. }
  1166. ZT_VirtualNetworkStatus Network::_status() const
  1167. {
  1168. if (_portError)
  1169. return ZT_NETWORK_STATUS_PORT_ERROR;
  1170. switch(_netconfFailure) {
  1171. case NETCONF_FAILURE_ACCESS_DENIED:
  1172. return ZT_NETWORK_STATUS_ACCESS_DENIED;
  1173. case NETCONF_FAILURE_NOT_FOUND:
  1174. return ZT_NETWORK_STATUS_NOT_FOUND;
  1175. case NETCONF_FAILURE_NONE:
  1176. return ((_config) ? ZT_NETWORK_STATUS_OK : ZT_NETWORK_STATUS_REQUESTING_CONFIGURATION);
  1177. default:
  1178. return ZT_NETWORK_STATUS_PORT_ERROR;
  1179. }
  1180. }
  1181. void Network::_externalConfig(ZT_VirtualNetworkConfig *ec) const
  1182. {
  1183. // assumes _config_l is locked
  1184. ec->nwid = _id;
  1185. ec->mac = _mac.toInt();
  1186. if (_config)
  1187. Utils::scopy(ec->name,sizeof(ec->name),_config.name);
  1188. else ec->name[0] = (char)0;
  1189. ec->status = _status();
  1190. ec->type = (_config) ? (_config.isPrivate() ? ZT_NETWORK_TYPE_PRIVATE : ZT_NETWORK_TYPE_PUBLIC) : ZT_NETWORK_TYPE_PRIVATE;
  1191. ec->mtu = (_config) ? _config.mtu : ZT_DEFAULT_MTU;
  1192. ec->dhcp = 0;
  1193. std::vector<Address> ab(_config.activeBridges());
  1194. ec->bridge = (std::find(ab.begin(),ab.end(),RR->identity.address()) != ab.end()) ? 1 : 0;
  1195. ec->broadcastEnabled = (_config) ? (_config.enableBroadcast() ? 1 : 0) : 0;
  1196. ec->portError = _portError;
  1197. ec->netconfRevision = (_config) ? (unsigned long)_config.revision : 0;
  1198. ec->assignedAddressCount = 0;
  1199. for(unsigned int i=0;i<ZT_MAX_ZT_ASSIGNED_ADDRESSES;++i) {
  1200. if (i < _config.staticIpCount) {
  1201. memcpy(&(ec->assignedAddresses[i]),&(_config.staticIps[i]),sizeof(struct sockaddr_storage));
  1202. ++ec->assignedAddressCount;
  1203. } else {
  1204. memset(&(ec->assignedAddresses[i]),0,sizeof(struct sockaddr_storage));
  1205. }
  1206. }
  1207. ec->routeCount = 0;
  1208. for(unsigned int i=0;i<ZT_MAX_NETWORK_ROUTES;++i) {
  1209. if (i < _config.routeCount) {
  1210. memcpy(&(ec->routes[i]),&(_config.routes[i]),sizeof(ZT_VirtualNetworkRoute));
  1211. ++ec->routeCount;
  1212. } else {
  1213. memset(&(ec->routes[i]),0,sizeof(ZT_VirtualNetworkRoute));
  1214. }
  1215. }
  1216. ec->multicastSubscriptionCount = (unsigned int)_myMulticastGroups.size();
  1217. for(unsigned long i=0;i<(unsigned long)_myMulticastGroups.size();++i) {
  1218. ec->multicastSubscriptions[i].mac = _myMulticastGroups[i].mac().toInt();
  1219. ec->multicastSubscriptions[i].adi = _myMulticastGroups[i].adi();
  1220. }
  1221. }
  1222. void Network::_announceMulticastGroups(void *tPtr,bool force)
  1223. {
  1224. // Assumes _myMulticastGroups_l and _memberships_l are locked
  1225. const int64_t now = RR->node->now();
  1226. const std::vector<MulticastGroup> groups(_allMulticastGroups());
  1227. _announceMulticastGroupsTo(tPtr,controller(),groups);
  1228. {
  1229. Address *a = (Address *)0;
  1230. Membership *m = (Membership *)0;
  1231. Hashtable<Address,Membership>::Iterator i(_memberships);
  1232. while (i.next(a,m)) {
  1233. bool announce = m->multicastLikeGate(now); // force this to be called even if 'force' is true since it updates last push time
  1234. if ((!announce)&&(force))
  1235. announce = true;
  1236. if ((announce)&&(m->isAllowedOnNetwork(_config)))
  1237. _announceMulticastGroupsTo(tPtr,*a,groups);
  1238. }
  1239. }
  1240. }
  1241. void Network::_announceMulticastGroupsTo(void *tPtr,const Address &peer,const std::vector<MulticastGroup> &allMulticastGroups)
  1242. {
  1243. // Assumes _myMulticastGroups_l and _memberships_l are locked
  1244. Packet *const outp = new Packet(peer,RR->identity.address(),Packet::VERB_MULTICAST_LIKE);
  1245. for(std::vector<MulticastGroup>::const_iterator mg(allMulticastGroups.begin());mg!=allMulticastGroups.end();++mg) {
  1246. if ((outp->size() + 24) >= ZT_PROTO_MAX_PACKET_LENGTH) {
  1247. outp->compress();
  1248. RR->sw->send(tPtr,*outp,true);
  1249. outp->reset(peer,RR->identity.address(),Packet::VERB_MULTICAST_LIKE);
  1250. }
  1251. // network ID, MAC, ADI
  1252. outp->append((uint64_t)_id);
  1253. mg->mac().appendTo(*outp);
  1254. outp->append((uint32_t)mg->adi());
  1255. }
  1256. if (outp->size() > ZT_PROTO_MIN_PACKET_LENGTH) {
  1257. outp->compress();
  1258. RR->sw->send(tPtr,*outp,true);
  1259. }
  1260. delete outp;
  1261. }
  1262. std::vector<MulticastGroup> Network::_allMulticastGroups() const
  1263. {
  1264. // Assumes _myMulticastGroups_l is locked
  1265. std::vector<MulticastGroup> mgs;
  1266. mgs.reserve(_myMulticastGroups.size() + _multicastGroupsBehindMe.size() + 1);
  1267. mgs.insert(mgs.end(),_myMulticastGroups.begin(),_myMulticastGroups.end());
  1268. _multicastGroupsBehindMe.appendKeys(mgs);
  1269. if ((_config)&&(_config.enableBroadcast()))
  1270. mgs.push_back(Network::BROADCAST);
  1271. std::sort(mgs.begin(),mgs.end());
  1272. mgs.erase(std::unique(mgs.begin(),mgs.end()),mgs.end());
  1273. return mgs;
  1274. }
  1275. } // namespace ZeroTier