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 19KB

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