Switch.cpp 41 KB

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