Network.cpp 65 KB

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