Switch.cpp 34 KB

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