Switch.cpp 32 KB

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