Switch.cpp 39 KB

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