Switch.cpp 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749
  1. /*
  2. * ZeroTier One - Network Virtualization Everywhere
  3. * Copyright (C) 2011-2017 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. _outstandingWhoisRequests(32),
  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 uint64_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,path->nextOutgoingCounter());
  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->amRoot()) && (!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. if (rq->packetId != fragmentPacketId) {
  108. // No packet found, so we received a fragment without its head.
  109. rq->timestamp = now;
  110. rq->packetId = fragmentPacketId;
  111. rq->frags[fragmentNumber - 1] = fragment;
  112. rq->totalFragments = totalFragments; // total fragment count is known
  113. rq->haveFragments = 1 << fragmentNumber; // we have only this fragment
  114. rq->complete = false;
  115. } else if (!(rq->haveFragments & (1 << fragmentNumber))) {
  116. // We have other fragments and maybe the head, so add this one and check
  117. rq->frags[fragmentNumber - 1] = fragment;
  118. rq->totalFragments = totalFragments;
  119. if (Utils::countBits(rq->haveFragments |= (1 << fragmentNumber)) == totalFragments) {
  120. // We have all fragments -- assemble and process full Packet
  121. for(unsigned int f=1;f<totalFragments;++f)
  122. rq->frag0.append(rq->frags[f - 1].payload(),rq->frags[f - 1].payloadLength());
  123. if (rq->frag0.tryDecode(RR,tPtr)) {
  124. rq->timestamp = 0; // packet decoded, free entry
  125. } else {
  126. rq->complete = true; // set complete flag but leave entry since it probably needs WHOIS or something
  127. }
  128. }
  129. } // else this is a duplicate fragment, ignore
  130. }
  131. }
  132. // --------------------------------------------------------------------
  133. } else if (len >= ZT_PROTO_MIN_PACKET_LENGTH) { // min length check is important!
  134. // Handle packet head -------------------------------------------------
  135. const Address destination(reinterpret_cast<const uint8_t *>(data) + 8,ZT_ADDRESS_LENGTH);
  136. const Address source(reinterpret_cast<const uint8_t *>(data) + 13,ZT_ADDRESS_LENGTH);
  137. if (source == RR->identity.address())
  138. return;
  139. if (destination != RR->identity.address()) {
  140. if ( (!RR->topology->amRoot()) && (!path->trustEstablished(now)) && (source != RR->identity.address()) )
  141. return;
  142. Packet packet(data,len);
  143. if (packet.hops() < ZT_RELAY_MAX_HOPS) {
  144. packet.incrementHops();
  145. SharedPtr<Peer> relayTo = RR->topology->getPeer(tPtr,destination);
  146. if ((relayTo)&&(relayTo->sendDirect(tPtr,packet.data(),packet.size(),now,false))) {
  147. if ((source != RR->identity.address())&&(_shouldUnite(now,source,destination))) { // don't send RENDEZVOUS for cluster frontplane relays
  148. const InetAddress *hintToSource = (InetAddress *)0;
  149. const InetAddress *hintToDest = (InetAddress *)0;
  150. InetAddress destV4,destV6;
  151. InetAddress sourceV4,sourceV6;
  152. relayTo->getRendezvousAddresses(now,destV4,destV6);
  153. const SharedPtr<Peer> sourcePeer(RR->topology->getPeer(tPtr,source));
  154. if (sourcePeer) {
  155. sourcePeer->getRendezvousAddresses(now,sourceV4,sourceV6);
  156. if ((destV6)&&(sourceV6)) {
  157. hintToSource = &destV6;
  158. hintToDest = &sourceV6;
  159. } else if ((destV4)&&(sourceV4)) {
  160. hintToSource = &destV4;
  161. hintToDest = &sourceV4;
  162. }
  163. if ((hintToSource)&&(hintToDest)) {
  164. unsigned int alt = (unsigned int)RR->node->prng() & 1; // randomize which hint we send first for obscure NAT-t reasons
  165. const unsigned int completed = alt + 2;
  166. while (alt != completed) {
  167. if ((alt & 1) == 0) {
  168. Packet outp(source,RR->identity.address(),Packet::VERB_RENDEZVOUS);
  169. outp.append((uint8_t)0);
  170. destination.appendTo(outp);
  171. outp.append((uint16_t)hintToSource->port());
  172. if (hintToSource->ss_family == AF_INET6) {
  173. outp.append((uint8_t)16);
  174. outp.append(hintToSource->rawIpData(),16);
  175. } else {
  176. outp.append((uint8_t)4);
  177. outp.append(hintToSource->rawIpData(),4);
  178. }
  179. send(tPtr,outp,true);
  180. } else {
  181. Packet outp(destination,RR->identity.address(),Packet::VERB_RENDEZVOUS);
  182. outp.append((uint8_t)0);
  183. source.appendTo(outp);
  184. outp.append((uint16_t)hintToDest->port());
  185. if (hintToDest->ss_family == AF_INET6) {
  186. outp.append((uint8_t)16);
  187. outp.append(hintToDest->rawIpData(),16);
  188. } else {
  189. outp.append((uint8_t)4);
  190. outp.append(hintToDest->rawIpData(),4);
  191. }
  192. send(tPtr,outp,true);
  193. }
  194. ++alt;
  195. }
  196. }
  197. }
  198. }
  199. } else {
  200. relayTo = RR->topology->getUpstreamPeer(&source,1,true);
  201. if (relayTo)
  202. relayTo->sendDirect(tPtr,packet.data(),packet.size(),now,true);
  203. }
  204. }
  205. } else if ((reinterpret_cast<const uint8_t *>(data)[ZT_PACKET_IDX_FLAGS] & ZT_PROTO_FLAG_FRAGMENTED) != 0) {
  206. // Packet is the head of a fragmented packet series
  207. const uint64_t packetId = (
  208. (((uint64_t)reinterpret_cast<const uint8_t *>(data)[0]) << 56) |
  209. (((uint64_t)reinterpret_cast<const uint8_t *>(data)[1]) << 48) |
  210. (((uint64_t)reinterpret_cast<const uint8_t *>(data)[2]) << 40) |
  211. (((uint64_t)reinterpret_cast<const uint8_t *>(data)[3]) << 32) |
  212. (((uint64_t)reinterpret_cast<const uint8_t *>(data)[4]) << 24) |
  213. (((uint64_t)reinterpret_cast<const uint8_t *>(data)[5]) << 16) |
  214. (((uint64_t)reinterpret_cast<const uint8_t *>(data)[6]) << 8) |
  215. ((uint64_t)reinterpret_cast<const uint8_t *>(data)[7])
  216. );
  217. RXQueueEntry *const rq = _findRXQueueEntry(packetId);
  218. if (rq->packetId != packetId) {
  219. // If we have no other fragments yet, create an entry and save the head
  220. rq->timestamp = now;
  221. rq->packetId = packetId;
  222. rq->frag0.init(data,len,path,now);
  223. rq->totalFragments = 0;
  224. rq->haveFragments = 1;
  225. rq->complete = false;
  226. } else if (!(rq->haveFragments & 1)) {
  227. // If we have other fragments but no head, see if we are complete with the head
  228. if ((rq->totalFragments > 1)&&(Utils::countBits(rq->haveFragments |= 1) == rq->totalFragments)) {
  229. // We have all fragments -- assemble and process full Packet
  230. rq->frag0.init(data,len,path,now);
  231. for(unsigned int f=1;f<rq->totalFragments;++f)
  232. rq->frag0.append(rq->frags[f - 1].payload(),rq->frags[f - 1].payloadLength());
  233. if (rq->frag0.tryDecode(RR,tPtr)) {
  234. rq->timestamp = 0; // packet decoded, free entry
  235. } else {
  236. rq->complete = true; // set complete flag but leave entry since it probably needs WHOIS or something
  237. }
  238. } else {
  239. // Still waiting on more fragments, but keep the head
  240. rq->frag0.init(data,len,path,now);
  241. }
  242. } // else this is a duplicate head, ignore
  243. } else {
  244. // Packet is unfragmented, so just process it
  245. IncomingPacket packet(data,len,path,now);
  246. if (!packet.tryDecode(RR,tPtr)) {
  247. RXQueueEntry *const rq = _nextRXQueueEntry();
  248. rq->timestamp = now;
  249. rq->packetId = packet.packetId();
  250. rq->frag0 = packet;
  251. rq->totalFragments = 1;
  252. rq->haveFragments = 1;
  253. rq->complete = true;
  254. }
  255. }
  256. // --------------------------------------------------------------------
  257. }
  258. }
  259. } catch ( ... ) {} // sanity check, should be caught elsewhere
  260. }
  261. 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)
  262. {
  263. if (!network->hasConfig())
  264. return;
  265. // Check if this packet is from someone other than the tap -- i.e. bridged in
  266. bool fromBridged;
  267. if ((fromBridged = (from != network->mac()))) {
  268. if (!network->config().permitsBridging(RR->identity.address())) {
  269. RR->t->outgoingNetworkFrameDropped(tPtr,network,from,to,etherType,vlanId,len,"not a bridge");
  270. return;
  271. }
  272. }
  273. if (to.isMulticast()) {
  274. MulticastGroup multicastGroup(to,0);
  275. if (to.isBroadcast()) {
  276. 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)) ) {
  277. /* IPv4 ARP is one of the few special cases that we impose upon what is
  278. * otherwise a straightforward Ethernet switch emulation. Vanilla ARP
  279. * is dumb old broadcast and simply doesn't scale. ZeroTier multicast
  280. * groups have an additional field called ADI (additional distinguishing
  281. * information) which was added specifically for ARP though it could
  282. * be used for other things too. We then take ARP broadcasts and turn
  283. * them into multicasts by stuffing the IP address being queried into
  284. * the 32-bit ADI field. In practice this uses our multicast pub/sub
  285. * system to implement a kind of extended/distributed ARP table. */
  286. multicastGroup = MulticastGroup::deriveMulticastGroupForAddressResolution(InetAddress(((const unsigned char *)data) + 24,4,0));
  287. } else if (!network->config().enableBroadcast()) {
  288. // Don't transmit broadcasts if this network doesn't want them
  289. RR->t->outgoingNetworkFrameDropped(tPtr,network,from,to,etherType,vlanId,len,"broadcast disabled");
  290. return;
  291. }
  292. } else if ((etherType == ZT_ETHERTYPE_IPV6)&&(len >= (40 + 8 + 16))) {
  293. // IPv6 NDP emulation for certain very special patterns of private IPv6 addresses -- if enabled
  294. if ((network->config().ndpEmulation())&&(reinterpret_cast<const uint8_t *>(data)[6] == 0x3a)&&(reinterpret_cast<const uint8_t *>(data)[40] == 0x87)) { // ICMPv6 neighbor solicitation
  295. Address v6EmbeddedAddress;
  296. const uint8_t *const pkt6 = reinterpret_cast<const uint8_t *>(data) + 40 + 8;
  297. const uint8_t *my6 = (const uint8_t *)0;
  298. // ZT-RFC4193 address: fdNN:NNNN:NNNN:NNNN:NN99:93DD:DDDD:DDDD / 88 (one /128 per actual host)
  299. // ZT-6PLANE address: fcXX:XXXX:XXDD:DDDD:DDDD:####:####:#### / 40 (one /80 per actual host)
  300. // (XX - lower 32 bits of network ID XORed with higher 32 bits)
  301. // For these to work, we must have a ZT-managed address assigned in one of the
  302. // above formats, and the query must match its prefix.
  303. for(unsigned int sipk=0;sipk<network->config().staticIpCount;++sipk) {
  304. const InetAddress *const sip = &(network->config().staticIps[sipk]);
  305. if (sip->ss_family == AF_INET6) {
  306. my6 = reinterpret_cast<const uint8_t *>(reinterpret_cast<const struct sockaddr_in6 *>(&(*sip))->sin6_addr.s6_addr);
  307. const unsigned int sipNetmaskBits = Utils::ntoh((uint16_t)reinterpret_cast<const struct sockaddr_in6 *>(&(*sip))->sin6_port);
  308. if ((sipNetmaskBits == 88)&&(my6[0] == 0xfd)&&(my6[9] == 0x99)&&(my6[10] == 0x93)) { // ZT-RFC4193 /88 ???
  309. unsigned int ptr = 0;
  310. while (ptr != 11) {
  311. if (pkt6[ptr] != my6[ptr])
  312. break;
  313. ++ptr;
  314. }
  315. if (ptr == 11) { // prefix match!
  316. v6EmbeddedAddress.setTo(pkt6 + ptr,5);
  317. break;
  318. }
  319. } else if (sipNetmaskBits == 40) { // ZT-6PLANE /40 ???
  320. const uint32_t nwid32 = (uint32_t)((network->id() ^ (network->id() >> 32)) & 0xffffffff);
  321. 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))) {
  322. unsigned int ptr = 0;
  323. while (ptr != 5) {
  324. if (pkt6[ptr] != my6[ptr])
  325. break;
  326. ++ptr;
  327. }
  328. if (ptr == 5) { // prefix match!
  329. v6EmbeddedAddress.setTo(pkt6 + ptr,5);
  330. break;
  331. }
  332. }
  333. }
  334. }
  335. }
  336. if ((v6EmbeddedAddress)&&(v6EmbeddedAddress != RR->identity.address())) {
  337. const MAC peerMac(v6EmbeddedAddress,network->id());
  338. uint8_t adv[72];
  339. adv[0] = 0x60; adv[1] = 0x00; adv[2] = 0x00; adv[3] = 0x00;
  340. adv[4] = 0x00; adv[5] = 0x20;
  341. adv[6] = 0x3a; adv[7] = 0xff;
  342. for(int i=0;i<16;++i) adv[8 + i] = pkt6[i];
  343. for(int i=0;i<16;++i) adv[24 + i] = my6[i];
  344. adv[40] = 0x88; adv[41] = 0x00;
  345. adv[42] = 0x00; adv[43] = 0x00; // future home of checksum
  346. adv[44] = 0x60; adv[45] = 0x00; adv[46] = 0x00; adv[47] = 0x00;
  347. for(int i=0;i<16;++i) adv[48 + i] = pkt6[i];
  348. adv[64] = 0x02; adv[65] = 0x01;
  349. adv[66] = peerMac[0]; adv[67] = peerMac[1]; adv[68] = peerMac[2]; adv[69] = peerMac[3]; adv[70] = peerMac[4]; adv[71] = peerMac[5];
  350. uint16_t pseudo_[36];
  351. uint8_t *const pseudo = reinterpret_cast<uint8_t *>(pseudo_);
  352. for(int i=0;i<32;++i) pseudo[i] = adv[8 + i];
  353. pseudo[32] = 0x00; pseudo[33] = 0x00; pseudo[34] = 0x00; pseudo[35] = 0x20;
  354. pseudo[36] = 0x00; pseudo[37] = 0x00; pseudo[38] = 0x00; pseudo[39] = 0x3a;
  355. for(int i=0;i<32;++i) pseudo[40 + i] = adv[40 + i];
  356. uint32_t checksum = 0;
  357. for(int i=0;i<36;++i) checksum += Utils::hton(pseudo_[i]);
  358. while ((checksum >> 16)) checksum = (checksum & 0xffff) + (checksum >> 16);
  359. checksum = ~checksum;
  360. adv[42] = (checksum >> 8) & 0xff;
  361. adv[43] = checksum & 0xff;
  362. RR->node->putFrame(tPtr,network->id(),network->userPtr(),peerMac,from,ZT_ETHERTYPE_IPV6,0,adv,72);
  363. return; // NDP emulation done. We have forged a "fake" reply, so no need to send actual NDP query.
  364. } // else no NDP emulation
  365. } // else no NDP emulation
  366. }
  367. // Check this after NDP emulation, since that has to be allowed in exactly this case
  368. if (network->config().multicastLimit == 0) {
  369. RR->t->outgoingNetworkFrameDropped(tPtr,network,from,to,etherType,vlanId,len,"multicast disabled");
  370. return;
  371. }
  372. /* Learn multicast groups for bridged-in hosts.
  373. * Note that some OSes, most notably Linux, do this for you by learning
  374. * multicast addresses on bridge interfaces and subscribing each slave.
  375. * But in that case this does no harm, as the sets are just merged. */
  376. if (fromBridged)
  377. network->learnBridgedMulticastGroup(tPtr,multicastGroup,RR->node->now());
  378. // First pass sets noTee to false, but noTee is set to true in OutboundMulticast to prevent duplicates.
  379. if (!network->filterOutgoingPacket(tPtr,false,RR->identity.address(),Address(),from,to,(const uint8_t *)data,len,etherType,vlanId)) {
  380. RR->t->outgoingNetworkFrameDropped(tPtr,network,from,to,etherType,vlanId,len,"filter blocked");
  381. return;
  382. }
  383. RR->mc->send(
  384. tPtr,
  385. network->config().multicastLimit,
  386. RR->node->now(),
  387. network->id(),
  388. network->config().disableCompression(),
  389. network->config().activeBridges(),
  390. multicastGroup,
  391. (fromBridged) ? from : MAC(),
  392. etherType,
  393. data,
  394. len);
  395. } else if (to == network->mac()) {
  396. // Destination is this node, so just reinject it
  397. RR->node->putFrame(tPtr,network->id(),network->userPtr(),from,to,etherType,vlanId,data,len);
  398. } else if (to[0] == MAC::firstOctetForNetwork(network->id())) {
  399. // Destination is another ZeroTier peer on the same network
  400. Address toZT(to.toAddress(network->id())); // since in-network MACs are derived from addresses and network IDs, we can reverse this
  401. SharedPtr<Peer> toPeer(RR->topology->getPeer(tPtr,toZT));
  402. if (!network->filterOutgoingPacket(tPtr,false,RR->identity.address(),toZT,from,to,(const uint8_t *)data,len,etherType,vlanId)) {
  403. RR->t->outgoingNetworkFrameDropped(tPtr,network,from,to,etherType,vlanId,len,"filter blocked");
  404. return;
  405. }
  406. if (fromBridged) {
  407. Packet outp(toZT,RR->identity.address(),Packet::VERB_EXT_FRAME);
  408. outp.append(network->id());
  409. outp.append((unsigned char)0x00);
  410. to.appendTo(outp);
  411. from.appendTo(outp);
  412. outp.append((uint16_t)etherType);
  413. outp.append(data,len);
  414. if (!network->config().disableCompression())
  415. outp.compress();
  416. send(tPtr,outp,true);
  417. } else {
  418. Packet outp(toZT,RR->identity.address(),Packet::VERB_FRAME);
  419. outp.append(network->id());
  420. outp.append((uint16_t)etherType);
  421. outp.append(data,len);
  422. if (!network->config().disableCompression())
  423. outp.compress();
  424. send(tPtr,outp,true);
  425. }
  426. } else {
  427. // Destination is bridged behind a remote peer
  428. // We filter with a NULL destination ZeroTier address first. Filtrations
  429. // for each ZT destination are also done below. This is the same rationale
  430. // and design as for multicast.
  431. if (!network->filterOutgoingPacket(tPtr,false,RR->identity.address(),Address(),from,to,(const uint8_t *)data,len,etherType,vlanId)) {
  432. RR->t->outgoingNetworkFrameDropped(tPtr,network,from,to,etherType,vlanId,len,"filter blocked");
  433. return;
  434. }
  435. Address bridges[ZT_MAX_BRIDGE_SPAM];
  436. unsigned int numBridges = 0;
  437. /* Create an array of up to ZT_MAX_BRIDGE_SPAM recipients for this bridged frame. */
  438. bridges[0] = network->findBridgeTo(to);
  439. std::vector<Address> activeBridges(network->config().activeBridges());
  440. if ((bridges[0])&&(bridges[0] != RR->identity.address())&&(network->config().permitsBridging(bridges[0]))) {
  441. /* We have a known bridge route for this MAC, send it there. */
  442. ++numBridges;
  443. } else if (!activeBridges.empty()) {
  444. /* If there is no known route, spam to up to ZT_MAX_BRIDGE_SPAM active
  445. * bridges. If someone responds, we'll learn the route. */
  446. std::vector<Address>::const_iterator ab(activeBridges.begin());
  447. if (activeBridges.size() <= ZT_MAX_BRIDGE_SPAM) {
  448. // If there are <= ZT_MAX_BRIDGE_SPAM active bridges, spam them all
  449. while (ab != activeBridges.end()) {
  450. bridges[numBridges++] = *ab;
  451. ++ab;
  452. }
  453. } else {
  454. // Otherwise pick a random set of them
  455. while (numBridges < ZT_MAX_BRIDGE_SPAM) {
  456. if (ab == activeBridges.end())
  457. ab = activeBridges.begin();
  458. if (((unsigned long)RR->node->prng() % (unsigned long)activeBridges.size()) == 0) {
  459. bridges[numBridges++] = *ab;
  460. ++ab;
  461. } else ++ab;
  462. }
  463. }
  464. }
  465. for(unsigned int b=0;b<numBridges;++b) {
  466. if (network->filterOutgoingPacket(tPtr,true,RR->identity.address(),bridges[b],from,to,(const uint8_t *)data,len,etherType,vlanId)) {
  467. Packet outp(bridges[b],RR->identity.address(),Packet::VERB_EXT_FRAME);
  468. outp.append(network->id());
  469. outp.append((uint8_t)0x00);
  470. to.appendTo(outp);
  471. from.appendTo(outp);
  472. outp.append((uint16_t)etherType);
  473. outp.append(data,len);
  474. if (!network->config().disableCompression())
  475. outp.compress();
  476. send(tPtr,outp,true);
  477. } else {
  478. RR->t->outgoingNetworkFrameDropped(tPtr,network,from,to,etherType,vlanId,len,"filter blocked (bridge replication)");
  479. }
  480. }
  481. }
  482. }
  483. void Switch::send(void *tPtr,Packet &packet,bool encrypt)
  484. {
  485. if (packet.destination() == RR->identity.address())
  486. return;
  487. if (!_trySend(tPtr,packet,encrypt)) {
  488. Mutex::Lock _l(_txQueue_m);
  489. _txQueue.push_back(TXQueueEntry(packet.destination(),RR->node->now(),packet,encrypt));
  490. }
  491. }
  492. void Switch::requestWhois(void *tPtr,const Address &addr)
  493. {
  494. if (addr == RR->identity.address())
  495. return;
  496. bool inserted = false;
  497. {
  498. Mutex::Lock _l(_outstandingWhoisRequests_m);
  499. WhoisRequest &r = _outstandingWhoisRequests[addr];
  500. if (r.lastSent) {
  501. r.retries = 0; // reset retry count if entry already existed, but keep waiting and retry again after normal timeout
  502. } else {
  503. r.lastSent = RR->node->now();
  504. inserted = true;
  505. }
  506. }
  507. if (inserted)
  508. _sendWhoisRequest(tPtr,addr,(const Address *)0,0);
  509. }
  510. void Switch::doAnythingWaitingForPeer(void *tPtr,const SharedPtr<Peer> &peer)
  511. {
  512. { // cancel pending WHOIS since we now know this peer
  513. Mutex::Lock _l(_outstandingWhoisRequests_m);
  514. _outstandingWhoisRequests.erase(peer->address());
  515. }
  516. // finish processing any packets waiting on peer's public key / identity
  517. const uint64_t now = RR->node->now();
  518. for(unsigned int ptr=0;ptr<ZT_RX_QUEUE_SIZE;++ptr) {
  519. RXQueueEntry *const rq = &(_rxQueue[ptr]);
  520. if ((rq->timestamp)&&(rq->complete)) {
  521. if ((rq->frag0.tryDecode(RR,tPtr))||((now - rq->timestamp) > ZT_RECEIVE_QUEUE_TIMEOUT))
  522. rq->timestamp = 0;
  523. }
  524. }
  525. { // finish sending any packets waiting on peer's public key / identity
  526. Mutex::Lock _l(_txQueue_m);
  527. for(std::list< TXQueueEntry >::iterator txi(_txQueue.begin());txi!=_txQueue.end();) {
  528. if (txi->dest == peer->address()) {
  529. if (_trySend(tPtr,txi->packet,txi->encrypt))
  530. _txQueue.erase(txi++);
  531. else ++txi;
  532. } else ++txi;
  533. }
  534. }
  535. }
  536. unsigned long Switch::doTimerTasks(void *tPtr,uint64_t now)
  537. {
  538. unsigned long nextDelay = 0xffffffff; // ceiling delay, caller will cap to minimum
  539. { // Retry outstanding WHOIS requests
  540. Mutex::Lock _l(_outstandingWhoisRequests_m);
  541. Hashtable< Address,WhoisRequest >::Iterator i(_outstandingWhoisRequests);
  542. Address *a = (Address *)0;
  543. WhoisRequest *r = (WhoisRequest *)0;
  544. while (i.next(a,r)) {
  545. const unsigned long since = (unsigned long)(now - r->lastSent);
  546. if (since >= ZT_WHOIS_RETRY_DELAY) {
  547. if (r->retries >= ZT_MAX_WHOIS_RETRIES) {
  548. _outstandingWhoisRequests.erase(*a);
  549. } else {
  550. r->lastSent = now;
  551. r->peersConsulted[r->retries] = _sendWhoisRequest(tPtr,*a,r->peersConsulted,(r->retries > 1) ? r->retries : 0);
  552. ++r->retries;
  553. nextDelay = std::min(nextDelay,(unsigned long)ZT_WHOIS_RETRY_DELAY);
  554. }
  555. } else {
  556. nextDelay = std::min(nextDelay,ZT_WHOIS_RETRY_DELAY - since);
  557. }
  558. }
  559. }
  560. { // Time out TX queue packets that never got WHOIS lookups or other info.
  561. Mutex::Lock _l(_txQueue_m);
  562. for(std::list< TXQueueEntry >::iterator txi(_txQueue.begin());txi!=_txQueue.end();) {
  563. if (_trySend(tPtr,txi->packet,txi->encrypt))
  564. _txQueue.erase(txi++);
  565. else if ((now - txi->creationTime) > ZT_TRANSMIT_QUEUE_TIMEOUT) {
  566. RR->t->txTimedOut(tPtr,txi->dest);
  567. _txQueue.erase(txi++);
  568. } else ++txi;
  569. }
  570. }
  571. { // Remove really old last unite attempt entries to keep table size controlled
  572. Mutex::Lock _l(_lastUniteAttempt_m);
  573. Hashtable< _LastUniteKey,uint64_t >::Iterator i(_lastUniteAttempt);
  574. _LastUniteKey *k = (_LastUniteKey *)0;
  575. uint64_t *v = (uint64_t *)0;
  576. while (i.next(k,v)) {
  577. if ((now - *v) >= (ZT_MIN_UNITE_INTERVAL * 8))
  578. _lastUniteAttempt.erase(*k);
  579. }
  580. }
  581. return nextDelay;
  582. }
  583. bool Switch::_shouldUnite(const uint64_t now,const Address &source,const Address &destination)
  584. {
  585. Mutex::Lock _l(_lastUniteAttempt_m);
  586. uint64_t &ts = _lastUniteAttempt[_LastUniteKey(source,destination)];
  587. if ((now - ts) >= ZT_MIN_UNITE_INTERVAL) {
  588. ts = now;
  589. return true;
  590. }
  591. return false;
  592. }
  593. Address Switch::_sendWhoisRequest(void *tPtr,const Address &addr,const Address *peersAlreadyConsulted,unsigned int numPeersAlreadyConsulted)
  594. {
  595. SharedPtr<Peer> upstream(RR->topology->getUpstreamPeer(peersAlreadyConsulted,numPeersAlreadyConsulted,false));
  596. if (upstream) {
  597. Packet outp(upstream->address(),RR->identity.address(),Packet::VERB_WHOIS);
  598. addr.appendTo(outp);
  599. RR->node->expectReplyTo(outp.packetId());
  600. send(tPtr,outp,true);
  601. }
  602. return Address();
  603. }
  604. bool Switch::_trySend(void *tPtr,Packet &packet,bool encrypt)
  605. {
  606. SharedPtr<Path> viaPath;
  607. const uint64_t now = RR->node->now();
  608. const Address destination(packet.destination());
  609. const SharedPtr<Peer> peer(RR->topology->getPeer(tPtr,destination));
  610. if (peer) {
  611. /* First get the best path, and if it's dead (and this is not a root)
  612. * we attempt to re-activate that path but this packet will flow
  613. * upstream. If the path comes back alive, it will be used in the future.
  614. * For roots we don't do the alive check since roots are not required
  615. * to send heartbeats "down" and because we have to at least try to
  616. * go somewhere. */
  617. viaPath = peer->getBestPath(now,false);
  618. if ( (viaPath) && (!viaPath->alive(now)) && (!RR->topology->isUpstream(peer->identity())) ) {
  619. if ((now - viaPath->lastOut()) > std::max((now - viaPath->lastIn()) * 4,(uint64_t)ZT_PATH_MIN_REACTIVATE_INTERVAL)) {
  620. peer->attemptToContactAt(tPtr,viaPath->localSocket(),viaPath->address(),now,false,viaPath->nextOutgoingCounter());
  621. viaPath->sent(now);
  622. }
  623. viaPath.zero();
  624. }
  625. if (!viaPath) {
  626. peer->tryMemorizedPath(tPtr,now); // periodically attempt memorized or statically defined paths, if any are known
  627. const SharedPtr<Peer> relay(RR->topology->getUpstreamPeer());
  628. if ( (!relay) || (!(viaPath = relay->getBestPath(now,false))) ) {
  629. if (!(viaPath = peer->getBestPath(now,true)))
  630. return false;
  631. }
  632. }
  633. } else {
  634. requestWhois(tPtr,destination);
  635. return false; // if we are not in cluster mode, there is no way we can send without knowing the peer directly
  636. }
  637. unsigned int chunkSize = std::min(packet.size(),(unsigned int)ZT_UDP_DEFAULT_PAYLOAD_MTU);
  638. packet.setFragmented(chunkSize < packet.size());
  639. const uint64_t trustedPathId = RR->topology->getOutboundPathTrust(viaPath->address());
  640. if (trustedPathId) {
  641. packet.setTrusted(trustedPathId);
  642. } else {
  643. packet.armor(peer->key(),encrypt,viaPath->nextOutgoingCounter());
  644. }
  645. if (viaPath->send(RR,tPtr,packet.data(),chunkSize,now)) {
  646. if (chunkSize < packet.size()) {
  647. // Too big for one packet, fragment the rest
  648. unsigned int fragStart = chunkSize;
  649. unsigned int remaining = packet.size() - chunkSize;
  650. unsigned int fragsRemaining = (remaining / (ZT_UDP_DEFAULT_PAYLOAD_MTU - ZT_PROTO_MIN_FRAGMENT_LENGTH));
  651. if ((fragsRemaining * (ZT_UDP_DEFAULT_PAYLOAD_MTU - ZT_PROTO_MIN_FRAGMENT_LENGTH)) < remaining)
  652. ++fragsRemaining;
  653. const unsigned int totalFragments = fragsRemaining + 1;
  654. for(unsigned int fno=1;fno<totalFragments;++fno) {
  655. chunkSize = std::min(remaining,(unsigned int)(ZT_UDP_DEFAULT_PAYLOAD_MTU - ZT_PROTO_MIN_FRAGMENT_LENGTH));
  656. Packet::Fragment frag(packet,fragStart,chunkSize,fno,totalFragments);
  657. viaPath->send(RR,tPtr,frag.data(),frag.size(),now);
  658. fragStart += chunkSize;
  659. remaining -= chunkSize;
  660. }
  661. }
  662. }
  663. return true;
  664. }
  665. } // namespace ZeroTier