Switch.cpp 23 KB

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