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

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