Switch.cpp 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706
  1. /*
  2. * ZeroTier One - Network Virtualization Everywhere
  3. * Copyright (C) 2011-2018 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. * --
  19. *
  20. * You can be released from the requirements of the license by purchasing
  21. * a commercial license. Buying such a license is mandatory as soon as you
  22. * develop commercial closed-source software that incorporates or links
  23. * directly against ZeroTier software without disclosing the source code
  24. * of your own application.
  25. */
  26. #include <stdio.h>
  27. #include <stdlib.h>
  28. #include <algorithm>
  29. #include <utility>
  30. #include <stdexcept>
  31. #include "../version.h"
  32. #include "../include/ZeroTierOne.h"
  33. #include "Constants.hpp"
  34. #include "RuntimeEnvironment.hpp"
  35. #include "Switch.hpp"
  36. #include "Node.hpp"
  37. #include "InetAddress.hpp"
  38. #include "Topology.hpp"
  39. #include "Peer.hpp"
  40. #include "SelfAwareness.hpp"
  41. #include "Packet.hpp"
  42. #include "Trace.hpp"
  43. namespace ZeroTier {
  44. Switch::Switch(const RuntimeEnvironment *renv) :
  45. RR(renv),
  46. _lastBeaconResponse(0),
  47. _lastCheckedQueues(0),
  48. _lastUniteAttempt(8) // only really used on root servers and upstreams, and it'll grow there just fine
  49. {
  50. }
  51. void Switch::onRemotePacket(void *tPtr,const int64_t localSocket,const InetAddress &fromAddr,const void *data,unsigned int len)
  52. {
  53. try {
  54. const int64_t now = RR->node->now();
  55. const SharedPtr<Path> path(RR->topology->getPath(localSocket,fromAddr));
  56. path->received(now);
  57. if (len == 13) {
  58. /* LEGACY: before VERB_PUSH_DIRECT_PATHS, peers used broadcast
  59. * announcements on the LAN to solve the 'same network problem.' We
  60. * no longer send these, but we'll listen for them for a while to
  61. * locate peers with versions <1.0.4. */
  62. const Address beaconAddr(reinterpret_cast<const char *>(data) + 8,5);
  63. if (beaconAddr == RR->identity.address())
  64. return;
  65. if (!RR->node->shouldUsePathForZeroTierTraffic(tPtr,beaconAddr,localSocket,fromAddr))
  66. return;
  67. const SharedPtr<Peer> peer(RR->topology->getPeer(tPtr,beaconAddr));
  68. if (peer) { // we'll only respond to beacons from known peers
  69. if ((now - _lastBeaconResponse) >= 2500) { // limit rate of responses
  70. _lastBeaconResponse = now;
  71. Packet outp(peer->address(),RR->identity.address(),Packet::VERB_NOP);
  72. outp.armor(peer->key(),true);
  73. path->send(RR,tPtr,outp.data(),outp.size(),now);
  74. }
  75. }
  76. } else if (len > ZT_PROTO_MIN_FRAGMENT_LENGTH) { // SECURITY: min length check is important since we do some C-style stuff below!
  77. if (reinterpret_cast<const uint8_t *>(data)[ZT_PACKET_FRAGMENT_IDX_FRAGMENT_INDICATOR] == ZT_PACKET_FRAGMENT_INDICATOR) {
  78. // Handle fragment ----------------------------------------------------
  79. Packet::Fragment fragment(data,len);
  80. const Address destination(fragment.destination());
  81. if (destination != RR->identity.address()) {
  82. if ( (!RR->topology->amUpstream()) && (!path->trustEstablished(now)) )
  83. return;
  84. if (fragment.hops() < ZT_RELAY_MAX_HOPS) {
  85. fragment.incrementHops();
  86. // Note: we don't bother initiating NAT-t for fragments, since heads will set that off.
  87. // It wouldn't hurt anything, just redundant and unnecessary.
  88. SharedPtr<Peer> relayTo = RR->topology->getPeer(tPtr,destination);
  89. if ((!relayTo)||(!relayTo->sendDirect(tPtr,fragment.data(),fragment.size(),now,false))) {
  90. // Don't know peer or no direct path -- so relay via someone upstream
  91. relayTo = RR->topology->getUpstreamPeer();
  92. if (relayTo)
  93. relayTo->sendDirect(tPtr,fragment.data(),fragment.size(),now,true);
  94. }
  95. }
  96. } else {
  97. // Fragment looks like ours
  98. const uint64_t fragmentPacketId = fragment.packetId();
  99. const unsigned int fragmentNumber = fragment.fragmentNumber();
  100. const unsigned int totalFragments = fragment.totalFragments();
  101. if ((totalFragments <= ZT_MAX_PACKET_FRAGMENTS)&&(fragmentNumber < ZT_MAX_PACKET_FRAGMENTS)&&(fragmentNumber > 0)&&(totalFragments > 1)) {
  102. // Fragment appears basically sane. Its fragment number must be
  103. // 1 or more, since a Packet with fragmented bit set is fragment 0.
  104. // Total fragments must be more than 1, otherwise why are we
  105. // seeing a Packet::Fragment?
  106. RXQueueEntry *const rq = _findRXQueueEntry(fragmentPacketId);
  107. Mutex::Lock rql(rq->lock);
  108. if (rq->packetId != fragmentPacketId) {
  109. // No packet found, so we received a fragment without its head.
  110. rq->timestamp = now;
  111. rq->packetId = fragmentPacketId;
  112. rq->frags[fragmentNumber - 1] = fragment;
  113. rq->totalFragments = totalFragments; // total fragment count is known
  114. rq->haveFragments = 1 << fragmentNumber; // we have only this fragment
  115. rq->complete = false;
  116. } else if (!(rq->haveFragments & (1 << fragmentNumber))) {
  117. // We have other fragments and maybe the head, so add this one and check
  118. rq->frags[fragmentNumber - 1] = fragment;
  119. rq->totalFragments = totalFragments;
  120. if (Utils::countBits(rq->haveFragments |= (1 << fragmentNumber)) == totalFragments) {
  121. // We have all fragments -- assemble and process full Packet
  122. for(unsigned int f=1;f<totalFragments;++f)
  123. rq->frag0.append(rq->frags[f - 1].payload(),rq->frags[f - 1].payloadLength());
  124. if (rq->frag0.tryDecode(RR,tPtr)) {
  125. rq->timestamp = 0; // packet decoded, free entry
  126. } else {
  127. rq->complete = true; // set complete flag but leave entry since it probably needs WHOIS or something
  128. }
  129. }
  130. } // else this is a duplicate fragment, ignore
  131. }
  132. }
  133. // --------------------------------------------------------------------
  134. } else if (len >= ZT_PROTO_MIN_PACKET_LENGTH) { // min length check is important!
  135. // Handle packet head -------------------------------------------------
  136. const Address destination(reinterpret_cast<const uint8_t *>(data) + 8,ZT_ADDRESS_LENGTH);
  137. const Address source(reinterpret_cast<const uint8_t *>(data) + 13,ZT_ADDRESS_LENGTH);
  138. if (source == RR->identity.address())
  139. return;
  140. if (destination != RR->identity.address()) {
  141. if ( (!RR->topology->amUpstream()) && (!path->trustEstablished(now)) && (source != RR->identity.address()) )
  142. return;
  143. Packet packet(data,len);
  144. if (packet.hops() < ZT_RELAY_MAX_HOPS) {
  145. packet.incrementHops();
  146. SharedPtr<Peer> relayTo = RR->topology->getPeer(tPtr,destination);
  147. if ((relayTo)&&(relayTo->sendDirect(tPtr,packet.data(),packet.size(),now,false))) {
  148. if ((source != RR->identity.address())&&(_shouldUnite(now,source,destination))) {
  149. const SharedPtr<Peer> sourcePeer(RR->topology->getPeer(tPtr,source));
  150. if (sourcePeer)
  151. relayTo->introduce(tPtr,now,sourcePeer);
  152. }
  153. } else {
  154. relayTo = RR->topology->getUpstreamPeer();
  155. if ((relayTo)&&(relayTo->address() != source)) {
  156. if (relayTo->sendDirect(tPtr,packet.data(),packet.size(),now,true)) {
  157. const SharedPtr<Peer> sourcePeer(RR->topology->getPeer(tPtr,source));
  158. if (sourcePeer)
  159. relayTo->introduce(tPtr,now,sourcePeer);
  160. }
  161. }
  162. }
  163. }
  164. } else if ((reinterpret_cast<const uint8_t *>(data)[ZT_PACKET_IDX_FLAGS] & ZT_PROTO_FLAG_FRAGMENTED) != 0) {
  165. // Packet is the head of a fragmented packet series
  166. const uint64_t packetId = (
  167. (((uint64_t)reinterpret_cast<const uint8_t *>(data)[0]) << 56) |
  168. (((uint64_t)reinterpret_cast<const uint8_t *>(data)[1]) << 48) |
  169. (((uint64_t)reinterpret_cast<const uint8_t *>(data)[2]) << 40) |
  170. (((uint64_t)reinterpret_cast<const uint8_t *>(data)[3]) << 32) |
  171. (((uint64_t)reinterpret_cast<const uint8_t *>(data)[4]) << 24) |
  172. (((uint64_t)reinterpret_cast<const uint8_t *>(data)[5]) << 16) |
  173. (((uint64_t)reinterpret_cast<const uint8_t *>(data)[6]) << 8) |
  174. ((uint64_t)reinterpret_cast<const uint8_t *>(data)[7])
  175. );
  176. RXQueueEntry *const rq = _findRXQueueEntry(packetId);
  177. Mutex::Lock rql(rq->lock);
  178. if (rq->packetId != packetId) {
  179. // If we have no other fragments yet, create an entry and save the head
  180. rq->timestamp = now;
  181. rq->packetId = packetId;
  182. rq->frag0.init(data,len,path,now);
  183. rq->totalFragments = 0;
  184. rq->haveFragments = 1;
  185. rq->complete = false;
  186. } else if (!(rq->haveFragments & 1)) {
  187. // If we have other fragments but no head, see if we are complete with the head
  188. if ((rq->totalFragments > 1)&&(Utils::countBits(rq->haveFragments |= 1) == rq->totalFragments)) {
  189. // We have all fragments -- assemble and process full Packet
  190. rq->frag0.init(data,len,path,now);
  191. for(unsigned int f=1;f<rq->totalFragments;++f)
  192. rq->frag0.append(rq->frags[f - 1].payload(),rq->frags[f - 1].payloadLength());
  193. if (rq->frag0.tryDecode(RR,tPtr)) {
  194. rq->timestamp = 0; // packet decoded, free entry
  195. } else {
  196. rq->complete = true; // set complete flag but leave entry since it probably needs WHOIS or something
  197. }
  198. } else {
  199. // Still waiting on more fragments, but keep the head
  200. rq->frag0.init(data,len,path,now);
  201. }
  202. } // else this is a duplicate head, ignore
  203. } else {
  204. // Packet is unfragmented, so just process it
  205. IncomingPacket packet(data,len,path,now);
  206. if (!packet.tryDecode(RR,tPtr)) {
  207. RXQueueEntry *const rq = _nextRXQueueEntry();
  208. Mutex::Lock rql(rq->lock);
  209. rq->timestamp = now;
  210. rq->packetId = packet.packetId();
  211. rq->frag0 = packet;
  212. rq->totalFragments = 1;
  213. rq->haveFragments = 1;
  214. rq->complete = true;
  215. }
  216. }
  217. // --------------------------------------------------------------------
  218. }
  219. }
  220. } catch ( ... ) {} // sanity check, should be caught elsewhere
  221. }
  222. void Switch::onLocalEthernet(void *tPtr,const SharedPtr<Network> &network,const MAC &from,const MAC &to,unsigned int etherType,unsigned int vlanId,const void *data,unsigned int len)
  223. {
  224. if (!network->hasConfig())
  225. return;
  226. // Check if this packet is from someone other than the tap -- i.e. bridged in
  227. bool fromBridged;
  228. if ((fromBridged = (from != network->mac()))) {
  229. if (!network->config().permitsBridging(RR->identity.address())) {
  230. RR->t->outgoingNetworkFrameDropped(tPtr,network,from,to,etherType,vlanId,len,"not a bridge");
  231. return;
  232. }
  233. }
  234. if (to.isMulticast()) {
  235. MulticastGroup multicastGroup(to,0);
  236. if (to.isBroadcast()) {
  237. if ( (etherType == ZT_ETHERTYPE_ARP) && (len >= 28) && ((((const uint8_t *)data)[2] == 0x08)&&(((const uint8_t *)data)[3] == 0x00)&&(((const uint8_t *)data)[4] == 6)&&(((const uint8_t *)data)[5] == 4)&&(((const uint8_t *)data)[7] == 0x01)) ) {
  238. /* IPv4 ARP is one of the few special cases that we impose upon what is
  239. * otherwise a straightforward Ethernet switch emulation. Vanilla ARP
  240. * is dumb old broadcast and simply doesn't scale. ZeroTier multicast
  241. * groups have an additional field called ADI (additional distinguishing
  242. * information) which was added specifically for ARP though it could
  243. * be used for other things too. We then take ARP broadcasts and turn
  244. * them into multicasts by stuffing the IP address being queried into
  245. * the 32-bit ADI field. In practice this uses our multicast pub/sub
  246. * system to implement a kind of extended/distributed ARP table. */
  247. multicastGroup = MulticastGroup::deriveMulticastGroupForAddressResolution(InetAddress(((const unsigned char *)data) + 24,4,0));
  248. } else if (!network->config().enableBroadcast()) {
  249. // Don't transmit broadcasts if this network doesn't want them
  250. RR->t->outgoingNetworkFrameDropped(tPtr,network,from,to,etherType,vlanId,len,"broadcast disabled");
  251. return;
  252. }
  253. } else if ((etherType == ZT_ETHERTYPE_IPV6)&&(len >= (40 + 8 + 16))) {
  254. // IPv6 NDP emulation for certain very special patterns of private IPv6 addresses -- if enabled
  255. if ((network->config().ndpEmulation())&&(reinterpret_cast<const uint8_t *>(data)[6] == 0x3a)&&(reinterpret_cast<const uint8_t *>(data)[40] == 0x87)) { // ICMPv6 neighbor solicitation
  256. Address v6EmbeddedAddress;
  257. const uint8_t *const pkt6 = reinterpret_cast<const uint8_t *>(data) + 40 + 8;
  258. const uint8_t *my6 = (const uint8_t *)0;
  259. // ZT-RFC4193 address: fdNN:NNNN:NNNN:NNNN:NN99:93DD:DDDD:DDDD / 88 (one /128 per actual host)
  260. // ZT-6PLANE address: fcXX:XXXX:XXDD:DDDD:DDDD:####:####:#### / 40 (one /80 per actual host)
  261. // (XX - lower 32 bits of network ID XORed with higher 32 bits)
  262. // For these to work, we must have a ZT-managed address assigned in one of the
  263. // above formats, and the query must match its prefix.
  264. for(unsigned int sipk=0;sipk<network->config().staticIpCount;++sipk) {
  265. const InetAddress *const sip = &(network->config().staticIps[sipk]);
  266. if (sip->ss_family == AF_INET6) {
  267. my6 = reinterpret_cast<const uint8_t *>(reinterpret_cast<const struct sockaddr_in6 *>(&(*sip))->sin6_addr.s6_addr);
  268. const unsigned int sipNetmaskBits = Utils::ntoh((uint16_t)reinterpret_cast<const struct sockaddr_in6 *>(&(*sip))->sin6_port);
  269. if ((sipNetmaskBits == 88)&&(my6[0] == 0xfd)&&(my6[9] == 0x99)&&(my6[10] == 0x93)) { // ZT-RFC4193 /88 ???
  270. unsigned int ptr = 0;
  271. while (ptr != 11) {
  272. if (pkt6[ptr] != my6[ptr])
  273. break;
  274. ++ptr;
  275. }
  276. if (ptr == 11) { // prefix match!
  277. v6EmbeddedAddress.setTo(pkt6 + ptr,5);
  278. break;
  279. }
  280. } else if (sipNetmaskBits == 40) { // ZT-6PLANE /40 ???
  281. const uint32_t nwid32 = (uint32_t)((network->id() ^ (network->id() >> 32)) & 0xffffffff);
  282. if ( (my6[0] == 0xfc) && (my6[1] == (uint8_t)((nwid32 >> 24) & 0xff)) && (my6[2] == (uint8_t)((nwid32 >> 16) & 0xff)) && (my6[3] == (uint8_t)((nwid32 >> 8) & 0xff)) && (my6[4] == (uint8_t)(nwid32 & 0xff))) {
  283. unsigned int ptr = 0;
  284. while (ptr != 5) {
  285. if (pkt6[ptr] != my6[ptr])
  286. break;
  287. ++ptr;
  288. }
  289. if (ptr == 5) { // prefix match!
  290. v6EmbeddedAddress.setTo(pkt6 + ptr,5);
  291. break;
  292. }
  293. }
  294. }
  295. }
  296. }
  297. if ((v6EmbeddedAddress)&&(v6EmbeddedAddress != RR->identity.address())) {
  298. const MAC peerMac(v6EmbeddedAddress,network->id());
  299. uint8_t adv[72];
  300. adv[0] = 0x60; adv[1] = 0x00; adv[2] = 0x00; adv[3] = 0x00;
  301. adv[4] = 0x00; adv[5] = 0x20;
  302. adv[6] = 0x3a; adv[7] = 0xff;
  303. for(int i=0;i<16;++i) adv[8 + i] = pkt6[i];
  304. for(int i=0;i<16;++i) adv[24 + i] = my6[i];
  305. adv[40] = 0x88; adv[41] = 0x00;
  306. adv[42] = 0x00; adv[43] = 0x00; // future home of checksum
  307. adv[44] = 0x60; adv[45] = 0x00; adv[46] = 0x00; adv[47] = 0x00;
  308. for(int i=0;i<16;++i) adv[48 + i] = pkt6[i];
  309. adv[64] = 0x02; adv[65] = 0x01;
  310. adv[66] = peerMac[0]; adv[67] = peerMac[1]; adv[68] = peerMac[2]; adv[69] = peerMac[3]; adv[70] = peerMac[4]; adv[71] = peerMac[5];
  311. uint16_t pseudo_[36];
  312. uint8_t *const pseudo = reinterpret_cast<uint8_t *>(pseudo_);
  313. for(int i=0;i<32;++i) pseudo[i] = adv[8 + i];
  314. pseudo[32] = 0x00; pseudo[33] = 0x00; pseudo[34] = 0x00; pseudo[35] = 0x20;
  315. pseudo[36] = 0x00; pseudo[37] = 0x00; pseudo[38] = 0x00; pseudo[39] = 0x3a;
  316. for(int i=0;i<32;++i) pseudo[40 + i] = adv[40 + i];
  317. uint32_t checksum = 0;
  318. for(int i=0;i<36;++i) checksum += Utils::hton(pseudo_[i]);
  319. while ((checksum >> 16)) checksum = (checksum & 0xffff) + (checksum >> 16);
  320. checksum = ~checksum;
  321. adv[42] = (checksum >> 8) & 0xff;
  322. adv[43] = checksum & 0xff;
  323. RR->node->putFrame(tPtr,network->id(),network->userPtr(),peerMac,from,ZT_ETHERTYPE_IPV6,0,adv,72);
  324. return; // NDP emulation done. We have forged a "fake" reply, so no need to send actual NDP query.
  325. } // else no NDP emulation
  326. } // else no NDP emulation
  327. }
  328. // Check this after NDP emulation, since that has to be allowed in exactly this case
  329. if (network->config().multicastLimit == 0) {
  330. RR->t->outgoingNetworkFrameDropped(tPtr,network,from,to,etherType,vlanId,len,"multicast disabled");
  331. return;
  332. }
  333. /* Learn multicast groups for bridged-in hosts.
  334. * Note that some OSes, most notably Linux, do this for you by learning
  335. * multicast addresses on bridge interfaces and subscribing each slave.
  336. * But in that case this does no harm, as the sets are just merged. */
  337. if (fromBridged)
  338. network->learnBridgedMulticastGroup(tPtr,multicastGroup,RR->node->now());
  339. // First pass sets noTee to false, but noTee is set to true in OutboundMulticast to prevent duplicates.
  340. if (!network->filterOutgoingPacket(tPtr,false,RR->identity.address(),Address(),from,to,(const uint8_t *)data,len,etherType,vlanId)) {
  341. RR->t->outgoingNetworkFrameDropped(tPtr,network,from,to,etherType,vlanId,len,"filter blocked");
  342. return;
  343. }
  344. RR->mc->send(
  345. tPtr,
  346. RR->node->now(),
  347. network,
  348. Address(),
  349. multicastGroup,
  350. (fromBridged) ? from : MAC(),
  351. etherType,
  352. data,
  353. len);
  354. } else if (to == network->mac()) {
  355. // Destination is this node, so just reinject it
  356. RR->node->putFrame(tPtr,network->id(),network->userPtr(),from,to,etherType,vlanId,data,len);
  357. } else if (to[0] == MAC::firstOctetForNetwork(network->id())) {
  358. // Destination is another ZeroTier peer on the same network
  359. Address toZT(to.toAddress(network->id())); // since in-network MACs are derived from addresses and network IDs, we can reverse this
  360. SharedPtr<Peer> toPeer(RR->topology->getPeer(tPtr,toZT));
  361. if (!network->filterOutgoingPacket(tPtr,false,RR->identity.address(),toZT,from,to,(const uint8_t *)data,len,etherType,vlanId)) {
  362. RR->t->outgoingNetworkFrameDropped(tPtr,network,from,to,etherType,vlanId,len,"filter blocked");
  363. return;
  364. }
  365. if (fromBridged) {
  366. Packet outp(toZT,RR->identity.address(),Packet::VERB_EXT_FRAME);
  367. outp.append(network->id());
  368. outp.append((unsigned char)0x00);
  369. to.appendTo(outp);
  370. from.appendTo(outp);
  371. outp.append((uint16_t)etherType);
  372. outp.append(data,len);
  373. if (!network->config().disableCompression())
  374. outp.compress();
  375. send(tPtr,outp,true);
  376. } else {
  377. Packet outp(toZT,RR->identity.address(),Packet::VERB_FRAME);
  378. outp.append(network->id());
  379. outp.append((uint16_t)etherType);
  380. outp.append(data,len);
  381. if (!network->config().disableCompression())
  382. outp.compress();
  383. send(tPtr,outp,true);
  384. }
  385. } else {
  386. // Destination is bridged behind a remote peer
  387. // We filter with a NULL destination ZeroTier address first. Filtrations
  388. // for each ZT destination are also done below. This is the same rationale
  389. // and design as for multicast.
  390. if (!network->filterOutgoingPacket(tPtr,false,RR->identity.address(),Address(),from,to,(const uint8_t *)data,len,etherType,vlanId)) {
  391. RR->t->outgoingNetworkFrameDropped(tPtr,network,from,to,etherType,vlanId,len,"filter blocked");
  392. return;
  393. }
  394. Address bridges[ZT_MAX_BRIDGE_SPAM];
  395. unsigned int numBridges = 0;
  396. /* Create an array of up to ZT_MAX_BRIDGE_SPAM recipients for this bridged frame. */
  397. bridges[0] = network->findBridgeTo(to);
  398. std::vector<Address> activeBridges(network->config().activeBridges());
  399. if ((bridges[0])&&(bridges[0] != RR->identity.address())&&(network->config().permitsBridging(bridges[0]))) {
  400. /* We have a known bridge route for this MAC, send it there. */
  401. ++numBridges;
  402. } else if (!activeBridges.empty()) {
  403. /* If there is no known route, spam to up to ZT_MAX_BRIDGE_SPAM active
  404. * bridges. If someone responds, we'll learn the route. */
  405. std::vector<Address>::const_iterator ab(activeBridges.begin());
  406. if (activeBridges.size() <= ZT_MAX_BRIDGE_SPAM) {
  407. // If there are <= ZT_MAX_BRIDGE_SPAM active bridges, spam them all
  408. while (ab != activeBridges.end()) {
  409. bridges[numBridges++] = *ab;
  410. ++ab;
  411. }
  412. } else {
  413. // Otherwise pick a random set of them
  414. while (numBridges < ZT_MAX_BRIDGE_SPAM) {
  415. if (ab == activeBridges.end())
  416. ab = activeBridges.begin();
  417. if (((unsigned long)RR->node->prng() % (unsigned long)activeBridges.size()) == 0) {
  418. bridges[numBridges++] = *ab;
  419. ++ab;
  420. } else ++ab;
  421. }
  422. }
  423. }
  424. for(unsigned int b=0;b<numBridges;++b) {
  425. if (network->filterOutgoingPacket(tPtr,true,RR->identity.address(),bridges[b],from,to,(const uint8_t *)data,len,etherType,vlanId)) {
  426. Packet outp(bridges[b],RR->identity.address(),Packet::VERB_EXT_FRAME);
  427. outp.append(network->id());
  428. outp.append((uint8_t)0x00);
  429. to.appendTo(outp);
  430. from.appendTo(outp);
  431. outp.append((uint16_t)etherType);
  432. outp.append(data,len);
  433. if (!network->config().disableCompression())
  434. outp.compress();
  435. send(tPtr,outp,true);
  436. } else {
  437. RR->t->outgoingNetworkFrameDropped(tPtr,network,from,to,etherType,vlanId,len,"filter blocked (bridge replication)");
  438. }
  439. }
  440. }
  441. }
  442. void Switch::send(void *tPtr,Packet &packet,bool encrypt)
  443. {
  444. const Address dest(packet.destination());
  445. if (dest == RR->identity.address())
  446. return;
  447. if (!_trySend(tPtr,packet,encrypt)) {
  448. {
  449. Mutex::Lock _l(_txQueue_m);
  450. if (_txQueue.size() >= ZT_TX_QUEUE_SIZE) {
  451. _txQueue.pop_front();
  452. }
  453. _txQueue.push_back(TXQueueEntry(dest,RR->node->now(),packet,encrypt));
  454. }
  455. if (!RR->topology->getPeer(tPtr,dest))
  456. requestWhois(tPtr,RR->node->now(),dest);
  457. }
  458. }
  459. void Switch::requestWhois(void *tPtr,const int64_t now,const Address &addr)
  460. {
  461. if (addr == RR->identity.address())
  462. return;
  463. {
  464. Mutex::Lock _l(_lastSentWhoisRequest_m);
  465. int64_t &last = _lastSentWhoisRequest[addr];
  466. if ((now - last) < ZT_WHOIS_RETRY_DELAY)
  467. return;
  468. else last = now;
  469. }
  470. const SharedPtr<Peer> upstream(RR->topology->getUpstreamPeer());
  471. if (upstream) {
  472. Packet outp(upstream->address(),RR->identity.address(),Packet::VERB_WHOIS);
  473. addr.appendTo(outp);
  474. RR->node->expectReplyTo(outp.packetId());
  475. send(tPtr,outp,true);
  476. }
  477. }
  478. void Switch::doAnythingWaitingForPeer(void *tPtr,const SharedPtr<Peer> &peer)
  479. {
  480. {
  481. Mutex::Lock _l(_lastSentWhoisRequest_m);
  482. _lastSentWhoisRequest.erase(peer->address());
  483. }
  484. const int64_t now = RR->node->now();
  485. for(unsigned int ptr=0;ptr<ZT_RX_QUEUE_SIZE;++ptr) {
  486. RXQueueEntry *const rq = &(_rxQueue[ptr]);
  487. Mutex::Lock rql(rq->lock);
  488. if ((rq->timestamp)&&(rq->complete)) {
  489. if ((rq->frag0.tryDecode(RR,tPtr))||((now - rq->timestamp) > ZT_RECEIVE_QUEUE_TIMEOUT))
  490. rq->timestamp = 0;
  491. }
  492. }
  493. {
  494. Mutex::Lock _l(_txQueue_m);
  495. for(std::list< TXQueueEntry >::iterator txi(_txQueue.begin());txi!=_txQueue.end();) {
  496. if (txi->dest == peer->address()) {
  497. if (_trySend(tPtr,txi->packet,txi->encrypt)) {
  498. _txQueue.erase(txi++);
  499. } else {
  500. ++txi;
  501. }
  502. } else {
  503. ++txi;
  504. }
  505. }
  506. }
  507. }
  508. unsigned long Switch::doTimerTasks(void *tPtr,int64_t now)
  509. {
  510. const uint64_t timeSinceLastCheck = now - _lastCheckedQueues;
  511. if (timeSinceLastCheck < ZT_WHOIS_RETRY_DELAY)
  512. return (unsigned long)(ZT_WHOIS_RETRY_DELAY - timeSinceLastCheck);
  513. _lastCheckedQueues = now;
  514. std::vector<Address> needWhois;
  515. {
  516. Mutex::Lock _l(_txQueue_m);
  517. for(std::list< TXQueueEntry >::iterator txi(_txQueue.begin());txi!=_txQueue.end();) {
  518. if (_trySend(tPtr,txi->packet,txi->encrypt)) {
  519. _txQueue.erase(txi++);
  520. } else if ((now - txi->creationTime) > ZT_TRANSMIT_QUEUE_TIMEOUT) {
  521. _txQueue.erase(txi++);
  522. } else {
  523. if (!RR->topology->getPeer(tPtr,txi->dest))
  524. needWhois.push_back(txi->dest);
  525. ++txi;
  526. }
  527. }
  528. }
  529. for(std::vector<Address>::const_iterator i(needWhois.begin());i!=needWhois.end();++i)
  530. requestWhois(tPtr,now,*i);
  531. for(unsigned int ptr=0;ptr<ZT_RX_QUEUE_SIZE;++ptr) {
  532. RXQueueEntry *const rq = &(_rxQueue[ptr]);
  533. Mutex::Lock rql(rq->lock);
  534. if ((rq->timestamp)&&(rq->complete)) {
  535. if ((rq->frag0.tryDecode(RR,tPtr))||((now - rq->timestamp) > ZT_RECEIVE_QUEUE_TIMEOUT)) {
  536. rq->timestamp = 0;
  537. } else {
  538. const Address src(rq->frag0.source());
  539. if (!RR->topology->getPeer(tPtr,src))
  540. requestWhois(tPtr,now,src);
  541. }
  542. }
  543. }
  544. {
  545. Mutex::Lock _l(_lastUniteAttempt_m);
  546. Hashtable< _LastUniteKey,uint64_t >::Iterator i(_lastUniteAttempt);
  547. _LastUniteKey *k = (_LastUniteKey *)0;
  548. uint64_t *v = (uint64_t *)0;
  549. while (i.next(k,v)) {
  550. if ((now - *v) >= (ZT_MIN_UNITE_INTERVAL * 8))
  551. _lastUniteAttempt.erase(*k);
  552. }
  553. }
  554. {
  555. Mutex::Lock _l(_lastSentWhoisRequest_m);
  556. Hashtable< Address,int64_t >::Iterator i(_lastSentWhoisRequest);
  557. Address *a = (Address *)0;
  558. int64_t *ts = (int64_t *)0;
  559. while (i.next(a,ts)) {
  560. if ((now - *ts) > (ZT_WHOIS_RETRY_DELAY * 2))
  561. _lastSentWhoisRequest.erase(*a);
  562. }
  563. }
  564. return ZT_WHOIS_RETRY_DELAY;
  565. }
  566. bool Switch::_shouldUnite(const int64_t now,const Address &source,const Address &destination)
  567. {
  568. Mutex::Lock _l(_lastUniteAttempt_m);
  569. uint64_t &ts = _lastUniteAttempt[_LastUniteKey(source,destination)];
  570. if ((now - ts) >= ZT_MIN_UNITE_INTERVAL) {
  571. ts = now;
  572. return true;
  573. }
  574. return false;
  575. }
  576. bool Switch::_trySend(void *tPtr,Packet &packet,bool encrypt)
  577. {
  578. SharedPtr<Path> viaPath;
  579. const int64_t now = RR->node->now();
  580. const Address destination(packet.destination());
  581. const SharedPtr<Peer> peer(RR->topology->getPeer(tPtr,destination));
  582. if (peer) {
  583. viaPath = peer->getBestPath(now,false);
  584. if (!viaPath) {
  585. peer->tryMemorizedPath(tPtr,now); // periodically attempt memorized or statically defined paths, if any are known
  586. const SharedPtr<Peer> relay(RR->topology->getUpstreamPeer());
  587. if ( (!relay) || (!(viaPath = relay->getBestPath(now,false))) ) {
  588. if (!(viaPath = peer->getBestPath(now,true)))
  589. return false;
  590. }
  591. }
  592. } else {
  593. return false;
  594. }
  595. unsigned int mtu = ZT_DEFAULT_PHYSMTU;
  596. uint64_t trustedPathId = 0;
  597. RR->topology->getOutboundPathInfo(viaPath->address(),mtu,trustedPathId);
  598. unsigned int chunkSize = std::min(packet.size(),mtu);
  599. packet.setFragmented(chunkSize < packet.size());
  600. if (trustedPathId) {
  601. packet.setTrusted(trustedPathId);
  602. } else {
  603. packet.armor(peer->key(),encrypt);
  604. }
  605. if (viaPath->send(RR,tPtr,packet.data(),chunkSize,now)) {
  606. if (chunkSize < packet.size()) {
  607. // Too big for one packet, fragment the rest
  608. unsigned int fragStart = chunkSize;
  609. unsigned int remaining = packet.size() - chunkSize;
  610. unsigned int fragsRemaining = (remaining / (mtu - ZT_PROTO_MIN_FRAGMENT_LENGTH));
  611. if ((fragsRemaining * (mtu - ZT_PROTO_MIN_FRAGMENT_LENGTH)) < remaining)
  612. ++fragsRemaining;
  613. const unsigned int totalFragments = fragsRemaining + 1;
  614. for(unsigned int fno=1;fno<totalFragments;++fno) {
  615. chunkSize = std::min(remaining,(unsigned int)(mtu - ZT_PROTO_MIN_FRAGMENT_LENGTH));
  616. Packet::Fragment frag(packet,fragStart,chunkSize,fno,totalFragments);
  617. viaPath->send(RR,tPtr,frag.data(),frag.size(),now);
  618. fragStart += chunkSize;
  619. remaining -= chunkSize;
  620. }
  621. }
  622. }
  623. return true;
  624. }
  625. } // namespace ZeroTier