Switch.cpp 29 KB

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