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

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