Switch.cpp 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881
  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(void *tPtr,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(tPtr,beaconAddr,localAddr,fromAddr))
  74. return;
  75. const SharedPtr<Peer> peer(RR->topology->getPeer(tPtr,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,tPtr,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(tPtr,destination);
  102. if ((!relayTo)||(!relayTo->sendDirect(tPtr,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(tPtr,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,tPtr)) {
  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(tPtr,destination);
  182. if ((relayTo)&&(relayTo->sendDirect(tPtr,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(tPtr,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(tPtr,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(tPtr,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(tPtr,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,tPtr)) {
  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,tPtr)) {
  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(void *tPtr,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(tPtr,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(tPtr,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(tPtr,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. tPtr,
  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(tPtr,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(tPtr,toZT));
  462. if (!network->filterOutgoingPacket(tPtr,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(tPtr,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(tPtr,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(tPtr,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(tPtr,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(tPtr,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(void *tPtr,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(tPtr,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(void *tPtr,const Address &addr)
  556. {
  557. #ifdef ZT_TRACE
  558. if (addr == RR->identity.address()) {
  559. fprintf(stderr,"FATAL BUG: Switch::requestWhois() caught attempt to WHOIS self" ZT_EOL_S);
  560. abort();
  561. }
  562. #endif
  563. bool inserted = false;
  564. {
  565. Mutex::Lock _l(_outstandingWhoisRequests_m);
  566. WhoisRequest &r = _outstandingWhoisRequests[addr];
  567. if (r.lastSent) {
  568. r.retries = 0; // reset retry count if entry already existed, but keep waiting and retry again after normal timeout
  569. } else {
  570. r.lastSent = RR->node->now();
  571. inserted = true;
  572. }
  573. }
  574. if (inserted)
  575. _sendWhoisRequest(tPtr,addr,(const Address *)0,0);
  576. }
  577. void Switch::doAnythingWaitingForPeer(void *tPtr,const SharedPtr<Peer> &peer)
  578. {
  579. { // cancel pending WHOIS since we now know this peer
  580. Mutex::Lock _l(_outstandingWhoisRequests_m);
  581. _outstandingWhoisRequests.erase(peer->address());
  582. }
  583. { // finish processing any packets waiting on peer's public key / identity
  584. Mutex::Lock _l(_rxQueue_m);
  585. unsigned long i = ZT_RX_QUEUE_SIZE;
  586. while (i) {
  587. RXQueueEntry *rq = &(_rxQueue[--i]);
  588. if ((rq->timestamp)&&(rq->complete)) {
  589. if (rq->frag0.tryDecode(RR,tPtr))
  590. rq->timestamp = 0;
  591. }
  592. }
  593. }
  594. { // finish sending any packets waiting on peer's public key / identity
  595. Mutex::Lock _l(_txQueue_m);
  596. for(std::list< TXQueueEntry >::iterator txi(_txQueue.begin());txi!=_txQueue.end();) {
  597. if (txi->dest == peer->address()) {
  598. if (_trySend(tPtr,txi->packet,txi->encrypt))
  599. _txQueue.erase(txi++);
  600. else ++txi;
  601. } else ++txi;
  602. }
  603. }
  604. }
  605. unsigned long Switch::doTimerTasks(void *tPtr,uint64_t now)
  606. {
  607. unsigned long nextDelay = 0xffffffff; // ceiling delay, caller will cap to minimum
  608. { // Retry outstanding WHOIS requests
  609. Mutex::Lock _l(_outstandingWhoisRequests_m);
  610. Hashtable< Address,WhoisRequest >::Iterator i(_outstandingWhoisRequests);
  611. Address *a = (Address *)0;
  612. WhoisRequest *r = (WhoisRequest *)0;
  613. while (i.next(a,r)) {
  614. const unsigned long since = (unsigned long)(now - r->lastSent);
  615. if (since >= ZT_WHOIS_RETRY_DELAY) {
  616. if (r->retries >= ZT_MAX_WHOIS_RETRIES) {
  617. TRACE("WHOIS %s timed out",a->toString().c_str());
  618. _outstandingWhoisRequests.erase(*a);
  619. } else {
  620. r->lastSent = now;
  621. r->peersConsulted[r->retries] = _sendWhoisRequest(tPtr,*a,r->peersConsulted,(r->retries > 1) ? r->retries : 0);
  622. TRACE("WHOIS %s (retry %u)",a->toString().c_str(),r->retries);
  623. ++r->retries;
  624. nextDelay = std::min(nextDelay,(unsigned long)ZT_WHOIS_RETRY_DELAY);
  625. }
  626. } else {
  627. nextDelay = std::min(nextDelay,ZT_WHOIS_RETRY_DELAY - since);
  628. }
  629. }
  630. }
  631. { // Time out TX queue packets that never got WHOIS lookups or other info.
  632. Mutex::Lock _l(_txQueue_m);
  633. for(std::list< TXQueueEntry >::iterator txi(_txQueue.begin());txi!=_txQueue.end();) {
  634. if (_trySend(tPtr,txi->packet,txi->encrypt))
  635. _txQueue.erase(txi++);
  636. else if ((now - txi->creationTime) > ZT_TRANSMIT_QUEUE_TIMEOUT) {
  637. TRACE("TX %s -> %s timed out",txi->packet.source().toString().c_str(),txi->packet.destination().toString().c_str());
  638. _txQueue.erase(txi++);
  639. } else ++txi;
  640. }
  641. }
  642. { // Remove really old last unite attempt entries to keep table size controlled
  643. Mutex::Lock _l(_lastUniteAttempt_m);
  644. Hashtable< _LastUniteKey,uint64_t >::Iterator i(_lastUniteAttempt);
  645. _LastUniteKey *k = (_LastUniteKey *)0;
  646. uint64_t *v = (uint64_t *)0;
  647. while (i.next(k,v)) {
  648. if ((now - *v) >= (ZT_MIN_UNITE_INTERVAL * 8))
  649. _lastUniteAttempt.erase(*k);
  650. }
  651. }
  652. return nextDelay;
  653. }
  654. bool Switch::_shouldUnite(const uint64_t now,const Address &source,const Address &destination)
  655. {
  656. Mutex::Lock _l(_lastUniteAttempt_m);
  657. uint64_t &ts = _lastUniteAttempt[_LastUniteKey(source,destination)];
  658. if ((now - ts) >= ZT_MIN_UNITE_INTERVAL) {
  659. ts = now;
  660. return true;
  661. }
  662. return false;
  663. }
  664. Address Switch::_sendWhoisRequest(void *tPtr,const Address &addr,const Address *peersAlreadyConsulted,unsigned int numPeersAlreadyConsulted)
  665. {
  666. SharedPtr<Peer> upstream(RR->topology->getUpstreamPeer(peersAlreadyConsulted,numPeersAlreadyConsulted,false));
  667. if (upstream) {
  668. Packet outp(upstream->address(),RR->identity.address(),Packet::VERB_WHOIS);
  669. addr.appendTo(outp);
  670. RR->node->expectReplyTo(outp.packetId());
  671. send(tPtr,outp,true);
  672. }
  673. return Address();
  674. }
  675. bool Switch::_trySend(void *tPtr,Packet &packet,bool encrypt)
  676. {
  677. SharedPtr<Path> viaPath;
  678. const uint64_t now = RR->node->now();
  679. const Address destination(packet.destination());
  680. #ifdef ZT_ENABLE_CLUSTER
  681. uint64_t clusterMostRecentTs = 0;
  682. int clusterMostRecentMemberId = -1;
  683. uint8_t clusterPeerSecret[ZT_PEER_SECRET_KEY_LENGTH];
  684. if (RR->cluster)
  685. clusterMostRecentMemberId = RR->cluster->checkSendViaCluster(destination,clusterMostRecentTs,clusterPeerSecret);
  686. #endif
  687. const SharedPtr<Peer> peer(RR->topology->getPeer(tPtr,destination));
  688. if (peer) {
  689. /* First get the best path, and if it's dead (and this is not a root)
  690. * we attempt to re-activate that path but this packet will flow
  691. * upstream. If the path comes back alive, it will be used in the future.
  692. * For roots we don't do the alive check since roots are not required
  693. * to send heartbeats "down" and because we have to at least try to
  694. * go somewhere. */
  695. viaPath = peer->getBestPath(now,false);
  696. if ( (viaPath) && (!viaPath->alive(now)) && (!RR->topology->isUpstream(peer->identity())) ) {
  697. #ifdef ZT_ENABLE_CLUSTER
  698. if ((clusterMostRecentMemberId < 0)||(viaPath->lastIn() > clusterMostRecentTs)) {
  699. #endif
  700. if ((now - viaPath->lastOut()) > std::max((now - viaPath->lastIn()) * 4,(uint64_t)ZT_PATH_MIN_REACTIVATE_INTERVAL)) {
  701. peer->attemptToContactAt(tPtr,viaPath->localAddress(),viaPath->address(),now,false,viaPath->nextOutgoingCounter());
  702. viaPath->sent(now);
  703. }
  704. #ifdef ZT_ENABLE_CLUSTER
  705. }
  706. #endif
  707. viaPath.zero();
  708. }
  709. #ifdef ZT_ENABLE_CLUSTER
  710. if (clusterMostRecentMemberId >= 0) {
  711. if ((viaPath)&&(viaPath->lastIn() < clusterMostRecentTs))
  712. viaPath.zero();
  713. } else if (!viaPath) {
  714. #else
  715. if (!viaPath) {
  716. #endif
  717. peer->tryMemorizedPath(tPtr,now); // periodically attempt memorized or statically defined paths, if any are known
  718. const SharedPtr<Peer> relay(RR->topology->getUpstreamPeer());
  719. if ( (!relay) || (!(viaPath = relay->getBestPath(now,false))) ) {
  720. if (!(viaPath = peer->getBestPath(now,true)))
  721. return false;
  722. }
  723. #ifdef ZT_ENABLE_CLUSTER
  724. }
  725. #else
  726. }
  727. #endif
  728. } else {
  729. #ifdef ZT_ENABLE_CLUSTER
  730. if (clusterMostRecentMemberId < 0) {
  731. #else
  732. requestWhois(tPtr,destination);
  733. return false; // if we are not in cluster mode, there is no way we can send without knowing the peer directly
  734. #endif
  735. #ifdef ZT_ENABLE_CLUSTER
  736. }
  737. #endif
  738. }
  739. unsigned int chunkSize = std::min(packet.size(),(unsigned int)ZT_UDP_DEFAULT_PAYLOAD_MTU);
  740. packet.setFragmented(chunkSize < packet.size());
  741. #ifdef ZT_ENABLE_CLUSTER
  742. const uint64_t trustedPathId = (viaPath) ? RR->topology->getOutboundPathTrust(viaPath->address()) : 0;
  743. if (trustedPathId) {
  744. packet.setTrusted(trustedPathId);
  745. } else {
  746. packet.armor((clusterMostRecentMemberId >= 0) ? clusterPeerSecret : peer->key(),encrypt,(viaPath) ? viaPath->nextOutgoingCounter() : 0);
  747. }
  748. #else
  749. const uint64_t trustedPathId = RR->topology->getOutboundPathTrust(viaPath->address());
  750. if (trustedPathId) {
  751. packet.setTrusted(trustedPathId);
  752. } else {
  753. packet.armor(peer->key(),encrypt,viaPath->nextOutgoingCounter());
  754. }
  755. #endif
  756. #ifdef ZT_ENABLE_CLUSTER
  757. if ( ((viaPath)&&(viaPath->send(RR,tPtr,packet.data(),chunkSize,now))) || ((clusterMostRecentMemberId >= 0)&&(RR->cluster->sendViaCluster(clusterMostRecentMemberId,destination,packet.data(),chunkSize))) ) {
  758. #else
  759. if (viaPath->send(RR,tPtr,packet.data(),chunkSize,now)) {
  760. #endif
  761. if (chunkSize < packet.size()) {
  762. // Too big for one packet, fragment the rest
  763. unsigned int fragStart = chunkSize;
  764. unsigned int remaining = packet.size() - chunkSize;
  765. unsigned int fragsRemaining = (remaining / (ZT_UDP_DEFAULT_PAYLOAD_MTU - ZT_PROTO_MIN_FRAGMENT_LENGTH));
  766. if ((fragsRemaining * (ZT_UDP_DEFAULT_PAYLOAD_MTU - ZT_PROTO_MIN_FRAGMENT_LENGTH)) < remaining)
  767. ++fragsRemaining;
  768. const unsigned int totalFragments = fragsRemaining + 1;
  769. for(unsigned int fno=1;fno<totalFragments;++fno) {
  770. chunkSize = std::min(remaining,(unsigned int)(ZT_UDP_DEFAULT_PAYLOAD_MTU - ZT_PROTO_MIN_FRAGMENT_LENGTH));
  771. Packet::Fragment frag(packet,fragStart,chunkSize,fno,totalFragments);
  772. #ifdef ZT_ENABLE_CLUSTER
  773. if (viaPath)
  774. viaPath->send(RR,tPtr,frag.data(),frag.size(),now);
  775. else if (clusterMostRecentMemberId >= 0)
  776. RR->cluster->sendViaCluster(clusterMostRecentMemberId,destination,frag.data(),frag.size());
  777. #else
  778. viaPath->send(RR,tPtr,frag.data(),frag.size(),now);
  779. #endif
  780. fragStart += chunkSize;
  781. remaining -= chunkSize;
  782. }
  783. }
  784. }
  785. return true;
  786. }
  787. } // namespace ZeroTier