Switch.cpp 30 KB

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