Switch.cpp 31 KB

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