Switch.cpp 33 KB

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