Switch.cpp 24 KB

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