Switch.cpp 43 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256
  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: 2026-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 "Switch.hpp"
  14. #include "../include/ZeroTierOne.h"
  15. #include "../version.h"
  16. #include "Constants.hpp"
  17. #include "InetAddress.hpp"
  18. #include "Metrics.hpp"
  19. #include "Node.hpp"
  20. #include "Packet.hpp"
  21. #include "Peer.hpp"
  22. #include "RuntimeEnvironment.hpp"
  23. #include "SelfAwareness.hpp"
  24. #include "Topology.hpp"
  25. #include "Trace.hpp"
  26. #include <algorithm>
  27. #include <stdexcept>
  28. #include <stdio.h>
  29. #include <stdlib.h>
  30. #include <utility>
  31. namespace ZeroTier {
  32. Switch::Switch(const RuntimeEnvironment* renv) : RR(renv), _lastBeaconResponse(0), _lastCheckedQueues(0), _lastUniteAttempt(8) // only really used on root servers and upstreams, and it'll grow there just fine
  33. {
  34. }
  35. // Returns true if packet appears valid; pos and proto will be set
  36. static bool _ipv6GetPayload(const uint8_t* frameData, unsigned int frameLen, unsigned int& pos, unsigned int& proto)
  37. {
  38. if (frameLen < 40) {
  39. return false;
  40. }
  41. pos = 40;
  42. proto = frameData[6];
  43. while (pos <= frameLen) {
  44. switch (proto) {
  45. case 0: // hop-by-hop options
  46. case 43: // routing
  47. case 60: // destination options
  48. case 135: // mobility options
  49. if ((pos + 8) > frameLen) {
  50. return false; // invalid!
  51. }
  52. proto = frameData[pos];
  53. pos += ((unsigned int)frameData[pos + 1] * 8) + 8;
  54. break;
  55. // case 44: // fragment -- we currently can't parse these and they are deprecated in IPv6 anyway
  56. // case 50:
  57. // case 51: // IPSec ESP and AH -- we have to stop here since this is encrypted stuff
  58. default:
  59. return true;
  60. }
  61. }
  62. return false; // overflow == invalid
  63. }
  64. void Switch::onRemotePacket(void* tPtr, const int64_t localSocket, const InetAddress& fromAddr, const void* data, unsigned int len)
  65. {
  66. int32_t flowId = ZT_QOS_NO_FLOW;
  67. try {
  68. const int64_t now = RR->node->now();
  69. const SharedPtr<Path> path(RR->topology->getPath(localSocket, fromAddr));
  70. path->received(now);
  71. if (len == 13) {
  72. /* LEGACY: before VERB_PUSH_DIRECT_PATHS, peers used broadcast
  73. * announcements on the LAN to solve the 'same network problem.' We
  74. * no longer send these, but we'll listen for them for a while to
  75. * locate peers with versions <1.0.4. */
  76. const Address beaconAddr(reinterpret_cast<const char*>(data) + 8, 5);
  77. if (beaconAddr == RR->identity.address()) {
  78. return;
  79. }
  80. if (! RR->node->shouldUsePathForZeroTierTraffic(tPtr, beaconAddr, localSocket, fromAddr)) {
  81. return;
  82. }
  83. const SharedPtr<Peer> peer(RR->topology->getPeer(tPtr, beaconAddr));
  84. if (peer) { // we'll only respond to beacons from known peers
  85. if ((now - _lastBeaconResponse) >= 2500) { // limit rate of responses
  86. _lastBeaconResponse = now;
  87. Packet outp(peer->address(), RR->identity.address(), Packet::VERB_NOP);
  88. outp.armor(peer->key(), true, peer->aesKeysIfSupported());
  89. Metrics::pkt_nop_out++;
  90. path->send(RR, tPtr, outp.data(), outp.size(), now);
  91. }
  92. }
  93. }
  94. else if (len > ZT_PROTO_MIN_FRAGMENT_LENGTH) { // SECURITY: min length check is important since we do some C-style stuff below!
  95. if (reinterpret_cast<const uint8_t*>(data)[ZT_PACKET_FRAGMENT_IDX_FRAGMENT_INDICATOR] == ZT_PACKET_FRAGMENT_INDICATOR) {
  96. // Handle fragment ----------------------------------------------------
  97. Packet::Fragment fragment(data, len);
  98. const Address destination(fragment.destination());
  99. if (destination != RR->identity.address()) {
  100. if ((! RR->topology->amUpstream()) && (! path->trustEstablished(now))) {
  101. return;
  102. }
  103. if (fragment.hops() < ZT_RELAY_MAX_HOPS) {
  104. fragment.incrementHops();
  105. // Note: we don't bother initiating NAT-t for fragments, since heads will set that off.
  106. // It wouldn't hurt anything, just redundant and unnecessary.
  107. SharedPtr<Peer> relayTo = RR->topology->getPeer(tPtr, destination);
  108. if ((! relayTo) || (! relayTo->sendDirect(tPtr, fragment.data(), fragment.size(), now, false))) {
  109. // Don't know peer or no direct path -- so relay via someone upstream
  110. relayTo = RR->topology->getUpstreamPeer();
  111. if (relayTo) {
  112. relayTo->sendDirect(tPtr, fragment.data(), fragment.size(), now, true);
  113. }
  114. }
  115. }
  116. }
  117. else {
  118. // Fragment looks like ours
  119. const uint64_t fragmentPacketId = fragment.packetId();
  120. const unsigned int fragmentNumber = fragment.fragmentNumber();
  121. const unsigned int totalFragments = fragment.totalFragments();
  122. if ((totalFragments <= ZT_MAX_PACKET_FRAGMENTS) && (fragmentNumber < ZT_MAX_PACKET_FRAGMENTS) && (fragmentNumber > 0) && (totalFragments > 1)) {
  123. // Fragment appears basically sane. Its fragment number must be
  124. // 1 or more, since a Packet with fragmented bit set is fragment 0.
  125. // Total fragments must be more than 1, otherwise why are we
  126. // seeing a Packet::Fragment?
  127. RXQueueEntry* const rq = _findRXQueueEntry(fragmentPacketId);
  128. Mutex::Lock rql(rq->lock);
  129. if (rq->packetId != fragmentPacketId) {
  130. // No packet found, so we received a fragment without its head.
  131. rq->flowId = flowId;
  132. rq->timestamp = now;
  133. rq->packetId = fragmentPacketId;
  134. rq->frags[fragmentNumber - 1] = fragment;
  135. rq->totalFragments = totalFragments; // total fragment count is known
  136. rq->haveFragments = 1 << fragmentNumber; // we have only this fragment
  137. rq->complete = false;
  138. }
  139. else if (! (rq->haveFragments & (1 << fragmentNumber))) {
  140. // We have other fragments and maybe the head, so add this one and check
  141. rq->frags[fragmentNumber - 1] = fragment;
  142. rq->totalFragments = totalFragments;
  143. if (Utils::countBits(rq->haveFragments |= (1 << fragmentNumber)) == totalFragments) {
  144. // We have all fragments -- assemble and process full Packet
  145. for (unsigned int f = 1; f < totalFragments; ++f) {
  146. rq->frag0.append(rq->frags[f - 1].payload(), rq->frags[f - 1].payloadLength());
  147. }
  148. if (rq->frag0.tryDecode(RR, tPtr, flowId)) {
  149. rq->timestamp = 0; // packet decoded, free entry
  150. }
  151. else {
  152. rq->complete = true; // set complete flag but leave entry since it probably needs WHOIS or something
  153. }
  154. }
  155. } // else this is a duplicate fragment, ignore
  156. }
  157. }
  158. // --------------------------------------------------------------------
  159. }
  160. else if (len >= ZT_PROTO_MIN_PACKET_LENGTH) { // min length check is important!
  161. // Handle packet head -------------------------------------------------
  162. const Address destination(reinterpret_cast<const uint8_t*>(data) + 8, ZT_ADDRESS_LENGTH);
  163. const Address source(reinterpret_cast<const uint8_t*>(data) + 13, ZT_ADDRESS_LENGTH);
  164. if (source == RR->identity.address()) {
  165. return;
  166. }
  167. if (destination != RR->identity.address()) {
  168. if ((! RR->topology->amUpstream()) && (! path->trustEstablished(now)) && (source != RR->identity.address())) {
  169. return;
  170. }
  171. Packet packet(data, len);
  172. if (packet.hops() < ZT_RELAY_MAX_HOPS) {
  173. packet.incrementHops();
  174. SharedPtr<Peer> relayTo = RR->topology->getPeer(tPtr, destination);
  175. if ((relayTo) && (relayTo->sendDirect(tPtr, packet.data(), packet.size(), now, false))) {
  176. if ((source != RR->identity.address()) && (_shouldUnite(now, source, destination))) {
  177. const SharedPtr<Peer> sourcePeer(RR->topology->getPeer(tPtr, source));
  178. if (sourcePeer) {
  179. relayTo->introduce(tPtr, now, sourcePeer);
  180. }
  181. }
  182. }
  183. else {
  184. relayTo = RR->topology->getUpstreamPeer();
  185. if ((relayTo) && (relayTo->address() != source)) {
  186. if (relayTo->sendDirect(tPtr, packet.data(), packet.size(), now, true)) {
  187. const SharedPtr<Peer> sourcePeer(RR->topology->getPeer(tPtr, source));
  188. if (sourcePeer) {
  189. relayTo->introduce(tPtr, now, sourcePeer);
  190. }
  191. }
  192. }
  193. }
  194. }
  195. }
  196. else if ((reinterpret_cast<const uint8_t*>(data)[ZT_PACKET_IDX_FLAGS] & ZT_PROTO_FLAG_FRAGMENTED) != 0) {
  197. // Packet is the head of a fragmented packet series
  198. const uint64_t packetId =
  199. ((((uint64_t)reinterpret_cast<const uint8_t*>(data)[0]) << 56) | (((uint64_t)reinterpret_cast<const uint8_t*>(data)[1]) << 48) | (((uint64_t)reinterpret_cast<const uint8_t*>(data)[2]) << 40)
  200. | (((uint64_t)reinterpret_cast<const uint8_t*>(data)[3]) << 32) | (((uint64_t)reinterpret_cast<const uint8_t*>(data)[4]) << 24) | (((uint64_t)reinterpret_cast<const uint8_t*>(data)[5]) << 16)
  201. | (((uint64_t)reinterpret_cast<const uint8_t*>(data)[6]) << 8) | ((uint64_t)reinterpret_cast<const uint8_t*>(data)[7]));
  202. RXQueueEntry* const rq = _findRXQueueEntry(packetId);
  203. Mutex::Lock rql(rq->lock);
  204. if (rq->packetId != packetId) {
  205. // If we have no other fragments yet, create an entry and save the head
  206. rq->flowId = flowId;
  207. rq->timestamp = now;
  208. rq->packetId = packetId;
  209. rq->frag0.init(data, len, path, now);
  210. rq->totalFragments = 0;
  211. rq->haveFragments = 1;
  212. rq->complete = false;
  213. }
  214. else if (! (rq->haveFragments & 1)) {
  215. // If we have other fragments but no head, see if we are complete with the head
  216. if ((rq->totalFragments > 1) && (Utils::countBits(rq->haveFragments |= 1) == rq->totalFragments)) {
  217. // We have all fragments -- assemble and process full Packet
  218. rq->frag0.init(data, len, path, now);
  219. for (unsigned int f = 1; f < rq->totalFragments; ++f) {
  220. rq->frag0.append(rq->frags[f - 1].payload(), rq->frags[f - 1].payloadLength());
  221. }
  222. if (rq->frag0.tryDecode(RR, tPtr, flowId)) {
  223. rq->timestamp = 0; // packet decoded, free entry
  224. }
  225. else {
  226. rq->complete = true; // set complete flag but leave entry since it probably needs WHOIS or something
  227. }
  228. }
  229. else {
  230. // Still waiting on more fragments, but keep the head
  231. rq->frag0.init(data, len, path, now);
  232. }
  233. } // else this is a duplicate head, ignore
  234. }
  235. else {
  236. // Packet is unfragmented, so just process it
  237. IncomingPacket packet(data, len, path, now);
  238. if (! packet.tryDecode(RR, tPtr, flowId)) {
  239. RXQueueEntry* const rq = _nextRXQueueEntry();
  240. Mutex::Lock rql(rq->lock);
  241. rq->flowId = flowId;
  242. rq->timestamp = now;
  243. rq->packetId = packet.packetId();
  244. rq->frag0 = packet;
  245. rq->totalFragments = 1;
  246. rq->haveFragments = 1;
  247. rq->complete = true;
  248. }
  249. }
  250. // --------------------------------------------------------------------
  251. }
  252. }
  253. }
  254. catch (...) {
  255. } // sanity check, should be caught elsewhere
  256. }
  257. 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)
  258. {
  259. if (! network->hasConfig()) {
  260. return;
  261. }
  262. // Check if this packet is from someone other than the tap -- i.e. bridged in
  263. bool fromBridged;
  264. if ((fromBridged = (from != network->mac()))) {
  265. if (! network->config().permitsBridging(RR->identity.address())) {
  266. RR->t->outgoingNetworkFrameDropped(tPtr, network, from, to, etherType, vlanId, len, "not a bridge");
  267. return;
  268. }
  269. }
  270. uint8_t qosBucket = ZT_AQM_DEFAULT_BUCKET;
  271. /**
  272. * A pseudo-unique identifier used by balancing and bonding policies to
  273. * categorize individual flows/conversations for assignment to a specific
  274. * physical path. This identifier consists of the source port and
  275. * destination port of the encapsulated frame.
  276. *
  277. * A flowId of -1 will indicate that there is no preference for how this
  278. * packet shall be sent. An example of this would be an ICMP packet.
  279. */
  280. int32_t flowId = ZT_QOS_NO_FLOW;
  281. if (etherType == ZT_ETHERTYPE_IPV4 && (len >= 20)) {
  282. uint16_t srcPort = 0;
  283. uint16_t dstPort = 0;
  284. uint8_t proto = (reinterpret_cast<const uint8_t*>(data)[9]);
  285. const unsigned int headerLen = 4 * (reinterpret_cast<const uint8_t*>(data)[0] & 0xf);
  286. switch (proto) {
  287. case 0x01: // ICMP
  288. // flowId = 0x01;
  289. break;
  290. // All these start with 16-bit source and destination port in that order
  291. case 0x06: // TCP
  292. case 0x11: // UDP
  293. case 0x84: // SCTP
  294. case 0x88: // UDPLite
  295. if (len > (headerLen + 4)) {
  296. unsigned int pos = headerLen + 0;
  297. srcPort = (reinterpret_cast<const uint8_t*>(data)[pos++]) << 8;
  298. srcPort |= (reinterpret_cast<const uint8_t*>(data)[pos]);
  299. pos++;
  300. dstPort = (reinterpret_cast<const uint8_t*>(data)[pos++]) << 8;
  301. dstPort |= (reinterpret_cast<const uint8_t*>(data)[pos]);
  302. flowId = dstPort ^ srcPort ^ proto;
  303. }
  304. break;
  305. }
  306. }
  307. if (etherType == ZT_ETHERTYPE_IPV6 && (len >= 40)) {
  308. uint16_t srcPort = 0;
  309. uint16_t dstPort = 0;
  310. unsigned int pos;
  311. unsigned int proto;
  312. _ipv6GetPayload((const uint8_t*)data, len, pos, proto);
  313. switch (proto) {
  314. case 0x3A: // ICMPv6
  315. // flowId = 0x3A;
  316. break;
  317. // All these start with 16-bit source and destination port in that order
  318. case 0x06: // TCP
  319. case 0x11: // UDP
  320. case 0x84: // SCTP
  321. case 0x88: // UDPLite
  322. if (len > (pos + 4)) {
  323. srcPort = (reinterpret_cast<const uint8_t*>(data)[pos++]) << 8;
  324. srcPort |= (reinterpret_cast<const uint8_t*>(data)[pos]);
  325. pos++;
  326. dstPort = (reinterpret_cast<const uint8_t*>(data)[pos++]) << 8;
  327. dstPort |= (reinterpret_cast<const uint8_t*>(data)[pos]);
  328. flowId = dstPort ^ srcPort ^ proto;
  329. }
  330. break;
  331. default:
  332. break;
  333. }
  334. }
  335. if (to.isMulticast()) {
  336. MulticastGroup multicastGroup(to, 0);
  337. if (to.isBroadcast()) {
  338. if ((etherType == ZT_ETHERTYPE_ARP) && (len >= 28)
  339. && ((((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))) {
  340. /* IPv4 ARP is one of the few special cases that we impose upon what is
  341. * otherwise a straightforward Ethernet switch emulation. Vanilla ARP
  342. * is dumb old broadcast and simply doesn't scale. ZeroTier multicast
  343. * groups have an additional field called ADI (additional distinguishing
  344. * information) which was added specifically for ARP though it could
  345. * be used for other things too. We then take ARP broadcasts and turn
  346. * them into multicasts by stuffing the IP address being queried into
  347. * the 32-bit ADI field. In practice this uses our multicast pub/sub
  348. * system to implement a kind of extended/distributed ARP table. */
  349. multicastGroup = MulticastGroup::deriveMulticastGroupForAddressResolution(InetAddress(((const unsigned char*)data) + 24, 4, 0));
  350. }
  351. else if (! network->config().enableBroadcast()) {
  352. // Don't transmit broadcasts if this network doesn't want them
  353. RR->t->outgoingNetworkFrameDropped(tPtr, network, from, to, etherType, vlanId, len, "broadcast disabled");
  354. return;
  355. }
  356. }
  357. else if ((etherType == ZT_ETHERTYPE_IPV6) && (len >= (40 + 8 + 16))) {
  358. // IPv6 NDP emulation for certain very special patterns of private IPv6 addresses -- if enabled
  359. if ((network->config().ndpEmulation()) && (reinterpret_cast<const uint8_t*>(data)[6] == 0x3a) && (reinterpret_cast<const uint8_t*>(data)[40] == 0x87)) { // ICMPv6 neighbor solicitation
  360. Address v6EmbeddedAddress;
  361. const uint8_t* const pkt6 = reinterpret_cast<const uint8_t*>(data) + 40 + 8;
  362. const uint8_t* my6 = (const uint8_t*)0;
  363. // ZT-RFC4193 address: fdNN:NNNN:NNNN:NNNN:NN99:93DD:DDDD:DDDD / 88 (one /128 per actual host)
  364. // ZT-6PLANE address: fcXX:XXXX:XXDD:DDDD:DDDD:####:####:#### / 40 (one /80 per actual host)
  365. // (XX - lower 32 bits of network ID XORed with higher 32 bits)
  366. // For these to work, we must have a ZT-managed address assigned in one of the
  367. // above formats, and the query must match its prefix.
  368. for (unsigned int sipk = 0; sipk < network->config().staticIpCount; ++sipk) {
  369. const InetAddress* const sip = &(network->config().staticIps[sipk]);
  370. if (sip->ss_family == AF_INET6) {
  371. my6 = reinterpret_cast<const uint8_t*>(reinterpret_cast<const struct sockaddr_in6*>(&(*sip))->sin6_addr.s6_addr);
  372. const unsigned int sipNetmaskBits = Utils::ntoh((uint16_t)reinterpret_cast<const struct sockaddr_in6*>(&(*sip))->sin6_port);
  373. if ((sipNetmaskBits == 88) && (my6[0] == 0xfd) && (my6[9] == 0x99) && (my6[10] == 0x93)) { // ZT-RFC4193 /88 ???
  374. unsigned int ptr = 0;
  375. while (ptr != 11) {
  376. if (pkt6[ptr] != my6[ptr]) {
  377. break;
  378. }
  379. ++ptr;
  380. }
  381. if (ptr == 11) { // prefix match!
  382. v6EmbeddedAddress.setTo(pkt6 + ptr, 5);
  383. break;
  384. }
  385. }
  386. else if (sipNetmaskBits == 40) { // ZT-6PLANE /40 ???
  387. const uint32_t nwid32 = (uint32_t)((network->id() ^ (network->id() >> 32)) & 0xffffffff);
  388. 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))) {
  389. unsigned int ptr = 0;
  390. while (ptr != 5) {
  391. if (pkt6[ptr] != my6[ptr]) {
  392. break;
  393. }
  394. ++ptr;
  395. }
  396. if (ptr == 5) { // prefix match!
  397. v6EmbeddedAddress.setTo(pkt6 + ptr, 5);
  398. break;
  399. }
  400. }
  401. }
  402. }
  403. }
  404. if ((v6EmbeddedAddress) && (v6EmbeddedAddress != RR->identity.address())) {
  405. const MAC peerMac(v6EmbeddedAddress, network->id());
  406. uint8_t adv[72];
  407. adv[0] = 0x60;
  408. adv[1] = 0x00;
  409. adv[2] = 0x00;
  410. adv[3] = 0x00;
  411. adv[4] = 0x00;
  412. adv[5] = 0x20;
  413. adv[6] = 0x3a;
  414. adv[7] = 0xff;
  415. for (int i = 0; i < 16; ++i) {
  416. adv[8 + i] = pkt6[i];
  417. }
  418. for (int i = 0; i < 16; ++i) {
  419. adv[24 + i] = my6[i];
  420. }
  421. adv[40] = 0x88;
  422. adv[41] = 0x00;
  423. adv[42] = 0x00;
  424. adv[43] = 0x00; // future home of checksum
  425. adv[44] = 0x60;
  426. adv[45] = 0x00;
  427. adv[46] = 0x00;
  428. adv[47] = 0x00;
  429. for (int i = 0; i < 16; ++i) {
  430. adv[48 + i] = pkt6[i];
  431. }
  432. adv[64] = 0x02;
  433. adv[65] = 0x01;
  434. adv[66] = peerMac[0];
  435. adv[67] = peerMac[1];
  436. adv[68] = peerMac[2];
  437. adv[69] = peerMac[3];
  438. adv[70] = peerMac[4];
  439. adv[71] = peerMac[5];
  440. uint16_t pseudo_[36];
  441. uint8_t* const pseudo = reinterpret_cast<uint8_t*>(pseudo_);
  442. for (int i = 0; i < 32; ++i) {
  443. pseudo[i] = adv[8 + i];
  444. }
  445. pseudo[32] = 0x00;
  446. pseudo[33] = 0x00;
  447. pseudo[34] = 0x00;
  448. pseudo[35] = 0x20;
  449. pseudo[36] = 0x00;
  450. pseudo[37] = 0x00;
  451. pseudo[38] = 0x00;
  452. pseudo[39] = 0x3a;
  453. for (int i = 0; i < 32; ++i) {
  454. pseudo[40 + i] = adv[40 + i];
  455. }
  456. uint32_t checksum = 0;
  457. for (int i = 0; i < 36; ++i) {
  458. checksum += Utils::hton(pseudo_[i]);
  459. }
  460. while ((checksum >> 16)) {
  461. checksum = (checksum & 0xffff) + (checksum >> 16);
  462. }
  463. checksum = ~checksum;
  464. adv[42] = (checksum >> 8) & 0xff;
  465. adv[43] = checksum & 0xff;
  466. //
  467. // call on separate background thread
  468. // this prevents problems related to trying to do rx while inside of doing tx, such as acquiring same lock recursively
  469. //
  470. std::thread([=]() {
  471. RR->node->putFrame(tPtr, network->id(), network->userPtr(), peerMac, from, ZT_ETHERTYPE_IPV6, 0, adv, 72);
  472. }).detach();
  473. return; // NDP emulation done. We have forged a "fake" reply, so no need to send actual NDP query.
  474. } // else no NDP emulation
  475. } // else no NDP emulation
  476. }
  477. // Check this after NDP emulation, since that has to be allowed in exactly this case
  478. if (network->config().multicastLimit == 0) {
  479. RR->t->outgoingNetworkFrameDropped(tPtr, network, from, to, etherType, vlanId, len, "multicast disabled");
  480. return;
  481. }
  482. /* Learn multicast groups for bridged-in hosts.
  483. * Note that some OSes, most notably Linux, do this for you by learning
  484. * multicast addresses on bridge interfaces and subscribing each slave.
  485. * But in that case this does no harm, as the sets are just merged. */
  486. if (fromBridged) {
  487. network->learnBridgedMulticastGroup(tPtr, multicastGroup, RR->node->now());
  488. }
  489. // First pass sets noTee to false, but noTee is set to true in OutboundMulticast to prevent duplicates.
  490. if (! network->filterOutgoingPacket(tPtr, false, RR->identity.address(), Address(), from, to, (const uint8_t*)data, len, etherType, vlanId, qosBucket)) {
  491. RR->t->outgoingNetworkFrameDropped(tPtr, network, from, to, etherType, vlanId, len, "filter blocked");
  492. return;
  493. }
  494. RR->mc->send(tPtr, RR->node->now(), network, Address(), multicastGroup, (fromBridged) ? from : MAC(), etherType, data, len);
  495. }
  496. else if (to == network->mac()) {
  497. // Destination is this node, so just reinject it
  498. //
  499. // same pattern as putFrame call above
  500. //
  501. std::thread([=]() {
  502. RR->node->putFrame(tPtr, network->id(), network->userPtr(), from, to, etherType, vlanId, data, len);
  503. }).detach();
  504. }
  505. else if (to[0] == MAC::firstOctetForNetwork(network->id())) {
  506. // Destination is another ZeroTier peer on the same network
  507. Address toZT(to.toAddress(network->id())); // since in-network MACs are derived from addresses and network IDs, we can reverse this
  508. SharedPtr<Peer> toPeer(RR->topology->getPeer(tPtr, toZT));
  509. if (! network->filterOutgoingPacket(tPtr, false, RR->identity.address(), toZT, from, to, (const uint8_t*)data, len, etherType, vlanId, qosBucket)) {
  510. RR->t->outgoingNetworkFrameDropped(tPtr, network, from, to, etherType, vlanId, len, "filter blocked");
  511. return;
  512. }
  513. network->pushCredentialsIfNeeded(tPtr, toZT, RR->node->now());
  514. if (! fromBridged) {
  515. Packet outp(toZT, RR->identity.address(), Packet::VERB_FRAME);
  516. outp.append(network->id());
  517. outp.append((uint16_t)etherType);
  518. outp.append(data, len);
  519. // 1.4.8: disable compression for unicast as it almost never helps
  520. // if (!network->config().disableCompression())
  521. // outp.compress();
  522. aqm_enqueue(tPtr, network, outp, true, qosBucket, flowId);
  523. }
  524. else {
  525. Packet outp(toZT, RR->identity.address(), Packet::VERB_EXT_FRAME);
  526. outp.append(network->id());
  527. outp.append((unsigned char)0x00);
  528. to.appendTo(outp);
  529. from.appendTo(outp);
  530. outp.append((uint16_t)etherType);
  531. outp.append(data, len);
  532. // 1.4.8: disable compression for unicast as it almost never helps
  533. // if (!network->config().disableCompression())
  534. // outp.compress();
  535. aqm_enqueue(tPtr, network, outp, true, qosBucket, flowId);
  536. }
  537. }
  538. else {
  539. // Destination is bridged behind a remote peer
  540. // We filter with a NULL destination ZeroTier address first. Filtrations
  541. // for each ZT destination are also done below. This is the same rationale
  542. // and design as for multicast.
  543. if (! network->filterOutgoingPacket(tPtr, false, RR->identity.address(), Address(), from, to, (const uint8_t*)data, len, etherType, vlanId, qosBucket)) {
  544. RR->t->outgoingNetworkFrameDropped(tPtr, network, from, to, etherType, vlanId, len, "filter blocked");
  545. return;
  546. }
  547. Address bridges[ZT_MAX_BRIDGE_SPAM];
  548. unsigned int numBridges = 0;
  549. /* Create an array of up to ZT_MAX_BRIDGE_SPAM recipients for this bridged frame. */
  550. bridges[0] = network->findBridgeTo(to);
  551. std::vector<Address> activeBridges(network->config().activeBridges());
  552. if ((bridges[0]) && (bridges[0] != RR->identity.address()) && (network->config().permitsBridging(bridges[0]))) {
  553. /* We have a known bridge route for this MAC, send it there. */
  554. ++numBridges;
  555. }
  556. else if (! activeBridges.empty()) {
  557. /* If there is no known route, spam to up to ZT_MAX_BRIDGE_SPAM active
  558. * bridges. If someone responds, we'll learn the route. */
  559. std::vector<Address>::const_iterator ab(activeBridges.begin());
  560. if (activeBridges.size() <= ZT_MAX_BRIDGE_SPAM) {
  561. // If there are <= ZT_MAX_BRIDGE_SPAM active bridges, spam them all
  562. while (ab != activeBridges.end()) {
  563. bridges[numBridges++] = *ab;
  564. ++ab;
  565. }
  566. }
  567. else {
  568. // Otherwise pick a random set of them
  569. while (numBridges < ZT_MAX_BRIDGE_SPAM) {
  570. if (ab == activeBridges.end()) {
  571. ab = activeBridges.begin();
  572. }
  573. if (((unsigned long)RR->node->prng() % (unsigned long)activeBridges.size()) == 0) {
  574. bridges[numBridges++] = *ab;
  575. ++ab;
  576. }
  577. else {
  578. ++ab;
  579. }
  580. }
  581. }
  582. }
  583. for (unsigned int b = 0; b < numBridges; ++b) {
  584. if (network->filterOutgoingPacket(tPtr, true, RR->identity.address(), bridges[b], from, to, (const uint8_t*)data, len, etherType, vlanId, qosBucket)) {
  585. Packet outp(bridges[b], RR->identity.address(), Packet::VERB_EXT_FRAME);
  586. outp.append(network->id());
  587. outp.append((uint8_t)0x00);
  588. to.appendTo(outp);
  589. from.appendTo(outp);
  590. outp.append((uint16_t)etherType);
  591. outp.append(data, len);
  592. // 1.4.8: disable compression for unicast as it almost never helps
  593. // if (!network->config().disableCompression())
  594. // outp.compress();
  595. aqm_enqueue(tPtr, network, outp, true, qosBucket, flowId);
  596. }
  597. else {
  598. RR->t->outgoingNetworkFrameDropped(tPtr, network, from, to, etherType, vlanId, len, "filter blocked (bridge replication)");
  599. }
  600. }
  601. }
  602. }
  603. void Switch::aqm_enqueue(void* tPtr, const SharedPtr<Network>& network, Packet& packet, bool encrypt, int qosBucket, int32_t flowId)
  604. {
  605. if (! network->qosEnabled()) {
  606. send(tPtr, packet, encrypt, flowId);
  607. return;
  608. }
  609. NetworkQoSControlBlock* nqcb = _netQueueControlBlock[network->id()];
  610. if (! nqcb) {
  611. nqcb = new NetworkQoSControlBlock();
  612. _netQueueControlBlock[network->id()] = nqcb;
  613. // Initialize ZT_QOS_NUM_BUCKETS queues and place them in the INACTIVE list
  614. // These queues will be shuffled between the new/old/inactive lists by the enqueue/dequeue algorithm
  615. for (int i = 0; i < ZT_AQM_NUM_BUCKETS; i++) {
  616. nqcb->inactiveQueues.push_back(new ManagedQueue(i));
  617. }
  618. }
  619. // Don't apply QoS scheduling to ZT protocol traffic
  620. if (packet.verb() != Packet::VERB_FRAME && packet.verb() != Packet::VERB_EXT_FRAME) {
  621. send(tPtr, packet, encrypt, flowId);
  622. }
  623. _aqm_m.lock();
  624. // Enqueue packet and move queue to appropriate list
  625. const Address dest(packet.destination());
  626. TXQueueEntry* txEntry = new TXQueueEntry(dest, RR->node->now(), packet, encrypt, flowId);
  627. ManagedQueue* selectedQueue = nullptr;
  628. for (size_t i = 0; i < ZT_AQM_NUM_BUCKETS; i++) {
  629. if (i < nqcb->oldQueues.size()) { // search old queues first (I think this is best since old would imply most recent usage of the queue)
  630. if (nqcb->oldQueues[i]->id == qosBucket) {
  631. selectedQueue = nqcb->oldQueues[i];
  632. }
  633. }
  634. if (i < nqcb->newQueues.size()) { // search new queues (this would imply not often-used queues)
  635. if (nqcb->newQueues[i]->id == qosBucket) {
  636. selectedQueue = nqcb->newQueues[i];
  637. }
  638. }
  639. if (i < nqcb->inactiveQueues.size()) { // search inactive queues
  640. if (nqcb->inactiveQueues[i]->id == qosBucket) {
  641. selectedQueue = nqcb->inactiveQueues[i];
  642. // move queue to end of NEW queue list
  643. selectedQueue->byteCredit = ZT_AQM_QUANTUM;
  644. // DEBUG_INFO("moving q=%p from INACTIVE to NEW list", selectedQueue);
  645. nqcb->newQueues.push_back(selectedQueue);
  646. nqcb->inactiveQueues.erase(nqcb->inactiveQueues.begin() + i);
  647. }
  648. }
  649. }
  650. if (! selectedQueue) {
  651. _aqm_m.unlock();
  652. return;
  653. }
  654. selectedQueue->q.push_back(txEntry);
  655. selectedQueue->byteLength += txEntry->packet.payloadLength();
  656. nqcb->_currEnqueuedPackets++;
  657. // DEBUG_INFO("nq=%2lu, oq=%2lu, iq=%2lu, nqcb.size()=%3d, bucket=%2d, q=%p", nqcb->newQueues.size(), nqcb->oldQueues.size(), nqcb->inactiveQueues.size(), nqcb->_currEnqueuedPackets, qosBucket, selectedQueue);
  658. // Drop a packet if necessary
  659. ManagedQueue* selectedQueueToDropFrom = nullptr;
  660. if (nqcb->_currEnqueuedPackets > ZT_AQM_MAX_ENQUEUED_PACKETS) {
  661. // DEBUG_INFO("too many enqueued packets (%d), finding packet to drop", nqcb->_currEnqueuedPackets);
  662. int maxQueueLength = 0;
  663. for (size_t i = 0; i < ZT_AQM_NUM_BUCKETS; i++) {
  664. if (i < nqcb->oldQueues.size()) {
  665. if (nqcb->oldQueues[i]->byteLength > maxQueueLength) {
  666. maxQueueLength = nqcb->oldQueues[i]->byteLength;
  667. selectedQueueToDropFrom = nqcb->oldQueues[i];
  668. }
  669. }
  670. if (i < nqcb->newQueues.size()) {
  671. if (nqcb->newQueues[i]->byteLength > maxQueueLength) {
  672. maxQueueLength = nqcb->newQueues[i]->byteLength;
  673. selectedQueueToDropFrom = nqcb->newQueues[i];
  674. }
  675. }
  676. if (i < nqcb->inactiveQueues.size()) {
  677. if (nqcb->inactiveQueues[i]->byteLength > maxQueueLength) {
  678. maxQueueLength = nqcb->inactiveQueues[i]->byteLength;
  679. selectedQueueToDropFrom = nqcb->inactiveQueues[i];
  680. }
  681. }
  682. }
  683. if (selectedQueueToDropFrom) {
  684. // DEBUG_INFO("dropping packet from head of largest queue (%d payload bytes)", maxQueueLength);
  685. int sizeOfDroppedPacket = selectedQueueToDropFrom->q.front()->packet.payloadLength();
  686. delete selectedQueueToDropFrom->q.front();
  687. selectedQueueToDropFrom->q.pop_front();
  688. selectedQueueToDropFrom->byteLength -= sizeOfDroppedPacket;
  689. nqcb->_currEnqueuedPackets--;
  690. }
  691. }
  692. _aqm_m.unlock();
  693. aqm_dequeue(tPtr);
  694. }
  695. uint64_t Switch::control_law(uint64_t t, int count)
  696. {
  697. return (uint64_t)(t + ZT_AQM_INTERVAL / sqrt(count));
  698. }
  699. Switch::dqr Switch::dodequeue(ManagedQueue* q, uint64_t now)
  700. {
  701. dqr r;
  702. r.ok_to_drop = false;
  703. r.p = q->q.front();
  704. if (r.p == NULL) {
  705. q->first_above_time = 0;
  706. return r;
  707. }
  708. uint64_t sojourn_time = now - r.p->creationTime;
  709. if (sojourn_time < ZT_AQM_TARGET || q->byteLength <= ZT_DEFAULT_MTU) {
  710. // went below - stay below for at least interval
  711. q->first_above_time = 0;
  712. }
  713. else {
  714. if (q->first_above_time == 0) {
  715. // just went above from below. if still above at
  716. // first_above_time, will say it's ok to drop.
  717. q->first_above_time = now + ZT_AQM_INTERVAL;
  718. }
  719. else if (now >= q->first_above_time) {
  720. r.ok_to_drop = true;
  721. }
  722. }
  723. return r;
  724. }
  725. Switch::TXQueueEntry* Switch::CoDelDequeue(ManagedQueue* q, bool isNew, uint64_t now)
  726. {
  727. dqr r = dodequeue(q, now);
  728. if (q->dropping) {
  729. if (! r.ok_to_drop) {
  730. q->dropping = false;
  731. }
  732. while (now >= q->drop_next && q->dropping) {
  733. q->q.pop_front(); // drop
  734. r = dodequeue(q, now);
  735. if (! r.ok_to_drop) {
  736. // leave dropping state
  737. q->dropping = false;
  738. }
  739. else {
  740. ++(q->count);
  741. // schedule the next drop.
  742. q->drop_next = control_law(q->drop_next, q->count);
  743. }
  744. }
  745. }
  746. else if (r.ok_to_drop) {
  747. q->q.pop_front(); // drop
  748. r = dodequeue(q, now);
  749. q->dropping = true;
  750. q->count = (q->count > 2 && now - q->drop_next < 8 * ZT_AQM_INTERVAL) ? q->count - 2 : 1;
  751. q->drop_next = control_law(now, q->count);
  752. }
  753. return r.p;
  754. }
  755. void Switch::aqm_dequeue(void* tPtr)
  756. {
  757. // Cycle through network-specific QoS control blocks
  758. for (std::map<uint64_t, NetworkQoSControlBlock*>::iterator nqcb(_netQueueControlBlock.begin()); nqcb != _netQueueControlBlock.end();) {
  759. if (! (*nqcb).second->_currEnqueuedPackets) {
  760. return;
  761. }
  762. uint64_t now = RR->node->now();
  763. TXQueueEntry* entryToEmit = nullptr;
  764. std::vector<ManagedQueue*>* currQueues = &((*nqcb).second->newQueues);
  765. std::vector<ManagedQueue*>* oldQueues = &((*nqcb).second->oldQueues);
  766. std::vector<ManagedQueue*>* inactiveQueues = &((*nqcb).second->inactiveQueues);
  767. _aqm_m.lock();
  768. // Attempt dequeue from queues in NEW list
  769. bool examiningNewQueues = true;
  770. while (currQueues->size()) {
  771. ManagedQueue* queueAtFrontOfList = currQueues->front();
  772. if (queueAtFrontOfList->byteCredit < 0) {
  773. queueAtFrontOfList->byteCredit += ZT_AQM_QUANTUM;
  774. // Move to list of OLD queues
  775. // DEBUG_INFO("moving q=%p from NEW to OLD list", queueAtFrontOfList);
  776. oldQueues->push_back(queueAtFrontOfList);
  777. currQueues->erase(currQueues->begin());
  778. }
  779. else {
  780. entryToEmit = CoDelDequeue(queueAtFrontOfList, examiningNewQueues, now);
  781. if (! entryToEmit) {
  782. // Move to end of list of OLD queues
  783. // DEBUG_INFO("moving q=%p from NEW to OLD list", queueAtFrontOfList);
  784. oldQueues->push_back(queueAtFrontOfList);
  785. currQueues->erase(currQueues->begin());
  786. }
  787. else {
  788. int len = entryToEmit->packet.payloadLength();
  789. queueAtFrontOfList->byteLength -= len;
  790. queueAtFrontOfList->byteCredit -= len;
  791. // Send the packet!
  792. queueAtFrontOfList->q.pop_front();
  793. send(tPtr, entryToEmit->packet, entryToEmit->encrypt, entryToEmit->flowId);
  794. (*nqcb).second->_currEnqueuedPackets--;
  795. }
  796. if (queueAtFrontOfList) {
  797. // DEBUG_INFO("dequeuing from q=%p, len=%lu in NEW list (byteCredit=%d)", queueAtFrontOfList, queueAtFrontOfList->q.size(), queueAtFrontOfList->byteCredit);
  798. }
  799. break;
  800. }
  801. }
  802. // Attempt dequeue from queues in OLD list
  803. examiningNewQueues = false;
  804. currQueues = &((*nqcb).second->oldQueues);
  805. while (currQueues->size()) {
  806. ManagedQueue* queueAtFrontOfList = currQueues->front();
  807. if (queueAtFrontOfList->byteCredit < 0) {
  808. queueAtFrontOfList->byteCredit += ZT_AQM_QUANTUM;
  809. oldQueues->push_back(queueAtFrontOfList);
  810. currQueues->erase(currQueues->begin());
  811. }
  812. else {
  813. entryToEmit = CoDelDequeue(queueAtFrontOfList, examiningNewQueues, now);
  814. if (! entryToEmit) {
  815. // DEBUG_INFO("moving q=%p from OLD to INACTIVE list", queueAtFrontOfList);
  816. // Move to inactive list of queues
  817. inactiveQueues->push_back(queueAtFrontOfList);
  818. currQueues->erase(currQueues->begin());
  819. }
  820. else {
  821. int len = entryToEmit->packet.payloadLength();
  822. queueAtFrontOfList->byteLength -= len;
  823. queueAtFrontOfList->byteCredit -= len;
  824. queueAtFrontOfList->q.pop_front();
  825. send(tPtr, entryToEmit->packet, entryToEmit->encrypt, entryToEmit->flowId);
  826. (*nqcb).second->_currEnqueuedPackets--;
  827. }
  828. if (queueAtFrontOfList) {
  829. // DEBUG_INFO("dequeuing from q=%p, len=%lu in OLD list (byteCredit=%d)", queueAtFrontOfList, queueAtFrontOfList->q.size(), queueAtFrontOfList->byteCredit);
  830. }
  831. break;
  832. }
  833. }
  834. nqcb++;
  835. _aqm_m.unlock();
  836. }
  837. }
  838. void Switch::removeNetworkQoSControlBlock(uint64_t nwid)
  839. {
  840. NetworkQoSControlBlock* nq = _netQueueControlBlock[nwid];
  841. if (nq) {
  842. _netQueueControlBlock.erase(nwid);
  843. delete nq;
  844. nq = NULL;
  845. }
  846. }
  847. void Switch::send(void* tPtr, Packet& packet, bool encrypt, int32_t flowId)
  848. {
  849. const Address dest(packet.destination());
  850. if (dest == RR->identity.address()) {
  851. return;
  852. }
  853. _recordOutgoingPacketMetrics(packet);
  854. if (! _trySend(tPtr, packet, encrypt, flowId)) {
  855. {
  856. Mutex::Lock _l(_txQueue_m);
  857. if (_txQueue.size() >= ZT_TX_QUEUE_SIZE) {
  858. _txQueue.pop_front();
  859. }
  860. _txQueue.push_back(TXQueueEntry(dest, RR->node->now(), packet, encrypt, flowId));
  861. }
  862. if (! RR->topology->getPeer(tPtr, dest)) {
  863. requestWhois(tPtr, RR->node->now(), dest);
  864. }
  865. }
  866. }
  867. void Switch::requestWhois(void* tPtr, const int64_t now, const Address& addr)
  868. {
  869. if (addr == RR->identity.address()) {
  870. return;
  871. }
  872. {
  873. Mutex::Lock _l(_lastSentWhoisRequest_m);
  874. int64_t& last = _lastSentWhoisRequest[addr];
  875. if ((now - last) < ZT_WHOIS_RETRY_DELAY) {
  876. return;
  877. }
  878. else {
  879. last = now;
  880. }
  881. }
  882. const SharedPtr<Peer> upstream(RR->topology->getUpstreamPeer());
  883. if (upstream) {
  884. int32_t flowId = ZT_QOS_NO_FLOW;
  885. Packet outp(upstream->address(), RR->identity.address(), Packet::VERB_WHOIS);
  886. addr.appendTo(outp);
  887. send(tPtr, outp, true, flowId);
  888. }
  889. }
  890. void Switch::doAnythingWaitingForPeer(void* tPtr, const SharedPtr<Peer>& peer)
  891. {
  892. {
  893. Mutex::Lock _l(_lastSentWhoisRequest_m);
  894. _lastSentWhoisRequest.erase(peer->address());
  895. }
  896. const int64_t now = RR->node->now();
  897. for (unsigned int ptr = 0; ptr < ZT_RX_QUEUE_SIZE; ++ptr) {
  898. RXQueueEntry* const rq = &(_rxQueue[ptr]);
  899. Mutex::Lock rql(rq->lock);
  900. if ((rq->timestamp) && (rq->complete)) {
  901. if ((rq->frag0.tryDecode(RR, tPtr, rq->flowId)) || ((now - rq->timestamp) > ZT_RECEIVE_QUEUE_TIMEOUT)) {
  902. rq->timestamp = 0;
  903. }
  904. }
  905. }
  906. {
  907. Mutex::Lock _l(_txQueue_m);
  908. for (std::list<TXQueueEntry>::iterator txi(_txQueue.begin()); txi != _txQueue.end();) {
  909. if (txi->dest == peer->address()) {
  910. if (_trySend(tPtr, txi->packet, txi->encrypt, txi->flowId)) {
  911. _txQueue.erase(txi++);
  912. }
  913. else {
  914. ++txi;
  915. }
  916. }
  917. else {
  918. ++txi;
  919. }
  920. }
  921. }
  922. }
  923. unsigned long Switch::doTimerTasks(void* tPtr, int64_t now)
  924. {
  925. const uint64_t timeSinceLastCheck = now - _lastCheckedQueues;
  926. if (timeSinceLastCheck < ZT_WHOIS_RETRY_DELAY) {
  927. return (unsigned long)(ZT_WHOIS_RETRY_DELAY - timeSinceLastCheck);
  928. }
  929. _lastCheckedQueues = now;
  930. std::vector<Address> needWhois;
  931. {
  932. Mutex::Lock _l(_txQueue_m);
  933. for (std::list<TXQueueEntry>::iterator txi(_txQueue.begin()); txi != _txQueue.end();) {
  934. if (_trySend(tPtr, txi->packet, txi->encrypt, txi->flowId)) {
  935. _txQueue.erase(txi++);
  936. }
  937. else if ((now - txi->creationTime) > ZT_TRANSMIT_QUEUE_TIMEOUT) {
  938. _txQueue.erase(txi++);
  939. }
  940. else {
  941. if (! RR->topology->getPeer(tPtr, txi->dest)) {
  942. needWhois.push_back(txi->dest);
  943. }
  944. ++txi;
  945. }
  946. }
  947. }
  948. for (std::vector<Address>::const_iterator i(needWhois.begin()); i != needWhois.end(); ++i) {
  949. requestWhois(tPtr, now, *i);
  950. }
  951. for (unsigned int ptr = 0; ptr < ZT_RX_QUEUE_SIZE; ++ptr) {
  952. RXQueueEntry* const rq = &(_rxQueue[ptr]);
  953. Mutex::Lock rql(rq->lock);
  954. if ((rq->timestamp) && (rq->complete)) {
  955. if ((rq->frag0.tryDecode(RR, tPtr, rq->flowId)) || ((now - rq->timestamp) > ZT_RECEIVE_QUEUE_TIMEOUT)) {
  956. rq->timestamp = 0;
  957. }
  958. else {
  959. const Address src(rq->frag0.source());
  960. if (! RR->topology->getPeer(tPtr, src)) {
  961. requestWhois(tPtr, now, src);
  962. }
  963. }
  964. }
  965. }
  966. {
  967. Mutex::Lock _l(_lastUniteAttempt_m);
  968. Hashtable<_LastUniteKey, uint64_t>::Iterator i(_lastUniteAttempt);
  969. _LastUniteKey* k = (_LastUniteKey*)0;
  970. uint64_t* v = (uint64_t*)0;
  971. while (i.next(k, v)) {
  972. if ((now - *v) >= (ZT_MIN_UNITE_INTERVAL * 8)) {
  973. _lastUniteAttempt.erase(*k);
  974. }
  975. }
  976. }
  977. {
  978. Mutex::Lock _l(_lastSentWhoisRequest_m);
  979. Hashtable<Address, int64_t>::Iterator i(_lastSentWhoisRequest);
  980. Address* a = (Address*)0;
  981. int64_t* ts = (int64_t*)0;
  982. while (i.next(a, ts)) {
  983. if ((now - *ts) > (ZT_WHOIS_RETRY_DELAY * 2)) {
  984. _lastSentWhoisRequest.erase(*a);
  985. }
  986. }
  987. }
  988. return ZT_WHOIS_RETRY_DELAY;
  989. }
  990. bool Switch::_shouldUnite(const int64_t now, const Address& source, const Address& destination)
  991. {
  992. Mutex::Lock _l(_lastUniteAttempt_m);
  993. uint64_t& ts = _lastUniteAttempt[_LastUniteKey(source, destination)];
  994. if ((now - ts) >= ZT_MIN_UNITE_INTERVAL) {
  995. ts = now;
  996. return true;
  997. }
  998. return false;
  999. }
  1000. bool Switch::_trySend(void* tPtr, Packet& packet, bool encrypt, int32_t flowId)
  1001. {
  1002. SharedPtr<Path> viaPath;
  1003. const int64_t now = RR->node->now();
  1004. const Address destination(packet.destination());
  1005. const SharedPtr<Peer> peer(RR->topology->getPeer(tPtr, destination));
  1006. if (peer) {
  1007. if ((peer->bondingPolicy() == ZT_BOND_POLICY_BROADCAST) && (packet.verb() == Packet::VERB_FRAME || packet.verb() == Packet::VERB_EXT_FRAME)) {
  1008. const SharedPtr<Peer> relay(RR->topology->getUpstreamPeer());
  1009. Mutex::Lock _l(peer->_paths_m);
  1010. for (int i = 0; i < ZT_MAX_PEER_NETWORK_PATHS; ++i) {
  1011. if (peer->_paths[i].p && peer->_paths[i].p->alive(now)) {
  1012. uint16_t userSpecifiedMtu = peer->_paths[i].p->mtu();
  1013. _sendViaSpecificPath(tPtr, peer, peer->_paths[i].p, userSpecifiedMtu, now, packet, encrypt, flowId);
  1014. }
  1015. }
  1016. return true;
  1017. }
  1018. else {
  1019. viaPath = peer->getAppropriatePath(now, false, flowId);
  1020. if (! viaPath) {
  1021. peer->tryMemorizedPath(tPtr, now); // periodically attempt memorized or statically defined paths, if any are known
  1022. const SharedPtr<Peer> relay(RR->topology->getUpstreamPeer());
  1023. if ((! relay) || (! (viaPath = relay->getAppropriatePath(now, false, flowId)))) {
  1024. if (! (viaPath = peer->getAppropriatePath(now, true, flowId))) {
  1025. return false;
  1026. }
  1027. }
  1028. }
  1029. if (viaPath) {
  1030. uint16_t userSpecifiedMtu = viaPath->mtu();
  1031. _sendViaSpecificPath(tPtr, peer, viaPath, userSpecifiedMtu, now, packet, encrypt, flowId);
  1032. return true;
  1033. }
  1034. }
  1035. }
  1036. return false;
  1037. }
  1038. void Switch::_sendViaSpecificPath(void* tPtr, SharedPtr<Peer> peer, SharedPtr<Path> viaPath, uint16_t userSpecifiedMtu, int64_t now, Packet& packet, bool encrypt, int32_t flowId)
  1039. {
  1040. unsigned int mtu = ZT_DEFAULT_PHYSMTU;
  1041. uint64_t trustedPathId = 0;
  1042. RR->topology->getOutboundPathInfo(viaPath->address(), mtu, trustedPathId);
  1043. if (userSpecifiedMtu > 0) {
  1044. mtu = userSpecifiedMtu;
  1045. }
  1046. unsigned int chunkSize = std::min(packet.size(), mtu);
  1047. packet.setFragmented(chunkSize < packet.size());
  1048. if (trustedPathId) {
  1049. packet.setTrusted(trustedPathId);
  1050. }
  1051. else {
  1052. if (! packet.isEncrypted()) {
  1053. packet.armor(peer->key(), encrypt, peer->aesKeysIfSupported());
  1054. }
  1055. RR->node->expectReplyTo(packet.packetId());
  1056. }
  1057. peer->recordOutgoingPacket(viaPath, packet.packetId(), packet.payloadLength(), packet.verb(), flowId, now);
  1058. if (viaPath->send(RR, tPtr, packet.data(), chunkSize, now)) {
  1059. if (chunkSize < packet.size()) {
  1060. // Too big for one packet, fragment the rest
  1061. unsigned int fragStart = chunkSize;
  1062. unsigned int remaining = packet.size() - chunkSize;
  1063. unsigned int fragsRemaining = (remaining / (mtu - ZT_PROTO_MIN_FRAGMENT_LENGTH));
  1064. if ((fragsRemaining * (mtu - ZT_PROTO_MIN_FRAGMENT_LENGTH)) < remaining) {
  1065. ++fragsRemaining;
  1066. }
  1067. const unsigned int totalFragments = fragsRemaining + 1;
  1068. for (unsigned int fno = 1; fno < totalFragments; ++fno) {
  1069. chunkSize = std::min(remaining, (unsigned int)(mtu - ZT_PROTO_MIN_FRAGMENT_LENGTH));
  1070. Packet::Fragment frag(packet, fragStart, chunkSize, fno, totalFragments);
  1071. viaPath->send(RR, tPtr, frag.data(), frag.size(), now);
  1072. fragStart += chunkSize;
  1073. remaining -= chunkSize;
  1074. }
  1075. }
  1076. }
  1077. }
  1078. void Switch::_recordOutgoingPacketMetrics(const Packet& p)
  1079. {
  1080. switch (p.verb()) {
  1081. case Packet::VERB_NOP:
  1082. Metrics::pkt_nop_out++;
  1083. break;
  1084. case Packet::VERB_HELLO:
  1085. Metrics::pkt_hello_out++;
  1086. break;
  1087. case Packet::VERB_ERROR:
  1088. Metrics::pkt_error_out++;
  1089. break;
  1090. case Packet::VERB_OK:
  1091. Metrics::pkt_ok_out++;
  1092. break;
  1093. case Packet::VERB_WHOIS:
  1094. Metrics::pkt_whois_out++;
  1095. break;
  1096. case Packet::VERB_RENDEZVOUS:
  1097. Metrics::pkt_rendezvous_out++;
  1098. break;
  1099. case Packet::VERB_FRAME:
  1100. Metrics::pkt_frame_out++;
  1101. break;
  1102. case Packet::VERB_EXT_FRAME:
  1103. Metrics::pkt_ext_frame_out++;
  1104. break;
  1105. case Packet::VERB_ECHO:
  1106. Metrics::pkt_echo_out++;
  1107. break;
  1108. case Packet::VERB_MULTICAST_LIKE:
  1109. Metrics::pkt_multicast_like_out++;
  1110. break;
  1111. case Packet::VERB_NETWORK_CREDENTIALS:
  1112. Metrics::pkt_network_credentials_out++;
  1113. break;
  1114. case Packet::VERB_NETWORK_CONFIG_REQUEST:
  1115. Metrics::pkt_network_config_request_out++;
  1116. break;
  1117. case Packet::VERB_NETWORK_CONFIG:
  1118. Metrics::pkt_network_config_out++;
  1119. break;
  1120. case Packet::VERB_MULTICAST_GATHER:
  1121. Metrics::pkt_multicast_gather_out++;
  1122. break;
  1123. case Packet::VERB_MULTICAST_FRAME:
  1124. Metrics::pkt_multicast_frame_out++;
  1125. break;
  1126. case Packet::VERB_PUSH_DIRECT_PATHS:
  1127. Metrics::pkt_push_direct_paths_out++;
  1128. break;
  1129. case Packet::VERB_ACK:
  1130. Metrics::pkt_ack_out++;
  1131. break;
  1132. case Packet::VERB_QOS_MEASUREMENT:
  1133. Metrics::pkt_qos_out++;
  1134. break;
  1135. case Packet::VERB_USER_MESSAGE:
  1136. Metrics::pkt_user_message_out++;
  1137. break;
  1138. case Packet::VERB_REMOTE_TRACE:
  1139. Metrics::pkt_remote_trace_out++;
  1140. break;
  1141. case Packet::VERB_PATH_NEGOTIATION_REQUEST:
  1142. Metrics::pkt_path_negotiation_request_out++;
  1143. break;
  1144. }
  1145. }
  1146. } // namespace ZeroTier