Switch.cpp 28 KB

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