Switch.cpp 43 KB

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