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

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