Switch.cpp 35 KB

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