Switch.cpp 30 KB

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