Switch.cpp 29 KB

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