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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562
  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)
  69. {
  70. setShared(::shared);
  71. sock = socket;
  72. supportsLocalCursor = true;
  73. supportsDesktopResize = true;
  74. supportsLEDState = true;
  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. // See callback below
  103. sock->inStream().setBlockCallback(this);
  104. setServerName(serverHost);
  105. setStreams(&sock->inStream(), &sock->outStream());
  106. initialiseProtocol();
  107. OptionsDialog::addCallback(handleOptions, this);
  108. }
  109. CConn::~CConn()
  110. {
  111. OptionsDialog::removeCallback(handleOptions);
  112. Fl::remove_timeout(handleUpdateTimeout, this);
  113. if (desktop)
  114. delete desktop;
  115. delete [] serverHost;
  116. if (sock)
  117. Fl::remove_fd(sock->getFd());
  118. delete sock;
  119. }
  120. const char *CConn::connectionInfo()
  121. {
  122. static char infoText[1024] = "";
  123. char scratch[100];
  124. char pfStr[100];
  125. // Crude way of avoiding constant overflow checks
  126. assert((sizeof(scratch) + 1) * 10 < sizeof(infoText));
  127. infoText[0] = '\0';
  128. snprintf(scratch, sizeof(scratch),
  129. _("Desktop name: %.80s"), server.name());
  130. strcat(infoText, scratch);
  131. strcat(infoText, "\n");
  132. snprintf(scratch, sizeof(scratch),
  133. _("Host: %.80s port: %d"), serverHost, serverPort);
  134. strcat(infoText, scratch);
  135. strcat(infoText, "\n");
  136. snprintf(scratch, sizeof(scratch),
  137. _("Size: %d x %d"), server.width(), server.height());
  138. strcat(infoText, scratch);
  139. strcat(infoText, "\n");
  140. // TRANSLATORS: Will be filled in with a string describing the
  141. // protocol pixel format in a fairly language neutral way
  142. server.pf().print(pfStr, 100);
  143. snprintf(scratch, sizeof(scratch),
  144. _("Pixel format: %s"), pfStr);
  145. strcat(infoText, scratch);
  146. strcat(infoText, "\n");
  147. // TRANSLATORS: Similar to the earlier "Pixel format" string
  148. serverPF.print(pfStr, 100);
  149. snprintf(scratch, sizeof(scratch),
  150. _("(server default %s)"), pfStr);
  151. strcat(infoText, scratch);
  152. strcat(infoText, "\n");
  153. snprintf(scratch, sizeof(scratch),
  154. _("Requested encoding: %s"), encodingName(getPreferredEncoding()));
  155. strcat(infoText, scratch);
  156. strcat(infoText, "\n");
  157. snprintf(scratch, sizeof(scratch),
  158. _("Last used encoding: %s"), encodingName(lastServerEncoding));
  159. strcat(infoText, scratch);
  160. strcat(infoText, "\n");
  161. snprintf(scratch, sizeof(scratch),
  162. _("Line speed estimate: %d kbit/s"), sock->inStream().kbitsPerSecond());
  163. strcat(infoText, scratch);
  164. strcat(infoText, "\n");
  165. snprintf(scratch, sizeof(scratch),
  166. _("Protocol version: %d.%d"), server.majorVersion, server.minorVersion);
  167. strcat(infoText, scratch);
  168. strcat(infoText, "\n");
  169. snprintf(scratch, sizeof(scratch),
  170. _("Security method: %s"), secTypeName(csecurity->getType()));
  171. strcat(infoText, scratch);
  172. strcat(infoText, "\n");
  173. return infoText;
  174. }
  175. unsigned CConn::getUpdateCount()
  176. {
  177. return updateCount;
  178. }
  179. unsigned CConn::getPixelCount()
  180. {
  181. return pixelCount;
  182. }
  183. unsigned CConn::getPosition()
  184. {
  185. return sock->inStream().pos();
  186. }
  187. // The RFB core is not properly asynchronous, so it calls this callback
  188. // whenever it needs to block to wait for more data. Since FLTK is
  189. // monitoring the socket, we just make sure FLTK gets to run.
  190. void CConn::blockCallback()
  191. {
  192. run_mainloop();
  193. if (should_exit())
  194. throw rdr::Exception("Termination requested");
  195. }
  196. void CConn::socketEvent(FL_SOCKET fd, void *data)
  197. {
  198. CConn *cc;
  199. static bool recursing = false;
  200. assert(data);
  201. cc = (CConn*)data;
  202. // I don't think processMsg() is recursion safe, so add this check
  203. if (recursing)
  204. return;
  205. recursing = true;
  206. try {
  207. // processMsg() only processes one message, so we need to loop
  208. // until the buffers are empty or things will stall.
  209. do {
  210. cc->processMsg();
  211. // Make sure that the FLTK handling and the timers gets some CPU
  212. // time in case of back to back messages
  213. Fl::check();
  214. Timer::checkTimeouts();
  215. // Also check if we need to stop reading and terminate
  216. if (should_exit())
  217. break;
  218. } while (cc->sock->inStream().checkNoWait(1));
  219. } catch (rdr::EndOfStream& e) {
  220. vlog.info("%s", e.str());
  221. exit_vncviewer();
  222. } catch (rdr::Exception& e) {
  223. vlog.error("%s", e.str());
  224. // Somebody might already have requested us to terminate, and
  225. // might have already provided an error message.
  226. if (!should_exit())
  227. exit_vncviewer(e.str());
  228. }
  229. recursing = false;
  230. }
  231. ////////////////////// CConnection callback methods //////////////////////
  232. // initDone() is called when the serverInit message has been received. At
  233. // this point we create the desktop window and display it. We also tell the
  234. // server the pixel format and encodings to use and request the first update.
  235. void CConn::initDone()
  236. {
  237. // If using AutoSelect with old servers, start in FullColor
  238. // mode. See comment in autoSelectFormatAndEncoding.
  239. if (server.beforeVersion(3, 8) && autoSelect)
  240. fullColour.setParam(true);
  241. serverPF = server.pf();
  242. desktop = new DesktopWindow(server.width(), server.height(),
  243. server.name(), serverPF, this);
  244. fullColourPF = desktop->getPreferredPF();
  245. // Force a switch to the format and encoding we'd like
  246. updatePixelFormat();
  247. int encNum = encodingNum(::preferredEncoding);
  248. if (encNum != -1)
  249. setPreferredEncoding(encNum);
  250. }
  251. // setDesktopSize() is called when the desktop size changes (including when
  252. // it is set initially).
  253. void CConn::setDesktopSize(int w, int h)
  254. {
  255. CConnection::setDesktopSize(w,h);
  256. resizeFramebuffer();
  257. }
  258. // setExtendedDesktopSize() is a more advanced version of setDesktopSize()
  259. void CConn::setExtendedDesktopSize(unsigned reason, unsigned result,
  260. int w, int h, const rfb::ScreenSet& layout)
  261. {
  262. CConnection::setExtendedDesktopSize(reason, result, w, h, layout);
  263. if ((reason == reasonClient) && (result != resultSuccess)) {
  264. vlog.error(_("SetDesktopSize failed: %d"), result);
  265. return;
  266. }
  267. resizeFramebuffer();
  268. }
  269. // setName() is called when the desktop name changes
  270. void CConn::setName(const char* name)
  271. {
  272. CConnection::setName(name);
  273. desktop->setName(name);
  274. }
  275. // framebufferUpdateStart() is called at the beginning of an update.
  276. // Here we try to send out a new framebuffer update request so that the
  277. // next update can be sent out in parallel with us decoding the current
  278. // one.
  279. void CConn::framebufferUpdateStart()
  280. {
  281. CConnection::framebufferUpdateStart();
  282. // Update the screen prematurely for very slow updates
  283. Fl::add_timeout(1.0, handleUpdateTimeout, this);
  284. }
  285. // framebufferUpdateEnd() is called at the end of an update.
  286. // For each rectangle, the FdInStream will have timed the speed
  287. // of the connection, allowing us to select format and encoding
  288. // appropriately, and then request another incremental update.
  289. void CConn::framebufferUpdateEnd()
  290. {
  291. CConnection::framebufferUpdateEnd();
  292. updateCount++;
  293. Fl::remove_timeout(handleUpdateTimeout, this);
  294. desktop->updateWindow();
  295. // Compute new settings based on updated bandwidth values
  296. if (autoSelect)
  297. autoSelectFormatAndEncoding();
  298. }
  299. // The rest of the callbacks are fairly self-explanatory...
  300. void CConn::setColourMapEntries(int firstColour, int nColours, rdr::U16* rgbs)
  301. {
  302. vlog.error(_("Invalid SetColourMapEntries from server!"));
  303. }
  304. void CConn::bell()
  305. {
  306. fl_beep();
  307. }
  308. void CConn::serverCutText(const char* str, rdr::U32 len)
  309. {
  310. desktop->serverCutText(str, len);
  311. }
  312. void CConn::dataRect(const Rect& r, int encoding)
  313. {
  314. sock->inStream().startTiming();
  315. if (encoding != encodingCopyRect)
  316. lastServerEncoding = encoding;
  317. CConnection::dataRect(r, encoding);
  318. sock->inStream().stopTiming();
  319. pixelCount += r.area();
  320. }
  321. void CConn::setCursor(int width, int height, const Point& hotspot,
  322. const rdr::U8* data)
  323. {
  324. desktop->setCursor(width, height, hotspot, data);
  325. }
  326. void CConn::fence(rdr::U32 flags, unsigned len, const char data[])
  327. {
  328. CMsgHandler::fence(flags, len, data);
  329. if (flags & fenceFlagRequest) {
  330. // We handle everything synchronously so we trivially honor these modes
  331. flags = flags & (fenceFlagBlockBefore | fenceFlagBlockAfter);
  332. writer()->writeFence(flags, len, data);
  333. return;
  334. }
  335. }
  336. void CConn::setLEDState(unsigned int state)
  337. {
  338. CConnection::setLEDState(state);
  339. desktop->setLEDState(state);
  340. }
  341. ////////////////////// Internal methods //////////////////////
  342. void CConn::resizeFramebuffer()
  343. {
  344. desktop->resizeFramebuffer(server.width(), server.height());
  345. }
  346. // autoSelectFormatAndEncoding() chooses the format and encoding appropriate
  347. // to the connection speed:
  348. //
  349. // First we wait for at least one second of bandwidth measurement.
  350. //
  351. // Above 16Mbps (i.e. LAN), we choose the second highest JPEG quality,
  352. // which should be perceptually lossless.
  353. //
  354. // If the bandwidth is below that, we choose a more lossy JPEG quality.
  355. //
  356. // If the bandwidth drops below 256 Kbps, we switch to palette mode.
  357. //
  358. // Note: The system here is fairly arbitrary and should be replaced
  359. // with something more intelligent at the server end.
  360. //
  361. void CConn::autoSelectFormatAndEncoding()
  362. {
  363. int kbitsPerSecond = sock->inStream().kbitsPerSecond();
  364. unsigned int timeWaited = sock->inStream().timeWaited();
  365. bool newFullColour = fullColour;
  366. int newQualityLevel = ::qualityLevel;
  367. // Always use Tight
  368. setPreferredEncoding(encodingTight);
  369. // Check that we have a decent bandwidth measurement
  370. if ((kbitsPerSecond == 0) || (timeWaited < 10000))
  371. return;
  372. // Select appropriate quality level
  373. if (!noJpeg) {
  374. if (kbitsPerSecond > 16000)
  375. newQualityLevel = 8;
  376. else
  377. newQualityLevel = 6;
  378. if (newQualityLevel != ::qualityLevel) {
  379. vlog.info(_("Throughput %d kbit/s - changing to quality %d"),
  380. kbitsPerSecond, newQualityLevel);
  381. ::qualityLevel.setParam(newQualityLevel);
  382. setQualityLevel(newQualityLevel);
  383. }
  384. }
  385. if (server.beforeVersion(3, 8)) {
  386. // Xvnc from TightVNC 1.2.9 sends out FramebufferUpdates with
  387. // cursors "asynchronously". If this happens in the middle of a
  388. // pixel format change, the server will encode the cursor with
  389. // the old format, but the client will try to decode it
  390. // according to the new format. This will lead to a
  391. // crash. Therefore, we do not allow automatic format change for
  392. // old servers.
  393. return;
  394. }
  395. // Select best color level
  396. newFullColour = (kbitsPerSecond > 256);
  397. if (newFullColour != fullColour) {
  398. if (newFullColour)
  399. vlog.info(_("Throughput %d kbit/s - full color is now enabled"),
  400. kbitsPerSecond);
  401. else
  402. vlog.info(_("Throughput %d kbit/s - full color is now disabled"),
  403. kbitsPerSecond);
  404. fullColour.setParam(newFullColour);
  405. updatePixelFormat();
  406. }
  407. }
  408. // requestNewUpdate() requests an update from the server, having set the
  409. // format and encoding appropriately.
  410. void CConn::updatePixelFormat()
  411. {
  412. PixelFormat pf;
  413. if (fullColour) {
  414. pf = fullColourPF;
  415. } else {
  416. if (lowColourLevel == 0)
  417. pf = verylowColourPF;
  418. else if (lowColourLevel == 1)
  419. pf = lowColourPF;
  420. else
  421. pf = mediumColourPF;
  422. }
  423. char str[256];
  424. pf.print(str, 256);
  425. vlog.info(_("Using pixel format %s"),str);
  426. setPF(pf);
  427. }
  428. void CConn::handleOptions(void *data)
  429. {
  430. CConn *self = (CConn*)data;
  431. // Checking all the details of the current set of encodings is just
  432. // a pain. Assume something has changed, as resending the encoding
  433. // list is cheap. Avoid overriding what the auto logic has selected
  434. // though.
  435. if (!autoSelect) {
  436. int encNum = encodingNum(::preferredEncoding);
  437. if (encNum != -1)
  438. self->setPreferredEncoding(encNum);
  439. }
  440. if (customCompressLevel)
  441. self->setCompressLevel(::compressLevel);
  442. else
  443. self->setCompressLevel(-1);
  444. if (!noJpeg && !autoSelect)
  445. self->setQualityLevel(::qualityLevel);
  446. else
  447. self->setQualityLevel(-1);
  448. self->updatePixelFormat();
  449. }
  450. void CConn::handleUpdateTimeout(void *data)
  451. {
  452. CConn *self = (CConn *)data;
  453. assert(self);
  454. self->desktop->updateWindow();
  455. Fl::repeat_timeout(1.0, handleUpdateTimeout, data);
  456. }