Switch.cpp 33 KB

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