Switch.cpp 35 KB

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