Switch.cpp 33 KB

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