Switch.cpp 24 KB

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