Switch.cpp 34 KB

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