Network.cpp 56 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429
  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_WATCH: return "ACTION_WATCH";
  48. case ZT_NETWORK_RULE_ACTION_REDIRECT: return "ACTION_REDIRECT";
  49. case ZT_NETWORK_RULE_ACTION_DEBUG_LOG: return "ACTION_DEBUG_LOG";
  50. case ZT_NETWORK_RULE_MATCH_SOURCE_ZEROTIER_ADDRESS: return "MATCH_SOURCE_ZEROTIER_ADDRESS";
  51. case ZT_NETWORK_RULE_MATCH_DEST_ZEROTIER_ADDRESS: return "MATCH_DEST_ZEROTIER_ADDRESS";
  52. case ZT_NETWORK_RULE_MATCH_VLAN_ID: return "MATCH_VLAN_ID";
  53. case ZT_NETWORK_RULE_MATCH_VLAN_PCP: return "MATCH_VLAN_PCP";
  54. case ZT_NETWORK_RULE_MATCH_VLAN_DEI: return "MATCH_VLAN_DEI";
  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_ETHERTYPE: return "MATCH_ETHERTYPE";
  64. case ZT_NETWORK_RULE_MATCH_ICMP: return "MATCH_ICMP";
  65. case ZT_NETWORK_RULE_MATCH_IP_SOURCE_PORT_RANGE: return "MATCH_IP_SOURCE_PORT_RANGE";
  66. case ZT_NETWORK_RULE_MATCH_IP_DEST_PORT_RANGE: return "MATCH_IP_DEST_PORT_RANGE";
  67. case ZT_NETWORK_RULE_MATCH_CHARACTERISTICS: return "MATCH_CHARACTERISTICS";
  68. case ZT_NETWORK_RULE_MATCH_FRAME_SIZE_RANGE: return "MATCH_FRAME_SIZE_RANGE";
  69. case ZT_NETWORK_RULE_MATCH_TAGS_DIFFERENCE: return "MATCH_TAGS_DIFFERENCE";
  70. case ZT_NETWORK_RULE_MATCH_TAGS_BITWISE_AND: return "MATCH_TAGS_BITWISE_AND";
  71. case ZT_NETWORK_RULE_MATCH_TAGS_BITWISE_OR: return "MATCH_TAGS_BITWISE_OR";
  72. case ZT_NETWORK_RULE_MATCH_TAGS_BITWISE_XOR: return "MATCH_TAGS_BITWISE_XOR";
  73. default: return "???";
  74. }
  75. }
  76. 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)
  77. {
  78. static volatile unsigned long cnt = 0;
  79. printf("%.6lu %c %s %s frameLen=%u etherType=%u" ZT_EOL_S,
  80. cnt++,
  81. ((thisSetMatches) ? 'Y' : '.'),
  82. ruleName,
  83. ((inbound) ? "INBOUND" : "OUTBOUND"),
  84. frameLen,
  85. etherType
  86. );
  87. for(std::vector<std::string>::const_iterator m(dlog.begin());m!=dlog.end();++m)
  88. printf(" | %s" ZT_EOL_S,m->c_str());
  89. printf(" + %c %s->%s %.2x:%.2x:%.2x:%.2x:%.2x:%.2x->%.2x:%.2x:%.2x:%.2x:%.2x:%.2x" ZT_EOL_S,
  90. ((thisSetMatches) ? 'Y' : '.'),
  91. ztSource.toString().c_str(),
  92. ztDest.toString().c_str(),
  93. (unsigned int)macSource[0],
  94. (unsigned int)macSource[1],
  95. (unsigned int)macSource[2],
  96. (unsigned int)macSource[3],
  97. (unsigned int)macSource[4],
  98. (unsigned int)macSource[5],
  99. (unsigned int)macDest[0],
  100. (unsigned int)macDest[1],
  101. (unsigned int)macDest[2],
  102. (unsigned int)macDest[3],
  103. (unsigned int)macDest[4],
  104. (unsigned int)macDest[5]
  105. );
  106. if (msg)
  107. printf(" + (%s)" ZT_EOL_S,msg);
  108. fflush(stdout);
  109. }
  110. #else
  111. #define FILTER_TRACE(f,...) {}
  112. #endif // ZT_RULES_ENGINE_DEBUGGING
  113. // Returns true if packet appears valid; pos and proto will be set
  114. static bool _ipv6GetPayload(const uint8_t *frameData,unsigned int frameLen,unsigned int &pos,unsigned int &proto)
  115. {
  116. if (frameLen < 40)
  117. return false;
  118. pos = 40;
  119. proto = frameData[6];
  120. while (pos <= frameLen) {
  121. switch(proto) {
  122. case 0: // hop-by-hop options
  123. case 43: // routing
  124. case 60: // destination options
  125. case 135: // mobility options
  126. if ((pos + 8) > frameLen)
  127. return false; // invalid!
  128. proto = frameData[pos];
  129. pos += ((unsigned int)frameData[pos + 1] * 8) + 8;
  130. break;
  131. //case 44: // fragment -- we currently can't parse these and they are deprecated in IPv6 anyway
  132. //case 50:
  133. //case 51: // IPSec ESP and AH -- we have to stop here since this is encrypted stuff
  134. default:
  135. return true;
  136. }
  137. }
  138. return false; // overflow == invalid
  139. }
  140. enum _doZtFilterResult
  141. {
  142. DOZTFILTER_NO_MATCH,
  143. DOZTFILTER_DROP,
  144. DOZTFILTER_REDIRECT,
  145. DOZTFILTER_ACCEPT,
  146. DOZTFILTER_SUPER_ACCEPT
  147. };
  148. static _doZtFilterResult _doZtFilter(
  149. const RuntimeEnvironment *RR,
  150. const NetworkConfig &nconf,
  151. const Membership *membership, // can be NULL
  152. const bool inbound,
  153. const Address &ztSource,
  154. Address &ztDest, // MUTABLE -- is changed on REDIRECT actions
  155. const MAC &macSource,
  156. const MAC &macDest,
  157. const uint8_t *const frameData,
  158. const unsigned int frameLen,
  159. const unsigned int etherType,
  160. const unsigned int vlanId,
  161. const ZT_VirtualNetworkRule *rules, // cannot be NULL
  162. const unsigned int ruleCount,
  163. Address &cc, // MUTABLE -- set to TEE destination if TEE action is taken or left alone otherwise
  164. unsigned int &ccLength, // MUTABLE -- set to length of packet payload to TEE
  165. bool &ccWatch) // MUTABLE -- set to true for WATCH target as opposed to normal TEE
  166. {
  167. #ifdef ZT_RULES_ENGINE_DEBUGGING
  168. char dpbuf[1024]; // used by FILTER_TRACE macro
  169. std::vector<std::string> dlog;
  170. #endif // ZT_RULES_ENGINE_DEBUGGING
  171. // The default match state for each set of entries starts as 'true' since an
  172. // ACTION with no MATCH entries preceding it is always taken.
  173. uint8_t thisSetMatches = 1;
  174. for(unsigned int rn=0;rn<ruleCount;++rn) {
  175. const ZT_VirtualNetworkRuleType rt = (ZT_VirtualNetworkRuleType)(rules[rn].t & 0x3f);
  176. // First check if this is an ACTION
  177. if ((unsigned int)rt <= (unsigned int)ZT_NETWORK_RULE_ACTION__MAX_ID) {
  178. if (thisSetMatches) {
  179. switch(rt) {
  180. case ZT_NETWORK_RULE_ACTION_DROP:
  181. #ifdef ZT_RULES_ENGINE_DEBUGGING
  182. _dumpFilterTrace("ACTION_DROP",thisSetMatches,inbound,ztSource,ztDest,macSource,macDest,dlog,frameLen,etherType,(const char *)0);
  183. #endif // ZT_RULES_ENGINE_DEBUGGING
  184. return DOZTFILTER_DROP;
  185. case ZT_NETWORK_RULE_ACTION_ACCEPT:
  186. #ifdef ZT_RULES_ENGINE_DEBUGGING
  187. _dumpFilterTrace("ACTION_ACCEPT",thisSetMatches,inbound,ztSource,ztDest,macSource,macDest,dlog,frameLen,etherType,(const char *)0);
  188. #endif // ZT_RULES_ENGINE_DEBUGGING
  189. return DOZTFILTER_ACCEPT; // match, accept packet
  190. // These are initially handled together since preliminary logic is common
  191. case ZT_NETWORK_RULE_ACTION_TEE:
  192. case ZT_NETWORK_RULE_ACTION_WATCH:
  193. case ZT_NETWORK_RULE_ACTION_REDIRECT: {
  194. const Address fwdAddr(rules[rn].v.fwd.address);
  195. if (fwdAddr == ztSource) {
  196. #ifdef ZT_RULES_ENGINE_DEBUGGING
  197. _dumpFilterTrace(_rtn(rt),thisSetMatches,inbound,ztSource,ztDest,macSource,macDest,dlog,frameLen,etherType,"skipped as no-op since source is target");
  198. dlog.clear();
  199. #endif // ZT_RULES_ENGINE_DEBUGGING
  200. } else if (fwdAddr == RR->identity.address()) {
  201. if (inbound) {
  202. #ifdef ZT_RULES_ENGINE_DEBUGGING
  203. _dumpFilterTrace(_rtn(rt),thisSetMatches,inbound,ztSource,ztDest,macSource,macDest,dlog,frameLen,etherType,"interpreted as super-ACCEPT on inbound since we are target");
  204. #endif // ZT_RULES_ENGINE_DEBUGGING
  205. return DOZTFILTER_SUPER_ACCEPT;
  206. } else {
  207. #ifdef ZT_RULES_ENGINE_DEBUGGING
  208. _dumpFilterTrace(_rtn(rt),thisSetMatches,inbound,ztSource,ztDest,macSource,macDest,dlog,frameLen,etherType,"skipped as no-op on outbound since we are target");
  209. dlog.clear();
  210. #endif // ZT_RULES_ENGINE_DEBUGGING
  211. }
  212. } else if (fwdAddr == ztDest) {
  213. #ifdef ZT_RULES_ENGINE_DEBUGGING
  214. _dumpFilterTrace(_rtn(rt),thisSetMatches,inbound,ztSource,ztDest,macSource,macDest,dlog,frameLen,etherType,"skipped as no-op because destination is already target");
  215. dlog.clear();
  216. #endif // ZT_RULES_ENGINE_DEBUGGING
  217. } else {
  218. if (rt == ZT_NETWORK_RULE_ACTION_REDIRECT) {
  219. #ifdef ZT_RULES_ENGINE_DEBUGGING
  220. _dumpFilterTrace("ACTION_REDIRECT",thisSetMatches,inbound,ztSource,ztDest,macSource,macDest,dlog,frameLen,etherType,(const char *)0);
  221. #endif // ZT_RULES_ENGINE_DEBUGGING
  222. ztDest = fwdAddr;
  223. return DOZTFILTER_REDIRECT;
  224. } else {
  225. #ifdef ZT_RULES_ENGINE_DEBUGGING
  226. _dumpFilterTrace("ACTION_TEE",thisSetMatches,inbound,ztSource,ztDest,macSource,macDest,dlog,frameLen,etherType,(const char *)0);
  227. dlog.clear();
  228. #endif // ZT_RULES_ENGINE_DEBUGGING
  229. cc = fwdAddr;
  230. ccLength = (rules[rn].v.fwd.length != 0) ? ((frameLen < (unsigned int)rules[rn].v.fwd.length) ? frameLen : (unsigned int)rules[rn].v.fwd.length) : frameLen;
  231. ccWatch = (rt == ZT_NETWORK_RULE_ACTION_WATCH);
  232. }
  233. }
  234. } continue;
  235. // This is a no-op that exists for use with rules engine tracing and isn't for use in production
  236. case ZT_NETWORK_RULE_ACTION_DEBUG_LOG: // a no-op target specifically for debugging purposes
  237. #ifdef ZT_RULES_ENGINE_DEBUGGING
  238. _dumpFilterTrace("ACTION_DEBUG_LOG",thisSetMatches,inbound,ztSource,ztDest,macSource,macDest,dlog,frameLen,etherType,(const char *)0);
  239. dlog.clear();
  240. #endif // ZT_RULES_ENGINE_DEBUGGING
  241. continue;
  242. // Unrecognized ACTIONs are ignored as no-ops
  243. default:
  244. #ifdef ZT_RULES_ENGINE_DEBUGGING
  245. _dumpFilterTrace(_rtn(rt),thisSetMatches,inbound,ztSource,ztDest,macSource,macDest,dlog,frameLen,etherType,(const char *)0);
  246. dlog.clear();
  247. #endif // ZT_RULES_ENGINE_DEBUGGING
  248. continue;
  249. }
  250. } else {
  251. #ifdef ZT_RULES_ENGINE_DEBUGGING
  252. _dumpFilterTrace(_rtn(rt),thisSetMatches,inbound,ztSource,ztDest,macSource,macDest,dlog,frameLen,etherType,(const char *)0);
  253. dlog.clear();
  254. #endif // ZT_RULES_ENGINE_DEBUGGING
  255. thisSetMatches = 1; // reset to default true for next batch of entries
  256. continue;
  257. }
  258. }
  259. // Circuit breaker: no need to evaluate an AND if the set's match state
  260. // is currently false since anything AND false is false.
  261. if ((!thisSetMatches)&&(!(rules[rn].t & 0x40)))
  262. continue;
  263. // If this was not an ACTION evaluate next MATCH and update thisSetMatches with (AND [result])
  264. uint8_t thisRuleMatches = 0;
  265. switch(rt) {
  266. case ZT_NETWORK_RULE_MATCH_SOURCE_ZEROTIER_ADDRESS:
  267. thisRuleMatches = (uint8_t)(rules[rn].v.zt == ztSource.toInt());
  268. 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);
  269. break;
  270. case ZT_NETWORK_RULE_MATCH_DEST_ZEROTIER_ADDRESS:
  271. thisRuleMatches = (uint8_t)(rules[rn].v.zt == ztDest.toInt());
  272. 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);
  273. break;
  274. case ZT_NETWORK_RULE_MATCH_VLAN_ID:
  275. thisRuleMatches = (uint8_t)(rules[rn].v.vlanId == (uint16_t)vlanId);
  276. 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);
  277. break;
  278. case ZT_NETWORK_RULE_MATCH_VLAN_PCP:
  279. // NOT SUPPORTED YET
  280. thisRuleMatches = (uint8_t)(rules[rn].v.vlanPcp == 0);
  281. 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);
  282. break;
  283. case ZT_NETWORK_RULE_MATCH_VLAN_DEI:
  284. // NOT SUPPORTED YET
  285. thisRuleMatches = (uint8_t)(rules[rn].v.vlanDei == 0);
  286. 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);
  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_ETHERTYPE:
  364. thisRuleMatches = (uint8_t)(rules[rn].v.etherType == (uint16_t)etherType);
  365. 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);
  366. break;
  367. case ZT_NETWORK_RULE_MATCH_ICMP:
  368. if ((etherType == ZT_ETHERTYPE_IPV4)&&(frameLen >= 20)) {
  369. if (frameData[9] == 0x01) { // IP protocol == ICMP
  370. const unsigned int ihl = (frameData[0] & 0xf) * 4;
  371. if (frameLen >= (ihl + 2)) {
  372. if (rules[rn].v.icmp.type == frameData[ihl]) {
  373. if ((rules[rn].v.icmp.flags & 0x01) != 0) {
  374. thisRuleMatches = (uint8_t)(frameData[ihl+1] == rules[rn].v.icmp.code);
  375. } else {
  376. thisRuleMatches = 1;
  377. }
  378. } else {
  379. thisRuleMatches = 0;
  380. }
  381. 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);
  382. } else {
  383. thisRuleMatches = 0;
  384. FILTER_TRACE("%u %s %c [IPv4 frame invalid] -> 0",rn,_rtn(rt),(((rules[rn].t & 0x80) != 0) ? '!' : '='));
  385. }
  386. } else {
  387. thisRuleMatches = 0;
  388. FILTER_TRACE("%u %s %c [frame not ICMP] -> 0",rn,_rtn(rt),(((rules[rn].t & 0x80) != 0) ? '!' : '='));
  389. }
  390. } else if (etherType == ZT_ETHERTYPE_IPV6) {
  391. unsigned int pos = 0,proto = 0;
  392. if (_ipv6GetPayload(frameData,frameLen,pos,proto)) {
  393. if ((proto == 0x3a)&&(frameLen >= (pos+2))) {
  394. if (rules[rn].v.icmp.type == frameData[pos]) {
  395. if ((rules[rn].v.icmp.flags & 0x01) != 0) {
  396. thisRuleMatches = (uint8_t)(frameData[pos+1] == rules[rn].v.icmp.code);
  397. } else {
  398. thisRuleMatches = 1;
  399. }
  400. } else {
  401. thisRuleMatches = 0;
  402. }
  403. FILTER_TRACE("%u %s %c (IPv6) 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);
  404. } else {
  405. thisRuleMatches = 0;
  406. FILTER_TRACE("%u %s %c [frame not ICMPv6] -> 0",rn,_rtn(rt),(((rules[rn].t & 0x80) != 0) ? '!' : '='));
  407. }
  408. } else {
  409. thisRuleMatches = 0;
  410. FILTER_TRACE("%u %s %c [invalid IPv6] -> 0",rn,_rtn(rt),(((rules[rn].t & 0x80) != 0) ? '!' : '='));
  411. }
  412. } else {
  413. thisRuleMatches = 0;
  414. FILTER_TRACE("%u %s %c [frame not IP] -> 0",rn,_rtn(rt),(((rules[rn].t & 0x80) != 0) ? '!' : '='));
  415. }
  416. break;
  417. break;
  418. case ZT_NETWORK_RULE_MATCH_IP_SOURCE_PORT_RANGE:
  419. case ZT_NETWORK_RULE_MATCH_IP_DEST_PORT_RANGE:
  420. if ((etherType == ZT_ETHERTYPE_IPV4)&&(frameLen >= 20)) {
  421. const unsigned int headerLen = 4 * (frameData[0] & 0xf);
  422. int p = -1;
  423. switch(frameData[9]) { // IP protocol number
  424. // All these start with 16-bit source and destination port in that order
  425. case 0x06: // TCP
  426. case 0x11: // UDP
  427. case 0x84: // SCTP
  428. case 0x88: // UDPLite
  429. if (frameLen > (headerLen + 4)) {
  430. unsigned int pos = headerLen + ((rt == ZT_NETWORK_RULE_MATCH_IP_DEST_PORT_RANGE) ? 2 : 0);
  431. p = (int)frameData[pos++] << 8;
  432. p |= (int)frameData[pos];
  433. }
  434. break;
  435. }
  436. thisRuleMatches = (p >= 0) ? (uint8_t)((p >= (int)rules[rn].v.port[0])&&(p <= (int)rules[rn].v.port[1])) : (uint8_t)0;
  437. 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);
  438. } else if (etherType == ZT_ETHERTYPE_IPV6) {
  439. unsigned int pos = 0,proto = 0;
  440. if (_ipv6GetPayload(frameData,frameLen,pos,proto)) {
  441. int p = -1;
  442. switch(proto) { // IP protocol number
  443. // All these start with 16-bit source and destination port in that order
  444. case 0x06: // TCP
  445. case 0x11: // UDP
  446. case 0x84: // SCTP
  447. case 0x88: // UDPLite
  448. if (frameLen > (pos + 4)) {
  449. if (rt == ZT_NETWORK_RULE_MATCH_IP_DEST_PORT_RANGE) pos += 2;
  450. p = (int)frameData[pos++] << 8;
  451. p |= (int)frameData[pos];
  452. }
  453. break;
  454. }
  455. thisRuleMatches = (p > 0) ? (uint8_t)((p >= (int)rules[rn].v.port[0])&&(p <= (int)rules[rn].v.port[1])) : (uint8_t)0;
  456. 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);
  457. } else {
  458. thisRuleMatches = 0;
  459. FILTER_TRACE("%u %s %c [invalid IPv6] -> 0",rn,_rtn(rt),(((rules[rn].t & 0x80) != 0) ? '!' : '='));
  460. }
  461. } else {
  462. thisRuleMatches = 0;
  463. FILTER_TRACE("%u %s %c [frame not IP] -> 0",rn,_rtn(rt),(((rules[rn].t & 0x80) != 0) ? '!' : '='));
  464. }
  465. break;
  466. case ZT_NETWORK_RULE_MATCH_CHARACTERISTICS: {
  467. uint64_t cf = (inbound) ? ZT_RULE_PACKET_CHARACTERISTICS_INBOUND : 0ULL;
  468. if (macDest.isMulticast()) cf |= ZT_RULE_PACKET_CHARACTERISTICS_MULTICAST;
  469. if (macDest.isBroadcast()) cf |= ZT_RULE_PACKET_CHARACTERISTICS_BROADCAST;
  470. if ((etherType == ZT_ETHERTYPE_IPV4)&&(frameLen >= 20)&&(frameData[9] == 0x06)) {
  471. const unsigned int headerLen = 4 * (frameData[0] & 0xf);
  472. cf |= (uint64_t)frameData[headerLen + 13];
  473. cf |= (((uint64_t)(frameData[headerLen + 12] & 0x0f)) << 8);
  474. } else if (etherType == ZT_ETHERTYPE_IPV6) {
  475. unsigned int pos = 0,proto = 0;
  476. if (_ipv6GetPayload(frameData,frameLen,pos,proto)) {
  477. if ((proto == 0x06)&&(frameLen > (pos + 14))) {
  478. cf |= (uint64_t)frameData[pos + 13];
  479. cf |= (((uint64_t)(frameData[pos + 12] & 0x0f)) << 8);
  480. }
  481. }
  482. }
  483. thisRuleMatches = (uint8_t)((cf & rules[rn].v.characteristics) != 0);
  484. FILTER_TRACE("%u %s %c (%.16llx | %.16llx)!=0 -> %u",rn,_rtn(rt),(((rules[rn].t & 0x80) != 0) ? '!' : '='),cf,rules[rn].v.characteristics,(unsigned int)thisRuleMatches);
  485. } break;
  486. case ZT_NETWORK_RULE_MATCH_FRAME_SIZE_RANGE:
  487. thisRuleMatches = (uint8_t)((frameLen >= (unsigned int)rules[rn].v.frameSize[0])&&(frameLen <= (unsigned int)rules[rn].v.frameSize[1]));
  488. 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);
  489. break;
  490. case ZT_NETWORK_RULE_MATCH_RANDOM:
  491. thisRuleMatches = (uint8_t)((uint32_t)(RR->node->prng() & 0xffffffffULL) <= rules[rn].v.randomProbability);
  492. FILTER_TRACE("%u %s %c -> %u",rn,_rtn(rt),(((rules[rn].t & 0x80) != 0) ? '!' : '='),(unsigned int)thisRuleMatches);
  493. break;
  494. case ZT_NETWORK_RULE_MATCH_TAGS_DIFFERENCE:
  495. case ZT_NETWORK_RULE_MATCH_TAGS_BITWISE_AND:
  496. case ZT_NETWORK_RULE_MATCH_TAGS_BITWISE_OR:
  497. case ZT_NETWORK_RULE_MATCH_TAGS_BITWISE_XOR:
  498. case ZT_NETWORK_RULE_MATCH_TAGS_EQUAL: {
  499. const Tag *const localTag = std::lower_bound(&(nconf.tags[0]),&(nconf.tags[nconf.tagCount]),rules[rn].v.tag.id,Tag::IdComparePredicate());
  500. if ((localTag != &(nconf.tags[nconf.tagCount]))&&(localTag->id() == rules[rn].v.tag.id)) {
  501. const Tag *const remoteTag = ((membership) ? membership->getTag(nconf,rules[rn].v.tag.id) : (const Tag *)0);
  502. if (remoteTag) {
  503. const uint32_t ltv = localTag->value();
  504. const uint32_t rtv = remoteTag->value();
  505. if (rt == ZT_NETWORK_RULE_MATCH_TAGS_DIFFERENCE) {
  506. const uint32_t diff = (ltv > rtv) ? (ltv - rtv) : (rtv - ltv);
  507. thisRuleMatches = (uint8_t)(diff <= rules[rn].v.tag.value);
  508. 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);
  509. } else if (rt == ZT_NETWORK_RULE_MATCH_TAGS_BITWISE_AND) {
  510. thisRuleMatches = (uint8_t)((ltv & rtv) == rules[rn].v.tag.value);
  511. 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);
  512. } else if (rt == ZT_NETWORK_RULE_MATCH_TAGS_BITWISE_OR) {
  513. thisRuleMatches = (uint8_t)((ltv | rtv) == rules[rn].v.tag.value);
  514. 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);
  515. } else if (rt == ZT_NETWORK_RULE_MATCH_TAGS_BITWISE_XOR) {
  516. thisRuleMatches = (uint8_t)((ltv ^ rtv) == rules[rn].v.tag.value);
  517. 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);
  518. } else if (rt == ZT_NETWORK_RULE_MATCH_TAGS_EQUAL) {
  519. thisRuleMatches = (uint8_t)((ltv == rules[rn].v.tag.value)&&(rtv == rules[rn].v.tag.value));
  520. FILTER_TRACE("%u %s %c TAG %u local:%.8x and 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);
  521. } else { // sanity check, can't really happen
  522. thisRuleMatches = 0;
  523. }
  524. } else {
  525. if (inbound) {
  526. thisRuleMatches = 0;
  527. 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);
  528. } else {
  529. thisRuleMatches = 1;
  530. 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);
  531. }
  532. }
  533. } else {
  534. thisRuleMatches = 0;
  535. 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);
  536. }
  537. } break;
  538. // The result of an unsupported MATCH is configurable at the network
  539. // level via a flag.
  540. default:
  541. thisRuleMatches = (uint8_t)((nconf.flags & ZT_NETWORKCONFIG_FLAG_RULES_RESULT_OF_UNSUPPORTED_MATCH) != 0);
  542. break;
  543. }
  544. if ((rules[rn].t & 0x40))
  545. thisSetMatches |= (thisRuleMatches ^ ((rules[rn].t >> 7) & 1));
  546. else thisSetMatches &= (thisRuleMatches ^ ((rules[rn].t >> 7) & 1));
  547. }
  548. return DOZTFILTER_NO_MATCH;
  549. }
  550. } // anonymous namespace
  551. const ZeroTier::MulticastGroup Network::BROADCAST(ZeroTier::MAC(0xffffffffffffULL),0);
  552. Network::Network(const RuntimeEnvironment *renv,uint64_t nwid,void *uptr) :
  553. RR(renv),
  554. _uPtr(uptr),
  555. _id(nwid),
  556. _lastAnnouncedMulticastGroupsUpstream(0),
  557. _mac(renv->identity.address(),nwid),
  558. _portInitialized(false),
  559. _lastConfigUpdate(0),
  560. _destroyed(false),
  561. _netconfFailure(NETCONF_FAILURE_NONE),
  562. _portError(0)
  563. {
  564. for(int i=0;i<ZT_NETWORK_MAX_INCOMING_UPDATES;++i)
  565. _incomingConfigChunks[i].ts = 0;
  566. char confn[128];
  567. Utils::snprintf(confn,sizeof(confn),"networks.d/%.16llx.conf",_id);
  568. bool gotConf = false;
  569. Dictionary<ZT_NETWORKCONFIG_DICT_CAPACITY> *dconf = new Dictionary<ZT_NETWORKCONFIG_DICT_CAPACITY>();
  570. NetworkConfig *nconf = new NetworkConfig();
  571. try {
  572. std::string conf(RR->node->dataStoreGet(confn));
  573. if (conf.length()) {
  574. dconf->load(conf.c_str());
  575. if (nconf->fromDictionary(*dconf)) {
  576. this->setConfiguration(*nconf,false);
  577. _lastConfigUpdate = 0; // we still want to re-request a new config from the network
  578. gotConf = true;
  579. }
  580. }
  581. } catch ( ... ) {} // ignore invalids, we'll re-request
  582. delete nconf;
  583. delete dconf;
  584. if (!gotConf) {
  585. // Save a one-byte CR to persist membership while we request a real netconf
  586. RR->node->dataStorePut(confn,"\n",1,false);
  587. }
  588. if (!_portInitialized) {
  589. ZT_VirtualNetworkConfig ctmp;
  590. _externalConfig(&ctmp);
  591. _portError = RR->node->configureVirtualNetworkPort(_id,&_uPtr,ZT_VIRTUAL_NETWORK_CONFIG_OPERATION_UP,&ctmp);
  592. _portInitialized = true;
  593. }
  594. }
  595. Network::~Network()
  596. {
  597. ZT_VirtualNetworkConfig ctmp;
  598. _externalConfig(&ctmp);
  599. char n[128];
  600. if (_destroyed) {
  601. RR->node->configureVirtualNetworkPort(_id,&_uPtr,ZT_VIRTUAL_NETWORK_CONFIG_OPERATION_DESTROY,&ctmp);
  602. Utils::snprintf(n,sizeof(n),"networks.d/%.16llx.conf",_id);
  603. RR->node->dataStoreDelete(n);
  604. } else {
  605. RR->node->configureVirtualNetworkPort(_id,&_uPtr,ZT_VIRTUAL_NETWORK_CONFIG_OPERATION_DOWN,&ctmp);
  606. }
  607. }
  608. bool Network::filterOutgoingPacket(
  609. const bool noTee,
  610. const Address &ztSource,
  611. const Address &ztDest,
  612. const MAC &macSource,
  613. const MAC &macDest,
  614. const uint8_t *frameData,
  615. const unsigned int frameLen,
  616. const unsigned int etherType,
  617. const unsigned int vlanId)
  618. {
  619. const uint64_t now = RR->node->now();
  620. Address ztFinalDest(ztDest);
  621. int localCapabilityIndex = -1;
  622. bool accept = false;
  623. Mutex::Lock _l(_lock);
  624. Membership *const membership = (ztDest) ? _memberships.get(ztDest) : (Membership *)0;
  625. Address cc;
  626. unsigned int ccLength = 0;
  627. bool ccWatch = false;
  628. switch(_doZtFilter(RR,_config,membership,false,ztSource,ztFinalDest,macSource,macDest,frameData,frameLen,etherType,vlanId,_config.rules,_config.ruleCount,cc,ccLength,ccWatch)) {
  629. case DOZTFILTER_NO_MATCH:
  630. for(unsigned int c=0;c<_config.capabilityCount;++c) {
  631. ztFinalDest = ztDest; // sanity check, shouldn't be possible if there was no match
  632. Address cc2;
  633. unsigned int ccLength2 = 0;
  634. bool ccWatch2 = false;
  635. 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)) {
  636. case DOZTFILTER_NO_MATCH:
  637. case DOZTFILTER_DROP: // explicit DROP in a capability just terminates its evaluation and is an anti-pattern
  638. break;
  639. case DOZTFILTER_REDIRECT: // interpreted as ACCEPT but ztFinalDest will have been changed in _doZtFilter()
  640. case DOZTFILTER_ACCEPT:
  641. case DOZTFILTER_SUPER_ACCEPT: // no difference in behavior on outbound side
  642. localCapabilityIndex = (int)c;
  643. accept = true;
  644. if ((!noTee)&&(cc2)) {
  645. Membership &m2 = _membership(cc2);
  646. m2.pushCredentials(RR,now,cc2,_config,localCapabilityIndex,false);
  647. Packet outp(cc2,RR->identity.address(),Packet::VERB_EXT_FRAME);
  648. outp.append(_id);
  649. outp.append((uint8_t)(ccWatch2 ? 0x16 : 0x02));
  650. macDest.appendTo(outp);
  651. macSource.appendTo(outp);
  652. outp.append((uint16_t)etherType);
  653. outp.append(frameData,ccLength2);
  654. outp.compress();
  655. RR->sw->send(outp,true);
  656. }
  657. break;
  658. }
  659. if (accept)
  660. break;
  661. }
  662. break;
  663. case DOZTFILTER_DROP:
  664. return false;
  665. case DOZTFILTER_REDIRECT: // interpreted as ACCEPT but ztFinalDest will have been changed in _doZtFilter()
  666. case DOZTFILTER_ACCEPT:
  667. case DOZTFILTER_SUPER_ACCEPT: // no difference in behavior on outbound side
  668. accept = true;
  669. break;
  670. }
  671. if (accept) {
  672. if (membership)
  673. membership->pushCredentials(RR,now,ztDest,_config,localCapabilityIndex,false);
  674. if ((!noTee)&&(cc)) {
  675. Membership &m2 = _membership(cc);
  676. m2.pushCredentials(RR,now,cc,_config,localCapabilityIndex,false);
  677. Packet outp(cc,RR->identity.address(),Packet::VERB_EXT_FRAME);
  678. outp.append(_id);
  679. outp.append((uint8_t)(ccWatch ? 0x16 : 0x02));
  680. macDest.appendTo(outp);
  681. macSource.appendTo(outp);
  682. outp.append((uint16_t)etherType);
  683. outp.append(frameData,ccLength);
  684. outp.compress();
  685. RR->sw->send(outp,true);
  686. }
  687. if ((ztDest != ztFinalDest)&&(ztFinalDest)) {
  688. Membership &m2 = _membership(ztFinalDest);
  689. m2.pushCredentials(RR,now,ztFinalDest,_config,localCapabilityIndex,false);
  690. Packet outp(ztFinalDest,RR->identity.address(),Packet::VERB_EXT_FRAME);
  691. outp.append(_id);
  692. outp.append((uint8_t)0x04);
  693. macDest.appendTo(outp);
  694. macSource.appendTo(outp);
  695. outp.append((uint16_t)etherType);
  696. outp.append(frameData,frameLen);
  697. outp.compress();
  698. RR->sw->send(outp,true);
  699. return false; // DROP locally, since we redirected
  700. } else {
  701. return true;
  702. }
  703. } else {
  704. return false;
  705. }
  706. }
  707. int Network::filterIncomingPacket(
  708. const SharedPtr<Peer> &sourcePeer,
  709. const Address &ztDest,
  710. const MAC &macSource,
  711. const MAC &macDest,
  712. const uint8_t *frameData,
  713. const unsigned int frameLen,
  714. const unsigned int etherType,
  715. const unsigned int vlanId)
  716. {
  717. Address ztFinalDest(ztDest);
  718. int accept = 0;
  719. Mutex::Lock _l(_lock);
  720. Membership &membership = _membership(sourcePeer->address());
  721. Address cc;
  722. unsigned int ccLength = 0;
  723. bool ccWatch = false;
  724. switch (_doZtFilter(RR,_config,&membership,true,sourcePeer->address(),ztFinalDest,macSource,macDest,frameData,frameLen,etherType,vlanId,_config.rules,_config.ruleCount,cc,ccLength,ccWatch)) {
  725. case DOZTFILTER_NO_MATCH: {
  726. Membership::CapabilityIterator mci(membership,_config);
  727. const Capability *c;
  728. while ((c = mci.next())) {
  729. ztFinalDest = ztDest; // sanity check, should be unmodified if there was no match
  730. Address cc2;
  731. unsigned int ccLength2 = 0;
  732. bool ccWatch2 = false;
  733. switch(_doZtFilter(RR,_config,&membership,true,sourcePeer->address(),ztFinalDest,macSource,macDest,frameData,frameLen,etherType,vlanId,c->rules(),c->ruleCount(),cc2,ccLength2,ccWatch2)) {
  734. case DOZTFILTER_NO_MATCH:
  735. case DOZTFILTER_DROP: // explicit DROP in a capability just terminates its evaluation and is an anti-pattern
  736. break;
  737. case DOZTFILTER_REDIRECT: // interpreted as ACCEPT but ztDest will have been changed in _doZtFilter()
  738. case DOZTFILTER_ACCEPT:
  739. accept = 1; // ACCEPT
  740. break;
  741. case DOZTFILTER_SUPER_ACCEPT:
  742. accept = 2; // super-ACCEPT
  743. break;
  744. }
  745. if (accept) {
  746. if (cc2) {
  747. _membership(cc2).pushCredentials(RR,RR->node->now(),cc2,_config,-1,false);
  748. Packet outp(cc2,RR->identity.address(),Packet::VERB_EXT_FRAME);
  749. outp.append(_id);
  750. outp.append((uint8_t)(ccWatch2 ? 0x1c : 0x08));
  751. macDest.appendTo(outp);
  752. macSource.appendTo(outp);
  753. outp.append((uint16_t)etherType);
  754. outp.append(frameData,ccLength2);
  755. outp.compress();
  756. RR->sw->send(outp,true);
  757. }
  758. break;
  759. }
  760. }
  761. } break;
  762. case DOZTFILTER_DROP:
  763. return 0; // DROP
  764. case DOZTFILTER_REDIRECT: // interpreted as ACCEPT but ztFinalDest will have been changed in _doZtFilter()
  765. case DOZTFILTER_ACCEPT:
  766. accept = 1; // ACCEPT
  767. break;
  768. case DOZTFILTER_SUPER_ACCEPT:
  769. accept = 2; // super-ACCEPT
  770. break;
  771. }
  772. if (accept) {
  773. if (cc) {
  774. _membership(cc).pushCredentials(RR,RR->node->now(),cc,_config,-1,false);
  775. Packet outp(cc,RR->identity.address(),Packet::VERB_EXT_FRAME);
  776. outp.append(_id);
  777. outp.append((uint8_t)(ccWatch ? 0x1c : 0x08));
  778. macDest.appendTo(outp);
  779. macSource.appendTo(outp);
  780. outp.append((uint16_t)etherType);
  781. outp.append(frameData,ccLength);
  782. outp.compress();
  783. RR->sw->send(outp,true);
  784. }
  785. if ((ztDest != ztFinalDest)&&(ztFinalDest)) {
  786. _membership(ztFinalDest).pushCredentials(RR,RR->node->now(),ztFinalDest,_config,-1,false);
  787. Packet outp(ztFinalDest,RR->identity.address(),Packet::VERB_EXT_FRAME);
  788. outp.append(_id);
  789. outp.append((uint8_t)0x0a);
  790. macDest.appendTo(outp);
  791. macSource.appendTo(outp);
  792. outp.append((uint16_t)etherType);
  793. outp.append(frameData,frameLen);
  794. outp.compress();
  795. RR->sw->send(outp,true);
  796. return 0; // DROP locally, since we redirected
  797. }
  798. }
  799. return accept;
  800. }
  801. bool Network::subscribedToMulticastGroup(const MulticastGroup &mg,bool includeBridgedGroups) const
  802. {
  803. Mutex::Lock _l(_lock);
  804. if (std::binary_search(_myMulticastGroups.begin(),_myMulticastGroups.end(),mg))
  805. return true;
  806. else if (includeBridgedGroups)
  807. return _multicastGroupsBehindMe.contains(mg);
  808. return false;
  809. }
  810. void Network::multicastSubscribe(const MulticastGroup &mg)
  811. {
  812. Mutex::Lock _l(_lock);
  813. if (!std::binary_search(_myMulticastGroups.begin(),_myMulticastGroups.end(),mg)) {
  814. _myMulticastGroups.insert(std::upper_bound(_myMulticastGroups.begin(),_myMulticastGroups.end(),mg),mg);
  815. _sendUpdatesToMembers(&mg);
  816. }
  817. }
  818. void Network::multicastUnsubscribe(const MulticastGroup &mg)
  819. {
  820. Mutex::Lock _l(_lock);
  821. std::vector<MulticastGroup>::iterator i(std::lower_bound(_myMulticastGroups.begin(),_myMulticastGroups.end(),mg));
  822. if ( (i != _myMulticastGroups.end()) && (*i == mg) )
  823. _myMulticastGroups.erase(i);
  824. }
  825. uint64_t Network::handleConfigChunk(const Packet &chunk,unsigned int ptr)
  826. {
  827. const unsigned int start = ptr;
  828. ptr += 8; // skip network ID, which is already obviously known
  829. const unsigned int chunkLen = chunk.at<uint16_t>(ptr); ptr += 2;
  830. const void *chunkData = chunk.field(ptr,chunkLen); ptr += chunkLen;
  831. NetworkConfig *nc = (NetworkConfig *)0;
  832. uint64_t configUpdateId;
  833. {
  834. Mutex::Lock _l(_lock);
  835. _IncomingConfigChunk *c = (_IncomingConfigChunk *)0;
  836. uint64_t chunkId = 0;
  837. unsigned long totalLength,chunkIndex;
  838. if (ptr < chunk.size()) {
  839. const bool fastPropagate = ((chunk[ptr++] & 0x01) != 0);
  840. configUpdateId = chunk.at<uint64_t>(ptr); ptr += 8;
  841. totalLength = chunk.at<uint32_t>(ptr); ptr += 4;
  842. chunkIndex = chunk.at<uint32_t>(ptr); ptr += 4;
  843. if (((chunkIndex + chunkLen) > totalLength)||(totalLength >= ZT_NETWORKCONFIG_DICT_CAPACITY)) { // >= since we need room for a null at the end
  844. TRACE("discarded chunk from %s: invalid length or length overflow",chunk.source().toString().c_str());
  845. return 0;
  846. }
  847. if ((chunk[ptr] != 1)||(chunk.at<uint16_t>(ptr + 1) != ZT_C25519_SIGNATURE_LEN)) {
  848. TRACE("discarded chunk from %s: unrecognized signature type",chunk.source().toString().c_str());
  849. return 0;
  850. }
  851. const uint8_t *sig = reinterpret_cast<const uint8_t *>(chunk.field(ptr + 3,ZT_C25519_SIGNATURE_LEN));
  852. // We can use the signature, which is unique per chunk, to get a per-chunk ID for local deduplication use
  853. for(unsigned int i=0;i<16;++i)
  854. reinterpret_cast<uint8_t *>(&chunkId)[i & 7] ^= sig[i];
  855. // Find existing or new slot for this update and check if this is a duplicate chunk
  856. for(int i=0;i<ZT_NETWORK_MAX_INCOMING_UPDATES;++i) {
  857. if (_incomingConfigChunks[i].updateId == configUpdateId) {
  858. c = &(_incomingConfigChunks[i]);
  859. for(unsigned long j=0;j<c->haveChunks;++j) {
  860. if (c->haveChunkIds[j] == chunkId)
  861. return 0;
  862. }
  863. break;
  864. } else if ((!c)||(_incomingConfigChunks[i].ts < c->ts)) {
  865. c = &(_incomingConfigChunks[i]);
  866. }
  867. }
  868. // If it's not a duplicate, check chunk signature
  869. const Identity controllerId(RR->topology->getIdentity(controller()));
  870. if (!controllerId) { // we should always have the controller identity by now, otherwise how would we have queried it the first time?
  871. TRACE("unable to verify chunk from %s: don't have controller identity",chunk.source().toString().c_str());
  872. return 0;
  873. }
  874. if (!controllerId.verify(chunk.field(start,ptr - start),ptr - start,sig,ZT_C25519_SIGNATURE_LEN)) {
  875. TRACE("discarded chunk from %s: signature check failed",chunk.source().toString().c_str());
  876. return 0;
  877. }
  878. // New properly verified chunks can be flooded "virally" through the network
  879. if (fastPropagate) {
  880. Address *a = (Address *)0;
  881. Membership *m = (Membership *)0;
  882. Hashtable<Address,Membership>::Iterator i(_memberships);
  883. while (i.next(a,m)) {
  884. if ((*a != chunk.source())&&(*a != controller())) {
  885. Packet outp(*a,RR->identity.address(),Packet::VERB_NETWORK_CONFIG);
  886. outp.append(reinterpret_cast<const uint8_t *>(chunk.data()) + start,chunk.size() - start);
  887. RR->sw->send(outp,true);
  888. }
  889. }
  890. }
  891. } else if (chunk.source() == controller()) {
  892. // Legacy support for OK(NETWORK_CONFIG_REQUEST) from older controllers
  893. chunkId = chunk.packetId();
  894. configUpdateId = chunkId;
  895. totalLength = chunkLen;
  896. chunkIndex = 0;
  897. if (totalLength >= ZT_NETWORKCONFIG_DICT_CAPACITY)
  898. return 0;
  899. for(int i=0;i<ZT_NETWORK_MAX_INCOMING_UPDATES;++i) {
  900. if ((!c)||(_incomingConfigChunks[i].ts < c->ts))
  901. c = &(_incomingConfigChunks[i]);
  902. }
  903. } else {
  904. TRACE("discarded single-chunk unsigned legacy config: this is only allowed if the sender is the controller itself");
  905. return 0;
  906. }
  907. ++c->ts; // newer is higher, that's all we need
  908. if (c->updateId != configUpdateId) {
  909. c->updateId = configUpdateId;
  910. c->haveChunks = 0;
  911. c->haveBytes = 0;
  912. }
  913. if (c->haveChunks >= ZT_NETWORK_MAX_UPDATE_CHUNKS)
  914. return false;
  915. c->haveChunkIds[c->haveChunks++] = chunkId;
  916. memcpy(c->data.unsafeData() + chunkIndex,chunkData,chunkLen);
  917. c->haveBytes += chunkLen;
  918. if (c->haveBytes == totalLength) {
  919. c->data.unsafeData()[c->haveBytes] = (char)0; // ensure null terminated
  920. nc = new NetworkConfig();
  921. try {
  922. if (!nc->fromDictionary(c->data)) {
  923. delete nc;
  924. nc = (NetworkConfig *)0;
  925. }
  926. } catch ( ... ) {
  927. delete nc;
  928. nc = (NetworkConfig *)0;
  929. }
  930. }
  931. }
  932. if (nc) {
  933. this->setConfiguration(*nc,true);
  934. delete nc;
  935. return configUpdateId;
  936. } else {
  937. return 0;
  938. }
  939. return 0;
  940. }
  941. int Network::setConfiguration(const NetworkConfig &nconf,bool saveToDisk)
  942. {
  943. // _lock is NOT locked when this is called
  944. try {
  945. if ((nconf.issuedTo != RR->identity.address())||(nconf.networkId != _id))
  946. return 0;
  947. if (_config == nconf)
  948. return 1; // OK config, but duplicate of what we already have
  949. ZT_VirtualNetworkConfig ctmp;
  950. bool oldPortInitialized;
  951. {
  952. Mutex::Lock _l(_lock);
  953. _config = nconf;
  954. _lastConfigUpdate = RR->node->now();
  955. _netconfFailure = NETCONF_FAILURE_NONE;
  956. oldPortInitialized = _portInitialized;
  957. _portInitialized = true;
  958. _externalConfig(&ctmp);
  959. }
  960. _portError = RR->node->configureVirtualNetworkPort(_id,&_uPtr,(oldPortInitialized) ? ZT_VIRTUAL_NETWORK_CONFIG_OPERATION_CONFIG_UPDATE : ZT_VIRTUAL_NETWORK_CONFIG_OPERATION_UP,&ctmp);
  961. if (saveToDisk) {
  962. Dictionary<ZT_NETWORKCONFIG_DICT_CAPACITY> *d = new Dictionary<ZT_NETWORKCONFIG_DICT_CAPACITY>();
  963. try {
  964. char n[64];
  965. Utils::snprintf(n,sizeof(n),"networks.d/%.16llx.conf",_id);
  966. if (nconf.toDictionary(*d,false))
  967. RR->node->dataStorePut(n,(const void *)d->data(),d->sizeBytes(),true);
  968. } catch ( ... ) {}
  969. delete d;
  970. }
  971. return 2; // OK and configuration has changed
  972. } catch ( ... ) {
  973. TRACE("ignored invalid configuration for network %.16llx",(unsigned long long)_id);
  974. }
  975. return 0;
  976. }
  977. void Network::requestConfiguration()
  978. {
  979. const Address ctrl(controller());
  980. Dictionary<ZT_NETWORKCONFIG_METADATA_DICT_CAPACITY> rmd;
  981. rmd.add(ZT_NETWORKCONFIG_REQUEST_METADATA_KEY_VERSION,(uint64_t)ZT_NETWORKCONFIG_VERSION);
  982. rmd.add(ZT_NETWORKCONFIG_REQUEST_METADATA_KEY_NODE_VENDOR,(uint64_t)ZT_VENDOR_ZEROTIER);
  983. rmd.add(ZT_NETWORKCONFIG_REQUEST_METADATA_KEY_PROTOCOL_VERSION,(uint64_t)ZT_PROTO_VERSION);
  984. rmd.add(ZT_NETWORKCONFIG_REQUEST_METADATA_KEY_NODE_MAJOR_VERSION,(uint64_t)ZEROTIER_ONE_VERSION_MAJOR);
  985. rmd.add(ZT_NETWORKCONFIG_REQUEST_METADATA_KEY_NODE_MINOR_VERSION,(uint64_t)ZEROTIER_ONE_VERSION_MINOR);
  986. rmd.add(ZT_NETWORKCONFIG_REQUEST_METADATA_KEY_NODE_REVISION,(uint64_t)ZEROTIER_ONE_VERSION_REVISION);
  987. rmd.add(ZT_NETWORKCONFIG_REQUEST_METADATA_KEY_MAX_NETWORK_RULES,(uint64_t)ZT_MAX_NETWORK_RULES);
  988. rmd.add(ZT_NETWORKCONFIG_REQUEST_METADATA_KEY_MAX_NETWORK_CAPABILITIES,(uint64_t)ZT_MAX_NETWORK_CAPABILITIES);
  989. rmd.add(ZT_NETWORKCONFIG_REQUEST_METADATA_KEY_MAX_CAPABILITY_RULES,(uint64_t)ZT_MAX_CAPABILITY_RULES);
  990. rmd.add(ZT_NETWORKCONFIG_REQUEST_METADATA_KEY_MAX_NETWORK_TAGS,(uint64_t)ZT_MAX_NETWORK_TAGS);
  991. rmd.add(ZT_NETWORKCONFIG_REQUEST_METADATA_KEY_FLAGS,(uint64_t)0);
  992. rmd.add(ZT_NETWORKCONFIG_REQUEST_METADATA_KEY_RULES_ENGINE_REV,(uint64_t)ZT_RULES_ENGINE_REVISION);
  993. rmd.add(ZT_NETWORKCONFIG_REQUEST_METADATA_KEY_NODE_RELAY_POLICY,(uint64_t)RR->node->relayPolicy());
  994. if (ctrl == RR->identity.address()) {
  995. if (RR->localNetworkController) {
  996. RR->localNetworkController->request(_id,InetAddress(),0xffffffffffffffffULL,RR->identity,rmd);
  997. } else {
  998. this->setNotFound();
  999. }
  1000. return;
  1001. }
  1002. TRACE("requesting netconf for network %.16llx from controller %s",(unsigned long long)_id,ctrl.toString().c_str());
  1003. Packet outp(ctrl,RR->identity.address(),Packet::VERB_NETWORK_CONFIG_REQUEST);
  1004. outp.append((uint64_t)_id);
  1005. const unsigned int rmdSize = rmd.sizeBytes();
  1006. outp.append((uint16_t)rmdSize);
  1007. outp.append((const void *)rmd.data(),rmdSize);
  1008. if (_config) {
  1009. outp.append((uint64_t)_config.revision);
  1010. outp.append((uint64_t)_config.timestamp);
  1011. } else {
  1012. outp.append((unsigned char)0,16);
  1013. }
  1014. RR->node->expectReplyTo(outp.packetId());
  1015. outp.compress();
  1016. RR->sw->send(outp,true);
  1017. }
  1018. bool Network::gate(const SharedPtr<Peer> &peer)
  1019. {
  1020. const uint64_t now = RR->node->now();
  1021. Mutex::Lock _l(_lock);
  1022. try {
  1023. if (_config) {
  1024. Membership *m = _memberships.get(peer->address());
  1025. if ( (_config.isPublic()) || ((m)&&(m->isAllowedOnNetwork(_config))) ) {
  1026. if (!m)
  1027. m = &(_membership(peer->address()));
  1028. m->pushCredentials(RR,now,peer->address(),_config,-1,false);
  1029. if (m->shouldLikeMulticasts(now)) {
  1030. _announceMulticastGroupsTo(peer->address(),_allMulticastGroups());
  1031. m->likingMulticasts(now);
  1032. }
  1033. return true;
  1034. }
  1035. }
  1036. } catch ( ... ) {
  1037. TRACE("gate() check failed for peer %s: unexpected exception",peer->address().toString().c_str());
  1038. }
  1039. return false;
  1040. }
  1041. void Network::clean()
  1042. {
  1043. const uint64_t now = RR->node->now();
  1044. Mutex::Lock _l(_lock);
  1045. if (_destroyed)
  1046. return;
  1047. {
  1048. Hashtable< MulticastGroup,uint64_t >::Iterator i(_multicastGroupsBehindMe);
  1049. MulticastGroup *mg = (MulticastGroup *)0;
  1050. uint64_t *ts = (uint64_t *)0;
  1051. while (i.next(mg,ts)) {
  1052. if ((now - *ts) > (ZT_MULTICAST_LIKE_EXPIRE * 2))
  1053. _multicastGroupsBehindMe.erase(*mg);
  1054. }
  1055. }
  1056. {
  1057. Address *a = (Address *)0;
  1058. Membership *m = (Membership *)0;
  1059. Hashtable<Address,Membership>::Iterator i(_memberships);
  1060. while (i.next(a,m)) {
  1061. if (!RR->topology->getPeerNoCache(*a))
  1062. _memberships.erase(*a);
  1063. }
  1064. }
  1065. }
  1066. void Network::learnBridgeRoute(const MAC &mac,const Address &addr)
  1067. {
  1068. Mutex::Lock _l(_lock);
  1069. _remoteBridgeRoutes[mac] = addr;
  1070. // Anti-DOS circuit breaker to prevent nodes from spamming us with absurd numbers of bridge routes
  1071. while (_remoteBridgeRoutes.size() > ZT_MAX_BRIDGE_ROUTES) {
  1072. Hashtable< Address,unsigned long > counts;
  1073. Address maxAddr;
  1074. unsigned long maxCount = 0;
  1075. MAC *m = (MAC *)0;
  1076. Address *a = (Address *)0;
  1077. // Find the address responsible for the most entries
  1078. {
  1079. Hashtable<MAC,Address>::Iterator i(_remoteBridgeRoutes);
  1080. while (i.next(m,a)) {
  1081. const unsigned long c = ++counts[*a];
  1082. if (c > maxCount) {
  1083. maxCount = c;
  1084. maxAddr = *a;
  1085. }
  1086. }
  1087. }
  1088. // Kill this address from our table, since it's most likely spamming us
  1089. {
  1090. Hashtable<MAC,Address>::Iterator i(_remoteBridgeRoutes);
  1091. while (i.next(m,a)) {
  1092. if (*a == maxAddr)
  1093. _remoteBridgeRoutes.erase(*m);
  1094. }
  1095. }
  1096. }
  1097. }
  1098. void Network::learnBridgedMulticastGroup(const MulticastGroup &mg,uint64_t now)
  1099. {
  1100. Mutex::Lock _l(_lock);
  1101. const unsigned long tmp = (unsigned long)_multicastGroupsBehindMe.size();
  1102. _multicastGroupsBehindMe.set(mg,now);
  1103. if (tmp != _multicastGroupsBehindMe.size())
  1104. _sendUpdatesToMembers(&mg);
  1105. }
  1106. Membership::AddCredentialResult Network::addCredential(const CertificateOfMembership &com)
  1107. {
  1108. if (com.networkId() != _id)
  1109. return Membership::ADD_REJECTED;
  1110. const Address a(com.issuedTo());
  1111. Mutex::Lock _l(_lock);
  1112. Membership &m = _membership(a);
  1113. const Membership::AddCredentialResult result = m.addCredential(RR,_config,com);
  1114. if ((result == Membership::ADD_ACCEPTED_NEW)||(result == Membership::ADD_ACCEPTED_REDUNDANT)) {
  1115. m.pushCredentials(RR,RR->node->now(),a,_config,-1,false);
  1116. RR->mc->addCredential(com,true);
  1117. }
  1118. return result;
  1119. }
  1120. Membership::AddCredentialResult Network::addCredential(const Address &sentFrom,const Revocation &rev)
  1121. {
  1122. if (rev.networkId() != _id)
  1123. return Membership::ADD_REJECTED;
  1124. Mutex::Lock _l(_lock);
  1125. Membership &m = _membership(rev.target());
  1126. const Membership::AddCredentialResult result = m.addCredential(RR,_config,rev);
  1127. if ((result == Membership::ADD_ACCEPTED_NEW)&&(rev.fastPropagate())) {
  1128. Address *a = (Address *)0;
  1129. Membership *m = (Membership *)0;
  1130. Hashtable<Address,Membership>::Iterator i(_memberships);
  1131. while (i.next(a,m)) {
  1132. if ((*a != sentFrom)&&(*a != rev.signer())) {
  1133. Packet outp(*a,RR->identity.address(),Packet::VERB_NETWORK_CREDENTIALS);
  1134. outp.append((uint8_t)0x00); // no COM
  1135. outp.append((uint16_t)0); // no capabilities
  1136. outp.append((uint16_t)0); // no tags
  1137. outp.append((uint16_t)1); // one revocation!
  1138. rev.serialize(outp);
  1139. RR->sw->send(outp,true);
  1140. }
  1141. }
  1142. }
  1143. return result;
  1144. }
  1145. void Network::destroy()
  1146. {
  1147. Mutex::Lock _l(_lock);
  1148. _destroyed = true;
  1149. }
  1150. ZT_VirtualNetworkStatus Network::_status() const
  1151. {
  1152. // assumes _lock is locked
  1153. if (_portError)
  1154. return ZT_NETWORK_STATUS_PORT_ERROR;
  1155. switch(_netconfFailure) {
  1156. case NETCONF_FAILURE_ACCESS_DENIED:
  1157. return ZT_NETWORK_STATUS_ACCESS_DENIED;
  1158. case NETCONF_FAILURE_NOT_FOUND:
  1159. return ZT_NETWORK_STATUS_NOT_FOUND;
  1160. case NETCONF_FAILURE_NONE:
  1161. return ((_config) ? ZT_NETWORK_STATUS_OK : ZT_NETWORK_STATUS_REQUESTING_CONFIGURATION);
  1162. default:
  1163. return ZT_NETWORK_STATUS_PORT_ERROR;
  1164. }
  1165. }
  1166. void Network::_externalConfig(ZT_VirtualNetworkConfig *ec) const
  1167. {
  1168. // assumes _lock is locked
  1169. ec->nwid = _id;
  1170. ec->mac = _mac.toInt();
  1171. if (_config)
  1172. Utils::scopy(ec->name,sizeof(ec->name),_config.name);
  1173. else ec->name[0] = (char)0;
  1174. ec->status = _status();
  1175. ec->type = (_config) ? (_config.isPrivate() ? ZT_NETWORK_TYPE_PRIVATE : ZT_NETWORK_TYPE_PUBLIC) : ZT_NETWORK_TYPE_PRIVATE;
  1176. ec->mtu = ZT_IF_MTU;
  1177. ec->physicalMtu = ZT_UDP_DEFAULT_PAYLOAD_MTU - (ZT_PACKET_IDX_PAYLOAD + 16);
  1178. ec->dhcp = 0;
  1179. std::vector<Address> ab(_config.activeBridges());
  1180. ec->bridge = ((_config.allowPassiveBridging())||(std::find(ab.begin(),ab.end(),RR->identity.address()) != ab.end())) ? 1 : 0;
  1181. ec->broadcastEnabled = (_config) ? (_config.enableBroadcast() ? 1 : 0) : 0;
  1182. ec->portError = _portError;
  1183. ec->netconfRevision = (_config) ? (unsigned long)_config.revision : 0;
  1184. ec->assignedAddressCount = 0;
  1185. for(unsigned int i=0;i<ZT_MAX_ZT_ASSIGNED_ADDRESSES;++i) {
  1186. if (i < _config.staticIpCount) {
  1187. memcpy(&(ec->assignedAddresses[i]),&(_config.staticIps[i]),sizeof(struct sockaddr_storage));
  1188. ++ec->assignedAddressCount;
  1189. } else {
  1190. memset(&(ec->assignedAddresses[i]),0,sizeof(struct sockaddr_storage));
  1191. }
  1192. }
  1193. ec->routeCount = 0;
  1194. for(unsigned int i=0;i<ZT_MAX_NETWORK_ROUTES;++i) {
  1195. if (i < _config.routeCount) {
  1196. memcpy(&(ec->routes[i]),&(_config.routes[i]),sizeof(ZT_VirtualNetworkRoute));
  1197. ++ec->routeCount;
  1198. } else {
  1199. memset(&(ec->routes[i]),0,sizeof(ZT_VirtualNetworkRoute));
  1200. }
  1201. }
  1202. }
  1203. void Network::_sendUpdatesToMembers(const MulticastGroup *const newMulticastGroup)
  1204. {
  1205. // Assumes _lock is locked
  1206. const uint64_t now = RR->node->now();
  1207. std::vector<MulticastGroup> groups;
  1208. if (newMulticastGroup)
  1209. groups.push_back(*newMulticastGroup);
  1210. else groups = _allMulticastGroups();
  1211. if ((newMulticastGroup)||((now - _lastAnnouncedMulticastGroupsUpstream) >= ZT_MULTICAST_ANNOUNCE_PERIOD)) {
  1212. if (!newMulticastGroup)
  1213. _lastAnnouncedMulticastGroupsUpstream = now;
  1214. // Announce multicast groups to upstream peers (roots, etc.) and also send
  1215. // them our COM so that MULTICAST_GATHER can be authenticated properly.
  1216. const std::vector<Address> upstreams(RR->topology->upstreamAddresses());
  1217. for(std::vector<Address>::const_iterator a(upstreams.begin());a!=upstreams.end();++a) {
  1218. if (_config.com) {
  1219. Packet outp(*a,RR->identity.address(),Packet::VERB_NETWORK_CREDENTIALS);
  1220. _config.com.serialize(outp);
  1221. outp.append((uint8_t)0x00);
  1222. RR->sw->send(outp,true);
  1223. }
  1224. _announceMulticastGroupsTo(*a,groups);
  1225. }
  1226. // Also announce to controller, and send COM to simplify and generalize behavior even though in theory it does not need it
  1227. const Address c(controller());
  1228. if ( (std::find(upstreams.begin(),upstreams.end(),c) == upstreams.end()) && (!_memberships.contains(c)) ) {
  1229. if (_config.com) {
  1230. Packet outp(c,RR->identity.address(),Packet::VERB_NETWORK_CREDENTIALS);
  1231. _config.com.serialize(outp);
  1232. outp.append((uint8_t)0x00);
  1233. RR->sw->send(outp,true);
  1234. }
  1235. _announceMulticastGroupsTo(c,groups);
  1236. }
  1237. }
  1238. // Make sure that all "network anchors" have Membership records so we will
  1239. // push multicasts to them. Note that _membership() also does this but in a
  1240. // piecemeal on-demand fashion.
  1241. const std::vector<Address> anchors(_config.anchors());
  1242. for(std::vector<Address>::const_iterator a(anchors.begin());a!=anchors.end();++a)
  1243. _membership(*a);
  1244. // Send credentials and multicast LIKEs to members, upstreams, and controller
  1245. {
  1246. Address *a = (Address *)0;
  1247. Membership *m = (Membership *)0;
  1248. Hashtable<Address,Membership>::Iterator i(_memberships);
  1249. while (i.next(a,m)) {
  1250. m->pushCredentials(RR,now,*a,_config,-1,false);
  1251. if ( ((newMulticastGroup)||(m->shouldLikeMulticasts(now))) && (m->isAllowedOnNetwork(_config)) ) {
  1252. if (!newMulticastGroup)
  1253. m->likingMulticasts(now);
  1254. _announceMulticastGroupsTo(*a,groups);
  1255. }
  1256. }
  1257. }
  1258. }
  1259. void Network::_announceMulticastGroupsTo(const Address &peer,const std::vector<MulticastGroup> &allMulticastGroups)
  1260. {
  1261. // Assumes _lock is locked
  1262. Packet outp(peer,RR->identity.address(),Packet::VERB_MULTICAST_LIKE);
  1263. for(std::vector<MulticastGroup>::const_iterator mg(allMulticastGroups.begin());mg!=allMulticastGroups.end();++mg) {
  1264. if ((outp.size() + 24) >= ZT_PROTO_MAX_PACKET_LENGTH) {
  1265. outp.compress();
  1266. RR->sw->send(outp,true);
  1267. outp.reset(peer,RR->identity.address(),Packet::VERB_MULTICAST_LIKE);
  1268. }
  1269. // network ID, MAC, ADI
  1270. outp.append((uint64_t)_id);
  1271. mg->mac().appendTo(outp);
  1272. outp.append((uint32_t)mg->adi());
  1273. }
  1274. if (outp.size() > ZT_PROTO_MIN_PACKET_LENGTH) {
  1275. outp.compress();
  1276. RR->sw->send(outp,true);
  1277. }
  1278. }
  1279. std::vector<MulticastGroup> Network::_allMulticastGroups() const
  1280. {
  1281. // Assumes _lock is locked
  1282. std::vector<MulticastGroup> mgs;
  1283. mgs.reserve(_myMulticastGroups.size() + _multicastGroupsBehindMe.size() + 1);
  1284. mgs.insert(mgs.end(),_myMulticastGroups.begin(),_myMulticastGroups.end());
  1285. _multicastGroupsBehindMe.appendKeys(mgs);
  1286. if ((_config)&&(_config.enableBroadcast()))
  1287. mgs.push_back(Network::BROADCAST);
  1288. std::sort(mgs.begin(),mgs.end());
  1289. mgs.erase(std::unique(mgs.begin(),mgs.end()),mgs.end());
  1290. return mgs;
  1291. }
  1292. Membership &Network::_membership(const Address &a)
  1293. {
  1294. // assumes _lock is locked
  1295. return _memberships[a];
  1296. }
  1297. } // namespace ZeroTier