Switch.cpp 23 KB

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