2
0

Switch.cpp 39 KB

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