Switch.cpp 39 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075
  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_EXT_FRAME);
  451. outp.append(network->id());
  452. outp.append((unsigned char)0x00);
  453. to.appendTo(outp);
  454. from.appendTo(outp);
  455. outp.append((uint16_t)etherType);
  456. outp.append(data,len);
  457. if (!network->config().disableCompression())
  458. outp.compress();
  459. aqm_enqueue(tPtr,network,outp,true,qosBucket,flowId);
  460. } else {
  461. Packet outp(toZT,RR->identity.address(),Packet::VERB_FRAME);
  462. outp.append(network->id());
  463. outp.append((uint16_t)etherType);
  464. outp.append(data,len);
  465. if (!network->config().disableCompression())
  466. outp.compress();
  467. aqm_enqueue(tPtr,network,outp,true,qosBucket,flowId);
  468. }
  469. } else {
  470. // Destination is bridged behind a remote peer
  471. // We filter with a NULL destination ZeroTier address first. Filtrations
  472. // for each ZT destination are also done below. This is the same rationale
  473. // and design as for multicast.
  474. if (!network->filterOutgoingPacket(tPtr,false,RR->identity.address(),Address(),from,to,(const uint8_t *)data,len,etherType,vlanId,qosBucket)) {
  475. RR->t->outgoingNetworkFrameDropped(tPtr,network,from,to,etherType,vlanId,len,"filter blocked");
  476. return;
  477. }
  478. Address bridges[ZT_MAX_BRIDGE_SPAM];
  479. unsigned int numBridges = 0;
  480. /* Create an array of up to ZT_MAX_BRIDGE_SPAM recipients for this bridged frame. */
  481. bridges[0] = network->findBridgeTo(to);
  482. std::vector<Address> activeBridges(network->config().activeBridges());
  483. if ((bridges[0])&&(bridges[0] != RR->identity.address())&&(network->config().permitsBridging(bridges[0]))) {
  484. /* We have a known bridge route for this MAC, send it there. */
  485. ++numBridges;
  486. } else if (!activeBridges.empty()) {
  487. /* If there is no known route, spam to up to ZT_MAX_BRIDGE_SPAM active
  488. * bridges. If someone responds, we'll learn the route. */
  489. std::vector<Address>::const_iterator ab(activeBridges.begin());
  490. if (activeBridges.size() <= ZT_MAX_BRIDGE_SPAM) {
  491. // If there are <= ZT_MAX_BRIDGE_SPAM active bridges, spam them all
  492. while (ab != activeBridges.end()) {
  493. bridges[numBridges++] = *ab;
  494. ++ab;
  495. }
  496. } else {
  497. // Otherwise pick a random set of them
  498. while (numBridges < ZT_MAX_BRIDGE_SPAM) {
  499. if (ab == activeBridges.end())
  500. ab = activeBridges.begin();
  501. if (((unsigned long)RR->node->prng() % (unsigned long)activeBridges.size()) == 0) {
  502. bridges[numBridges++] = *ab;
  503. ++ab;
  504. } else ++ab;
  505. }
  506. }
  507. }
  508. for(unsigned int b=0;b<numBridges;++b) {
  509. if (network->filterOutgoingPacket(tPtr,true,RR->identity.address(),bridges[b],from,to,(const uint8_t *)data,len,etherType,vlanId,qosBucket)) {
  510. Packet outp(bridges[b],RR->identity.address(),Packet::VERB_EXT_FRAME);
  511. outp.append(network->id());
  512. outp.append((uint8_t)0x00);
  513. to.appendTo(outp);
  514. from.appendTo(outp);
  515. outp.append((uint16_t)etherType);
  516. outp.append(data,len);
  517. if (!network->config().disableCompression())
  518. outp.compress();
  519. aqm_enqueue(tPtr,network,outp,true,qosBucket,flowId);
  520. } else {
  521. RR->t->outgoingNetworkFrameDropped(tPtr,network,from,to,etherType,vlanId,len,"filter blocked (bridge replication)");
  522. }
  523. }
  524. }
  525. }
  526. void Switch::aqm_enqueue(void *tPtr, const SharedPtr<Network> &network, Packet &packet,bool encrypt,int qosBucket,int32_t flowId)
  527. {
  528. if(!network->qosEnabled()) {
  529. send(tPtr, packet, encrypt, flowId);
  530. return;
  531. }
  532. NetworkQoSControlBlock *nqcb = _netQueueControlBlock[network->id()];
  533. if (!nqcb) {
  534. nqcb = new NetworkQoSControlBlock();
  535. _netQueueControlBlock[network->id()] = nqcb;
  536. // Initialize ZT_QOS_NUM_BUCKETS queues and place them in the INACTIVE list
  537. // These queues will be shuffled between the new/old/inactive lists by the enqueue/dequeue algorithm
  538. for (int i=0; i<ZT_AQM_NUM_BUCKETS; i++) {
  539. nqcb->inactiveQueues.push_back(new ManagedQueue(i));
  540. }
  541. }
  542. // Don't apply QoS scheduling to ZT protocol traffic
  543. if (packet.verb() != Packet::VERB_FRAME && packet.verb() != Packet::VERB_EXT_FRAME) {
  544. send(tPtr, packet, encrypt, flowId);
  545. }
  546. _aqm_m.lock();
  547. // Enqueue packet and move queue to appropriate list
  548. const Address dest(packet.destination());
  549. TXQueueEntry *txEntry = new TXQueueEntry(dest,RR->node->now(),packet,encrypt,flowId);
  550. ManagedQueue *selectedQueue = nullptr;
  551. for (size_t i=0; i<ZT_AQM_NUM_BUCKETS; i++) {
  552. if (i < nqcb->oldQueues.size()) { // search old queues first (I think this is best since old would imply most recent usage of the queue)
  553. if (nqcb->oldQueues[i]->id == qosBucket) {
  554. selectedQueue = nqcb->oldQueues[i];
  555. }
  556. } if (i < nqcb->newQueues.size()) { // search new queues (this would imply not often-used queues)
  557. if (nqcb->newQueues[i]->id == qosBucket) {
  558. selectedQueue = nqcb->newQueues[i];
  559. }
  560. } if (i < nqcb->inactiveQueues.size()) { // search inactive queues
  561. if (nqcb->inactiveQueues[i]->id == qosBucket) {
  562. selectedQueue = nqcb->inactiveQueues[i];
  563. // move queue to end of NEW queue list
  564. selectedQueue->byteCredit = ZT_AQM_QUANTUM;
  565. // DEBUG_INFO("moving q=%p from INACTIVE to NEW list", selectedQueue);
  566. nqcb->newQueues.push_back(selectedQueue);
  567. nqcb->inactiveQueues.erase(nqcb->inactiveQueues.begin() + i);
  568. }
  569. }
  570. }
  571. if (!selectedQueue) {
  572. return;
  573. }
  574. selectedQueue->q.push_back(txEntry);
  575. selectedQueue->byteLength+=txEntry->packet.payloadLength();
  576. nqcb->_currEnqueuedPackets++;
  577. // 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);
  578. // Drop a packet if necessary
  579. ManagedQueue *selectedQueueToDropFrom = nullptr;
  580. if (nqcb->_currEnqueuedPackets > ZT_AQM_MAX_ENQUEUED_PACKETS)
  581. {
  582. // DEBUG_INFO("too many enqueued packets (%d), finding packet to drop", nqcb->_currEnqueuedPackets);
  583. int maxQueueLength = 0;
  584. for (size_t i=0; i<ZT_AQM_NUM_BUCKETS; i++) {
  585. if (i < nqcb->oldQueues.size()) {
  586. if (nqcb->oldQueues[i]->byteLength > maxQueueLength) {
  587. maxQueueLength = nqcb->oldQueues[i]->byteLength;
  588. selectedQueueToDropFrom = nqcb->oldQueues[i];
  589. }
  590. } if (i < nqcb->newQueues.size()) {
  591. if (nqcb->newQueues[i]->byteLength > maxQueueLength) {
  592. maxQueueLength = nqcb->newQueues[i]->byteLength;
  593. selectedQueueToDropFrom = nqcb->newQueues[i];
  594. }
  595. } if (i < nqcb->inactiveQueues.size()) {
  596. if (nqcb->inactiveQueues[i]->byteLength > maxQueueLength) {
  597. maxQueueLength = nqcb->inactiveQueues[i]->byteLength;
  598. selectedQueueToDropFrom = nqcb->inactiveQueues[i];
  599. }
  600. }
  601. }
  602. if (selectedQueueToDropFrom) {
  603. // DEBUG_INFO("dropping packet from head of largest queue (%d payload bytes)", maxQueueLength);
  604. int sizeOfDroppedPacket = selectedQueueToDropFrom->q.front()->packet.payloadLength();
  605. delete selectedQueueToDropFrom->q.front();
  606. selectedQueueToDropFrom->q.pop_front();
  607. selectedQueueToDropFrom->byteLength-=sizeOfDroppedPacket;
  608. nqcb->_currEnqueuedPackets--;
  609. }
  610. }
  611. _aqm_m.unlock();
  612. aqm_dequeue(tPtr);
  613. }
  614. uint64_t Switch::control_law(uint64_t t, int count)
  615. {
  616. return (uint64_t)(t + ZT_AQM_INTERVAL / sqrt(count));
  617. }
  618. Switch::dqr Switch::dodequeue(ManagedQueue *q, uint64_t now)
  619. {
  620. dqr r;
  621. r.ok_to_drop = false;
  622. r.p = q->q.front();
  623. if (r.p == NULL) {
  624. q->first_above_time = 0;
  625. return r;
  626. }
  627. uint64_t sojourn_time = now - r.p->creationTime;
  628. if (sojourn_time < ZT_AQM_TARGET || q->byteLength <= ZT_DEFAULT_MTU) {
  629. // went below - stay below for at least interval
  630. q->first_above_time = 0;
  631. } else {
  632. if (q->first_above_time == 0) {
  633. // just went above from below. if still above at
  634. // first_above_time, will say it's ok to drop.
  635. q->first_above_time = now + ZT_AQM_INTERVAL;
  636. } else if (now >= q->first_above_time) {
  637. r.ok_to_drop = true;
  638. }
  639. }
  640. return r;
  641. }
  642. Switch::TXQueueEntry * Switch::CoDelDequeue(ManagedQueue *q, bool isNew, uint64_t now)
  643. {
  644. dqr r = dodequeue(q, now);
  645. if (q->dropping) {
  646. if (!r.ok_to_drop) {
  647. q->dropping = false;
  648. }
  649. while (now >= q->drop_next && q->dropping) {
  650. q->q.pop_front(); // drop
  651. r = dodequeue(q, now);
  652. if (!r.ok_to_drop) {
  653. // leave dropping state
  654. q->dropping = false;
  655. } else {
  656. ++(q->count);
  657. // schedule the next drop.
  658. q->drop_next = control_law(q->drop_next, q->count);
  659. }
  660. }
  661. } else if (r.ok_to_drop) {
  662. q->q.pop_front(); // drop
  663. r = dodequeue(q, now);
  664. q->dropping = true;
  665. q->count = (q->count > 2 && now - q->drop_next < 8*ZT_AQM_INTERVAL)?
  666. q->count - 2 : 1;
  667. q->drop_next = control_law(now, q->count);
  668. }
  669. return r.p;
  670. }
  671. void Switch::aqm_dequeue(void *tPtr)
  672. {
  673. // Cycle through network-specific QoS control blocks
  674. for(std::map<uint64_t,NetworkQoSControlBlock*>::iterator nqcb(_netQueueControlBlock.begin());nqcb!=_netQueueControlBlock.end();) {
  675. if (!(*nqcb).second->_currEnqueuedPackets) {
  676. return;
  677. }
  678. uint64_t now = RR->node->now();
  679. TXQueueEntry *entryToEmit = nullptr;
  680. std::vector<ManagedQueue*> *currQueues = &((*nqcb).second->newQueues);
  681. std::vector<ManagedQueue*> *oldQueues = &((*nqcb).second->oldQueues);
  682. std::vector<ManagedQueue*> *inactiveQueues = &((*nqcb).second->inactiveQueues);
  683. _aqm_m.lock();
  684. // Attempt dequeue from queues in NEW list
  685. bool examiningNewQueues = true;
  686. while (currQueues->size()) {
  687. ManagedQueue *queueAtFrontOfList = currQueues->front();
  688. if (queueAtFrontOfList->byteCredit < 0) {
  689. queueAtFrontOfList->byteCredit += ZT_AQM_QUANTUM;
  690. // Move to list of OLD queues
  691. // DEBUG_INFO("moving q=%p from NEW to OLD list", queueAtFrontOfList);
  692. oldQueues->push_back(queueAtFrontOfList);
  693. currQueues->erase(currQueues->begin());
  694. } else {
  695. entryToEmit = CoDelDequeue(queueAtFrontOfList, examiningNewQueues, now);
  696. if (!entryToEmit) {
  697. // Move to end of list of OLD queues
  698. // DEBUG_INFO("moving q=%p from NEW to OLD list", queueAtFrontOfList);
  699. oldQueues->push_back(queueAtFrontOfList);
  700. currQueues->erase(currQueues->begin());
  701. }
  702. else {
  703. int len = entryToEmit->packet.payloadLength();
  704. queueAtFrontOfList->byteLength -= len;
  705. queueAtFrontOfList->byteCredit -= len;
  706. // Send the packet!
  707. queueAtFrontOfList->q.pop_front();
  708. send(tPtr, entryToEmit->packet, entryToEmit->encrypt, entryToEmit->flowId);
  709. (*nqcb).second->_currEnqueuedPackets--;
  710. }
  711. if (queueAtFrontOfList) {
  712. //DEBUG_INFO("dequeuing from q=%p, len=%lu in NEW list (byteCredit=%d)", queueAtFrontOfList, queueAtFrontOfList->q.size(), queueAtFrontOfList->byteCredit);
  713. }
  714. break;
  715. }
  716. }
  717. // Attempt dequeue from queues in OLD list
  718. examiningNewQueues = false;
  719. currQueues = &((*nqcb).second->oldQueues);
  720. while (currQueues->size()) {
  721. ManagedQueue *queueAtFrontOfList = currQueues->front();
  722. if (queueAtFrontOfList->byteCredit < 0) {
  723. queueAtFrontOfList->byteCredit += ZT_AQM_QUANTUM;
  724. oldQueues->push_back(queueAtFrontOfList);
  725. currQueues->erase(currQueues->begin());
  726. } else {
  727. entryToEmit = CoDelDequeue(queueAtFrontOfList, examiningNewQueues, now);
  728. if (!entryToEmit) {
  729. //DEBUG_INFO("moving q=%p from OLD to INACTIVE list", queueAtFrontOfList);
  730. // Move to inactive list of queues
  731. inactiveQueues->push_back(queueAtFrontOfList);
  732. currQueues->erase(currQueues->begin());
  733. }
  734. else {
  735. int len = entryToEmit->packet.payloadLength();
  736. queueAtFrontOfList->byteLength -= len;
  737. queueAtFrontOfList->byteCredit -= len;
  738. queueAtFrontOfList->q.pop_front();
  739. send(tPtr, entryToEmit->packet, entryToEmit->encrypt, entryToEmit->flowId);
  740. (*nqcb).second->_currEnqueuedPackets--;
  741. }
  742. if (queueAtFrontOfList) {
  743. //DEBUG_INFO("dequeuing from q=%p, len=%lu in OLD list (byteCredit=%d)", queueAtFrontOfList, queueAtFrontOfList->q.size(), queueAtFrontOfList->byteCredit);
  744. }
  745. break;
  746. }
  747. }
  748. nqcb++;
  749. _aqm_m.unlock();
  750. }
  751. }
  752. void Switch::removeNetworkQoSControlBlock(uint64_t nwid)
  753. {
  754. NetworkQoSControlBlock *nq = _netQueueControlBlock[nwid];
  755. if (nq) {
  756. _netQueueControlBlock.erase(nwid);
  757. delete nq;
  758. nq = NULL;
  759. }
  760. }
  761. void Switch::send(void *tPtr,Packet &packet,bool encrypt,int32_t flowId)
  762. {
  763. const Address dest(packet.destination());
  764. if (dest == RR->identity.address())
  765. return;
  766. if (!_trySend(tPtr,packet,encrypt,flowId)) {
  767. {
  768. Mutex::Lock _l(_txQueue_m);
  769. if (_txQueue.size() >= ZT_TX_QUEUE_SIZE) {
  770. _txQueue.pop_front();
  771. }
  772. _txQueue.push_back(TXQueueEntry(dest,RR->node->now(),packet,encrypt,flowId));
  773. }
  774. if (!RR->topology->getPeer(tPtr,dest))
  775. requestWhois(tPtr,RR->node->now(),dest);
  776. }
  777. }
  778. void Switch::requestWhois(void *tPtr,const int64_t now,const Address &addr)
  779. {
  780. if (addr == RR->identity.address())
  781. return;
  782. {
  783. Mutex::Lock _l(_lastSentWhoisRequest_m);
  784. int64_t &last = _lastSentWhoisRequest[addr];
  785. if ((now - last) < ZT_WHOIS_RETRY_DELAY)
  786. return;
  787. else last = now;
  788. }
  789. const SharedPtr<Peer> upstream(RR->topology->getUpstreamPeer());
  790. if (upstream) {
  791. int32_t flowId = ZT_QOS_NO_FLOW;
  792. Packet outp(upstream->address(),RR->identity.address(),Packet::VERB_WHOIS);
  793. addr.appendTo(outp);
  794. send(tPtr,outp,true,flowId);
  795. }
  796. }
  797. void Switch::doAnythingWaitingForPeer(void *tPtr,const SharedPtr<Peer> &peer)
  798. {
  799. {
  800. Mutex::Lock _l(_lastSentWhoisRequest_m);
  801. _lastSentWhoisRequest.erase(peer->address());
  802. }
  803. const int64_t now = RR->node->now();
  804. for(unsigned int ptr=0;ptr<ZT_RX_QUEUE_SIZE;++ptr) {
  805. RXQueueEntry *const rq = &(_rxQueue[ptr]);
  806. Mutex::Lock rql(rq->lock);
  807. if ((rq->timestamp)&&(rq->complete)) {
  808. if ((rq->frag0.tryDecode(RR,tPtr,rq->flowId))||((now - rq->timestamp) > ZT_RECEIVE_QUEUE_TIMEOUT))
  809. rq->timestamp = 0;
  810. }
  811. }
  812. {
  813. Mutex::Lock _l(_txQueue_m);
  814. for(std::list< TXQueueEntry >::iterator txi(_txQueue.begin());txi!=_txQueue.end();) {
  815. if (txi->dest == peer->address()) {
  816. if (_trySend(tPtr,txi->packet,txi->encrypt,txi->flowId)) {
  817. _txQueue.erase(txi++);
  818. } else {
  819. ++txi;
  820. }
  821. } else {
  822. ++txi;
  823. }
  824. }
  825. }
  826. }
  827. unsigned long Switch::doTimerTasks(void *tPtr,int64_t now)
  828. {
  829. const uint64_t timeSinceLastCheck = now - _lastCheckedQueues;
  830. if (timeSinceLastCheck < ZT_WHOIS_RETRY_DELAY)
  831. return (unsigned long)(ZT_WHOIS_RETRY_DELAY - timeSinceLastCheck);
  832. _lastCheckedQueues = now;
  833. std::vector<Address> needWhois;
  834. {
  835. Mutex::Lock _l(_txQueue_m);
  836. for(std::list< TXQueueEntry >::iterator txi(_txQueue.begin());txi!=_txQueue.end();) {
  837. if (_trySend(tPtr,txi->packet,txi->encrypt,txi->flowId)) {
  838. _txQueue.erase(txi++);
  839. } else if ((now - txi->creationTime) > ZT_TRANSMIT_QUEUE_TIMEOUT) {
  840. _txQueue.erase(txi++);
  841. } else {
  842. if (!RR->topology->getPeer(tPtr,txi->dest))
  843. needWhois.push_back(txi->dest);
  844. ++txi;
  845. }
  846. }
  847. }
  848. for(std::vector<Address>::const_iterator i(needWhois.begin());i!=needWhois.end();++i)
  849. requestWhois(tPtr,now,*i);
  850. for(unsigned int ptr=0;ptr<ZT_RX_QUEUE_SIZE;++ptr) {
  851. RXQueueEntry *const rq = &(_rxQueue[ptr]);
  852. Mutex::Lock rql(rq->lock);
  853. if ((rq->timestamp)&&(rq->complete)) {
  854. if ((rq->frag0.tryDecode(RR,tPtr,rq->flowId))||((now - rq->timestamp) > ZT_RECEIVE_QUEUE_TIMEOUT)) {
  855. rq->timestamp = 0;
  856. } else {
  857. const Address src(rq->frag0.source());
  858. if (!RR->topology->getPeer(tPtr,src))
  859. requestWhois(tPtr,now,src);
  860. }
  861. }
  862. }
  863. {
  864. Mutex::Lock _l(_lastUniteAttempt_m);
  865. Hashtable< _LastUniteKey,uint64_t >::Iterator i(_lastUniteAttempt);
  866. _LastUniteKey *k = (_LastUniteKey *)0;
  867. uint64_t *v = (uint64_t *)0;
  868. while (i.next(k,v)) {
  869. if ((now - *v) >= (ZT_MIN_UNITE_INTERVAL * 8))
  870. _lastUniteAttempt.erase(*k);
  871. }
  872. }
  873. {
  874. Mutex::Lock _l(_lastSentWhoisRequest_m);
  875. Hashtable< Address,int64_t >::Iterator i(_lastSentWhoisRequest);
  876. Address *a = (Address *)0;
  877. int64_t *ts = (int64_t *)0;
  878. while (i.next(a,ts)) {
  879. if ((now - *ts) > (ZT_WHOIS_RETRY_DELAY * 2))
  880. _lastSentWhoisRequest.erase(*a);
  881. }
  882. }
  883. return ZT_WHOIS_RETRY_DELAY;
  884. }
  885. bool Switch::_shouldUnite(const int64_t now,const Address &source,const Address &destination)
  886. {
  887. Mutex::Lock _l(_lastUniteAttempt_m);
  888. uint64_t &ts = _lastUniteAttempt[_LastUniteKey(source,destination)];
  889. if ((now - ts) >= ZT_MIN_UNITE_INTERVAL) {
  890. ts = now;
  891. return true;
  892. }
  893. return false;
  894. }
  895. bool Switch::_trySend(void *tPtr,Packet &packet,bool encrypt,int32_t flowId)
  896. {
  897. SharedPtr<Path> viaPath;
  898. const int64_t now = RR->node->now();
  899. const Address destination(packet.destination());
  900. const SharedPtr<Peer> peer(RR->topology->getPeer(tPtr,destination));
  901. if (peer) {
  902. if ((peer->bondingPolicy() == ZT_BONDING_POLICY_BROADCAST)
  903. && (packet.verb() == Packet::VERB_FRAME || packet.verb() == Packet::VERB_EXT_FRAME)) {
  904. const SharedPtr<Peer> relay(RR->topology->getUpstreamPeer());
  905. Mutex::Lock _l(peer->_paths_m);
  906. for(int i=0;i<ZT_MAX_PEER_NETWORK_PATHS;++i) {
  907. if (peer->_paths[i].p && peer->_paths[i].p->alive(now)) {
  908. char pathStr[128];
  909. peer->_paths[i].p->address().toString(pathStr);
  910. _sendViaSpecificPath(tPtr,peer,peer->_paths[i].p,now,packet,encrypt,flowId);
  911. }
  912. }
  913. return true;
  914. }
  915. else {
  916. viaPath = peer->getAppropriatePath(now,false,flowId);
  917. if (!viaPath) {
  918. peer->tryMemorizedPath(tPtr,now); // periodically attempt memorized or statically defined paths, if any are known
  919. const SharedPtr<Peer> relay(RR->topology->getUpstreamPeer());
  920. if ( (!relay) || (!(viaPath = relay->getAppropriatePath(now,false,flowId))) ) {
  921. if (!(viaPath = peer->getAppropriatePath(now,true,flowId)))
  922. return false;
  923. }
  924. }
  925. if (viaPath) {
  926. _sendViaSpecificPath(tPtr,peer,viaPath,now,packet,encrypt,flowId);
  927. return true;
  928. }
  929. }
  930. }
  931. return false;
  932. }
  933. void Switch::_sendViaSpecificPath(void *tPtr,SharedPtr<Peer> peer,SharedPtr<Path> viaPath,int64_t now,Packet &packet,bool encrypt,int32_t flowId)
  934. {
  935. unsigned int mtu = ZT_DEFAULT_PHYSMTU;
  936. uint64_t trustedPathId = 0;
  937. RR->topology->getOutboundPathInfo(viaPath->address(),mtu,trustedPathId);
  938. unsigned int chunkSize = std::min(packet.size(),mtu);
  939. packet.setFragmented(chunkSize < packet.size());
  940. if (trustedPathId) {
  941. packet.setTrusted(trustedPathId);
  942. } else {
  943. Packet::Verb v = packet.verb();
  944. packet.armor(peer->key(),encrypt,peer->aesKeysIfSupported());
  945. RR->node->expectReplyTo(packet.packetId());
  946. }
  947. peer->recordOutgoingPacket(viaPath, packet.packetId(), packet.payloadLength(), packet.verb(), flowId, now);
  948. if (viaPath->send(RR,tPtr,packet.data(),chunkSize,now)) {
  949. if (chunkSize < packet.size()) {
  950. // Too big for one packet, fragment the rest
  951. unsigned int fragStart = chunkSize;
  952. unsigned int remaining = packet.size() - chunkSize;
  953. unsigned int fragsRemaining = (remaining / (mtu - ZT_PROTO_MIN_FRAGMENT_LENGTH));
  954. if ((fragsRemaining * (mtu - ZT_PROTO_MIN_FRAGMENT_LENGTH)) < remaining)
  955. ++fragsRemaining;
  956. const unsigned int totalFragments = fragsRemaining + 1;
  957. for(unsigned int fno=1;fno<totalFragments;++fno) {
  958. chunkSize = std::min(remaining,(unsigned int)(mtu - ZT_PROTO_MIN_FRAGMENT_LENGTH));
  959. Packet::Fragment frag(packet,fragStart,chunkSize,fno,totalFragments);
  960. viaPath->send(RR,tPtr,frag.data(),frag.size(),now);
  961. fragStart += chunkSize;
  962. remaining -= chunkSize;
  963. }
  964. }
  965. }
  966. }
  967. } // namespace ZeroTier