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

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