Switch.cpp 30 KB

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