Switch.cpp 35 KB

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