Switch.cpp 29 KB

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