Switch.cpp 32 KB

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