Switch.cpp 42 KB

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