Switch.cpp 35 KB

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