1
0

Switch.cpp 40 KB

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