Switch.cpp 25 KB

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