Network.cpp 50 KB

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