Switch.cpp 40 KB

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