Switch.cpp 41 KB

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