Switch.cpp 42 KB

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