Network.cpp 51 KB

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