Switch.cpp 41 KB

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