Network.cpp 54 KB

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