Network.cpp 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990
  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.zt),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));
  148. macDest.appendTo(outp);
  149. macSource.appendTo(outp);
  150. outp.append((uint16_t)etherType);
  151. outp.append(frameData,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. _destroyed(false),
  385. _netconfFailure(NETCONF_FAILURE_NONE),
  386. _portError(0)
  387. {
  388. char confn[128];
  389. Utils::snprintf(confn,sizeof(confn),"networks.d/%.16llx.conf",_id);
  390. bool gotConf = false;
  391. Dictionary<ZT_NETWORKCONFIG_DICT_CAPACITY> *dconf = new Dictionary<ZT_NETWORKCONFIG_DICT_CAPACITY>();
  392. NetworkConfig *nconf = new NetworkConfig();
  393. try {
  394. std::string conf(RR->node->dataStoreGet(confn));
  395. if (conf.length()) {
  396. dconf->load(conf.c_str());
  397. if (nconf->fromDictionary(Identity(),*dconf)) {
  398. this->setConfiguration(*nconf,false);
  399. _lastConfigUpdate = 0; // we still want to re-request a new config from the network
  400. gotConf = true;
  401. }
  402. }
  403. } catch ( ... ) {} // ignore invalids, we'll re-request
  404. delete nconf;
  405. delete dconf;
  406. if (!gotConf) {
  407. // Save a one-byte CR to persist membership while we request a real netconf
  408. RR->node->dataStorePut(confn,"\n",1,false);
  409. }
  410. if (!_portInitialized) {
  411. ZT_VirtualNetworkConfig ctmp;
  412. _externalConfig(&ctmp);
  413. _portError = RR->node->configureVirtualNetworkPort(_id,&_uPtr,ZT_VIRTUAL_NETWORK_CONFIG_OPERATION_UP,&ctmp);
  414. _portInitialized = true;
  415. }
  416. }
  417. Network::~Network()
  418. {
  419. ZT_VirtualNetworkConfig ctmp;
  420. _externalConfig(&ctmp);
  421. char n[128];
  422. if (_destroyed) {
  423. RR->node->configureVirtualNetworkPort(_id,&_uPtr,ZT_VIRTUAL_NETWORK_CONFIG_OPERATION_DESTROY,&ctmp);
  424. Utils::snprintf(n,sizeof(n),"networks.d/%.16llx.conf",_id);
  425. RR->node->dataStoreDelete(n);
  426. } else {
  427. RR->node->configureVirtualNetworkPort(_id,&_uPtr,ZT_VIRTUAL_NETWORK_CONFIG_OPERATION_DOWN,&ctmp);
  428. }
  429. }
  430. bool Network::filterOutgoingPacket(
  431. const Address &ztSource,
  432. const Address &ztDest,
  433. const MAC &macSource,
  434. const MAC &macDest,
  435. const uint8_t *frameData,
  436. const unsigned int frameLen,
  437. const unsigned int etherType,
  438. const unsigned int vlanId)
  439. {
  440. uint32_t remoteTagIds[ZT_MAX_NETWORK_TAGS];
  441. uint32_t remoteTagValues[ZT_MAX_NETWORK_TAGS];
  442. const Tag *relevantLocalTags[ZT_MAX_NETWORK_TAGS];
  443. unsigned int relevantLocalTagCount = 0;
  444. Mutex::Lock _l(_lock);
  445. Membership &m = _memberships[ztDest];
  446. const unsigned int remoteTagCount = m.getAllTags(_config,remoteTagIds,remoteTagValues,ZT_MAX_NETWORK_TAGS);
  447. 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)) {
  448. case -1:
  449. return false;
  450. case 1:
  451. m.sendCredentialsIfNeeded(RR,RR->node->now(),ztDest,_config.com,(const Capability *)0,relevantLocalTags,relevantLocalTagCount);
  452. return true;
  453. }
  454. for(unsigned int c=0;c<_config.capabilityCount;++c) {
  455. relevantLocalTagCount = 0;
  456. 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)) {
  457. case -1:
  458. return false;
  459. case 1:
  460. m.sendCredentialsIfNeeded(RR,RR->node->now(),ztDest,_config.com,&(_config.capabilities[c]),relevantLocalTags,relevantLocalTagCount);
  461. return true;
  462. }
  463. }
  464. return false;
  465. }
  466. bool Network::filterIncomingPacket(
  467. const SharedPtr<Peer> &sourcePeer,
  468. const Address &ztDest,
  469. const MAC &macSource,
  470. const MAC &macDest,
  471. const uint8_t *frameData,
  472. const unsigned int frameLen,
  473. const unsigned int etherType,
  474. const unsigned int vlanId)
  475. {
  476. uint32_t remoteTagIds[ZT_MAX_NETWORK_TAGS];
  477. uint32_t remoteTagValues[ZT_MAX_NETWORK_TAGS];
  478. const Tag *relevantLocalTags[ZT_MAX_NETWORK_TAGS];
  479. unsigned int relevantLocalTagCount = 0;
  480. Mutex::Lock _l(_lock);
  481. Membership &m = _memberships[ztDest];
  482. const unsigned int remoteTagCount = m.getAllTags(_config,remoteTagIds,remoteTagValues,ZT_MAX_NETWORK_TAGS);
  483. 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)) {
  484. case -1:
  485. return false;
  486. case 1:
  487. return true;
  488. }
  489. Membership::CapabilityIterator mci(m);
  490. const Capability *c;
  491. while ((c = mci.next(_config))) {
  492. relevantLocalTagCount = 0;
  493. 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)) {
  494. case -1:
  495. return false;
  496. case 1:
  497. return true;
  498. }
  499. }
  500. return false;
  501. }
  502. bool Network::subscribedToMulticastGroup(const MulticastGroup &mg,bool includeBridgedGroups) const
  503. {
  504. Mutex::Lock _l(_lock);
  505. if (std::binary_search(_myMulticastGroups.begin(),_myMulticastGroups.end(),mg))
  506. return true;
  507. else if (includeBridgedGroups)
  508. return _multicastGroupsBehindMe.contains(mg);
  509. else return false;
  510. }
  511. void Network::multicastSubscribe(const MulticastGroup &mg)
  512. {
  513. {
  514. Mutex::Lock _l(_lock);
  515. if (std::binary_search(_myMulticastGroups.begin(),_myMulticastGroups.end(),mg))
  516. return;
  517. _myMulticastGroups.push_back(mg);
  518. std::sort(_myMulticastGroups.begin(),_myMulticastGroups.end());
  519. }
  520. _announceMulticastGroups();
  521. }
  522. void Network::multicastUnsubscribe(const MulticastGroup &mg)
  523. {
  524. Mutex::Lock _l(_lock);
  525. std::vector<MulticastGroup> nmg;
  526. for(std::vector<MulticastGroup>::const_iterator i(_myMulticastGroups.begin());i!=_myMulticastGroups.end();++i) {
  527. if (*i != mg)
  528. nmg.push_back(*i);
  529. }
  530. if (nmg.size() != _myMulticastGroups.size())
  531. _myMulticastGroups.swap(nmg);
  532. }
  533. bool Network::tryAnnounceMulticastGroupsTo(const SharedPtr<Peer> &peer)
  534. {
  535. Mutex::Lock _l(_lock);
  536. if (
  537. (_isAllowed(peer)) ||
  538. (peer->address() == this->controller()) ||
  539. (RR->topology->isUpstream(peer->identity()))
  540. ) {
  541. _announceMulticastGroupsTo(peer,_allMulticastGroups());
  542. return true;
  543. }
  544. return false;
  545. }
  546. bool Network::applyConfiguration(const NetworkConfig &conf)
  547. {
  548. if (_destroyed) // sanity check
  549. return false;
  550. try {
  551. if ((conf.networkId == _id)&&(conf.issuedTo == RR->identity.address())) {
  552. ZT_VirtualNetworkConfig ctmp;
  553. bool portInitialized;
  554. {
  555. Mutex::Lock _l(_lock);
  556. _config = conf;
  557. _lastConfigUpdate = RR->node->now();
  558. _netconfFailure = NETCONF_FAILURE_NONE;
  559. _externalConfig(&ctmp);
  560. portInitialized = _portInitialized;
  561. _portInitialized = true;
  562. }
  563. _portError = RR->node->configureVirtualNetworkPort(_id,&_uPtr,(portInitialized) ? ZT_VIRTUAL_NETWORK_CONFIG_OPERATION_CONFIG_UPDATE : ZT_VIRTUAL_NETWORK_CONFIG_OPERATION_UP,&ctmp);
  564. return true;
  565. } else {
  566. TRACE("ignored invalid configuration for network %.16llx (configuration contains mismatched network ID or issued-to address)",(unsigned long long)_id);
  567. }
  568. } catch (std::exception &exc) {
  569. TRACE("ignored invalid configuration for network %.16llx (%s)",(unsigned long long)_id,exc.what());
  570. } catch ( ... ) {
  571. TRACE("ignored invalid configuration for network %.16llx (unknown exception)",(unsigned long long)_id);
  572. }
  573. return false;
  574. }
  575. int Network::setConfiguration(const NetworkConfig &nconf,bool saveToDisk)
  576. {
  577. try {
  578. {
  579. Mutex::Lock _l(_lock);
  580. if (_config == nconf)
  581. return 1; // OK config, but duplicate of what we already have
  582. }
  583. if (applyConfiguration(nconf)) {
  584. if (saveToDisk) {
  585. char n[64];
  586. Utils::snprintf(n,sizeof(n),"networks.d/%.16llx.conf",_id);
  587. Dictionary<ZT_NETWORKCONFIG_DICT_CAPACITY> d;
  588. if (nconf.toDictionary(d,false))
  589. RR->node->dataStorePut(n,(const void *)d.data(),d.sizeBytes(),true);
  590. }
  591. return 2; // OK and configuration has changed
  592. }
  593. } catch ( ... ) {
  594. TRACE("ignored invalid configuration for network %.16llx",(unsigned long long)_id);
  595. }
  596. return 0;
  597. }
  598. void Network::handleInboundConfigChunk(const uint64_t inRePacketId,const void *data,unsigned int chunkSize,unsigned int chunkIndex,unsigned int totalSize)
  599. {
  600. std::string newConfig;
  601. if ((_inboundConfigPacketId == inRePacketId)&&(totalSize < ZT_NETWORKCONFIG_DICT_CAPACITY)&&((chunkIndex + chunkSize) <= totalSize)) {
  602. Mutex::Lock _l(_lock);
  603. _inboundConfigChunks[chunkIndex].append((const char *)data,chunkSize);
  604. unsigned int totalWeHave = 0;
  605. for(std::map<unsigned int,std::string>::iterator c(_inboundConfigChunks.begin());c!=_inboundConfigChunks.end();++c)
  606. totalWeHave += (unsigned int)c->second.length();
  607. if (totalWeHave == totalSize) {
  608. TRACE("have all chunks for network config request %.16llx, assembling...",inRePacketId);
  609. for(std::map<unsigned int,std::string>::iterator c(_inboundConfigChunks.begin());c!=_inboundConfigChunks.end();++c)
  610. newConfig.append(c->second);
  611. _inboundConfigPacketId = 0;
  612. _inboundConfigChunks.clear();
  613. } else if (totalWeHave > totalSize) {
  614. _inboundConfigPacketId = 0;
  615. _inboundConfigChunks.clear();
  616. }
  617. } else {
  618. return;
  619. }
  620. if ((newConfig.length() > 0)&&(newConfig.length() < ZT_NETWORKCONFIG_DICT_CAPACITY)) {
  621. Dictionary<ZT_NETWORKCONFIG_DICT_CAPACITY> *dict = new Dictionary<ZT_NETWORKCONFIG_DICT_CAPACITY>(newConfig.c_str());
  622. NetworkConfig *nc = new NetworkConfig();
  623. try {
  624. Identity controllerId(RR->topology->getIdentity(this->controller()));
  625. if (controllerId) {
  626. if (nc->fromDictionary(controllerId,*dict)) {
  627. this->setConfiguration(*nc,true);
  628. } else {
  629. TRACE("error parsing new config with length %u: deserialization of NetworkConfig failed (certificate error?)",(unsigned int)newConfig.length());
  630. }
  631. }
  632. delete nc;
  633. delete dict;
  634. } catch ( ... ) {
  635. TRACE("error parsing new config with length %u: unexpected exception",(unsigned int)newConfig.length());
  636. delete nc;
  637. delete dict;
  638. throw;
  639. }
  640. }
  641. }
  642. void Network::requestConfiguration()
  643. {
  644. Dictionary<ZT_NETWORKCONFIG_METADATA_DICT_CAPACITY> rmd;
  645. rmd.add(ZT_NETWORKCONFIG_REQUEST_METADATA_KEY_VERSION,(uint64_t)ZT_NETWORKCONFIG_VERSION);
  646. rmd.add(ZT_NETWORKCONFIG_REQUEST_METADATA_KEY_PROTOCOL_VERSION,(uint64_t)ZT_PROTO_VERSION);
  647. rmd.add(ZT_NETWORKCONFIG_REQUEST_METADATA_KEY_NODE_MAJOR_VERSION,(uint64_t)ZEROTIER_ONE_VERSION_MAJOR);
  648. rmd.add(ZT_NETWORKCONFIG_REQUEST_METADATA_KEY_NODE_MINOR_VERSION,(uint64_t)ZEROTIER_ONE_VERSION_MINOR);
  649. rmd.add(ZT_NETWORKCONFIG_REQUEST_METADATA_KEY_NODE_REVISION,(uint64_t)ZEROTIER_ONE_VERSION_REVISION);
  650. rmd.add(ZT_NETWORKCONFIG_REQUEST_METADATA_KEY_MAX_NETWORK_RULES,(uint64_t)ZT_MAX_NETWORK_RULES);
  651. rmd.add(ZT_NETWORKCONFIG_REQUEST_METADATA_KEY_MAX_NETWORK_CAPABILITIES,(uint64_t)ZT_MAX_NETWORK_CAPABILITIES);
  652. rmd.add(ZT_NETWORKCONFIG_REQUEST_METADATA_KEY_MAX_CAPABILITY_RULES,(uint64_t)ZT_MAX_CAPABILITY_RULES);
  653. rmd.add(ZT_NETWORKCONFIG_REQUEST_METADATA_KEY_MAX_NETWORK_TAGS,(uint64_t)ZT_MAX_NETWORK_TAGS);
  654. rmd.add(ZT_NETWORKCONFIG_REQUEST_METADATA_KEY_FLAGS,(uint64_t)0);
  655. if (controller() == RR->identity.address()) {
  656. if (RR->localNetworkController) {
  657. NetworkConfig nconf;
  658. switch(RR->localNetworkController->doNetworkConfigRequest(InetAddress(),RR->identity,RR->identity,_id,rmd,nconf)) {
  659. case NetworkController::NETCONF_QUERY_OK:
  660. this->setConfiguration(nconf,true);
  661. return;
  662. case NetworkController::NETCONF_QUERY_OBJECT_NOT_FOUND:
  663. this->setNotFound();
  664. return;
  665. case NetworkController::NETCONF_QUERY_ACCESS_DENIED:
  666. this->setAccessDenied();
  667. return;
  668. default:
  669. return;
  670. }
  671. } else {
  672. this->setNotFound();
  673. return;
  674. }
  675. }
  676. TRACE("requesting netconf for network %.16llx from controller %s",(unsigned long long)_id,controller().toString().c_str());
  677. Packet outp(controller(),RR->identity.address(),Packet::VERB_NETWORK_CONFIG_REQUEST);
  678. outp.append((uint64_t)_id);
  679. const unsigned int rmdSize = rmd.sizeBytes();
  680. outp.append((uint16_t)rmdSize);
  681. outp.append((const void *)rmd.data(),rmdSize);
  682. if (_config) {
  683. outp.append((uint64_t)_config.revision);
  684. outp.append((uint64_t)_config.timestamp);
  685. } else {
  686. outp.append((unsigned char)0,16);
  687. }
  688. outp.compress();
  689. RR->sw->send(outp,true);
  690. // Expect replies with this in-re packet ID
  691. _inboundConfigPacketId = outp.packetId();
  692. _inboundConfigChunks.clear();
  693. }
  694. void Network::clean()
  695. {
  696. const uint64_t now = RR->node->now();
  697. Mutex::Lock _l(_lock);
  698. if (_destroyed)
  699. return;
  700. {
  701. Hashtable< MulticastGroup,uint64_t >::Iterator i(_multicastGroupsBehindMe);
  702. MulticastGroup *mg = (MulticastGroup *)0;
  703. uint64_t *ts = (uint64_t *)0;
  704. while (i.next(mg,ts)) {
  705. if ((now - *ts) > (ZT_MULTICAST_LIKE_EXPIRE * 2))
  706. _multicastGroupsBehindMe.erase(*mg);
  707. }
  708. }
  709. {
  710. Address *a = (Address *)0;
  711. Membership *m = (Membership *)0;
  712. Hashtable<Address,Membership>::Iterator i(_memberships);
  713. while (i.next(a,m)) {
  714. if ((now - m->clean(now)) > ZT_MEMBERSHIP_EXPIRATION_TIME)
  715. _memberships.erase(*a);
  716. }
  717. }
  718. }
  719. void Network::learnBridgeRoute(const MAC &mac,const Address &addr)
  720. {
  721. Mutex::Lock _l(_lock);
  722. _remoteBridgeRoutes[mac] = addr;
  723. // Anti-DOS circuit breaker to prevent nodes from spamming us with absurd numbers of bridge routes
  724. while (_remoteBridgeRoutes.size() > ZT_MAX_BRIDGE_ROUTES) {
  725. Hashtable< Address,unsigned long > counts;
  726. Address maxAddr;
  727. unsigned long maxCount = 0;
  728. MAC *m = (MAC *)0;
  729. Address *a = (Address *)0;
  730. // Find the address responsible for the most entries
  731. {
  732. Hashtable<MAC,Address>::Iterator i(_remoteBridgeRoutes);
  733. while (i.next(m,a)) {
  734. const unsigned long c = ++counts[*a];
  735. if (c > maxCount) {
  736. maxCount = c;
  737. maxAddr = *a;
  738. }
  739. }
  740. }
  741. // Kill this address from our table, since it's most likely spamming us
  742. {
  743. Hashtable<MAC,Address>::Iterator i(_remoteBridgeRoutes);
  744. while (i.next(m,a)) {
  745. if (*a == maxAddr)
  746. _remoteBridgeRoutes.erase(*m);
  747. }
  748. }
  749. }
  750. }
  751. void Network::learnBridgedMulticastGroup(const MulticastGroup &mg,uint64_t now)
  752. {
  753. Mutex::Lock _l(_lock);
  754. const unsigned long tmp = (unsigned long)_multicastGroupsBehindMe.size();
  755. _multicastGroupsBehindMe.set(mg,now);
  756. if (tmp != _multicastGroupsBehindMe.size())
  757. _announceMulticastGroups();
  758. }
  759. void Network::destroy()
  760. {
  761. Mutex::Lock _l(_lock);
  762. _destroyed = true;
  763. }
  764. ZT_VirtualNetworkStatus Network::_status() const
  765. {
  766. // assumes _lock is locked
  767. if (_portError)
  768. return ZT_NETWORK_STATUS_PORT_ERROR;
  769. switch(_netconfFailure) {
  770. case NETCONF_FAILURE_ACCESS_DENIED:
  771. return ZT_NETWORK_STATUS_ACCESS_DENIED;
  772. case NETCONF_FAILURE_NOT_FOUND:
  773. return ZT_NETWORK_STATUS_NOT_FOUND;
  774. case NETCONF_FAILURE_NONE:
  775. return ((_config) ? ZT_NETWORK_STATUS_OK : ZT_NETWORK_STATUS_REQUESTING_CONFIGURATION);
  776. default:
  777. return ZT_NETWORK_STATUS_PORT_ERROR;
  778. }
  779. }
  780. void Network::_externalConfig(ZT_VirtualNetworkConfig *ec) const
  781. {
  782. // assumes _lock is locked
  783. ec->nwid = _id;
  784. ec->mac = _mac.toInt();
  785. if (_config)
  786. Utils::scopy(ec->name,sizeof(ec->name),_config.name);
  787. else ec->name[0] = (char)0;
  788. ec->status = _status();
  789. ec->type = (_config) ? (_config.isPrivate() ? ZT_NETWORK_TYPE_PRIVATE : ZT_NETWORK_TYPE_PUBLIC) : ZT_NETWORK_TYPE_PRIVATE;
  790. ec->mtu = ZT_IF_MTU;
  791. ec->dhcp = 0;
  792. std::vector<Address> ab(_config.activeBridges());
  793. ec->bridge = ((_config.allowPassiveBridging())||(std::find(ab.begin(),ab.end(),RR->identity.address()) != ab.end())) ? 1 : 0;
  794. ec->broadcastEnabled = (_config) ? (_config.enableBroadcast() ? 1 : 0) : 0;
  795. ec->portError = _portError;
  796. ec->netconfRevision = (_config) ? (unsigned long)_config.revision : 0;
  797. ec->assignedAddressCount = 0;
  798. for(unsigned int i=0;i<ZT_MAX_ZT_ASSIGNED_ADDRESSES;++i) {
  799. if (i < _config.staticIpCount) {
  800. memcpy(&(ec->assignedAddresses[i]),&(_config.staticIps[i]),sizeof(struct sockaddr_storage));
  801. ++ec->assignedAddressCount;
  802. } else {
  803. memset(&(ec->assignedAddresses[i]),0,sizeof(struct sockaddr_storage));
  804. }
  805. }
  806. ec->routeCount = 0;
  807. for(unsigned int i=0;i<ZT_MAX_NETWORK_ROUTES;++i) {
  808. if (i < _config.routeCount) {
  809. memcpy(&(ec->routes[i]),&(_config.routes[i]),sizeof(ZT_VirtualNetworkRoute));
  810. ++ec->routeCount;
  811. } else {
  812. memset(&(ec->routes[i]),0,sizeof(ZT_VirtualNetworkRoute));
  813. }
  814. }
  815. }
  816. bool Network::_isAllowed(const SharedPtr<Peer> &peer) const
  817. {
  818. // Assumes _lock is locked
  819. try {
  820. if (_config) {
  821. if (_config.isPublic()) {
  822. return true;
  823. } else {
  824. const Membership *m = _memberships.get(peer->address());
  825. if (m)
  826. return _config.com.agreesWith(m->com());
  827. }
  828. }
  829. } catch ( ... ) {
  830. TRACE("isAllowed() check failed for peer %s: unexpected exception: unexpected exception",peer->address().toString().c_str());
  831. }
  832. return false;
  833. }
  834. class _MulticastAnnounceAll
  835. {
  836. public:
  837. _MulticastAnnounceAll(const RuntimeEnvironment *renv,Network *nw) :
  838. _now(renv->node->now()),
  839. _controller(nw->controller()),
  840. _network(nw),
  841. _anchors(nw->config().anchors()),
  842. _upstreamAddresses(renv->topology->upstreamAddresses())
  843. {}
  844. inline void operator()(Topology &t,const SharedPtr<Peer> &p)
  845. {
  846. if ( (_network->_isAllowed(p)) || // FIXME: this causes multicast LIKEs for public networks to get spammed, which isn't terrible but is a bit stupid
  847. (p->address() == _controller) ||
  848. (std::find(_upstreamAddresses.begin(),_upstreamAddresses.end(),p->address()) != _upstreamAddresses.end()) ||
  849. (std::find(_anchors.begin(),_anchors.end(),p->address()) != _anchors.end()) ) {
  850. peers.push_back(p);
  851. }
  852. }
  853. std::vector< SharedPtr<Peer> > peers;
  854. private:
  855. const uint64_t _now;
  856. const Address _controller;
  857. Network *const _network;
  858. const std::vector<Address> _anchors;
  859. const std::vector<Address> _upstreamAddresses;
  860. };
  861. void Network::_announceMulticastGroups()
  862. {
  863. // Assumes _lock is locked
  864. std::vector<MulticastGroup> allMulticastGroups(_allMulticastGroups());
  865. _MulticastAnnounceAll gpfunc(RR,this);
  866. RR->topology->eachPeer<_MulticastAnnounceAll &>(gpfunc);
  867. for(std::vector< SharedPtr<Peer> >::const_iterator i(gpfunc.peers.begin());i!=gpfunc.peers.end();++i)
  868. _announceMulticastGroupsTo(*i,allMulticastGroups);
  869. }
  870. void Network::_announceMulticastGroupsTo(const SharedPtr<Peer> &peer,const std::vector<MulticastGroup> &allMulticastGroups)
  871. {
  872. // Assumes _lock is locked
  873. // Anyone we announce multicast groups to will need our COM to authenticate GATHER requests.
  874. {
  875. Membership *m = _memberships.get(peer->address());
  876. if (m)
  877. m->sendCredentialsIfNeeded(RR,RR->node->now(),peer->address(),_config.com,(const Capability *)0,(const Tag **)0,0);
  878. }
  879. Packet outp(peer->address(),RR->identity.address(),Packet::VERB_MULTICAST_LIKE);
  880. for(std::vector<MulticastGroup>::const_iterator mg(allMulticastGroups.begin());mg!=allMulticastGroups.end();++mg) {
  881. if ((outp.size() + 24) >= ZT_PROTO_MAX_PACKET_LENGTH) {
  882. outp.compress();
  883. RR->sw->send(outp,true);
  884. outp.reset(peer->address(),RR->identity.address(),Packet::VERB_MULTICAST_LIKE);
  885. }
  886. // network ID, MAC, ADI
  887. outp.append((uint64_t)_id);
  888. mg->mac().appendTo(outp);
  889. outp.append((uint32_t)mg->adi());
  890. }
  891. if (outp.size() > ZT_PROTO_MIN_PACKET_LENGTH) {
  892. outp.compress();
  893. RR->sw->send(outp,true);
  894. }
  895. }
  896. std::vector<MulticastGroup> Network::_allMulticastGroups() const
  897. {
  898. // Assumes _lock is locked
  899. std::vector<MulticastGroup> mgs;
  900. mgs.reserve(_myMulticastGroups.size() + _multicastGroupsBehindMe.size() + 1);
  901. mgs.insert(mgs.end(),_myMulticastGroups.begin(),_myMulticastGroups.end());
  902. _multicastGroupsBehindMe.appendKeys(mgs);
  903. if ((_config)&&(_config.enableBroadcast()))
  904. mgs.push_back(Network::BROADCAST);
  905. std::sort(mgs.begin(),mgs.end());
  906. mgs.erase(std::unique(mgs.begin(),mgs.end()),mgs.end());
  907. return mgs;
  908. }
  909. } // namespace ZeroTier