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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576
  1. /* Copyright (C) 2002-2005 RealVNC Ltd. All Rights Reserved.
  2. * Copyright 2009-2011 Pierre Ossman <ossman@cendio.se> for Cendio AB
  3. *
  4. * This is free software; you can redistribute it and/or modify
  5. * it under the terms of the GNU General Public License as published by
  6. * the Free Software Foundation; either version 2 of the License, or
  7. * (at your option) any later version.
  8. *
  9. * This software is distributed in the hope that it will be useful,
  10. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. * GNU General Public License for more details.
  13. *
  14. * You should have received a copy of the GNU General Public License
  15. * along with this software; if not, write to the Free Software
  16. * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307,
  17. * USA.
  18. */
  19. #include <assert.h>
  20. #ifndef _WIN32
  21. #include <unistd.h>
  22. #endif
  23. #include <rfb/CMsgWriter.h>
  24. #include <rfb/encodings.h>
  25. #include <rfb/Hostname.h>
  26. #include <rfb/LogWriter.h>
  27. #include <rfb/util.h>
  28. #include <rfb/screenTypes.h>
  29. #include <rfb/Timer.h>
  30. #include <network/TcpSocket.h>
  31. #include <FL/Fl.H>
  32. #include <FL/fl_ask.H>
  33. #include "CConn.h"
  34. #include "OptionsDialog.h"
  35. #include "i18n.h"
  36. #include "parameters.h"
  37. #include "vncviewer.h"
  38. #ifdef WIN32
  39. #include "win32.h"
  40. #endif
  41. using namespace rdr;
  42. using namespace rfb;
  43. using namespace std;
  44. static rfb::LogWriter vlog("CConn");
  45. static const PixelFormat mediumColourPF(8,3,0,1,1,1,1,2,1,0);
  46. static const PixelFormat lowColourPF(8,6,0,1,3,3,3,4,2,0);
  47. static const PixelFormat verylowColourPF(8,8,0,0);
  48. CConn::CConn(const char* vncServerName)
  49. : serverHost(0), serverPort(0), sock(NULL), desktop(NULL),
  50. currentEncoding(encodingTight), lastServerEncoding((unsigned int)-1),
  51. formatChange(false), encodingChange(false),
  52. firstUpdate(true), pendingUpdate(false),
  53. forceNonincremental(false)
  54. {
  55. setShared(::shared);
  56. int encNum = encodingNum(preferredEncoding);
  57. if (encNum != -1)
  58. currentEncoding = encNum;
  59. cp.supportsLocalCursor = true;
  60. cp.supportsDesktopResize = true;
  61. cp.supportsExtendedDesktopSize = true;
  62. cp.supportsDesktopRename = true;
  63. cp.customCompressLevel = customCompressLevel;
  64. cp.compressLevel = compressLevel;
  65. cp.noJpeg = noJpeg;
  66. cp.qualityLevel = qualityLevel;
  67. try {
  68. getHostAndPort(vncServerName, &serverHost, &serverPort);
  69. sock = new network::TcpSocket(serverHost, serverPort);
  70. vlog.info(_("connected to host %s port %d"), serverHost, serverPort);
  71. } catch (rdr::Exception& e) {
  72. vlog.error(e.str());
  73. fl_alert(e.str());
  74. exit_vncviewer();
  75. return;
  76. }
  77. Fl::add_fd(sock->getFd(), FL_READ | FL_EXCEPT, socketEvent, this);
  78. // See callback below
  79. sock->inStream().setBlockCallback(this);
  80. setServerName(serverHost);
  81. setStreams(&sock->inStream(), &sock->outStream());
  82. initialiseProtocol();
  83. OptionsDialog::addCallback(handleOptions, this);
  84. }
  85. CConn::~CConn()
  86. {
  87. OptionsDialog::removeCallback(handleOptions);
  88. if (desktop)
  89. delete desktop;
  90. free(serverHost);
  91. if (sock)
  92. Fl::remove_fd(sock->getFd());
  93. delete sock;
  94. }
  95. void CConn::refreshFramebuffer()
  96. {
  97. // FIXME: We cannot safely trigger an update request directly but must
  98. // wait for the next update to arrive.
  99. if (!formatChange)
  100. forceNonincremental = true;
  101. }
  102. const char *CConn::connectionInfo()
  103. {
  104. static char infoText[1024] = "";
  105. char pfStr[100];
  106. char spfStr[100];
  107. cp.pf().print(pfStr, 100);
  108. serverPF.print(spfStr, 100);
  109. int secType = csecurity->getType();
  110. snprintf(infoText, sizeof(infoText),
  111. _("Desktop name: %.80s\n"
  112. "Host: %.80s port: %d\n"
  113. "Size: %d x %d\n"
  114. "Pixel format: %s\n"
  115. "(server default %s)\n"
  116. "Requested encoding: %s\n"
  117. "Last used encoding: %s\n"
  118. "Line speed estimate: %d kbit/s\n"
  119. "Protocol version: %d.%d\n"
  120. "Security method: %s\n"),
  121. cp.name(), serverHost, serverPort, cp.width, cp.height,
  122. pfStr, spfStr, encodingName(currentEncoding),
  123. encodingName(lastServerEncoding),
  124. sock->inStream().kbitsPerSecond(),
  125. cp.majorVersion, cp.minorVersion,
  126. secTypeName(secType));
  127. return infoText;
  128. }
  129. // The RFB core is not properly asynchronous, so it calls this callback
  130. // whenever it needs to block to wait for more data. Since FLTK is
  131. // monitoring the socket, we just make sure FLTK gets to run.
  132. void CConn::blockCallback()
  133. {
  134. int next_timer;
  135. next_timer = Timer::checkTimeouts();
  136. if (next_timer == 0)
  137. next_timer = INT_MAX;
  138. Fl::wait((double)next_timer / 1000.0);
  139. }
  140. void CConn::socketEvent(int fd, void *data)
  141. {
  142. CConn *cc;
  143. static bool recursing = false;
  144. assert(data);
  145. cc = (CConn*)data;
  146. // I don't think processMsg() is recursion safe, so add this check
  147. if (recursing)
  148. return;
  149. recursing = true;
  150. try {
  151. // processMsg() only processes one message, so we need to loop
  152. // until the buffers are empty or things will stall.
  153. do {
  154. cc->processMsg();
  155. } while (cc->sock->inStream().checkNoWait(1));
  156. } catch (rdr::EndOfStream& e) {
  157. vlog.info(e.str());
  158. exit_vncviewer();
  159. } catch (rdr::Exception& e) {
  160. vlog.error(e.str());
  161. exit_vncviewer(e.str());
  162. }
  163. recursing = false;
  164. }
  165. ////////////////////// CConnection callback methods //////////////////////
  166. // serverInit() is called when the serverInit message has been received. At
  167. // this point we create the desktop window and display it. We also tell the
  168. // server the pixel format and encodings to use and request the first update.
  169. void CConn::serverInit()
  170. {
  171. CConnection::serverInit();
  172. // If using AutoSelect with old servers, start in FullColor
  173. // mode. See comment in autoSelectFormatAndEncoding.
  174. if (cp.beforeVersion(3, 8) && autoSelect)
  175. fullColour.setParam(true);
  176. serverPF = cp.pf();
  177. desktop = new DesktopWindow(cp.width, cp.height, cp.name(), serverPF, this);
  178. fullColourPF = desktop->getPreferredPF();
  179. formatChange = encodingChange = true;
  180. requestNewUpdate();
  181. }
  182. // setDesktopSize() is called when the desktop size changes (including when
  183. // it is set initially).
  184. void CConn::setDesktopSize(int w, int h)
  185. {
  186. CConnection::setDesktopSize(w,h);
  187. resizeFramebuffer();
  188. }
  189. // setExtendedDesktopSize() is a more advanced version of setDesktopSize()
  190. void CConn::setExtendedDesktopSize(int reason, int result, int w, int h,
  191. const rfb::ScreenSet& layout)
  192. {
  193. CConnection::setExtendedDesktopSize(reason, result, w, h, layout);
  194. if ((reason == reasonClient) && (result != resultSuccess)) {
  195. vlog.error(_("SetDesktopSize failed: %d"), result);
  196. return;
  197. }
  198. resizeFramebuffer();
  199. }
  200. // setName() is called when the desktop name changes
  201. void CConn::setName(const char* name)
  202. {
  203. CConnection::setName(name);
  204. if (desktop)
  205. desktop->setName(name);
  206. }
  207. // framebufferUpdateStart() is called at the beginning of an update.
  208. // Here we try to send out a new framebuffer update request so that the
  209. // next update can be sent out in parallel with us decoding the current
  210. // one. We cannot do this if we're in the middle of a format change
  211. // though.
  212. void CConn::framebufferUpdateStart()
  213. {
  214. if (!formatChange) {
  215. pendingUpdate = true;
  216. requestNewUpdate();
  217. } else
  218. pendingUpdate = false;
  219. }
  220. // framebufferUpdateEnd() is called at the end of an update.
  221. // For each rectangle, the FdInStream will have timed the speed
  222. // of the connection, allowing us to select format and encoding
  223. // appropriately, and then request another incremental update.
  224. void CConn::framebufferUpdateEnd()
  225. {
  226. desktop->updateWindow();
  227. if (firstUpdate) {
  228. int width, height;
  229. if (cp.supportsSetDesktopSize &&
  230. sscanf(desktopSize.getValueStr(), "%dx%d", &width, &height) == 2) {
  231. ScreenSet layout;
  232. layout = cp.screenLayout;
  233. if (layout.num_screens() == 0)
  234. layout.add_screen(rfb::Screen());
  235. else if (layout.num_screens() != 1) {
  236. ScreenSet::iterator iter;
  237. while (true) {
  238. iter = layout.begin();
  239. ++iter;
  240. if (iter == layout.end())
  241. break;
  242. layout.remove_screen(iter->id);
  243. }
  244. }
  245. layout.begin()->dimensions.tl.x = 0;
  246. layout.begin()->dimensions.tl.y = 0;
  247. layout.begin()->dimensions.br.x = width;
  248. layout.begin()->dimensions.br.y = height;
  249. writer()->writeSetDesktopSize(width, height, layout);
  250. }
  251. firstUpdate = false;
  252. }
  253. // A format change prevented us from sending this before the update,
  254. // so make sure to send it now.
  255. if (formatChange && !pendingUpdate)
  256. requestNewUpdate();
  257. // Compute new settings based on updated bandwidth values
  258. if (autoSelect)
  259. autoSelectFormatAndEncoding();
  260. // Make sure that the FLTK handling and the timers gets some CPU time
  261. // in case of back to back framebuffer updates.
  262. Fl::check();
  263. Timer::checkTimeouts();
  264. }
  265. // The rest of the callbacks are fairly self-explanatory...
  266. void CConn::setColourMapEntries(int firstColour, int nColours, rdr::U16* rgbs)
  267. {
  268. desktop->setColourMapEntries(firstColour, nColours, rgbs);
  269. }
  270. void CConn::bell()
  271. {
  272. fl_beep();
  273. }
  274. void CConn::serverCutText(const char* str, rdr::U32 len)
  275. {
  276. char *buffer;
  277. int size, ret;
  278. size = fl_utf8froma(NULL, 0, str, len);
  279. if (size <= 0)
  280. return;
  281. size++;
  282. buffer = new char[size];
  283. ret = fl_utf8froma(buffer, size, str, len);
  284. assert(ret < size);
  285. vlog.debug("Got clipboard data: '%s'", buffer);
  286. Fl::copy(buffer, ret, 1);
  287. delete [] buffer;
  288. }
  289. // We start timing on beginRect and stop timing on endRect, to
  290. // avoid skewing the bandwidth estimation as a result of the server
  291. // being slow or the network having high latency
  292. void CConn::beginRect(const Rect& r, int encoding)
  293. {
  294. sock->inStream().startTiming();
  295. if (encoding != encodingCopyRect) {
  296. lastServerEncoding = encoding;
  297. }
  298. }
  299. void CConn::endRect(const Rect& r, int encoding)
  300. {
  301. sock->inStream().stopTiming();
  302. }
  303. void CConn::fillRect(const rfb::Rect& r, rfb::Pixel p)
  304. {
  305. desktop->fillRect(r,p);
  306. }
  307. void CConn::imageRect(const rfb::Rect& r, void* p)
  308. {
  309. desktop->imageRect(r,p);
  310. }
  311. void CConn::copyRect(const rfb::Rect& r, int sx, int sy)
  312. {
  313. desktop->copyRect(r,sx,sy);
  314. }
  315. void CConn::setCursor(int width, int height, const Point& hotspot,
  316. void* data, void* mask)
  317. {
  318. desktop->setCursor(width, height, hotspot, data, mask);
  319. }
  320. ////////////////////// Internal methods //////////////////////
  321. void CConn::resizeFramebuffer()
  322. {
  323. if (!desktop)
  324. return;
  325. desktop->resizeFramebuffer(cp.width, cp.height);
  326. }
  327. // autoSelectFormatAndEncoding() chooses the format and encoding appropriate
  328. // to the connection speed:
  329. //
  330. // First we wait for at least one second of bandwidth measurement.
  331. //
  332. // Above 16Mbps (i.e. LAN), we choose the second highest JPEG quality,
  333. // which should be perceptually lossless.
  334. //
  335. // If the bandwidth is below that, we choose a more lossy JPEG quality.
  336. //
  337. // If the bandwidth drops below 256 Kbps, we switch to palette mode.
  338. //
  339. // Note: The system here is fairly arbitrary and should be replaced
  340. // with something more intelligent at the server end.
  341. //
  342. void CConn::autoSelectFormatAndEncoding()
  343. {
  344. int kbitsPerSecond = sock->inStream().kbitsPerSecond();
  345. unsigned int timeWaited = sock->inStream().timeWaited();
  346. bool newFullColour = fullColour;
  347. int newQualityLevel = qualityLevel;
  348. // Always use Tight
  349. if (currentEncoding != encodingTight) {
  350. currentEncoding = encodingTight;
  351. encodingChange = true;
  352. }
  353. // Check that we have a decent bandwidth measurement
  354. if ((kbitsPerSecond == 0) || (timeWaited < 10000))
  355. return;
  356. // Select appropriate quality level
  357. if (!noJpeg) {
  358. if (kbitsPerSecond > 16000)
  359. newQualityLevel = 8;
  360. else
  361. newQualityLevel = 6;
  362. if (newQualityLevel != qualityLevel) {
  363. vlog.info(_("Throughput %d kbit/s - changing to quality %d"),
  364. kbitsPerSecond, newQualityLevel);
  365. cp.qualityLevel = newQualityLevel;
  366. qualityLevel.setParam(newQualityLevel);
  367. encodingChange = true;
  368. }
  369. }
  370. if (cp.beforeVersion(3, 8)) {
  371. // Xvnc from TightVNC 1.2.9 sends out FramebufferUpdates with
  372. // cursors "asynchronously". If this happens in the middle of a
  373. // pixel format change, the server will encode the cursor with
  374. // the old format, but the client will try to decode it
  375. // according to the new format. This will lead to a
  376. // crash. Therefore, we do not allow automatic format change for
  377. // old servers.
  378. return;
  379. }
  380. // Select best color level
  381. newFullColour = (kbitsPerSecond > 256);
  382. if (newFullColour != fullColour) {
  383. vlog.info(_("Throughput %d kbit/s - full color is now %s"),
  384. kbitsPerSecond,
  385. newFullColour ? _("enabled") : _("disabled"));
  386. fullColour.setParam(newFullColour);
  387. formatChange = true;
  388. }
  389. }
  390. // checkEncodings() sends a setEncodings message if one is needed.
  391. void CConn::checkEncodings()
  392. {
  393. if (encodingChange && writer()) {
  394. vlog.info(_("Using %s encoding"),encodingName(currentEncoding));
  395. writer()->writeSetEncodings(currentEncoding, true);
  396. encodingChange = false;
  397. }
  398. }
  399. // requestNewUpdate() requests an update from the server, having set the
  400. // format and encoding appropriately.
  401. void CConn::requestNewUpdate()
  402. {
  403. if (formatChange) {
  404. PixelFormat pf;
  405. /* Catch incorrect requestNewUpdate calls */
  406. assert(pendingUpdate == false);
  407. if (fullColour) {
  408. pf = fullColourPF;
  409. } else {
  410. if (lowColourLevel == 0)
  411. pf = mediumColourPF;
  412. else if (lowColourLevel == 1)
  413. pf = lowColourPF;
  414. else
  415. pf = verylowColourPF;
  416. }
  417. char str[256];
  418. pf.print(str, 256);
  419. vlog.info(_("Using pixel format %s"),str);
  420. desktop->setServerPF(pf);
  421. cp.setPF(pf);
  422. writer()->writeSetPixelFormat(pf);
  423. forceNonincremental = true;
  424. formatChange = false;
  425. }
  426. checkEncodings();
  427. writer()->writeFramebufferUpdateRequest(Rect(0, 0, cp.width, cp.height),
  428. !forceNonincremental);
  429. forceNonincremental = false;
  430. }
  431. void CConn::handleOptions(void *data)
  432. {
  433. CConn *self = (CConn*)data;
  434. // Checking all the details of the current set of encodings is just
  435. // a pain. Assume something has changed, as resending the encoding
  436. // list is cheap. Avoid overriding what the auto logic has selected
  437. // though.
  438. if (!autoSelect) {
  439. int encNum = encodingNum(preferredEncoding);
  440. if (encNum != -1)
  441. self->currentEncoding = encNum;
  442. self->cp.qualityLevel = qualityLevel;
  443. }
  444. self->cp.supportsLocalCursor = true;
  445. self->cp.customCompressLevel = customCompressLevel;
  446. self->cp.compressLevel = compressLevel;
  447. self->cp.noJpeg = noJpeg;
  448. self->encodingChange = true;
  449. // Format changes refreshes the entire screen though and are therefore
  450. // very costly. It's probably worth the effort to see if it is necessary
  451. // here.
  452. PixelFormat pf;
  453. if (fullColour) {
  454. pf = self->fullColourPF;
  455. } else {
  456. if (lowColourLevel == 0)
  457. pf = mediumColourPF;
  458. else if (lowColourLevel == 1)
  459. pf = lowColourPF;
  460. else
  461. pf = verylowColourPF;
  462. }
  463. if (!pf.equal(self->cp.pf()))
  464. self->formatChange = true;
  465. }