2
0

Switch.cpp 42 KB

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