Switch.cpp 23 KB

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