You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

CConn.cxx 18KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656
  1. /* Copyright (C) 2002-2005 RealVNC Ltd. All Rights Reserved.
  2. * Copyright (C) 2011 D. R. Commander. All Rights Reserved.
  3. * Copyright 2009-2014 Pierre Ossman for Cendio AB
  4. *
  5. * This 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 2 of the License, or
  8. * (at your option) any later version.
  9. *
  10. * This software 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 software; if not, write to the Free Software
  17. * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307,
  18. * USA.
  19. */
  20. #ifdef HAVE_CONFIG_H
  21. #include <config.h>
  22. #endif
  23. #include <assert.h>
  24. #ifndef _WIN32
  25. #include <unistd.h>
  26. #endif
  27. #include <rfb/CMsgWriter.h>
  28. #include <rfb/encodings.h>
  29. #include <rfb/Decoder.h>
  30. #include <rfb/Hostname.h>
  31. #include <rfb/LogWriter.h>
  32. #include <rfb/util.h>
  33. #include <rfb/screenTypes.h>
  34. #include <rfb/fenceTypes.h>
  35. #include <rfb/Timer.h>
  36. #include <rdr/MemInStream.h>
  37. #include <rdr/MemOutStream.h>
  38. #include <network/TcpSocket.h>
  39. #include <FL/Fl.H>
  40. #include <FL/fl_ask.H>
  41. #include "CConn.h"
  42. #include "OptionsDialog.h"
  43. #include "DesktopWindow.h"
  44. #include "i18n.h"
  45. #include "parameters.h"
  46. #include "vncviewer.h"
  47. #ifdef WIN32
  48. #include "win32.h"
  49. #endif
  50. using namespace rdr;
  51. using namespace rfb;
  52. using namespace std;
  53. static rfb::LogWriter vlog("CConn");
  54. // 8 colours (1 bit per component)
  55. static const PixelFormat verylowColourPF(8, 3,false, true,
  56. 1, 1, 1, 2, 1, 0);
  57. // 64 colours (2 bits per component)
  58. static const PixelFormat lowColourPF(8, 6, false, true,
  59. 3, 3, 3, 4, 2, 0);
  60. // 256 colours (2-3 bits per component)
  61. static const PixelFormat mediumColourPF(8, 8, false, true,
  62. 7, 7, 3, 5, 2, 0);
  63. CConn::CConn(const char* vncServerName, network::Socket* socket=NULL)
  64. : serverHost(0), serverPort(0), desktop(NULL),
  65. pendingPFChange(false),
  66. currentEncoding(encodingTight), lastServerEncoding((unsigned int)-1),
  67. formatChange(false), encodingChange(false),
  68. firstUpdate(true), pendingUpdate(false), continuousUpdates(false),
  69. forceNonincremental(true), supportsSyncFence(false)
  70. {
  71. setShared(::shared);
  72. sock = socket;
  73. memset(decoders, 0, sizeof(decoders));
  74. int encNum = encodingNum(preferredEncoding);
  75. if (encNum != -1)
  76. currentEncoding = encNum;
  77. cp.supportsLocalCursor = true;
  78. cp.supportsDesktopResize = true;
  79. cp.supportsExtendedDesktopSize = true;
  80. cp.supportsDesktopRename = true;
  81. if (customCompressLevel)
  82. cp.compressLevel = compressLevel;
  83. else
  84. cp.compressLevel = -1;
  85. if (!noJpeg)
  86. cp.qualityLevel = qualityLevel;
  87. else
  88. cp.qualityLevel = -1;
  89. if(sock == NULL) {
  90. try {
  91. getHostAndPort(vncServerName, &serverHost, &serverPort);
  92. sock = new network::TcpSocket(serverHost, serverPort);
  93. vlog.info(_("connected to host %s port %d"), serverHost, serverPort);
  94. } catch (rdr::Exception& e) {
  95. vlog.error("%s", e.str());
  96. fl_alert("%s", e.str());
  97. exit_vncviewer();
  98. return;
  99. }
  100. }
  101. Fl::add_fd(sock->getFd(), FL_READ | FL_EXCEPT, socketEvent, this);
  102. // See callback below
  103. sock->inStream().setBlockCallback(this);
  104. setServerName(serverHost);
  105. setStreams(&sock->inStream(), &sock->outStream());
  106. initialiseProtocol();
  107. OptionsDialog::addCallback(handleOptions, this);
  108. }
  109. CConn::~CConn()
  110. {
  111. OptionsDialog::removeCallback(handleOptions);
  112. for (int i = 0; i < sizeof(decoders)/sizeof(decoders[0]); i++)
  113. delete decoders[i];
  114. if (desktop)
  115. delete desktop;
  116. delete [] serverHost;
  117. if (sock)
  118. Fl::remove_fd(sock->getFd());
  119. delete sock;
  120. }
  121. void CConn::refreshFramebuffer()
  122. {
  123. forceNonincremental = true;
  124. // Without fences, we cannot safely trigger an update request directly
  125. // but must wait for the next update to arrive.
  126. if (supportsSyncFence)
  127. requestNewUpdate();
  128. }
  129. const char *CConn::connectionInfo()
  130. {
  131. static char infoText[1024] = "";
  132. char pfStr[100];
  133. char spfStr[100];
  134. cp.pf().print(pfStr, 100);
  135. serverPF.print(spfStr, 100);
  136. int secType = csecurity->getType();
  137. snprintf(infoText, sizeof(infoText),
  138. _("Desktop name: %.80s\n"
  139. "Host: %.80s port: %d\n"
  140. "Size: %d x %d\n"
  141. "Pixel format: %s\n"
  142. "(server default %s)\n"
  143. "Requested encoding: %s\n"
  144. "Last used encoding: %s\n"
  145. "Line speed estimate: %d kbit/s\n"
  146. "Protocol version: %d.%d\n"
  147. "Security method: %s\n"),
  148. cp.name(), serverHost, serverPort, cp.width, cp.height,
  149. pfStr, spfStr, encodingName(currentEncoding),
  150. encodingName(lastServerEncoding),
  151. sock->inStream().kbitsPerSecond(),
  152. cp.majorVersion, cp.minorVersion,
  153. secTypeName(secType));
  154. return infoText;
  155. }
  156. // The RFB core is not properly asynchronous, so it calls this callback
  157. // whenever it needs to block to wait for more data. Since FLTK is
  158. // monitoring the socket, we just make sure FLTK gets to run.
  159. void CConn::blockCallback()
  160. {
  161. int next_timer;
  162. next_timer = Timer::checkTimeouts();
  163. if (next_timer == 0)
  164. next_timer = INT_MAX;
  165. Fl::wait((double)next_timer / 1000.0);
  166. }
  167. void CConn::socketEvent(FL_SOCKET fd, void *data)
  168. {
  169. CConn *cc;
  170. static bool recursing = false;
  171. assert(data);
  172. cc = (CConn*)data;
  173. // I don't think processMsg() is recursion safe, so add this check
  174. if (recursing)
  175. return;
  176. recursing = true;
  177. try {
  178. // processMsg() only processes one message, so we need to loop
  179. // until the buffers are empty or things will stall.
  180. do {
  181. cc->processMsg();
  182. } while (cc->sock->inStream().checkNoWait(1));
  183. } catch (rdr::EndOfStream& e) {
  184. vlog.info("%s", e.str());
  185. exit_vncviewer();
  186. } catch (rdr::Exception& e) {
  187. vlog.error("%s", e.str());
  188. exit_vncviewer(e.str());
  189. }
  190. recursing = false;
  191. }
  192. ////////////////////// CConnection callback methods //////////////////////
  193. // serverInit() is called when the serverInit message has been received. At
  194. // this point we create the desktop window and display it. We also tell the
  195. // server the pixel format and encodings to use and request the first update.
  196. void CConn::serverInit()
  197. {
  198. CConnection::serverInit();
  199. // If using AutoSelect with old servers, start in FullColor
  200. // mode. See comment in autoSelectFormatAndEncoding.
  201. if (cp.beforeVersion(3, 8) && autoSelect)
  202. fullColour.setParam(true);
  203. serverPF = cp.pf();
  204. desktop = new DesktopWindow(cp.width, cp.height, cp.name(), serverPF, this);
  205. fullColourPF = desktop->getPreferredPF();
  206. // Force a switch to the format and encoding we'd like
  207. formatChange = encodingChange = true;
  208. // And kick off the update cycle
  209. requestNewUpdate();
  210. // This initial update request is a bit of a corner case, so we need
  211. // to help out setting the correct format here.
  212. assert(pendingPFChange);
  213. cp.setPF(pendingPF);
  214. pendingPFChange = false;
  215. }
  216. // setDesktopSize() is called when the desktop size changes (including when
  217. // it is set initially).
  218. void CConn::setDesktopSize(int w, int h)
  219. {
  220. CConnection::setDesktopSize(w,h);
  221. resizeFramebuffer();
  222. }
  223. // setExtendedDesktopSize() is a more advanced version of setDesktopSize()
  224. void CConn::setExtendedDesktopSize(int reason, int result, int w, int h,
  225. const rfb::ScreenSet& layout)
  226. {
  227. CConnection::setExtendedDesktopSize(reason, result, w, h, layout);
  228. if ((reason == reasonClient) && (result != resultSuccess)) {
  229. vlog.error(_("SetDesktopSize failed: %d"), result);
  230. return;
  231. }
  232. resizeFramebuffer();
  233. }
  234. // setName() is called when the desktop name changes
  235. void CConn::setName(const char* name)
  236. {
  237. CConnection::setName(name);
  238. if (desktop)
  239. desktop->setName(name);
  240. }
  241. // framebufferUpdateStart() is called at the beginning of an update.
  242. // Here we try to send out a new framebuffer update request so that the
  243. // next update can be sent out in parallel with us decoding the current
  244. // one.
  245. void CConn::framebufferUpdateStart()
  246. {
  247. // Note: This might not be true if sync fences are supported
  248. pendingUpdate = false;
  249. requestNewUpdate();
  250. }
  251. // framebufferUpdateEnd() is called at the end of an update.
  252. // For each rectangle, the FdInStream will have timed the speed
  253. // of the connection, allowing us to select format and encoding
  254. // appropriately, and then request another incremental update.
  255. void CConn::framebufferUpdateEnd()
  256. {
  257. desktop->updateWindow();
  258. if (firstUpdate) {
  259. // We need fences to make extra update requests and continuous
  260. // updates "safe". See fence() for the next step.
  261. if (cp.supportsFence)
  262. writer()->writeFence(fenceFlagRequest | fenceFlagSyncNext, 0, NULL);
  263. firstUpdate = false;
  264. }
  265. // A format change has been scheduled and we are now past the update
  266. // with the old format. Time to active the new one.
  267. if (pendingPFChange) {
  268. cp.setPF(pendingPF);
  269. pendingPFChange = false;
  270. }
  271. // Compute new settings based on updated bandwidth values
  272. if (autoSelect)
  273. autoSelectFormatAndEncoding();
  274. // Make sure that the FLTK handling and the timers gets some CPU time
  275. // in case of back to back framebuffer updates.
  276. Fl::check();
  277. Timer::checkTimeouts();
  278. }
  279. // The rest of the callbacks are fairly self-explanatory...
  280. void CConn::setColourMapEntries(int firstColour, int nColours, rdr::U16* rgbs)
  281. {
  282. vlog.error("Invalid SetColourMapEntries from server!");
  283. }
  284. void CConn::bell()
  285. {
  286. fl_beep();
  287. }
  288. void CConn::serverCutText(const char* str, rdr::U32 len)
  289. {
  290. char *buffer;
  291. int size, ret;
  292. if (!acceptClipboard)
  293. return;
  294. size = fl_utf8froma(NULL, 0, str, len);
  295. if (size <= 0)
  296. return;
  297. size++;
  298. buffer = new char[size];
  299. ret = fl_utf8froma(buffer, size, str, len);
  300. assert(ret < size);
  301. vlog.debug("Got clipboard data (%d bytes)", strlen(buffer));
  302. // RFB doesn't have separate selection and clipboard concepts, so we
  303. // dump the data into both variants.
  304. Fl::copy(buffer, ret, 0);
  305. Fl::copy(buffer, ret, 1);
  306. delete [] buffer;
  307. }
  308. void CConn::dataRect(const Rect& r, int encoding)
  309. {
  310. sock->inStream().startTiming();
  311. if (encoding != encodingCopyRect)
  312. lastServerEncoding = encoding;
  313. if (!Decoder::supported(encoding)) {
  314. fprintf(stderr, "Unknown rect encoding %d\n", encoding);
  315. throw Exception("Unknown rect encoding");
  316. }
  317. if (!decoders[encoding]) {
  318. decoders[encoding] = Decoder::createDecoder(encoding, this);
  319. if (!decoders[encoding]) {
  320. fprintf(stderr, "Unknown rect encoding %d\n", encoding);
  321. throw Exception("Unknown rect encoding");
  322. }
  323. }
  324. decoders[encoding]->readRect(r, desktop->getFramebuffer());
  325. sock->inStream().stopTiming();
  326. }
  327. void CConn::setCursor(int width, int height, const Point& hotspot,
  328. void* data, void* mask)
  329. {
  330. desktop->setCursor(width, height, hotspot, data, mask);
  331. }
  332. void CConn::fence(rdr::U32 flags, unsigned len, const char data[])
  333. {
  334. CMsgHandler::fence(flags, len, data);
  335. if (flags & fenceFlagRequest) {
  336. // We handle everything synchronously so we trivially honor these modes
  337. flags = flags & (fenceFlagBlockBefore | fenceFlagBlockAfter);
  338. writer()->writeFence(flags, len, data);
  339. return;
  340. }
  341. if (len == 0) {
  342. // Initial probe
  343. if (flags & fenceFlagSyncNext) {
  344. supportsSyncFence = true;
  345. if (cp.supportsContinuousUpdates) {
  346. vlog.info(_("Enabling continuous updates"));
  347. continuousUpdates = true;
  348. writer()->writeEnableContinuousUpdates(true, 0, 0, cp.width, cp.height);
  349. }
  350. }
  351. } else {
  352. // Pixel format change
  353. rdr::MemInStream memStream(data, len);
  354. PixelFormat pf;
  355. pf.read(&memStream);
  356. cp.setPF(pf);
  357. }
  358. }
  359. ////////////////////// Internal methods //////////////////////
  360. void CConn::resizeFramebuffer()
  361. {
  362. if (!desktop)
  363. return;
  364. if (continuousUpdates)
  365. writer()->writeEnableContinuousUpdates(true, 0, 0, cp.width, cp.height);
  366. desktop->resizeFramebuffer(cp.width, cp.height);
  367. }
  368. // autoSelectFormatAndEncoding() chooses the format and encoding appropriate
  369. // to the connection speed:
  370. //
  371. // First we wait for at least one second of bandwidth measurement.
  372. //
  373. // Above 16Mbps (i.e. LAN), we choose the second highest JPEG quality,
  374. // which should be perceptually lossless.
  375. //
  376. // If the bandwidth is below that, we choose a more lossy JPEG quality.
  377. //
  378. // If the bandwidth drops below 256 Kbps, we switch to palette mode.
  379. //
  380. // Note: The system here is fairly arbitrary and should be replaced
  381. // with something more intelligent at the server end.
  382. //
  383. void CConn::autoSelectFormatAndEncoding()
  384. {
  385. int kbitsPerSecond = sock->inStream().kbitsPerSecond();
  386. unsigned int timeWaited = sock->inStream().timeWaited();
  387. bool newFullColour = fullColour;
  388. int newQualityLevel = qualityLevel;
  389. // Always use Tight
  390. if (currentEncoding != encodingTight) {
  391. currentEncoding = encodingTight;
  392. encodingChange = true;
  393. }
  394. // Check that we have a decent bandwidth measurement
  395. if ((kbitsPerSecond == 0) || (timeWaited < 10000))
  396. return;
  397. // Select appropriate quality level
  398. if (!noJpeg) {
  399. if (kbitsPerSecond > 16000)
  400. newQualityLevel = 8;
  401. else
  402. newQualityLevel = 6;
  403. if (newQualityLevel != qualityLevel) {
  404. vlog.info(_("Throughput %d kbit/s - changing to quality %d"),
  405. kbitsPerSecond, newQualityLevel);
  406. cp.qualityLevel = newQualityLevel;
  407. qualityLevel.setParam(newQualityLevel);
  408. encodingChange = true;
  409. }
  410. }
  411. if (cp.beforeVersion(3, 8)) {
  412. // Xvnc from TightVNC 1.2.9 sends out FramebufferUpdates with
  413. // cursors "asynchronously". If this happens in the middle of a
  414. // pixel format change, the server will encode the cursor with
  415. // the old format, but the client will try to decode it
  416. // according to the new format. This will lead to a
  417. // crash. Therefore, we do not allow automatic format change for
  418. // old servers.
  419. return;
  420. }
  421. // Select best color level
  422. newFullColour = (kbitsPerSecond > 256);
  423. if (newFullColour != fullColour) {
  424. vlog.info(_("Throughput %d kbit/s - full color is now %s"),
  425. kbitsPerSecond,
  426. newFullColour ? _("enabled") : _("disabled"));
  427. fullColour.setParam(newFullColour);
  428. formatChange = true;
  429. }
  430. }
  431. // checkEncodings() sends a setEncodings message if one is needed.
  432. void CConn::checkEncodings()
  433. {
  434. if (encodingChange && writer()) {
  435. vlog.info(_("Using %s encoding"),encodingName(currentEncoding));
  436. writer()->writeSetEncodings(currentEncoding, true);
  437. encodingChange = false;
  438. }
  439. }
  440. // requestNewUpdate() requests an update from the server, having set the
  441. // format and encoding appropriately.
  442. void CConn::requestNewUpdate()
  443. {
  444. if (formatChange) {
  445. PixelFormat pf;
  446. /* Catch incorrect requestNewUpdate calls */
  447. assert(!pendingUpdate || supportsSyncFence);
  448. if (fullColour) {
  449. pf = fullColourPF;
  450. } else {
  451. if (lowColourLevel == 0)
  452. pf = verylowColourPF;
  453. else if (lowColourLevel == 1)
  454. pf = lowColourPF;
  455. else
  456. pf = mediumColourPF;
  457. }
  458. if (supportsSyncFence) {
  459. // We let the fence carry the pixel format and switch once we
  460. // get the response back. That way we will be synchronised with
  461. // when the server switches.
  462. rdr::MemOutStream memStream;
  463. pf.write(&memStream);
  464. writer()->writeFence(fenceFlagRequest | fenceFlagSyncNext,
  465. memStream.length(), (const char*)memStream.data());
  466. } else {
  467. // New requests are sent out at the start of processing the last
  468. // one, so we cannot switch our internal format right now (doing so
  469. // would mean misdecoding the current update).
  470. pendingPFChange = true;
  471. pendingPF = pf;
  472. }
  473. char str[256];
  474. pf.print(str, 256);
  475. vlog.info(_("Using pixel format %s"),str);
  476. writer()->writeSetPixelFormat(pf);
  477. formatChange = false;
  478. }
  479. checkEncodings();
  480. if (forceNonincremental || !continuousUpdates) {
  481. pendingUpdate = true;
  482. writer()->writeFramebufferUpdateRequest(Rect(0, 0, cp.width, cp.height),
  483. !forceNonincremental);
  484. }
  485. forceNonincremental = false;
  486. }
  487. void CConn::handleOptions(void *data)
  488. {
  489. CConn *self = (CConn*)data;
  490. // Checking all the details of the current set of encodings is just
  491. // a pain. Assume something has changed, as resending the encoding
  492. // list is cheap. Avoid overriding what the auto logic has selected
  493. // though.
  494. if (!autoSelect) {
  495. int encNum = encodingNum(preferredEncoding);
  496. if (encNum != -1)
  497. self->currentEncoding = encNum;
  498. }
  499. self->cp.supportsLocalCursor = true;
  500. if (customCompressLevel)
  501. self->cp.compressLevel = compressLevel;
  502. else
  503. self->cp.compressLevel = -1;
  504. if (!noJpeg && !autoSelect)
  505. self->cp.qualityLevel = qualityLevel;
  506. else
  507. self->cp.qualityLevel = -1;
  508. self->encodingChange = true;
  509. // Format changes refreshes the entire screen though and are therefore
  510. // very costly. It's probably worth the effort to see if it is necessary
  511. // here.
  512. PixelFormat pf;
  513. if (fullColour) {
  514. pf = self->fullColourPF;
  515. } else {
  516. if (lowColourLevel == 0)
  517. pf = verylowColourPF;
  518. else if (lowColourLevel == 1)
  519. pf = lowColourPF;
  520. else
  521. pf = mediumColourPF;
  522. }
  523. if (!pf.equal(self->cp.pf())) {
  524. self->formatChange = true;
  525. // Without fences, we cannot safely trigger an update request directly
  526. // but must wait for the next update to arrive.
  527. if (self->supportsSyncFence)
  528. self->requestNewUpdate();
  529. }
  530. }