Switch.cpp 43 KB

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