Switch.cpp 42 KB

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