Switch.cpp 42 KB

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