Switch.cpp 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881
  1. /*
  2. * ZeroTier One - Network Virtualization Everywhere
  3. * Copyright (C) 2011-2015 ZeroTier, Inc.
  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. * ZeroTier may be used and distributed under the terms of the GPLv3, which
  21. * are available at: http://www.gnu.org/licenses/gpl-3.0.html
  22. *
  23. * If you would like to embed ZeroTier into a commercial application or
  24. * redistribute it in a modified binary form, please contact ZeroTier Networks
  25. * LLC. Start here: http://www.zerotier.com/
  26. */
  27. #include <stdio.h>
  28. #include <stdlib.h>
  29. #include <algorithm>
  30. #include <utility>
  31. #include <stdexcept>
  32. #include "../version.h"
  33. #include "../include/ZeroTierOne.h"
  34. #include "Constants.hpp"
  35. #include "RuntimeEnvironment.hpp"
  36. #include "Switch.hpp"
  37. #include "Node.hpp"
  38. #include "InetAddress.hpp"
  39. #include "Topology.hpp"
  40. #include "Peer.hpp"
  41. #include "AntiRecursion.hpp"
  42. #include "SelfAwareness.hpp"
  43. #include "Packet.hpp"
  44. #include "Cluster.hpp"
  45. namespace ZeroTier {
  46. #ifdef ZT_TRACE
  47. static const char *etherTypeName(const unsigned int etherType)
  48. {
  49. switch(etherType) {
  50. case ZT_ETHERTYPE_IPV4: return "IPV4";
  51. case ZT_ETHERTYPE_ARP: return "ARP";
  52. case ZT_ETHERTYPE_RARP: return "RARP";
  53. case ZT_ETHERTYPE_ATALK: return "ATALK";
  54. case ZT_ETHERTYPE_AARP: return "AARP";
  55. case ZT_ETHERTYPE_IPX_A: return "IPX_A";
  56. case ZT_ETHERTYPE_IPX_B: return "IPX_B";
  57. case ZT_ETHERTYPE_IPV6: return "IPV6";
  58. }
  59. return "UNKNOWN";
  60. }
  61. #endif // ZT_TRACE
  62. Switch::Switch(const RuntimeEnvironment *renv) :
  63. RR(renv),
  64. _lastBeaconResponse(0),
  65. _outstandingWhoisRequests(32),
  66. _defragQueue(32),
  67. _lastUniteAttempt(8) // only really used on root servers and upstreams, and it'll grow there just fine
  68. {
  69. }
  70. Switch::~Switch()
  71. {
  72. }
  73. void Switch::onRemotePacket(const InetAddress &localAddr,const InetAddress &fromAddr,const void *data,unsigned int len)
  74. {
  75. try {
  76. if (len == 13) {
  77. /* LEGACY: before VERB_PUSH_DIRECT_PATHS, peers used broadcast
  78. * announcements on the LAN to solve the 'same network problem.' We
  79. * no longer send these, but we'll listen for them for a while to
  80. * locate peers with versions <1.0.4. */
  81. Address beaconAddr(reinterpret_cast<const char *>(data) + 8,5);
  82. if (beaconAddr == RR->identity.address())
  83. return;
  84. SharedPtr<Peer> peer(RR->topology->getPeer(beaconAddr));
  85. if (peer) { // we'll only respond to beacons from known peers
  86. const uint64_t now = RR->node->now();
  87. if ((now - _lastBeaconResponse) >= 2500) { // limit rate of responses
  88. _lastBeaconResponse = now;
  89. Packet outp(peer->address(),RR->identity.address(),Packet::VERB_NOP);
  90. outp.armor(peer->key(),false);
  91. RR->node->putPacket(localAddr,fromAddr,outp.data(),outp.size());
  92. }
  93. }
  94. } else if (len > ZT_PROTO_MIN_FRAGMENT_LENGTH) {
  95. if (((const unsigned char *)data)[ZT_PACKET_FRAGMENT_IDX_FRAGMENT_INDICATOR] == ZT_PACKET_FRAGMENT_INDICATOR) {
  96. _handleRemotePacketFragment(localAddr,fromAddr,data,len);
  97. } else if (len >= ZT_PROTO_MIN_PACKET_LENGTH) {
  98. _handleRemotePacketHead(localAddr,fromAddr,data,len);
  99. }
  100. }
  101. } catch (std::exception &ex) {
  102. TRACE("dropped packet from %s: unexpected exception: %s",fromAddr.toString().c_str(),ex.what());
  103. } catch ( ... ) {
  104. TRACE("dropped packet from %s: unexpected exception: (unknown)",fromAddr.toString().c_str());
  105. }
  106. }
  107. 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)
  108. {
  109. SharedPtr<NetworkConfig> nconf(network->config2());
  110. if (!nconf)
  111. return;
  112. // Sanity check -- bridge loop? OS problem?
  113. if (to == network->mac())
  114. return;
  115. /* Check anti-recursion module to ensure that this is not ZeroTier talking over its own links.
  116. * Note: even when we introduce a more purposeful binding of the main UDP port, this can
  117. * still happen because Windows likes to send broadcasts over interfaces that have little
  118. * to do with their intended target audience. :P */
  119. if (!RR->antiRec->checkEthernetFrame(data,len)) {
  120. TRACE("%.16llx: rejected recursively addressed ZeroTier packet by tail match (type %s, length: %u)",network->id(),etherTypeName(etherType),len);
  121. return;
  122. }
  123. // Check to make sure this protocol is allowed on this network
  124. if (!nconf->permitsEtherType(etherType)) {
  125. TRACE("%.16llx: ignored tap: %s -> %s: ethertype %s not allowed on network %.16llx",network->id(),from.toString().c_str(),to.toString().c_str(),etherTypeName(etherType),(unsigned long long)network->id());
  126. return;
  127. }
  128. // Check if this packet is from someone other than the tap -- i.e. bridged in
  129. bool fromBridged = false;
  130. if (from != network->mac()) {
  131. if (!network->permitsBridging(RR->identity.address())) {
  132. 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));
  133. return;
  134. }
  135. fromBridged = true;
  136. }
  137. if (to.isMulticast()) {
  138. // Destination is a multicast address (including broadcast)
  139. MulticastGroup mg(to,0);
  140. if (to.isBroadcast()) {
  141. 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)) ) {
  142. /* IPv4 ARP is one of the few special cases that we impose upon what is
  143. * otherwise a straightforward Ethernet switch emulation. Vanilla ARP
  144. * is dumb old broadcast and simply doesn't scale. ZeroTier multicast
  145. * groups have an additional field called ADI (additional distinguishing
  146. * information) which was added specifically for ARP though it could
  147. * be used for other things too. We then take ARP broadcasts and turn
  148. * them into multicasts by stuffing the IP address being queried into
  149. * the 32-bit ADI field. In practice this uses our multicast pub/sub
  150. * system to implement a kind of extended/distributed ARP table. */
  151. mg = MulticastGroup::deriveMulticastGroupForAddressResolution(InetAddress(((const unsigned char *)data) + 24,4,0));
  152. } else if (!nconf->enableBroadcast()) {
  153. // Don't transmit broadcasts if this network doesn't want them
  154. TRACE("%.16llx: dropped broadcast since ff:ff:ff:ff:ff:ff is not enabled",network->id());
  155. return;
  156. }
  157. } else if ((etherType == ZT_ETHERTYPE_IPV6)&&(len >= (40 + 8 + 16))) {
  158. /* IPv6 NDP emulation on ZeroTier-RFC4193 addressed networks! This allows
  159. * for multicast-free operation in IPv6 networks, which both improves
  160. * performance and is friendlier to mobile and (especially) IoT devices.
  161. * In the future there may be a no-multicast build option for embedded
  162. * and IoT use and this will be the preferred addressing mode. Note that
  163. * it plays nice with our L2 emulation philosophy and even with bridging.
  164. * While "real" devices behind the bridge can't have ZT-RFC4193 addresses
  165. * themselves, they can look these addresses up with NDP and it will
  166. * work just fine. */
  167. if ((reinterpret_cast<const uint8_t *>(data)[6] == 0x3a)&&(reinterpret_cast<const uint8_t *>(data)[40] == 0x87)) { // ICMPv6 neighbor solicitation
  168. for(std::vector<InetAddress>::const_iterator sip(nconf->staticIps().begin()),sipend(nconf->staticIps().end());sip!=sipend;++sip) {
  169. if ((sip->ss_family == AF_INET6)&&(Utils::ntoh((uint16_t)reinterpret_cast<const struct sockaddr_in6 *>(&(*sip))->sin6_port) == 88)) {
  170. const uint8_t *my6 = reinterpret_cast<const uint8_t *>(reinterpret_cast<const struct sockaddr_in6 *>(&(*sip))->sin6_addr.s6_addr);
  171. if ((my6[0] == 0xfd)&&(my6[9] == 0x99)&&(my6[10] == 0x93)) { // ZT-RFC4193 == fd__:____:____:____:__99:93__:____:____ / 88
  172. const uint8_t *pkt6 = reinterpret_cast<const uint8_t *>(data) + 40 + 8;
  173. unsigned int ptr = 0;
  174. while (ptr != 11) {
  175. if (pkt6[ptr] != my6[ptr])
  176. break;
  177. ++ptr;
  178. }
  179. if (ptr == 11) { // /88 matches an assigned address on this network
  180. const Address atPeer(pkt6 + ptr,5);
  181. if (atPeer != RR->identity.address()) {
  182. const MAC atPeerMac(atPeer,network->id());
  183. TRACE("ZT-RFC4193 NDP emulation: %.16llx: forging response for %s/%s",network->id(),atPeer.toString().c_str(),atPeerMac.toString().c_str());
  184. uint8_t adv[72];
  185. adv[0] = 0x60; adv[1] = 0x00; adv[2] = 0x00; adv[3] = 0x00;
  186. adv[4] = 0x00; adv[5] = 0x20;
  187. adv[6] = 0x3a; adv[7] = 0xff;
  188. for(int i=0;i<16;++i) adv[8 + i] = pkt6[i];
  189. for(int i=0;i<16;++i) adv[24 + i] = my6[i];
  190. adv[40] = 0x88; adv[41] = 0x00;
  191. adv[42] = 0x00; adv[43] = 0x00; // future home of checksum
  192. adv[44] = 0x60; adv[45] = 0x00; adv[46] = 0x00; adv[47] = 0x00;
  193. for(int i=0;i<16;++i) adv[48 + i] = pkt6[i];
  194. adv[64] = 0x02; adv[65] = 0x01;
  195. adv[66] = atPeerMac[0]; adv[67] = atPeerMac[1]; adv[68] = atPeerMac[2]; adv[69] = atPeerMac[3]; adv[70] = atPeerMac[4]; adv[71] = atPeerMac[5];
  196. uint16_t pseudo_[36];
  197. uint8_t *const pseudo = reinterpret_cast<uint8_t *>(pseudo_);
  198. for(int i=0;i<32;++i) pseudo[i] = adv[8 + i];
  199. pseudo[32] = 0x00; pseudo[33] = 0x00; pseudo[34] = 0x00; pseudo[35] = 0x20;
  200. pseudo[36] = 0x00; pseudo[37] = 0x00; pseudo[38] = 0x00; pseudo[39] = 0x3a;
  201. for(int i=0;i<32;++i) pseudo[40 + i] = adv[40 + i];
  202. uint32_t checksum = 0;
  203. for(int i=0;i<36;++i) checksum += Utils::hton(pseudo_[i]);
  204. while ((checksum >> 16)) checksum = (checksum & 0xffff) + (checksum >> 16);
  205. checksum = ~checksum;
  206. adv[42] = (checksum >> 8) & 0xff;
  207. adv[43] = checksum & 0xff;
  208. RR->node->putFrame(network->id(),atPeerMac,from,ZT_ETHERTYPE_IPV6,0,adv,72);
  209. return; // stop processing: we have handled this frame with a spoofed local reply so no need to send it anywhere
  210. }
  211. }
  212. }
  213. }
  214. }
  215. }
  216. }
  217. /* Learn multicast groups for bridged-in hosts.
  218. * Note that some OSes, most notably Linux, do this for you by learning
  219. * multicast addresses on bridge interfaces and subscribing each slave.
  220. * But in that case this does no harm, as the sets are just merged. */
  221. if (fromBridged)
  222. network->learnBridgedMulticastGroup(mg,RR->node->now());
  223. //TRACE("%.16llx: MULTICAST %s -> %s %s %u",network->id(),from.toString().c_str(),mg.toString().c_str(),etherTypeName(etherType),len);
  224. RR->mc->send(
  225. ((!nconf->isPublic())&&(nconf->com())) ? &(nconf->com()) : (const CertificateOfMembership *)0,
  226. nconf->multicastLimit(),
  227. RR->node->now(),
  228. network->id(),
  229. nconf->activeBridges(),
  230. mg,
  231. (fromBridged) ? from : MAC(),
  232. etherType,
  233. data,
  234. len);
  235. return;
  236. }
  237. if (to[0] == MAC::firstOctetForNetwork(network->id())) {
  238. // Destination is another ZeroTier peer on the same network
  239. Address toZT(to.toAddress(network->id())); // since in-network MACs are derived from addresses and network IDs, we can reverse this
  240. SharedPtr<Peer> toPeer(RR->topology->getPeer(toZT));
  241. const bool includeCom = ( (nconf->isPrivate()) && (nconf->com()) && ((!toPeer)||(toPeer->needsOurNetworkMembershipCertificate(network->id(),RR->node->now(),true))) );
  242. if ((fromBridged)||(includeCom)) {
  243. Packet outp(toZT,RR->identity.address(),Packet::VERB_EXT_FRAME);
  244. outp.append(network->id());
  245. if (includeCom) {
  246. outp.append((unsigned char)0x01); // 0x01 -- COM included
  247. nconf->com().serialize(outp);
  248. } else {
  249. outp.append((unsigned char)0x00);
  250. }
  251. to.appendTo(outp);
  252. from.appendTo(outp);
  253. outp.append((uint16_t)etherType);
  254. outp.append(data,len);
  255. outp.compress();
  256. send(outp,true,network->id());
  257. } else {
  258. Packet outp(toZT,RR->identity.address(),Packet::VERB_FRAME);
  259. outp.append(network->id());
  260. outp.append((uint16_t)etherType);
  261. outp.append(data,len);
  262. outp.compress();
  263. send(outp,true,network->id());
  264. }
  265. //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);
  266. return;
  267. }
  268. {
  269. // Destination is bridged behind a remote peer
  270. Address bridges[ZT_MAX_BRIDGE_SPAM];
  271. unsigned int numBridges = 0;
  272. /* Create an array of up to ZT_MAX_BRIDGE_SPAM recipients for this bridged frame. */
  273. bridges[0] = network->findBridgeTo(to);
  274. if ((bridges[0])&&(bridges[0] != RR->identity.address())&&(network->permitsBridging(bridges[0]))) {
  275. /* We have a known bridge route for this MAC, send it there. */
  276. ++numBridges;
  277. } else if (!nconf->activeBridges().empty()) {
  278. /* If there is no known route, spam to up to ZT_MAX_BRIDGE_SPAM active
  279. * bridges. If someone responds, we'll learn the route. */
  280. std::vector<Address>::const_iterator ab(nconf->activeBridges().begin());
  281. if (nconf->activeBridges().size() <= ZT_MAX_BRIDGE_SPAM) {
  282. // If there are <= ZT_MAX_BRIDGE_SPAM active bridges, spam them all
  283. while (ab != nconf->activeBridges().end()) {
  284. bridges[numBridges++] = *ab;
  285. ++ab;
  286. }
  287. } else {
  288. // Otherwise pick a random set of them
  289. while (numBridges < ZT_MAX_BRIDGE_SPAM) {
  290. if (ab == nconf->activeBridges().end())
  291. ab = nconf->activeBridges().begin();
  292. if (((unsigned long)RR->node->prng() % (unsigned long)nconf->activeBridges().size()) == 0) {
  293. bridges[numBridges++] = *ab;
  294. ++ab;
  295. } else ++ab;
  296. }
  297. }
  298. }
  299. for(unsigned int b=0;b<numBridges;++b) {
  300. SharedPtr<Peer> bridgePeer(RR->topology->getPeer(bridges[b]));
  301. Packet outp(bridges[b],RR->identity.address(),Packet::VERB_EXT_FRAME);
  302. outp.append(network->id());
  303. if ( (nconf->isPrivate()) && (nconf->com()) && ((!bridgePeer)||(bridgePeer->needsOurNetworkMembershipCertificate(network->id(),RR->node->now(),true))) ) {
  304. outp.append((unsigned char)0x01); // 0x01 -- COM included
  305. nconf->com().serialize(outp);
  306. } else {
  307. outp.append((unsigned char)0);
  308. }
  309. to.appendTo(outp);
  310. from.appendTo(outp);
  311. outp.append((uint16_t)etherType);
  312. outp.append(data,len);
  313. outp.compress();
  314. send(outp,true,network->id());
  315. }
  316. }
  317. }
  318. void Switch::send(const Packet &packet,bool encrypt,uint64_t nwid)
  319. {
  320. if (packet.destination() == RR->identity.address()) {
  321. TRACE("BUG: caught attempt to send() to self, ignored");
  322. return;
  323. }
  324. //TRACE(">> %s to %s (%u bytes, encrypt==%d, nwid==%.16llx)",Packet::verbString(packet.verb()),packet.destination().toString().c_str(),packet.size(),(int)encrypt,nwid);
  325. if (!_trySend(packet,encrypt,nwid)) {
  326. Mutex::Lock _l(_txQueue_m);
  327. _txQueue.push_back(TXQueueEntry(packet.destination(),RR->node->now(),packet,encrypt,nwid));
  328. }
  329. }
  330. bool Switch::unite(const Address &p1,const Address &p2)
  331. {
  332. if ((p1 == RR->identity.address())||(p2 == RR->identity.address()))
  333. return false;
  334. SharedPtr<Peer> p1p = RR->topology->getPeer(p1);
  335. if (!p1p)
  336. return false;
  337. SharedPtr<Peer> p2p = RR->topology->getPeer(p2);
  338. if (!p2p)
  339. return false;
  340. const uint64_t now = RR->node->now();
  341. std::pair<InetAddress,InetAddress> cg(Peer::findCommonGround(*p1p,*p2p,now));
  342. if ((!(cg.first))||(cg.first.ipScope() != cg.second.ipScope()))
  343. return false;
  344. TRACE("unite: %s(%s) <> %s(%s)",p1.toString().c_str(),cg.second.toString().c_str(),p2.toString().c_str(),cg.first.toString().c_str());
  345. /* Tell P1 where to find P2 and vice versa, sending the packets to P1 and
  346. * P2 in randomized order in terms of which gets sent first. This is done
  347. * since in a few cases NAT-t can be sensitive to slight timing differences
  348. * in terms of when the two peers initiate. Normally this is accounted for
  349. * by the nearly-simultaneous RENDEZVOUS kickoff from the relay, but
  350. * given that relay are hosted on cloud providers this can in some
  351. * cases have a few ms of latency between packet departures. By randomizing
  352. * the order we make each attempted NAT-t favor one or the other going
  353. * first, meaning if it doesn't succeed the first time it might the second
  354. * and so forth. */
  355. unsigned int alt = (unsigned int)RR->node->prng() & 1;
  356. unsigned int completed = alt + 2;
  357. while (alt != completed) {
  358. if ((alt & 1) == 0) {
  359. // Tell p1 where to find p2.
  360. Packet outp(p1,RR->identity.address(),Packet::VERB_RENDEZVOUS);
  361. outp.append((unsigned char)0);
  362. p2.appendTo(outp);
  363. outp.append((uint16_t)cg.first.port());
  364. if (cg.first.isV6()) {
  365. outp.append((unsigned char)16);
  366. outp.append(cg.first.rawIpData(),16);
  367. } else {
  368. outp.append((unsigned char)4);
  369. outp.append(cg.first.rawIpData(),4);
  370. }
  371. outp.armor(p1p->key(),true);
  372. p1p->send(RR,outp.data(),outp.size(),now);
  373. } else {
  374. // Tell p2 where to find p1.
  375. Packet outp(p2,RR->identity.address(),Packet::VERB_RENDEZVOUS);
  376. outp.append((unsigned char)0);
  377. p1.appendTo(outp);
  378. outp.append((uint16_t)cg.second.port());
  379. if (cg.second.isV6()) {
  380. outp.append((unsigned char)16);
  381. outp.append(cg.second.rawIpData(),16);
  382. } else {
  383. outp.append((unsigned char)4);
  384. outp.append(cg.second.rawIpData(),4);
  385. }
  386. outp.armor(p2p->key(),true);
  387. p2p->send(RR,outp.data(),outp.size(),now);
  388. }
  389. ++alt; // counts up and also flips LSB
  390. }
  391. return true;
  392. }
  393. void Switch::rendezvous(const SharedPtr<Peer> &peer,const InetAddress &localAddr,const InetAddress &atAddr)
  394. {
  395. TRACE("sending NAT-t message to %s(%s)",peer->address().toString().c_str(),atAddr.toString().c_str());
  396. const uint64_t now = RR->node->now();
  397. peer->sendHELLO(RR,localAddr,atAddr,now,2); // first attempt: send low-TTL packet to 'open' local NAT
  398. {
  399. Mutex::Lock _l(_contactQueue_m);
  400. _contactQueue.push_back(ContactQueueEntry(peer,now + ZT_NAT_T_TACTICAL_ESCALATION_DELAY,localAddr,atAddr));
  401. }
  402. }
  403. void Switch::requestWhois(const Address &addr)
  404. {
  405. bool inserted = false;
  406. {
  407. Mutex::Lock _l(_outstandingWhoisRequests_m);
  408. WhoisRequest &r = _outstandingWhoisRequests[addr];
  409. if (r.lastSent) {
  410. r.retries = 0; // reset retry count if entry already existed, but keep waiting and retry again after normal timeout
  411. } else {
  412. r.lastSent = RR->node->now();
  413. inserted = true;
  414. }
  415. }
  416. if (inserted)
  417. _sendWhoisRequest(addr,(const Address *)0,0);
  418. }
  419. void Switch::cancelWhoisRequest(const Address &addr)
  420. {
  421. Mutex::Lock _l(_outstandingWhoisRequests_m);
  422. _outstandingWhoisRequests.erase(addr);
  423. }
  424. void Switch::doAnythingWaitingForPeer(const SharedPtr<Peer> &peer)
  425. {
  426. { // cancel pending WHOIS since we now know this peer
  427. Mutex::Lock _l(_outstandingWhoisRequests_m);
  428. _outstandingWhoisRequests.erase(peer->address());
  429. }
  430. { // finish processing any packets waiting on peer's public key / identity
  431. Mutex::Lock _l(_rxQueue_m);
  432. for(std::list< SharedPtr<IncomingPacket> >::iterator rxi(_rxQueue.begin());rxi!=_rxQueue.end();) {
  433. if ((*rxi)->tryDecode(RR,false))
  434. _rxQueue.erase(rxi++);
  435. else ++rxi;
  436. }
  437. }
  438. { // finish sending any packets waiting on peer's public key / identity
  439. Mutex::Lock _l(_txQueue_m);
  440. for(std::list< TXQueueEntry >::iterator txi(_txQueue.begin());txi!=_txQueue.end();) {
  441. if (txi->dest == peer->address()) {
  442. if (_trySend(txi->packet,txi->encrypt,txi->nwid))
  443. _txQueue.erase(txi++);
  444. else ++txi;
  445. } else ++txi;
  446. }
  447. }
  448. }
  449. unsigned long Switch::doTimerTasks(uint64_t now)
  450. {
  451. unsigned long nextDelay = 0xffffffff; // ceiling delay, caller will cap to minimum
  452. { // Iterate through NAT traversal strategies for entries in contact queue
  453. Mutex::Lock _l(_contactQueue_m);
  454. for(std::list<ContactQueueEntry>::iterator qi(_contactQueue.begin());qi!=_contactQueue.end();) {
  455. if (now >= qi->fireAtTime) {
  456. if (qi->peer->hasActiveDirectPath(now)) {
  457. // Cancel if connection has succeeded
  458. _contactQueue.erase(qi++);
  459. continue;
  460. } else {
  461. if (qi->strategyIteration == 0) {
  462. // First strategy: send packet directly to destination
  463. qi->peer->sendHELLO(RR,qi->localAddr,qi->inaddr,now);
  464. } else if (qi->strategyIteration <= 3) {
  465. // Strategies 1-3: try escalating ports for symmetric NATs that remap sequentially
  466. InetAddress tmpaddr(qi->inaddr);
  467. int p = (int)qi->inaddr.port() + qi->strategyIteration;
  468. if (p < 0xffff) {
  469. tmpaddr.setPort((unsigned int)p);
  470. qi->peer->sendHELLO(RR,qi->localAddr,tmpaddr,now);
  471. } else qi->strategyIteration = 5;
  472. } else {
  473. // All strategies tried, expire entry
  474. _contactQueue.erase(qi++);
  475. continue;
  476. }
  477. ++qi->strategyIteration;
  478. qi->fireAtTime = now + ZT_NAT_T_TACTICAL_ESCALATION_DELAY;
  479. nextDelay = std::min(nextDelay,(unsigned long)ZT_NAT_T_TACTICAL_ESCALATION_DELAY);
  480. }
  481. } else {
  482. nextDelay = std::min(nextDelay,(unsigned long)(qi->fireAtTime - now));
  483. }
  484. ++qi; // if qi was erased, loop will have continued before here
  485. }
  486. }
  487. { // Retry outstanding WHOIS requests
  488. Mutex::Lock _l(_outstandingWhoisRequests_m);
  489. Hashtable< Address,WhoisRequest >::Iterator i(_outstandingWhoisRequests);
  490. Address *a = (Address *)0;
  491. WhoisRequest *r = (WhoisRequest *)0;
  492. while (i.next(a,r)) {
  493. const unsigned long since = (unsigned long)(now - r->lastSent);
  494. if (since >= ZT_WHOIS_RETRY_DELAY) {
  495. if (r->retries >= ZT_MAX_WHOIS_RETRIES) {
  496. TRACE("WHOIS %s timed out",a->toString().c_str());
  497. _outstandingWhoisRequests.erase(*a);
  498. } else {
  499. r->lastSent = now;
  500. r->peersConsulted[r->retries] = _sendWhoisRequest(*a,r->peersConsulted,r->retries);
  501. ++r->retries;
  502. TRACE("WHOIS %s (retry %u)",a->toString().c_str(),r->retries);
  503. nextDelay = std::min(nextDelay,(unsigned long)ZT_WHOIS_RETRY_DELAY);
  504. }
  505. } else {
  506. nextDelay = std::min(nextDelay,ZT_WHOIS_RETRY_DELAY - since);
  507. }
  508. }
  509. }
  510. { // Time out TX queue packets that never got WHOIS lookups or other info.
  511. Mutex::Lock _l(_txQueue_m);
  512. for(std::list< TXQueueEntry >::iterator txi(_txQueue.begin());txi!=_txQueue.end();) {
  513. if (_trySend(txi->packet,txi->encrypt,txi->nwid))
  514. _txQueue.erase(txi++);
  515. else if ((now - txi->creationTime) > ZT_TRANSMIT_QUEUE_TIMEOUT) {
  516. TRACE("TX %s -> %s timed out",txi->packet.source().toString().c_str(),txi->packet.destination().toString().c_str());
  517. _txQueue.erase(txi++);
  518. } else ++txi;
  519. }
  520. }
  521. { // Time out RX queue packets that never got WHOIS lookups or other info.
  522. Mutex::Lock _l(_rxQueue_m);
  523. for(std::list< SharedPtr<IncomingPacket> >::iterator i(_rxQueue.begin());i!=_rxQueue.end();) {
  524. if ((now - (*i)->receiveTime()) > ZT_RECEIVE_QUEUE_TIMEOUT) {
  525. TRACE("RX %s -> %s timed out",(*i)->source().toString().c_str(),(*i)->destination().toString().c_str());
  526. _rxQueue.erase(i++);
  527. } else ++i;
  528. }
  529. }
  530. { // Time out packets that didn't get all their fragments.
  531. Mutex::Lock _l(_defragQueue_m);
  532. Hashtable< uint64_t,DefragQueueEntry >::Iterator i(_defragQueue);
  533. uint64_t *packetId = (uint64_t *)0;
  534. DefragQueueEntry *qe = (DefragQueueEntry *)0;
  535. while (i.next(packetId,qe)) {
  536. if ((now - qe->creationTime) > ZT_FRAGMENTED_PACKET_RECEIVE_TIMEOUT) {
  537. TRACE("incomplete fragmented packet %.16llx timed out, fragments discarded",*packetId);
  538. _defragQueue.erase(*packetId);
  539. }
  540. }
  541. }
  542. { // Remove really old last unite attempt entries to keep table size controlled
  543. Mutex::Lock _l(_lastUniteAttempt_m);
  544. Hashtable< _LastUniteKey,uint64_t >::Iterator i(_lastUniteAttempt);
  545. _LastUniteKey *k = (_LastUniteKey *)0;
  546. uint64_t *v = (uint64_t *)0;
  547. while (i.next(k,v)) {
  548. if ((now - *v) >= (ZT_MIN_UNITE_INTERVAL * 8))
  549. _lastUniteAttempt.erase(*k);
  550. }
  551. }
  552. return nextDelay;
  553. }
  554. void Switch::_handleRemotePacketFragment(const InetAddress &localAddr,const InetAddress &fromAddr,const void *data,unsigned int len)
  555. {
  556. Packet::Fragment fragment(data,len);
  557. Address destination(fragment.destination());
  558. if (destination != RR->identity.address()) {
  559. // Fragment is not for us, so try to relay it
  560. if (fragment.hops() < ZT_RELAY_MAX_HOPS) {
  561. fragment.incrementHops();
  562. // Note: we don't bother initiating NAT-t for fragments, since heads will set that off.
  563. // It wouldn't hurt anything, just redundant and unnecessary.
  564. SharedPtr<Peer> relayTo = RR->topology->getPeer(destination);
  565. if ((!relayTo)||(!relayTo->send(RR,fragment.data(),fragment.size(),RR->node->now()))) {
  566. #ifdef ZT_ENABLE_CLUSTER
  567. if (RR->cluster) {
  568. RR->cluster->sendViaCluster(Address(),destination,fragment.data(),fragment.size(),false);
  569. return;
  570. }
  571. #endif
  572. // Don't know peer or no direct path -- so relay via root server
  573. relayTo = RR->topology->getBestRoot();
  574. if (relayTo)
  575. relayTo->send(RR,fragment.data(),fragment.size(),RR->node->now());
  576. }
  577. } else {
  578. TRACE("dropped relay [fragment](%s) -> %s, max hops exceeded",fromAddr.toString().c_str(),destination.toString().c_str());
  579. }
  580. } else {
  581. // Fragment looks like ours
  582. uint64_t pid = fragment.packetId();
  583. unsigned int fno = fragment.fragmentNumber();
  584. unsigned int tf = fragment.totalFragments();
  585. if ((tf <= ZT_MAX_PACKET_FRAGMENTS)&&(fno < ZT_MAX_PACKET_FRAGMENTS)&&(fno > 0)&&(tf > 1)) {
  586. // Fragment appears basically sane. Its fragment number must be
  587. // 1 or more, since a Packet with fragmented bit set is fragment 0.
  588. // Total fragments must be more than 1, otherwise why are we
  589. // seeing a Packet::Fragment?
  590. Mutex::Lock _l(_defragQueue_m);
  591. DefragQueueEntry &dq = _defragQueue[pid];
  592. if (!dq.creationTime) {
  593. // We received a Packet::Fragment without its head, so queue it and wait
  594. dq.creationTime = RR->node->now();
  595. dq.frags[fno - 1] = fragment;
  596. dq.totalFragments = tf; // total fragment count is known
  597. dq.haveFragments = 1 << fno; // we have only this fragment
  598. //TRACE("fragment (%u/%u) of %.16llx from %s",fno + 1,tf,pid,fromAddr.toString().c_str());
  599. } else if (!(dq.haveFragments & (1 << fno))) {
  600. // We have other fragments and maybe the head, so add this one and check
  601. dq.frags[fno - 1] = fragment;
  602. dq.totalFragments = tf;
  603. //TRACE("fragment (%u/%u) of %.16llx from %s",fno + 1,tf,pid,fromAddr.toString().c_str());
  604. if (Utils::countBits(dq.haveFragments |= (1 << fno)) == tf) {
  605. // We have all fragments -- assemble and process full Packet
  606. //TRACE("packet %.16llx is complete, assembling and processing...",pid);
  607. SharedPtr<IncomingPacket> packet(dq.frag0);
  608. for(unsigned int f=1;f<tf;++f)
  609. packet->append(dq.frags[f - 1].payload(),dq.frags[f - 1].payloadLength());
  610. _defragQueue.erase(pid); // dq no longer valid after this
  611. if (!packet->tryDecode(RR,false)) {
  612. Mutex::Lock _l(_rxQueue_m);
  613. _rxQueue.push_back(packet);
  614. }
  615. }
  616. } // else this is a duplicate fragment, ignore
  617. }
  618. }
  619. }
  620. void Switch::_handleRemotePacketHead(const InetAddress &localAddr,const InetAddress &fromAddr,const void *data,unsigned int len)
  621. {
  622. const uint64_t now = RR->node->now();
  623. SharedPtr<IncomingPacket> packet(new IncomingPacket(data,len,localAddr,fromAddr,now));
  624. Address source(packet->source());
  625. Address destination(packet->destination());
  626. // Catch this and toss it -- it would never work, but it could happen if we somehow
  627. // mistakenly guessed an address we're bound to as a destination for another peer.
  628. if (source == RR->identity.address())
  629. return;
  630. //TRACE("<< %.16llx %s -> %s (size: %u)",(unsigned long long)packet->packetId(),source.toString().c_str(),destination.toString().c_str(),packet->size());
  631. if (destination != RR->identity.address()) {
  632. // Packet is not for us, so try to relay it
  633. if (packet->hops() < ZT_RELAY_MAX_HOPS) {
  634. packet->incrementHops();
  635. SharedPtr<Peer> relayTo = RR->topology->getPeer(destination);
  636. if ((relayTo)&&((relayTo->send(RR,packet->data(),packet->size(),now)))) {
  637. Mutex::Lock _l(_lastUniteAttempt_m);
  638. uint64_t &luts = _lastUniteAttempt[_LastUniteKey(source,destination)];
  639. if ((now - luts) >= ZT_MIN_UNITE_INTERVAL) {
  640. luts = now;
  641. unite(source,destination);
  642. }
  643. } else {
  644. #ifdef ZT_ENABLE_CLUSTER
  645. if (RR->cluster) {
  646. bool shouldUnite;
  647. {
  648. Mutex::Lock _l(_lastUniteAttempt_m);
  649. uint64_t &luts = _lastUniteAttempt[_LastUniteKey(source,destination)];
  650. shouldUnite = ((now - luts) >= ZT_MIN_UNITE_INTERVAL);
  651. if (shouldUnite)
  652. luts = now;
  653. }
  654. RR->cluster->sendViaCluster(source,destination,packet->data(),packet->size(),shouldUnite);
  655. return;
  656. }
  657. #endif
  658. relayTo = RR->topology->getBestRoot(&source,1,true);
  659. if (relayTo)
  660. relayTo->send(RR,packet->data(),packet->size(),now);
  661. }
  662. } else {
  663. TRACE("dropped relay %s(%s) -> %s, max hops exceeded",packet->source().toString().c_str(),fromAddr.toString().c_str(),destination.toString().c_str());
  664. }
  665. } else if (packet->fragmented()) {
  666. // Packet is the head of a fragmented packet series
  667. uint64_t pid = packet->packetId();
  668. Mutex::Lock _l(_defragQueue_m);
  669. DefragQueueEntry &dq = _defragQueue[pid];
  670. if (!dq.creationTime) {
  671. // If we have no other fragments yet, create an entry and save the head
  672. dq.creationTime = now;
  673. dq.frag0 = packet;
  674. dq.totalFragments = 0; // 0 == unknown, waiting for Packet::Fragment
  675. dq.haveFragments = 1; // head is first bit (left to right)
  676. //TRACE("fragment (0/?) of %.16llx from %s",pid,fromAddr.toString().c_str());
  677. } else if (!(dq.haveFragments & 1)) {
  678. // If we have other fragments but no head, see if we are complete with the head
  679. if ((dq.totalFragments)&&(Utils::countBits(dq.haveFragments |= 1) == dq.totalFragments)) {
  680. // We have all fragments -- assemble and process full Packet
  681. //TRACE("packet %.16llx is complete, assembling and processing...",pid);
  682. // packet already contains head, so append fragments
  683. for(unsigned int f=1;f<dq.totalFragments;++f)
  684. packet->append(dq.frags[f - 1].payload(),dq.frags[f - 1].payloadLength());
  685. _defragQueue.erase(pid); // dq no longer valid after this
  686. if (!packet->tryDecode(RR,false)) {
  687. Mutex::Lock _l(_rxQueue_m);
  688. _rxQueue.push_back(packet);
  689. }
  690. } else {
  691. // Still waiting on more fragments, so queue the head
  692. dq.frag0 = packet;
  693. }
  694. } // else this is a duplicate head, ignore
  695. } else {
  696. // Packet is unfragmented, so just process it
  697. if (!packet->tryDecode(RR,false)) {
  698. Mutex::Lock _l(_rxQueue_m);
  699. _rxQueue.push_back(packet);
  700. }
  701. }
  702. }
  703. Address Switch::_sendWhoisRequest(const Address &addr,const Address *peersAlreadyConsulted,unsigned int numPeersAlreadyConsulted)
  704. {
  705. SharedPtr<Peer> root(RR->topology->getBestRoot(peersAlreadyConsulted,numPeersAlreadyConsulted,false));
  706. if (root) {
  707. Packet outp(root->address(),RR->identity.address(),Packet::VERB_WHOIS);
  708. addr.appendTo(outp);
  709. outp.armor(root->key(),true);
  710. if (root->send(RR,outp.data(),outp.size(),RR->node->now()))
  711. return root->address();
  712. }
  713. return Address();
  714. }
  715. bool Switch::_trySend(const Packet &packet,bool encrypt,uint64_t nwid)
  716. {
  717. SharedPtr<Peer> peer(RR->topology->getPeer(packet.destination()));
  718. if (peer) {
  719. const uint64_t now = RR->node->now();
  720. SharedPtr<Network> network;
  721. SharedPtr<NetworkConfig> nconf;
  722. if (nwid) {
  723. network = RR->node->network(nwid);
  724. if (!network)
  725. return false; // we probably just left this network, let its packets die
  726. nconf = network->config2();
  727. if (!nconf)
  728. return false; // sanity check: unconfigured network? why are we trying to talk to it?
  729. }
  730. Path *viaPath = peer->getBestPath(now);
  731. SharedPtr<Peer> relay;
  732. if (!viaPath) {
  733. // See if this network has a preferred relay (if packet has an associated network)
  734. if (nconf) {
  735. unsigned int bestq = ~((unsigned int)0);
  736. for(std::vector< std::pair<Address,InetAddress> >::const_iterator r(nconf->relays().begin());r!=nconf->relays().end();++r) {
  737. if (r->first != peer->address()) {
  738. SharedPtr<Peer> rp(RR->topology->getPeer(r->first));
  739. if (rp) {
  740. const unsigned int q = rp->relayQuality(now);
  741. if (q < bestq) { // SUBTILE: < == don't use these if they are nil quality (unsigned int max), instead use a root
  742. bestq = q;
  743. rp.swap(relay);
  744. }
  745. }
  746. }
  747. }
  748. }
  749. // Otherwise relay off a root server
  750. if (!relay)
  751. relay = RR->topology->getBestRoot();
  752. if (!(relay)||(!(viaPath = relay->getBestPath(now))))
  753. return false; // no paths, no root servers?
  754. }
  755. if ((network)&&(relay)&&(network->isAllowed(peer))) {
  756. // Push hints for direct connectivity to this peer if we are relaying
  757. peer->pushDirectPaths(RR,viaPath,now,false);
  758. }
  759. Packet tmp(packet);
  760. unsigned int chunkSize = std::min(tmp.size(),(unsigned int)ZT_UDP_DEFAULT_PAYLOAD_MTU);
  761. tmp.setFragmented(chunkSize < tmp.size());
  762. tmp.armor(peer->key(),encrypt);
  763. if (viaPath->send(RR,tmp.data(),chunkSize,now)) {
  764. if (chunkSize < tmp.size()) {
  765. // Too big for one packet, fragment the rest
  766. unsigned int fragStart = chunkSize;
  767. unsigned int remaining = tmp.size() - chunkSize;
  768. unsigned int fragsRemaining = (remaining / (ZT_UDP_DEFAULT_PAYLOAD_MTU - ZT_PROTO_MIN_FRAGMENT_LENGTH));
  769. if ((fragsRemaining * (ZT_UDP_DEFAULT_PAYLOAD_MTU - ZT_PROTO_MIN_FRAGMENT_LENGTH)) < remaining)
  770. ++fragsRemaining;
  771. unsigned int totalFragments = fragsRemaining + 1;
  772. for(unsigned int fno=1;fno<totalFragments;++fno) {
  773. chunkSize = std::min(remaining,(unsigned int)(ZT_UDP_DEFAULT_PAYLOAD_MTU - ZT_PROTO_MIN_FRAGMENT_LENGTH));
  774. Packet::Fragment frag(tmp,fragStart,chunkSize,fno,totalFragments);
  775. viaPath->send(RR,frag.data(),frag.size(),now);
  776. fragStart += chunkSize;
  777. remaining -= chunkSize;
  778. }
  779. }
  780. return true;
  781. }
  782. } else {
  783. requestWhois(packet.destination());
  784. }
  785. return false;
  786. }
  787. } // namespace ZeroTier