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.

VNCSConnectionST.cxx 30KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099
  1. /* Copyright (C) 2002-2005 RealVNC Ltd. All Rights Reserved.
  2. * Copyright 2009-2018 Pierre Ossman for Cendio AB
  3. * Copyright 2018 Peter Astrand 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. #include <network/TcpSocket.h>
  21. #include <rfb/ComparingUpdateTracker.h>
  22. #include <rfb/Encoder.h>
  23. #include <rfb/KeyRemapper.h>
  24. #include <rfb/LogWriter.h>
  25. #include <rfb/Security.h>
  26. #include <rfb/ServerCore.h>
  27. #include <rfb/SMsgWriter.h>
  28. #include <rfb/VNCServerST.h>
  29. #include <rfb/VNCSConnectionST.h>
  30. #include <rfb/screenTypes.h>
  31. #include <rfb/fenceTypes.h>
  32. #include <rfb/ledStates.h>
  33. #define XK_LATIN1
  34. #define XK_MISCELLANY
  35. #define XK_XKB_KEYS
  36. #include <rfb/keysymdef.h>
  37. using namespace rfb;
  38. static LogWriter vlog("VNCSConnST");
  39. static Cursor emptyCursor(0, 0, Point(0, 0), NULL);
  40. VNCSConnectionST::VNCSConnectionST(VNCServerST* server_, network::Socket *s,
  41. bool reverse)
  42. : sock(s), reverseConnection(reverse),
  43. inProcessMessages(false),
  44. pendingSyncFence(false), syncFence(false), fenceFlags(0),
  45. fenceDataLen(0), fenceData(NULL), congestionTimer(this),
  46. losslessTimer(this), server(server_), updates(false),
  47. updateRenderedCursor(false), removeRenderedCursor(false),
  48. continuousUpdates(false), encodeManager(this), idleTimer(this),
  49. pointerEventTime(0), clientHasCursor(false)
  50. {
  51. setStreams(&sock->inStream(), &sock->outStream());
  52. peerEndpoint.buf = sock->getPeerEndpoint();
  53. // Configure the socket
  54. setSocketTimeouts();
  55. // Kick off the idle timer
  56. if (rfb::Server::idleTimeout) {
  57. // minimum of 15 seconds while authenticating
  58. if (rfb::Server::idleTimeout < 15)
  59. idleTimer.start(secsToMillis(15));
  60. else
  61. idleTimer.start(secsToMillis(rfb::Server::idleTimeout));
  62. }
  63. }
  64. VNCSConnectionST::~VNCSConnectionST()
  65. {
  66. // If we reach here then VNCServerST is deleting us!
  67. if (closeReason.buf)
  68. vlog.info("closing %s: %s", peerEndpoint.buf, closeReason.buf);
  69. // Release any keys the client still had pressed
  70. while (!pressedKeys.empty()) {
  71. rdr::U32 keysym, keycode;
  72. keysym = pressedKeys.begin()->second;
  73. keycode = pressedKeys.begin()->first;
  74. pressedKeys.erase(pressedKeys.begin());
  75. vlog.debug("Releasing key 0x%x / 0x%x on client disconnect",
  76. keysym, keycode);
  77. server->keyEvent(keysym, keycode, false);
  78. }
  79. delete [] fenceData;
  80. }
  81. // SConnection methods
  82. bool VNCSConnectionST::accessCheck(AccessRights ar) const
  83. {
  84. // Reverse connections are user initiated, so they are implicitly
  85. // allowed to bypass the query
  86. if (reverseConnection)
  87. ar &= ~AccessNoQuery;
  88. return SConnection::accessCheck(ar);
  89. }
  90. void VNCSConnectionST::close(const char* reason)
  91. {
  92. // Log the reason for the close
  93. if (!closeReason.buf)
  94. closeReason.buf = strDup(reason);
  95. else
  96. vlog.debug("second close: %s (%s)", peerEndpoint.buf, reason);
  97. // Just shutdown the socket and mark our state as closing. Eventually the
  98. // calling code will call VNCServerST's removeSocket() method causing us to
  99. // be deleted.
  100. sock->shutdown();
  101. SConnection::close(reason);
  102. }
  103. // Methods called from VNCServerST
  104. bool VNCSConnectionST::init()
  105. {
  106. try {
  107. initialiseProtocol();
  108. } catch (rdr::Exception& e) {
  109. close(e.str());
  110. return false;
  111. }
  112. return true;
  113. }
  114. void VNCSConnectionST::processMessages()
  115. {
  116. if (state() == RFBSTATE_CLOSING) return;
  117. try {
  118. // - Now set appropriate socket timeouts and process data
  119. setSocketTimeouts();
  120. inProcessMessages = true;
  121. // Get the underlying TCP layer to build large packets if we send
  122. // multiple small responses.
  123. sock->cork(true);
  124. while (getInStream()->checkNoWait(1)) {
  125. if (pendingSyncFence) {
  126. syncFence = true;
  127. pendingSyncFence = false;
  128. }
  129. processMsg();
  130. if (syncFence) {
  131. writer()->writeFence(fenceFlags, fenceDataLen, fenceData);
  132. syncFence = false;
  133. }
  134. }
  135. // Flush out everything in case we go idle after this.
  136. sock->cork(false);
  137. inProcessMessages = false;
  138. // If there were anything requiring an update, try to send it here.
  139. // We wait until now with this to aggregate responses and to give
  140. // higher priority to user actions such as keyboard and pointer events.
  141. writeFramebufferUpdate();
  142. } catch (rdr::EndOfStream&) {
  143. close("Clean disconnection");
  144. } catch (rdr::Exception &e) {
  145. close(e.str());
  146. }
  147. }
  148. void VNCSConnectionST::flushSocket()
  149. {
  150. if (state() == RFBSTATE_CLOSING) return;
  151. try {
  152. setSocketTimeouts();
  153. sock->outStream().flush();
  154. // Flushing the socket might release an update that was previously
  155. // delayed because of congestion.
  156. if (sock->outStream().bufferUsage() == 0)
  157. writeFramebufferUpdate();
  158. } catch (rdr::Exception &e) {
  159. close(e.str());
  160. }
  161. }
  162. void VNCSConnectionST::pixelBufferChange()
  163. {
  164. try {
  165. if (!authenticated()) return;
  166. if (cp.width && cp.height &&
  167. (server->getPixelBuffer()->width() != cp.width ||
  168. server->getPixelBuffer()->height() != cp.height))
  169. {
  170. // We need to clip the next update to the new size, but also add any
  171. // extra bits if it's bigger. If we wanted to do this exactly, something
  172. // like the code below would do it, but at the moment we just update the
  173. // entire new size. However, we do need to clip the damagedCursorRegion
  174. // because that might be added to updates in writeFramebufferUpdate().
  175. //updates.intersect(server->pb->getRect());
  176. //
  177. //if (server->pb->width() > cp.width)
  178. // updates.add_changed(Rect(cp.width, 0, server->pb->width(),
  179. // server->pb->height()));
  180. //if (server->pb->height() > cp.height)
  181. // updates.add_changed(Rect(0, cp.height, cp.width,
  182. // server->pb->height()));
  183. damagedCursorRegion.assign_intersect(server->getPixelBuffer()->getRect());
  184. cp.width = server->getPixelBuffer()->width();
  185. cp.height = server->getPixelBuffer()->height();
  186. cp.screenLayout = server->getScreenLayout();
  187. if (state() == RFBSTATE_NORMAL) {
  188. // We should only send EDS to client asking for both
  189. if (!writer()->writeExtendedDesktopSize()) {
  190. if (!writer()->writeSetDesktopSize()) {
  191. close("Client does not support desktop resize");
  192. return;
  193. }
  194. }
  195. }
  196. // Drop any lossy tracking that is now outside the framebuffer
  197. encodeManager.pruneLosslessRefresh(Region(server->getPixelBuffer()->getRect()));
  198. }
  199. // Just update the whole screen at the moment because we're too lazy to
  200. // work out what's actually changed.
  201. updates.clear();
  202. updates.add_changed(server->getPixelBuffer()->getRect());
  203. writeFramebufferUpdate();
  204. } catch(rdr::Exception &e) {
  205. close(e.str());
  206. }
  207. }
  208. void VNCSConnectionST::writeFramebufferUpdateOrClose()
  209. {
  210. try {
  211. writeFramebufferUpdate();
  212. } catch(rdr::Exception &e) {
  213. close(e.str());
  214. }
  215. }
  216. void VNCSConnectionST::screenLayoutChangeOrClose(rdr::U16 reason)
  217. {
  218. try {
  219. screenLayoutChange(reason);
  220. writeFramebufferUpdate();
  221. } catch(rdr::Exception &e) {
  222. close(e.str());
  223. }
  224. }
  225. void VNCSConnectionST::bellOrClose()
  226. {
  227. try {
  228. if (state() == RFBSTATE_NORMAL) writer()->writeBell();
  229. } catch(rdr::Exception& e) {
  230. close(e.str());
  231. }
  232. }
  233. void VNCSConnectionST::serverCutTextOrClose(const char *str, int len)
  234. {
  235. try {
  236. if (!accessCheck(AccessCutText)) return;
  237. if (!rfb::Server::sendCutText) return;
  238. if (state() == RFBSTATE_NORMAL)
  239. writer()->writeServerCutText(str, len);
  240. } catch(rdr::Exception& e) {
  241. close(e.str());
  242. }
  243. }
  244. void VNCSConnectionST::setDesktopNameOrClose(const char *name)
  245. {
  246. try {
  247. setDesktopName(name);
  248. writeFramebufferUpdate();
  249. } catch(rdr::Exception& e) {
  250. close(e.str());
  251. }
  252. }
  253. void VNCSConnectionST::setCursorOrClose()
  254. {
  255. try {
  256. setCursor();
  257. writeFramebufferUpdate();
  258. } catch(rdr::Exception& e) {
  259. close(e.str());
  260. }
  261. }
  262. void VNCSConnectionST::setLEDStateOrClose(unsigned int state)
  263. {
  264. try {
  265. setLEDState(state);
  266. writeFramebufferUpdate();
  267. } catch(rdr::Exception& e) {
  268. close(e.str());
  269. }
  270. }
  271. bool VNCSConnectionST::getComparerState()
  272. {
  273. // We interpret a low compression level as an indication that the client
  274. // wants to prioritise CPU usage over bandwidth, and hence disable the
  275. // comparing update tracker.
  276. return (cp.compressLevel == -1) || (cp.compressLevel > 1);
  277. }
  278. // renderedCursorChange() is called whenever the server-side rendered cursor
  279. // changes shape or position. It ensures that the next update will clean up
  280. // the old rendered cursor and if necessary draw the new rendered cursor.
  281. void VNCSConnectionST::renderedCursorChange()
  282. {
  283. if (state() != RFBSTATE_NORMAL) return;
  284. // Are we switching between client-side and server-side cursor?
  285. if (clientHasCursor == needRenderedCursor())
  286. setCursorOrClose();
  287. bool hasRenderedCursor = !damagedCursorRegion.is_empty();
  288. if (hasRenderedCursor)
  289. removeRenderedCursor = true;
  290. if (needRenderedCursor()) {
  291. updateRenderedCursor = true;
  292. writeFramebufferUpdateOrClose();
  293. }
  294. }
  295. // needRenderedCursor() returns true if this client needs the server-side
  296. // rendered cursor. This may be because it does not support local cursor or
  297. // because the current cursor position has not been set by this client.
  298. // Unfortunately we can't know for sure when the current cursor position has
  299. // been set by this client. We guess that this is the case when the current
  300. // cursor position is the same as the last pointer event from this client, or
  301. // if it is a very short time since this client's last pointer event (up to a
  302. // second). [ Ideally we should do finer-grained timing here and make the time
  303. // configurable, but I don't think it's that important. ]
  304. bool VNCSConnectionST::needRenderedCursor()
  305. {
  306. if (state() != RFBSTATE_NORMAL)
  307. return false;
  308. if (!cp.supportsLocalCursorWithAlpha &&
  309. !cp.supportsLocalCursor && !cp.supportsLocalXCursor)
  310. return true;
  311. if (!server->getCursorPos().equals(pointerEventPos) &&
  312. (time(0) - pointerEventTime) > 0)
  313. return true;
  314. return false;
  315. }
  316. void VNCSConnectionST::approveConnectionOrClose(bool accept,
  317. const char* reason)
  318. {
  319. try {
  320. approveConnection(accept, reason);
  321. } catch (rdr::Exception& e) {
  322. close(e.str());
  323. }
  324. }
  325. // -=- Callbacks from SConnection
  326. void VNCSConnectionST::authSuccess()
  327. {
  328. if (rfb::Server::idleTimeout)
  329. idleTimer.start(secsToMillis(rfb::Server::idleTimeout));
  330. // - Set the connection parameters appropriately
  331. cp.width = server->getPixelBuffer()->width();
  332. cp.height = server->getPixelBuffer()->height();
  333. cp.screenLayout = server->getScreenLayout();
  334. cp.setName(server->getName());
  335. cp.setLEDState(server->getLEDState());
  336. // - Set the default pixel format
  337. cp.setPF(server->getPixelBuffer()->getPF());
  338. char buffer[256];
  339. cp.pf().print(buffer, 256);
  340. vlog.info("Server default pixel format %s", buffer);
  341. // - Mark the entire display as "dirty"
  342. updates.add_changed(server->getPixelBuffer()->getRect());
  343. }
  344. void VNCSConnectionST::queryConnection(const char* userName)
  345. {
  346. server->queryConnection(this, userName);
  347. }
  348. void VNCSConnectionST::clientInit(bool shared)
  349. {
  350. if (rfb::Server::idleTimeout)
  351. idleTimer.start(secsToMillis(rfb::Server::idleTimeout));
  352. if (rfb::Server::alwaysShared || reverseConnection) shared = true;
  353. if (!accessCheck(AccessNonShared)) shared = true;
  354. if (rfb::Server::neverShared) shared = false;
  355. SConnection::clientInit(shared);
  356. server->clientReady(this, shared);
  357. }
  358. void VNCSConnectionST::setPixelFormat(const PixelFormat& pf)
  359. {
  360. SConnection::setPixelFormat(pf);
  361. char buffer[256];
  362. pf.print(buffer, 256);
  363. vlog.info("Client pixel format %s", buffer);
  364. setCursor();
  365. }
  366. void VNCSConnectionST::pointerEvent(const Point& pos, int buttonMask)
  367. {
  368. if (rfb::Server::idleTimeout)
  369. idleTimer.start(secsToMillis(rfb::Server::idleTimeout));
  370. pointerEventTime = time(0);
  371. if (!accessCheck(AccessPtrEvents)) return;
  372. if (!rfb::Server::acceptPointerEvents) return;
  373. pointerEventPos = pos;
  374. server->pointerEvent(this, pointerEventPos, buttonMask);
  375. }
  376. class VNCSConnectionSTShiftPresser {
  377. public:
  378. VNCSConnectionSTShiftPresser(VNCServerST* server_)
  379. : server(server_), pressed(false) {}
  380. ~VNCSConnectionSTShiftPresser() {
  381. if (pressed) {
  382. vlog.debug("Releasing fake Shift_L");
  383. server->keyEvent(XK_Shift_L, 0, false);
  384. }
  385. }
  386. void press() {
  387. vlog.debug("Pressing fake Shift_L");
  388. server->keyEvent(XK_Shift_L, 0, true);
  389. pressed = true;
  390. }
  391. VNCServerST* server;
  392. bool pressed;
  393. };
  394. // keyEvent() - record in the pressedKeys which keys were pressed. Allow
  395. // multiple down events (for autorepeat), but only allow a single up event.
  396. void VNCSConnectionST::keyEvent(rdr::U32 keysym, rdr::U32 keycode, bool down) {
  397. rdr::U32 lookup;
  398. if (rfb::Server::idleTimeout)
  399. idleTimer.start(secsToMillis(rfb::Server::idleTimeout));
  400. if (!accessCheck(AccessKeyEvents)) return;
  401. if (!rfb::Server::acceptKeyEvents) return;
  402. if (down)
  403. vlog.debug("Key pressed: 0x%x / 0x%x", keysym, keycode);
  404. else
  405. vlog.debug("Key released: 0x%x / 0x%x", keysym, keycode);
  406. // Avoid lock keys if we don't know the server state
  407. if ((server->getLEDState() == ledUnknown) &&
  408. ((keysym == XK_Caps_Lock) ||
  409. (keysym == XK_Num_Lock) ||
  410. (keysym == XK_Scroll_Lock))) {
  411. vlog.debug("Ignoring lock key (e.g. caps lock)");
  412. return;
  413. }
  414. // Lock key heuristics
  415. // (only for clients that do not support the LED state extension)
  416. if (!cp.supportsLEDState) {
  417. // Always ignore ScrollLock as we don't have a heuristic
  418. // for that
  419. if (keysym == XK_Scroll_Lock) {
  420. vlog.debug("Ignoring lock key (e.g. caps lock)");
  421. return;
  422. }
  423. if (down && (server->getLEDState() != ledUnknown)) {
  424. // CapsLock synchronisation heuristic
  425. // (this assumes standard interaction between CapsLock the Shift
  426. // keys and normal characters)
  427. if (((keysym >= XK_A) && (keysym <= XK_Z)) ||
  428. ((keysym >= XK_a) && (keysym <= XK_z))) {
  429. bool uppercase, shift, lock;
  430. uppercase = (keysym >= XK_A) && (keysym <= XK_Z);
  431. shift = isShiftPressed();
  432. lock = server->getLEDState() & ledCapsLock;
  433. if (lock == (uppercase == shift)) {
  434. vlog.debug("Inserting fake CapsLock to get in sync with client");
  435. server->keyEvent(XK_Caps_Lock, 0, true);
  436. server->keyEvent(XK_Caps_Lock, 0, false);
  437. }
  438. }
  439. // NumLock synchronisation heuristic
  440. // (this is more cautious because of the differences between Unix,
  441. // Windows and macOS)
  442. if (((keysym >= XK_KP_Home) && (keysym <= XK_KP_Delete)) ||
  443. ((keysym >= XK_KP_0) && (keysym <= XK_KP_9)) ||
  444. (keysym == XK_KP_Separator) || (keysym == XK_KP_Decimal)) {
  445. bool number, shift, lock;
  446. number = ((keysym >= XK_KP_0) && (keysym <= XK_KP_9)) ||
  447. (keysym == XK_KP_Separator) || (keysym == XK_KP_Decimal);
  448. shift = isShiftPressed();
  449. lock = server->getLEDState() & ledNumLock;
  450. if (shift) {
  451. // We don't know the appropriate NumLock state for when Shift
  452. // is pressed as it could be one of:
  453. //
  454. // a) A Unix client where Shift negates NumLock
  455. //
  456. // b) A Windows client where Shift only cancels NumLock
  457. //
  458. // c) A macOS client where Shift doesn't have any effect
  459. //
  460. } else if (lock == (number == shift)) {
  461. vlog.debug("Inserting fake NumLock to get in sync with client");
  462. server->keyEvent(XK_Num_Lock, 0, true);
  463. server->keyEvent(XK_Num_Lock, 0, false);
  464. }
  465. }
  466. }
  467. }
  468. // Turn ISO_Left_Tab into shifted Tab.
  469. VNCSConnectionSTShiftPresser shiftPresser(server);
  470. if (keysym == XK_ISO_Left_Tab) {
  471. if (!isShiftPressed())
  472. shiftPresser.press();
  473. keysym = XK_Tab;
  474. }
  475. // We need to be able to track keys, so generate a fake index when we
  476. // aren't given a keycode
  477. if (keycode == 0)
  478. lookup = 0x80000000 | keysym;
  479. else
  480. lookup = keycode;
  481. // We force the same keysym for an already down key for the
  482. // sake of sanity
  483. if (pressedKeys.find(lookup) != pressedKeys.end())
  484. keysym = pressedKeys[lookup];
  485. if (down) {
  486. pressedKeys[lookup] = keysym;
  487. } else {
  488. if (!pressedKeys.erase(lookup))
  489. return;
  490. }
  491. server->keyEvent(keysym, keycode, down);
  492. }
  493. void VNCSConnectionST::clientCutText(const char* str, int len)
  494. {
  495. if (!accessCheck(AccessCutText)) return;
  496. if (!rfb::Server::acceptCutText) return;
  497. server->clientCutText(str, len);
  498. }
  499. void VNCSConnectionST::framebufferUpdateRequest(const Rect& r,bool incremental)
  500. {
  501. Rect safeRect;
  502. if (!accessCheck(AccessView)) return;
  503. SConnection::framebufferUpdateRequest(r, incremental);
  504. // Check that the client isn't sending crappy requests
  505. if (!r.enclosed_by(Rect(0, 0, cp.width, cp.height))) {
  506. vlog.error("FramebufferUpdateRequest %dx%d at %d,%d exceeds framebuffer %dx%d",
  507. r.width(), r.height(), r.tl.x, r.tl.y, cp.width, cp.height);
  508. safeRect = r.intersect(Rect(0, 0, cp.width, cp.height));
  509. } else {
  510. safeRect = r;
  511. }
  512. // Just update the requested region.
  513. // Framebuffer update will be sent a bit later, see processMessages().
  514. Region reqRgn(r);
  515. if (!incremental || !continuousUpdates)
  516. requested.assign_union(reqRgn);
  517. if (!incremental) {
  518. // Non-incremental update - treat as if area requested has changed
  519. updates.add_changed(reqRgn);
  520. // And send the screen layout to the client (which, unlike the
  521. // framebuffer dimensions, the client doesn't get during init)
  522. writer()->writeExtendedDesktopSize();
  523. // We do not send a DesktopSize since it only contains the
  524. // framebuffer size (which the client already should know) and
  525. // because some clients don't handle extra DesktopSize events
  526. // very well.
  527. }
  528. }
  529. void VNCSConnectionST::setDesktopSize(int fb_width, int fb_height,
  530. const ScreenSet& layout)
  531. {
  532. unsigned int result;
  533. if (!accessCheck(AccessSetDesktopSize)) return;
  534. if (!rfb::Server::acceptSetDesktopSize) return;
  535. result = server->setDesktopSize(this, fb_width, fb_height, layout);
  536. writer()->writeExtendedDesktopSize(reasonClient, result,
  537. fb_width, fb_height, layout);
  538. }
  539. void VNCSConnectionST::fence(rdr::U32 flags, unsigned len, const char data[])
  540. {
  541. rdr::U8 type;
  542. if (flags & fenceFlagRequest) {
  543. if (flags & fenceFlagSyncNext) {
  544. pendingSyncFence = true;
  545. fenceFlags = flags & (fenceFlagBlockBefore | fenceFlagBlockAfter | fenceFlagSyncNext);
  546. fenceDataLen = len;
  547. delete [] fenceData;
  548. fenceData = NULL;
  549. if (len > 0) {
  550. fenceData = new char[len];
  551. memcpy(fenceData, data, len);
  552. }
  553. return;
  554. }
  555. // We handle everything synchronously so we trivially honor these modes
  556. flags = flags & (fenceFlagBlockBefore | fenceFlagBlockAfter);
  557. writer()->writeFence(flags, len, data);
  558. return;
  559. }
  560. if (len < 1)
  561. vlog.error("Fence response of unexpected size received");
  562. type = data[0];
  563. switch (type) {
  564. case 0:
  565. // Initial dummy fence;
  566. break;
  567. case 1:
  568. congestion.gotPong();
  569. break;
  570. default:
  571. vlog.error("Fence response of unexpected type received");
  572. }
  573. }
  574. void VNCSConnectionST::enableContinuousUpdates(bool enable,
  575. int x, int y, int w, int h)
  576. {
  577. Rect rect;
  578. if (!cp.supportsFence || !cp.supportsContinuousUpdates)
  579. throw Exception("Client tried to enable continuous updates when not allowed");
  580. continuousUpdates = enable;
  581. rect.setXYWH(x, y, w, h);
  582. cuRegion.reset(rect);
  583. if (enable) {
  584. requested.clear();
  585. } else {
  586. writer()->writeEndOfContinuousUpdates();
  587. }
  588. }
  589. // supportsLocalCursor() is called whenever the status of
  590. // cp.supportsLocalCursor has changed. If the client does now support local
  591. // cursor, we make sure that the old server-side rendered cursor is cleaned up
  592. // and the cursor is sent to the client.
  593. void VNCSConnectionST::supportsLocalCursor()
  594. {
  595. bool hasRenderedCursor = !damagedCursorRegion.is_empty();
  596. if (hasRenderedCursor && !needRenderedCursor())
  597. removeRenderedCursor = true;
  598. setCursor();
  599. }
  600. void VNCSConnectionST::supportsFence()
  601. {
  602. char type = 0;
  603. writer()->writeFence(fenceFlagRequest, sizeof(type), &type);
  604. }
  605. void VNCSConnectionST::supportsContinuousUpdates()
  606. {
  607. // We refuse to use continuous updates if we cannot monitor the buffer
  608. // usage using fences.
  609. if (!cp.supportsFence)
  610. return;
  611. writer()->writeEndOfContinuousUpdates();
  612. }
  613. void VNCSConnectionST::supportsLEDState()
  614. {
  615. writer()->writeLEDState();
  616. }
  617. bool VNCSConnectionST::handleTimeout(Timer* t)
  618. {
  619. try {
  620. if ((t == &congestionTimer) ||
  621. (t == &losslessTimer))
  622. writeFramebufferUpdate();
  623. } catch (rdr::Exception& e) {
  624. close(e.str());
  625. }
  626. if (t == &idleTimer)
  627. close("Idle timeout");
  628. return false;
  629. }
  630. bool VNCSConnectionST::isShiftPressed()
  631. {
  632. std::map<rdr::U32, rdr::U32>::const_iterator iter;
  633. for (iter = pressedKeys.begin(); iter != pressedKeys.end(); ++iter) {
  634. if (iter->second == XK_Shift_L)
  635. return true;
  636. if (iter->second == XK_Shift_R)
  637. return true;
  638. }
  639. return false;
  640. }
  641. void VNCSConnectionST::writeRTTPing()
  642. {
  643. char type;
  644. if (!cp.supportsFence)
  645. return;
  646. congestion.updatePosition(sock->outStream().length());
  647. // We need to make sure any old update are already processed by the
  648. // time we get the response back. This allows us to reliably throttle
  649. // back on client overload, as well as network overload.
  650. type = 1;
  651. writer()->writeFence(fenceFlagRequest | fenceFlagBlockBefore,
  652. sizeof(type), &type);
  653. congestion.sentPing();
  654. }
  655. bool VNCSConnectionST::isCongested()
  656. {
  657. int eta;
  658. congestionTimer.stop();
  659. // Stuff still waiting in the send buffer?
  660. sock->outStream().flush();
  661. congestion.debugTrace("congestion-trace.csv", sock->getFd());
  662. if (sock->outStream().bufferUsage() > 0)
  663. return true;
  664. if (!cp.supportsFence)
  665. return false;
  666. congestion.updatePosition(sock->outStream().length());
  667. if (!congestion.isCongested())
  668. return false;
  669. eta = congestion.getUncongestedETA();
  670. if (eta >= 0)
  671. congestionTimer.start(eta);
  672. return true;
  673. }
  674. void VNCSConnectionST::writeFramebufferUpdate()
  675. {
  676. congestion.updatePosition(sock->outStream().length());
  677. // We're in the middle of processing a command that's supposed to be
  678. // synchronised. Allowing an update to slip out right now might violate
  679. // that synchronisation.
  680. if (syncFence)
  681. return;
  682. // We try to aggregate responses, so don't send out anything whilst we
  683. // still have incoming messages. processMessages() will give us another
  684. // chance to run once things are idle.
  685. if (inProcessMessages)
  686. return;
  687. if (state() != RFBSTATE_NORMAL)
  688. return;
  689. if (requested.is_empty() && !continuousUpdates)
  690. return;
  691. // Check that we actually have some space on the link and retry in a
  692. // bit if things are congested.
  693. if (isCongested())
  694. return;
  695. // Updates often consists of many small writes, and in continuous
  696. // mode, we will also have small fence messages around the update. We
  697. // need to aggregate these in order to not clog up TCP's congestion
  698. // window.
  699. sock->cork(true);
  700. // First take care of any updates that cannot contain framebuffer data
  701. // changes.
  702. writeNoDataUpdate();
  703. // Then real data (if possible)
  704. writeDataUpdate();
  705. sock->cork(false);
  706. congestion.updatePosition(sock->outStream().length());
  707. }
  708. void VNCSConnectionST::writeNoDataUpdate()
  709. {
  710. if (!writer()->needNoDataUpdate())
  711. return;
  712. writer()->writeNoDataUpdate();
  713. // Make sure no data update is sent until next request
  714. requested.clear();
  715. }
  716. void VNCSConnectionST::writeDataUpdate()
  717. {
  718. Region req, pending;
  719. UpdateInfo ui;
  720. bool needNewUpdateInfo;
  721. const RenderedCursor *cursor;
  722. updates.enable_copyrect(cp.useCopyRect);
  723. // See what the client has requested (if anything)
  724. if (continuousUpdates)
  725. req = cuRegion.union_(requested);
  726. else
  727. req = requested;
  728. if (req.is_empty())
  729. return;
  730. // Get any framebuffer changes we haven't yet been informed of
  731. pending = server->getPendingRegion();
  732. // Get the lists of updates. Prior to exporting the data to the `ui' object,
  733. // getUpdateInfo() will normalize the `updates' object such way that its
  734. // `changed' and `copied' regions would not intersect.
  735. updates.getUpdateInfo(&ui, req);
  736. needNewUpdateInfo = false;
  737. // If the previous position of the rendered cursor overlaps the source of the
  738. // copy, then when the copy happens the corresponding rectangle in the
  739. // destination will be wrong, so add it to the changed region.
  740. if (!ui.copied.is_empty() && !damagedCursorRegion.is_empty()) {
  741. Region bogusCopiedCursor;
  742. bogusCopiedCursor = damagedCursorRegion;
  743. bogusCopiedCursor.translate(ui.copy_delta);
  744. bogusCopiedCursor.assign_intersect(server->getPixelBuffer()->getRect());
  745. if (!ui.copied.intersect(bogusCopiedCursor).is_empty()) {
  746. updates.add_changed(bogusCopiedCursor);
  747. needNewUpdateInfo = true;
  748. }
  749. }
  750. // If we need to remove the old rendered cursor, just add the region to
  751. // the changed region.
  752. if (removeRenderedCursor) {
  753. updates.add_changed(damagedCursorRegion);
  754. needNewUpdateInfo = true;
  755. damagedCursorRegion.clear();
  756. removeRenderedCursor = false;
  757. }
  758. // If we need a full cursor update then make sure its entire region
  759. // is marked as changed.
  760. if (updateRenderedCursor) {
  761. updates.add_changed(server->getRenderedCursor()->getEffectiveRect());
  762. needNewUpdateInfo = true;
  763. updateRenderedCursor = false;
  764. }
  765. // The `updates' object could change, make sure we have valid update info.
  766. if (needNewUpdateInfo)
  767. updates.getUpdateInfo(&ui, req);
  768. // If there are queued updates then we cannot safely send an update
  769. // without risking a partially updated screen
  770. if (!pending.is_empty()) {
  771. // However we might still be able to send a lossless refresh
  772. req.assign_subtract(pending);
  773. req.assign_subtract(ui.changed);
  774. req.assign_subtract(ui.copied);
  775. ui.changed.clear();
  776. ui.copied.clear();
  777. }
  778. // Does the client need a server-side rendered cursor?
  779. cursor = NULL;
  780. if (needRenderedCursor()) {
  781. Rect renderedCursorRect;
  782. cursor = server->getRenderedCursor();
  783. renderedCursorRect = cursor->getEffectiveRect();
  784. // Check that we don't try to copy over the cursor area, and
  785. // if that happens we need to treat it as changed so that we can
  786. // re-render it
  787. if (!ui.copied.intersect(renderedCursorRect).is_empty()) {
  788. ui.changed.assign_union(ui.copied.intersect(renderedCursorRect));
  789. ui.copied.assign_subtract(renderedCursorRect);
  790. }
  791. // Track where we've rendered the cursor
  792. damagedCursorRegion.assign_union(ui.changed.intersect(renderedCursorRect));
  793. }
  794. // Return if there is nothing to send the client.
  795. if (ui.is_empty() && !writer()->needFakeUpdate()) {
  796. int eta;
  797. // Any lossless refresh that needs handling?
  798. if (!encodeManager.needsLosslessRefresh(req))
  799. return;
  800. // Now? Or later?
  801. eta = encodeManager.getNextLosslessRefresh(req);
  802. if (eta > 0) {
  803. losslessTimer.start(eta);
  804. return;
  805. }
  806. }
  807. writeRTTPing();
  808. if (!ui.is_empty())
  809. encodeManager.writeUpdate(ui, server->getPixelBuffer(), cursor);
  810. else {
  811. int nextUpdate;
  812. // FIXME: If continuous updates aren't used then the client might
  813. // be slower than frameRate in its requests and we could
  814. // afford a larger update size
  815. nextUpdate = server->msToNextUpdate();
  816. if (nextUpdate > 0) {
  817. size_t bandwidth, maxUpdateSize;
  818. // FIXME: Bandwidth estimation without congestion control
  819. bandwidth = congestion.getBandwidth();
  820. // FIXME: Hard coded value for maximum CPU throughput
  821. if (bandwidth > 5000000)
  822. bandwidth = 5000000;
  823. maxUpdateSize = bandwidth * nextUpdate / 1000;
  824. encodeManager.writeLosslessRefresh(req, server->getPixelBuffer(),
  825. cursor, maxUpdateSize);
  826. }
  827. }
  828. writeRTTPing();
  829. // The request might be for just part of the screen, so we cannot
  830. // just clear the entire update tracker.
  831. updates.subtract(req);
  832. requested.clear();
  833. }
  834. void VNCSConnectionST::screenLayoutChange(rdr::U16 reason)
  835. {
  836. if (!authenticated())
  837. return;
  838. cp.screenLayout = server->getScreenLayout();
  839. if (state() != RFBSTATE_NORMAL)
  840. return;
  841. writer()->writeExtendedDesktopSize(reason, 0, cp.width, cp.height,
  842. cp.screenLayout);
  843. }
  844. // setCursor() is called whenever the cursor has changed shape or pixel format.
  845. // If the client supports local cursor then it will arrange for the cursor to
  846. // be sent to the client.
  847. void VNCSConnectionST::setCursor()
  848. {
  849. if (state() != RFBSTATE_NORMAL)
  850. return;
  851. // We need to blank out the client's cursor or there will be two
  852. if (needRenderedCursor()) {
  853. cp.setCursor(emptyCursor);
  854. clientHasCursor = false;
  855. } else {
  856. cp.setCursor(*server->getCursor());
  857. clientHasCursor = true;
  858. }
  859. if (!writer()->writeSetCursorWithAlpha()) {
  860. if (!writer()->writeSetCursor()) {
  861. if (!writer()->writeSetXCursor()) {
  862. // No client support
  863. return;
  864. }
  865. }
  866. }
  867. }
  868. void VNCSConnectionST::setDesktopName(const char *name)
  869. {
  870. cp.setName(name);
  871. if (state() != RFBSTATE_NORMAL)
  872. return;
  873. if (!writer()->writeSetDesktopName()) {
  874. fprintf(stderr, "Client does not support desktop rename\n");
  875. return;
  876. }
  877. }
  878. void VNCSConnectionST::setLEDState(unsigned int ledstate)
  879. {
  880. if (state() != RFBSTATE_NORMAL)
  881. return;
  882. cp.setLEDState(ledstate);
  883. writer()->writeLEDState();
  884. }
  885. void VNCSConnectionST::setSocketTimeouts()
  886. {
  887. int timeoutms = rfb::Server::clientWaitTimeMillis;
  888. if (timeoutms == 0)
  889. timeoutms = -1;
  890. sock->inStream().setTimeout(timeoutms);
  891. sock->outStream().setTimeout(timeoutms);
  892. }