Switch.cpp 52 KB

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