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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605
  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 <network/TcpSocket.h>
  37. #ifndef WIN32
  38. #include <network/UnixSocket.h>
  39. #endif
  40. #include <FL/Fl.H>
  41. #include <FL/fl_ask.H>
  42. #include "CConn.h"
  43. #include "OptionsDialog.h"
  44. #include "DesktopWindow.h"
  45. #include "PlatformPixelBuffer.h"
  46. #include "i18n.h"
  47. #include "parameters.h"
  48. #include "vncviewer.h"
  49. #ifdef WIN32
  50. #include "win32.h"
  51. #endif
  52. using namespace rdr;
  53. using namespace rfb;
  54. using namespace std;
  55. static rfb::LogWriter vlog("CConn");
  56. // 8 colours (1 bit per component)
  57. static const PixelFormat verylowColourPF(8, 3,false, true,
  58. 1, 1, 1, 2, 1, 0);
  59. // 64 colours (2 bits per component)
  60. static const PixelFormat lowColourPF(8, 6, false, true,
  61. 3, 3, 3, 4, 2, 0);
  62. // 256 colours (2-3 bits per component)
  63. static const PixelFormat mediumColourPF(8, 8, false, true,
  64. 7, 7, 3, 5, 2, 0);
  65. // Time new bandwidth estimates are weighted against (in ms)
  66. static const unsigned bpsEstimateWindow = 1000;
  67. CConn::CConn(const char* vncServerName, network::Socket* socket=NULL)
  68. : serverHost(0), serverPort(0), desktop(NULL),
  69. updateCount(0), pixelCount(0),
  70. lastServerEncoding((unsigned int)-1), bpsEstimate(20000000)
  71. {
  72. setShared(::shared);
  73. sock = socket;
  74. supportsLocalCursor = true;
  75. supportsCursorPosition = true;
  76. supportsDesktopResize = true;
  77. supportsLEDState = false;
  78. if (customCompressLevel)
  79. setCompressLevel(::compressLevel);
  80. if (!noJpeg)
  81. setQualityLevel(::qualityLevel);
  82. if(sock == NULL) {
  83. try {
  84. #ifndef WIN32
  85. if (strchr(vncServerName, '/') != NULL) {
  86. sock = new network::UnixSocket(vncServerName);
  87. serverHost = sock->getPeerAddress();
  88. vlog.info(_("Connected to socket %s"), serverHost);
  89. } else
  90. #endif
  91. {
  92. getHostAndPort(vncServerName, &serverHost, &serverPort);
  93. sock = new network::TcpSocket(serverHost, serverPort);
  94. vlog.info(_("Connected to host %s port %d"), serverHost, serverPort);
  95. }
  96. } catch (rdr::Exception& e) {
  97. vlog.error("%s", e.str());
  98. abort_connection(_("Failed to connect to \"%s\":\n\n%s"),
  99. vncServerName, e.str());
  100. return;
  101. }
  102. }
  103. Fl::add_fd(sock->getFd(), FL_READ | FL_EXCEPT, socketEvent, this);
  104. setServerName(serverHost);
  105. setStreams(&sock->inStream(), &sock->outStream());
  106. initialiseProtocol();
  107. OptionsDialog::addCallback(handleOptions, this);
  108. }
  109. CConn::~CConn()
  110. {
  111. close();
  112. OptionsDialog::removeCallback(handleOptions);
  113. Fl::remove_timeout(handleUpdateTimeout, this);
  114. if (desktop)
  115. delete desktop;
  116. delete [] serverHost;
  117. if (sock)
  118. Fl::remove_fd(sock->getFd());
  119. delete sock;
  120. }
  121. const char *CConn::connectionInfo()
  122. {
  123. static char infoText[1024] = "";
  124. char scratch[100];
  125. char pfStr[100];
  126. // Crude way of avoiding constant overflow checks
  127. assert((sizeof(scratch) + 1) * 10 < sizeof(infoText));
  128. infoText[0] = '\0';
  129. snprintf(scratch, sizeof(scratch),
  130. _("Desktop name: %.80s"), server.name());
  131. strcat(infoText, scratch);
  132. strcat(infoText, "\n");
  133. snprintf(scratch, sizeof(scratch),
  134. _("Host: %.80s port: %d"), serverHost, serverPort);
  135. strcat(infoText, scratch);
  136. strcat(infoText, "\n");
  137. snprintf(scratch, sizeof(scratch),
  138. _("Size: %d x %d"), server.width(), server.height());
  139. strcat(infoText, scratch);
  140. strcat(infoText, "\n");
  141. // TRANSLATORS: Will be filled in with a string describing the
  142. // protocol pixel format in a fairly language neutral way
  143. server.pf().print(pfStr, 100);
  144. snprintf(scratch, sizeof(scratch),
  145. _("Pixel format: %s"), pfStr);
  146. strcat(infoText, scratch);
  147. strcat(infoText, "\n");
  148. // TRANSLATORS: Similar to the earlier "Pixel format" string
  149. serverPF.print(pfStr, 100);
  150. snprintf(scratch, sizeof(scratch),
  151. _("(server default %s)"), pfStr);
  152. strcat(infoText, scratch);
  153. strcat(infoText, "\n");
  154. snprintf(scratch, sizeof(scratch),
  155. _("Requested encoding: %s"), encodingName(getPreferredEncoding()));
  156. strcat(infoText, scratch);
  157. strcat(infoText, "\n");
  158. snprintf(scratch, sizeof(scratch),
  159. _("Last used encoding: %s"), encodingName(lastServerEncoding));
  160. strcat(infoText, scratch);
  161. strcat(infoText, "\n");
  162. snprintf(scratch, sizeof(scratch),
  163. _("Line speed estimate: %d kbit/s"), (int)(bpsEstimate/1000));
  164. strcat(infoText, scratch);
  165. strcat(infoText, "\n");
  166. snprintf(scratch, sizeof(scratch),
  167. _("Protocol version: %d.%d"), server.majorVersion, server.minorVersion);
  168. strcat(infoText, scratch);
  169. strcat(infoText, "\n");
  170. snprintf(scratch, sizeof(scratch),
  171. _("Security method: %s"), secTypeName(csecurity->getType()));
  172. strcat(infoText, scratch);
  173. strcat(infoText, "\n");
  174. return infoText;
  175. }
  176. unsigned CConn::getUpdateCount()
  177. {
  178. return updateCount;
  179. }
  180. unsigned CConn::getPixelCount()
  181. {
  182. return pixelCount;
  183. }
  184. unsigned CConn::getPosition()
  185. {
  186. return sock->inStream().pos();
  187. }
  188. void CConn::socketEvent(FL_SOCKET fd, void *data)
  189. {
  190. CConn *cc;
  191. static bool recursing = false;
  192. int when;
  193. assert(data);
  194. cc = (CConn*)data;
  195. // I don't think processMsg() is recursion safe, so add this check
  196. if (recursing)
  197. return;
  198. recursing = true;
  199. try {
  200. // We might have been called to flush unwritten socket data
  201. cc->sock->outStream().flush();
  202. cc->sock->outStream().cork(true);
  203. // processMsg() only processes one message, so we need to loop
  204. // until the buffers are empty or things will stall.
  205. while (cc->processMsg()) {
  206. // Make sure that the FLTK handling and the timers gets some CPU
  207. // time in case of back to back messages
  208. Fl::check();
  209. Timer::checkTimeouts();
  210. // Also check if we need to stop reading and terminate
  211. if (should_disconnect())
  212. break;
  213. }
  214. cc->sock->outStream().cork(false);
  215. cc->sock->outStream().flush();
  216. } catch (rdr::EndOfStream& e) {
  217. vlog.info("%s", e.str());
  218. if (!cc->desktop) {
  219. vlog.error(_("The connection was dropped by the server before "
  220. "the session could be established."));
  221. abort_connection(_("The connection was dropped by the server "
  222. "before the session could be established."));
  223. } else {
  224. disconnect();
  225. }
  226. } catch (rdr::Exception& e) {
  227. vlog.error("%s", e.str());
  228. abort_connection(_("An unexpected error occurred when communicating "
  229. "with the server:\n\n%s"), e.str());
  230. }
  231. when = FL_READ | FL_EXCEPT;
  232. if (cc->sock->outStream().hasBufferedData())
  233. when |= FL_WRITE;
  234. Fl::add_fd(fd, when, socketEvent, data);
  235. recursing = false;
  236. }
  237. ////////////////////// CConnection callback methods //////////////////////
  238. // initDone() is called when the serverInit message has been received. At
  239. // this point we create the desktop window and display it. We also tell the
  240. // server the pixel format and encodings to use and request the first update.
  241. void CConn::initDone()
  242. {
  243. // If using AutoSelect with old servers, start in FullColor
  244. // mode. See comment in autoSelectFormatAndEncoding.
  245. if (server.beforeVersion(3, 8) && autoSelect)
  246. fullColour.setParam(true);
  247. serverPF = server.pf();
  248. desktop = new DesktopWindow(server.width(), server.height(),
  249. server.name(), serverPF, this);
  250. fullColourPF = desktop->getPreferredPF();
  251. // Force a switch to the format and encoding we'd like
  252. updatePixelFormat();
  253. int encNum = encodingNum(::preferredEncoding);
  254. if (encNum != -1)
  255. setPreferredEncoding(encNum);
  256. }
  257. // setDesktopSize() is called when the desktop size changes (including when
  258. // it is set initially).
  259. void CConn::setDesktopSize(int w, int h)
  260. {
  261. CConnection::setDesktopSize(w,h);
  262. resizeFramebuffer();
  263. }
  264. // setExtendedDesktopSize() is a more advanced version of setDesktopSize()
  265. void CConn::setExtendedDesktopSize(unsigned reason, unsigned result,
  266. int w, int h, const rfb::ScreenSet& layout)
  267. {
  268. CConnection::setExtendedDesktopSize(reason, result, w, h, layout);
  269. if ((reason == reasonClient) && (result != resultSuccess)) {
  270. vlog.error(_("SetDesktopSize failed: %d"), result);
  271. return;
  272. }
  273. resizeFramebuffer();
  274. }
  275. // setName() is called when the desktop name changes
  276. void CConn::setName(const char* name)
  277. {
  278. CConnection::setName(name);
  279. desktop->setName(name);
  280. }
  281. // framebufferUpdateStart() is called at the beginning of an update.
  282. // Here we try to send out a new framebuffer update request so that the
  283. // next update can be sent out in parallel with us decoding the current
  284. // one.
  285. void CConn::framebufferUpdateStart()
  286. {
  287. CConnection::framebufferUpdateStart();
  288. // For bandwidth estimate
  289. gettimeofday(&updateStartTime, NULL);
  290. updateStartPos = sock->inStream().pos();
  291. // Update the screen prematurely for very slow updates
  292. Fl::add_timeout(1.0, handleUpdateTimeout, this);
  293. }
  294. // framebufferUpdateEnd() is called at the end of an update.
  295. // For each rectangle, the FdInStream will have timed the speed
  296. // of the connection, allowing us to select format and encoding
  297. // appropriately, and then request another incremental update.
  298. void CConn::framebufferUpdateEnd()
  299. {
  300. unsigned long long elapsed, bps, weight;
  301. struct timeval now;
  302. CConnection::framebufferUpdateEnd();
  303. updateCount++;
  304. // Calculate bandwidth everything managed to maintain during this update
  305. gettimeofday(&now, NULL);
  306. elapsed = (now.tv_sec - updateStartTime.tv_sec) * 1000000;
  307. elapsed += now.tv_usec - updateStartTime.tv_usec;
  308. if (elapsed == 0)
  309. elapsed = 1;
  310. bps = (unsigned long long)(sock->inStream().pos() -
  311. updateStartPos) * 8 *
  312. 1000000 / elapsed;
  313. // Allow this update to influence things more the longer it took, to a
  314. // maximum of 20% of the new value.
  315. weight = elapsed * 1000 / bpsEstimateWindow;
  316. if (weight > 200000)
  317. weight = 200000;
  318. bpsEstimate = ((bpsEstimate * (1000000 - weight)) +
  319. (bps * weight)) / 1000000;
  320. Fl::remove_timeout(handleUpdateTimeout, this);
  321. desktop->updateWindow();
  322. // Compute new settings based on updated bandwidth values
  323. if (autoSelect)
  324. autoSelectFormatAndEncoding();
  325. }
  326. // The rest of the callbacks are fairly self-explanatory...
  327. void CConn::setColourMapEntries(int firstColour, int nColours, rdr::U16* rgbs)
  328. {
  329. vlog.error(_("Invalid SetColourMapEntries from server!"));
  330. }
  331. void CConn::bell()
  332. {
  333. fl_beep();
  334. }
  335. bool CConn::dataRect(const Rect& r, int encoding)
  336. {
  337. bool ret;
  338. if (encoding != encodingCopyRect)
  339. lastServerEncoding = encoding;
  340. ret = CConnection::dataRect(r, encoding);
  341. if (ret)
  342. pixelCount += r.area();
  343. return ret;
  344. }
  345. void CConn::setCursor(int width, int height, const Point& hotspot,
  346. const rdr::U8* data)
  347. {
  348. desktop->setCursor(width, height, hotspot, data);
  349. }
  350. void CConn::setCursorPos(const Point& pos)
  351. {
  352. desktop->setCursorPos(pos);
  353. }
  354. void CConn::fence(rdr::U32 flags, unsigned len, const char data[])
  355. {
  356. CMsgHandler::fence(flags, len, data);
  357. if (flags & fenceFlagRequest) {
  358. // We handle everything synchronously so we trivially honor these modes
  359. flags = flags & (fenceFlagBlockBefore | fenceFlagBlockAfter);
  360. writer()->writeFence(flags, len, data);
  361. return;
  362. }
  363. }
  364. void CConn::setLEDState(unsigned int state)
  365. {
  366. CConnection::setLEDState(state);
  367. desktop->setLEDState(state);
  368. }
  369. void CConn::handleClipboardRequest()
  370. {
  371. desktop->handleClipboardRequest();
  372. }
  373. void CConn::handleClipboardAnnounce(bool available)
  374. {
  375. desktop->handleClipboardAnnounce(available);
  376. }
  377. void CConn::handleClipboardData(const char* data)
  378. {
  379. desktop->handleClipboardData(data);
  380. }
  381. ////////////////////// Internal methods //////////////////////
  382. void CConn::resizeFramebuffer()
  383. {
  384. desktop->resizeFramebuffer(server.width(), server.height());
  385. }
  386. // autoSelectFormatAndEncoding() chooses the format and encoding appropriate
  387. // to the connection speed:
  388. //
  389. // First we wait for at least one second of bandwidth measurement.
  390. //
  391. // Above 16Mbps (i.e. LAN), we choose the second highest JPEG quality,
  392. // which should be perceptually lossless.
  393. //
  394. // If the bandwidth is below that, we choose a more lossy JPEG quality.
  395. //
  396. // If the bandwidth drops below 256 Kbps, we switch to palette mode.
  397. //
  398. // Note: The system here is fairly arbitrary and should be replaced
  399. // with something more intelligent at the server end.
  400. //
  401. void CConn::autoSelectFormatAndEncoding()
  402. {
  403. bool newFullColour = fullColour;
  404. int newQualityLevel = ::qualityLevel;
  405. // Always use Tight
  406. setPreferredEncoding(encodingTight);
  407. // Select appropriate quality level
  408. if (!noJpeg) {
  409. if (bpsEstimate > 16000000)
  410. newQualityLevel = 8;
  411. else
  412. newQualityLevel = 6;
  413. if (newQualityLevel != ::qualityLevel) {
  414. vlog.info(_("Throughput %d kbit/s - changing to quality %d"),
  415. (int)(bpsEstimate/1000), newQualityLevel);
  416. ::qualityLevel.setParam(newQualityLevel);
  417. setQualityLevel(newQualityLevel);
  418. }
  419. }
  420. if (server.beforeVersion(3, 8)) {
  421. // Xvnc from TightVNC 1.2.9 sends out FramebufferUpdates with
  422. // cursors "asynchronously". If this happens in the middle of a
  423. // pixel format change, the server will encode the cursor with
  424. // the old format, but the client will try to decode it
  425. // according to the new format. This will lead to a
  426. // crash. Therefore, we do not allow automatic format change for
  427. // old servers.
  428. return;
  429. }
  430. // Select best color level
  431. newFullColour = (bpsEstimate > 256000);
  432. if (newFullColour != fullColour) {
  433. if (newFullColour)
  434. vlog.info(_("Throughput %d kbit/s - full color is now enabled"),
  435. (int)(bpsEstimate/1000));
  436. else
  437. vlog.info(_("Throughput %d kbit/s - full color is now disabled"),
  438. (int)(bpsEstimate/1000));
  439. fullColour.setParam(newFullColour);
  440. updatePixelFormat();
  441. }
  442. }
  443. // requestNewUpdate() requests an update from the server, having set the
  444. // format and encoding appropriately.
  445. void CConn::updatePixelFormat()
  446. {
  447. PixelFormat pf;
  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. char str[256];
  459. pf.print(str, 256);
  460. vlog.info(_("Using pixel format %s"),str);
  461. setPF(pf);
  462. }
  463. void CConn::handleOptions(void *data)
  464. {
  465. CConn *self = (CConn*)data;
  466. // Checking all the details of the current set of encodings is just
  467. // a pain. Assume something has changed, as resending the encoding
  468. // list is cheap. Avoid overriding what the auto logic has selected
  469. // though.
  470. if (!autoSelect) {
  471. int encNum = encodingNum(::preferredEncoding);
  472. if (encNum != -1)
  473. self->setPreferredEncoding(encNum);
  474. }
  475. if (customCompressLevel)
  476. self->setCompressLevel(::compressLevel);
  477. else
  478. self->setCompressLevel(-1);
  479. if (!noJpeg && !autoSelect)
  480. self->setQualityLevel(::qualityLevel);
  481. else
  482. self->setQualityLevel(-1);
  483. self->updatePixelFormat();
  484. }
  485. void CConn::handleUpdateTimeout(void *data)
  486. {
  487. CConn *self = (CConn *)data;
  488. assert(self);
  489. self->desktop->updateWindow();
  490. Fl::repeat_timeout(1.0, handleUpdateTimeout, data);
  491. }