Network.cpp 66 KB

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