Network.cpp 54 KB

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