Switch.cpp 27 KB

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