Network.cpp 38 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043
  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_IP_SOURCE_PORT_RANGE: return "MATCH_IP_SOURCE_PORT_RANGE";
  63. case ZT_NETWORK_RULE_MATCH_IP_DEST_PORT_RANGE: return "MATCH_IP_DEST_PORT_RANGE";
  64. case ZT_NETWORK_RULE_MATCH_CHARACTERISTICS: return "MATCH_CHARACTERISTICS";
  65. default: return "BAD_RULE_TYPE";
  66. }
  67. }
  68. #else
  69. #define FILTER_TRACE(f,...) {}
  70. #endif // ZT_RULES_ENGINE_DEBUGGING
  71. // Returns true if packet appears valid; pos and proto will be set
  72. static bool _ipv6GetPayload(const uint8_t *frameData,unsigned int frameLen,unsigned int &pos,unsigned int &proto)
  73. {
  74. if (frameLen < 40)
  75. return false;
  76. pos = 40;
  77. proto = frameData[6];
  78. while (pos <= frameLen) {
  79. switch(proto) {
  80. case 0: // hop-by-hop options
  81. case 43: // routing
  82. case 60: // destination options
  83. case 135: // mobility options
  84. if ((pos + 8) > frameLen)
  85. return false; // invalid!
  86. proto = frameData[pos];
  87. pos += ((unsigned int)frameData[pos + 1] * 8) + 8;
  88. break;
  89. //case 44: // fragment -- we currently can't parse these and they are deprecated in IPv6 anyway
  90. //case 50:
  91. //case 51: // IPSec ESP and AH -- we have to stop here since this is encrypted stuff
  92. default:
  93. return true;
  94. }
  95. }
  96. return false; // overflow == invalid
  97. }
  98. // 0 == no match, -1 == match/drop, 1 == match/accept
  99. static int _doZtFilter(
  100. const RuntimeEnvironment *RR,
  101. const bool noRedirect,
  102. const NetworkConfig &nconf,
  103. const bool inbound,
  104. const Address &ztSource,
  105. const Address &ztDest,
  106. const MAC &macSource,
  107. const MAC &macDest,
  108. const uint8_t *frameData,
  109. const unsigned int frameLen,
  110. const unsigned int etherType,
  111. const unsigned int vlanId,
  112. const ZT_VirtualNetworkRule *rules,
  113. const unsigned int ruleCount,
  114. const Tag *localTags,
  115. const unsigned int localTagCount,
  116. const uint32_t *remoteTagIds,
  117. const uint32_t *remoteTagValues,
  118. const unsigned int remoteTagCount,
  119. const Tag **relevantLocalTags, // pointer array must be at least [localTagCount] in size
  120. unsigned int &relevantLocalTagCount)
  121. {
  122. // For each set of rules we start by assuming that they match (since no constraints
  123. // yields a 'match all' rule).
  124. uint8_t thisSetMatches = 1;
  125. #ifdef ZT_RULES_ENGINE_DEBUGGING
  126. std::vector<std::string> dlog;
  127. char dpbuf[1024];
  128. #endif
  129. for(unsigned int rn=0;rn<ruleCount;++rn) {
  130. const ZT_VirtualNetworkRuleType rt = (ZT_VirtualNetworkRuleType)(rules[rn].t & 0x7f);
  131. uint8_t thisRuleMatches = 0;
  132. switch(rt) {
  133. // Actions -------------------------------------------------------------
  134. // An action is performed if thisSetMatches is true, and if not
  135. // (or if the action is non-terminating) we start a new set of rules.
  136. case ZT_NETWORK_RULE_ACTION_DROP:
  137. if (thisSetMatches) {
  138. return -1; // match, drop packet
  139. } else {
  140. thisRuleMatches = 1;
  141. thisSetMatches = 1; // no match, evaluate next set
  142. }
  143. break;
  144. case ZT_NETWORK_RULE_ACTION_ACCEPT:
  145. if (thisSetMatches) {
  146. return 1; // match, accept packet
  147. } else {
  148. thisRuleMatches = 1;
  149. thisSetMatches = 1; // no match, evaluate next set
  150. }
  151. break;
  152. case ZT_NETWORK_RULE_ACTION_TEE:
  153. case ZT_NETWORK_RULE_ACTION_REDIRECT: {
  154. if (!noRedirect) {
  155. Packet outp(Address(rules[rn].v.fwd.address),RR->identity.address(),Packet::VERB_EXT_FRAME);
  156. outp.append(nconf.networkId);
  157. outp.append((uint8_t)( ((rt == ZT_NETWORK_RULE_ACTION_REDIRECT) ? 0x04 : 0x02) | (inbound ? 0x08 : 0x00) ));
  158. macDest.appendTo(outp);
  159. macSource.appendTo(outp);
  160. outp.append((uint16_t)etherType);
  161. outp.append(frameData,(rules[rn].v.fwd.length != 0) ? ((frameLen < (unsigned int)rules[rn].v.fwd.length) ? frameLen : (unsigned int)rules[rn].v.fwd.length) : frameLen);
  162. outp.compress();
  163. RR->sw->send(outp,true);
  164. }
  165. if (rt == ZT_NETWORK_RULE_ACTION_REDIRECT) {
  166. return -1; // match, drop packet (we redirected it)
  167. } else {
  168. thisRuleMatches = 1;
  169. thisSetMatches = 1; // TEE does not terminate evaluation
  170. }
  171. } break;
  172. case ZT_NETWORK_RULE_ACTION_DEBUG_LOG:
  173. #ifdef ZT_RULES_ENGINE_DEBUGGING
  174. if (thisSetMatches) {
  175. printf("[FILTER] MATCH %s->%s %.2x:%.2x:%.2x:%.2x:%.2x:%.2x->%.2x:%.2x:%.2x:%.2x:%.2x:%.2x inbound=%d noRedirect=%d frameLen=%u etherType=%u" ZT_EOL_S,
  176. ztSource.toString().c_str(),
  177. ztDest.toString().c_str(),
  178. (unsigned int)macSource[0],
  179. (unsigned int)macSource[1],
  180. (unsigned int)macSource[2],
  181. (unsigned int)macSource[3],
  182. (unsigned int)macSource[4],
  183. (unsigned int)macSource[5],
  184. (unsigned int)macDest[0],
  185. (unsigned int)macDest[1],
  186. (unsigned int)macDest[2],
  187. (unsigned int)macDest[3],
  188. (unsigned int)macDest[4],
  189. (unsigned int)macDest[5],
  190. (int)inbound,
  191. (int)noRedirect,
  192. frameLen,
  193. etherType
  194. );
  195. for(std::vector<std::string>::iterator m(dlog.begin());m!=dlog.end();++m)
  196. printf(" %s" ZT_EOL_S,m->c_str());
  197. dlog.clear();
  198. }
  199. #endif // ZT_RULES_ENGINE_DEBUGGING
  200. thisRuleMatches = 1;
  201. thisSetMatches = 1; // DEBUG_LOG does not terminate evaluation
  202. break;
  203. // Rules ---------------------------------------------------------------
  204. // thisSetMatches is the binary AND of the result of all rules in a set
  205. case ZT_NETWORK_RULE_MATCH_SOURCE_ZEROTIER_ADDRESS:
  206. FILTER_TRACE("%u %s param0=%.10llx",rn,_rtn(rt),rules[rn].v.zt);
  207. thisRuleMatches = (uint8_t)(rules[rn].v.zt == ztSource.toInt());
  208. break;
  209. case ZT_NETWORK_RULE_MATCH_DEST_ZEROTIER_ADDRESS:
  210. FILTER_TRACE("%u %s param0=%.10llx",rn,_rtn(rt),rules[rn].v.zt);
  211. thisRuleMatches = (uint8_t)(rules[rn].v.zt == ztDest.toInt());
  212. break;
  213. case ZT_NETWORK_RULE_MATCH_VLAN_ID:
  214. FILTER_TRACE("%u %s param0=%u",rn,_rtn(rt),(unsigned int)rules[rn].v.vlanId);
  215. thisRuleMatches = (uint8_t)(rules[rn].v.vlanId == (uint16_t)vlanId);
  216. break;
  217. case ZT_NETWORK_RULE_MATCH_VLAN_PCP:
  218. // NOT SUPPORTED YET
  219. FILTER_TRACE("%u %s param0=%u",rn,_rtn(rt),(unsigned int)rules[rn].v.vlanPcp);
  220. thisRuleMatches = (uint8_t)(rules[rn].v.vlanPcp == 0);
  221. break;
  222. case ZT_NETWORK_RULE_MATCH_VLAN_DEI:
  223. // NOT SUPPORTED YET
  224. FILTER_TRACE("%u %s param0=%u",rn,_rtn(rt),(unsigned int)rules[rn].v.vlanDei);
  225. thisRuleMatches = (uint8_t)(rules[rn].v.vlanDei == 0);
  226. break;
  227. case ZT_NETWORK_RULE_MATCH_ETHERTYPE:
  228. FILTER_TRACE("%u %s param0=%u etherType=%u",rn,_rtn(rt),(unsigned int)rules[rn].v.etherType,etherType);
  229. thisRuleMatches = (uint8_t)(rules[rn].v.etherType == (uint16_t)etherType);
  230. break;
  231. case ZT_NETWORK_RULE_MATCH_MAC_SOURCE:
  232. FILTER_TRACE("%u %s param0=%.12llx",rn,_rtn(rt),rules[rn].v.mac);
  233. thisRuleMatches = (uint8_t)(MAC(rules[rn].v.mac,6) == macSource);
  234. break;
  235. case ZT_NETWORK_RULE_MATCH_MAC_DEST:
  236. FILTER_TRACE("%u %s param0=%.12llx",rn,_rtn(rt),rules[rn].v.mac);
  237. thisRuleMatches = (uint8_t)(MAC(rules[rn].v.mac,6) == macDest);
  238. break;
  239. case ZT_NETWORK_RULE_MATCH_IPV4_SOURCE:
  240. FILTER_TRACE("%u %s param0=%s",rn,_rtn(rt),InetAddress((const void *)&(rules[rn].v.ipv4.ip),4,rules[rn].v.ipv4.mask).toString().c_str());
  241. if ((etherType == ZT_ETHERTYPE_IPV4)&&(frameLen >= 20)) {
  242. 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)));
  243. } else {
  244. thisRuleMatches = 0;
  245. }
  246. break;
  247. case ZT_NETWORK_RULE_MATCH_IPV4_DEST:
  248. FILTER_TRACE("%u %s param0=%s",rn,_rtn(rt),InetAddress((const void *)&(rules[rn].v.ipv4.ip),4,rules[rn].v.ipv4.mask).toString().c_str());
  249. if ((etherType == ZT_ETHERTYPE_IPV4)&&(frameLen >= 20)) {
  250. 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)));
  251. } else {
  252. thisRuleMatches = 0;
  253. }
  254. break;
  255. case ZT_NETWORK_RULE_MATCH_IPV6_SOURCE:
  256. FILTER_TRACE("%u %s param0=%s",rn,_rtn(rt),InetAddress((const void *)rules[rn].v.ipv6.ip,16,rules[rn].v.ipv6.mask).toString().c_str());
  257. if ((etherType == ZT_ETHERTYPE_IPV6)&&(frameLen >= 40)) {
  258. 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)));
  259. } else {
  260. thisRuleMatches = 0;
  261. }
  262. break;
  263. case ZT_NETWORK_RULE_MATCH_IPV6_DEST:
  264. FILTER_TRACE("%u %s param0=%s",rn,_rtn(rt),InetAddress((const void *)rules[rn].v.ipv6.ip,16,rules[rn].v.ipv6.mask).toString().c_str());
  265. if ((etherType == ZT_ETHERTYPE_IPV6)&&(frameLen >= 40)) {
  266. 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)));
  267. } else {
  268. thisRuleMatches = 0;
  269. }
  270. break;
  271. case ZT_NETWORK_RULE_MATCH_IP_TOS:
  272. FILTER_TRACE("%u %s param0=%u",rn,_rtn(rt),(unsigned int)rules[rn].v.ipTos);
  273. if ((etherType == ZT_ETHERTYPE_IPV4)&&(frameLen >= 20)) {
  274. thisRuleMatches = (uint8_t)(rules[rn].v.ipTos == ((frameData[1] & 0xfc) >> 2));
  275. } else if ((etherType == ZT_ETHERTYPE_IPV6)&&(frameLen >= 40)) {
  276. const uint8_t trafficClass = ((frameData[0] << 4) & 0xf0) | ((frameData[1] >> 4) & 0x0f);
  277. thisRuleMatches = (uint8_t)(rules[rn].v.ipTos == ((trafficClass & 0xfc) >> 2));
  278. } else {
  279. thisRuleMatches = 0;
  280. }
  281. break;
  282. case ZT_NETWORK_RULE_MATCH_IP_PROTOCOL:
  283. FILTER_TRACE("%u %s param0=%u",rn,_rtn(rt),(unsigned int)rules[rn].v.ipProtocol);
  284. if ((etherType == ZT_ETHERTYPE_IPV4)&&(frameLen >= 20)) {
  285. thisRuleMatches = (uint8_t)(rules[rn].v.ipProtocol == frameData[9]);
  286. } else if (etherType == ZT_ETHERTYPE_IPV6) {
  287. unsigned int pos = 0,proto = 0;
  288. if (_ipv6GetPayload(frameData,frameLen,pos,proto)) {
  289. thisRuleMatches = (uint8_t)(rules[rn].v.ipProtocol == (uint8_t)proto);
  290. } else {
  291. thisRuleMatches = 0;
  292. }
  293. } else {
  294. thisRuleMatches = 0;
  295. }
  296. break;
  297. case ZT_NETWORK_RULE_MATCH_IP_SOURCE_PORT_RANGE:
  298. case ZT_NETWORK_RULE_MATCH_IP_DEST_PORT_RANGE:
  299. if ((etherType == ZT_ETHERTYPE_IPV4)&&(frameLen >= 20)) {
  300. const unsigned int headerLen = 4 * (frameData[0] & 0xf);
  301. int p = -1;
  302. switch(frameData[9]) { // IP protocol number
  303. // All these start with 16-bit source and destination port in that order
  304. case 0x06: // TCP
  305. case 0x11: // UDP
  306. case 0x84: // SCTP
  307. case 0x88: // UDPLite
  308. if (frameLen > (headerLen + 4)) {
  309. unsigned int pos = headerLen + ((rt == ZT_NETWORK_RULE_MATCH_IP_DEST_PORT_RANGE) ? 2 : 0);
  310. p = (int)frameData[pos++] << 8;
  311. p |= (int)frameData[pos];
  312. }
  313. break;
  314. }
  315. FILTER_TRACE("%u %s param0=%u param1=%u port==%u proto==%u etherType=%u (IPv4)",rn,_rtn(rt),(unsigned int)rules[rn].v.port[0],(unsigned int)rules[rn].v.port[1],p,(unsigned int)frameData[9],etherType);
  316. thisRuleMatches = (p > 0) ? (uint8_t)((p >= (int)rules[rn].v.port[0])&&(p <= (int)rules[rn].v.port[1])) : (uint8_t)0;
  317. } else if (etherType == ZT_ETHERTYPE_IPV6) {
  318. unsigned int pos = 0,proto = 0;
  319. if (_ipv6GetPayload(frameData,frameLen,pos,proto)) {
  320. int p = -1;
  321. switch(proto) { // IP protocol number
  322. // All these start with 16-bit source and destination port in that order
  323. case 0x06: // TCP
  324. case 0x11: // UDP
  325. case 0x84: // SCTP
  326. case 0x88: // UDPLite
  327. if (frameLen > (pos + 4)) {
  328. if (rt == ZT_NETWORK_RULE_MATCH_IP_DEST_PORT_RANGE) pos += 2;
  329. p = (int)frameData[pos++] << 8;
  330. p |= (int)frameData[pos];
  331. }
  332. break;
  333. }
  334. FILTER_TRACE("%u %s param0=%u param1=%u port==%u proto=%u etherType=%u (IPv6)",rn,_rtn(rt),(unsigned int)rules[rn].v.port[0],(unsigned int)rules[rn].v.port[1],p,proto,etherType);
  335. thisRuleMatches = (p > 0) ? (uint8_t)((p >= (int)rules[rn].v.port[0])&&(p <= (int)rules[rn].v.port[1])) : (uint8_t)0;
  336. } else {
  337. FILTER_TRACE("%u %s param0=%u param1=%u port=0 proto=0 etherType=%u (IPv6 parse failed)",rn,_rtn(rt),(unsigned int)rules[rn].v.port[0],(unsigned int)rules[rn].v.port[1],etherType);
  338. thisRuleMatches = 0;
  339. }
  340. } else {
  341. FILTER_TRACE("%u %s param0=%u param1=%u port=0 proto=0 etherType=%u (not IPv4 or IPv6)",rn,_rtn(rt),(unsigned int)rules[rn].v.port[0],(unsigned int)rules[rn].v.port[1],etherType);
  342. thisRuleMatches = 0;
  343. }
  344. break;
  345. case ZT_NETWORK_RULE_MATCH_CHARACTERISTICS: {
  346. uint64_t cf = (inbound) ? ZT_RULE_PACKET_CHARACTERISTICS_INBOUND : 0ULL;
  347. if (macDest.isMulticast()) cf |= ZT_RULE_PACKET_CHARACTERISTICS_MULTICAST;
  348. if (macDest.isBroadcast()) cf |= ZT_RULE_PACKET_CHARACTERISTICS_BROADCAST;
  349. if ((etherType == ZT_ETHERTYPE_IPV4)&&(frameLen >= 20)&&(frameData[9] == 0x06)) {
  350. const unsigned int headerLen = 4 * (frameData[0] & 0xf);
  351. cf |= (uint64_t)frameData[headerLen + 13];
  352. cf |= (((uint64_t)(frameData[headerLen + 12] & 0x0f)) << 8);
  353. } else if (etherType == ZT_ETHERTYPE_IPV6) {
  354. unsigned int pos = 0,proto = 0;
  355. if (_ipv6GetPayload(frameData,frameLen,pos,proto)) {
  356. if ((proto == 0x06)&&(frameLen > (pos + 14))) {
  357. cf |= (uint64_t)frameData[pos + 13];
  358. cf |= (((uint64_t)(frameData[pos + 12] & 0x0f)) << 8);
  359. }
  360. }
  361. }
  362. FILTER_TRACE("%u %s param0=%.16llx param1=%.16llx actual=%.16llx",rn,_rtn(rt),rules[rn].v.characteristics[0],rules[rn].v.characteristics[1],cf);
  363. thisRuleMatches = (uint8_t)((cf & rules[rn].v.characteristics[0]) == rules[rn].v.characteristics[1]);
  364. } break;
  365. case ZT_NETWORK_RULE_MATCH_FRAME_SIZE_RANGE:
  366. FILTER_TRACE("%u %s param0=%u param1=%u",rn,_rtn(rt),(unsigned int)rules[rn].v.frameSize[0],(unsigned int)rules[rn].v.frameSize[1]);
  367. thisRuleMatches = (uint8_t)((frameLen >= (unsigned int)rules[rn].v.frameSize[0])&&(frameLen <= (unsigned int)rules[rn].v.frameSize[1]));
  368. break;
  369. case ZT_NETWORK_RULE_MATCH_TAGS_SAMENESS:
  370. case ZT_NETWORK_RULE_MATCH_TAGS_BITWISE_AND:
  371. case ZT_NETWORK_RULE_MATCH_TAGS_BITWISE_OR:
  372. case ZT_NETWORK_RULE_MATCH_TAGS_BITWISE_XOR: {
  373. FILTER_TRACE("%u %s param0=%u",rn,_rtn(rt),(unsigned int)rules[rn].v.tag.value);
  374. const Tag *lt = (const Tag *)0;
  375. for(unsigned int i=0;i<localTagCount;++i) {
  376. if (rules[rn].v.tag.id == localTags[i].id()) {
  377. lt = &(localTags[i]);
  378. break;
  379. }
  380. }
  381. if (!lt) {
  382. thisRuleMatches = 0;
  383. } else {
  384. const uint32_t *rtv = (const uint32_t *)0;
  385. for(unsigned int i=0;i<remoteTagCount;++i) {
  386. if (rules[rn].v.tag.id == remoteTagIds[i]) {
  387. rtv = &(remoteTagValues[i]);
  388. break;
  389. }
  390. }
  391. if (!rtv) {
  392. thisRuleMatches = 0;
  393. } else {
  394. if (rt == ZT_NETWORK_RULE_MATCH_TAGS_SAMENESS) {
  395. const uint32_t sameness = (lt->value() > *rtv) ? (lt->value() - *rtv) : (*rtv - lt->value());
  396. thisRuleMatches = (uint8_t)(sameness <= rules[rn].v.tag.value);
  397. } else if (rt == ZT_NETWORK_RULE_MATCH_TAGS_BITWISE_AND) {
  398. thisRuleMatches = (uint8_t)((lt->value() & *rtv) <= rules[rn].v.tag.value);
  399. } else if (rt == ZT_NETWORK_RULE_MATCH_TAGS_BITWISE_OR) {
  400. thisRuleMatches = (uint8_t)((lt->value() | *rtv) <= rules[rn].v.tag.value);
  401. } else if (rt == ZT_NETWORK_RULE_MATCH_TAGS_BITWISE_XOR) {
  402. thisRuleMatches = (uint8_t)((lt->value() ^ *rtv) <= rules[rn].v.tag.value);
  403. } else { // sanity check, can't really happen
  404. thisRuleMatches = 0;
  405. }
  406. if (thisRuleMatches) {
  407. relevantLocalTags[relevantLocalTagCount++] = lt;
  408. }
  409. }
  410. }
  411. } break;
  412. }
  413. // thisSetMatches remains true if the current rule matched (or did NOT match if NOT bit is set)
  414. thisSetMatches &= (thisRuleMatches ^ ((rules[rn].t & 0x80) >> 7));
  415. FILTER_TRACE("%u %s/%u thisRuleMatches==%u thisSetMatches==%u",rn,_rtn(rt),(unsigned int)rt,(unsigned int)thisRuleMatches,(unsigned int)thisSetMatches);
  416. }
  417. return 0;
  418. }
  419. const ZeroTier::MulticastGroup Network::BROADCAST(ZeroTier::MAC(0xffffffffffffULL),0);
  420. Network::Network(const RuntimeEnvironment *renv,uint64_t nwid,void *uptr) :
  421. RR(renv),
  422. _uPtr(uptr),
  423. _id(nwid),
  424. _mac(renv->identity.address(),nwid),
  425. _portInitialized(false),
  426. _inboundConfigPacketId(0),
  427. _lastConfigUpdate(0),
  428. _lastRequestedConfiguration(0),
  429. _destroyed(false),
  430. _netconfFailure(NETCONF_FAILURE_NONE),
  431. _portError(0)
  432. {
  433. char confn[128];
  434. Utils::snprintf(confn,sizeof(confn),"networks.d/%.16llx.conf",_id);
  435. bool gotConf = false;
  436. Dictionary<ZT_NETWORKCONFIG_DICT_CAPACITY> *dconf = new Dictionary<ZT_NETWORKCONFIG_DICT_CAPACITY>();
  437. NetworkConfig *nconf = new NetworkConfig();
  438. try {
  439. std::string conf(RR->node->dataStoreGet(confn));
  440. if (conf.length()) {
  441. dconf->load(conf.c_str());
  442. if (nconf->fromDictionary(*dconf)) {
  443. this->setConfiguration(*nconf,false);
  444. _lastConfigUpdate = 0; // we still want to re-request a new config from the network
  445. gotConf = true;
  446. }
  447. }
  448. } catch ( ... ) {} // ignore invalids, we'll re-request
  449. delete nconf;
  450. delete dconf;
  451. if (!gotConf) {
  452. // Save a one-byte CR to persist membership while we request a real netconf
  453. RR->node->dataStorePut(confn,"\n",1,false);
  454. }
  455. if (!_portInitialized) {
  456. ZT_VirtualNetworkConfig ctmp;
  457. _externalConfig(&ctmp);
  458. _portError = RR->node->configureVirtualNetworkPort(_id,&_uPtr,ZT_VIRTUAL_NETWORK_CONFIG_OPERATION_UP,&ctmp);
  459. _portInitialized = true;
  460. }
  461. }
  462. Network::~Network()
  463. {
  464. ZT_VirtualNetworkConfig ctmp;
  465. _externalConfig(&ctmp);
  466. char n[128];
  467. if (_destroyed) {
  468. RR->node->configureVirtualNetworkPort(_id,&_uPtr,ZT_VIRTUAL_NETWORK_CONFIG_OPERATION_DESTROY,&ctmp);
  469. Utils::snprintf(n,sizeof(n),"networks.d/%.16llx.conf",_id);
  470. RR->node->dataStoreDelete(n);
  471. } else {
  472. RR->node->configureVirtualNetworkPort(_id,&_uPtr,ZT_VIRTUAL_NETWORK_CONFIG_OPERATION_DOWN,&ctmp);
  473. }
  474. }
  475. bool Network::filterOutgoingPacket(
  476. const bool noRedirect,
  477. const Address &ztSource,
  478. const Address &ztDest,
  479. const MAC &macSource,
  480. const MAC &macDest,
  481. const uint8_t *frameData,
  482. const unsigned int frameLen,
  483. const unsigned int etherType,
  484. const unsigned int vlanId)
  485. {
  486. uint32_t remoteTagIds[ZT_MAX_NETWORK_TAGS];
  487. uint32_t remoteTagValues[ZT_MAX_NETWORK_TAGS];
  488. const Tag *relevantLocalTags[ZT_MAX_NETWORK_TAGS];
  489. unsigned int relevantLocalTagCount = 0;
  490. Mutex::Lock _l(_lock);
  491. Membership &m = _memberships[ztDest];
  492. const unsigned int remoteTagCount = m.getAllTags(_config,remoteTagIds,remoteTagValues,ZT_MAX_NETWORK_TAGS);
  493. switch(_doZtFilter(RR,noRedirect,_config,false,ztSource,ztDest,macSource,macDest,frameData,frameLen,etherType,vlanId,_config.rules,_config.ruleCount,_config.tags,_config.tagCount,remoteTagIds,remoteTagValues,remoteTagCount,relevantLocalTags,relevantLocalTagCount)) {
  494. case -1:
  495. return false;
  496. case 1:
  497. if (ztDest)
  498. m.sendCredentialsIfNeeded(RR,RR->node->now(),ztDest,_config.com,(const Capability *)0,relevantLocalTags,relevantLocalTagCount);
  499. return true;
  500. }
  501. for(unsigned int c=0;c<_config.capabilityCount;++c) {
  502. relevantLocalTagCount = 0;
  503. switch (_doZtFilter(RR,noRedirect,_config,false,ztSource,ztDest,macSource,macDest,frameData,frameLen,etherType,vlanId,_config.capabilities[c].rules(),_config.capabilities[c].ruleCount(),_config.tags,_config.tagCount,remoteTagIds,remoteTagValues,remoteTagCount,relevantLocalTags,relevantLocalTagCount)) {
  504. case -1:
  505. return false;
  506. case 1:
  507. if (ztDest)
  508. m.sendCredentialsIfNeeded(RR,RR->node->now(),ztDest,_config.com,&(_config.capabilities[c]),relevantLocalTags,relevantLocalTagCount);
  509. return true;
  510. }
  511. }
  512. return false;
  513. }
  514. bool Network::filterIncomingPacket(
  515. const SharedPtr<Peer> &sourcePeer,
  516. const Address &ztDest,
  517. const MAC &macSource,
  518. const MAC &macDest,
  519. const uint8_t *frameData,
  520. const unsigned int frameLen,
  521. const unsigned int etherType,
  522. const unsigned int vlanId)
  523. {
  524. uint32_t remoteTagIds[ZT_MAX_NETWORK_TAGS];
  525. uint32_t remoteTagValues[ZT_MAX_NETWORK_TAGS];
  526. const Tag *relevantLocalTags[ZT_MAX_NETWORK_TAGS];
  527. unsigned int relevantLocalTagCount = 0;
  528. Mutex::Lock _l(_lock);
  529. Membership &m = _memberships[ztDest];
  530. const unsigned int remoteTagCount = m.getAllTags(_config,remoteTagIds,remoteTagValues,ZT_MAX_NETWORK_TAGS);
  531. switch (_doZtFilter(RR,false,_config,true,sourcePeer->address(),ztDest,macSource,macDest,frameData,frameLen,etherType,vlanId,_config.rules,_config.ruleCount,_config.tags,_config.tagCount,remoteTagIds,remoteTagValues,remoteTagCount,relevantLocalTags,relevantLocalTagCount)) {
  532. case -1:
  533. return false;
  534. case 1:
  535. return true;
  536. }
  537. Membership::CapabilityIterator mci(m);
  538. const Capability *c;
  539. while ((c = mci.next(_config))) {
  540. relevantLocalTagCount = 0;
  541. switch(_doZtFilter(RR,false,_config,false,sourcePeer->address(),ztDest,macSource,macDest,frameData,frameLen,etherType,vlanId,c->rules(),c->ruleCount(),_config.tags,_config.tagCount,remoteTagIds,remoteTagValues,remoteTagCount,relevantLocalTags,relevantLocalTagCount)) {
  542. case -1:
  543. return false;
  544. case 1:
  545. return true;
  546. }
  547. }
  548. return false;
  549. }
  550. bool Network::subscribedToMulticastGroup(const MulticastGroup &mg,bool includeBridgedGroups) const
  551. {
  552. Mutex::Lock _l(_lock);
  553. if (std::binary_search(_myMulticastGroups.begin(),_myMulticastGroups.end(),mg))
  554. return true;
  555. else if (includeBridgedGroups)
  556. return _multicastGroupsBehindMe.contains(mg);
  557. else return false;
  558. }
  559. void Network::multicastSubscribe(const MulticastGroup &mg)
  560. {
  561. {
  562. Mutex::Lock _l(_lock);
  563. if (std::binary_search(_myMulticastGroups.begin(),_myMulticastGroups.end(),mg))
  564. return;
  565. _myMulticastGroups.push_back(mg);
  566. std::sort(_myMulticastGroups.begin(),_myMulticastGroups.end());
  567. }
  568. _announceMulticastGroups();
  569. }
  570. void Network::multicastUnsubscribe(const MulticastGroup &mg)
  571. {
  572. Mutex::Lock _l(_lock);
  573. std::vector<MulticastGroup> nmg;
  574. for(std::vector<MulticastGroup>::const_iterator i(_myMulticastGroups.begin());i!=_myMulticastGroups.end();++i) {
  575. if (*i != mg)
  576. nmg.push_back(*i);
  577. }
  578. if (nmg.size() != _myMulticastGroups.size())
  579. _myMulticastGroups.swap(nmg);
  580. }
  581. bool Network::tryAnnounceMulticastGroupsTo(const SharedPtr<Peer> &peer)
  582. {
  583. Mutex::Lock _l(_lock);
  584. if (
  585. (_isAllowed(peer)) ||
  586. (peer->address() == this->controller()) ||
  587. (RR->topology->isUpstream(peer->identity()))
  588. ) {
  589. _announceMulticastGroupsTo(peer,_allMulticastGroups());
  590. return true;
  591. }
  592. return false;
  593. }
  594. bool Network::applyConfiguration(const NetworkConfig &conf)
  595. {
  596. if (_destroyed) // sanity check
  597. return false;
  598. try {
  599. if ((conf.networkId == _id)&&(conf.issuedTo == RR->identity.address())) {
  600. ZT_VirtualNetworkConfig ctmp;
  601. bool portInitialized;
  602. {
  603. Mutex::Lock _l(_lock);
  604. _config = conf;
  605. _lastConfigUpdate = RR->node->now();
  606. _netconfFailure = NETCONF_FAILURE_NONE;
  607. _externalConfig(&ctmp);
  608. portInitialized = _portInitialized;
  609. _portInitialized = true;
  610. }
  611. _portError = RR->node->configureVirtualNetworkPort(_id,&_uPtr,(portInitialized) ? ZT_VIRTUAL_NETWORK_CONFIG_OPERATION_CONFIG_UPDATE : ZT_VIRTUAL_NETWORK_CONFIG_OPERATION_UP,&ctmp);
  612. return true;
  613. } else {
  614. TRACE("ignored invalid configuration for network %.16llx (configuration contains mismatched network ID or issued-to address)",(unsigned long long)_id);
  615. }
  616. } catch (std::exception &exc) {
  617. TRACE("ignored invalid configuration for network %.16llx (%s)",(unsigned long long)_id,exc.what());
  618. } catch ( ... ) {
  619. TRACE("ignored invalid configuration for network %.16llx (unknown exception)",(unsigned long long)_id);
  620. }
  621. return false;
  622. }
  623. int Network::setConfiguration(const NetworkConfig &nconf,bool saveToDisk)
  624. {
  625. try {
  626. {
  627. Mutex::Lock _l(_lock);
  628. if (_config == nconf)
  629. return 1; // OK config, but duplicate of what we already have
  630. }
  631. if (applyConfiguration(nconf)) {
  632. if (saveToDisk) {
  633. char n[64];
  634. Utils::snprintf(n,sizeof(n),"networks.d/%.16llx.conf",_id);
  635. Dictionary<ZT_NETWORKCONFIG_DICT_CAPACITY> d;
  636. if (nconf.toDictionary(d,false))
  637. RR->node->dataStorePut(n,(const void *)d.data(),d.sizeBytes(),true);
  638. }
  639. return 2; // OK and configuration has changed
  640. }
  641. } catch ( ... ) {
  642. TRACE("ignored invalid configuration for network %.16llx",(unsigned long long)_id);
  643. }
  644. return 0;
  645. }
  646. void Network::handleInboundConfigChunk(const uint64_t inRePacketId,const void *data,unsigned int chunkSize,unsigned int chunkIndex,unsigned int totalSize)
  647. {
  648. std::string newConfig;
  649. if ((_inboundConfigPacketId == inRePacketId)&&(totalSize < ZT_NETWORKCONFIG_DICT_CAPACITY)&&((chunkIndex + chunkSize) <= totalSize)) {
  650. Mutex::Lock _l(_lock);
  651. _inboundConfigChunks[chunkIndex].append((const char *)data,chunkSize);
  652. unsigned int totalWeHave = 0;
  653. for(std::map<unsigned int,std::string>::iterator c(_inboundConfigChunks.begin());c!=_inboundConfigChunks.end();++c)
  654. totalWeHave += (unsigned int)c->second.length();
  655. if (totalWeHave == totalSize) {
  656. TRACE("have all chunks for network config request %.16llx, assembling...",inRePacketId);
  657. for(std::map<unsigned int,std::string>::iterator c(_inboundConfigChunks.begin());c!=_inboundConfigChunks.end();++c)
  658. newConfig.append(c->second);
  659. _inboundConfigPacketId = 0;
  660. _inboundConfigChunks.clear();
  661. } else if (totalWeHave > totalSize) {
  662. _inboundConfigPacketId = 0;
  663. _inboundConfigChunks.clear();
  664. }
  665. } else {
  666. return;
  667. }
  668. if ((newConfig.length() > 0)&&(newConfig.length() < ZT_NETWORKCONFIG_DICT_CAPACITY)) {
  669. Dictionary<ZT_NETWORKCONFIG_DICT_CAPACITY> *dict = new Dictionary<ZT_NETWORKCONFIG_DICT_CAPACITY>(newConfig.c_str());
  670. NetworkConfig *nc = new NetworkConfig();
  671. try {
  672. Identity controllerId(RR->topology->getIdentity(this->controller()));
  673. if (controllerId) {
  674. if (nc->fromDictionary(*dict)) {
  675. this->setConfiguration(*nc,true);
  676. } else {
  677. TRACE("error parsing new config with length %u: deserialization of NetworkConfig failed (certificate error?)",(unsigned int)newConfig.length());
  678. }
  679. }
  680. delete nc;
  681. delete dict;
  682. } catch ( ... ) {
  683. TRACE("error parsing new config with length %u: unexpected exception",(unsigned int)newConfig.length());
  684. delete nc;
  685. delete dict;
  686. throw;
  687. }
  688. }
  689. }
  690. void Network::requestConfiguration()
  691. {
  692. // Sanity limit: do not request more often than once per second
  693. const uint64_t now = RR->node->now();
  694. if ((now - _lastRequestedConfiguration) < 1000ULL)
  695. return;
  696. _lastRequestedConfiguration = RR->node->now();
  697. const Address ctrl(controller());
  698. Dictionary<ZT_NETWORKCONFIG_METADATA_DICT_CAPACITY> rmd;
  699. rmd.add(ZT_NETWORKCONFIG_REQUEST_METADATA_KEY_VERSION,(uint64_t)ZT_NETWORKCONFIG_VERSION);
  700. rmd.add(ZT_NETWORKCONFIG_REQUEST_METADATA_KEY_PROTOCOL_VERSION,(uint64_t)ZT_PROTO_VERSION);
  701. rmd.add(ZT_NETWORKCONFIG_REQUEST_METADATA_KEY_NODE_MAJOR_VERSION,(uint64_t)ZEROTIER_ONE_VERSION_MAJOR);
  702. rmd.add(ZT_NETWORKCONFIG_REQUEST_METADATA_KEY_NODE_MINOR_VERSION,(uint64_t)ZEROTIER_ONE_VERSION_MINOR);
  703. rmd.add(ZT_NETWORKCONFIG_REQUEST_METADATA_KEY_NODE_REVISION,(uint64_t)ZEROTIER_ONE_VERSION_REVISION);
  704. rmd.add(ZT_NETWORKCONFIG_REQUEST_METADATA_KEY_MAX_NETWORK_RULES,(uint64_t)ZT_MAX_NETWORK_RULES);
  705. rmd.add(ZT_NETWORKCONFIG_REQUEST_METADATA_KEY_MAX_NETWORK_CAPABILITIES,(uint64_t)ZT_MAX_NETWORK_CAPABILITIES);
  706. rmd.add(ZT_NETWORKCONFIG_REQUEST_METADATA_KEY_MAX_CAPABILITY_RULES,(uint64_t)ZT_MAX_CAPABILITY_RULES);
  707. rmd.add(ZT_NETWORKCONFIG_REQUEST_METADATA_KEY_MAX_NETWORK_TAGS,(uint64_t)ZT_MAX_NETWORK_TAGS);
  708. rmd.add(ZT_NETWORKCONFIG_REQUEST_METADATA_KEY_FLAGS,(uint64_t)0);
  709. if (ctrl == RR->identity.address()) {
  710. if (RR->localNetworkController) {
  711. NetworkConfig nconf;
  712. switch(RR->localNetworkController->doNetworkConfigRequest(InetAddress(),RR->identity,RR->identity,_id,rmd,nconf)) {
  713. case NetworkController::NETCONF_QUERY_OK:
  714. this->setConfiguration(nconf,true);
  715. return;
  716. case NetworkController::NETCONF_QUERY_OBJECT_NOT_FOUND:
  717. this->setNotFound();
  718. return;
  719. case NetworkController::NETCONF_QUERY_ACCESS_DENIED:
  720. this->setAccessDenied();
  721. return;
  722. default:
  723. return;
  724. }
  725. } else {
  726. this->setNotFound();
  727. return;
  728. }
  729. }
  730. TRACE("requesting netconf for network %.16llx from controller %s",(unsigned long long)_id,ctrl.toString().c_str());
  731. Packet outp(ctrl,RR->identity.address(),Packet::VERB_NETWORK_CONFIG_REQUEST);
  732. outp.append((uint64_t)_id);
  733. const unsigned int rmdSize = rmd.sizeBytes();
  734. outp.append((uint16_t)rmdSize);
  735. outp.append((const void *)rmd.data(),rmdSize);
  736. if (_config) {
  737. outp.append((uint64_t)_config.revision);
  738. outp.append((uint64_t)_config.timestamp);
  739. } else {
  740. outp.append((unsigned char)0,16);
  741. }
  742. outp.compress();
  743. RR->sw->send(outp,true);
  744. // Expect replies with this in-re packet ID
  745. _inboundConfigPacketId = outp.packetId();
  746. _inboundConfigChunks.clear();
  747. }
  748. void Network::clean()
  749. {
  750. const uint64_t now = RR->node->now();
  751. Mutex::Lock _l(_lock);
  752. if (_destroyed)
  753. return;
  754. {
  755. Hashtable< MulticastGroup,uint64_t >::Iterator i(_multicastGroupsBehindMe);
  756. MulticastGroup *mg = (MulticastGroup *)0;
  757. uint64_t *ts = (uint64_t *)0;
  758. while (i.next(mg,ts)) {
  759. if ((now - *ts) > (ZT_MULTICAST_LIKE_EXPIRE * 2))
  760. _multicastGroupsBehindMe.erase(*mg);
  761. }
  762. }
  763. {
  764. Address *a = (Address *)0;
  765. Membership *m = (Membership *)0;
  766. Hashtable<Address,Membership>::Iterator i(_memberships);
  767. while (i.next(a,m)) {
  768. if ((now - m->clean(now)) > ZT_MEMBERSHIP_EXPIRATION_TIME)
  769. _memberships.erase(*a);
  770. }
  771. }
  772. }
  773. void Network::learnBridgeRoute(const MAC &mac,const Address &addr)
  774. {
  775. Mutex::Lock _l(_lock);
  776. _remoteBridgeRoutes[mac] = addr;
  777. // Anti-DOS circuit breaker to prevent nodes from spamming us with absurd numbers of bridge routes
  778. while (_remoteBridgeRoutes.size() > ZT_MAX_BRIDGE_ROUTES) {
  779. Hashtable< Address,unsigned long > counts;
  780. Address maxAddr;
  781. unsigned long maxCount = 0;
  782. MAC *m = (MAC *)0;
  783. Address *a = (Address *)0;
  784. // Find the address responsible for the most entries
  785. {
  786. Hashtable<MAC,Address>::Iterator i(_remoteBridgeRoutes);
  787. while (i.next(m,a)) {
  788. const unsigned long c = ++counts[*a];
  789. if (c > maxCount) {
  790. maxCount = c;
  791. maxAddr = *a;
  792. }
  793. }
  794. }
  795. // Kill this address from our table, since it's most likely spamming us
  796. {
  797. Hashtable<MAC,Address>::Iterator i(_remoteBridgeRoutes);
  798. while (i.next(m,a)) {
  799. if (*a == maxAddr)
  800. _remoteBridgeRoutes.erase(*m);
  801. }
  802. }
  803. }
  804. }
  805. void Network::learnBridgedMulticastGroup(const MulticastGroup &mg,uint64_t now)
  806. {
  807. Mutex::Lock _l(_lock);
  808. const unsigned long tmp = (unsigned long)_multicastGroupsBehindMe.size();
  809. _multicastGroupsBehindMe.set(mg,now);
  810. if (tmp != _multicastGroupsBehindMe.size())
  811. _announceMulticastGroups();
  812. }
  813. void Network::destroy()
  814. {
  815. Mutex::Lock _l(_lock);
  816. _destroyed = true;
  817. }
  818. ZT_VirtualNetworkStatus Network::_status() const
  819. {
  820. // assumes _lock is locked
  821. if (_portError)
  822. return ZT_NETWORK_STATUS_PORT_ERROR;
  823. switch(_netconfFailure) {
  824. case NETCONF_FAILURE_ACCESS_DENIED:
  825. return ZT_NETWORK_STATUS_ACCESS_DENIED;
  826. case NETCONF_FAILURE_NOT_FOUND:
  827. return ZT_NETWORK_STATUS_NOT_FOUND;
  828. case NETCONF_FAILURE_NONE:
  829. return ((_config) ? ZT_NETWORK_STATUS_OK : ZT_NETWORK_STATUS_REQUESTING_CONFIGURATION);
  830. default:
  831. return ZT_NETWORK_STATUS_PORT_ERROR;
  832. }
  833. }
  834. void Network::_externalConfig(ZT_VirtualNetworkConfig *ec) const
  835. {
  836. // assumes _lock is locked
  837. ec->nwid = _id;
  838. ec->mac = _mac.toInt();
  839. if (_config)
  840. Utils::scopy(ec->name,sizeof(ec->name),_config.name);
  841. else ec->name[0] = (char)0;
  842. ec->status = _status();
  843. ec->type = (_config) ? (_config.isPrivate() ? ZT_NETWORK_TYPE_PRIVATE : ZT_NETWORK_TYPE_PUBLIC) : ZT_NETWORK_TYPE_PRIVATE;
  844. ec->mtu = ZT_IF_MTU;
  845. ec->dhcp = 0;
  846. std::vector<Address> ab(_config.activeBridges());
  847. ec->bridge = ((_config.allowPassiveBridging())||(std::find(ab.begin(),ab.end(),RR->identity.address()) != ab.end())) ? 1 : 0;
  848. ec->broadcastEnabled = (_config) ? (_config.enableBroadcast() ? 1 : 0) : 0;
  849. ec->portError = _portError;
  850. ec->netconfRevision = (_config) ? (unsigned long)_config.revision : 0;
  851. ec->assignedAddressCount = 0;
  852. for(unsigned int i=0;i<ZT_MAX_ZT_ASSIGNED_ADDRESSES;++i) {
  853. if (i < _config.staticIpCount) {
  854. memcpy(&(ec->assignedAddresses[i]),&(_config.staticIps[i]),sizeof(struct sockaddr_storage));
  855. ++ec->assignedAddressCount;
  856. } else {
  857. memset(&(ec->assignedAddresses[i]),0,sizeof(struct sockaddr_storage));
  858. }
  859. }
  860. ec->routeCount = 0;
  861. for(unsigned int i=0;i<ZT_MAX_NETWORK_ROUTES;++i) {
  862. if (i < _config.routeCount) {
  863. memcpy(&(ec->routes[i]),&(_config.routes[i]),sizeof(ZT_VirtualNetworkRoute));
  864. ++ec->routeCount;
  865. } else {
  866. memset(&(ec->routes[i]),0,sizeof(ZT_VirtualNetworkRoute));
  867. }
  868. }
  869. }
  870. bool Network::_isAllowed(const SharedPtr<Peer> &peer) const
  871. {
  872. // Assumes _lock is locked
  873. try {
  874. if (_config) {
  875. const Membership *const m = _memberships.get(peer->address());
  876. if (m)
  877. return m->isAllowedOnNetwork(_config);
  878. }
  879. } catch ( ... ) {
  880. TRACE("isAllowed() check failed for peer %s: unexpected exception",peer->address().toString().c_str());
  881. }
  882. return false;
  883. }
  884. class _MulticastAnnounceAll
  885. {
  886. public:
  887. _MulticastAnnounceAll(const RuntimeEnvironment *renv,Network *nw) :
  888. _now(renv->node->now()),
  889. _controller(nw->controller()),
  890. _network(nw),
  891. _anchors(nw->config().anchors()),
  892. _upstreamAddresses(renv->topology->upstreamAddresses())
  893. {}
  894. inline void operator()(Topology &t,const SharedPtr<Peer> &p)
  895. {
  896. if ( (_network->_isAllowed(p)) || // FIXME: this causes multicast LIKEs for public networks to get spammed, which isn't terrible but is a bit stupid
  897. (p->address() == _controller) ||
  898. (std::find(_upstreamAddresses.begin(),_upstreamAddresses.end(),p->address()) != _upstreamAddresses.end()) ||
  899. (std::find(_anchors.begin(),_anchors.end(),p->address()) != _anchors.end()) ) {
  900. peers.push_back(p);
  901. }
  902. }
  903. std::vector< SharedPtr<Peer> > peers;
  904. private:
  905. const uint64_t _now;
  906. const Address _controller;
  907. Network *const _network;
  908. const std::vector<Address> _anchors;
  909. const std::vector<Address> _upstreamAddresses;
  910. };
  911. void Network::_announceMulticastGroups()
  912. {
  913. // Assumes _lock is locked
  914. std::vector<MulticastGroup> allMulticastGroups(_allMulticastGroups());
  915. _MulticastAnnounceAll gpfunc(RR,this);
  916. RR->topology->eachPeer<_MulticastAnnounceAll &>(gpfunc);
  917. for(std::vector< SharedPtr<Peer> >::const_iterator i(gpfunc.peers.begin());i!=gpfunc.peers.end();++i)
  918. _announceMulticastGroupsTo(*i,allMulticastGroups);
  919. }
  920. void Network::_announceMulticastGroupsTo(const SharedPtr<Peer> &peer,const std::vector<MulticastGroup> &allMulticastGroups)
  921. {
  922. // Assumes _lock is locked
  923. // Anyone we announce multicast groups to will need our COM to authenticate GATHER requests.
  924. {
  925. Membership *m = _memberships.get(peer->address());
  926. if (m)
  927. m->sendCredentialsIfNeeded(RR,RR->node->now(),peer->address(),_config.com,(const Capability *)0,(const Tag **)0,0);
  928. }
  929. Packet outp(peer->address(),RR->identity.address(),Packet::VERB_MULTICAST_LIKE);
  930. for(std::vector<MulticastGroup>::const_iterator mg(allMulticastGroups.begin());mg!=allMulticastGroups.end();++mg) {
  931. if ((outp.size() + 24) >= ZT_PROTO_MAX_PACKET_LENGTH) {
  932. outp.compress();
  933. RR->sw->send(outp,true);
  934. outp.reset(peer->address(),RR->identity.address(),Packet::VERB_MULTICAST_LIKE);
  935. }
  936. // network ID, MAC, ADI
  937. outp.append((uint64_t)_id);
  938. mg->mac().appendTo(outp);
  939. outp.append((uint32_t)mg->adi());
  940. }
  941. if (outp.size() > ZT_PROTO_MIN_PACKET_LENGTH) {
  942. outp.compress();
  943. RR->sw->send(outp,true);
  944. }
  945. }
  946. std::vector<MulticastGroup> Network::_allMulticastGroups() const
  947. {
  948. // Assumes _lock is locked
  949. std::vector<MulticastGroup> mgs;
  950. mgs.reserve(_myMulticastGroups.size() + _multicastGroupsBehindMe.size() + 1);
  951. mgs.insert(mgs.end(),_myMulticastGroups.begin(),_myMulticastGroups.end());
  952. _multicastGroupsBehindMe.appendKeys(mgs);
  953. if ((_config)&&(_config.enableBroadcast()))
  954. mgs.push_back(Network::BROADCAST);
  955. std::sort(mgs.begin(),mgs.end());
  956. mgs.erase(std::unique(mgs.begin(),mgs.end()),mgs.end());
  957. return mgs;
  958. }
  959. } // namespace ZeroTier