Switch.cpp 28 KB

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