Network.cpp 51 KB

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