Network.cpp 50 KB

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