Switch.cpp 28 KB

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