Switch.cpp 35 KB

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