Network.cpp 36 KB

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