2
0

Network.cpp 52 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311
  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. // Uncomment to make the rules engine dump trace info to stdout
  36. //#define ZT_RULES_ENGINE_DEBUGGING 1
  37. namespace ZeroTier {
  38. namespace {
  39. #ifdef ZT_RULES_ENGINE_DEBUGGING
  40. #define FILTER_TRACE(f,...) { Utils::snprintf(dpbuf,sizeof(dpbuf),f,##__VA_ARGS__); dlog.push_back(std::string(dpbuf)); }
  41. static const char *_rtn(const ZT_VirtualNetworkRuleType rt)
  42. {
  43. switch(rt) {
  44. case ZT_NETWORK_RULE_ACTION_DROP: return "ACTION_DROP";
  45. case ZT_NETWORK_RULE_ACTION_ACCEPT: return "ACTION_ACCEPT";
  46. case ZT_NETWORK_RULE_ACTION_TEE: return "ACTION_TEE";
  47. case ZT_NETWORK_RULE_ACTION_REDIRECT: return "ACTION_REDIRECT";
  48. case ZT_NETWORK_RULE_ACTION_DEBUG_LOG: return "ACTION_DEBUG_LOG";
  49. case ZT_NETWORK_RULE_MATCH_SOURCE_ZEROTIER_ADDRESS: return "MATCH_SOURCE_ZEROTIER_ADDRESS";
  50. case ZT_NETWORK_RULE_MATCH_DEST_ZEROTIER_ADDRESS: return "MATCH_DEST_ZEROTIER_ADDRESS";
  51. case ZT_NETWORK_RULE_MATCH_VLAN_ID: return "MATCH_VLAN_ID";
  52. case ZT_NETWORK_RULE_MATCH_VLAN_PCP: return "MATCH_VLAN_PCP";
  53. case ZT_NETWORK_RULE_MATCH_VLAN_DEI: return "MATCH_VLAN_DEI";
  54. case ZT_NETWORK_RULE_MATCH_ETHERTYPE: return "MATCH_ETHERTYPE";
  55. case ZT_NETWORK_RULE_MATCH_MAC_SOURCE: return "MATCH_MAC_SOURCE";
  56. case ZT_NETWORK_RULE_MATCH_MAC_DEST: return "MATCH_MAC_DEST";
  57. case ZT_NETWORK_RULE_MATCH_IPV4_SOURCE: return "MATCH_IPV4_SOURCE";
  58. case ZT_NETWORK_RULE_MATCH_IPV4_DEST: return "MATCH_IPV4_DEST";
  59. case ZT_NETWORK_RULE_MATCH_IPV6_SOURCE: return "MATCH_IPV6_SOURCE";
  60. case ZT_NETWORK_RULE_MATCH_IPV6_DEST: return "MATCH_IPV6_DEST";
  61. case ZT_NETWORK_RULE_MATCH_IP_TOS: return "MATCH_IP_TOS";
  62. case ZT_NETWORK_RULE_MATCH_IP_PROTOCOL: return "MATCH_IP_PROTOCOL";
  63. case ZT_NETWORK_RULE_MATCH_ICMP: return "MATCH_ICMP";
  64. case ZT_NETWORK_RULE_MATCH_IP_SOURCE_PORT_RANGE: return "MATCH_IP_SOURCE_PORT_RANGE";
  65. case ZT_NETWORK_RULE_MATCH_IP_DEST_PORT_RANGE: return "MATCH_IP_DEST_PORT_RANGE";
  66. case ZT_NETWORK_RULE_MATCH_CHARACTERISTICS: return "MATCH_CHARACTERISTICS";
  67. case ZT_NETWORK_RULE_MATCH_FRAME_SIZE_RANGE: return "MATCH_FRAME_SIZE_RANGE";
  68. case ZT_NETWORK_RULE_MATCH_TAGS_DIFFERENCE: return "MATCH_TAGS_DIFFERENCE";
  69. case ZT_NETWORK_RULE_MATCH_TAGS_BITWISE_AND: return "MATCH_TAGS_BITWISE_AND";
  70. case ZT_NETWORK_RULE_MATCH_TAGS_BITWISE_OR: return "MATCH_TAGS_BITWISE_OR";
  71. case ZT_NETWORK_RULE_MATCH_TAGS_BITWISE_XOR: return "MATCH_TAGS_BITWISE_XOR";
  72. default: return "???";
  73. }
  74. }
  75. 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)
  76. {
  77. static volatile unsigned long cnt = 0;
  78. printf("%.6lu %c %s %s frameLen=%u etherType=%u" ZT_EOL_S,
  79. cnt++,
  80. ((thisSetMatches) ? 'Y' : '.'),
  81. ruleName,
  82. ((inbound) ? "INBOUND" : "OUTBOUND"),
  83. frameLen,
  84. etherType
  85. );
  86. for(std::vector<std::string>::const_iterator m(dlog.begin());m!=dlog.end();++m)
  87. printf(" | %s" ZT_EOL_S,m->c_str());
  88. printf(" + %c %s->%s %.2x:%.2x:%.2x:%.2x:%.2x:%.2x->%.2x:%.2x:%.2x:%.2x:%.2x:%.2x" ZT_EOL_S,
  89. ((thisSetMatches) ? 'Y' : '.'),
  90. ztSource.toString().c_str(),
  91. ztDest.toString().c_str(),
  92. (unsigned int)macSource[0],
  93. (unsigned int)macSource[1],
  94. (unsigned int)macSource[2],
  95. (unsigned int)macSource[3],
  96. (unsigned int)macSource[4],
  97. (unsigned int)macSource[5],
  98. (unsigned int)macDest[0],
  99. (unsigned int)macDest[1],
  100. (unsigned int)macDest[2],
  101. (unsigned int)macDest[3],
  102. (unsigned int)macDest[4],
  103. (unsigned int)macDest[5]
  104. );
  105. if (msg)
  106. printf(" + (%s)" ZT_EOL_S,msg);
  107. }
  108. #else
  109. #define FILTER_TRACE(f,...) {}
  110. #endif // ZT_RULES_ENGINE_DEBUGGING
  111. // Returns true if packet appears valid; pos and proto will be set
  112. static bool _ipv6GetPayload(const uint8_t *frameData,unsigned int frameLen,unsigned int &pos,unsigned int &proto)
  113. {
  114. if (frameLen < 40)
  115. return false;
  116. pos = 40;
  117. proto = frameData[6];
  118. while (pos <= frameLen) {
  119. switch(proto) {
  120. case 0: // hop-by-hop options
  121. case 43: // routing
  122. case 60: // destination options
  123. case 135: // mobility options
  124. if ((pos + 8) > frameLen)
  125. return false; // invalid!
  126. proto = frameData[pos];
  127. pos += ((unsigned int)frameData[pos + 1] * 8) + 8;
  128. break;
  129. //case 44: // fragment -- we currently can't parse these and they are deprecated in IPv6 anyway
  130. //case 50:
  131. //case 51: // IPSec ESP and AH -- we have to stop here since this is encrypted stuff
  132. default:
  133. return true;
  134. }
  135. }
  136. return false; // overflow == invalid
  137. }
  138. enum _doZtFilterResult
  139. {
  140. DOZTFILTER_NO_MATCH,
  141. DOZTFILTER_DROP,
  142. DOZTFILTER_REDIRECT,
  143. DOZTFILTER_ACCEPT,
  144. DOZTFILTER_SUPER_ACCEPT
  145. };
  146. static _doZtFilterResult _doZtFilter(
  147. const RuntimeEnvironment *RR,
  148. const NetworkConfig &nconf,
  149. const bool inbound,
  150. const Address &ztSource,
  151. Address &ztDest, // MUTABLE
  152. const MAC &macSource,
  153. const MAC &macDest,
  154. const uint8_t *const frameData,
  155. const unsigned int frameLen,
  156. const unsigned int etherType,
  157. const unsigned int vlanId,
  158. const ZT_VirtualNetworkRule *rules,
  159. const unsigned int ruleCount,
  160. const Tag *localTags,
  161. const unsigned int localTagCount,
  162. const uint32_t *const remoteTagIds,
  163. const uint32_t *const remoteTagValues,
  164. const unsigned int remoteTagCount,
  165. Address &cc, // MUTABLE
  166. unsigned int &ccLength) // MUTABLE
  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. // The default match state for each set of entries starts as 'true' since an
  173. // ACTION with no MATCH entries preceding it is always taken.
  174. uint8_t thisSetMatches = 1;
  175. for(unsigned int rn=0;rn<ruleCount;++rn) {
  176. const ZT_VirtualNetworkRuleType rt = (ZT_VirtualNetworkRuleType)(rules[rn].t & 0x7f);
  177. // First check if this is an ACTION
  178. if ((unsigned int)rt <= (unsigned int)ZT_NETWORK_RULE_ACTION__MAX_ID) {
  179. if (thisSetMatches) {
  180. switch(rt) {
  181. case ZT_NETWORK_RULE_ACTION_DROP:
  182. #ifdef ZT_RULES_ENGINE_DEBUGGING
  183. _dumpFilterTrace("ACTION_DROP",thisSetMatches,inbound,ztSource,ztDest,macSource,macDest,dlog,frameLen,etherType,(const char *)0);
  184. #endif // ZT_RULES_ENGINE_DEBUGGING
  185. return DOZTFILTER_DROP;
  186. case ZT_NETWORK_RULE_ACTION_ACCEPT:
  187. #ifdef ZT_RULES_ENGINE_DEBUGGING
  188. _dumpFilterTrace("ACTION_ACCEPT",thisSetMatches,inbound,ztSource,ztDest,macSource,macDest,dlog,frameLen,etherType,(const char *)0);
  189. #endif // ZT_RULES_ENGINE_DEBUGGING
  190. return DOZTFILTER_ACCEPT; // match, accept packet
  191. // These are initially handled together since preliminary logic is common
  192. case ZT_NETWORK_RULE_ACTION_TEE:
  193. case ZT_NETWORK_RULE_ACTION_REDIRECT: {
  194. const Address fwdAddr(rules[rn].v.fwd.address);
  195. if (fwdAddr == ztSource) {
  196. #ifdef ZT_RULES_ENGINE_DEBUGGING
  197. _dumpFilterTrace(_rtn(rt),thisSetMatches,inbound,ztSource,ztDest,macSource,macDest,dlog,frameLen,etherType,"skipped as no-op since source is target");
  198. dlog.clear();
  199. #endif // ZT_RULES_ENGINE_DEBUGGING
  200. } else if (fwdAddr == RR->identity.address()) {
  201. if (inbound) {
  202. #ifdef ZT_RULES_ENGINE_DEBUGGING
  203. _dumpFilterTrace(_rtn(rt),thisSetMatches,inbound,ztSource,ztDest,macSource,macDest,dlog,frameLen,etherType,"interpreted as super-ACCEPT on inbound since we are target");
  204. #endif // ZT_RULES_ENGINE_DEBUGGING
  205. return DOZTFILTER_SUPER_ACCEPT;
  206. } else {
  207. #ifdef ZT_RULES_ENGINE_DEBUGGING
  208. _dumpFilterTrace(_rtn(rt),thisSetMatches,inbound,ztSource,ztDest,macSource,macDest,dlog,frameLen,etherType,"skipped as no-op on outbound since we are target");
  209. dlog.clear();
  210. #endif // ZT_RULES_ENGINE_DEBUGGING
  211. }
  212. } else if (fwdAddr == ztDest) {
  213. #ifdef ZT_RULES_ENGINE_DEBUGGING
  214. _dumpFilterTrace(_rtn(rt),thisSetMatches,inbound,ztSource,ztDest,macSource,macDest,dlog,frameLen,etherType,"skipped as no-op because destination is already target");
  215. dlog.clear();
  216. #endif // ZT_RULES_ENGINE_DEBUGGING
  217. } else {
  218. if (rt == ZT_NETWORK_RULE_ACTION_REDIRECT) {
  219. #ifdef ZT_RULES_ENGINE_DEBUGGING
  220. _dumpFilterTrace("ACTION_REDIRECT",thisSetMatches,inbound,ztSource,ztDest,macSource,macDest,dlog,frameLen,etherType,(const char *)0);
  221. #endif // ZT_RULES_ENGINE_DEBUGGING
  222. ztDest = fwdAddr;
  223. return DOZTFILTER_REDIRECT;
  224. } else {
  225. #ifdef ZT_RULES_ENGINE_DEBUGGING
  226. _dumpFilterTrace("ACTION_TEE",thisSetMatches,inbound,ztSource,ztDest,macSource,macDest,dlog,frameLen,etherType,(const char *)0);
  227. dlog.clear();
  228. #endif // ZT_RULES_ENGINE_DEBUGGING
  229. cc = fwdAddr;
  230. ccLength = (rules[rn].v.fwd.length != 0) ? ((frameLen < (unsigned int)rules[rn].v.fwd.length) ? frameLen : (unsigned int)rules[rn].v.fwd.length) : frameLen;
  231. }
  232. }
  233. } continue;
  234. // This is a no-op that exists for use with rules engine tracing and isn't for use in production
  235. case ZT_NETWORK_RULE_ACTION_DEBUG_LOG: // a no-op target specifically for debugging purposes
  236. #ifdef ZT_RULES_ENGINE_DEBUGGING
  237. _dumpFilterTrace("ACTION_DEBUG_LOG",thisSetMatches,inbound,ztSource,ztDest,macSource,macDest,dlog,frameLen,etherType,(const char *)0);
  238. dlog.clear();
  239. #endif // ZT_RULES_ENGINE_DEBUGGING
  240. continue;
  241. // Unrecognized ACTIONs are ignored as no-ops
  242. default:
  243. #ifdef ZT_RULES_ENGINE_DEBUGGING
  244. _dumpFilterTrace(_rtn(rt),thisSetMatches,inbound,ztSource,ztDest,macSource,macDest,dlog,frameLen,etherType,(const char *)0);
  245. dlog.clear();
  246. #endif // ZT_RULES_ENGINE_DEBUGGING
  247. continue;
  248. }
  249. } else {
  250. #ifdef ZT_RULES_ENGINE_DEBUGGING
  251. _dumpFilterTrace(_rtn(rt),thisSetMatches,inbound,ztSource,ztDest,macSource,macDest,dlog,frameLen,etherType,(const char *)0);
  252. dlog.clear();
  253. #endif // ZT_RULES_ENGINE_DEBUGGING
  254. thisSetMatches = 1; // reset to default true for next batch of entries
  255. continue;
  256. }
  257. }
  258. // Circuit breaker: skip further MATCH entries up to next ACTION if match state is false
  259. if (!thisSetMatches)
  260. continue;
  261. // If this was not an ACTION evaluate next MATCH and update thisSetMatches with (AND [result])
  262. uint8_t thisRuleMatches = 0;
  263. switch(rt) {
  264. case ZT_NETWORK_RULE_MATCH_SOURCE_ZEROTIER_ADDRESS:
  265. thisRuleMatches = (uint8_t)(rules[rn].v.zt == ztSource.toInt());
  266. 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);
  267. break;
  268. case ZT_NETWORK_RULE_MATCH_DEST_ZEROTIER_ADDRESS:
  269. thisRuleMatches = (uint8_t)(rules[rn].v.zt == ztDest.toInt());
  270. 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);
  271. break;
  272. case ZT_NETWORK_RULE_MATCH_VLAN_ID:
  273. thisRuleMatches = (uint8_t)(rules[rn].v.vlanId == (uint16_t)vlanId);
  274. 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);
  275. break;
  276. case ZT_NETWORK_RULE_MATCH_VLAN_PCP:
  277. // NOT SUPPORTED YET
  278. thisRuleMatches = (uint8_t)(rules[rn].v.vlanPcp == 0);
  279. 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);
  280. break;
  281. case ZT_NETWORK_RULE_MATCH_VLAN_DEI:
  282. // NOT SUPPORTED YET
  283. thisRuleMatches = (uint8_t)(rules[rn].v.vlanDei == 0);
  284. 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);
  285. break;
  286. case ZT_NETWORK_RULE_MATCH_ETHERTYPE:
  287. thisRuleMatches = (uint8_t)(rules[rn].v.etherType == (uint16_t)etherType);
  288. 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);
  289. break;
  290. case ZT_NETWORK_RULE_MATCH_MAC_SOURCE:
  291. thisRuleMatches = (uint8_t)(MAC(rules[rn].v.mac,6) == macSource);
  292. 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);
  293. break;
  294. case ZT_NETWORK_RULE_MATCH_MAC_DEST:
  295. thisRuleMatches = (uint8_t)(MAC(rules[rn].v.mac,6) == macDest);
  296. 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);
  297. break;
  298. case ZT_NETWORK_RULE_MATCH_IPV4_SOURCE:
  299. if ((etherType == ZT_ETHERTYPE_IPV4)&&(frameLen >= 20)) {
  300. 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)));
  301. 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);
  302. } else {
  303. thisRuleMatches = 0;
  304. FILTER_TRACE("%u %s %c [frame not IPv4] -> 0",rn,_rtn(rt),(((rules[rn].t & 0x80) != 0) ? '!' : '='));
  305. }
  306. break;
  307. case ZT_NETWORK_RULE_MATCH_IPV4_DEST:
  308. if ((etherType == ZT_ETHERTYPE_IPV4)&&(frameLen >= 20)) {
  309. 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)));
  310. 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);
  311. } else {
  312. thisRuleMatches = 0;
  313. FILTER_TRACE("%u %s %c [frame not IPv4] -> 0",rn,_rtn(rt),(((rules[rn].t & 0x80) != 0) ? '!' : '='));
  314. }
  315. break;
  316. case ZT_NETWORK_RULE_MATCH_IPV6_SOURCE:
  317. if ((etherType == ZT_ETHERTYPE_IPV6)&&(frameLen >= 40)) {
  318. 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)));
  319. 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);
  320. } else {
  321. thisRuleMatches = 0;
  322. FILTER_TRACE("%u %s %c [frame not IPv6] -> 0",rn,_rtn(rt),(((rules[rn].t & 0x80) != 0) ? '!' : '='));
  323. }
  324. break;
  325. case ZT_NETWORK_RULE_MATCH_IPV6_DEST:
  326. if ((etherType == ZT_ETHERTYPE_IPV6)&&(frameLen >= 40)) {
  327. 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)));
  328. 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);
  329. } else {
  330. thisRuleMatches = 0;
  331. FILTER_TRACE("%u %s %c [frame not IPv6] -> 0",rn,_rtn(rt),(((rules[rn].t & 0x80) != 0) ? '!' : '='));
  332. }
  333. break;
  334. case ZT_NETWORK_RULE_MATCH_IP_TOS:
  335. if ((etherType == ZT_ETHERTYPE_IPV4)&&(frameLen >= 20)) {
  336. thisRuleMatches = (uint8_t)(rules[rn].v.ipTos == ((frameData[1] & 0xfc) >> 2));
  337. FILTER_TRACE("%u %s %c (IPv4) %u==%u -> %u",rn,_rtn(rt),(((rules[rn].t & 0x80) != 0) ? '!' : '='),(unsigned int)rules[rn].v.ipTos,(unsigned int)((frameData[1] & 0xfc) >> 2),(unsigned int)thisRuleMatches);
  338. } else if ((etherType == ZT_ETHERTYPE_IPV6)&&(frameLen >= 40)) {
  339. const uint8_t trafficClass = ((frameData[0] << 4) & 0xf0) | ((frameData[1] >> 4) & 0x0f);
  340. thisRuleMatches = (uint8_t)(rules[rn].v.ipTos == ((trafficClass & 0xfc) >> 2));
  341. FILTER_TRACE("%u %s %c (IPv6) %u==%u -> %u",rn,_rtn(rt),(((rules[rn].t & 0x80) != 0) ? '!' : '='),(unsigned int)rules[rn].v.ipTos,(unsigned int)((trafficClass & 0xfc) >> 2),(unsigned int)thisRuleMatches);
  342. } else {
  343. thisRuleMatches = 0;
  344. FILTER_TRACE("%u %s %c [frame not IP] -> 0",rn,_rtn(rt),(((rules[rn].t & 0x80) != 0) ? '!' : '='));
  345. }
  346. break;
  347. case ZT_NETWORK_RULE_MATCH_IP_PROTOCOL:
  348. if ((etherType == ZT_ETHERTYPE_IPV4)&&(frameLen >= 20)) {
  349. thisRuleMatches = (uint8_t)(rules[rn].v.ipProtocol == frameData[9]);
  350. 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);
  351. } else if (etherType == ZT_ETHERTYPE_IPV6) {
  352. unsigned int pos = 0,proto = 0;
  353. if (_ipv6GetPayload(frameData,frameLen,pos,proto)) {
  354. thisRuleMatches = (uint8_t)(rules[rn].v.ipProtocol == (uint8_t)proto);
  355. 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);
  356. } else {
  357. thisRuleMatches = 0;
  358. FILTER_TRACE("%u %s %c [invalid IPv6] -> 0",rn,_rtn(rt),(((rules[rn].t & 0x80) != 0) ? '!' : '='));
  359. }
  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_ICMP:
  366. if ((etherType == ZT_ETHERTYPE_IPV4)&&(frameLen >= 20)) {
  367. if (frameData[9] == 0x01) {
  368. const unsigned int ihl = (frameData[0] & 0xf) * 32;
  369. if (frameLen >= (ihl + 2)) {
  370. if (rules[rn].v.icmp.type == frameData[ihl]) {
  371. if ((rules[rn].v.icmp.flags & 0x01) != 0) {
  372. thisRuleMatches = (uint8_t)(frameData[ihl+1] == rules[rn].v.icmp.code);
  373. } else {
  374. thisRuleMatches = 1;
  375. }
  376. } else {
  377. thisRuleMatches = 0;
  378. }
  379. 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);
  380. } else {
  381. thisRuleMatches = 0;
  382. FILTER_TRACE("%u %s %c [IPv4 frame invalid] -> 0",rn,_rtn(rt),(((rules[rn].t & 0x80) != 0) ? '!' : '='));
  383. }
  384. } else {
  385. thisRuleMatches = 0;
  386. FILTER_TRACE("%u %s %c [frame not ICMP] -> 0",rn,_rtn(rt),(((rules[rn].t & 0x80) != 0) ? '!' : '='));
  387. }
  388. } else if (etherType == ZT_ETHERTYPE_IPV6) {
  389. unsigned int pos = 0,proto = 0;
  390. if (_ipv6GetPayload(frameData,frameLen,pos,proto)) {
  391. if ((proto == 0x3a)&&(frameLen >= (pos+2))) {
  392. if (rules[rn].v.icmp.type == frameData[pos]) {
  393. if ((rules[rn].v.icmp.flags & 0x01) != 0) {
  394. thisRuleMatches = (uint8_t)(frameData[pos+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[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);
  402. } else {
  403. thisRuleMatches = 0;
  404. FILTER_TRACE("%u %s %c [frame not ICMPv6] -> 0",rn,_rtn(rt),(((rules[rn].t & 0x80) != 0) ? '!' : '='));
  405. }
  406. } else {
  407. thisRuleMatches = 0;
  408. FILTER_TRACE("%u %s %c [invalid IPv6] -> 0",rn,_rtn(rt),(((rules[rn].t & 0x80) != 0) ? '!' : '='));
  409. }
  410. } else {
  411. thisRuleMatches = 0;
  412. FILTER_TRACE("%u %s %c [frame not IP] -> 0",rn,_rtn(rt),(((rules[rn].t & 0x80) != 0) ? '!' : '='));
  413. }
  414. break;
  415. break;
  416. case ZT_NETWORK_RULE_MATCH_IP_SOURCE_PORT_RANGE:
  417. case ZT_NETWORK_RULE_MATCH_IP_DEST_PORT_RANGE:
  418. if ((etherType == ZT_ETHERTYPE_IPV4)&&(frameLen >= 20)) {
  419. const unsigned int headerLen = 4 * (frameData[0] & 0xf);
  420. int p = -1;
  421. switch(frameData[9]) { // IP protocol number
  422. // All these start with 16-bit source and destination port in that order
  423. case 0x06: // TCP
  424. case 0x11: // UDP
  425. case 0x84: // SCTP
  426. case 0x88: // UDPLite
  427. if (frameLen > (headerLen + 4)) {
  428. unsigned int pos = headerLen + ((rt == ZT_NETWORK_RULE_MATCH_IP_DEST_PORT_RANGE) ? 2 : 0);
  429. p = (int)frameData[pos++] << 8;
  430. p |= (int)frameData[pos];
  431. }
  432. break;
  433. }
  434. thisRuleMatches = (p >= 0) ? (uint8_t)((p >= (int)rules[rn].v.port[0])&&(p <= (int)rules[rn].v.port[1])) : (uint8_t)0;
  435. 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);
  436. } else if (etherType == ZT_ETHERTYPE_IPV6) {
  437. unsigned int pos = 0,proto = 0;
  438. if (_ipv6GetPayload(frameData,frameLen,pos,proto)) {
  439. int p = -1;
  440. switch(proto) { // IP protocol number
  441. // All these start with 16-bit source and destination port in that order
  442. case 0x06: // TCP
  443. case 0x11: // UDP
  444. case 0x84: // SCTP
  445. case 0x88: // UDPLite
  446. if (frameLen > (pos + 4)) {
  447. if (rt == ZT_NETWORK_RULE_MATCH_IP_DEST_PORT_RANGE) pos += 2;
  448. p = (int)frameData[pos++] << 8;
  449. p |= (int)frameData[pos];
  450. }
  451. break;
  452. }
  453. thisRuleMatches = (p > 0) ? (uint8_t)((p >= (int)rules[rn].v.port[0])&&(p <= (int)rules[rn].v.port[1])) : (uint8_t)0;
  454. 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);
  455. } else {
  456. thisRuleMatches = 0;
  457. FILTER_TRACE("%u %s %c [invalid IPv6] -> 0",rn,_rtn(rt),(((rules[rn].t & 0x80) != 0) ? '!' : '='));
  458. }
  459. } else {
  460. thisRuleMatches = 0;
  461. FILTER_TRACE("%u %s %c [frame not IP] -> 0",rn,_rtn(rt),(((rules[rn].t & 0x80) != 0) ? '!' : '='));
  462. }
  463. break;
  464. case ZT_NETWORK_RULE_MATCH_CHARACTERISTICS: {
  465. uint64_t cf = (inbound) ? ZT_RULE_PACKET_CHARACTERISTICS_INBOUND : 0ULL;
  466. if (macDest.isMulticast()) cf |= ZT_RULE_PACKET_CHARACTERISTICS_MULTICAST;
  467. if (macDest.isBroadcast()) cf |= ZT_RULE_PACKET_CHARACTERISTICS_BROADCAST;
  468. if ((etherType == ZT_ETHERTYPE_IPV4)&&(frameLen >= 20)&&(frameData[9] == 0x06)) {
  469. const unsigned int headerLen = 4 * (frameData[0] & 0xf);
  470. cf |= (uint64_t)frameData[headerLen + 13];
  471. cf |= (((uint64_t)(frameData[headerLen + 12] & 0x0f)) << 8);
  472. } else if (etherType == ZT_ETHERTYPE_IPV6) {
  473. unsigned int pos = 0,proto = 0;
  474. if (_ipv6GetPayload(frameData,frameLen,pos,proto)) {
  475. if ((proto == 0x06)&&(frameLen > (pos + 14))) {
  476. cf |= (uint64_t)frameData[pos + 13];
  477. cf |= (((uint64_t)(frameData[pos + 12] & 0x0f)) << 8);
  478. }
  479. }
  480. }
  481. thisRuleMatches = (uint8_t)((cf & rules[rn].v.characteristics[0]) == rules[rn].v.characteristics[1]);
  482. FILTER_TRACE("%u %s %c (%.16llx & %.16llx)==%.16llx -> %u",rn,_rtn(rt),(((rules[rn].t & 0x80) != 0) ? '!' : '='),cf,rules[rn].v.characteristics[0],rules[rn].v.characteristics[1],(unsigned int)thisRuleMatches);
  483. } break;
  484. case ZT_NETWORK_RULE_MATCH_FRAME_SIZE_RANGE:
  485. thisRuleMatches = (uint8_t)((frameLen >= (unsigned int)rules[rn].v.frameSize[0])&&(frameLen <= (unsigned int)rules[rn].v.frameSize[1]));
  486. 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);
  487. break;
  488. case ZT_NETWORK_RULE_MATCH_TAGS_DIFFERENCE:
  489. case ZT_NETWORK_RULE_MATCH_TAGS_BITWISE_AND:
  490. case ZT_NETWORK_RULE_MATCH_TAGS_BITWISE_OR:
  491. case ZT_NETWORK_RULE_MATCH_TAGS_BITWISE_XOR: {
  492. const Tag *lt = (const Tag *)0;
  493. for(unsigned int i=0;i<localTagCount;++i) {
  494. if (rules[rn].v.tag.id == localTags[i].id()) {
  495. lt = &(localTags[i]);
  496. break;
  497. }
  498. }
  499. if (!lt) {
  500. thisRuleMatches = 0;
  501. 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);
  502. } else {
  503. const uint32_t *rtv = (const uint32_t *)0;
  504. for(unsigned int i=0;i<remoteTagCount;++i) {
  505. if (rules[rn].v.tag.id == remoteTagIds[i]) {
  506. rtv = &(remoteTagValues[i]);
  507. break;
  508. }
  509. }
  510. if (!rtv) {
  511. if (inbound) {
  512. thisRuleMatches = 0;
  513. 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);
  514. } else {
  515. thisRuleMatches = 1;
  516. FILTER_TRACE("%u %s %c remote tag %u not found -> 1 (outbound side is not strict)",rn,_rtn(rt),(((rules[rn].t & 0x80) != 0) ? '!' : '='),(unsigned int)rules[rn].v.tag.id);
  517. }
  518. } else {
  519. if (rt == ZT_NETWORK_RULE_MATCH_TAGS_DIFFERENCE) {
  520. const uint32_t diff = (lt->value() > *rtv) ? (lt->value() - *rtv) : (*rtv - lt->value());
  521. thisRuleMatches = (uint8_t)(diff <= rules[rn].v.tag.value);
  522. 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,lt->value(),*rtv,diff,(unsigned int)rules[rn].v.tag.value,thisRuleMatches);
  523. } else if (rt == ZT_NETWORK_RULE_MATCH_TAGS_BITWISE_AND) {
  524. thisRuleMatches = (uint8_t)((lt->value() & *rtv) == rules[rn].v.tag.value);
  525. 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,lt->value(),*rtv,(unsigned int)rules[rn].v.tag.value,(unsigned int)thisRuleMatches);
  526. } else if (rt == ZT_NETWORK_RULE_MATCH_TAGS_BITWISE_OR) {
  527. thisRuleMatches = (uint8_t)((lt->value() | *rtv) == rules[rn].v.tag.value);
  528. 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,lt->value(),*rtv,(unsigned int)rules[rn].v.tag.value,(unsigned int)thisRuleMatches);
  529. } else if (rt == ZT_NETWORK_RULE_MATCH_TAGS_BITWISE_XOR) {
  530. thisRuleMatches = (uint8_t)((lt->value() ^ *rtv) == rules[rn].v.tag.value);
  531. 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,lt->value(),*rtv,(unsigned int)rules[rn].v.tag.value,(unsigned int)thisRuleMatches);
  532. } else { // sanity check, can't really happen
  533. thisRuleMatches = 0;
  534. }
  535. }
  536. }
  537. } break;
  538. // The result of an unsupported MATCH is configurable at the network
  539. // level via a flag.
  540. default:
  541. thisRuleMatches = (uint8_t)((nconf.flags & ZT_NETWORKCONFIG_FLAG_RULES_RESULT_OF_UNSUPPORTED_MATCH) != 0);
  542. break;
  543. }
  544. // State of equals state AND result of last MATCH (possibly NOTed depending on bit 0x80)
  545. thisSetMatches &= (thisRuleMatches ^ ((rules[rn].t >> 7) & 1));
  546. }
  547. return DOZTFILTER_NO_MATCH;
  548. }
  549. } // anonymous namespace
  550. const ZeroTier::MulticastGroup Network::BROADCAST(ZeroTier::MAC(0xffffffffffffULL),0);
  551. Network::Network(const RuntimeEnvironment *renv,uint64_t nwid,void *uptr) :
  552. RR(renv),
  553. _uPtr(uptr),
  554. _id(nwid),
  555. _mac(renv->identity.address(),nwid),
  556. _portInitialized(false),
  557. _inboundConfigPacketId(0),
  558. _lastConfigUpdate(0),
  559. _lastRequestedConfiguration(0),
  560. _destroyed(false),
  561. _netconfFailure(NETCONF_FAILURE_NONE),
  562. _portError(0)
  563. {
  564. char confn[128];
  565. Utils::snprintf(confn,sizeof(confn),"networks.d/%.16llx.conf",_id);
  566. bool gotConf = false;
  567. Dictionary<ZT_NETWORKCONFIG_DICT_CAPACITY> *dconf = new Dictionary<ZT_NETWORKCONFIG_DICT_CAPACITY>();
  568. NetworkConfig *nconf = new NetworkConfig();
  569. try {
  570. std::string conf(RR->node->dataStoreGet(confn));
  571. if (conf.length()) {
  572. dconf->load(conf.c_str());
  573. if (nconf->fromDictionary(*dconf)) {
  574. this->setConfiguration(*nconf,false);
  575. _lastConfigUpdate = 0; // we still want to re-request a new config from the network
  576. gotConf = true;
  577. }
  578. }
  579. } catch ( ... ) {} // ignore invalids, we'll re-request
  580. delete nconf;
  581. delete dconf;
  582. if (!gotConf) {
  583. // Save a one-byte CR to persist membership while we request a real netconf
  584. RR->node->dataStorePut(confn,"\n",1,false);
  585. }
  586. if (!_portInitialized) {
  587. ZT_VirtualNetworkConfig ctmp;
  588. _externalConfig(&ctmp);
  589. _portError = RR->node->configureVirtualNetworkPort(_id,&_uPtr,ZT_VIRTUAL_NETWORK_CONFIG_OPERATION_UP,&ctmp);
  590. _portInitialized = true;
  591. }
  592. }
  593. Network::~Network()
  594. {
  595. ZT_VirtualNetworkConfig ctmp;
  596. _externalConfig(&ctmp);
  597. char n[128];
  598. if (_destroyed) {
  599. RR->node->configureVirtualNetworkPort(_id,&_uPtr,ZT_VIRTUAL_NETWORK_CONFIG_OPERATION_DESTROY,&ctmp);
  600. Utils::snprintf(n,sizeof(n),"networks.d/%.16llx.conf",_id);
  601. RR->node->dataStoreDelete(n);
  602. } else {
  603. RR->node->configureVirtualNetworkPort(_id,&_uPtr,ZT_VIRTUAL_NETWORK_CONFIG_OPERATION_DOWN,&ctmp);
  604. }
  605. }
  606. bool Network::filterOutgoingPacket(
  607. const bool noTee,
  608. const Address &ztSource,
  609. const Address &ztDest,
  610. const MAC &macSource,
  611. const MAC &macDest,
  612. const uint8_t *frameData,
  613. const unsigned int frameLen,
  614. const unsigned int etherType,
  615. const unsigned int vlanId)
  616. {
  617. uint32_t remoteTagIds[ZT_MAX_NETWORK_TAGS];
  618. uint32_t remoteTagValues[ZT_MAX_NETWORK_TAGS];
  619. Address ztDest2(ztDest);
  620. Address cc;
  621. const Capability *relevantCap = (const Capability *)0;
  622. unsigned int ccLength = 0;
  623. bool accept = false;
  624. Mutex::Lock _l(_lock);
  625. Membership &m = _memberships[ztDest];
  626. const unsigned int remoteTagCount = m.getAllTags(_config,remoteTagIds,remoteTagValues,ZT_MAX_NETWORK_TAGS);
  627. switch(_doZtFilter(RR,_config,false,ztSource,ztDest2,macSource,macDest,frameData,frameLen,etherType,vlanId,_config.rules,_config.ruleCount,_config.tags,_config.tagCount,remoteTagIds,remoteTagValues,remoteTagCount,cc,ccLength)) {
  628. case DOZTFILTER_NO_MATCH:
  629. for(unsigned int c=0;c<_config.capabilityCount;++c) {
  630. ztDest2 = ztDest; // sanity check
  631. Address cc2;
  632. unsigned int ccLength2 = 0;
  633. switch (_doZtFilter(RR,_config,false,ztSource,ztDest2,macSource,macDest,frameData,frameLen,etherType,vlanId,_config.capabilities[c].rules(),_config.capabilities[c].ruleCount(),_config.tags,_config.tagCount,remoteTagIds,remoteTagValues,remoteTagCount,cc2,ccLength2)) {
  634. case DOZTFILTER_NO_MATCH:
  635. case DOZTFILTER_DROP: // explicit DROP in a capability just terminates its evaluation and is an anti-pattern
  636. break;
  637. case DOZTFILTER_REDIRECT: // interpreted as ACCEPT but ztDest2 will have been changed in _doZtFilter()
  638. case DOZTFILTER_ACCEPT:
  639. case DOZTFILTER_SUPER_ACCEPT: // no difference in behavior on outbound side
  640. relevantCap = &(_config.capabilities[c]);
  641. accept = true;
  642. if ((!noTee)&&(cc2)) {
  643. _memberships[cc2].sendCredentialsIfNeeded(RR,RR->node->now(),cc2,_config,relevantCap);
  644. Packet outp(cc2,RR->identity.address(),Packet::VERB_EXT_FRAME);
  645. outp.append(_id);
  646. outp.append((uint8_t)0x02); // TEE/REDIRECT from outbound side: 0x02
  647. macDest.appendTo(outp);
  648. macSource.appendTo(outp);
  649. outp.append((uint16_t)etherType);
  650. outp.append(frameData,ccLength2);
  651. outp.compress();
  652. RR->sw->send(outp,true);
  653. }
  654. break;
  655. }
  656. if (accept)
  657. break;
  658. }
  659. break;
  660. case DOZTFILTER_DROP:
  661. return false;
  662. case DOZTFILTER_REDIRECT: // interpreted as ACCEPT but ztDest2 will have been changed in _doZtFilter()
  663. case DOZTFILTER_ACCEPT:
  664. case DOZTFILTER_SUPER_ACCEPT: // no difference in behavior on outbound side
  665. accept = true;
  666. break;
  667. }
  668. if (accept) {
  669. if ((!noTee)&&(cc)) {
  670. _memberships[cc].sendCredentialsIfNeeded(RR,RR->node->now(),cc,_config,relevantCap);
  671. Packet outp(cc,RR->identity.address(),Packet::VERB_EXT_FRAME);
  672. outp.append(_id);
  673. outp.append((uint8_t)0x02); // TEE/REDIRECT from outbound side: 0x02
  674. macDest.appendTo(outp);
  675. macSource.appendTo(outp);
  676. outp.append((uint16_t)etherType);
  677. outp.append(frameData,ccLength);
  678. outp.compress();
  679. RR->sw->send(outp,true);
  680. }
  681. if ((ztDest != ztDest2)&&(ztDest2)) {
  682. _memberships[ztDest2].sendCredentialsIfNeeded(RR,RR->node->now(),ztDest2,_config,relevantCap);
  683. Packet outp(ztDest2,RR->identity.address(),Packet::VERB_EXT_FRAME);
  684. outp.append(_id);
  685. outp.append((uint8_t)0x02); // TEE/REDIRECT from outbound side: 0x02
  686. macDest.appendTo(outp);
  687. macSource.appendTo(outp);
  688. outp.append((uint16_t)etherType);
  689. outp.append(frameData,frameLen);
  690. outp.compress();
  691. RR->sw->send(outp,true);
  692. return false; // DROP locally, since we redirected
  693. } else if (ztDest) {
  694. m.sendCredentialsIfNeeded(RR,RR->node->now(),ztDest,_config,relevantCap);
  695. }
  696. }
  697. return accept;
  698. }
  699. int Network::filterIncomingPacket(
  700. const SharedPtr<Peer> &sourcePeer,
  701. const Address &ztDest,
  702. const MAC &macSource,
  703. const MAC &macDest,
  704. const uint8_t *frameData,
  705. const unsigned int frameLen,
  706. const unsigned int etherType,
  707. const unsigned int vlanId)
  708. {
  709. uint32_t remoteTagIds[ZT_MAX_NETWORK_TAGS];
  710. uint32_t remoteTagValues[ZT_MAX_NETWORK_TAGS];
  711. Address ztDest2(ztDest);
  712. Address cc;
  713. unsigned int ccLength = 0;
  714. int accept = 0;
  715. Mutex::Lock _l(_lock);
  716. Membership &m = _memberships[ztDest];
  717. const unsigned int remoteTagCount = m.getAllTags(_config,remoteTagIds,remoteTagValues,ZT_MAX_NETWORK_TAGS);
  718. switch (_doZtFilter(RR,_config,true,sourcePeer->address(),ztDest2,macSource,macDest,frameData,frameLen,etherType,vlanId,_config.rules,_config.ruleCount,_config.tags,_config.tagCount,remoteTagIds,remoteTagValues,remoteTagCount,cc,ccLength)) {
  719. case DOZTFILTER_NO_MATCH: {
  720. Membership::CapabilityIterator mci(m);
  721. const Capability *c;
  722. while ((c = mci.next(_config))) {
  723. ztDest2 = ztDest; // sanity check
  724. Address cc2;
  725. unsigned int ccLength2 = 0;
  726. switch(_doZtFilter(RR,_config,true,sourcePeer->address(),ztDest2,macSource,macDest,frameData,frameLen,etherType,vlanId,c->rules(),c->ruleCount(),_config.tags,_config.tagCount,remoteTagIds,remoteTagValues,remoteTagCount,cc2,ccLength2)) {
  727. case DOZTFILTER_NO_MATCH:
  728. case DOZTFILTER_DROP: // explicit DROP in a capability just terminates its evaluation and is an anti-pattern
  729. break;
  730. case DOZTFILTER_REDIRECT: // interpreted as ACCEPT but ztDest will have been changed in _doZtFilter()
  731. case DOZTFILTER_ACCEPT:
  732. accept = 1; // ACCEPT
  733. break;
  734. case DOZTFILTER_SUPER_ACCEPT:
  735. accept = 2; // super-ACCEPT
  736. break;
  737. }
  738. if (accept) {
  739. if (cc2) {
  740. _memberships[cc2].sendCredentialsIfNeeded(RR,RR->node->now(),cc2,_config,(const Capability *)0);
  741. Packet outp(cc2,RR->identity.address(),Packet::VERB_EXT_FRAME);
  742. outp.append(_id);
  743. outp.append((uint8_t)0x06); // TEE/REDIRECT from inbound side: 0x06
  744. macDest.appendTo(outp);
  745. macSource.appendTo(outp);
  746. outp.append((uint16_t)etherType);
  747. outp.append(frameData,ccLength2);
  748. outp.compress();
  749. RR->sw->send(outp,true);
  750. }
  751. break;
  752. }
  753. }
  754. } break;
  755. case DOZTFILTER_DROP:
  756. return 0; // DROP
  757. case DOZTFILTER_REDIRECT: // interpreted as ACCEPT but ztDest2 will have been changed in _doZtFilter()
  758. case DOZTFILTER_ACCEPT:
  759. accept = 1; // ACCEPT
  760. break;
  761. case DOZTFILTER_SUPER_ACCEPT:
  762. accept = 2; // super-ACCEPT
  763. break;
  764. }
  765. if (accept) {
  766. if (cc) {
  767. _memberships[cc].sendCredentialsIfNeeded(RR,RR->node->now(),cc,_config,(const Capability *)0);
  768. Packet outp(cc,RR->identity.address(),Packet::VERB_EXT_FRAME);
  769. outp.append(_id);
  770. outp.append((uint8_t)0x06); // TEE/REDIRECT from inbound side: 0x06
  771. macDest.appendTo(outp);
  772. macSource.appendTo(outp);
  773. outp.append((uint16_t)etherType);
  774. outp.append(frameData,ccLength);
  775. outp.compress();
  776. RR->sw->send(outp,true);
  777. }
  778. if ((ztDest != ztDest2)&&(ztDest2)) {
  779. _memberships[ztDest2].sendCredentialsIfNeeded(RR,RR->node->now(),ztDest2,_config,(const Capability *)0);
  780. Packet outp(ztDest2,RR->identity.address(),Packet::VERB_EXT_FRAME);
  781. outp.append(_id);
  782. outp.append((uint8_t)0x06); // TEE/REDIRECT from inbound side: 0x06
  783. macDest.appendTo(outp);
  784. macSource.appendTo(outp);
  785. outp.append((uint16_t)etherType);
  786. outp.append(frameData,frameLen);
  787. outp.compress();
  788. RR->sw->send(outp,true);
  789. return 0; // DROP locally, since we redirected
  790. }
  791. }
  792. return accept;
  793. }
  794. bool Network::subscribedToMulticastGroup(const MulticastGroup &mg,bool includeBridgedGroups) const
  795. {
  796. Mutex::Lock _l(_lock);
  797. if (std::binary_search(_myMulticastGroups.begin(),_myMulticastGroups.end(),mg))
  798. return true;
  799. else if (includeBridgedGroups)
  800. return _multicastGroupsBehindMe.contains(mg);
  801. else return false;
  802. }
  803. void Network::multicastSubscribe(const MulticastGroup &mg)
  804. {
  805. {
  806. Mutex::Lock _l(_lock);
  807. if (std::binary_search(_myMulticastGroups.begin(),_myMulticastGroups.end(),mg))
  808. return;
  809. _myMulticastGroups.push_back(mg);
  810. std::sort(_myMulticastGroups.begin(),_myMulticastGroups.end());
  811. }
  812. _announceMulticastGroups();
  813. }
  814. void Network::multicastUnsubscribe(const MulticastGroup &mg)
  815. {
  816. Mutex::Lock _l(_lock);
  817. std::vector<MulticastGroup> nmg;
  818. for(std::vector<MulticastGroup>::const_iterator i(_myMulticastGroups.begin());i!=_myMulticastGroups.end();++i) {
  819. if (*i != mg)
  820. nmg.push_back(*i);
  821. }
  822. if (nmg.size() != _myMulticastGroups.size())
  823. _myMulticastGroups.swap(nmg);
  824. }
  825. bool Network::tryAnnounceMulticastGroupsTo(const SharedPtr<Peer> &peer)
  826. {
  827. Mutex::Lock _l(_lock);
  828. if (
  829. (_isAllowed(peer)) ||
  830. (peer->address() == this->controller()) ||
  831. (RR->topology->isUpstream(peer->identity()))
  832. ) {
  833. _announceMulticastGroupsTo(peer,_allMulticastGroups());
  834. return true;
  835. }
  836. return false;
  837. }
  838. bool Network::applyConfiguration(const NetworkConfig &conf)
  839. {
  840. if (_destroyed) // sanity check
  841. return false;
  842. try {
  843. if ((conf.networkId == _id)&&(conf.issuedTo == RR->identity.address())) {
  844. ZT_VirtualNetworkConfig ctmp;
  845. bool portInitialized;
  846. {
  847. Mutex::Lock _l(_lock);
  848. _config = conf;
  849. _lastConfigUpdate = RR->node->now();
  850. _netconfFailure = NETCONF_FAILURE_NONE;
  851. _externalConfig(&ctmp);
  852. portInitialized = _portInitialized;
  853. _portInitialized = true;
  854. }
  855. _portError = RR->node->configureVirtualNetworkPort(_id,&_uPtr,(portInitialized) ? ZT_VIRTUAL_NETWORK_CONFIG_OPERATION_CONFIG_UPDATE : ZT_VIRTUAL_NETWORK_CONFIG_OPERATION_UP,&ctmp);
  856. return true;
  857. } else {
  858. TRACE("ignored invalid configuration for network %.16llx (configuration contains mismatched network ID or issued-to address)",(unsigned long long)_id);
  859. }
  860. } catch (std::exception &exc) {
  861. TRACE("ignored invalid configuration for network %.16llx (%s)",(unsigned long long)_id,exc.what());
  862. } catch ( ... ) {
  863. TRACE("ignored invalid configuration for network %.16llx (unknown exception)",(unsigned long long)_id);
  864. }
  865. return false;
  866. }
  867. int Network::setConfiguration(const NetworkConfig &nconf,bool saveToDisk)
  868. {
  869. try {
  870. {
  871. Mutex::Lock _l(_lock);
  872. if (_config == nconf)
  873. return 1; // OK config, but duplicate of what we already have
  874. }
  875. if (applyConfiguration(nconf)) {
  876. if (saveToDisk) {
  877. char n[64];
  878. Utils::snprintf(n,sizeof(n),"networks.d/%.16llx.conf",_id);
  879. Dictionary<ZT_NETWORKCONFIG_DICT_CAPACITY> d;
  880. if (nconf.toDictionary(d,false))
  881. RR->node->dataStorePut(n,(const void *)d.data(),d.sizeBytes(),true);
  882. }
  883. return 2; // OK and configuration has changed
  884. }
  885. } catch ( ... ) {
  886. TRACE("ignored invalid configuration for network %.16llx",(unsigned long long)_id);
  887. }
  888. return 0;
  889. }
  890. void Network::handleInboundConfigChunk(const uint64_t inRePacketId,const void *data,unsigned int chunkSize,unsigned int chunkIndex,unsigned int totalSize)
  891. {
  892. std::string newConfig;
  893. if ((_inboundConfigPacketId == inRePacketId)&&(totalSize < ZT_NETWORKCONFIG_DICT_CAPACITY)&&((chunkIndex + chunkSize) <= totalSize)) {
  894. Mutex::Lock _l(_lock);
  895. _inboundConfigChunks[chunkIndex].append((const char *)data,chunkSize);
  896. unsigned int totalWeHave = 0;
  897. for(std::map<unsigned int,std::string>::iterator c(_inboundConfigChunks.begin());c!=_inboundConfigChunks.end();++c)
  898. totalWeHave += (unsigned int)c->second.length();
  899. if (totalWeHave == totalSize) {
  900. TRACE("have all chunks for network config request %.16llx, assembling...",inRePacketId);
  901. for(std::map<unsigned int,std::string>::iterator c(_inboundConfigChunks.begin());c!=_inboundConfigChunks.end();++c)
  902. newConfig.append(c->second);
  903. _inboundConfigPacketId = 0;
  904. _inboundConfigChunks.clear();
  905. } else if (totalWeHave > totalSize) {
  906. _inboundConfigPacketId = 0;
  907. _inboundConfigChunks.clear();
  908. }
  909. } else {
  910. return;
  911. }
  912. if ((newConfig.length() > 0)&&(newConfig.length() < ZT_NETWORKCONFIG_DICT_CAPACITY)) {
  913. Dictionary<ZT_NETWORKCONFIG_DICT_CAPACITY> *dict = new Dictionary<ZT_NETWORKCONFIG_DICT_CAPACITY>(newConfig.c_str());
  914. NetworkConfig *nc = new NetworkConfig();
  915. try {
  916. Identity controllerId(RR->topology->getIdentity(this->controller()));
  917. if (controllerId) {
  918. if (nc->fromDictionary(*dict)) {
  919. this->setConfiguration(*nc,true);
  920. } else {
  921. TRACE("error parsing new config with length %u: deserialization of NetworkConfig failed (certificate error?)",(unsigned int)newConfig.length());
  922. }
  923. }
  924. delete nc;
  925. delete dict;
  926. } catch ( ... ) {
  927. TRACE("error parsing new config with length %u: unexpected exception",(unsigned int)newConfig.length());
  928. delete nc;
  929. delete dict;
  930. throw;
  931. }
  932. }
  933. }
  934. void Network::requestConfiguration()
  935. {
  936. // Sanity limit: do not request more often than once per second
  937. const uint64_t now = RR->node->now();
  938. if ((now - _lastRequestedConfiguration) < 1000ULL)
  939. return;
  940. _lastRequestedConfiguration = RR->node->now();
  941. const Address ctrl(controller());
  942. Dictionary<ZT_NETWORKCONFIG_METADATA_DICT_CAPACITY> rmd;
  943. rmd.add(ZT_NETWORKCONFIG_REQUEST_METADATA_KEY_VERSION,(uint64_t)ZT_NETWORKCONFIG_VERSION);
  944. rmd.add(ZT_NETWORKCONFIG_REQUEST_METADATA_KEY_PROTOCOL_VERSION,(uint64_t)ZT_PROTO_VERSION);
  945. rmd.add(ZT_NETWORKCONFIG_REQUEST_METADATA_KEY_NODE_MAJOR_VERSION,(uint64_t)ZEROTIER_ONE_VERSION_MAJOR);
  946. rmd.add(ZT_NETWORKCONFIG_REQUEST_METADATA_KEY_NODE_MINOR_VERSION,(uint64_t)ZEROTIER_ONE_VERSION_MINOR);
  947. rmd.add(ZT_NETWORKCONFIG_REQUEST_METADATA_KEY_NODE_REVISION,(uint64_t)ZEROTIER_ONE_VERSION_REVISION);
  948. rmd.add(ZT_NETWORKCONFIG_REQUEST_METADATA_KEY_MAX_NETWORK_RULES,(uint64_t)ZT_MAX_NETWORK_RULES);
  949. rmd.add(ZT_NETWORKCONFIG_REQUEST_METADATA_KEY_MAX_NETWORK_CAPABILITIES,(uint64_t)ZT_MAX_NETWORK_CAPABILITIES);
  950. rmd.add(ZT_NETWORKCONFIG_REQUEST_METADATA_KEY_MAX_CAPABILITY_RULES,(uint64_t)ZT_MAX_CAPABILITY_RULES);
  951. rmd.add(ZT_NETWORKCONFIG_REQUEST_METADATA_KEY_MAX_NETWORK_TAGS,(uint64_t)ZT_MAX_NETWORK_TAGS);
  952. rmd.add(ZT_NETWORKCONFIG_REQUEST_METADATA_KEY_FLAGS,(uint64_t)0);
  953. rmd.add(ZT_NETWORKCONFIG_REQUEST_METADATA_KEY_RULES_ENGINE_REV,(uint64_t)ZT_RULES_ENGINE_REVISION);
  954. if (ctrl == RR->identity.address()) {
  955. if (RR->localNetworkController) {
  956. NetworkConfig nconf;
  957. switch(RR->localNetworkController->doNetworkConfigRequest(InetAddress(),RR->identity,RR->identity,_id,rmd,nconf)) {
  958. case NetworkController::NETCONF_QUERY_OK:
  959. this->setConfiguration(nconf,true);
  960. return;
  961. case NetworkController::NETCONF_QUERY_OBJECT_NOT_FOUND:
  962. this->setNotFound();
  963. return;
  964. case NetworkController::NETCONF_QUERY_ACCESS_DENIED:
  965. this->setAccessDenied();
  966. return;
  967. default:
  968. return;
  969. }
  970. } else {
  971. this->setNotFound();
  972. return;
  973. }
  974. }
  975. TRACE("requesting netconf for network %.16llx from controller %s",(unsigned long long)_id,ctrl.toString().c_str());
  976. Packet outp(ctrl,RR->identity.address(),Packet::VERB_NETWORK_CONFIG_REQUEST);
  977. outp.append((uint64_t)_id);
  978. const unsigned int rmdSize = rmd.sizeBytes();
  979. outp.append((uint16_t)rmdSize);
  980. outp.append((const void *)rmd.data(),rmdSize);
  981. if (_config) {
  982. outp.append((uint64_t)_config.revision);
  983. outp.append((uint64_t)_config.timestamp);
  984. } else {
  985. outp.append((unsigned char)0,16);
  986. }
  987. outp.compress();
  988. RR->sw->send(outp,true);
  989. // Expect replies with this in-re packet ID
  990. _inboundConfigPacketId = outp.packetId();
  991. _inboundConfigChunks.clear();
  992. }
  993. void Network::clean()
  994. {
  995. const uint64_t now = RR->node->now();
  996. Mutex::Lock _l(_lock);
  997. if (_destroyed)
  998. return;
  999. {
  1000. Hashtable< MulticastGroup,uint64_t >::Iterator i(_multicastGroupsBehindMe);
  1001. MulticastGroup *mg = (MulticastGroup *)0;
  1002. uint64_t *ts = (uint64_t *)0;
  1003. while (i.next(mg,ts)) {
  1004. if ((now - *ts) > (ZT_MULTICAST_LIKE_EXPIRE * 2))
  1005. _multicastGroupsBehindMe.erase(*mg);
  1006. }
  1007. }
  1008. {
  1009. Address *a = (Address *)0;
  1010. Membership *m = (Membership *)0;
  1011. Hashtable<Address,Membership>::Iterator i(_memberships);
  1012. while (i.next(a,m)) {
  1013. if ((now - m->clean(now)) > ZT_MEMBERSHIP_EXPIRATION_TIME)
  1014. _memberships.erase(*a);
  1015. }
  1016. }
  1017. }
  1018. void Network::learnBridgeRoute(const MAC &mac,const Address &addr)
  1019. {
  1020. Mutex::Lock _l(_lock);
  1021. _remoteBridgeRoutes[mac] = addr;
  1022. // Anti-DOS circuit breaker to prevent nodes from spamming us with absurd numbers of bridge routes
  1023. while (_remoteBridgeRoutes.size() > ZT_MAX_BRIDGE_ROUTES) {
  1024. Hashtable< Address,unsigned long > counts;
  1025. Address maxAddr;
  1026. unsigned long maxCount = 0;
  1027. MAC *m = (MAC *)0;
  1028. Address *a = (Address *)0;
  1029. // Find the address responsible for the most entries
  1030. {
  1031. Hashtable<MAC,Address>::Iterator i(_remoteBridgeRoutes);
  1032. while (i.next(m,a)) {
  1033. const unsigned long c = ++counts[*a];
  1034. if (c > maxCount) {
  1035. maxCount = c;
  1036. maxAddr = *a;
  1037. }
  1038. }
  1039. }
  1040. // Kill this address from our table, since it's most likely spamming us
  1041. {
  1042. Hashtable<MAC,Address>::Iterator i(_remoteBridgeRoutes);
  1043. while (i.next(m,a)) {
  1044. if (*a == maxAddr)
  1045. _remoteBridgeRoutes.erase(*m);
  1046. }
  1047. }
  1048. }
  1049. }
  1050. void Network::learnBridgedMulticastGroup(const MulticastGroup &mg,uint64_t now)
  1051. {
  1052. Mutex::Lock _l(_lock);
  1053. const unsigned long tmp = (unsigned long)_multicastGroupsBehindMe.size();
  1054. _multicastGroupsBehindMe.set(mg,now);
  1055. if (tmp != _multicastGroupsBehindMe.size())
  1056. _announceMulticastGroups();
  1057. }
  1058. void Network::destroy()
  1059. {
  1060. Mutex::Lock _l(_lock);
  1061. _destroyed = true;
  1062. }
  1063. ZT_VirtualNetworkStatus Network::_status() const
  1064. {
  1065. // assumes _lock is locked
  1066. if (_portError)
  1067. return ZT_NETWORK_STATUS_PORT_ERROR;
  1068. switch(_netconfFailure) {
  1069. case NETCONF_FAILURE_ACCESS_DENIED:
  1070. return ZT_NETWORK_STATUS_ACCESS_DENIED;
  1071. case NETCONF_FAILURE_NOT_FOUND:
  1072. return ZT_NETWORK_STATUS_NOT_FOUND;
  1073. case NETCONF_FAILURE_NONE:
  1074. return ((_config) ? ZT_NETWORK_STATUS_OK : ZT_NETWORK_STATUS_REQUESTING_CONFIGURATION);
  1075. default:
  1076. return ZT_NETWORK_STATUS_PORT_ERROR;
  1077. }
  1078. }
  1079. void Network::_externalConfig(ZT_VirtualNetworkConfig *ec) const
  1080. {
  1081. // assumes _lock is locked
  1082. ec->nwid = _id;
  1083. ec->mac = _mac.toInt();
  1084. if (_config)
  1085. Utils::scopy(ec->name,sizeof(ec->name),_config.name);
  1086. else ec->name[0] = (char)0;
  1087. ec->status = _status();
  1088. ec->type = (_config) ? (_config.isPrivate() ? ZT_NETWORK_TYPE_PRIVATE : ZT_NETWORK_TYPE_PUBLIC) : ZT_NETWORK_TYPE_PRIVATE;
  1089. ec->mtu = ZT_IF_MTU;
  1090. ec->dhcp = 0;
  1091. std::vector<Address> ab(_config.activeBridges());
  1092. ec->bridge = ((_config.allowPassiveBridging())||(std::find(ab.begin(),ab.end(),RR->identity.address()) != ab.end())) ? 1 : 0;
  1093. ec->broadcastEnabled = (_config) ? (_config.enableBroadcast() ? 1 : 0) : 0;
  1094. ec->portError = _portError;
  1095. ec->netconfRevision = (_config) ? (unsigned long)_config.revision : 0;
  1096. ec->assignedAddressCount = 0;
  1097. for(unsigned int i=0;i<ZT_MAX_ZT_ASSIGNED_ADDRESSES;++i) {
  1098. if (i < _config.staticIpCount) {
  1099. memcpy(&(ec->assignedAddresses[i]),&(_config.staticIps[i]),sizeof(struct sockaddr_storage));
  1100. ++ec->assignedAddressCount;
  1101. } else {
  1102. memset(&(ec->assignedAddresses[i]),0,sizeof(struct sockaddr_storage));
  1103. }
  1104. }
  1105. ec->routeCount = 0;
  1106. for(unsigned int i=0;i<ZT_MAX_NETWORK_ROUTES;++i) {
  1107. if (i < _config.routeCount) {
  1108. memcpy(&(ec->routes[i]),&(_config.routes[i]),sizeof(ZT_VirtualNetworkRoute));
  1109. ++ec->routeCount;
  1110. } else {
  1111. memset(&(ec->routes[i]),0,sizeof(ZT_VirtualNetworkRoute));
  1112. }
  1113. }
  1114. }
  1115. bool Network::_isAllowed(const SharedPtr<Peer> &peer) const
  1116. {
  1117. // Assumes _lock is locked
  1118. try {
  1119. if (_config) {
  1120. const Membership *const m = _memberships.get(peer->address());
  1121. if (m)
  1122. return m->isAllowedOnNetwork(_config);
  1123. }
  1124. } catch ( ... ) {
  1125. TRACE("isAllowed() check failed for peer %s: unexpected exception",peer->address().toString().c_str());
  1126. }
  1127. return false;
  1128. }
  1129. class _MulticastAnnounceAll
  1130. {
  1131. public:
  1132. _MulticastAnnounceAll(const RuntimeEnvironment *renv,Network *nw) :
  1133. _now(renv->node->now()),
  1134. _controller(nw->controller()),
  1135. _network(nw),
  1136. _anchors(nw->config().anchors()),
  1137. _upstreamAddresses(renv->topology->upstreamAddresses())
  1138. {}
  1139. inline void operator()(Topology &t,const SharedPtr<Peer> &p)
  1140. {
  1141. if ( (_network->_isAllowed(p)) || // FIXME: this causes multicast LIKEs for public networks to get spammed, which isn't terrible but is a bit stupid
  1142. (p->address() == _controller) ||
  1143. (std::find(_upstreamAddresses.begin(),_upstreamAddresses.end(),p->address()) != _upstreamAddresses.end()) ||
  1144. (std::find(_anchors.begin(),_anchors.end(),p->address()) != _anchors.end()) ) {
  1145. peers.push_back(p);
  1146. }
  1147. }
  1148. std::vector< SharedPtr<Peer> > peers;
  1149. private:
  1150. const uint64_t _now;
  1151. const Address _controller;
  1152. Network *const _network;
  1153. const std::vector<Address> _anchors;
  1154. const std::vector<Address> _upstreamAddresses;
  1155. };
  1156. void Network::_announceMulticastGroups()
  1157. {
  1158. // Assumes _lock is locked
  1159. std::vector<MulticastGroup> allMulticastGroups(_allMulticastGroups());
  1160. _MulticastAnnounceAll gpfunc(RR,this);
  1161. RR->topology->eachPeer<_MulticastAnnounceAll &>(gpfunc);
  1162. for(std::vector< SharedPtr<Peer> >::const_iterator i(gpfunc.peers.begin());i!=gpfunc.peers.end();++i)
  1163. _announceMulticastGroupsTo(*i,allMulticastGroups);
  1164. }
  1165. void Network::_announceMulticastGroupsTo(const SharedPtr<Peer> &peer,const std::vector<MulticastGroup> &allMulticastGroups)
  1166. {
  1167. // Assumes _lock is locked
  1168. // Anyone we announce multicast groups to will need our COM to authenticate GATHER requests.
  1169. {
  1170. Membership *m = _memberships.get(peer->address());
  1171. if (m)
  1172. m->sendCredentialsIfNeeded(RR,RR->node->now(),peer->address(),_config,(const Capability *)0);
  1173. }
  1174. Packet outp(peer->address(),RR->identity.address(),Packet::VERB_MULTICAST_LIKE);
  1175. for(std::vector<MulticastGroup>::const_iterator mg(allMulticastGroups.begin());mg!=allMulticastGroups.end();++mg) {
  1176. if ((outp.size() + 24) >= ZT_PROTO_MAX_PACKET_LENGTH) {
  1177. outp.compress();
  1178. RR->sw->send(outp,true);
  1179. outp.reset(peer->address(),RR->identity.address(),Packet::VERB_MULTICAST_LIKE);
  1180. }
  1181. // network ID, MAC, ADI
  1182. outp.append((uint64_t)_id);
  1183. mg->mac().appendTo(outp);
  1184. outp.append((uint32_t)mg->adi());
  1185. }
  1186. if (outp.size() > ZT_PROTO_MIN_PACKET_LENGTH) {
  1187. outp.compress();
  1188. RR->sw->send(outp,true);
  1189. }
  1190. }
  1191. std::vector<MulticastGroup> Network::_allMulticastGroups() const
  1192. {
  1193. // Assumes _lock is locked
  1194. std::vector<MulticastGroup> mgs;
  1195. mgs.reserve(_myMulticastGroups.size() + _multicastGroupsBehindMe.size() + 1);
  1196. mgs.insert(mgs.end(),_myMulticastGroups.begin(),_myMulticastGroups.end());
  1197. _multicastGroupsBehindMe.appendKeys(mgs);
  1198. if ((_config)&&(_config.enableBroadcast()))
  1199. mgs.push_back(Network::BROADCAST);
  1200. std::sort(mgs.begin(),mgs.end());
  1201. mgs.erase(std::unique(mgs.begin(),mgs.end()),mgs.end());
  1202. return mgs;
  1203. }
  1204. } // namespace ZeroTier