Network.cpp 51 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302
  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. _lastAnnouncedMulticastGroupsUpstream(0),
  556. _mac(renv->identity.address(),nwid),
  557. _portInitialized(false),
  558. _inboundConfigPacketId(0),
  559. _lastConfigUpdate(0),
  560. _lastRequestedConfiguration(0),
  561. _destroyed(false),
  562. _netconfFailure(NETCONF_FAILURE_NONE),
  563. _portError(0)
  564. {
  565. char confn[128];
  566. Utils::snprintf(confn,sizeof(confn),"networks.d/%.16llx.conf",_id);
  567. bool gotConf = false;
  568. Dictionary<ZT_NETWORKCONFIG_DICT_CAPACITY> *dconf = new Dictionary<ZT_NETWORKCONFIG_DICT_CAPACITY>();
  569. NetworkConfig *nconf = new NetworkConfig();
  570. try {
  571. std::string conf(RR->node->dataStoreGet(confn));
  572. if (conf.length()) {
  573. dconf->load(conf.c_str());
  574. if (nconf->fromDictionary(*dconf)) {
  575. this->setConfiguration(*nconf,false);
  576. _lastConfigUpdate = 0; // we still want to re-request a new config from the network
  577. gotConf = true;
  578. }
  579. }
  580. } catch ( ... ) {} // ignore invalids, we'll re-request
  581. delete nconf;
  582. delete dconf;
  583. if (!gotConf) {
  584. // Save a one-byte CR to persist membership while we request a real netconf
  585. RR->node->dataStorePut(confn,"\n",1,false);
  586. }
  587. if (!_portInitialized) {
  588. ZT_VirtualNetworkConfig ctmp;
  589. _externalConfig(&ctmp);
  590. _portError = RR->node->configureVirtualNetworkPort(_id,&_uPtr,ZT_VIRTUAL_NETWORK_CONFIG_OPERATION_UP,&ctmp);
  591. _portInitialized = true;
  592. }
  593. }
  594. Network::~Network()
  595. {
  596. ZT_VirtualNetworkConfig ctmp;
  597. _externalConfig(&ctmp);
  598. char n[128];
  599. if (_destroyed) {
  600. RR->node->configureVirtualNetworkPort(_id,&_uPtr,ZT_VIRTUAL_NETWORK_CONFIG_OPERATION_DESTROY,&ctmp);
  601. Utils::snprintf(n,sizeof(n),"networks.d/%.16llx.conf",_id);
  602. RR->node->dataStoreDelete(n);
  603. } else {
  604. RR->node->configureVirtualNetworkPort(_id,&_uPtr,ZT_VIRTUAL_NETWORK_CONFIG_OPERATION_DOWN,&ctmp);
  605. }
  606. }
  607. bool Network::filterOutgoingPacket(
  608. const bool noTee,
  609. const Address &ztSource,
  610. const Address &ztDest,
  611. const MAC &macSource,
  612. const MAC &macDest,
  613. const uint8_t *frameData,
  614. const unsigned int frameLen,
  615. const unsigned int etherType,
  616. const unsigned int vlanId)
  617. {
  618. uint32_t remoteTagIds[ZT_MAX_NETWORK_TAGS];
  619. uint32_t remoteTagValues[ZT_MAX_NETWORK_TAGS];
  620. Address ztDest2(ztDest);
  621. Address cc;
  622. const Capability *relevantCap = (const Capability *)0;
  623. unsigned int ccLength = 0;
  624. bool accept = false;
  625. Mutex::Lock _l(_lock);
  626. Membership &m = _memberships[ztDest];
  627. const unsigned int remoteTagCount = m.getAllTags(_config,remoteTagIds,remoteTagValues,ZT_MAX_NETWORK_TAGS);
  628. 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)) {
  629. case DOZTFILTER_NO_MATCH:
  630. for(unsigned int c=0;c<_config.capabilityCount;++c) {
  631. ztDest2 = ztDest; // sanity check
  632. Address cc2;
  633. unsigned int ccLength2 = 0;
  634. 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)) {
  635. case DOZTFILTER_NO_MATCH:
  636. case DOZTFILTER_DROP: // explicit DROP in a capability just terminates its evaluation and is an anti-pattern
  637. break;
  638. case DOZTFILTER_REDIRECT: // interpreted as ACCEPT but ztDest2 will have been changed in _doZtFilter()
  639. case DOZTFILTER_ACCEPT:
  640. case DOZTFILTER_SUPER_ACCEPT: // no difference in behavior on outbound side
  641. relevantCap = &(_config.capabilities[c]);
  642. accept = true;
  643. if ((!noTee)&&(cc2)) {
  644. _memberships[cc2].sendCredentialsIfNeeded(RR,RR->node->now(),cc2,_config,relevantCap);
  645. Packet outp(cc2,RR->identity.address(),Packet::VERB_EXT_FRAME);
  646. outp.append(_id);
  647. outp.append((uint8_t)0x02); // TEE/REDIRECT from outbound side: 0x02
  648. macDest.appendTo(outp);
  649. macSource.appendTo(outp);
  650. outp.append((uint16_t)etherType);
  651. outp.append(frameData,ccLength2);
  652. outp.compress();
  653. RR->sw->send(outp,true);
  654. }
  655. break;
  656. }
  657. if (accept)
  658. break;
  659. }
  660. break;
  661. case DOZTFILTER_DROP:
  662. return false;
  663. case DOZTFILTER_REDIRECT: // interpreted as ACCEPT but ztDest2 will have been changed in _doZtFilter()
  664. case DOZTFILTER_ACCEPT:
  665. case DOZTFILTER_SUPER_ACCEPT: // no difference in behavior on outbound side
  666. accept = true;
  667. break;
  668. }
  669. if (accept) {
  670. if ((!noTee)&&(cc)) {
  671. _memberships[cc].sendCredentialsIfNeeded(RR,RR->node->now(),cc,_config,relevantCap);
  672. Packet outp(cc,RR->identity.address(),Packet::VERB_EXT_FRAME);
  673. outp.append(_id);
  674. outp.append((uint8_t)0x02); // TEE/REDIRECT from outbound side: 0x02
  675. macDest.appendTo(outp);
  676. macSource.appendTo(outp);
  677. outp.append((uint16_t)etherType);
  678. outp.append(frameData,ccLength);
  679. outp.compress();
  680. RR->sw->send(outp,true);
  681. }
  682. if ((ztDest != ztDest2)&&(ztDest2)) {
  683. _memberships[ztDest2].sendCredentialsIfNeeded(RR,RR->node->now(),ztDest2,_config,relevantCap);
  684. Packet outp(ztDest2,RR->identity.address(),Packet::VERB_EXT_FRAME);
  685. outp.append(_id);
  686. outp.append((uint8_t)0x02); // TEE/REDIRECT from outbound side: 0x02
  687. macDest.appendTo(outp);
  688. macSource.appendTo(outp);
  689. outp.append((uint16_t)etherType);
  690. outp.append(frameData,frameLen);
  691. outp.compress();
  692. RR->sw->send(outp,true);
  693. return false; // DROP locally, since we redirected
  694. } else if (ztDest) {
  695. m.sendCredentialsIfNeeded(RR,RR->node->now(),ztDest,_config,relevantCap);
  696. }
  697. }
  698. return accept;
  699. }
  700. int Network::filterIncomingPacket(
  701. const SharedPtr<Peer> &sourcePeer,
  702. const Address &ztDest,
  703. const MAC &macSource,
  704. const MAC &macDest,
  705. const uint8_t *frameData,
  706. const unsigned int frameLen,
  707. const unsigned int etherType,
  708. const unsigned int vlanId)
  709. {
  710. uint32_t remoteTagIds[ZT_MAX_NETWORK_TAGS];
  711. uint32_t remoteTagValues[ZT_MAX_NETWORK_TAGS];
  712. Address ztDest2(ztDest);
  713. Address cc;
  714. unsigned int ccLength = 0;
  715. int accept = 0;
  716. Mutex::Lock _l(_lock);
  717. Membership &m = _memberships[ztDest];
  718. const unsigned int remoteTagCount = m.getAllTags(_config,remoteTagIds,remoteTagValues,ZT_MAX_NETWORK_TAGS);
  719. 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)) {
  720. case DOZTFILTER_NO_MATCH: {
  721. Membership::CapabilityIterator mci(m);
  722. const Capability *c;
  723. while ((c = mci.next(_config))) {
  724. ztDest2 = ztDest; // sanity check
  725. Address cc2;
  726. unsigned int ccLength2 = 0;
  727. 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)) {
  728. case DOZTFILTER_NO_MATCH:
  729. case DOZTFILTER_DROP: // explicit DROP in a capability just terminates its evaluation and is an anti-pattern
  730. break;
  731. case DOZTFILTER_REDIRECT: // interpreted as ACCEPT but ztDest will have been changed in _doZtFilter()
  732. case DOZTFILTER_ACCEPT:
  733. accept = 1; // ACCEPT
  734. break;
  735. case DOZTFILTER_SUPER_ACCEPT:
  736. accept = 2; // super-ACCEPT
  737. break;
  738. }
  739. if (accept) {
  740. if (cc2) {
  741. _memberships[cc2].sendCredentialsIfNeeded(RR,RR->node->now(),cc2,_config,(const Capability *)0);
  742. Packet outp(cc2,RR->identity.address(),Packet::VERB_EXT_FRAME);
  743. outp.append(_id);
  744. outp.append((uint8_t)0x06); // TEE/REDIRECT from inbound side: 0x06
  745. macDest.appendTo(outp);
  746. macSource.appendTo(outp);
  747. outp.append((uint16_t)etherType);
  748. outp.append(frameData,ccLength2);
  749. outp.compress();
  750. RR->sw->send(outp,true);
  751. }
  752. break;
  753. }
  754. }
  755. } break;
  756. case DOZTFILTER_DROP:
  757. return 0; // DROP
  758. case DOZTFILTER_REDIRECT: // interpreted as ACCEPT but ztDest2 will have been changed in _doZtFilter()
  759. case DOZTFILTER_ACCEPT:
  760. accept = 1; // ACCEPT
  761. break;
  762. case DOZTFILTER_SUPER_ACCEPT:
  763. accept = 2; // super-ACCEPT
  764. break;
  765. }
  766. if (accept) {
  767. if (cc) {
  768. _memberships[cc].sendCredentialsIfNeeded(RR,RR->node->now(),cc,_config,(const Capability *)0);
  769. Packet outp(cc,RR->identity.address(),Packet::VERB_EXT_FRAME);
  770. outp.append(_id);
  771. outp.append((uint8_t)0x06); // TEE/REDIRECT from inbound side: 0x06
  772. macDest.appendTo(outp);
  773. macSource.appendTo(outp);
  774. outp.append((uint16_t)etherType);
  775. outp.append(frameData,ccLength);
  776. outp.compress();
  777. RR->sw->send(outp,true);
  778. }
  779. if ((ztDest != ztDest2)&&(ztDest2)) {
  780. _memberships[ztDest2].sendCredentialsIfNeeded(RR,RR->node->now(),ztDest2,_config,(const Capability *)0);
  781. Packet outp(ztDest2,RR->identity.address(),Packet::VERB_EXT_FRAME);
  782. outp.append(_id);
  783. outp.append((uint8_t)0x06); // TEE/REDIRECT from inbound side: 0x06
  784. macDest.appendTo(outp);
  785. macSource.appendTo(outp);
  786. outp.append((uint16_t)etherType);
  787. outp.append(frameData,frameLen);
  788. outp.compress();
  789. RR->sw->send(outp,true);
  790. return 0; // DROP locally, since we redirected
  791. }
  792. }
  793. return accept;
  794. }
  795. bool Network::subscribedToMulticastGroup(const MulticastGroup &mg,bool includeBridgedGroups) const
  796. {
  797. Mutex::Lock _l(_lock);
  798. if (std::binary_search(_myMulticastGroups.begin(),_myMulticastGroups.end(),mg))
  799. return true;
  800. else if (includeBridgedGroups)
  801. return _multicastGroupsBehindMe.contains(mg);
  802. else return false;
  803. }
  804. void Network::multicastSubscribe(const MulticastGroup &mg)
  805. {
  806. {
  807. Mutex::Lock _l(_lock);
  808. if (std::binary_search(_myMulticastGroups.begin(),_myMulticastGroups.end(),mg))
  809. return;
  810. _myMulticastGroups.push_back(mg);
  811. std::sort(_myMulticastGroups.begin(),_myMulticastGroups.end());
  812. _announceMulticastGroups(&mg);
  813. }
  814. }
  815. void Network::multicastUnsubscribe(const MulticastGroup &mg)
  816. {
  817. Mutex::Lock _l(_lock);
  818. std::vector<MulticastGroup> nmg;
  819. for(std::vector<MulticastGroup>::const_iterator i(_myMulticastGroups.begin());i!=_myMulticastGroups.end();++i) {
  820. if (*i != mg)
  821. nmg.push_back(*i);
  822. }
  823. if (nmg.size() != _myMulticastGroups.size())
  824. _myMulticastGroups.swap(nmg);
  825. }
  826. bool Network::applyConfiguration(const NetworkConfig &conf)
  827. {
  828. if (_destroyed) // sanity check
  829. return false;
  830. try {
  831. if ((conf.networkId == _id)&&(conf.issuedTo == RR->identity.address())) {
  832. ZT_VirtualNetworkConfig ctmp;
  833. bool portInitialized;
  834. {
  835. Mutex::Lock _l(_lock);
  836. _config = conf;
  837. _lastConfigUpdate = RR->node->now();
  838. _netconfFailure = NETCONF_FAILURE_NONE;
  839. _externalConfig(&ctmp);
  840. portInitialized = _portInitialized;
  841. _portInitialized = true;
  842. }
  843. _portError = RR->node->configureVirtualNetworkPort(_id,&_uPtr,(portInitialized) ? ZT_VIRTUAL_NETWORK_CONFIG_OPERATION_CONFIG_UPDATE : ZT_VIRTUAL_NETWORK_CONFIG_OPERATION_UP,&ctmp);
  844. return true;
  845. } else {
  846. TRACE("ignored invalid configuration for network %.16llx (configuration contains mismatched network ID or issued-to address)",(unsigned long long)_id);
  847. }
  848. } catch (std::exception &exc) {
  849. TRACE("ignored invalid configuration for network %.16llx (%s)",(unsigned long long)_id,exc.what());
  850. } catch ( ... ) {
  851. TRACE("ignored invalid configuration for network %.16llx (unknown exception)",(unsigned long long)_id);
  852. }
  853. return false;
  854. }
  855. int Network::setConfiguration(const NetworkConfig &nconf,bool saveToDisk)
  856. {
  857. try {
  858. {
  859. Mutex::Lock _l(_lock);
  860. if (_config == nconf)
  861. return 1; // OK config, but duplicate of what we already have
  862. }
  863. if (applyConfiguration(nconf)) {
  864. if (saveToDisk) {
  865. char n[64];
  866. Utils::snprintf(n,sizeof(n),"networks.d/%.16llx.conf",_id);
  867. Dictionary<ZT_NETWORKCONFIG_DICT_CAPACITY> d;
  868. if (nconf.toDictionary(d,false))
  869. RR->node->dataStorePut(n,(const void *)d.data(),d.sizeBytes(),true);
  870. }
  871. return 2; // OK and configuration has changed
  872. }
  873. } catch ( ... ) {
  874. TRACE("ignored invalid configuration for network %.16llx",(unsigned long long)_id);
  875. }
  876. return 0;
  877. }
  878. void Network::handleInboundConfigChunk(const uint64_t inRePacketId,const void *data,unsigned int chunkSize,unsigned int chunkIndex,unsigned int totalSize)
  879. {
  880. std::string newConfig;
  881. if ((_inboundConfigPacketId == inRePacketId)&&(totalSize < ZT_NETWORKCONFIG_DICT_CAPACITY)&&((chunkIndex + chunkSize) <= totalSize)) {
  882. Mutex::Lock _l(_lock);
  883. _inboundConfigChunks[chunkIndex].append((const char *)data,chunkSize);
  884. unsigned int totalWeHave = 0;
  885. for(std::map<unsigned int,std::string>::iterator c(_inboundConfigChunks.begin());c!=_inboundConfigChunks.end();++c)
  886. totalWeHave += (unsigned int)c->second.length();
  887. if (totalWeHave == totalSize) {
  888. TRACE("have all chunks for network config request %.16llx, assembling...",inRePacketId);
  889. for(std::map<unsigned int,std::string>::iterator c(_inboundConfigChunks.begin());c!=_inboundConfigChunks.end();++c)
  890. newConfig.append(c->second);
  891. _inboundConfigPacketId = 0;
  892. _inboundConfigChunks.clear();
  893. } else if (totalWeHave > totalSize) {
  894. _inboundConfigPacketId = 0;
  895. _inboundConfigChunks.clear();
  896. }
  897. } else {
  898. return;
  899. }
  900. if ((newConfig.length() > 0)&&(newConfig.length() < ZT_NETWORKCONFIG_DICT_CAPACITY)) {
  901. Dictionary<ZT_NETWORKCONFIG_DICT_CAPACITY> *dict = new Dictionary<ZT_NETWORKCONFIG_DICT_CAPACITY>(newConfig.c_str());
  902. NetworkConfig *nc = new NetworkConfig();
  903. try {
  904. Identity controllerId(RR->topology->getIdentity(this->controller()));
  905. if (controllerId) {
  906. if (nc->fromDictionary(*dict)) {
  907. this->setConfiguration(*nc,true);
  908. } else {
  909. TRACE("error parsing new config with length %u: deserialization of NetworkConfig failed (certificate error?)",(unsigned int)newConfig.length());
  910. }
  911. }
  912. delete nc;
  913. delete dict;
  914. } catch ( ... ) {
  915. TRACE("error parsing new config with length %u: unexpected exception",(unsigned int)newConfig.length());
  916. delete nc;
  917. delete dict;
  918. throw;
  919. }
  920. }
  921. }
  922. void Network::requestConfiguration()
  923. {
  924. // Sanity limit: do not request more often than once per second
  925. const uint64_t now = RR->node->now();
  926. if ((now - _lastRequestedConfiguration) < 1000ULL)
  927. return;
  928. _lastRequestedConfiguration = RR->node->now();
  929. const Address ctrl(controller());
  930. Dictionary<ZT_NETWORKCONFIG_METADATA_DICT_CAPACITY> rmd;
  931. rmd.add(ZT_NETWORKCONFIG_REQUEST_METADATA_KEY_VERSION,(uint64_t)ZT_NETWORKCONFIG_VERSION);
  932. rmd.add(ZT_NETWORKCONFIG_REQUEST_METADATA_KEY_PROTOCOL_VERSION,(uint64_t)ZT_PROTO_VERSION);
  933. rmd.add(ZT_NETWORKCONFIG_REQUEST_METADATA_KEY_NODE_MAJOR_VERSION,(uint64_t)ZEROTIER_ONE_VERSION_MAJOR);
  934. rmd.add(ZT_NETWORKCONFIG_REQUEST_METADATA_KEY_NODE_MINOR_VERSION,(uint64_t)ZEROTIER_ONE_VERSION_MINOR);
  935. rmd.add(ZT_NETWORKCONFIG_REQUEST_METADATA_KEY_NODE_REVISION,(uint64_t)ZEROTIER_ONE_VERSION_REVISION);
  936. rmd.add(ZT_NETWORKCONFIG_REQUEST_METADATA_KEY_MAX_NETWORK_RULES,(uint64_t)ZT_MAX_NETWORK_RULES);
  937. rmd.add(ZT_NETWORKCONFIG_REQUEST_METADATA_KEY_MAX_NETWORK_CAPABILITIES,(uint64_t)ZT_MAX_NETWORK_CAPABILITIES);
  938. rmd.add(ZT_NETWORKCONFIG_REQUEST_METADATA_KEY_MAX_CAPABILITY_RULES,(uint64_t)ZT_MAX_CAPABILITY_RULES);
  939. rmd.add(ZT_NETWORKCONFIG_REQUEST_METADATA_KEY_MAX_NETWORK_TAGS,(uint64_t)ZT_MAX_NETWORK_TAGS);
  940. rmd.add(ZT_NETWORKCONFIG_REQUEST_METADATA_KEY_FLAGS,(uint64_t)0);
  941. rmd.add(ZT_NETWORKCONFIG_REQUEST_METADATA_KEY_RULES_ENGINE_REV,(uint64_t)ZT_RULES_ENGINE_REVISION);
  942. if (ctrl == RR->identity.address()) {
  943. if (RR->localNetworkController) {
  944. NetworkConfig nconf;
  945. switch(RR->localNetworkController->doNetworkConfigRequest(InetAddress(),RR->identity,RR->identity,_id,rmd,nconf)) {
  946. case NetworkController::NETCONF_QUERY_OK:
  947. this->setConfiguration(nconf,true);
  948. return;
  949. case NetworkController::NETCONF_QUERY_OBJECT_NOT_FOUND:
  950. this->setNotFound();
  951. return;
  952. case NetworkController::NETCONF_QUERY_ACCESS_DENIED:
  953. this->setAccessDenied();
  954. return;
  955. default:
  956. return;
  957. }
  958. } else {
  959. this->setNotFound();
  960. return;
  961. }
  962. }
  963. TRACE("requesting netconf for network %.16llx from controller %s",(unsigned long long)_id,ctrl.toString().c_str());
  964. Packet outp(ctrl,RR->identity.address(),Packet::VERB_NETWORK_CONFIG_REQUEST);
  965. outp.append((uint64_t)_id);
  966. const unsigned int rmdSize = rmd.sizeBytes();
  967. outp.append((uint16_t)rmdSize);
  968. outp.append((const void *)rmd.data(),rmdSize);
  969. if (_config) {
  970. outp.append((uint64_t)_config.revision);
  971. outp.append((uint64_t)_config.timestamp);
  972. } else {
  973. outp.append((unsigned char)0,16);
  974. }
  975. outp.compress();
  976. RR->sw->send(outp,true);
  977. // Expect replies with this in-re packet ID
  978. _inboundConfigPacketId = outp.packetId();
  979. _inboundConfigChunks.clear();
  980. }
  981. void Network::clean()
  982. {
  983. const uint64_t now = RR->node->now();
  984. Mutex::Lock _l(_lock);
  985. if (_destroyed)
  986. return;
  987. {
  988. Hashtable< MulticastGroup,uint64_t >::Iterator i(_multicastGroupsBehindMe);
  989. MulticastGroup *mg = (MulticastGroup *)0;
  990. uint64_t *ts = (uint64_t *)0;
  991. while (i.next(mg,ts)) {
  992. if ((now - *ts) > (ZT_MULTICAST_LIKE_EXPIRE * 2))
  993. _multicastGroupsBehindMe.erase(*mg);
  994. }
  995. }
  996. {
  997. Address *a = (Address *)0;
  998. Membership *m = (Membership *)0;
  999. Hashtable<Address,Membership>::Iterator i(_memberships);
  1000. while (i.next(a,m)) {
  1001. if (RR->topology->getPeerNoCache(*a))
  1002. m->clean(_config);
  1003. else _memberships.erase(*a);
  1004. }
  1005. }
  1006. }
  1007. void Network::learnBridgeRoute(const MAC &mac,const Address &addr)
  1008. {
  1009. Mutex::Lock _l(_lock);
  1010. _remoteBridgeRoutes[mac] = addr;
  1011. // Anti-DOS circuit breaker to prevent nodes from spamming us with absurd numbers of bridge routes
  1012. while (_remoteBridgeRoutes.size() > ZT_MAX_BRIDGE_ROUTES) {
  1013. Hashtable< Address,unsigned long > counts;
  1014. Address maxAddr;
  1015. unsigned long maxCount = 0;
  1016. MAC *m = (MAC *)0;
  1017. Address *a = (Address *)0;
  1018. // Find the address responsible for the most entries
  1019. {
  1020. Hashtable<MAC,Address>::Iterator i(_remoteBridgeRoutes);
  1021. while (i.next(m,a)) {
  1022. const unsigned long c = ++counts[*a];
  1023. if (c > maxCount) {
  1024. maxCount = c;
  1025. maxAddr = *a;
  1026. }
  1027. }
  1028. }
  1029. // Kill this address from our table, since it's most likely spamming us
  1030. {
  1031. Hashtable<MAC,Address>::Iterator i(_remoteBridgeRoutes);
  1032. while (i.next(m,a)) {
  1033. if (*a == maxAddr)
  1034. _remoteBridgeRoutes.erase(*m);
  1035. }
  1036. }
  1037. }
  1038. }
  1039. void Network::learnBridgedMulticastGroup(const MulticastGroup &mg,uint64_t now)
  1040. {
  1041. Mutex::Lock _l(_lock);
  1042. const unsigned long tmp = (unsigned long)_multicastGroupsBehindMe.size();
  1043. _multicastGroupsBehindMe.set(mg,now);
  1044. if (tmp != _multicastGroupsBehindMe.size())
  1045. _announceMulticastGroups(&mg);
  1046. }
  1047. void Network::destroy()
  1048. {
  1049. Mutex::Lock _l(_lock);
  1050. _destroyed = true;
  1051. }
  1052. ZT_VirtualNetworkStatus Network::_status() const
  1053. {
  1054. // assumes _lock is locked
  1055. if (_portError)
  1056. return ZT_NETWORK_STATUS_PORT_ERROR;
  1057. switch(_netconfFailure) {
  1058. case NETCONF_FAILURE_ACCESS_DENIED:
  1059. return ZT_NETWORK_STATUS_ACCESS_DENIED;
  1060. case NETCONF_FAILURE_NOT_FOUND:
  1061. return ZT_NETWORK_STATUS_NOT_FOUND;
  1062. case NETCONF_FAILURE_NONE:
  1063. return ((_config) ? ZT_NETWORK_STATUS_OK : ZT_NETWORK_STATUS_REQUESTING_CONFIGURATION);
  1064. default:
  1065. return ZT_NETWORK_STATUS_PORT_ERROR;
  1066. }
  1067. }
  1068. void Network::_externalConfig(ZT_VirtualNetworkConfig *ec) const
  1069. {
  1070. // assumes _lock is locked
  1071. ec->nwid = _id;
  1072. ec->mac = _mac.toInt();
  1073. if (_config)
  1074. Utils::scopy(ec->name,sizeof(ec->name),_config.name);
  1075. else ec->name[0] = (char)0;
  1076. ec->status = _status();
  1077. ec->type = (_config) ? (_config.isPrivate() ? ZT_NETWORK_TYPE_PRIVATE : ZT_NETWORK_TYPE_PUBLIC) : ZT_NETWORK_TYPE_PRIVATE;
  1078. ec->mtu = ZT_IF_MTU;
  1079. ec->dhcp = 0;
  1080. std::vector<Address> ab(_config.activeBridges());
  1081. ec->bridge = ((_config.allowPassiveBridging())||(std::find(ab.begin(),ab.end(),RR->identity.address()) != ab.end())) ? 1 : 0;
  1082. ec->broadcastEnabled = (_config) ? (_config.enableBroadcast() ? 1 : 0) : 0;
  1083. ec->portError = _portError;
  1084. ec->netconfRevision = (_config) ? (unsigned long)_config.revision : 0;
  1085. ec->assignedAddressCount = 0;
  1086. for(unsigned int i=0;i<ZT_MAX_ZT_ASSIGNED_ADDRESSES;++i) {
  1087. if (i < _config.staticIpCount) {
  1088. memcpy(&(ec->assignedAddresses[i]),&(_config.staticIps[i]),sizeof(struct sockaddr_storage));
  1089. ++ec->assignedAddressCount;
  1090. } else {
  1091. memset(&(ec->assignedAddresses[i]),0,sizeof(struct sockaddr_storage));
  1092. }
  1093. }
  1094. ec->routeCount = 0;
  1095. for(unsigned int i=0;i<ZT_MAX_NETWORK_ROUTES;++i) {
  1096. if (i < _config.routeCount) {
  1097. memcpy(&(ec->routes[i]),&(_config.routes[i]),sizeof(ZT_VirtualNetworkRoute));
  1098. ++ec->routeCount;
  1099. } else {
  1100. memset(&(ec->routes[i]),0,sizeof(ZT_VirtualNetworkRoute));
  1101. }
  1102. }
  1103. }
  1104. bool Network::_isAllowed(const SharedPtr<Peer> &peer) const
  1105. {
  1106. // Assumes _lock is locked
  1107. try {
  1108. if (_config) {
  1109. const Membership *const m = _memberships.get(peer->address());
  1110. if (m)
  1111. return m->isAllowedOnNetwork(_config);
  1112. }
  1113. } catch ( ... ) {
  1114. TRACE("isAllowed() check failed for peer %s: unexpected exception",peer->address().toString().c_str());
  1115. }
  1116. return false;
  1117. }
  1118. void Network::_announceMulticastGroups(const MulticastGroup *const onlyThis)
  1119. {
  1120. // Assumes _lock is locked
  1121. const uint64_t now = RR->node->now();
  1122. std::vector<MulticastGroup> groups;
  1123. if (onlyThis)
  1124. groups.push_back(*onlyThis);
  1125. else groups = _allMulticastGroups();
  1126. if ((onlyThis)||((now - _lastAnnouncedMulticastGroupsUpstream) >= ZT_MULTICAST_ANNOUNCE_PERIOD)) {
  1127. if (!onlyThis)
  1128. _lastAnnouncedMulticastGroupsUpstream = now;
  1129. // Announce multicast groups to upstream peers (roots, etc.) and also send
  1130. // them our COM so that MULTICAST_GATHER can be authenticated properly.
  1131. const std::vector<Address> upstreams(RR->topology->upstreamAddresses());
  1132. for(std::vector<Address>::const_iterator a(upstreams.begin());a!=upstreams.end();++a) {
  1133. if ((_config.isPrivate())&&(_config.com)) {
  1134. Packet outp(*a,RR->identity.address(),Packet::VERB_NETWORK_CREDENTIALS);
  1135. _config.com.serialize(outp);
  1136. outp.append((uint8_t)0x00);
  1137. RR->sw->send(outp,true);
  1138. }
  1139. _announceMulticastGroupsTo(*a,groups);
  1140. }
  1141. }
  1142. // Make sure that all "network anchors" have Membership records so we will
  1143. // push multicasts to them.
  1144. const std::vector<Address> anchors(_config.anchors());
  1145. for(std::vector<Address>::const_iterator a(anchors.begin());a!=anchors.end();++a)
  1146. _memberships[*a];
  1147. // Send MULTICAST_LIKE(s) to all members of this network
  1148. {
  1149. Address *a = (Address *)0;
  1150. Membership *m = (Membership *)0;
  1151. Hashtable<Address,Membership>::Iterator i(_memberships);
  1152. while (i.next(a,m)) {
  1153. if ((onlyThis)||(m->shouldLikeMulticasts(now))) {
  1154. if (!onlyThis)
  1155. m->likingMulticasts(now);
  1156. m->sendCredentialsIfNeeded(RR,RR->node->now(),*a,_config,(const Capability *)0);
  1157. _announceMulticastGroupsTo(*a,groups);
  1158. }
  1159. }
  1160. }
  1161. }
  1162. void Network::_announceMulticastGroupsTo(const Address &peer,const std::vector<MulticastGroup> &allMulticastGroups)
  1163. {
  1164. // Assumes _lock is locked
  1165. Packet outp(peer,RR->identity.address(),Packet::VERB_MULTICAST_LIKE);
  1166. for(std::vector<MulticastGroup>::const_iterator mg(allMulticastGroups.begin());mg!=allMulticastGroups.end();++mg) {
  1167. if ((outp.size() + 24) >= ZT_PROTO_MAX_PACKET_LENGTH) {
  1168. outp.compress();
  1169. RR->sw->send(outp,true);
  1170. outp.reset(peer,RR->identity.address(),Packet::VERB_MULTICAST_LIKE);
  1171. }
  1172. // network ID, MAC, ADI
  1173. outp.append((uint64_t)_id);
  1174. mg->mac().appendTo(outp);
  1175. outp.append((uint32_t)mg->adi());
  1176. }
  1177. if (outp.size() > ZT_PROTO_MIN_PACKET_LENGTH) {
  1178. outp.compress();
  1179. RR->sw->send(outp,true);
  1180. }
  1181. }
  1182. std::vector<MulticastGroup> Network::_allMulticastGroups() const
  1183. {
  1184. // Assumes _lock is locked
  1185. std::vector<MulticastGroup> mgs;
  1186. mgs.reserve(_myMulticastGroups.size() + _multicastGroupsBehindMe.size() + 1);
  1187. mgs.insert(mgs.end(),_myMulticastGroups.begin(),_myMulticastGroups.end());
  1188. _multicastGroupsBehindMe.appendKeys(mgs);
  1189. if ((_config)&&(_config.enableBroadcast()))
  1190. mgs.push_back(Network::BROADCAST);
  1191. std::sort(mgs.begin(),mgs.end());
  1192. mgs.erase(std::unique(mgs.begin(),mgs.end()),mgs.end());
  1193. return mgs;
  1194. }
  1195. } // namespace ZeroTier