Switch.cpp 34 KB

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