Switch.cpp 41 KB

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