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

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