Network.cpp 53 KB

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