Switch.cpp 27 KB

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