Switch.cpp 35 KB

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