Switch.cpp 35 KB

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