Switch.cpp 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928
  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. {
  53. }
  54. Switch::~Switch()
  55. {
  56. }
  57. void Switch::onRemotePacket(const SharedPtr<Socket> &fromSock,const InetAddress &fromAddr,Buffer<ZT_SOCKET_MAX_MESSAGE_LEN> &data)
  58. {
  59. try {
  60. if (data.size() == ZT_PROTO_BEACON_LENGTH) {
  61. _handleBeacon(fromSock,fromAddr,data);
  62. } else if (data.size() > ZT_PROTO_MIN_FRAGMENT_LENGTH) {
  63. if (data[ZT_PACKET_FRAGMENT_IDX_FRAGMENT_INDICATOR] == ZT_PACKET_FRAGMENT_INDICATOR)
  64. _handleRemotePacketFragment(fromSock,fromAddr,data);
  65. else if (data.size() >= ZT_PROTO_MIN_PACKET_LENGTH)
  66. _handleRemotePacketHead(fromSock,fromAddr,data);
  67. }
  68. } catch (std::exception &ex) {
  69. TRACE("dropped packet from %s: unexpected exception: %s",fromAddr.toString().c_str(),ex.what());
  70. } catch ( ... ) {
  71. TRACE("dropped packet from %s: unexpected exception: (unknown)",fromAddr.toString().c_str());
  72. }
  73. }
  74. void Switch::onLocalEthernet(const SharedPtr<Network> &network,const MAC &from,const MAC &to,unsigned int etherType,const Buffer<4096> &data)
  75. {
  76. SharedPtr<NetworkConfig> nconf(network->config2());
  77. if (!nconf)
  78. return;
  79. // Sanity check -- bridge loop? OS problem?
  80. if (to == network->mac())
  81. return;
  82. /* Check anti-recursion module to ensure that this is not ZeroTier talking over its own links.
  83. * Note: even when we introduce a more purposeful binding of the main UDP port, this can
  84. * still happen because Windows likes to send broadcasts over interfaces that have little
  85. * to do with their intended target audience. :P */
  86. if (!RR->antiRec->checkEthernetFrame(data.data(),data.size())) {
  87. TRACE("%s: rejected recursively addressed ZeroTier packet by tail match (type %s, length: %u)",network->tapDeviceName().c_str(),etherTypeName(etherType),data.size());
  88. return;
  89. }
  90. // Check to make sure this protocol is allowed on this network
  91. if (!nconf->permitsEtherType(etherType)) {
  92. TRACE("%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());
  93. return;
  94. }
  95. // Check if this packet is from someone other than the tap -- i.e. bridged in
  96. bool fromBridged = false;
  97. if (from != network->mac()) {
  98. if (!network->permitsBridging(RR->identity.address())) {
  99. LOG("%s: %s -> %s %s not forwarded, bridging disabled on %.16llx or this peer not a bridge",network->tapDeviceName().c_str(),from.toString().c_str(),to.toString().c_str(),etherTypeName(etherType),network->id());
  100. return;
  101. }
  102. fromBridged = true;
  103. }
  104. if (to.isMulticast()) {
  105. // Destination is a multicast address (including broadcast)
  106. uint64_t now = Utils::now();
  107. MulticastGroup mg(to,0);
  108. if (to.isBroadcast()) {
  109. if ((etherType == ZT_ETHERTYPE_ARP)&&(data.size() >= 28)&&(data[2] == 0x08)&&(data[3] == 0x00)&&(data[4] == 6)&&(data[5] == 4)&&(data[7] == 0x01)) {
  110. // Cram IPv4 IP into ADI field to make IPv4 ARP broadcast channel specific and scalable
  111. // Also: enableBroadcast() does not apply to ARP since it's required for IPv4
  112. mg = MulticastGroup::deriveMulticastGroupForAddressResolution(InetAddress(data.field(24,4),4,0));
  113. } else if (!nconf->enableBroadcast()) {
  114. // Don't transmit broadcasts if this network doesn't want them
  115. TRACE("%s: dropped broadcast since ff:ff:ff:ff:ff:ff is not enabled on network %.16llx",network->tapDeviceName().c_str(),network->id());
  116. return;
  117. }
  118. }
  119. /* Learn multicast groups for bridged-in hosts.
  120. * Note that some OSes, most notably Linux, do this for you by learning
  121. * multicast addresses on bridge interfaces and subscribing each slave.
  122. * But in that case this does no harm, as the sets are just merged. */
  123. if (fromBridged)
  124. network->learnBridgedMulticastGroup(mg,now);
  125. // Check multicast/broadcast bandwidth quotas and reject if quota exceeded
  126. if (!network->updateAndCheckMulticastBalance(RR->identity.address(),mg,data.size())) {
  127. TRACE("%s: didn't multicast %d bytes, quota exceeded for multicast group %s",network->tapDeviceName().c_str(),(int)data.size(),mg.toString().c_str());
  128. return;
  129. }
  130. TRACE("%s: MULTICAST %s -> %s %s %d",network->tapDeviceName().c_str(),from.toString().c_str(),mg.toString().c_str(),etherTypeName(etherType),(int)data.size());
  131. /* old P5 multicast algorithm
  132. const unsigned int mcid = ++_multicastIdCounter & 0xffffff;
  133. const uint16_t bloomNonce = (uint16_t)(RR->prng->next32() & 0xffff); // doesn't need to be cryptographically strong
  134. unsigned char bloom[ZT_PROTO_VERB_MULTICAST_FRAME_LEN_PROPAGATION_BLOOM];
  135. unsigned char fifo[ZT_PROTO_VERB_MULTICAST_FRAME_LEN_PROPAGATION_FIFO + ZT_ADDRESS_LENGTH]; // extra ZT_ADDRESS_LENGTH is for first hop, not put in packet but serves as destination for packet
  136. unsigned char *const fifoEnd = fifo + sizeof(fifo);
  137. const unsigned int signedPartLen = (ZT_PROTO_VERB_MULTICAST_FRAME_IDX_FRAME - ZT_PROTO_VERB_MULTICAST_FRAME_IDX__START_OF_SIGNED_PORTION) + data.size();
  138. const SharedPtr<Peer> supernode(RR->topology->getBestSupernode());
  139. // For each bit prefix send a packet to a list of destinations within it
  140. for(unsigned int prefix=0,np=((unsigned int)2 << (nconf->multicastPrefixBits() - 1));prefix<np;++prefix) {
  141. memset(bloom,0,sizeof(bloom));
  142. unsigned char *fifoPtr = fifo;
  143. // Add all active bridges and then next hops we know about to propagation queue
  144. Multicaster::AddToPropagationQueue appender(
  145. &fifoPtr,
  146. fifoEnd,
  147. bloom,
  148. bloomNonce,
  149. RR->identity.address(),
  150. nconf->multicastPrefixBits(),
  151. prefix,
  152. RR->topology,
  153. now);
  154. for(std::set<Address>::const_iterator ab(nconf->activeBridges().begin());ab!=nconf->activeBridges().end();++ab) {
  155. if (!appender(*ab))
  156. break;
  157. }
  158. RR->mc->getNextHops(network->id(),mg,appender);
  159. // Pad remainder of FIFO with zeroes
  160. while (fifoPtr != fifoEnd)
  161. *(fifoPtr++) = (unsigned char)0;
  162. // First element in FIFO is first hop, rest of FIFO is sent in packet *to* first hop
  163. Address firstHop(fifo,ZT_ADDRESS_LENGTH);
  164. if (!firstHop) {
  165. if (supernode)
  166. firstHop = supernode->address();
  167. else continue; // nowhere to go
  168. }
  169. Packet outp(firstHop,RR->identity.address(),Packet::VERB_MULTICAST_FRAME);
  170. outp.append((uint16_t)0);
  171. outp.append(fifo + ZT_ADDRESS_LENGTH,ZT_PROTO_VERB_MULTICAST_FRAME_LEN_PROPAGATION_FIFO); // remainder of fifo is loaded into packet
  172. outp.append(bloom,ZT_PROTO_VERB_MULTICAST_FRAME_LEN_PROPAGATION_BLOOM);
  173. outp.append((nconf->com()) ? (unsigned char)ZT_PROTO_VERB_MULTICAST_FRAME_FLAGS_HAS_MEMBERSHIP_CERTIFICATE : (unsigned char)0);
  174. outp.append(network->id());
  175. outp.append(bloomNonce);
  176. outp.append((unsigned char)nconf->multicastPrefixBits());
  177. outp.append((unsigned char)prefix);
  178. RR->identity.address().appendTo(outp); // lower 40 bits of MCID are my address
  179. outp.append((unsigned char)((mcid >> 16) & 0xff));
  180. outp.append((unsigned char)((mcid >> 8) & 0xff));
  181. outp.append((unsigned char)(mcid & 0xff)); // upper 24 bits of MCID are from our counter
  182. from.appendTo(outp);
  183. mg.mac().appendTo(outp);
  184. outp.append(mg.adi());
  185. outp.append((uint16_t)etherType);
  186. outp.append((uint16_t)data.size());
  187. outp.append(data);
  188. C25519::Signature sig(RR->identity.sign(outp.field(ZT_PROTO_VERB_MULTICAST_FRAME_IDX__START_OF_SIGNED_PORTION,signedPartLen),signedPartLen));
  189. outp.append((uint16_t)sig.size());
  190. outp.append(sig.data,(unsigned int)sig.size());
  191. // FIXME: now we send the netconf cert with every single multicast,
  192. // which pretty much ensures everyone has it ahead of time but adds
  193. // some redundant payload. Maybe think abouut this in the future.
  194. if (nconf->com())
  195. nconf->com().serialize(outp);
  196. outp.compress();
  197. send(outp,true);
  198. }
  199. */
  200. return;
  201. }
  202. if (to[0] == MAC::firstOctetForNetwork(network->id())) {
  203. // Destination is another ZeroTier node
  204. Address toZT(to.toAddress(network->id()));
  205. if (network->isAllowed(toZT)) {
  206. network->pushMembershipCertificate(toZT,false,Utils::now());
  207. if (fromBridged) {
  208. // Must use EXT_FRAME if source is not myself
  209. Packet outp(toZT,RR->identity.address(),Packet::VERB_EXT_FRAME);
  210. outp.append(network->id());
  211. outp.append((unsigned char)0);
  212. to.appendTo(outp);
  213. from.appendTo(outp);
  214. outp.append((uint16_t)etherType);
  215. outp.append(data);
  216. outp.compress();
  217. send(outp,true);
  218. } else {
  219. // VERB_FRAME is really just lighter weight EXT_FRAME, can use for direct-to-direct (before bridging this was the only unicast method)
  220. Packet outp(toZT,RR->identity.address(),Packet::VERB_FRAME);
  221. outp.append(network->id());
  222. outp.append((uint16_t)etherType);
  223. outp.append(data);
  224. outp.compress();
  225. send(outp,true);
  226. }
  227. } else {
  228. 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());
  229. }
  230. return;
  231. }
  232. {
  233. // Destination is behind another bridge
  234. Address bridges[ZT_MAX_BRIDGE_SPAM];
  235. unsigned int numBridges = 0;
  236. bridges[0] = network->findBridgeTo(to);
  237. if ((bridges[0])&&(bridges[0] != RR->identity.address())&&(network->isAllowed(bridges[0]))&&(network->permitsBridging(bridges[0]))) {
  238. // We have a known bridge route for this MAC.
  239. ++numBridges;
  240. } else if (!nconf->activeBridges().empty()) {
  241. /* If there is no known route, spam to up to ZT_MAX_BRIDGE_SPAM active
  242. * bridges. This is similar to what many switches do -- if they do not
  243. * know which port corresponds to a MAC, they send it to all ports. If
  244. * there aren't any active bridges, numBridges will stay 0 and packet
  245. * is dropped. */
  246. std::set<Address>::const_iterator ab(nconf->activeBridges().begin());
  247. if (nconf->activeBridges().size() <= ZT_MAX_BRIDGE_SPAM) {
  248. // If there are <= ZT_MAX_BRIDGE_SPAM active bridges, spam them all
  249. while (ab != nconf->activeBridges().end()) {
  250. if (network->isAllowed(*ab)) // config sanity check
  251. bridges[numBridges++] = *ab;
  252. ++ab;
  253. }
  254. } else {
  255. // Otherwise pick a random set of them
  256. while (numBridges < ZT_MAX_BRIDGE_SPAM) {
  257. if (ab == nconf->activeBridges().end())
  258. ab = nconf->activeBridges().begin();
  259. if (((unsigned long)RR->prng->next32() % (unsigned long)nconf->activeBridges().size()) == 0) {
  260. if (network->isAllowed(*ab)) // config sanity check
  261. bridges[numBridges++] = *ab;
  262. ++ab;
  263. } else ++ab;
  264. }
  265. }
  266. }
  267. for(unsigned int b=0;b<numBridges;++b) {
  268. Packet outp(bridges[b],RR->identity.address(),Packet::VERB_EXT_FRAME);
  269. outp.append(network->id());
  270. outp.append((unsigned char)0);
  271. to.appendTo(outp);
  272. from.appendTo(outp);
  273. outp.append((uint16_t)etherType);
  274. outp.append(data);
  275. outp.compress();
  276. send(outp,true);
  277. }
  278. }
  279. }
  280. void Switch::send(const Packet &packet,bool encrypt)
  281. {
  282. if (packet.destination() == RR->identity.address()) {
  283. TRACE("BUG: caught attempt to send() to self, ignored");
  284. return;
  285. }
  286. if (!_trySend(packet,encrypt)) {
  287. Mutex::Lock _l(_txQueue_m);
  288. _txQueue.insert(std::pair< Address,TXQueueEntry >(packet.destination(),TXQueueEntry(Utils::now(),packet,encrypt)));
  289. }
  290. }
  291. void Switch::sendHELLO(const Address &dest)
  292. {
  293. Packet outp(dest,RR->identity.address(),Packet::VERB_HELLO);
  294. outp.append((unsigned char)ZT_PROTO_VERSION);
  295. outp.append((unsigned char)ZEROTIER_ONE_VERSION_MAJOR);
  296. outp.append((unsigned char)ZEROTIER_ONE_VERSION_MINOR);
  297. outp.append((uint16_t)ZEROTIER_ONE_VERSION_REVISION);
  298. outp.append(Utils::now());
  299. RR->identity.serialize(outp,false);
  300. send(outp,false);
  301. }
  302. bool Switch::sendHELLO(const SharedPtr<Peer> &dest,const Path &path)
  303. {
  304. uint64_t now = Utils::now();
  305. Packet outp(dest->address(),RR->identity.address(),Packet::VERB_HELLO);
  306. outp.append((unsigned char)ZT_PROTO_VERSION);
  307. outp.append((unsigned char)ZEROTIER_ONE_VERSION_MAJOR);
  308. outp.append((unsigned char)ZEROTIER_ONE_VERSION_MINOR);
  309. outp.append((uint16_t)ZEROTIER_ONE_VERSION_REVISION);
  310. outp.append(now);
  311. RR->identity.serialize(outp,false);
  312. outp.armor(dest->key(),false);
  313. RR->antiRec->logOutgoingZT(outp.data(),outp.size());
  314. return RR->sm->send(path.address(),path.tcp(),path.type() == Path::PATH_TYPE_TCP_OUT,outp.data(),outp.size());
  315. }
  316. bool Switch::sendHELLO(const SharedPtr<Peer> &dest,const InetAddress &destUdp)
  317. {
  318. uint64_t now = Utils::now();
  319. Packet outp(dest->address(),RR->identity.address(),Packet::VERB_HELLO);
  320. outp.append((unsigned char)ZT_PROTO_VERSION);
  321. outp.append((unsigned char)ZEROTIER_ONE_VERSION_MAJOR);
  322. outp.append((unsigned char)ZEROTIER_ONE_VERSION_MINOR);
  323. outp.append((uint16_t)ZEROTIER_ONE_VERSION_REVISION);
  324. outp.append(now);
  325. RR->identity.serialize(outp,false);
  326. outp.armor(dest->key(),false);
  327. RR->antiRec->logOutgoingZT(outp.data(),outp.size());
  328. return RR->sm->send(destUdp,false,false,outp.data(),outp.size());
  329. }
  330. bool Switch::unite(const Address &p1,const Address &p2,bool force)
  331. {
  332. if ((p1 == RR->identity.address())||(p2 == RR->identity.address()))
  333. return false;
  334. SharedPtr<Peer> p1p = RR->topology->getPeer(p1);
  335. if (!p1p)
  336. return false;
  337. SharedPtr<Peer> p2p = RR->topology->getPeer(p2);
  338. if (!p2p)
  339. return false;
  340. uint64_t now = Utils::now();
  341. std::pair<InetAddress,InetAddress> cg(Peer::findCommonGround(*p1p,*p2p,now));
  342. if (!(cg.first))
  343. return false;
  344. // Addresses are sorted in key for last unite attempt map for order
  345. // invariant lookup: (p1,p2) == (p2,p1)
  346. Array<Address,2> uniteKey;
  347. if (p1 >= p2) {
  348. uniteKey[0] = p2;
  349. uniteKey[1] = p1;
  350. } else {
  351. uniteKey[0] = p1;
  352. uniteKey[1] = p2;
  353. }
  354. {
  355. Mutex::Lock _l(_lastUniteAttempt_m);
  356. std::map< Array< Address,2 >,uint64_t >::const_iterator e(_lastUniteAttempt.find(uniteKey));
  357. if ((!force)&&(e != _lastUniteAttempt.end())&&((now - e->second) < ZT_MIN_UNITE_INTERVAL))
  358. return false;
  359. else _lastUniteAttempt[uniteKey] = now;
  360. }
  361. TRACE("unite: %s(%s) <> %s(%s)",p1.toString().c_str(),cg.second.toString().c_str(),p2.toString().c_str(),cg.first.toString().c_str());
  362. /* Tell P1 where to find P2 and vice versa, sending the packets to P1 and
  363. * P2 in randomized order in terms of which gets sent first. This is done
  364. * since in a few cases NAT-t can be sensitive to slight timing differences
  365. * in terms of when the two peers initiate. Normally this is accounted for
  366. * by the nearly-simultaneous RENDEZVOUS kickoff from the supernode, but
  367. * given that supernodes are hosted on cloud providers this can in some
  368. * cases have a few ms of latency between packet departures. By randomizing
  369. * the order we make each attempted NAT-t favor one or the other going
  370. * first, meaning if it doesn't succeed the first time it might the second
  371. * and so forth. */
  372. unsigned int alt = RR->prng->next32() & 1;
  373. unsigned int completed = alt + 2;
  374. while (alt != completed) {
  375. if ((alt & 1) == 0) {
  376. // Tell p1 where to find p2.
  377. Packet outp(p1,RR->identity.address(),Packet::VERB_RENDEZVOUS);
  378. outp.append((unsigned char)0);
  379. p2.appendTo(outp);
  380. outp.append((uint16_t)cg.first.port());
  381. if (cg.first.isV6()) {
  382. outp.append((unsigned char)16);
  383. outp.append(cg.first.rawIpData(),16);
  384. } else {
  385. outp.append((unsigned char)4);
  386. outp.append(cg.first.rawIpData(),4);
  387. }
  388. outp.armor(p1p->key(),true);
  389. p1p->send(RR,outp.data(),outp.size(),now);
  390. } else {
  391. // Tell p2 where to find p1.
  392. Packet outp(p2,RR->identity.address(),Packet::VERB_RENDEZVOUS);
  393. outp.append((unsigned char)0);
  394. p1.appendTo(outp);
  395. outp.append((uint16_t)cg.second.port());
  396. if (cg.second.isV6()) {
  397. outp.append((unsigned char)16);
  398. outp.append(cg.second.rawIpData(),16);
  399. } else {
  400. outp.append((unsigned char)4);
  401. outp.append(cg.second.rawIpData(),4);
  402. }
  403. outp.armor(p2p->key(),true);
  404. p2p->send(RR,outp.data(),outp.size(),now);
  405. }
  406. ++alt; // counts up and also flips LSB
  407. }
  408. return true;
  409. }
  410. void Switch::contact(const SharedPtr<Peer> &peer,const InetAddress &atAddr)
  411. {
  412. // Send simple packet directly to indicated address -- works for most NATs
  413. sendHELLO(peer,atAddr);
  414. TRACE("sending NAT-t HELLO to %s(%s)",peer->address().toString().c_str(),atAddr.toString().c_str());
  415. // If we have not punched through after this timeout, open refreshing can of whupass
  416. {
  417. Mutex::Lock _l(_contactQueue_m);
  418. _contactQueue.push_back(ContactQueueEntry(peer,Utils::now() + ZT_NAT_T_TACTICAL_ESCALATION_DELAY,atAddr));
  419. }
  420. // Kick main loop out of wait so that it can pick up this
  421. // change to our scheduled timer tasks.
  422. RR->sm->whack();
  423. }
  424. void Switch::announceMulticastGroups(const std::map< SharedPtr<Network>,std::set<MulticastGroup> > &allMemberships)
  425. {
  426. std::vector< SharedPtr<Peer> > directPeers;
  427. RR->topology->eachPeer(Topology::CollectPeersWithActiveDirectPath(directPeers,Utils::now()));
  428. #ifdef ZT_TRACE
  429. unsigned int totalMulticastGroups = 0;
  430. for(std::map< SharedPtr<Network>,std::set<MulticastGroup> >::const_iterator i(allMemberships.begin());i!=allMemberships.end();++i)
  431. totalMulticastGroups += (unsigned int)i->second.size();
  432. TRACE("announcing %u multicast groups for %u networks to %u peers",totalMulticastGroups,(unsigned int)allMemberships.size(),(unsigned int)directPeers.size());
  433. #endif
  434. uint64_t now = Utils::now();
  435. for(std::vector< SharedPtr<Peer> >::iterator p(directPeers.begin());p!=directPeers.end();++p) {
  436. Packet outp((*p)->address(),RR->identity.address(),Packet::VERB_MULTICAST_LIKE);
  437. for(std::map< SharedPtr<Network>,std::set<MulticastGroup> >::const_iterator nwmgs(allMemberships.begin());nwmgs!=allMemberships.end();++nwmgs) {
  438. nwmgs->first->pushMembershipCertificate((*p)->address(),false,now);
  439. if ((RR->topology->isSupernode((*p)->address()))||(nwmgs->first->isAllowed((*p)->address()))) {
  440. for(std::set<MulticastGroup>::iterator mg(nwmgs->second.begin());mg!=nwmgs->second.end();++mg) {
  441. if ((outp.size() + 18) > ZT_UDP_DEFAULT_PAYLOAD_MTU) {
  442. send(outp,true);
  443. outp.reset((*p)->address(),RR->identity.address(),Packet::VERB_MULTICAST_LIKE);
  444. }
  445. // network ID, MAC, ADI
  446. outp.append((uint64_t)nwmgs->first->id());
  447. mg->mac().appendTo(outp);
  448. outp.append((uint32_t)mg->adi());
  449. }
  450. }
  451. }
  452. if (outp.size() > ZT_PROTO_MIN_PACKET_LENGTH)
  453. send(outp,true);
  454. }
  455. }
  456. void Switch::announceMulticastGroups(const SharedPtr<Peer> &peer)
  457. {
  458. Packet outp(peer->address(),RR->identity.address(),Packet::VERB_MULTICAST_LIKE);
  459. std::vector< SharedPtr<Network> > networks(RR->nc->networks());
  460. uint64_t now = Utils::now();
  461. for(std::vector< SharedPtr<Network> >::iterator n(networks.begin());n!=networks.end();++n) {
  462. if (((*n)->isAllowed(peer->address()))||(RR->topology->isSupernode(peer->address()))) {
  463. (*n)->pushMembershipCertificate(peer->address(),false,now);
  464. std::set<MulticastGroup> mgs((*n)->multicastGroups());
  465. for(std::set<MulticastGroup>::iterator mg(mgs.begin());mg!=mgs.end();++mg) {
  466. if ((outp.size() + 18) > ZT_UDP_DEFAULT_PAYLOAD_MTU) {
  467. send(outp,true);
  468. outp.reset(peer->address(),RR->identity.address(),Packet::VERB_MULTICAST_LIKE);
  469. }
  470. // network ID, MAC, ADI
  471. outp.append((uint64_t)(*n)->id());
  472. mg->mac().appendTo(outp);
  473. outp.append((uint32_t)mg->adi());
  474. }
  475. }
  476. }
  477. if (outp.size() > ZT_PROTO_MIN_PACKET_LENGTH)
  478. send(outp,true);
  479. }
  480. void Switch::requestWhois(const Address &addr)
  481. {
  482. //TRACE("requesting WHOIS for %s",addr.toString().c_str());
  483. bool inserted = false;
  484. {
  485. Mutex::Lock _l(_outstandingWhoisRequests_m);
  486. std::pair< std::map< Address,WhoisRequest >::iterator,bool > entry(_outstandingWhoisRequests.insert(std::pair<Address,WhoisRequest>(addr,WhoisRequest())));
  487. if ((inserted = entry.second))
  488. entry.first->second.lastSent = Utils::now();
  489. entry.first->second.retries = 0; // reset retry count if entry already existed
  490. }
  491. if (inserted)
  492. _sendWhoisRequest(addr,(const Address *)0,0);
  493. }
  494. void Switch::cancelWhoisRequest(const Address &addr)
  495. {
  496. Mutex::Lock _l(_outstandingWhoisRequests_m);
  497. _outstandingWhoisRequests.erase(addr);
  498. }
  499. void Switch::doAnythingWaitingForPeer(const SharedPtr<Peer> &peer)
  500. {
  501. { // cancel pending WHOIS since we now know this peer
  502. Mutex::Lock _l(_outstandingWhoisRequests_m);
  503. _outstandingWhoisRequests.erase(peer->address());
  504. }
  505. { // finish processing any packets waiting on peer's public key / identity
  506. Mutex::Lock _l(_rxQueue_m);
  507. for(std::list< SharedPtr<IncomingPacket> >::iterator rxi(_rxQueue.begin());rxi!=_rxQueue.end();) {
  508. if ((*rxi)->tryDecode(_r))
  509. _rxQueue.erase(rxi++);
  510. else ++rxi;
  511. }
  512. }
  513. { // finish sending any packets waiting on peer's public key / identity
  514. Mutex::Lock _l(_txQueue_m);
  515. std::pair< std::multimap< Address,TXQueueEntry >::iterator,std::multimap< Address,TXQueueEntry >::iterator > waitingTxQueueItems(_txQueue.equal_range(peer->address()));
  516. for(std::multimap< Address,TXQueueEntry >::iterator txi(waitingTxQueueItems.first);txi!=waitingTxQueueItems.second;) {
  517. if (_trySend(txi->second.packet,txi->second.encrypt))
  518. _txQueue.erase(txi++);
  519. else ++txi;
  520. }
  521. }
  522. }
  523. unsigned long Switch::doTimerTasks()
  524. {
  525. unsigned long nextDelay = ~((unsigned long)0); // big number, caller will cap return value
  526. uint64_t now = Utils::now();
  527. {
  528. Mutex::Lock _l(_contactQueue_m);
  529. for(std::list<ContactQueueEntry>::iterator qi(_contactQueue.begin());qi!=_contactQueue.end();) {
  530. if (now >= qi->fireAtTime) {
  531. if (!qi->peer->hasActiveDirectPath(now)) {
  532. TRACE("deploying aggressive NAT-t against %s(%s)",qi->peer->address().toString().c_str(),qi->inaddr.toString().c_str());
  533. /* Shotgun approach -- literally -- against symmetric NATs. Most of these
  534. * either increment or decrement ports so this gets a good number. Also try
  535. * the original port one more time for good measure, since sometimes it
  536. * fails first time around. */
  537. int p = (int)qi->inaddr.port() - 2;
  538. for(int k=0;k<5;++k) {
  539. if ((p > 0)&&(p <= 0xffff)) {
  540. qi->inaddr.setPort((unsigned int)p);
  541. sendHELLO(qi->peer,qi->inaddr);
  542. }
  543. ++p;
  544. }
  545. }
  546. _contactQueue.erase(qi++);
  547. } else {
  548. nextDelay = std::min(nextDelay,(unsigned long)(qi->fireAtTime - now));
  549. ++qi;
  550. }
  551. }
  552. }
  553. {
  554. Mutex::Lock _l(_outstandingWhoisRequests_m);
  555. for(std::map< Address,WhoisRequest >::iterator i(_outstandingWhoisRequests.begin());i!=_outstandingWhoisRequests.end();) {
  556. unsigned long since = (unsigned long)(now - i->second.lastSent);
  557. if (since >= ZT_WHOIS_RETRY_DELAY) {
  558. if (i->second.retries >= ZT_MAX_WHOIS_RETRIES) {
  559. TRACE("WHOIS %s timed out",i->first.toString().c_str());
  560. _outstandingWhoisRequests.erase(i++);
  561. continue;
  562. } else {
  563. i->second.lastSent = now;
  564. i->second.peersConsulted[i->second.retries] = _sendWhoisRequest(i->first,i->second.peersConsulted,i->second.retries);
  565. ++i->second.retries;
  566. TRACE("WHOIS %s (retry %u)",i->first.toString().c_str(),i->second.retries);
  567. nextDelay = std::min(nextDelay,(unsigned long)ZT_WHOIS_RETRY_DELAY);
  568. }
  569. } else nextDelay = std::min(nextDelay,ZT_WHOIS_RETRY_DELAY - since);
  570. ++i;
  571. }
  572. }
  573. {
  574. Mutex::Lock _l(_txQueue_m);
  575. for(std::multimap< Address,TXQueueEntry >::iterator i(_txQueue.begin());i!=_txQueue.end();) {
  576. if (_trySend(i->second.packet,i->second.encrypt))
  577. _txQueue.erase(i++);
  578. else if ((now - i->second.creationTime) > ZT_TRANSMIT_QUEUE_TIMEOUT) {
  579. TRACE("TX %s -> %s timed out",i->second.packet.source().toString().c_str(),i->second.packet.destination().toString().c_str());
  580. _txQueue.erase(i++);
  581. } else ++i;
  582. }
  583. }
  584. {
  585. Mutex::Lock _l(_rxQueue_m);
  586. for(std::list< SharedPtr<IncomingPacket> >::iterator i(_rxQueue.begin());i!=_rxQueue.end();) {
  587. if ((now - (*i)->receiveTime()) > ZT_RECEIVE_QUEUE_TIMEOUT) {
  588. TRACE("RX %s -> %s timed out",(*i)->source().toString().c_str(),(*i)->destination().toString().c_str());
  589. _rxQueue.erase(i++);
  590. } else ++i;
  591. }
  592. }
  593. {
  594. Mutex::Lock _l(_defragQueue_m);
  595. for(std::map< uint64_t,DefragQueueEntry >::iterator i(_defragQueue.begin());i!=_defragQueue.end();) {
  596. if ((now - i->second.creationTime) > ZT_FRAGMENTED_PACKET_RECEIVE_TIMEOUT) {
  597. TRACE("incomplete fragmented packet %.16llx timed out, fragments discarded",i->first);
  598. _defragQueue.erase(i++);
  599. } else ++i;
  600. }
  601. }
  602. return std::max(nextDelay,(unsigned long)10); // minimum delay
  603. }
  604. const char *Switch::etherTypeName(const unsigned int etherType)
  605. throw()
  606. {
  607. switch(etherType) {
  608. case ZT_ETHERTYPE_IPV4: return "IPV4";
  609. case ZT_ETHERTYPE_ARP: return "ARP";
  610. case ZT_ETHERTYPE_RARP: return "RARP";
  611. case ZT_ETHERTYPE_ATALK: return "ATALK";
  612. case ZT_ETHERTYPE_AARP: return "AARP";
  613. case ZT_ETHERTYPE_IPX_A: return "IPX_A";
  614. case ZT_ETHERTYPE_IPX_B: return "IPX_B";
  615. case ZT_ETHERTYPE_IPV6: return "IPV6";
  616. }
  617. return "UNKNOWN";
  618. }
  619. void Switch::_handleRemotePacketFragment(const SharedPtr<Socket> &fromSock,const InetAddress &fromAddr,const Buffer<4096> &data)
  620. {
  621. Packet::Fragment fragment(data);
  622. Address destination(fragment.destination());
  623. if (destination != RR->identity.address()) {
  624. // Fragment is not for us, so try to relay it
  625. if (fragment.hops() < ZT_RELAY_MAX_HOPS) {
  626. fragment.incrementHops();
  627. // Note: we don't bother initiating NAT-t for fragments, since heads will set that off.
  628. // It wouldn't hurt anything, just redundant and unnecessary.
  629. SharedPtr<Peer> relayTo = RR->topology->getPeer(destination);
  630. if ((!relayTo)||(relayTo->send(RR,fragment.data(),fragment.size(),Utils::now()) == Path::PATH_TYPE_NULL)) {
  631. // Don't know peer or no direct path -- so relay via supernode
  632. relayTo = RR->topology->getBestSupernode();
  633. if (relayTo)
  634. relayTo->send(RR,fragment.data(),fragment.size(),Utils::now());
  635. }
  636. } else {
  637. TRACE("dropped relay [fragment](%s) -> %s, max hops exceeded",fromAddr.toString().c_str(),destination.toString().c_str());
  638. }
  639. } else {
  640. // Fragment looks like ours
  641. uint64_t pid = fragment.packetId();
  642. unsigned int fno = fragment.fragmentNumber();
  643. unsigned int tf = fragment.totalFragments();
  644. if ((tf <= ZT_MAX_PACKET_FRAGMENTS)&&(fno < ZT_MAX_PACKET_FRAGMENTS)&&(fno > 0)&&(tf > 1)) {
  645. // Fragment appears basically sane. Its fragment number must be
  646. // 1 or more, since a Packet with fragmented bit set is fragment 0.
  647. // Total fragments must be more than 1, otherwise why are we
  648. // seeing a Packet::Fragment?
  649. Mutex::Lock _l(_defragQueue_m);
  650. std::map< uint64_t,DefragQueueEntry >::iterator dqe(_defragQueue.find(pid));
  651. if (dqe == _defragQueue.end()) {
  652. // We received a Packet::Fragment without its head, so queue it and wait
  653. DefragQueueEntry &dq = _defragQueue[pid];
  654. dq.creationTime = Utils::now();
  655. dq.frags[fno - 1] = fragment;
  656. dq.totalFragments = tf; // total fragment count is known
  657. dq.haveFragments = 1 << fno; // we have only this fragment
  658. //TRACE("fragment (%u/%u) of %.16llx from %s",fno + 1,tf,pid,fromAddr.toString().c_str());
  659. } else if (!(dqe->second.haveFragments & (1 << fno))) {
  660. // We have other fragments and maybe the head, so add this one and check
  661. dqe->second.frags[fno - 1] = fragment;
  662. dqe->second.totalFragments = tf;
  663. //TRACE("fragment (%u/%u) of %.16llx from %s",fno + 1,tf,pid,fromAddr.toString().c_str());
  664. if (Utils::countBits(dqe->second.haveFragments |= (1 << fno)) == tf) {
  665. // We have all fragments -- assemble and process full Packet
  666. //TRACE("packet %.16llx is complete, assembling and processing...",pid);
  667. SharedPtr<IncomingPacket> packet(dqe->second.frag0);
  668. for(unsigned int f=1;f<tf;++f)
  669. packet->append(dqe->second.frags[f - 1].payload(),dqe->second.frags[f - 1].payloadLength());
  670. _defragQueue.erase(dqe);
  671. if (!packet->tryDecode(_r)) {
  672. Mutex::Lock _l(_rxQueue_m);
  673. _rxQueue.push_back(packet);
  674. }
  675. }
  676. } // else this is a duplicate fragment, ignore
  677. }
  678. }
  679. }
  680. void Switch::_handleRemotePacketHead(const SharedPtr<Socket> &fromSock,const InetAddress &fromAddr,const Buffer<4096> &data)
  681. {
  682. SharedPtr<IncomingPacket> packet(new IncomingPacket(data,fromSock,fromAddr));
  683. Address source(packet->source());
  684. Address destination(packet->destination());
  685. //TRACE("<< %.16llx %s -> %s (size: %u)",(unsigned long long)packet->packetId(),source.toString().c_str(),destination.toString().c_str(),packet->size());
  686. if (destination != RR->identity.address()) {
  687. // Packet is not for us, so try to relay it
  688. if (packet->hops() < ZT_RELAY_MAX_HOPS) {
  689. packet->incrementHops();
  690. SharedPtr<Peer> relayTo = RR->topology->getPeer(destination);
  691. Path::Type relayedVia;
  692. if ((relayTo)&&((relayedVia = relayTo->send(RR,packet->data(),packet->size(),Utils::now())) != Path::PATH_TYPE_NULL)) {
  693. /* If both paths are UDP, attempt to invoke UDP NAT-t between peers
  694. * by sending VERB_RENDEZVOUS. Do not do this for TCP due to GitHub
  695. * issue #63. */
  696. if ((fromSock->udp())&&(relayedVia == Path::PATH_TYPE_UDP))
  697. unite(source,destination,false);
  698. } else {
  699. // Don't know peer or no direct path -- so relay via supernode
  700. relayTo = RR->topology->getBestSupernode(&source,1,true);
  701. if (relayTo)
  702. relayTo->send(RR,packet->data(),packet->size(),Utils::now());
  703. }
  704. } else {
  705. TRACE("dropped relay %s(%s) -> %s, max hops exceeded",packet->source().toString().c_str(),fromAddr.toString().c_str(),destination.toString().c_str());
  706. }
  707. } else if (packet->fragmented()) {
  708. // Packet is the head of a fragmented packet series
  709. uint64_t pid = packet->packetId();
  710. Mutex::Lock _l(_defragQueue_m);
  711. std::map< uint64_t,DefragQueueEntry >::iterator dqe(_defragQueue.find(pid));
  712. if (dqe == _defragQueue.end()) {
  713. // If we have no other fragments yet, create an entry and save the head
  714. DefragQueueEntry &dq = _defragQueue[pid];
  715. dq.creationTime = Utils::now();
  716. dq.frag0 = packet;
  717. dq.totalFragments = 0; // 0 == unknown, waiting for Packet::Fragment
  718. dq.haveFragments = 1; // head is first bit (left to right)
  719. //TRACE("fragment (0/?) of %.16llx from %s",pid,fromAddr.toString().c_str());
  720. } else if (!(dqe->second.haveFragments & 1)) {
  721. // If we have other fragments but no head, see if we are complete with the head
  722. if ((dqe->second.totalFragments)&&(Utils::countBits(dqe->second.haveFragments |= 1) == dqe->second.totalFragments)) {
  723. // We have all fragments -- assemble and process full Packet
  724. //TRACE("packet %.16llx is complete, assembling and processing...",pid);
  725. // packet already contains head, so append fragments
  726. for(unsigned int f=1;f<dqe->second.totalFragments;++f)
  727. packet->append(dqe->second.frags[f - 1].payload(),dqe->second.frags[f - 1].payloadLength());
  728. _defragQueue.erase(dqe);
  729. if (!packet->tryDecode(_r)) {
  730. Mutex::Lock _l(_rxQueue_m);
  731. _rxQueue.push_back(packet);
  732. }
  733. } else {
  734. // Still waiting on more fragments, so queue the head
  735. dqe->second.frag0 = packet;
  736. }
  737. } // else this is a duplicate head, ignore
  738. } else {
  739. // Packet is unfragmented, so just process it
  740. if (!packet->tryDecode(_r)) {
  741. Mutex::Lock _l(_rxQueue_m);
  742. _rxQueue.push_back(packet);
  743. }
  744. }
  745. }
  746. void Switch::_handleBeacon(const SharedPtr<Socket> &fromSock,const InetAddress &fromAddr,const Buffer<4096> &data)
  747. {
  748. Address beaconAddr(data.field(ZT_PROTO_BEACON_IDX_ADDRESS,ZT_ADDRESS_LENGTH),ZT_ADDRESS_LENGTH);
  749. if (beaconAddr == RR->identity.address())
  750. return;
  751. SharedPtr<Peer> peer(RR->topology->getPeer(beaconAddr));
  752. if (peer) {
  753. uint64_t now = Utils::now();
  754. if (peer->haveUdpPath(fromAddr)) {
  755. if ((now - peer->lastDirectReceive()) >= ZT_PEER_DIRECT_PING_DELAY)
  756. peer->sendPing(RR,now);
  757. } else {
  758. if ((now - _lastBeacon) < ZT_MIN_BEACON_RESPONSE_INTERVAL)
  759. return;
  760. _lastBeacon = now;
  761. sendHELLO(peer,fromAddr);
  762. }
  763. }
  764. }
  765. Address Switch::_sendWhoisRequest(const Address &addr,const Address *peersAlreadyConsulted,unsigned int numPeersAlreadyConsulted)
  766. {
  767. SharedPtr<Peer> supernode(RR->topology->getBestSupernode(peersAlreadyConsulted,numPeersAlreadyConsulted,false));
  768. if (supernode) {
  769. Packet outp(supernode->address(),RR->identity.address(),Packet::VERB_WHOIS);
  770. addr.appendTo(outp);
  771. outp.armor(supernode->key(),true);
  772. uint64_t now = Utils::now();
  773. if (supernode->send(RR,outp.data(),outp.size(),now) != Path::PATH_TYPE_NULL)
  774. return supernode->address();
  775. }
  776. return Address();
  777. }
  778. bool Switch::_trySend(const Packet &packet,bool encrypt)
  779. {
  780. SharedPtr<Peer> peer(RR->topology->getPeer(packet.destination()));
  781. if (peer) {
  782. uint64_t now = Utils::now();
  783. SharedPtr<Peer> via;
  784. if (peer->hasActiveDirectPath(now)) {
  785. via = peer;
  786. } else {
  787. via = RR->topology->getBestSupernode();
  788. if (!via)
  789. return false;
  790. }
  791. Packet tmp(packet);
  792. unsigned int chunkSize = std::min(tmp.size(),(unsigned int)ZT_UDP_DEFAULT_PAYLOAD_MTU);
  793. tmp.setFragmented(chunkSize < tmp.size());
  794. tmp.armor(peer->key(),encrypt);
  795. if (via->send(RR,tmp.data(),chunkSize,now) != Path::PATH_TYPE_NULL) {
  796. if (chunkSize < tmp.size()) {
  797. // Too big for one bite, fragment the rest
  798. unsigned int fragStart = chunkSize;
  799. unsigned int remaining = tmp.size() - chunkSize;
  800. unsigned int fragsRemaining = (remaining / (ZT_UDP_DEFAULT_PAYLOAD_MTU - ZT_PROTO_MIN_FRAGMENT_LENGTH));
  801. if ((fragsRemaining * (ZT_UDP_DEFAULT_PAYLOAD_MTU - ZT_PROTO_MIN_FRAGMENT_LENGTH)) < remaining)
  802. ++fragsRemaining;
  803. unsigned int totalFragments = fragsRemaining + 1;
  804. for(unsigned int f=0;f<fragsRemaining;++f) {
  805. chunkSize = std::min(remaining,(unsigned int)(ZT_UDP_DEFAULT_PAYLOAD_MTU - ZT_PROTO_MIN_FRAGMENT_LENGTH));
  806. Packet::Fragment frag(tmp,fragStart,chunkSize,f + 1,totalFragments);
  807. via->send(RR,frag.data(),frag.size(),now);
  808. fragStart += chunkSize;
  809. remaining -= chunkSize;
  810. }
  811. }
  812. return true;
  813. }
  814. } else requestWhois(packet.destination());
  815. return false;
  816. }
  817. } // namespace ZeroTier