Network.cpp 50 KB

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