Network.cpp 51 KB

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