Switch.cpp 26 KB

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