Network.cpp 53 KB

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