Switch.cpp 34 KB

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