Switch.cpp 32 KB

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