Switch.cpp 28 KB

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