Switch.cpp 28 KB

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