Switch.cpp 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957
  1. /*
  2. * Copyright (c)2019 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: 2023-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 <cstdio>
  14. #include <cstdlib>
  15. #include <algorithm>
  16. #include <utility>
  17. #include <stdexcept>
  18. #include "../include/ZeroTierOne.h"
  19. #include "Constants.hpp"
  20. #include "RuntimeEnvironment.hpp"
  21. #include "Switch.hpp"
  22. #include "Node.hpp"
  23. #include "InetAddress.hpp"
  24. #include "Topology.hpp"
  25. #include "Peer.hpp"
  26. #include "SelfAwareness.hpp"
  27. #include "Packet.hpp"
  28. #include "Trace.hpp"
  29. namespace ZeroTier {
  30. Switch::Switch(const RuntimeEnvironment *renv) :
  31. RR(renv),
  32. _lastCheckedQueues(0),
  33. _lastUniteAttempt(8) // only really used on root servers and upstreams, and it'll grow there just fine
  34. {
  35. }
  36. void Switch::onRemotePacket(void *tPtr,const int64_t localSocket,const InetAddress &fromAddr,const void *data,unsigned int len)
  37. {
  38. try {
  39. const int64_t now = RR->node->now();
  40. const SharedPtr<Path> path(RR->topology->getPath(localSocket,fromAddr));
  41. path->received(now);
  42. if (len > ZT_PROTO_MIN_FRAGMENT_LENGTH) { // SECURITY: min length check is important since we do some C-style stuff below!
  43. if (reinterpret_cast<const uint8_t *>(data)[ZT_PACKET_FRAGMENT_IDX_FRAGMENT_INDICATOR] == ZT_PACKET_FRAGMENT_INDICATOR) {
  44. // Handle fragment ----------------------------------------------------
  45. Packet::Fragment fragment(data,len);
  46. const Address destination(fragment.destination());
  47. if (destination != RR->identity.address()) {
  48. if (fragment.hops() < ZT_RELAY_MAX_HOPS) {
  49. fragment.incrementHops();
  50. // Note: we don't bother initiating NAT-t for fragments, since heads will set that off.
  51. // It wouldn't hurt anything, just redundant and unnecessary.
  52. SharedPtr<Peer> relayTo = RR->topology->get(destination);
  53. if ((!relayTo)||(!relayTo->sendDirect(tPtr,fragment.data(),fragment.size(),now,false))) {
  54. // Don't know peer or no direct path -- so relay via someone upstream
  55. relayTo = RR->topology->findRelayTo(now,destination);
  56. if (relayTo)
  57. relayTo->sendDirect(tPtr,fragment.data(),fragment.size(),now,true);
  58. }
  59. }
  60. } else {
  61. // Fragment looks like ours
  62. const uint64_t fragmentPacketId = fragment.packetId();
  63. const unsigned int fragmentNumber = fragment.fragmentNumber();
  64. const unsigned int totalFragments = fragment.totalFragments();
  65. if ((totalFragments <= ZT_MAX_PACKET_FRAGMENTS)&&(fragmentNumber < ZT_MAX_PACKET_FRAGMENTS)&&(fragmentNumber > 0)&&(totalFragments > 1)) {
  66. // Fragment appears basically sane. Its fragment number must be
  67. // 1 or more, since a Packet with fragmented bit set is fragment 0.
  68. // Total fragments must be more than 1, otherwise why are we
  69. // seeing a Packet::Fragment?
  70. RXQueueEntry *const rq = _findRXQueueEntry(fragmentPacketId);
  71. Mutex::Lock rql(rq->lock);
  72. if (rq->packetId != fragmentPacketId) {
  73. // No packet found, so we received a fragment without its head.
  74. rq->timestamp = now;
  75. rq->packetId = fragmentPacketId;
  76. rq->frags[fragmentNumber - 1] = fragment;
  77. rq->totalFragments = totalFragments; // total fragment count is known
  78. rq->haveFragments = 1 << fragmentNumber; // we have only this fragment
  79. rq->complete = false;
  80. } else if (!(rq->haveFragments & (1 << fragmentNumber))) {
  81. // We have other fragments and maybe the head, so add this one and check
  82. rq->frags[fragmentNumber - 1] = fragment;
  83. rq->totalFragments = totalFragments;
  84. if (Utils::countBits(rq->haveFragments |= (1 << fragmentNumber)) == totalFragments) {
  85. // We have all fragments -- assemble and process full Packet
  86. for(unsigned int f=1;f<totalFragments;++f)
  87. rq->frag0.append(rq->frags[f - 1].payload(),rq->frags[f - 1].payloadLength());
  88. if (rq->frag0.tryDecode(RR,tPtr)) {
  89. rq->timestamp = 0; // packet decoded, free entry
  90. } else {
  91. rq->complete = true; // set complete flag but leave entry since it probably needs WHOIS or something
  92. }
  93. }
  94. } // else this is a duplicate fragment, ignore
  95. }
  96. }
  97. // --------------------------------------------------------------------
  98. } else if (len >= ZT_PROTO_MIN_PACKET_LENGTH) { // min length check is important!
  99. // Handle packet head -------------------------------------------------
  100. const Address destination(reinterpret_cast<const uint8_t *>(data) + 8,ZT_ADDRESS_LENGTH);
  101. const Address source(reinterpret_cast<const uint8_t *>(data) + 13,ZT_ADDRESS_LENGTH);
  102. if (source == RR->identity.address())
  103. return;
  104. if (destination != RR->identity.address()) {
  105. // This packet is not for this node, so possibly relay it ----------
  106. Packet packet(data,len);
  107. if (packet.hops() < ZT_RELAY_MAX_HOPS) {
  108. packet.incrementHops();
  109. SharedPtr<Peer> relayTo = RR->topology->get(destination);
  110. if ((relayTo)&&(relayTo->sendDirect(tPtr,packet.data(),packet.size(),now,false))) {
  111. if ((source != RR->identity.address())&&(_shouldUnite(now,source,destination))) {
  112. const SharedPtr<Peer> sourcePeer(RR->topology->get(source));
  113. if (sourcePeer)
  114. relayTo->introduce(tPtr,now,sourcePeer);
  115. }
  116. } else {
  117. relayTo = RR->topology->findRelayTo(now,destination);
  118. if ((relayTo)&&(relayTo->address() != source)) {
  119. if (relayTo->sendDirect(tPtr,packet.data(),packet.size(),now,true)) {
  120. const SharedPtr<Peer> sourcePeer(RR->topology->get(source));
  121. if (sourcePeer)
  122. relayTo->introduce(tPtr,now,sourcePeer);
  123. }
  124. }
  125. }
  126. }
  127. } else if ((reinterpret_cast<const uint8_t *>(data)[ZT_PACKET_IDX_FLAGS] & ZT_PROTO_FLAG_FRAGMENTED) != 0) {
  128. // Packet is the head of a fragmented packet series ----------------
  129. const uint64_t packetId = (
  130. (((uint64_t)reinterpret_cast<const uint8_t *>(data)[0]) << 56) |
  131. (((uint64_t)reinterpret_cast<const uint8_t *>(data)[1]) << 48) |
  132. (((uint64_t)reinterpret_cast<const uint8_t *>(data)[2]) << 40) |
  133. (((uint64_t)reinterpret_cast<const uint8_t *>(data)[3]) << 32) |
  134. (((uint64_t)reinterpret_cast<const uint8_t *>(data)[4]) << 24) |
  135. (((uint64_t)reinterpret_cast<const uint8_t *>(data)[5]) << 16) |
  136. (((uint64_t)reinterpret_cast<const uint8_t *>(data)[6]) << 8) |
  137. ((uint64_t)reinterpret_cast<const uint8_t *>(data)[7])
  138. );
  139. RXQueueEntry *const rq = _findRXQueueEntry(packetId);
  140. Mutex::Lock rql(rq->lock);
  141. if (rq->packetId != packetId) {
  142. // If we have no other fragments yet, create an entry and save the head
  143. rq->timestamp = now;
  144. rq->packetId = packetId;
  145. rq->frag0.init(data,len,path,now);
  146. rq->totalFragments = 0;
  147. rq->haveFragments = 1;
  148. rq->complete = false;
  149. } else if (!(rq->haveFragments & 1)) {
  150. // Check if packet is complete -----------------------------------
  151. if ((rq->totalFragments > 1)&&(Utils::countBits(rq->haveFragments |= 1) == rq->totalFragments)) {
  152. // We have all fragments -- assemble and process full Packet ---
  153. rq->frag0.init(data,len,path,now);
  154. for(unsigned int f=1;f<rq->totalFragments;++f)
  155. rq->frag0.append(rq->frags[f - 1].payload(),rq->frags[f - 1].payloadLength());
  156. if (rq->frag0.tryDecode(RR,tPtr)) {
  157. rq->timestamp = 0; // packet decoded, free entry
  158. } else {
  159. rq->complete = true; // set complete flag but leave entry since it probably needs WHOIS or something
  160. }
  161. } else {
  162. // Still waiting on more fragments, but keep the head ----------
  163. rq->frag0.init(data,len,path,now);
  164. }
  165. } // else this is a duplicate head, ignore
  166. } else {
  167. // Packet is unfragmented, so just process it ----------------------
  168. IncomingPacket packet(data,len,path,now);
  169. if (!packet.tryDecode(RR,tPtr)) {
  170. RXQueueEntry *const rq = _nextRXQueueEntry();
  171. Mutex::Lock rql(rq->lock);
  172. rq->timestamp = now;
  173. rq->packetId = packet.packetId();
  174. rq->frag0 = packet;
  175. rq->totalFragments = 1;
  176. rq->haveFragments = 1;
  177. rq->complete = true;
  178. }
  179. }
  180. // --------------------------------------------------------------------
  181. }
  182. }
  183. } catch ( ... ) {} // sanity check, should be caught elsewhere
  184. }
  185. 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)
  186. {
  187. if (!network->hasConfig())
  188. return;
  189. // Check if this packet is from someone other than the tap -- i.e. bridged in
  190. bool fromBridged;
  191. if ((fromBridged = (from != network->mac()))) {
  192. if (!network->config().permitsBridging(RR->identity.address())) {
  193. RR->t->outgoingNetworkFrameDropped(tPtr,network,from,to,etherType,vlanId,len,"not a bridge");
  194. return;
  195. }
  196. }
  197. uint8_t qosBucket = ZT_QOS_DEFAULT_BUCKET;
  198. if (to.isMulticast()) {
  199. MulticastGroup multicastGroup(to,0);
  200. if (to.isBroadcast()) {
  201. if ( (etherType == ZT_ETHERTYPE_ARP) && (len >= 28) && ((((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)) ) {
  202. /* IPv4 ARP is one of the few special cases that we impose upon what is
  203. * otherwise a straightforward Ethernet switch emulation. Vanilla ARP
  204. * is dumb old broadcast and simply doesn't scale. ZeroTier multicast
  205. * groups have an additional field called ADI (additional distinguishing
  206. * information) which was added specifically for ARP though it could
  207. * be used for other things too. We then take ARP broadcasts and turn
  208. * them into multicasts by stuffing the IP address being queried into
  209. * the 32-bit ADI field. In practice this uses our multicast pub/sub
  210. * system to implement a kind of extended/distributed ARP table. */
  211. multicastGroup = MulticastGroup::deriveMulticastGroupForAddressResolution(InetAddress(((const unsigned char *)data) + 24,4,0));
  212. } else if (!network->config().enableBroadcast()) {
  213. // Don't transmit broadcasts if this network doesn't want them
  214. RR->t->outgoingNetworkFrameDropped(tPtr,network,from,to,etherType,vlanId,len,"broadcast disabled");
  215. return;
  216. }
  217. } else if ((etherType == ZT_ETHERTYPE_IPV6)&&(len >= (40 + 8 + 16))) {
  218. // IPv6 NDP emulation for certain very special patterns of private IPv6 addresses -- if enabled
  219. if ((network->config().ndpEmulation())&&(reinterpret_cast<const uint8_t *>(data)[6] == 0x3a)&&(reinterpret_cast<const uint8_t *>(data)[40] == 0x87)) { // ICMPv6 neighbor solicitation
  220. Address v6EmbeddedAddress;
  221. const uint8_t *const pkt6 = reinterpret_cast<const uint8_t *>(data) + 40 + 8;
  222. const uint8_t *my6 = (const uint8_t *)0;
  223. // ZT-RFC4193 address: fdNN:NNNN:NNNN:NNNN:NN99:93DD:DDDD:DDDD / 88 (one /128 per actual host)
  224. // ZT-6PLANE address: fcXX:XXXX:XXDD:DDDD:DDDD:####:####:#### / 40 (one /80 per actual host)
  225. // (XX - lower 32 bits of network ID XORed with higher 32 bits)
  226. // For these to work, we must have a ZT-managed address assigned in one of the
  227. // above formats, and the query must match its prefix.
  228. for(unsigned int sipk=0;sipk<network->config().staticIpCount;++sipk) {
  229. const InetAddress *const sip = &(network->config().staticIps[sipk]);
  230. if (sip->ss_family == AF_INET6) {
  231. my6 = reinterpret_cast<const uint8_t *>(reinterpret_cast<const struct sockaddr_in6 *>(&(*sip))->sin6_addr.s6_addr);
  232. const unsigned int sipNetmaskBits = Utils::ntoh((uint16_t)reinterpret_cast<const struct sockaddr_in6 *>(&(*sip))->sin6_port);
  233. if ((sipNetmaskBits == 88)&&(my6[0] == 0xfd)&&(my6[9] == 0x99)&&(my6[10] == 0x93)) { // ZT-RFC4193 /88 ???
  234. unsigned int ptr = 0;
  235. while (ptr != 11) {
  236. if (pkt6[ptr] != my6[ptr])
  237. break;
  238. ++ptr;
  239. }
  240. if (ptr == 11) { // prefix match!
  241. v6EmbeddedAddress.setTo(pkt6 + ptr,5);
  242. break;
  243. }
  244. } else if (sipNetmaskBits == 40) { // ZT-6PLANE /40 ???
  245. const uint32_t nwid32 = (uint32_t)((network->id() ^ (network->id() >> 32)) & 0xffffffff);
  246. 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))) {
  247. unsigned int ptr = 0;
  248. while (ptr != 5) {
  249. if (pkt6[ptr] != my6[ptr])
  250. break;
  251. ++ptr;
  252. }
  253. if (ptr == 5) { // prefix match!
  254. v6EmbeddedAddress.setTo(pkt6 + ptr,5);
  255. break;
  256. }
  257. }
  258. }
  259. }
  260. }
  261. if ((v6EmbeddedAddress)&&(v6EmbeddedAddress != RR->identity.address())) {
  262. const MAC peerMac(v6EmbeddedAddress,network->id());
  263. uint8_t adv[72];
  264. adv[0] = 0x60; adv[1] = 0x00; adv[2] = 0x00; adv[3] = 0x00;
  265. adv[4] = 0x00; adv[5] = 0x20;
  266. adv[6] = 0x3a; adv[7] = 0xff;
  267. for(int i=0;i<16;++i) adv[8 + i] = pkt6[i];
  268. for(int i=0;i<16;++i) adv[24 + i] = my6[i];
  269. adv[40] = 0x88; adv[41] = 0x00;
  270. adv[42] = 0x00; adv[43] = 0x00; // future home of checksum
  271. adv[44] = 0x60; adv[45] = 0x00; adv[46] = 0x00; adv[47] = 0x00;
  272. for(int i=0;i<16;++i) adv[48 + i] = pkt6[i];
  273. adv[64] = 0x02; adv[65] = 0x01;
  274. adv[66] = peerMac[0]; adv[67] = peerMac[1]; adv[68] = peerMac[2]; adv[69] = peerMac[3]; adv[70] = peerMac[4]; adv[71] = peerMac[5];
  275. uint16_t pseudo_[36];
  276. uint8_t *const pseudo = reinterpret_cast<uint8_t *>(pseudo_);
  277. for(int i=0;i<32;++i) pseudo[i] = adv[8 + i];
  278. pseudo[32] = 0x00; pseudo[33] = 0x00; pseudo[34] = 0x00; pseudo[35] = 0x20;
  279. pseudo[36] = 0x00; pseudo[37] = 0x00; pseudo[38] = 0x00; pseudo[39] = 0x3a;
  280. for(int i=0;i<32;++i) pseudo[40 + i] = adv[40 + i];
  281. uint32_t checksum = 0;
  282. for(int i=0;i<36;++i) checksum += Utils::hton(pseudo_[i]);
  283. while ((checksum >> 16)) checksum = (checksum & 0xffff) + (checksum >> 16);
  284. checksum = ~checksum;
  285. adv[42] = (checksum >> 8) & 0xff;
  286. adv[43] = checksum & 0xff;
  287. RR->node->putFrame(tPtr,network->id(),network->userPtr(),peerMac,from,ZT_ETHERTYPE_IPV6,0,adv,72);
  288. return; // NDP emulation done. We have forged a "fake" reply, so no need to send actual NDP query.
  289. } // else no NDP emulation
  290. } // else no NDP emulation
  291. }
  292. // Check this after NDP emulation, since that has to be allowed in exactly this case
  293. if (network->config().multicastLimit == 0) {
  294. RR->t->outgoingNetworkFrameDropped(tPtr,network,from,to,etherType,vlanId,len,"multicast disabled");
  295. return;
  296. }
  297. /* Learn multicast groups for bridged-in hosts.
  298. * Note that some OSes, most notably Linux, do this for you by learning
  299. * multicast addresses on bridge interfaces and subscribing each slave.
  300. * But in that case this does no harm, as the sets are just merged. */
  301. if (fromBridged)
  302. network->learnBridgedMulticastGroup(tPtr,multicastGroup,RR->node->now());
  303. // First pass sets noTee to false, but noTee is set to true in OutboundMulticast to prevent duplicates.
  304. if (!network->filterOutgoingPacket(tPtr,false,RR->identity.address(),Address(),from,to,(const uint8_t *)data,len,etherType,vlanId,qosBucket)) {
  305. RR->t->outgoingNetworkFrameDropped(tPtr,network,from,to,etherType,vlanId,len,"filter blocked");
  306. return;
  307. }
  308. // TODO
  309. /*
  310. RR->mc->send(
  311. tPtr,
  312. RR->node->now(),
  313. network,
  314. Address(),
  315. multicastGroup,
  316. (fromBridged) ? from : MAC(),
  317. etherType,
  318. data,
  319. len);
  320. */
  321. } else if (to == network->mac()) {
  322. // Destination is this node, so just reinject it -------------------------
  323. RR->node->putFrame(tPtr,network->id(),network->userPtr(),from,to,etherType,vlanId,data,len);
  324. } else if (to[0] == MAC::firstOctetForNetwork(network->id())) {
  325. // Destination is another ZeroTier peer on the same network --------------
  326. Address toZT(to.toAddress(network->id())); // since in-network MACs are derived from addresses and network IDs, we can reverse this
  327. SharedPtr<Peer> toPeer(RR->topology->get(toZT));
  328. if (!network->filterOutgoingPacket(tPtr,false,RR->identity.address(),toZT,from,to,(const uint8_t *)data,len,etherType,vlanId,qosBucket)) {
  329. RR->t->outgoingNetworkFrameDropped(tPtr,network,from,to,etherType,vlanId,len,"filter blocked");
  330. return;
  331. }
  332. network->pushCredentialsIfNeeded(tPtr,toZT,RR->node->now());
  333. if (fromBridged) {
  334. Packet outp(toZT,RR->identity.address(),Packet::VERB_EXT_FRAME);
  335. outp.append(network->id());
  336. outp.append((unsigned char)0x00);
  337. to.appendTo(outp);
  338. from.appendTo(outp);
  339. outp.append((uint16_t)etherType);
  340. outp.append(data,len);
  341. if (!network->config().disableCompression())
  342. outp.compress();
  343. aqm_enqueue(tPtr,network,outp,true,qosBucket);
  344. } else {
  345. Packet outp(toZT,RR->identity.address(),Packet::VERB_FRAME);
  346. outp.append(network->id());
  347. outp.append((uint16_t)etherType);
  348. outp.append(data,len);
  349. if (!network->config().disableCompression())
  350. outp.compress();
  351. aqm_enqueue(tPtr,network,outp,true,qosBucket);
  352. }
  353. } else {
  354. // Destination is bridged behind a remote peer ---------------------------
  355. // We filter with a NULL destination ZeroTier address first. Filtrations
  356. // for each ZT destination are also done below. This is the same rationale
  357. // and design as for multicast.
  358. if (!network->filterOutgoingPacket(tPtr,false,RR->identity.address(),Address(),from,to,(const uint8_t *)data,len,etherType,vlanId,qosBucket)) {
  359. RR->t->outgoingNetworkFrameDropped(tPtr,network,from,to,etherType,vlanId,len,"filter blocked");
  360. return;
  361. }
  362. Address bridges[ZT_MAX_BRIDGE_SPAM];
  363. unsigned int numBridges = 0;
  364. /* Create an array of up to ZT_MAX_BRIDGE_SPAM recipients for this bridged frame. */
  365. bridges[0] = network->findBridgeTo(to);
  366. std::vector<Address> activeBridges;
  367. for(unsigned int i=0;i<network->config().specialistCount;++i) {
  368. if ((network->config().specialists[i] & ZT_NETWORKCONFIG_SPECIALIST_TYPE_ACTIVE_BRIDGE) != 0)
  369. activeBridges.push_back(Address(network->config().specialists[i]));
  370. }
  371. if ((bridges[0])&&(bridges[0] != RR->identity.address())&&(network->config().permitsBridging(bridges[0]))) {
  372. /* We have a known bridge route for this MAC, send it there. */
  373. ++numBridges;
  374. } else if (!activeBridges.empty()) {
  375. /* If there is no known route, spam to up to ZT_MAX_BRIDGE_SPAM active
  376. * bridges. If someone responds, we'll learn the route. */
  377. std::vector<Address>::const_iterator ab(activeBridges.begin());
  378. if (activeBridges.size() <= ZT_MAX_BRIDGE_SPAM) {
  379. // If there are <= ZT_MAX_BRIDGE_SPAM active bridges, spam them all
  380. while (ab != activeBridges.end()) {
  381. bridges[numBridges++] = *ab;
  382. ++ab;
  383. }
  384. } else {
  385. // Otherwise pick a random set of them
  386. while (numBridges < ZT_MAX_BRIDGE_SPAM) {
  387. if (ab == activeBridges.end())
  388. ab = activeBridges.begin();
  389. if (((unsigned long)Utils::random() % (unsigned long)activeBridges.size()) == 0) {
  390. bridges[numBridges++] = *ab;
  391. ++ab;
  392. } else ++ab;
  393. }
  394. }
  395. }
  396. for(unsigned int b=0;b<numBridges;++b) {
  397. if (network->filterOutgoingPacket(tPtr,true,RR->identity.address(),bridges[b],from,to,(const uint8_t *)data,len,etherType,vlanId,qosBucket)) {
  398. Packet outp(bridges[b],RR->identity.address(),Packet::VERB_EXT_FRAME);
  399. outp.append(network->id());
  400. outp.append((uint8_t)0x00);
  401. to.appendTo(outp);
  402. from.appendTo(outp);
  403. outp.append((uint16_t)etherType);
  404. outp.append(data,len);
  405. if (!network->config().disableCompression())
  406. outp.compress();
  407. aqm_enqueue(tPtr,network,outp,true,qosBucket);
  408. } else {
  409. RR->t->outgoingNetworkFrameDropped(tPtr,network,from,to,etherType,vlanId,len,"filter blocked (bridge replication)");
  410. }
  411. }
  412. }
  413. }
  414. void Switch::aqm_enqueue(void *tPtr, const SharedPtr<Network> &network, Packet &packet,bool encrypt,int qosBucket)
  415. {
  416. if(!network->qosEnabled()) {
  417. send(tPtr, packet, encrypt);
  418. return;
  419. }
  420. NetworkQoSControlBlock *nqcb = _netQueueControlBlock[network->id()];
  421. if (!nqcb) {
  422. // DEBUG_INFO("creating network QoS control block (NQCB) for network %llx", network->id());
  423. nqcb = new NetworkQoSControlBlock();
  424. _netQueueControlBlock[network->id()] = nqcb;
  425. // Initialize ZT_QOS_NUM_BUCKETS queues and place them in the INACTIVE list
  426. // These queues will be shuffled between the new/old/inactive lists by the enqueue/dequeue algorithm
  427. for (int i=0; i<ZT_QOS_NUM_BUCKETS; i++) {
  428. nqcb->inactiveQueues.push_back(new ManagedQueue(i));
  429. }
  430. }
  431. if (packet.verb() != Packet::VERB_FRAME && packet.verb() != Packet::VERB_EXT_FRAME) {
  432. // DEBUG_INFO("skipping, no QoS for this packet, verb=%x", packet.verb());
  433. // just send packet normally, no QoS for ZT protocol traffic
  434. send(tPtr, packet, encrypt);
  435. }
  436. _aqm_m.lock();
  437. // Enqueue packet and move queue to appropriate list
  438. const Address dest(packet.destination());
  439. TXQueueEntry *txEntry = new TXQueueEntry(dest,RR->node->now(),packet,encrypt);
  440. ManagedQueue *selectedQueue = nullptr;
  441. for (size_t i=0; i<ZT_QOS_NUM_BUCKETS; i++) {
  442. if (i < nqcb->oldQueues.size()) { // search old queues first (I think this is best since old would imply most recent usage of the queue)
  443. if (nqcb->oldQueues[i]->id == qosBucket) {
  444. selectedQueue = nqcb->oldQueues[i];
  445. }
  446. } if (i < nqcb->newQueues.size()) { // search new queues (this would imply not often-used queues)
  447. if (nqcb->newQueues[i]->id == qosBucket) {
  448. selectedQueue = nqcb->newQueues[i];
  449. }
  450. } if (i < nqcb->inactiveQueues.size()) { // search inactive queues
  451. if (nqcb->inactiveQueues[i]->id == qosBucket) {
  452. selectedQueue = nqcb->inactiveQueues[i];
  453. // move queue to end of NEW queue list
  454. selectedQueue->byteCredit = ZT_QOS_QUANTUM;
  455. // DEBUG_INFO("moving q=%p from INACTIVE to NEW list", selectedQueue);
  456. nqcb->newQueues.push_back(selectedQueue);
  457. nqcb->inactiveQueues.erase(nqcb->inactiveQueues.begin() + i);
  458. }
  459. }
  460. }
  461. if (!selectedQueue) {
  462. return;
  463. }
  464. selectedQueue->q.push_back(txEntry);
  465. selectedQueue->byteLength+=txEntry->packet.payloadLength();
  466. nqcb->_currEnqueuedPackets++;
  467. // 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);
  468. // Drop a packet if necessary
  469. ManagedQueue *selectedQueueToDropFrom = nullptr;
  470. if (nqcb->_currEnqueuedPackets > ZT_QOS_MAX_ENQUEUED_PACKETS)
  471. {
  472. // DEBUG_INFO("too many enqueued packets (%d), finding packet to drop", nqcb->_currEnqueuedPackets);
  473. int maxQueueLength = 0;
  474. for (size_t i=0; i<ZT_QOS_NUM_BUCKETS; i++) {
  475. if (i < nqcb->oldQueues.size()) {
  476. if (nqcb->oldQueues[i]->byteLength > maxQueueLength) {
  477. maxQueueLength = nqcb->oldQueues[i]->byteLength;
  478. selectedQueueToDropFrom = nqcb->oldQueues[i];
  479. }
  480. } if (i < nqcb->newQueues.size()) {
  481. if (nqcb->newQueues[i]->byteLength > maxQueueLength) {
  482. maxQueueLength = nqcb->newQueues[i]->byteLength;
  483. selectedQueueToDropFrom = nqcb->newQueues[i];
  484. }
  485. } if (i < nqcb->inactiveQueues.size()) {
  486. if (nqcb->inactiveQueues[i]->byteLength > maxQueueLength) {
  487. maxQueueLength = nqcb->inactiveQueues[i]->byteLength;
  488. selectedQueueToDropFrom = nqcb->inactiveQueues[i];
  489. }
  490. }
  491. }
  492. if (selectedQueueToDropFrom) {
  493. // DEBUG_INFO("dropping packet from head of largest queue (%d payload bytes)", maxQueueLength);
  494. int sizeOfDroppedPacket = selectedQueueToDropFrom->q.front()->packet.payloadLength();
  495. delete selectedQueueToDropFrom->q.front();
  496. selectedQueueToDropFrom->q.pop_front();
  497. selectedQueueToDropFrom->byteLength-=sizeOfDroppedPacket;
  498. nqcb->_currEnqueuedPackets--;
  499. }
  500. }
  501. _aqm_m.unlock();
  502. aqm_dequeue(tPtr);
  503. }
  504. uint64_t Switch::control_law(uint64_t t, int count)
  505. {
  506. return (uint64_t)(t + ZT_QOS_INTERVAL / sqrt(count));
  507. }
  508. Switch::dqr Switch::dodequeue(ManagedQueue *q, uint64_t now)
  509. {
  510. dqr r;
  511. r.ok_to_drop = false;
  512. r.p = q->q.front();
  513. if (r.p == NULL) {
  514. q->first_above_time = 0;
  515. return r;
  516. }
  517. uint64_t sojourn_time = now - r.p->creationTime;
  518. if (sojourn_time < ZT_QOS_TARGET || q->byteLength <= ZT_DEFAULT_MTU) {
  519. // went below - stay below for at least interval
  520. q->first_above_time = 0;
  521. } else {
  522. if (q->first_above_time == 0) {
  523. // just went above from below. if still above at
  524. // first_above_time, will say it's ok to drop.
  525. q->first_above_time = now + ZT_QOS_INTERVAL;
  526. } else if (now >= q->first_above_time) {
  527. r.ok_to_drop = true;
  528. }
  529. }
  530. return r;
  531. }
  532. Switch::TXQueueEntry * Switch::CoDelDequeue(ManagedQueue *q, bool isNew, uint64_t now)
  533. {
  534. dqr r = dodequeue(q, now);
  535. if (q->dropping) {
  536. if (!r.ok_to_drop) {
  537. q->dropping = false;
  538. }
  539. while (now >= q->drop_next && q->dropping) {
  540. q->q.pop_front(); // drop
  541. r = dodequeue(q, now);
  542. if (!r.ok_to_drop) {
  543. // leave dropping state
  544. q->dropping = false;
  545. } else {
  546. ++(q->count);
  547. // schedule the next drop.
  548. q->drop_next = control_law(q->drop_next, q->count);
  549. }
  550. }
  551. } else if (r.ok_to_drop) {
  552. q->q.pop_front(); // drop
  553. r = dodequeue(q, now);
  554. q->dropping = true;
  555. q->count = (q->count > 2 && now - q->drop_next < 8*ZT_QOS_INTERVAL)?
  556. q->count - 2 : 1;
  557. q->drop_next = control_law(now, q->count);
  558. }
  559. return r.p;
  560. }
  561. void Switch::aqm_dequeue(void *tPtr)
  562. {
  563. // Cycle through network-specific QoS control blocks
  564. for(std::map<uint64_t,NetworkQoSControlBlock*>::iterator nqcb(_netQueueControlBlock.begin());nqcb!=_netQueueControlBlock.end();) {
  565. if (!(*nqcb).second->_currEnqueuedPackets) {
  566. return;
  567. }
  568. uint64_t now = RR->node->now();
  569. TXQueueEntry *entryToEmit = nullptr;
  570. std::vector<ManagedQueue*> *currQueues = &((*nqcb).second->newQueues);
  571. std::vector<ManagedQueue*> *oldQueues = &((*nqcb).second->oldQueues);
  572. std::vector<ManagedQueue*> *inactiveQueues = &((*nqcb).second->inactiveQueues);
  573. _aqm_m.lock();
  574. // Attempt dequeue from queues in NEW list
  575. bool examiningNewQueues = true;
  576. while (currQueues->size()) {
  577. ManagedQueue *queueAtFrontOfList = currQueues->front();
  578. if (queueAtFrontOfList->byteCredit < 0) {
  579. queueAtFrontOfList->byteCredit += ZT_QOS_QUANTUM;
  580. // Move to list of OLD queues
  581. // DEBUG_INFO("moving q=%p from NEW to OLD list", queueAtFrontOfList);
  582. oldQueues->push_back(queueAtFrontOfList);
  583. currQueues->erase(currQueues->begin());
  584. } else {
  585. entryToEmit = CoDelDequeue(queueAtFrontOfList, examiningNewQueues, now);
  586. if (!entryToEmit) {
  587. // Move to end of list of OLD queues
  588. // DEBUG_INFO("moving q=%p from NEW to OLD list", queueAtFrontOfList);
  589. oldQueues->push_back(queueAtFrontOfList);
  590. currQueues->erase(currQueues->begin());
  591. }
  592. else {
  593. int len = entryToEmit->packet.payloadLength();
  594. queueAtFrontOfList->byteLength -= len;
  595. queueAtFrontOfList->byteCredit -= len;
  596. // Send the packet!
  597. queueAtFrontOfList->q.pop_front();
  598. send(tPtr, entryToEmit->packet, entryToEmit->encrypt);
  599. (*nqcb).second->_currEnqueuedPackets--;
  600. }
  601. if (queueAtFrontOfList) {
  602. //DEBUG_INFO("dequeuing from q=%p, len=%lu in NEW list (byteCredit=%d)", queueAtFrontOfList, queueAtFrontOfList->q.size(), queueAtFrontOfList->byteCredit);
  603. }
  604. break;
  605. }
  606. }
  607. // Attempt dequeue from queues in OLD list
  608. examiningNewQueues = false;
  609. currQueues = &((*nqcb).second->oldQueues);
  610. while (currQueues->size()) {
  611. ManagedQueue *queueAtFrontOfList = currQueues->front();
  612. if (queueAtFrontOfList->byteCredit < 0) {
  613. queueAtFrontOfList->byteCredit += ZT_QOS_QUANTUM;
  614. oldQueues->push_back(queueAtFrontOfList);
  615. currQueues->erase(currQueues->begin());
  616. } else {
  617. entryToEmit = CoDelDequeue(queueAtFrontOfList, examiningNewQueues, now);
  618. if (!entryToEmit) {
  619. //DEBUG_INFO("moving q=%p from OLD to INACTIVE list", queueAtFrontOfList);
  620. // Move to inactive list of queues
  621. inactiveQueues->push_back(queueAtFrontOfList);
  622. currQueues->erase(currQueues->begin());
  623. }
  624. else {
  625. int len = entryToEmit->packet.payloadLength();
  626. queueAtFrontOfList->byteLength -= len;
  627. queueAtFrontOfList->byteCredit -= len;
  628. queueAtFrontOfList->q.pop_front();
  629. send(tPtr, entryToEmit->packet, entryToEmit->encrypt);
  630. (*nqcb).second->_currEnqueuedPackets--;
  631. }
  632. if (queueAtFrontOfList) {
  633. //DEBUG_INFO("dequeuing from q=%p, len=%lu in OLD list (byteCredit=%d)", queueAtFrontOfList, queueAtFrontOfList->q.size(), queueAtFrontOfList->byteCredit);
  634. }
  635. break;
  636. }
  637. }
  638. nqcb++;
  639. _aqm_m.unlock();
  640. }
  641. }
  642. void Switch::removeNetworkQoSControlBlock(uint64_t nwid)
  643. {
  644. NetworkQoSControlBlock *nq = _netQueueControlBlock[nwid];
  645. if (nq) {
  646. _netQueueControlBlock.erase(nwid);
  647. delete nq;
  648. nq = NULL;
  649. }
  650. }
  651. void Switch::send(void *tPtr,Packet &packet,bool encrypt)
  652. {
  653. const Address dest(packet.destination());
  654. if (dest == RR->identity.address())
  655. return;
  656. if (!_trySend(tPtr,packet,encrypt)) {
  657. {
  658. Mutex::Lock _l(_txQueue_m);
  659. if (_txQueue.size() >= ZT_TX_QUEUE_SIZE) {
  660. _txQueue.pop_front();
  661. }
  662. _txQueue.push_back(TXQueueEntry(dest,RR->node->now(),packet,encrypt));
  663. }
  664. if (!RR->topology->get(dest))
  665. requestWhois(tPtr,RR->node->now(),dest);
  666. }
  667. }
  668. void Switch::requestWhois(void *tPtr,const int64_t now,const Address &addr)
  669. {
  670. if (addr == RR->identity.address())
  671. return;
  672. {
  673. Mutex::Lock _l(_lastSentWhoisRequest_m);
  674. int64_t &last = _lastSentWhoisRequest[addr];
  675. if ((now - last) < ZT_WHOIS_RETRY_DELAY)
  676. return;
  677. else last = now;
  678. }
  679. const SharedPtr<Peer> root(RR->topology->root(now));
  680. if (root) {
  681. Packet outp(root->address(),RR->identity.address(),Packet::VERB_WHOIS);
  682. addr.appendTo(outp);
  683. RR->node->expectReplyTo(outp.packetId());
  684. root->sendDirect(tPtr,outp.data(),outp.size(),now,true);
  685. }
  686. }
  687. void Switch::doAnythingWaitingForPeer(void *tPtr,const SharedPtr<Peer> &peer)
  688. {
  689. {
  690. Mutex::Lock _l(_lastSentWhoisRequest_m);
  691. _lastSentWhoisRequest.erase(peer->address());
  692. }
  693. const int64_t now = RR->node->now();
  694. for(unsigned int ptr=0;ptr<ZT_RX_QUEUE_SIZE;++ptr) {
  695. RXQueueEntry *const rq = &(_rxQueue[ptr]);
  696. Mutex::Lock rql(rq->lock);
  697. if ((rq->timestamp)&&(rq->complete)) {
  698. if ((rq->frag0.tryDecode(RR,tPtr))||((now - rq->timestamp) > ZT_RECEIVE_QUEUE_TIMEOUT))
  699. rq->timestamp = 0;
  700. }
  701. }
  702. {
  703. Mutex::Lock _l(_txQueue_m);
  704. for(std::list< TXQueueEntry >::iterator txi(_txQueue.begin());txi!=_txQueue.end();) {
  705. if (txi->dest == peer->address()) {
  706. if (_trySend(tPtr,txi->packet,txi->encrypt)) {
  707. _txQueue.erase(txi++);
  708. } else {
  709. ++txi;
  710. }
  711. } else {
  712. ++txi;
  713. }
  714. }
  715. }
  716. }
  717. unsigned long Switch::doTimerTasks(void *tPtr,int64_t now)
  718. {
  719. const uint64_t timeSinceLastCheck = now - _lastCheckedQueues;
  720. if (timeSinceLastCheck < ZT_WHOIS_RETRY_DELAY)
  721. return (unsigned long)(ZT_WHOIS_RETRY_DELAY - timeSinceLastCheck);
  722. _lastCheckedQueues = now;
  723. std::vector<Address> needWhois;
  724. {
  725. Mutex::Lock _l(_txQueue_m);
  726. for(std::list< TXQueueEntry >::iterator txi(_txQueue.begin());txi!=_txQueue.end();) {
  727. if (_trySend(tPtr,txi->packet,txi->encrypt)) {
  728. _txQueue.erase(txi++);
  729. } else if ((now - txi->creationTime) > ZT_TRANSMIT_QUEUE_TIMEOUT) {
  730. _txQueue.erase(txi++);
  731. } else {
  732. if (!RR->topology->get(txi->dest))
  733. needWhois.push_back(txi->dest);
  734. ++txi;
  735. }
  736. }
  737. }
  738. for(std::vector<Address>::const_iterator i(needWhois.begin());i!=needWhois.end();++i)
  739. requestWhois(tPtr,now,*i);
  740. for(unsigned int ptr=0;ptr<ZT_RX_QUEUE_SIZE;++ptr) {
  741. RXQueueEntry *const rq = &(_rxQueue[ptr]);
  742. Mutex::Lock rql(rq->lock);
  743. if ((rq->timestamp)&&(rq->complete)) {
  744. if ((rq->frag0.tryDecode(RR,tPtr))||((now - rq->timestamp) > ZT_RECEIVE_QUEUE_TIMEOUT)) {
  745. rq->timestamp = 0;
  746. } else {
  747. const Address src(rq->frag0.source());
  748. if (!RR->topology->get(src))
  749. requestWhois(tPtr,now,src);
  750. }
  751. }
  752. }
  753. {
  754. Mutex::Lock _l(_lastUniteAttempt_m);
  755. Hashtable< _LastUniteKey,uint64_t >::Iterator i(_lastUniteAttempt);
  756. _LastUniteKey *k = (_LastUniteKey *)0;
  757. uint64_t *v = (uint64_t *)0;
  758. while (i.next(k,v)) {
  759. if ((now - *v) >= (ZT_MIN_UNITE_INTERVAL * 8))
  760. _lastUniteAttempt.erase(*k);
  761. }
  762. }
  763. {
  764. Mutex::Lock _l(_lastSentWhoisRequest_m);
  765. Hashtable< Address,int64_t >::Iterator i(_lastSentWhoisRequest);
  766. Address *a = (Address *)0;
  767. int64_t *ts = (int64_t *)0;
  768. while (i.next(a,ts)) {
  769. if ((now - *ts) > (ZT_WHOIS_RETRY_DELAY * 2))
  770. _lastSentWhoisRequest.erase(*a);
  771. }
  772. }
  773. return ZT_WHOIS_RETRY_DELAY;
  774. }
  775. bool Switch::_shouldUnite(const int64_t now,const Address &source,const Address &destination)
  776. {
  777. Mutex::Lock _l(_lastUniteAttempt_m);
  778. uint64_t &ts = _lastUniteAttempt[_LastUniteKey(source,destination)];
  779. if ((now - ts) >= ZT_MIN_UNITE_INTERVAL) {
  780. ts = now;
  781. return true;
  782. }
  783. return false;
  784. }
  785. bool Switch::_trySend(void *tPtr,Packet &packet,bool encrypt)
  786. {
  787. SharedPtr<Path> viaPath;
  788. const int64_t now = RR->node->now();
  789. const Address destination(packet.destination());
  790. const SharedPtr<Peer> peer(RR->topology->get(destination));
  791. if (peer) {
  792. viaPath = peer->getAppropriatePath(now,false);
  793. if (!viaPath) {
  794. if (peer->rateGateTryStaticPath(now)) {
  795. InetAddress tryAddr;
  796. bool gotPath = RR->node->externalPathLookup(tPtr,peer->identity(),AF_INET6,tryAddr);
  797. if ((gotPath)&&(tryAddr)) {
  798. peer->sendHELLO(tPtr,-1,tryAddr,now);
  799. } else {
  800. gotPath = RR->node->externalPathLookup(tPtr,peer->identity(),AF_INET,tryAddr);
  801. if ((gotPath)&&(tryAddr))
  802. peer->sendHELLO(tPtr,-1,tryAddr,now);
  803. }
  804. }
  805. const SharedPtr<Peer> relay(RR->topology->findRelayTo(now,destination));
  806. if (relay) {
  807. viaPath = relay->getAppropriatePath(now,true);
  808. if (!viaPath)
  809. return false;
  810. }
  811. return false;
  812. }
  813. } else {
  814. return false;
  815. }
  816. unsigned int mtu = ZT_DEFAULT_PHYSMTU;
  817. uint64_t trustedPathId = 0;
  818. RR->topology->getOutboundPathInfo(viaPath->address(),mtu,trustedPathId);
  819. unsigned int chunkSize = std::min(packet.size(),mtu);
  820. packet.setFragmented(chunkSize < packet.size());
  821. peer->recordOutgoingPacket(viaPath, packet.packetId(), packet.payloadLength(), packet.verb(), now);
  822. if (trustedPathId) {
  823. packet.setTrusted(trustedPathId);
  824. } else {
  825. packet.armor(peer->key(),encrypt);
  826. }
  827. if (viaPath->send(RR,tPtr,packet.data(),chunkSize,now)) {
  828. if (chunkSize < packet.size()) {
  829. // Too big for one packet, fragment the rest
  830. unsigned int fragStart = chunkSize;
  831. unsigned int remaining = packet.size() - chunkSize;
  832. unsigned int fragsRemaining = (remaining / (mtu - ZT_PROTO_MIN_FRAGMENT_LENGTH));
  833. if ((fragsRemaining * (mtu - ZT_PROTO_MIN_FRAGMENT_LENGTH)) < remaining)
  834. ++fragsRemaining;
  835. const unsigned int totalFragments = fragsRemaining + 1;
  836. for(unsigned int fno=1;fno<totalFragments;++fno) {
  837. chunkSize = std::min(remaining,(unsigned int)(mtu - ZT_PROTO_MIN_FRAGMENT_LENGTH));
  838. Packet::Fragment frag(packet,fragStart,chunkSize,fno,totalFragments);
  839. viaPath->send(RR,tPtr,frag.data(),frag.size(),now);
  840. fragStart += chunkSize;
  841. remaining -= chunkSize;
  842. }
  843. }
  844. }
  845. return true;
  846. }
  847. } // namespace ZeroTier