Switch.cpp 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686
  1. /*
  2. * ZeroTier One - Global Peer to Peer Ethernet
  3. * Copyright (C) 2012-2013 ZeroTier Networks LLC
  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 "Constants.hpp"
  33. #ifdef __WINDOWS__
  34. #include <WinSock2.h>
  35. #include <Windows.h>
  36. #endif
  37. #include "Switch.hpp"
  38. #include "Node.hpp"
  39. #include "EthernetTap.hpp"
  40. #include "InetAddress.hpp"
  41. #include "Topology.hpp"
  42. #include "RuntimeEnvironment.hpp"
  43. #include "Peer.hpp"
  44. #include "NodeConfig.hpp"
  45. #include "Demarc.hpp"
  46. #include "Filter.hpp"
  47. #include "../version.h"
  48. namespace ZeroTier {
  49. Switch::Switch(const RuntimeEnvironment *renv) :
  50. _r(renv)
  51. {
  52. }
  53. Switch::~Switch()
  54. {
  55. }
  56. void Switch::onRemotePacket(Demarc::Port localPort,const InetAddress &fromAddr,const Buffer<4096> &data)
  57. {
  58. try {
  59. if (data.size() > ZT_PROTO_MIN_FRAGMENT_LENGTH) {
  60. if (data[ZT_PACKET_FRAGMENT_IDX_FRAGMENT_INDICATOR] == ZT_PACKET_FRAGMENT_INDICATOR)
  61. _handleRemotePacketFragment(localPort,fromAddr,data);
  62. else if (data.size() > ZT_PROTO_MIN_PACKET_LENGTH)
  63. _handleRemotePacketHead(localPort,fromAddr,data);
  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,const Buffer<4096> &data)
  72. {
  73. if (from != network->tap().mac()) {
  74. LOG("ignored tap: %s -> %s %s (bridging is not (yet?) supported)",from.toString().c_str(),to.toString().c_str(),Filter::etherTypeName(etherType));
  75. return;
  76. }
  77. if (to == network->tap().mac()) {
  78. LOG("%s: frame received from self, ignoring (bridge loop? OS bug?)",network->tap().deviceName().c_str());
  79. return;
  80. }
  81. if (!network->permitsEtherType(etherType)) {
  82. LOG("ignored tap: %s -> %s: ethernet type %s not allowed on network %.16llx",from.toString().c_str(),to.toString().c_str(),Filter::etherTypeName(etherType),(unsigned long long)network->id());
  83. return;
  84. }
  85. if (to.isMulticast()) {
  86. MulticastGroup mg(to,0);
  87. if (to.isBroadcast()) {
  88. // Cram IPv4 IP into ADI field to make IPv4 ARP broadcast channel specific and scalable
  89. if ((etherType == ZT_ETHERTYPE_ARP)&&(data.size() == 28)&&(data[2] == 0x08)&&(data[3] == 0x00)&&(data[4] == 6)&&(data[5] == 4)&&(data[7] == 0x01))
  90. mg = MulticastGroup::deriveMulticastGroupForAddressResolution(InetAddress(data.field(24,4),4,0));
  91. }
  92. uint64_t crc = Multicaster::computeMulticastDedupCrc(network->id(),from,mg,etherType,data.data(),data.size());
  93. uint64_t now = Utils::now();
  94. if (_r->multicaster->checkDuplicate(crc,now)) {
  95. LOG("%s/%.16llx: multicast group %s: dropped %u bytes, duplicate multicast in too short a time frame",network->tap().deviceName().c_str(),(unsigned long long)network->id(),mg.toString().c_str(),(unsigned int)data.size());
  96. return;
  97. }
  98. _r->multicaster->addToDedupHistory(crc,now);
  99. if (!network->updateAndCheckMulticastBalance(_r->identity.address(),mg,data.size())) {
  100. LOG("%s/%.16llx: multicast group %s: dropped %u bytes, out of budget",network->tap().deviceName().c_str(),(unsigned long long)network->id(),mg.toString().c_str(),(unsigned int)data.size());
  101. return;
  102. }
  103. Multicaster::MulticastBloomFilter bloom;
  104. SharedPtr<Peer> propPeers[ZT_MULTICAST_PROPAGATION_BREADTH];
  105. unsigned int np = _r->multicaster->pickSocialPropagationPeers(
  106. *(_r->prng),
  107. *(_r->topology),
  108. network->id(),
  109. mg,
  110. _r->identity.address(),
  111. Address(),
  112. bloom,
  113. ZT_MULTICAST_PROPAGATION_BREADTH,
  114. propPeers,
  115. now);
  116. if (!np)
  117. return;
  118. C25519::Signature signature(Multicaster::signMulticastPacket(_r->identity,network->id(),from,mg,etherType,data.data(),data.size()));
  119. Packet outpTmpl(propPeers[0]->address(),_r->identity.address(),Packet::VERB_MULTICAST_FRAME);
  120. outpTmpl.append((uint8_t)0);
  121. outpTmpl.append((uint64_t)network->id());
  122. _r->identity.address().appendTo(outpTmpl);
  123. outpTmpl.append(from.data,6);
  124. outpTmpl.append(mg.mac().data,6);
  125. outpTmpl.append((uint32_t)mg.adi());
  126. outpTmpl.append(bloom.data(),ZT_PROTO_VERB_MULTICAST_FRAME_BLOOM_FILTER_SIZE_BYTES);
  127. outpTmpl.append((uint8_t)0); // 0 hops
  128. outpTmpl.append((uint16_t)etherType);
  129. outpTmpl.append((uint16_t)data.size());
  130. outpTmpl.append((uint16_t)signature.size());
  131. outpTmpl.append(data.data(),data.size());
  132. outpTmpl.append(signature.data,(unsigned int)signature.size());
  133. outpTmpl.compress();
  134. send(outpTmpl,true);
  135. for(unsigned int i=1;i<np;++i) {
  136. outpTmpl.newInitializationVector();
  137. outpTmpl.setDestination(propPeers[i]->address());
  138. send(outpTmpl,true);
  139. }
  140. } else if (to.isZeroTier()) {
  141. // Simple unicast frame from us to another node
  142. Address toZT(to.data + 1,ZT_ADDRESS_LENGTH);
  143. if (network->isAllowed(toZT)) {
  144. Packet outp(toZT,_r->identity.address(),Packet::VERB_FRAME);
  145. outp.append(network->id());
  146. outp.append((uint16_t)etherType);
  147. outp.append(data);
  148. outp.compress();
  149. send(outp,true);
  150. } else {
  151. TRACE("UNICAST: %s -> %s %s (dropped, destination not a member of closed network %llu)",from.toString().c_str(),to.toString().c_str(),Filter::etherTypeName(etherType),network->id());
  152. }
  153. } else {
  154. TRACE("UNICAST: %s -> %s %s (dropped, destination MAC not ZeroTier)",from.toString().c_str(),to.toString().c_str(),Filter::etherTypeName(etherType));
  155. }
  156. }
  157. void Switch::send(const Packet &packet,bool encrypt)
  158. {
  159. if (packet.destination() == _r->identity.address()) {
  160. TRACE("BUG: caught attempt to send() to self, ignored");
  161. return;
  162. }
  163. //TRACE(">> %.16llx %s -> %s (size: %u) (enc: %s)",(unsigned long long)packet.packetId(),packet.source().toString().c_str(),packet.destination().toString().c_str(),packet.size(),(encrypt ? "yes" : "no"));
  164. if (!_trySend(packet,encrypt)) {
  165. Mutex::Lock _l(_txQueue_m);
  166. _txQueue.insert(std::pair< Address,TXQueueEntry >(packet.destination(),TXQueueEntry(Utils::now(),packet,encrypt)));
  167. }
  168. }
  169. void Switch::sendHELLO(const Address &dest)
  170. {
  171. Packet outp(dest,_r->identity.address(),Packet::VERB_HELLO);
  172. outp.append((unsigned char)ZT_PROTO_VERSION);
  173. outp.append((unsigned char)ZEROTIER_ONE_VERSION_MAJOR);
  174. outp.append((unsigned char)ZEROTIER_ONE_VERSION_MINOR);
  175. outp.append((uint16_t)ZEROTIER_ONE_VERSION_REVISION);
  176. outp.append(Utils::now());
  177. _r->identity.serialize(outp,false);
  178. send(outp,false);
  179. }
  180. bool Switch::sendHELLO(const SharedPtr<Peer> &dest,Demarc::Port localPort,const InetAddress &remoteAddr)
  181. {
  182. uint64_t now = Utils::now();
  183. Packet outp(dest->address(),_r->identity.address(),Packet::VERB_HELLO);
  184. outp.append((unsigned char)ZT_PROTO_VERSION);
  185. outp.append((unsigned char)ZEROTIER_ONE_VERSION_MAJOR);
  186. outp.append((unsigned char)ZEROTIER_ONE_VERSION_MINOR);
  187. outp.append((uint16_t)ZEROTIER_ONE_VERSION_REVISION);
  188. outp.append(now);
  189. _r->identity.serialize(outp,false);
  190. outp.macSet(dest->macKey());
  191. if (_r->demarc->send(localPort,remoteAddr,outp.data(),outp.size(),-1)) {
  192. dest->onSent(_r,false,Packet::VERB_HELLO,now);
  193. return true;
  194. }
  195. return false;
  196. }
  197. bool Switch::unite(const Address &p1,const Address &p2,bool force)
  198. {
  199. if ((p1 == _r->identity.address())||(p2 == _r->identity.address()))
  200. return false;
  201. SharedPtr<Peer> p1p = _r->topology->getPeer(p1);
  202. if (!p1p)
  203. return false;
  204. SharedPtr<Peer> p2p = _r->topology->getPeer(p2);
  205. if (!p2p)
  206. return false;
  207. uint64_t now = Utils::now();
  208. std::pair<InetAddress,InetAddress> cg(Peer::findCommonGround(*p1p,*p2p,now));
  209. if (!(cg.first))
  210. return false;
  211. // Addresses are sorted in key for last unite attempt map for order
  212. // invariant lookup: (p1,p2) == (p2,p1)
  213. Array<Address,2> uniteKey;
  214. if (p1 >= p2) {
  215. uniteKey[0] = p2;
  216. uniteKey[1] = p1;
  217. } else {
  218. uniteKey[0] = p1;
  219. uniteKey[1] = p2;
  220. }
  221. {
  222. Mutex::Lock _l(_lastUniteAttempt_m);
  223. std::map< Array< Address,2 >,uint64_t >::const_iterator e(_lastUniteAttempt.find(uniteKey));
  224. if ((!force)&&(e != _lastUniteAttempt.end())&&((now - e->second) < ZT_MIN_UNITE_INTERVAL))
  225. return false;
  226. else _lastUniteAttempt[uniteKey] = now;
  227. }
  228. TRACE("unite: %s(%s) <> %s(%s)",p1.toString().c_str(),cg.second.toString().c_str(),p2.toString().c_str(),cg.first.toString().c_str());
  229. { // tell p1 where to find p2
  230. Packet outp(p1,_r->identity.address(),Packet::VERB_RENDEZVOUS);
  231. p2.appendTo(outp);
  232. outp.append((uint16_t)cg.first.port());
  233. if (cg.first.isV6()) {
  234. outp.append((unsigned char)16);
  235. outp.append(cg.first.rawIpData(),16);
  236. } else {
  237. outp.append((unsigned char)4);
  238. outp.append(cg.first.rawIpData(),4);
  239. }
  240. outp.encrypt(p1p->cryptKey());
  241. outp.macSet(p1p->macKey());
  242. if (p1p->send(_r,outp.data(),outp.size(),now))
  243. p1p->onSent(_r,false,Packet::VERB_RENDEZVOUS,now);
  244. }
  245. { // tell p2 where to find p1
  246. Packet outp(p2,_r->identity.address(),Packet::VERB_RENDEZVOUS);
  247. p1.appendTo(outp);
  248. outp.append((uint16_t)cg.second.port());
  249. if (cg.second.isV6()) {
  250. outp.append((unsigned char)16);
  251. outp.append(cg.second.rawIpData(),16);
  252. } else {
  253. outp.append((unsigned char)4);
  254. outp.append(cg.second.rawIpData(),4);
  255. }
  256. outp.encrypt(p2p->cryptKey());
  257. outp.macSet(p2p->macKey());
  258. if (p2p->send(_r,outp.data(),outp.size(),now))
  259. p2p->onSent(_r,false,Packet::VERB_RENDEZVOUS,now);
  260. }
  261. return true;
  262. }
  263. void Switch::contact(const SharedPtr<Peer> &peer,const InetAddress &atAddr)
  264. {
  265. Demarc::Port fromPort = _r->demarc->pick(atAddr);
  266. _r->demarc->send(fromPort,atAddr,"\0",1,ZT_FIREWALL_OPENER_HOPS);
  267. {
  268. Mutex::Lock _l(_contactQueue_m);
  269. _contactQueue.push_back(ContactQueueEntry(peer,Utils::now() + ZT_RENDEZVOUS_NAT_T_DELAY,fromPort,atAddr));
  270. }
  271. // Kick main loop out of wait so that it can pick up this
  272. // change to our scheduled timer tasks.
  273. _r->mainLoopWaitCondition.signal();
  274. }
  275. unsigned long Switch::doTimerTasks()
  276. {
  277. unsigned long nextDelay = ~((unsigned long)0); // big number, caller will cap return value
  278. uint64_t now = Utils::now();
  279. {
  280. Mutex::Lock _l(_contactQueue_m);
  281. for(std::list<ContactQueueEntry>::iterator qi(_contactQueue.begin());qi!=_contactQueue.end();) {
  282. if (now >= qi->fireAtTime) {
  283. TRACE("sending NAT-T HELLO to %s(%s)",qi->peer->address().toString().c_str(),qi->inaddr.toString().c_str());
  284. sendHELLO(qi->peer,qi->localPort,qi->inaddr);
  285. _contactQueue.erase(qi++);
  286. } else {
  287. nextDelay = std::min(nextDelay,(unsigned long)(qi->fireAtTime - now));
  288. ++qi;
  289. }
  290. }
  291. }
  292. {
  293. Mutex::Lock _l(_outstandingWhoisRequests_m);
  294. for(std::map< Address,WhoisRequest >::iterator i(_outstandingWhoisRequests.begin());i!=_outstandingWhoisRequests.end();) {
  295. unsigned long since = (unsigned long)(now - i->second.lastSent);
  296. if (since >= ZT_WHOIS_RETRY_DELAY) {
  297. if (i->second.retries >= ZT_MAX_WHOIS_RETRIES) {
  298. TRACE("WHOIS %s timed out",i->first.toString().c_str());
  299. _outstandingWhoisRequests.erase(i++);
  300. continue;
  301. } else {
  302. i->second.lastSent = now;
  303. i->second.peersConsulted[i->second.retries] = _sendWhoisRequest(i->first,i->second.peersConsulted,i->second.retries);
  304. ++i->second.retries;
  305. TRACE("WHOIS %s (retry %u)",i->first.toString().c_str(),i->second.retries);
  306. nextDelay = std::min(nextDelay,(unsigned long)ZT_WHOIS_RETRY_DELAY);
  307. }
  308. } else nextDelay = std::min(nextDelay,ZT_WHOIS_RETRY_DELAY - since);
  309. ++i;
  310. }
  311. }
  312. {
  313. Mutex::Lock _l(_txQueue_m);
  314. for(std::multimap< Address,TXQueueEntry >::iterator i(_txQueue.begin());i!=_txQueue.end();) {
  315. if (_trySend(i->second.packet,i->second.encrypt))
  316. _txQueue.erase(i++);
  317. else if ((now - i->second.creationTime) > ZT_TRANSMIT_QUEUE_TIMEOUT) {
  318. TRACE("TX %s -> %s timed out",i->second.packet.source().toString().c_str(),i->second.packet.destination().toString().c_str());
  319. _txQueue.erase(i++);
  320. } else ++i;
  321. }
  322. }
  323. {
  324. Mutex::Lock _l(_rxQueue_m);
  325. for(std::list< SharedPtr<PacketDecoder> >::iterator i(_rxQueue.begin());i!=_rxQueue.end();) {
  326. if ((now - (*i)->receiveTime()) > ZT_RECEIVE_QUEUE_TIMEOUT) {
  327. TRACE("RX %s -> %s timed out",(*i)->source().toString().c_str(),(*i)->destination().toString().c_str());
  328. _rxQueue.erase(i++);
  329. } else ++i;
  330. }
  331. }
  332. {
  333. Mutex::Lock _l(_defragQueue_m);
  334. for(std::map< uint64_t,DefragQueueEntry >::iterator i(_defragQueue.begin());i!=_defragQueue.end();) {
  335. if ((now - i->second.creationTime) > ZT_FRAGMENTED_PACKET_RECEIVE_TIMEOUT) {
  336. TRACE("incomplete fragmented packet %.16llx timed out, fragments discarded",i->first);
  337. _defragQueue.erase(i++);
  338. } else ++i;
  339. }
  340. }
  341. return std::max(nextDelay,(unsigned long)10); // minimum delay
  342. }
  343. void Switch::announceMulticastGroups(const std::map< SharedPtr<Network>,std::set<MulticastGroup> > &allMemberships)
  344. {
  345. std::vector< SharedPtr<Peer> > directPeers;
  346. _r->topology->eachPeer(Topology::CollectPeersWithActiveDirectPath(directPeers));
  347. #ifdef ZT_TRACE
  348. unsigned int totalMulticastGroups = 0;
  349. for(std::map< SharedPtr<Network>,std::set<MulticastGroup> >::const_iterator i(allMemberships.begin());i!=allMemberships.end();++i)
  350. totalMulticastGroups += (unsigned int)i->second.size();
  351. TRACE("announcing %u multicast groups for %u networks to %u peers",totalMulticastGroups,(unsigned int)allMemberships.size(),(unsigned int)directPeers.size());
  352. #endif
  353. for(std::vector< SharedPtr<Peer> >::iterator p(directPeers.begin());p!=directPeers.end();++p) {
  354. Packet outp((*p)->address(),_r->identity.address(),Packet::VERB_MULTICAST_LIKE);
  355. for(std::map< SharedPtr<Network>,std::set<MulticastGroup> >::const_iterator nwmgs(allMemberships.begin());nwmgs!=allMemberships.end();++nwmgs) {
  356. if ((_r->topology->isSupernode((*p)->address()))||(nwmgs->first->isAllowed((*p)->address()))) {
  357. for(std::set<MulticastGroup>::iterator mg(nwmgs->second.begin());mg!=nwmgs->second.end();++mg) {
  358. if ((outp.size() + 18) > ZT_UDP_DEFAULT_PAYLOAD_MTU) {
  359. send(outp,true);
  360. outp.reset((*p)->address(),_r->identity.address(),Packet::VERB_MULTICAST_LIKE);
  361. }
  362. outp.append((uint64_t)nwmgs->first->id());
  363. outp.append(mg->mac().data,6);
  364. outp.append((uint32_t)mg->adi());
  365. }
  366. }
  367. }
  368. if (outp.size() > ZT_PROTO_MIN_PACKET_LENGTH)
  369. send(outp,true);
  370. }
  371. }
  372. void Switch::requestWhois(const Address &addr)
  373. {
  374. TRACE("requesting WHOIS for %s",addr.toString().c_str());
  375. {
  376. Mutex::Lock _l(_outstandingWhoisRequests_m);
  377. std::pair< std::map< Address,WhoisRequest >::iterator,bool > entry(_outstandingWhoisRequests.insert(std::pair<Address,WhoisRequest>(addr,WhoisRequest())));
  378. entry.first->second.lastSent = Utils::now();
  379. entry.first->second.retries = 0; // reset retry count if entry already existed
  380. }
  381. _sendWhoisRequest(addr,(const Address *)0,0);
  382. }
  383. void Switch::doAnythingWaitingForPeer(const SharedPtr<Peer> &peer)
  384. {
  385. {
  386. Mutex::Lock _l(_outstandingWhoisRequests_m);
  387. _outstandingWhoisRequests.erase(peer->address());
  388. }
  389. {
  390. Mutex::Lock _l(_rxQueue_m);
  391. for(std::list< SharedPtr<PacketDecoder> >::iterator rxi(_rxQueue.begin());rxi!=_rxQueue.end();) {
  392. if ((*rxi)->tryDecode(_r))
  393. _rxQueue.erase(rxi++);
  394. else ++rxi;
  395. }
  396. }
  397. {
  398. Mutex::Lock _l(_txQueue_m);
  399. std::pair< std::multimap< Address,TXQueueEntry >::iterator,std::multimap< Address,TXQueueEntry >::iterator > waitingTxQueueItems(_txQueue.equal_range(peer->address()));
  400. for(std::multimap< Address,TXQueueEntry >::iterator txi(waitingTxQueueItems.first);txi!=waitingTxQueueItems.second;) {
  401. if (_trySend(txi->second.packet,txi->second.encrypt))
  402. _txQueue.erase(txi++);
  403. else ++txi;
  404. }
  405. }
  406. }
  407. void Switch::_handleRemotePacketFragment(Demarc::Port localPort,const InetAddress &fromAddr,const Buffer<4096> &data)
  408. {
  409. Packet::Fragment fragment(data);
  410. Address destination(fragment.destination());
  411. if (destination != _r->identity.address()) {
  412. // Fragment is not for us, so try to relay it
  413. if (fragment.hops() < ZT_RELAY_MAX_HOPS) {
  414. fragment.incrementHops();
  415. SharedPtr<Peer> relayTo = _r->topology->getPeer(destination);
  416. if ((!relayTo)||(!relayTo->send(_r,fragment.data(),fragment.size(),Utils::now()))) {
  417. relayTo = _r->topology->getBestSupernode();
  418. if (relayTo)
  419. relayTo->send(_r,fragment.data(),fragment.size(),Utils::now());
  420. }
  421. } else {
  422. TRACE("dropped relay [fragment](%s) -> %s, max hops exceeded",fromAddr.toString().c_str(),destination.toString().c_str());
  423. }
  424. } else {
  425. // Fragment looks like ours
  426. uint64_t pid = fragment.packetId();
  427. unsigned int fno = fragment.fragmentNumber();
  428. unsigned int tf = fragment.totalFragments();
  429. if ((tf <= ZT_MAX_PACKET_FRAGMENTS)&&(fno < ZT_MAX_PACKET_FRAGMENTS)&&(fno > 0)&&(tf > 1)) {
  430. // Fragment appears basically sane. Its fragment number must be
  431. // 1 or more, since a Packet with fragmented bit set is fragment 0.
  432. // Total fragments must be more than 1, otherwise why are we
  433. // seeing a Packet::Fragment?
  434. Mutex::Lock _l(_defragQueue_m);
  435. std::map< uint64_t,DefragQueueEntry >::iterator dqe(_defragQueue.find(pid));
  436. if (dqe == _defragQueue.end()) {
  437. // We received a Packet::Fragment without its head, so queue it and wait
  438. DefragQueueEntry &dq = _defragQueue[pid];
  439. dq.creationTime = Utils::now();
  440. dq.frags[fno - 1] = fragment;
  441. dq.totalFragments = tf; // total fragment count is known
  442. dq.haveFragments = 1 << fno; // we have only this fragment
  443. //TRACE("fragment (%u/%u) of %.16llx from %s",fno + 1,tf,pid,fromAddr.toString().c_str());
  444. } else if (!(dqe->second.haveFragments & (1 << fno))) {
  445. // We have other fragments and maybe the head, so add this one and check
  446. dqe->second.frags[fno - 1] = fragment;
  447. dqe->second.totalFragments = tf;
  448. //TRACE("fragment (%u/%u) of %.16llx from %s",fno + 1,tf,pid,fromAddr.toString().c_str());
  449. if (Utils::countBits(dqe->second.haveFragments |= (1 << fno)) == tf) {
  450. // We have all fragments -- assemble and process full Packet
  451. //TRACE("packet %.16llx is complete, assembling and processing...",pid);
  452. SharedPtr<PacketDecoder> packet(dqe->second.frag0);
  453. for(unsigned int f=1;f<tf;++f)
  454. packet->append(dqe->second.frags[f - 1].payload(),dqe->second.frags[f - 1].payloadLength());
  455. _defragQueue.erase(dqe);
  456. if (!packet->tryDecode(_r)) {
  457. Mutex::Lock _l(_rxQueue_m);
  458. _rxQueue.push_back(packet);
  459. }
  460. }
  461. } // else this is a duplicate fragment, ignore
  462. }
  463. }
  464. }
  465. void Switch::_handleRemotePacketHead(Demarc::Port localPort,const InetAddress &fromAddr,const Buffer<4096> &data)
  466. {
  467. SharedPtr<PacketDecoder> packet(new PacketDecoder(data,localPort,fromAddr));
  468. Address source(packet->source());
  469. Address destination(packet->destination());
  470. //TRACE("<< %.16llx %s -> %s (size: %u)",(unsigned long long)packet->packetId(),source.toString().c_str(),destination.toString().c_str(),packet->size());
  471. if (destination != _r->identity.address()) {
  472. // Packet is not for us, so try to relay it
  473. if (packet->hops() < ZT_RELAY_MAX_HOPS) {
  474. packet->incrementHops();
  475. SharedPtr<Peer> relayTo = _r->topology->getPeer(destination);
  476. if ((relayTo)&&(relayTo->send(_r,packet->data(),packet->size(),Utils::now()))) {
  477. // If we've relayed, this periodically tries to get them to
  478. // talk directly to save our bandwidth.
  479. unite(source,destination,false);
  480. } else {
  481. // If we've received a packet not for us and we don't have
  482. // a direct path to its recipient, pass it to (another)
  483. // supernode. This can happen due to Internet weather -- the
  484. // most direct supernode may not be reachable, yet another
  485. // further away may be.
  486. relayTo = _r->topology->getBestSupernode(&source,1,true);
  487. if (relayTo)
  488. relayTo->send(_r,packet->data(),packet->size(),Utils::now());
  489. }
  490. } else {
  491. TRACE("dropped relay %s(%s) -> %s, max hops exceeded",packet->source().toString().c_str(),fromAddr.toString().c_str(),destination.toString().c_str());
  492. }
  493. } else if (packet->fragmented()) {
  494. // Packet is the head of a fragmented packet series
  495. uint64_t pid = packet->packetId();
  496. Mutex::Lock _l(_defragQueue_m);
  497. std::map< uint64_t,DefragQueueEntry >::iterator dqe(_defragQueue.find(pid));
  498. if (dqe == _defragQueue.end()) {
  499. // If we have no other fragments yet, create an entry and save the head
  500. DefragQueueEntry &dq = _defragQueue[pid];
  501. dq.creationTime = Utils::now();
  502. dq.frag0 = packet;
  503. dq.totalFragments = 0; // 0 == unknown, waiting for Packet::Fragment
  504. dq.haveFragments = 1; // head is first bit (left to right)
  505. //TRACE("fragment (0/?) of %.16llx from %s",pid,fromAddr.toString().c_str());
  506. } else if (!(dqe->second.haveFragments & 1)) {
  507. // If we have other fragments but no head, see if we are complete with the head
  508. if ((dqe->second.totalFragments)&&(Utils::countBits(dqe->second.haveFragments |= 1) == dqe->second.totalFragments)) {
  509. // We have all fragments -- assemble and process full Packet
  510. //TRACE("packet %.16llx is complete, assembling and processing...",pid);
  511. // packet already contains head, so append fragments
  512. for(unsigned int f=1;f<dqe->second.totalFragments;++f)
  513. packet->append(dqe->second.frags[f - 1].payload(),dqe->second.frags[f - 1].payloadLength());
  514. _defragQueue.erase(dqe);
  515. if (!packet->tryDecode(_r)) {
  516. Mutex::Lock _l(_rxQueue_m);
  517. _rxQueue.push_back(packet);
  518. }
  519. } else {
  520. // Still waiting on more fragments, so queue the head
  521. dqe->second.frag0 = packet;
  522. }
  523. } // else this is a duplicate head, ignore
  524. } else {
  525. // Packet is unfragmented, so just process it
  526. if (!packet->tryDecode(_r)) {
  527. Mutex::Lock _l(_rxQueue_m);
  528. _rxQueue.push_back(packet);
  529. }
  530. }
  531. }
  532. Address Switch::_sendWhoisRequest(const Address &addr,const Address *peersAlreadyConsulted,unsigned int numPeersAlreadyConsulted)
  533. {
  534. SharedPtr<Peer> supernode(_r->topology->getBestSupernode(peersAlreadyConsulted,numPeersAlreadyConsulted,false));
  535. if (supernode) {
  536. Packet outp(supernode->address(),_r->identity.address(),Packet::VERB_WHOIS);
  537. addr.appendTo(outp);
  538. outp.encrypt(supernode->cryptKey());
  539. outp.macSet(supernode->macKey());
  540. uint64_t now = Utils::now();
  541. if (supernode->send(_r,outp.data(),outp.size(),now)) {
  542. supernode->onSent(_r,false,Packet::VERB_WHOIS,now);
  543. return supernode->address();
  544. }
  545. }
  546. return Address();
  547. }
  548. bool Switch::_trySend(const Packet &packet,bool encrypt)
  549. {
  550. SharedPtr<Peer> peer(_r->topology->getPeer(packet.destination()));
  551. if (peer) {
  552. uint64_t now = Utils::now();
  553. bool isRelay;
  554. SharedPtr<Peer> via;
  555. if ((_r->topology->isSupernode(peer->address()))||(peer->hasActiveDirectPath(now))) {
  556. isRelay = false;
  557. via = peer;
  558. } else {
  559. isRelay = true;
  560. via = _r->topology->getBestSupernode();
  561. if (!via)
  562. return false;
  563. }
  564. Packet tmp(packet);
  565. unsigned int chunkSize = std::min(tmp.size(),(unsigned int)ZT_UDP_DEFAULT_PAYLOAD_MTU);
  566. tmp.setFragmented(chunkSize < tmp.size());
  567. if (encrypt)
  568. tmp.encrypt(peer->cryptKey());
  569. tmp.macSet(peer->macKey());
  570. if (via->send(_r,tmp.data(),chunkSize,now)) {
  571. if (chunkSize < tmp.size()) {
  572. // Too big for one bite, fragment the rest
  573. unsigned int fragStart = chunkSize;
  574. unsigned int remaining = tmp.size() - chunkSize;
  575. unsigned int fragsRemaining = (remaining / (ZT_UDP_DEFAULT_PAYLOAD_MTU - ZT_PROTO_MIN_FRAGMENT_LENGTH));
  576. if ((fragsRemaining * (ZT_UDP_DEFAULT_PAYLOAD_MTU - ZT_PROTO_MIN_FRAGMENT_LENGTH)) < remaining)
  577. ++fragsRemaining;
  578. unsigned int totalFragments = fragsRemaining + 1;
  579. for(unsigned int f=0;f<fragsRemaining;++f) {
  580. chunkSize = std::min(remaining,(unsigned int)(ZT_UDP_DEFAULT_PAYLOAD_MTU - ZT_PROTO_MIN_FRAGMENT_LENGTH));
  581. Packet::Fragment frag(tmp,fragStart,chunkSize,f + 1,totalFragments);
  582. if (!via->send(_r,frag.data(),frag.size(),now)) {
  583. TRACE("WARNING: packet send to %s failed on later fragment #%u (check IP layer buffer sizes?)",via->address().toString().c_str(),f + 1);
  584. }
  585. fragStart += chunkSize;
  586. remaining -= chunkSize;
  587. }
  588. }
  589. via->onSent(_r,isRelay,packet.verb(),now);
  590. return true;
  591. }
  592. return false;
  593. }
  594. requestWhois(packet.destination());
  595. return false;
  596. }
  597. } // namespace ZeroTier