Network.cpp 36 KB

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