Switch.cpp 28 KB

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