Switch.cpp 24 KB

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