Switch.cpp 29 KB

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