Switch.cpp 33 KB

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